File size: 10,259 Bytes
8b7b267 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |
/**
* Feature Flags Manager - Frontend
* Handles feature flag state and synchronization with backend
*/
class FeatureFlagsManager {
constructor() {
this.flags = {};
this.localStorageKey = 'crypto_monitor_feature_flags';
this.apiEndpoint = '/api/feature-flags';
this.listeners = [];
}
/**
* Initialize feature flags from backend and localStorage
*/
async init() {
// Load from localStorage first (for offline/fast access)
this.loadFromLocalStorage();
// Sync with backend
await this.syncWithBackend();
// Set up periodic sync (every 30 seconds)
setInterval(() => this.syncWithBackend(), 30000);
return this.flags;
}
/**
* Load flags from localStorage
*/
loadFromLocalStorage() {
try {
const stored = localStorage.getItem(this.localStorageKey);
if (stored) {
const data = JSON.parse(stored);
this.flags = data.flags || {};
console.log('[FeatureFlags] Loaded from localStorage:', this.flags);
}
} catch (error) {
console.error('[FeatureFlags] Error loading from localStorage:', error);
}
}
/**
* Save flags to localStorage
*/
saveToLocalStorage() {
try {
const data = {
flags: this.flags,
updated_at: new Date().toISOString()
};
localStorage.setItem(this.localStorageKey, JSON.stringify(data));
console.log('[FeatureFlags] Saved to localStorage');
} catch (error) {
console.error('[FeatureFlags] Error saving to localStorage:', error);
}
}
/**
* Sync with backend
*/
async syncWithBackend() {
try {
const response = await fetch(this.apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
this.flags = data.flags || {};
this.saveToLocalStorage();
this.notifyListeners();
console.log('[FeatureFlags] Synced with backend:', this.flags);
return this.flags;
} catch (error) {
console.error('[FeatureFlags] Error syncing with backend:', error);
// Fall back to localStorage
return this.flags;
}
}
/**
* Check if a feature is enabled
*/
isEnabled(flagName) {
return this.flags[flagName] === true;
}
/**
* Get all flags
*/
getAll() {
return { ...this.flags };
}
/**
* Set a single flag
*/
async setFlag(flagName, value) {
try {
const response = await fetch(`${this.apiEndpoint}/${flagName}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
flag_name: flagName,
value: value
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
if (data.success) {
this.flags[flagName] = value;
this.saveToLocalStorage();
this.notifyListeners();
console.log(`[FeatureFlags] Set ${flagName} = ${value}`);
return true;
}
return false;
} catch (error) {
console.error(`[FeatureFlags] Error setting flag ${flagName}:`, error);
return false;
}
}
/**
* Update multiple flags
*/
async updateFlags(updates) {
try {
const response = await fetch(this.apiEndpoint, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
flags: updates
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
if (data.success) {
this.flags = data.flags;
this.saveToLocalStorage();
this.notifyListeners();
console.log('[FeatureFlags] Updated flags:', updates);
return true;
}
return false;
} catch (error) {
console.error('[FeatureFlags] Error updating flags:', error);
return false;
}
}
/**
* Reset to defaults
*/
async resetToDefaults() {
try {
const response = await fetch(`${this.apiEndpoint}/reset`, {
method: 'POST'
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
if (data.success) {
this.flags = data.flags;
this.saveToLocalStorage();
this.notifyListeners();
console.log('[FeatureFlags] Reset to defaults');
return true;
}
return false;
} catch (error) {
console.error('[FeatureFlags] Error resetting flags:', error);
return false;
}
}
/**
* Add change listener
*/
onChange(callback) {
this.listeners.push(callback);
return () => {
const index = this.listeners.indexOf(callback);
if (index > -1) {
this.listeners.splice(index, 1);
}
};
}
/**
* Notify all listeners of changes
*/
notifyListeners() {
this.listeners.forEach(callback => {
try {
callback(this.flags);
} catch (error) {
console.error('[FeatureFlags] Error in listener:', error);
}
});
}
/**
* Render feature flags UI
*/
renderUI(containerId) {
const container = document.getElementById(containerId);
if (!container) {
console.error(`[FeatureFlags] Container #${containerId} not found`);
return;
}
const flagDescriptions = {
enableWhaleTracking: 'Show whale transaction tracking',
enableMarketOverview: 'Display market overview dashboard',
enableFearGreedIndex: 'Show Fear & Greed sentiment index',
enableNewsFeed: 'Display cryptocurrency news feed',
enableSentimentAnalysis: 'Enable sentiment analysis features',
enableMlPredictions: 'Show ML-powered price predictions',
enableProxyAutoMode: 'Automatic proxy for failing APIs',
enableDefiProtocols: 'Display DeFi protocol data',
enableTrendingCoins: 'Show trending cryptocurrencies',
enableGlobalStats: 'Display global market statistics',
enableProviderRotation: 'Enable provider rotation system',
enableWebSocketStreaming: 'Real-time WebSocket updates',
enableDatabaseLogging: 'Log provider health to database',
enableRealTimeAlerts: 'Show real-time alert notifications',
enableAdvancedCharts: 'Display advanced charting',
enableExportFeatures: 'Enable data export functions',
enableCustomProviders: 'Allow custom API providers',
enablePoolManagement: 'Enable provider pool management',
enableHFIntegration: 'HuggingFace model integration'
};
let html = '<div class="feature-flags-container">';
html += '<h3>Feature Flags</h3>';
html += '<div class="feature-flags-list">';
Object.keys(this.flags).forEach(flagName => {
const enabled = this.flags[flagName];
const description = flagDescriptions[flagName] || flagName;
html += `
<div class="feature-flag-item">
<label class="feature-flag-label">
<input
type="checkbox"
class="feature-flag-toggle"
data-flag="${flagName}"
${enabled ? 'checked' : ''}
/>
<span class="feature-flag-name">${description}</span>
</label>
<span class="feature-flag-status ${enabled ? 'enabled' : 'disabled'}">
${enabled ? '✓ Enabled' : '✗ Disabled'}
</span>
</div>
`;
});
html += '</div>';
html += '<div class="feature-flags-actions">';
html += '<button id="ff-reset-btn" class="btn btn-secondary">Reset to Defaults</button>';
html += '</div>';
html += '</div>';
container.innerHTML = html;
// Add event listeners
container.querySelectorAll('.feature-flag-toggle').forEach(toggle => {
toggle.addEventListener('change', async (e) => {
const flagName = e.target.dataset.flag;
const value = e.target.checked;
await this.setFlag(flagName, value);
});
});
const resetBtn = container.querySelector('#ff-reset-btn');
if (resetBtn) {
resetBtn.addEventListener('click', async () => {
if (confirm('Reset all feature flags to defaults?')) {
await this.resetToDefaults();
this.renderUI(containerId);
}
});
}
// Listen for changes and re-render
this.onChange(() => {
this.renderUI(containerId);
});
}
}
// Global instance
window.featureFlagsManager = new FeatureFlagsManager();
// Auto-initialize on DOMContentLoaded
document.addEventListener('DOMContentLoaded', () => {
window.featureFlagsManager.init().then(() => {
console.log('[FeatureFlags] Initialized');
});
});
|