jsdom.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global require, exports */
  24. const fs = require("fs");
  25. const crypto = require("crypto");
  26. const { JSDOM, VirtualConsole } = require("jsdom");
  27. const dataUri = require("strong-data-uri");
  28. const iconv = require("iconv-lite");
  29. const request = require("request-promise-native");
  30. const SCRIPTS = [
  31. "../../lib/frame-tree/content/content-frame-tree.js",
  32. "../../lib/single-file/util/doc-util.js",
  33. "../../lib/single-file/util/doc-helper.js",
  34. "../../lib/single-file/vendor/css-tree.js",
  35. "../../lib/single-file/vendor/html-srcset-parser.js",
  36. "../../lib/single-file/vendor/css-minifier.js",
  37. "../../lib/single-file/vendor/css-font-property-parser.js",
  38. "../../lib/single-file/vendor/css-media-query-parser.js",
  39. "../../lib/single-file/modules/html-minifier.js",
  40. "../../lib/single-file/modules/css-fonts-minifier.js",
  41. "../../lib/single-file/modules/css-fonts-alt-minifier.js",
  42. "../../lib/single-file/modules/css-matched-rules.js",
  43. "../../lib/single-file/modules/css-medias-alt-minifier.js",
  44. "../../lib/single-file/modules/css-rules-minifier.js",
  45. "../../lib/single-file/modules/html-images-alt-minifier.js",
  46. "../../lib/single-file/modules/html-serializer.js",
  47. "../../lib/single-file/single-file-core.js"
  48. ];
  49. exports.getPageData = async options => {
  50. const pageContent = (await request({
  51. method: "GET",
  52. uri: options.url,
  53. resolveWithFullResponse: true,
  54. encoding: null,
  55. headers: {
  56. "User-Agent": options.userAgent
  57. }
  58. })).body.toString();
  59. const jsdomOptions = {
  60. url: options.url,
  61. virtualConsole: new VirtualConsole(),
  62. userAgent: options.userAgent,
  63. pretendToBeVisual: true,
  64. runScripts: "outside-only",
  65. resources: "usable"
  66. };
  67. if (options.browserWidth && options.browserHeight) {
  68. jsdomOptions.beforeParse = function (window) {
  69. window.outerWidth = window.innerWidth = options.browserWidth;
  70. window.outerHeight = window.innerHeight = options.browserHeight;
  71. };
  72. }
  73. let dom;
  74. try {
  75. dom = new JSDOM(pageContent, jsdomOptions);
  76. const win = dom.window;
  77. const doc = win.document;
  78. const scripts = (await Promise.all(SCRIPTS.map(scriptPath => fs.readFileSync(require.resolve(scriptPath)).toString()))).join("\n");
  79. dom.window.eval(scripts);
  80. if (dom.window.document.readyState == "loading") {
  81. await new Promise(resolve => win.document.onload = resolve);
  82. }
  83. win.Element.prototype.getBoundingClientRect = undefined;
  84. executeFrameScripts(doc, scripts);
  85. if (!options.saveRawPage && !options.removeFrames) {
  86. options.framesData = await win.frameTree.getAsync(options);
  87. }
  88. options.win = win;
  89. options.doc = doc;
  90. options.removeHiddenElements = false;
  91. const SingleFile = getSingleFileClass(win);
  92. const singleFile = new SingleFile(options);
  93. await singleFile.run();
  94. return singleFile.getPageData();
  95. } finally {
  96. if (dom && dom.window) {
  97. dom.window.close();
  98. }
  99. }
  100. };
  101. function executeFrameScripts(doc, scripts) {
  102. const frameElements = doc.querySelectorAll("iframe, frame");
  103. frameElements.forEach(frameElement => {
  104. try {
  105. frameElement.contentWindow.Element.prototype.getBoundingClientRect = undefined;
  106. frameElement.contentWindow.eval(scripts);
  107. executeFrameScripts(frameElement.contentDocument, scripts);
  108. } catch (error) {
  109. // ignored
  110. }
  111. });
  112. }
  113. function getSingleFileClass(win) {
  114. const docHelper = win.docHelper;
  115. const modules = {
  116. docHelper: docHelper,
  117. srcsetParser: win.srcsetParser,
  118. cssMinifier: win.cssMinifier,
  119. htmlMinifier: win.htmlMinifier,
  120. serializer: win.serializer,
  121. fontsMinifier: win.fontsMinifier.getInstance(win.cssTree, win.fontPropertyParser, docHelper),
  122. fontsAltMinifier: win.fontsAltMinifier.getInstance(win.cssTree),
  123. cssRulesMinifier: win.cssRulesMinifier.getInstance(win.cssTree),
  124. matchedRules: win.matchedRules.getInstance(win.cssTree),
  125. mediasAltMinifier: win.mediasAltMinifier.getInstance(win.cssTree, win.mediaQueryParser),
  126. imagesAltMinifier: win.imagesAltMinifier.getInstance(win.srcsetParser)
  127. };
  128. const domUtil = {
  129. getResourceContent,
  130. isValidFontUrl,
  131. digestText
  132. };
  133. return win.SingleFileCore.getClass(win.docUtil.getInstance(modules, domUtil), win.cssTree);
  134. }
  135. async function digestText(algo, text) {
  136. const hash = crypto.createHash(algo.replace("-", "").toLowerCase());
  137. hash.update(text, "utf-8");
  138. return hash.digest("hex");
  139. }
  140. function isValidFontUrl(/* urlFunction */) {
  141. // TODO?
  142. return true;
  143. }
  144. async function getResourceContent(resourceURL, options) {
  145. const resourceContent = await request({
  146. method: "GET",
  147. uri: resourceURL,
  148. resolveWithFullResponse: true,
  149. encoding: null,
  150. headers: {
  151. "User-Agent": options.userAgent
  152. }
  153. });
  154. return {
  155. getUrl() {
  156. return resourceContent.request.href;
  157. },
  158. getContentType() {
  159. return resourceContent.headers["content-type"];
  160. },
  161. getStatusCode() {
  162. return resourceContent.statusCode;
  163. },
  164. getSize() {
  165. return resourceContent.body.byteLength;
  166. },
  167. getText(charset) {
  168. return iconv.decode(resourceContent.body, charset);
  169. },
  170. async getDataUri(contentType) {
  171. return dataUri.encode(resourceContent.body, contentType || this.getContentType());
  172. }
  173. };
  174. }