All files / lib/core/security escapeHtml.js

98.5% Statements 66/67
92.3% Branches 12/13
100% Functions 4/4
98.5% Lines 66/67

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 6912x 12x 12x 12x 12x 12x 12x 12x 12x 12x 47x 47x 47x 47x 47x 47x 47x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 4x 4x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 4x 4x 3x 3x 1x 3x   2x 2x 2x 3x 4x 1x 1x 11x 12x    
/**
 * Provides utility for escaping HTML characters to prevent XSS.
 */
export class HtmlEscaper {
    /**
     * Escapes special HTML characters in a string.
     * @param {any} value - The value to escape.
     * @returns {string} The escaped string.
     */
    escape(value) {
        return String(value)
            .replace(/&/g, '&')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }
}
 
/**
 * A wrapper class to designate that a string is safe HTML and should not be escaped.
 */
export class SafeHtml {
    /**
     * @param {any} value
     */
    constructor(value) {
        this.value = String(value);
    }
 
    /**
     * @returns {string}
     */
    toString() {
        return this.value;
    }
}
 
/**
 * Creates a SafeHtml wrapper for raw HTML insertion.
 * Can be used as a standard function: html('<p>unsafe</p>')
 * or as a tagged template literal: html`<p>${unsafe}</p>`
 * @param {string|TemplateStringsArray} strings
 * @param {...any} values
 * @returns {SafeHtml}
 */
export function html(strings, ...values) {
    if (Array.isArray(strings) && strings.raw) {
        const escaper = new HtmlEscaper();
        let result = '';
        for (let i = 0; i < strings.length; i++) {
            result += strings[i];
            if (i < values.length) {
                const val = values[i];
                if (val instanceof SafeHtml) {
                    result += val.toString();
                } else if (val == null) {
                    result += '';
                } else {
                    result += escaper.escape(val);
                }
            }
        }
        return new SafeHtml(result);
    }
    return new SafeHtml(strings);
}