@lmnr-ai/lmnr 0.8.40 → 0.8.41

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dist-D-1LE3Xx.mjs","names":["initializeLogger","logger","isStringUUID","newUUID","uuidv4","otelSpanIdToUUID","otelTraceIdToUUID","loadEnv"],"sources":["../../types/dist/index.mjs","../package.json","../src/opentelemetry-lib/tracing/attributes.ts","../src/utils.ts","../../client/dist/index.mjs"],"sourcesContent":["//#region src/debug-session.ts\n/** Directory the debug-session file lives in, relative to the working dir. */\nconst DEBUG_SESSION_DIR = \".lmnr\";\n/** Filename of the debug-session file inside {@link DEBUG_SESSION_DIR}. */\nconst DEBUG_SESSION_FILE = \"debug-session.json\";\n//#endregion\n//#region src/tracing.ts\n/**\n* Tracing levels to conditionally disable tracing.\n*\n* OFF - No tracing is sent.\n* META_ONLY - Only metadata is sent (e.g. tokens, costs, etc.).\n* ALL - All data is sent.\n*/\nlet TracingLevel = /* @__PURE__ */ function(TracingLevel) {\n\tTracingLevel[\"OFF\"] = \"off\";\n\tTracingLevel[\"META_ONLY\"] = \"meta_only\";\n\tTracingLevel[\"ALL\"] = \"all\";\n\treturn TracingLevel;\n}({});\n//#endregion\n//#region src/utils.ts\nconst errorMessage = (error) => error instanceof Error ? error.message : String(error);\n//#endregion\nexport { DEBUG_SESSION_DIR, DEBUG_SESSION_FILE, TracingLevel, errorMessage };\n\n//# sourceMappingURL=index.mjs.map","","export const SPAN_INPUT = \"lmnr.span.input\";\nexport const SPAN_OUTPUT = \"lmnr.span.output\";\nexport const SPAN_TYPE = \"lmnr.span.type\";\nexport const SPAN_PATH = \"lmnr.span.path\";\nexport const SPAN_IDS_PATH = \"lmnr.span.ids_path\";\nexport const PARENT_SPAN_PATH = \"lmnr.span.parent_path\";\nexport const PARENT_SPAN_IDS_PATH = \"lmnr.span.parent_ids_path\";\nexport const SPAN_INSTRUMENTATION_SOURCE = \"lmnr.span.instrumentation_source\";\nexport const SPAN_SDK_VERSION = \"lmnr.span.sdk_version\";\nexport const SPAN_LANGUAGE_VERSION = \"lmnr.span.language_version\";\nexport const SPAN_INSTRUMENTATION_SCOPE_NAME = \"lmnr.span.instrumentation_scope.name\";\nexport const SPAN_INSTRUMENTATION_SCOPE_VERSION = \"lmnr.span.instrumentation_scope.version\";\nexport const OVERRIDE_PARENT_SPAN = \"lmnr.internal.override_parent_span\";\nexport const TRACE_HAS_BROWSER_SESSION = \"lmnr.internal.has_browser_session\";\nexport const EXTRACTED_FROM_NEXT_JS = \"lmnr.span.extracted_from.next_js\";\nexport const HUMAN_EVALUATOR_OPTIONS = 'lmnr.span.human_evaluator_options';\nexport const ASSOCIATION_PROPERTIES = \"lmnr.association.properties\";\nexport const SESSION_ID = \"lmnr.association.properties.session_id\";\nexport const USER_ID = \"lmnr.association.properties.user_id\";\nexport const TRACE_TYPE = \"lmnr.association.properties.trace_type\";\n\nexport const ASSOCIATION_PROPERTIES_OVERRIDES: Record<string, string> = {\n \"span_type\": SPAN_TYPE,\n};\n\nexport const LaminarAttributes = {\n // == This is the minimum set of attributes for a proper LLM span ==\n //\n INPUT_TOKEN_COUNT: \"gen_ai.usage.input_tokens\",\n OUTPUT_TOKEN_COUNT: \"gen_ai.usage.output_tokens\",\n TOTAL_TOKEN_COUNT: \"llm.usage.total_tokens\",\n // TODO: Update to gen_ai.provider.name\n PROVIDER: \"gen_ai.system\",\n REQUEST_MODEL: \"gen_ai.request.model\",\n RESPONSE_MODEL: \"gen_ai.response.model\",\n //\n // == End of minimum set ==\n // == Additional attributes ==\n //\n INPUT_COST: \"gen_ai.usage.input_cost\",\n OUTPUT_COST: \"gen_ai.usage.output_cost\",\n TOTAL_COST: \"gen_ai.usage.cost\",\n //\n // == End of additional attributes ==\n};\n","import {\n DebugContext,\n errorMessage,\n LaminarSpanContext,\n TraceType,\n TracingLevel,\n} from '@lmnr-ai/types';\nimport { AttributeValue, SpanContext, TraceFlags } from '@opentelemetry/api';\nimport { config } from 'dotenv';\nimport * as path from \"path\";\nimport pino, { Level } from 'pino';\nimport { PinoPretty } from 'pino-pretty';\nimport { fileURLToPath } from \"url\";\nimport { v4 as uuidv4 } from 'uuid';\n\nimport { ASSOCIATION_PROPERTIES } from './opentelemetry-lib/tracing/attributes';\n\nexport function initializeLogger(options?: { colorize?: boolean, level?: Level }) {\n const colorize = options?.colorize ?? true;\n const level = options?.level\n ?? (process.env.LMNR_LOG_LEVEL?.toLowerCase()?.trim() as Level)\n ?? 'info';\n\n return pino(\n {\n level,\n },\n PinoPretty({\n colorize,\n minimumLevel: level,\n }),\n );\n}\n\nconst logger = initializeLogger();\n\nexport type StringUUID = `${string}-${string}-${string}-${string}-${string}`;\n\nexport const isStringUUID = (id: string): id is StringUUID =>\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id);\n\nexport const NIL_UUID: StringUUID = '00000000-0000-0000-0000-000000000000';\n\nexport const newUUID = (): StringUUID => {\n // crypto.randomUUID is available in most of the modern browsers and node,\n // but is not available in \"insecure\" contexts, e.g. not https, not localhost\n // so we fallback to uuidv4 in those cases, which is less secure, but works\n // just fine.\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n } else {\n return uuidv4() as `${string}-${string}-${string}-${string}-${string}`;\n }\n};\n\n// Coerce a hex trace id to the 32-char raw form an OTel `SpanContext`\n// requires. Unlike `otelTraceIdToUUID`, this returns plain hex (no dashes)\n// and truncates (`slice(-32)`) rather than producing invalid output for\n// longer-than-32-char inputs — callers passing ids from upstream frameworks\n// (e.g. Mastra) that occasionally emit non-canonical ids rely on that\n// truncation to stay within OTel's spec.\nexport const normalizeOtelTraceId = (traceId: string): string => {\n let id = traceId.toLowerCase();\n if (id.startsWith('0x')) {\n id = id.slice(2);\n }\n return id.padStart(32, '0').slice(-32);\n};\n\n// Raw-hex counterpart of `normalizeOtelTraceId` for 16-char span ids.\nexport const normalizeOtelSpanId = (spanId: string): string => {\n let id = spanId.toLowerCase();\n if (id.startsWith('0x')) {\n id = id.slice(2);\n }\n return id.padStart(16, '0').slice(-16);\n};\n\nexport const otelSpanIdToUUID = (spanId: string): string => {\n let id = spanId.toLowerCase();\n if (id.startsWith('0x')) {\n id = id.slice(2);\n }\n if (id.length !== 16) {\n logger.warn(`Span ID ${spanId} is not 16 hex chars long. ` +\n 'This is not a valid OpenTelemetry span ID.');\n }\n\n if (!/^[0-9a-f]+$/.test(id)) {\n logger.error(`Span ID ${spanId} is not a valid hex string. ` +\n 'Generating a random UUID instead.');\n return newUUID();\n }\n\n return id.padStart(32, '0').replace(\n /^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/,\n '$1-$2-$3-$4-$5',\n );\n};\n\nexport const otelTraceIdToUUID = (traceId: string): StringUUID => {\n let id = traceId.toLowerCase();\n if (id.startsWith('0x')) {\n id = id.slice(2);\n }\n if (id.length !== 32) {\n logger.warn(`Trace ID ${traceId} is not 32 hex chars long. ` +\n 'This is not a valid OpenTelemetry trace ID.');\n }\n if (!/^[0-9a-f]+$/.test(id)) {\n logger.error(`Trace ID ${traceId} is not a valid hex string. ` +\n 'Generating a random UUID instead.');\n return newUUID();\n }\n\n return id.replace(\n /^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/,\n '$1-$2-$3-$4-$5',\n ) as StringUUID;\n};\n\nexport const uuidToOtelTraceId = (uuid: string): string => uuid.replace(/-/g, '');\nexport const uuidToOtelSpanId = (uuid: string): string => uuid.replace(/-/g, '').slice(16);\n\n/**\n * This is a simple implementation of a semaphore to replicate\n * the behavior of the `asyncio.Semaphore` in Python.\n */\nexport class Semaphore {\n /**\n * Number of permits available.\n */\n private _value: number;\n /**\n * List of promises that will be resolved when a permit becomes available.\n */\n private _waiters: ((...args: any[]) => any)[] = [];\n\n constructor(value = 1) {\n if (value < 0) {\n throw new Error(\"Semaphore value must be >= 0\");\n }\n this._value = value;\n this._waiters = [];\n }\n\n async acquire() {\n if (this._value > 0) {\n this._value--;\n return;\n }\n\n // Create a promise that will be resolved when a permit becomes available\n return new Promise(resolve => {\n this._waiters.push(resolve);\n });\n }\n\n release() {\n if (this._waiters.length > 0) {\n // If there are waiters, wake up the first one\n const resolve = this._waiters.shift();\n resolve?.();\n } else {\n this._value++;\n }\n }\n\n // Python-like context manager functionality\n async using<T>(fn: (...args: any[]) => Promise<T>) {\n try {\n await this.acquire();\n return await fn();\n } finally {\n this.release();\n }\n }\n}\n\nexport const tryToOtelSpanContext = (\n spanContext: LaminarSpanContext | Record<string, unknown> | string | SpanContext,\n): SpanContext => {\n if (typeof spanContext === 'string') {\n try {\n const record = JSON.parse(spanContext) as Record<string, unknown>;\n return recordToOtelSpanContext(record);\n } catch (e) {\n throw new Error(`Failed to parse span context ${spanContext}. ` +\n 'The string must be a json representation of a LaminarSpanContext.'\n + `Error: ${errorMessage(e)}`);\n }\n } else if (isRecord(spanContext)) {\n // This covers the `LaminarSpanContext` case too.\n return recordToOtelSpanContext(spanContext);\n } else if (typeof spanContext.traceId === 'string'\n && typeof spanContext.spanId === 'string'\n && spanContext.traceId.length === 32\n && spanContext.spanId.length === 16) {\n logger.warn('The span context is already an OpenTelemetry SpanContext. ' +\n 'Returning it as is. Please use `LaminarSpanContext` objects instead.');\n return spanContext;\n }\n else {\n throw new Error(`Invalid span context ${JSON.stringify(spanContext)}. ` +\n 'Must be a LaminarSpanContext or its json representation.');\n }\n};\n\nconst recordToOtelSpanContext = (record: Record<string, unknown>): SpanContext => {\n if ((typeof record.spanId === 'string' && typeof record.traceId === 'string') ||\n (typeof record.span_id === 'string' && typeof record.trace_id === 'string')) {\n return {\n spanId: uuidToOtelSpanId(record?.spanId as string ?? record?.['span_id'] as string),\n traceId: uuidToOtelTraceId(record?.traceId as string ?? record?.['trace_id'] as string),\n isRemote: record?.isRemote ?? record?.['is_remote'] ?? false,\n traceFlags: record?.traceFlags ?? TraceFlags.SAMPLED,\n } as SpanContext;\n } else {\n throw new Error(`Invalid span context ${JSON.stringify(record)}. ` +\n 'Must be a json representation of a LaminarSpanContext.');\n }\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && !Array.isArray(value) && value !== null;\n\n/**\n * Deserialize a LaminarSpanContext from a string or record.\n * Handles both camelCase and snake_case keys for cross-language compatibility.\n *\n * @param data - The data to deserialize (string or record)\n * @returns The deserialized LaminarSpanContext\n * @throws Error if the data is invalid\n */\nexport const deserializeLaminarSpanContext = (\n data: Record<string, unknown> | string,\n): LaminarSpanContext => {\n if (typeof data === 'string') {\n try {\n const record = JSON.parse(data) as Record<string, unknown>;\n return deserializeLaminarSpanContext(record);\n } catch (e) {\n throw new Error(\n `Failed to parse LaminarSpanContext: ${errorMessage(e)}`,\n );\n }\n }\n\n if (!isRecord(data)) {\n throw new Error('Invalid LaminarSpanContext: must be a string or object');\n }\n\n // Handle both camelCase and snake_case for all fields\n const traceId = data.traceId ?? data.trace_id;\n const spanId = data.spanId ?? data.span_id;\n const isRemote = data.isRemote ?? data.is_remote ?? false;\n const spanPath = data.spanPath ?? data.span_path;\n const spanIdsPath = data.spanIdsPath ?? data.span_ids_path;\n const userId = data.userId ?? data.user_id;\n const sessionId = data.sessionId ?? data.session_id;\n const metadata = data.metadata;\n const traceType = data.traceType ?? data.trace_type;\n const tracingLevel = data.tracingLevel ?? data.tracing_level;\n const debug = data.debug;\n\n if (typeof traceId !== 'string' || typeof spanId !== 'string') {\n throw new Error('Invalid LaminarSpanContext: traceId and spanId must be strings');\n }\n\n // Validate UUID format\n if (!isStringUUID(traceId) || !isStringUUID(spanId)) {\n throw new Error('Invalid LaminarSpanContext: traceId and spanId must be valid UUIDs');\n }\n\n return {\n traceId: traceId,\n spanId: spanId,\n isRemote: Boolean(isRemote),\n spanPath: Array.isArray(spanPath) ? spanPath as string[] : undefined,\n spanIdsPath: Array.isArray(spanIdsPath) ? spanIdsPath as StringUUID[] : undefined,\n userId: userId as string | undefined,\n sessionId: sessionId as string | undefined,\n metadata: metadata as Record<string, unknown> | undefined,\n traceType: traceType as TraceType | undefined,\n tracingLevel: tracingLevel as TracingLevel | undefined,\n debug: isRecord(debug) ? deserializeDebugContext(debug) : undefined,\n };\n};\n\n/**\n * Normalize a value to a canonical lowercase UUID string, or undefined.\n *\n * The debug block's `sessionId` / `replayTraceId` are always full ids; a value\n * that isn't UUID-shaped is dropped (treated as absent) rather than thrown, so\n * a partially-broken block never breaks span-context parsing.\n */\nconst asString = (value: unknown): string | undefined =>\n typeof value === 'string' && value.length > 0 ? value : undefined;\n\n/**\n * Parse a debug block, accepting camelCase and snake_case. All ids are kept\n * VERBATIM: the producer emits the run's exact session / replay-trace /\n * cache-until strings (un-normalized — `LMNR_DEBUG_SESSION_ID` may be an\n * arbitrary non-UUID value), so the consumer must round-trip them unchanged or\n * a downstream run never joins the run. Keep line-comparable with the Python\n * `DebugContext.deserialize`.\n */\nconst deserializeDebugContext = (data: Record<string, unknown>): DebugContext => ({\n // Strict `=== true`, NOT Boolean(...): the producer always emits a real\n // boolean, so anything else (e.g. the string \"false\", which is truthy) is a\n // malformed/forged block and must NOT arm a downstream runtime.\n enabled: data.enabled === true,\n sessionId: asString(data.sessionId ?? data.session_id),\n replayTraceId: asString(data.replayTraceId ?? data.replay_trace_id),\n cacheUntil: asString(data.cacheUntil ?? data.cache_until),\n});\n\n\nexport const getDirname = () => {\n if (typeof __dirname !== 'undefined') {\n return __dirname;\n }\n\n if (typeof import.meta?.url !== 'undefined') {\n return path.dirname(fileURLToPath(import.meta.url));\n }\n\n return process.cwd();\n};\n\nexport const MAX_MANUAL_SPAN_PAYLOAD_SIZE = 1024 * 1024 * 10; // 10MB\nexport const TRUNCATION_SUFFIX = \"...[Laminar: truncated]\";\n\n/**\n * Cut an oversized span payload down to the limit rather than dropping it.\n *\n * Keeping the leading bytes preserves the start of the value, which is the useful part when\n * debugging. Mirrors `_truncate_payload` in the Python SDK.\n *\n * Callers pass the result of `JSON.stringify`, whose TS signature claims `string` but which\n * actually returns `undefined` for a top-level `undefined`, function, or symbol. Guard at\n * runtime and hand such values straight back: `setAttribute` treats them as a no-op, which is\n * the behaviour these payloads had before truncation existed.\n */\nexport const truncateSpanPayload = (\n serialized: string,\n kind: \"input\" | \"output\",\n): string => {\n if (typeof serialized !== \"string\") {\n return serialized;\n }\n if (serialized.length <= MAX_MANUAL_SPAN_PAYLOAD_SIZE) {\n return serialized;\n }\n logger.warn(\n `Laminar: span ${kind} is ${serialized.length} bytes, which exceeds the ` +\n `${MAX_MANUAL_SPAN_PAYLOAD_SIZE} byte limit. Truncating to the limit; ` +\n `the recorded value will not be valid JSON.`,\n );\n const keep = MAX_MANUAL_SPAN_PAYLOAD_SIZE - TRUNCATION_SUFFIX.length;\n return serialized.slice(0, keep) + TRUNCATION_SUFFIX;\n};\n\nexport const slicePayload = <T>(value: T, length: number) => {\n if (value === null || value === undefined) {\n return value;\n }\n\n const str = JSON.stringify(value);\n if (str.length <= length) {\n return value;\n }\n\n return (str.slice(0, length) + '...');\n};\n\nexport const isOtelAttributeValueType = (value: unknown): value is AttributeValue => {\n if (typeof value === 'string'\n || typeof value === 'number'\n || typeof value === 'boolean') {\n return true;\n }\n\n if (Array.isArray(value)) {\n const allStrings = value.every(value => (value == null) || typeof value === 'string');\n const allNumbers = value.every(value => (value == null) || typeof value === 'number');\n const allBooleans = value.every(value => (value == null) || typeof value === 'boolean');\n return allStrings || allNumbers || allBooleans;\n }\n return false;\n};\n\nexport const metadataToAttributes = (\n metadata: Record<string, unknown>,\n): Record<string, AttributeValue> => Object.fromEntries(\n Object.entries(metadata).map(([key, value]) => {\n if (isOtelAttributeValueType(value)) {\n return [`${ASSOCIATION_PROPERTIES}.metadata.${key}`, value];\n } else {\n return [`${ASSOCIATION_PROPERTIES}.metadata.${key}`, JSON.stringify(value)];\n }\n }),\n);\n\n/**\n * Get OTEL environment variable with priority order.\n * Checks in order:\n * 1. OTEL_EXPORTER_OTLP_TRACES_{varName}\n * 2. OTEL_EXPORTER_OTLP_{varName}\n * 3. OTEL_{varName}\n *\n * @param varName - The variable name (e.g., 'ENDPOINT', 'HEADERS', 'PROTOCOL')\n * @returns The environment variable value or undefined if not found\n */\nexport const getOtelEnvVar = (varName: string): string | undefined => {\n const candidates = [\n `OTEL_EXPORTER_OTLP_TRACES_${varName}`,\n `OTEL_EXPORTER_OTLP_${varName}`,\n `OTEL_${varName}`,\n ];\n\n for (const candidate of candidates) {\n const value = process?.env?.[candidate];\n if (value) {\n return value;\n }\n }\n return undefined;\n};\n\n/**\n * Check if OTEL configuration is available.\n * @returns true if OTEL endpoint is configured\n */\nexport const hasOtelConfig = (): boolean => !!getOtelEnvVar('ENDPOINT');\n\n/**\n * Parse OTEL headers string into a record object.\n * Format: key1=value1,key2=value2\n * Values are URL-decoded.\n *\n * @param headersStr - Headers string in OTEL format\n * @returns Parsed headers object\n */\nexport const parseOtelHeaders = (headersStr: string | undefined): Record<string, string> => {\n if (!headersStr) {\n return {};\n }\n\n const headers: Record<string, string> = {};\n for (const pair of headersStr.split(',')) {\n const equalIndex = pair.indexOf('=');\n if (equalIndex !== -1) {\n // Manually split instead of .split('=', 2) because\n // the latter only returns the first 2 elements of the array after the split\n const key = pair.substring(0, equalIndex).trim();\n const value = pair.substring(equalIndex + 1).trim();\n headers[key] = decodeURIComponent(value);\n }\n }\n return headers;\n};\n\n/**\n * Validate that either Laminar API key or OTEL configuration is present.\n * Throws an error if neither is configured.\n *\n * @param apiKey - The Laminar API key (if provided)\n * @throws Error if neither API key nor OTEL configuration is present\n */\nexport const validateTracingConfig = (apiKey?: string): void => {\n if (!apiKey && !hasOtelConfig()) {\n throw new Error(\n 'Please initialize the Laminar object with your project API key ' +\n 'or set the LMNR_PROJECT_API_KEY environment variable, ' +\n 'or configure OTEL environment variables (OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, etc.)',\n );\n }\n};\n\nexport const loadEnv = (\n options?: {\n quiet?: boolean;\n paths?: string[];\n },\n): void => {\n const nodeEnv = process.env.NODE_ENV || 'development';\n const envDir = process.cwd();\n\n // Files to load in order (lowest to highest priority)\n // Later files override earlier ones\n const envFiles = [\n '.env',\n '.env.local',\n `.env.${nodeEnv}`,\n `.env.${nodeEnv}.local`,\n ];\n\n const logLevel = process.env.LMNR_LOG_LEVEL ?? 'info';\n const verbose = ['debug', 'trace'].includes(logLevel.trim().toLowerCase());\n\n const quiet = options?.quiet ?? !verbose;\n\n config({\n path: options?.paths ?? envFiles.map(envFile => path.resolve(envDir, envFile)),\n quiet,\n });\n};\n\n/**\n * Converts an API base URL to the frontend/web URL.\n * - Converts https://api.lmnr.ai to https://www.laminar.sh\n * - Removes trailing slashes\n * - For localhost/127.0.0.1, ensures a port is specified (defaults to 5667)\n *\n * @param baseUrl - The API base URL (defaults to \"https://api.lmnr.ai\")\n * @returns The frontend URL\n */\nexport const getFrontendUrl = (\n baseUrl?: string,\n frontendPort?: number,\n): string => {\n let url = baseUrl ?? \"https://api.lmnr.ai\";\n if (url === \"https://api.lmnr.ai\") {\n url = \"https://www.laminar.sh\";\n }\n url = url.replace(/\\/$/, '');\n\n if (/localhost|127\\.0\\.0\\.1/.test(url)) {\n const port = frontendPort ?? url.match(/:\\d{1,5}$/g)?.[0]?.slice(1) ?? 5667;\n if (/:(\\d{1,5})$/.test(url)) {\n // URL has a port, replace it\n url = url.replace(/:\\d{1,5}$/g, `:${port}`);\n } else {\n // URL has no port, append it\n url = `${url}:${port}`;\n }\n }\n return url;\n};\n","import { config } from \"dotenv\";\nimport * as path from \"path\";\nimport pino from \"pino\";\nimport { PinoPretty } from \"pino-pretty\";\nimport { v4 } from \"uuid\";\nimport { errorMessage } from \"@lmnr-ai/types\";\n//#region package.json\nvar version = \"0.8.41\";\n//#endregion\n//#region src/version.ts\nfunction getLangVersion() {\n\tif (typeof process !== \"undefined\" && process.versions && process.versions.node) return `node-${process.versions.node}`;\n\tif (typeof navigator !== \"undefined\" && navigator.userAgent) return `browser-${navigator.userAgent}`;\n\treturn null;\n}\n//#endregion\n//#region src/resources/index.ts\nvar BaseResource = class {\n\tconstructor(baseHttpUrl, auth) {\n\t\tthis.baseHttpUrl = baseHttpUrl;\n\t\tthis.auth = auth;\n\t\tthis.credential = auth.type === \"apiKey\" ? auth.key : auth.token;\n\t}\n\t/** API path prefix: `/v1/cli` for CLI user-token auth, `/v1` otherwise. */\n\tget apiPrefix() {\n\t\treturn this.auth.type === \"userToken\" ? \"/v1/cli\" : \"/v1\";\n\t}\n\theaders() {\n\t\treturn {\n\t\t\tAuthorization: `Bearer ${this.credential}`,\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tAccept: \"application/json\",\n\t\t\t...this.auth.type === \"userToken\" ? { \"x-lmnr-project-id\": this.auth.projectId } : {}\n\t\t};\n\t}\n\tasync handleError(response) {\n\t\tconst errorMsg = await response.text();\n\t\tthrow new Error(`${response.status} ${errorMsg}`);\n\t}\n};\n//#endregion\n//#region src/resources/browser-events.ts\nvar BrowserEventsResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\tasync send({ sessionId, traceId, events }) {\n\t\tconst payload = {\n\t\t\tsessionId,\n\t\t\ttraceId,\n\t\t\tevents,\n\t\t\tsource: getLangVersion() ?? \"javascript\",\n\t\t\tsdkVersion: version\n\t\t};\n\t\tconst jsonString = JSON.stringify(payload);\n\t\tconst compressedStream = new Blob([jsonString], { type: \"application/json\" }).stream().pipeThrough(new CompressionStream(\"gzip\"));\n\t\tconst compressedData = await new Response(compressedStream).arrayBuffer();\n\t\tconst response = await fetch(this.baseHttpUrl + \"/v1/browser-sessions/events\", {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t...this.headers(),\n\t\t\t\t\"Content-Encoding\": \"gzip\"\n\t\t\t},\n\t\t\tbody: compressedData\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n};\n//#endregion\n//#region src/resources/cli.ts\n/**\n* Locale-aware, case-insensitive comparator for the project listing. Ordering\n* lives here — the single choke point every CLI surface (the `project list`\n* table + its `--json`, and the interactive picker used by `setup` / `plugin\n* add`) reads from — so the order can't drift between surfaces.\n*/\nconst projectCollator = new Intl.Collator(void 0, { sensitivity: \"base\" });\n/** Sort projects by workspace name, then project name (stable, human-scannable). */\nconst sortProjects = (projects) => [...projects].sort((a, b) => projectCollator.compare(a.workspaceName ?? \"\", b.workspaceName ?? \"\") || projectCollator.compare(a.name ?? \"\", b.name ?? \"\"));\n/**\n* User-scoped CLI endpoints that don't target a specific project. Authed by the\n* BetterAuth user JWT (the `credential`); deliberately does NOT send an\n* `x-lmnr-project-id` header (these routes are project discovery, pre-selection).\n*\n* Discovery exception: this resource always hits `/v1/cli/projects` with the\n* bare bearer and overrides `BaseResource.headers()`/`apiPrefix`, so it works\n* even when constructed with a `userToken` auth that has no real project id yet.\n*/\nvar CliResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/** Workspaces + projects the authenticated user can access. */\n\tasync listProjects() {\n\t\tconst response = await fetch(`${this.baseHttpUrl}/v1/cli/projects`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${this.credential}`,\n\t\t\t\tAccept: \"application/json\"\n\t\t\t}\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\tconst body = await response.json();\n\t\treturn Array.isArray(body?.projects) ? sortProjects(body.projects) : [];\n\t}\n\t/**\n\t* Resolve which project a project API key belongs to. Authed by the user JWT\n\t* (the bearer); the project key travels in the body, NOT in `Authorization`.\n\t* The server verifies the key and that the authenticated user is a member of\n\t* the resolved project. Returns a tri-state probe so callers can distinguish a\n\t* revoked key (401 → `invalid`) from a server/access problem (`unverifiable`).\n\t*/\n\tasync resolveProjectByApiKey(apiKey) {\n\t\tlet response;\n\t\ttry {\n\t\t\tresponse = await fetch(`${this.baseHttpUrl}/v1/cli/project`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${this.credential}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tAccept: \"application/json\"\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({ apiKey })\n\t\t\t});\n\t\t} catch {\n\t\t\treturn { status: \"unverifiable\" };\n\t\t}\n\t\tif (response.status === 401) return { status: \"invalid\" };\n\t\tif (!response.ok) return { status: \"unverifiable\" };\n\t\tconst body = await response.json().catch(() => null);\n\t\treturn body?.projectId ? {\n\t\t\tstatus: \"ok\",\n\t\t\tprojectId: body.projectId\n\t\t} : { status: \"unverifiable\" };\n\t}\n};\n//#endregion\n//#region src/utils.ts\nfunction initializeLogger(options) {\n\tconst colorize = options?.colorize ?? true;\n\tconst level = options?.level ?? process.env.LMNR_LOG_LEVEL?.toLowerCase()?.trim() ?? \"info\";\n\treturn pino({ level }, PinoPretty({\n\t\tcolorize,\n\t\tminimumLevel: level\n\t}));\n}\nconst logger$4 = initializeLogger();\nconst isStringUUID = (id) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id);\nconst newUUID = () => {\n\tif (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") return crypto.randomUUID();\n\telse return v4();\n};\nconst otelSpanIdToUUID = (spanId) => {\n\tlet id = spanId.toLowerCase();\n\tif (id.startsWith(\"0x\")) id = id.slice(2);\n\tif (id.length !== 16) logger$4.warn(`Span ID ${spanId} is not 16 hex chars long. This is not a valid OpenTelemetry span ID.`);\n\tif (!/^[0-9a-f]+$/.test(id)) {\n\t\tlogger$4.error(`Span ID ${spanId} is not a valid hex string. Generating a random UUID instead.`);\n\t\treturn newUUID();\n\t}\n\treturn id.padStart(32, \"0\").replace(/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/, \"$1-$2-$3-$4-$5\");\n};\nconst otelTraceIdToUUID = (traceId) => {\n\tlet id = traceId.toLowerCase();\n\tif (id.startsWith(\"0x\")) id = id.slice(2);\n\tif (id.length !== 32) logger$4.warn(`Trace ID ${traceId} is not 32 hex chars long. This is not a valid OpenTelemetry trace ID.`);\n\tif (!/^[0-9a-f]+$/.test(id)) {\n\t\tlogger$4.error(`Trace ID ${traceId} is not a valid hex string. Generating a random UUID instead.`);\n\t\treturn newUUID();\n\t}\n\treturn id.replace(/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/, \"$1-$2-$3-$4-$5\");\n};\nconst slicePayload = (value, length) => {\n\tif (value === null || value === void 0) return value;\n\tconst str = JSON.stringify(value);\n\tif (str.length <= length) return value;\n\treturn str.slice(0, length) + \"...\";\n};\nconst loadEnv = (options) => {\n\tconst nodeEnv = process.env.NODE_ENV || \"development\";\n\tconst envDir = process.cwd();\n\tconst envFiles = [\n\t\t\".env\",\n\t\t\".env.local\",\n\t\t`.env.${nodeEnv}`,\n\t\t`.env.${nodeEnv}.local`\n\t];\n\tconst logLevel = process.env.LMNR_LOG_LEVEL ?? \"info\";\n\tconst verbose = [\"debug\", \"trace\"].includes(logLevel.trim().toLowerCase());\n\tconst quiet = options?.quiet ?? !verbose;\n\tconfig({\n\t\tpath: options?.paths ?? envFiles.map((envFile) => path.resolve(envDir, envFile)),\n\t\tquiet\n\t});\n};\n//#endregion\n//#region src/resources/datasets.ts\nconst logger$3 = initializeLogger();\nconst DEFAULT_DATASET_PULL_LIMIT = 100;\nconst DEFAULT_DATASET_PUSH_BATCH_SIZE = 100;\nvar DatasetsResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* List all datasets.\n\t*\n\t* @returns {Promise<Dataset[]>} Array of datasets\n\t*/\n\tasync listDatasets() {\n\t\tconst response = await fetch(this.baseHttpUrl + this.apiPrefix + \"/datasets\", {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n\t/**\n\t* Get a dataset by name.\n\t*\n\t* @param {string} name - Name of the dataset\n\t* @returns {Promise<Dataset[]>} Array of datasets with matching name\n\t*/\n\tasync getDatasetByName(name) {\n\t\tconst params = new URLSearchParams({ name });\n\t\tconst response = await fetch(this.baseHttpUrl + `${this.apiPrefix}/datasets?${params.toString()}`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n\t/**\n\t* Push datapoints to a dataset.\n\t*\n\t* @param {Object} options - Push options\n\t* @param {Datapoint<D, T>[]} options.points - Datapoints to push\n\t* @param {string} [options.name] - Name of the dataset (either name or id must be provided)\n\t* @param {StringUUID} [options.id] - ID of the dataset (either name or id must be provided)\n\t* @param {number} [options.batchSize] - Batch size for pushing (default: 100)\n\t* @param {boolean} [options.createDataset] - Whether to create the dataset if it doesn't exist\n\t* @returns {Promise<PushDatapointsResponse | undefined>}\n\t*/\n\tasync push({ points, name, id, batchSize = DEFAULT_DATASET_PUSH_BATCH_SIZE, createDataset = false }) {\n\t\tif (!name && !id) throw new Error(\"Either name or id must be provided\");\n\t\tif (name && id) throw new Error(\"Only one of name or id must be provided\");\n\t\tif (createDataset && !name) throw new Error(\"Name must be provided when creating a new dataset\");\n\t\tconst identifier = name ? { name } : { datasetId: id };\n\t\tconst totalBatches = Math.ceil(points.length / batchSize);\n\t\tlet response;\n\t\tfor (let i = 0; i < points.length; i += batchSize) {\n\t\t\tconst batchNum = Math.floor(i / batchSize) + 1;\n\t\t\tlogger$3.debug(`Pushing batch ${batchNum} of ${totalBatches}`);\n\t\t\tconst batch = points.slice(i, i + batchSize);\n\t\t\tconst fetchResponse = await fetch(this.baseHttpUrl + this.apiPrefix + \"/datasets/datapoints\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: this.headers(),\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t...identifier,\n\t\t\t\t\tdatapoints: batch.map((point) => ({\n\t\t\t\t\t\tdata: point.data,\n\t\t\t\t\t\ttarget: point.target ?? {},\n\t\t\t\t\t\tmetadata: point.metadata ?? {}\n\t\t\t\t\t})),\n\t\t\t\t\tcreateDataset\n\t\t\t\t})\n\t\t\t});\n\t\t\tif (fetchResponse.status !== 200 && fetchResponse.status !== 201) await this.handleError(fetchResponse);\n\t\t\tresponse = await fetchResponse.json();\n\t\t}\n\t\treturn response;\n\t}\n\t/**\n\t* Pull datapoints from a dataset.\n\t*\n\t* @param {Object} options - Pull options\n\t* @param {string} [options.name] - Name of the dataset (either name or id must be provided)\n\t* @param {StringUUID} [options.id] - ID of the dataset (either name or id must be provided)\n\t* @param {number} [options.limit] - Maximum number of datapoints to return (default: 100)\n\t* @param {number} [options.offset] - Offset for pagination (default: 0)\n\t* @returns {Promise<GetDatapointsResponse<D, T>>}\n\t*/\n\tasync pull({ name, id, limit = DEFAULT_DATASET_PULL_LIMIT, offset = 0 }) {\n\t\tif (!name && !id) throw new Error(\"Either name or id must be provided\");\n\t\tif (name && id) throw new Error(\"Only one of name or id must be provided\");\n\t\tconst paramsObj = {\n\t\t\toffset: offset.toString(),\n\t\t\tlimit: limit.toString()\n\t\t};\n\t\tif (name) paramsObj.name = name;\n\t\telse paramsObj.datasetId = id;\n\t\tconst params = new URLSearchParams(paramsObj);\n\t\tconst response = await fetch(this.baseHttpUrl + `${this.apiPrefix}/datasets/datapoints?${params.toString()}`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n};\n//#endregion\n//#region src/resources/evals.ts\nconst logger$2 = initializeLogger();\nconst INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH = 16e6;\nvar EvalsResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* Initialize an evaluation.\n\t*\n\t* @param {string} name - Name of the evaluation\n\t* @param {string} groupName - Group name of the evaluation\n\t* @param {Record<string, any>} metadata - Optional metadata\n\t* @returns {Promise<InitEvaluationResponse>} Response from the evaluation initialization\n\t*/\n\tasync init(name, groupName, metadata) {\n\t\tconst response = await fetch(this.baseHttpUrl + \"/v1/evals\", {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({\n\t\t\t\tname: name ?? null,\n\t\t\t\tgroupName: groupName ?? null,\n\t\t\t\tmetadata: metadata ?? null\n\t\t\t})\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n\t/**\n\t* Create a new evaluation and return its ID.\n\t*\n\t* @param {string} [name] - Optional name of the evaluation\n\t* @param {string} [groupName] - An identifier to group evaluations\n\t* @param {Record<string, any>} [metadata] - Optional metadata\n\t* @returns {Promise<StringUUID>} The evaluation ID\n\t*/\n\tasync create(args) {\n\t\treturn (await this.init(args?.name, args?.groupName, args?.metadata)).id;\n\t}\n\t/**\n\t* Update an evaluation's name and/or metadata. The group ID is immutable.\n\t* Fields left undefined are kept unchanged.\n\t*\n\t* @param {Object} options - Update evaluation options\n\t* @param {string} options.evalId - The evaluation ID\n\t* @param {string} [options.name] - New name of the evaluation\n\t* @param {Record<string, any>} [options.metadata] - New metadata for the evaluation\n\t* @returns {Promise<InitEvaluationResponse>} The updated evaluation\n\t*/\n\tasync update({ evalId, name, metadata }) {\n\t\tconst response = await fetch(this.baseHttpUrl + `/v1/evals/${evalId}`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({\n\t\t\t\tname: name ?? null,\n\t\t\t\tmetadata: metadata ?? null\n\t\t\t})\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n\t/**\n\t* Create a new evaluation and return its ID.\n\t* @deprecated use `create` instead.\n\t*/\n\tasync createEvaluation(name, groupName, metadata) {\n\t\treturn (await this.init(name, groupName, metadata)).id;\n\t}\n\t/**\n\t* Create a datapoint for an evaluation.\n\t*\n\t* @param {Object} options - Create datapoint options\n\t* @param {string} options.evalId - The evaluation ID\n\t* @param {D} options.data - The input data for the executor\n\t* @param {T} [options.target] - The target/expected output for evaluators\n\t* @param {Record<string, any>} [options.metadata] - Optional metadata\n\t* @param {number} [options.index] - Optional index of the datapoint\n\t* @param {string} [options.traceId] - Optional trace ID\n\t* @returns {Promise<StringUUID>} The datapoint ID\n\t*/\n\tasync createDatapoint({ evalId, data, target, metadata, index, traceId }) {\n\t\tconst datapointId = newUUID();\n\t\tconst partialDatapoint = {\n\t\t\tid: datapointId,\n\t\t\tdata,\n\t\t\ttarget,\n\t\t\tindex: index ?? 0,\n\t\t\ttraceId: traceId ?? newUUID(),\n\t\t\texecutorSpanId: newUUID(),\n\t\t\tmetadata\n\t\t};\n\t\tawait this.saveDatapoints({\n\t\t\tevalId,\n\t\t\tdatapoints: [partialDatapoint]\n\t\t});\n\t\treturn datapointId;\n\t}\n\t/**\n\t* Update a datapoint with evaluation results.\n\t*\n\t* @param {Object} options - Update datapoint options\n\t* @param {string} options.evalId - The evaluation ID\n\t* @param {string} options.datapointId - The datapoint ID\n\t* @param {Record<string, number>} options.scores - The scores\n\t* @param {O} [options.executorOutput] - The executor output\n\t* @returns {Promise<void>}\n\t*/\n\tasync updateDatapoint({ evalId, datapointId, scores, executorOutput }) {\n\t\tconst response = await fetch(this.baseHttpUrl + `/v1/evals/${evalId}/datapoints/${datapointId}`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({\n\t\t\t\texecutorOutput,\n\t\t\t\tscores\n\t\t\t})\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n\t/**\n\t* Save evaluation datapoints.\n\t*\n\t* @param {Object} options - Save datapoints options\n\t* @param {string} options.evalId - ID of the evaluation\n\t* @param {EvaluationDatapoint<D, T, O>[]} options.datapoints - Datapoint to add\n\t* @param {string} [options.groupName] - Group name of the evaluation\n\t* @returns {Promise<void>} Response from the datapoint addition\n\t*/\n\tasync saveDatapoints({ evalId, datapoints, groupName }) {\n\t\tconst response = await fetch(this.baseHttpUrl + `/v1/evals/${evalId}/datapoints`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({\n\t\t\t\tpoints: datapoints.map((d) => ({\n\t\t\t\t\t...d,\n\t\t\t\t\tdata: slicePayload(d.data, INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH),\n\t\t\t\t\ttarget: slicePayload(d.target, INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH),\n\t\t\t\t\texecutorOutput: slicePayload(d.executorOutput, INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH)\n\t\t\t\t})),\n\t\t\t\tgroupName: groupName ?? null\n\t\t\t})\n\t\t});\n\t\tif (response.status === 413) return await this.retrySaveDatapoints({\n\t\t\tevalId,\n\t\t\tdatapoints,\n\t\t\tgroupName\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n\t/**\n\t* Get evaluation datapoints.\n\t*\n\t* @deprecated Use `client.datasets.pull()` instead.\n\t* @param {Object} options - Get datapoints options\n\t* @param {string} options.datasetName - Name of the dataset\n\t* @param {number} options.offset - Offset at which to start the query\n\t* @param {number} options.limit - Maximum number of datapoints to return\n\t* @returns {Promise<GetDatapointsResponse>} Response from the datapoint retrieval\n\t*/\n\tasync getDatapoints({ datasetName, offset, limit }) {\n\t\tlogger$2.warn(\"evals.getDatapoints() is deprecated. Use client.datasets.pull() instead.\");\n\t\tconst params = new URLSearchParams({\n\t\t\tname: datasetName,\n\t\t\toffset: offset.toString(),\n\t\t\tlimit: limit.toString()\n\t\t});\n\t\tconst response = await fetch(this.baseHttpUrl + `/v1/datasets/datapoints?${params.toString()}`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn await response.json();\n\t}\n\tasync retrySaveDatapoints({ evalId, datapoints, groupName, maxRetries = 25, initialLength = INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH }) {\n\t\tlet length = initialLength;\n\t\tlet lastResponse = null;\n\t\tfor (let i = 0; i < maxRetries; i++) {\n\t\t\tlogger$2.debug(`Retrying save datapoints... ${i + 1} of ${maxRetries}, length: ${length}`);\n\t\t\tconst response = await fetch(this.baseHttpUrl + `/v1/evals/${evalId}/datapoints`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: this.headers(),\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tpoints: datapoints.map((d) => ({\n\t\t\t\t\t\t...d,\n\t\t\t\t\t\tdata: slicePayload(d.data, length),\n\t\t\t\t\t\ttarget: slicePayload(d.target, length),\n\t\t\t\t\t\texecutorOutput: slicePayload(d.executorOutput, length)\n\t\t\t\t\t})),\n\t\t\t\t\tgroupName: groupName ?? null\n\t\t\t\t})\n\t\t\t});\n\t\t\tlastResponse = response;\n\t\t\tlength = Math.floor(length / 2);\n\t\t\tif (response.status !== 413) break;\n\t\t}\n\t\tif (lastResponse && !lastResponse.ok) await this.handleError(lastResponse);\n\t}\n};\n//#endregion\n//#region src/resources/evaluators.ts\n/**\n* Resource for creating evaluator scores\n*/\nvar EvaluatorsResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* Create a score for a span or trace\n\t*\n\t* @param {ScoreOptions} options - Score creation options\n\t* @param {string} options.name - Name of the score\n\t* @param {string} [options.traceId] - The trace ID to score (will be attached to top-level span)\n\t* @param {string} [options.spanId] - The span ID to score\n\t* @param {Record<string, any>} [options.metadata] - Additional metadata\n\t* @param {number} options.score - The score value (float)\n\t* @returns {Promise<void>}\n\t*\n\t* @example\n\t* // Score by trace ID (will attach to root span)\n\t* await evaluators.score({\n\t* name: \"quality\",\n\t* traceId: \"trace-id-here\",\n\t* score: 0.95,\n\t* metadata: { model: \"gpt-4\" }\n\t* });\n\t*\n\t* @example\n\t* // Score by span ID\n\t* await evaluators.score({\n\t* name: \"relevance\",\n\t* spanId: \"span-id-here\",\n\t* score: 0.87\n\t* });\n\t*/\n\tasync score(options) {\n\t\tconst { name, metadata, score } = options;\n\t\tlet payload;\n\t\tif (\"traceId\" in options && options.traceId) payload = {\n\t\t\tname,\n\t\t\tmetadata,\n\t\t\tscore,\n\t\t\tsource: \"Code\",\n\t\t\ttraceId: isStringUUID(options.traceId) ? options.traceId : otelTraceIdToUUID(options.traceId)\n\t\t};\n\t\telse if (\"spanId\" in options && options.spanId) payload = {\n\t\t\tname,\n\t\t\tmetadata,\n\t\t\tscore,\n\t\t\tsource: \"Code\",\n\t\t\tspanId: isStringUUID(options.spanId) ? options.spanId : otelSpanIdToUUID(options.spanId)\n\t\t};\n\t\telse throw new Error(\"Either 'traceId' or 'spanId' must be provided.\");\n\t\tconst response = await fetch(this.baseHttpUrl + \"/v1/evaluators/score\", {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify(payload)\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n};\n//#endregion\n//#region src/resources/rollout-sessions.ts\nconst logger$1 = initializeLogger();\n/**\n* Map the opaque HIT `response` payload onto a {@link CachedSpan} the provider\n* wrappers can replay. The server-side shape of `response` is not yet frozen\n* (app-server plan 01 leaves it as a `serde_json::Value`), so this stays\n* deliberately tolerant: the whole payload is serialized into `output` (the only\n* field the AI SDK wrapper's `parseCachedSpan` actually reads, via\n* `JSON.parse`), and a `finishReason` is surfaced into `attributes` when the\n* payload carries one. `name`/`input` are irrelevant to replay and left empty.\n*/\nconst toCachedSpan = (response) => {\n\tconst output = typeof response === \"string\" ? response : JSON.stringify(response ?? null);\n\tconst attributes = {};\n\tif (response !== null && typeof response === \"object\" && typeof response.finishReason === \"string\") attributes[\"ai.response.finishReason\"] = response.finishReason;\n\treturn {\n\t\tname: \"\",\n\t\tinput: \"\",\n\t\toutput,\n\t\tattributes\n\t};\n};\nvar RolloutSessionsResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* Idempotently register (upsert) a debug session on the backend, keyed on the\n\t* SDK-supplied session id. The backend stores the row so the session is\n\t* visible in the UI; a null/omitted name never clobbers a name set elsewhere.\n\t*\n\t* Returns the backend-resolved `projectId` (derived from the API key) so the\n\t* caller can build the debugger URL; null if the body can't be parsed.\n\t*/\n\tasync register({ sessionId, name }) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/rollouts/${sessionId}`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({ name })\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\ttry {\n\t\t\treturn (await response.json()).projectId ?? null;\n\t\t} catch (e) {\n\t\t\tlogger$1.warn(`Failed to parse rollout register response: ${errorMessage(e)}`);\n\t\t\treturn null;\n\t\t}\n\t}\n\t/**\n\t* Rename an existing debug session. Update-only: the backend returns 404 (and\n\t* this throws) when the session id is unknown for the project, so a mistyped\n\t* id surfaces as an error rather than silently creating a session. Creation\n\t* stays the SDK's job via {@link register}.\n\t*/\n\tasync setName({ sessionId, name }) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/rollouts/${sessionId}/name`, {\n\t\t\tmethod: \"PATCH\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({ name })\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n\t/**\n\t* Append a block to a debug session (debugger session blocks).\n\t*\n\t* A debug session renders as an ordered list of blocks; this writes one to the\n\t* backend keyed by session id. The CLI uses it for `text` blocks — standalone\n\t* agent notes attached post-factum via `lmnr-cli debug session add-note` — so\n\t* a note is tied to the SESSION, not to a specific trace / evaluation (those\n\t* blocks are written at ingest from `rollout.session_id` metadata).\n\t*\n\t* A 404 (the session is unknown for the project) is logged and swallowed\n\t* unless `failOnNotFound` is set — CLI callers pass it so an exit 0 means the\n\t* block actually landed. Any other non-OK status throws.\n\t*\n\t* Returns the created block id, or null when the response body can't be parsed.\n\t*/\n\tasync addBlock({ sessionId, type, content, failOnNotFound, signal }) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/rollouts/${sessionId}/blocks`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({\n\t\t\t\ttype,\n\t\t\t\tcontent\n\t\t\t}),\n\t\t\tsignal\n\t\t});\n\t\tif (response.status === 404) {\n\t\t\tconst message = `Could not add a note: HTTP 404 for session ${sessionId}. Either the session isn't registered in this project (mint one with \\`lmnr-cli debug session new\\`, or run under LMNR_DEBUG=1), or this Laminar server doesn't expose the session-blocks write endpoint (POST /v1/rollouts/{sessionId}/blocks) yet.`;\n\t\t\tif (failOnNotFound) throw new Error(message);\n\t\t\tlogger$1.warn(message);\n\t\t\treturn null;\n\t\t}\n\t\tif (!response.ok) await this.handleError(response);\n\t\ttry {\n\t\t\treturn (await response.json()).id ?? null;\n\t\t} catch (e) {\n\t\t\tlogger$1.warn(`Failed to parse add-block response: ${errorMessage(e)}`);\n\t\t\treturn null;\n\t\t}\n\t}\n\t/**\n\t* List a debug session's blocks in creation order.\n\t*\n\t* Returns every `trace` / `evaluation` / `text` block on the session — the\n\t* same data the debugger UI renders. Used by `lmnr-cli debug session summary`\n\t* to print a chronological digest of the session. Returns an empty array when\n\t* the session has no blocks or the body can't be parsed.\n\t*/\n\tasync listBlocks({ sessionId }) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/rollouts/${sessionId}/blocks`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\ttry {\n\t\t\tconst body = await response.json();\n\t\t\treturn (Array.isArray(body) ? body : body.blocks) ?? [];\n\t\t} catch (e) {\n\t\t\tlogger$1.warn(`Failed to parse list-blocks response: ${errorMessage(e)}`);\n\t\t\treturn [];\n\t\t}\n\t}\n\t/**\n\t* Look up the debug-replay cache for a single LLM call (debug-replay v2).\n\t*\n\t* The server is keyed by `inputHash` (hex blake3 of the canonicalized,\n\t* system-stripped input messages). It returns one of three outcomes:\n\t* - `{ outcome: \"hit\", response }` — a cached response to replay.\n\t* - `{ outcome: \"miss\" }` — no entry; caller latches live mode.\n\t* - `{ outcome: \"live\" }` — run this call live (COLD degrade).\n\t*\n\t* Error posture: a non-OK response or a transport error degrades to\n\t* `{ kind: \"live\" }` for THIS call only — it never throws and never latches\n\t* the process-wide live flag (only a real MISS does that). This keeps a flaky\n\t* cache backend from turning a replay into a crash.\n\t*/\n\tasync cache({ sessionId, replayTraceId, cacheUntil, inputHash }) {\n\t\tlet response;\n\t\ttry {\n\t\t\tresponse = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/rollouts/${sessionId}/cache`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: this.headers(),\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\treplayTraceId,\n\t\t\t\t\tcacheUntil,\n\t\t\t\t\tinputHash\n\t\t\t\t})\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tlogger$1.warn(`Debug cache lookup failed, running live: ${errorMessage(e)}`);\n\t\t\treturn { kind: \"live\" };\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tlogger$1.warn(`Debug cache lookup returned ${response.status}, running live`);\n\t\t\treturn { kind: \"live\" };\n\t\t}\n\t\tlet body;\n\t\ttry {\n\t\t\tbody = await response.json();\n\t\t} catch (e) {\n\t\t\tlogger$1.warn(`Failed to parse debug cache response, running live: ${errorMessage(e)}`);\n\t\t\treturn { kind: \"live\" };\n\t\t}\n\t\tswitch (body.outcome) {\n\t\t\tcase \"hit\":\n\t\t\t\tif (body.response === null || body.response === void 0) {\n\t\t\t\t\tlogger$1.warn(\"Debug cache HIT had no response payload, running live\");\n\t\t\t\t\treturn { kind: \"live\" };\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"hit\",\n\t\t\t\t\tcached: toCachedSpan(body.response)\n\t\t\t\t};\n\t\t\tcase \"miss\": return { kind: \"miss\" };\n\t\t\tcase \"live\": return { kind: \"live\" };\n\t\t\tdefault:\n\t\t\t\tlogger$1.warn(`Unknown debug cache outcome \"${body.outcome}\", running live`);\n\t\t\t\treturn { kind: \"live\" };\n\t\t}\n\t}\n\tasync delete({ sessionId }) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/rollouts/${sessionId}`, {\n\t\t\tmethod: \"DELETE\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n};\n//#endregion\n//#region src/resources/sql.ts\nvar SqlResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\tasync query(sql, parameters = {}) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/sql/query`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { ...this.headers() },\n\t\t\tbody: JSON.stringify({\n\t\t\t\tquery: sql,\n\t\t\t\tparameters\n\t\t\t})\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn (await response.json()).data;\n\t}\n\t/**\n\t* Fetch the queryable tables, columns, and enums. Server-rendered from\n\t* app-server's `query_engine::schema`, so it is the same source that backs\n\t* the MCP `query_laminar_sql` tool description — never a client-side copy.\n\t*/\n\tasync schema() {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/sql/schema`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: { ...this.headers() }\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn await response.json();\n\t}\n};\n//#endregion\n//#region src/resources/tags.ts\n/** Resource for tagging traces. */\nvar TagsResource = class extends BaseResource {\n\t/** Resource for tagging traces. */\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* Tag a trace with a list of tags. Note that the trace must be ended before\n\t* tagging it. You may want to call `await Laminar.flush()` after the trace\n\t* that you want to tag.\n\t*\n\t* @param {string | StringUUID} trace_id - The trace id to tag.\n\t* @param {string[] | string} tags - The tag or list of tags to add to the trace.\n\t* @returns {Promise<any>} The response from the server.\n\t* @example\n\t* ```javascript\n\t* import { Laminar, observe, LaminarClient } from \"@lmnr-ai/lmnr\";\n\t* Laminar.initialize();\n\t* const client = new LaminarClient();\n\t* let traceId: StringUUID | null = null;\n\t* // Make sure this is called outside of traced context.\n\t* await observe(\n\t* {\n\t* name: \"my-trace\",\n\t* },\n\t* async () => {\n\t* traceId = await Laminar.getTraceId();\n\t* await foo();\n\t* },\n\t* );\n\t*\n\t* // or make sure the trace is ended by this point.\n\t* await Laminar.flush();\n\t* if (traceId) {\n\t* await client.tags.tag(traceId, [\"tag1\", \"tag2\"]);\n\t* }\n\t* ```\n\t*/\n\tasync tag(trace_id, tags) {\n\t\tconst traceTags = Array.isArray(tags) ? tags : [tags];\n\t\tconst formattedTraceId = isStringUUID(trace_id) ? trace_id : otelTraceIdToUUID(trace_id);\n\t\tconst url = this.baseHttpUrl + \"/v1/tag\";\n\t\tconst payload = {\n\t\t\t\"traceId\": formattedTraceId,\n\t\t\t\"names\": traceTags\n\t\t};\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify(payload)\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n};\n//#endregion\n//#region src/resources/traces.ts\n/** Resource for post-factum operations on existing traces. */\nconst logger = initializeLogger();\nvar TracesResource = class extends BaseResource {\n\t/** Resource for post-factum operations on existing traces. */\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* Push a metadata patch to an existing trace.\n\t*\n\t* The patch is shallow-merged server-side into the trace's existing metadata\n\t* (`existing || patch`, last-write-wins per top-level key). Useful for\n\t* attaching post-factum signals — quality scores, human edits, triage labels —\n\t* to a trace that has already finished. The patch does NOT extend `endTime`\n\t* or change tokens / cost / top span / tags / span names. `numSpans` is\n\t* incremented by 1 (paid by the virtual span that carried the patch through\n\t* the ingestion queue) so the new ClickHouse row beats the prior version on\n\t* `ReplacingMergeTree(numSpans)`. No row is added to the `spans` table.\n\t*\n\t* Compared to `Laminar.setTraceMetadata` (which sets metadata on the\n\t* currently in-flight trace via OpenTelemetry attributes), this method\n\t* operates on a finished trace by trace id, so it must be called after the\n\t* trace has been flushed.\n\t*\n\t* A 404 response (the trace was not found in the project — typically because\n\t* it has not been flushed yet) is logged as a warning and the call returns\n\t* without throwing, since the 404 may be expected when pushing too soon\n\t* after the trace run. Pass `failOnNotFound: true` to throw instead (e.g.\n\t* CLI callers that must report the failure). Any other non-OK status throws.\n\t*\n\t* @param traceId - The trace id to push metadata to. Accepts a UUID string\n\t* or a 32-char OTel hex trace id.\n\t* @param metadata - The metadata patch. Top-level keys are merged into the\n\t* trace's existing metadata. Must be non-empty (the server rejects empty\n\t* patches with 400).\n\t* @param options - `failOnNotFound`: throw on 404 instead of warn-and-return.\n\t* @example\n\t* ```typescript\n\t* import { Laminar, observe, LaminarClient } from \"@lmnr-ai/lmnr\";\n\t* Laminar.initialize();\n\t* const client = new LaminarClient();\n\t*\n\t* let traceId: string | null = null;\n\t* await observe({ name: \"generate\" }, async () => {\n\t* traceId = await Laminar.getTraceId();\n\t* });\n\t* await Laminar.flush();\n\t*\n\t* if (traceId) {\n\t* await client.traces.pushMetadata(traceId, {\n\t* score: 0.85,\n\t* reviewer: \"alice\",\n\t* needsReview: false,\n\t* });\n\t* }\n\t* ```\n\t*/\n\tasync pushMetadata(traceId, metadata, options) {\n\t\tif (!metadata || Object.keys(metadata).length === 0) throw new Error(\"metadata must be a non-empty object\");\n\t\tconst formattedTraceId = isStringUUID(traceId) ? traceId : otelTraceIdToUUID(traceId);\n\t\tconst url = this.baseHttpUrl + this.apiPrefix + \"/traces/metadata\";\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({\n\t\t\t\ttraceId: formattedTraceId,\n\t\t\t\tmetadata\n\t\t\t})\n\t\t});\n\t\tif (response.status === 404) {\n\t\t\tconst message = `Trace ${formattedTraceId} not found. The trace may not have been flushed yet — call await Laminar.flush() and retry.`;\n\t\t\tif (options?.failOnNotFound) throw new Error(message);\n\t\t\tlogger.warn(message);\n\t\t\treturn;\n\t\t}\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n};\n//#endregion\n//#region src/index.ts\nvar LaminarClient = class LaminarClient {\n\tconstructor({ baseUrl, port, auth, projectApiKey, cliUserProjectId } = {}) {\n\t\tloadEnv();\n\t\tthis.auth = LaminarClient.normalizeAuth(auth, projectApiKey, cliUserProjectId);\n\t\tconst httpPort = port ?? (baseUrl?.match(/:\\d{1,5}$/g) ? parseInt(baseUrl.match(/:\\d{1,5}$/g)[0].slice(1)) : 443);\n\t\tconst baseUrlNoPort = (baseUrl ?? process.env.LMNR_BASE_URL)?.replace(/\\/$/, \"\").replace(/:\\d{1,5}$/g, \"\");\n\t\tthis.baseUrl = `${baseUrlNoPort ?? \"https://api.lmnr.ai\"}:${httpPort}`;\n\t\tthis._browserEvents = new BrowserEventsResource(this.baseUrl, this.auth);\n\t\tthis._cli = new CliResource(this.baseUrl, this.auth);\n\t\tthis._datasets = new DatasetsResource(this.baseUrl, this.auth);\n\t\tthis._evals = new EvalsResource(this.baseUrl, this.auth);\n\t\tthis._evaluators = new EvaluatorsResource(this.baseUrl, this.auth);\n\t\tthis._rolloutSessions = new RolloutSessionsResource(this.baseUrl, this.auth);\n\t\tthis._sql = new SqlResource(this.baseUrl, this.auth);\n\t\tthis._tags = new TagsResource(this.baseUrl, this.auth);\n\t\tthis._traces = new TracesResource(this.baseUrl, this.auth);\n\t}\n\t/**\n\t* The fully-resolved API origin every resource fetches from, e.g.\n\t* `http://localhost:8000`. Already normalized: trailing slash removed, any\n\t* port embedded in `baseUrl` stripped, and the effective port appended.\n\t*\n\t* Exposed so callers can name the real address in diagnostics instead of\n\t* rebuilding it from `baseUrl` + `port` — that reconstruction drifts from\n\t* this normalization and prints things like `http://host:8000:9000`.\n\t*/\n\tget apiBaseUrl() {\n\t\treturn this.baseUrl;\n\t}\n\t/**\n\t* Normalize the constructor's auth inputs into a {@link LaminarAuth} union.\n\t* Precedence: an explicit `auth` wins; otherwise the legacy\n\t* `projectApiKey` (+ optional `cliUserProjectId`) is mapped — a present\n\t* `cliUserProjectId` selects the user-token surface, otherwise the project\n\t* key surface. Falls back to `LMNR_PROJECT_API_KEY` as a project key.\n\t*/\n\tstatic normalizeAuth(auth, projectApiKey, cliUserProjectId) {\n\t\tif (auth) return auth;\n\t\tconst key = projectApiKey ?? process.env.LMNR_PROJECT_API_KEY;\n\t\tif (cliUserProjectId) return {\n\t\t\ttype: \"userToken\",\n\t\t\ttoken: key,\n\t\t\tprojectId: cliUserProjectId\n\t\t};\n\t\treturn {\n\t\t\ttype: \"apiKey\",\n\t\t\tkey\n\t\t};\n\t}\n\tget browserEvents() {\n\t\treturn this._browserEvents;\n\t}\n\tget cli() {\n\t\treturn this._cli;\n\t}\n\tget datasets() {\n\t\treturn this._datasets;\n\t}\n\tget evals() {\n\t\treturn this._evals;\n\t}\n\tget evaluators() {\n\t\treturn this._evaluators;\n\t}\n\tget rolloutSessions() {\n\t\treturn this._rolloutSessions;\n\t}\n\tget sql() {\n\t\treturn this._sql;\n\t}\n\tget tags() {\n\t\treturn this._tags;\n\t}\n\tget traces() {\n\t\treturn this._traces;\n\t}\n};\n//#endreg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mBAAmB,KAAK,SAAS,KAAK,IAAI;EACjE,KAAK,mBAAmB,IAAI,wBAAwB,KAAK,SAAS,KAAK,IAAI;EAC3E,KAAK,OAAO,IAAI,YAAY,KAAK,SAAS,KAAK,IAAI;EACnD,KAAK,QAAQ,IAAI,aAAa,KAAK,SAAS,KAAK,IAAI;EACrD,KAAK,UAAU,IAAI,eAAe,KAAK,SAAS,KAAK,IAAI;CAC1D;;;;;;;;;;CAUA,IAAI,aAAa;EAChB,OAAO,KAAK;CACb;;;;;;;;CAQA,OAAO,cAAc,MAAM,eAAe,kBAAkB;EAC3D,IAAI,MAAM,OAAO;EACjB,MAAM,MAAM,iBAAiB,QAAQ,IAAI;EACzC,IAAI,kBAAkB,OAAO;GAC5B,MAAM;GACN,OAAO;GACP,WAAW;EACZ;EACA,OAAO;GACN,MAAM;GACN;EACD;CACD;CACA,IAAI,gBAAgB;EACnB,OAAO,KAAK;CACb;CACA,IAAI,MAAM;EACT,OAAO,KAAK;CACb;CACA,IAAI,WAAW;EACd,OAAO,KAAK;CACb;CACA,IAAI,QAAQ;EACX,OAAO,KAAK;CACb;CACA,IAAI,aAAa;EAChB,OAAO,KAAK;CACb;CACA,IAAI,kBAAkB;EACrB,OAAO,KAAK;CACb;CACA,IAAI,MAAM;EACT,OAAO,KAAK;CACb;CACA,IAAI,OAAO;EACV,OAAO,KAAK;CACb;CACA,IAAI,SAAS;EACZ,OAAO,KAAK;CACb;AACD"}
@@ -169,6 +169,44 @@ interface SessionBlock {
169
169
  /** Type-specific payload; narrow via the `*BlockContent` interfaces. */
170
170
  content: Record<string, unknown>;
171
171
  } //#endregion
