UNPKG

twing

Version:

First-class Twig engine for Node.js

43 lines (42 loc) 1.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createJsEscapingStrategyHandler = void 0; const phpSprintf = require('locutus/php/strings/sprintf'); const createJsEscapingStrategyHandler = () => { return (value) => { // escape all non-alphanumeric characters // into their \x or \uHHHH representations value = value.replace(/[^a-zA-Z0-9,._]/ug, function (matches) { let char = matches; /** * A few characters have short escape sequences in JSON and JavaScript. * Escape sequences supported only by JavaScript, not JSON, are ommitted. * \" is also supported but omitted, because the resulting string is not HTML safe. */ let shortMap = new Map([ ['\\', '\\\\'], ['/', '\\/'], ["\x08", '\\b'], ["\x0C", '\\f'], ["\x0A", '\\n'], ["\x0D", '\\r'], ["\x09", '\\t'], ]); if (shortMap.has(char)) { return shortMap.get(char); } let codePoint = char.codePointAt(0); if (codePoint <= 0x10000) { return phpSprintf('\\u%04X', codePoint); } // Split characters outside the BMP into surrogate pairs // https://tools.ietf.org/html/rfc2781.html#section-2.1 codePoint = codePoint - 0x10000; const high = 0xD800 | (codePoint >> 10); const low = 0xDC00 | (codePoint & 0x3FF); return phpSprintf('\\u%04X\\u%04X', high, low); }); return value; }; }; exports.createJsEscapingStrategyHandler = createJsEscapingStrategyHandler;