decode.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. import { htmlDecodeTree } from "./generated/decode-data-html.js";
  2. import { xmlDecodeTree } from "./generated/decode-data-xml.js";
  3. import { replaceCodePoint, fromCodePoint } from "./decode-codepoint.js";
  4. var CharCodes;
  5. (function (CharCodes) {
  6. CharCodes[CharCodes["NUM"] = 35] = "NUM";
  7. CharCodes[CharCodes["SEMI"] = 59] = "SEMI";
  8. CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS";
  9. CharCodes[CharCodes["ZERO"] = 48] = "ZERO";
  10. CharCodes[CharCodes["NINE"] = 57] = "NINE";
  11. CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A";
  12. CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F";
  13. CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X";
  14. CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z";
  15. CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A";
  16. CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F";
  17. CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z";
  18. })(CharCodes || (CharCodes = {}));
  19. /** Bit that needs to be set to convert an upper case ASCII character to lower case */
  20. const TO_LOWER_BIT = 32;
  21. export var BinTrieFlags;
  22. (function (BinTrieFlags) {
  23. BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
  24. BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH";
  25. BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE";
  26. })(BinTrieFlags || (BinTrieFlags = {}));
  27. function isNumber(code) {
  28. return code >= CharCodes.ZERO && code <= CharCodes.NINE;
  29. }
  30. function isHexadecimalCharacter(code) {
  31. return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F) ||
  32. (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F));
  33. }
  34. function isAsciiAlphaNumeric(code) {
  35. return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z) ||
  36. (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z) ||
  37. isNumber(code));
  38. }
  39. /**
  40. * Checks if the given character is a valid end character for an entity in an attribute.
  41. *
  42. * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error.
  43. * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
  44. */
  45. function isEntityInAttributeInvalidEnd(code) {
  46. return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code);
  47. }
  48. var EntityDecoderState;
  49. (function (EntityDecoderState) {
  50. EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart";
  51. EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart";
  52. EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal";
  53. EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex";
  54. EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity";
  55. })(EntityDecoderState || (EntityDecoderState = {}));
  56. export var DecodingMode;
  57. (function (DecodingMode) {
  58. /** Entities in text nodes that can end with any character. */
  59. DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy";
  60. /** Only allow entities terminated with a semicolon. */
  61. DecodingMode[DecodingMode["Strict"] = 1] = "Strict";
  62. /** Entities in attributes have limitations on ending characters. */
  63. DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute";
  64. })(DecodingMode || (DecodingMode = {}));
  65. /**
  66. * Token decoder with support of writing partial entities.
  67. */
  68. export class EntityDecoder {
  69. constructor(
  70. /** The tree used to decode entities. */
  71. decodeTree,
  72. /**
  73. * The function that is called when a codepoint is decoded.
  74. *
  75. * For multi-byte named entities, this will be called multiple times,
  76. * with the second codepoint, and the same `consumed` value.
  77. *
  78. * @param codepoint The decoded codepoint.
  79. * @param consumed The number of bytes consumed by the decoder.
  80. */
  81. emitCodePoint,
  82. /** An object that is used to produce errors. */
  83. errors) {
  84. this.decodeTree = decodeTree;
  85. this.emitCodePoint = emitCodePoint;
  86. this.errors = errors;
  87. /** The current state of the decoder. */
  88. this.state = EntityDecoderState.EntityStart;
  89. /** Characters that were consumed while parsing an entity. */
  90. this.consumed = 1;
  91. /**
  92. * The result of the entity.
  93. *
  94. * Either the result index of a numeric entity, or the codepoint of a
  95. * numeric entity.
  96. */
  97. this.result = 0;
  98. /** The current index in the decode tree. */
  99. this.treeIndex = 0;
  100. /** The number of characters that were consumed in excess. */
  101. this.excess = 1;
  102. /** The mode in which the decoder is operating. */
  103. this.decodeMode = DecodingMode.Strict;
  104. }
  105. /** Resets the instance to make it reusable. */
  106. startEntity(decodeMode) {
  107. this.decodeMode = decodeMode;
  108. this.state = EntityDecoderState.EntityStart;
  109. this.result = 0;
  110. this.treeIndex = 0;
  111. this.excess = 1;
  112. this.consumed = 1;
  113. }
  114. /**
  115. * Write an entity to the decoder. This can be called multiple times with partial entities.
  116. * If the entity is incomplete, the decoder will return -1.
  117. *
  118. * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
  119. * entity is incomplete, and resume when the next string is written.
  120. *
  121. * @param input The string containing the entity (or a continuation of the entity).
  122. * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
  123. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  124. */
  125. write(input, offset) {
  126. switch (this.state) {
  127. case EntityDecoderState.EntityStart: {
  128. if (input.charCodeAt(offset) === CharCodes.NUM) {
  129. this.state = EntityDecoderState.NumericStart;
  130. this.consumed += 1;
  131. return this.stateNumericStart(input, offset + 1);
  132. }
  133. this.state = EntityDecoderState.NamedEntity;
  134. return this.stateNamedEntity(input, offset);
  135. }
  136. case EntityDecoderState.NumericStart: {
  137. return this.stateNumericStart(input, offset);
  138. }
  139. case EntityDecoderState.NumericDecimal: {
  140. return this.stateNumericDecimal(input, offset);
  141. }
  142. case EntityDecoderState.NumericHex: {
  143. return this.stateNumericHex(input, offset);
  144. }
  145. case EntityDecoderState.NamedEntity: {
  146. return this.stateNamedEntity(input, offset);
  147. }
  148. }
  149. }
  150. /**
  151. * Switches between the numeric decimal and hexadecimal states.
  152. *
  153. * Equivalent to the `Numeric character reference state` in the HTML spec.
  154. *
  155. * @param input The string containing the entity (or a continuation of the entity).
  156. * @param offset The current offset.
  157. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  158. */
  159. stateNumericStart(input, offset) {
  160. if (offset >= input.length) {
  161. return -1;
  162. }
  163. if ((input.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
  164. this.state = EntityDecoderState.NumericHex;
  165. this.consumed += 1;
  166. return this.stateNumericHex(input, offset + 1);
  167. }
  168. this.state = EntityDecoderState.NumericDecimal;
  169. return this.stateNumericDecimal(input, offset);
  170. }
  171. addToNumericResult(input, start, end, base) {
  172. if (start !== end) {
  173. const digitCount = end - start;
  174. this.result =
  175. this.result * Math.pow(base, digitCount) +
  176. Number.parseInt(input.substr(start, digitCount), base);
  177. this.consumed += digitCount;
  178. }
  179. }
  180. /**
  181. * Parses a hexadecimal numeric entity.
  182. *
  183. * Equivalent to the `Hexademical character reference state` in the HTML spec.
  184. *
  185. * @param input The string containing the entity (or a continuation of the entity).
  186. * @param offset The current offset.
  187. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  188. */
  189. stateNumericHex(input, offset) {
  190. const startIndex = offset;
  191. while (offset < input.length) {
  192. const char = input.charCodeAt(offset);
  193. if (isNumber(char) || isHexadecimalCharacter(char)) {
  194. offset += 1;
  195. }
  196. else {
  197. this.addToNumericResult(input, startIndex, offset, 16);
  198. return this.emitNumericEntity(char, 3);
  199. }
  200. }
  201. this.addToNumericResult(input, startIndex, offset, 16);
  202. return -1;
  203. }
  204. /**
  205. * Parses a decimal numeric entity.
  206. *
  207. * Equivalent to the `Decimal character reference state` in the HTML spec.
  208. *
  209. * @param input The string containing the entity (or a continuation of the entity).
  210. * @param offset The current offset.
  211. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  212. */
  213. stateNumericDecimal(input, offset) {
  214. const startIndex = offset;
  215. while (offset < input.length) {
  216. const char = input.charCodeAt(offset);
  217. if (isNumber(char)) {
  218. offset += 1;
  219. }
  220. else {
  221. this.addToNumericResult(input, startIndex, offset, 10);
  222. return this.emitNumericEntity(char, 2);
  223. }
  224. }
  225. this.addToNumericResult(input, startIndex, offset, 10);
  226. return -1;
  227. }
  228. /**
  229. * Validate and emit a numeric entity.
  230. *
  231. * Implements the logic from the `Hexademical character reference start
  232. * state` and `Numeric character reference end state` in the HTML spec.
  233. *
  234. * @param lastCp The last code point of the entity. Used to see if the
  235. * entity was terminated with a semicolon.
  236. * @param expectedLength The minimum number of characters that should be
  237. * consumed. Used to validate that at least one digit
  238. * was consumed.
  239. * @returns The number of characters that were consumed.
  240. */
  241. emitNumericEntity(lastCp, expectedLength) {
  242. var _a;
  243. // Ensure we consumed at least one digit.
  244. if (this.consumed <= expectedLength) {
  245. (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed);
  246. return 0;
  247. }
  248. // Figure out if this is a legit end of the entity
  249. if (lastCp === CharCodes.SEMI) {
  250. this.consumed += 1;
  251. }
  252. else if (this.decodeMode === DecodingMode.Strict) {
  253. return 0;
  254. }
  255. this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
  256. if (this.errors) {
  257. if (lastCp !== CharCodes.SEMI) {
  258. this.errors.missingSemicolonAfterCharacterReference();
  259. }
  260. this.errors.validateNumericCharacterReference(this.result);
  261. }
  262. return this.consumed;
  263. }
  264. /**
  265. * Parses a named entity.
  266. *
  267. * Equivalent to the `Named character reference state` in the HTML spec.
  268. *
  269. * @param input The string containing the entity (or a continuation of the entity).
  270. * @param offset The current offset.
  271. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  272. */
  273. stateNamedEntity(input, offset) {
  274. const { decodeTree } = this;
  275. let current = decodeTree[this.treeIndex];
  276. // The mask is the number of bytes of the value, including the current byte.
  277. let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
  278. for (; offset < input.length; offset++, this.excess++) {
  279. const char = input.charCodeAt(offset);
  280. this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
  281. if (this.treeIndex < 0) {
  282. return this.result === 0 ||
  283. // If we are parsing an attribute
  284. (this.decodeMode === DecodingMode.Attribute &&
  285. // We shouldn't have consumed any characters after the entity,
  286. (valueLength === 0 ||
  287. // And there should be no invalid characters.
  288. isEntityInAttributeInvalidEnd(char)))
  289. ? 0
  290. : this.emitNotTerminatedNamedEntity();
  291. }
  292. current = decodeTree[this.treeIndex];
  293. valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
  294. // If the branch is a value, store it and continue
  295. if (valueLength !== 0) {
  296. // If the entity is terminated by a semicolon, we are done.
  297. if (char === CharCodes.SEMI) {
  298. return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
  299. }
  300. // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it.
  301. if (this.decodeMode !== DecodingMode.Strict) {
  302. this.result = this.treeIndex;
  303. this.consumed += this.excess;
  304. this.excess = 0;
  305. }
  306. }
  307. }
  308. return -1;
  309. }
  310. /**
  311. * Emit a named entity that was not terminated with a semicolon.
  312. *
  313. * @returns The number of characters consumed.
  314. */
  315. emitNotTerminatedNamedEntity() {
  316. var _a;
  317. const { result, decodeTree } = this;
  318. const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14;
  319. this.emitNamedEntityData(result, valueLength, this.consumed);
  320. (_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference();
  321. return this.consumed;
  322. }
  323. /**
  324. * Emit a named entity.
  325. *
  326. * @param result The index of the entity in the decode tree.
  327. * @param valueLength The number of bytes in the entity.
  328. * @param consumed The number of characters consumed.
  329. *
  330. * @returns The number of characters consumed.
  331. */
  332. emitNamedEntityData(result, valueLength, consumed) {
  333. const { decodeTree } = this;
  334. this.emitCodePoint(valueLength === 1
  335. ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH
  336. : decodeTree[result + 1], consumed);
  337. if (valueLength === 3) {
  338. // For multi-byte values, we need to emit the second byte.
  339. this.emitCodePoint(decodeTree[result + 2], consumed);
  340. }
  341. return consumed;
  342. }
  343. /**
  344. * Signal to the parser that the end of the input was reached.
  345. *
  346. * Remaining data will be emitted and relevant errors will be produced.
  347. *
  348. * @returns The number of characters consumed.
  349. */
  350. end() {
  351. var _a;
  352. switch (this.state) {
  353. case EntityDecoderState.NamedEntity: {
  354. // Emit a named entity if we have one.
  355. return this.result !== 0 &&
  356. (this.decodeMode !== DecodingMode.Attribute ||
  357. this.result === this.treeIndex)
  358. ? this.emitNotTerminatedNamedEntity()
  359. : 0;
  360. }
  361. // Otherwise, emit a numeric entity if we have one.
  362. case EntityDecoderState.NumericDecimal: {
  363. return this.emitNumericEntity(0, 2);
  364. }
  365. case EntityDecoderState.NumericHex: {
  366. return this.emitNumericEntity(0, 3);
  367. }
  368. case EntityDecoderState.NumericStart: {
  369. (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed);
  370. return 0;
  371. }
  372. case EntityDecoderState.EntityStart: {
  373. // Return 0 if we have no entity.
  374. return 0;
  375. }
  376. }
  377. }
  378. }
  379. /**
  380. * Creates a function that decodes entities in a string.
  381. *
  382. * @param decodeTree The decode tree.
  383. * @returns A function that decodes entities in a string.
  384. */
  385. function getDecoder(decodeTree) {
  386. let returnValue = "";
  387. const decoder = new EntityDecoder(decodeTree, (data) => (returnValue += fromCodePoint(data)));
  388. return function decodeWithTrie(input, decodeMode) {
  389. let lastIndex = 0;
  390. let offset = 0;
  391. while ((offset = input.indexOf("&", offset)) >= 0) {
  392. returnValue += input.slice(lastIndex, offset);
  393. decoder.startEntity(decodeMode);
  394. const length = decoder.write(input,
  395. // Skip the "&"
  396. offset + 1);
  397. if (length < 0) {
  398. lastIndex = offset + decoder.end();
  399. break;
  400. }
  401. lastIndex = offset + length;
  402. // If `length` is 0, skip the current `&` and continue.
  403. offset = length === 0 ? lastIndex + 1 : lastIndex;
  404. }
  405. const result = returnValue + input.slice(lastIndex);
  406. // Make sure we don't keep a reference to the final string.
  407. returnValue = "";
  408. return result;
  409. };
  410. }
  411. /**
  412. * Determines the branch of the current node that is taken given the current
  413. * character. This function is used to traverse the trie.
  414. *
  415. * @param decodeTree The trie.
  416. * @param current The current node.
  417. * @param nodeIdx The index right after the current node and its value.
  418. * @param char The current character.
  419. * @returns The index of the next node, or -1 if no branch is taken.
  420. */
  421. export function determineBranch(decodeTree, current, nodeIndex, char) {
  422. const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
  423. const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
  424. // Case 1: Single branch encoded in jump offset
  425. if (branchCount === 0) {
  426. return jumpOffset !== 0 && char === jumpOffset ? nodeIndex : -1;
  427. }
  428. // Case 2: Multiple branches encoded in jump table
  429. if (jumpOffset) {
  430. const value = char - jumpOffset;
  431. return value < 0 || value >= branchCount
  432. ? -1
  433. : decodeTree[nodeIndex + value] - 1;
  434. }
  435. // Case 3: Multiple branches encoded in dictionary
  436. // Binary search for the character.
  437. let lo = nodeIndex;
  438. let hi = lo + branchCount - 1;
  439. while (lo <= hi) {
  440. const mid = (lo + hi) >>> 1;
  441. const midValue = decodeTree[mid];
  442. if (midValue < char) {
  443. lo = mid + 1;
  444. }
  445. else if (midValue > char) {
  446. hi = mid - 1;
  447. }
  448. else {
  449. return decodeTree[mid + branchCount];
  450. }
  451. }
  452. return -1;
  453. }
  454. const htmlDecoder = /* #__PURE__ */ getDecoder(htmlDecodeTree);
  455. const xmlDecoder = /* #__PURE__ */ getDecoder(xmlDecodeTree);
  456. /**
  457. * Decodes an HTML string.
  458. *
  459. * @param htmlString The string to decode.
  460. * @param mode The decoding mode.
  461. * @returns The decoded string.
  462. */
  463. export function decodeHTML(htmlString, mode = DecodingMode.Legacy) {
  464. return htmlDecoder(htmlString, mode);
  465. }
  466. /**
  467. * Decodes an HTML string in an attribute.
  468. *
  469. * @param htmlAttribute The string to decode.
  470. * @returns The decoded string.
  471. */
  472. export function decodeHTMLAttribute(htmlAttribute) {
  473. return htmlDecoder(htmlAttribute, DecodingMode.Attribute);
  474. }
  475. /**
  476. * Decodes an HTML string, requiring all entities to be terminated by a semicolon.
  477. *
  478. * @param htmlString The string to decode.
  479. * @returns The decoded string.
  480. */
  481. export function decodeHTMLStrict(htmlString) {
  482. return htmlDecoder(htmlString, DecodingMode.Strict);
  483. }
  484. /**
  485. * Decodes an XML string, requiring all entities to be terminated by a semicolon.
  486. *
  487. * @param xmlString The string to decode.
  488. * @returns The decoded string.
  489. */
  490. export function decodeXML(xmlString) {
  491. return xmlDecoder(xmlString, DecodingMode.Strict);
  492. }
  493. // Re-export for use by eg. htmlparser2
  494. export { htmlDecodeTree } from "./generated/decode-data-html.js";
  495. export { xmlDecodeTree } from "./generated/decode-data-xml.js";
  496. export { decodeCodePoint, replaceCodePoint, fromCodePoint, } from "./decode-codepoint.js";
  497. //# sourceMappingURL=decode.js.map