172
+ //#region src/sql-schema.d.ts
173
+ /**
174
+ * Shared contract for `GET /v1/sql/schema` (and its `/v1/cli` twin) — the
175
+ * logical tables, columns, and enums the SQL engine exposes.
176
+ *
177
+ * The server serializes this straight from app-server's
178
+ * `query_engine::schema` consts, which also render the MCP `query_laminar_sql`
179
+ * tool description and the Platform Agent prompt. That is the point: the CLI
180
+ * used to carry a hand-maintained copy, and it drifted badly enough to
181
+ * advertise columns that did not exist. Do NOT reintroduce a local copy —
182
+ * `lmnr-cli sql schema` renders whatever the server returns.
183
+ */
184
+ /** One column of a queryable table. `type` is the ClickHouse type as a string. */
185
+ interface SqlSchemaColumn {
186
+ name: string;
187
+ /** ClickHouse type, e.g. `UUID`, `DateTime64(9,'UTC')`, `String (enum status)`. */
188
+ type: string;
189
+ description: string;
190
+ }
191
+ /**
192
+ * One logical table. The caller writes this name; the engine rewrites it to a
193
+ * project-scoped view.
194
+ */
195
+ interface SqlSchemaTable {
196
+ name: string;
197
+ description: string;
198
+ columns: SqlSchemaColumn[];
199
+ }
200
+ /** A constrained column and the literals it accepts. */
201
+ interface SqlSchemaEnum {
202
+ name: string;
203
+ values: string[];
204
+ }
205
+ /** Full response body of the schema endpoint. */
206
+ interface SqlSchema {
207
+ tables: SqlSchemaTable[];
208
+ enums: SqlSchemaEnum[];
209
+ } //#endregion
172
210
  //#region src/tracing.d.ts
