/**
 * Test Exporter for Observability
 *
 * A full-featured exporter primarily designed for testing purposes that provides:
 * - In-memory event collection for ALL signals (Traces, Metrics, Logs, Scores, Feedback)
 * - File output support
 * - Span lifecycle tracking and validation
 * - Query methods for filtering spans by type, trace ID, span ID, etc.
 * - Query methods for filtering logs, metrics, scores, and feedback
 * - Statistics and analytics on all collected signals
 * - Internal metrics collection with summary on flush()
 */
import type { TracingEvent, TracingEventType, AnyExportedSpan, ExportedSpan, SpanType, LogEvent, MetricEvent, ScoreEvent, FeedbackEvent, ExportedLog, ExportedMetric, ExportedScore, ExportedFeedback, LogLevel } from '@mastra/core/observability';
import { BaseExporter } from './base.js';
import type { BaseExporterConfig } from './base.js';
/**
 * Span state tracking for lifecycle validation
 */
interface SpanState {
    /** Whether SPAN_STARTED was received */
    hasStart: boolean;
    /** Whether SPAN_ENDED was received */
    hasEnd: boolean;
    /** Whether SPAN_UPDATED was received */
    hasUpdate: boolean;
    /** All events for this span in order */
    events: TracingEvent[];
    /** Whether this is an event span (zero duration) */
    isEventSpan?: boolean;
}
/**
 * Statistics about all collected signals
 */
export interface TestExporterStats {
    /** Total number of tracing events collected */
    totalTracingEvents: number;
    /** Number of unique spans */
    totalSpans: number;
    /** Number of unique traces */
    totalTraces: number;
    /** Number of completed spans */
    completedSpans: number;
    /** Number of incomplete spans (started but not ended) */
    incompleteSpans: number;
    /** Breakdown by tracing event type */
    byEventType: {
        started: number;
        updated: number;
        ended: number;
    };
    /** Breakdown by span type */
    bySpanType: Record<string, number>;
    /** Total number of log events collected */
    totalLogs: number;
    /** Breakdown of logs by level */
    logsByLevel: Record<string, number>;
    /** Total number of metric events collected */
    totalMetrics: number;
    /** Breakdown of metrics by name */
    metricsByName: Record<string, number>;
    /** Total number of score events collected */
    totalScores: number;
    /** Breakdown of scores by scorer name */
    scoresByScorer: Record<string, number>;
    /** Total number of feedback events collected */
    totalFeedback: number;
    /** Breakdown of feedback by type */
    feedbackByType: Record<string, number>;
    /** @deprecated Use totalTracingEvents instead */
    totalEvents: number;
}
/**
 * Internal metrics collected by the TestExporter while running.
 * Dumped as a summary on flush().
 */
export interface TestExporterInternalMetrics {
    /** Timestamp when the exporter was created */
    startedAt: Date;
    /** Timestamp of the last event received */
    lastEventAt: Date | null;
    /** Total events received across all signal types */
    totalEventsReceived: number;
    /** Breakdown by signal type */
    bySignal: {
        tracing: number;
        log: number;
        metric: number;
        score: number;
        feedback: number;
    };
    /** Number of flush() calls */
    flushCount: number;
    /** Total bytes of JSON output produced (estimated from toJSON) */
    estimatedJsonBytes: number;
}
/**
 * Span node in a tree structure with nested children
 */
export interface SpanTreeNode {
    /** The span data */
    span: AnyExportedSpan;
    /** Child spans nested under this span */
    children: SpanTreeNode[];
}
/**
 * Normalized span data for snapshot testing.
 * Dynamic fields (IDs, timestamps) are replaced with stable values.
 */
export interface NormalizedSpan {
    /** Stable ID like <span-1>, <span-2> */
    id: string;
    /** Normalized trace ID like <trace-1>, <trace-2> */
    traceId: string;
    /** Normalized parent ID, or undefined for root */
    parentId?: string;
    /** Span name */
    name: string;
    /** Span type */
    type: string;
    /** Entity type */
    entityType?: string;
    /** Entity ID */
    entityId?: string;
    /** Whether the span completed (had an endTime) */
    completed: boolean;
    /** Span attributes */
    attributes?: Record<string, unknown>;
    /** Span metadata */
    metadata?: Record<string, unknown>;
    /** Input data */
    input?: unknown;
    /** Output data */
    output?: unknown;
    /** Error info if span failed */
    errorInfo?: unknown;
    /** Is an event span */
    isEvent: boolean;
    /** Is root span */
    isRootSpan: boolean;
    /** Tags */
    tags?: string[];
}
/**
 * Normalized tree node for snapshot testing
 */
