single-file-core.js 25 KB

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