@guardaian/sdk
Version:
Zero-friction AI governance and monitoring SDK for Node.js applications
353 lines (313 loc) • 10.5 kB
JavaScript
/**
* GuardAIan SDK - Auto Import (Bulletproof Production Version)
*
* CRITICAL GUARANTEES:
* 1. Customer AI calls NEVER blocked, even if GuardAIan is completely down
* 2. All patching errors are isolated and non-blocking
* 3. Graceful degradation in all failure scenarios
* 4. Zero impact on customer application performance
*
* Usage:
* 1. GuardAIan.init({ apiKey: 'gai_abc123' })
* 2. import '@guardaian/sdk/auto'
*/
// Import with complete error protection
let GuardAIanClient, patchOpenAI, patchGemini;
let patchAnthropic, patchAzureOpenAI, patchBedrock, patchCohere, patchHuggingFace;
try {
GuardAIanClient = require('./client');
} catch (error) {
console.warn('⚠️ GuardAIan: Failed to load client - tracking disabled');
module.exports = { disabled: true, error: 'client_load_failed' };
return;
}
// Load core interceptors with error protection
try {
({ patchOpenAI } = require('./interceptors/openai'));
} catch (error) {
console.warn('⚠️ GuardAIan: OpenAI interceptor unavailable');
patchOpenAI = null;
}
try {
({ patchGemini } = require('./interceptors/gemini'));
} catch (error) {
console.warn('⚠️ GuardAIan: Gemini interceptor unavailable');
patchGemini = null;
}
// Load optional interceptors with graceful fallback
try {
({ patchAnthropic } = require('./interceptors/anthropic'));
} catch (e) {
patchAnthropic = null;
}
try {
({ patchAzureOpenAI } = require('./interceptors/azure'));
} catch (e) {
patchAzureOpenAI = null;
}
try {
({ patchBedrock } = require('./interceptors/bedrock'));
} catch (e) {
patchBedrock = null;
}
try {
({ patchCohere } = require('./interceptors/cohere'));
} catch (e) {
patchCohere = null;
}
try {
({ patchHuggingFace } = require('./interceptors/huggingface'));
} catch (e) {
patchHuggingFace = null;
}
// Check initialization with error protection
let config;
try {
config = global.__GUARDAIAN_CONFIG__;
} catch (error) {
console.warn('⚠️ GuardAIan: Configuration access failed - tracking disabled');
module.exports = { disabled: true, error: 'config_access_failed' };
return;
}
// Validate configuration
if (!config || !config.apiKey) {
if (process.env.NODE_ENV !== 'production') {
console.warn('⚠️ GuardAIan: Not initialized. Call GuardAIan.init({ apiKey }) first.');
}
// Don't block - just disable tracking
module.exports = { disabled: true, error: 'not_initialized' };
return;
}
// Initialize GuardAIan client with bulletproof error handling
let guardaianClient;
try {
guardaianClient = new GuardAIanClient({
apiKey: config.apiKey,
baseURL: config.baseURL || 'http://localhost:5000', // Use localhost for development
environment: config.environment || process.env.NODE_ENV || 'development',
debug: config.debug || false,
timeout: 3000, // Aggressive timeout
maxRetries: 2, // Limited retries
enableFallback: true
});
if (config.debug) {
console.log('🛡️ GuardAIan SDK initialized with bulletproof protection');
}
} catch (error) {
console.warn('⚠️ GuardAIan SDK initialization failed (non-blocking):', error.message);
// Don't block customer code - continue without tracking
module.exports = { disabled: true, error: 'client_init_failed' };
return;
}
// Bulletproof module patching system
const Module = require('module');
let originalRequire;
try {
originalRequire = Module.prototype.require;
} catch (error) {
console.warn('⚠️ GuardAIan: Module system unavailable - tracking disabled');
module.exports = { disabled: true, error: 'module_system_failed' };
return;
}
// Track patched libraries safely
const patchedLibraries = new Set();
// Override require with complete error isolation
Module.prototype.require = function(id, ...args) {
let module;
try {
// CRITICAL: Always call original require first
module = originalRequire.apply(this, [id, ...args]);
} catch (requireError) {
// Re-throw original require errors - don't interfere
throw requireError;
}
// CRITICAL: All patching happens in isolated context
// Customer's module import always succeeds regardless of patching
try {
// IMMEDIATE patching for critical modules
patchLibraryIfNeeded(id, module);
} catch (patchError) {
// Patching errors are completely isolated
if (guardaianClient?.options?.debug) {
console.warn(`⚠️ GuardAIan: Patching error for ${id} (non-blocking):`, patchError.message);
}
}
// CRITICAL: Always return original module unchanged
return module;
};
/**
* Patch library with complete error isolation - IMMEDIATE EXECUTION
*/
function patchLibraryIfNeeded(moduleId, moduleExports) {
try {
// OpenAI patching
if (moduleId === 'openai' && !patchedLibraries.has('openai')) {
if (patchOpenAI && moduleExports) {
patchOpenAI(moduleExports, guardaianClient);
patchedLibraries.add('openai');
// Also try Azure OpenAI detection
if (patchAzureOpenAI) {
try {
patchAzureOpenAI(moduleExports, guardaianClient);
patchedLibraries.add('azure');
} catch (azureError) {
debugLog('Azure OpenAI patch failed (non-blocking):', azureError.message);
}
}
debugLog('🔧 OpenAI library patched successfully');
}
return;
}
// Google Generative AI patching
if (moduleId === '@google/generative-ai' && !patchedLibraries.has('google')) {
if (patchGemini && moduleExports) {
patchGemini(moduleExports, guardaianClient);
patchedLibraries.add('google');
debugLog('🔧 Google Generative AI library patched successfully');
}
return;
}
// Anthropic patching
if (moduleId === '@anthropic-ai/sdk' && !patchedLibraries.has('anthropic')) {
if (patchAnthropic && (moduleExports.default || moduleExports.Anthropic)) {
const anthropicClass = moduleExports.default || moduleExports.Anthropic;
patchAnthropic(anthropicClass, guardaianClient);
patchedLibraries.add('anthropic');
debugLog('🔧 Anthropic library patched successfully');
}
return;
}
// AWS Bedrock patching
if (moduleId === '@aws-sdk/client-bedrock-runtime' && !patchedLibraries.has('bedrock')) {
if (patchBedrock && moduleExports.BedrockRuntimeClient) {
patchBedrock(moduleExports, guardaianClient);
patchedLibraries.add('bedrock');
debugLog('🔧 AWS Bedrock library patched successfully');
}
return;
}
// Cohere patching
if (moduleId === 'cohere-ai' && !patchedLibraries.has('cohere')) {
if (patchCohere && moduleExports.CohereClient) {
patchCohere(moduleExports.CohereClient, guardaianClient);
patchedLibraries.add('cohere');
debugLog('🔧 Cohere library patched successfully');
}
return;
}
// Hugging Face patching
if (moduleId === '@huggingface/inference' && !patchedLibraries.has('huggingface')) {
if (patchHuggingFace && moduleExports.HfInference) {
patchHuggingFace(moduleExports.HfInference, guardaianClient);
patchedLibraries.add('huggingface');
debugLog('🔧 Hugging Face library patched successfully');
}
return;
}
} catch (patchError) {
// Individual patching errors should never crash
debugLog(`❌ Failed to patch ${moduleId} (non-blocking):`, patchError.message);
}
}
/**
* Safe debug logging
*/
function debugLog(message, ...args) {
try {
if (guardaianClient?.options?.debug) {
console.log(`🛡️ GuardAIan: ${message}`, ...args);
}
} catch (logError) {
// Even logging can fail - do nothing
}
}
// Bulletproof process cleanup
function safeCleanup() {
try {
if (guardaianClient && typeof guardaianClient.flush === 'function') {
// Fire-and-forget cleanup
guardaianClient.flush().catch(() => {});
}
} catch (cleanupError) {
// Cleanup errors should never crash
}
}
// Process event handlers with error protection
try {
process.on('exit', safeCleanup);
process.on('SIGINT', () => {
safeCleanup();
process.exit(0);
});
process.on('SIGTERM', () => {
safeCleanup();
process.exit(0);
});
} catch (eventError) {
// Event handler setup errors should not crash
debugLog('Warning: Process event handlers not set up:', eventError.message);
}
// Mark auto module as loaded
try {
global.__GUARDAIAN_AUTO_LOADED__ = true;
} catch (globalError) {
// Even this can fail in some environments
}
// Log available interceptors safely
if (config.debug) {
try {
const availableInterceptors = [];
if (patchAnthropic) availableInterceptors.push('Anthropic');
if (patchAzureOpenAI) availableInterceptors.push('Azure OpenAI');
if (patchBedrock) availableInterceptors.push('AWS Bedrock');
if (patchCohere) availableInterceptors.push('Cohere');
if (patchHuggingFace) availableInterceptors.push('Hugging Face');
const baseInterceptors = ['OpenAI', 'Google Gemini'];
const allInterceptors = [...baseInterceptors, ...availableInterceptors];
console.log(`🛡️ GuardAIan: Available interceptors - ${allInterceptors.join(', ')}`);
console.log(`🛡️ GuardAIan: Bulletproof protection enabled - customer AI calls guaranteed to work`);
} catch (logError) {
// Logging errors should not crash
}
}
// Health check endpoint for the SDK itself
function getSDKHealth() {
try {
return {
initialized: !!guardaianClient,
clientHealth: guardaianClient?.getHealthStatus?.() || null,
patchedLibraries: Array.from(patchedLibraries),
availableInterceptors: {
openai: !!patchOpenAI,
gemini: !!patchGemini,
anthropic: !!patchAnthropic,
azure: !!patchAzureOpenAI,
bedrock: !!patchBedrock,
cohere: !!patchCohere,
huggingface: !!patchHuggingFace
},
timestamp: new Date().toISOString()
};
} catch (error) {
return {
error: error.message,
timestamp: new Date().toISOString()
};
}
}
// Export with error protection
try {
module.exports = {
client: guardaianClient,
patchedLibraries: Array.from(patchedLibraries),
getHealth: getSDKHealth,
disabled: false
};
} catch (exportError) {
// Final fallback - ensure something is exported
module.exports = {
disabled: true,
error: 'export_failed',
message: 'GuardAIan SDK disabled due to export error'
};
}