single-file-core.js 68 KB

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