export interface NormalizedTreeNode {
    /** Normalized span data */
    span: NormalizedSpan;
    /** Child nodes (omitted if empty) */
    children?: NormalizedTreeNode[];
}
/**
 * Incomplete span information for debugging
 */
export interface IncompleteSpanInfo {
    spanId: string;
    span: AnyExportedSpan | undefined;
    state: {
        hasStart: boolean;
        hasUpdate: boolean;
        hasEnd: boolean;
    };
}
/**
 * Configuration for TestExporter
 */
export interface TestExporterConfig extends BaseExporterConfig {
    /**
     * Whether to validate span lifecycles in real-time.
     * When true, will log warnings for lifecycle violations.
     * @default true
     */
    validateLifecycle?: boolean;
    /**
     * Whether to store verbose logs for debugging.
     * @default true
     */
    storeLogs?: boolean;
    /**
     * Indentation for JSON output (number of spaces, or undefined for compact).
     * @default 2
     */
    jsonIndent?: number;
    /**
     * Whether to log a summary of internal metrics on flush().
     * @default true
     */
    logMetricsOnFlush?: boolean;
}
/**
 * Test Exporter for observability testing and debugging.
 *
 * Provides comprehensive in-memory event collection, querying, and JSON output
 * capabilities designed primarily for testing purposes but useful for debugging as well.
 *
 * @example
 * ```typescript
 * const exporter = new TestExporter();
 *
 * // Use with Mastra
 * const mastra = new Mastra({
 *   observability: {
 *     configs: {
 *       test: {
 *         serviceName: 'test',
 *         exporters: [exporter],
 *       },
 *     },
 *   },
 * });
 *
 * // Run some operations...
 *
 * // Query spans
 * const agentSpans = exporter.getSpansByType('agent_run');
 * const traceSpans = exporter.getByTraceId('abc123');
 *
 * // Get statistics
 * const stats = exporter.getStatistics();
 *
 * // Export to JSON
 * await exporter.writeToFile('./traces.json');
 * const jsonString = exporter.toJSON();
 * ```
 */
