escape.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. const xmlCodeMap = new Map([
  2. [34, """],
  3. [38, "&"],
  4. [39, "'"],
  5. [60, "<"],
  6. [62, ">"],
  7. ]);
  8. // For compatibility with node < 4, we wrap `codePointAt`
  9. export const getCodePoint: (c: string, index: number) => number =
  10. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  11. String.prototype.codePointAt == null
  12. ? (c: string, index: number): number =>
  13. (c.charCodeAt(index) & 0xfc_00) === 0xd8_00
  14. ? (c.charCodeAt(index) - 0xd8_00) * 0x4_00 +
  15. c.charCodeAt(index + 1) -
  16. 0xdc_00 +
  17. 0x1_00_00
  18. : c.charCodeAt(index)
  19. : // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  20. (input: string, index: number): number => input.codePointAt(index)!;
  21. /**
  22. * Bitset for ASCII characters that need to be escaped in XML.
  23. */
  24. export const XML_BITSET_VALUE = 0x50_00_00_c4; // 32..63 -> 34 ("),38 (&),39 ('),60 (<),62 (>)
  25. /**
  26. * Encodes all non-ASCII characters, as well as characters not valid in XML
  27. * documents using XML entities. Uses a fast bitset scan instead of RegExp.
  28. *
  29. * If a character has no equivalent entity, a numeric hexadecimal reference
  30. * (eg. `&#xfc;`) will be used.
  31. */
  32. export function encodeXML(input: string): string {
  33. let out: string | undefined;
  34. let last = 0;
  35. const { length } = input;
  36. for (let index = 0; index < length; index++) {
  37. const char = input.charCodeAt(index);
  38. // Check for ASCII chars that don't need escaping
  39. if (
  40. char < 0x80 &&
  41. (((XML_BITSET_VALUE >>> char) & 1) === 0 || char >= 64 || char < 32)
  42. ) {
  43. continue;
  44. }
  45. if (out === undefined) out = input.substring(0, index);
  46. else if (last !== index) out += input.substring(last, index);
  47. if (char < 64) {
  48. // Known replacement
  49. out += xmlCodeMap.get(char)!;
  50. last = index + 1;
  51. continue;
  52. }
  53. // Non-ASCII: encode as numeric entity (handle surrogate pair)
  54. const cp = getCodePoint(input, index);
  55. out += `&#x${cp.toString(16)};`;
  56. if (cp !== char) index++; // Skip trailing surrogate
  57. last = index + 1;
  58. }
  59. if (out === undefined) return input;
  60. if (last < length) out += input.substr(last);
  61. return out;
  62. }
  63. /**
  64. * Encodes all non-ASCII characters, as well as characters not valid in XML
  65. * documents using numeric hexadecimal reference (eg. `&#xfc;`).
  66. *
  67. * Have a look at `escapeUTF8` if you want a more concise output at the expense
  68. * of reduced transportability.
  69. *
  70. * @param data String to escape.
  71. */
  72. export const escape: typeof encodeXML = encodeXML;
  73. /**
  74. * Creates a function that escapes all characters matched by the given regular
  75. * expression using the given map of characters to escape to their entities.
  76. *
  77. * @param regex Regular expression to match characters to escape.
  78. * @param map Map of characters to escape to their entities.
  79. *
  80. * @returns Function that escapes all characters matched by the given regular
  81. * expression using the given map of characters to escape to their entities.
  82. */
  83. function getEscaper(
  84. regex: RegExp,
  85. map: Map<number, string>,
  86. ): (data: string) => string {
  87. return function escape(data: string): string {
  88. let match: RegExpExecArray | null;
  89. let lastIndex = 0;
  90. let result = "";
  91. while ((match = regex.exec(data))) {
  92. if (lastIndex !== match.index) {
  93. result += data.substring(lastIndex, match.index);
  94. }
  95. // We know that this character will be in the map.
  96. result += map.get(match[0].charCodeAt(0))!;
  97. // Every match will be of length 1
  98. lastIndex = match.index + 1;
  99. }
  100. return result + data.substring(lastIndex);
  101. };
  102. }
  103. /**
  104. * Encodes all characters not valid in XML documents using XML entities.
  105. *
  106. * Note that the output will be character-set dependent.
  107. *
  108. * @param data String to escape.
  109. */
  110. export const escapeUTF8: (data: string) => string = /* #__PURE__ */ getEscaper(
  111. /["&'<>]/g,
  112. xmlCodeMap,
  113. );
  114. /**
  115. * Encodes all characters that have to be escaped in HTML attributes,
  116. * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
  117. *
  118. * @param data String to escape.
  119. */
  120. export const escapeAttribute: (data: string) => string =
  121. /* #__PURE__ */ getEscaper(
  122. /["&\u00A0]/g,
  123. new Map([
  124. [34, "&quot;"],
  125. [38, "&amp;"],
  126. [160, "&nbsp;"],
  127. ]),
  128. );
  129. /**
  130. * Encodes all characters that have to be escaped in HTML text,
  131. * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
  132. *
  133. * @param data String to escape.
  134. */
  135. export const escapeText: (data: string) => string = /* #__PURE__ */ getEscaper(
  136. /[&<>\u00A0]/g,
  137. new Map([
  138. [38, "&amp;"],
  139. [60, "&lt;"],
  140. [62, "&gt;"],
  141. [160, "&nbsp;"],
  142. ]),
  143. );