parse5-adapter.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
  3. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  4. if (ar || !(i in from)) {
  5. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  6. ar[i] = from[i];
  7. }
  8. }
  9. return to.concat(ar || Array.prototype.slice.call(from));
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. exports.renderWithParse5 = exports.parseWithParse5 = void 0;
  13. var domhandler_1 = require("domhandler");
  14. var parse5_1 = require("parse5");
  15. var parse5_htmlparser2_tree_adapter_1 = require("parse5-htmlparser2-tree-adapter");
  16. /**
  17. * Parse the content with `parse5` in the context of the given `ParentNode`.
  18. *
  19. * @param content - The content to parse.
  20. * @param options - A set of options to use to parse.
  21. * @param isDocument - Whether to parse the content as a full HTML document.
  22. * @param context - The context in which to parse the content.
  23. * @returns The parsed content.
  24. */
  25. function parseWithParse5(content, options, isDocument, context) {
  26. var opts = {
  27. scriptingEnabled: typeof options.scriptingEnabled === 'boolean'
  28. ? options.scriptingEnabled
  29. : true,
  30. treeAdapter: parse5_htmlparser2_tree_adapter_1.adapter,
  31. sourceCodeLocationInfo: options.sourceCodeLocationInfo,
  32. };
  33. return isDocument
  34. ? (0, parse5_1.parse)(content, opts)
  35. : (0, parse5_1.parseFragment)(context, content, opts);
  36. }
  37. exports.parseWithParse5 = parseWithParse5;
  38. var renderOpts = { treeAdapter: parse5_htmlparser2_tree_adapter_1.adapter };
  39. /**
  40. * Renders the given DOM tree with `parse5` and returns the result as a string.
  41. *
  42. * @param dom - The DOM tree to render.
  43. * @returns The rendered document.
  44. */
  45. function renderWithParse5(dom) {
  46. var _a;
  47. /*
  48. * `dom-serializer` passes over the special "root" node and renders the
  49. * node's children in its place. To mimic this behavior with `parse5`, an
  50. * equivalent operation must be applied to the input array.
  51. */
  52. var nodes = 'length' in dom ? dom : [dom];
  53. for (var index = 0; index < nodes.length; index += 1) {
  54. var node = nodes[index];
  55. if ((0, domhandler_1.isDocument)(node)) {
  56. (_a = Array.prototype.splice).call.apply(_a, __spreadArray([nodes, index, 1], node.children, false));
  57. }
  58. }
  59. var result = '';
  60. for (var index = 0; index < nodes.length; index += 1) {
  61. var node = nodes[index];
  62. result += (0, parse5_1.serializeOuter)(node, renderOpts);
  63. }
  64. return result;
  65. }
  66. exports.renderWithParse5 = renderWithParse5;
  67. //# sourceMappingURL=parse5-adapter.js.map