UNPKG

twing

Version:

First-class Twig engine for Node.js

57 lines (56 loc) 2.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createHtmlAttributeEscapingStrategyHandler = void 0; const phpOrd = require('locutus/php/strings/ord'); const createHtmlAttributeEscapingStrategyHandler = () => { return (value) => { value = value.replace(/[^a-zA-Z0-9,.\-_]/ug, function (matches) { /** * This function is adapted from code coming from Zend Framework. * * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /* * While HTML supports far more named entities, the lowest common denominator * has become HTML5's XML Serialisation which is restricted to the those named * entities that XML supports. Using HTML entities would result in this error: * XML Parsing Error: undefined entity */ let entityMap = new Map([ [34, 'quot'], /* quotation mark */ [38, 'amp'], /* ampersand */ [60, 'lt'], /* less-than sign */ [62, 'gt'] /* greater-than sign */ ]); let chr = matches; let ord = phpOrd(chr); /* * The following replaces characters undefined in HTML with the * hex entity for the Unicode replacement character. */ if ((ord <= 0x1f && chr != "\t" && chr != "\n" && chr != "\r") || (ord >= 0x7f && ord <= 0x9f)) { return '&#xFFFD;'; } /* * Check if the current character to escape has a name entity we should * replace it with while grabbing the hex value of the character. */ let int = chr.codePointAt(0); if (entityMap.has(int)) { return `&${entityMap.get(int)};`; } let hex = int.toString(16).toUpperCase(); if (hex.length === 1 || hex.length === 3) { hex = '0' + hex; } /* * Per OWASP recommendations, we'll use hex entities for any other * characters where a named entity does not exist. */ return `&#x${hex};`; }); return value; }; }; exports.createHtmlAttributeEscapingStrategyHandler = createHtmlAttributeEscapingStrategyHandler;