decode.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.decodeHTML = exports.decodeHTMLStrict = exports.decodeXML = void 0;
  7. var entities_json_1 = __importDefault(require("./maps/entities.json"));
  8. var legacy_json_1 = __importDefault(require("./maps/legacy.json"));
  9. var xml_json_1 = __importDefault(require("./maps/xml.json"));
  10. var decode_codepoint_1 = __importDefault(require("./decode_codepoint"));
  11. exports.decodeXML = getStrictDecoder(xml_json_1.default);
  12. exports.decodeHTMLStrict = getStrictDecoder(entities_json_1.default);
  13. function getStrictDecoder(map) {
  14. var keys = Object.keys(map).join("|");
  15. var replace = getReplacer(map);
  16. keys += "|#[xX][\\da-fA-F]+|#\\d+";
  17. var re = new RegExp("&(?:" + keys + ");", "g");
  18. return function (str) { return String(str).replace(re, replace); };
  19. }
  20. var sorter = function (a, b) { return (a < b ? 1 : -1); };
  21. exports.decodeHTML = (function () {
  22. var legacy = Object.keys(legacy_json_1.default).sort(sorter);
  23. var keys = Object.keys(entities_json_1.default).sort(sorter);
  24. for (var i = 0, j = 0; i < keys.length; i++) {
  25. if (legacy[j] === keys[i]) {
  26. keys[i] += ";?";
  27. j++;
  28. }
  29. else {
  30. keys[i] += ";";
  31. }
  32. }
  33. var re = new RegExp("&(?:" + keys.join("|") + "|#[xX][\\da-fA-F]+;?|#\\d+;?)", "g");
  34. var replace = getReplacer(entities_json_1.default);
  35. function replacer(str) {
  36. if (str.substr(-1) !== ";")
  37. str += ";";
  38. return replace(str);
  39. }
  40. //TODO consider creating a merged map
  41. return function (str) { return String(str).replace(re, replacer); };
  42. })();
  43. function getReplacer(map) {
  44. return function replace(str) {
  45. if (str.charAt(1) === "#") {
  46. var secondChar = str.charAt(2);
  47. if (secondChar === "X" || secondChar === "x") {
  48. return decode_codepoint_1.default(parseInt(str.substr(3), 16));
  49. }
  50. return decode_codepoint_1.default(parseInt(str.substr(2), 10));
  51. }
  52. return map[str.slice(1, -1)];
  53. };
  54. }