173
211
  /**
174
212
  * Span types to categorize spans.
@@ -713,6 +751,12 @@ declare class RolloutSessionsResource extends BaseResource {
713
751
  declare class SqlResource extends BaseResource {
714
752
  constructor(baseHttpUrl: string, auth: LaminarAuth);
715
753
  query(sql: string, parameters?: Record<string, any>): Promise<Array<Record<string, any>>>;
754
+ /**
755
+ * Fetch the queryable tables, columns, and enums. Server-rendered from
756
+ * app-server's `query_engine::schema`, so it is the same source that backs
757
+ * the MCP `query_laminar_sql` tool description — never a client-side copy.
758
+ */
759
+ schema(): Promise<SqlSchema>;
716
760
  } //#endregion
717
761
  //#region src/resources/tags.d.ts
718
762
  declare class TagsResource extends BaseResource {
@@ -854,6 +898,16 @@ declare class LaminarClient {
854
898
  */
855
899
  cliUserProjectId?: string;
856
900
  });
901
+ /**
902
+ * The fully-resolved API origin every resource fetches from, e.g.
903
+ * `http://localhost:8000`. Already normalized: trailing slash removed, any
904
+ * port embedded in `baseUrl` stripped, and the effective port appended.
905
+ *
906
+ * Exposed so callers can name the real address in diagnostics instead of
907
+ * rebuilding it from `baseUrl` + `port` — that reconstruction drifts from
908
+ * this normalization and prints things like `http://host:8000:9000`.
909
+ */
910
+ get apiBaseUrl(): string;
857
911
  /**
858
912
  * Normalize the constructor's auth inputs into a {@link LaminarAuth} union.
859
913
  * Precedence: an explicit `auth` wins; otherwise the legacy
@@ -878,11 +932,18 @@ declare abstract class EvaluationDataset<D, T> {
878
932
  slice(start: number, end: number): Promise<Datapoint<D, T>[]>;
879
933
  abstract size(): Promise<number> | number;
880
934
  abstract get(index: number): Promise<Datapoint<D, T>> | Datapoint<D, T>;
935
+ sourceDataset(): LaminarDataset<D, T> | undefined;
936
+ take(n: number): EvaluationDataset<D, T>;
937
+ select(indices: number[]): EvaluationDataset<D, T>;
938
+ shuffle({
939
+ seed
940
+ }?: {
941
+ seed?: number;
942
+ }): EvaluationDataset<D, T>;
881
943
  }
882
944
  declare class LaminarDataset<D, T> extends EvaluationDataset<D, T> {
883
- private fetchedItems;
945
+ private pages;
884
946
  private len;
885
- private offset;
886
947
  private fetchSize;
887
948
  private client;
888
949
  name: string | undefined;
@@ -892,7 +953,9 @@ declare class LaminarDataset<D, T> extends EvaluationDataset<D, T> {
892
953
  fetchSize?: number;
893
954
  });
894
955
  setClient(client: LaminarClient): void;
895
- private fetchBatch;
956
+ sourceDataset(): LaminarDataset<D, T> | undefined;
957
+ private fetchPage;
958
+ private doFetchPage;
896
959
  size(): Promise<number>;
897
960
  get(index: number): Promise<Datapoint<D, T>>;
898
961
  /**
@@ -31324,6 +31387,7 @@ declare class Evaluation<D, T, O> {
31324
31387
  private traceExportBatchSize;
31325
31388
  private uploadPromises;
31326
31389
  private client;
31390
+ private datasetSource;
31327
31391
  constructor({
31328
31392
  data,
31329
31393
  executor,
@@ -31368,4 +31432,4 @@ declare function evaluate<D, T, O>({
31368
31432
  }: EvaluationConstructorProps<D, T, O>): Promise<EvaluationRunResult | undefined>;
31369
31433
  //#endregion
31370
31434
  export { __exportAll as C, TracingLevel as S, MaskInputOptions as _, HumanEvaluator as a, SpanType as b, InitializeOptions as c, LaminarClient as d, Dataset as f, LaminarSpanContext as g, Event as h, EvaluatorFunctionReturn as i, EvaluationDataset as l, EvaluationDatapointDatasetLink as m, Evaluation as n, evaluate as o, EvaluationDatapoint as p, EvaluatorFunction as r, StringUUID as s, Datapoint as t, LaminarDataset as u, PushDatapointsResponse as v, TraceType as x, SessionRecordingOptions as y };
31371
- //# sourceMappingURL=evaluations-CDYtUG8k.d.cts.map
31435
+ //# sourceMappingURL=evaluations-CeDsphK5.d.cts.map
@@ -170,6 +170,44 @@ interface SessionBlock {
170
170
  /** Type-specific payload; narrow via the `*BlockContent` interfaces. */