export declare class TestExporter extends BaseExporter {
    #private;
    name: string;
    constructor(config?: TestExporterConfig);
    /**
     * Process incoming tracing events with lifecycle tracking
     */
    protected _exportTracingEvent(event: TracingEvent): Promise<void>;
    /**
     * Process incoming log events
     */
    onLogEvent(event: LogEvent): Promise<void>;
    /**
     * Process incoming metric events
     */
    onMetricEvent(event: MetricEvent): Promise<void>;
    /**
     * Process incoming score events
     */
    onScoreEvent(event: ScoreEvent): Promise<void>;
    /**
     * Process incoming feedback events
     */
    onFeedbackEvent(event: FeedbackEvent): Promise<void>;
    /**
     * Get all collected tracing events
     */
    get events(): TracingEvent[];
    /**
     * Get completed spans by SpanType (e.g., 'agent_run', 'tool_call')
     *
     * @param type - The SpanType to filter by
     * @returns Array of completed exported spans of the specified type
     */
    getSpansByType<T extends SpanType>(type: T): ExportedSpan<T>[];
    /**
     * Get events by TracingEventType (SPAN_STARTED, SPAN_UPDATED, SPAN_ENDED)
     *
     * @param type - The TracingEventType to filter by
     * @returns Array of events of the specified type
     */
    getByEventType(type: TracingEventType): TracingEvent[];
    /**
     * Get all events and spans for a specific trace
     *
     * @param traceId - The trace ID to filter by
     * @returns Object containing tracing events, final spans, plus logs/scores/feedback for the trace
     */
    getByTraceId(traceId: string): {
        events: TracingEvent[];
        spans: AnyExportedSpan[];
        logs: ExportedLog[];
        scores: ExportedScore[];
        feedback: ExportedFeedback[];
    };
    /**
     * Get all events for a specific span
     *
     * @param spanId - The span ID to filter by
     * @returns Object containing events and final span state
     */
    getBySpanId(spanId: string): {
        events: TracingEvent[];
        span: AnyExportedSpan | undefined;
        state: SpanState | undefined;
    };
    /**
     * Get all unique spans (returns the final state of each span)
     */
    getAllSpans(): AnyExportedSpan[];
    /**
     * Get only completed spans (those that have received SPAN_ENDED)
     */
    getCompletedSpans(): AnyExportedSpan[];
    /**
     * Get root spans only (spans with no parent)
     */
    getRootSpans(): AnyExportedSpan[];
    /**
     * Get incomplete spans (started but not yet ended)
     */
    getIncompleteSpans(): IncompleteSpanInfo[];
    /**
     * Get unique trace IDs from all collected signals
     */
    getTraceIds(): string[];
    /**
     * Get all collected log events
     */
    getLogEvents(): LogEvent[];
    /**
     * Get all collected logs (unwrapped from events)
     */
    getAllLogs(): ExportedLog[];
    /**
     * Get logs filtered by level
     */
    getLogsByLevel(level: LogLevel): ExportedLog[];
    /**
     * Get logs for a specific trace
     */
    getLogsByTraceId(traceId: string): ExportedLog[];
    /**
     * Get all collected metric events
     */
    getMetricEvents(): MetricEvent[];
    /**
     * Get all collected metrics (unwrapped from events)
     */
    getAllMetrics(): ExportedMetric[];
    /**
     * Get metrics filtered by name
     */
    getMetricsByName(name: string): ExportedMetric[];
    /**
     * @deprecated MetricType is no longer stored. Use getMetricsByName() instead.
     */
    getMetricsByType(_metricType: string): ExportedMetric[];
    /**
     * Get all collected score events
     */
    getScoreEvents(): ScoreEvent[];
    /**
     * Get all collected scores (unwrapped from events)
     */
    getAllScores(): ExportedScore[];
    /**
     * Get scores filtered by scorer id
     */
    getScoresByScorer(scorerId: string): ExportedScore[];
    /**
     * Get scores for a specific trace
     */
    getScoresByTraceId(traceId: string): ExportedScore[];
    /**
     * Get all collected feedback events
     */
    getFeedbackEvents(): FeedbackEvent[];
    /**
     * Get all collected feedback (unwrapped from events)
     */
    getAllFeedback(): ExportedFeedback[];
    /**
     * Get feedback filtered by type
     */
    getFeedbackByType(feedbackType: string): ExportedFeedback[];
    /**
     * Get feedback for a specific trace
     */
    getFeedbackByTraceId(traceId: string): ExportedFeedback[];
    /**
     * Get comprehensive statistics about all collected signals
     */
    getStatistics(): TestExporterStats;
    /**
     * Serialize all collected data to JSON string
     *
     * @param options - Serialization options
     * @returns JSON string of all collected data
     */
    toJSON(options?: {
        indent?: number;
        includeEvents?: boolean;
        includeStats?: boolean;
    }): string;
    /**
     * Build a tree structure from spans, nesting children under their parents
     *
     * @returns Array of root span tree nodes (spans with no parent)
     */
    buildSpanTree(): SpanTreeNode[];
    /**
     * Serialize spans as a tree structure to JSON string
     *
     * @param options - Serialization options
     * @returns JSON string with spans nested in tree format
     */
    toTreeJSON(options?: {
        indent?: number;
        includeStats?: boolean;
    }): string;
    /**
     * Build a normalized tree structure suitable for snapshot testing.
     *
     * Normalizations applied:
     * - Span IDs replaced with stable placeholders (<span-1>, <span-2>, etc.)
     * - Trace IDs replaced with stable placeholders (<trace-1>, <trace-2>, etc.)
     * - parentSpanId replaced with normalized parent ID
     * - Timestamps replaced with durationMs (or null if not ended)
     * - Empty children arrays are omitted
     *
     * @returns Array of normalized root tree nodes
     */
    buildNormalizedTree(): NormalizedTreeNode[];
    /**
     * Generate an ASCII tree structure graph for debugging.
     * Shows span type and name in a hierarchical format.
     *
     * @param nodes - Normalized tree nodes (defaults to current normalized tree)
     * @returns Array of strings representing the tree structure
     *
     * @example
     * ```
     * agent_run: "agent run: 'test-agent'"
     * ├── processor_run: "input processor: validator"
     * │   └── agent_run: "agent run: 'validator-agent'"
     * └── model_generation: "llm: 'mock-model-id'"
     * ```
     */
    generateStructureGraph(nodes?: NormalizedTreeNode[]): string[];
    /**
     * Serialize spans as a normalized tree structure for snapshot testing.
     * Includes a __structure__ field with an ASCII tree graph for readability.
     *
     * @param options - Serialization options
     * @returns JSON string with normalized spans in tree format
     */
    toNormalizedTreeJSON(options?: {
        indent?: number;
        includeStructure?: boolean;
    }): string;
    /**
     * Write collected data to a JSON file
     *
     * @param filePath - Path to write the JSON file
     * @param options - Serialization options
     */
    writeToFile(filePath: string, options?: {
        indent?: number;
        includeEvents?: boolean;
        includeStats?: boolean;
        format?: 'flat' | 'tree' | 'normalized';
    }): Promise<void>;
    /**
     * Assert that the current normalized tree matches a snapshot file.
     * Throws an error with a diff if they don't match.
     *
     * The snapshot format includes:
     * - `__structure__`: ASCII tree graph (compared first for quick validation)
     * - `spans`: The normalized span tree (detailed comparison)
     *
     * Supports special markers in the snapshot:
     * - `{"__or__": ["value1", "value2"]}` - matches if actual equals any listed value
     * - `{"__any__": "string"}` - matches any string value
     * - `{"__any__": "number"}` - matches any number value
     * - `{"__any__": "boolean"}` - matches any boolean value
     * - `{"__any__": "object"}` - matches any object value
     * - `{"__any__": "array"}` - matches any array value
     * - `{"__any__": true}` - matches any non-null/undefined value
     *
     * Environment variables:
     * Use `{ updateSnapshot: true }` option to update the snapshot instead of comparing
     *
     * @param snapshotName - Name of the snapshot file (resolved relative to __snapshots__ directory)
     * @param options - Options for snapshot comparison
     * @param options.updateSnapshot - If true, update the snapshot file instead of comparing
     * @throws Error if the snapshot doesn't match (and updateSnapshot is false)
     */
    assertMatchesSnapshot(snapshotName: string, options?: {
        updateSnapshot?: boolean;
    }): Promise<void>;
    /**
     * Get all stored debug logs (internal exporter logging, not signal logs)
     */
    getLogs(): string[];
    /**
     * Dump debug logs to console for debugging (uses console.error for visibility in test output)
     */
    dumpLogs(): void;
    /**
     * Validate final state - useful for test assertions
     *
     * @returns Object with validation results
     */
    validateFinalState(): {
        valid: boolean;
        singleTraceId: boolean;
        allSpansComplete: boolean;
        traceIds: string[];
        incompleteSpans: IncompleteSpanInfo[];
    };
    /**
     * Clear all collected events and state across all signals
     */
    clearEvents(): void;
    /**
     * Alias for clearEvents (compatibility with TestExporter)
     */
    reset(): void;
    /**
     * Get internal metrics about the exporter's own activity.
     */
    getInternalMetrics(): TestExporterInternalMetrics;
    /**
     * Flush buffered data and log internal metrics summary.
     */
    flush(): Promise<void>;
    shutdown(): Promise<void>;
}
/**
 * @deprecated Use `TestExporter` instead. This alias will be removed in a future version.
 */
export declare const JsonExporter: typeof TestExporter;
/**
 * @deprecated Use `TestExporter` instead. This is a type alias for backward compatibility.
 */
export type JsonExporter = TestExporter;
/**
 * @deprecated Use `TestExporterConfig` instead.
 */
export type JsonExporterConfig = TestExporterConfig;
/**
 * @deprecated Use `TestExporterStats` instead.
 */
export type JsonExporterStats = TestExporterStats;
/**
 * @deprecated Use `TestExporterInternalMetrics` instead.
 */
export type JsonExporterInternalMetrics = TestExporterInternalMetrics;
export {};
//# sourceMappingURL=test.d.ts.map