1
0

single-file-core.js 74 KB

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