171
171
  content: Record<string, unknown>;
172
172
  } //#endregion
173
+ //#region src/sql-schema.d.ts
174
+ /**
175
+ * Shared contract for `GET /v1/sql/schema` (and its `/v1/cli` twin) — the
176
+ * logical tables, columns, and enums the SQL engine exposes.
177
+ *
178
+ * The server serializes this straight from app-server's
179
+ * `query_engine::schema` consts, which also render the MCP `query_laminar_sql`
180
+ * tool description and the Platform Agent prompt. That is the point: the CLI
181
+ * used to carry a hand-maintained copy, and it drifted badly enough to
182
+ * advertise columns that did not exist. Do NOT reintroduce a local copy —
183
+ * `lmnr-cli sql schema` renders whatever the server returns.
184
+ */
185
+ /** One column of a queryable table. `type` is the ClickHouse type as a string. */
186
+ interface SqlSchemaColumn {
187
+ name: string;
188
+ /** ClickHouse type, e.g. `UUID`, `DateTime64(9,'UTC')`, `String (enum status)`. */
189
+ type: string;
190
+ description: string;
191
+ }
192
+ /**
193
+ * One logical table. The caller writes this name; the engine rewrites it to a
194
+ * project-scoped view.
195
+ */
196
+ interface SqlSchemaTable {
197
+ name: string;
198
+ description: string;
199
+ columns: SqlSchemaColumn[];
200
+ }
201
+ /** A constrained column and the literals it accepts. */
202
+ interface SqlSchemaEnum {
203
+ name: string;
204
+ values: string[];
205
+ }
206
+ /** Full response body of the schema endpoint. */
207
+ interface SqlSchema {
208
+ tables: SqlSchemaTable[];
209
+ enums: SqlSchemaEnum[];
210
+ } //#endregion
173
211
  //#region src/tracing.d.ts
