single-file-core.js 68 KB

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