single-file-core.js 82 KB

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