| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866 |
- /*
- * Copyright 2010-2019 Gildas Lormeau
- * contact : gildas.lormeau <at> gmail.com
- *
- * This file is part of SingleFile.
- *
- * The code in this file is free software: you can redistribute it and/or
- * modify it under the terms of the GNU Affero General Public License
- * (GNU AGPL) as published by the Free Software Foundation, either version 3
- * of the License, or (at your option) any later version.
- *
- * The code in this file is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
- * General Public License for more details.
- *
- * As additional permission under GNU AGPL version 3 section 7, you may
- * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
- * AGPL normally required by section 4, provided you include this license
- * notice and a URL through which recipients can access the Corresponding
- * Source.
- */
- this.SingleFileCore = this.SingleFileCore || (() => {
- const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
- const DEBUG = false;
- let docUtil, cssTree, sessionId = 0;
- function getClass(...args) {
- [docUtil, cssTree] = args;
- return SingleFileClass;
- }
- class SingleFileClass {
- constructor(options) {
- this.options = options;
- options.insertFaviconLink = true;
- if (options.sessionId === undefined) {
- options.sessionId = sessionId;
- sessionId++;
- }
- }
- async run() {
- this.runner = new Runner(this.options, true);
- await this.runner.loadPage();
- await this.runner.initialize();
- await this.runner.run();
- }
- async getPageData() {
- return this.runner.getPageData();
- }
- }
- SingleFileClass.SELECTED_CONTENT_ATTRIBUTE_NAME = SELECTED_CONTENT_ATTRIBUTE_NAME;
- // -------------
- // ProgressEvent
- // -------------
- const PAGE_LOADING = "page-loading";
- const PAGE_LOADED = "page-loaded";
- const RESOURCES_INITIALIZING = "resource-initializing";
- const RESOURCES_INITIALIZED = "resources-initialized";
- const RESOURCE_LOADED = "resource-loaded";
- const PAGE_ENDED = "page-ended";
- const STAGE_STARTED = "stage-started";
- const STAGE_ENDED = "stage-ended";
- const STAGE_TASK_STARTED = "stage-task-started";
- const STAGE_TASK_ENDED = "stage-task-ended";
- class ProgressEvent {
- constructor(type, detail) {
- 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 };
- }
- }
- // ------
- // Runner
- // ------
- const RESOLVE_URLS_STAGE = 0;
- const REPLACE_DATA_STAGE = 1;
- const REPLACE_DOCS_STAGE = 2;
- const POST_PROCESS_STAGE = 3;
- const STAGES = [{
- sequential: [
- { action: "preProcessPage" },
- { action: "replaceStyleContents" },
- { option: "selected", action: "removeUnselectedElements" },
- { option: "removeVideoSrc", action: "insertVideoPosters" },
- { option: "removeFrames", action: "removeFrames" },
- { option: "removeImports", action: "removeImports" },
- { option: "removeScripts", action: "removeScripts" },
- { option: "removeVideoSrc", action: "removeVideoSources" },
- { option: "removeAudioSrc", action: "removeAudioSources" },
- { action: "removeDiscardedResources" },
- { action: "resetCharsetMeta" },
- { action: "setInputValues" },
- { option: "insertFaviconLink", action: "insertFaviconLink" },
- { action: "replaceCanvasElements" },
- { action: "insertFonts" },
- { option: "removeHiddenElements", action: "removeHiddenElements" },
- { action: "resolveHrefs" },
- { action: "resolveStyleAttributeURLs" }
- ],
- parallel: [
- { action: "resolveStylesheetURLs" },
- { action: "resolveShadowRootURLs" },
- { option: "!removeFrames", action: "resolveFrameURLs" },
- { option: "!removeImports", action: "resolveHtmlImportURLs" }
- ]
- }, {
- sequential: [
- { option: "removeUnusedStyles", action: "removeUnusedStyles" },
- { option: "removeAlternativeMedias", action: "removeAlternativeMedias" },
- { option: "removeUnusedFonts", action: "removeUnusedFonts" }
- ],
- parallel: [
- { action: "processStylesheets" },
- { action: "processStyleAttributes" },
- { action: "processPageResources" },
- { option: "!removeScripts", action: "processScripts" }
- ]
- }, {
- sequential: [
- { option: "removeAlternativeImages", action: "removeAlternativeImages" },
- { option: "removeAlternativeFonts", action: "removeAlternativeFonts" }
- ],
- parallel: [
- { option: "!removeFrames", action: "processFrames" },
- { action: "processShadowRoots" },
- { option: "!removeImports", action: "processHtmlImports" },
- ]
- }, {
- sequential: [
- { action: "replaceStylesheets" },
- { action: "replaceStyleAttributes" },
- { action: "insertVariables" },
- { option: "compressHTML", action: "compressHTML" }
- ]
- }];
- class Runner {
- constructor(options, root) {
- this.root = root;
- this.options = options;
- this.options.url = this.options.url || (this.options.doc && this.options.doc.location.href);
- this.options.baseURI = this.options.doc && this.options.doc.baseURI;
- this.batchRequest = new BatchRequest();
- this.processor = new Processor(options, this.batchRequest);
- if (this.options.doc) {
- const docData = docUtil.preProcessDoc(this.options.doc, this.options.win, this.options);
- this.options.canvasData = docData.canvasData;
- this.options.fontsData = docData.fontsData;
- this.options.stylesheetsData = docData.stylesheetsData;
- this.options.imageData = docData.imageData;
- this.options.postersData = docData.postersData;
- this.options.usedFonts = docData.usedFonts;
- this.options.shadowRootsData = docData.shadowRootsData;
- this.options.referrer = docData.referrer;
- }
- if (this.options.saveRawPage) {
- this.options.removeFrames = true;
- }
- this.options.content = this.options.content || (this.options.doc ? docUtil.serialize(this.options.doc, false) : null);
- this.onprogress = options.onprogress || (() => { });
- }
- async loadPage() {
- this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url, frame: !this.root }));
- await this.processor.loadPage(this.options.content);
- this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url, frame: !this.root }));
- }
- async initialize() {
- this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
- await this.executeStage(RESOLVE_URLS_STAGE);
- this.pendingPromises = this.executeStage(REPLACE_DATA_STAGE);
- if (this.options.doc) {
- docUtil.postProcessDoc(this.options.doc, this.options);
- }
- this.options.doc = null;
- this.options.win = null;
- }
- async run() {
- if (this.root) {
- this.processor.initialize(this.batchRequest);
- this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: this.processor.maxResources }));
- }
- await this.batchRequest.run(detail => {
- detail.pageURL = this.options.url;
- this.onprogress(new ProgressEvent(RESOURCE_LOADED, detail));
- }, this.options);
- await this.pendingPromises;
- await this.executeStage(REPLACE_DOCS_STAGE);
- await this.executeStage(POST_PROCESS_STAGE);
- await this.processor.finalize();
- }
- getDocument() {
- return this.processor.doc;
- }
- async getPageData() {
- if (this.root) {
- this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
- }
- return this.processor.getPageData();
- }
- async executeStage(step) {
- if (DEBUG) {
- log("**** STARTED STAGE", step, "****");
- }
- const frame = !this.root;
- this.onprogress(new ProgressEvent(STAGE_STARTED, { pageURL: this.options.url, step, frame }));
- STAGES[step].sequential.forEach(task => {
- let startTime;
- if (DEBUG) {
- startTime = Date.now();
- log(" -- STARTED task =", task.action);
- }
- this.onprogress(new ProgressEvent(STAGE_TASK_STARTED, { pageURL: this.options.url, step, task: task.action, frame }));
- this.executeTask(task);
- this.onprogress(new ProgressEvent(STAGE_TASK_ENDED, { pageURL: this.options.url, step, task: task.action, frame }));
- if (DEBUG) {
- log(" -- ENDED task =", task.action, "delay =", Date.now() - startTime);
- }
- });
- let parallelTasksPromise;
- if (STAGES[step].parallel) {
- parallelTasksPromise = await Promise.all(STAGES[step].parallel.map(async task => {
- let startTime;
- if (DEBUG) {
- startTime = Date.now();
- log(" // STARTED task =", task.action);
- }
- this.onprogress(new ProgressEvent(STAGE_TASK_STARTED, { pageURL: this.options.url, step, task: task.action, frame }));
- await this.executeTask(task);
- this.onprogress(new ProgressEvent(STAGE_TASK_ENDED, { pageURL: this.options.url, step, task: task.action, frame }));
- if (DEBUG) {
- log(" // ENDED task =", task.action, "delay =", Date.now() - startTime);
- }
- }));
- } else {
- parallelTasksPromise = Promise.resolve();
- }
- this.onprogress(new ProgressEvent(STAGE_ENDED, { pageURL: this.options.url, step, frame }));
- if (DEBUG) {
- log("**** ENDED STAGE", step, "****");
- }
- return parallelTasksPromise;
- }
- executeTask(task) {
- if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
- return this.processor[task.action]();
- }
- }
- }
- // ------------
- // BatchRequest
- // ------------
- class BatchRequest {
- constructor() {
- this.requests = new Map();
- this.duplicates = new Map();
- }
- async addURL(resourceURL, asDataURI, groupDuplicates) {
- return new Promise((resolve, reject) => {
- const requestKey = JSON.stringify([resourceURL, asDataURI]);
- let resourceRequests = this.requests.get(requestKey);
- if (!resourceRequests) {
- resourceRequests = [];
- this.requests.set(requestKey, resourceRequests);
- }
- const callbacks = { resolve, reject };
- resourceRequests.push(callbacks);
- if (groupDuplicates) {
- let duplicateRequests = this.duplicates.get(requestKey);
- if (!duplicateRequests) {
- duplicateRequests = [];
- this.duplicates.set(requestKey, duplicateRequests);
- }
- duplicateRequests.push(callbacks);
- }
- });
- }
- getMaxResources() {
- return this.requests.size;
- }
- async run(onloadListener, options) {
- const resourceURLs = Array.from(this.requests.keys());
- let indexResource = 0;
- return Promise.all(resourceURLs.map(async requestKey => {
- const [resourceURL, asDataURI] = JSON.parse(requestKey);
- const resourceRequests = this.requests.get(requestKey);
- this.requests.delete(requestKey);
- try {
- const content = await docUtil.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
- indexResource = indexResource + 1;
- onloadListener({ index: indexResource, url: resourceURL });
- resourceRequests.forEach(callbacks => {
- const duplicateCallbacks = this.duplicates.get(requestKey);
- const duplicate = duplicateCallbacks && duplicateCallbacks.length > 1 && duplicateCallbacks.includes(callbacks);
- callbacks.resolve({ content: content.data, indexResource, duplicate });
- });
- } catch (error) {
- indexResource = indexResource + 1;
- onloadListener({ index: indexResource, url: resourceURL });
- resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
- }
- }));
- }
- }
- // ---------
- // Processor
- // ---------
- const PREFIXES_FORBIDDEN_DATA_URI = ["data:text/"];
- const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
- const EMPTY_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
- const SCRIPT_TAG_FOUND = /<script/gi;
- const NOSCRIPT_TAG_FOUND = /<noscript/gi;
- const WC_ATTRIBUTE_NAME = "data-single-file-web-component";
- class Processor {
- constructor(options, batchRequest) {
- this.options = options;
- this.stats = new Stats(options);
- this.baseURI = Util.normalizeURL(options.baseURI || options.url);
- this.batchRequest = batchRequest;
- this.stylesheets = new Map();
- this.styles = new Map();
- this.cssVariables = new Map();
- }
- initialize() {
- this.options.saveDate = new Date();
- this.options.saveUrl = this.options.url;
- if (this.options.enableMaff) {
- this.maffMetaDataPromise = this.batchRequest.addURL(docUtil.resolveURL("index.rdf", this.options.baseURI || this.options.url), false);
- }
- this.maxResources = this.batchRequest.getMaxResources();
- if (!this.options.saveRawPage && !this.options.removeFrames && this.options.framesData) {
- this.options.framesData.forEach(frameData => this.maxResources += frameData.maxResources || 0);
- }
- if (this.options.shadowRootsData) {
- this.options.shadowRootsData.forEach(shadowRootData => this.maxResources += shadowRootData.maxResources || 0);
- }
- this.stats.set("processed", "resources", this.maxResources);
- }
- async loadPage(pageContent, charset) {
- let content;
- if (!pageContent || this.options.saveRawPage) {
- content = await docUtil.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, charset });
- pageContent = content.data;
- }
- this.doc = docUtil.parseDocContent(pageContent, this.baseURI);
- if (this.options.saveRawPage) {
- let charset;
- this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
- const charsetDeclaration = element.content.split(";")[1];
- if (charsetDeclaration && !charset) {
- charset = charsetDeclaration.split("=")[1].trim().toLowerCase();
- }
- });
- if (charset && charset != content.charset) {
- return this.loadPage(pageContent, charset);
- }
- }
- this.workStyleElement = this.doc.createElement("style");
- this.doc.body.appendChild(this.workStyleElement);
- this.onEventAttributeNames = Util.getOnEventAttributeNames(this.doc);
- }
- async finalize() {
- if (this.workStyleElement.parentNode) {
- this.workStyleElement.remove();
- }
- const metaCharset = this.doc.head.querySelector("meta[charset]");
- if (metaCharset) {
- this.doc.head.insertBefore(metaCharset, this.doc.head.firstChild);
- }
- this.doc.querySelectorAll("base").forEach(element => element.remove());
- if (this.doc.head.querySelectorAll("*").length == 1 && metaCharset && this.doc.body.childNodes.length == 0) {
- this.doc.head.querySelector("meta[charset]").remove();
- }
- if (this.maffMetaDataPromise) {
- const maffMetaData = await this.maffMetaDataPromise;
- if (maffMetaData && maffMetaData.content) {
- const NAMESPACE_RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
- const maffDoc = docUtil.parseXMLContent(maffMetaData.content);
- const originalURLElement = maffDoc.querySelector("RDF > Description > originalurl");
- const archiveTimeElement = maffDoc.querySelector("RDF > Description > archivetime");
- if (originalURLElement) {
- this.options.saveUrl = originalURLElement.getAttributeNS(NAMESPACE_RDF, "resource");
- }
- if (archiveTimeElement) {
- const value = archiveTimeElement.getAttributeNS(NAMESPACE_RDF, "resource");
- if (value) {
- const date = new Date(value);
- if (!isNaN(date.getTime())) {
- this.options.saveDate = new Date(value);
- }
- }
- }
- }
- }
- const titleElement = this.doc.querySelector("title");
- const descriptionElement = this.doc.querySelector("meta[name=description]");
- const authorElement = this.doc.querySelector("meta[name=author]");
- const creatorElement = this.doc.querySelector("meta[name=creator]");
- const publisherElement = this.doc.querySelector("meta[name=publisher]");
- this.options.title = titleElement ? titleElement.textContent.trim() : "";
- this.options.infobarContent = await ProcessorHelper.evalTemplate(this.options.infobarTemplate, this.options, null, true);
- this.options.info = {
- description: descriptionElement && descriptionElement.content ? descriptionElement.content.trim() : "",
- lang: this.doc.documentElement.lang,
- author: authorElement && authorElement.content ? authorElement.content.trim() : "",
- creator: creatorElement && creatorElement.content ? creatorElement.content.trim() : "",
- publisher: publisherElement && publisherElement.content ? publisherElement.content.trim() : ""
- };
- }
- async getPageData() {
- docUtil.postProcessDoc(this.doc, this.options);
- const url = docUtil.parseURL(this.baseURI);
- if (this.options.insertSingleFileComment) {
- const infobarContent = (this.options.infobarContent || "").replace(/\\n/g, "\n").replace(/\\t/g, "\t");
- const commentNode = this.doc.createComment("\n Page saved with SingleFile" +
- " \n url: " + this.options.saveUrl +
- " \n saved date: " + this.options.saveDate +
- (infobarContent ? " \n info: " + infobarContent : "") + "\n");
- this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
- }
- let size;
- if (this.options.displayStats) {
- size = docUtil.getContentSize(this.doc.documentElement.outerHTML);
- }
- const content = docUtil.serialize(this.doc, this.options.compressHTML);
- if (this.options.displayStats) {
- const contentSize = docUtil.getContentSize(content);
- this.stats.set("processed", "HTML bytes", contentSize);
- this.stats.add("discarded", "HTML bytes", size - contentSize);
- }
- let filename = await ProcessorHelper.evalTemplate(this.options.filenameTemplate, this.options, content) || "";
- filename = filename.replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, "_"); // eslint-disable-line no-control-regex
- filename = filename.replace(/\.\.\//g, "").replace(/^\/+/, "").replace(/\/+/g, "/").replace(/\/$/, "").replace(/\.$/, "").replace(/\.\//g, "._").replace(/\/\./g, "/_");
- if (!this.options.backgroundSave) {
- filename = filename.replace(/\//g, "_");
- }
- if (docUtil.getContentSize(filename) > 192) {
- const extensionMatch = filename.match(/(\.[^.]{3,4})$/);
- const extension = extensionMatch && extensionMatch[0] && extensionMatch[0].length > 1 ? extensionMatch[0] : "";
- filename = await docUtil.truncateContent(filename, 192 - extension.length);
- filename = filename + "…" + extension;
- }
- if (!filename) {
- filename = "Unnamed page";
- }
- const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
- return {
- stats: this.stats.data,
- title: this.options.title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "")),
- filename,
- content
- };
- }
- preProcessPage() {
- if (this.options.win) {
- 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));
- }
- if (this.options.imageData && !this.options.saveRawPage) {
- const dataAttributeName = docUtil.IMAGE_ATTRIBUTE_NAME;
- this.doc.querySelectorAll("img").forEach(imgElement => {
- const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
- if (this.options.removeHiddenElements && imgData.size && !imgData.size.pxWidth && !imgData.size.pxHeight) {
- imgElement.setAttribute("src", EMPTY_IMAGE);
- } else if (imgData.currentSrc) {
- imgElement.setAttribute("src", imgData.currentSrc);
- }
- });
- if (this.options.loadDeferredImages) {
- this.doc.querySelectorAll("img[data-src]").forEach(imgElement => {
- const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
- if ((!imgElement.getAttribute("src") || imgElement.getAttribute("src") == EMPTY_IMAGE) && imgElement.getAttribute("data-src")) {
- imgData.src = imgElement.dataset.src;
- imgElement.setAttribute("src", imgElement.dataset.src);
- imgElement.removeAttribute("data-src");
- }
- });
- this.doc.querySelectorAll("img[data-srcset]").forEach(imgElement => {
- if (!imgElement.getAttribute("srcset") && imgElement.getAttribute("data-srcset")) {
- imgElement.setAttribute("srcset", imgElement.dataset.srcset);
- imgElement.removeAttribute("data-srcset");
- }
- });
- }
- }
- }
- replaceStyleContents() {
- if (this.options.stylesheetsData) {
- this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
- if (this.options.stylesheetsData[styleIndex]) {
- styleElement.textContent = this.options.stylesheetsData[styleIndex];
- }
- });
- }
- }
- removeUnselectedElements() {
- removeUnmarkedElements(this.doc.body);
- this.doc.body.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
- function removeUnmarkedElements(element) {
- let selectedElementFound = false;
- Array.from(element.childNodes).forEach(node => {
- if (node.nodeType == 1) {
- const isSelectedElement = node.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "";
- selectedElementFound = selectedElementFound || isSelectedElement;
- if (isSelectedElement) {
- node.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
- removeUnmarkedElements(node);
- } else if (selectedElementFound) {
- removeNode(node);
- } else {
- if (canHideNode(node)) {
- node.style.setProperty("display", "none", "important");
- Array.from(node.childNodes).forEach(removeNode);
- }
- }
- }
- });
- }
- function removeNode(node) {
- if (canHideNode(node)) {
- node.remove();
- }
- }
- function canHideNode(node) {
- if (node.nodeType == 1) {
- const tagName = node.tagName && node.tagName.toLowerCase();
- return (tagName != "svg" && tagName != "style" && tagName != "link");
- }
- }
- }
- insertVideoPosters() {
- if (this.options.postersData) {
- this.doc.querySelectorAll("video[src], video > source[src]").forEach((element, videoIndex) => {
- let videoElement;
- if (element.tagName == "VIDEO") {
- videoElement = element;
- } else {
- videoElement = element.parentElement;
- }
- if (!videoElement.poster && this.options.postersData[videoIndex]) {
- videoElement.setAttribute("poster", this.options.postersData[videoIndex]);
- }
- });
- }
- }
- removeFrames() {
- const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
- this.stats.set("discarded", "frames", frameElements.length);
- this.stats.set("processed", "frames", frameElements.length);
- this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
- }
- removeImports() {
- const importElements = this.doc.querySelectorAll("link[rel=import]");
- this.stats.set("discarded", "HTML imports", importElements.length);
- this.stats.set("processed", "HTML imports", importElements.length);
- importElements.forEach(element => element.remove());
- }
- removeScripts() {
- this.onEventAttributeNames.forEach(attributeName => this.doc.querySelectorAll("[" + attributeName + "]").forEach(element => element.removeAttribute(attributeName)));
- this.doc.querySelectorAll("[href]").forEach(element => {
- if (element.href && element.href.match && element.href.match(/^\s*javascript:/)) {
- element.setAttribute("href", "");
- }
- });
- this.doc.querySelectorAll("[src]").forEach(element => {
- if (element.src && element.src.match(/^\s*javascript:/)) {
- element.removeAttribute("src");
- }
- });
- const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
- this.stats.set("discarded", "scripts", scriptElements.length);
- this.stats.set("processed", "scripts", scriptElements.length);
- scriptElements.forEach(element => element.remove());
- }
- removeVideoSources() {
- const videoSourceElements = this.doc.querySelectorAll("video[src], video > source");
- this.stats.set("discarded", "video sources", videoSourceElements.length);
- this.stats.set("processed", "video sources", videoSourceElements.length);
- videoSourceElements.forEach(element => {
- if (element.tagName == "SOURCE") {
- element.remove();
- } else {
- videoSourceElements.forEach(element => element.removeAttribute("src"));
- }
- });
- }
- removeAudioSources() {
- const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
- this.stats.set("discarded", "audio sources", audioSourceElements.length);
- this.stats.set("processed", "audio sources", audioSourceElements.length);
- audioSourceElements.forEach(element => {
- if (element.tagName == "SOURCE") {
- element.remove();
- } else {
- audioSourceElements.forEach(element => element.removeAttribute("src"));
- }
- });
- }
- removeDiscardedResources() {
- this.doc.querySelectorAll("singlefile-infobar, singlefile-mask, singlefile-logs-window").forEach(element => element.remove());
- const objectElements = this.doc.querySelectorAll("applet, meta[http-equiv=refresh], meta[disabled-http-equiv], object[data]:not([type=\"image/svg+xml\"]):not([type=\"image/svg-xml\"]):not([type=\"text/html\"]), embed[src]:not([src*=\".svg\"]):not([src*=\".pdf\"])");
- this.stats.set("discarded", "objects", objectElements.length);
- this.stats.set("processed", "objects", objectElements.length);
- objectElements.forEach(element => element.remove());
- const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
- replacedAttributeValue.forEach(element => {
- const relValue = element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "").trim();
- if (relValue.length) {
- element.setAttribute("rel", relValue);
- } else {
- element.remove();
- }
- });
- this.doc.querySelectorAll("link[rel*=stylesheet][rel*=alternate][title]").forEach(element => element.remove());
- this.doc.querySelectorAll("meta[http-equiv=\"content-security-policy\"]").forEach(element => element.remove());
- if (this.options.compressHTML) {
- this.doc.querySelectorAll("input[type=hidden]").forEach(element => element.remove());
- }
- this.doc.querySelectorAll("a[ping]").forEach(element => element.removeAttribute("ping"));
- }
- resetCharsetMeta() {
- let charset;
- this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
- const charsetDeclaration = element.content.split(";")[1];
- if (charsetDeclaration && !charset) {
- charset = charsetDeclaration.split("=")[1];
- if (charset) {
- this.charset = charset.trim().toLowerCase();
- }
- }
- element.remove();
- });
- const metaElement = this.doc.createElement("meta");
- metaElement.setAttribute("charset", "utf-8");
- if (this.doc.head.firstChild) {
- this.doc.head.insertBefore(metaElement, this.doc.head.firstChild);
- } else {
- this.doc.head.appendChild(metaElement);
- }
- }
- setInputValues() {
- this.doc.querySelectorAll("input").forEach(input => {
- const value = input.getAttribute(docUtil.INPUT_VALUE_ATTRIBUTE_NAME);
- input.setAttribute("value", value || "");
- });
- this.doc.querySelectorAll("input[type=radio], input[type=checkbox]").forEach(input => {
- const value = input.getAttribute(docUtil.INPUT_VALUE_ATTRIBUTE_NAME);
- if (value == "true") {
- input.setAttribute("checked", "");
- }
- });
- this.doc.querySelectorAll("textarea").forEach(textarea => {
- const value = textarea.getAttribute(docUtil.INPUT_VALUE_ATTRIBUTE_NAME);
- textarea.textContent = value || "";
- });
- this.doc.querySelectorAll("select").forEach(select => {
- select.querySelectorAll("option").forEach(option => {
- const selected = option.getAttribute(docUtil.INPUT_VALUE_ATTRIBUTE_NAME) != null;
- if (selected) {
- option.setAttribute("selected", "");
- }
- });
- });
- }
- insertFaviconLink() {
- let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
- if (!faviconElement) {
- faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
- }
- if (!faviconElement) {
- faviconElement = this.doc.createElement("link");
- faviconElement.setAttribute("type", "image/x-icon");
- faviconElement.setAttribute("rel", "shortcut icon");
- faviconElement.setAttribute("href", "/favicon.ico");
- }
- this.doc.head.appendChild(faviconElement);
- }
- replaceCanvasElements() {
- if (this.options.canvasData) {
- this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
- const canvasData = this.options.canvasData[indexCanvasElement];
- if (canvasData) {
- ProcessorHelper.setBackgroundImage(canvasElement, "url(" + canvasData.dataURI + ")");
- this.stats.add("processed", "canvas", 1);
- }
- });
- }
- }
- insertFonts() {
- if (this.options.fontsData && this.options.fontsData.length) {
- let stylesheetContent = "";
- this.options.fontsData.forEach(fontStyles => {
- if (fontStyles["font-family"] && fontStyles.src) {
- stylesheetContent += "@font-face{";
- let stylesContent = "";
- Object.keys(fontStyles).forEach(fontStyle => {
- if (stylesContent) {
- stylesContent += ";";
- }
- stylesContent += fontStyle + ":" + fontStyles[fontStyle];
- });
- stylesheetContent += stylesContent + "}";
- }
- });
- if (stylesheetContent) {
- const styleElement = this.doc.createElement("style");
- styleElement.textContent = stylesheetContent;
- const existingStyleElement = this.doc.querySelector("style");
- if (existingStyleElement) {
- existingStyleElement.parentElement.insertBefore(styleElement, existingStyleElement);
- } else {
- this.doc.head.insertBefore(styleElement, this.doc.head.firstChild);
- }
- }
- }
- }
- removeHiddenElements() {
- const hiddenElements = this.doc.querySelectorAll("[" + docUtil.REMOVED_CONTENT_ATTRIBUTE_NAME + "]");
- this.stats.set("discarded", "hidden elements", hiddenElements.length);
- this.stats.set("processed", "hidden elements", hiddenElements.length);
- hiddenElements.forEach(element => element.remove());
- }
- resolveHrefs() {
- this.doc.querySelectorAll("a[href], area[href], link[href]").forEach(element => {
- const href = element.getAttribute("href").trim();
- if (!Util.testIgnoredPath(href)) {
- let resolvedURL;
- try {
- resolvedURL = docUtil.resolveURL(href, this.options.baseURI || this.options.url);
- } catch (error) {
- // ignored
- }
- if (resolvedURL) {
- if (resolvedURL.startsWith(this.options.url + "#")) {
- resolvedURL = resolvedURL.substring(this.options.url.length);
- }
- try {
- element.setAttribute("href", resolvedURL);
- } catch (error) {
- // ignored
- }
- }
- }
- });
- }
- resolveStyleAttributeURLs() {
- this.doc.querySelectorAll("[style]").forEach(element => {
- let styleContent = element.getAttribute("style");
- if (this.options.compressCSS) {
- styleContent = docUtil.compressCSS(styleContent);
- }
- styleContent = ProcessorHelper.resolveStylesheetURLs(styleContent, this.baseURI);
- const declarationList = cssTree.parse(styleContent, { context: "declarationList" });
- this.styles.set(element, declarationList);
- });
- }
- async resolveStylesheetURLs() {
- await Promise.all(Array.from(this.doc.querySelectorAll("style, link[rel*=stylesheet]"))
- .map(async element => {
- let mediaText;
- if (element.media) {
- mediaText = element.media.toLowerCase();
- }
- this.stylesheets.set(element, { mediaText });
- const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, url: this.options.url, charset: this.charset, compressCSS: this.options.compressCSS };
- let stylesheetContent;
- if (element.tagName.toLowerCase() == "link") {
- if (element.charset) {
- options.charset = element.charset;
- }
- stylesheetContent = await ProcessorHelper.resolveLinkStylesheetURLs(element.href, this.baseURI, options, this.workStyleElement);
- } else {
- stylesheetContent = await ProcessorHelper.resolveImportURLs(element.textContent, this.baseURI, options, this.workStyleElement);
- }
- let stylesheet;
- try {
- stylesheet = cssTree.parse(Util.removeCssComments(stylesheetContent));
- } catch (error) {
- // ignored
- }
- if (stylesheet && stylesheet.children) {
- if (this.options.compressCSS) {
- ProcessorHelper.removeSingleLineCssComments(stylesheet);
- }
- this.stylesheets.get(element).stylesheet = stylesheet;
- } else {
- this.stylesheets.delete(element);
- }
- }));
- }
- async resolveFrameURLs() {
- if (!this.options.saveRawPage && this.options.framesData) {
- const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
- await Promise.all(frameElements.map(async frameElement => {
- if (frameElement.tagName == "OBJECT") {
- frameElement.setAttribute("data", "data:text/html,");
- } else {
- frameElement.removeAttribute("src");
- frameElement.removeAttribute("srcdoc");
- }
- const frameWindowId = frameElement.getAttribute(docUtil.WIN_ID_ATTRIBUTE_NAME);
- if (frameWindowId) {
- const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
- if (frameData) {
- await initializeProcessor(frameData, frameElement, frameWindowId, this.batchRequest, Object.create(this.options));
- }
- }
- }));
- }
- async function initializeProcessor(frameData, frameElement, frameWindowId, batchRequest, options) {
- options.insertSingleFileComment = false;
- options.insertFaviconLink = false;
- options.doc = null;
- options.win = null;
- options.url = frameData.baseURI;
- options.windowId = frameWindowId;
- if (frameData.content) {
- options.content = frameData.content;
- options.postersData = frameData.postersData;
- options.canvasData = frameData.canvasData;
- options.stylesheetsData = frameData.stylesheetsData;
- options.fontsData = frameData.fontsData;
- options.imageData = frameData.imageData;
- options.usedFonts = frameData.usedFonts;
- options.shadowRootsData = frameData.shadowRootsData;
- frameData.processor = new Runner(options);
- frameData.frameElement = frameElement;
- await frameData.processor.loadPage();
- await frameData.processor.initialize();
- frameData.maxResources = batchRequest.getMaxResources();
- }
- }
- }
- async resolveShadowRootURLs() {
- const rootOptions = this.options;
- const batchRequest = this.batchRequest;
- if (this.options.shadowRootsData && this.options.shadowRootsData.length) {
- await resolveURLs(this.doc);
- }
- async function resolveURLs(rootElement) {
- const shadowRootElements = Array.from((rootElement.querySelectorAll("[" + docUtil.SHADOW_ROOT_ATTRIBUTE_NAME + "]")));
- await Promise.all(shadowRootElements.map(async element => {
- const id = element.getAttribute(docUtil.SHADOW_ROOT_ATTRIBUTE_NAME);
- const shadowRootData = rootOptions.shadowRootsData[Number(id)];
- const options = Object.create(rootOptions);
- options.insertSingleFileComment = false;
- options.insertFaviconLink = false;
- options.doc = null;
- options.win = null;
- options.url = options.baseURI = rootOptions.url;
- if (shadowRootData.content) {
- const doc = docUtil.parseDocContent(shadowRootData.content);
- const docData = docUtil.preProcessDoc(doc, options.win, options);
- options.content = docUtil.serialize(doc);
- docUtil.postProcessDoc(doc, options);
- options.postersData = docData.postersData;
- options.canvasData = docData.canvasData;
- options.stylesheetsData = docData.stylesheetsData;
- options.fontsData = docData.fontsData;
- options.imageData = docData.imageData;
- options.usedFonts = docData.usedFonts;
- options.shadowRootsData = docData.shadowRootsData;
- shadowRootData.processor = new Runner(options);
- shadowRootData.element = element;
- await shadowRootData.processor.loadPage();
- await shadowRootData.processor.initialize();
- shadowRootData.maxResources = batchRequest.getMaxResources();
- await resolveURLs(shadowRootData.processor.getDocument());
- }
- }));
- }
- }
- async resolveHtmlImportURLs() {
- const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
- if (!this.relImportProcessors) {
- this.relImportProcessors = new Map();
- }
- await Promise.all(linkElements.map(async linkElement => {
- const resourceURL = linkElement.href;
- linkElement.removeAttribute("href");
- const options = Object.create(this.options);
- options.insertSingleFileComment = false;
- options.insertFaviconLink = false;
- options.doc = null;
- options.win = null;
- options.url = resourceURL;
- if (!Util.testIgnoredPath(resourceURL) && Util.testValidPath(resourceURL)) {
- const processor = new Runner(options);
- this.relImportProcessors.set(linkElement, processor);
- await processor.loadPage();
- return processor.initialize();
- }
- }));
- }
- removeUnusedStyles() {
- if (!this.mediaAllInfo) {
- this.mediaAllInfo = docUtil.getMediaAllInfo(this.doc, this.stylesheets, this.styles);
- }
- const stats = docUtil.minifyCSSRules(this.stylesheets, this.styles, this.mediaAllInfo);
- this.stats.set("processed", "CSS rules", stats.processed);
- this.stats.set("discarded", "CSS rules", stats.discarded);
- }
- removeUnusedFonts() {
- docUtil.removeUnusedFonts(this.doc, this.stylesheets, this.styles, this.options);
- }
- removeAlternativeMedias() {
- const stats = docUtil.minifyMedias(this.stylesheets);
- this.stats.set("processed", "medias", stats.processed);
- this.stats.set("discarded", "medias", stats.discarded);
- }
- async processStylesheets() {
- await Promise.all(Array.from(this.stylesheets).map(([, stylesheetInfo]) =>
- ProcessorHelper.processStylesheet(stylesheetInfo.stylesheet.children, this.baseURI, this.options, this.cssVariables, this.batchRequest)
- ));
- }
- async processStyleAttributes() {
- return Promise.all(Array.from(this.styles).map(([, declarationList]) =>
- ProcessorHelper.processStyle(declarationList.children.toArray(), this.baseURI, this.options, this.cssVariables, this.batchRequest)
- ));
- }
- async processPageResources() {
- const processAttributeArgs = [
- ["link[href][rel*=\"icon\"]", "href", false, true],
- ["object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]", "data"],
- ["img[src], input[src][type=image]", "src", true],
- ["embed[src*=\".svg\"], embed[src*=\".pdf\"]", "src"],
- ["video[poster]", "poster"],
- ["*[background]", "background"],
- ["image", "xlink:href"]
- ];
- let resourcePromises = processAttributeArgs.map(([selector, attributeName, processDuplicates, removeElementIfMissing]) =>
- ProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), attributeName, this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest, processDuplicates, removeElementIfMissing)
- );
- resourcePromises = resourcePromises.concat([
- ProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.options, this.batchRequest),
- ProcessorHelper.processSrcset(this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", this.baseURI, this.batchRequest)
- ]);
- if (!this.options.removeAudioSrc) {
- resourcePromises.push(ProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest));
- }
- if (!this.options.removeVideoSrc) {
- resourcePromises.push(ProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest));
- }
- await Promise.all(resourcePromises);
- ProcessorHelper.processShortcutIcons(this.doc);
- }
- async processScripts() {
- await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
- let resourceURL;
- const scriptSrc = scriptElement.getAttribute("src");
- scriptElement.removeAttribute("src");
- scriptElement.textContent = "";
- try {
- resourceURL = docUtil.resolveURL(scriptSrc, this.baseURI);
- } catch (error) {
- // ignored
- }
- if (Util.testValidURL(resourceURL)) {
- this.stats.add("processed", "scripts", 1);
- const content = await docUtil.getContent(resourceURL, { asDataURI: true, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
- scriptElement.setAttribute("src", content.data);
- }
- }));
- }
- removeAlternativeImages() {
- docUtil.removeAlternativeImages(this.doc);
- }
- removeAlternativeFonts() {
- docUtil.removeAlternativeFonts(this.doc, this.stylesheets);
- }
- async processFrames() {
- if (this.options.framesData) {
- const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
- await Promise.all(frameElements.map(async frameElement => {
- const frameWindowId = frameElement.getAttribute(docUtil.WIN_ID_ATTRIBUTE_NAME);
- if (frameWindowId) {
- const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
- if (frameData) {
- this.options.framesData = this.options.framesData.filter(frame => frame.windowId != frameWindowId);
- if (frameData.processor) {
- this.stats.add("processed", "frames", 1);
- await frameData.processor.run();
- const pageData = await frameData.processor.getPageData();
- frameElement.removeAttribute(docUtil.WIN_ID_ATTRIBUTE_NAME);
- let sandbox = "allow-popups allow-top-navigation allow-top-navigation-by-user-activation";
- if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND)) {
- sandbox += " allow-scripts allow-same-origin";
- }
- frameElement.setAttribute("sandbox", sandbox);
- if (frameElement.tagName == "OBJECT") {
- frameElement.setAttribute("data", "data:text/html," + pageData.content);
- } else {
- if (frameElement.tagName == "FRAME") {
- frameElement.setAttribute("src", "data:text/html," + pageData.content.replace(/#/g, "%23"));
- } else {
- frameElement.setAttribute("srcdoc", pageData.content);
- frameElement.removeAttribute("src");
- }
- }
- this.stats.addAll(pageData);
- } else {
- this.stats.add("discarded", "frames", 1);
- }
- }
- }
- }));
- }
- }
- async processShadowRoots() {
- const rootDoc = this.doc;
- const options = this.options;
- const stats = this.stats;
- if (this.options.shadowRootsData && this.options.shadowRootsData.length) {
- await processRootElement(this.doc);
- const scriptElement = rootDoc.createElement("script");
- scriptElement.textContent = `(()=>{processNode(document);function processNode(node){node.querySelectorAll("[${WC_ATTRIBUTE_NAME}]").forEach(element=>{const shadowRoot=element.parentElement.attachShadow({mode:"open"});shadowRoot.innerHTML=element.innerHTML;element.remove();processNode(shadowRoot)})}})()`;
- this.doc.body.appendChild(scriptElement);
- }
- async function processRootElement(rootElement) {
- const shadowRootElements = Array.from(rootElement.querySelectorAll("[" + docUtil.SHADOW_ROOT_ATTRIBUTE_NAME + "]"));
- await Promise.all(shadowRootElements.map(async element => {
- const id = element.getAttribute(docUtil.SHADOW_ROOT_ATTRIBUTE_NAME);
- if (id) {
- const shadowRootData = options.shadowRootsData[Number(id)];
- if (shadowRootData) {
- options.shadowRootsData = options.shadowRootsData.filter(shadowRootData => shadowRootData.id != id);
- if (shadowRootData.processor) {
- stats.add("processed", "shadow root elements", 1);
- await shadowRootData.processor.run();
- const doc = shadowRootData.processor.getDocument();
- const templateElement = rootDoc.createElement("template");
- templateElement.setAttribute(WC_ATTRIBUTE_NAME, "");
- if (doc.head) {
- const metaCharset = doc.head.querySelector("meta[charset]");
- if (metaCharset) {
- metaCharset.remove();
- }
- doc.head.childNodes.forEach(node => templateElement.appendChild(doc.importNode(node, true)));
- }
- if (doc.body) {
- doc.body.childNodes.forEach(node => templateElement.appendChild(doc.importNode(node, true)));
- }
- await processRootElement(templateElement);
- if (element.firstChild) {
- element.insertBefore(templateElement, element.firstChild);
- } else {
- element.appendChild(templateElement);
- }
- } else {
- stats.add("discarded", "shadow root elements", 1);
- }
- }
- }
- }));
- }
- }
- async processHtmlImports() {
- const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
- await Promise.all(linkElements.map(async linkElement => {
- const processor = this.relImportProcessors.get(linkElement);
- if (processor) {
- this.stats.add("processed", "HTML imports", 1);
- this.relImportProcessors.delete(linkElement);
- const pageData = await processor.getPageData();
- linkElement.setAttribute("href", "data:text/html," + pageData.content);
- this.stats.addAll(pageData);
- } else {
- this.stats.add("discarded", "HTML imports", 1);
- }
- }));
- }
- replaceStylesheets() {
- this.doc.querySelectorAll("style").forEach(styleElement => {
- const stylesheetInfo = this.stylesheets.get(styleElement);
- if (stylesheetInfo) {
- this.stylesheets.delete(styleElement);
- let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
- styleElement.textContent = stylesheetContent;
- if (stylesheetInfo.mediaText) {
- styleElement.media = stylesheetInfo.mediaText;
- }
- } else if (!styleElement.closest("[" + WC_ATTRIBUTE_NAME + "]")) {
- styleElement.remove();
- }
- });
- this.doc.querySelectorAll("link[rel*=stylesheet]").forEach(linkElement => {
- const stylesheetInfo = this.stylesheets.get(linkElement);
- if (stylesheetInfo) {
- this.stylesheets.delete(linkElement);
- const styleElement = this.doc.createElement("style");
- if (stylesheetInfo.mediaText) {
- styleElement.media = stylesheetInfo.mediaText;
- }
- let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
- styleElement.textContent = stylesheetContent;
- linkElement.parentElement.replaceChild(styleElement, linkElement);
- } else {
- linkElement.remove();
- }
- });
- }
- replaceStyleAttributes() {
- this.doc.querySelectorAll("[style]").forEach(async element => {
- const declarations = this.styles.get(element);
- if (declarations) {
- this.styles.delete(element);
- let styleContent = cssTree.generate(declarations);
- element.setAttribute("style", styleContent);
- } else if (!element.closest("[" + WC_ATTRIBUTE_NAME + "]")) {
- element.setAttribute("style", "");
- }
- });
- }
- insertVariables() {
- if (this.cssVariables.size) {
- const styleElement = this.doc.createElement("style");
- const firstStyleElement = this.doc.head.querySelector("style");
- if (firstStyleElement) {
- this.doc.head.insertBefore(styleElement, firstStyleElement);
- } else {
- this.doc.head.appendChild(styleElement);
- }
- let stylesheetContent = "";
- this.cssVariables.forEach((content, indexResource) => {
- this.cssVariables.delete(indexResource);
- if (stylesheetContent) {
- stylesheetContent += ";";
- }
- stylesheetContent += `${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")`;
- });
- styleElement.textContent = ":root{" + stylesheetContent + "}";
- }
- }
- compressHTML() {
- let size;
- if (this.options.displayStats) {
- size = docUtil.getContentSize(this.doc.documentElement.outerHTML);
- }
- docUtil.minifyHTML(this.doc, { PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME: docUtil.PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME });
- if (this.options.displayStats) {
- this.stats.add("discarded", "HTML bytes", size - docUtil.getContentSize(this.doc.documentElement.outerHTML));
- }
- }
- }
- // ---------------
- // ProcessorHelper
- // ---------------
- const DATA_URI_PREFIX = "data:";
- const ABOUT_BLANK_URI = "about:blank";
- const EMPTY_DATA_URI = "data:base64,";
- const REGEXP_AMP = /&/g;
- const REGEXP_NBSP = /\u00a0/g;
- const REGEXP_START_TAG = /</g;
- const REGEXP_END_TAG = />/g;
- const REGEXP_URL_HASH = /(#.+?)$/;
- const PREFIX_DATA_URI_VND = "data:application/vnd.";
- const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
- class ProcessorHelper {
- static async evalTemplate(template = "", options, content, dontReplaceSlash) {
- const date = options.saveDate;
- const url = docUtil.parseURL(options.saveUrl);
- template = await Util.evalTemplateVariable(template, "page-title", () => options.title || "No title", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "page-language", () => options.info.lang || "No language", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "page-description", () => options.info.description || "No description", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "page-author", () => options.info.author || "No author", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "page-creator", () => options.info.creator || "No creator", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "page-publisher", () => options.info.publisher || "No publisher", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "datetime-iso", () => date.toISOString(), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "date-iso", () => date.toISOString().split("T")[0], dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0], dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "date-locale", () => date.toLocaleDateString(), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "time-locale", () => date.toLocaleTimeString(), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "day-locale", () => String(date.getDate()).padStart(2, "0"), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "month-locale", () => String(date.getMonth() + 1).padStart(2, "0"), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "year-locale", () => String(date.getFullYear()), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "datetime-locale", () => date.toLocaleString(), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "datetime-utc", () => date.toUTCString(), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "day-utc", () => String(date.getUTCDate()).padStart(2, "0"), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "month-utc", () => String(date.getUTCMonth() + 1).padStart(2, "0"), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "year-utc", () => String(date.getUTCFullYear()), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "hours-locale", () => String(date.getHours()).padStart(2, "0"), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "minutes-locale", () => String(date.getMinutes()).padStart(2, "0"), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "seconds-locale", () => String(date.getSeconds()).padStart(2, "0"), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "hours-utc", () => String(date.getUTCHours()).padStart(2, "0"), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "minutes-utc", () => String(date.getUTCMinutes()).padStart(2, "0"), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "seconds-utc", () => String(date.getUTCSeconds()).padStart(2, "0"), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "url-hash", () => url.hash.substring(1) || "No hash", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "url-host", () => url.host.replace(/\/$/, "") || "No host", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "url-hostname", () => url.hostname.replace(/\/$/, "") || "No hostname", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "url-href", () => decodeURI(url.href) || "No href", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "url-referrer", () => decodeURI(options.referrer) || "No referrer", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "url-password", () => url.password || "No password", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "url-pathname", () => decodeURI(url.pathname).replace(/^\//, "").replace(/\/$/, "") || "No pathname", dontReplaceSlash === undefined ? true : dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "url-port", () => url.port || "No port", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "url-protocol", () => url.protocol || "No protocol", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "url-search", () => url.search.substring(1) || "No search", dontReplaceSlash);
- const params = url.search.substring(1).split("&").map(parameter => parameter.split("="));
- for (const [name, value] of params) {
- template = await Util.evalTemplateVariable(template, "url-search-" + name, () => value || "", dontReplaceSlash);
- }
- template = template.replace(/{\s*url-search-[^}\s]*\s*}/gi, "");
- template = await Util.evalTemplateVariable(template, "url-username", () => url.username || "No username", dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "tab-id", () => String(options.tabId || "No tab id"), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "tab-index", () => String(options.tabIndex || "No tab index"), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "url-last-segment", () => decodeURI(Util.getLastSegment(url)) || "No last segment", dontReplaceSlash);
- if (content) {
- template = await Util.evalTemplateVariable(template, "digest-sha-256", async () => docUtil.digest("SHA-256", content), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "digest-sha-384", async () => docUtil.digest("SHA-384", content), dontReplaceSlash);
- template = await Util.evalTemplateVariable(template, "digest-sha-512", async () => docUtil.digest("SHA-512", content), dontReplaceSlash);
- }
- return template.trim();
- }
- static setBackgroundImage(element, url, style) {
- element.style.setProperty("background-blend-mode", "normal", "important");
- element.style.setProperty("background-clip", "content-box", "important");
- element.style.setProperty("background-position", style && style["background-position"] ? style["background-position"] : "center", "important");
- element.style.setProperty("background-color", style && style["background-color"] ? style["background-color"] : "transparent", "important");
- element.style.setProperty("background-image", url, "important");
- element.style.setProperty("background-size", style && style["background-size"] ? style["background-size"] : "100% 100%", "important");
- element.style.setProperty("background-origin", "content-box", "important");
- element.style.setProperty("background-repeat", "no-repeat", "important");
- }
- static processShortcutIcons(doc) {
- let shortcutIcon = Util.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel=\"icon\"], link[href][rel=\"shortcut icon\"]")));
- if (!shortcutIcon) {
- shortcutIcon = Util.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel*=\"icon\"]")));
- if (shortcutIcon) {
- shortcutIcon.rel = "icon";
- }
- }
- if (shortcutIcon) {
- doc.querySelectorAll("link[href][rel*=\"icon\"]").forEach(linkElement => {
- if (linkElement != shortcutIcon) {
- linkElement.remove();
- }
- });
- }
- }
- static removeSingleLineCssComments(stylesheet) {
- const removedRules = [];
- for (let cssRule = stylesheet.children.head; cssRule; cssRule = cssRule.next) {
- const ruleData = cssRule.data;
- if (ruleData.type == "Raw" && ruleData.value && ruleData.value.trim().startsWith("//")) {
- removedRules.push(cssRule);
- }
- }
- removedRules.forEach(cssRule => stylesheet.children.remove(cssRule));
- }
- static async resolveImportURLs(stylesheetContent, baseURI, options, workStylesheet) {
- stylesheetContent = ProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
- const imports = Util.getImportFunctions(stylesheetContent);
- await Promise.all(imports.map(async cssImport => {
- const match = Util.matchImport(cssImport);
- if (match) {
- let resourceURL = Util.normalizeURL(match.resourceURL);
- if (!Util.testIgnoredPath(resourceURL) && Util.testValidPath(resourceURL)) {
- try {
- resourceURL = docUtil.resolveURL(match.resourceURL, baseURI);
- } catch (error) {
- // ignored
- }
- if (Util.testValidURL(resourceURL)) {
- const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, validateTextContentType: true };
- const content = await docUtil.getContent(resourceURL, downloadOptions);
- resourceURL = content.resourceURL;
- let importedStylesheetContent = Util.removeCssComments(content.data);
- if (options.compressCSS) {
- importedStylesheetContent = docUtil.compressCSS(importedStylesheetContent);
- }
- importedStylesheetContent = Util.wrapMediaQuery(importedStylesheetContent, match.media);
- if (stylesheetContent.includes(cssImport)) {
- importedStylesheetContent = await ProcessorHelper.resolveImportURLs(importedStylesheetContent, resourceURL, options, workStylesheet);
- workStylesheet.textContent = importedStylesheetContent;
- if (workStylesheet.sheet.cssRules.length) {
- stylesheetContent = stylesheetContent.replace(Util.getRegExp(cssImport), importedStylesheetContent);
- } else {
- stylesheetContent = stylesheetContent.replace(Util.getRegExp(cssImport), "");
- }
- }
- }
- }
- }
- }));
- return stylesheetContent;
- }
- static resolveStylesheetURLs(stylesheetContent, baseURI) {
- const urlFunctions = Util.getUrlFunctions(stylesheetContent);
- urlFunctions.map(urlFunction => {
- const originalResourceURL = Util.matchURL(urlFunction);
- const resourceURL = Util.normalizeURL(originalResourceURL);
- if (!Util.testIgnoredPath(resourceURL)) {
- if (!resourceURL || Util.testValidPath(resourceURL)) {
- let resolvedURL;
- try {
- resolvedURL = docUtil.resolveURL(resourceURL, baseURI);
- } catch (error) {
- // ignored
- }
- if (Util.testValidURL(resolvedURL) && resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
- stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
- }
- } else {
- let newUrlFunction;
- if (originalResourceURL) {
- newUrlFunction = urlFunction.replace(originalResourceURL, EMPTY_DATA_URI);
- } else {
- newUrlFunction = "url(" + EMPTY_DATA_URI + ")";
- }
- stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), newUrlFunction);
- }
- } else {
- if (resourceURL.startsWith(DATA_URI_PREFIX)) {
- const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&").replace(REGEXP_NBSP, " ").replace(REGEXP_START_TAG, "<").replace(REGEXP_END_TAG, ">");
- if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
- stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
- }
- }
- }
- });
- return stylesheetContent;
- }
- static async resolveLinkStylesheetURLs(resourceURL, baseURI, options, workStylesheet) {
- resourceURL = Util.normalizeURL(resourceURL);
- if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
- const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, charset: options.charset };
- const content = await docUtil.getContent(resourceURL, downloadOptions);
- resourceURL = content.resourceURL;
- let stylesheetContent = Util.removeCssComments(content.data);
- if (options.compressCSS) {
- stylesheetContent = docUtil.compressCSS(stylesheetContent);
- }
- stylesheetContent = await ProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options, workStylesheet);
- return stylesheetContent;
- }
- }
- static async processStylesheet(cssRules, baseURI, options, cssVariables, batchRequest) {
- const promises = [];
- const removedRules = [];
- for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
- const ruleData = cssRule.data;
- if (ruleData.type == "Atrule" && ruleData.name == "charset") {
- removedRules.push(cssRule);
- } else if (ruleData.block && ruleData.block.children) {
- if (ruleData.type == "Rule") {
- promises.push(this.processStyle(ruleData.block.children.toArray(), baseURI, options, cssVariables, batchRequest));
- } else if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports")) {
- promises.push(this.processStylesheet(ruleData.block.children, baseURI, options, cssVariables, batchRequest));
- } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
- promises.push(processFontFaceRule(ruleData));
- }
- }
- }
- removedRules.forEach(cssRule => cssRules.remove(cssRule));
- await Promise.all(promises);
- async function processFontFaceRule(ruleData) {
- await Promise.all(ruleData.block.children.toArray().map(async declaration => {
- if (declaration.type == "Declaration" && declaration.value.children) {
- const urlFunctions = Util.getUrlFunctions(Util.getCSSValue(declaration.value));
- await Promise.all(urlFunctions.map(async urlFunction => {
- const originalResourceURL = Util.matchURL(urlFunction);
- const resourceURL = Util.normalizeURL(originalResourceURL);
- if (!Util.testIgnoredPath(resourceURL)) {
- if (Util.testValidURL(resourceURL)) {
- let { content } = await batchRequest.addURL(resourceURL, true);
- if (content != EMPTY_DATA_URI && !content.startsWith(PREFIX_DATA_URI_VND) && !content.startsWith(PREFIX_DATA_URI_IMAGE_SVG)) {
- const validResource = await docUtil.validFont(urlFunction);
- if (!validResource) {
- content = EMPTY_DATA_URI;
- }
- }
- replaceURLs(declaration, originalResourceURL, content);
- }
- } else if (resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(PREFIX_DATA_URI_VND) && !resourceURL.startsWith(PREFIX_DATA_URI_IMAGE_SVG)) {
- const validResource = await docUtil.validFont(urlFunction);
- if (!validResource) {
- replaceURLs(declaration, originalResourceURL, EMPTY_DATA_URI);
- }
- }
- }));
- }
- }));
- function replaceURLs(declaration, oldURL, newURL) {
- declaration.value.children.forEach(token => {
- if (token.type == "Url" && docUtil.removeQuotes(Util.getCSSValue(token.value)) == oldURL) {
- token.value.value = newURL;
- }
- });
- }
- }
- }
- static async processStyle(declarations, baseURI, options, cssVariables, batchRequest) {
- await Promise.all(declarations.map(async declaration => {
- if (declaration.type == "Declaration" && declaration.value.children) {
- const urlFunctions = Util.getUrlFunctions(Util.getCSSValue(declaration.value));
- await Promise.all(urlFunctions.map(async urlFunction => {
- const originalResourceURL = Util.matchURL(urlFunction);
- const resourceURL = Util.normalizeURL(originalResourceURL);
- if (!Util.testIgnoredPath(resourceURL)) {
- if (Util.testValidURL(resourceURL)) {
- let { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL, true, true);
- let variableDefined;
- const tokens = [];
- findURLToken(originalResourceURL, declaration.value.children, (token, parent, rootFunction) => {
- if (duplicate && options.groupDuplicateImages && rootFunction) {
- const value = cssTree.parse("var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")", { context: "value" }).children.head;
- tokens.push({ parent, token, value });
- variableDefined = true;
- } else {
- token.data.value.value = content;
- }
- });
- if (variableDefined) {
- cssVariables.set(indexResource, content);
- tokens.forEach(({ parent, token, value }) => parent.replace(token, value));
- }
- }
- }
- }));
- }
- }));
- function findURLToken(url, children, callback, depth = 0) {
- for (let token = children.head; token; token = token.next) {
- if (token.data.children) {
- findURLToken(url, token.data.children, callback, depth + 1);
- }
- if (token.data.type == "Url" && docUtil.removeQuotes(Util.getCSSValue(token.data.value)) == url) {
- callback(token, children, depth == 0);
- }
- }
- }
- }
- static async processAttribute(resourceElements, attributeName, baseURI, options, cssVariables, styles, batchRequest, processDuplicates, removeElementIfMissing) {
- await Promise.all(Array.from(resourceElements).map(async resourceElement => {
- let resourceURL = resourceElement.getAttribute(attributeName);
- resourceURL = Util.normalizeURL(resourceURL);
- if (!Util.testIgnoredPath(resourceURL)) {
- resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
- if (Util.testValidPath(resourceURL)) {
- try {
- resourceURL = docUtil.resolveURL(resourceURL, baseURI);
- } catch (error) {
- // ignored
- }
- if (Util.testValidURL(resourceURL)) {
- const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL, true, resourceElement.tagName == "IMG" && attributeName == "src");
- if (removeElementIfMissing && content == EMPTY_DATA_URI) {
- resourceElement.remove();
- } else {
- const forbiddenPrefixFound = PREFIXES_FORBIDDEN_DATA_URI.filter(prefixDataURI => content.startsWith(prefixDataURI)).length;
- if (!forbiddenPrefixFound) {
- const isSVG = content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
- if (processDuplicates && duplicate && options.groupDuplicateImages && !isSVG) {
- if (ProcessorHelper.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
- cssVariables.set(indexResource, content);
- const declarationList = cssTree.parse(resourceElement.getAttribute("style"), { context: "declarationList" });
- styles.set(resourceElement, declarationList);
- } else {
- resourceElement.setAttribute(attributeName, content);
- }
- } else {
- resourceElement.setAttribute(attributeName, content);
- }
- }
- }
- }
- }
- }
- }));
- }
- static async processXLinks(resourceElements, baseURI, options, batchRequest) {
- const attributeName = "xlink:href";
- await Promise.all(Array.from(resourceElements).map(async resourceElement => {
- const originalResourceURL = resourceElement.getAttribute(attributeName);
- let resourceURL = Util.normalizeURL(originalResourceURL);
- if (Util.testValidPath(resourceURL) && !Util.testIgnoredPath(resourceURL)) {
- resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
- try {
- resourceURL = docUtil.resolveURL(resourceURL, baseURI);
- } catch (error) {
- // ignored
- }
- if (Util.testValidURL(resourceURL)) {
- try {
- const { content } = await batchRequest.addURL(resourceURL);
- const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
- if (hashMatch && hashMatch[0]) {
- const svgDoc = docUtil.parseSVGContent(content);
- const symbolElement = svgDoc.querySelector(hashMatch[0]);
- if (symbolElement) {
- resourceElement.setAttribute(attributeName, hashMatch[0]);
- resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
- }
- } else {
- resourceElement.setAttribute(attributeName, PREFIX_DATA_URI_IMAGE_SVG + "," + content);
- }
- } catch (error) {
- /* ignored */
- }
- }
- } else if (resourceURL == options.url) {
- resourceElement.setAttribute(attributeName, originalResourceURL.substring(resourceURL.length));
- }
- }));
- }
- static async processSrcset(resourceElements, attributeName, baseURI, batchRequest) {
- await Promise.all(Array.from(resourceElements).map(async resourceElement => {
- const srcset = docUtil.parseSrcset(resourceElement.getAttribute(attributeName));
- const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
- let resourceURL = Util.normalizeURL(srcsetValue.url);
- if (!Util.testIgnoredPath(resourceURL)) {
- if (Util.testValidPath(resourceURL)) {
- try {
- resourceURL = docUtil.resolveURL(resourceURL, baseURI);
- } catch (error) {
- // ignored
- }
- if (Util.testValidURL(resourceURL)) {
- const { content } = await batchRequest.addURL(resourceURL, true);
- const forbiddenPrefixFound = PREFIXES_FORBIDDEN_DATA_URI.filter(prefixDataURI => content.startsWith(prefixDataURI)).length;
- if (forbiddenPrefixFound) {
- return "";
- }
- return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
- } else {
- return "";
- }
- } else {
- return "";
- }
- } else {
- return resourceURL + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
- }
- }));
- resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
- }));
- }
- static replaceImageSource(imgElement, variableName, options) {
- const dataAttributeName = docUtil.IMAGE_ATTRIBUTE_NAME;
- if (imgElement.getAttribute(dataAttributeName) != null) {
- const imgData = options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
- if (imgData.replaceable) {
- imgElement.setAttribute("src", `${PREFIX_DATA_URI_IMAGE_SVG},<svg xmlns="http://www.w3.org/2000/svg" width="${imgData.size.pxWidth}" height="${imgData.size.pxHeight}"><rect fill-opacity="0"/></svg>`);
- const backgroundStyle = {};
- const backgroundSize = (imgData.objectFit == "content" || imgData.objectFit == "cover") && imgData.objectFit;
- if (backgroundSize) {
- backgroundStyle["background-size"] = imgData.objectFit;
- }
- if (imgData.objectPosition) {
- backgroundStyle["background-position"] = imgData.objectPosition;
- }
- if (imgData.backgroundColor) {
- backgroundStyle["background-color"] = imgData.backgroundColor;
- }
- ProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")", backgroundStyle);
- imgElement.removeAttribute(dataAttributeName);
- return true;
- }
- }
- }
- }
- // ----
- // Util
- // ----
- const BLOB_URI_PREFIX = "blob:";
- const HTTP_URI_PREFIX = /^https?:\/\//;
- const FILE_URI_PREFIX = /^file:\/\//;
- const EMPTY_URL = /^https?:\/\/+\s*$/;
- const NOT_EMPTY_URL = /^(https?:\/\/|file:\/\/|blob:).+/;
- const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
- const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
- const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
- const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
- 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;
- const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
- const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
- const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
- const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
- const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
- const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
- const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
- class Util {
- static normalizeURL(url) {
- if (!url || url.startsWith(DATA_URI_PREFIX)) {
- return url;
- } else {
- return url.split("#")[0];
- }
- }
- static getCSSValue(value) {
- let result = "";
- try {
- result = cssTree.generate(value);
- } catch (error) {
- // ignored
- }
- return result;
- }
- static getOnEventAttributeNames(doc) {
- const element = doc.createElement("div");
- const attributeNames = [];
- for (const propertyName in element) {
- if (propertyName.startsWith("on")) {
- attributeNames.push(propertyName);
- }
- }
- return attributeNames;
- }
- static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
- const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
- if (template && template.match(replaceRegExp)) {
- let value = await valueGetter();
- if (!dontReplaceSlash) {
- value = value.replace(/\/+/g, "_");
- }
- return template.replace(replaceRegExp, value);
- }
- return template;
- }
- static getLastSegment(url) {
- let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/), lastSegment = lastSegmentMatch && lastSegmentMatch[0];
- if (!lastSegment) {
- lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
- lastSegment = lastSegmentMatch && lastSegmentMatch[0];
- }
- if (!lastSegment) {
- lastSegmentMatch = lastSegment.match(/(.*)\.[^.]+$/);
- lastSegment = lastSegmentMatch && lastSegmentMatch[0];
- }
- if (!lastSegment) {
- lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
- }
- lastSegmentMatch = lastSegment.match(/(.*)\.[^.]+$/);
- if (lastSegmentMatch && lastSegmentMatch[1]) {
- lastSegment = lastSegmentMatch[1];
- }
- lastSegment = lastSegment.replace(/\/$/, "").replace(/^\//, "");
- return lastSegment;
- }
- static getRegExp(string) {
- return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
- }
- static getUrlFunctions(stylesheetContent) {
- return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
- }
- static getImportFunctions(stylesheetContent) {
- return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
- }
- static findShortcutIcon(shortcutIcons) {
- shortcutIcons = shortcutIcons.filter(linkElement => linkElement.href != EMPTY_IMAGE);
- shortcutIcons.sort((linkElement1, linkElement2) => (parseInt(linkElement2.sizes, 10) || 16) - (parseInt(linkElement1.sizes, 10) || 16));
- return shortcutIcons[0];
- }
- static matchURL(stylesheetContent) {
- const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
- stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
- stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
- return match && match[1];
- }
- static testIgnoredPath(resourceURL) {
- return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) || resourceURL == ABOUT_BLANK_URI);
- }
- static testValidPath(resourceURL) {
- return resourceURL && !resourceURL.match(EMPTY_URL);
- }
- static testValidURL(resourceURL) {
- return Util.testValidPath(resourceURL) && (resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(FILE_URI_PREFIX) || resourceURL.startsWith(BLOB_URI_PREFIX)) && resourceURL.match(NOT_EMPTY_URL);
- }
- static matchImport(stylesheetContent) {
- const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
- stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
- stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
- stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
- stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
- stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
- if (match) {
- const [, resourceURL, media] = match;
- return { resourceURL, media };
- }
- }
- static removeCssComments(stylesheetContent) {
- let start, end;
- do {
- start = stylesheetContent.indexOf("/*");
- end = stylesheetContent.indexOf("*/", start + 2);
- if (start != -1 && end != -1) {
- stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
- }
- } while (start != -1 && end != -1);
- return stylesheetContent;
- }
- static wrapMediaQuery(stylesheetContent, mediaQuery) {
- if (mediaQuery) {
- return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
- } else {
- return stylesheetContent;
- }
- }
- }
- function log(...args) {
- console.log("S-File <core> ", ...args); // eslint-disable-line no-console
- }
- // -----
- // Stats
- // -----
- const STATS_DEFAULT_VALUES = {
- discarded: {
- "HTML bytes": 0,
- "hidden elements": 0,
- "HTML imports": 0,
- scripts: 0,
- objects: 0,
- "audio sources": 0,
- "video sources": 0,
- frames: 0,
- "CSS rules": 0,
- canvas: 0,
- stylesheets: 0,
- resources: 0,
- medias: 0
- },
- processed: {
- "HTML bytes": 0,
- "hidden elements": 0,
- "HTML imports": 0,
- scripts: 0,
- objects: 0,
- "audio sources": 0,
- "video sources": 0,
- frames: 0,
- "CSS rules": 0,
- canvas: 0,
- stylesheets: 0,
- resources: 0,
- medias: 0
- }
- };
- class Stats {
- constructor(options) {
- this.options = options;
- if (options.displayStats) {
- this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
- }
- }
- set(type, subType, value) {
- if (this.options.displayStats) {
- this.data[type][subType] = value;
- }
- }
- add(type, subType, value) {
- if (this.options.displayStats) {
- this.data[type][subType] += value;
- }
- }
- addAll(pageData) {
- if (this.options.displayStats) {
- Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
- Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
- }
- }
- }
- return { getClass };
- })();
|