single-file-core.js 72 KB

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