single-file-core.js 77 KB

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