@omote/core 0.9.7 → 0.10.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{chunk-Y3DTP5P3.mjs → chunk-VSYYT4HO.mjs} +1 -1
- package/dist/{chunk-X5OTUOE6.mjs.map → chunk-VSYYT4HO.mjs.map} +1 -1
- package/dist/index.d.mts +261 -1305
- package/dist/index.d.ts +261 -1305
- package/dist/index.js +6380 -11034
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +6379 -11033
- package/dist/index.mjs.map +1 -1
- package/dist/logging/index.js.map +1 -1
- package/dist/logging/index.mjs +1 -1
- package/package.json +1 -2
- package/dist/Logger-BeUI6jG7.d.mts +0 -145
- package/dist/Logger-BeUI6jG7.d.ts +0 -145
- package/dist/Logger-DSoGAYJu.d.mts +0 -141
- package/dist/Logger-DSoGAYJu.d.ts +0 -141
- package/dist/chunk-3NDJA3I4.mjs +0 -853
- package/dist/chunk-3NDJA3I4.mjs.map +0 -1
- package/dist/chunk-CYBTTLG7.mjs +0 -927
- package/dist/chunk-CYBTTLG7.mjs.map +0 -1
- package/dist/chunk-ESU52TDS.mjs +0 -287
- package/dist/chunk-ESU52TDS.mjs.map +0 -1
- package/dist/chunk-MXKJOF4I.mjs +0 -38
- package/dist/chunk-MXKJOF4I.mjs.map +0 -1
- package/dist/chunk-X5OTUOE6.mjs +0 -927
- package/dist/chunk-XK22BRG4.mjs +0 -38
- package/dist/chunk-XK22BRG4.mjs.map +0 -1
- package/dist/chunk-Y3DTP5P3.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/logging/index.ts","../../src/logging/types.ts","../../src/logging/formatters.ts","../../src/logging/Clock.ts","../../src/telemetry/OmoteTelemetry.ts","../../src/logging/Logger.ts","../../src/logging/ErrorCodes.ts"],"sourcesContent":["/**\n * Omote SDK Logging Module\n *\n * Unified logging system for all Muse components with:\n * - 6 log levels: error, warn, info, debug, trace, verbose\n * - Structured JSON output for machine parsing\n * - Pretty output for human readability\n * - Module-based child loggers\n * - Runtime configuration\n * - Browser and Node.js compatible\n *\n * @example\n * ```typescript\n * import { configureLogging, createLogger } from '@omote/core';\n *\n * // Configure globally\n * configureLogging({\n * level: 'debug',\n * format: 'pretty',\n * });\n *\n * // Create module logger\n * const logger = createLogger('MyModule');\n * logger.info('Operation complete', { durationMs: 123 });\n * ```\n */\n\n// Types\nexport type {\n LogLevel,\n LogEntry,\n LogSink,\n LogFormatter,\n LoggingConfig,\n ILogger,\n} from './types';\n\nexport {\n LOG_LEVEL_PRIORITY,\n DEFAULT_LOGGING_CONFIG,\n} from './types';\n\n// Formatters\nexport {\n jsonFormatter,\n prettyFormatter,\n getFormatter,\n} from './formatters';\n\n// Logger\nexport {\n configureLogging,\n getLoggingConfig,\n resetLoggingConfig,\n setLogLevel,\n setLoggingEnabled,\n createLogger,\n clearLoggerCache,\n noopLogger,\n getNoopLogger,\n} from './Logger';\n\n// Clock (runtime-agnostic timing)\nexport { getClock, configureClock, defaultClock } from './Clock';\nexport type { Clock } from './Clock';\n\n// Error codes\nexport { ErrorCodes } from './ErrorCodes';\nexport type { ErrorCode } from './ErrorCodes';\n","/**\n * Logging types for Omote SDK\n *\n * 6-level logging system with structured output:\n * - error: Critical failures that prevent operation\n * - warn: Recoverable issues or degraded performance\n * - info: Key lifecycle events (model loaded, inference complete)\n * - debug: Detailed operational info for development\n * - trace: Fine-grained tracing for performance analysis\n * - verbose: Extremely detailed output (tensor shapes, intermediate values)\n */\n\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'verbose';\n\n/**\n * Numeric priority for log levels (lower = more severe)\n */\nexport const LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n trace: 4,\n verbose: 5,\n};\n\n/**\n * Structured log entry\n */\nexport interface LogEntry {\n /** Unix timestamp in milliseconds */\n timestamp: number;\n /** Log level */\n level: LogLevel;\n /** Module name (e.g., 'LocalInference', 'ModelCache') */\n module: string;\n /** Human-readable message */\n message: string;\n /** Optional structured error code from ErrorCodes (e.g., 'OMOTE_INF_001') */\n code?: string;\n /** Optional structured data */\n data?: Record<string, unknown>;\n /** Optional error object */\n error?: Error;\n /** Trace ID from active telemetry span (log-to-span correlation) */\n traceId?: string;\n /** Span ID from active telemetry span (log-to-span correlation) */\n spanId?: string;\n}\n\n/**\n * Log output sink interface.\n *\n * **Portability contract**: Replace the default console sink to route logs to\n * any backend — Node.js winston/pino, Unreal UE_LOG, Unity Debug.Log, or a\n * remote telemetry service. Register via `configureLogging({ sink: mySink })`.\n */\nexport interface LogSink {\n (entry: LogEntry): void;\n}\n\n/**\n * Log formatter interface\n */\nexport interface LogFormatter {\n (entry: LogEntry): string;\n}\n\n/**\n * Global logging configuration\n */\nexport interface LoggingConfig {\n /** Minimum log level to output (default: 'info') */\n level: LogLevel;\n /** Enable/disable logging globally (default: true) */\n enabled: boolean;\n /** Output format: 'json' for structured, 'pretty' for human-readable */\n format: 'json' | 'pretty';\n /** Custom output sink (default: console) */\n sink?: LogSink;\n /** Include timestamps in output (default: true) */\n timestamps?: boolean;\n /** Include module name in output (default: true) */\n includeModule?: boolean;\n}\n\n/**\n * Logger interface for module-specific logging.\n *\n * **Portability contract**: All SDK modules depend only on this interface.\n * To integrate with a non-browser runtime (Node.js, Unreal, Unity), either:\n * 1. Use the built-in Logger with a custom `LogSink`, or\n * 2. Provide your own `ILogger` implementation that bridges to the host\n * runtime's logging system (e.g., `console.log`, `UE_LOG`, `Debug.Log`).\n */\nexport interface ILogger {\n error(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n info(message: string, data?: Record<string, unknown>): void;\n debug(message: string, data?: Record<string, unknown>): void;\n trace(message: string, data?: Record<string, unknown>): void;\n verbose(message: string, data?: Record<string, unknown>): void;\n\n /** Create a child logger with a sub-module name */\n child(subModule: string): ILogger;\n\n /** Get the module name for this logger */\n readonly module: string;\n}\n\n/**\n * Default configuration\n */\nexport const DEFAULT_LOGGING_CONFIG: LoggingConfig = {\n level: 'info',\n enabled: true,\n format: 'pretty',\n timestamps: true,\n includeModule: true,\n};\n","/**\n * Log formatters for different output formats\n */\n\nimport type { LogEntry, LogFormatter, LogLevel } from './types';\n\n/**\n * ANSI color codes for terminal output\n */\nconst COLORS = {\n reset: '\\x1b[0m',\n red: '\\x1b[31m',\n yellow: '\\x1b[33m',\n blue: '\\x1b[34m',\n cyan: '\\x1b[36m',\n gray: '\\x1b[90m',\n white: '\\x1b[37m',\n magenta: '\\x1b[35m',\n};\n\n/**\n * Level-specific colors\n */\nconst LEVEL_COLORS: Record<LogLevel, string> = {\n error: COLORS.red,\n warn: COLORS.yellow,\n info: COLORS.blue,\n debug: COLORS.cyan,\n trace: COLORS.magenta,\n verbose: COLORS.gray,\n};\n\n/**\n * Level display names (padded for alignment)\n */\nconst LEVEL_NAMES: Record<LogLevel, string> = {\n error: 'ERROR ',\n warn: 'WARN ',\n info: 'INFO ',\n debug: 'DEBUG ',\n trace: 'TRACE ',\n verbose: 'VERBOSE',\n};\n\n/**\n * Check if we're in a browser environment\n */\nconst isBrowser = typeof window !== 'undefined';\n\n/**\n * Format timestamp as ISO string or relative time\n */\nfunction formatTimestamp(timestamp: number): string {\n const date = new Date(timestamp);\n return date.toISOString().substring(11, 23); // HH:mm:ss.SSS\n}\n\n/**\n * Safely serialize data to JSON, handling circular references\n */\nfunction safeStringify(data: unknown): string {\n const seen = new WeakSet();\n return JSON.stringify(data, (key, value) => {\n if (typeof value === 'object' && value !== null) {\n if (seen.has(value)) {\n return '[Circular]';\n }\n seen.add(value);\n }\n // Handle special types\n if (value instanceof Error) {\n return {\n name: value.name,\n message: value.message,\n stack: value.stack,\n };\n }\n if (value instanceof Float32Array || value instanceof Int16Array) {\n return `${value.constructor.name}(${value.length})`;\n }\n if (ArrayBuffer.isView(value)) {\n return `${value.constructor.name}(${value.byteLength})`;\n }\n return value;\n });\n}\n\n/**\n * JSON formatter - structured output for machine parsing\n */\nexport const jsonFormatter: LogFormatter = (entry: LogEntry): string => {\n const output: Record<string, unknown> = {\n timestamp: entry.timestamp,\n level: entry.level,\n module: entry.module,\n message: entry.message,\n };\n\n if (entry.data && Object.keys(entry.data).length > 0) {\n output.data = entry.data;\n }\n\n if (entry.error) {\n output.error = {\n name: entry.error.name,\n message: entry.error.message,\n stack: entry.error.stack,\n };\n }\n\n return safeStringify(output);\n};\n\n/**\n * Pretty formatter - human-readable output with colors\n */\nexport const prettyFormatter: LogFormatter = (entry: LogEntry): string => {\n const time = formatTimestamp(entry.timestamp);\n const level = LEVEL_NAMES[entry.level];\n const module = entry.module;\n const message = entry.message;\n\n // Build the base message\n let output: string;\n\n if (isBrowser) {\n // Browser: no ANSI colors, use plain text\n output = `${time} ${level} [${module}] ${message}`;\n } else {\n // Terminal: use ANSI colors\n const color = LEVEL_COLORS[entry.level];\n output = `${COLORS.gray}${time}${COLORS.reset} ${color}${level}${COLORS.reset} ${COLORS.cyan}[${module}]${COLORS.reset} ${message}`;\n }\n\n // Append data if present\n if (entry.data && Object.keys(entry.data).length > 0) {\n const dataStr = safeStringify(entry.data);\n // For pretty format, indent multi-line data\n if (dataStr.length > 80) {\n output += '\\n ' + JSON.stringify(entry.data, null, 2).replace(/\\n/g, '\\n ');\n } else {\n output += ' ' + dataStr;\n }\n }\n\n // Append error if present\n if (entry.error) {\n output += `\\n ${entry.error.name}: ${entry.error.message}`;\n if (entry.error.stack) {\n const stackLines = entry.error.stack.split('\\n').slice(1, 4);\n output += '\\n ' + stackLines.join('\\n ');\n }\n }\n\n return output;\n};\n\n/**\n * Get formatter by name\n */\nexport function getFormatter(format: 'json' | 'pretty'): LogFormatter {\n return format === 'json' ? jsonFormatter : prettyFormatter;\n}\n\n/**\n * Create browser console arguments for styled output\n * Returns [formatString, ...styleArgs] for console.log\n */\nexport function createBrowserConsoleArgs(entry: LogEntry): [string, ...string[]] {\n const time = formatTimestamp(entry.timestamp);\n const level = entry.level.toUpperCase().padEnd(7);\n const module = entry.module;\n const message = entry.message;\n\n // CSS styles for browser console\n const styles = {\n time: 'color: gray;',\n error: 'color: red; font-weight: bold;',\n warn: 'color: orange; font-weight: bold;',\n info: 'color: blue;',\n debug: 'color: cyan;',\n trace: 'color: magenta;',\n verbose: 'color: gray;',\n module: 'color: teal; font-weight: bold;',\n message: 'color: inherit;',\n };\n\n let formatStr = '%c%s %c%s %c[%s]%c %s';\n const args: string[] = [\n styles.time,\n time,\n styles[entry.level],\n level,\n styles.module,\n module,\n styles.message,\n message,\n ];\n\n // Append data\n if (entry.data && Object.keys(entry.data).length > 0) {\n formatStr += ' %o';\n args.push(entry.data as unknown as string);\n }\n\n return [formatStr, ...args];\n}\n","/**\n * Abstract monotonic clock for runtime-agnostic timing.\n *\n * **Portability contract**: To port the SDK to Node.js, Python, Unreal, or Unity,\n * implement this interface with your runtime's high-resolution timer and call\n * `configureClock()` at startup.\n *\n * @example Node.js\n * ```typescript\n * import { configureClock } from '@omote/core';\n * configureClock({\n * now: () => Number(process.hrtime.bigint() / 1_000_000n),\n * timestamp: () => Date.now(),\n * });\n * ```\n *\n * @example Unreal Engine (via wasm-bindgen)\n * ```typescript\n * configureClock({\n * now: () => FPlatformTime.Seconds() * 1000,\n * timestamp: () => FDateTime.UtcNow().ToUnixTimestamp() * 1000,\n * });\n * ```\n *\n * @example Unity (via jslib bridge)\n * ```typescript\n * configureClock({\n * now: () => Time.realtimeSinceStartup * 1000,\n * timestamp: () => Date.now(),\n * });\n * ```\n */\nexport interface Clock {\n /** Monotonic high-resolution milliseconds (for durations, telemetry spans) */\n now(): number;\n /** Wall-clock milliseconds since epoch (for log timestamps) */\n timestamp(): number;\n}\n\nexport const defaultClock: Clock = {\n now: () => performance.now(),\n timestamp: () => Date.now(),\n};\n\nlet activeClock: Clock = defaultClock;\n\n/** Replace the default browser clock with a custom implementation. */\nexport function configureClock(clock: Clock): void {\n activeClock = clock;\n}\n\n/** Get the active clock instance. */\nexport function getClock(): Clock {\n return activeClock;\n}\n","/**\n * Muse Telemetry\n *\n * Main orchestrator for SDK telemetry. Manages spans, metrics, and exporters.\n *\n * @category Telemetry\n */\n\nimport type { TelemetryConfig, SpanAttributes, SamplingConfig } from './types';\nimport type { SpanData, MetricData, TelemetryExporterInterface } from './exporters/console';\nimport { ConsoleExporter } from './exporters/console';\nimport { OTLPExporter } from './exporters/otlp';\nimport { getClock } from '../logging/Clock';\n\n/**\n * Generate a random hex ID\n */\nfunction generateId(length: number = 16): string {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Span context for tracing\n */\ninterface SpanContext {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n}\n\n/**\n * Active span handle returned by startSpan\n */\nexport interface ActiveSpan {\n /** End the span with success status */\n end(): void;\n /** End the span with error status */\n endWithError(error: Error): void;\n /** Add attributes to the span */\n setAttributes(attrs: Partial<SpanAttributes>): void;\n /** Get the span context */\n getContext(): SpanContext;\n}\n\n/**\n * Global telemetry instance\n */\nlet globalTelemetry: OmoteTelemetry | null = null;\n\n/**\n * Configure global telemetry\n *\n * @example\n * ```typescript\n * // Development\n * configureTelemetry({\n * enabled: true,\n * serviceName: 'omote-dev',\n * exporter: 'console',\n * });\n *\n * // Production\n * configureTelemetry({\n * enabled: true,\n * serviceName: 'omote-prod',\n * exporter: 'otlp',\n * exporterConfig: {\n * endpoint: 'https://tempo.example.com',\n * },\n * sampling: { ratio: 0.1 },\n * });\n * ```\n */\nexport function configureTelemetry(config: TelemetryConfig): OmoteTelemetry {\n if (globalTelemetry) {\n globalTelemetry.shutdown();\n }\n globalTelemetry = new OmoteTelemetry(config);\n return globalTelemetry;\n}\n\n/**\n * Get the global telemetry instance\n */\nexport function getTelemetry(): OmoteTelemetry | null {\n return globalTelemetry;\n}\n\n/**\n * Main telemetry class\n *\n * Manages spans, metrics, and exports to configured backends.\n */\nexport class OmoteTelemetry {\n private config: Required<Omit<TelemetryConfig, 'exporterConfig'>> & { exporterConfig?: TelemetryConfig['exporterConfig'] };\n private exporter: TelemetryExporterInterface | null = null;\n private activeTraceId: string | null = null;\n private metricsIntervalId: ReturnType<typeof setInterval> | null = null;\n\n // Span stack for log-to-span correlation\n private spanStack: Array<{ traceId: string; spanId: string }> = [];\n\n // Metric accumulators\n private counters: Map<string, { value: number; attributes: Record<string, string | number | boolean> }> = new Map();\n private histograms: Map<string, { count: number; sum: number; min: number; max: number; attributes: Record<string, string | number | boolean> }> = new Map();\n\n constructor(config: TelemetryConfig) {\n this.config = {\n enabled: config.enabled ?? false,\n serviceName: config.serviceName ?? 'omote-sdk',\n serviceVersion: config.serviceVersion ?? '0.1.0',\n exporter: config.exporter ?? 'none',\n exporterConfig: config.exporterConfig,\n sampling: config.sampling ?? { ratio: 1.0, alwaysSampleErrors: true },\n metricsEnabled: config.metricsEnabled ?? true,\n metricsIntervalMs: config.metricsIntervalMs ?? 60000,\n };\n\n if (this.config.enabled) {\n this.initExporter();\n this.startMetricsCollection();\n }\n }\n\n /**\n * Initialize the configured exporter\n */\n private initExporter(): void {\n switch (this.config.exporter) {\n case 'console':\n this.exporter = new ConsoleExporter({ enabled: true });\n break;\n case 'otlp':\n if (!this.config.exporterConfig) {\n console.warn('[Telemetry] OTLP exporter requires exporterConfig with endpoint');\n return;\n }\n this.exporter = new OTLPExporter(\n this.config.exporterConfig,\n this.config.serviceName,\n this.config.serviceVersion\n );\n break;\n case 'none':\n default:\n this.exporter = null;\n }\n }\n\n /**\n * Start periodic metrics collection\n */\n private startMetricsCollection(): void {\n if (!this.config.metricsEnabled || !this.exporter) return;\n\n this.metricsIntervalId = setInterval(() => {\n this.flushMetrics();\n }, this.config.metricsIntervalMs);\n }\n\n /**\n * Check if this operation should be sampled\n */\n private shouldSample(isError: boolean = false): boolean {\n if (!this.config.enabled) return false;\n\n const sampling = this.config.sampling as SamplingConfig;\n if (isError && sampling.alwaysSampleErrors) return true;\n\n const ratio = sampling.ratio ?? 1.0;\n return Math.random() < ratio;\n }\n\n /**\n * Start a new span\n *\n * @example\n * ```typescript\n * const span = telemetry.startSpan('Wav2Vec2.infer', {\n * 'inference.input_samples': samples.length,\n * 'model.backend': 'webgpu',\n * });\n *\n * try {\n * const result = await doInference();\n * span.setAttributes({ 'inference.output_frames': result.frames });\n * span.end();\n * } catch (error) {\n * span.endWithError(error);\n * }\n * ```\n */\n startSpan(name: string, attributes: Partial<SpanAttributes> = {}, parentContext?: SpanContext): ActiveSpan {\n const traceId = parentContext?.traceId ?? this.activeTraceId ?? generateId(16);\n const spanId = generateId(8);\n const parentSpanId = parentContext?.spanId;\n const startTime = getClock().now();\n\n // Set active trace if this is a root span\n if (!parentContext && !this.activeTraceId) {\n this.activeTraceId = traceId;\n }\n\n let spanAttributes = { ...attributes };\n let ended = false;\n let sampled = this.shouldSample();\n\n const context: SpanContext = { traceId, spanId, parentSpanId };\n\n // Push to span stack for log-to-span correlation\n this.spanStack.push({ traceId, spanId });\n\n const endSpan = (status: 'ok' | 'error', error?: Error): void => {\n if (ended) return;\n ended = true;\n\n // Pop from span stack\n const idx = this.spanStack.findIndex(s => s.spanId === spanId);\n if (idx !== -1) this.spanStack.splice(idx, 1);\n\n const endTime = getClock().now();\n const durationMs = endTime - startTime;\n\n // Re-check sampling for errors\n if (status === 'error' && !sampled) {\n sampled = this.shouldSample(true);\n }\n\n if (!sampled || !this.exporter) return;\n\n const spanData: SpanData = {\n name,\n traceId,\n spanId,\n parentSpanId,\n startTime,\n endTime,\n durationMs,\n status,\n attributes: spanAttributes as SpanAttributes,\n error,\n };\n\n this.exporter.exportSpan(spanData);\n\n // Clear active trace if this was the root span\n if (!parentSpanId && this.activeTraceId === traceId) {\n this.activeTraceId = null;\n }\n };\n\n return {\n end: () => endSpan('ok'),\n endWithError: (error: Error) => endSpan('error', error),\n setAttributes: (attrs: Partial<SpanAttributes>) => {\n spanAttributes = { ...spanAttributes, ...attrs };\n },\n getContext: () => context,\n };\n }\n\n /**\n * Wrap an async function with a span\n *\n * @example\n * ```typescript\n * const result = await telemetry.withSpan('Model.load', async (span) => {\n * const model = await loadModel();\n * span.setAttributes({ 'model.size_bytes': model.size });\n * return model;\n * });\n * ```\n */\n async withSpan<T>(\n name: string,\n fn: (span: ActiveSpan) => Promise<T>,\n attributes: Partial<SpanAttributes> = {},\n parentContext?: SpanContext\n ): Promise<T> {\n const span = this.startSpan(name, attributes, parentContext);\n\n try {\n const result = await fn(span);\n span.end();\n return result;\n } catch (error) {\n span.endWithError(error as Error);\n throw error;\n }\n }\n\n /**\n * Increment a counter metric\n *\n * @example\n * ```typescript\n * telemetry.incrementCounter('omote.inference.total', 1, {\n * model: 'wav2vec2',\n * backend: 'webgpu',\n * status: 'success',\n * });\n * ```\n */\n incrementCounter(\n name: string,\n value: number = 1,\n attributes: Record<string, string | number | boolean> = {}\n ): void {\n if (!this.config.enabled || !this.config.metricsEnabled) return;\n\n const key = this.getMetricKey(name, attributes);\n const existing = this.counters.get(key);\n\n if (existing) {\n existing.value += value;\n } else {\n this.counters.set(key, { value, attributes });\n }\n }\n\n /**\n * Record a histogram value\n *\n * @example\n * ```typescript\n * telemetry.recordHistogram('omote.inference.latency', durationMs, {\n * model: 'wav2vec2',\n * backend: 'webgpu',\n * });\n * ```\n */\n recordHistogram(\n name: string,\n value: number,\n attributes: Record<string, string | number | boolean> = {}\n ): void {\n if (!this.config.enabled || !this.config.metricsEnabled) return;\n\n const key = this.getMetricKey(name, attributes);\n const existing = this.histograms.get(key);\n\n if (existing) {\n existing.count++;\n existing.sum += value;\n if (value < existing.min) existing.min = value;\n if (value > existing.max) existing.max = value;\n } else {\n this.histograms.set(key, { count: 1, sum: value, min: value, max: value, attributes });\n }\n }\n\n /**\n * Generate unique key for metric with attributes\n */\n private getMetricKey(name: string, attributes: Record<string, string | number | boolean>): string {\n // Fast path: no attributes → return name directly (avoids Object.entries + sort + join)\n const keys = Object.keys(attributes);\n if (keys.length === 0) return name;\n\n const sortedAttrs = Object.entries(attributes)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}=${v}`)\n .join(',');\n return `${name}|${sortedAttrs}`;\n }\n\n /**\n * Flush accumulated metrics to exporter\n */\n private flushMetrics(): void {\n if (!this.exporter) return;\n\n const timestamp = getClock().now();\n\n // Export counters (delta temporality — reset after export)\n for (const [key, data] of this.counters) {\n if (data.value === 0) continue;\n const name = key.split('|')[0];\n const metric: MetricData = {\n name,\n type: 'counter',\n value: data.value,\n attributes: data.attributes,\n timestamp,\n };\n this.exporter.exportMetric(metric);\n data.value = 0;\n }\n\n // Export histogram aggregates (O(1) — no array spread)\n for (const [key, data] of this.histograms) {\n const name = key.split('|')[0];\n if (data.count === 0) continue;\n\n const avg = data.sum / data.count;\n\n const metric: MetricData = {\n name,\n type: 'histogram',\n value: avg,\n attributes: {\n ...data.attributes,\n count: data.count,\n sum: data.sum,\n min: data.min,\n max: data.max,\n },\n timestamp,\n };\n this.exporter.exportMetric(metric);\n\n // Reset accumulators after export\n data.count = 0;\n data.sum = 0;\n data.min = Infinity;\n data.max = -Infinity;\n }\n }\n\n /**\n * Force flush all pending data\n */\n async flush(): Promise<void> {\n this.flushMetrics();\n await this.exporter?.flush();\n }\n\n /**\n * Shutdown telemetry\n */\n async shutdown(): Promise<void> {\n if (this.metricsIntervalId) {\n clearInterval(this.metricsIntervalId);\n this.metricsIntervalId = null;\n }\n\n await this.flush();\n await this.exporter?.shutdown();\n this.exporter = null;\n }\n\n /**\n * Check if telemetry is enabled\n */\n isEnabled(): boolean {\n return this.config.enabled;\n }\n\n /**\n * Get current configuration\n */\n getConfig(): TelemetryConfig {\n return { ...this.config };\n }\n\n /**\n * Get the active span context for log-to-span correlation.\n * Returns the most recent (top of stack) active span, or null if none.\n */\n getActiveContext(): { traceId: string; spanId: string } | null {\n return this.spanStack.length > 0 ? this.spanStack[this.spanStack.length - 1] : null;\n }\n}\n","/**\n * Omote SDK Logger\n *\n * Unified logging system with:\n * - 6 log levels (error, warn, info, debug, trace, verbose)\n * - Structured JSON output for machine parsing\n * - Pretty output for human readability\n * - Module-based child loggers\n * - Runtime configuration\n * - Browser and Node.js compatible\n */\n\nimport type {\n LogLevel,\n LogEntry,\n LoggingConfig,\n LogSink,\n ILogger,\n} from './types';\nimport { LOG_LEVEL_PRIORITY, DEFAULT_LOGGING_CONFIG } from './types';\nimport { getFormatter, createBrowserConsoleArgs } from './formatters';\nimport { getTelemetry } from '../telemetry/OmoteTelemetry';\nimport { getClock } from './Clock';\n\n/**\n * Check if running in browser\n */\nconst isBrowser = typeof window !== 'undefined';\n\n/**\n * Global logging configuration\n */\nlet globalConfig: LoggingConfig = { ...DEFAULT_LOGGING_CONFIG };\n\n/**\n * Configure global logging settings\n */\nexport function configureLogging(config: Partial<LoggingConfig>): void {\n globalConfig = { ...globalConfig, ...config };\n}\n\n/**\n * Get current logging configuration\n */\nexport function getLoggingConfig(): LoggingConfig {\n return { ...globalConfig };\n}\n\n/**\n * Reset logging configuration to defaults\n */\nexport function resetLoggingConfig(): void {\n globalConfig = { ...DEFAULT_LOGGING_CONFIG };\n}\n\n/**\n * Set log level at runtime\n */\nexport function setLogLevel(level: LogLevel): void {\n globalConfig.level = level;\n}\n\n/**\n * Enable or disable logging\n */\nexport function setLoggingEnabled(enabled: boolean): void {\n globalConfig.enabled = enabled;\n}\n\n/**\n * Default console sink with browser-optimized output\n */\nconst consoleSink: LogSink = (entry: LogEntry): void => {\n const consoleMethod = entry.level === 'error' ? 'error'\n : entry.level === 'warn' ? 'warn'\n : 'log';\n\n if (globalConfig.format === 'pretty' && isBrowser) {\n // Use styled console output in browser\n const args = createBrowserConsoleArgs(entry);\n (console as unknown as Record<string, (...args: unknown[]) => void>)[consoleMethod](...args);\n } else {\n // Use formatter for terminal or JSON output\n const formatter = getFormatter(globalConfig.format);\n const formatted = formatter(entry);\n (console as unknown as Record<string, (...args: unknown[]) => void>)[consoleMethod](formatted);\n }\n};\n\n/**\n * Get the active sink (custom or default console)\n */\nfunction getActiveSink(): LogSink {\n return globalConfig.sink || consoleSink;\n}\n\n/**\n * Check if a log level should be output given current config\n */\nfunction shouldLog(level: LogLevel): boolean {\n if (!globalConfig.enabled) return false;\n return LOG_LEVEL_PRIORITY[level] <= LOG_LEVEL_PRIORITY[globalConfig.level];\n}\n\n/**\n * Logger implementation\n */\nclass Logger implements ILogger {\n readonly module: string;\n\n constructor(module: string) {\n this.module = module;\n }\n\n private log(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (!shouldLog(level)) return;\n\n const entry: LogEntry = {\n timestamp: getClock().timestamp(),\n level,\n module: this.module,\n message,\n data,\n };\n\n // Attach active span context for log-to-span correlation\n const ctx = getTelemetry()?.getActiveContext();\n if (ctx) {\n entry.traceId = ctx.traceId;\n entry.spanId = ctx.spanId;\n }\n\n // Extract error from data if present\n if (data?.error instanceof Error) {\n entry.error = data.error;\n // Remove from data to avoid duplication\n const { error, ...rest } = data;\n entry.data = Object.keys(rest).length > 0 ? rest : undefined;\n }\n\n getActiveSink()(entry);\n }\n\n error(message: string, data?: Record<string, unknown>): void {\n this.log('error', message, data);\n }\n\n warn(message: string, data?: Record<string, unknown>): void {\n this.log('warn', message, data);\n }\n\n info(message: string, data?: Record<string, unknown>): void {\n this.log('info', message, data);\n }\n\n debug(message: string, data?: Record<string, unknown>): void {\n this.log('debug', message, data);\n }\n\n trace(message: string, data?: Record<string, unknown>): void {\n this.log('trace', message, data);\n }\n\n verbose(message: string, data?: Record<string, unknown>): void {\n this.log('verbose', message, data);\n }\n\n child(subModule: string): ILogger {\n return new Logger(`${this.module}.${subModule}`);\n }\n}\n\n/**\n * Logger cache for reusing instances\n */\nconst loggerCache = new Map<string, Logger>();\n\n/**\n * Create a logger for a specific module\n *\n * @param module - Module name (e.g., 'LocalInference', 'ModelCache')\n * @returns Logger instance\n *\n * @example\n * ```typescript\n * const logger = createLogger('LocalInference');\n * logger.info('Model loaded', { backend: 'webgpu', loadTimeMs: 1234 });\n * ```\n */\nexport function createLogger(module: string): ILogger {\n let logger = loggerCache.get(module);\n if (!logger) {\n logger = new Logger(module);\n loggerCache.set(module, logger);\n }\n return logger;\n}\n\n/**\n * Clear logger cache (useful for testing)\n */\nexport function clearLoggerCache(): void {\n loggerCache.clear();\n}\n\n/**\n * No-op logger for when logging is completely disabled\n */\nexport const noopLogger: ILogger = {\n module: 'noop',\n error: () => {},\n warn: () => {},\n info: () => {},\n debug: () => {},\n trace: () => {},\n verbose: () => {},\n child: () => noopLogger,\n};\n\n/**\n * Get a no-op logger (for production builds that tree-shake logging)\n */\nexport function getNoopLogger(): ILogger {\n return noopLogger;\n}\n","/**\n * Structured error codes for the Omote SDK.\n *\n * Codes follow the pattern `OMOTE_{CATEGORY}_{SEQ}` where:\n * - **INF** = Inference (model loading, session, OOM)\n * - **AUD** = Audio (AudioContext, scheduling, decoding)\n * - **SPH** = Speech (VAD, ASR, microphone)\n * - **TTS** = Text-to-Speech (synthesis, streaming, phonemizer)\n * - **PIP** = Pipeline (state machine, abort)\n * - **CAC** = Cache (IndexedDB quota, eviction, staleness)\n * - **NET** = Network (fetch, timeout, WebSocket)\n *\n * Exported as a const object (not enum) for tree-shaking.\n */\nexport const ErrorCodes = {\n // ── Inference ──────────────────────────────────────────────────────────\n /** Model failed to load (file not found, corrupted, unsupported format) */\n INF_LOAD_FAILED: 'OMOTE_INF_001',\n /** ORT session poisoned after WebGPU device loss — must reload tab */\n INF_SESSION_POISON: 'OMOTE_INF_002',\n /** Inference exceeded timeout threshold */\n INF_TIMEOUT: 'OMOTE_INF_003',\n /** Out-of-memory during inference or model loading */\n INF_OOM: 'OMOTE_INF_004',\n /** WebGPU unavailable, fell back to WASM */\n INF_WEBGPU_FALLBACK: 'OMOTE_INF_005',\n /** Input tensor shape does not match model expectations */\n INF_SHAPE_MISMATCH: 'OMOTE_INF_006',\n\n // ── Audio ──────────────────────────────────────────────────────────────\n /** AudioContext creation or resume failed */\n AUD_CONTEXT_FAILED: 'OMOTE_AUD_001',\n /** Gap detected in audio scheduling (buffer underrun) */\n AUD_SCHEDULE_GAP: 'OMOTE_AUD_002',\n /** Audio buffer decoding failed */\n AUD_DECODE_FAILED: 'OMOTE_AUD_003',\n\n // ── Speech ─────────────────────────────────────────────────────────────\n /** Voice activity detection error */\n SPH_VAD_ERROR: 'OMOTE_SPH_001',\n /** Automatic speech recognition error */\n SPH_ASR_ERROR: 'OMOTE_SPH_002',\n /** Microphone access denied or unavailable */\n SPH_MIC_DENIED: 'OMOTE_SPH_003',\n\n // ── TTS ────────────────────────────────────────────────────────────────\n /** TTS synthesis failed */\n TTS_SYNTH_FAILED: 'OMOTE_TTS_001',\n /** TTS streaming error (chunk delivery failure) */\n TTS_STREAM_ERROR: 'OMOTE_TTS_002',\n /** Phonemizer (eSpeak-NG WASM) ran out of memory */\n TTS_PHONEMIZER_OOM: 'OMOTE_TTS_003',\n\n // ── Pipeline ───────────────────────────────────────────────────────────\n /** Invalid state transition in pipeline state machine */\n PIP_STATE_ERROR: 'OMOTE_PIP_001',\n /** Pipeline operation aborted (user interrupt or signal) */\n PIP_ABORT: 'OMOTE_PIP_002',\n\n // ── Cache ──────────────────────────────────────────────────────────────\n /** IndexedDB storage quota exceeded */\n CAC_QUOTA_EXCEEDED: 'OMOTE_CAC_001',\n /** Cache entry evicted (LRU or manual) */\n CAC_EVICTION: 'OMOTE_CAC_002',\n /** Cached model is stale (version mismatch) */\n CAC_STALE: 'OMOTE_CAC_003',\n\n // ── Network ────────────────────────────────────────────────────────────\n /** HTTP fetch failed (model download, CDN) */\n NET_FETCH_FAILED: 'OMOTE_NET_001',\n /** Network request timed out */\n NET_TIMEOUT: 'OMOTE_NET_002',\n /** WebSocket connection error */\n NET_WEBSOCKET_ERROR: 'OMOTE_NET_003',\n} as const;\n\n/** Union type of all error code string values. */\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA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AAAA,EAIX,kBAAkB;AAAA;AAAA,EAElB,aAAa;AAAA;AAAA,EAEb,qBAAqB;AACvB;","names":["module","isBrowser","module"]}
|
|
1
|
+
{"version":3,"sources":["../../src/logging/index.ts","../../src/logging/types.ts","../../src/logging/formatters.ts","../../src/logging/Clock.ts","../../src/telemetry/OmoteTelemetry.ts","../../src/logging/Logger.ts","../../src/logging/ErrorCodes.ts"],"sourcesContent":["/**\n * Omote SDK Logging Module\n *\n * Unified logging system for all Muse components with:\n * - 6 log levels: error, warn, info, debug, trace, verbose\n * - Structured JSON output for machine parsing\n * - Pretty output for human readability\n * - Module-based child loggers\n * - Runtime configuration\n * - Browser and Node.js compatible\n *\n * @example\n * ```typescript\n * import { configureLogging, createLogger } from '@omote/core';\n *\n * // Configure globally\n * configureLogging({\n * level: 'debug',\n * format: 'pretty',\n * });\n *\n * // Create module logger\n * const logger = createLogger('MyModule');\n * logger.info('Operation complete', { durationMs: 123 });\n * ```\n */\n\n// Types\nexport type {\n LogLevel,\n LogEntry,\n LogSink,\n LogFormatter,\n LoggingConfig,\n ILogger,\n} from './types';\n\nexport {\n LOG_LEVEL_PRIORITY,\n DEFAULT_LOGGING_CONFIG,\n} from './types';\n\n// Formatters\nexport {\n jsonFormatter,\n prettyFormatter,\n getFormatter,\n} from './formatters';\n\n// Logger\nexport {\n configureLogging,\n getLoggingConfig,\n resetLoggingConfig,\n setLogLevel,\n setLoggingEnabled,\n createLogger,\n clearLoggerCache,\n noopLogger,\n getNoopLogger,\n} from './Logger';\n\n// Clock (runtime-agnostic timing)\nexport { getClock, configureClock, defaultClock } from './Clock';\nexport type { Clock } from './Clock';\n\n// Error codes\nexport { ErrorCodes } from './ErrorCodes';\nexport type { ErrorCode } from './ErrorCodes';\n","/**\n * Logging types for Omote SDK\n *\n * 6-level logging system with structured output:\n * - error: Critical failures that prevent operation\n * - warn: Recoverable issues or degraded performance\n * - info: Key lifecycle events (model loaded, inference complete)\n * - debug: Detailed operational info for development\n * - trace: Fine-grained tracing for performance analysis\n * - verbose: Extremely detailed output (tensor shapes, intermediate values)\n */\n\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'verbose';\n\n/**\n * Numeric priority for log levels (lower = more severe)\n */\nexport const LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n trace: 4,\n verbose: 5,\n};\n\n/**\n * Structured log entry\n */\nexport interface LogEntry {\n /** Unix timestamp in milliseconds */\n timestamp: number;\n /** Log level */\n level: LogLevel;\n /** Module name (e.g., 'LocalInference', 'ModelCache') */\n module: string;\n /** Human-readable message */\n message: string;\n /** Optional structured error code from ErrorCodes (e.g., 'OMOTE_INF_001') */\n code?: string;\n /** Optional structured data */\n data?: Record<string, unknown>;\n /** Optional error object */\n error?: Error;\n /** Trace ID from active telemetry span (log-to-span correlation) */\n traceId?: string;\n /** Span ID from active telemetry span (log-to-span correlation) */\n spanId?: string;\n}\n\n/**\n * Log output sink interface.\n *\n * **Portability contract**: Replace the default console sink to route logs to\n * any backend — Node.js winston/pino, Unreal UE_LOG, Unity Debug.Log, or a\n * remote telemetry service. Register via `configureLogging({ sink: mySink })`.\n */\nexport interface LogSink {\n (entry: LogEntry): void;\n}\n\n/**\n * Log formatter interface\n */\nexport interface LogFormatter {\n (entry: LogEntry): string;\n}\n\n/**\n * Global logging configuration\n */\nexport interface LoggingConfig {\n /** Minimum log level to output (default: 'info') */\n level: LogLevel;\n /** Enable/disable logging globally (default: true) */\n enabled: boolean;\n /** Output format: 'json' for structured, 'pretty' for human-readable */\n format: 'json' | 'pretty';\n /** Custom output sink (default: console) */\n sink?: LogSink;\n /** Include timestamps in output (default: true) */\n timestamps?: boolean;\n /** Include module name in output (default: true) */\n includeModule?: boolean;\n}\n\n/**\n * Logger interface for module-specific logging.\n *\n * **Portability contract**: All SDK modules depend only on this interface.\n * To integrate with a non-browser runtime (Node.js, Unreal, Unity), either:\n * 1. Use the built-in Logger with a custom `LogSink`, or\n * 2. Provide your own `ILogger` implementation that bridges to the host\n * runtime's logging system (e.g., `console.log`, `UE_LOG`, `Debug.Log`).\n */\nexport interface ILogger {\n error(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n info(message: string, data?: Record<string, unknown>): void;\n debug(message: string, data?: Record<string, unknown>): void;\n trace(message: string, data?: Record<string, unknown>): void;\n verbose(message: string, data?: Record<string, unknown>): void;\n\n /** Create a child logger with a sub-module name */\n child(subModule: string): ILogger;\n\n /** Get the module name for this logger */\n readonly module: string;\n}\n\n/**\n * Default configuration\n */\nexport const DEFAULT_LOGGING_CONFIG: LoggingConfig = {\n level: 'info',\n enabled: true,\n format: 'pretty',\n timestamps: true,\n includeModule: true,\n};\n","/**\n * Log formatters for different output formats\n */\n\nimport type { LogEntry, LogFormatter, LogLevel } from './types';\n\n/**\n * ANSI color codes for terminal output\n */\nconst COLORS = {\n reset: '\\x1b[0m',\n red: '\\x1b[31m',\n yellow: '\\x1b[33m',\n blue: '\\x1b[34m',\n cyan: '\\x1b[36m',\n gray: '\\x1b[90m',\n white: '\\x1b[37m',\n magenta: '\\x1b[35m',\n};\n\n/**\n * Level-specific colors\n */\nconst LEVEL_COLORS: Record<LogLevel, string> = {\n error: COLORS.red,\n warn: COLORS.yellow,\n info: COLORS.blue,\n debug: COLORS.cyan,\n trace: COLORS.magenta,\n verbose: COLORS.gray,\n};\n\n/**\n * Level display names (padded for alignment)\n */\nconst LEVEL_NAMES: Record<LogLevel, string> = {\n error: 'ERROR ',\n warn: 'WARN ',\n info: 'INFO ',\n debug: 'DEBUG ',\n trace: 'TRACE ',\n verbose: 'VERBOSE',\n};\n\n/**\n * Check if we're in a browser environment\n */\nconst isBrowser = typeof window !== 'undefined';\n\n/**\n * Format timestamp as ISO string or relative time\n */\nfunction formatTimestamp(timestamp: number): string {\n const date = new Date(timestamp);\n return date.toISOString().substring(11, 23); // HH:mm:ss.SSS\n}\n\n/**\n * Safely serialize data to JSON, handling circular references\n */\nfunction safeStringify(data: unknown): string {\n const seen = new WeakSet();\n return JSON.stringify(data, (key, value) => {\n if (typeof value === 'object' && value !== null) {\n if (seen.has(value)) {\n return '[Circular]';\n }\n seen.add(value);\n }\n // Handle special types\n if (value instanceof Error) {\n return {\n name: value.name,\n message: value.message,\n stack: value.stack,\n };\n }\n if (value instanceof Float32Array || value instanceof Int16Array) {\n return `${value.constructor.name}(${value.length})`;\n }\n if (ArrayBuffer.isView(value)) {\n return `${value.constructor.name}(${value.byteLength})`;\n }\n return value;\n });\n}\n\n/**\n * JSON formatter - structured output for machine parsing\n */\nexport const jsonFormatter: LogFormatter = (entry: LogEntry): string => {\n const output: Record<string, unknown> = {\n timestamp: entry.timestamp,\n level: entry.level,\n module: entry.module,\n message: entry.message,\n };\n\n if (entry.data && Object.keys(entry.data).length > 0) {\n output.data = entry.data;\n }\n\n if (entry.error) {\n output.error = {\n name: entry.error.name,\n message: entry.error.message,\n stack: entry.error.stack,\n };\n }\n\n return safeStringify(output);\n};\n\n/**\n * Pretty formatter - human-readable output with colors\n */\nexport const prettyFormatter: LogFormatter = (entry: LogEntry): string => {\n const time = formatTimestamp(entry.timestamp);\n const level = LEVEL_NAMES[entry.level];\n const module = entry.module;\n const message = entry.message;\n\n // Build the base message\n let output: string;\n\n if (isBrowser) {\n // Browser: no ANSI colors, use plain text\n output = `${time} ${level} [${module}] ${message}`;\n } else {\n // Terminal: use ANSI colors\n const color = LEVEL_COLORS[entry.level];\n output = `${COLORS.gray}${time}${COLORS.reset} ${color}${level}${COLORS.reset} ${COLORS.cyan}[${module}]${COLORS.reset} ${message}`;\n }\n\n // Append data if present\n if (entry.data && Object.keys(entry.data).length > 0) {\n const dataStr = safeStringify(entry.data);\n // For pretty format, indent multi-line data\n if (dataStr.length > 80) {\n output += '\\n ' + JSON.stringify(entry.data, null, 2).replace(/\\n/g, '\\n ');\n } else {\n output += ' ' + dataStr;\n }\n }\n\n // Append error if present\n if (entry.error) {\n output += `\\n ${entry.error.name}: ${entry.error.message}`;\n if (entry.error.stack) {\n const stackLines = entry.error.stack.split('\\n').slice(1, 4);\n output += '\\n ' + stackLines.join('\\n ');\n }\n }\n\n return output;\n};\n\n/**\n * Get formatter by name\n */\nexport function getFormatter(format: 'json' | 'pretty'): LogFormatter {\n return format === 'json' ? jsonFormatter : prettyFormatter;\n}\n\n/**\n * Create browser console arguments for styled output\n * Returns [formatString, ...styleArgs] for console.log\n */\nexport function createBrowserConsoleArgs(entry: LogEntry): [string, ...string[]] {\n const time = formatTimestamp(entry.timestamp);\n const level = entry.level.toUpperCase().padEnd(7);\n const module = entry.module;\n const message = entry.message;\n\n // CSS styles for browser console\n const styles = {\n time: 'color: gray;',\n error: 'color: red; font-weight: bold;',\n warn: 'color: orange; font-weight: bold;',\n info: 'color: blue;',\n debug: 'color: cyan;',\n trace: 'color: magenta;',\n verbose: 'color: gray;',\n module: 'color: teal; font-weight: bold;',\n message: 'color: inherit;',\n };\n\n let formatStr = '%c%s %c%s %c[%s]%c %s';\n const args: string[] = [\n styles.time,\n time,\n styles[entry.level],\n level,\n styles.module,\n module,\n styles.message,\n message,\n ];\n\n // Append data\n if (entry.data && Object.keys(entry.data).length > 0) {\n formatStr += ' %o';\n args.push(entry.data as unknown as string);\n }\n\n return [formatStr, ...args];\n}\n","/**\n * Abstract monotonic clock for runtime-agnostic timing.\n *\n * **Portability contract**: To port the SDK to Node.js, Python, Unreal, or Unity,\n * implement this interface with your runtime's high-resolution timer and call\n * `configureClock()` at startup.\n *\n * @example Node.js\n * ```typescript\n * import { configureClock } from '@omote/core';\n * configureClock({\n * now: () => Number(process.hrtime.bigint() / 1_000_000n),\n * timestamp: () => Date.now(),\n * });\n * ```\n *\n * @example Unreal Engine (via wasm-bindgen)\n * ```typescript\n * configureClock({\n * now: () => FPlatformTime.Seconds() * 1000,\n * timestamp: () => FDateTime.UtcNow().ToUnixTimestamp() * 1000,\n * });\n * ```\n *\n * @example Unity (via jslib bridge)\n * ```typescript\n * configureClock({\n * now: () => Time.realtimeSinceStartup * 1000,\n * timestamp: () => Date.now(),\n * });\n * ```\n */\nexport interface Clock {\n /** Monotonic high-resolution milliseconds (for durations, telemetry spans) */\n now(): number;\n /** Wall-clock milliseconds since epoch (for log timestamps) */\n timestamp(): number;\n}\n\nexport const defaultClock: Clock = {\n now: () => performance.now(),\n timestamp: () => Date.now(),\n};\n\nlet activeClock: Clock = defaultClock;\n\n/** Replace the default browser clock with a custom implementation. */\nexport function configureClock(clock: Clock): void {\n activeClock = clock;\n}\n\n/** Get the active clock instance. */\nexport function getClock(): Clock {\n return activeClock;\n}\n","/**\n * Muse Telemetry\n *\n * Main orchestrator for SDK telemetry. Manages spans, metrics, and exporters.\n *\n * @category Telemetry\n */\n\nimport type { TelemetryConfig, SpanAttributes, SamplingConfig } from './types';\nimport type { SpanData, MetricData, TelemetryExporterInterface } from './exporters/console';\nimport { ConsoleExporter } from './exporters/console';\nimport { OTLPExporter } from './exporters/otlp';\nimport { getClock } from '../logging/Clock';\n\n/**\n * Generate a random hex ID\n */\nfunction generateId(length: number = 16): string {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Span context for tracing\n */\ninterface SpanContext {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n}\n\n/**\n * Active span handle returned by startSpan\n */\nexport interface ActiveSpan {\n /** End the span with success status */\n end(): void;\n /** End the span with error status */\n endWithError(error: Error): void;\n /** Add attributes to the span */\n setAttributes(attrs: Partial<SpanAttributes>): void;\n /** Get the span context */\n getContext(): SpanContext;\n}\n\n/**\n * Global telemetry instance\n */\nlet globalTelemetry: OmoteTelemetry | null = null;\n\n/**\n * Configure global telemetry\n *\n * @example\n * ```typescript\n * // Development\n * configureTelemetry({\n * enabled: true,\n * serviceName: 'omote-dev',\n * exporter: 'console',\n * });\n *\n * // Production\n * configureTelemetry({\n * enabled: true,\n * serviceName: 'omote-prod',\n * exporter: 'otlp',\n * exporterConfig: {\n * endpoint: 'https://tempo.example.com',\n * },\n * sampling: { ratio: 0.1 },\n * });\n * ```\n */\nexport function configureTelemetry(config: TelemetryConfig): OmoteTelemetry {\n if (globalTelemetry) {\n globalTelemetry.shutdown();\n }\n globalTelemetry = new OmoteTelemetry(config);\n return globalTelemetry;\n}\n\n/**\n * Get the global telemetry instance\n */\nexport function getTelemetry(): OmoteTelemetry | null {\n return globalTelemetry;\n}\n\n/**\n * Main telemetry class\n *\n * Manages spans, metrics, and exports to configured backends.\n */\nexport class OmoteTelemetry {\n private config: Required<Omit<TelemetryConfig, 'exporterConfig'>> & { exporterConfig?: TelemetryConfig['exporterConfig'] };\n private exporter: TelemetryExporterInterface | null = null;\n private activeTraceId: string | null = null;\n private metricsIntervalId: ReturnType<typeof setInterval> | null = null;\n\n // Span stack for log-to-span correlation\n private spanStack: Array<{ traceId: string; spanId: string }> = [];\n\n // Metric accumulators\n private counters: Map<string, { value: number; attributes: Record<string, string | number | boolean> }> = new Map();\n private histograms: Map<string, { count: number; sum: number; min: number; max: number; attributes: Record<string, string | number | boolean> }> = new Map();\n\n constructor(config: TelemetryConfig) {\n this.config = {\n enabled: config.enabled ?? false,\n serviceName: config.serviceName ?? 'omote-sdk',\n serviceVersion: config.serviceVersion ?? '0.1.0',\n exporter: config.exporter ?? 'none',\n exporterConfig: config.exporterConfig,\n sampling: config.sampling ?? { ratio: 1.0, alwaysSampleErrors: true },\n metricsEnabled: config.metricsEnabled ?? true,\n metricsIntervalMs: config.metricsIntervalMs ?? 60000,\n };\n\n if (this.config.enabled) {\n this.initExporter();\n this.startMetricsCollection();\n }\n }\n\n /**\n * Initialize the configured exporter\n */\n private initExporter(): void {\n switch (this.config.exporter) {\n case 'console':\n this.exporter = new ConsoleExporter({ enabled: true });\n break;\n case 'otlp':\n if (!this.config.exporterConfig) {\n console.warn('[Telemetry] OTLP exporter requires exporterConfig with endpoint');\n return;\n }\n this.exporter = new OTLPExporter(\n this.config.exporterConfig,\n this.config.serviceName,\n this.config.serviceVersion\n );\n break;\n case 'none':\n default:\n this.exporter = null;\n }\n }\n\n /**\n * Start periodic metrics collection\n */\n private startMetricsCollection(): void {\n if (!this.config.metricsEnabled || !this.exporter) return;\n\n this.metricsIntervalId = setInterval(() => {\n this.flushMetrics();\n }, this.config.metricsIntervalMs);\n }\n\n /**\n * Check if this operation should be sampled\n */\n private shouldSample(isError: boolean = false): boolean {\n if (!this.config.enabled) return false;\n\n const sampling = this.config.sampling as SamplingConfig;\n if (isError && sampling.alwaysSampleErrors) return true;\n\n const ratio = sampling.ratio ?? 1.0;\n return Math.random() < ratio;\n }\n\n /**\n * Start a new span\n *\n * @example\n * ```typescript\n * const span = telemetry.startSpan('Wav2Vec2.infer', {\n * 'inference.input_samples': samples.length,\n * 'model.backend': 'webgpu',\n * });\n *\n * try {\n * const result = await doInference();\n * span.setAttributes({ 'inference.output_frames': result.frames });\n * span.end();\n * } catch (error) {\n * span.endWithError(error);\n * }\n * ```\n */\n startSpan(name: string, attributes: Partial<SpanAttributes> = {}, parentContext?: SpanContext): ActiveSpan {\n const traceId = parentContext?.traceId ?? this.activeTraceId ?? generateId(16);\n const spanId = generateId(8);\n const parentSpanId = parentContext?.spanId;\n const startTime = getClock().now();\n\n // Set active trace if this is a root span\n if (!parentContext && !this.activeTraceId) {\n this.activeTraceId = traceId;\n }\n\n let spanAttributes = { ...attributes };\n let ended = false;\n let sampled = this.shouldSample();\n\n const context: SpanContext = { traceId, spanId, parentSpanId };\n\n // Push to span stack for log-to-span correlation\n this.spanStack.push({ traceId, spanId });\n\n const endSpan = (status: 'ok' | 'error', error?: Error): void => {\n if (ended) return;\n ended = true;\n\n // Pop from span stack\n const idx = this.spanStack.findIndex(s => s.spanId === spanId);\n if (idx !== -1) this.spanStack.splice(idx, 1);\n\n const endTime = getClock().now();\n const durationMs = endTime - startTime;\n\n // Re-check sampling for errors\n if (status === 'error' && !sampled) {\n sampled = this.shouldSample(true);\n }\n\n if (!sampled || !this.exporter) return;\n\n const spanData: SpanData = {\n name,\n traceId,\n spanId,\n parentSpanId,\n startTime,\n endTime,\n durationMs,\n status,\n attributes: spanAttributes as SpanAttributes,\n error,\n };\n\n this.exporter.exportSpan(spanData);\n\n // Clear active trace if this was the root span\n if (!parentSpanId && this.activeTraceId === traceId) {\n this.activeTraceId = null;\n }\n };\n\n return {\n end: () => endSpan('ok'),\n endWithError: (error: Error) => endSpan('error', error),\n setAttributes: (attrs: Partial<SpanAttributes>) => {\n spanAttributes = { ...spanAttributes, ...attrs };\n },\n getContext: () => context,\n };\n }\n\n /**\n * Wrap an async function with a span\n *\n * @example\n * ```typescript\n * const result = await telemetry.withSpan('Model.load', async (span) => {\n * const model = await loadModel();\n * span.setAttributes({ 'model.size_bytes': model.size });\n * return model;\n * });\n * ```\n */\n async withSpan<T>(\n name: string,\n fn: (span: ActiveSpan) => Promise<T>,\n attributes: Partial<SpanAttributes> = {},\n parentContext?: SpanContext\n ): Promise<T> {\n const span = this.startSpan(name, attributes, parentContext);\n\n try {\n const result = await fn(span);\n span.end();\n return result;\n } catch (error) {\n span.endWithError(error as Error);\n throw error;\n }\n }\n\n /**\n * Increment a counter metric\n *\n * @example\n * ```typescript\n * telemetry.incrementCounter('omote.inference.total', 1, {\n * model: 'wav2vec2',\n * backend: 'webgpu',\n * status: 'success',\n * });\n * ```\n */\n incrementCounter(\n name: string,\n value: number = 1,\n attributes: Record<string, string | number | boolean> = {}\n ): void {\n if (!this.config.enabled || !this.config.metricsEnabled) return;\n\n const key = this.getMetricKey(name, attributes);\n const existing = this.counters.get(key);\n\n if (existing) {\n existing.value += value;\n } else {\n this.counters.set(key, { value, attributes });\n }\n }\n\n /**\n * Record a histogram value\n *\n * @example\n * ```typescript\n * telemetry.recordHistogram('omote.inference.latency', durationMs, {\n * model: 'wav2vec2',\n * backend: 'webgpu',\n * });\n * ```\n */\n recordHistogram(\n name: string,\n value: number,\n attributes: Record<string, string | number | boolean> = {}\n ): void {\n if (!this.config.enabled || !this.config.metricsEnabled) return;\n\n const key = this.getMetricKey(name, attributes);\n const existing = this.histograms.get(key);\n\n if (existing) {\n existing.count++;\n existing.sum += value;\n if (value < existing.min) existing.min = value;\n if (value > existing.max) existing.max = value;\n } else {\n this.histograms.set(key, { count: 1, sum: value, min: value, max: value, attributes });\n }\n }\n\n /**\n * Generate unique key for metric with attributes\n */\n private getMetricKey(name: string, attributes: Record<string, string | number | boolean>): string {\n // Fast path: no attributes → return name directly (avoids Object.entries + sort + join)\n const keys = Object.keys(attributes);\n if (keys.length === 0) return name;\n\n const sortedAttrs = Object.entries(attributes)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}=${v}`)\n .join(',');\n return `${name}|${sortedAttrs}`;\n }\n\n /**\n * Flush accumulated metrics to exporter\n */\n private flushMetrics(): void {\n if (!this.exporter) return;\n\n const timestamp = getClock().now();\n\n // Export counters (delta temporality — reset after export)\n for (const [key, data] of this.counters) {\n if (data.value === 0) continue;\n const name = key.split('|')[0];\n const metric: MetricData = {\n name,\n type: 'counter',\n value: data.value,\n attributes: data.attributes,\n timestamp,\n };\n this.exporter.exportMetric(metric);\n data.value = 0;\n }\n\n // Export histogram aggregates (O(1) — no array spread)\n for (const [key, data] of this.histograms) {\n const name = key.split('|')[0];\n if (data.count === 0) continue;\n\n const avg = data.sum / data.count;\n\n const metric: MetricData = {\n name,\n type: 'histogram',\n value: avg,\n attributes: {\n ...data.attributes,\n count: data.count,\n sum: data.sum,\n min: data.min,\n max: data.max,\n },\n timestamp,\n };\n this.exporter.exportMetric(metric);\n\n // Reset accumulators after export\n data.count = 0;\n data.sum = 0;\n data.min = Infinity;\n data.max = -Infinity;\n }\n }\n\n /**\n * Force flush all pending data\n */\n async flush(): Promise<void> {\n this.flushMetrics();\n await this.exporter?.flush();\n }\n\n /**\n * Shutdown telemetry\n */\n async shutdown(): Promise<void> {\n if (this.metricsIntervalId) {\n clearInterval(this.metricsIntervalId);\n this.metricsIntervalId = null;\n }\n\n await this.flush();\n await this.exporter?.shutdown();\n this.exporter = null;\n }\n\n /**\n * Check if telemetry is enabled\n */\n isEnabled(): boolean {\n return this.config.enabled;\n }\n\n /**\n * Get current configuration\n */\n getConfig(): TelemetryConfig {\n return { ...this.config };\n }\n\n /**\n * Get the active span context for log-to-span correlation.\n * Returns the most recent (top of stack) active span, or null if none.\n */\n getActiveContext(): { traceId: string; spanId: string } | null {\n return this.spanStack.length > 0 ? this.spanStack[this.spanStack.length - 1] : null;\n }\n}\n","/**\n * Omote SDK Logger\n *\n * Unified logging system with:\n * - 6 log levels (error, warn, info, debug, trace, verbose)\n * - Structured JSON output for machine parsing\n * - Pretty output for human readability\n * - Module-based child loggers\n * - Runtime configuration\n * - Browser and Node.js compatible\n */\n\nimport type {\n LogLevel,\n LogEntry,\n LoggingConfig,\n LogSink,\n ILogger,\n} from './types';\nimport { LOG_LEVEL_PRIORITY, DEFAULT_LOGGING_CONFIG } from './types';\nimport { getFormatter, createBrowserConsoleArgs } from './formatters';\nimport { getTelemetry } from '../telemetry/OmoteTelemetry';\nimport { getClock } from './Clock';\n\n/**\n * Check if running in browser\n */\nconst isBrowser = typeof window !== 'undefined';\n\n/**\n * Global logging configuration\n */\nlet globalConfig: LoggingConfig = { ...DEFAULT_LOGGING_CONFIG };\n\n/**\n * Configure global logging settings\n */\nexport function configureLogging(config: Partial<LoggingConfig>): void {\n globalConfig = { ...globalConfig, ...config };\n}\n\n/**\n * Get current logging configuration\n */\nexport function getLoggingConfig(): LoggingConfig {\n return { ...globalConfig };\n}\n\n/**\n * Reset logging configuration to defaults\n */\nexport function resetLoggingConfig(): void {\n globalConfig = { ...DEFAULT_LOGGING_CONFIG };\n}\n\n/**\n * Set log level at runtime\n */\nexport function setLogLevel(level: LogLevel): void {\n globalConfig.level = level;\n}\n\n/**\n * Enable or disable logging\n */\nexport function setLoggingEnabled(enabled: boolean): void {\n globalConfig.enabled = enabled;\n}\n\n/**\n * Default console sink with browser-optimized output\n */\nconst consoleSink: LogSink = (entry: LogEntry): void => {\n const consoleMethod = entry.level === 'error' ? 'error'\n : entry.level === 'warn' ? 'warn'\n : 'log';\n\n if (globalConfig.format === 'pretty' && isBrowser) {\n // Use styled console output in browser\n const args = createBrowserConsoleArgs(entry);\n (console as unknown as Record<string, (...args: unknown[]) => void>)[consoleMethod](...args);\n } else {\n // Use formatter for terminal or JSON output\n const formatter = getFormatter(globalConfig.format);\n const formatted = formatter(entry);\n (console as unknown as Record<string, (...args: unknown[]) => void>)[consoleMethod](formatted);\n }\n};\n\n/**\n * Get the active sink (custom or default console)\n */\nfunction getActiveSink(): LogSink {\n return globalConfig.sink || consoleSink;\n}\n\n/**\n * Check if a log level should be output given current config\n */\nfunction shouldLog(level: LogLevel): boolean {\n if (!globalConfig.enabled) return false;\n return LOG_LEVEL_PRIORITY[level] <= LOG_LEVEL_PRIORITY[globalConfig.level];\n}\n\n/**\n * Logger implementation\n */\nclass Logger implements ILogger {\n readonly module: string;\n\n constructor(module: string) {\n this.module = module;\n }\n\n private log(level: LogLevel, message: string, data?: Record<string, unknown>): void {\n if (!shouldLog(level)) return;\n\n const entry: LogEntry = {\n timestamp: getClock().timestamp(),\n level,\n module: this.module,\n message,\n data,\n };\n\n // Attach active span context for log-to-span correlation\n const ctx = getTelemetry()?.getActiveContext();\n if (ctx) {\n entry.traceId = ctx.traceId;\n entry.spanId = ctx.spanId;\n }\n\n // Extract error from data if present\n if (data?.error instanceof Error) {\n entry.error = data.error;\n // Remove from data to avoid duplication\n const { error, ...rest } = data;\n entry.data = Object.keys(rest).length > 0 ? rest : undefined;\n }\n\n getActiveSink()(entry);\n }\n\n error(message: string, data?: Record<string, unknown>): void {\n this.log('error', message, data);\n }\n\n warn(message: string, data?: Record<string, unknown>): void {\n this.log('warn', message, data);\n }\n\n info(message: string, data?: Record<string, unknown>): void {\n this.log('info', message, data);\n }\n\n debug(message: string, data?: Record<string, unknown>): void {\n this.log('debug', message, data);\n }\n\n trace(message: string, data?: Record<string, unknown>): void {\n this.log('trace', message, data);\n }\n\n verbose(message: string, data?: Record<string, unknown>): void {\n this.log('verbose', message, data);\n }\n\n child(subModule: string): ILogger {\n return new Logger(`${this.module}.${subModule}`);\n }\n}\n\n/**\n * Logger cache for reusing instances\n */\nconst loggerCache = new Map<string, Logger>();\n\n/**\n * Create a logger for a specific module\n *\n * @param module - Module name (e.g., 'LocalInference', 'ModelCache')\n * @returns Logger instance\n *\n * @example\n * ```typescript\n * const logger = createLogger('LocalInference');\n * logger.info('Model loaded', { backend: 'webgpu', loadTimeMs: 1234 });\n * ```\n */\nexport function createLogger(module: string): ILogger {\n let logger = loggerCache.get(module);\n if (!logger) {\n logger = new Logger(module);\n loggerCache.set(module, logger);\n }\n return logger;\n}\n\n/**\n * Clear logger cache (useful for testing)\n */\nexport function clearLoggerCache(): void {\n loggerCache.clear();\n}\n\n/**\n * No-op logger for when logging is completely disabled\n */\nexport const noopLogger: ILogger = {\n module: 'noop',\n error: () => {},\n warn: () => {},\n info: () => {},\n debug: () => {},\n trace: () => {},\n verbose: () => {},\n child: () => noopLogger,\n};\n\n/**\n * Get a no-op logger (for production builds that tree-shake logging)\n */\nexport function getNoopLogger(): ILogger {\n return noopLogger;\n}\n","/**\r\n * Structured error codes for the Omote SDK.\r\n *\r\n * Codes follow the pattern `OMOTE_{CATEGORY}_{SEQ}` where:\r\n * - **INF** = Inference (model loading, session, OOM)\r\n * - **AUD** = Audio (AudioContext, scheduling, decoding)\r\n * - **SPH** = Speech (VAD, ASR, microphone)\r\n * - **TTS** = Text-to-Speech (synthesis, streaming, phonemizer)\r\n * - **PIP** = Pipeline (state machine, abort)\r\n * - **CAC** = Cache (IndexedDB quota, eviction, staleness)\r\n * - **NET** = Network (fetch, timeout, WebSocket)\r\n *\r\n * Exported as a const object (not enum) for tree-shaking.\r\n */\r\nexport const ErrorCodes = {\r\n // ── Inference ──────────────────────────────────────────────────────────\r\n /** Model failed to load (file not found, corrupted, unsupported format) */\r\n INF_LOAD_FAILED: 'OMOTE_INF_001',\r\n /** ORT session poisoned after WebGPU device loss — must reload tab */\r\n INF_SESSION_POISON: 'OMOTE_INF_002',\r\n /** Inference exceeded timeout threshold */\r\n INF_TIMEOUT: 'OMOTE_INF_003',\r\n /** Out-of-memory during inference or model loading */\r\n INF_OOM: 'OMOTE_INF_004',\r\n /** WebGPU unavailable, fell back to WASM */\r\n INF_WEBGPU_FALLBACK: 'OMOTE_INF_005',\r\n /** Input tensor shape does not match model expectations */\r\n INF_SHAPE_MISMATCH: 'OMOTE_INF_006',\r\n\r\n // ── Audio ──────────────────────────────────────────────────────────────\r\n /** AudioContext creation or resume failed */\r\n AUD_CONTEXT_FAILED: 'OMOTE_AUD_001',\r\n /** Gap detected in audio scheduling (buffer underrun) */\r\n AUD_SCHEDULE_GAP: 'OMOTE_AUD_002',\r\n /** Audio buffer decoding failed */\r\n AUD_DECODE_FAILED: 'OMOTE_AUD_003',\r\n\r\n // ── Speech ─────────────────────────────────────────────────────────────\r\n /** Voice activity detection error */\r\n SPH_VAD_ERROR: 'OMOTE_SPH_001',\r\n /** Automatic speech recognition error */\r\n SPH_ASR_ERROR: 'OMOTE_SPH_002',\r\n /** Microphone access denied or unavailable */\r\n SPH_MIC_DENIED: 'OMOTE_SPH_003',\r\n\r\n // ── TTS ────────────────────────────────────────────────────────────────\r\n /** TTS synthesis failed */\r\n TTS_SYNTH_FAILED: 'OMOTE_TTS_001',\r\n /** TTS streaming error (chunk delivery failure) */\r\n TTS_STREAM_ERROR: 'OMOTE_TTS_002',\r\n /** Phonemizer (eSpeak-NG WASM) ran out of memory */\r\n TTS_PHONEMIZER_OOM: 'OMOTE_TTS_003',\r\n\r\n // ── Pipeline ───────────────────────────────────────────────────────────\r\n /** Invalid state transition in pipeline state machine */\r\n PIP_STATE_ERROR: 'OMOTE_PIP_001',\r\n /** Pipeline operation aborted (user interrupt or signal) */\r\n PIP_ABORT: 'OMOTE_PIP_002',\r\n\r\n // ── Cache ──────────────────────────────────────────────────────────────\r\n /** IndexedDB storage quota exceeded */\r\n CAC_QUOTA_EXCEEDED: 'OMOTE_CAC_001',\r\n /** Cache entry evicted (LRU or manual) */\r\n CAC_EVICTION: 'OMOTE_CAC_002',\r\n /** Cached model is stale (version mismatch) */\r\n CAC_STALE: 'OMOTE_CAC_003',\r\n\r\n // ── Network ────────────────────────────────────────────────────────────\r\n /** HTTP fetch failed (model download, CDN) */\r\n NET_FETCH_FAILED: 'OMOTE_NET_001',\r\n /** Network request timed out */\r\n NET_TIMEOUT: 'OMOTE_NET_002',\r\n /** WebSocket connection error */\r\n NET_WEBSOCKET_ERROR: 'OMOTE_NET_003',\r\n} as const;\r\n\r\n/** Union type of all error code string values. */\r\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBO,IAAM,qBAA+C;AAAA,EAC1D,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AAAA,EACP,SAAS;AACX;AAyFO,IAAM,yBAAwC;AAAA,EACnD,OAAO;AAAA,EACP,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,eAAe;AACjB;;;AC9GA,IAAM,SAAS;AAAA,EACb,OAAO;AAAA,EACP,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,SAAS;AACX;AAKA,IAAM,eAAyC;AAAA,EAC7C,OAAO,OAAO;AAAA,EACd,MAAM,OAAO;AAAA,EACb,MAAM,OAAO;AAAA,EACb,OAAO,OAAO;AAAA,EACd,OAAO,OAAO;AAAA,EACd,SAAS,OAAO;AAClB;AAKA,IAAM,cAAwC;AAAA,EAC5C,O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AAA;AAAA,EAEpB,aAAa;AAAA;AAAA,EAEb,SAAS;AAAA;AAAA,EAET,qBAAqB;AAAA;AAAA,EAErB,oBAAoB;AAAA;AAAA;AAAA,EAIpB,oBAAoB;AAAA;AAAA,EAEpB,kBAAkB;AAAA;AAAA,EAElB,mBAAmB;AAAA;AAAA;AAAA,EAInB,eAAe;AAAA;AAAA,EAEf,eAAe;AAAA;AAAA,EAEf,gBAAgB;AAAA;AAAA;AAAA,EAIhB,kBAAkB;AAAA;AAAA,EAElB,kBAAkB;AAAA;AAAA,EAElB,oBAAoB;AAAA;AAAA;AAAA,EAIpB,iBAAiB;AAAA;AAAA,EAEjB,WAAW;AAAA;AAAA;AAAA,EAIX,oBAAoB;AAAA;AAAA,EAEpB,cAAc;AAAA;AAAA,EAEd,WAAW;AAAA;AAAA;AAAA,EAIX,kBAAkB;AAAA;AAAA,EAElB,aAAa;AAAA;AAAA,EAEb,qBAAqB;AACvB;","names":["module","isBrowser","module"]}
|
package/dist/logging/index.mjs
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@omote/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.5",
|
|
4
4
|
"description": "Renderer-agnostic core SDK for Omote AI Characters",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -40,7 +40,6 @@
|
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
42
|
"cmu-pronouncing-dictionary": "^3.0.0",
|
|
43
|
-
"debug": "^4.4.3",
|
|
44
43
|
"onnxruntime-web": "^1.23.2",
|
|
45
44
|
"phonemize": "^1.1.0",
|
|
46
45
|
"simplex-noise": "^4.0.3"
|
|
@@ -1,145 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Logging types for Omote SDK
|
|
3
|
-
*
|
|
4
|
-
* 6-level logging system with structured output:
|
|
5
|
-
* - error: Critical failures that prevent operation
|
|
6
|
-
* - warn: Recoverable issues or degraded performance
|
|
7
|
-
* - info: Key lifecycle events (model loaded, inference complete)
|
|
8
|
-
* - debug: Detailed operational info for development
|
|
9
|
-
* - trace: Fine-grained tracing for performance analysis
|
|
10
|
-
* - verbose: Extremely detailed output (tensor shapes, intermediate values)
|
|
11
|
-
*/
|
|
12
|
-
type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'verbose';
|
|
13
|
-
/**
|
|
14
|
-
* Numeric priority for log levels (lower = more severe)
|
|
15
|
-
*/
|
|
16
|
-
declare const LOG_LEVEL_PRIORITY: Record<LogLevel, number>;
|
|
17
|
-
/**
|
|
18
|
-
* Structured log entry
|
|
19
|
-
*/
|
|
20
|
-
interface LogEntry {
|
|
21
|
-
/** Unix timestamp in milliseconds */
|
|
22
|
-
timestamp: number;
|
|
23
|
-
/** Log level */
|
|
24
|
-
level: LogLevel;
|
|
25
|
-
/** Module name (e.g., 'LocalInference', 'ModelCache') */
|
|
26
|
-
module: string;
|
|
27
|
-
/** Human-readable message */
|
|
28
|
-
message: string;
|
|
29
|
-
/** Optional structured data */
|
|
30
|
-
data?: Record<string, unknown>;
|
|
31
|
-
/** Optional error object */
|
|
32
|
-
error?: Error;
|
|
33
|
-
/** Trace ID from active telemetry span (log-to-span correlation) */
|
|
34
|
-
traceId?: string;
|
|
35
|
-
/** Span ID from active telemetry span (log-to-span correlation) */
|
|
36
|
-
spanId?: string;
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Log output sink interface
|
|
40
|
-
*/
|
|
41
|
-
interface LogSink {
|
|
42
|
-
(entry: LogEntry): void;
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* Log formatter interface
|
|
46
|
-
*/
|
|
47
|
-
interface LogFormatter {
|
|
48
|
-
(entry: LogEntry): string;
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Global logging configuration
|
|
52
|
-
*/
|
|
53
|
-
interface LoggingConfig {
|
|
54
|
-
/** Minimum log level to output (default: 'info') */
|
|
55
|
-
level: LogLevel;
|
|
56
|
-
/** Enable/disable logging globally (default: true) */
|
|
57
|
-
enabled: boolean;
|
|
58
|
-
/** Output format: 'json' for structured, 'pretty' for human-readable */
|
|
59
|
-
format: 'json' | 'pretty';
|
|
60
|
-
/** Custom output sink (default: console) */
|
|
61
|
-
sink?: LogSink;
|
|
62
|
-
/** Include timestamps in output (default: true) */
|
|
63
|
-
timestamps?: boolean;
|
|
64
|
-
/** Include module name in output (default: true) */
|
|
65
|
-
includeModule?: boolean;
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* Logger interface for module-specific logging
|
|
69
|
-
*/
|
|
70
|
-
interface ILogger {
|
|
71
|
-
error(message: string, data?: Record<string, unknown>): void;
|
|
72
|
-
warn(message: string, data?: Record<string, unknown>): void;
|
|
73
|
-
info(message: string, data?: Record<string, unknown>): void;
|
|
74
|
-
debug(message: string, data?: Record<string, unknown>): void;
|
|
75
|
-
trace(message: string, data?: Record<string, unknown>): void;
|
|
76
|
-
verbose(message: string, data?: Record<string, unknown>): void;
|
|
77
|
-
/** Create a child logger with a sub-module name */
|
|
78
|
-
child(subModule: string): ILogger;
|
|
79
|
-
/** Get the module name for this logger */
|
|
80
|
-
readonly module: string;
|
|
81
|
-
}
|
|
82
|
-
/**
|
|
83
|
-
* Default configuration
|
|
84
|
-
*/
|
|
85
|
-
declare const DEFAULT_LOGGING_CONFIG: LoggingConfig;
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* Omote SDK Logger
|
|
89
|
-
*
|
|
90
|
-
* Unified logging system with:
|
|
91
|
-
* - 6 log levels (error, warn, info, debug, trace, verbose)
|
|
92
|
-
* - Structured JSON output for machine parsing
|
|
93
|
-
* - Pretty output for human readability
|
|
94
|
-
* - Module-based child loggers
|
|
95
|
-
* - Runtime configuration
|
|
96
|
-
* - Browser and Node.js compatible
|
|
97
|
-
*/
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Configure global logging settings
|
|
101
|
-
*/
|
|
102
|
-
declare function configureLogging(config: Partial<LoggingConfig>): void;
|
|
103
|
-
/**
|
|
104
|
-
* Get current logging configuration
|
|
105
|
-
*/
|
|
106
|
-
declare function getLoggingConfig(): LoggingConfig;
|
|
107
|
-
/**
|
|
108
|
-
* Reset logging configuration to defaults
|
|
109
|
-
*/
|
|
110
|
-
declare function resetLoggingConfig(): void;
|
|
111
|
-
/**
|
|
112
|
-
* Set log level at runtime
|
|
113
|
-
*/
|
|
114
|
-
declare function setLogLevel(level: LogLevel): void;
|
|
115
|
-
/**
|
|
116
|
-
* Enable or disable logging
|
|
117
|
-
*/
|
|
118
|
-
declare function setLoggingEnabled(enabled: boolean): void;
|
|
119
|
-
/**
|
|
120
|
-
* Create a logger for a specific module
|
|
121
|
-
*
|
|
122
|
-
* @param module - Module name (e.g., 'LocalInference', 'ModelCache')
|
|
123
|
-
* @returns Logger instance
|
|
124
|
-
*
|
|
125
|
-
* @example
|
|
126
|
-
* ```typescript
|
|
127
|
-
* const logger = createLogger('LocalInference');
|
|
128
|
-
* logger.info('Model loaded', { backend: 'webgpu', loadTimeMs: 1234 });
|
|
129
|
-
* ```
|
|
130
|
-
*/
|
|
131
|
-
declare function createLogger(module: string): ILogger;
|
|
132
|
-
/**
|
|
133
|
-
* Clear logger cache (useful for testing)
|
|
134
|
-
*/
|
|
135
|
-
declare function clearLoggerCache(): void;
|
|
136
|
-
/**
|
|
137
|
-
* No-op logger for when logging is completely disabled
|
|
138
|
-
*/
|
|
139
|
-
declare const noopLogger: ILogger;
|
|
140
|
-
/**
|
|
141
|
-
* Get a no-op logger (for production builds that tree-shake logging)
|
|
142
|
-
*/
|
|
143
|
-
declare function getNoopLogger(): ILogger;
|
|
144
|
-
|
|
145
|
-
export { DEFAULT_LOGGING_CONFIG as D, type ILogger as I, type LogFormatter as L, LOG_LEVEL_PRIORITY as a, type LogEntry as b, type LogLevel as c, type LogSink as d, type LoggingConfig as e, clearLoggerCache as f, configureLogging as g, createLogger as h, getLoggingConfig as i, getNoopLogger as j, setLoggingEnabled as k, noopLogger as n, resetLoggingConfig as r, setLogLevel as s };
|
|
@@ -1,145 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Logging types for Omote SDK
|
|
3
|
-
*
|
|
4
|
-
* 6-level logging system with structured output:
|
|
5
|
-
* - error: Critical failures that prevent operation
|
|
6
|
-
* - warn: Recoverable issues or degraded performance
|
|
7
|
-
* - info: Key lifecycle events (model loaded, inference complete)
|
|
8
|
-
* - debug: Detailed operational info for development
|
|
9
|
-
* - trace: Fine-grained tracing for performance analysis
|
|
10
|
-
* - verbose: Extremely detailed output (tensor shapes, intermediate values)
|
|
11
|
-
*/
|
|
12
|
-
type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'verbose';
|
|
13
|
-
/**
|
|
14
|
-
* Numeric priority for log levels (lower = more severe)
|
|
15
|
-
*/
|
|
16
|
-
declare const LOG_LEVEL_PRIORITY: Record<LogLevel, number>;
|
|
17
|
-
/**
|
|
18
|
-
* Structured log entry
|
|
19
|
-
*/
|
|
20
|
-
interface LogEntry {
|
|
21
|
-
/** Unix timestamp in milliseconds */
|
|
22
|
-
timestamp: number;
|
|
23
|
-
/** Log level */
|
|
24
|
-
level: LogLevel;
|
|
25
|
-
/** Module name (e.g., 'LocalInference', 'ModelCache') */
|
|
26
|
-
module: string;
|
|
27
|
-
/** Human-readable message */
|
|
28
|
-
message: string;
|
|
29
|
-
/** Optional structured data */
|
|
30
|
-
data?: Record<string, unknown>;
|
|
31
|
-
/** Optional error object */
|
|
32
|
-
error?: Error;
|
|
33
|
-
/** Trace ID from active telemetry span (log-to-span correlation) */
|
|
34
|
-
traceId?: string;
|
|
35
|
-
/** Span ID from active telemetry span (log-to-span correlation) */
|
|
36
|
-
spanId?: string;
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Log output sink interface
|
|
40
|
-
*/
|
|
41
|
-
interface LogSink {
|
|
42
|
-
(entry: LogEntry): void;
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* Log formatter interface
|
|
46
|
-
*/
|
|
47
|
-
interface LogFormatter {
|
|
48
|
-
(entry: LogEntry): string;
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Global logging configuration
|
|
52
|
-
*/
|
|
53
|
-
interface LoggingConfig {
|
|
54
|
-
/** Minimum log level to output (default: 'info') */
|
|
55
|
-
level: LogLevel;
|
|
56
|
-
/** Enable/disable logging globally (default: true) */
|
|
57
|
-
enabled: boolean;
|
|
58
|
-
/** Output format: 'json' for structured, 'pretty' for human-readable */
|
|
59
|
-
format: 'json' | 'pretty';
|
|
60
|
-
/** Custom output sink (default: console) */
|
|
61
|
-
sink?: LogSink;
|
|
62
|
-
/** Include timestamps in output (default: true) */
|
|
63
|
-
timestamps?: boolean;
|
|
64
|
-
/** Include module name in output (default: true) */
|
|
65
|
-
includeModule?: boolean;
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* Logger interface for module-specific logging
|
|
69
|
-
*/
|
|
70
|
-
interface ILogger {
|
|
71
|
-
error(message: string, data?: Record<string, unknown>): void;
|
|
72
|
-
warn(message: string, data?: Record<string, unknown>): void;
|
|
73
|
-
info(message: string, data?: Record<string, unknown>): void;
|
|
74
|
-
debug(message: string, data?: Record<string, unknown>): void;
|
|
75
|
-
trace(message: string, data?: Record<string, unknown>): void;
|
|
76
|
-
verbose(message: string, data?: Record<string, unknown>): void;
|
|
77
|
-
/** Create a child logger with a sub-module name */
|
|
78
|
-
child(subModule: string): ILogger;
|
|
79
|
-
/** Get the module name for this logger */
|
|
80
|
-
readonly module: string;
|
|
81
|
-
}
|
|
82
|
-
/**
|
|
83
|
-
* Default configuration
|
|
84
|
-
*/
|
|
85
|
-
declare const DEFAULT_LOGGING_CONFIG: LoggingConfig;
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* Omote SDK Logger
|
|
89
|
-
*
|
|
90
|
-
* Unified logging system with:
|
|
91
|
-
* - 6 log levels (error, warn, info, debug, trace, verbose)
|
|
92
|
-
* - Structured JSON output for machine parsing
|
|
93
|
-
* - Pretty output for human readability
|
|
94
|
-
* - Module-based child loggers
|
|
95
|
-
* - Runtime configuration
|
|
96
|
-
* - Browser and Node.js compatible
|
|
97
|
-
*/
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Configure global logging settings
|
|
101
|
-
*/
|
|
102
|
-
declare function configureLogging(config: Partial<LoggingConfig>): void;
|
|
103
|
-
/**
|
|
104
|
-
* Get current logging configuration
|
|
105
|
-
*/
|
|
106
|
-
declare function getLoggingConfig(): LoggingConfig;
|
|
107
|
-
/**
|
|
108
|
-
* Reset logging configuration to defaults
|
|
109
|
-
*/
|
|
110
|
-
declare function resetLoggingConfig(): void;
|
|
111
|
-
/**
|
|
112
|
-
* Set log level at runtime
|
|
113
|
-
*/
|
|
114
|
-
declare function setLogLevel(level: LogLevel): void;
|
|
115
|
-
/**
|
|
116
|
-
* Enable or disable logging
|
|
117
|
-
*/
|
|
118
|
-
declare function setLoggingEnabled(enabled: boolean): void;
|
|
119
|
-
/**
|
|
120
|
-
* Create a logger for a specific module
|
|
121
|
-
*
|
|
122
|
-
* @param module - Module name (e.g., 'LocalInference', 'ModelCache')
|
|
123
|
-
* @returns Logger instance
|
|
124
|
-
*
|
|
125
|
-
* @example
|
|
126
|
-
* ```typescript
|
|
127
|
-
* const logger = createLogger('LocalInference');
|
|
128
|
-
* logger.info('Model loaded', { backend: 'webgpu', loadTimeMs: 1234 });
|
|
129
|
-
* ```
|
|
130
|
-
*/
|
|
131
|
-
declare function createLogger(module: string): ILogger;
|
|
132
|
-
/**
|
|
133
|
-
* Clear logger cache (useful for testing)
|
|
134
|
-
*/
|
|
135
|
-
declare function clearLoggerCache(): void;
|
|
136
|
-
/**
|
|
137
|
-
* No-op logger for when logging is completely disabled
|
|
138
|
-
*/
|
|
139
|
-
declare const noopLogger: ILogger;
|
|
140
|
-
/**
|
|
141
|
-
* Get a no-op logger (for production builds that tree-shake logging)
|
|
142
|
-
*/
|
|
143
|
-
declare function getNoopLogger(): ILogger;
|
|
144
|
-
|
|
145
|
-
export { DEFAULT_LOGGING_CONFIG as D, type ILogger as I, type LogFormatter as L, LOG_LEVEL_PRIORITY as a, type LogEntry as b, type LogLevel as c, type LogSink as d, type LoggingConfig as e, clearLoggerCache as f, configureLogging as g, createLogger as h, getLoggingConfig as i, getNoopLogger as j, setLoggingEnabled as k, noopLogger as n, resetLoggingConfig as r, setLogLevel as s };
|