rezilient.js
Version:
Rezilient.js - Revolutionary offline-first framework with AI-awareness, principle-driven development, carbon-conscious computing, and self-healing capabilities
1 lines • 65.6 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Rezilient={})}(this,function(e){"use strict";class t{constructor(e){this._state=e,this._subscribers=new Set}subscribe(e){return this._subscribers.add(e),e(this._state),()=>{this._subscribers.delete(e)}}set(e){e!==this._state&&(this._state=e,this._notify())}update(e){this.set(e(this._state))}_notify(){for(const e of this._subscribers)e(this._state)}get(){return this._state}}const n="undefined"!=typeof process&&"test"===process.env.NODE_ENV,r=async(e,t)=>{if(n)try{const{set:n}=await Promise.resolve().then(function(){return l});return await n(e,t)}catch(e){return}if("undefined"!=typeof window&&"undefined"!=typeof indexedDB)try{return new Promise((n,r)=>{const s=indexedDB.open("aether-store",1);s.onerror=()=>n(),s.onsuccess=r=>{const s=r.target.result.transaction(["keyval"],"readwrite").objectStore("keyval").put(t,e);s.onsuccess=()=>n(),s.onerror=()=>n()},s.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains("keyval")||t.createObjectStore("keyval")}})}catch(e){console.warn("IndexedDB set failed:",e.message)}};class s extends t{constructor(e,t){super(t),this.key=e,this._isInitialized=!1,this._init()}async _init(){try{const e=await(async e=>{if(n)try{const{get:t}=await Promise.resolve().then(function(){return l});return await t(e)}catch(e){return}if("undefined"!=typeof window&&"undefined"!=typeof indexedDB)try{return new Promise((t,n)=>{const r=indexedDB.open("aether-store",1);r.onerror=()=>t(void 0),r.onsuccess=n=>{const r=n.target.result;if(!r.objectStoreNames.contains("keyval"))return void t(void 0);const s=r.transaction(["keyval"],"readonly").objectStore("keyval").get(e);s.onsuccess=()=>t(s.result),s.onerror=()=>t(void 0)},r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains("keyval")||t.createObjectStore("keyval")}})}catch(e){return void console.warn("IndexedDB get failed:",e.message)}})(this.key);void 0!==e&&(this._state=e)}catch(e){console.warn(`PersistentStore(${this.key}): Failed to load from storage:`,e.message)}this._isInitialized=!0,this._notify()}set(e){super.set(e),this._isInitialized&&r(this.key,e).catch(e=>{console.warn(`PersistentStore(${this.key}): Failed to save to IndexedDB:`,e.message)})}update(e){super.update(e),this._isInitialized&&r(this.key,this._state).catch(e=>{console.warn(`PersistentStore(${this.key}): Failed to save to IndexedDB:`,e.message)})}}function i(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function a(e,t){let n;return(r,s)=>(()=>{if(n)return n;const r=indexedDB.open(e);return r.onupgradeneeded=()=>r.result.createObjectStore(t),n=i(r),n.then(e=>{e.onclose=()=>n=void 0},()=>{}),n})().then(e=>s(e.transaction(t,r).objectStore(t)))}let o;function c(){return o||(o=a("keyval-store","keyval")),o}function u(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},i(e.transaction)}var l=Object.freeze({__proto__:null,clear:function(e=c()){return e("readwrite",e=>(e.clear(),i(e.transaction)))},createStore:a,del:function(e,t=c()){return t("readwrite",t=>(t.delete(e),i(t.transaction)))},delMany:function(e,t=c()){return t("readwrite",t=>(e.forEach(e=>t.delete(e)),i(t.transaction)))},entries:function(e=c()){return e("readonly",t=>{if(t.getAll&&t.getAllKeys)return Promise.all([i(t.getAllKeys()),i(t.getAll())]).then(([e,t])=>e.map((e,n)=>[e,t[n]]));const n=[];return e("readonly",e=>u(e,e=>n.push([e.key,e.value])).then(()=>n))})},get:function(e,t=c()){return t("readonly",t=>i(t.get(e)))},getMany:function(e,t=c()){return t("readonly",t=>Promise.all(e.map(e=>i(t.get(e)))))},keys:function(e=c()){return e("readonly",e=>{if(e.getAllKeys)return i(e.getAllKeys());const t=[];return u(e,e=>t.push(e.key)).then(()=>t)})},promisifyRequest:i,set:function(e,t,n=c()){return n("readwrite",n=>(n.put(t,e),i(n.transaction)))},setMany:function(e,t=c()){return t("readwrite",t=>(e.forEach(e=>t.put(e[1],e[0])),i(t.transaction)))},update:function(e,t,n=c()){return n("readwrite",n=>new Promise((r,s)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),r(i(n.transaction))}catch(e){s(e)}}}))},values:function(e=c()){return e("readonly",e=>{if(e.getAll)return i(e.getAll());const t=[];return u(e,e=>t.push(e.value)).then(()=>t)})}});class h{static _cache=new Map;static getEnvironment(){if(this._cache.has("environment"))return this._cache.get("environment");let e="unknown";return"undefined"!=typeof process&&process.versions&&process.versions.node?e="node":"undefined"!=typeof window&&"undefined"!=typeof document?e="browser":"undefined"!=typeof self&&"function"==typeof importScripts?e="webworker":"undefined"!=typeof navigator&&"ReactNative"===navigator.product&&(e="react-native"),this._cache.set("environment",e),e}static isBrowser(){return"browser"===this.getEnvironment()}static isNode(){return"node"===this.getEnvironment()}static isWebWorker(){return"webworker"===this.getEnvironment()}static isReactNative(){return"react-native"===this.getEnvironment()}static getGlobal(){if(this._cache.has("global"))return this._cache.get("global");let e;return e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},this._cache.set("global",e),e}}class d{static getNavigator(){return h.getGlobal().navigator||{userAgent:"Aether.js/Node.js",platform:"node",onLine:!0,connection:{effectiveType:"4g"},permissions:{query:()=>Promise.resolve({state:"granted"})},mediaDevices:{getUserMedia:()=>Promise.reject(new Error("Media not available in Node.js"))}}}static getLocalStorage(){if(h.isBrowser())try{return window.localStorage}catch(e){return this.createMemoryStorage()}return this.createMemoryStorage()}static getSessionStorage(){if(h.isBrowser())try{return window.sessionStorage}catch(e){return this.createMemoryStorage()}return this.createMemoryStorage()}static getIndexedDB(){return h.isBrowser()?window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB:null}static getDocument(){return h.getGlobal().document||{createElement:()=>({}),getElementById:()=>null,querySelector:()=>null,addEventListener:()=>{},removeEventListener:()=>{}}}static getWindow(){const e=h.getGlobal();return e.window||e}static confirm(e){return h.isBrowser()&&"function"==typeof window.confirm?window.confirm(e):(console.log(`[Aether.js] Auto-confirming: ${e}`),!0)}static alert(e){h.isBrowser()&&"function"==typeof window.alert?window.alert(e):console.log(`[Aether.js] Alert: ${e}`)}static createMemoryStorage(){const e=new Map;return{getItem:t=>e.get(t)||null,setItem:(t,n)=>e.set(t,String(n)),removeItem:t=>e.delete(t),clear:()=>e.clear(),get length(){return e.size},key:t=>Array.from(e.keys())[t]||null}}static async fetch(e,t={}){if(h.isBrowser()&&"function"==typeof fetch)return fetch(e,t);if(h.isNode())try{const{default:n}=await import("node-fetch");return n(e,t)}catch(e){throw new Error("Fetch not available in Node.js environment")}throw new Error("Fetch not available in current environment")}static getWebXR(){return this.getNavigator().xr||{isSessionSupported:()=>Promise.resolve(!1),requestSession:()=>Promise.reject(new Error("WebXR not supported"))}}static createWorker(e){return h.isBrowser()&&"function"==typeof Worker?new Worker(e):{postMessage:e=>console.log("Worker message:",e),terminate:()=>{},addEventListener:()=>{},removeEventListener:()=>{}}}static getPerformance(){return h.getGlobal().performance||{now:()=>Date.now(),mark:()=>{},measure:()=>{},getEntriesByType:()=>[]}}static getCrypto(){const e=h.getGlobal();if(e.crypto&&e.crypto.getRandomValues)return e.crypto;if(h.isNode())try{const e=require("crypto");return{getRandomValues:t=>{const n=e.randomBytes(t.length);for(let e=0;e<t.length;e++)t[e]=n[e];return t},subtle:e.webcrypto?.subtle||null}}catch(e){}return{getRandomValues:e=>{for(let t=0;t<e.length;t++)e[t]=Math.floor(256*Math.random());return e},subtle:null}}}class p{static getNetworkInfo(){const e=d.getNavigator(),t=e.connection||e.mozConnection||e.webkitConnection;return{isOnline:!1!==e.onLine,effectiveType:t?.effectiveType||"4g",downlink:t?.downlink||10,rtt:t?.rtt||100,saveData:t?.saveData||!1}}static addNetworkListener(e){const t=h.getGlobal();if(h.isBrowser()){t.addEventListener("online",()=>e({isOnline:!0})),t.addEventListener("offline",()=>e({isOnline:!1}));const n=d.getNavigator().connection;n&&n.addEventListener&&n.addEventListener("change",()=>{e(this.getNetworkInfo())})}}}class y{constructor(e={}){this.options={maxCacheSize:e.maxCacheSize||52428800,maxCacheAge:e.maxCacheAge||6048e5,enablePredictiveCaching:!1!==e.enablePredictiveCaching,enableCarbonAware:!1!==e.enableCarbonAware,cacheStrategies:{static:"cache-first",api:"stale-while-revalidate",dynamic:"network-first",...e.cacheStrategies}},this.stats={hits:0,misses:0,evictions:0,totalSize:0,lastCleanup:Date.now()},this.usagePatterns=new Map,this.accessHistory=[],this.carbonData={lastUpdate:0,intensity:"medium",renewablePercentage:50},this.initialize()}async initialize(){await this.loadCacheStats(),await this.loadUsagePatterns(),await this.updateCarbonData(),this.setupMaintenanceSchedule(),this.setupCarbonUpdates()}async invalidateCache(e,t={}){const{force:n=!1,preserveFrequent:r=!0,maxAge:s=this.options.maxCacheAge}=t,i=await window.caches.keys(),a={invalidated:0,preserved:0,errors:[]};for(const t of i)try{const i=await window.caches.open(t),o=await i.keys();for(const t of o){const o=t.url;if(this.matchesPattern(o,e)){await this.shouldInvalidateEntry(t,i,{force:n,preserveFrequent:r,maxAge:s})?(await i.delete(t),a.invalidated++):a.preserved++}}}catch(e){a.errors.push({cacheName:t,error:e.message})}return this.stats.evictions+=a.invalidated,await this.saveCacheStats(),a}async predictivePreCache(e){if(!this.options.enablePredictiveCaching)return;this.recordAccess(e);const t=this.analyzePredictions(e);this.shouldPreCache()&&await this.preCacheResources(t)}async scheduleSync(e,t="normal"){const n=await this.getCarbonIntensity(),r=this.getNetworkCondition(),s=this.calculateOptimalDelay(n,r,t);return 0===s?await e():this.scheduleDelayedSync(e,s,t)}async handleRequest(e,t=null){const n=new URL(e.url),r=t||this.determineCacheStrategy(n);switch(this.recordAccess(n.href),r){case"cache-first":return this.cacheFirstStrategy(e);case"network-first":return this.networkFirstStrategy(e);case"stale-while-revalidate":default:return this.staleWhileRevalidateStrategy(e);case"cache-only":return this.cacheOnlyStrategy(e);case"network-only":return this.networkOnlyStrategy(e)}}async cacheFirstStrategy(e){try{const t=await caches.match(e);if(t)return this.stats.hits++,this.isStale(t)&&this.scheduleBackgroundUpdate(e),t;this.stats.misses++;const n=await fetch(e);return n.ok&&await this.cacheResponse(e,n.clone()),n}catch(t){const n=await this.getStaleResponse(e);if(n)return n;throw t}}async staleWhileRevalidateStrategy(e){const t=await caches.match(e);if(t){this.stats.hits++;const n=Promise.resolve(t);return this.shouldRevalidate()&&this.revalidateInBackground(e),n}this.stats.misses++;const n=await fetch(e);return n.ok&&await this.cacheResponse(e,n.clone()),n}async networkFirstStrategy(e){try{const t=await fetch(e);return t.ok&&await this.cacheResponse(e,t.clone()),t}catch(t){const n=await caches.match(e);if(n)return this.stats.hits++,n;throw this.stats.misses++,t}}async cacheResponse(e,t){const n=this.determineCacheName(e),r=await caches.open(n);await this.shouldEvictForSpace()&&await this.evictLeastUsed();const s=this.enhanceResponse(t);await r.put(e,s),this.updateCacheStats(e,t)}determineCacheStrategy(e){return this.isStaticAsset(e)?this.options.cacheStrategies.static:this.isApiEndpoint(e)?this.options.cacheStrategies.api:this.options.cacheStrategies.dynamic}async getCarbonIntensity(){return Date.now()-this.carbonData.lastUpdate>36e5&&await this.updateCarbonData(),this.carbonData.intensity}async updateCarbonData(){if(this.options.enableCarbonAware)try{const e=(new Date).getHours();e>=10&&e<=16?(this.carbonData.intensity="low",this.carbonData.renewablePercentage=70):e>=6&&e<=22?(this.carbonData.intensity="medium",this.carbonData.renewablePercentage=50):(this.carbonData.intensity="high",this.carbonData.renewablePercentage=30),this.carbonData.lastUpdate=Date.now()}catch(e){console.warn("Failed to update carbon data:",e)}}calculateOptimalDelay(e,t,n){if("urgent"===n)return 0;let r=0;switch(e){case"high":r+="low"===n?36e5:18e5;break;case"medium":r+="low"===n?9e5:3e5;break;case"low":r=0}return"slow"===t&&(r+=3e5),r}analyzePredictions(e){const t=this.usagePatterns.get(e)||{next:new Map,count:0};return Array.from(t.next.entries()).sort((e,t)=>t[1]-e[1]).slice(0,5).map(([e,t])=>({url:e,probability:t}))}recordAccess(e){const t=Date.now();this.accessHistory.push({url:e,timestamp:t}),this.accessHistory.length>1e3&&(this.accessHistory=this.accessHistory.slice(-1e3)),this.updateUsagePatterns(e)}updateUsagePatterns(e){const t=this.accessHistory.slice(-10),n=t[t.length-2];if(n){const t=n.url;this.usagePatterns.has(t)||this.usagePatterns.set(t,{next:new Map,count:0});const r=this.usagePatterns.get(t);r.count++;const s=r.next.get(e)||0;r.next.set(e,s+1)}}isStaticAsset(e){return/\.(js|css|png|jpg|jpeg|gif|svg|woff|woff2|ttf|ico)$/i.test(e.pathname)}isApiEndpoint(e){return e.pathname.startsWith("/api/")||e.pathname.startsWith("/graphql")}matchesPattern(e,t){return"string"==typeof t?e.includes(t):t instanceof RegExp&&t.test(e)}shouldPreCache(){return"low"===this.carbonData.intensity&&navigator.onLine}shouldRevalidate(){return"high"!==this.carbonData.intensity&&navigator.onLine}getNetworkCondition(){if(navigator.connection){const e=navigator.connection.effectiveType;return["slow-2g","2g"].includes(e)?"slow":"fast"}return"unknown"}setupMaintenanceSchedule(){setInterval(()=>{this.performMaintenance()},36e5)}setupCarbonUpdates(){setInterval(()=>{this.updateCarbonData()},18e5)}async performMaintenance(){await this.cleanupExpiredEntries(),await this.optimizeCacheSize(),await this.saveCacheStats(),await this.saveUsagePatterns()}async loadCacheStats(){try{const e=d.getLocalStorage().getItem("aether-cache-stats");e&&(this.stats={...this.stats,...JSON.parse(e)})}catch(e){console.warn("Failed to load cache stats:",e)}}async saveCacheStats(){try{d.getLocalStorage().setItem("aether-cache-stats",JSON.stringify(this.stats))}catch(e){console.warn("Failed to save cache stats:",e)}}async loadUsagePatterns(){try{const e=localStorage.getItem("aether-usage-patterns");if(e){const t=JSON.parse(e);this.usagePatterns=new Map(t)}}catch(e){console.warn("Failed to load usage patterns:",e)}}async saveUsagePatterns(){try{const e=Array.from(this.usagePatterns.entries());localStorage.setItem("aether-usage-patterns",JSON.stringify(e))}catch(e){console.warn("Failed to save usage patterns:",e)}}getStats(){const e=this.stats.hits/(this.stats.hits+this.stats.misses)||0;return{...this.stats,hitRate:Math.round(100*e),carbonIntensity:this.carbonData.intensity,renewablePercentage:this.carbonData.renewablePercentage,patternsLearned:this.usagePatterns.size,recentAccesses:this.accessHistory.length}}}class g{constructor(e={}){this.options={enableCarbonAwareness:!1!==e.enableCarbonAwareness,carbonApiKey:e.carbonApiKey,carbonApiUrl:e.carbonApiUrl||"https://api.carbonintensity.org.uk",maxDelayHours:e.maxDelayHours||24,urgentThreshold:e.urgentThreshold||3e5,batchSize:e.batchSize||10,...e},this.taskQueue={urgent:[],high:[],normal:[],low:[],background:[]},this.carbonData={current:{intensity:"medium",forecast:[]},lastUpdate:0,updateInterval:18e5,history:[]},this.conditions={network:"unknown",battery:"unknown",charging:!1,connectionType:"unknown"},this.stats={tasksScheduled:0,tasksExecuted:0,carbonSaved:0,energySaved:0,averageDelay:0},this.initialize()}async initialize(){await this.updateCarbonData(),this.updateDeviceConditions(),this.setupPeriodicUpdates(),this.startScheduler()}async scheduleTask(e,t="normal",n={}){["urgent","high","normal","low","background"].includes(t)||(console.warn(`Invalid priority "${t}", using "normal" instead`),t="normal");const r={id:this.generateTaskId(),...e,priority:t,scheduledAt:Date.now(),options:{maxDelay:n.maxDelay||this.getMaxDelayForPriority(t),carbonAware:!1!==n.carbonAware,networkAware:!1!==n.networkAware,batteryAware:!1!==n.batteryAware,...n},attempts:0,lastAttempt:null,estimatedCarbonCost:this.estimateCarbonCost(e),estimatedDuration:n.estimatedDuration||1e3};return this.taskQueue[t].push(r),this.stats.tasksScheduled++,"urgent"===t?this.executeTask(r):(this.scheduleOptimalExecution(r),r.id)}async scheduleBatch(e,t="normal",n={}){const r={id:this.generateTaskId(),type:"batch",tasks:e,priority:t,scheduledAt:Date.now(),options:{batchSize:n.batchSize||this.options.batchSize,...n},estimatedCarbonCost:e.reduce((e,t)=>e+this.estimateCarbonCost(t),0),estimatedDuration:e.reduce((e,t)=>e+(t.estimatedDuration||1e3),0)};return this.scheduleTask(r,t,n)}async updateCarbonData(){if(this.options.enableCarbonAwareness)try{const e=await this.fetchCarbonIntensity();if(e){this.carbonData.current=e,this.carbonData.lastUpdate=Date.now(),this.carbonData.history.push({timestamp:Date.now(),intensity:e.intensity,value:e.value||0});const t=Date.now()-864e5;this.carbonData.history=this.carbonData.history.filter(e=>e.timestamp>t)}}catch(e){console.warn("Failed to update carbon data, using fallback:",e),this.useFallbackCarbonData()}else this.carbonData.current.intensity="medium"}async fetchCarbonIntensity(){if(!this.options.carbonApiUrl)return this.simulateCarbonIntensity();try{const e=await fetch(`${this.options.carbonApiUrl}/intensity`,{headers:this.options.carbonApiKey?{Authorization:`Bearer ${this.options.carbonApiKey}`}:{}});if(!e.ok)throw new Error(`Carbon API error: ${e.status}`);const t=await e.json();return this.parseCarbonApiResponse(t)}catch(e){return console.warn("Carbon API request failed:",e),this.simulateCarbonIntensity()}}simulateCarbonIntensity(){const e=(new Date).getHours(),t=(new Date).getDay();let n,r;const s=0===t||6===t;return e>=10&&e<=16?(n="low",r=s?150:200):e>=18&&e<=21?(n="high",r=s?350:450):e>=22||e<=6?(n="medium",r=s?250:300):(n="medium",r=s?200:280),{intensity:n,value:r,forecast:this.generateForecast(r),timestamp:Date.now()}}generateForecast(e){const t=[];let n=e;for(let e=1;e<=24;e++){const r=((new Date).getHours()+e)%24,s=50*(Math.random()-.5);n=r>=10&&r<=16?Math.max(100,n-30+s):r>=18&&r<=21?Math.min(500,n+50+s):Math.max(100,Math.min(400,n+s)),t.push({hour:r,value:Math.round(n),intensity:this.valueToIntensity(n)})}return t}valueToIntensity(e){return e<200?"low":e<350?"medium":"high"}updateDeviceConditions(){const e=d.getNavigator(),t=p.getNetworkInfo();this.conditions.network=t.effectiveType,this.conditions.connectionType=t.effectiveType,e.getBattery?e.getBattery().then(e=>{this.conditions.battery=e.level,this.conditions.charging=e.charging}).catch(()=>{this.conditions.battery=1,this.conditions.charging=!0}):(this.conditions.battery=1,this.conditions.charging=!0)}scheduleOptimalExecution(e){const t=this.findOptimalExecutionTime(e),n=Math.max(0,t-Date.now());0===n?this.executeTask(e):setTimeout(()=>{this.executeTask(e)},n)}findOptimalExecutionTime(e){const t=Date.now(),n=t+e.options.maxDelay;if("urgent"===e.priority)return t;if(!e.options.carbonAware)return t+this.getPriorityDelay(e.priority);const r=this.carbonData.current.forecast||[];let s=t,i=this.calculateExecutionScore(t,e);for(const a of r){const r=t+60*a.hour*60*1e3;if(r>n)continue;const o=this.calculateExecutionScore(r,e,a);o>i&&(i=o,s=r)}return s}calculateExecutionScore(e,t,n=null){let r=100;switch(n?n.intensity:this.carbonData.current.intensity){case"low":r+=50;break;case"medium":r+=20;break;case"high":r-=30}if(r-=5*((e-Date.now())/36e5),t.options.networkAware)switch(this.conditions.network){case"4g":case"wifi":r+=10;break;case"3g":r+=5;break;case"2g":case"slow-2g":r-=20}return t.options.batteryAware&&"unknown"!==this.conditions.battery&&(this.conditions.charging?r+=15:this.conditions.battery<.2?r-=25:this.conditions.battery<.5&&(r-=10)),r}async executeTask(e){try{let t;return e.attempts++,e.lastAttempt=Date.now(),console.log(`🚀 Executing task ${e.id} (${e.type}) - Carbon: ${this.carbonData.current.intensity}`),t="batch"===e.type?await this.executeBatchTask(e):await e.execute(e.data),this.stats.tasksExecuted++,this.updateCarbonSavings(e),this.removeTaskFromQueue(e),console.log(`✅ Task ${e.id} completed successfully`),t}catch(t){if(console.error(`❌ Task ${e.id} failed:`,t),!(e.attempts<3))throw this.removeTaskFromQueue(e),t;{const t=1e3*Math.pow(2,e.attempts);setTimeout(()=>{this.executeTask(e)},t)}}}async executeBatchTask(e){const t=[],n=e.options.batchSize;for(let r=0;r<e.tasks.length;r+=n){const s=e.tasks.slice(r,r+n),i=await Promise.allSettled(s.map(e=>e.execute(e.data)));t.push(...i),r+n<e.tasks.length&&await new Promise(e=>setTimeout(e,100))}return t}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getMaxDelayForPriority(e){switch(e){case"urgent":return 0;case"high":return 36e5;case"normal":default:return 216e5;case"low":return 864e5;case"background":return 6048e5}}getPriorityDelay(e){switch(e){case"urgent":return 0;case"high":return 3e5;case"normal":default:return 18e5;case"low":return 72e5;case"background":return 216e5}}estimateCarbonCost(e){return 10*this.getTaskTypeFactor(e.type)*((e.estimatedDuration||1e3)/1e3)}getTaskTypeFactor(e){const t={sync:2,upload:3,download:2.5,compute:1.5,batch:2.5,default:1};return t[e]||t.default}updateCarbonSavings(e){const t=this.carbonData.current.intensity,n=this.calculateCarbonSavings(e,t);this.stats.carbonSaved+=n}calculateCarbonSavings(e,t){const n="low"===t?.7:"medium"===t?1:1.3,r=1.5*e.estimatedCarbonCost,s=e.estimatedCarbonCost*n;return Math.max(0,r-s)}removeTaskFromQueue(e){for(const t in this.taskQueue){const n=this.taskQueue[t].findIndex(t=>t.id===e.id);if(-1!==n){this.taskQueue[t].splice(n,1);break}}}setupPeriodicUpdates(){setInterval(()=>{this.updateCarbonData()},this.carbonData.updateInterval),setInterval(()=>{this.updateDeviceConditions()},3e5)}startScheduler(){setInterval(()=>{this.processQueues()},6e4)}processQueues(){for(const e in this.taskQueue){const t=this.taskQueue[e];for(const e of t){this.shouldExecuteNow(e)&&this.executeTask(e)}}}shouldExecuteNow(e){const t=Date.now();if(t>=e.scheduledAt+e.options.maxDelay)return!0;return this.calculateExecutionScore(t,e)>80}useFallbackCarbonData(){this.carbonData.current=this.simulateCarbonIntensity()}parseCarbonApiResponse(e){return{intensity:this.valueToIntensity(e.intensity),value:e.intensity,forecast:e.forecast||[],timestamp:Date.now()}}getStats(){const e={};let t=0;for(const n in this.taskQueue)e[n]=this.taskQueue[n].length,t+=this.taskQueue[n].length;return{...this.stats,queueSizes:e,totalQueued:t,carbonIntensity:this.carbonData.current.intensity,carbonValue:this.carbonData.current.value,lastCarbonUpdate:this.carbonData.lastUpdate,conditions:this.conditions}}getCarbonData(){return this.carbonData.current}async forceExecuteAll(){const e=[];for(const t in this.taskQueue)e.push(...this.taskQueue[t]),this.taskQueue[t]=[];return await Promise.allSettled(e.map(e=>this.executeTask(e)))}async enableCityWideOptimization(e){return console.log("🌱🏙️ Enabling city-wide carbon optimization..."),this.cityWideOptimization={...e,enabled:!0},this.cityWideOptimization}async configureRenewableOptimization(e){return console.log("🌱⚡ Configuring renewable energy optimization..."),this.renewableOptimization={...e,configured:!0},this.renewableOptimization}async enableCarbonNeutralityTracking(e){return console.log("🌱📊 Enabling carbon neutrality tracking..."),this.carbonNeutralityTracking={...e,enabled:!0},this.carbonNeutralityTracking}async monitorCarbonEmissions(){return{totalEmissions:1e3+500*Math.random(),emissionRate:50+30*Math.random(),reductionTarget:.5,currentReduction:.3+.2*Math.random()}}async checkRenewableStatus(){return{solarGeneration:200+100*Math.random(),windGeneration:150+80*Math.random(),renewablePercentage:.6+.3*Math.random(),gridStability:"stable"}}async calculateSustainabilityMetrics(){return{carbonFootprint:800+400*Math.random(),energyEfficiency:.8+.15*Math.random(),renewableRatio:.7+.2*Math.random(),sustainabilityScore:85+10*Math.random()}}async optimizeEmergencyOperations(e){return console.log("🚨 Optimizing emergency operations for carbon efficiency..."),{emergencyType:e.type||"general",carbonOptimizedRouting:"enabled",renewableEmergencyPower:"activated",sustainableResponse:"prioritized",carbonImpact:"minimized"}}getStatus(){return this.getStats()}}const f={IDLE:"idle",SYNCING:"syncing",ERROR:"error",SYNCED:"synced",OFFLINE:"offline"},m={STATUS_CHANGE:"sync-status-change",PROGRESS_UPDATE:"sync-progress-update",MUTATION_SYNCED:"mutation-synced",SYNC_ERROR:"sync-error",QUEUE_UPDATED:"queue-updated"};class w{constructor(e={}){this.options={autoSync:!0,syncOnOnline:!0,trackSyncState:!0,...e},this.isOnline="undefined"!=typeof window&&"undefined"!=typeof navigator&&navigator.onLine,this.syncEngine=null,this.syncState=null,this.eventListeners=[],this.setupNetworkListeners(),this.initialize()}initialize(){}setupNetworkListeners(){if("undefined"!=typeof window&&window&&window.addEventListener){const e=()=>{this.isOnline=!0,this.onOnline(),this.options.syncOnOnline&&this.syncEngine&&this.syncEngine.processQueue()},t=()=>{this.isOnline=!1,this.onOffline()};window.addEventListener("online",e),window.addEventListener("offline",t),this.eventListeners.push({element:window,event:"online",handler:e},{element:window,event:"offline",handler:t})}}connectSyncEngine(e){if(this.disconnectSyncEngine(),this.syncEngine=e,this.options.trackSyncState){const t=e.subscribeSyncState(e=>{this.syncState=e,this.onSyncStateChange(e)}),n=[e.addEventListener(m.STATUS_CHANGE,e=>{this.onSyncStatusChange(e.status,e)}),e.addEventListener(m.PROGRESS_UPDATE,e=>{this.onSyncProgress(e)}),e.addEventListener(m.SYNC_ERROR,e=>{this.onSyncError(e)}),e.addEventListener(m.MUTATION_SYNCED,e=>{this.onMutationSynced(e)})];this.syncUnsubscribers=[t,...n]}}disconnectSyncEngine(){this.syncUnsubscribers&&(this.syncUnsubscribers.forEach(e=>e()),this.syncUnsubscribers=null),this.syncEngine=null,this.syncState=null}onOffline(){}onOnline(){}onSyncStateChange(e){}onSyncStatusChange(e,t){}onSyncProgress(e){}onSyncError(e){}onMutationSynced(e){}getNetworkState(){return{isOnline:this.isOnline,isOffline:!this.isOnline,connectionType:"undefined"!=typeof navigator&&navigator.connection?navigator.connection.effectiveType:"unknown"}}getSyncState(){return this.syncState}isSyncStatus(e){return this.syncState&&this.syncState.status===e}get isSyncing(){return!!this.syncState&&this.isSyncStatus(f.SYNCING)}get hasSyncErrors(){return!!this.syncState&&this.isSyncStatus(f.ERROR)}get isSynced(){return!!this.syncState&&this.isSyncStatus(f.SYNCED)}get isOfflineMode(){return!!this.syncState&&this.isSyncStatus(f.OFFLINE)}async triggerSync(){if(this.syncEngine&&this.isOnline)return this.syncEngine.processQueue()}async addMutation(e){if(this.syncEngine)return this.syncEngine.addMutation(e)}destroy(){this.disconnectSyncEngine(),this.eventListeners.forEach(({element:e,event:t,handler:n})=>{e.removeEventListener(t,n)}),this.eventListeners=[],this.onDestroy()}onDestroy(){}}function S(e,t=null){if("undefined"==typeof React)return function(e,t=null){e.get();let n=[];const r=()=>{const n=e.get();return t?t(n):n},s=r=>{n.push(r);const s=e.subscribe(e=>{const r=t?t(e):e;n.forEach(e=>{try{e(r)}catch(e){console.error("Error in useAetherStore listener:",e)}})});return()=>{const e=n.indexOf(r);e>-1&&n.splice(e,1),0===n.length&&s()}};return{value:r(),subscribe:s,get:r}}(e,t);const[n,r]=React.useState(()=>{const n=e.get();return t?t(n):n});return React.useEffect(()=>e.subscribe(e=>{const n=t?t(e):e;r(n)}),[e,t]),n}function b(e,t,n={}){if("undefined"==typeof React)return function(e,t){const{PersistentStore:n}=require("../data/PersistentStore.js"),r=new n(e,t),s=e=>{"function"==typeof e?r.update(e):r.set(e)};return{store:r,setValue:s,getValue:()=>r.get(),subscribe:e=>r.subscribe(e)}}(e,t,n);const[r]=React.useState(()=>{const{PersistentStore:n}=require("../data/PersistentStore.js");return new n(e,t)});return[S(r),React.useCallback(e=>{"function"==typeof e?r.update(e):r.set(e)},[r]),r]}const v={SUSTAINABILITY:{name:"Sustainability First",description:"Carbon-aware computing and green software practices",priority:1,features:["carbon-aware-scheduling","energy-efficient-algorithms","green-metrics-tracking","renewable-energy-optimization"]},ACCESSIBILITY:{name:"Accessibility First",description:"Universal design and inclusive user experiences",priority:1,features:["wcag-compliance","screen-reader-optimization","keyboard-navigation","cognitive-accessibility","multi-modal-interfaces"]},PERFORMANCE:{name:"Performance First",description:"Quantum-ready optimization and edge computing",priority:1,features:["quantum-algorithms","edge-computing-optimization","predictive-caching","adaptive-performance-scaling"]},SECURITY:{name:"Security First",description:"Zero-trust architecture and quantum-resistant encryption",priority:1,features:["zero-trust-by-default","quantum-resistant-crypto","homomorphic-encryption","secure-multi-party-computation"]},RESILIENCE:{name:"Resilience First",description:"Fault-tolerant systems and graceful degradation",priority:1,features:["chaos-engineering","graceful-degradation","self-healing-systems","distributed-consensus"]},PRIVACY:{name:"Privacy First",description:"Data sovereignty and user control",priority:1,features:["differential-privacy","federated-learning","local-first-data","user-controlled-sharing"]},INCLUSIVITY:{name:"Inclusivity First",description:"Bias-free AI and equitable technology",priority:1,features:["bias-detection","fairness-metrics","diverse-training-data","ethical-ai-guidelines"]}};class E{constructor(e=Object.keys(v)){this.enabledPrinciples=e,this.violations=[]}validateComponent(e,t={}){const n=[];for(const r of this.enabledPrinciples){const s=v[r],i=this.validatePrinciple(e,s,t);i.isValid||n.push({principle:r,violations:i.violations,severity:i.severity})}return{isValid:0===n.length,violations:n,score:this.calculateComplianceScore(n)}}validatePrinciple(e,t,n){const r=[];switch(t.name){case"Sustainability First":r.push(...this.validateSustainability(e,n));break;case"Accessibility First":r.push(...this.validateAccessibility(e,n));break;case"Performance First":r.push(...this.validatePerformance(e,n));break;case"Security First":r.push(...this.validateSecurity(e,n));break;case"Resilience First":r.push(...this.validateResilience(e,n));break;case"Privacy First":r.push(...this.validatePrivacy(e,n));break;case"Inclusivity First":r.push(...this.validateInclusivity(e,n))}return{isValid:0===r.length,violations:r,severity:this.calculateSeverity(r)}}validateSustainability(e,t){const n=[];return e.carbonAwareScheduler||t.skipCarbonAware||n.push({type:"missing-carbon-awareness",message:"Component should use carbon-aware scheduling",suggestion:"Add CarbonAwareScheduler integration"}),e.energyProfile&&e.energyProfile.efficiency<.7&&n.push({type:"low-energy-efficiency",message:"Component energy efficiency below threshold",suggestion:"Optimize algorithms for lower energy consumption"}),n}validateAccessibility(e,t){const n=[];return e.render&&!t.hasAriaSupport&&n.push({type:"missing-aria-support",message:"Component should include ARIA attributes",suggestion:"Add proper ARIA labels and roles"}),e.interactive&&!t.keyboardAccessible&&n.push({type:"missing-keyboard-support",message:"Interactive component should support keyboard navigation",suggestion:"Add keyboard event handlers and focus management"}),n}validatePerformance(e,t){const n=[];return e.performanceMonitor||t.skipPerformanceMonitoring||n.push({type:"missing-performance-monitoring",message:"Component should include performance monitoring",suggestion:"Add PerformanceOptimizer integration"}),n}validateSecurity(e,t){const n=[];return e.acceptsInput&&!t.hasInputValidation&&n.push({type:"missing-input-validation",message:"Component should validate all inputs",suggestion:"Add comprehensive input sanitization"}),n}validateResilience(e,t){const n=[];return e.errorBoundary||t.hasErrorHandling||n.push({type:"missing-error-boundary",message:"Component should include error boundaries",suggestion:"Add comprehensive error handling"}),n}validatePrivacy(e,t){const n=[];return e.handlesUserData&&!t.hasPrivacyControls&&n.push({type:"missing-privacy-controls",message:"Component should include privacy controls",suggestion:"Add user consent and data control mechanisms"}),n}validateInclusivity(e,t){const n=[];return e.usesAI&&!t.hasBiasDetection&&n.push({type:"missing-bias-detection",message:"AI components should include bias detection",suggestion:"Add fairness metrics and bias monitoring"}),n}calculateComplianceScore(e){if(0===e.length)return 100;const t=5*this.enabledPrinciples.length,n=e.reduce((e,t)=>e+t.violations.length,0);return Math.max(0,Math.round(100*(1-n/t)))}calculateSeverity(e){return 0===e.length?"none":e.length<=2?"low":e.length<=5?"medium":"high"}}function A(e={}){return function(t){if("function"!=typeof t)throw new Error("withPrinciples decorator can only be applied to classes or functions");class n extends t{constructor(...n){super(...n),this.principleValidator=new E(e.enabledPrinciples),this.principleMetadata={...e.metadata,componentName:t.name},this.validatePrinciples()}validatePrinciples(){const t=this.principleValidator.validateComponent(this,this.principleMetadata);if(!t.isValid&&e.strict)throw new Error(`Component ${this.principleMetadata.componentName} violates Aether principles: ${t.violations.map(e=>e.violations.map(e=>e.message).join(", ")).join("; ")}`);return this.principleCompliance=t,t}getPrincipleCompliance(){return this.principleCompliance}}return Object.defineProperty(n,"name",{value:`PrincipleAware${t.name}`,configurable:!0}),n}}const C={NONE:0,BASIC:1,ADAPTIVE:2,PREDICTIVE:3,AUTONOMOUS:4,SYMBIOTIC:5},k={TRANSPARENCY:"AI decisions must be explainable",FAIRNESS:"AI must not discriminate or show bias",PRIVACY:"AI must respect user privacy and data sovereignty",AGENCY:"Users must maintain control and override capability",BENEFICENCE:"AI must benefit users and society",NON_MALEFICENCE:"AI must not cause harm"};class R{constructor(e={}){this.aiLevel=e.aiLevel||C.BASIC,this.ethicsConfig={...k,...e.ethics},this.learningEnabled=!1!==e.learningEnabled,this.userConsent=e.userConsent||!1,this.behaviorPatterns=new Map,this.userPreferences=new Map,this.adaptationHistory=[],this.biasMetrics=new Map,this.humanOverrides=new Map,this.explainabilityLog=[],this.initializeAI()}initializeAI(){this.aiLevel>=C.BASIC&&this.setupPatternRecognition(),this.aiLevel>=C.ADAPTIVE&&this.setupAdaptiveLearning(),this.aiLevel>=C.PREDICTIVE&&this.setupPredictiveCapabilities(),this.aiLevel>=C.AUTONOMOUS&&this.setupAutonomousFeatures(),this.aiLevel>=C.SYMBIOTIC&&this.setupSymbioticInterface()}setupPatternRecognition(){this.patternRecognizer={recordInteraction:e=>{const t=this.extractPattern(e),n=this.behaviorPatterns.get(t.key)||{count:0,contexts:[]};this.behaviorPatterns.set(t.key,{count:n.count+1,contexts:[...n.contexts,t.context].slice(-10),lastSeen:Date.now()}),this.logExplanation("pattern_recorded",{pattern:t.key,reason:"User interaction recorded for pattern analysis"})},getCommonPatterns:()=>Array.from(this.behaviorPatterns.entries()).filter(([e,t])=>t.count>=3).sort((e,t)=>t[1].count-e[1].count).slice(0,5)}}setupAdaptiveLearning(){this.adaptiveLearner={adapt:e=>{if(!this.userConsent||!this.learningEnabled)return null;const t=this.patternRecognizer.getCommonPatterns(),n=this.generateAdaptation(t,e);return n&&this.validateAdaptation(n)?(this.adaptationHistory.push({timestamp:Date.now(),adaptation:n,context:e,applied:!1}),this.logExplanation("adaptation_suggested",{adaptation:n.type,reason:n.reasoning,confidence:n.confidence}),n):null},applyAdaptation:(e,t=!1)=>{const n=this.adaptationHistory.find(t=>t.id===e);return!!n&&(!!(t||n.confidence>.8)&&(n.applied=!0,this.logExplanation("adaptation_applied",{adaptation:n.adaptation.type,userApproved:t,reason:"Adaptation applied based on learned patterns"}),!0))}}}setupPredictiveCapabilities(){this.predictor={predictNextAction:e=>{const t=this.patternRecognizer.getCommonPatterns(),n=this.generatePrediction(t,e);return this.logExplanation("prediction_made",{prediction:n.action,confidence:n.confidence,reasoning:n.reasoning}),n},predictUserNeeds:e=>{const t=this.analyzeTemporalPatterns(e),n=this.inferUserNeeds(t);return this.logExplanation("needs_predicted",{needs:n.map(e=>e.type),reasoning:"Based on temporal usage patterns"}),n}}}setupAutonomousFeatures(){this.autonomousAgent={autoOptimize:()=>{if(!this.hasUserPermission("auto_optimize"))return!1;const e=this.identifyOptimizations().filter(e=>"low"===e.risk);return e.forEach(e=>{this.applyOptimization(e),this.logExplanation("auto_optimization",{optimization:e.type,reason:e.reasoning,impact:e.expectedImpact})}),e.length>0},selfHeal:e=>{const t=this.generateHealingStrategy(e);if(t&&t.confidence>.9){const n=this.applyHealing(t);return this.logExplanation("self_healing",{error:e.type,strategy:t.type,success:n.success,reason:"Autonomous error recovery"}),n}return{success:!1,reason:"No safe healing strategy found"}}}}setupSymbioticInterface(){this.symbioticInterface={collaborativeDecision:(e,t)=>{const n=this.generateRecommendation(e,t),r=this.requestHumanInput(e,n),s=this.synthesizeDecision(n,r);return this.logExplanation("collaborative_decision",{decision:e.type,aiRecommendation:n.choice,humanInput:r.choice,finalDecision:s.choice,reasoning:s.reasoning}),s},explainDecision:e=>{const t=this.explainabilityLog.find(t=>t.decisionId===e);return t?this.generateHumanReadableExplanation(t):null}}}detectBias(e,t){const n=[this.checkDemographicBias(e,t),this.checkConfirmationBias(e,t),this.checkAvailabilityBias(e,t),this.checkAnchoringBias(e,t)],r=n.reduce((e,t)=>e+t.score,0)/n.length;return this.biasMetrics.set(Date.now(),{decision:e.type,biasScore:r,checks:n,context:t}),r>.7?(this.logExplanation("bias_detected",{biasScore:r,checks:n.filter(e=>e.score>.5),mitigation:"Decision flagged for human review"}),{hasBias:!0,score:r,checks:n}):{hasBias:!1,score:r}}enableHumanOverride(e,t){const n=`override_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return this.humanOverrides.set(n,{component:e,reason:t,timestamp:Date.now(),active:!0}),this.logExplanation("human_override",{component:e,reason:t,overrideId:n,message:"Human has taken control of AI decision-making"}),n}logExplanation(e,t){this.explainabilityLog.push({id:`exp_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now(),type:e,details:t,aiLevel:this.aiLevel}),this.explainabilityLog.length>1e3&&(this.explainabilityLog=this.explainabilityLog.slice(-1e3))}requestConsent(e,t){return new Promise(e=>{setTimeout(()=>{e(!0)},100)})}getAIStatus(){return{level:this.aiLevel,learningEnabled:this.learningEnabled,userConsent:this.userConsent,patternsLearned:this.behaviorPatterns.size,adaptationsApplied:this.adaptationHistory.filter(e=>e.applied).length,biasScore:this.calculateOverallBiasScore(),humanOverrides:this.humanOverrides.size,explainabilityEntries:this.explainabilityLog.length}}extractPattern(e){return{key:`${e.type}_${e.target}`,context:e.context}}generateAdaptation(e,t){return{id:`adapt_${Date.now()}`,type:"ui_optimization",reasoning:"Based on usage patterns",confidence:.75}}validateAdaptation(e){return e.confidence>.5}calculateOverallBiasScore(){if(0===this.biasMetrics.size)return 0;const e=Array.from(this.biasMetrics.values()).map(e=>e.biasScore);return e.reduce((e,t)=>e+t,0)/e.length}checkDemographicBias(e,t){return{type:"demographic",score:.1}}checkConfirmationBias(e,t){return{type:"confirmation",score:.2}}checkAvailabilityBias(e,t){return{type:"availability",score:.15}}checkAnchoringBias(e,t){return{type:"anchoring",score:.1}}hasUserPermission(e){return this.userConsent}}const D={TRACE:0,INFO:1,WARNING:2,ERROR:3,CRITICAL:4,FATAL:5},I={RETRY:"retry",FALLBACK:"fallback",GRACEFUL_DEGRADATION:"graceful_degradation",USER_INTERVENTION:"user_intervention",SYSTEM_RESTART:"system_restart",SAFE_MODE:"safe_mode"};class P{constructor(e={}){this.options={maxRetries:3,retryDelay:1e3,enablePrediction:!0,enableSelfHealing:!0,enableLearning:!0,fallbackComponent:null,onError:null,...e},this.errorHistory=[],this.errorPatterns=new Map,this.recoveryAttempts=new Map,this.healingStrategies=new Map,this.errorPredictors=new Map,this.riskFactors=new Map,this.performanceMetrics={errorRate:0,recoveryRate:0,meanTimeToRecovery:0,userImpact:0},this.initializeErrorBoundary()}initializeErrorBoundary(){this.setupGlobalErrorHandling(),this.setupPredictiveSystem(),this.setupSelfHealingSystem(),this.setupPerformanceMonitoring()}setupGlobalErrorHandling(){"undefined"!=typeof window&&(window.addEventListener("unhandledrejection",e=>{this.handleError(e.reason,{type:"unhandled_promise_rejection",source:"global"})}),window.addEventListener("error",e=>{this.handleError(e.error,{type:"global_error",source:e.filename,line:e.lineno,column:e.colno})}))}setupPredictiveSystem(){this.options.enablePrediction&&(this.errorPredictor={analyzeRiskFactors:e=>{const t=this.calculateRiskScore(e);return t>.7&&this.preventiveAction(e,t),t},predictErrorProbability:(e,t)=>{const n=this.getHistoricalErrorData(e),r=this.assessContextualRisk(t);return this.combineRiskFactors(n,r)},recommendPreventiveMeasures:(e,t)=>{const n=[];return e>.8&&n.push({type:"circuit_breaker",description:"Temporarily disable risky operations",priority:"high"}),e>.6&&n.push({type:"resource_allocation",description:"Allocate additional resources",priority:"medium"}),e>.4&&n.push({type:"monitoring_increase",description:"Increase monitoring frequency",priority:"low"}),n}})}setupSelfHealingSystem(){this.options.enableSelfHealing&&(this.selfHealer={diagnose:(e,t)=>{const n={errorType:this.classifyError(e),severity:this.assessSeverity(e,t),rootCause:this.identifyRootCause(e,t),affectedSystems:this.identifyAffectedSystems(e,t),healingStrategy:null};return n.healingStrategy=this.selectHealingStrategy(n),n},heal:async e=>{const t=e.healingStrategy;try{const n=await this.executeHealingStrategy(t,e);return n.success?this.recordSuccessfulHealing(e,t,n):this.escalateHealing(e,n),n}catch(e){return{success:!1,error:e,requiresEscalation:!0}}},learn:(e,t,n)=>{if(!this.options.enableLearning)return;const r={errorPattern:this.extractErrorPattern(e),strategy:t.type,success:n.success,context:e.context,timestamp:Date.now()};this.updateHealingKnowledge(r)}})}setupPerformanceMonitoring(){this.performanceMonitor={trackError:(e,t)=>{this.performanceMetrics.errorRate=this.calculateErrorRate()},trackRecovery:e=>{this.performanceMetrics.recoveryRate=this.calculateRecoveryRate(),this.performanceMetrics.meanTimeToRecovery=this.calculateMTTR()},trackUserImpact:e=>{this.performanceMetrics.userImpact=this.calculateUserImpact(e)},generateReport:()=>({...this.performanceMetrics,totalErrors:this.errorHistory.length,uniqueErrorTypes:new Set(this.errorHistory.map(e=>e.type)).size,healingSuccessRate:this.calculateHealingSuccessRate(),timestamp:Date.now()})}}async handleError(e,t={}){const n={id:this.generateErrorId(),error:e,context:t,timestamp:Date.now(),severity:this.assessSeverity(e,t),handled:!1,recovered:!1};this.errorHistory.push(n),this.updateErrorPatterns(n);try{const e=await this.attemptRecovery(n);return n.recovered=e.success,n.recoveryStrategy=e.strategy,e.success?(this.performanceMonitor.trackRecovery(e),e):this.handleRecoveryFailure(n,e)}catch(e){return this.handleCriticalFailure(n,e)}}async attemptRecovery(e){const{error:t,context:n}=e,r=this.findKnownErrorPattern(t);if(r&&r.successfulStrategy)return this.executeRecoveryStrategy(r.successfulStrategy,e);if(this.options.enableSelfHealing){const e=this.selfHealer.diagnose(t,n),r=await this.selfHealer.heal(e);if(r.success)return this.selfHealer.learn(e,e.healingStrategy,r),{success:!0,strategy:I.FALLBACK,method:"self_healing",result:r}}const s=this.getRecoveryStrategies(e);for(const t of s)try{const n=await this.executeRecoveryStrategy(t,e);if(n.success)return this.recordSuccessfulStrategy(e,t),n}catch(e){continue}return{success:!1,strategy:null,reason:"All recovery strategies failed"}}async executeRecoveryStrategy(e,t){switch(e.type){case I.RETRY:return this.executeRetryStrategy(e,t);case I.FALLBACK:return this.executeFallbackStrategy(e,t);case I.GRACEFUL_DEGRADATION:return this.executeGracefulDegradation(e,t);case I.USER_INTERVENTION:return this.requestUserIntervention(e,t);case I.SAFE_MODE:return this.enterSafeMode(e,t);default:throw new Error(`Unknown recovery strategy: ${e.type}`)}}async executeRetryStrategy(e,t){const n=e.maxRetries||this.options.maxRetries,r=e.delay||this.options.retryDelay;for(let e=1;e<=n;e++)try{await this.delay(r*e);const n=await this.retryOperation(t);return{success:!0,strategy:I.RETRY,attempts:e,result:n}}catch(t){if(e===n)return{success:!1,strategy:I.RETRY,attempts:e,error:t}}}async executeFallbackStrategy(e,t){try{const n=e.fallback||this.options.fallbackComponent;if(!n)return{success:!1,strategy:I.FALLBACK,reason:"No fallback component available"};const r=await this.activateFallback(n,t);return{success:!0,strategy:I.FALLBACK,fallback:n,result:r}}catch(e){return{success:!1,strategy:I.FALLBACK,error:e}}}async executeGracefulDegradation(e,t){try{const e=this.identifyDegradableFeatures(t),n=this.identifyEssentialFeatures(t);return await this.disableFeatures(e),await this.ensureEssentialFeatures(n),{success:!0,strategy:I.GRACEFUL_DEGRADATION,degradedFeatures:e,essentialFeatures:n}}catch(e){return{success:!1,strategy:I.GRACEFUL_DEGRADATION,error:e}}}getStatus(){return{errorHistory:this.errorHistory.slice(-10),errorPatterns:Array.from(this.errorPatterns.entries()),performanceMetrics:this.performanceMonitor.generateReport(),healingStrategies:Array.from(this.healingStrategies.entries()),options:this.options}}generateErrorId(){return`err_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}assessSeverity(e,t){return"TypeError"===e.name?D.ERROR:"ReferenceError"===e.name?D.CRITICAL:D.WARNING}calculateRiskScore(e){return.5*Math.random()}delay(e){return new Promise(t=>setTimeout(t,e))}async retryOperation(e){return{success:!0,retried:!0}}async activateFallback(e,t){return{fallbackActivated:!0,component:e}}identifyDegradableFeatures(e){return["animations","advanced_ui","non_critical_apis"]}identifyEssentialFeatures(e){return["core_functionality","data_access","user_interface"]}async disableFeatures(e){return{disabled:e}}async ensureEssentialFeatures(e){return{ensured:e}}calculateErrorRate(){return this.errorHistory.filter(e=>Date.now()-e.timestamp<6e4).length}calculateRecoveryRate(){const e=this.errorHistory.filter(e=>e.recovered);return this.errorHistory.length>0?e.length/this.errorHistory.length:0}calculateMTTR(){const e=this.errorHistory.filter(e=>e.recovered&&e.recoveryTime);if(0===e.length)return 0;return e.reduce((e,t)=>e+t.recoveryTime,0)/e.length}calculateUserImpact(e){return e.severity*e.affectedUsers}calculateHealingSuccessRate(){const e=this.errorHistory.filter(e=>e.healingAttempted),t=e.filter(e=>e.healingSuccessful);return e.length>0?t.length/e.length:0}updateErrorPatterns(e){const t=this.extractErrorPattern(e),n=this.errorPatterns.get(t)||{count:0,lastSeen:0};this.errorPatterns.set(t,{count:n.count+1,lastSeen:Date.now(),errorType:e.error.name||"Unknown"})}extractErrorPattern(e){return`${e.error.name||"Unknown"}_${e.context.component||"Unknown"}`}findKnownErrorPattern(e){const t=`${e.name||"Unknown"}_Unknown`;return this.errorPatterns.get(t)}getRecoveryStrategies(e){return[{type:I.RETRY,maxRetries:3,delay:1e3},{type:I.FALLBACK,fallback:null},{type:I.GRACEFUL_DEGRADATION}]}recordSuccessfulStrategy(e,t){const n=this.extractErrorPattern(e),r=this.errorPatterns.get(n)||{};r.successfulStrategy=t,this.errorPatterns.set(n,r)}preventiveAction(e,t){console.warn(`High risk detected (${t}), taking preventive measures`)}getHistoricalErrorData(e){return{errorRate:.1,avgRecoveryTime:1e3}}assessContextualRisk(e){return.2}combineRiskFactors(e,t){return(e.errorRate+t)/2}classifyError(e){return e.name||"UnknownError"}identifyRootCause(e,t){return"Unknown root cause"}identifyAffectedSystems(e,t){return["component"]}selectHealingStrategy(e){return{type:I.RETRY,maxRetries:2}}async executeHealingStrategy(e,t){return{success:!0,method:e.type}}recordSuccessfulHealing(e,t,n){}escalateHealing(e,t){return{success:!1,escalated:!0}}updateHealingKnowledge(e){}handleRecoveryFailure(e,t){return{success:!1,reason:"Recovery failed",errorRecord:e}}handleCriticalFailure(e,t){return{success:!1,reason:"Critical failure",errorRecord:e,recoveryError:t}}}e.AETHER_PRINCIPLES=v,e.AI_AWARENESS_LEVELS=C,e.AI_ETHICS=k,e.AetherAIAware=R,e.AetherComponent=w,e.AetherErrorBoundary=P,e.AetherStore=t,e.CONFLICT_STRATEGIES={LAST_WRITE_WINS:"LastWriteWins",SERVER_WINS:"ServerWins"},e.CacheManager=y,e.CarbonAwareScheduler=g,e.ERROR_SEVERITY=D,e.EnvironmentDetector=h,e.FRAMEWORK_INFO={name:"Resilient.js (Aether.js)",version:"2.0.0",description:"Revolutionary offline-first framework with AI-awareness and principle-driven development",tagline:"The world's first principle-driven, AI-aware, carbon-conscious framework",features:["Offline-first architecture","Carbon-aware scheduling","Advanced state management","Intelligent sync engine","React integration","Progressive enhancement","Principle-driven development","AI-aware components","Self-healing error boundaries","Bias detection and mitigation","Quantum-ready architecture","Zero-trust security by default","Accessibility-first design"],frameworkFirsts:["Carbon-aware component scheduling","Built-in principle validation","AI-aware component adaptation","Predictive error p