@pixora-dev-ai/dev-sentinel
Version:
🛡️ Enterprise-grade observability SDK for React applications. Real-time diagnostics with 14+ specialized packs: Network Intelligence, Security Guards, Privacy Protection, Code Quality Analysis, Device Monitoring, and more.
1,418 lines (1,342 loc) • 47.1 kB
TypeScript
import { ZodTypeAny, ZodSchema } from 'zod';
import React from 'react';
import { FallbackProps } from 'react-error-boundary';
interface DevSentinelTransport {
send(logs: DevSentinelLogEntry[]): Promise<void>;
flush?(): Promise<void>;
}
declare const createNoopTransport: () => DevSentinelTransport;
type PostTransportOptions = {
batchSize?: number;
debounceMs?: number;
/**
* Optional redactor to scrub or trim payloads before sending to the remote endpoint.
*/
redactor?: (entry: DevSentinelLogEntry) => DevSentinelLogEntry;
/**
* Soft budget for JSON-encoded log payloads; entries exceeding the budget are truncated.
*/
maxPayloadBytes?: number;
} | number;
declare const createPostTransport: (url: string, batchOrOptions?: PostTransportOptions, debounceMs?: number) => DevSentinelTransport;
type EndpointPattern = string | RegExp;
interface NetworkPackConfig {
wrapGlobalFetch?: boolean;
devOnly?: boolean;
defaultTimeoutMs?: number;
retryAttempts?: number;
retryDelayMs?: number;
slowThresholdMs?: number;
frequencyWindowMs?: number;
frequencyThreshold?: number;
nPlusOneWindowMs?: number;
nPlusOneThreshold?: number;
criticalEndpoints?: EndpointPattern[];
optOut?: boolean;
payloadSampleLimitBytes?: number;
}
type NetworkEventType = 'network_request' | 'endpoint_health_update' | 'api_contract_error' | 'network_waterfall_entry' | 'critical_network_issue';
type DevFetchOptions = RequestInit & {
timeoutMs?: number;
retries?: number;
retryDelayMs?: number;
sentinel?: {
parentId?: string;
label?: string;
critical?: boolean;
expectedContentType?: string;
schemaKey?: string | RegExp;
};
};
declare class NetworkIntelligencePack {
private config;
private health;
private validator;
private waterfall;
private watchdog;
private smartFetch;
constructor(config?: Partial<NetworkPackConfig>);
start(): void;
stop(): void;
getFetch(): typeof fetch;
registerSchema(pattern: string | RegExp, schema: ZodTypeAny): void;
}
declare const initNetworkIntelligencePack: (config?: Partial<NetworkPackConfig>) => NetworkIntelligencePack;
declare const registerNetworkModule: (orchestrator: {
registerModule: (namespace: string, moduleInstance: {
start: () => void;
stop: () => void;
}) => void;
}, config?: Partial<NetworkPackConfig>) => NetworkIntelligencePack;
declare const devFetch: (input: RequestInfo | URL, init?: DevFetchOptions) => Promise<Response>;
type DevSentinelLevel = 'error' | 'warning' | 'info' | 'debug';
type DevSentinelSource = 'window-error' | 'unhandled-rejection' | 'console' | 'network' | 'route' | 'react-error-boundary' | 'custom' | 'api-health' | 'schema-violation' | 'critical-path' | 'data-anomaly' | 'retry-analysis' | 'silent-failure';
interface DevSentinelLogEntry {
id: string;
level: DevSentinelLevel;
message: string;
source: DevSentinelSource;
route?: string;
timestamp: string;
stack?: string;
meta?: Record<string, unknown>;
}
interface DevSentinelInitOptions {
enableConsoleCapture?: boolean;
enableWindowErrorCapture?: boolean;
enableUnhandledRejectionCapture?: boolean;
enableFetchCapture?: boolean;
enableNetworkPack?: boolean;
routeResolver?: () => string;
onNewLog?: (entry: DevSentinelLogEntry) => void;
transport?: DevSentinelTransport;
logRouteChanges?: boolean;
networkPackConfig?: Partial<NetworkPackConfig>;
}
type DevSentinelListener = (logs: DevSentinelLogEntry[]) => void;
/**
* Dev Sentinel Advanced Configuration
*
* Unified configuration system for all observability features.
* Each feature can be enabled/disabled via environment variables or runtime config.
*/
/**
* Feature-specific configuration options
*/
interface EndpointHealthConfig {
enabled: boolean;
/** Sample rate for successful requests (0-1). Errors always sampled at 100% */
sampleRate?: number;
/** Maximum number of endpoints to track */
maxEndpoints?: number;
/** Maximum requests per endpoint to store */
maxRequestsPerEndpoint?: number;
/** Health check thresholds */
thresholds?: {
errorRateWarning?: number;
errorRateCritical?: number;
latencyWarning?: number;
latencyCritical?: number;
};
}
interface SchemaValidationConfig {
enabled: boolean;
/** Endpoint pattern → Zod schema mapping */
schemas?: Map<string | RegExp, ZodSchema>;
/** Log successful validations (verbose mode) */
logSuccess?: boolean;
/** Auto-detect common issues */
autoDetectIssues?: boolean;
}
interface CriticalPathStep {
id: string;
description: string;
/** Endpoint URL or pattern */
endpoint?: string | RegExp;
/** Route path */
route?: string;
/** Maximum allowed time in milliseconds */
maxMs?: number;
/** Type of critical step */
type?: 'api' | 'route' | 'render';
}
interface CriticalPathConfig {
enabled: boolean;
/** Critical path definitions */
paths?: CriticalPathStep[];
/** Alert immediately on failure */
alertOnFailure?: boolean;
}
interface DataAnomalyDetector {
name: string;
detect: (value: unknown, context: {
field: string;
componentName: string;
}) => {
isAnomaly: boolean;
message?: string;
};
}
interface DataAnomalyConfig {
enabled: boolean;
/** Custom anomaly detectors */
detectors?: DataAnomalyDetector[];
/** Built-in detector toggles */
detectNaN?: boolean;
detectNull?: boolean;
detectEmpty?: boolean;
detectTypeMismatch?: boolean;
}
interface RetryAnalysisConfig {
enabled: boolean;
/** Number of failures within time window to trigger alert */
retryLoopThreshold?: number;
/** Time window in ms (default: 30000 = 30s) */
retryLoopWindow?: number;
/** Track silent failures (caught errors with no logging) */
detectSilentFailures?: boolean;
}
/**
* Master configuration for all Dev Sentinel features
*/
interface DevSentinelFeatureConfig {
endpointHealth?: EndpointHealthConfig;
schemaValidation?: SchemaValidationConfig;
criticalPath?: CriticalPathConfig;
dataAnomaly?: DataAnomalyConfig;
retryAnalysis?: RetryAnalysisConfig;
}
/**
* Get current feature configuration
*/
declare const getFeatureConfig: () => DevSentinelFeatureConfig;
/**
* Update feature configuration at runtime
*/
declare const updateFeatureConfig: (config: Partial<DevSentinelFeatureConfig>) => void;
declare const initDevSentinel: (options?: DevSentinelInitOptions & {
features?: Partial<DevSentinelFeatureConfig>;
}) => void;
type LogInput = Omit<DevSentinelLogEntry, 'id' | 'timestamp'> & {
timestamp?: string;
};
declare const logDevSentinel: (input: LogInput) => void;
declare const logRouteChange: (route: string) => void;
declare const getDevSentinelLogs: () => DevSentinelLogEntry[];
declare const clearDevSentinelLogs: () => void;
declare const subscribeToLogs: (listener: DevSentinelListener) => () => void;
declare const registerRouteResolver: (resolver?: () => string) => void;
declare const flushTransport: (drainAll?: boolean) => Promise<void>;
declare const downloadDevSentinelLogs: (logs: DevSentinelLogEntry[]) => void;
interface DevSentinelContextValue {
logs: DevSentinelLogEntry[];
log: typeof logDevSentinel;
clearLogs: typeof clearDevSentinelLogs;
downloadLogs: () => void;
}
declare const DevSentinelProvider: React.FC<{
children: React.ReactNode;
options?: DevSentinelInitOptions;
}>;
interface DevSentinelErrorBoundaryProps {
children: React.ReactNode;
fallback?: React.ReactElement | ((props: FallbackProps) => React.ReactElement);
}
declare const DevSentinelErrorBoundary: React.FC<DevSentinelErrorBoundaryProps>;
declare const DevSentinelPanel: React.FC;
declare const useDevSentinel: () => DevSentinelContextValue;
/**
* Dev Sentinel Orchestrator
*
* Central coordinator for all observability features.
* Manages initialization, teardown, and cross-feature integration.
*/
/**
* Initialize Dev Sentinel Orchestrator
*/
declare const initOrchestrator: (config?: Partial<DevSentinelFeatureConfig>) => void;
/**
* Teardown orchestrator and all features
*/
declare const teardownOrchestrator: () => void;
/**
* Check if orchestrator is initialized
*/
declare const isOrchestratorInitialized: () => boolean;
/**
* Update configuration at runtime
*/
declare const updateOrchestratorConfig: (config: Partial<DevSentinelFeatureConfig>) => void;
/**
* Get current configuration
*/
declare const getOrchestratorConfig: () => DevSentinelFeatureConfig;
/**
* Endpoint Health Types
*
* Type definitions for network monitoring and endpoint health tracking.
*/
interface EndpointRequestRecord {
url: string;
method: string;
timestamp: number;
duration: number;
status: number;
ok: boolean;
errorType?: 'timeout' | 'network' | 'server' | 'client';
responseSize?: number;
}
interface EndpointMetrics {
endpoint: string;
totalCalls: number;
errorCount: number;
successCount: number;
errorRate: number;
avgLatency: number;
minLatency: number;
maxLatency: number;
totalSize: number;
avgSize: number;
requests: EndpointRequestRecord[];
lastFailure?: EndpointRequestRecord;
lastSuccess?: EndpointRequestRecord;
}
type EndpointHealthStatus = 'healthy' | 'warning' | 'critical';
interface EndpointHealth {
endpoint: string;
status: EndpointHealthStatus;
metrics: EndpointMetrics;
message?: string;
}
interface HealthMapData {
endpoints: Map<string, EndpointMetrics>;
healthStatuses: Map<string, EndpointHealth>;
lastUpdated: number;
}
/**
* Export health map data for UI
*/
declare const getEndpointHealthMap: () => HealthMapData;
/**
* Export endpoint metrics
*/
declare const getEndpointMetrics: (endpoint: string) => EndpointMetrics | undefined;
/**
* Export health summary
*/
declare const getHealthSummary: () => {
total: number;
healthy: number;
warning: number;
critical: number;
};
/**
* Clear all health data
*/
declare const clearHealthData: () => void;
/**
* Schema Registry
*
* Manages endpoint → Zod schema mappings for runtime validation.
* Supports both exact string matches and RegExp patterns.
*/
/**
* Public API: Register endpoint schema
*/
declare const registerEndpointSchema: (endpoint: string | RegExp, schema: ZodSchema, description?: string) => void;
/**
* Schema Validator
*
* Runtime validation of API responses against registered Zod schemas.
* Computes diffs and logs violations.
*/
interface ValidationResult {
success: boolean;
url: string;
schema?: ZodSchema;
errors?: Array<{
path: (string | number)[];
message: string;
code: string;
}>;
receivedData?: unknown;
}
/**
* Validate response against schema
*/
declare const validateResponse: (url: string, data: unknown) => ValidationResult;
/**
* Get validation statistics
*/
declare const getValidationStats: () => {
totalSchemas: number;
schemasRegistered: Array<{
pattern: string | RegExp;
description?: string;
}>;
};
/**
* Critical Path Monitor
*
* Tracks critical user journeys and alerts on failures or slow performance.
*/
interface CriticalPathEvent {
stepId: string;
timestamp: number;
duration?: number;
success: boolean;
url?: string;
route?: string;
errorMessage?: string;
}
interface CriticalPathStatus {
stepId: string;
description: string;
status: 'ok' | 'slow' | 'failed';
lastEvent?: CriticalPathEvent;
lastSuccess?: CriticalPathEvent;
lastFailure?: CriticalPathEvent;
totalAttempts: number;
successCount: number;
failureCount: number;
avgDuration: number;
}
/**
* Public API: Register critical path step
*/
declare const registerCriticalPathStep: (step: CriticalPathStep) => void;
/**
* Public API: Track API call for critical path
*/
declare const trackCriticalPathAPI: (stepId: string, url: string, duration: number, success: boolean, errorMessage?: string) => void;
/**
* Public API: Track route change for critical path
*/
declare const trackCriticalPathRoute: (stepId: string, route: string, duration: number, success: boolean) => void;
/**
* Get all critical path statuses
*/
declare const getCriticalPathStatuses: () => CriticalPathStatus[];
/**
* Get critical path summary
*/
declare const getCriticalPathSummary: () => {
total: number;
ok: number;
slow: number;
failed: number;
};
/**
* Data Anomaly Detectors
*
* Built-in and pluggable anomaly detectors for runtime data validation.
*/
interface AnomalyDetectionResult {
isAnomaly: boolean;
message?: string;
field: string;
value: unknown;
detectorName: string;
}
/**
* Public API: Check data for anomalies
*/
declare const sentinelCheckData: (componentName: string, data: unknown, options?: {
fields?: string[];
customDetectors?: DataAnomalyDetector[];
}) => AnomalyDetectionResult[];
/**
* Create Zustand middleware for state tracking
*/
declare const createDevSentinelMiddleware: <T extends object>(storeName: string) => (config: (set: (fn: (state: T) => T) => void, get: () => T, api: unknown) => T) => (set: (fn: (state: T) => T) => void, get: () => T, api: unknown) => T;
/**
* Retry Analyzer
*
* Tracks repeated failures, retry loops, and silent error handling.
*/
interface FailureRecord {
endpoint: string;
timestamp: number;
error: string;
stackTrace?: string;
}
interface RetryPattern {
endpoint: string;
failures: FailureRecord[];
firstFailure: number;
lastFailure: number;
count: number;
suspectedLoop: boolean;
}
/**
* Public API: Track endpoint failure
*/
declare const trackEndpointFailure: (endpoint: string, error: string, stackTrace?: string) => void;
/**
* Public API: Track silent failure
*/
declare const trackSilentFailure: (endpoint: string, error: string, stackTrace?: string) => void;
/**
* Get retry patterns
*/
declare const getRetryPatterns: () => RetryPattern[];
/**
* Get silent failures
*/
declare const getSilentFailures: () => FailureRecord[];
/**
* Get retry analysis stats
*/
declare const getRetryAnalysisStats: () => {
totalRetryPatterns: number;
totalSilentFailures: number;
suspectedLoops: number;
};
type StoredLog = {
id?: number;
type: string;
payload: unknown;
timestamp: number;
};
type RegressionIssueRecord = {
fingerprint: string;
eventType: string;
canonicalMessage?: string;
moduleName?: string;
route?: string;
firstSeenAt: number;
lastSeenAt: number;
reintroducedAt?: number;
resolvedAt?: number;
occurrencesCount: number;
severity?: string;
status?: string;
baselineFrequency?: number;
lastFrequencySample?: number;
regressionFingerprint?: {
stacks?: string[];
routes?: string[];
environments?: string[];
packSources?: string[];
};
metadata?: Record<string, unknown>;
};
type RegressionEventRecord = {
id?: number;
fingerprint: string;
eventType: string;
timestamp: number;
route?: string;
environment?: string;
severity?: string;
payloadSummary?: Record<string, unknown>;
};
type TestingEventType = 'test_non_deterministic_behavior' | 'test_flaky_interaction' | 'test_ui_render_divergence' | 'test_async_race_condition' | 'test_missing_coverage_critical_path' | 'test_hard_to_mock_component' | 'test_unreachable_state_under_tests';
type TestEnvironmentKind = 'jest' | 'vitest' | 'unknown' | 'none';
interface CriticalPathsConfig {
routes?: string[];
components?: string[];
apis?: string[];
functions?: string[];
}
interface TestingPackConfig {
enabled?: boolean;
environment?: 'auto' | 'jest' | 'vitest';
detectFlakiness?: boolean;
detectNonDeterminism?: boolean;
detectAsyncRaces?: boolean;
detectMissingCriticalCoverage?: boolean;
detectHardToMockComponents?: boolean;
detectUnreachableStates?: boolean;
criticalPaths?: CriticalPathsConfig;
flakinessThresholdMs?: number;
domSnapshotCharBudget?: number;
}
interface TestCaseInfo {
id: string;
name: string;
file?: string;
suite?: string[];
}
interface TestCaseResult {
status: 'passed' | 'failed' | 'skipped' | 'todo';
durationMs?: number;
errorMessage?: string;
retries?: number;
}
interface Observation {
testId?: string;
type: string;
data: Record<string, unknown>;
}
type CodeSmellSeverity = 'low' | 'medium' | 'high';
type CodeSmellEventType = 'code_smell_duplicate_logic' | 'code_smell_deeply_nested_component' | 'code_smell_magic_number' | 'code_smell_props_explosion' | 'code_smell_abstraction_candidate' | 'code_smell_component_antipattern' | 'code_smell_state_misuse' | 'code_smell_global_state_abuse' | 'code_smell_ai_review';
type FraudScoreThresholds = {
warning: number;
highRisk: number;
};
type SecureUiConfig = {
enabled?: boolean;
environment?: 'development' | 'staging' | 'all';
trackForms?: boolean;
trackAuthFlows?: boolean;
trackPaymentFlows?: boolean;
detectBruteForce?: boolean;
detectClickInjection?: boolean;
detectHiddenOverlayAttacks?: boolean;
detectAutofillAbuse?: boolean;
maxEventsPerSession?: number;
fraudScoreThresholds?: FraudScoreThresholds;
overlayScanIntervalMs?: number;
};
type FraudLevel = 'normal' | 'warning' | 'high_risk';
type SecureUiEventType = 'secure_ui_suspicious_input_sequence' | 'secure_ui_autofill_or_hidden_field_abuse' | 'secure_ui_brute_force_indicator' | 'secure_ui_fake_overlay_or_clickjacking' | 'secure_ui_click_injection_pattern' | 'secure_ui_session_fraud_score';
type SecureUiSignal = {
id: string;
type: SecureUiEventType;
level: FraudLevel;
score: number;
context: Record<string, unknown>;
createdAt: number;
};
type FormInteractionEvent = {
kind: 'form';
event: 'focus' | 'blur' | 'input' | 'change' | 'submit';
formId: string;
fieldName?: string;
fieldType?: string;
valueMeta?: {
length: number;
pattern: 'empty' | 'numeric' | 'alpha' | 'alphanumeric' | 'mixed';
entropyHint: 'low' | 'medium' | 'high';
cleared?: boolean;
pasted?: boolean;
};
isAutofillCandidate?: boolean;
skipped?: boolean;
timestamp: number;
};
type AuthFlowKind = 'login' | 'signup' | 'reset' | 'mfa' | 'unknown';
type AuthFlowEvent = {
kind: 'auth';
flowType: AuthFlowKind;
identifierHash?: string;
success?: boolean;
reason?: string;
formId?: string;
timestamp: number;
};
type PointerInteractionEvent = {
kind: 'pointer';
type: 'click' | 'pointerdown';
x: number;
y: number;
targetSignature: string;
isTrusted: boolean;
isVisible: boolean;
route?: string;
timestamp: number;
};
type OverlayObservationEvent = {
kind: 'overlay';
overlayId: string;
elementSignature: string;
zIndex: number;
coverage: number;
timestamp: number;
};
type AutofillOrHiddenFieldEvent = {
kind: 'autofill';
formId?: string;
fieldName?: string;
reason: 'hidden_field' | 'autofill_without_focus' | 'invisible_input';
visibility?: string;
timestamp: number;
};
type SecureUiCollectorEvent = FormInteractionEvent | AuthFlowEvent | PointerInteractionEvent | OverlayObservationEvent | AutofillOrHiddenFieldEvent;
type SecureUiSummary = {
sessionsObserved: number;
warningSessions: number;
highRiskSessions: number;
topForms: Array<{
formId: string;
signals: number;
lastSignalAt: number;
}>;
topRoutes: Array<{
route: string;
signals: number;
}>;
};
type AuthAbuseSummary = {
totalAttempts: number;
suspectedBruteForce: number;
flows: Array<{
flowType: AuthFlowKind;
attempts: number;
suspects: number;
}>;
};
type ClickInjectionSummary = {
suspiciousOverlays: number;
clickBursts: number;
hiddenTargets: number;
};
type SecureUiRuntimeSnapshot = {
config: SecureUiConfig;
sessionScore: number;
level: FraudLevel;
signals: SecureUiSignal[];
};
type SecureUiReporter = {
getSecureUiSummary: () => Promise<SecureUiSummary>;
getAuthAbuseSummary: () => Promise<AuthAbuseSummary>;
getClickInjectionSummary: () => Promise<ClickInjectionSummary>;
};
type PrivacySeverity = 'low' | 'medium' | 'high';
type PrivacyLevel = 'good' | 'needs_attention' | 'at_risk';
type PIIFieldKind = 'email' | 'phone' | 'name' | 'full_name' | 'address' | 'national_id' | 'user_id' | 'account_id' | 'dob' | 'unknown';
type PrivacyIssueType = 'console_pii' | 'storage_pii' | 'analytics_pii' | 'over_posting' | 'object_logging_abuse';
type PrivacyEventType = 'privacy_console_pii_leak' | 'privacy_storage_pii_issue' | 'privacy_analytics_pii_leak' | 'privacy_over_posting' | 'privacy_object_logging_abuse' | 'privacy_session_score';
type PrivacyGuardConfig = {
enabled?: boolean;
detectConsolePII?: boolean;
detectStoragePII?: boolean;
detectAnalyticsPII?: boolean;
detectOverPosting?: boolean;
detectObjectLoggingAbuse?: boolean;
piiPatternsOverride?: string[];
analyticsDomains?: string[];
maxPayloadSampleSize?: number;
};
type PrivacyIssue = {
id: string;
type: PrivacyIssueType;
severity: PrivacySeverity;
piiFields: PIIFieldKind[];
timestamp: number;
source: string;
details?: Record<string, unknown>;
};
type PrivacySessionScore = {
sessionId: string;
score: number;
level: PrivacyLevel;
issueCountsByType: Record<PrivacyIssueType, number>;
};
type RedactionRule = {
keys?: Array<string | RegExp>;
maxStringLength?: number;
replacement?: string;
};
declare const defaultSensitiveKeys: Array<string | RegExp>;
type Redactor = (payload: unknown, ctx?: {
eventType?: string;
}) => unknown;
declare const createRedactor: (ruleOverrides?: RedactionRule) => Redactor;
type CanonicalDesignEventType = 'layout_shift' | 'responsive_issue' | 'contrast_error' | 'ui_performance_issue' | 'visual_regression';
type LegacyDesignEventType = 'layout_shift_detected' | 'responsive_issue' | 'a11y_color_contrast_error' | 'ui_repaint_issue' | 'visual_regression_detected';
type DesignEventType = CanonicalDesignEventType | LegacyDesignEventType;
type DevSentinelEventType = DesignEventType | NetworkEventType | TestingEventType | CodeSmellEventType | SecureUiEventType | PrivacyEventType | DeviceEventType | EnvironmentEventType | RegressionEventType;
type RegressionEventType = 'regression_novel_issue_detected' | 'regression_issue_updated' | 'regression_issue_reintroduced' | 'regression_issue_frequency_spike' | 'regression_issue_timeline_snapshot';
type DeviceEventType = 'device_issue';
type EnvironmentEventType = 'environment_issue';
type Listener = (event: StoredLog) => void;
declare function hydrateFromDb(): Promise<void>;
declare function hydrateCodeSmellFromDb(): Promise<void>;
declare function hydrateSecureUiFromDb(): Promise<void>;
declare function hydratePrivacyFromDb(): Promise<void>;
declare function hydrateDeviceFromDb(): Promise<void>;
declare function hydrateEnvFromDb(): Promise<void>;
declare function log(eventType: DevSentinelEventType, payload: unknown): Promise<StoredLog | null>;
declare function subscribe(listener: Listener): () => void;
declare function subscribeNetwork(listener: Listener): () => void;
declare function subscribeCodeSmell(listener: Listener): () => void;
declare function subscribePrivacy(listener: Listener): () => void;
declare function subscribeDevice(listener: Listener): () => void;
declare function subscribeEnvironment(listener: Listener): () => void;
declare function get(eventType?: DevSentinelEventType): Promise<StoredLog[]>;
declare function clear(eventType?: DesignEventType): Promise<void>;
declare function getNetwork(eventType?: NetworkEventType): Promise<StoredLog[]>;
declare function clearNetwork(eventType?: NetworkEventType): Promise<void>;
declare function getCodeSmell(eventType?: CodeSmellEventType): Promise<StoredLog[]>;
declare function clearCodeSmell(eventType?: CodeSmellEventType): Promise<void>;
declare function getSecureUi(eventType?: SecureUiEventType): Promise<StoredLog[]>;
declare function getPrivacy(eventType?: PrivacyEventType): Promise<StoredLog[]>;
declare function getDevice(eventType?: DeviceEventType): Promise<StoredLog[]>;
declare function getEnvironment(eventType?: EnvironmentEventType): Promise<StoredLog[]>;
declare function clearSecureUi(eventType?: SecureUiEventType): Promise<void>;
declare function clearPrivacy(eventType?: PrivacyEventType): Promise<void>;
declare function clearDevice(eventType?: DeviceEventType): Promise<void>;
declare function clearEnvironment(eventType?: EnvironmentEventType): Promise<void>;
declare function subscribeSecureUi(listener: Listener): () => void;
declare function normalizeDesignEventType(eventType: DesignEventType): CanonicalDesignEventType;
declare function configureDevSentinelRedaction(customRedactor?: Redactor | null): void;
declare const defaultDevSentinelRedactor: Redactor;
declare const devSentinel: {
log: typeof log;
subscribe: typeof subscribe;
subscribeNetwork: typeof subscribeNetwork;
subscribeCodeSmell: typeof subscribeCodeSmell;
subscribeSecureUi: typeof subscribeSecureUi;
subscribePrivacy: typeof subscribePrivacy;
subscribeDevice: typeof subscribeDevice;
subscribeEnvironment: typeof subscribeEnvironment;
get: typeof get;
getNetwork: typeof getNetwork;
getCodeSmell: typeof getCodeSmell;
getSecureUi: typeof getSecureUi;
getPrivacy: typeof getPrivacy;
getDevice: typeof getDevice;
getEnvironment: typeof getEnvironment;
clear: typeof clear;
clearNetwork: typeof clearNetwork;
clearCodeSmell: typeof clearCodeSmell;
clearSecureUi: typeof clearSecureUi;
clearPrivacy: typeof clearPrivacy;
clearDevice: typeof clearDevice;
clearEnvironment: typeof clearEnvironment;
hydrateFromDb: typeof hydrateFromDb;
hydrateCodeSmellFromDb: typeof hydrateCodeSmellFromDb;
hydrateSecureUiFromDb: typeof hydrateSecureUiFromDb;
hydratePrivacyFromDb: typeof hydratePrivacyFromDb;
hydrateDeviceFromDb: typeof hydrateDeviceFromDb;
hydrateEnvFromDb: typeof hydrateEnvFromDb;
normalizeDesignEventType: typeof normalizeDesignEventType;
configureRedaction: typeof configureDevSentinelRedaction;
};
declare global {
interface Window {
devSentinel?: typeof devSentinel;
}
}
declare const DevPanel: React.FC;
type Breakpoint = {
name: string;
width: number;
height?: number;
};
type ResponsiveAnalyzerConfig = {
breakpoints: Breakpoint[];
};
declare function startResponsiveAnalyzer(config?: Partial<ResponsiveAnalyzerConfig>): void;
declare function stopResponsiveAnalyzer(): void;
declare function rerunResponsiveAnalyzer(): Promise<void> | void;
type VisualRegressionConfig = {
selectors: string[];
diffThreshold: number;
};
declare function startVisualRegressionEngine(config?: Partial<VisualRegressionConfig>): void;
declare function stopVisualRegressionEngine(): void;
declare function updateVisualRegressionConfig(config: Partial<VisualRegressionConfig>): void;
type DesignDiagnosticsConfig = {
visualRegression?: Partial<VisualRegressionConfig>;
responsive?: Partial<ResponsiveAnalyzerConfig>;
};
declare function registerDesignDiagnostics(orchestrator: SentinelOrchestrator, config?: DesignDiagnosticsConfig): void;
type ComponentId = string;
type HookUsageSummary = {
useState: number;
useEffect: number;
useMemo: number;
useCallback: number;
useContext: number;
customHooks: number;
};
type ComponentStructureMetrics = {
componentName: string;
filePath?: string;
depth?: number;
directChildren?: number;
maxNesting?: number;
hookUsage: HookUsageSummary;
localStateKeys: string[];
};
type PropsShapeSummary = {
totalProps: number;
optionalProps: string[];
requiredProps: string[];
deepProps: string[];
nullableProps: string[];
spreadPropsCount: number;
largeProps: string[];
maxSampledSize: number;
};
type StateUsageSummary = {
declared: string[];
used: string[];
unused: string[];
constantStateKeys: string[];
updateCount: number;
renderAffectedUpdates: number;
nonAffectingUpdates: number;
};
type GlobalAccessSummary = {
globals: string[];
windowAccesses: number;
storageAccesses: number;
sharedMutableAccesses: number;
eventBusAccesses: number;
};
type RenderBehaviorSummary = {
renderCount: number;
lastRenderAt?: number;
propChangeRenderRatio?: number;
wastedRenders?: number;
dynamicChildrenRange?: [number, number];
};
type RuntimeMetricsSummary = {
structure?: ComponentStructureMetrics;
props?: PropsShapeSummary;
state?: StateUsageSummary;
globals?: GlobalAccessSummary;
render?: RenderBehaviorSummary;
};
type StaticAnalysisSummary = {
cyclomaticComplexity?: number;
jsxNestingDepth?: number;
inlineFunctionCount?: number;
magicNumbers?: number[];
largeSwitchStatements?: number;
longConditionalCount?: number;
componentName?: string;
filePath?: string;
};
type RuleBasedFinding = {
smellType: CodeSmellEventType;
severity: CodeSmellSeverity;
summary: string;
evidence?: Record<string, unknown>;
suggestions?: string[];
};
type ComponentAnalysisInput = {
componentName: string;
filePath?: string;
runtimeMetrics: RuntimeMetricsSummary;
staticSnapshot?: StaticAnalysisSummary;
};
type ComponentAIAnalysisResult = {
severity: CodeSmellSeverity;
smells: string[];
explanation: string;
suggestions: string[];
recommendedRefactors?: string[];
};
type ComponentRuntimeProfile = {
componentId: ComponentId;
componentName: string;
filePath?: string;
runtime: RuntimeMetricsSummary;
staticAnalysis?: StaticAnalysisSummary;
ruleFindings: RuleBasedFinding[];
aiResult?: ComponentAIAnalysisResult;
lastAnalyzed: number;
timesAnalyzed: number;
aiQueued?: boolean;
};
type ComponentRenderSample = {
componentId: ComponentId;
componentName: string;
filePath?: string;
props?: Record<string, unknown>;
propsSpreadCount?: number;
state?: Record<string, unknown>;
stateUsageHints?: {
usedKeys?: string[];
updatedKeys?: string[];
renderAffectingKeys?: string[];
};
hooks?: Partial<HookUsageSummary>;
depth?: number;
childrenCount?: number;
renderedAt?: number;
globalAccesses?: string[];
dynamicChildrenCount?: number;
};
type PendingAIInput = {
componentId: ComponentId;
input: ComponentAnalysisInput;
ruleFindings: RuleBasedFinding[];
queuedAt: number;
};
type CodeSmellConfig = {
enabled?: boolean;
enableRuntimeMetrics?: boolean;
enableStaticSnapshots?: boolean;
enableAIAnalysis?: boolean;
maxComponentsAnalyzedPerSession?: number;
maxPropsSampleSizePerComponent?: number;
aiProvider?: 'prepilot' | 'custom' | 'none';
};
declare class CodeSmellRuntime {
private static _instance;
private config;
private detectors;
private components;
private meta;
private pendingAI;
private initialized;
static get instance(): CodeSmellRuntime;
init(config?: CodeSmellConfig): void;
captureRenderSample(sample: ComponentRenderSample, options?: {
staticSource?: string;
}): void;
analyzeComponent(componentId: string): void;
private shouldQueueAI;
private queueAI;
getPendingAIInputs(): PendingAIInput[];
submitAIAnalysis(componentId: string, result: ComponentAIAnalysisResult): void;
ingestStaticSnapshot(componentId: string, source: string): void;
getFindings(): ComponentRuntimeProfile[];
exportReport(): string;
start(config?: CodeSmellConfig): void;
stop(): void;
register(orchestrator: {
registerModule: (namespace: string, module: {
start: () => void;
stop: () => void;
}) => void;
}): void;
}
declare const codeSmellRuntime: CodeSmellRuntime;
type PendingAiEnvelope = PendingAIInput & {
prompt: string;
};
/**
* Default AI adapter keeps pending requests in-memory and exposes a prompt payload
* so external orchestrators (PrePilot, custom bridges) can pick them up.
*/
declare class DefaultCodeSmellAIAdapter {
private pending;
enqueue(input: PendingAIInput): void;
dequeue(componentId: string): PendingAiEnvelope | undefined;
list(): PendingAiEnvelope[];
clear(componentId?: string): void;
attachResult(componentId: string, result: ComponentAIAnalysisResult): {
componentId: string;
result: ComponentAIAnalysisResult;
} | null;
private buildPrompt;
}
declare const defaultAiAdapter: DefaultCodeSmellAIAdapter;
type CPUSnapshot = {
throttlingScore: number;
longTaskFrequency: number;
averageFrameDelta: number;
stallEventsCount: number;
fps?: number;
};
type GPUSnapshot = {
gpuHealthScore: number;
gpuContextResets: number;
softwareRenderingFlag: boolean;
renderer?: string;
fps?: number;
};
type MemorySnapshot = {
memoryPressureLevel: 'low' | 'moderate' | 'high';
usedJSHeapFraction?: number;
forcedReflowCount: number;
domNodes?: number;
};
type NetworkSnapshot = {
networkQuality: '4g' | '3g' | '2g' | 'slow-2g' | 'unknown';
bandwidthEstimate?: number;
saveDataEnabled?: boolean;
effectiveType?: string;
downlink?: number;
};
type BatterySnapshot = {
batterySaverEnabled: boolean;
batteryLevel: number | null;
dischargeRateHeuristic: number | null;
charging?: boolean;
};
type AccessibilitySnapshot = {
reducedMotion: boolean;
highContrastEnabled: boolean;
};
type WebViewSnapshot = {
isWebView: boolean;
webViewType: 'iOS' | 'Android' | 'Unknown';
pwaMode: boolean;
knownLimitations: string[];
};
type DeviceEnvironmentSnapshot = {
cpu: CPUSnapshot;
gpu: GPUSnapshot;
memory: MemorySnapshot;
network: NetworkSnapshot;
battery: BatterySnapshot;
accessibility: AccessibilitySnapshot;
webview: WebViewSnapshot;
collectedAt: number;
deviceHealthScore: number;
deviceHealthCategory: DeviceHealthCategory;
};
type DeviceHealthCategory = 'excellent' | 'normal' | 'degraded' | 'critical';
type DeviceIssue = {
type: 'cpu_throttling' | 'gpu_degradation' | 'memory_pressure' | 'low_network_mode' | 'battery_saver' | 'motion_reduction' | 'webview_environment';
severity: 'info' | 'warn' | 'error';
message: string;
meta?: Record<string, unknown>;
detectedAt: number;
};
type DeviceDiagnosticsConfig = {
enabled: boolean;
allowInProduction?: boolean;
cpu: {
threshold: number;
fpsFloor?: number;
};
gpu: {
enableWebGLChecks: boolean;
fpsThreshold?: number;
};
memory: {
highPressureThreshold: number;
};
network: {
trackChanges: boolean;
};
battery: {
detectSaver: boolean;
};
accessibility: {
detectReducedMotion: boolean;
};
webview: {
detectAll: boolean;
};
pollingIntervalMs?: number;
};
type RegressionSeverity = 'low' | 'medium' | 'high' | 'critical';
type RegressionStatus = 'novel' | 'active' | 'regression' | 'stable';
type RegressionFingerprint = {
id: string;
stacks: string[];
routes: string[];
environments: string[];
packSources: string[];
};
type RegressionIssue = RegressionIssueRecord & {
status: RegressionStatus;
severity: RegressionSeverity;
regressionFingerprint?: RegressionFingerprint;
};
type RegressionReport = {
generatedAt: string;
issues: RegressionIssue[];
eventsSample: RegressionEventRecord[];
};
type RegressionConfig = {
enabled?: boolean;
novelIssueSensitivity?: 'low' | 'medium' | 'high';
minOccurrencesForStableFingerprint?: number;
regressionCooldownMinutes?: number;
maxIssuesTracked?: number;
ignoreEventTypes?: string[];
};
type SentinelDesignConfig = {
visualRegression?: DesignDiagnosticsConfig['visualRegression'];
responsive?: DesignDiagnosticsConfig['responsive'];
networkPack?: NetworkIntelligencePack;
codeSmell?: CodeSmellConfig;
secureUi?: SecureUiConfig;
privacy?: PrivacyGuardConfig;
deviceDiagnostics?: DeviceDiagnosticsConfig;
regression?: RegressionConfig;
};
type OrchestratorModule = {
start: () => void | Promise<void>;
stop: () => void | Promise<void>;
};
declare class SentinelOrchestrator {
private started;
private config;
private modules;
constructor(config?: SentinelDesignConfig);
start(): void;
stop(): void;
rerunResponsive(): void;
updateConfig(config: SentinelDesignConfig): void;
registerModule(namespace: string, moduleInstance: OrchestratorModule): void;
}
declare function initDesignOrchestrator(config?: SentinelDesignConfig): SentinelOrchestrator;
declare function startLayoutStabilityMonitor(): void;
declare function stopLayoutStabilityMonitor(): void;
declare function startColorContrastScanner(): void;
declare function stopColorContrastScanner(): void;
declare function startUiPerformanceMonitor(): void;
declare function stopUiPerformanceMonitor(): void;
type TestRecord = {
info: TestCaseInfo;
results: TestCaseResult[];
domSnapshots: string[];
interactions: Array<{
path: string;
outcome: string;
}>;
timersPending: number;
};
type TestingState = {
runId: string;
env: TestEnvironmentKind;
config: Required<TestingPackConfig>;
tests: Map<string, TestRecord>;
observedCritical: {
routes: Set<string>;
components: Set<string>;
apis: Set<string>;
functions: Set<string>;
};
};
declare const testingRuntime: {
init(config?: TestingPackConfig): void;
getRunId(): string;
getEnvironment(): TestEnvironmentKind;
recordCriticalUsage(type: keyof CriticalPathsConfig, id: string): void;
onTestCaseStart(info: TestCaseInfo): void;
onTestCaseEnd(info: TestCaseInfo, result: TestCaseResult): void;
addDomSnapshot(info: TestCaseInfo, html: string): void;
notePendingTimers(info: TestCaseInfo, count: number): void;
recordObservation(observation: Observation): void;
getTests(): TestRecord[];
getConfig(): Required<TestingPackConfig>;
getObservedCritical(): TestingState["observedCritical"];
};
declare const initTestingPack: (config?: TestingPackConfig) => void;
declare const TestingInsightsPanel: React.FC;
declare const FlakinessPanel: React.FC;
declare const CoverageHintsPanel: React.FC;
declare const CodeSmellPanel: React.FC;
type Props = {
componentId?: string;
};
declare const RefactoringSuggestionsPanel: React.FC<Props>;
declare class SecureUiRuntime {
private static _instance;
private config;
private bus;
private collectors;
private detectors;
private aggregator;
private signals;
private started;
private authCollector;
static get instance(): SecureUiRuntime;
init(config?: SecureUiConfig): void;
start(config?: SecureUiConfig): void;
stop(): void;
private recordSignal;
private handleLevelChange;
emit(event: SecureUiCollectorEvent): void;
recordAuthAttempt(event: Partial<AuthFlowEvent>): void;
getCurrentSessionScore(): number;
getFindings(): SecureUiSignal[];
exportFraudSignals(): SecureUiRuntimeSnapshot;
register(orchestrator: {
registerModule: (namespace: string, module: {
start: () => void;
stop: () => void;
}) => void;
}): void;
}
declare const secureUiRuntime: SecureUiRuntime;
declare const secureUiReporter: SecureUiReporter;
declare const SecureUIPanel: React.FC;
declare const AuthAbusePanel: React.FC;
declare const ClickInjectionPanel: React.FC;
declare class PrivacyRuntime {
private static _instance;
private config;
private aggregator;
private teardownFns;
private started;
static get instance(): PrivacyRuntime;
init(config?: PrivacyGuardConfig): void;
start(config?: PrivacyGuardConfig): void;
stop(): void;
getFindings(): PrivacyIssue[];
getSessionPrivacyScore(): PrivacySessionScore;
exportPrivacyReport(): {
summary: {
score: number;
level: PrivacySessionScore["level"];
totals: Record<PrivacyIssueType, number>;
};
piiUsage: {
fieldCounts: Record<PIIFieldKind, number>;
};
overPosting: {
endpoints: Record<string, number>;
};
analyticsLeaks: {
vendors: Record<string, number>;
};
};
register(orchestrator: {
registerModule: (namespace: string, module: {
start: () => void;
stop: () => void;
}) => void;
}): void;
}
declare const privacyRuntime: PrivacyRuntime;
declare const PrivacyGuardPanel: React.FC;
declare const DataMinimizationPanel: React.FC;
declare const AnalyticsLeakPanel: React.FC;
declare class DeviceDiagnosticsRuntime {
private static _instance;
private config;
private cpu;
private gpu;
private memory;
private network;
private battery;
private accessibility;
private webview;
private timer;
private pendingEval;
private started;
private snapshots;
private issuesHistory;
private lastIssueAt;
private previousForceDev;
static get instance(): DeviceDiagnosticsRuntime;
start(config?: Partial<DeviceDiagnosticsConfig>): void;
stop(): void;
getLatestSnapshot(): DeviceEnvironmentSnapshot | null;
getTimeline(): DeviceEnvironmentSnapshot[];
getIssues(): DeviceIssue[];
exportReport(): {
snapshots: DeviceEnvironmentSnapshot[];
issues: DeviceIssue[];
};
private scheduleEvaluation;
private shouldRun;
private evaluate;
private collectSnapshot;
private detectIssues;
private recordIssue;
}
declare const deviceDiagnosticsRuntime: DeviceDiagnosticsRuntime;
declare const DeviceDiagnosticsPanel: React.FC;
declare const EnvironmentHealthPanel: React.FC;
declare class RegressionRuntime {
private static _instance;
private config;
private issues;
private hydrated;
private running;
private subscriptions;
private frequencyWindows;
private baselineFrequency;
static get instance(): RegressionRuntime;
init(config?: RegressionConfig): void;
register(orchestrator: {
registerModule: (namespace: string, module: {
start: () => void;
stop: () => void;
}) => void;
}): void;
start(config?: RegressionConfig): Promise<void>;
stop(): void;
ingest(event: StoredLog): Promise<void>;
reset(): void;
getIssueByFingerprint(fingerprint: string): RegressionIssue | undefined;
getIssues(): RegressionIssue[];
getNovelIssues(): RegressionIssue[];
getRegressions(): RegressionIssue[];
exportRegressionReport(): Promise<RegressionReport>;
getTimeline(fingerprint: string): Promise<RegressionEventRecord[]>;
private hydrate;
private attach;
private handleEvent;
private updateFrequency;
}
declare const regressionRuntime: RegressionRuntime;
declare const RegressionPanel: React.FC;
declare const NovelIssuesPanel: React.FC;
declare const RegressionTimelinePanel: React.FC;
export { AnalyticsLeakPanel, AuthAbusePanel, ClickInjectionPanel, type CodeSmellConfig, type CodeSmellEventType, CodeSmellPanel, CodeSmellRuntime, type CodeSmellSeverity, type ComponentAIAnalysisResult, type ComponentAnalysisInput, type ComponentRenderSample, CoverageHintsPanel, type CriticalPathConfig, type CriticalPathStep, type DataAnomalyConfig, type DataAnomalyDetector, DataMinimizationPanel, type DesignDiagnosticsConfig, type DesignEventType, type DevFetchOptions, DevPanel as DevSentinelDesignPanel, DevSentinelErrorBoundary, type DevSentinelFeatureConfig, type DevSentinelInitOptions, type DevSentinelLevel, type DevSentinelLogEntry, DevSentinelPanel, DevSentinelProvider, type DevSentinelTransport, type DeviceDiagnosticsConfig, DeviceDiagnosticsPanel, type DeviceEventType, type DeviceHealthCategory, type EndpointHealth, type EndpointHealthConfig, type EndpointHealthStatus, type EndpointMetrics, type EndpointRequestRecord, type EnvironmentEventType, EnvironmentHealthPanel, FlakinessPanel, type HealthMapData, type NetworkEventType, NetworkIntelligencePack, type NetworkPackConfig, NovelIssuesPanel, type PostTransportOptions, type PrivacyEventType, type PrivacyGuardConfig, PrivacyGuardPanel, type PrivacySessionScore, type RedactionRule, type Redactor, RefactoringSuggestionsPanel, type RegressionConfig, type RegressionIssue, RegressionPanel, type RegressionReport, RegressionRuntime, type RegressionSeverity, type RegressionStatus, RegressionTimelinePanel, type RetryAnalysisConfig, type SchemaValidationConfig, SecureUIPanel, type SecureUiConfig, type SecureUiEventType, type SecureUiSignal, type SentinelDesignConfig, SentinelOrchestrator, type TestingEventType, TestingInsightsPanel, type TestingPackConfig, clearDevSentinelLogs, clearHealthData, defaultAiAdapter as codeSmellDefaultAiAdapter, codeSmellRuntime, configureDevSentinelRedaction, createDevSentinelMiddleware, createNoopTransport, createPostTransport, createRedactor, defaultDevSentinelRedactor, defaultSensitiveKeys, devFetch, devSentinel, deviceDiagnosticsRuntime, downloadDevSentinelLogs, flushTransport, getCriticalPathStatuses, getCriticalPathSummary, getDevSentinelLogs, getEndpointHealthMap, getEndpointMetrics, getFeatureConfig, getHealthSummary, getOrchestratorConfig, getRetryAnalysisStats, getRetryPatterns, getSilentFailures, getValidationStats, initDesignOrchestrator, initDevSentinel, initNetworkIntelligencePack, initOrchestrator, initTestingPack, isOrchestratorInitialized, logDevSentinel, logRouteChange, privacyRuntime, registerCriticalPathStep, registerDesignDiagnostics, registerEndpointSchema, registerNetworkModule, registerRouteResolver, regressionRuntime, rerunResponsiveAnalyzer, secureUiReporter, secureUiRuntime, sentinelCheckData, startColorContrastScanner, startLayoutStabilityMonitor, startResponsiveAnalyzer, startUiPerformanceMonitor, startVisualRegressionEngine, stopColorContrastScanner, stopLayoutStabilityMonitor, stopResponsiveAnalyzer, stopUiPerformanceMonitor, stopVisualRegressionEngine, subscribeToLogs, teardownOrchestrator, testingRuntime, trackCriticalPathAPI, trackCriticalPathRoute, trackEndpointFailure, trackSilentFailure, updateFeatureConfig, updateOrchestratorConfig, updateVisualRegressionConfig, useDevSentinel, validateResponse };