174
212
  /**
175
213
  * Span types to categorize spans.
@@ -714,6 +752,12 @@ declare class RolloutSessionsResource extends BaseResource {
714
752
  declare class SqlResource extends BaseResource {
715
753
  constructor(baseHttpUrl: string, auth: LaminarAuth);
716
754
  query(sql: string, parameters?: Record<string, any>): Promise<Array<Record<string, any>>>;
755
+ /**
756
+ * Fetch the queryable tables, columns, and enums. Server-rendered from
757
+ * app-server's `query_engine::schema`, so it is the same source that backs
758
+ * the MCP `query_laminar_sql` tool description — never a client-side copy.
759
+ */
760
+ schema(): Promise<SqlSchema>;
717
761
  } //#endregion
718
762
  //#region src/resources/tags.d.ts
719
763
  declare class TagsResource extends BaseResource {
@@ -855,6 +899,16 @@ declare class LaminarClient {
855
899
  */
856
900
  cliUserProjectId?: string;
857
901
  });
902
+ /**
903
+ * The fully-resolved API origin every resource fetches from, e.g.
904
+ * `http://localhost:8000`. Already normalized: trailing slash removed, any
905
+ * port embedded in `baseUrl` stripped, and the effective port appended.
906
+ *
907
+ * Exposed so callers can name the real address in diagnostics instead of
908
+ * rebuilding it from `baseUrl` + `port` — that reconstruction drifts from
909
+ * this normalization and prints things like `http://host:8000:9000`.
910
+ */
911
+ get apiBaseUrl(): string;
858
912
  /**
859
913
  * Normalize the constructor's auth inputs into a {@link LaminarAuth} union.
860
914
  * Precedence: an explicit `auth` wins; otherwise the legacy
@@ -879,11 +933,18 @@ declare abstract class EvaluationDataset<D, T> {
879
933
  slice(start: number, end: number): Promise<Datapoint<D, T>[]>;
880
934
  abstract size(): Promise<number> | number;
881
935
  abstract get(index: number): Promise<Datapoint<D, T>> | Datapoint<D, T>;
936
+ sourceDataset(): LaminarDataset<D, T> | undefined;
937
+ take(n: number): EvaluationDataset<D, T>;
938
+ select(indices: number[]): EvaluationDataset<D, T>;
939
+ shuffle({
940
+ seed
941
+ }?: {
942
+ seed?: number;
943
+ }): EvaluationDataset<D, T>;
882
944
  }
883
945
  declare class LaminarDataset<D, T> extends EvaluationDataset<D, T> {
884
- private fetchedItems;
946
+ private pages;
885
947
  private len;
886
- private offset;
887
948
  private fetchSize;
888
949
  private client;
889
950
  name: string | undefined;
@@ -893,7 +954,9 @@ declare class LaminarDataset<D, T> extends EvaluationDataset<D, T> {
893
954
  fetchSize?: number;
894
955
  });
895
956
  setClient(client: LaminarClient): void;
896
- private fetchBatch;
957
+ sourceDataset(): LaminarDataset<D, T> | undefined;
958
+ private fetchPage;
959
+ private doFetchPage;
897
960
  size(): Promise<number>;
898
961
  get(index: number): Promise<Datapoint<D, T>>;
899
962
  /**
@@ -31325,6 +31388,7 @@ declare class Evaluation<D, T, O> {
31325
31388
  private traceExportBatchSize;
31326
31389
  private uploadPromises;
31327
31390
  private client;
31391
+ private datasetSource;
31328
31392
  constructor({
31329
31393
  data,
31330
31394
  executor,
@@ -31369,4 +31433,4 @@ declare function evaluate<D, T, O>({
31369
31433
  }: EvaluationConstructorProps<D, T, O>): Promise<EvaluationRunResult | undefined>;
31370
31434
  //#endregion
31371
31435
  export { TracingLevel as S, MaskInputOptions as _, HumanEvaluator as a, SpanType as b, InitializeOptions as c, LaminarClient as d, Dataset as f, LaminarSpanContext as g, Event as h, EvaluatorFunctionReturn as i, EvaluationDataset as l, EvaluationDatapointDatasetLink as m, Evaluation as n, evaluate as o, EvaluationDatapoint as p, EvaluatorFunction as r, StringUUID as s, Datapoint as t, LaminarDataset as u, PushDatapointsResponse as v, TraceType as x, SessionRecordingOptions as y };
31372
- //# sourceMappingURL=evaluations-BVOIJvt0.d.mts.map
31436
+ //# sourceMappingURL=evaluations-pCcE5lVy.d.mts.map
@@ -1,5 +1,5 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-CVvi-lCc.cjs");
2
- const require_dist = require("./dist-UjRFzemZ.cjs");
2
+ const require_dist = require("./dist-BNoIH9xW.cjs");
3
3
  let path = require("path");
4
4
  path = require_rolldown_runtime.__toESM(path);
5
5
  let fs = require("fs");
@@ -541,4 +541,4 @@ Object.defineProperty(exports, "writeToFile", {
541
541
  }
542
542
  });
543
543
 
544
- //# sourceMappingURL=file-utils-DTijgWTv.cjs.map
544
+ //# sourceMappingURL=file-utils-B7VBQSna.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"file-utils-DTijgWTv.cjs","names":["initializeLogger","fs","errorMessage","asString","generateCsv","mkConfig"],"sources":["../../../node_modules/.pnpm/csv-parser@3.2.1/node_modules/csv-parser/index.js","../../../node_modules/.pnpm/export-to-csv@1.4.0/node_modules/export-to-csv/output/index.js","../src/cli/file-utils.ts"],"sourcesContent":["const { Transform } = require('stream')\n\nconst [cr] = Buffer.from('\\r')\nconst [nl] = Buffer.from('\\n')\nconst defaults = {\n escape: '\"',\n headers: null,\n mapHeaders: ({ header }) => header,\n mapValues: ({ value }) => value,\n newline: '\\n',\n quote: '\"',\n raw: false,\n separator: ',',\n skipComments: false,\n skipLines: null,\n maxRowBytes: Number.MAX_SAFE_INTEGER,\n strict: false,\n outputByteOffset: false\n}\n\nconst DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype'])\n\nfunction sanitizeHeader(header) {\n if (typeof header !== 'string') {\n return null\n }\n\n if (DANGEROUS_KEYS.has(header)) {\n return null\n }\n\n return header\n}\n\nclass CsvParser extends Transform {\n constructor (opts = {}) {\n super({ objectMode: true, highWaterMark: 16 })\n\n if (Array.isArray(opts)) opts = { headers: opts }\n\n const options = Object.assign({}, defaults, opts)\n\n options.customNewline = options.newline !== defaults.newline\n\n for (const key of ['newline', 'quote', 'separator']) {\n if (typeof options[key] !== 'undefined') {\n ([options[key]] = Buffer.from(options[key]))\n }\n }\n\n // if escape is not defined on the passed options, use the end value of quote\n options.escape = (opts || {}).escape ? Buffer.from(options.escape)[0] : options.quote\n\n this.state = {\n empty: options.raw ? Buffer.alloc(0) : '',\n escaped: false,\n first: true,\n lineNumber: 0,\n previousEnd: 0,\n rowLength: 0,\n quoted: false\n }\n\n this._prev = null\n\n if (options.headers === false) {\n // enforce, as the column length check will fail if headers:false\n options.strict = false\n }\n\n if (options.headers || options.headers === false) {\n this.state.first = false\n }\n\n this.options = options\n this.headers = options.headers\n this.bytesRead = 0\n }\n\n parseCell (buffer, start, end) {\n const { escape, quote } = this.options\n // remove quotes from quoted cells\n if (buffer[start] === quote && buffer[end - 1] === quote) {\n start++\n end--\n }\n\n let y = start\n\n for (let i = start; i < end; i++) {\n // check for escape characters and skip them\n if (buffer[i] === escape && i + 1 < end && buffer[i + 1] === quote) {\n i++\n }\n\n if (y !== i) {\n buffer[y] = buffer[i]\n }\n y++\n }\n\n return this.parseValue(buffer, start, y)\n }\n\n parseLine (buffer, start, end) {\n const { customNewline, escape, mapHeaders, mapValues, quote, separator, skipComments, skipLines } = this.options\n\n end-- // trim newline\n if (!customNewline && buffer.length && buffer[end - 1] === cr) {\n end--\n }\n\n const comma = separator\n const cells = []\n let isQuoted = false\n let offset = start\n\n if (skipComments) {\n const char = typeof skipComments === 'string' ? skipComments : '#'\n if (buffer[start] === Buffer.from(char)[0]) {\n return\n }\n }\n\n const mapValue = (value) => {\n if (this.state.first) {\n return value\n }\n\n const index = cells.length\n const header = this.headers[index]\n\n return mapValues({ header, index, value })\n }\n\n for (let i = start; i < end; i++) {\n const isStartingQuote = !isQuoted && buffer[i] === quote\n const isEndingQuote = isQuoted && buffer[i] === quote && i + 1 <= end && buffer[i + 1] === comma\n const isEscape = isQuoted && buffer[i] === escape && i + 1 < end && buffer[i + 1] === quote\n\n if (isStartingQuote || isEndingQuote) {\n isQuoted = !isQuoted\n continue\n } else if (isEscape) {\n i++\n continue\n }\n\n if (buffer[i] === comma && !isQuoted) {\n let value = this.parseCell(buffer, offset, i)\n value = mapValue(value)\n cells.push(value)\n offset = i + 1\n }\n }\n\n if (offset < end) {\n let value = this.parseCell(buffer, offset, end)\n value = mapValue(value)\n cells.push(value)\n }\n\n if (buffer[end - 1] === comma) {\n cells.push(mapValue(this.state.empty))\n }\n\n const skip = skipLines && skipLines > this.state.lineNumber\n this.state.lineNumber++\n\n if (this.state.first && !skip) {\n this.state.first = false\n this.headers = cells.map((header, index) => {\n const mapped = mapHeaders({ header, index })\n\n if (mapped === null) {\n return null\n }\n\n return sanitizeHeader(mapped)\n })\n\n this.emit('headers', this.headers)\n return\n }\n\n if (!skip && this.options.strict && cells.length !== this.headers.length) {\n const e = new RangeError('Row length does not match headers')\n this.emit('error', e)\n } else {\n if (!skip) {\n const byteOffset = this.bytesRead - buffer.length + start\n this.writeRow(cells, byteOffset)\n }\n }\n }\n\n parseValue (buffer, start, end) {\n if (this.options.raw) {\n return buffer.slice(start, end)\n }\n\n return buffer.toString('utf-8', start, end)\n }\n\n writeRow (cells, byteOffset) {\n const headers = (this.headers === false) ? cells.map((value, index) => index) : this.headers\n\n const row = cells.reduce((o, cell, index) => {\n const header = headers[index]\n if (header === null) return o // skip columns\n if (header !== undefined) {\n o[header] = cell\n } else {\n o[`_${index}`] = cell\n }\n return o\n }, {})\n\n if (this.options.outputByteOffset) {\n this.push({ row, byteOffset })\n } else {\n this.push(row)\n }\n }\n\n _flush (cb) {\n if (this.state.escaped || !this._prev) return cb()\n this.parseLine(this._prev, this.state.previousEnd, this._prev.length + 1) // plus since online -1s\n cb()\n }\n\n _transform (data, enc, cb) {\n if (typeof data === 'string') {\n data = Buffer.from(data)\n }\n\n const { escape, quote } = this.options\n let start = 0\n let buffer = data\n this.bytesRead += data.byteLength\n\n if (this._prev) {\n start = this._prev.length\n buffer = Buffer.concat([this._prev, data])\n this._prev = null\n }\n\n const bufferLength = buffer.length\n\n for (let i = start; i < bufferLength; i++) {\n const chr = buffer[i]\n const nextChr = i + 1 < bufferLength ? buffer[i + 1] : null\n\n this.state.rowLength++\n if (this.state.rowLength > this.options.maxRowBytes) {\n return cb(new Error('Row exceeds the maximum size'))\n }\n\n if (!this.state.escaped && chr === escape && nextChr === quote && i !== start) {\n this.state.escaped = true\n continue\n } else if (chr === quote) {\n if (this.state.escaped) {\n this.state.escaped = false\n // non-escaped quote (quoting the cell)\n } else {\n this.state.quoted = !this.state.quoted\n }\n continue\n }\n\n if (!this.state.quoted) {\n if (this.state.first && !this.options.customNewline) {\n if (chr === nl) {\n this.options.newline = nl\n } else if (chr === cr) {\n if (nextChr !== nl) {\n this.options.newline = cr\n }\n }\n }\n\n if (chr === this.options.newline) {\n this.parseLine(buffer, this.state.previousEnd, i + 1)\n this.state.previousEnd = i + 1\n this.state.rowLength = 0\n }\n }\n }\n\n if (this.state.previousEnd === bufferLength) {\n this.state.previousEnd = 0\n return cb()\n }\n\n if (bufferLength - this.state.previousEnd < data.length) {\n this._prev = data\n this.state.previousEnd -= (bufferLength - data.length)\n return cb()\n }\n\n this._prev = buffer\n cb()\n }\n}\n\nmodule.exports = (opts) => new CsvParser(opts)\n","var q;(function(x){x[\"csv\"]=\"text/csv\";x[\"tsv\"]=\"text/tab-separated-values\";x[\"plain\"]=\"text/plain\"})(q||(q={}));var X=(W)=>W,z=(W)=>W,Z=X,_=X,Y=X,N=X,V=X;var h={fieldSeparator:\",\",decimalSeparator:\".\",quoteStrings:!0,quoteCharacter:'\"',showTitle:!1,title:\"My Generated Report\",filename:\"generated\",showColumnHeaders:!0,useTextFile:!1,fileExtension:\"csv\",mediaType:q.csv,useBom:!0,columnHeaders:[],useKeysAsHeaders:!1,boolDisplay:{true:\"TRUE\",false:\"FALSE\"},replaceUndefinedWith:\"\"},F=\"\\r\\n\",R=\"\\uFEFF\",G=(W)=>Object.assign({},h,W);class K extends Error{constructor(W){super(W);this.name=\"CsvGenerationError\"}}class B extends Error{constructor(W){super(W);this.name=\"EmptyHeadersError\"}}class L extends Error{constructor(W){super(W);this.name=\"CsvDownloadEnvironmentError\"}}class P extends Error{constructor(W){super(W);this.name=\"UnsupportedDataFormatError\"}}var s=function(W,$){if($=='\"'&&W.indexOf('\"')>-1)return W.replace(/\"/g,'\"\"');return W},w=(W)=>typeof W===\"object\"?N(W.key):N(W),y=(W)=>typeof W===\"object\"?V(W.displayLabel):V(W),T=(W,...$)=>$.reduce((j,x)=>x(j),W),E=(W)=>($)=>W.useBom?_(z($)+R):$,M=(W)=>($)=>W.showTitle?S(_(z($)+W.title))(Y(\"\")):$,S=(W)=>($)=>_(z(W)+z($)+F),O=(W)=>($,j)=>l(W)(Y(z($)+z(j))),l=(W)=>($)=>X(z($)+W.fieldSeparator),b=(W,$)=>(j)=>{if(!W.showColumnHeaders)return j;if($.length<1)throw new B(\"Option to show headers but none supplied. Make sure there are keys in your collection or that you've supplied headers through the config options.\");let x=Y(\"\");for(let A=0;A<$.length;A++){const J=y($[A]);x=O(W)(x,v(W,z(J)))}return x=Y(z(x).slice(0,-1)),S(j)(x)},C=(W,$,j)=>(x)=>{let A=x;for(var J=0;J<j.length;J++){let I=Y(\"\");for(let U=0;U<$.length;U++){const H=w($[U]),D=j[J][z(H)];I=O(W)(I,v(W,D))}I=Y(z(I).slice(0,-1)),A=S(A)(I)}return A},k=z,m=(W)=>+W===W&&(!isFinite(W)||Boolean(W%1)),p=(W,$)=>{if(m($)){if(W.decimalSeparator===\"locale\")return Z($.toLocaleString());if(W.decimalSeparator)return Z($.toString().replace(\".\",W.decimalSeparator))}return Z($.toString())},Q=(W,$)=>{let j=$;if(W.quoteStrings||W.fieldSeparator&&$.indexOf(W.fieldSeparator)>-1||W.quoteCharacter&&$.indexOf(W.quoteCharacter)>-1||$.indexOf(\"\\n\")>-1||$.indexOf(\"\\r\")>-1)j=W.quoteCharacter+s($,W.quoteCharacter)+W.quoteCharacter;return Z(j)},g=(W,$)=>{const j=$?\"true\":\"false\";return Z(W.boolDisplay[j])},r=(W,$)=>{if(typeof $===\"undefined\"&&W.replaceUndefinedWith!==void 0)return Q(W,W.replaceUndefinedWith+\"\");if($===null)return Q(W,\"null\");return Q(W,\"\")},v=(W,$)=>{if(typeof $===\"number\")return p(W,$);if(typeof $===\"string\")return Q(W,$);if(typeof $===\"boolean\"&&W.boolDisplay)return g(W,$);if($===null||typeof $===\"undefined\")return r(W,$);throw new P(`\n typeof ${typeof $} isn't supported. Only number, string, boolean, null and undefined are supported.\n Please convert the data in your object to one of those before generating the CSV.\n `)};var BW=(W)=>($)=>{const j=G(W),x=j.useKeysAsHeaders?Object.keys($[0]):j.columnHeaders;let A=T(_(\"\"),E(j),M(j),b(j,x),C(j,x,$));if(z(A).length<1)throw new K(\"Output is empty. Is your data formatted correctly?\");return A},f=(W)=>($)=>{const j=G(W),x=z($),A=j.useTextFile?\"text/plain\":j.mediaType;return new Blob([x],{type:`${A};charset=utf8;`})},LW=(W)=>($)=>{if(!window)throw new L(\"Downloading only supported in a browser environment.\");const j=f(W)($),x=G(W),A=x.useTextFile?\"txt\":x.fileExtension,J=`${x.filename}.${A}`,I=document.createElement(\"a\");I.download=J,I.href=URL.createObjectURL(j),I.setAttribute(\"visibility\",\"hidden\"),document.body.appendChild(I),I.click(),document.body.removeChild(I)};export{G as mkConfig,BW as generateCsv,LW as download,k as asString,f as asBlob,q as MediaType};\n","import { errorMessage } from '@lmnr-ai/types';\nimport csv from 'csv-parser';\nimport { asString, generateCsv, mkConfig } from 'export-to-csv';\nimport { createReadStream } from 'fs';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\n\nimport { Datapoint } from '../evaluations';\nimport { initializeLogger } from '../utils';\n\nconst logger = initializeLogger();\n\n/**\n * Check if a file has a supported extension.\n */\nconst isSupportedFile = (file: string): boolean => {\n const ext = path.extname(file).toLowerCase();\n return ['.json', '.csv', '.jsonl'].includes(ext);\n};\n\n/**\n * Collect all supported files from the given paths.\n * Handles both files and directories.\n */\nexport const collectFiles = async (\n paths: string[],\n recursive: boolean = false,\n): Promise<string[]> => {\n const collectedFiles: string[] = [];\n\n for (const filepath of paths) {\n try {\n const stats = await fs.stat(filepath);\n\n if (stats.isFile()) {\n if (isSupportedFile(filepath)) {\n collectedFiles.push(filepath);\n } else {\n logger.warn(`Skipping unsupported file type: ${filepath}`);\n }\n } else if (stats.isDirectory()) {\n const entries = await fs.readdir(filepath);\n\n for (const entry of entries) {\n const fullPath = path.join(filepath, entry);\n const entryStats = await fs.stat(fullPath);\n\n if (entryStats.isFile() && isSupportedFile(fullPath)) {\n collectedFiles.push(fullPath);\n } else if (recursive && entryStats.isDirectory()) {\n const subFiles = await collectFiles([fullPath], true);\n collectedFiles.push(...subFiles);\n }\n }\n }\n } catch (error) {\n logger.warn(\n `Path does not exist or is not accessible: ${filepath}. `\n + `Error: ${errorMessage(error)}`,\n );\n }\n }\n\n return collectedFiles;\n};\n\n/**\n * Read a JSON file and return its contents.\n */\nconst readJsonFile = async (filepath: string): Promise<any[]> => {\n const content = await fs.readFile(filepath, 'utf-8');\n const parsed = JSON.parse(content);\n return Array.isArray(parsed) ? parsed : [parsed];\n};\n\n/**\n * Try to parse a string as JSON. If it fails, return the original string.\n */\nconst tryParseJson = (content: string): any => {\n // Don't try to parse if it's not a string or doesn't look like JSON\n if (typeof content !== 'string') {\n return content;\n }\n\n // If it doesn't start with { or [, it's probably not JSON\n const trimmed = content.trim();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {\n return content;\n }\n\n try {\n return JSON.parse(content);\n } catch (error) {\n logger.debug(\n `Error parsing JSON: ${errorMessage(error)}`,\n );\n return content;\n }\n};\n\n/**\n * Parse each field in a CSV row, attempting to convert JSON strings back to objects.\n */\nconst parseCsvRow = (row: Record<string, string>): any => {\n const parsed: any = {};\n for (const [key, value] of Object.entries(row)) {\n parsed[key] = tryParseJson(value);\n }\n return parsed;\n};\n\n/**\n * Read a CSV file and return its contents as an array of objects.\n */\nconst readCsvFile = async (filepath: string): Promise<any[]> => new Promise((resolve, reject) => {\n const results: any[] = [];\n createReadStream(filepath)\n .pipe(csv())\n .on('data', (data) => results.push(parseCsvRow(data)))\n .on('end', () => resolve(results))\n .on('error', reject);\n});\n\n/**\n * Read a JSONL file and return its contents as an array of objects.\n */\nasync function readJsonlFile(filepath: string): Promise<any[]> {\n const content = await fs.readFile(filepath, 'utf-8');\n const lines = content.split('\\n').filter((line) => line.trim());\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return lines.map((line) => JSON.parse(line));\n}\n\n/**\n * Read a single file and return its contents.\n */\nasync function readFile(filepath: string): Promise<any[]> {\n const ext = path.extname(filepath).toLowerCase();\n\n if (ext === '.json') {\n return readJsonFile(filepath);\n } else if (ext === '.csv') {\n return readCsvFile(filepath);\n } else if (ext === '.jsonl') {\n return readJsonlFile(filepath);\n } else {\n throw new Error(`Unsupported file type: ${ext}`);\n }\n}\n\n/**\n * Load data from all files in the specified paths.\n */\nexport const loadFromPaths = async <D = any, T = any>(\n paths: string[],\n recursive: boolean = false,\n): Promise<Datapoint<D, T>[]> => {\n const files = await collectFiles(paths, recursive);\n\n if (files.length === 0) {\n logger.warn('No supported files found in the specified paths');\n return [];\n }\n\n logger.info(`Found ${files.length} file(s) to read`);\n\n const result: Datapoint<D, T>[] = [];\n\n for (const file of files) {\n try {\n const data = await readFile(file);\n result.push(...data);\n logger.info(`Read ${data.length} record(s) from ${file}`);\n } catch (error) {\n logger.error(\n `Error reading file ${file}: ${errorMessage(error)}`,\n );\n throw error;\n }\n }\n\n return result;\n};\n\n/**\n * Write data to a JSON file.\n */\nconst writeJsonFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n): Promise<void> => {\n const content = JSON.stringify(data, null, 2);\n await fs.writeFile(filepath, content, 'utf-8');\n};\n\n/**\n * Write data to a CSV file.\n */\nconst writeCsvFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n): Promise<void> => {\n if (data.length === 0) {\n throw new Error('No data to write to CSV');\n }\n\n const formattedData = data.map(item =>\n Object.fromEntries(Object.entries(item).map(([key, value]) => [key, stringifyForCsv(value)]),\n ));\n\n const csvConfig = mkConfig({ useKeysAsHeaders: true });\n\n const csvOutput = generateCsv(csvConfig)(formattedData);\n const csvString = asString(csvOutput);\n\n await fs.writeFile(filepath, csvString, 'utf-8');\n};\n\n/**\n * Write data to a JSONL file.\n */\nconst writeJsonlFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n): Promise<void> => {\n const lines = data.map((item) => JSON.stringify(item)).join('\\n');\n await fs.writeFile(filepath, lines + '\\n', 'utf-8');\n};\n\n/**\n * Write data to a file based on the file extension.\n */\nexport const writeToFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n format?: 'json' | 'csv' | 'jsonl',\n): Promise<void> => {\n // Create parent directories if they don't exist\n const dir = path.dirname(filepath);\n await fs.mkdir(dir, { recursive: true });\n\n // Determine the format\n const ext = format ?? path.extname(filepath).slice(1);\n\n if (format && format !== path.extname(filepath).slice(1)) {\n logger.warn(\n `Output format ${format} does not match file extension ${path.extname(filepath).slice(1)}`,\n );\n }\n\n if (ext === 'json') {\n await writeJsonFile(filepath, data);\n } else if (ext === 'csv') {\n await writeCsvFile(filepath, data);\n } else if (ext === 'jsonl') {\n await writeJsonlFile(filepath, data);\n } else {\n throw new Error(`Unsupported output format: ${ext}`);\n }\n};\n\n/**\n * Convert a value to a CSV-safe string.\n * - Strings and numbers pass through\n * - null/undefined become empty strings\n * - Objects and arrays are stringified to JSON\n */\nconst stringifyForCsv = (value: any): string => {\n if (value === null || value === undefined) {\n return '';\n }\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n // For objects and arrays, stringify to JSON\n return JSON.stringify(value);\n};\n\n/**\n * Print data to console in the specified format.\n */\nexport const printToConsole = <D, T>(\n data: Datapoint<D, T>[],\n format: 'json' | 'csv' | 'jsonl' = 'json',\n) => {\n if (format === 'json') {\n console.log(JSON.stringify(data, null, 2));\n } else if (format === 'csv') {\n if (data.length === 0) {\n logger.error('No data to print');\n return;\n }\n\n const formattedData = data.map(item =>\n Object.fromEntries(Object.entries(item).map(([key, value]) => [key, stringifyForCsv(value)]),\n ));\n\n const csvConfig = mkConfig({ useKeysAsHeaders: true });\n\n const csvOutput = generateCsv(csvConfig)(formattedData);\n const csvString = asString(csvOutput);\n console.log(csvString);\n } else if (format === 'jsonl') {\n data.forEach((item) => console.log(JSON.stringify(item)));\n } else {\n throw new Error(\n `Unsupported output format: ${String(format)}. `\n + \"(supported formats: json, csv, jsonl)\",\n );\n }\n};\n\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;;;;;CAAA,MAAM,EAAE,cAAc,QAAQ,QAAQ;CAEtC,MAAM,CAAC,MAAM,OAAO,KAAK,IAAI;CAC7B,MAAM,CAAC,MAAM,OAAO,KAAK,IAAI;CAC7B,MAAM,WAAW;EACf,QAAQ;EACR,SAAS;EACT,aAAa,EAAE,aAAa;EAC5B,YAAY,EAAE,YAAY;EAC1B,SAAS;EACT,OAAO;EACP,KAAK;EACL,WAAW;EACX,cAAc;EACd,WAAW;EACX,aAAa,OAAO;EACpB,QAAQ;EACR,kBAAkB;CACpB;CAEA,MAAM,iBAAiB,IAAI,IAAI;EAAC;EAAa;EAAe;CAAW,CAAC;CAExE,SAAS,eAAe,QAAQ;EAC9B,IAAI,OAAO,WAAW,UACpB,OAAO;EAGT,IAAI,eAAe,IAAI,MAAM,GAC3B,OAAO;EAGT,OAAO;CACT;CAEA,IAAM,YAAN,cAAwB,UAAU;EAChC,YAAa,OAAO,CAAC,GAAG;GACtB,MAAM;IAAE,YAAY;IAAM,eAAe;GAAG,CAAC;GAE7C,IAAI,MAAM,QAAQ,IAAI,GAAG,OAAO,EAAE,SAAS,KAAK;GAEhD,MAAM,UAAU,OAAO,OAAO,CAAC,GAAG,UAAU,IAAI;GAEhD,QAAQ,gBAAgB,QAAQ,YAAY,SAAS;GAErD,KAAK,MAAM,OAAO;IAAC;IAAW;IAAS;GAAW,GAChD,IAAI,OAAO,QAAQ,SAAS,aAC1B,CAAE,QAAQ,QAAQ,OAAO,KAAK,QAAQ,IAAI;GAK9C,QAAQ,UAAU,QAAQ,CAAC,EAAA,CAAG,SAAS,OAAO,KAAK,QAAQ,MAAM,CAAC,CAAC,KAAK,QAAQ;GAEhF,KAAK,QAAQ;IACX,OAAO,QAAQ,MA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;EAKH,MAAM,YAAYE,EADAC,GAFAC,EAAS,EAAE,kBAAkB,KAAK,CAEd,CAAC,CAAC,CAAC,aACN,CAAC;EACpC,QAAQ,IAAI,SAAS;CACvB,OAAO,IAAI,WAAW,SACpB,KAAK,SAAS,SAAS,QAAQ,IAAI,KAAK,UAAU,IAAI,CAAC,CAAC;MAExD,MAAM,IAAI,MACR,8BAA8B,OAAO,MAAM,EAAE,wCAE/C;AAEJ"}
1
+ {"version":3,"file":"file-utils-B7VBQSna.cjs","names":["initializeLogger","fs","errorMessage","asString","generateCsv","mkConfig"],"sources":["../../../node_modules/.pnpm/csv-parser@3.2.1/node_modules/csv-parser/index.js","../../../node_modules/.pnpm/export-to-csv@1.4.0/node_modules/export-to-csv/output/index.js","../src/cli/file-utils.ts"],"sourcesContent":["const { Transform } = require('stream')\n\nconst [cr] = Buffer.from('\\r')\nconst [nl] = Buffer.from('\\n')\nconst defaults = {\n escape: '\"',\n headers: null,\n mapHeaders: ({ header }) => header,\n mapValues: ({ value }) => value,\n newline: '\\n',\n quote: '\"',\n raw: false,\n separator: ',',\n skipComments: false,\n skipLines: null,\n maxRowBytes: Number.MAX_SAFE_INTEGER,\n strict: false,\n outputByteOffset: false\n}\n\nconst DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype'])\n\nfunction sanitizeHeader(header) {\n if (typeof header !== 'string') {\n return null\n }\n\n if (DANGEROUS_KEYS.has(header)) {\n return null\n }\n\n return header\n}\n\nclass CsvParser extends Transform {\n constructor (opts = {}) {\n super({ objectMode: true, highWaterMark: 16 })\n\n if (Array.isArray(opts)) opts = { headers: opts }\n\n const options = Object.assign({}, defaults, opts)\n\n options.customNewline = options.newline !== defaults.newline\n\n for (const key of ['newline', 'quote', 'separator']) {\n if (typeof options[key] !== 'undefined') {\n ([options[key]] = Buffer.from(options[key]))\n }\n }\n\n // if escape is not defined on the passed options, use the end value of quote\n options.escape = (opts || {}).escape ? Buffer.from(options.escape)[0] : options.quote\n\n this.state = {\n empty: options.raw ? Buffer.alloc(0) : '',\n escaped: false,\n first: true,\n lineNumber: 0,\n previousEnd: 0,\n rowLength: 0,\n quoted: false\n }\n\n this._prev = null\n\n if (options.headers === false) {\n // enforce, as the column length check will fail if headers:false\n options.strict = false\n }\n\n if (options.headers || options.headers === false) {\n this.state.first = false\n }\n\n this.options = options\n this.headers = options.headers\n this.bytesRead = 0\n }\n\n parseCell (buffer, start, end) {\n const { escape, quote } = this.options\n // remove quotes from quoted cells\n if (buffer[start] === quote && buffer[end - 1] === quote) {\n start++\n end--\n }\n\n let y = start\n\n for (let i = start; i < end; i++) {\n // check for escape characters and skip them\n if (buffer[i] === escape && i + 1 < end && buffer[i + 1] === quote) {\n i++\n }\n\n if (y !== i) {\n buffer[y] = buffer[i]\n }\n y++\n }\n\n return this.parseValue(buffer, start, y)\n }\n\n parseLine (buffer, start, end) {\n const { customNewline, escape, mapHeaders, mapValues, quote, separator, skipComments, skipLines } = this.options\n\n end-- // trim newline\n if (!customNewline && buffer.length && buffer[end - 1] === cr) {\n end--\n }\n\n const comma = separator\n const cells = []\n let isQuoted = false\n let offset = start\n\n if (skipComments) {\n const char = typeof skipComments === 'string' ? skipComments : '#'\n if (buffer[start] === Buffer.from(char)[0]) {\n return\n }\n }\n\n const mapValue = (value) => {\n if (this.state.first) {\n return value\n }\n\n const index = cells.length\n const header = this.headers[index]\n\n return mapValues({ header, index, value })\n }\n\n for (let i = start; i < end; i++) {\n const isStartingQuote = !isQuoted && buffer[i] === quote\n const isEndingQuote = isQuoted && buffer[i] === quote && i + 1 <= end && buffer[i + 1] === comma\n const isEscape = isQuoted && buffer[i] === escape && i + 1 < end && buffer[i + 1] === quote\n\n if (isStartingQuote || isEndingQuote) {\n isQuoted = !isQuoted\n continue\n } else if (isEscape) {\n i++\n continue\n }\n\n if (buffer[i] === comma && !isQuoted) {\n let value = this.parseCell(buffer, offset, i)\n value = mapValue(value)\n cells.push(value)\n offset = i + 1\n }\n }\n\n if (offset < end) {\n let value = this.parseCell(buffer, offset, end)\n value = mapValue(value)\n cells.push(value)\n }\n\n if (buffer[end - 1] === comma) {\n cells.push(mapValue(this.state.empty))\n }\n\n const skip = skipLines && skipLines > this.state.lineNumber\n this.state.lineNumber++\n\n if (this.state.first && !skip) {\n this.state.first = false\n this.headers = cells.map((header, index) => {\n const mapped = mapHeaders({ header, index })\n\n if (mapped === null) {\n return null\n }\n\n return sanitizeHeader(mapped)\n })\n\n this.emit('headers', this.headers)\n return\n }\n\n if (!skip && this.options.strict && cells.length !== this.headers.length) {\n const e = new RangeError('Row length does not match headers')\n this.emit('error', e)\n } else {\n if (!skip) {\n const byteOffset = this.bytesRead - buffer.length + start\n this.writeRow(cells, byteOffset)\n }\n }\n }\n\n parseValue (buffer, start, end) {\n if (this.options.raw) {\n return buffer.slice(start, end)\n }\n\n return buffer.toString('utf-8', start, end)\n }\n\n writeRow (cells, byteOffset) {\n const headers = (this.headers === false) ? cells.map((value, index) => index) : this.headers\n\n const row = cells.reduce((o, cell, index) => {\n const header = headers[index]\n if (header === null) return o // skip columns\n if (header !== undefined) {\n o[header] = cell\n } else {\n o[`_${index}`] = cell\n }\n return o\n }, {})\n\n if (this.options.outputByteOffset) {\n this.push({ row, byteOffset })\n } else {\n this.push(row)\n }\n }\n\n _flush (cb) {\n if (this.state.escaped || !this._prev) return cb()\n this.parseLine(this._prev, this.state.previousEnd, this._prev.length + 1) // plus since online -1s\n cb()\n }\n\n _transform (data, enc, cb) {\n if (typeof data === 'string') {\n data = Buffer.from(data)\n }\n\n const { escape, quote } = this.options\n let start = 0\n let buffer = data\n this.bytesRead += data.byteLength\n\n if (this._prev) {\n start = this._prev.length\n buffer = Buffer.concat([this._prev, data])\n this._prev = null\n }\n\n const bufferLength = buffer.length\n\n for (let i = start; i < bufferLength; i++) {\n const chr = buffer[i]\n const nextChr = i + 1 < bufferLength ? buffer[i + 1] : null\n\n this.state.rowLength++\n if (this.state.rowLength > this.options.maxRowBytes) {\n return cb(new Error('Row exceeds the maximum size'))\n }\n\n if (!this.state.escaped && chr === escape && nextChr === quote && i !== start) {\n this.state.escaped = true\n continue\n } else if (chr === quote) {\n if (this.state.escaped) {\n this.state.escaped = false\n // non-escaped quote (quoting the cell)\n } else {\n this.state.quoted = !this.state.quoted\n }\n continue\n }\n\n if (!this.state.quoted) {\n if (this.state.first && !this.options.customNewline) {\n if (chr === nl) {\n this.options.newline = nl\n } else if (chr === cr) {\n if (nextChr !== nl) {\n this.options.newline = cr\n }\n }\n }\n\n if (chr === this.options.newline) {\n this.parseLine(buffer, this.state.previousEnd, i + 1)\n this.state.previousEnd = i + 1\n this.state.rowLength = 0\n }\n }\n }\n\n if (this.state.previousEnd === bufferLength) {\n this.state.previousEnd = 0\n return cb()\n }\n\n if (bufferLength - this.state.previousEnd < data.length) {\n this._prev = data\n this.state.previousEnd -= (bufferLength - data.length)\n return cb()\n }\n\n this._prev = buffer\n cb()\n }\n}\n\nmodule.exports = (opts) => new CsvParser(opts)\n","var q;(function(x){x[\"csv\"]=\"text/csv\";x[\"tsv\"]=\"text/tab-separated-values\";x[\"plain\"]=\"text/plain\"})(q||(q={}));var X=(W)=>W,z=(W)=>W,Z=X,_=X,Y=X,N=X,V=X;var h={fieldSeparator:\",\",decimalSeparator:\".\",quoteStrings:!0,quoteCharacter:'\"',showTitle:!1,title:\"My Generated Report\",filename:\"generated\",showColumnHeaders:!0,useTextFile:!1,fileExtension:\"csv\",mediaType:q.csv,useBom:!0,columnHeaders:[],useKeysAsHeaders:!1,boolDisplay:{true:\"TRUE\",false:\"FALSE\"},replaceUndefinedWith:\"\"},F=\"\\r\\n\",R=\"\\uFEFF\",G=(W)=>Object.assign({},h,W);class K extends Error{constructor(W){super(W);this.name=\"CsvGenerationError\"}}class B extends Error{constructor(W){super(W);this.name=\"EmptyHeadersError\"}}class L extends Error{constructor(W){super(W);this.name=\"CsvDownloadEnvironmentError\"}}class P extends Error{constructor(W){super(W);this.name=\"UnsupportedDataFormatError\"}}var s=function(W,$){if($=='\"'&&W.indexOf('\"')>-1)return W.replace(/\"/g,'\"\"');return W},w=(W)=>typeof W===\"object\"?N(W.key):N(W),y=(W)=>typeof W===\"object\"?V(W.displayLabel):V(W),T=(W,...$)=>$.reduce((j,x)=>x(j),W),E=(W)=>($)=>W.useBom?_(z($)+R):$,M=(W)=>($)=>W.showTitle?S(_(z($)+W.title))(Y(\"\")):$,S=(W)=>($)=>_(z(W)+z($)+F),O=(W)=>($,j)=>l(W)(Y(z($)+z(j))),l=(W)=>($)=>X(z($)+W.fieldSeparator),b=(W,$)=>(j)=>{if(!W.showColumnHeaders)return j;if($.length<1)throw new B(\"Option to show headers but none supplied. Make sure there are keys in your collection or that you've supplied headers through the config options.\");let x=Y(\"\");for(let A=0;A<$.length;A++){const J=y($[A]);x=O(W)(x,v(W,z(J)))}return x=Y(z(x).slice(0,-1)),S(j)(x)},C=(W,$,j)=>(x)=>{let A=x;for(var J=0;J<j.length;J++){let I=Y(\"\");for(let U=0;U<$.length;U++){const H=w($[U]),D=j[J][z(H)];I=O(W)(I,v(W,D))}I=Y(z(I).slice(0,-1)),A=S(A)(I)}return A},k=z,m=(W)=>+W===W&&(!isFinite(W)||Boolean(W%1)),p=(W,$)=>{if(m($)){if(W.decimalSeparator===\"locale\")return Z($.toLocaleString());if(W.decimalSeparator)return Z($.toString().replace(\".\",W.decimalSeparator))}return Z($.toString())},Q=(W,$)=>{let j=$;if(W.quoteStrings||W.fieldSeparator&&$.indexOf(W.fieldSeparator)>-1||W.quoteCharacter&&$.indexOf(W.quoteCharacter)>-1||$.indexOf(\"\\n\")>-1||$.indexOf(\"\\r\")>-1)j=W.quoteCharacter+s($,W.quoteCharacter)+W.quoteCharacter;return Z(j)},g=(W,$)=>{const j=$?\"true\":\"false\";return Z(W.boolDisplay[j])},r=(W,$)=>{if(typeof $===\"undefined\"&&W.replaceUndefinedWith!==void 0)return Q(W,W.replaceUndefinedWith+\"\");if($===null)return Q(W,\"null\");return Q(W,\"\")},v=(W,$)=>{if(typeof $===\"number\")return p(W,$);if(typeof $===\"string\")return Q(W,$);if(typeof $===\"boolean\"&&W.boolDisplay)return g(W,$);if($===null||typeof $===\"undefined\")return r(W,$);throw new P(`\n typeof ${typeof $} isn't supported. Only number, string, boolean, null and undefined are supported.\n Please convert the data in your object to one of those before generating the CSV.\n `)};var BW=(W)=>($)=>{const j=G(W),x=j.useKeysAsHeaders?Object.keys($[0]):j.columnHeaders;let A=T(_(\"\"),E(j),M(j),b(j,x),C(j,x,$));if(z(A).length<1)throw new K(\"Output is empty. Is your data formatted correctly?\");return A},f=(W)=>($)=>{const j=G(W),x=z($),A=j.useTextFile?\"text/plain\":j.mediaType;return new Blob([x],{type:`${A};charset=utf8;`})},LW=(W)=>($)=>{if(!window)throw new L(\"Downloading only supported in a browser environment.\");const j=f(W)($),x=G(W),A=x.useTextFile?\"txt\":x.fileExtension,J=`${x.filename}.${A}`,I=document.createElement(\"a\");I.download=J,I.href=URL.createObjectURL(j),I.setAttribute(\"visibility\",\"hidden\"),document.body.appendChild(I),I.click(),document.body.removeChild(I)};export{G as mkConfig,BW as generateCsv,LW as download,k as asString,f as asBlob,q as MediaType};\n","import { errorMessage } from '@lmnr-ai/types';\nimport csv from 'csv-parser';\nimport { asString, generateCsv, mkConfig } from 'export-to-csv';\nimport { createReadStream } from 'fs';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\n\nimport { Datapoint } from '../evaluations';\nimport { initializeLogger } from '../utils';\n\nconst logger = initializeLogger();\n\n/**\n * Check if a file has a supported extension.\n */\nconst isSupportedFile = (file: string): boolean => {\n const ext = path.extname(file).toLowerCase();\n return ['.json', '.csv', '.jsonl'].includes(ext);\n};\n\n/**\n * Collect all supported files from the given paths.\n * Handles both files and directories.\n */\nexport const collectFiles = async (\n paths: string[],\n recursive: boolean = false,\n): Promise<string[]> => {\n const collectedFiles: string[] = [];\n\n for (const filepath of paths) {\n try {\n const stats = await fs.stat(filepath);\n\n if (stats.isFile()) {\n if (isSupportedFile(filepath)) {\n collectedFiles.push(filepath);\n } else {\n logger.warn(`Skipping unsupported file type: ${filepath}`);\n }\n } else if (stats.isDirectory()) {\n const entries = await fs.readdir(filepath);\n\n for (const entry of entries) {\n const fullPath = path.join(filepath, entry);\n const entryStats = await fs.stat(fullPath);\n\n if (entryStats.isFile() && isSupportedFile(fullPath)) {\n collectedFiles.push(fullPath);\n } else if (recursive && entryStats.isDirectory()) {\n const subFiles = await collectFiles([fullPath], true);\n collectedFiles.push(...subFiles);\n }\n }\n }\n } catch (error) {\n logger.warn(\n `Path does not exist or is not accessible: ${filepath}. `\n + `Error: ${errorMessage(error)}`,\n );\n }\n }\n\n return collectedFiles;\n};\n\n/**\n * Read a JSON file and return its contents.\n */\nconst readJsonFile = async (filepath: string): Promise<any[]> => {\n const content = await fs.readFile(filepath, 'utf-8');\n const parsed = JSON.parse(content);\n return Array.isArray(parsed) ? parsed : [parsed];\n};\n\n/**\n * Try to parse a string as JSON. If it fails, return the original string.\n */\nconst tryParseJson = (content: string): any => {\n // Don't try to parse if it's not a string or doesn't look like JSON\n if (typeof content !== 'string') {\n return content;\n }\n\n // If it doesn't start with { or [, it's probably not JSON\n const trimmed = content.trim();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {\n return content;\n }\n\n try {\n return JSON.parse(content);\n } catch (error) {\n logger.debug(\n `Error parsing JSON: ${errorMessage(error)}`,\n );\n return content;\n }\n};\n\n/**\n * Parse each field in a CSV row, attempting to convert JSON strings back to objects.\n */\nconst parseCsvRow = (row: Record<string, string>): any => {\n const parsed: any = {};\n for (const [key, value] of Object.entries(row)) {\n parsed[key] = tryParseJson(value);\n }\n return parsed;\n};\n\n/**\n * Read a CSV file and return its contents as an array of objects.\n */\nconst readCsvFile = async (filepath: string): Promise<any[]> => new Promise((resolve, reject) => {\n const results: any[] = [];\n createReadStream(filepath)\n .pipe(csv())\n .on('data', (data) => results.push(parseCsvRow(data)))\n .on('end', () => resolve(results))\n .on('error', reject);\n});\n\n/**\n * Read a JSONL file and return its contents as an array of objects.\n */\nasync function readJsonlFile(filepath: string): Promise<any[]> {\n const content = await fs.readFile(filepath, 'utf-8');\n const lines = content.split('\\n').filter((line) => line.trim());\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return lines.map((line) => JSON.parse(line));\n}\n\n/**\n * Read a single file and return its contents.\n */\nasync function readFile(filepath: string): Promise<any[]> {\n const ext = path.extname(filepath).toLowerCase();\n\n if (ext === '.json') {\n return readJsonFile(filepath);\n } else if (ext === '.csv') {\n return readCsvFile(filepath);\n } else if (ext === '.jsonl') {\n return readJsonlFile(filepath);\n } else {\n throw new Error(`Unsupported file type: ${ext}`);\n }\n}\n\n/**\n * Load data from all files in the specified paths.\n */\nexport const loadFromPaths = async <D = any, T = any>(\n paths: string[],\n recursive: boolean = false,\n): Promise<Datapoint<D, T>[]> => {\n const files = await collectFiles(paths, recursive);\n\n if (files.length === 0) {\n logger.warn('No supported files found in the specified paths');\n return [];\n }\n\n logger.info(`Found ${files.length} file(s) to read`);\n\n const result: Datapoint<D, T>[] = [];\n\n for (const file of files) {\n try {\n const data = await readFile(file);\n result.push(...data);\n logger.info(`Read ${data.length} record(s) from ${file}`);\n } catch (error) {\n logger.error(\n `Error reading file ${file}: ${errorMessage(error)}`,\n );\n throw error;\n }\n }\n\n return result;\n};\n\n/**\n * Write data to a JSON file.\n */\nconst writeJsonFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n): Promise<void> => {\n const content = JSON.stringify(data, null, 2);\n await fs.writeFile(filepath, content, 'utf-8');\n};\n\n/**\n * Write data to a CSV file.\n */\nconst writeCsvFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n): Promise<void> => {\n if (data.length === 0) {\n throw new Error('No data to write to CSV');\n }\n\n const formattedData = data.map(item =>\n Object.fromEntries(Object.entries(item).map(([key, value]) => [key, stringifyForCsv(value)]),\n ));\n\n const csvConfig = mkConfig({ useKeysAsHeaders: true });\n\n const csvOutput = generateCsv(csvConfig)(formattedData);\n const csvString = asString(csvOutput);\n\n await fs.writeFile(filepath, csvString, 'utf-8');\n};\n\n/**\n * Write data to a JSONL file.\n */\nconst writeJsonlFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n): Promise<void> => {\n const lines = data.map((item) => JSON.stringify(item)).join('\\n');\n await fs.writeFile(filepath, lines + '\\n', 'utf-8');\n};\n\n/**\n * Write data to a file based on the file extension.\n */\nexport const writeToFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n format?: 'json' | 'csv' | 'jsonl',\n): Promise<void> => {\n // Create parent directories if they don't exist\n const dir = path.dirname(filepath);\n await fs.mkdir(dir, { recursive: true });\n\n // Determine the format\n const ext = format ?? path.extname(filepath).slice(1);\n\n if (format && format !== path.extname(filepath).slice(1)) {\n logger.warn(\n `Output format ${format} does not match file extension ${path.extname(filepath).slice(1)}`,\n );\n }\n\n if (ext === 'json') {\n await writeJsonFile(filepath, data);\n } else if (ext === 'csv') {\n await writeCsvFile(filepath, data);\n } else if (ext === 'jsonl') {\n await writeJsonlFile(filepath, data);\n } else {\n throw new Error(`Unsupported output format: ${ext}`);\n }\n};\n\n/**\n * Convert a value to a CSV-safe string.\n * - Strings and numbers pass through\n * - null/undefined become empty strings\n * - Objects and arrays are stringified to JSON\n */\nconst stringifyForCsv = (value: any): string => {\n if (value === null || value === undefined) {\n return '';\n }\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n // For objects and arrays, stringify to JSON\n return JSON.stringify(value);\n};\n\n/**\n * Print data to console in the specified format.\n */\nexport const printToConsole = <D, T>(\n data: Datapoint<D, T>[],\n format: 'json' | 'csv' | 'jsonl' = 'json',\n) => {\n if (format === 'json') {\n console.log(JSON.stringify(data, null, 2));\n } else if (format === 'csv') {\n if (data.length === 0) {\n logger.error('No data to print');\n return;\n }\n\n const formattedData = data.map(item =>\n Object.fromEntries(Object.entries(item).map(([key, value]) => [key, stringifyForCsv(value)]),\n ));\n\n const csvConfig = mkConfig({ useKeysAsHeaders: true });\n\n const csvOutput = generateCsv(csvConfig)(formattedData);\n const csvString = asString(csvOutput);\n console.log(csvString);\n } else if (format === 'jsonl') {\n data.forEach((item) => console.log(JSON.stringify(item)));\n } else {\n throw new Error(\n `Unsupported output format: ${String(format)}. `\n + \"(supported formats: json, csv, jsonl)\",\n );\n }\n};\n\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;;;;;CAAA,MAAM,EAAE,cAAc,QAAQ,QAAQ;CAEtC,MAAM,CAAC,MAAM,OAAO,KAAK,IAAI;CAC7B,MAAM,CAAC,MAAM,OAAO,KAAK,IAAI;CAC7B,MAAM,WAAW;EACf,QAAQ;EACR,SAAS;EACT,aAAa,EAAE,aAAa;EAC5B,YAAY,EAAE,YAAY;EAC1B,SAAS;EACT,OAAO;EACP,KAAK;EACL,WAAW;EACX,cAAc;EACd,WAAW;EACX,aAAa,OAAO;EACpB,QAAQ;EACR,kBAAkB;CACpB;CAEA,MAAM,iBAAiB,IAAI,IAAI;EAAC;EAAa;EAAe;CAAW,CAAC;CAExE,SAAS,eAAe,QAAQ;EAC9B,IAAI,OAAO,WAAW,UACpB,OAAO;EAGT,IAAI,eAAe,IAAI,MAAM,GAC3B,OAAO;EAGT,OAAO;CACT;CAEA,IAAM,YAAN,cAAwB,UAAU;EAChC,YAAa,OAAO,CAAC,GAAG;GACtB,MAAM;IAAE,YAAY;IAAM,eAAe;GAAG,CAAC;GAE7C,IAAI,MAAM,QAAQ,IAAI,GAAG,OAAO,EAAE,SAAS,KAAK;GAEhD,MAAM,UAAU,OAAO,OAAO,CAAC,GAAG,UAAU,IAAI;GAEhD,QAAQ,gBAAgB,QAAQ,YAAY,SAAS;GAErD,KAAK,MAAM,OAAO;IAAC;IAAW;IAAS;GAAW,GAChD,IAAI,OAAO,QAAQ,SAAS,aAC1B,CAAE,QAAQ,QAAQ,OAAO,KAAK,QAAQ,IAAI;GAK9C,QAAQ,UAAU,QAAQ,CAAC,EAAA,CAAG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