single-file-core.js 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. this.SingleFileCore = this.SingleFileCore || (() => {
  24. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  25. const SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = "data-single-file-selected-content-root";
  26. const DEBUG = false;
  27. let Download, DOM, URL, cssTree, sessionId = 0;
  28. function getClass(...args) {
  29. [Download, DOM, URL, cssTree] = args;
  30. return SingleFileClass;
  31. }
  32. class SingleFileClass {
  33. constructor(options) {
  34. this.options = options;
  35. if (options.sessionId === undefined) {
  36. options.sessionId = sessionId;
  37. sessionId++;
  38. }
  39. }
  40. async initialize() {
  41. this.processor = new PageProcessor(this.options, true);
  42. await this.processor.loadPage();
  43. await this.processor.initialize();
  44. }
  45. async run() {
  46. await this.processor.run();
  47. }
  48. async getPageData() {
  49. return this.processor.getPageData();
  50. }
  51. }
  52. SingleFileClass.SELECTED_CONTENT_ATTRIBUTE_NAME = SELECTED_CONTENT_ATTRIBUTE_NAME;
  53. SingleFileClass.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME;
  54. // -------------
  55. // ProgressEvent
  56. // -------------
  57. const PAGE_LOADING = "page-loading";
  58. const PAGE_LOADED = "page-loaded";
  59. const RESOURCES_INITIALIZING = "resource-initializing";
  60. const RESOURCES_INITIALIZED = "resources-initialized";
  61. const RESOURCE_LOADED = "resource-loaded";
  62. const PAGE_ENDED = "page-ended";
  63. const STAGE_STARTED = "stage-started";
  64. const STAGE_ENDED = "stage-ended";
  65. const STAGE_TASK_STARTED = "stage-task-started";
  66. const STAGE_TASK_ENDED = "stage-task-ended";
  67. class ProgressEvent {
  68. constructor(type, detail) {
  69. return { type, detail, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADED, PAGE_ENDED, STAGE_STARTED, STAGE_ENDED, STAGE_TASK_STARTED, STAGE_TASK_ENDED };
  70. }
  71. }
  72. // -------------
  73. // PageProcessor
  74. // -------------
  75. const RESOLVE_URLS_STAGE = 0;
  76. const REPLACE_DATA_STAGE = 1;
  77. const REPLACE_DOCS_STAGE = 2;
  78. const POST_PROCESS_STAGE = 3;
  79. const STAGES = [{
  80. sequential: [
  81. { action: "preProcessPage" },
  82. { action: "insertShadowRootContents" },
  83. { action: "replaceStyleContents" },
  84. { option: "selected", action: "removeUnselectedElements" },
  85. { option: "removeVideoSrc", action: "insertVideoPosters" },
  86. { option: "removeFrames", action: "removeFrames" },
  87. { option: "removeImports", action: "removeImports" },
  88. { option: "removeScripts", action: "removeScripts" },
  89. { action: "removeDiscardedResources" },
  90. { action: "resetCharsetMeta" },
  91. { action: "setInputValues" },
  92. { option: "insertFaviconLink", action: "insertFaviconLink" },
  93. { action: "resolveHrefs" },
  94. { action: "replaceCanvasElements" },
  95. { action: "insertFonts" },
  96. { option: "removeHiddenElements", action: "removeHiddenElements" },
  97. { action: "resolveStyleAttributeURLs" }
  98. ],
  99. parallel: [
  100. { action: "resolveStylesheetURLs" },
  101. { option: "!removeFrames", action: "resolveFrameURLs" },
  102. { option: "!removeImports", action: "resolveHtmlImportURLs" }
  103. ]
  104. }, {
  105. sequential: [
  106. { option: "removeUnusedStyles", action: "removeUnusedStyles" },
  107. { option: "removeAlternativeMedias", action: "removeAlternativeMedias" },
  108. { option: "removeUnusedStyles", action: "removeUnusedFonts" }
  109. ],
  110. parallel: [
  111. { action: "processStylesheets" },
  112. { action: "processStyleAttributes" },
  113. { action: "processPageResources" },
  114. { option: "!removeScripts", action: "processScripts" }
  115. ]
  116. }, {
  117. sequential: [
  118. { option: "removeAlternativeImages", action: "removeAlternativeImages" },
  119. { option: "removeAlternativeFonts", action: "removeAlternativeFonts" }
  120. ],
  121. parallel: [
  122. { option: "!removeFrames", action: "processFrames" },
  123. { option: "!removeImports", action: "processHtmlImports" },
  124. ]
  125. }, {
  126. sequential: [
  127. { action: "replaceStylesheets" },
  128. { action: "replaceStyleAttributes" },
  129. { action: "insertVariables" },
  130. { option: "compressHTML", action: "compressHTML" }
  131. ]
  132. }];
  133. class PageProcessor {
  134. constructor(options, root) {
  135. this.root = root;
  136. this.options = options;
  137. this.options.url = this.options.url || this.options.doc.location.href;
  138. this.options.baseURI = this.options.doc && this.options.doc.baseURI;
  139. this.batchRequest = new BatchRequest();
  140. this.processor = new DOMProcessor(options, this.batchRequest);
  141. if (this.options.doc) {
  142. const docData = DOM.preProcessDoc(this.options.doc, this.options.win, this.options);
  143. this.options.canvasData = docData.canvasData;
  144. this.options.fontsData = docData.fontsData;
  145. this.options.stylesheetContents = docData.stylesheetContents;
  146. this.options.imageData = docData.imageData;
  147. this.options.postersData = docData.postersData;
  148. this.options.usedFonts = docData.usedFonts;
  149. this.options.shadowRootContents = docData.shadowRootContents;
  150. }
  151. this.options.content = this.options.content || (this.options.doc ? DOM.serialize(this.options.doc, false) : null);
  152. this.onprogress = options.onprogress || (() => { });
  153. }
  154. async loadPage() {
  155. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url, frame: !this.root }));
  156. await this.processor.loadPage(this.options.content);
  157. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url, frame: !this.root }));
  158. }
  159. async initialize() {
  160. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  161. await this.executeStage(RESOLVE_URLS_STAGE);
  162. this.pendingPromises = this.executeStage(REPLACE_DATA_STAGE);
  163. if (this.options.doc) {
  164. DOM.postProcessDoc(this.options.doc, this.options);
  165. this.options.doc = null;
  166. this.options.win = null;
  167. }
  168. }
  169. async run() {
  170. if (this.root) {
  171. this.processor.initialize(this.batchRequest);
  172. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: this.processor.maxResources }));
  173. }
  174. await this.batchRequest.run(detail => {
  175. detail.pageURL = this.options.url;
  176. this.onprogress(new ProgressEvent(RESOURCE_LOADED, detail));
  177. }, this.options);
  178. await this.pendingPromises;
  179. await this.executeStage(REPLACE_DOCS_STAGE);
  180. await this.executeStage(POST_PROCESS_STAGE);
  181. await this.processor.end();
  182. }
  183. async getPageData() {
  184. if (this.root) {
  185. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  186. }
  187. return this.processor.getPageData();
  188. }
  189. async executeStage(step) {
  190. if (DEBUG) {
  191. log("**** STARTED STAGE", step, "****");
  192. }
  193. const frame = !this.root;
  194. this.onprogress(new ProgressEvent(STAGE_STARTED, { pageURL: this.options.url, step, frame }));
  195. STAGES[step].sequential.forEach(task => {
  196. let startTime;
  197. if (DEBUG) {
  198. startTime = Date.now();
  199. log(" -- STARTED task =", task.action);
  200. }
  201. this.onprogress(new ProgressEvent(STAGE_TASK_STARTED, { pageURL: this.options.url, step, task: task.action, frame }));
  202. this.executeTask(task);
  203. this.onprogress(new ProgressEvent(STAGE_TASK_ENDED, { pageURL: this.options.url, step, task: task.action, frame }));
  204. if (DEBUG) {
  205. log(" -- ENDED task =", task.action, "delay =", Date.now() - startTime);
  206. }
  207. });
  208. let parallelTasksPromise;
  209. if (STAGES[step].parallel) {
  210. parallelTasksPromise = await Promise.all(STAGES[step].parallel.map(task => {
  211. let startTime;
  212. if (DEBUG) {
  213. startTime = Date.now();
  214. log(" // STARTED task =", task.action);
  215. }
  216. this.onprogress(new ProgressEvent(STAGE_TASK_STARTED, { pageURL: this.options.url, step, task: task.action, frame }));
  217. const promise = this.executeTask(task);
  218. promise.then(() => this.onprogress(new ProgressEvent(STAGE_TASK_ENDED, { pageURL: this.options.url, step, task: task.action, frame })));
  219. if (DEBUG) {
  220. promise.then(() => log(" // ENDED task =", task.action, "delay =", Date.now() - startTime));
  221. }
  222. return promise;
  223. }));
  224. } else {
  225. parallelTasksPromise = Promise.resolve();
  226. }
  227. this.onprogress(new ProgressEvent(STAGE_ENDED, { pageURL: this.options.url, step, frame }));
  228. if (DEBUG) {
  229. log("**** ENDED STAGE", step, "****");
  230. }
  231. return parallelTasksPromise;
  232. }
  233. executeTask(task) {
  234. if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
  235. return this.processor[task.action]();
  236. }
  237. }
  238. }
  239. // --------
  240. // BatchRequest
  241. // --------
  242. class BatchRequest {
  243. constructor() {
  244. this.requests = new Map();
  245. }
  246. async addURL(resourceURL, asDataURI = true) {
  247. return new Promise((resolve, reject) => {
  248. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  249. const resourceRequests = this.requests.get(requestKey);
  250. if (resourceRequests) {
  251. resourceRequests.push({ resolve, reject });
  252. } else {
  253. this.requests.set(requestKey, [{ resolve, reject }]);
  254. }
  255. });
  256. }
  257. getMaxResources() {
  258. return Array.from(this.requests.keys()).length;
  259. }
  260. async run(onloadListener, options) {
  261. const resourceURLs = Array.from(this.requests.keys());
  262. let indexResource = 0;
  263. return Promise.all(resourceURLs.map(async requestKey => {
  264. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  265. const resourceRequests = this.requests.get(requestKey);
  266. try {
  267. const resourceContent = await Download.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  268. indexResource = indexResource + 1;
  269. onloadListener({ index: indexResource, url: resourceURL });
  270. resourceRequests.forEach(resourceRequest => resourceRequest.resolve({ content: resourceContent, indexResource, duplicate: Boolean(resourceRequests.length > 1) }));
  271. } catch (error) {
  272. indexResource = indexResource + 1;
  273. onloadListener({ index: indexResource, url: resourceURL });
  274. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  275. }
  276. this.requests.delete(requestKey);
  277. }));
  278. }
  279. }
  280. // ------------
  281. // DOMProcessor
  282. // ------------
  283. const EMPTY_DATA_URI = "data:base64,";
  284. const EMPTY_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  285. const SCRIPT_TAG_FOUND = /<script/gi;
  286. const NOSCRIPT_TAG_FOUND = /<noscript/gi;
  287. class DOMProcessor {
  288. constructor(options, batchRequest) {
  289. this.options = options;
  290. this.stats = new Stats(options);
  291. this.baseURI = DomUtil.normalizeURL(options.baseURI || options.url);
  292. this.batchRequest = batchRequest;
  293. this.stylesheets = new Map();
  294. this.styles = new Map();
  295. this.cssVariables = new Map();
  296. }
  297. initialize() {
  298. this.maxResources = this.batchRequest.getMaxResources();
  299. if (!this.options.removeFrames) {
  300. this.options.framesData.forEach(frameData => this.maxResources += frameData.maxResources || 0);
  301. }
  302. this.stats.set("processed", "resources", this.maxResources);
  303. }
  304. async loadPage(pageContent) {
  305. if (!pageContent || this.options.saveRawPage) {
  306. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  307. }
  308. this.doc = DOM.createDoc(pageContent, this.baseURI);
  309. this.onEventAttributeNames = DOM.getOnEventAttributeNames(this.doc);
  310. }
  311. async getPageData() {
  312. DOM.postProcessDoc(this.doc, this.options);
  313. const url = new URL(this.baseURI);
  314. if (this.options.insertSingleFileComment) {
  315. const infobarContent = (this.options.infobarContent || "").replace(/\\n/g, "\n").replace(/\\t/g, "\t");
  316. const commentNode = this.doc.createComment("\n Page saved with SingleFile" +
  317. " \n url: " + this.options.url +
  318. " \n saved date: " + new Date() +
  319. (infobarContent ? " \n info: " + infobarContent : "") + "\n");
  320. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  321. }
  322. let size;
  323. if (this.options.displayStats) {
  324. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  325. }
  326. const content = DOM.serialize(this.doc, this.options.compressHTML);
  327. if (this.options.displayStats) {
  328. const contentSize = DOM.getContentSize(content);
  329. this.stats.set("processed", "HTML bytes", contentSize);
  330. this.stats.add("discarded", "HTML bytes", size - contentSize);
  331. }
  332. let filename = await DomProcessorHelper.evalTemplate(this.options.filenameTemplate, this.options, content);
  333. filename = filename.replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, "_"); // eslint-disable-line no-control-regex
  334. filename = filename.replace(/\.\.\//g, "").replace(/^\/+/, "").replace(/\/+/g, "/").replace(/\/$/, "");
  335. if (!this.options.backgroundSave) {
  336. filename = filename.replace(/\//g, "_");
  337. }
  338. if (filename.length > 192) {
  339. const extensionMatch = filename.match(/(\.[^.]{3,4})$/);
  340. const extension = extensionMatch && extensionMatch[0] && extensionMatch[0].length > 1 ? extensionMatch[0] : "";
  341. filename = filename.substring(0, 192 - extension.length) + "…" + extension;
  342. }
  343. if (!filename) {
  344. filename = "Unnamed page";
  345. }
  346. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  347. return {
  348. stats: this.stats.data,
  349. title: this.options.title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "")),
  350. filename,
  351. content
  352. };
  353. }
  354. removeUnselectedElements() {
  355. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  356. if (rootElement) {
  357. DomProcessorHelper.isolateElements(rootElement);
  358. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  359. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  360. }
  361. }
  362. setInputValues() {
  363. this.doc.querySelectorAll("input").forEach(input => {
  364. const value = input.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  365. input.setAttribute("value", value || "");
  366. });
  367. this.doc.querySelectorAll("textarea").forEach(textarea => {
  368. const value = textarea.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  369. textarea.textContent = value || "";
  370. });
  371. this.doc.querySelectorAll("select").forEach(select => {
  372. select.querySelectorAll("option").forEach(option => {
  373. const selected = option.getAttribute(DOM.inputValueAttributeName(this.options.sessionId)) != null;
  374. if (selected) {
  375. option.setAttribute("selected", "");
  376. }
  377. });
  378. });
  379. }
  380. removeDiscardedResources() {
  381. const objectElements = this.doc.querySelectorAll("applet, meta[http-equiv=refresh], object[data]:not([type=\"image/svg+xml\"]):not([type=\"image/svg-xml\"]):not([type=\"text/html\"]), embed[src]:not([src*=\".svg\"])");
  382. this.stats.set("discarded", "objects", objectElements.length);
  383. this.stats.set("processed", "objects", objectElements.length);
  384. objectElements.forEach(element => element.remove());
  385. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  386. replacedAttributeValue.forEach(element => {
  387. const relValue = element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "").trim();
  388. if (relValue.length) {
  389. element.setAttribute("rel", relValue);
  390. } else {
  391. element.remove();
  392. }
  393. });
  394. this.doc.querySelectorAll("meta[http-equiv=\"content-security-policy\"]").forEach(element => element.remove());
  395. if (this.options.compressHTML) {
  396. this.doc.querySelectorAll("input[type=hidden]").forEach(element => element.remove());
  397. }
  398. this.doc.querySelectorAll("a[ping]").forEach(element => element.removeAttribute("ping"));
  399. if (this.options.removeScripts) {
  400. this.onEventAttributeNames.forEach(attributeName => this.doc.querySelectorAll("[" + attributeName + "]").forEach(element => element.removeAttribute(attributeName)));
  401. this.doc.querySelectorAll("[href]").forEach(element => {
  402. if (element.href && element.href.match && element.href.match(/^\s*javascript:/)) {
  403. element.setAttribute("href", "");
  404. }
  405. });
  406. this.doc.querySelectorAll("[src]").forEach(element => {
  407. if (element.src && element.src.match(/^\s*javascript:/)) {
  408. element.removeAttribute("src");
  409. }
  410. });
  411. }
  412. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  413. this.stats.set("processed", "audio sources", audioSourceElements.length);
  414. if (this.options.removeAudioSrc) {
  415. this.stats.set("discarded", "audio sources", audioSourceElements.length);
  416. audioSourceElements.forEach(element => element.removeAttribute("src"));
  417. }
  418. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  419. this.stats.set("processed", "video sources", videoSourceElements.length);
  420. if (this.options.removeVideoSrc) {
  421. this.stats.set("discarded", "video sources", videoSourceElements.length);
  422. videoSourceElements.forEach(element => element.removeAttribute("src"));
  423. }
  424. }
  425. async end() {
  426. const metaCharset = this.doc.head.querySelector("meta[charset]");
  427. if (metaCharset) {
  428. this.doc.head.insertBefore(metaCharset, this.doc.head.firstChild);
  429. }
  430. this.doc.querySelectorAll("base").forEach(element => element.remove());
  431. if (this.doc.head.querySelectorAll("*").length == 1 && metaCharset && this.doc.body.childNodes.length == 0) {
  432. this.doc.head.querySelector("meta[charset]").remove();
  433. }
  434. const titleElement = this.doc.querySelector("title");
  435. const descriptionElement = this.doc.querySelector("meta[name=description]");
  436. const authorElement = this.doc.querySelector("meta[name=author]");
  437. const creatorElement = this.doc.querySelector("meta[name=creator]");
  438. const publisherElement = this.doc.querySelector("meta[name=publisher]");
  439. this.options.title = titleElement ? titleElement.textContent.trim() : "";
  440. this.options.infobarContent = await DomProcessorHelper.evalTemplate(this.options.infobarTemplate, this.options, null, true);
  441. this.options.info = {
  442. description: descriptionElement ? descriptionElement.content.trim() : "",
  443. lang: this.doc.documentElement.lang,
  444. author: authorElement ? authorElement.content.trim() : "",
  445. creator: creatorElement ? creatorElement.content.trim() : "",
  446. publisher: publisherElement ? publisherElement.content.trim() : ""
  447. };
  448. }
  449. preProcessPage() {
  450. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask, singlefile-logs-window").forEach(element => element.remove());
  451. if (this.options.win) {
  452. this.doc.body.querySelectorAll(":not(svg) title, meta, link[href][rel*=\"icon\"]").forEach(element => element instanceof this.options.win.HTMLElement && this.doc.head.appendChild(element));
  453. }
  454. if (this.options.imageData) {
  455. const dataAttributeName = DOM.imagesAttributeName(this.options.sessionId);
  456. this.doc.querySelectorAll("img").forEach(imgElement => {
  457. const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  458. if (imgData.currentSrc) {
  459. imgElement.setAttribute("src", imgData.currentSrc);
  460. }
  461. });
  462. if (this.options.lazyLoadImages) {
  463. this.doc.querySelectorAll("img[data-src]").forEach(imgElement => {
  464. const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  465. if ((!imgElement.getAttribute("src") || imgElement.getAttribute("src") == EMPTY_IMAGE) && imgElement.getAttribute("data-src")) {
  466. imgData.src = imgElement.dataset.src;
  467. imgElement.setAttribute("src", imgElement.dataset.src);
  468. imgElement.removeAttribute("data-src");
  469. }
  470. });
  471. this.doc.querySelectorAll("img[data-srcset]").forEach(imgElement => {
  472. if (!imgElement.getAttribute("srcset") && imgElement.getAttribute("data-srcset")) {
  473. imgElement.setAttribute("srcset", imgElement.dataset.srcset);
  474. imgElement.removeAttribute("data-srcset");
  475. }
  476. });
  477. }
  478. }
  479. }
  480. removeScripts() {
  481. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  482. this.stats.set("discarded", "scripts", scriptElements.length);
  483. this.stats.set("processed", "scripts", scriptElements.length);
  484. scriptElements.forEach(element => element.remove());
  485. }
  486. removeFrames() {
  487. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  488. this.stats.set("discarded", "frames", frameElements.length);
  489. this.stats.set("processed", "frames", frameElements.length);
  490. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  491. }
  492. removeImports() {
  493. const importElements = this.doc.querySelectorAll("link[rel=import]");
  494. this.stats.set("discarded", "HTML imports", importElements.length);
  495. this.stats.set("processed", "HTML imports", importElements.length);
  496. importElements.forEach(element => element.remove());
  497. }
  498. resetCharsetMeta() {
  499. let charSet;
  500. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
  501. const charSetDeclaration = element.content.split(";")[1];
  502. if (charSetDeclaration && !charSet) {
  503. charSet = charSetDeclaration.split("=")[1];
  504. if (charSet) {
  505. this.charSet = charSet.trim().toLowerCase();
  506. }
  507. }
  508. element.remove();
  509. });
  510. const metaElement = this.doc.createElement("meta");
  511. metaElement.setAttribute("charset", "utf-8");
  512. if (this.doc.head.firstChild) {
  513. this.doc.head.insertBefore(metaElement, this.doc.head.firstChild);
  514. } else {
  515. this.doc.head.appendChild(metaElement);
  516. }
  517. }
  518. insertFaviconLink() {
  519. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  520. if (!faviconElement) {
  521. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  522. }
  523. if (!faviconElement) {
  524. faviconElement = this.doc.createElement("link");
  525. faviconElement.setAttribute("type", "image/x-icon");
  526. faviconElement.setAttribute("rel", "shortcut icon");
  527. faviconElement.setAttribute("href", "/favicon.ico");
  528. }
  529. this.doc.head.appendChild(faviconElement);
  530. }
  531. resolveHrefs() {
  532. this.doc.querySelectorAll("[href]").forEach(element => {
  533. if (element.href) {
  534. const href = element.href.baseVal ? element.href.baseVal : element.href;
  535. const normalizedHref = DomUtil.normalizeURL(href);
  536. if (normalizedHref == href && href) {
  537. element.setAttribute("href", href);
  538. }
  539. }
  540. });
  541. }
  542. removeUnusedStyles() {
  543. if (!this.mediaAllInfo) {
  544. this.mediaAllInfo = DOM.getMediaAllInfo(this.doc, { stylesheets: this.stylesheets, styles: this.styles });
  545. }
  546. const stats = DOM.minifyCSSRules(this.stylesheets, this.styles, this.mediaAllInfo);
  547. this.stats.set("processed", "CSS rules", stats.processed);
  548. this.stats.set("discarded", "CSS rules", stats.discarded);
  549. }
  550. removeUnusedFonts() {
  551. DOM.removeUnusedFonts(this.doc, this.stylesheets, this.styles, this.options);
  552. }
  553. removeAlternativeFonts() {
  554. DOM.removeAlternativeFonts(this.doc, this.stylesheets);
  555. }
  556. removeAlternativeImages() {
  557. DOM.removeAlternativeImages(this.doc);
  558. }
  559. removeHiddenElements() {
  560. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(this.options.sessionId) + "]");
  561. this.stats.set("discarded", "hidden elements", hiddenElements.length);
  562. this.stats.set("processed", "hidden elements", hiddenElements.length);
  563. hiddenElements.forEach(element => element.remove());
  564. }
  565. compressHTML() {
  566. let size;
  567. if (this.options.displayStats) {
  568. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  569. }
  570. DOM.minifyHTML(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  571. if (this.options.displayStats) {
  572. this.stats.add("discarded", "HTML bytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  573. }
  574. }
  575. removeAlternativeMedias() {
  576. const stats = DOM.minifyMedias(this.stylesheets);
  577. this.stats.set("processed", "medias", stats.processed);
  578. this.stats.set("discarded", "medias", stats.discarded);
  579. }
  580. replaceCanvasElements() {
  581. if (this.options.canvasData) {
  582. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  583. const canvasData = this.options.canvasData[indexCanvasElement];
  584. if (canvasData) {
  585. DomProcessorHelper.setBackgroundImage(canvasElement, "url(" + canvasData.dataURI + ")");
  586. this.stats.add("processed", "canvas", 1);
  587. }
  588. });
  589. }
  590. }
  591. insertFonts() {
  592. if (this.options.fontsData && this.options.fontsData.length) {
  593. let stylesheetContent = "";
  594. this.options.fontsData.forEach(fontStyles => {
  595. if (fontStyles["font-family"] && fontStyles.src) {
  596. stylesheetContent += "@font-face{";
  597. let stylesContent = "";
  598. Object.keys(fontStyles).forEach(fontStyle => {
  599. if (stylesContent) {
  600. stylesContent += ";";
  601. }
  602. stylesContent += fontStyle + ":" + fontStyles[fontStyle];
  603. });
  604. stylesheetContent += stylesContent + "}";
  605. }
  606. });
  607. if (stylesheetContent) {
  608. const styleElement = this.doc.createElement("style");
  609. styleElement.textContent = stylesheetContent;
  610. const existingStyleElement = this.doc.querySelector("style");
  611. if (existingStyleElement) {
  612. existingStyleElement.parentElement.insertBefore(styleElement, existingStyleElement);
  613. } else {
  614. this.doc.head.insertBefore(styleElement, this.doc.head.firstChild);
  615. }
  616. }
  617. }
  618. }
  619. replaceStyleContents() {
  620. if (this.options.stylesheetContents) {
  621. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  622. if (this.options.stylesheetContents[styleIndex]) {
  623. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  624. }
  625. });
  626. }
  627. }
  628. insertShadowRootContents() {
  629. if (this.options.shadowRootContents) {
  630. this.doc.querySelectorAll("[" + DOM.shadowRootAttributeName(this.options.sessionId) + "]").forEach((element, elementIndex) => {
  631. const DOMParser = DOM.getParser();
  632. const elementInfo = this.options.shadowRootContents[elementIndex];
  633. if (DOMParser && elementInfo) {
  634. const frameElement = this.doc.createElement("iframe");
  635. frameElement.setAttribute("style", "all:initial!important;border:0!important;width:100%!important;height:" + elementInfo.height + "px!important");
  636. const windowId = "shadow-" + this.options.framesData.length;
  637. frameElement.setAttribute(DOM.windowIdAttributeName(this.options.sessionId), windowId);
  638. this.options.framesData.push({ windowId, content: elementInfo.content, baseURI: this.baseURI });
  639. element.appendChild(frameElement);
  640. }
  641. });
  642. }
  643. }
  644. insertVideoPosters() {
  645. if (this.options.postersData) {
  646. this.doc.querySelectorAll("video[src], video > source[src]").forEach((element, videoIndex) => {
  647. let videoElement;
  648. if (element.tagName == "VIDEO") {
  649. videoElement = element;
  650. } else {
  651. videoElement = element.parentElement;
  652. }
  653. if (!videoElement.poster && this.options.postersData[videoIndex]) {
  654. videoElement.setAttribute("poster", this.options.postersData[videoIndex]);
  655. }
  656. });
  657. }
  658. }
  659. async processPageResources() {
  660. const processAttributeArgs = [
  661. ["link[href][rel*=\"icon\"]", "href", "data:", false, true],
  662. ["object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]", "data", PREFIX_DATA_URI_IMAGE_SVG],
  663. ["img[src], input[src][type=image]", "src", PREFIX_DATA_URI_IMAGE, true],
  664. ["embed[src*=\".svg\"]", "src", PREFIX_DATA_URI_IMAGE_SVG],
  665. ["video[poster]", "poster", PREFIX_DATA_URI_IMAGE],
  666. ["*[background]", "background", PREFIX_DATA_URI_IMAGE],
  667. ["image", "xlink:href", PREFIX_DATA_URI_IMAGE]
  668. ];
  669. let resourcePromises = processAttributeArgs.map(([selector, attributeName, prefixDataURI, processDuplicates, removeElementIfMissing]) =>
  670. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll(selector), attributeName, prefixDataURI, this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest, processDuplicates, removeElementIfMissing)
  671. );
  672. resourcePromises = resourcePromises.concat([
  673. DomProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.options, this.batchRequest),
  674. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest)
  675. ]);
  676. if (!this.options.removeAudioSrc) {
  677. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", PREFIX_DATA_URI_AUDIO, this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest));
  678. }
  679. if (!this.options.removeVideoSrc) {
  680. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("video[src], video > source[src]"), "src", PREFIX_DATA_URI_VIDEO, this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest));
  681. }
  682. await Promise.all(resourcePromises);
  683. DomProcessorHelper.processShortcutIcons(this.doc);
  684. }
  685. async resolveStylesheetURLs() {
  686. await Promise.all(Array.from(this.doc.querySelectorAll("style, link[rel*=stylesheet]"))
  687. .map(async element => {
  688. let mediaText;
  689. if (element.media) {
  690. mediaText = element.media;
  691. }
  692. this.stylesheets.set(element, { mediaText });
  693. const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, url: this.options.url, charSet: this.charSet, compressCSS: this.options.compressCSS };
  694. const isLinkTag = element.tagName.toLowerCase() == "link";
  695. if (isLinkTag && element.rel.includes("alternate") && element.title) {
  696. element.remove();
  697. } else {
  698. let stylesheetContent;
  699. if (isLinkTag) {
  700. if (element.charset) {
  701. options.charSet = element.charset;
  702. }
  703. stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(element.href, this.baseURI, options);
  704. } else {
  705. stylesheetContent = await DomProcessorHelper.resolveImportURLs(element.textContent, this.baseURI, options);
  706. }
  707. const stylesheet = cssTree.parse(stylesheetContent);
  708. if (this.options.compressCSS) {
  709. const removedRules = [];
  710. for (let cssRule = stylesheet.children.head; cssRule; cssRule = cssRule.next) {
  711. if (cssRule.data.type == "Raw" && cssRule.data.value && cssRule.data.value.trim().startsWith("//")) {
  712. removedRules.push(cssRule);
  713. }
  714. }
  715. removedRules.forEach(cssRule => stylesheet.children.remove(cssRule));
  716. }
  717. this.stylesheets.get(element).stylesheet = stylesheet;
  718. }
  719. }));
  720. }
  721. async processStylesheets() {
  722. await Promise.all(Array.from(this.stylesheets).map(([, stylesheetInfo]) =>
  723. DomProcessorHelper.processStylesheet(stylesheetInfo.stylesheet.children, this.baseURI, this.options, this.cssVariables, this.batchRequest)
  724. ));
  725. }
  726. replaceStylesheets() {
  727. this.doc.querySelectorAll("style").forEach(styleElement => {
  728. const stylesheetInfo = this.stylesheets.get(styleElement);
  729. if (stylesheetInfo) {
  730. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  731. styleElement.textContent = stylesheetContent;
  732. if (stylesheetInfo.mediaText) {
  733. styleElement.media = stylesheetInfo.mediaText;
  734. }
  735. } else {
  736. styleElement.remove();
  737. }
  738. });
  739. this.doc.querySelectorAll("link[rel*=stylesheet]").forEach(linkElement => {
  740. const stylesheetInfo = this.stylesheets.get(linkElement);
  741. if (stylesheetInfo) {
  742. const styleElement = this.doc.createElement("style");
  743. if (stylesheetInfo.mediaText) {
  744. styleElement.media = stylesheetInfo.mediaText;
  745. }
  746. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  747. styleElement.textContent = stylesheetContent;
  748. linkElement.parentElement.replaceChild(styleElement, linkElement);
  749. } else {
  750. linkElement.remove();
  751. }
  752. });
  753. }
  754. insertVariables() {
  755. if (this.cssVariables.size) {
  756. const styleElement = this.doc.createElement("style");
  757. const firstStyleElement = this.doc.head.querySelector("style");
  758. if (firstStyleElement) {
  759. this.doc.head.insertBefore(styleElement, firstStyleElement);
  760. } else {
  761. this.doc.head.appendChild(styleElement);
  762. }
  763. let stylesheetContent = "";
  764. this.cssVariables.forEach((content, indexResource) => {
  765. if (stylesheetContent) {
  766. stylesheetContent += ";";
  767. }
  768. stylesheetContent += `${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")`;
  769. });
  770. styleElement.textContent = ":root{" + stylesheetContent + "}";
  771. }
  772. }
  773. async processScripts() {
  774. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  775. if (scriptElement.src) {
  776. this.stats.add("processed", "scripts", 1);
  777. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  778. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  779. }
  780. scriptElement.removeAttribute("src");
  781. }));
  782. }
  783. async resolveFrameURLs() {
  784. if (this.options.framesData) {
  785. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  786. await Promise.all(frameElements.map(async frameElement => {
  787. DomProcessorHelper.setFrameEmptySrc(frameElement);
  788. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  789. if (frameWindowId) {
  790. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  791. if (frameData) {
  792. await initializeProcessor(frameData, frameElement, frameWindowId, this.batchRequest, Object.create(this.options));
  793. }
  794. }
  795. }));
  796. }
  797. async function initializeProcessor(frameData, frameElement, frameWindowId, batchRequest, options) {
  798. options.insertSingleFileComment = false;
  799. options.insertFaviconLink = false;
  800. options.doc = null;
  801. options.win = null;
  802. options.url = frameData.baseURI;
  803. options.windowId = frameWindowId;
  804. if (frameData.content) {
  805. options.content = frameData.content;
  806. options.canvasData = frameData.canvasData;
  807. options.stylesheetContents = frameData.stylesheetContents;
  808. options.fontsData = frameData.fontsData;
  809. options.imageData = frameData.imageData;
  810. options.usedFonts = frameData.usedFonts;
  811. frameData.processor = new PageProcessor(options);
  812. frameData.frameElement = frameElement;
  813. await frameData.processor.loadPage();
  814. await frameData.processor.initialize();
  815. frameData.maxResources = batchRequest.getMaxResources();
  816. }
  817. }
  818. }
  819. async processFrames() {
  820. if (this.options.framesData) {
  821. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  822. await Promise.all(frameElements.map(async frameElement => {
  823. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  824. if (frameWindowId) {
  825. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  826. if (frameData) {
  827. if (frameData.processor) {
  828. this.stats.add("processed", "frames", 1);
  829. await frameData.processor.run();
  830. const pageData = await frameData.processor.getPageData();
  831. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  832. if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND)) {
  833. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  834. } else {
  835. frameElement.setAttribute("sandbox", "");
  836. }
  837. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  838. this.stats.addAll(pageData);
  839. } else {
  840. this.stats.add("discarded", "frames", 1);
  841. }
  842. }
  843. }
  844. }));
  845. }
  846. }
  847. async resolveHtmlImportURLs() {
  848. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  849. if (!this.relImportProcessors) {
  850. this.relImportProcessors = new Map();
  851. }
  852. await Promise.all(linkElements.map(async linkElement => {
  853. const resourceURL = linkElement.href;
  854. linkElement.removeAttribute("href");
  855. const options = Object.create(this.options);
  856. options.insertSingleFileComment = false;
  857. options.insertFaviconLink = false;
  858. options.doc = null;
  859. options.win = null;
  860. options.url = resourceURL;
  861. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, this.baseURI, this.options.url)) {
  862. const processor = new PageProcessor(options);
  863. this.relImportProcessors.set(linkElement, processor);
  864. await processor.loadPage();
  865. return processor.initialize();
  866. }
  867. }));
  868. }
  869. async processHtmlImports() {
  870. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  871. await Promise.all(linkElements.map(async linkElement => {
  872. const processor = this.relImportProcessors.get(linkElement);
  873. if (processor) {
  874. this.stats.add("processed", "HTML imports", 1);
  875. this.relImportProcessors.delete(linkElement);
  876. const pageData = await processor.getPageData();
  877. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  878. this.stats.addAll(pageData);
  879. } else {
  880. this.stats.add("discarded", "HTML imports", 1);
  881. }
  882. }));
  883. }
  884. resolveStyleAttributeURLs() {
  885. this.doc.querySelectorAll("[style]").forEach(element => {
  886. let styleContent = element.getAttribute("style");
  887. if (this.options.compressCSS) {
  888. styleContent = DOM.compressCSS(styleContent);
  889. }
  890. styleContent = DomProcessorHelper.resolveStylesheetURLs(styleContent, this.baseURI, this.options);
  891. const declarationList = cssTree.parse(styleContent, { context: "declarationList" });
  892. this.styles.set(element, declarationList);
  893. });
  894. }
  895. async processStyleAttributes() {
  896. return Promise.all(Array.from(this.styles).map(([, declarationList]) =>
  897. DomProcessorHelper.processStyle(declarationList.children.toArray(), this.baseURI, this.options, this.cssVariables, this.batchRequest)
  898. ));
  899. }
  900. replaceStyleAttributes() {
  901. this.doc.querySelectorAll("[style]").forEach(async element => {
  902. const declarations = this.styles.get(element);
  903. if (declarations) {
  904. let styleContent = cssTree.generate(declarations);
  905. element.setAttribute("style", styleContent);
  906. } else {
  907. element.setAttribute("style", "");
  908. }
  909. });
  910. }
  911. }
  912. // ---------
  913. // DomHelper
  914. // ---------
  915. const REGEXP_AMP = /&/g;
  916. const REGEXP_NBSP = /\u00a0/g;
  917. const REGEXP_START_TAG = /</g;
  918. const REGEXP_END_TAG = />/g;
  919. const REGEXP_URL_HASH = /(#.+?)$/;
  920. const PREFIX_DATA_URI_IMAGE = "data:image/";
  921. const PREFIX_DATA_URI_AUDIO = "data:audio/";
  922. const PREFIX_DATA_URI_VIDEO = "data:video/";
  923. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  924. const PREFIX_DATA_URI_NO_MIMETYPE = "data:;";
  925. const PREFIX_DATA_URI_OCTET_STREAM = /^data:(application|binary)\/octet-stream/;
  926. const PREFIX_DATA_URI_VND = "data:application/vnd.";
  927. const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
  928. class DomProcessorHelper {
  929. static async evalTemplate(template, options, content, dontReplaceSlash) {
  930. const date = new Date();
  931. const url = new URL(options.url);
  932. template = await DomUtil.evalTemplateVariable(template, "page-title", () => options.title || "No title", dontReplaceSlash);
  933. template = await DomUtil.evalTemplateVariable(template, "page-language", () => options.info.lang || "No language", dontReplaceSlash);
  934. template = await DomUtil.evalTemplateVariable(template, "page-description", () => options.info.description || "No description", dontReplaceSlash);
  935. template = await DomUtil.evalTemplateVariable(template, "page-author", () => options.info.author || "No author", dontReplaceSlash);
  936. template = await DomUtil.evalTemplateVariable(template, "page-creator", () => options.info.creator || "No creator", dontReplaceSlash);
  937. template = await DomUtil.evalTemplateVariable(template, "page-publisher", () => options.info.publisher || "No publisher", dontReplaceSlash);
  938. template = await DomUtil.evalTemplateVariable(template, "datetime-iso", () => date.toISOString(), dontReplaceSlash);
  939. template = await DomUtil.evalTemplateVariable(template, "date-iso", () => date.toISOString().split("T")[0], dontReplaceSlash);
  940. template = await DomUtil.evalTemplateVariable(template, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0], dontReplaceSlash);
  941. template = await DomUtil.evalTemplateVariable(template, "date-locale", () => date.toLocaleDateString(), dontReplaceSlash);
  942. template = await DomUtil.evalTemplateVariable(template, "time-locale", () => date.toLocaleTimeString(), dontReplaceSlash);
  943. template = await DomUtil.evalTemplateVariable(template, "day-locale", () => String(date.getDate()).padStart(2, "0"), dontReplaceSlash);
  944. template = await DomUtil.evalTemplateVariable(template, "month-locale", () => String(date.getMonth() + 1).padStart(2, "0"), dontReplaceSlash);
  945. template = await DomUtil.evalTemplateVariable(template, "year-locale", () => String(date.getFullYear()), dontReplaceSlash);
  946. template = await DomUtil.evalTemplateVariable(template, "datetime-locale", () => date.toLocaleString(), dontReplaceSlash);
  947. template = await DomUtil.evalTemplateVariable(template, "datetime-utc", () => date.toUTCString(), dontReplaceSlash);
  948. template = await DomUtil.evalTemplateVariable(template, "day-utc", () => String(date.getUTCDate()).padStart(2, "0"), dontReplaceSlash);
  949. template = await DomUtil.evalTemplateVariable(template, "month-utc", () => String(date.getUTCMonth() + 1).padStart(2, "0"), dontReplaceSlash);
  950. template = await DomUtil.evalTemplateVariable(template, "year-utc", () => String(date.getUTCFullYear()), dontReplaceSlash);
  951. template = await DomUtil.evalTemplateVariable(template, "hours-locale", () => String(date.getHours()).padStart(2, "0"), dontReplaceSlash);
  952. template = await DomUtil.evalTemplateVariable(template, "minutes-locale", () => String(date.getMinutes()).padStart(2, "0"), dontReplaceSlash);
  953. template = await DomUtil.evalTemplateVariable(template, "seconds-locale", () => String(date.getSeconds()).padStart(2, "0"), dontReplaceSlash);
  954. template = await DomUtil.evalTemplateVariable(template, "hours-utc", () => String(date.getUTCHours()).padStart(2, "0"), dontReplaceSlash);
  955. template = await DomUtil.evalTemplateVariable(template, "minutes-utc", () => String(date.getUTCMinutes()).padStart(2, "0"), dontReplaceSlash);
  956. template = await DomUtil.evalTemplateVariable(template, "seconds-utc", () => String(date.getUTCSeconds()).padStart(2, "0"), dontReplaceSlash);
  957. template = await DomUtil.evalTemplateVariable(template, "url-hash", () => url.hash.substring(1), dontReplaceSlash);
  958. template = await DomUtil.evalTemplateVariable(template, "url-host", () => url.host.replace(/\/$/, ""), dontReplaceSlash);
  959. template = await DomUtil.evalTemplateVariable(template, "url-hostname", () => url.hostname.replace(/\/$/, ""), dontReplaceSlash);
  960. template = await DomUtil.evalTemplateVariable(template, "url-href", () => url.href, dontReplaceSlash);
  961. template = await DomUtil.evalTemplateVariable(template, "url-password", () => url.password, dontReplaceSlash);
  962. template = await DomUtil.evalTemplateVariable(template, "url-pathname", () => url.pathname.replace(/^\//, "").replace(/\/$/, ""), dontReplaceSlash === undefined ? true : dontReplaceSlash);
  963. template = await DomUtil.evalTemplateVariable(template, "url-port", () => url.port, dontReplaceSlash);
  964. template = await DomUtil.evalTemplateVariable(template, "url-protocol", () => url.protocol, dontReplaceSlash);
  965. template = await DomUtil.evalTemplateVariable(template, "url-search", () => url.search.substring(1), dontReplaceSlash);
  966. template = await DomUtil.evalTemplateVariable(template, "url-username", () => url.username, dontReplaceSlash);
  967. template = await DomUtil.evalTemplateVariable(template, "tab-id", () => String(options.tabId || "No tab id"), dontReplaceSlash);
  968. template = await DomUtil.evalTemplateVariable(template, "url-last-segment", () => DomUtil.getLastSegment(url), dontReplaceSlash);
  969. if (content) {
  970. template = await DomUtil.evalTemplateVariable(template, "digest-sha-256", async () => DOM.digest("SHA-256", content), dontReplaceSlash);
  971. template = await DomUtil.evalTemplateVariable(template, "digest-sha-384", async () => DOM.digest("SHA-384", content), dontReplaceSlash);
  972. template = await DomUtil.evalTemplateVariable(template, "digest-sha-512", async () => DOM.digest("SHA-512", content), dontReplaceSlash);
  973. }
  974. return template;
  975. }
  976. static setBackgroundImage(element, url, style) {
  977. element.style.setProperty("background-blend-mode", "normal", "important");
  978. element.style.setProperty("background-clip", "content-box", "important");
  979. element.style.setProperty("background-position", style && style["background-position"] ? style["background-position"] : "center", "important");
  980. element.style.setProperty("background-color", style && style["background-color"] ? style["background-color"] : "transparent", "important");
  981. element.style.setProperty("background-image", url, "important");
  982. element.style.setProperty("background-size", style && style["background-size"] ? style["background-size"] : "100% 100%", "important");
  983. element.style.setProperty("background-origin", "content-box", "important");
  984. element.style.setProperty("background-repeat", "no-repeat", "important");
  985. }
  986. static processShortcutIcons(doc) {
  987. let shortcutIcon = DomUtil.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel=\"icon\"], link[href][rel=\"shortcut icon\"]")));
  988. if (!shortcutIcon) {
  989. shortcutIcon = DomUtil.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel*=\"icon\"]")));
  990. if (shortcutIcon) {
  991. shortcutIcon.rel = "icon";
  992. }
  993. }
  994. if (shortcutIcon) {
  995. doc.querySelectorAll("link[href][rel*=\"icon\"]").forEach(linkElement => {
  996. if (linkElement != shortcutIcon) {
  997. linkElement.remove();
  998. }
  999. });
  1000. }
  1001. }
  1002. static setFrameEmptySrc(frameElement) {
  1003. if (frameElement.tagName == "OBJECT") {
  1004. frameElement.setAttribute("data", "data:text/html,");
  1005. } else {
  1006. frameElement.removeAttribute("src");
  1007. frameElement.removeAttribute("srcdoc");
  1008. }
  1009. }
  1010. static setFrameContent(frameElement, content) {
  1011. if (frameElement.tagName == "OBJECT") {
  1012. frameElement.setAttribute("data", "data:text/html," + content);
  1013. } else {
  1014. frameElement.setAttribute("srcdoc", content);
  1015. frameElement.removeAttribute("src");
  1016. }
  1017. }
  1018. static isolateElements(rootElement) {
  1019. rootElement.querySelectorAll("*:not(style)").forEach(element => {
  1020. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  1021. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  1022. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  1023. element.remove();
  1024. }
  1025. });
  1026. isolateParentElements(rootElement.parentElement, rootElement);
  1027. function isolateParentElements(parentElement, element) {
  1028. let elementFound = false;
  1029. Array.from(parentElement.childNodes).forEach(node => {
  1030. elementFound = elementFound || (node == element);
  1031. const tagName = node.tagName && node.tagName.toLowerCase();
  1032. if (node != element && tagName != "svg" && tagName != "style" && tagName != "link") {
  1033. if (elementFound) {
  1034. node.remove();
  1035. } else {
  1036. node.hidden = true;
  1037. if (node.childNodes && node.childNodes.length) {
  1038. Array.from(node.childNodes).forEach(node => node.remove());
  1039. }
  1040. }
  1041. }
  1042. });
  1043. element = element.parentElement;
  1044. if (element && element.parentElement && element.parentElement.tagName != "HTML") {
  1045. isolateParentElements(element.parentElement, element);
  1046. }
  1047. }
  1048. }
  1049. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  1050. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI, options);
  1051. const imports = DomUtil.getImportFunctions(stylesheetContent);
  1052. await Promise.all(imports.map(async cssImport => {
  1053. const match = DomUtil.matchImport(cssImport);
  1054. if (match) {
  1055. let resourceURL = DomUtil.normalizeURL(match.resourceURL);
  1056. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1057. resourceURL = new URL(match.resourceURL, baseURI).href;
  1058. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1059. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, validateTextContentType: true };
  1060. let importedStylesheetContent = await Download.getContent(resourceURL, downloadOptions);
  1061. if (options.compressCSS) {
  1062. importedStylesheetContent = DOM.compressCSS(DomUtil.removeCssComments(importedStylesheetContent));
  1063. }
  1064. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  1065. if (stylesheetContent.includes(cssImport)) {
  1066. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, resourceURL, options);
  1067. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(cssImport), importedStylesheetContent);
  1068. }
  1069. }
  1070. }
  1071. }
  1072. }));
  1073. return stylesheetContent;
  1074. }
  1075. static resolveStylesheetURLs(stylesheetContent, baseURI, options) {
  1076. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  1077. urlFunctions.map(urlFunction => {
  1078. const originalResourceURL = DomUtil.matchURL(urlFunction);
  1079. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1080. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1081. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1082. const resolvedURL = new URL(resourceURL, baseURI).href;
  1083. if (DomUtil.testValidURL(resolvedURL, baseURI, options.url) && resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  1084. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  1085. }
  1086. }
  1087. } else {
  1088. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  1089. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  1090. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  1091. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  1092. }
  1093. }
  1094. }
  1095. });
  1096. return stylesheetContent;
  1097. }
  1098. static async resolveLinkStylesheetURLs(resourceURL, baseURI, options) {
  1099. resourceURL = DomUtil.normalizeURL(resourceURL);
  1100. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  1101. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, charSet: options.charSet };
  1102. let stylesheetContent = await Download.getContent(resourceURL, downloadOptions);
  1103. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  1104. if (options.compressCSS) {
  1105. stylesheetContent = DOM.compressCSS(DomUtil.removeCssComments(stylesheetContent));
  1106. }
  1107. return stylesheetContent;
  1108. }
  1109. }
  1110. static async processStylesheet(cssRules, baseURI, options, cssVariables, batchRequest) {
  1111. const promises = [];
  1112. const removedRules = [];
  1113. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  1114. const ruleData = cssRule.data;
  1115. if (ruleData.block && ruleData.block.children) {
  1116. if (ruleData.type == "Rule") {
  1117. promises.push(this.processStyle(ruleData.block.children.toArray(), baseURI, options, cssVariables, batchRequest));
  1118. } else if (ruleData.type == "Atrule" && ruleData.name == "charset") {
  1119. removedRules.push(cssRule);
  1120. } else if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports")) {
  1121. promises.push(this.processStylesheet(ruleData.block.children.toArray(), baseURI, options, cssVariables, batchRequest));
  1122. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  1123. promises.push(processDeclaration(ruleData));
  1124. }
  1125. }
  1126. }
  1127. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  1128. await Promise.all(promises);
  1129. async function processDeclaration(cssRule) {
  1130. await Promise.all(cssRule.block.children.toArray().map(async declaration => {
  1131. if (declaration.type == "Declaration") {
  1132. let declarationValue = "";
  1133. try {
  1134. declarationValue = cssTree.generate(declaration.value);
  1135. } catch (error) {
  1136. // ignored
  1137. }
  1138. const urlFunctions = DomUtil.getUrlFunctions(declarationValue); // TODO: use OM
  1139. await Promise.all(urlFunctions.map(async urlFunction => {
  1140. const originalResourceURL = DomUtil.matchURL(urlFunction);
  1141. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1142. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1143. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1144. let { content } = await batchRequest.addURL(resourceURL);
  1145. let validResource = content == EMPTY_DATA_URI || content.startsWith(PREFIX_DATA_URI_VND) || content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
  1146. if (!validResource) {
  1147. validResource = await DOM.validFont(urlFunction);
  1148. }
  1149. if (!validResource) {
  1150. content = EMPTY_DATA_URI;
  1151. }
  1152. declaration.value.children.forEach(token => {
  1153. let tokenValue = "";
  1154. try {
  1155. tokenValue = cssTree.generate(token.value);
  1156. } catch (error) {
  1157. // ignored
  1158. }
  1159. if (token.type == "Url" && DOM.removeQuotes(tokenValue) == originalResourceURL) {
  1160. token.value.value = content;
  1161. }
  1162. });
  1163. }
  1164. }
  1165. }));
  1166. }
  1167. }));
  1168. }
  1169. }
  1170. static async processStyle(declarations, baseURI, options, cssVariables, batchRequest) {
  1171. await Promise.all(declarations.map(async declaration => {
  1172. if (declaration.type == "Declaration") {
  1173. const declarationValue = cssTree.generate(declaration.value);
  1174. const urlFunctions = DomUtil.getUrlFunctions(declarationValue);
  1175. await Promise.all(urlFunctions.map(async urlFunction => {
  1176. const originalResourceURL = DomUtil.matchURL(urlFunction);
  1177. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1178. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1179. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1180. let { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  1181. if (duplicate && options.groupDuplicateImages) {
  1182. const tokens = [];
  1183. for (let token = declaration.value.children.head; token; token = token.next) {
  1184. if (token.data.type == "Url") {
  1185. const value = cssTree.parse("var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")", { context: "value" }).children.head;
  1186. tokens.push({ token, value });
  1187. }
  1188. }
  1189. tokens.forEach(({ token, value }) => declaration.value.children.replace(token, value));
  1190. cssVariables.set(indexResource, content);
  1191. } else {
  1192. declaration.value.children.forEach(token => {
  1193. if (token.type == "Url") {
  1194. token.value.value = content;
  1195. }
  1196. });
  1197. }
  1198. }
  1199. }
  1200. }));
  1201. }
  1202. }));
  1203. }
  1204. static async processAttribute(doc, resourceElements, attributeName, prefixDataURI, baseURI, options, cssVariables, styles, batchRequest, processDuplicates, removeElementIfMissing) {
  1205. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1206. let resourceURL = resourceElement.getAttribute(attributeName);
  1207. resourceURL = DomUtil.normalizeURL(resourceURL);
  1208. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1209. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1210. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1211. resourceURL = new URL(resourceURL, baseURI).href;
  1212. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1213. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  1214. if (removeElementIfMissing && content == EMPTY_DATA_URI) {
  1215. resourceElement.remove();
  1216. } else {
  1217. if (content.startsWith(prefixDataURI) || content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) || content.match(PREFIX_DATA_URI_OCTET_STREAM)) {
  1218. const isSVG = content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
  1219. if (processDuplicates && duplicate && options.groupDuplicateImages && !isSVG) {
  1220. if (DomUtil.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
  1221. cssVariables.set(indexResource, content);
  1222. const declarationList = cssTree.parse(resourceElement.getAttribute("style"), { context: "declarationList" });
  1223. styles.set(resourceElement, declarationList);
  1224. } else {
  1225. resourceElement.setAttribute(attributeName, content);
  1226. }
  1227. } else {
  1228. resourceElement.setAttribute(attributeName, content);
  1229. }
  1230. }
  1231. }
  1232. }
  1233. }
  1234. }
  1235. }));
  1236. }
  1237. static async processXLinks(resourceElements, baseURI, options, batchRequest) {
  1238. const attributeName = "xlink:href";
  1239. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1240. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1241. let resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1242. if (DomUtil.testValidPath(resourceURL, baseURI, options.url) && !DomUtil.testIgnoredPath(resourceURL)) {
  1243. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1244. resourceURL = new URL(resourceURL, baseURI).href;
  1245. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1246. try {
  1247. const { content } = await batchRequest.addURL(resourceURL, false);
  1248. const DOMParser = DOM.getParser();
  1249. if (DOMParser) {
  1250. const svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  1251. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1252. if (hashMatch && hashMatch[0]) {
  1253. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1254. if (symbolElement) {
  1255. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1256. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1257. }
  1258. } else {
  1259. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1260. }
  1261. } else {
  1262. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1263. }
  1264. } catch (error) {
  1265. /* ignored */
  1266. }
  1267. }
  1268. } else if (resourceURL == options.url) {
  1269. resourceElement.setAttribute(attributeName, originalResourceURL.substring(resourceURL.length));
  1270. }
  1271. }));
  1272. }
  1273. static async processSrcset(resourceElements, attributeName, prefixDataURI, baseURI, options, batchRequest) {
  1274. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1275. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  1276. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1277. let resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  1278. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1279. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1280. resourceURL = new URL(resourceURL, baseURI).href;
  1281. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1282. const { content } = await batchRequest.addURL(resourceURL);
  1283. if (!content.startsWith(prefixDataURI) && !content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) && !content.match(PREFIX_DATA_URI_OCTET_STREAM)) {
  1284. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1285. }
  1286. return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1287. } else {
  1288. return "";
  1289. }
  1290. } else {
  1291. return "";
  1292. }
  1293. } else {
  1294. return resourceURL + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1295. }
  1296. }));
  1297. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1298. }));
  1299. }
  1300. }
  1301. // -------
  1302. // DomUtil
  1303. // -------
  1304. const DATA_URI_PREFIX = "data:";
  1305. const BLOB_URI_PREFIX = "blob:";
  1306. const HTTP_URI_PREFIX = /^https?:\/\//;
  1307. const FILE_URI_PREFIX = /^file:\/\//;
  1308. const EMPTY_URL = /^https?:\/\/+\s*$/;
  1309. const ABOUT_BLANK_URI = "about:blank";
  1310. const NOT_EMPTY_URL = /^(https?:\/\/|file:\/\/|blob:).+/;
  1311. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1312. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1313. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1314. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1315. 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;
  1316. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1317. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1318. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1319. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1320. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1321. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1322. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1323. class DomUtil {
  1324. static normalizeURL(url) {
  1325. if (!url || url.startsWith(DATA_URI_PREFIX)) {
  1326. return url;
  1327. } else {
  1328. return url.split("#")[0];
  1329. }
  1330. }
  1331. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
  1332. const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
  1333. if (template.match(replaceRegExp)) {
  1334. let value = await valueGetter();
  1335. if (!dontReplaceSlash) {
  1336. value = value.replace(/\/+/g, "_");
  1337. }
  1338. return template.replace(replaceRegExp, value);
  1339. }
  1340. return template;
  1341. }
  1342. static getLastSegment(url) {
  1343. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/), lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1344. if (!lastSegment) {
  1345. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1346. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1347. }
  1348. if (!lastSegment) {
  1349. lastSegmentMatch = lastSegment.match(/(.*)<\.[^.]+$/);
  1350. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1351. }
  1352. if (!lastSegment) {
  1353. lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
  1354. }
  1355. lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1356. return lastSegment;
  1357. }
  1358. static getRegExp(string) {
  1359. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1360. }
  1361. static getUrlFunctions(stylesheetContent) {
  1362. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1363. }
  1364. static getImportFunctions(stylesheetContent) {
  1365. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1366. }
  1367. static findShortcutIcon(shortcutIcons) {
  1368. shortcutIcons = shortcutIcons.filter(linkElement => linkElement.href != EMPTY_IMAGE);
  1369. shortcutIcons.sort((linkElement1, linkElement2) => (parseInt(linkElement2.sizes, 10) || 16) - (parseInt(linkElement1.sizes, 10) || 16));
  1370. return shortcutIcons[0];
  1371. }
  1372. static matchURL(stylesheetContent) {
  1373. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1374. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1375. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1376. return match && match[1];
  1377. }
  1378. static testIgnoredPath(resourceURL) {
  1379. return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) /*|| resourceURL.startsWith(BLOB_URI_PREFIX)*/ || resourceURL == ABOUT_BLANK_URI);
  1380. }
  1381. static testValidPath(resourceURL, baseURI, docURL) {
  1382. return resourceURL && resourceURL != baseURI && resourceURL != docURL && !resourceURL.match(EMPTY_URL);
  1383. }
  1384. static testValidURL(resourceURL, baseURI, docURL) {
  1385. return DomUtil.testValidPath(resourceURL, baseURI, docURL) && (resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(FILE_URI_PREFIX) || resourceURL.startsWith(BLOB_URI_PREFIX)) && resourceURL.match(NOT_EMPTY_URL);
  1386. }
  1387. static matchImport(stylesheetContent) {
  1388. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1389. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1390. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1391. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1392. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1393. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1394. if (match) {
  1395. const [, resourceURL, media] = match;
  1396. return { resourceURL, media };
  1397. }
  1398. }
  1399. static removeCssComments(stylesheetContent) {
  1400. let start, end;
  1401. do {
  1402. start = stylesheetContent.indexOf("/*");
  1403. end = stylesheetContent.indexOf("*/", start + 2);
  1404. if (start != -1 && end != -1) {
  1405. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1406. }
  1407. } while (start != -1 && end != -1);
  1408. return stylesheetContent;
  1409. }
  1410. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1411. if (mediaQuery) {
  1412. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1413. } else {
  1414. return stylesheetContent;
  1415. }
  1416. }
  1417. static replaceImageSource(imgElement, variableName, options) {
  1418. const dataAttributeName = DOM.imagesAttributeName(options.sessionId);
  1419. if (imgElement.getAttribute(dataAttributeName) != null) {
  1420. const imgData = options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  1421. if (imgData.replaceable) {
  1422. imgElement.setAttribute("src", `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="${imgData.size.pxWidth}" height="${imgData.size.pxHeight}"><rect fill-opacity="0"/></svg>`);
  1423. const backgroundStyle = {};
  1424. const backgroundSize = (imgData.objectFit == "content" || imgData.objectFit == "cover") && imgData.objectFit;
  1425. if (backgroundSize) {
  1426. backgroundStyle["background-size"] = imgData.objectFit;
  1427. }
  1428. if (imgData.objectPosition) {
  1429. backgroundStyle["background-position"] = imgData.objectPosition;
  1430. }
  1431. if (imgData.backgroundColor) {
  1432. backgroundStyle["background-color"] = imgData.backgroundColor;
  1433. }
  1434. DomProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")", backgroundStyle);
  1435. imgElement.removeAttribute(dataAttributeName);
  1436. return true;
  1437. }
  1438. }
  1439. }
  1440. }
  1441. function log(...args) {
  1442. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1443. }
  1444. // -----
  1445. // Stats
  1446. // -----
  1447. const STATS_DEFAULT_VALUES = {
  1448. discarded: {
  1449. "HTML bytes": 0,
  1450. "hidden elements": 0,
  1451. "HTML imports": 0,
  1452. scripts: 0,
  1453. objects: 0,
  1454. "audio sources": 0,
  1455. "video sources": 0,
  1456. frames: 0,
  1457. "CSS rules": 0,
  1458. canvas: 0,
  1459. stylesheets: 0,
  1460. resources: 0,
  1461. medias: 0
  1462. },
  1463. processed: {
  1464. "HTML bytes": 0,
  1465. "hidden elements": 0,
  1466. "HTML imports": 0,
  1467. scripts: 0,
  1468. objects: 0,
  1469. "audio sources": 0,
  1470. "video sources": 0,
  1471. frames: 0,
  1472. "CSS rules": 0,
  1473. canvas: 0,
  1474. stylesheets: 0,
  1475. resources: 0,
  1476. medias: 0
  1477. }
  1478. };
  1479. class Stats {
  1480. constructor(options) {
  1481. this.options = options;
  1482. if (options.displayStats) {
  1483. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1484. }
  1485. }
  1486. set(type, subType, value) {
  1487. if (this.options.displayStats) {
  1488. this.data[type][subType] = value;
  1489. }
  1490. }
  1491. add(type, subType, value) {
  1492. if (this.options.displayStats) {
  1493. this.data[type][subType] += value;
  1494. }
  1495. }
  1496. addAll(pageData) {
  1497. if (this.options.displayStats) {
  1498. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1499. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1500. }
  1501. }
  1502. }
  1503. return { getClass };
  1504. })();