single-file-core.js 71 KB

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