UNPKG

turbo-map

Version:

High-performance, type-safe Map implementation supporting complex nested objects as keys, fully compatible with ES Map API

1,492 lines (1,483 loc) 111 kB
'use strict'; class TypeUtils { static isPrimitive(value) { return value === null || value === undefined || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'symbol' || typeof value === 'bigint'; } static isSimpleObject(value) { if (!value || typeof value !== 'object' || Array.isArray(value)) { return false; } if (value instanceof Date || value instanceof RegExp || value instanceof Error || value instanceof Map || value instanceof Set) { return false; } if (typeof value === 'function') { return false; } try { const keys = Object.keys(value); if (keys.length > 0) { const firstKey = keys[0]; if (firstKey !== undefined) { const descriptor = Object.getOwnPropertyDescriptor(value, firstKey); if (descriptor && (descriptor.get || descriptor.set)) { return false; } } } return keys.length <= 5 && keys.every(key => { const prop = value[key]; if (this.isPrimitive(prop) || prop === null) { return true; } if (typeof prop === 'object' && prop !== null) { return this.isSimpleObject(prop); } return false; }); } catch { return false; } } static getObjectSignature(obj) { if (this.isPrimitive(obj)) { return `primitive:${typeof obj}`; } if (Array.isArray(obj)) { const elementHash = obj.map(item => { if (typeof item === 'string') { return `str:${item}`; } else if (typeof item === 'number') { return `num:${item}`; } else if (typeof item === 'boolean') { return `bool:${item}`; } else if (item === null) { return 'null'; } else if (typeof item === 'object') { return this.getObjectSignature(item); } return typeof item; }).join(','); return `array:${obj.length}:${elementHash}`; } if (obj instanceof Date) { return 'date'; } if (obj instanceof RegExp) { return 'regexp'; } if (obj instanceof Error) { return 'error'; } if (typeof obj === 'function') { return 'function'; } try { const keys = Object.keys(obj).sort(); const keySignature = keys.slice(0, 3).join(','); const valueHash = keys.slice(0, 2).map(key => { const value = obj[key]; if (typeof value === 'string') { return `str:${value}`; } else if (typeof value === 'number') { return `num:${value}`; } else if (typeof value === 'boolean') { return `bool:${value}`; } else if (value === null) { return 'null'; } else if (typeof value === 'object') { return this.getObjectSignature(value); } return typeof value; }).join(','); return `object:${keys.length}:${keySignature}:${valueHash}`; } catch { return 'unknown'; } } static safeAccess(obj, accessor, fallback) { try { if (obj === null || obj === undefined) { return fallback; } const result = accessor(); return result !== undefined ? result : fallback; } catch { return fallback; } } static isSerializable(obj, visited = new WeakSet()) { try { if (this.isPrimitive(obj)) { if (typeof obj === 'symbol' || obj === undefined) { return false; } return true; } if (typeof obj === 'object' && obj !== null) { if (visited.has(obj)) { return false; } visited.add(obj); if (Array.isArray(obj)) { return obj.every(item => this.isSerializable(item, visited)); } return Object.values(obj).every(value => this.isSerializable(value, visited)); } return false; } catch { return false; } } } class ObjectPool { pool = []; createFn; resetFn; maxSize; constructor(createFn, resetFn = () => { }, maxSize = 100) { this.createFn = createFn; this.resetFn = resetFn; this.maxSize = maxSize; } acquire() { const obj = this.pool.pop(); if (obj) { return obj; } return this.createFn(); } release(obj) { try { if (this.pool.length < this.maxSize) { this.resetFn(obj); this.pool.push(obj); } } catch (error) { console.warn('ObjectPool: Error releasing object:', error); } } get size() { return this.pool.length; } clear() { this.pool.length = 0; } } class EnhancedObjectPool { weakSetPool = []; mapPool = []; arrayPool = []; objectPool = []; maxPoolSize = 50; getWeakSet() { const weakSet = this.weakSetPool.pop(); if (weakSet) { return weakSet; } return new WeakSet(); } releaseWeakSet(weakSet) { try { if (this.weakSetPool.length < this.maxPoolSize) { this.weakSetPool.push(weakSet); } } catch (error) { console.warn('EnhancedObjectPool: Error releasing WeakSet:', error); } } getMap() { const map = this.mapPool.pop(); if (map) { map.clear(); return map; } return new Map(); } releaseMap(map) { try { if (this.mapPool.length < this.maxPoolSize) { map.clear(); this.mapPool.push(map); } } catch (error) { console.warn('EnhancedObjectPool: Error releasing Map:', error); } } getArray() { const array = this.arrayPool.pop(); if (array) { array.length = 0; return array; } return []; } releaseArray(array) { try { if (this.arrayPool.length < this.maxPoolSize) { array.length = 0; this.arrayPool.push(array); } } catch (error) { console.warn('EnhancedObjectPool: Error releasing Array:', error); } } getObject() { const obj = this.objectPool.pop(); if (obj) { for (const key in obj) { delete obj[key]; } return obj; } return {}; } releaseObject(obj) { try { if (this.objectPool.length < this.maxPoolSize) { for (const key in obj) { delete obj[key]; } this.objectPool.push(obj); } } catch (error) { console.warn('EnhancedObjectPool: Error releasing Object:', error); } } getStats() { return { weakSetPool: this.weakSetPool.length, mapPool: this.mapPool.length, arrayPool: this.arrayPool.length, objectPool: this.objectPool.length, totalSize: this.weakSetPool.length + this.mapPool.length + this.arrayPool.length + this.objectPool.length }; } clear() { this.weakSetPool.length = 0; this.mapPool.length = 0; this.arrayPool.length = 0; this.objectPool.length = 0; } } const globalObjectPool = new EnhancedObjectPool(); class FastHasher { strategyCache = new Map(); hitCount = 0; totalCount = 0; constructor() { this.initializeStrategies(); } initializeStrategies() { this.strategyCache.set('primitive:number', (obj) => `num:${obj}`); this.strategyCache.set('primitive:string', (obj) => `str:${obj}`); this.strategyCache.set('primitive:boolean', (obj) => `bool:${obj}`); this.strategyCache.set('primitive:null', () => 'null'); this.strategyCache.set('primitive:undefined', () => 'undefined'); this.strategyCache.set('primitive:symbol', (obj) => `sym:${obj.toString()}`); this.strategyCache.set('primitive:bigint', (obj) => `big:${obj.toString()}`); this.strategyCache.set('date', (obj) => `d:${obj.getTime()}`); this.strategyCache.set('regexp', (obj) => `r:${obj.toString()}`); this.strategyCache.set('error', (obj) => `err:${obj.name}:${obj.message}`); this.strategyCache.set('function', (obj) => `fn:${obj.name || 'anonymous'}:${obj.length}`); this.strategyCache.set('array', (obj) => { const arr = obj; if (arr.length === 0) return 'arr:[]'; const items = arr.map(item => { if (this.isPrimitive(item)) { return String(item); } return 'complex'; }); return `arr:${arr.length}:${items.join(',')}`; }); for (let i = 0; i <= 5; i++) { this.strategyCache.set(`object:${i}:`, (_obj) => this.hashSimpleObject(_obj)); } } isPrimitive(value) { return value === null || value === undefined || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'symbol' || typeof value === 'bigint'; } fastHash(obj) { this.totalCount++; try { const signature = TypeUtils.getObjectSignature(obj); const cached = this.strategyCache.get(signature); if (cached) { const result = cached(obj); if (result) { this.hitCount++; return result; } } if (this.isPrimitive(obj)) { const type = obj === null ? 'null' : typeof obj; const strategy = this.strategyCache.get(`primitive:${type}`); if (strategy) { const result = strategy(obj); if (result) { this.strategyCache.set(signature, strategy); return result; } } } if (obj instanceof Date) { const strategy = this.strategyCache.get('date'); if (strategy) { const result = strategy(obj); if (result) { this.strategyCache.set(signature, strategy); return result; } } } if (obj instanceof RegExp) { const strategy = this.strategyCache.get('regexp'); if (strategy) { const result = strategy(obj); if (result) { this.strategyCache.set(signature, strategy); return result; } } } if (obj instanceof Error) { const strategy = this.strategyCache.get('error'); if (strategy) { const result = strategy(obj); if (result) { this.strategyCache.set(signature, strategy); return result; } } } if (typeof obj === 'function') { const strategy = this.strategyCache.get('function'); if (strategy) { const result = strategy(obj); if (result) { this.strategyCache.set(signature, strategy); return result; } } } if (Array.isArray(obj)) { const strategy = this.strategyCache.get('array'); if (strategy) { const result = strategy(obj); if (result) { this.strategyCache.set(signature, strategy); return result; } } const result = this.hashSimpleArray(obj); if (result) { this.strategyCache.set(signature, (obj) => this.hashSimpleArray(obj)); return result; } } if (typeof obj === 'object' && obj !== null) { const keys = Object.keys(obj); for (let i = 0; i <= 5; i++) { if (keys.length <= i) { const strategy = this.strategyCache.get(`object:${i}:`); if (strategy) { const result = strategy(obj); if (result) { this.strategyCache.set(signature, strategy); return result; } } } } } for (const [key, strategy] of this.strategyCache.entries()) { if (!key.startsWith('object:') && !key.startsWith('primitive:')) { const result = strategy(obj); if (result) { this.strategyCache.set(signature, strategy); return result; } } } const result = this.hashSimpleObject(obj); if (result) { this.strategyCache.set(signature, (_obj) => this.hashSimpleObject(_obj)); return result; } return null; } catch { return null; } } hashSimpleObject(obj, depth = 0, visited = new WeakSet()) { try { if (depth > 10) { return 'obj:max_depth'; } if (typeof obj !== 'object' || obj === null) { return null; } if (visited.has(obj)) { const objectId = this.getObjectId(obj); return `obj:circular:${objectId}`; } visited.add(obj); const keys = Object.keys(obj).sort(); if (keys.length === 0) return 'obj:{}'; const pairs = keys.map(key => { const value = obj[key]; if (this.isPrimitive(value)) { return `${key}:${value}`; } if (typeof value === 'object' && value !== null) { if (Array.isArray(value)) { const arrayHash = this.hashSimpleArray(value); return `${key}:${arrayHash || 'complex'}`; } else { const nestedHash = this.hashSimpleObject(value, depth + 1, visited); return `${key}:${nestedHash || 'complex'}`; } } return `${key}:complex`; }); return `obj:{${pairs.join(',')}}`; } catch { return null; } } hashSimpleArray(arr) { try { if (arr.length === 0) return 'arr:[]'; const items = arr.map(item => { if (this.isPrimitive(item)) { return String(item); } return 'complex'; }); return `arr:${arr.length}:${items.join(',')}`; } catch { return null; } } getObjectId(_obj) { return `ref_${Math.random().toString(36).substr(2, 9)}_${Date.now()}`; } getStats() { return { hitCount: this.hitCount, totalCount: this.totalCount, hitRate: this.totalCount > 0 ? this.hitCount / this.totalCount : 0, strategies: this.strategyCache.size }; } resetStats() { this.hitCount = 0; this.totalCount = 0; } addStrategy(signature, strategy) { try { if (typeof signature === 'string' && typeof strategy === 'function') { this.strategyCache.set(signature, strategy); } } catch (error) { console.warn('FastHasher: Error adding strategy:', error); } } } const globalFastHasher = new FastHasher(); const safeGlobalThis = globalThis; const safeSetTimeout = (callback, ms) => { return safeGlobalThis.setTimeout(callback, ms); }; const safeClearTimeout = (id) => { return safeGlobalThis.clearTimeout(id); }; exports.RecoveryAction = void 0; (function (RecoveryAction) { RecoveryAction["RETRY"] = "retry"; RecoveryAction["FALLBACK_MODE"] = "fallback"; RecoveryAction["SKIP"] = "skip"; RecoveryAction["ABORT"] = "abort"; })(exports.RecoveryAction || (exports.RecoveryAction = {})); exports.ErrorType = void 0; (function (ErrorType) { ErrorType["SERIALIZATION"] = "serialization"; ErrorType["CACHE"] = "cache"; ErrorType["ITERATION"] = "iteration"; ErrorType["PLUGIN"] = "plugin"; ErrorType["MEMORY"] = "memory"; ErrorType["UNKNOWN"] = "unknown"; })(exports.ErrorType || (exports.ErrorType = {})); class ErrorRecoveryManager { errorHistory = new Map(); errorStats; policies = new Map(); globalFallbackMode = false; constructor() { this.errorStats = { total: 0, byType: Object.fromEntries(Object.values(exports.ErrorType).map(type => [type, 0])), byOperation: {}, recoveryActions: Object.fromEntries(Object.values(exports.RecoveryAction).map(action => [action, 0])) }; this.initializePolicies(); } initializePolicies() { this.policies.set(exports.ErrorType.SERIALIZATION, { maxRetries: 2, retryDelay: 0, escalationThreshold: 5, fallbackMode: true }); this.policies.set(exports.ErrorType.CACHE, { maxRetries: 3, retryDelay: 10, escalationThreshold: 10, fallbackMode: true }); this.policies.set(exports.ErrorType.ITERATION, { maxRetries: 1, retryDelay: 0, escalationThreshold: 3, fallbackMode: true }); this.policies.set(exports.ErrorType.PLUGIN, { maxRetries: 0, retryDelay: 0, escalationThreshold: 1, fallbackMode: false }); this.policies.set(exports.ErrorType.MEMORY, { maxRetries: 0, retryDelay: 0, escalationThreshold: 1, fallbackMode: true }); this.policies.set(exports.ErrorType.UNKNOWN, { maxRetries: 1, retryDelay: 100, escalationThreshold: 5, fallbackMode: true }); } handleError(error, operation, errorType = exports.ErrorType.UNKNOWN) { try { this.updateStats(error, operation, errorType); if (this.globalFallbackMode) { this.errorStats.recoveryActions[exports.RecoveryAction.FALLBACK_MODE]++; return exports.RecoveryAction.FALLBACK_MODE; } const policy = this.policies.get(errorType) || this.policies.get(exports.ErrorType.UNKNOWN); const errorKey = `${operation}:${errorType}`; const currentCount = this.errorHistory.get(errorKey) || 0; this.errorHistory.set(errorKey, currentCount + 1); let action; if (currentCount >= policy.escalationThreshold) { if (policy.fallbackMode) { action = exports.RecoveryAction.FALLBACK_MODE; this.globalFallbackMode = true; } else { action = exports.RecoveryAction.SKIP; } } else if (currentCount < policy.maxRetries) { action = exports.RecoveryAction.RETRY; if (policy.retryDelay > 0) { } } else { if (policy.fallbackMode) { action = exports.RecoveryAction.FALLBACK_MODE; } else { action = exports.RecoveryAction.SKIP; } } this.errorStats.recoveryActions[action]++; return action; } catch (recoveryError) { console.error('ErrorRecoveryManager: Error in error handling:', recoveryError); this.errorStats.recoveryActions[exports.RecoveryAction.ABORT]++; return exports.RecoveryAction.ABORT; } } updateStats(error, operation, errorType) { try { this.errorStats.total++; this.errorStats.byType[errorType]++; this.errorStats.byOperation[operation] = (this.errorStats.byOperation[operation] || 0) + 1; this.errorStats.lastError = { type: errorType, operation, message: error.message, timestamp: Date.now() }; } catch (statsError) { console.warn('ErrorRecoveryManager: Error updating stats:', statsError); } } executeWithRecovery(operation, fallback, operationName, errorType = exports.ErrorType.UNKNOWN) { try { return operation(); } catch (error) { const action = this.handleError(error, operationName, errorType); switch (action) { case exports.RecoveryAction.RETRY: try { return operation(); } catch (retryError) { console.warn(`ErrorRecoveryManager: Retry failed for ${operationName}:`, retryError); return fallback(); } case exports.RecoveryAction.FALLBACK_MODE: case exports.RecoveryAction.SKIP: return fallback(); case exports.RecoveryAction.ABORT: default: throw error; } } } async executeAsyncWithRecovery(operation, fallback, operationName, errorType = exports.ErrorType.UNKNOWN) { try { return await operation(); } catch (error) { const action = this.handleError(error, operationName, errorType); switch (action) { case exports.RecoveryAction.RETRY: try { const policy = this.policies.get(errorType); if (policy && policy.retryDelay > 0) { await this.delay(policy.retryDelay); } return await operation(); } catch (retryError) { console.warn(`ErrorRecoveryManager: Async retry failed for ${operationName}:`, retryError); return await fallback(); } case exports.RecoveryAction.FALLBACK_MODE: case exports.RecoveryAction.SKIP: return await fallback(); case exports.RecoveryAction.ABORT: default: throw error; } } } delay(ms) { return new Promise(resolve => safeSetTimeout(resolve, ms)); } resetErrorHistory(operation, errorType) { try { if (operation && errorType) { const errorKey = `${operation}:${errorType}`; this.errorHistory.delete(errorKey); } else if (operation) { for (const key of this.errorHistory.keys()) { if (key.startsWith(`${operation}:`)) { this.errorHistory.delete(key); } } } else { this.errorHistory.clear(); this.globalFallbackMode = false; } } catch (error) { console.warn('ErrorRecoveryManager: Error resetting history:', error); } } getStats() { return { ...this.errorStats }; } setPolicy(errorType, policy) { try { this.policies.set(errorType, { ...policy }); } catch (error) { console.warn('ErrorRecoveryManager: Error setting policy:', error); } } getPolicy(errorType) { try { const policy = this.policies.get(errorType); return policy ? { ...policy } : undefined; } catch (error) { console.warn('ErrorRecoveryManager: Error getting policy:', error); return undefined; } } isInFallbackMode() { return this.globalFallbackMode; } exitFallbackMode() { this.globalFallbackMode = false; this.errorHistory.clear(); } getHealthStatus() { try { const totalOperations = Object.values(this.errorStats.byOperation).reduce((sum, count) => sum + count, 0); const errorRate = totalOperations > 0 ? this.errorStats.total / totalOperations : 0; return { healthy: errorRate < 0.1 && !this.globalFallbackMode, errorRate, totalErrors: this.errorStats.total, inFallbackMode: this.globalFallbackMode, criticalErrors: this.errorStats.byType[exports.ErrorType.MEMORY] + this.errorStats.byType[exports.ErrorType.UNKNOWN], status: this.globalFallbackMode ? 'degraded' : errorRate > 0.2 ? 'warning' : errorRate > 0.1 ? 'caution' : 'healthy' }; } catch (error) { console.warn('ErrorRecoveryManager: Error getting health status:', error); return { healthy: false, errorRate: 1, totalErrors: this.errorStats.total, inFallbackMode: true, criticalErrors: 999, status: 'unknown' }; } } } const globalErrorRecovery = new ErrorRecoveryManager(); class EnhancedLRUCache { cache = new Map(); head; tail; maxSize; stats; constructor(maxSize = 1000) { this.maxSize = maxSize; this.stats = { hits: 0, misses: 0, sets: 0, deletes: 0, evictions: 0, hitRate: 0, size: 0, maxSize }; } get(key) { try { const node = this.cache.get(key); if (node) { this.stats.hits++; this.updateAccess(node); this.moveToHead(node); return node.value; } this.stats.misses++; this.updateHitRate(); return undefined; } catch (error) { console.warn('EnhancedLRUCache: Error in get:', error); this.stats.misses++; this.updateHitRate(); return undefined; } } set(key, value) { try { this.stats.sets++; const existingNode = this.cache.get(key); if (existingNode) { existingNode.value = value; this.updateAccess(existingNode); this.moveToHead(existingNode); return; } const newNode = { key, value, prev: undefined, next: undefined, frequency: 1, lastAccess: Date.now() }; this.cache.set(key, newNode); this.addToHead(newNode); this.stats.size++; if (this.cache.size > this.maxSize) { this.removeTail(); } this.updateHitRate(); } catch (error) { console.warn('EnhancedLRUCache: Error in set:', error); } } delete(key) { try { const node = this.cache.get(key); if (node) { this.removeNode(node); this.cache.delete(key); this.stats.deletes++; this.stats.size--; this.updateHitRate(); return true; } return false; } catch (error) { console.warn('EnhancedLRUCache: Error in delete:', error); return false; } } updateAccess(node) { try { node.frequency = (node.frequency || 0) + 1; node.lastAccess = Date.now(); } catch (error) { console.warn('EnhancedLRUCache: Error updating access:', error); } } moveToHead(node) { try { if (!node) return; this.removeNode(node); this.addToHead(node); } catch (error) { console.warn('EnhancedLRUCache: Error moving to head:', error); } } addToHead(node) { try { if (!node) return; node.prev = undefined; node.next = this.head; if (this.head) { this.head.prev = node; } this.head = node; if (!this.tail) { this.tail = node; } } catch (error) { console.warn('EnhancedLRUCache: Error adding to head:', error); } } removeNode(node) { try { if (!node) return; if (node.prev) { node.prev.next = node.next; } else { this.head = node.next; } if (node.next) { node.next.prev = node.prev; } else { this.tail = node.prev; } } catch (error) { console.warn('EnhancedLRUCache: Error removing node:', error); } } removeTail() { try { if (this.tail) { this.cache.delete(this.tail.key); this.removeNode(this.tail); this.stats.evictions++; this.stats.size--; } } catch (error) { console.warn('EnhancedLRUCache: Error removing tail:', error); } } updateHitRate() { const total = this.stats.hits + this.stats.misses; this.stats.hitRate = total > 0 ? this.stats.hits / total : 0; } getStats() { return { ...this.stats }; } clear() { try { this.cache.clear(); this.head = undefined; this.tail = undefined; this.stats.size = 0; } catch (error) { console.warn('EnhancedLRUCache: Error clearing cache:', error); } } get size() { return this.cache.size; } } class TieredCacheManager { l1Cache; l2Cache; promoteThreshold; accessCounts = new Map(); constructor(options) { const l1Size = Math.max(1, options.l1CacheSize || 100); const l2Size = Math.max(1, options.l2CacheSize || 1000); const threshold = Math.max(1, options.promoteThreshold || 3); this.l1Cache = new EnhancedLRUCache(l1Size); this.l2Cache = new EnhancedLRUCache(l2Size); this.promoteThreshold = threshold; } get(key) { try { let value = this.l1Cache.get(key); if (value !== undefined) { return value; } value = this.l2Cache.get(key); if (value !== undefined) { this.trackAccess(key); return value; } return undefined; } catch (error) { console.warn('TieredCacheManager: Error in get:', error); return undefined; } } set(key, value) { try { this.l2Cache.set(key, value); } catch (error) { console.warn('TieredCacheManager: Error in set:', error); } } trackAccess(key) { try { const count = this.accessCounts.get(key) || 0; const newCount = count + 1; this.accessCounts.set(key, newCount); if (newCount >= this.promoteThreshold) { const value = this.l2Cache.get(key); if (value !== undefined) { this.l1Cache.set(key, value); } this.accessCounts.delete(key); } } catch (error) { console.warn('TieredCacheManager: Error tracking access:', error); } } delete(key) { try { const l1Deleted = this.l1Cache.delete(key); const l2Deleted = this.l2Cache.delete(key); this.accessCounts.delete(key); return l1Deleted || l2Deleted; } catch (error) { console.warn('TieredCacheManager: Error in delete:', error); return false; } } getStats() { try { const l1Stats = this.l1Cache.getStats(); const l2Stats = this.l2Cache.getStats(); return { l1: l1Stats, l2: l2Stats, combined: { hits: l1Stats.hits + l2Stats.hits, misses: l1Stats.misses + l2Stats.misses, hitRate: (l1Stats.hits + l2Stats.hits) / (l1Stats.hits + l2Stats.hits + l1Stats.misses + l2Stats.misses), totalSize: l1Stats.size + l2Stats.size, pendingPromotions: this.accessCounts.size } }; } catch (error) { console.warn('TieredCacheManager: Error getting stats:', error); return { l1: this.l1Cache.getStats(), l2: this.l2Cache.getStats(), combined: { hits: 0, misses: 0, hitRate: 0, totalSize: 0, pendingPromotions: 0 } }; } } clear() { try { this.l1Cache.clear(); this.l2Cache.clear(); this.accessCounts.clear(); } catch (error) { console.warn('TieredCacheManager: Error clearing:', error); } } } class AdaptiveSerializer { strategies = new Map(); strategyStats = new Map(); cache; enableMetrics; objectIdMap = new WeakMap(); constructor(enableCache = true, enableMetrics = true) { this.cache = enableCache ? new TieredCacheManager({ l1CacheSize: 1000, l2CacheSize: 5000, promoteThreshold: 3 }) : undefined; this.enableMetrics = enableMetrics; this.initializeStrategies(); } initializeStrategies() { this.addStrategy({ name: 'primitive', priority: 100, canHandle: (obj) => TypeUtils.isPrimitive(obj), serialize: (obj) => { if (obj === null) return 'null'; if (obj === undefined) return 'undefined'; if (typeof obj === 'string') return `"${obj}"`; if (typeof obj === 'symbol') return this.serializeSymbol(obj); if (typeof obj === 'bigint') return `${obj}n`; return String(obj); } }); this.addStrategy({ name: 'simpleObject', priority: 95, canHandle: (obj) => TypeUtils.isSimpleObject(obj), serialize: (obj, context) => { try { const keys = Object.keys(obj).sort(); const pairs = keys.map(key => { const value = obj[key]; const serializedValue = this.serializeValue(value, context); return `"${key}":${serializedValue}`; }); return `{${pairs.join(',')}}`; } catch { return this.fallbackSerialize(obj); } } }); this.addStrategy({ name: 'simpleArray', priority: 90, canHandle: (obj) => { return Array.isArray(obj) && obj.length <= 10 && obj.every(item => TypeUtils.isPrimitive(item)); }, serialize: (obj) => { const items = obj.map((item) => { if (item === null) return 'null'; if (item === undefined) return 'undefined'; if (typeof item === 'string') return `"${item}"`; return String(item); }); return `[${items.join(',')}]`; } }); this.addStrategy({ name: 'date', priority: 85, canHandle: (obj) => obj instanceof Date, serialize: (obj) => `[Date:${obj.getTime()}]` }); this.addStrategy({ name: 'regexp', priority: 85, canHandle: (obj) => obj instanceof RegExp, serialize: (obj) => `[RegExp:${obj.toString()}]` }); this.addStrategy({ name: 'error', priority: 85, canHandle: (obj) => obj instanceof Error, serialize: (obj) => `[Error:${obj.name}:${obj.message}]` }); this.addStrategy({ name: 'function', priority: 80, canHandle: (obj) => typeof obj === 'function', serialize: (obj) => `[Function:${obj.name || 'anonymous'}:${obj.length}]` }); this.addStrategy({ name: 'complex', priority: 75, canHandle: () => true, serialize: (obj, context) => this.deepSerialize(obj, context) }); this.addStrategy({ name: 'fastHash', priority: 10, canHandle: (obj) => { const result = globalFastHasher.fastHash(obj); return result !== null; }, serialize: (obj) => { const result = globalFastHasher.fastHash(obj); return result || this.fallbackSerialize(obj); } }); } addStrategy(strategy) { try { this.strategies.set(strategy.name, strategy); this.strategyStats.set(strategy.name, { usage: 0, avgTime: 0 }); } catch (error) { console.warn('AdaptiveSerializer: Error adding strategy:', error); } } serialize(obj) { try { if (this.cache && typeof obj === 'object' && obj !== null) { const cached = this.cache.get(this.getObjectId(obj)); if (cached !== undefined) { return cached; } } const context = { visited: new WeakSet(), cache: this.cache, depth: 0, maxDepth: 50 }; try { const result = this.serializeValue(obj, context); if (this.cache && typeof obj === 'object' && obj !== null) { this.cache.set(this.getObjectId(obj), result); } return result; } finally { } } catch (error) { console.warn('AdaptiveSerializer: Serialization error:', error); return this.fallbackSerialize(obj); } } serializeValue(obj, context) { try { if (context.depth > context.maxDepth) { return '[MaxDepthExceeded]'; } if (typeof obj === 'object' && obj !== null) { if (context.visited.has(obj)) { const objectId = this.getObjectId(obj); return `[Circular:${objectId}]`; } } const strategies = Array.from(this.strategies.values()) .sort((a, b) => b.priority - a.priority); for (const strategy of strategies) { try { if (strategy.canHandle(obj)) { const startTime = this.enableMetrics ? performance.now() : 0; if (typeof obj === 'object' && obj !== null) { context.visited.add(obj); } const result = strategy.serialize(obj, { ...context, depth: context.depth + 1 }); if (this.enableMetrics) { this.updateStrategyStats(strategy.name, performance.now() - startTime); } return result; } } catch (strategyError) { console.warn(`AdaptiveSerializer: Strategy ${strategy.name} failed:`, strategyError); continue; } } return this.fallbackSerialize(obj); } catch (error) { console.warn('AdaptiveSerializer: Error in serializeValue:', error); return this.fallbackSerialize(obj); } } deepSerialize(obj, context) { try { if (Array.isArray(obj)) { const items = obj.map(item => this.serializeValue(item, context)); return `[${items.join(',')}]`; } if (obj && typeof obj === 'object') { const keys = Object.keys(obj).sort(); const pairs = keys.map(key => { try { const value = this.serializeValue(obj[key], context); return `"${key}":${value}`; } catch { return `"${key}":"[SerializationError]"`; } }); return `{${pairs.join(',')}}`; } return this.fallbackSerialize(obj); } catch { return this.fallbackSerialize(obj); } } fallbackSerialize(obj) { try { if (obj === null) return 'null'; if (obj === undefined) return 'undefined'; if (typeof obj === 'string') return `"${obj}"`; if (typeof obj === 'number') return String(obj); if (typeof obj === 'boolean') return String(obj); if (typeof obj === 'symbol') return this.serializeSymbol(obj); if (typeof obj === 'bigint') return `${obj}n`; try { return JSON.stringify(obj) || '[UnserializableObject]'; } catch { return `[${typeof obj}:${Object.prototype.toString.call(obj)}]`; } } catch { return '[CriticalSerializationError]'; } } serializeSymbol(sym) { try { const globalKey = Symbol.keyFor(sym); if (globalKey !== undefined) { return `Symbol.for("${globalKey}")`; } return 'Symbol()'; } catch { return `Symbol(${sym.toString()})`; } } getObjectId(obj) { try { if (typeof obj === 'object' && obj !== null) { if (this.objectIdMap.has(obj)) { return this.objectIdMap.get(obj); } const newId = `obj_${Math.random().toString(36).substr(2, 9)}`; this.objectIdMap.set(obj, newId); return newId; } return `obj_${TypeUtils.getObjectSignature(obj)}`; } catch { return `obj_unknown`; } } updateStrategyStats(strategyName, duration) { try { const stats = this.strategyStats.get(strategyName); if (stats) { stats.usage++; stats.avgTime = (stats.avgTime * (stats.usage - 1) + duration) / stats.usage; } } catch (error) { console.warn('AdaptiveSerializer: Error updating stats:', error); } } getStats() { try { const strategyStats = Object.fromEntries(this.strategyStats); const cacheStats = this.cache?.getStats(); const fastHashStats = globalFastHasher.getStats(); return { strategies: strategyStats, cache: cacheStats, fastHash: fastHashStats, totalStrategies: this.strategies.size }; } catch (error) { console.warn('AdaptiveSerializer: Error getting stats:', error); return { strategies: {}, cache: null, fastHash: null, totalStrategies: 0 }; } } resetStats() { try { this.strategyStats.forEach(stats => { stats.usage = 0; stats.avgTime = 0; }); this.cache?.clear(); globalFastHasher.resetStats(); } catch (error) { console.warn('AdaptiveSerializer: Error resetting stats:', error); } } clearCache() { try { this.cache?.clear(); } catch (error) { console.warn('AdaptiveSerializer: Error clearing cache:', error); } } } const globalSerializer = new AdaptiveSerializer(); class AsyncTurboMap { syncMap; options; constructor(syncMap, options = {}) { this.syncMap = syncMap; this.options = { batchSize: 100, delayBetweenBatches: 1, maxConcurrency: 10, timeoutMs: 30000, enableProgress: false, ...options }; } async setAsync(key, value) { return globalErrorRecovery.executeAsyncWithRecovery(async () => { await this.nextTick(); this.syncMap.set(key, value); return this; }, async () => { console.warn('AsyncTurboMap: Failed to set key, using fallback'); return this; }, 'setAsync', exports.ErrorType.UNKNOWN); } async getAsync(key) { return globalErrorRecovery.executeAsyncWithRecovery(async () => { await this.nextTick(); return this.syncMap.get(key); }, async () => { console.warn('AsyncTurboMap: Failed to get key, returning undefined'); return undefined; }, 'getAsync', exports.ErrorType.UNKNOWN); } async hasAsync(key) { return globalErrorRecovery.executeAsyncWithRecovery(async () => { await this.nextTick(); return this.syncMap.has(key); }, async () => { console.warn('AsyncTurboMap: Failed to check key, returning false'); return false; }, 'hasAsync', exports.ErrorType.UNKNOWN); } async deleteAsync(key) { return globalErrorRecovery.executeAsyncWithRecovery(async () => { await this.nextTick(); return this.syncMap.delete(key); }, async () => { console.warn('AsyncTurboMap: Failed to delete key, returning false'); return false; }, 'deleteAsync', exports.ErrorType.UNKNOWN); } async clearAsync() { return globalErrorRecovery.executeAsyncWithRecovery(async () => { await this.nextTick(); this.syncMap.clear(); }, async () => { console.warn('AsyncTurboMap: Failed to clear map'); }, 'clearAsync', exports.ErrorType.UNKNOWN); } async batchExecute(operations) { return globalErrorRecovery.executeAsyncWithRecovery(async () => { const results = []; const { batchSize = 100, delayBetweenBatches = 1 } = this.options; for (let i = 0; i < operations.length; i += batchSize) { const batch = operations.slice(i, i + batchSize); const batchResults = await this.processBatch(batch);