All files utils.logging.js

94.23% Statements 49/52
83.33% Branches 25/30
100% Functions 15/15
94% Lines 47/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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      3x     2x 1x       2x             271x 3x       271x 271x   271x             271x 51x       271x             271x             3x       1x       102x       1x                       5x   2x           22x 22x 19x   3x             2x 2x     1x 1x 1x           2x     2x         1x     2x         1x 1x         3x 1x     2x               2x 4x 1x 3x 1x 2x 1x 1x 1x       2x      
// Logging System for Error Detection
// Logs are stored in Memory.logs and collected by GitHub Actions
 
module.exports = {
    // Initialize logging system
    init: function () {
        if (!Memory.logs) {
            Memory.logs = [];
        }
 
        // Clean old logs (keep last 100)
        Iif (Memory.logs.length > 100) {
            Memory.logs = Memory.logs.slice(-100);
        }
    },
 
    // Log a message
    log: function (level, message) {
        if (!Memory.logs) {
            Memory.logs = [];
        }
 
        // Security: Truncate level and message to avoid Memory DoS (2MB limit)
        const sanitizedLevel = String(level).substring(0, 20);
        const sanitizedMessage = String(message).substring(0, 500);
 
        Memory.logs.push({
            time: Game.time,
            level: sanitizedLevel,
            message: sanitizedMessage,
        });
 
        // Security: Immediate rotation to prevent Memory DoS mid-tick
        if (Memory.logs.length > 100) {
            Memory.logs.shift();
        }
 
        // Also output to console with emoji
        const emoji = {
            error: '\u274c',
            warn: '\u26a0\ufe0f',
            info: '\u2139\ufe0f',
            debug: '\ud83d\udd0d',
        };
 
        console.log(
            `${emoji[sanitizedLevel] || '\ud83d\udcac'} [${sanitizedLevel}] ${sanitizedMessage}`
        );
    },
 
    // Convenience methods
    error: function (message) {
        this.log('error', message);
    },
 
    warn: function (message) {
        this.log('warn', message);
    },
 
    info: function (message) {
        this.log('info', message);
    },
 
    debug: function (message) {
        this.log('debug', message);
    },
 
    /**
     * Sanitizes a stack trace to remove internal file paths while keeping
     * function names and line numbers for debugging.
     *
     * Security: Rewritten to avoid ReDoS (super-linear backtracking).
     * Instead of a single complex regex, we use a simple split-based approach
     * that extracts only the filename:line:col portion without catastrophic backtracking.
     */
    getSafeStack: function (stack) {
        if (!stack) return '';
 
        return stack
            .split('\n')
            .map((line) => {
                // Match "filename:line:col" at the end of a path segment.
                // Uses a simple non-backtracking pattern: match the last
                // path component only, without nested quantifiers.
                const match = line.match(/[^/\\]+:\d+:\d+/);
                if (match) {
                    return match[0];
                }
                return line;
            })
            .join('\n');
    },
 
    // Wrap function with error catching
    tryCatch: function (fn, context, ...args) {
        try {
            return fn(...args);
        } catch (e) {
            // Security: Sanitize stack trace before logging to avoid path exposure
            const safeStack = this.getSafeStack(e.stack);
            this.error(`Exception in ${context}: ${e.message}\n${safeStack}`);
            return null;
        }
    },
 
    // Get recent logs
    getRecentLogs: function (count = 10) {
        Iif (!Memory.logs) {
            return [];
        }
        return Memory.logs.slice(-count);
    },
 
    // Get errors only
    getErrors: function (count = 10) {
        Iif (!Memory.logs) {
            return [];
        }
        return Memory.logs.filter((log) => log.level === 'error').slice(-count);
    },
 
    // Clear all logs
    clear: function () {
        Memory.logs = [];
        console.log('\ud83d\uddd1\ufe0f Logs cleared');
    },
 
    // Get statistics
    getStats: function () {
        if (!Memory.logs) {
            return {};
        }
 
        const stats = {
            total: Memory.logs.length,
            errors: 0,
            warnings: 0,
            info: 0,
            debug: 0,
        };
 
        Memory.logs.forEach((log) => {
            if (log.level === 'error') {
                stats.errors++;
            } else if (log.level === 'warn') {
                stats.warnings++;
            } else if (log.level === 'info') {
                stats.info++;
            } else Eif (log.level === 'debug') {
                stats.debug++;
            }
        });
 
        return stats;
    },
};