single-file-core.js 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  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. let mediaText;
  698. if (element.media) {
  699. mediaText = element.media;
  700. }
  701. this.stylesheets.set(element, { mediaText });
  702. const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, url: this.options.url, charSet: this.charSet, compressCSS: this.options.compressCSS };
  703. const isLinkTag = element.tagName.toLowerCase() == "link";
  704. if (isLinkTag && element.rel.includes("alternate") && element.title) {
  705. element.remove();
  706. } else {
  707. let stylesheetContent;
  708. if (isLinkTag) {
  709. if (element.charset) {
  710. options.charSet = element.charset;
  711. }
  712. stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(element.href, this.baseURI, options);
  713. } else {
  714. stylesheetContent = await DomProcessorHelper.resolveImportURLs(element.textContent, this.baseURI, options);
  715. }
  716. const stylesheet = cssTree.parse(stylesheetContent);
  717. if (this.options.compressCSS) {
  718. const removedRules = [];
  719. for (let cssRule = stylesheet.children.head; cssRule; cssRule = cssRule.next) {
  720. if (cssRule.data.type == "Raw" && cssRule.data.value && cssRule.data.value.trim().startsWith("//")) {
  721. removedRules.push(cssRule);
  722. }
  723. }
  724. removedRules.forEach(cssRule => stylesheet.children.remove(cssRule));
  725. }
  726. this.stylesheets.get(element).stylesheet = stylesheet;
  727. }
  728. }));
  729. }
  730. async processStylesheets() {
  731. await Promise.all(Array.from(this.stylesheets).map(([, stylesheetInfo]) =>
  732. DomProcessorHelper.processStylesheet(stylesheetInfo.stylesheet.children, this.baseURI, this.options, this.cssVariables, this.batchRequest)
  733. ));
  734. }
  735. replaceStylesheets() {
  736. this.doc.querySelectorAll("style").forEach(styleElement => {
  737. const stylesheetInfo = this.stylesheets.get(styleElement);
  738. if (stylesheetInfo) {
  739. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  740. styleElement.textContent = stylesheetContent;
  741. if (stylesheetInfo.mediaText) {
  742. styleElement.media = stylesheetInfo.mediaText;
  743. }
  744. } else {
  745. styleElement.remove();
  746. }
  747. });
  748. this.doc.querySelectorAll("link[rel*=stylesheet]").forEach(linkElement => {
  749. const stylesheetInfo = this.stylesheets.get(linkElement);
  750. if (stylesheetInfo) {
  751. const styleElement = this.doc.createElement("style");
  752. if (stylesheetInfo.mediaText) {
  753. styleElement.media = stylesheetInfo.mediaText;
  754. }
  755. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  756. styleElement.textContent = stylesheetContent;
  757. linkElement.parentElement.replaceChild(styleElement, linkElement);
  758. } else {
  759. linkElement.remove();
  760. }
  761. });
  762. }
  763. insertVariables() {
  764. if (this.cssVariables.size) {
  765. const styleElement = this.doc.createElement("style");
  766. const firstStyleElement = this.doc.head.querySelector("style");
  767. if (firstStyleElement) {
  768. this.doc.head.insertBefore(styleElement, firstStyleElement);
  769. } else {
  770. this.doc.head.appendChild(styleElement);
  771. }
  772. let stylesheetContent = "";
  773. this.cssVariables.forEach((content, indexResource) => {
  774. if (stylesheetContent) {
  775. stylesheetContent += ";";
  776. }
  777. stylesheetContent += `${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")`;
  778. });
  779. styleElement.textContent = ":root{" + stylesheetContent + "}";
  780. }
  781. }
  782. async processScripts() {
  783. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  784. if (scriptElement.src) {
  785. this.stats.add("processed", "scripts", 1);
  786. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  787. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  788. }
  789. scriptElement.removeAttribute("src");
  790. }));
  791. }
  792. async resolveFrameURLs() {
  793. if (this.options.framesData) {
  794. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  795. await Promise.all(frameElements.map(async frameElement => {
  796. DomProcessorHelper.setFrameEmptySrc(frameElement);
  797. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  798. if (frameWindowId) {
  799. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  800. if (frameData) {
  801. await initializeProcessor(frameData, frameElement, frameWindowId, this.batchRequest, Object.create(this.options));
  802. }
  803. }
  804. }));
  805. }
  806. async function initializeProcessor(frameData, frameElement, frameWindowId, batchRequest, options) {
  807. options.insertSingleFileComment = false;
  808. options.insertFaviconLink = false;
  809. options.doc = null;
  810. options.win = null;
  811. options.url = frameData.baseURI;
  812. options.windowId = frameWindowId;
  813. if (frameData.content) {
  814. options.content = frameData.content;
  815. options.canvasData = frameData.canvasData;
  816. options.stylesheetContents = frameData.stylesheetContents;
  817. options.fontsData = frameData.fontsData;
  818. options.imageData = frameData.imageData;
  819. options.usedFonts = frameData.usedFonts;
  820. frameData.processor = new PageProcessor(options);
  821. frameData.frameElement = frameElement;
  822. await frameData.processor.loadPage();
  823. await frameData.processor.initialize();
  824. frameData.maxResources = batchRequest.getMaxResources();
  825. }
  826. }
  827. }
  828. async processFrames() {
  829. if (this.options.framesData) {
  830. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  831. await Promise.all(frameElements.map(async frameElement => {
  832. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  833. if (frameWindowId) {
  834. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  835. if (frameData) {
  836. if (frameData.processor) {
  837. this.stats.add("processed", "frames", 1);
  838. await frameData.processor.run();
  839. const pageData = await frameData.processor.getPageData();
  840. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  841. if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND)) {
  842. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  843. } else {
  844. frameElement.setAttribute("sandbox", "");
  845. }
  846. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  847. this.stats.addAll(pageData);
  848. } else {
  849. this.stats.add("discarded", "frames", 1);
  850. }
  851. }
  852. }
  853. }));
  854. }
  855. }
  856. async resolveHtmlImportURLs() {
  857. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  858. if (!this.relImportProcessors) {
  859. this.relImportProcessors = new Map();
  860. }
  861. await Promise.all(linkElements.map(async linkElement => {
  862. const resourceURL = linkElement.href;
  863. linkElement.removeAttribute("href");
  864. const options = Object.create(this.options);
  865. options.insertSingleFileComment = false;
  866. options.insertFaviconLink = false;
  867. options.doc = null;
  868. options.win = null;
  869. options.url = resourceURL;
  870. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, this.baseURI, this.options.url)) {
  871. const processor = new PageProcessor(options);
  872. this.relImportProcessors.set(linkElement, processor);
  873. await processor.loadPage();
  874. return processor.initialize();
  875. }
  876. }));
  877. }
  878. async processHtmlImports() {
  879. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  880. await Promise.all(linkElements.map(async linkElement => {
  881. const processor = this.relImportProcessors.get(linkElement);
  882. if (processor) {
  883. this.stats.add("processed", "HTML imports", 1);
  884. this.relImportProcessors.delete(linkElement);
  885. const pageData = await processor.getPageData();
  886. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  887. this.stats.addAll(pageData);
  888. } else {
  889. this.stats.add("discarded", "HTML imports", 1);
  890. }
  891. }));
  892. }
  893. resolveStyleAttributeURLs() {
  894. Array.from(this.doc.querySelectorAll("[style]")).map(element => {
  895. let styleContent = element.getAttribute("style");
  896. if (this.options.compressCSS) {
  897. styleContent = DOM.compressCSS(styleContent);
  898. }
  899. styleContent = DomProcessorHelper.resolveStylesheetURLs(styleContent, this.baseURI, this.options);
  900. const declarationList = cssTree.parse(styleContent, { context: "declarationList" });
  901. this.styles.set(element, declarationList);
  902. });
  903. }
  904. async processStyleAttributes() {
  905. return Promise.all(Array.from(this.styles).map(([, declarationList]) => {
  906. return DomProcessorHelper.processStyle(declarationList.children.toArray(), this.baseURI, this.options, this.cssVariables, this.batchRequest);
  907. }));
  908. }
  909. replaceStyleAttributes() {
  910. this.doc.querySelectorAll("[style]").forEach(async element => {
  911. const declarations = this.styles.get(element);
  912. if (declarations) {
  913. let styleContent = cssTree.generate(declarations);
  914. element.setAttribute("style", styleContent);
  915. } else {
  916. element.setAttribute("style", "");
  917. }
  918. });
  919. }
  920. }
  921. // ---------
  922. // DomHelper
  923. // ---------
  924. const REGEXP_AMP = /&/g;
  925. const REGEXP_NBSP = /\u00a0/g;
  926. const REGEXP_START_TAG = /</g;
  927. const REGEXP_END_TAG = />/g;
  928. const REGEXP_URL_HASH = /(#.+?)$/;
  929. const PREFIX_DATA_URI_IMAGE = "data:image/";
  930. const PREFIX_DATA_URI_AUDIO = "data:audio/";
  931. const PREFIX_DATA_URI_VIDEO = "data:video/";
  932. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  933. const PREFIX_DATA_URI_NO_MIMETYPE = "data:;";
  934. const PREFIX_DATA_URI_OCTET_STREAM = /^data:(application|binary)\/octet-stream/;
  935. const PREFIX_DATA_URI_VND = "data:application/vnd.";
  936. const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
  937. class DomProcessorHelper {
  938. static async evalTemplate(template, options, content, dontReplaceSlash) {
  939. const date = new Date();
  940. const url = new URL(options.url);
  941. template = await DomUtil.evalTemplateVariable(template, "page-title", () => options.title || "No title", dontReplaceSlash);
  942. template = await DomUtil.evalTemplateVariable(template, "page-language", () => options.info.lang || "No language", dontReplaceSlash);
  943. template = await DomUtil.evalTemplateVariable(template, "page-description", () => options.info.description || "No description", dontReplaceSlash);
  944. template = await DomUtil.evalTemplateVariable(template, "page-author", () => options.info.author || "No author", dontReplaceSlash);
  945. template = await DomUtil.evalTemplateVariable(template, "page-creator", () => options.info.creator || "No creator", dontReplaceSlash);
  946. template = await DomUtil.evalTemplateVariable(template, "page-publisher", () => options.info.publisher || "No publisher", dontReplaceSlash);
  947. template = await DomUtil.evalTemplateVariable(template, "datetime-iso", () => date.toISOString(), dontReplaceSlash);
  948. template = await DomUtil.evalTemplateVariable(template, "date-iso", () => date.toISOString().split("T")[0], dontReplaceSlash);
  949. template = await DomUtil.evalTemplateVariable(template, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0], dontReplaceSlash);
  950. template = await DomUtil.evalTemplateVariable(template, "date-locale", () => date.toLocaleDateString(), dontReplaceSlash);
  951. template = await DomUtil.evalTemplateVariable(template, "time-locale", () => date.toLocaleTimeString(), dontReplaceSlash);
  952. template = await DomUtil.evalTemplateVariable(template, "day-locale", () => String(date.getDate()).padStart(2, "0"), dontReplaceSlash);
  953. template = await DomUtil.evalTemplateVariable(template, "month-locale", () => String(date.getMonth() + 1).padStart(2, "0"), dontReplaceSlash);
  954. template = await DomUtil.evalTemplateVariable(template, "year-locale", () => String(date.getFullYear()), dontReplaceSlash);
  955. template = await DomUtil.evalTemplateVariable(template, "datetime-locale", () => date.toLocaleString(), dontReplaceSlash);
  956. template = await DomUtil.evalTemplateVariable(template, "datetime-utc", () => date.toUTCString(), dontReplaceSlash);
  957. template = await DomUtil.evalTemplateVariable(template, "day-utc", () => String(date.getUTCDate()).padStart(2, "0"), dontReplaceSlash);
  958. template = await DomUtil.evalTemplateVariable(template, "month-utc", () => String(date.getUTCMonth() + 1).padStart(2, "0"), dontReplaceSlash);
  959. template = await DomUtil.evalTemplateVariable(template, "year-utc", () => String(date.getUTCFullYear()), dontReplaceSlash);
  960. template = await DomUtil.evalTemplateVariable(template, "hours-locale", () => String(date.getHours()).padStart(2, "0"), dontReplaceSlash);
  961. template = await DomUtil.evalTemplateVariable(template, "minutes-locale", () => String(date.getMinutes()).padStart(2, "0"), dontReplaceSlash);
  962. template = await DomUtil.evalTemplateVariable(template, "seconds-locale", () => String(date.getSeconds()).padStart(2, "0"), dontReplaceSlash);
  963. template = await DomUtil.evalTemplateVariable(template, "hours-utc", () => String(date.getUTCHours()).padStart(2, "0"), dontReplaceSlash);
  964. template = await DomUtil.evalTemplateVariable(template, "minutes-utc", () => String(date.getUTCMinutes()).padStart(2, "0"), dontReplaceSlash);
  965. template = await DomUtil.evalTemplateVariable(template, "seconds-utc", () => String(date.getUTCSeconds()).padStart(2, "0"), dontReplaceSlash);
  966. template = await DomUtil.evalTemplateVariable(template, "url-hash", () => url.hash.substring(1), dontReplaceSlash);
  967. template = await DomUtil.evalTemplateVariable(template, "url-host", () => url.host.replace(/\/$/, ""), dontReplaceSlash);
  968. template = await DomUtil.evalTemplateVariable(template, "url-hostname", () => url.hostname.replace(/\/$/, ""), dontReplaceSlash);
  969. template = await DomUtil.evalTemplateVariable(template, "url-href", () => url.href, dontReplaceSlash);
  970. template = await DomUtil.evalTemplateVariable(template, "url-password", () => url.password, dontReplaceSlash);
  971. template = await DomUtil.evalTemplateVariable(template, "url-pathname", () => url.pathname.replace(/^\//, "").replace(/\/$/, ""), dontReplaceSlash === undefined ? true : dontReplaceSlash);
  972. template = await DomUtil.evalTemplateVariable(template, "url-port", () => url.port, dontReplaceSlash);
  973. template = await DomUtil.evalTemplateVariable(template, "url-protocol", () => url.protocol, dontReplaceSlash);
  974. template = await DomUtil.evalTemplateVariable(template, "url-search", () => url.search.substring(1), dontReplaceSlash);
  975. template = await DomUtil.evalTemplateVariable(template, "url-username", () => url.username, dontReplaceSlash);
  976. template = await DomUtil.evalTemplateVariable(template, "tab-id", () => String(options.tabId || "No tab id"), dontReplaceSlash);
  977. template = await DomUtil.evalTemplateVariable(template, "url-last-segment", () => DomUtil.getLastSegment(url), dontReplaceSlash);
  978. if (content) {
  979. template = await DomUtil.evalTemplateVariable(template, "digest-sha-256", async () => DOM.digest("SHA-256", content), dontReplaceSlash);
  980. template = await DomUtil.evalTemplateVariable(template, "digest-sha-384", async () => DOM.digest("SHA-384", content), dontReplaceSlash);
  981. template = await DomUtil.evalTemplateVariable(template, "digest-sha-512", async () => DOM.digest("SHA-512", content), dontReplaceSlash);
  982. }
  983. return template;
  984. }
  985. static setBackgroundImage(element, url, style) {
  986. element.style.setProperty("background-blend-mode", "normal", "important");
  987. element.style.setProperty("background-clip", "content-box", "important");
  988. element.style.setProperty("background-position", style && style["background-position"] ? style["background-position"] : "center", "important");
  989. element.style.setProperty("background-color", style && style["background-color"] ? style["background-color"] : "transparent", "important");
  990. element.style.setProperty("background-image", url, "important");
  991. element.style.setProperty("background-size", style && style["background-size"] ? style["background-size"] : "100% 100%", "important");
  992. element.style.setProperty("background-origin", "content-box", "important");
  993. element.style.setProperty("background-repeat", "no-repeat", "important");
  994. }
  995. static setFrameEmptySrc(frameElement) {
  996. if (frameElement.tagName == "OBJECT") {
  997. frameElement.setAttribute("data", "data:text/html,");
  998. } else {
  999. frameElement.removeAttribute("src");
  1000. frameElement.removeAttribute("srcdoc");
  1001. }
  1002. }
  1003. static setFrameContent(frameElement, content) {
  1004. if (frameElement.tagName == "OBJECT") {
  1005. frameElement.setAttribute("data", "data:text/html," + content);
  1006. } else {
  1007. frameElement.setAttribute("srcdoc", content);
  1008. frameElement.removeAttribute("src");
  1009. }
  1010. }
  1011. static isolateElements(rootElement) {
  1012. rootElement.querySelectorAll("*:not(style)").forEach(element => {
  1013. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  1014. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  1015. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  1016. element.remove();
  1017. }
  1018. });
  1019. isolateParentElements(rootElement.parentElement, rootElement);
  1020. function isolateParentElements(parentElement, element) {
  1021. let elementFound = false;
  1022. Array.from(parentElement.childNodes).forEach(node => {
  1023. elementFound = elementFound || (node == element);
  1024. const tagName = node.tagName && node.tagName.toLowerCase();
  1025. if (node != element && tagName != "svg" && tagName != "style" && tagName != "link") {
  1026. if (elementFound) {
  1027. node.remove();
  1028. } else {
  1029. node.hidden = true;
  1030. if (node.childNodes && node.childNodes.length) {
  1031. Array.from(node.childNodes).forEach(node => node.remove());
  1032. }
  1033. }
  1034. }
  1035. });
  1036. element = element.parentElement;
  1037. if (element && element.parentElement && element.parentElement.tagName != "HTML") {
  1038. isolateParentElements(element.parentElement, element);
  1039. }
  1040. }
  1041. }
  1042. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  1043. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI, options);
  1044. const imports = DomUtil.getImportFunctions(stylesheetContent);
  1045. await Promise.all(imports.map(async cssImport => {
  1046. const match = DomUtil.matchImport(cssImport);
  1047. if (match) {
  1048. let resourceURL = DomUtil.normalizeURL(match.resourceURL);
  1049. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1050. resourceURL = new URL(match.resourceURL, baseURI).href;
  1051. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1052. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, validateTextContentType: true };
  1053. let importedStylesheetContent = await Download.getContent(resourceURL, downloadOptions);
  1054. if (options.compressCSS) {
  1055. importedStylesheetContent = DOM.compressCSS(DomUtil.removeCssComments(importedStylesheetContent));
  1056. }
  1057. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  1058. if (stylesheetContent.includes(cssImport)) {
  1059. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, resourceURL, options);
  1060. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(cssImport), importedStylesheetContent);
  1061. }
  1062. }
  1063. }
  1064. }
  1065. }));
  1066. return stylesheetContent;
  1067. }
  1068. static resolveStylesheetURLs(stylesheetContent, baseURI, options) {
  1069. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  1070. urlFunctions.map(urlFunction => {
  1071. const originalResourceURL = DomUtil.matchURL(urlFunction);
  1072. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1073. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1074. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1075. const resolvedURL = new URL(resourceURL, baseURI).href;
  1076. if (DomUtil.testValidURL(resolvedURL, baseURI, options.url) && resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  1077. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  1078. }
  1079. }
  1080. } else {
  1081. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  1082. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  1083. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  1084. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  1085. }
  1086. }
  1087. }
  1088. });
  1089. return stylesheetContent;
  1090. }
  1091. static async resolveLinkStylesheetURLs(resourceURL, baseURI, options) {
  1092. resourceURL = DomUtil.normalizeURL(resourceURL);
  1093. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  1094. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, charSet: options.charSet };
  1095. let stylesheetContent = await Download.getContent(resourceURL, downloadOptions);
  1096. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  1097. if (options.compressCSS) {
  1098. stylesheetContent = DOM.compressCSS(DomUtil.removeCssComments(stylesheetContent));
  1099. }
  1100. return stylesheetContent;
  1101. }
  1102. }
  1103. static async processStylesheet(cssRules, baseURI, options, cssVariables, batchRequest) {
  1104. const promises = [];
  1105. const removedRules = [];
  1106. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  1107. const ruleData = cssRule.data;
  1108. if (ruleData.block && ruleData.block.children) {
  1109. if (ruleData.type == "Rule") {
  1110. promises.push(this.processStyle(ruleData.block.children.toArray(), baseURI, options, cssVariables, batchRequest));
  1111. } else if (ruleData.type == "Atrule" && ruleData.name == "charset") {
  1112. removedRules.push(cssRule);
  1113. } else if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports")) {
  1114. promises.push(this.processStylesheet(ruleData.block.children.toArray(), baseURI, options, cssVariables, batchRequest));
  1115. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  1116. promises.push(processDeclaration(ruleData));
  1117. }
  1118. }
  1119. }
  1120. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  1121. await Promise.all(promises);
  1122. async function processDeclaration(cssRule) {
  1123. await Promise.all(cssRule.block.children.toArray().map(async declaration => {
  1124. if (declaration.type == "Declaration") {
  1125. let declarationValue = "";
  1126. try {
  1127. declarationValue = cssTree.generate(declaration.value);
  1128. } catch (error) {
  1129. // ignored
  1130. }
  1131. const urlFunctions = DomUtil.getUrlFunctions(declarationValue); // TODO: use OM
  1132. await Promise.all(urlFunctions.map(async urlFunction => {
  1133. const originalResourceURL = DomUtil.matchURL(urlFunction);
  1134. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1135. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1136. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1137. let { content } = await batchRequest.addURL(resourceURL);
  1138. let validResource = content == EMPTY_DATA_URI || content.startsWith(PREFIX_DATA_URI_VND) || content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
  1139. if (!validResource) {
  1140. validResource = await DOM.validFont(urlFunction);
  1141. }
  1142. if (!validResource) {
  1143. content = EMPTY_DATA_URI;
  1144. }
  1145. declaration.value.children.forEach(token => {
  1146. let tokenValue = "";
  1147. try {
  1148. tokenValue = cssTree.generate(token.value);
  1149. } catch (error) {
  1150. // ignored
  1151. }
  1152. if (token.type == "Url" && DOM.removeQuotes(tokenValue) == originalResourceURL) {
  1153. token.value.value = content;
  1154. }
  1155. });
  1156. }
  1157. }
  1158. }));
  1159. }
  1160. }));
  1161. }
  1162. }
  1163. static async processStyle(declarations, baseURI, options, cssVariables, batchRequest) {
  1164. await Promise.all(declarations.map(async declaration => {
  1165. if (declaration.type == "Declaration") {
  1166. const declarationValue = cssTree.generate(declaration.value);
  1167. const urlFunctions = DomUtil.getUrlFunctions(declarationValue);
  1168. await Promise.all(urlFunctions.map(async urlFunction => {
  1169. const originalResourceURL = DomUtil.matchURL(urlFunction);
  1170. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1171. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1172. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1173. let { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  1174. if (duplicate && options.groupDuplicateImages) {
  1175. const tokens = [];
  1176. for (let token = declaration.value.children.head; token; token = token.next) {
  1177. if (token.data.type == "Url") {
  1178. const value = cssTree.parse("var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")", { context: "value" }).children.head;
  1179. tokens.push({ token, value });
  1180. }
  1181. }
  1182. tokens.forEach(({ token, value }) => declaration.value.children.replace(token, value));
  1183. cssVariables.set(indexResource, content);
  1184. } else {
  1185. declaration.value.children.forEach(token => {
  1186. if (token.type == "Url") {
  1187. token.value.value = content;
  1188. }
  1189. });
  1190. }
  1191. }
  1192. }
  1193. }));
  1194. }
  1195. }));
  1196. }
  1197. static async processAttribute(doc, resourceElements, attributeName, prefixDataURI, baseURI, options, cssVariables, styles, batchRequest, processDuplicates, removeElementIfMissing) {
  1198. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1199. let resourceURL = resourceElement.getAttribute(attributeName);
  1200. resourceURL = DomUtil.normalizeURL(resourceURL);
  1201. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1202. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1203. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1204. resourceURL = new URL(resourceURL, baseURI).href;
  1205. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1206. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  1207. if (removeElementIfMissing && content == EMPTY_DATA_URI) {
  1208. resourceElement.remove();
  1209. } else {
  1210. if (content.startsWith(prefixDataURI) || content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) || content.match(PREFIX_DATA_URI_OCTET_STREAM)) {
  1211. const isSVG = content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
  1212. if (processDuplicates && duplicate && options.groupDuplicateImages && !isSVG) {
  1213. if (DomUtil.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
  1214. cssVariables.set(indexResource, content);
  1215. const declarationList = cssTree.parse(resourceElement.getAttribute("style"), { context: "declarationList" });
  1216. styles.set(resourceElement, declarationList);
  1217. } else {
  1218. resourceElement.setAttribute(attributeName, content);
  1219. }
  1220. } else {
  1221. resourceElement.setAttribute(attributeName, content);
  1222. }
  1223. }
  1224. }
  1225. }
  1226. }
  1227. }
  1228. }));
  1229. }
  1230. static async processXLinks(resourceElements, baseURI, options, batchRequest) {
  1231. const attributeName = "xlink:href";
  1232. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1233. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1234. let resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1235. if (DomUtil.testValidPath(resourceURL, baseURI, options.url) && !DomUtil.testIgnoredPath(resourceURL)) {
  1236. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1237. resourceURL = new URL(resourceURL, baseURI).href;
  1238. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1239. try {
  1240. const { content } = await batchRequest.addURL(resourceURL, false);
  1241. const DOMParser = DOM.getParser();
  1242. if (DOMParser) {
  1243. const svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  1244. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1245. if (hashMatch && hashMatch[0]) {
  1246. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1247. if (symbolElement) {
  1248. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1249. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1250. }
  1251. } else {
  1252. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1253. }
  1254. } else {
  1255. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1256. }
  1257. } catch (error) {
  1258. /* ignored */
  1259. }
  1260. }
  1261. } else if (resourceURL == options.url) {
  1262. resourceElement.setAttribute(attributeName, originalResourceURL.substring(resourceURL.length));
  1263. }
  1264. }));
  1265. }
  1266. static async processSrcset(resourceElements, attributeName, prefixDataURI, baseURI, options, batchRequest) {
  1267. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1268. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  1269. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1270. let resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  1271. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1272. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1273. resourceURL = new URL(resourceURL, baseURI).href;
  1274. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1275. const { content } = await batchRequest.addURL(resourceURL);
  1276. if (!content.startsWith(prefixDataURI) && !content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) && !content.match(PREFIX_DATA_URI_OCTET_STREAM)) {
  1277. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1278. }
  1279. return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1280. } else {
  1281. return "";
  1282. }
  1283. } else {
  1284. return "";
  1285. }
  1286. } else {
  1287. return resourceURL + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1288. }
  1289. }));
  1290. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1291. }));
  1292. }
  1293. }
  1294. // -------
  1295. // DomUtil
  1296. // -------
  1297. const DATA_URI_PREFIX = "data:";
  1298. const BLOB_URI_PREFIX = "blob:";
  1299. const HTTP_URI_PREFIX = /^https?:\/\//;
  1300. const FILE_URI_PREFIX = /^file:\/\//;
  1301. const EMPTY_URL = /^https?:\/\/+\s*$/;
  1302. const ABOUT_BLANK_URI = "about:blank";
  1303. const NOT_EMPTY_URL = /^(https?:\/\/|file:\/\/|blob:).+/;
  1304. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1305. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1306. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1307. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1308. 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;
  1309. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1310. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1311. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1312. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1313. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1314. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1315. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1316. class DomUtil {
  1317. static normalizeURL(url) {
  1318. if (!url || url.startsWith(DATA_URI_PREFIX)) {
  1319. return url;
  1320. } else {
  1321. return url.split("#")[0];
  1322. }
  1323. }
  1324. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
  1325. const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
  1326. if (template.match(replaceRegExp)) {
  1327. let value = await valueGetter();
  1328. if (!dontReplaceSlash) {
  1329. value = value.replace(/\/+/g, "_");
  1330. }
  1331. return template.replace(replaceRegExp, value);
  1332. }
  1333. return template;
  1334. }
  1335. static getLastSegment(url) {
  1336. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/), lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1337. if (!lastSegment) {
  1338. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1339. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1340. }
  1341. if (!lastSegment) {
  1342. lastSegmentMatch = lastSegment.match(/(.*)<\.[^.]+$/);
  1343. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1344. }
  1345. if (!lastSegment) {
  1346. lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
  1347. }
  1348. lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1349. return lastSegment;
  1350. }
  1351. static getRegExp(string) {
  1352. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1353. }
  1354. static getUrlFunctions(stylesheetContent) {
  1355. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1356. }
  1357. static getImportFunctions(stylesheetContent) {
  1358. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1359. }
  1360. static matchURL(stylesheetContent) {
  1361. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1362. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1363. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1364. return match && match[1];
  1365. }
  1366. static testIgnoredPath(resourceURL) {
  1367. return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) /*|| resourceURL.startsWith(BLOB_URI_PREFIX)*/ || resourceURL == ABOUT_BLANK_URI);
  1368. }
  1369. static testValidPath(resourceURL, baseURI, docURL) {
  1370. return resourceURL && resourceURL != baseURI && resourceURL != docURL && !resourceURL.match(EMPTY_URL);
  1371. }
  1372. static testValidURL(resourceURL, baseURI, docURL) {
  1373. 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);
  1374. }
  1375. static matchImport(stylesheetContent) {
  1376. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1377. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1378. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1379. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1380. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1381. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1382. if (match) {
  1383. const [, resourceURL, media] = match;
  1384. return { resourceURL, media };
  1385. }
  1386. }
  1387. static removeCssComments(stylesheetContent) {
  1388. let start, end;
  1389. do {
  1390. start = stylesheetContent.indexOf("/*");
  1391. end = stylesheetContent.indexOf("*/", start + 2);
  1392. if (start != -1 && end != -1) {
  1393. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1394. }
  1395. } while (start != -1 && end != -1);
  1396. return stylesheetContent;
  1397. }
  1398. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1399. if (mediaQuery) {
  1400. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1401. } else {
  1402. return stylesheetContent;
  1403. }
  1404. }
  1405. static replaceImageSource(imgElement, variableName, options) {
  1406. const dataAttributeName = DOM.imagesAttributeName(options.sessionId);
  1407. if (imgElement.getAttribute(dataAttributeName) != null) {
  1408. const imgData = options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  1409. if (imgData.replaceable) {
  1410. 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>`);
  1411. const backgroundStyle = {};
  1412. const backgroundSize = (imgData.objectFit == "content" || imgData.objectFit == "cover") && imgData.objectFit;
  1413. if (backgroundSize) {
  1414. backgroundStyle["background-size"] = imgData.objectFit;
  1415. }
  1416. if (imgData.objectPosition) {
  1417. backgroundStyle["background-position"] = imgData.objectPosition;
  1418. }
  1419. if (imgData.backgroundColor) {
  1420. backgroundStyle["background-color"] = imgData.backgroundColor;
  1421. }
  1422. DomProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")", backgroundStyle);
  1423. imgElement.removeAttribute(dataAttributeName);
  1424. return true;
  1425. }
  1426. }
  1427. }
  1428. }
  1429. function log(...args) {
  1430. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1431. }
  1432. // -----
  1433. // Stats
  1434. // -----
  1435. const STATS_DEFAULT_VALUES = {
  1436. discarded: {
  1437. "HTML bytes": 0,
  1438. "hidden elements": 0,
  1439. "HTML imports": 0,
  1440. scripts: 0,
  1441. objects: 0,
  1442. "audio sources": 0,
  1443. "video sources": 0,
  1444. frames: 0,
  1445. "CSS rules": 0,
  1446. canvas: 0,
  1447. stylesheets: 0,
  1448. resources: 0,
  1449. medias: 0
  1450. },
  1451. processed: {
  1452. "HTML bytes": 0,
  1453. "hidden elements": 0,
  1454. "HTML imports": 0,
  1455. scripts: 0,
  1456. objects: 0,
  1457. "audio sources": 0,
  1458. "video sources": 0,
  1459. frames: 0,
  1460. "CSS rules": 0,
  1461. canvas: 0,
  1462. stylesheets: 0,
  1463. resources: 0,
  1464. medias: 0
  1465. }
  1466. };
  1467. class Stats {
  1468. constructor(options) {
  1469. this.options = options;
  1470. if (options.displayStats) {
  1471. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1472. }
  1473. }
  1474. set(type, subType, value) {
  1475. if (this.options.displayStats) {
  1476. this.data[type][subType] = value;
  1477. }
  1478. }
  1479. add(type, subType, value) {
  1480. if (this.options.displayStats) {
  1481. this.data[type][subType] += value;
  1482. }
  1483. }
  1484. addAll(pageData) {
  1485. if (this.options.displayStats) {
  1486. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1487. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1488. }
  1489. }
  1490. }
  1491. return { getClass };
  1492. })();