single-file-core.js 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  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. /* global CSSRule */
  21. this.SingleFileCore = this.SingleFileCore || (() => {
  22. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  23. const SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = "data-single-file-selected-content-root";
  24. const DEBUG = false;
  25. let Download, DOM, URL, sessionId = 0;
  26. function getClass(...args) {
  27. [Download, DOM, URL] = args;
  28. return class {
  29. constructor(options) {
  30. this.options = options;
  31. options.sessionId = sessionId;
  32. sessionId++;
  33. this.SELECTED_CONTENT_ATTRIBUTE_NAME = SELECTED_CONTENT_ATTRIBUTE_NAME;
  34. this.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME;
  35. }
  36. async initialize() {
  37. this.processor = new PageProcessor(this.options);
  38. await this.processor.loadPage();
  39. await this.processor.initialize();
  40. }
  41. async preparePageData() {
  42. await this.processor.preparePageData();
  43. }
  44. async getPageData() {
  45. return this.processor.getPageData();
  46. }
  47. };
  48. }
  49. // -------------
  50. // ProgressEvent
  51. // -------------
  52. const PAGE_LOADING = "page-loading";
  53. const PAGE_LOADED = "page-loaded";
  54. const RESOURCES_INITIALIZING = "resource-initializing";
  55. const RESOURCES_INITIALIZED = "resources-initialized";
  56. const RESOURCE_LOADED = "resource-loaded";
  57. const PAGE_ENDED = "page-ended";
  58. class ProgressEvent {
  59. constructor(type, details) {
  60. return { type, details, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADED, PAGE_ENDED };
  61. }
  62. }
  63. // -------------
  64. // PageProcessor
  65. // -------------
  66. const STAGES = [{
  67. sequential: [
  68. { action: "removeUIElements" },
  69. { action: "replaceStyleContents" },
  70. { option: "removeVideoSrc", action: "insertVideoPosters" },
  71. { option: "removeSrcSet", action: "removeSrcSet" },
  72. { option: "removeFrames", action: "removeFrames" },
  73. { option: "removeImports", action: "removeImports" },
  74. { option: "removeScripts", action: "removeScripts" },
  75. { action: "removeDiscardedResources" },
  76. { action: "resetCharsetMeta" },
  77. { action: "setInputValues" },
  78. { option: "insertFaviconLink", action: "insertFaviconLink" },
  79. { action: "resolveHrefs" },
  80. { action: "replaceCanvasElements" },
  81. { action: "insertFonts" },
  82. { option: "removeHiddenElements", action: "removeHiddenElements" }
  83. ],
  84. parallel: [
  85. { action: "resolveStylesheetURLs" },
  86. { action: "resolveLinkedStylesheetURLs" },
  87. { action: "resolveStyleAttributeURLs" },
  88. { option: "!removeFrames", action: "resolveFrameURLs" },
  89. { option: "!removeImports", action: "resolveHtmlImportURLs" }
  90. ]
  91. }, {
  92. sequential: [
  93. { option: "removeUnusedStyles", action: "removeUnusedStyles" },
  94. { option: "groupDuplicateImages", action: "groupDuplicateImages" },
  95. { option: "removeAlternativeFonts", action: "removeAlternativeFonts" },
  96. { option: "removeAlternativeMedias", action: "removeAlternativeMedias" }
  97. ],
  98. parallel: [
  99. { action: "processStylesheets" },
  100. { action: "processStyleAttributes" },
  101. { action: "pageResources" },
  102. { option: "!removeScripts", action: "processScripts" }
  103. ]
  104. }, {
  105. sequential: [
  106. { option: "groupDuplicateImages", action: "setPreservedAspectRatios" },
  107. { option: "lazyLoadImages", action: "lazyLoadImages" },
  108. { option: "removeAlternativeFonts", action: "postRemoveAlternativeFonts" },
  109. { option: "compressCSS", action: "compressCSS" }
  110. ],
  111. parallel: [
  112. { option: "!removeFrames", action: "processFrames" },
  113. { option: "!removeImports", action: "processHtmlImports" },
  114. ]
  115. }, {
  116. sequential: [
  117. { option: "compressHTML", action: "compressHTML" },
  118. { option: "insertSingleFileComment", action: "insertSingleFileComment" },
  119. { action: "removeDefaultHeadTags" }
  120. ]
  121. }];
  122. class PageProcessor {
  123. constructor(options) {
  124. this.options = options;
  125. this.options.url = this.options.url || this.options.doc.location.href;
  126. this.options.baseURI = this.options.doc && this.options.doc.baseURI;
  127. this.batchRequest = new BatchRequest();
  128. this.processor = new DOMProcessor(options, this.batchRequest);
  129. if (this.options.doc) {
  130. const docData = DOM.preProcessDoc(this.options.doc, this.options.win, this.options);
  131. this.options.canvasData = docData.canvasData;
  132. this.options.fontsData = docData.fontsData;
  133. this.options.stylesheetContents = docData.stylesheetContents;
  134. this.options.responsiveImageData = docData.responsiveImageData;
  135. this.options.imageData = docData.imageData;
  136. this.options.postersData = docData.postersData;
  137. }
  138. this.options.content = this.options.content || (this.options.doc ? DOM.serialize(this.options.doc, false) : null);
  139. this.onprogress = options.onprogress || (() => { });
  140. }
  141. async loadPage() {
  142. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url }));
  143. await this.processor.loadPage(this.options.content);
  144. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url }));
  145. }
  146. async initialize() {
  147. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  148. await this.executeStage(0);
  149. this.pendingPromises = this.executeStage(1);
  150. if (this.options.doc) {
  151. DOM.postProcessDoc(this.options.doc, this.options);
  152. this.options.doc = null;
  153. this.options.win = null;
  154. }
  155. }
  156. async preparePageData() {
  157. if (!this.options.windowId) {
  158. this.processor.initialize(this.batchRequest);
  159. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: this.processor.maxResources }));
  160. }
  161. await this.batchRequest.run(details => {
  162. details.pageURL = this.options.url;
  163. this.onprogress(new ProgressEvent(RESOURCE_LOADED, details));
  164. }, this.options);
  165. await this.pendingPromises;
  166. await this.executeStage(2);
  167. await this.executeStage(3);
  168. }
  169. async getPageData() {
  170. if (!this.options.windowId) {
  171. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  172. }
  173. return this.processor.getPageData();
  174. }
  175. async executeStage(step) {
  176. if (DEBUG) {
  177. log("**** STARTED STAGE", step, "****");
  178. }
  179. STAGES[step].sequential.forEach(task => {
  180. let startTime;
  181. if (DEBUG) {
  182. startTime = Date.now();
  183. log(" -- STARTED task =", task.action);
  184. }
  185. this.executeTask(task);
  186. if (DEBUG) {
  187. log(" -- ENDED task =", task.action, "delay =", Date.now() - startTime);
  188. }
  189. });
  190. if (STAGES[step].parallel) {
  191. return await Promise.all(STAGES[step].parallel.map(task => {
  192. let startTime;
  193. if (DEBUG) {
  194. startTime = Date.now();
  195. log(" // STARTED task =", task.action);
  196. }
  197. const promise = this.executeTask(task);
  198. if (DEBUG) {
  199. promise.then(() => log(" // ENDED task =", task.action, "delay =", Date.now() - startTime));
  200. }
  201. return promise;
  202. }));
  203. }
  204. if (DEBUG) {
  205. log("**** ENDED STAGE", step, "****");
  206. }
  207. }
  208. executeTask(task) {
  209. if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
  210. return this.processor[task.action]();
  211. }
  212. }
  213. }
  214. // --------
  215. // BatchRequest
  216. // --------
  217. class BatchRequest {
  218. constructor() {
  219. this.requests = new Map();
  220. }
  221. async addURL(resourceURL, asDataURI = true) {
  222. return new Promise((resolve, reject) => {
  223. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  224. const resourceRequests = this.requests.get(requestKey);
  225. if (resourceRequests) {
  226. resourceRequests.push({ resolve, reject });
  227. } else {
  228. this.requests.set(requestKey, [{ resolve, reject }]);
  229. }
  230. });
  231. }
  232. getMaxResources() {
  233. return Array.from(this.requests.keys()).length;
  234. }
  235. async run(onloadListener, options) {
  236. const resourceURLs = Array.from(this.requests.keys());
  237. let indexResource = 0;
  238. return Promise.all(resourceURLs.map(async requestKey => {
  239. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  240. const resourceRequests = this.requests.get(requestKey);
  241. try {
  242. const dataURI = await Download.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  243. indexResource = indexResource + 1;
  244. onloadListener({ index: indexResource, url: resourceURL });
  245. resourceRequests.forEach(resourceRequest => resourceRequest.resolve(dataURI));
  246. } catch (error) {
  247. indexResource = indexResource + 1;
  248. onloadListener({ index: indexResource, url: resourceURL });
  249. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  250. }
  251. this.requests.delete(requestKey);
  252. }));
  253. }
  254. }
  255. // ------------
  256. // DOMProcessor
  257. // ------------
  258. const EMPTY_DATA_URI = "data:base64,";
  259. const EMPTY_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  260. class DOMProcessor {
  261. constructor(options, batchRequest) {
  262. this.options = options;
  263. this.stats = new Stats(options);
  264. this.baseURI = DomUtil.normalizeURL(options.baseURI || options.url);
  265. this.batchRequest = batchRequest;
  266. }
  267. initialize() {
  268. this.maxResources = this.batchRequest.getMaxResources();
  269. if (!this.options.removeFrames) {
  270. this.options.framesData.forEach(frameData => this.maxResources += frameData.maxResources || 0);
  271. }
  272. this.stats.set("processed", "resources", this.maxResources);
  273. }
  274. async loadPage(pageContent) {
  275. if (!pageContent || this.options.saveRawPage) {
  276. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  277. }
  278. this.doc = DOM.createDoc(pageContent, this.baseURI);
  279. this.onEventAttributeNames = DOM.getOnEventAttributeNames(this.doc);
  280. }
  281. async getPageData() {
  282. DOM.postProcessDoc(this.doc, this.options);
  283. if (this.options.selected) {
  284. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  285. if (rootElement) {
  286. DomProcessorHelper.isolateElements(rootElement);
  287. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  288. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  289. }
  290. }
  291. const titleElement = this.doc.querySelector("title");
  292. this.options.title = titleElement ? titleElement.textContent.trim() : "";
  293. this.options.info = {};
  294. const descriptionElement = this.doc.querySelector("meta[name=description]");
  295. this.options.info.description = descriptionElement ? descriptionElement.content.trim() : "";
  296. this.options.info.lang = this.doc.documentElement.lang;
  297. const authorElement = this.doc.querySelector("meta[name=author]");
  298. this.options.info.author = authorElement ? authorElement.content.trim() : "";
  299. const creatorElement = this.doc.querySelector("meta[name=creator]");
  300. this.options.info.creator = creatorElement ? creatorElement.content.trim() : "";
  301. const publisherElement = this.doc.querySelector("meta[name=publisher]");
  302. this.options.info.publisher = creatorElement ? publisherElement.content.trim() : "";
  303. const url = new URL(this.baseURI);
  304. let size;
  305. if (this.options.displayStats) {
  306. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  307. }
  308. const content = DOM.serialize(this.doc, this.options.compressHTML);
  309. if (this.options.displayStats) {
  310. const contentSize = DOM.getContentSize(content);
  311. this.stats.set("processed", "HTML bytes", contentSize);
  312. this.stats.add("discarded", "HTML bytes", size - contentSize);
  313. }
  314. const filename = await DomProcessorHelper.getFilename(this.options, content);
  315. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  316. return {
  317. stats: this.stats.data,
  318. title: this.options.title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "")),
  319. filename,
  320. content
  321. };
  322. }
  323. setInputValues() {
  324. this.doc.querySelectorAll("input").forEach(input => {
  325. const value = input.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  326. if (value) {
  327. input.setAttribute("value", value);
  328. }
  329. });
  330. this.doc.querySelectorAll("textarea").forEach(textarea => {
  331. const value = textarea.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  332. if (value) {
  333. textarea.textContent = value;
  334. }
  335. });
  336. this.doc.querySelectorAll("select").forEach(select => {
  337. select.querySelectorAll("option").forEach(option => {
  338. const selected = option.getAttribute(DOM.inputValueAttributeName(this.options.sessionId)) != null;
  339. if (selected) {
  340. option.setAttribute("selected", "");
  341. }
  342. });
  343. });
  344. }
  345. lazyLoadImages() {
  346. DOM.lazyLoad(this.doc);
  347. }
  348. removeDiscardedResources() {
  349. const objectElements = 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\"])");
  350. this.stats.set("discarded", "objects", objectElements.length);
  351. this.stats.set("processed", "objects", objectElements.length);
  352. objectElements.forEach(element => element.remove());
  353. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  354. replacedAttributeValue.forEach(element => {
  355. const relValue = element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "").trim();
  356. if (relValue.length) {
  357. element.setAttribute("rel", relValue);
  358. } else {
  359. element.remove();
  360. }
  361. });
  362. this.doc.querySelectorAll("meta[http-equiv=\"content-security-policy\"]").forEach(element => element.remove());
  363. if (this.options.compressHTML) {
  364. this.doc.querySelectorAll("input[type=hidden]").forEach(element => element.remove());
  365. }
  366. this.doc.querySelectorAll("a[ping]").forEach(element => element.removeAttribute("ping"));
  367. if (this.options.removeScripts) {
  368. this.onEventAttributeNames.forEach(attributeName => this.doc.querySelectorAll("[" + attributeName + "]").forEach(element => element.removeAttribute(attributeName)));
  369. this.doc.querySelectorAll("[href]").forEach(element => {
  370. if (element.href && element.href.match && element.href.match(/^\s*javascript:/)) {
  371. element.removeAttribute("href");
  372. }
  373. });
  374. this.doc.querySelectorAll("[src]").forEach(element => {
  375. if (element.src && element.src.match(/^\s*javascript:/)) {
  376. element.removeAttribute("src");
  377. }
  378. });
  379. }
  380. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  381. this.stats.set("processed", "audio sources", audioSourceElements.length);
  382. if (this.options.removeAudioSrc) {
  383. this.stats.set("discarded", "audio sources", audioSourceElements.length);
  384. audioSourceElements.forEach(element => element.removeAttribute("src"));
  385. }
  386. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  387. this.stats.set("processed", "video sources", videoSourceElements.length);
  388. if (this.options.removeVideoSrc) {
  389. this.stats.set("discarded", "video sources", videoSourceElements.length);
  390. videoSourceElements.forEach(element => element.removeAttribute("src"));
  391. }
  392. }
  393. removeDefaultHeadTags() {
  394. this.doc.querySelectorAll("base").forEach(element => element.remove());
  395. if (this.doc.head.querySelectorAll("*").length == 1 && this.doc.head.querySelector("meta[charset]") && this.doc.body.childNodes.length == 0) {
  396. this.doc.head.querySelector("meta[charset]").remove();
  397. }
  398. }
  399. removeUIElements() {
  400. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask").forEach(element => element.remove());
  401. }
  402. removeScripts() {
  403. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  404. this.stats.set("discarded", "scripts", scriptElements.length);
  405. this.stats.set("processed", "scripts", scriptElements.length);
  406. scriptElements.forEach(element => element.remove());
  407. }
  408. removeFrames() {
  409. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  410. this.stats.set("discarded", "frames", frameElements.length);
  411. this.stats.set("processed", "frames", frameElements.length);
  412. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  413. }
  414. removeImports() {
  415. const importElements = this.doc.querySelectorAll("link[rel=import]");
  416. this.stats.set("discarded", "HTML imports", importElements.length);
  417. this.stats.set("processed", "HTML imports", importElements.length);
  418. importElements.forEach(element => element.remove());
  419. }
  420. resetCharsetMeta() {
  421. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => element.remove());
  422. const metaElement = this.doc.createElement("meta");
  423. metaElement.setAttribute("charset", "utf-8");
  424. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  425. }
  426. insertFaviconLink() {
  427. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  428. if (!faviconElement) {
  429. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  430. }
  431. if (!faviconElement) {
  432. faviconElement = this.doc.createElement("link");
  433. faviconElement.setAttribute("type", "image/x-icon");
  434. faviconElement.setAttribute("rel", "shortcut icon");
  435. faviconElement.setAttribute("href", "/favicon.ico");
  436. }
  437. this.doc.head.appendChild(faviconElement);
  438. }
  439. resolveHrefs() {
  440. this.doc.querySelectorAll("[href]").forEach(element => {
  441. if (element.href) {
  442. const href = element.href.baseVal ? element.href.baseVal : element.href;
  443. const normalizedHref = DomUtil.normalizeURL(href);
  444. if (!normalizedHref || normalizedHref != this.baseURI) {
  445. element.setAttribute("href", href);
  446. }
  447. }
  448. });
  449. }
  450. removeUnusedStyles() {
  451. if (!this.mediaAllInfo) {
  452. this.mediaAllInfo = DOM.getMediaAllInfo(this.doc);
  453. }
  454. const stats = DOM.minifyCSS(this.doc, this.mediaAllInfo);
  455. this.stats.set("processed", "CSS rules", stats.processed);
  456. this.stats.set("discarded", "CSS rules", stats.discarded);
  457. }
  458. removeAlternativeFonts() {
  459. DOM.minifyFonts(this.doc);
  460. }
  461. removeSrcSet() {
  462. this.doc.querySelectorAll("picture, img[srcset]").forEach(element => {
  463. const tagName = element.tagName.toLowerCase();
  464. const dataAttributeName = DOM.responsiveImagesAttributeName(this.options.sessionId);
  465. const responsiveImageData = this.options.responsiveImageData[Number(element.getAttribute(dataAttributeName))];
  466. element.removeAttribute(dataAttributeName);
  467. if (responsiveImageData) {
  468. if (tagName == "img") {
  469. if (responsiveImageData.source.src && responsiveImageData.source.naturalWidth > 1 && responsiveImageData.source.naturalHeight > 1) {
  470. element.removeAttribute("srcset");
  471. element.removeAttribute("sizes");
  472. element.src = responsiveImageData.source.src;
  473. }
  474. }
  475. if (tagName == "picture") {
  476. const imageElement = element.querySelector("img");
  477. if (responsiveImageData.source && responsiveImageData.source.src && responsiveImageData.source.naturalWidth > 1 && responsiveImageData.source.naturalHeight > 1) {
  478. imageElement.removeAttribute("srcset");
  479. imageElement.removeAttribute("sizes");
  480. imageElement.src = responsiveImageData.source.src;
  481. element.querySelectorAll("source").forEach(sourceElement => sourceElement.remove());
  482. } else {
  483. if (responsiveImageData.sources) {
  484. element.querySelectorAll("source").forEach(sourceElement => {
  485. if (!sourceElement.srcset && !sourceElement.dataset.srcset && !sourceElement.src) {
  486. sourceElement.remove();
  487. }
  488. });
  489. const sourceElements = element.querySelectorAll("source");
  490. if (sourceElements.length) {
  491. const lastSourceElement = sourceElements[sourceElements.length - 1];
  492. if (imageElement) {
  493. if (lastSourceElement.src) {
  494. imageElement.src = lastSourceElement.src;
  495. } else {
  496. imageElement.removeAttribute("src");
  497. }
  498. if (lastSourceElement.srcset || lastSourceElement.dataset.srcset) {
  499. imageElement.srcset = lastSourceElement.srcset || lastSourceElement.dataset.srcset;
  500. } else {
  501. imageElement.removeAttribute("srcset");
  502. }
  503. element.querySelectorAll("source").forEach(sourceElement => sourceElement.remove());
  504. }
  505. }
  506. }
  507. }
  508. }
  509. }
  510. });
  511. }
  512. postRemoveAlternativeFonts() {
  513. DOM.minifyFonts(this.doc, true);
  514. }
  515. removeHiddenElements() {
  516. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(this.options.sessionId) + "]");
  517. this.stats.set("discarded", "hidden elements", hiddenElements.length);
  518. this.stats.set("processed", "hidden elements", hiddenElements.length);
  519. hiddenElements.forEach(element => element.remove());
  520. }
  521. compressHTML() {
  522. let size;
  523. if (this.options.displayStats) {
  524. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  525. }
  526. DOM.minifyHTML(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  527. if (this.options.displayStats) {
  528. this.stats.add("discarded", "HTML bytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  529. }
  530. }
  531. groupDuplicateImages() {
  532. if (this.options.imageData) {
  533. if (!this.mediaAllInfo) {
  534. this.mediaAllInfo = DOM.getMediaAllInfo(this.doc);
  535. }
  536. DOM.minifyImages(this.doc, this.mediaAllInfo, this.options);
  537. }
  538. }
  539. setPreservedAspectRatios() {
  540. DOM.setPreservedAspectRatios(this.doc);
  541. }
  542. removeAlternativeMedias() {
  543. const stats = DOM.minifyMedias(this.doc);
  544. this.stats.set("processed", "medias", stats.processed);
  545. this.stats.set("discarded", "medias", stats.discarded);
  546. }
  547. compressCSS() {
  548. this.doc.querySelectorAll("style").forEach(styleElement => {
  549. if (styleElement) {
  550. styleElement.textContent = DOM.compressCSS(styleElement.textContent);
  551. }
  552. });
  553. this.doc.querySelectorAll("[style]").forEach(element => {
  554. element.setAttribute("style", DOM.compressCSS(element.getAttribute("style")));
  555. });
  556. }
  557. insertSingleFileComment() {
  558. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  559. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  560. }
  561. replaceCanvasElements() {
  562. if (this.options.canvasData) {
  563. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  564. const canvasData = this.options.canvasData[indexCanvasElement];
  565. if (canvasData) {
  566. const imgElement = this.doc.createElement("img");
  567. imgElement.setAttribute("src", canvasData.dataURI);
  568. Array.from(canvasElement.attributes).forEach(attribute => {
  569. if (attribute.value) {
  570. imgElement.setAttribute(attribute.name, attribute.value);
  571. }
  572. });
  573. if (!imgElement.width && canvasData.width) {
  574. imgElement.style.pixelWidth = canvasData.width;
  575. }
  576. if (!imgElement.height && canvasData.height) {
  577. imgElement.style.pixelHeight = canvasData.height;
  578. }
  579. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  580. this.stats.add("processed", "canvas", 1);
  581. }
  582. });
  583. }
  584. }
  585. insertFonts() {
  586. if (this.options.fontsData && this.options.fontsData.length) {
  587. let stylesheetContent = "";
  588. this.options.fontsData.forEach(fontStyles => {
  589. if (fontStyles["font-family"] && fontStyles.src) {
  590. stylesheetContent += "@font-face{";
  591. let stylesContent = "";
  592. Object.keys(fontStyles).forEach(fontStyle => {
  593. if (stylesContent) {
  594. stylesContent += ";";
  595. }
  596. stylesContent += fontStyle + ":" + fontStyles[fontStyle];
  597. });
  598. stylesheetContent += stylesContent + "}";
  599. }
  600. });
  601. if (stylesheetContent) {
  602. const styleElement = this.doc.createElement("style");
  603. styleElement.textContent = stylesheetContent;
  604. const existingStyleElement = this.doc.querySelector("style");
  605. if (existingStyleElement) {
  606. existingStyleElement.parentElement.insertBefore(styleElement, existingStyleElement);
  607. } else {
  608. this.doc.head.insertBefore(styleElement, this.doc.head.firstChild);
  609. }
  610. }
  611. }
  612. }
  613. replaceStyleContents() {
  614. if (this.options.stylesheetContents) {
  615. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  616. if (this.options.stylesheetContents[styleIndex]) {
  617. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  618. }
  619. });
  620. }
  621. }
  622. insertVideoPosters() {
  623. if (this.options.postersData) {
  624. this.doc.querySelectorAll("video[src], video > source[src]").forEach((videoElement, videoIndex) => {
  625. if (!videoElement.poster && this.options.postersData[videoIndex]) {
  626. videoElement.setAttribute("poster", this.options.postersData[videoIndex]);
  627. }
  628. });
  629. }
  630. }
  631. async pageResources() {
  632. const resourcePromises = [
  633. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest),
  634. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]"), "data", PREFIX_DATA_URI_IMAGE_SVG, this.baseURI, this.batchRequest),
  635. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[src], input[src][type=image]"), "src", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest),
  636. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("embed[src*=\".svg\"]"), "src", PREFIX_DATA_URI_IMAGE_SVG, this.baseURI, this.batchRequest),
  637. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest),
  638. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest),
  639. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image"), "xlink:href", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest),
  640. DomProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.batchRequest),
  641. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest)
  642. ];
  643. if (!this.options.removeAudioSrc) {
  644. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", PREFIX_DATA_URI_AUDIO, this.baseURI, this.batchRequest));
  645. }
  646. if (!this.options.removeVideoSrc) {
  647. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", PREFIX_DATA_URI_VIDEO, this.baseURI, this.batchRequest));
  648. }
  649. if (this.options.lazyLoadImages) {
  650. const imageSelectors = DOM.lazyLoaderImageSelectors();
  651. Object.keys(imageSelectors.src).forEach(selector => resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), imageSelectors.src[selector], PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest)));
  652. Object.keys(imageSelectors.srcset).forEach(selector => resourcePromises.push(DomProcessorHelper.processSrcset(this.doc.querySelectorAll(selector), imageSelectors.srcset[selector], PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest)));
  653. }
  654. await resourcePromises;
  655. }
  656. async resolveStylesheetURLs() {
  657. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => styleElement.textContent = await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled })));
  658. }
  659. async processStylesheets() {
  660. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async (styleElement, indexStyle) => {
  661. this.stats.add("processed", "stylesheets", 1);
  662. styleElement.textContent = await DomProcessorHelper.processStylesheet(styleElement.textContent, styleElement.sheet.cssRules, this.baseURI, this.options, false, indexStyle, this.batchRequest);
  663. }));
  664. }
  665. async processScripts() {
  666. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  667. if (scriptElement.src) {
  668. this.stats.add("processed", "scripts", 1);
  669. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  670. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  671. }
  672. scriptElement.removeAttribute("src");
  673. }));
  674. }
  675. async resolveFrameURLs() {
  676. if (this.options.framesData) {
  677. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  678. await Promise.all(frameElements.map(async frameElement => {
  679. DomProcessorHelper.setFrameEmptySrc(frameElement);
  680. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  681. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  682. if (frameWindowId) {
  683. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  684. if (frameData) {
  685. const options = Object.create(this.options);
  686. options.insertSingleFileComment = false;
  687. options.insertFaviconLink = false;
  688. options.doc = null;
  689. options.win = null;
  690. options.url = frameData.baseURI;
  691. options.windowId = frameWindowId;
  692. if (frameData.content) {
  693. options.content = frameData.content;
  694. options.canvasData = frameData.canvasData;
  695. options.stylesheetContents = frameData.stylesheetContents;
  696. options.currentSrcImages = frameData.currentSrcImages;
  697. options.fontsData = frameData.fontsData;
  698. options.imageData = frameData.imageData;
  699. options.responsiveImageData = frameData.responsiveImageData;
  700. frameData.processor = new PageProcessor(options);
  701. frameData.frameElement = frameElement;
  702. await frameData.processor.loadPage();
  703. await frameData.processor.initialize();
  704. frameData.maxResources = this.batchRequest.getMaxResources();
  705. }
  706. }
  707. }
  708. }));
  709. }
  710. }
  711. async processFrames() {
  712. if (this.options.framesData) {
  713. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  714. await Promise.all(frameElements.map(async frameElement => {
  715. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  716. if (frameWindowId) {
  717. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  718. if (frameData) {
  719. if (frameData.processor) {
  720. this.stats.add("processed", "frames", 1);
  721. await frameData.processor.preparePageData();
  722. const pageData = await frameData.processor.getPageData();
  723. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  724. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  725. this.stats.addAll(pageData);
  726. } else {
  727. this.stats.add("discarded", "frames", 1);
  728. }
  729. }
  730. }
  731. }));
  732. }
  733. }
  734. async resolveHtmlImportURLs() {
  735. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  736. if (!this.relImportProcessors) {
  737. this.relImportProcessors = new Map();
  738. }
  739. await Promise.all(linkElements.map(async linkElement => {
  740. const resourceURL = linkElement.href;
  741. linkElement.setAttribute("href", EMPTY_DATA_URI);
  742. const options = Object.create(this.options);
  743. options.insertSingleFileComment = false;
  744. options.insertFaviconLink = false;
  745. options.doc = null;
  746. options.win = null;
  747. options.url = resourceURL;
  748. if (resourceURL) {
  749. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  750. const processor = new PageProcessor(options);
  751. this.relImportProcessors.set(linkElement, processor);
  752. await processor.loadPage();
  753. return processor.initialize();
  754. }
  755. }
  756. }));
  757. }
  758. async processHtmlImports() {
  759. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  760. await Promise.all(linkElements.map(async linkElement => {
  761. const processor = this.relImportProcessors.get(linkElement);
  762. if (processor) {
  763. this.stats.add("processed", "HTML imports", 1);
  764. this.relImportProcessors.delete(linkElement);
  765. const pageData = await processor.getPageData();
  766. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  767. this.stats.addAll(pageData);
  768. } else {
  769. this.stats.add("discarded", "HTML imports", 1);
  770. }
  771. }));
  772. }
  773. async resolveStyleAttributeURLs() {
  774. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => element.setAttribute("style", DomProcessorHelper.resolveStylesheetURLs(element.getAttribute("style"), this.baseURI))));
  775. }
  776. async processStyleAttributes() {
  777. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => element.setAttribute("style", await DomProcessorHelper.processStylesheet(element.getAttribute("style"), [{ type: CSSRule.STYLE_RULE, cssText: element.getAttribute("style") }], this.baseURI, this.options, true, 0, this.batchRequest))));
  778. }
  779. async resolveLinkedStylesheetURLs() {
  780. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  781. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  782. const styleElement = this.doc.createElement("style");
  783. styleElement.textContent = stylesheetContent;
  784. linkElement.parentElement.replaceChild(styleElement, linkElement);
  785. }));
  786. }
  787. }
  788. // ---------
  789. // DomHelper
  790. // ---------
  791. const REGEXP_AMP = /&/g;
  792. const REGEXP_NBSP = /\u00a0/g;
  793. const REGEXP_START_TAG = /</g;
  794. const REGEXP_END_TAG = />/g;
  795. const REGEXP_URL_HASH = /(#.+?)$/;
  796. const PREFIX_DATA_URI_IMAGE = "data:image/";
  797. const PREFIX_DATA_URI_AUDIO = "data:audio/";
  798. const PREFIX_DATA_URI_VIDEO = "data:video/";
  799. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  800. const PREFIX_DATA_URI_NO_MIMETYPE = "data:;";
  801. const PREFIX_DATA_URI_OCTET_STREAM = "data:application/octet-stream";
  802. class DomProcessorHelper {
  803. static async getFilename(options, content) {
  804. let filename = options.filenameTemplate;
  805. const date = new Date();
  806. const url = new URL(options.url);
  807. filename = await DomUtil.evalTemplateVariable(filename, "page-title", () => options.title || "No title");
  808. filename = await DomUtil.evalTemplateVariable(filename, "page-language", () => options.info.lang || "No language");
  809. filename = await DomUtil.evalTemplateVariable(filename, "page-description", () => options.info.description || "No description");
  810. filename = await DomUtil.evalTemplateVariable(filename, "page-author", () => options.info.author || "No author");
  811. filename = await DomUtil.evalTemplateVariable(filename, "page-creator", () => options.info.creator || "No creator");
  812. filename = await DomUtil.evalTemplateVariable(filename, "page-publisher", () => options.info.publisher || "No publisher");
  813. filename = await DomUtil.evalTemplateVariable(filename, "datetime-iso", () => date.toISOString());
  814. filename = await DomUtil.evalTemplateVariable(filename, "date-iso", () => date.toISOString().split("T")[0]);
  815. filename = await DomUtil.evalTemplateVariable(filename, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0]);
  816. filename = await DomUtil.evalTemplateVariable(filename, "date-locale", () => date.toLocaleDateString());
  817. filename = await DomUtil.evalTemplateVariable(filename, "time-locale", () => date.toLocaleTimeString());
  818. filename = await DomUtil.evalTemplateVariable(filename, "day-locale", () => String(date.getDate()));
  819. filename = await DomUtil.evalTemplateVariable(filename, "month-locale", () => String(date.getMonth()));
  820. filename = await DomUtil.evalTemplateVariable(filename, "year-locale", () => String(date.getFullYear()));
  821. filename = await DomUtil.evalTemplateVariable(filename, "datetime-locale", () => date.toLocaleString());
  822. filename = await DomUtil.evalTemplateVariable(filename, "datetime-utc", () => date.toUTCString());
  823. filename = await DomUtil.evalTemplateVariable(filename, "day-utc", () => String(date.getUTCDate()));
  824. filename = await DomUtil.evalTemplateVariable(filename, "month-utc", () => String(date.getUTCMonth()));
  825. filename = await DomUtil.evalTemplateVariable(filename, "year-utc", () => String(date.getUTCFullYear()));
  826. filename = await DomUtil.evalTemplateVariable(filename, "url-hash", () => url.hash.substring(1));
  827. filename = await DomUtil.evalTemplateVariable(filename, "url-host", () => url.host.replace(/\/$/, ""));
  828. filename = await DomUtil.evalTemplateVariable(filename, "url-hostname", () => url.hostname.replace(/\/$/, ""));
  829. filename = await DomUtil.evalTemplateVariable(filename, "url-href", () => url.href);
  830. filename = await DomUtil.evalTemplateVariable(filename, "url-password", () => url.password);
  831. filename = await DomUtil.evalTemplateVariable(filename, "url-pathname", () => url.pathname.replace(/^\//, "").replace(/\/$/, ""), true);
  832. filename = await DomUtil.evalTemplateVariable(filename, "url-port", () => url.port);
  833. filename = await DomUtil.evalTemplateVariable(filename, "url-protocol", () => url.protocol);
  834. filename = await DomUtil.evalTemplateVariable(filename, "url-search", () => url.search.substring(1));
  835. filename = await DomUtil.evalTemplateVariable(filename, "url-username", () => url.username);
  836. filename = await DomUtil.evalTemplateVariable(filename, "tab-id", () => String(options.tabId || "No tab id"));
  837. filename = await DomUtil.evalTemplateVariable(filename, "url-last-segment", () => DomUtil.getLastSegment(url));
  838. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-256", async () => DOM.digest("SHA-256", content));
  839. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-384", async () => DOM.digest("SHA-384", content));
  840. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-512", async () => DOM.digest("SHA-512", content));
  841. filename = filename.replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, "_"); // eslint-disable-line no-control-regex
  842. filename = filename.replace(/\.\.\//g, "").replace(/^\/+/, "").replace(/\/+/g, "/").replace(/\/$/, "");
  843. if (!options.backgroundSave) {
  844. filename = filename.replace(/\//g, "_");
  845. }
  846. if (filename.length > 192) {
  847. const extensionMatch = filename.match(/(\.[^.]{3,4})$/);
  848. const extension = extensionMatch && extensionMatch[0] && extensionMatch[0].length > 1 ? extensionMatch[0] : "";
  849. filename = filename.substring(0, 192 - extension.length) + "…" + extension;
  850. }
  851. if (!filename) {
  852. filename = "Unnamed page";
  853. }
  854. return filename;
  855. }
  856. static setFrameEmptySrc(frameElement) {
  857. if (frameElement.tagName == "OBJECT") {
  858. frameElement.setAttribute("data", "data:text/html,");
  859. } else {
  860. frameElement.setAttribute("srcdoc", "");
  861. frameElement.removeAttribute("src");
  862. }
  863. }
  864. static setFrameContent(frameElement, content) {
  865. if (frameElement.tagName == "OBJECT") {
  866. frameElement.setAttribute("data", "data:text/html," + content);
  867. } else {
  868. frameElement.setAttribute("srcdoc", content);
  869. frameElement.removeAttribute("src");
  870. }
  871. }
  872. static isolateElements(rootElement) {
  873. rootElement.querySelectorAll("*").forEach(element => {
  874. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  875. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  876. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  877. element.remove();
  878. }
  879. });
  880. isolateParentElements(rootElement.parentElement, rootElement);
  881. function isolateParentElements(parentElement, element) {
  882. if (parentElement) {
  883. Array.from(parentElement.childNodes).forEach(node => {
  884. if (node != element && node.tagName != "HEAD" && node.tagName != "STYLE") {
  885. node.remove();
  886. }
  887. });
  888. }
  889. element = element.parentElement;
  890. if (element && element.parentElement) {
  891. isolateParentElements(element.parentElement, element);
  892. }
  893. }
  894. }
  895. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  896. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  897. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  898. const imports = DomUtil.getImportFunctions(stylesheetContent);
  899. await Promise.all(imports.map(async cssImport => {
  900. const match = DomUtil.matchImport(cssImport);
  901. if (match) {
  902. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  903. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  904. const styleSheetUrl = new URL(match.resourceURL, baseURI).href;
  905. let importedStylesheetContent = await Download.getContent(styleSheetUrl, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  906. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  907. if (stylesheetContent.includes(cssImport)) {
  908. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, styleSheetUrl, options);
  909. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(cssImport), importedStylesheetContent);
  910. }
  911. }
  912. }
  913. }));
  914. return stylesheetContent;
  915. }
  916. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  917. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  918. urlFunctions.map(urlFunction => {
  919. const originalResourceURL = DomUtil.matchURL(urlFunction);
  920. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  921. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  922. const resolvedURL = new URL(resourceURL, baseURI).href;
  923. if (resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  924. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  925. }
  926. } else {
  927. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  928. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  929. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  930. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  931. }
  932. }
  933. }
  934. });
  935. return stylesheetContent;
  936. }
  937. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  938. resourceURL = DomUtil.normalizeURL(resourceURL);
  939. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  940. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  941. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  942. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  943. return stylesheetContent;
  944. }
  945. }
  946. static async processStylesheet(stylesheetContent, cssRules, baseURI, options, inline, indexStyle, batchRequest) {
  947. let sheetContent = "", variablesInfo = { index: 0, cssText: "" };
  948. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  949. const variableNames = new Map();
  950. const urlFunctionData = new Map();
  951. await Promise.all(urlFunctions.map(async urlFunction => {
  952. const originalResourceURL = DomUtil.matchURL(urlFunction);
  953. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  954. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL) && stylesheetContent.includes(urlFunction)) {
  955. const dataURI = await batchRequest.addURL(resourceURL);
  956. const regExpUrlFunction = DomUtil.getRegExp(urlFunction);
  957. const functions = stylesheetContent.match(regExpUrlFunction);
  958. if (options.groupDuplicateImages && functions.length > 1) {
  959. variableNames.set(urlFunction, "--single-file-" + indexStyle + "-" + variableNames.size);
  960. }
  961. urlFunctionData.set(urlFunction, { regExpUrlFunction, dataURI });
  962. }
  963. }));
  964. const rulesContent = processRules(cssRules);
  965. if (variablesInfo.cssText) {
  966. sheetContent += ":root{" + variablesInfo.cssText + "}";
  967. }
  968. return sheetContent + rulesContent;
  969. function processRules(cssRules) {
  970. let rulesContent = "";
  971. Array.from(cssRules).forEach(cssRule => {
  972. if (cssRule.type == CSSRule.MEDIA_RULE) {
  973. const mediaRulesContent = processRules(cssRule.cssRules);
  974. rulesContent += "@media " + Array.from(cssRule.media).join(",") + "{" + mediaRulesContent + "}";
  975. } else if (cssRule.type == CSSRule.STYLE_RULE) {
  976. rulesContent += processURLFunctions(cssRule.cssText, !inline && options.compressCSS);
  977. } else {
  978. rulesContent += processURLFunctions(cssRule.cssText);
  979. }
  980. });
  981. return rulesContent;
  982. }
  983. function processURLFunctions(cssText, useCustomProperties) {
  984. const urlFunctions = DomUtil.getUrlFunctions(cssText);
  985. urlFunctions.forEach(urlFunction => {
  986. const originalResourceURL = DomUtil.matchURL(urlFunction);
  987. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  988. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL) && cssText.includes(urlFunction)) {
  989. const resourceInfo = urlFunctionData.get(urlFunction);
  990. const dataURI = resourceInfo.dataURI;
  991. if (useCustomProperties) {
  992. const variableName = variableNames.get(urlFunction);
  993. if (variableName) {
  994. cssText = cssText.replace(resourceInfo.regExpUrlFunction, "var(" + variableName + ")");
  995. if (variablesInfo.cssText) {
  996. variablesInfo.cssText += ";";
  997. }
  998. variablesInfo.cssText += variableName + ":url(\"" + dataURI + "\")";
  999. variablesInfo.index++;
  1000. } else {
  1001. cssText = cssText.replace(resourceInfo.regExpUrlFunction, urlFunction.replace(originalResourceURL, dataURI));
  1002. }
  1003. } else {
  1004. cssText = cssText.replace(resourceInfo.regExpUrlFunction, urlFunction.replace(originalResourceURL, dataURI));
  1005. }
  1006. }
  1007. });
  1008. return cssText;
  1009. }
  1010. }
  1011. static async processAttribute(resourceElements, attributeName, prefixDataURI, baseURI, batchRequest) {
  1012. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1013. let resourceURL = resourceElement.getAttribute(attributeName);
  1014. if (resourceURL) {
  1015. resourceURL = DomUtil.normalizeURL(resourceURL);
  1016. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  1017. try {
  1018. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  1019. if (dataURI.startsWith(prefixDataURI) || dataURI.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) || dataURI.startsWith(PREFIX_DATA_URI_OCTET_STREAM)) {
  1020. resourceElement.setAttribute(attributeName, dataURI);
  1021. } else {
  1022. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1023. }
  1024. } catch (error) {
  1025. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1026. }
  1027. }
  1028. }
  1029. }));
  1030. }
  1031. static async processXLinks(resourceElements, baseURI, batchRequest) {
  1032. const attributeName = "xlink:href";
  1033. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1034. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1035. if (originalResourceURL) {
  1036. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1037. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  1038. try {
  1039. const content = await batchRequest.addURL(new URL(resourceURL, baseURI).href, false);
  1040. const DOMParser = DOM.getParser();
  1041. if (DOMParser) {
  1042. const svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  1043. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1044. if (hashMatch && hashMatch[0]) {
  1045. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1046. if (symbolElement) {
  1047. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1048. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1049. }
  1050. } else {
  1051. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1052. }
  1053. } else {
  1054. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1055. }
  1056. } catch (error) {
  1057. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1058. }
  1059. }
  1060. }
  1061. }));
  1062. }
  1063. static async processSrcset(resourceElements, attributeName, prefixDataURI, baseURI, batchRequest) {
  1064. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1065. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  1066. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1067. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  1068. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  1069. try {
  1070. let dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  1071. if (!dataURI.startsWith(prefixDataURI) && !dataURI.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) && !dataURI.startsWith(PREFIX_DATA_URI_OCTET_STREAM)) {
  1072. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1073. }
  1074. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1075. } catch (error) {
  1076. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1077. }
  1078. }
  1079. }));
  1080. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1081. }));
  1082. }
  1083. }
  1084. // -------
  1085. // DomUtil
  1086. // -------
  1087. const DATA_URI_PREFIX = "data:";
  1088. const BLOB_URI_PREFIX = "blob:";
  1089. const HTTP_URI_PREFIX = /^https?:\/\//;
  1090. const ABOUT_BLANK_URI = "about:blank";
  1091. const NOT_EMPTY_URL = /^https?:\/\/.+/;
  1092. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1093. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1094. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1095. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1096. 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;
  1097. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1098. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1099. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1100. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1101. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1102. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1103. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1104. class DomUtil {
  1105. static normalizeURL(url) {
  1106. if (url.startsWith(DATA_URI_PREFIX)) {
  1107. return url;
  1108. } else {
  1109. return url.split("#")[0];
  1110. }
  1111. }
  1112. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
  1113. const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
  1114. if (template.match(replaceRegExp)) {
  1115. let value = await valueGetter();
  1116. if (!dontReplaceSlash) {
  1117. value = value.replace(/\/+/g, "_");
  1118. }
  1119. return template.replace(replaceRegExp, value);
  1120. }
  1121. return template;
  1122. }
  1123. static getLastSegment(url) {
  1124. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/);
  1125. let lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1126. if (!lastSegment) {
  1127. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1128. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1129. }
  1130. if (!lastSegment) {
  1131. lastSegmentMatch = lastSegment.match(/(.*)<\.[^.]+$/);
  1132. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1133. }
  1134. if (!lastSegment) {
  1135. lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
  1136. }
  1137. lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1138. return lastSegment;
  1139. }
  1140. static getRegExp(string) {
  1141. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1142. }
  1143. static getUrlFunctions(stylesheetContent) {
  1144. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1145. }
  1146. static getImportFunctions(stylesheetContent) {
  1147. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1148. }
  1149. static matchURL(stylesheetContent) {
  1150. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1151. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1152. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1153. return match && match[1];
  1154. }
  1155. static testValidPath(resourceURL) {
  1156. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI && (!resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(NOT_EMPTY_URL));
  1157. }
  1158. static matchImport(stylesheetContent) {
  1159. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1160. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1161. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1162. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1163. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1164. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1165. if (match) {
  1166. const [, resourceURL, media] = match;
  1167. return { resourceURL, media };
  1168. }
  1169. }
  1170. static removeCssComments(stylesheetContent) {
  1171. let start, end;
  1172. do {
  1173. start = stylesheetContent.indexOf("/*");
  1174. end = stylesheetContent.indexOf("*/", start + 2);
  1175. if (start != -1 && end != -1) {
  1176. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1177. }
  1178. } while (start != -1 && end != -1);
  1179. return stylesheetContent;
  1180. }
  1181. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1182. if (mediaQuery) {
  1183. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1184. } else {
  1185. return stylesheetContent;
  1186. }
  1187. }
  1188. }
  1189. function log(...args) {
  1190. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1191. }
  1192. // -----
  1193. // Stats
  1194. // -----
  1195. const STATS_DEFAULT_VALUES = {
  1196. discarded: {
  1197. "HTML bytes": 0,
  1198. "hidden elements": 0,
  1199. "HTML imports": 0,
  1200. scripts: 0,
  1201. objects: 0,
  1202. "audio sources": 0,
  1203. "video sources": 0,
  1204. frames: 0,
  1205. "CSS rules": 0,
  1206. canvas: 0,
  1207. stylesheets: 0,
  1208. resources: 0,
  1209. medias: 0
  1210. },
  1211. processed: {
  1212. "HTML bytes": 0,
  1213. "hidden elements": 0,
  1214. "HTML imports": 0,
  1215. scripts: 0,
  1216. objects: 0,
  1217. "audio sources": 0,
  1218. "video sources": 0,
  1219. frames: 0,
  1220. "CSS rules": 0,
  1221. canvas: 0,
  1222. stylesheets: 0,
  1223. resources: 0,
  1224. medias: 0
  1225. }
  1226. };
  1227. class Stats {
  1228. constructor(options) {
  1229. this.options = options;
  1230. if (options.displayStats) {
  1231. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1232. }
  1233. }
  1234. set(type, subType, value) {
  1235. if (this.options.displayStats) {
  1236. this.data[type][subType] = value;
  1237. }
  1238. }
  1239. add(type, subType, value) {
  1240. if (this.options.displayStats) {
  1241. this.data[type][subType] += value;
  1242. }
  1243. }
  1244. addAll(pageData) {
  1245. if (this.options.displayStats) {
  1246. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1247. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1248. }
  1249. }
  1250. }
  1251. return { getClass };
  1252. })();