UNPKG

e2ed

Version:

E2E testing framework over Playwright

82 lines (81 loc) 2.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createSafeHtmlWithoutSanitize = createSafeHtmlWithoutSanitize; exports.isSafeHtml = isSafeHtml; exports.sanitizeValue = sanitizeValue; exports.sanitizeHtml = sanitizeHtml; exports.sanitizeJson = sanitizeJson; const assertValueIsDefined_1 = require("./assertValueIsDefined"); const assertValueIsDefined = assertValueIsDefined_1.assertValueIsDefined; /** * Creates SafeHtml from string without sanitize. * This base client function should not use scope variables (except other base functions). * @internal */ function createSafeHtmlWithoutSanitize(stringParts, ...values) { const key = Symbol.for('e2ed:SafeHtml:key'); const parts = []; for (let index = 0; index < values.length; index += 1) { const stringPart = stringParts[index]; assertValueIsDefined(stringPart); const value = String(values[index]); parts.push(stringPart, value); } const lastStringPart = stringParts.at(-1); assertValueIsDefined(lastStringPart); parts.push(lastStringPart); const html = parts.join(''); // eslint-disable-next-line no-new-wrappers const safeHtml = new String(html); Object.defineProperty(safeHtml, key, { value: undefined }); return safeHtml; } /** * Returns `true`, if value is `SafeHtml`, and `false` otherwise. * This base client function should not use scope variables (except other base functions). * @internal */ function isSafeHtml(value) { const key = Symbol.for('e2ed:SafeHtml:key'); return typeof value === 'object' && value !== null && key in value; } /** * Sanitizes arbitrary value. * This base client function should not use scope variables (except other base functions). * @internal */ function sanitizeValue(value) { return String(value) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#039;'); } /** * Sanitizes HTML code (simple protection against XSS attacks). * This base client function should not use scope variables (except other base functions). * @internal */ function sanitizeHtml(stringParts, ...values) { const parts = []; for (let index = 0; index < values.length; index += 1) { const stringPart = stringParts[index]; assertValueIsDefined(stringPart); const value = values[index]; const safeValue = isSafeHtml(value) ? String(value) : sanitizeValue(value); parts.push(stringPart, safeValue); } const lastStringPart = stringParts.at(-1); assertValueIsDefined(lastStringPart); parts.push(lastStringPart); const html = parts.join(''); return createSafeHtmlWithoutSanitize `${html}`; } /** * Sanitizes JSON string (simple protection against XSS attacks). * This base client function should not use scope variables (except other base functions). * @internal */ function sanitizeJson(json) { return json.replace(/</g, '&lt;'); }