single-file-core.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. const SingleFileCore = (() => {
  21. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  22. const REMOVED_CONTENT_ATTRIBUTE_NAME = "data-single-file-removed-content";
  23. let Download, DOM, URL;
  24. function SingleFileCore(...args) {
  25. [Download, DOM, URL] = args;
  26. return class {
  27. static async initialize(options) {
  28. const processor = new PageProcessor(options);
  29. processor.onprogress = options.onprogress;
  30. await processor.loadPage(options.content);
  31. return async () => {
  32. await processor.initialize();
  33. return await processor.getPageData();
  34. };
  35. }
  36. };
  37. }
  38. // -------------
  39. // ProgressEvent
  40. // -------------
  41. const PAGE_LOADING = "page-loading";
  42. const PAGE_LOADED = "page-loaded";
  43. const RESOURCES_INITIALIZING = "resource-initializing";
  44. const RESOURCES_INITIALIZED = "resources-initialized";
  45. const RESOURCE_LOADING = "resource-loading";
  46. const RESOURCE_LOADED = "resource-loaded";
  47. const PAGE_ENDED = "page-ended";
  48. class ProgressEvent {
  49. constructor(type, details) {
  50. return { type, details, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADING, RESOURCE_LOADED, PAGE_ENDED };
  51. }
  52. }
  53. // -------------
  54. // PageProcessor
  55. // -------------
  56. class PageProcessor {
  57. constructor(options) {
  58. this.options = options;
  59. this.processor = new DOMProcessor(options);
  60. }
  61. async loadPage(pageContent) {
  62. if (this.onprogress) {
  63. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url }));
  64. }
  65. await this.processor.loadPage(pageContent);
  66. if (this.onprogress) {
  67. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url }));
  68. }
  69. }
  70. async initialize() {
  71. if (this.onprogress) {
  72. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  73. }
  74. if (!this.options.jsEnabled || (this.options.saveRawPage && this.options.removeScripts)) {
  75. this.processor.insertNoscriptContents();
  76. }
  77. if (this.options.removeFrames) {
  78. this.processor.removeFrames();
  79. }
  80. if (this.options.removeImports) {
  81. this.processor.removeImports();
  82. }
  83. if (this.options.removeScripts) {
  84. this.processor.removeScripts();
  85. }
  86. this.processor.removeDiscardedResources();
  87. this.processor.resetCharsetMeta();
  88. if (this.options.compressHTML) {
  89. this.processor.compressHTML();
  90. }
  91. if (this.options.insertFaviconLink) {
  92. this.processor.insertFaviconLink();
  93. }
  94. this.processor.resolveHrefs();
  95. if (this.options.insertSingleFileComment) {
  96. this.processor.insertSingleFileCommentNode();
  97. }
  98. this.processor.replaceCanvasElements();
  99. if (this.options.removeHiddenElements) {
  100. this.processor.removeHiddenElements();
  101. }
  102. if (this.options.removeUnusedCSSRules) {
  103. this.processor.removeUnusedCSSRules();
  104. }
  105. const initializationPromises = [this.processor.inlineStylesheets(true), this.processor.linkStylesheets(), this.processor.attributeStyles(true)];
  106. if (!this.options.removeFrames) {
  107. initializationPromises.push(this.processor.frames(true));
  108. }
  109. if (!this.options.removeImports) {
  110. initializationPromises.push(this.processor.htmlImports(true));
  111. }
  112. await Promise.all(initializationPromises);
  113. this.pendingPromises = [this.processor.inlineStylesheets(), this.processor.attributeStyles(), this.processor.pageResources()];
  114. if (!this.options.removeScripts) {
  115. this.pendingPromises.push(this.processor.scripts());
  116. }
  117. if (this.onprogress) {
  118. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: batchRequest.getMaxResources() }));
  119. }
  120. }
  121. async getPageData() {
  122. await this.processor.retrieveResources(
  123. details => {
  124. if (this.onprogress) {
  125. details.pageURL = this.options.url;
  126. this.onprogress(new ProgressEvent(RESOURCE_LOADING, details));
  127. }
  128. },
  129. details => {
  130. if (this.onprogress) {
  131. details.pageURL = this.options.url;
  132. this.onprogress(new ProgressEvent(RESOURCE_LOADED, details));
  133. }
  134. });
  135. await this.pendingPromises;
  136. if (this.options.lazyLoadImages) {
  137. this.processor.lazyLoadImages();
  138. }
  139. if (this.options.removeUnusedCSSRules) {
  140. this.processor.removeUnusedCSSRules();
  141. }
  142. if (!this.options.removeFrames) {
  143. await this.processor.frames();
  144. }
  145. if (!this.options.removeImports) {
  146. await this.processor.htmlImports();
  147. }
  148. if (this.onprogress) {
  149. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  150. }
  151. return this.processor.getPageData();
  152. }
  153. }
  154. // --------
  155. // BatchRequest
  156. // --------
  157. class BatchRequest {
  158. constructor() {
  159. this.requests = new Map();
  160. }
  161. async addURL(resourceURL) {
  162. return new Promise((resolve, reject) => {
  163. const resourceRequests = this.requests.get(resourceURL);
  164. if (resourceRequests) {
  165. resourceRequests.push({ resolve, reject });
  166. } else {
  167. this.requests.set(resourceURL, [{ resolve, reject }]);
  168. }
  169. });
  170. }
  171. getMaxResources() {
  172. return Array.from(this.requests.keys()).length;
  173. }
  174. async run(beforeListener, afterListener, options) {
  175. const resourceURLs = Array.from(this.requests.keys());
  176. let indexResource = 1, indexAfterResource = 1;
  177. return Promise.all(resourceURLs.map(async resourceURL => {
  178. let error;
  179. const resourceRequests = this.requests.get(resourceURL);
  180. beforeListener({ index: indexResource, max: resourceURLs.length, url: resourceURL, error });
  181. indexResource = indexResource + 1;
  182. try {
  183. const dataURI = await Download.getContent(resourceURL, { asDataURI: true, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  184. resourceRequests.forEach(resourceRequest => resourceRequest.resolve(dataURI));
  185. } catch (responseError) {
  186. error = responseError;
  187. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  188. }
  189. afterListener({ index: indexAfterResource, max: resourceURLs.length, url: resourceURL, error });
  190. indexAfterResource = indexAfterResource + 1;
  191. this.requests.delete(resourceURL);
  192. }));
  193. }
  194. }
  195. // ------------
  196. // DOMProcessor
  197. // ------------
  198. const ESCAPED_FRAGMENT = "_escaped_fragment_=";
  199. const EMPTY_DATA_URI = "data:base64,";
  200. const batchRequest = new BatchRequest();
  201. class DOMProcessor {
  202. constructor(options) {
  203. this.options = options;
  204. this.baseURI = options.url;
  205. }
  206. async loadPage(pageContent) {
  207. if (!pageContent || this.options.saveRawPage) {
  208. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  209. }
  210. this.dom = DOM.create(pageContent, this.baseURI);
  211. this.DOMParser = this.dom.DOMParser;
  212. this.doc = this.dom.document;
  213. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  214. await DOMProcessor.loadEscapedFragmentPage();
  215. }
  216. }
  217. async loadEscapedFragmentPage() {
  218. if (this.baseURI.includes("?")) {
  219. this.baseURI += "&";
  220. } else {
  221. this.baseURI += "?";
  222. }
  223. this.baseURI += ESCAPED_FRAGMENT;
  224. await this.loadPage();
  225. }
  226. async retrieveResources(beforeListener, afterListener) {
  227. await batchRequest.run(beforeListener, afterListener, this.options);
  228. }
  229. getPageData() {
  230. if (this.options.selected) {
  231. const selectedElement = this.doc.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]");
  232. DomProcessorHelper.isolateElement(selectedElement.parentElement, selectedElement);
  233. selectedElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  234. }
  235. const titleElement = this.doc.querySelector("title");
  236. let title;
  237. if (titleElement) {
  238. title = titleElement.textContent.trim();
  239. }
  240. return {
  241. title: title || (this.baseURI ? this.baseURI.match(/([^/]*)\/?$/) : ""),
  242. content: this.dom.serialize()
  243. };
  244. }
  245. insertNoscriptContents() {
  246. if (this.DOMParser) {
  247. this.doc.querySelectorAll("noscript").forEach(element => {
  248. const fragment = this.doc.createDocumentFragment();
  249. Array.from(element.childNodes).forEach(node => {
  250. const parsedNode = new this.DOMParser().parseFromString(node.nodeValue, "text/html");
  251. Array.from(parsedNode.head.childNodes).concat(Array.from(parsedNode.body.childNodes)).forEach(node => {
  252. this.doc.importNode(node);
  253. fragment.appendChild(node);
  254. });
  255. });
  256. element.parentElement.replaceChild(fragment, element);
  257. });
  258. }
  259. }
  260. lazyLoadImages() {
  261. this.doc.querySelectorAll("img[data-src]").forEach(imgElement => {
  262. const dataSrc = imgElement.dataset.src;
  263. if (dataSrc && dataSrc.startsWith(DATA_URI_PREFIX) && dataSrc != EMPTY_DATA_URI && imgElement.src != dataSrc) {
  264. imgElement.src = imgElement.dataset.src;
  265. imgElement.removeAttribute("data-src");
  266. }
  267. });
  268. this.doc.querySelectorAll("img[data-original]").forEach(imgElement => {
  269. const dataOriginal = imgElement.dataset.original;
  270. if (dataOriginal && dataOriginal.startsWith(DATA_URI_PREFIX) && dataOriginal != EMPTY_DATA_URI && imgElement.src != dataOriginal) {
  271. imgElement.src = imgElement.dataset.original;
  272. imgElement.removeAttribute("data-original");
  273. }
  274. });
  275. this.doc.querySelectorAll("[data-bg]").forEach(element => {
  276. const dataBg = element.dataset.bg;
  277. if (dataBg && dataBg.startsWith(DATA_URI_PREFIX) && dataBg != EMPTY_DATA_URI && !element.style.backgroundImage.includes(dataBg)) {
  278. element.style.backgroundImage = "url(" + element.dataset.bg + ")";
  279. element.removeAttribute("data-bg");
  280. }
  281. });
  282. this.doc.querySelectorAll("[data-srcset]").forEach(imgElement => {
  283. if (imgElement.dataset.srcset && imgElement.srcset != imgElement.dataset.srcset) {
  284. imgElement.srcset = imgElement.dataset.srcset;
  285. imgElement.removeAttribute("data-srcset");
  286. imgElement.classList.remove("no-src");
  287. }
  288. });
  289. }
  290. removeDiscardedResources() {
  291. this.doc.querySelectorAll("applet, meta[http-equiv=refresh], object:not([type=\"image/svg+xml\"]):not([type=\"image/svg-xml\"]):not([type=\"text/html\"]), embed:not([src*=\".svg\"]), link[rel*=preload], link[rel*=prefetch]").forEach(element => element.remove());
  292. this.doc.querySelectorAll("[onload]").forEach(element => element.removeAttribute("onload"));
  293. this.doc.querySelectorAll("[onerror]").forEach(element => element.removeAttribute("onerror"));
  294. this.doc.querySelectorAll("audio[src], video[src]").forEach(element => element.removeAttribute("src"));
  295. }
  296. removeScripts() {
  297. this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])").forEach(element => element.remove());
  298. }
  299. removeFrames() {
  300. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  301. }
  302. removeImports() {
  303. this.doc.querySelectorAll("link[rel=import]").forEach(element => element.remove());
  304. }
  305. resetCharsetMeta() {
  306. this.doc.querySelectorAll("meta[charset]").forEach(element => element.remove());
  307. const metaElement = this.doc.createElement("meta");
  308. metaElement.setAttribute("charset", "utf-8");
  309. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  310. }
  311. insertFaviconLink() {
  312. let faviconElement = this.doc.querySelectorAll("link[href][rel*=\"icon\"]")[0];
  313. if (!faviconElement) {
  314. faviconElement = this.doc.createElement("link");
  315. faviconElement.setAttribute("type", "image/x-icon");
  316. faviconElement.setAttribute("rel", "shortcut icon");
  317. faviconElement.setAttribute("href", "/favicon.ico");
  318. this.doc.head.appendChild(faviconElement);
  319. }
  320. }
  321. resolveHrefs() {
  322. this.doc.querySelectorAll("[href]").forEach(element => element.setAttribute("href", element.href));
  323. }
  324. removeUnusedCSSRules() {
  325. const doc = this.doc;
  326. doc.querySelectorAll("style").forEach(style => {
  327. const cssRules = [];
  328. if (style.sheet) {
  329. processRules(style.sheet.cssRules, cssRules);
  330. const stylesheetContent = cssRules.join("");
  331. style.textContent = this.options.compressCSS ? this.dom.uglifycss(stylesheetContent) : stylesheetContent;
  332. }
  333. });
  334. function processRules(rules, cssRules) {
  335. const REGEXP = /::after|::before|::first-line|::first-letter|:focus|:focus-within|:hover|:link|:visited|:active/gi;
  336. if (rules) {
  337. Array.from(rules).forEach(rule => {
  338. if (rule.media) {
  339. cssRules.push("@media " + Array.prototype.join.call(rule.media, ",") + " {");
  340. processRules(rule.cssRules, cssRules);
  341. cssRules.push("}");
  342. } else if (rule.selectorText) {
  343. let selector = rule.selectorText;
  344. if (selector.match(REGEXP)) {
  345. let selectors = selector.split(/\s*,\s*/g);
  346. selector = selectors.map(selector => {
  347. const simpleSelectors = selector.split(/\s*[ >~+]\s*/g);
  348. const separators = selector.match(/\s*[ >~+]\s*/g);
  349. return simpleSelectors.map((selector, selectorIndex) => {
  350. while (selector.match(REGEXP)) {
  351. selector = selector.replace(REGEXP, "").trim();
  352. }
  353. selector = selector.replace(/:?:[^(]+\(\)/g, "");
  354. if (selector == "") {
  355. selector = "*";
  356. }
  357. return selector + (separators && separators[selectorIndex] ? separators[selectorIndex] : "");
  358. }).join("");
  359. }).join(",");
  360. }
  361. if (selector) {
  362. try {
  363. if (doc.querySelector(selector)) {
  364. cssRules.push(rule.cssText);
  365. }
  366. } catch (e) {
  367. cssRules.push(rule.cssText);
  368. }
  369. }
  370. } else {
  371. cssRules.push(rule.cssText);
  372. }
  373. });
  374. }
  375. }
  376. }
  377. removeHiddenElements() {
  378. this.doc.querySelectorAll("[" + REMOVED_CONTENT_ATTRIBUTE_NAME + "]").forEach(element => element.remove());
  379. }
  380. compressHTML() {
  381. const textNodesWalker = this.doc.createTreeWalker(this.doc.documentElement, 4, null, false);
  382. let node = textNodesWalker.nextNode();
  383. while (node) {
  384. let element = node.parentElement;
  385. while (element && element.tagName != "PRE") {
  386. element = element.parentElement;
  387. }
  388. if (!element) {
  389. node.textContent = node.textContent.replace(/ +/g, " ");
  390. node.textContent = node.textContent.replace(/\n+/g, " ");
  391. }
  392. node = textNodesWalker.nextNode();
  393. }
  394. const commentNodesWalker = this.doc.createTreeWalker(this.doc.documentElement, 128, null, false);
  395. node = commentNodesWalker.nextNode();
  396. let removedNodes = [];
  397. while (node) {
  398. removedNodes.push(node);
  399. node = commentNodesWalker.nextNode();
  400. }
  401. removedNodes.forEach(node => node.remove());
  402. }
  403. insertSingleFileCommentNode() {
  404. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  405. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  406. }
  407. replaceCanvasElements() {
  408. if (this.options.canvasData) {
  409. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  410. const canvasData = this.options.canvasData[indexCanvasElement];
  411. if (canvasData) {
  412. const imgElement = this.doc.createElement("img");
  413. imgElement.setAttribute("src", canvasData.dataURI);
  414. Array.from(canvasElement.attributes).forEach(attribute => {
  415. if (attribute.value) {
  416. imgElement.setAttribute(attribute.name, attribute.value);
  417. }
  418. });
  419. if (!imgElement.width && canvasData.width) {
  420. imgElement.style.pixelWidth = canvasData.width;
  421. }
  422. if (!imgElement.height && canvasData.height) {
  423. imgElement.style.pixelHeight = canvasData.height;
  424. }
  425. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  426. }
  427. });
  428. }
  429. }
  430. async pageResources() {
  431. const resourcePromises = [
  432. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI),
  433. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[src], input[src][type=image], object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"], embed[src*=\".svg\"]"), "src", this.baseURI),
  434. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI),
  435. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI),
  436. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image, use"), "xlink:href", this.baseURI),
  437. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[srcset]"), "srcset", this.baseURI, this.dom.parseSrcset)
  438. ];
  439. if (this.options.lazyLoadImages) {
  440. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[data-src]"), "data-src", this.baseURI));
  441. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[data-original]"), "data-original", this.baseURI));
  442. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[data-bg]"), "data-bg", this.baseURI));
  443. resourcePromises.push(DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[data-srcset]"), "data-srcset", this.baseURI, this.dom.parseSrcset));
  444. }
  445. await resourcePromises;
  446. }
  447. async inlineStylesheets(initialization) {
  448. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  449. const stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled }) : await DomProcessorHelper.processStylesheet(styleElement.textContent, this.baseURI);
  450. styleElement.textContent = this.options.compressCSS && !this.options.removeUnusedCSSRules ? this.dom.uglifycss(stylesheetContent) : stylesheetContent;
  451. }));
  452. }
  453. async scripts() {
  454. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  455. if (scriptElement.src) {
  456. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  457. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  458. }
  459. scriptElement.removeAttribute("src");
  460. }));
  461. }
  462. async frames(initialization) {
  463. let frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  464. frameElements = DomUtil.removeNoScriptFrames(frameElements);
  465. await Promise.all(frameElements.map(async (frameElement, frameIndex) => {
  466. const frameWindowId = (this.options.windowId || "0") + "." + frameIndex;
  467. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  468. if (frameData) {
  469. if (initialization) {
  470. const options = {
  471. insertSingleFileComment: false,
  472. insertFaviconLink: false,
  473. url: frameData.baseURI,
  474. windowId: frameWindowId,
  475. removeHiddenElements: this.options.removeHiddenElements,
  476. removeUnusedCSSRules: this.options.removeUnusedCSSRules,
  477. jsEnabled: this.options.jsEnabled,
  478. removeScripts: this.options.removeScripts,
  479. saveRawPage: this.options.saveRawPage,
  480. compressHTML: this.options.compressHTML,
  481. compressCSS: this.options.compressCSS,
  482. lazyLoadImages: this.options.lazyLoadImages,
  483. framesData: this.options.framesData,
  484. maxResourceSize: this.options.maxResourceSize,
  485. maxResourceSizeEnabled: this.options.maxResourceSizeEnabled
  486. };
  487. if (frameData.content) {
  488. frameData.processor = new PageProcessor(options);
  489. frameData.frameElement = frameElement;
  490. await frameData.processor.loadPage(frameData.content);
  491. return frameData.processor.initialize();
  492. }
  493. } else {
  494. if (frameElement.tagName == "OBJECT") {
  495. frameElement.setAttribute("data", "about:blank");
  496. } else {
  497. frameElement.setAttribute("src", "about:blank");
  498. }
  499. if (frameData.processor) {
  500. const pageData = await frameData.processor.getPageData();
  501. if (frameElement.tagName == "OBJECT") {
  502. frameElement.setAttribute("data", "data:text/html," + pageData.content);
  503. } else {
  504. frameElement.setAttribute("srcdoc", pageData.content);
  505. frameElement.sandbox = true;
  506. }
  507. }
  508. }
  509. } else {
  510. if (frameElement.tagName == "OBJECT") {
  511. frameElement.setAttribute("data", "about:blank");
  512. } else {
  513. frameElement.setAttribute("src", "about:blank");
  514. }
  515. }
  516. }));
  517. }
  518. async htmlImports(initialization) {
  519. let linkElements = this.doc.querySelectorAll("link[rel=import][href]");
  520. linkElements = DomUtil.removeNoScriptFrames(linkElements);
  521. if (!this.relImportProcessors) {
  522. this.relImportProcessors = new Map();
  523. }
  524. await Promise.all(linkElements.map(async linkElement => {
  525. if (initialization) {
  526. const resourceURL = linkElement.href;
  527. const options = {
  528. insertSingleFileComment: false,
  529. insertFaviconLink: false,
  530. url: resourceURL,
  531. removeHiddenElements: this.options.removeHiddenElements,
  532. removeUnusedCSSRules: this.options.removeUnusedCSSRules,
  533. jsEnabled: this.options.jsEnabled,
  534. removeScripts: this.options.removeScripts,
  535. saveRawPage: this.options.saveRawPage,
  536. compressHTML: this.options.compressHTML,
  537. compressCSS: this.options.compressCSS,
  538. lazyLoadImages: this.options.lazyLoadImages,
  539. framesData: this.options.framesData
  540. };
  541. if (resourceURL) {
  542. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  543. const processor = new PageProcessor(options);
  544. this.relImportProcessors.set(linkElement, processor);
  545. await processor.loadPage();
  546. return processor.initialize();
  547. }
  548. }
  549. } else {
  550. const processor = this.relImportProcessors.get(linkElement);
  551. if (processor) {
  552. this.relImportProcessors.delete(linkElement);
  553. const pageData = await processor.getPageData();
  554. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  555. } else {
  556. linkElement.setAttribute("href", "about:blank");
  557. }
  558. }
  559. }));
  560. }
  561. async attributeStyles(initialization) {
  562. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  563. const stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(element.getAttribute("style"), this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled }) : await DomProcessorHelper.processStylesheet(element.getAttribute("style"), this.baseURI);
  564. element.setAttribute("style", stylesheetContent);
  565. }));
  566. }
  567. async linkStylesheets() {
  568. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  569. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  570. const styleElement = this.doc.createElement("style");
  571. styleElement.textContent = this.options.compressCSS && !this.options.removeUnusedCSSRules ? this.dom.uglifycss(stylesheetContent) : stylesheetContent;
  572. linkElement.parentElement.replaceChild(styleElement, linkElement);
  573. }));
  574. }
  575. }
  576. // ---------
  577. // DomHelper
  578. // ---------
  579. class DomProcessorHelper {
  580. static isolateElement(parentElement, element) {
  581. Array.from(parentElement.childNodes).forEach(node => {
  582. if (node == element) {
  583. node.removeAttribute("style");
  584. node.style.all = "unset";
  585. } else {
  586. if (node.tagName != "HEAD" && node.tagName != "STYLE") {
  587. node.remove();
  588. }
  589. }
  590. });
  591. element = element.parentElement;
  592. if (element.parentElement) {
  593. DomProcessorHelper.isolateElement(element.parentElement, element);
  594. }
  595. }
  596. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  597. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  598. const imports = DomUtil.getImportFunctions(stylesheetContent);
  599. await Promise.all(imports.map(async cssImport => {
  600. const match = DomUtil.matchImport(cssImport);
  601. if (match) {
  602. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  603. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  604. let importedStylesheetContent = await Download.getContent(new URL(match.resourceURL, baseURI).href, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  605. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  606. if (stylesheetContent.indexOf(cssImport) != -1) {
  607. stylesheetContent = stylesheetContent.replace(cssImport, importedStylesheetContent);
  608. }
  609. }
  610. }
  611. }));
  612. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  613. if (imports.length) {
  614. return await DomProcessorHelper.resolveImportURLs(stylesheetContent, baseURI, options);
  615. } else {
  616. return stylesheetContent;
  617. }
  618. }
  619. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  620. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  621. urlFunctions.map(urlFunction => {
  622. let resourceURL = DomUtil.matchURL(urlFunction);
  623. resourceURL = DomUtil.normalizeURL(resourceURL);
  624. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  625. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, new URL(resourceURL, baseURI).href));
  626. }
  627. });
  628. return stylesheetContent;
  629. }
  630. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  631. resourceURL = DomUtil.normalizeURL(resourceURL);
  632. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  633. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  634. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  635. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  636. return stylesheetContent;
  637. }
  638. }
  639. static async processStylesheet(stylesheetContent, baseURI) {
  640. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  641. await Promise.all(urlFunctions.map(async urlFunction => {
  642. let resourceURL = DomUtil.matchURL(urlFunction);
  643. resourceURL = DomUtil.normalizeURL(resourceURL);
  644. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  645. const dataURI = await batchRequest.addURL(resourceURL);
  646. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, dataURI));
  647. }
  648. }));
  649. return stylesheetContent;
  650. }
  651. static async processAttribute(resourceElements, attributeName, baseURI) {
  652. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  653. let resourceURL = resourceElement.getAttribute(attributeName);
  654. if (resourceURL) {
  655. resourceURL = DomUtil.normalizeURL(resourceURL);
  656. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  657. try {
  658. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  659. resourceElement.setAttribute(attributeName, dataURI);
  660. } catch (e) {
  661. // ignored
  662. }
  663. }
  664. }
  665. }));
  666. }
  667. static async processSrcset(resourceElements, attributeName, baseURI, parseSrcset) {
  668. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  669. const srcset = parseSrcset(resourceElement.getAttribute(attributeName));
  670. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  671. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  672. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  673. try {
  674. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  675. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  676. } catch (e) {
  677. // ignored
  678. }
  679. }
  680. }));
  681. resourceElement.setAttribute(attributeName, srcsetValues.join(","));
  682. }));
  683. }
  684. }
  685. // -------
  686. // DomUtil
  687. // -------
  688. const DATA_URI_PREFIX = "data:";
  689. const BLOB_URI_PREFIX = "blob:";
  690. const ABOUT_BLANK_URI = "about:blank";
  691. const REGEXP_URL_FN = /(url\s*\(\s*'([^']*)'\s*\))|(url\s*\(\s*"([^"]*)"\s*\))|(url\s*\(\s*([^)]*)\s*\))/gi;
  692. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'([^']*)'\s*\)$/i;
  693. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"([^"]*)"\s*\)$/i;
  694. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*([^)]*)\s*\)$/i;
  695. const REGEXP_IMPORT_FN = /(@import\s*url\s*\(\s*'([^']*)'\s*\)\s*([^;]*);?)|(@import\s*url\s*\(\s*"([^"]*)"\s*\)\s*([^;]*);?)|(@import\s*url\s*\(\s*([^)]*)\s*\)\s*([^;]*);?)|(@import\s*'([^']*)'\s*([^;]*);?)|(@import\s*"([^"]*)"\s*([^;]*);?)|(@import\s*([^;]*)\s*([^;]*);?)/gi;
  696. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'([^']*)'\s*\)\s*([^;]*)/i;
  697. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"([^"]*)"\s*\)\s*([^;]*)/i;
  698. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*([^)]*)\s*\)\s*([^;]*)/i;
  699. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'([^']*)'\s*([^;]*)/i;
  700. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"([^"]*)"\s*([^;]*)/i;
  701. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*([^;]*)\s*([^;]*)/i;
  702. class DomUtil {
  703. static normalizeURL(url) {
  704. return url.split("#")[0];
  705. }
  706. static getUrlFunctions(stylesheetContent) {
  707. return stylesheetContent.match(REGEXP_URL_FN) || [];
  708. }
  709. static getImportFunctions(stylesheetContent) {
  710. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  711. }
  712. static matchURL(stylesheetContent) {
  713. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  714. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  715. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  716. return match && match[1];
  717. }
  718. static testValidPath(resourceURL) {
  719. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI;
  720. }
  721. static matchImport(stylesheetContent) {
  722. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  723. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  724. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  725. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  726. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  727. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  728. if (match) {
  729. const [, resourceURL, media] = match;
  730. return { resourceURL, media };
  731. }
  732. }
  733. static removeCssComments(stylesheetContent) {
  734. let start, end;
  735. do {
  736. start = stylesheetContent.indexOf("/*");
  737. end = stylesheetContent.indexOf("*/", start);
  738. if (start != -1 && end != -1) {
  739. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  740. }
  741. } while (start != -1 && end != -1);
  742. return stylesheetContent;
  743. }
  744. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  745. if (mediaQuery) {
  746. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  747. } else {
  748. return stylesheetContent;
  749. }
  750. }
  751. static removeNoScriptFrames(frameElements) {
  752. return Array.from(frameElements).filter(element => {
  753. element = element.parentElement;
  754. while (element && element.tagName != "NOSCRIPT") {
  755. element = element.parentElement;
  756. }
  757. return !element;
  758. });
  759. }
  760. }
  761. return SingleFileCore;
  762. })();
  763. if (typeof module != "undefined") {
  764. module.exports = SingleFileCore;
  765. }