From ee3857b54f9b235edd247388372c13b467cb8e9b Mon Sep 17 00:00:00 2001 From: Lewis Donovan <23400003+lewisdonovan@users.noreply.github.com> Date: Fri, 1 Nov 2024 12:02:20 +0100 Subject: [PATCH] Update readme. --- README.md | 3 +- dist/cjs/index.js | 77 ++++++++++++++++++++++++---------- dist/cjs/min/index.min.js | 2 +- dist/cjs/min/index.min.js.map | 2 +- dist/esm/index.mjs | 77 ++++++++++++++++++++++++---------- dist/esm/index.mjs.map | 2 +- dist/esm/min/index.min.mjs | 2 +- dist/esm/min/index.min.mjs.map | 2 +- dist/tsc/buildQueryString.js | 2 +- dist/tsc/getPrettyUrl.js | 71 ++++++++++++++++++++++--------- dist/tsc/index.js | 2 +- src/buildQueryString.ts | 2 +- 12 files changed, 168 insertions(+), 76 deletions(-) diff --git a/README.md b/README.md index c182091..68868c4 100644 --- a/README.md +++ b/README.md @@ -33,10 +33,9 @@ yarn add google-news-scraper Simply import the package and pass a config object. ```javascript import googleNewsScraper from 'google-news-scraper'; - const articles = await googleNewsScraper({ searchTerm: "The Oscars" }); - ``` +A minimum working example can be found in [this repo](https://github.com/lewisdonovan/gns-example). Full documentation on the [config object](#config) can be found below. ## Output 📲 diff --git a/dist/cjs/index.js b/dist/cjs/index.js index 3195123..b70933b 100644 --- a/dist/cjs/index.js +++ b/dist/cjs/index.js @@ -81,30 +81,61 @@ const getArticleType = (article) => { return ""; }; +// const getPrettyUrl = (uglyUrl: string, logger: winston.Logger): string | null => { +// const base64Match = uglyUrl.match(/\/read\/([A-Za-z0-9-_]+)/); +// if (!base64Match) { +// return null; +// } +// const base64String = base64Match[1]; +// try { +// const decodedString = Buffer.from(base64String, "base64").toString("ascii"); +// const urlPattern = /https?:\/\/[^\s"']+/g; +// const matches = decodedString.match(urlPattern) || []; +// const urls = matches.flatMap(match => { +// const splitUrls = match.split(/(? { +// const cleanUrl = url.trim().replace(/[^\w\-\/:.]+$/, '').replace(/\\x[0-9A-Fa-f]{2}/g, ''); +// return cleanUrl; +// }); +// }); +// const uniqueUrls = [...new Set(urls)]; +// const finalUrl = uniqueUrls.length ? uniqueUrls[0] : uglyUrl; +// logger.info(finalUrl); +// return finalUrl; +// } catch (error) { +// logger.error(error); +// return null; +// } +// } const getPrettyUrl = (uglyUrl, logger) => { - const base64Match = uglyUrl.match(/\/read\/([A-Za-z0-9-_]+)/); - if (!base64Match) { - return null; - } - const base64String = base64Match[1]; + var _a, _b; try { - const decodedString = Buffer.from(base64String, "base64").toString("ascii"); - const urlPattern = /https?:\/\/[^\s"']+/g; - const matches = decodedString.match(urlPattern) || []; - const urls = matches.flatMap(match => { - const splitUrls = match.split(/(? { - const cleanUrl = url.trim().replace(/[^\w\-\/:.]+$/, '').replace(/\\x[0-9A-Fa-f]{2}/g, ''); - return cleanUrl; - }); - }); - const uniqueUrls = [...new Set(urls)]; - const finalUrl = uniqueUrls.length ? uniqueUrls[0] : uglyUrl; - logger.info(finalUrl); - return finalUrl; + // Step 1: Extract the encoded portion between 'read/' and '?' + let encodedPart = uglyUrl.split('read/')[1].split('?')[0]; + // Step 2: Remove 'CB' prefix if present + if (encodedPart.startsWith('CB')) { + encodedPart = encodedPart.substring(2); + } + // Step 3: Replace URL-safe Base64 characters + encodedPart = encodedPart.replace(/-/g, '+').replace(/_/g, '/'); + // Step 4: Add padding if necessary + const padding = '='.repeat((4 - (encodedPart.length % 4)) % 4); + encodedPart += padding; + // Step 5: First Base64 decode + const firstDecodedBytes = atob(encodedPart); + // Step 6: Extract the second encoded string (Base64 URL-safe characters) + const secondEncodedPart = (_b = (_a = firstDecodedBytes === null || firstDecodedBytes === void 0 ? void 0 : firstDecodedBytes.match(/[A-Za-z0-9\-_]+/g)) === null || _a === void 0 ? void 0 : _a.join('')) !== null && _b !== void 0 ? _b : ''; + // Step 7: Replace URL-safe characters in the second string + let secondEncoded = secondEncodedPart.replace(/-/g, '+').replace(/_/g, '/'); + const secondPadding = '='.repeat((4 - (secondEncoded.length % 4)) % 4); + secondEncoded += secondPadding; + // Step 8: Second Base64 decode to get the final URL + const finalURL = atob(secondEncoded); + console.log('Final URL:', finalURL); + return finalURL; } catch (error) { - logger.error(error); + console.error('Error decoding URL:', error); return null; } }; @@ -114,7 +145,7 @@ const buildQueryString = (query) => { if (Object.keys(query).length === 0) return ""; // Build query string - // Example: { q: 'puppies', hl: 'en', gl: 'US' } => '?q=puppies&hl=en&gl=US' + // Example: { q: 'zapatos', gl: 'ES', ceid: "es:es" } => '?q=zapatos&gl=ES&ceid=ES:es' const queryString = Object.keys(query).reduce((acc, key, index) => { const prefix = index === 0 ? '?' : '&'; return `${acc}${prefix}${key}=${query[key]}`; @@ -2778,7 +2809,7 @@ const googleNewsScraper = (userConfig) => __awaiter(void 0, void 0, void 0, func const $ = cheerio__namespace.load(content); const articles = $('article'); let results = []; - $(articles).each(function (i) { + $(articles).each(function () { var _a, _b, _c, _d, _e, _f, _g, _h, _j; const link = ((_c = (_b = (_a = $(this)) === null || _a === void 0 ? void 0 : _a.find('a[href^="./article"]')) === null || _b === void 0 ? void 0 : _b.attr('href')) === null || _c === void 0 ? void 0 : _c.replace('./', 'https://news.google.com/')) || ((_f = (_e = (_d = $(this)) === null || _d === void 0 ? void 0 : _d.find('a[href^="./read"]')) === null || _e === void 0 ? void 0 : _e.attr('href')) === null || _f === void 0 ? void 0 : _f.replace('./', 'https://news.google.com/')) || ""; const srcset = (_g = $(this).find('figure').find('img').attr('srcset')) === null || _g === void 0 ? void 0 : _g.split(' '); @@ -2800,7 +2831,7 @@ const googleNewsScraper = (userConfig) => __awaiter(void 0, void 0, void 0, func }); if (config.prettyURLs) { results = yield Promise.all(results.map(article => { - const url = getPrettyUrl(article.link, logger); + const url = getPrettyUrl(article.link); if (url) { article.link = url; } diff --git a/dist/cjs/min/index.min.js b/dist/cjs/min/index.min.js index 387412a..402d0f2 100644 --- a/dist/cjs/min/index.min.js +++ b/dist/cjs/min/index.min.js @@ -1,2 +1,2 @@ -"use strict";var e=require("puppeteer"),t=require("cheerio"),i=require("winston"),r=require("jsdom");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var r=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var a=n(t);const s={levels:{none:0,error:1,warn:2,info:3,verbose:4},colors:{none:"black",error:"red",warn:"yellow",info:"blue",verbose:"white"}};i.addColors(s.colors);const o=e=>i.createLogger({levels:s.levels,format:i.format.combine(i.format.colorize(),i.format.simple()),transports:[new i.transports.Console],level:e});var l,c={exports:{}};function h(){return l||(l=1,function(e){function t(e,t){if(t&&t.documentElement)e=t,t=arguments[2];else if(!e||!e.documentElement)throw new Error("First argument to Readability constructor should be a document object.");if(t=t||{},this._doc=e,this._docJSDOMParser=this._doc.firstChild.__JSDOMParser__,this._articleTitle=null,this._articleByline=null,this._articleDir=null,this._articleSiteName=null,this._attempts=[],this._debug=!!t.debug,this._maxElemsToParse=t.maxElemsToParse||this.DEFAULT_MAX_ELEMS_TO_PARSE,this._nbTopCandidates=t.nbTopCandidates||this.DEFAULT_N_TOP_CANDIDATES,this._charThreshold=t.charThreshold||this.DEFAULT_CHAR_THRESHOLD,this._classesToPreserve=this.CLASSES_TO_PRESERVE.concat(t.classesToPreserve||[]),this._keepClasses=!!t.keepClasses,this._serializer=t.serializer||function(e){return e.innerHTML},this._disableJSONLD=!!t.disableJSONLD,this._allowedVideoRegex=t.allowedVideoRegex||this.REGEXPS.videos,this._flags=this.FLAG_STRIP_UNLIKELYS|this.FLAG_WEIGHT_CLASSES|this.FLAG_CLEAN_CONDITIONALLY,this._debug){let e=function(e){if(e.nodeType==e.TEXT_NODE)return`${e.nodeName} ("${e.textContent}")`;let t=Array.from(e.attributes||[],(function(e){return`${e.name}="${e.value}"`})).join(" ");return`<${e.localName} ${t}>`};this.log=function(){if("undefined"!=typeof console){let t=Array.from(arguments,(t=>t&&t.nodeType==this.ELEMENT_NODE?e(t):t));t.unshift("Reader: (Readability)"),console.log.apply(console,t)}else if("undefined"!=typeof dump){var t=Array.prototype.map.call(arguments,(function(t){return t&&t.nodeName?e(t):t})).join(" ");dump("Reader: (Readability) "+t+"\n")}}}else this.log=function(){}}t.prototype={FLAG_STRIP_UNLIKELYS:1,FLAG_WEIGHT_CLASSES:2,FLAG_CLEAN_CONDITIONALLY:4,ELEMENT_NODE:1,TEXT_NODE:3,DEFAULT_MAX_ELEMS_TO_PARSE:0,DEFAULT_N_TOP_CANDIDATES:5,DEFAULT_TAGS_TO_SCORE:"section,h2,h3,h4,h5,h6,p,td,pre".toUpperCase().split(","),DEFAULT_CHAR_THRESHOLD:500,REGEXPS:{unlikelyCandidates:/-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,okMaybeItsACandidate:/and|article|body|column|content|main|shadow/i,positive:/article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i,negative:/-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|foot|footer|footnote|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget/i,extraneous:/print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i,byline:/byline|author|dateline|writtenby|p-author/i,replaceFonts:/<(\/?)font[^>]*>/gi,normalize:/\s{2,}/g,videos:/\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i,shareElements:/(\b|_)(share|sharedaddy)(\b|_)/i,nextLink:/(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i,prevLink:/(prev|earl|old|new|<|«)/i,tokenize:/\W+/g,whitespace:/^\s*$/,hasContent:/\S$/,hashUrl:/^#.+/,srcsetUrl:/(\S+)(\s+[\d.]+[xw])?(\s*(?:,|$))/g,b64DataUrl:/^data:\s*([^\s;,]+)\s*;\s*base64\s*,/i,commas:/\u002C|\u060C|\uFE50|\uFE10|\uFE11|\u2E41|\u2E34|\u2E32|\uFF0C/g,jsonLdArticleTypes:/^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/},UNLIKELY_ROLES:["menu","menubar","complementary","navigation","alert","alertdialog","dialog"],DIV_TO_P_ELEMS:new Set(["BLOCKQUOTE","DL","DIV","IMG","OL","P","PRE","TABLE","UL"]),ALTER_TO_DIV_EXCEPTIONS:["DIV","ARTICLE","SECTION","P"],PRESENTATIONAL_ATTRIBUTES:["align","background","bgcolor","border","cellpadding","cellspacing","frame","hspace","rules","style","valign","vspace"],DEPRECATED_SIZE_ATTRIBUTE_ELEMS:["TABLE","TH","TD","HR","PRE"],PHRASING_ELEMS:["ABBR","AUDIO","B","BDO","BR","BUTTON","CITE","CODE","DATA","DATALIST","DFN","EM","EMBED","I","IMG","INPUT","KBD","LABEL","MARK","MATH","METER","NOSCRIPT","OBJECT","OUTPUT","PROGRESS","Q","RUBY","SAMP","SCRIPT","SELECT","SMALL","SPAN","STRONG","SUB","SUP","TEXTAREA","TIME","VAR","WBR"],CLASSES_TO_PRESERVE:["page"],HTML_ESCAPE_MAP:{lt:"<",gt:">",amp:"&",quot:'"',apos:"'"},_postProcessContent:function(e){this._fixRelativeUris(e),this._simplifyNestedElements(e),this._keepClasses||this._cleanClasses(e)},_removeNodes:function(e,t){if(this._docJSDOMParser&&e._isLiveNodeList)throw new Error("Do not pass live node lists to _removeNodes");for(var i=e.length-1;i>=0;i--){var r=e[i],n=r.parentNode;n&&(t&&!t.call(this,r,i,e)||n.removeChild(r))}},_replaceNodeTags:function(e,t){if(this._docJSDOMParser&&e._isLiveNodeList)throw new Error("Do not pass live node lists to _replaceNodeTags");for(const i of e)this._setNodeTag(i,t)},_forEachNode:function(e,t){Array.prototype.forEach.call(e,t,this)},_findNode:function(e,t){return Array.prototype.find.call(e,t,this)},_someNode:function(e,t){return Array.prototype.some.call(e,t,this)},_everyNode:function(e,t){return Array.prototype.every.call(e,t,this)},_concatNodeLists:function(){var e=Array.prototype.slice,t=e.call(arguments).map((function(t){return e.call(t)}));return Array.prototype.concat.apply([],t)},_getAllNodesWithTag:function(e,t){return e.querySelectorAll?e.querySelectorAll(t.join(",")):[].concat.apply([],t.map((function(t){var i=e.getElementsByTagName(t);return Array.isArray(i)?i:Array.from(i)})))},_cleanClasses:function(e){var t=this._classesToPreserve,i=(e.getAttribute("class")||"").split(/\s+/).filter((function(e){return-1!=t.indexOf(e)})).join(" ");for(i?e.setAttribute("class",i):e.removeAttribute("class"),e=e.firstElementChild;e;e=e.nextElementSibling)this._cleanClasses(e)},_fixRelativeUris:function(e){var t=this._doc.baseURI,i=this._doc.documentURI;function r(e){if(t==i&&"#"==e.charAt(0))return e;try{return new URL(e,t).href}catch(e){}return e}var n=this._getAllNodesWithTag(e,["a"]);this._forEachNode(n,(function(e){var t=e.getAttribute("href");if(t)if(0===t.indexOf("javascript:"))if(1===e.childNodes.length&&e.childNodes[0].nodeType===this.TEXT_NODE){var i=this._doc.createTextNode(e.textContent);e.parentNode.replaceChild(i,e)}else{for(var n=this._doc.createElement("span");e.firstChild;)n.appendChild(e.firstChild);e.parentNode.replaceChild(n,e)}else e.setAttribute("href",r(t))}));var a=this._getAllNodesWithTag(e,["img","picture","figure","video","audio","source"]);this._forEachNode(a,(function(e){var t=e.getAttribute("src"),i=e.getAttribute("poster"),n=e.getAttribute("srcset");if(t&&e.setAttribute("src",r(t)),i&&e.setAttribute("poster",r(i)),n){var a=n.replace(this.REGEXPS.srcsetUrl,(function(e,t,i,n){return r(t)+(i||"")+n}));e.setAttribute("srcset",a)}}))},_simplifyNestedElements:function(e){for(var t=e;t;){if(t.parentNode&&["DIV","SECTION"].includes(t.tagName)&&(!t.id||!t.id.startsWith("readability"))){if(this._isElementWithoutContent(t)){t=this._removeAndGetNext(t);continue}if(this._hasSingleTagInsideElement(t,"DIV")||this._hasSingleTagInsideElement(t,"SECTION")){for(var i=t.children[0],r=0;r»] /.test(t))r=/ [\\\/>»] /.test(t),n(t=i.replace(/(.*)[\|\-\\\/>»] .*/gi,"$1"))<3&&(t=i.replace(/[^\|\-\\\/>»]*[\|\-\\\/>»](.*)/gi,"$1"));else if(-1!==t.indexOf(": ")){var a=this._concatNodeLists(e.getElementsByTagName("h1"),e.getElementsByTagName("h2")),s=t.trim();this._someNode(a,(function(e){return e.textContent.trim()===s}))||(n(t=i.substring(i.lastIndexOf(":")+1))<3?t=i.substring(i.indexOf(":")+1):n(i.substr(0,i.indexOf(":")))>5&&(t=i))}else if(t.length>150||t.length<15){var o=e.getElementsByTagName("h1");1===o.length&&(t=this._getInnerText(o[0]))}var l=n(t=t.trim().replace(this.REGEXPS.normalize," "));return l<=4&&(!r||l!=n(i.replace(/[\|\-\\\/>»]+/g,""))-1)&&(t=i),t},_prepDocument:function(){var e=this._doc;this._removeNodes(this._getAllNodesWithTag(e,["style"])),e.body&&this._replaceBrs(e.body),this._replaceNodeTags(this._getAllNodesWithTag(e,["font"]),"SPAN")},_nextNode:function(e){for(var t=e;t&&t.nodeType!=this.ELEMENT_NODE&&this.REGEXPS.whitespace.test(t.textContent);)t=t.nextSibling;return t},_replaceBrs:function(e){this._forEachNode(this._getAllNodesWithTag(e,["br"]),(function(e){for(var t=e.nextSibling,i=!1;(t=this._nextNode(t))&&"BR"==t.tagName;){i=!0;var r=t.nextSibling;t.parentNode.removeChild(t),t=r}if(i){var n=this._doc.createElement("p");for(e.parentNode.replaceChild(n,e),t=n.nextSibling;t;){if("BR"==t.tagName){var a=this._nextNode(t.nextSibling);if(a&&"BR"==a.tagName)break}if(!this._isPhrasingContent(t))break;var s=t.nextSibling;n.appendChild(t),t=s}for(;n.lastChild&&this._isWhitespace(n.lastChild);)n.removeChild(n.lastChild);"P"===n.parentNode.tagName&&this._setNodeTag(n.parentNode,"DIV")}}))},_setNodeTag:function(e,t){if(this.log("_setNodeTag",e,t),this._docJSDOMParser)return e.localName=t.toLowerCase(),e.tagName=t.toUpperCase(),e;for(var i=e.ownerDocument.createElement(t);e.firstChild;)i.appendChild(e.firstChild);e.parentNode.replaceChild(i,e),e.readability&&(i.readability=e.readability);for(var r=0;r!i.includes(e))).join(" ").length/r.join(" ").length:0},_checkByline:function(e,t){if(this._articleByline)return!1;if(void 0!==e.getAttribute)var i=e.getAttribute("rel"),r=e.getAttribute("itemprop");return!(!("author"===i||r&&-1!==r.indexOf("author")||this.REGEXPS.byline.test(t))||!this._isValidByline(e.textContent))&&(this._articleByline=e.textContent.trim(),!0)},_getNodeAncestors:function(e,t){t=t||0;for(var i=0,r=[];e.parentNode&&(r.push(e.parentNode),!t||++i!==t);)e=e.parentNode;return r},_grabArticle:function(e){this.log("**** grabArticle ****");var t=this._doc,i=null!==e;if(!(e=e||this._doc.body))return this.log("No body found in document. Abort."),null;for(var r=e.innerHTML;;){this.log("Starting grabArticle loop");var n=this._flagIsActive(this.FLAG_STRIP_UNLIKELYS),a=[],s=this._doc.documentElement;let V=!0;for(;s;){"HTML"===s.tagName&&(this._articleLang=s.getAttribute("lang"));var o=s.className+" "+s.id;if(this._isProbablyVisible(s))if("true"!=s.getAttribute("aria-modal")||"dialog"!=s.getAttribute("role"))if(this._checkByline(s,o))s=this._removeAndGetNext(s);else if(V&&this._headerDuplicatesTitle(s))this.log("Removing header: ",s.textContent.trim(),this._articleTitle.trim()),V=!1,s=this._removeAndGetNext(s);else{if(n){if(this.REGEXPS.unlikelyCandidates.test(o)&&!this.REGEXPS.okMaybeItsACandidate.test(o)&&!this._hasAncestorTag(s,"table")&&!this._hasAncestorTag(s,"code")&&"BODY"!==s.tagName&&"A"!==s.tagName){this.log("Removing unlikely candidate - "+o),s=this._removeAndGetNext(s);continue}if(this.UNLIKELY_ROLES.includes(s.getAttribute("role"))){this.log("Removing content with role "+s.getAttribute("role")+" - "+o),s=this._removeAndGetNext(s);continue}}if("DIV"!==s.tagName&&"SECTION"!==s.tagName&&"HEADER"!==s.tagName&&"H1"!==s.tagName&&"H2"!==s.tagName&&"H3"!==s.tagName&&"H4"!==s.tagName&&"H5"!==s.tagName&&"H6"!==s.tagName||!this._isElementWithoutContent(s)){if(-1!==this.DEFAULT_TAGS_TO_SCORE.indexOf(s.tagName)&&a.push(s),"DIV"===s.tagName){for(var l=null,c=s.firstChild;c;){var h=c.nextSibling;if(this._isPhrasingContent(c))null!==l?l.appendChild(c):this._isWhitespace(c)||(l=t.createElement("p"),s.replaceChild(l,c),l.appendChild(c));else if(null!==l){for(;l.lastChild&&this._isWhitespace(l.lastChild);)l.removeChild(l.lastChild);l=null}c=h}if(this._hasSingleTagInsideElement(s,"P")&&this._getLinkDensity(s)<.25){var d=s.children[0];s.parentNode.replaceChild(d,s),s=d,a.push(s)}else this._hasChildBlockElement(s)||(s=this._setNodeTag(s,"P"),a.push(s))}s=this._getNextNode(s)}else s=this._removeAndGetNext(s)}else s=this._removeAndGetNext(s);else this.log("Removing hidden node - "+o),s=this._removeAndGetNext(s)}var g=[];this._forEachNode(a,(function(e){if(e.parentNode&&void 0!==e.parentNode.tagName){var t=this._getInnerText(e);if(!(t.length<25)){var i=this._getNodeAncestors(e,5);if(0!==i.length){var r=0;r+=1,r+=t.split(this.REGEXPS.commas).length,r+=Math.min(Math.floor(t.length/100),3),this._forEachNode(i,(function(e,t){if(e.tagName&&e.parentNode&&void 0!==e.parentNode.tagName){if(void 0===e.readability&&(this._initializeNode(e),g.push(e)),0===t)var i=1;else i=1===t?2:3*t;e.readability.contentScore+=r/i}}))}}}}));for(var u=[],m=0,f=g.length;mN.readability.contentScore){u.splice(b,0,p),u.length>this._nbTopCandidates&&u.pop();break}}}var v,E=u[0]||null,y=!1;if(null===E||"BODY"===E.tagName){for(E=t.createElement("DIV"),y=!0;e.firstChild;)this.log("Moving child out:",e.firstChild),E.appendChild(e.firstChild);e.appendChild(E),this._initializeNode(E)}else if(E){for(var T=[],A=1;A=.75&&T.push(this._getNodeAncestors(u[A]));if(T.length>=3)for(v=E.parentNode;"BODY"!==v.tagName;){for(var S=0,C=0;C=3){E=v;break}v=v.parentNode}E.readability||this._initializeNode(E),v=E.parentNode;for(var x=E.readability.contentScore,L=x/3;"BODY"!==v.tagName;)if(v.readability){var w=v.readability.contentScore;if(wx){E=v;break}x=v.readability.contentScore,v=v.parentNode}else v=v.parentNode;for(v=E.parentNode;"BODY"!=v.tagName&&1==v.children.length;)v=(E=v).parentNode;E.readability||this._initializeNode(E)}var I=t.createElement("DIV");i&&(I.id="readability-content");for(var R=Math.max(10,.2*E.readability.contentScore),O=(v=E.parentNode).children,D=0,P=O.length;D=R)B=!0;else if("P"===k.nodeName){var G=this._getLinkDensity(k),U=this._getInnerText(k),H=U.length;(H>80&&G<.25||H<80&&H>0&&0===G&&-1!==U.search(/\.( |$)/))&&(B=!0)}}B&&(this.log("Appending node:",k),-1===this.ALTER_TO_DIV_EXCEPTIONS.indexOf(k.nodeName)&&(this.log("Altering sibling:",k,"to div."),k=this._setNodeTag(k,"DIV")),I.appendChild(k),O=v.children,D-=1,P-=1)}if(this._debug&&this.log("Article content pre-prep: "+I.innerHTML),this._prepArticle(I),this._debug&&this.log("Article content post-prep: "+I.innerHTML),y)E.id="readability-page-1",E.className="page";else{var j=t.createElement("DIV");for(j.id="readability-page-1",j.className="page";I.firstChild;)j.appendChild(I.firstChild);I.appendChild(j)}this._debug&&this.log("Article content after paging: "+I.innerHTML);var W=!0,F=this._getInnerText(I,!0).length;if(F0&&e.length<100)},_unescapeHtmlEntities:function(e){if(!e)return e;var t=this.HTML_ESCAPE_MAP;return e.replace(/&(quot|amp|apos|lt|gt);/g,(function(e,i){return t[i]})).replace(/&#(?:x([0-9a-z]{1,4})|([0-9]{1,4}));/gi,(function(e,t,i){var r=parseInt(t||i,t?16:10);return String.fromCharCode(r)}))},_getJSONLD:function(e){var t,i=this._getAllNodesWithTag(e,["script"]);return this._forEachNode(i,(function(e){if(!t&&"application/ld+json"===e.getAttribute("type"))try{var i=e.textContent.replace(/^\s*\s*$/g,""),r=JSON.parse(i);if(!r["@context"]||!r["@context"].match(/^https?\:\/\/schema\.org$/))return;if(!r["@type"]&&Array.isArray(r["@graph"])&&(r=r["@graph"].find((function(e){return(e["@type"]||"").match(this.REGEXPS.jsonLdArticleTypes)}))),!r||!r["@type"]||!r["@type"].match(this.REGEXPS.jsonLdArticleTypes))return;if(t={},"string"==typeof r.name&&"string"==typeof r.headline&&r.name!==r.headline){var n=this._getArticleTitle(),a=this._textSimilarity(r.name,n)>.75,s=this._textSimilarity(r.headline,n)>.75;t.title=s&&!a?r.headline:r.name}else"string"==typeof r.name?t.title=r.name.trim():"string"==typeof r.headline&&(t.title=r.headline.trim());return r.author&&("string"==typeof r.author.name?t.byline=r.author.name.trim():Array.isArray(r.author)&&r.author[0]&&"string"==typeof r.author[0].name&&(t.byline=r.author.filter((function(e){return e&&"string"==typeof e.name})).map((function(e){return e.name.trim()})).join(", "))),"string"==typeof r.description&&(t.excerpt=r.description.trim()),r.publisher&&"string"==typeof r.publisher.name&&(t.siteName=r.publisher.name.trim()),void("string"==typeof r.datePublished&&(t.datePublished=r.datePublished.trim()))}catch(e){this.log(e.message)}})),t||{}},_getArticleMetadata:function(e){var t={},i={},r=this._doc.getElementsByTagName("meta"),n=/\s*(article|dc|dcterm|og|twitter)\s*:\s*(author|creator|description|published_time|title|site_name)\s*/gi,a=/^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|site_name)\s*$/i;return this._forEachNode(r,(function(e){var t=e.getAttribute("name"),r=e.getAttribute("property"),s=e.getAttribute("content");if(s){var o=null,l=null;r&&(o=r.match(n))&&(l=o[0].toLowerCase().replace(/\s/g,""),i[l]=s.trim()),!o&&t&&a.test(t)&&(l=t,s&&(l=l.toLowerCase().replace(/\s/g,"").replace(/\./g,":"),i[l]=s.trim()))}})),t.title=e.title||i["dc:title"]||i["dcterm:title"]||i["og:title"]||i["weibo:article:title"]||i["weibo:webpage:title"]||i.title||i["twitter:title"],t.title||(t.title=this._getArticleTitle()),t.byline=e.byline||i["dc:creator"]||i["dcterm:creator"]||i.author,t.excerpt=e.excerpt||i["dc:description"]||i["dcterm:description"]||i["og:description"]||i["weibo:article:description"]||i["weibo:webpage:description"]||i.description||i["twitter:description"],t.siteName=e.siteName||i["og:site_name"],t.publishedTime=e.datePublished||i["article:published_time"]||null,t.title=this._unescapeHtmlEntities(t.title),t.byline=this._unescapeHtmlEntities(t.byline),t.excerpt=this._unescapeHtmlEntities(t.excerpt),t.siteName=this._unescapeHtmlEntities(t.siteName),t.publishedTime=this._unescapeHtmlEntities(t.publishedTime),t},_isSingleImage:function(e){return"IMG"===e.tagName||1===e.children.length&&""===e.textContent.trim()&&this._isSingleImage(e.children[0])},_unwrapNoscriptImages:function(e){var t=Array.from(e.getElementsByTagName("img"));this._forEachNode(t,(function(e){for(var t=0;t0&&n>i)return!1;if(e.parentNode.tagName===t&&(!r||r(e.parentNode)))return!0;e=e.parentNode,n++}return!1},_getRowAndColumnCount:function(e){for(var t=0,i=0,r=e.getElementsByTagName("tr"),n=0;n0)r._readabilityDataTable=!0;else{if(["col","colgroup","tfoot","thead","th"].some((function(e){return!!r.getElementsByTagName(e)[0]})))this.log("Data table because found data-y descendant"),r._readabilityDataTable=!0;else if(r.getElementsByTagName("table")[0])r._readabilityDataTable=!1;else{var a=this._getRowAndColumnCount(r);a.rows>=10||a.columns>4?r._readabilityDataTable=!0:r._readabilityDataTable=a.rows*a.columns>10}}}else r._readabilityDataTable=!1;else r._readabilityDataTable=!1}},_fixLazyImages:function(e){this._forEachNode(this._getAllNodesWithTag(e,["img","picture","figure"]),(function(e){if(e.src&&this.REGEXPS.b64DataUrl.test(e.src)){if("image/svg+xml"===this.REGEXPS.b64DataUrl.exec(e.src)[1])return;for(var t=!1,i=0;ir+=this._getInnerText(e,!0).length)),r/i},_cleanConditionally:function(e,t){this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)&&this._removeNodes(this._getAllNodesWithTag(e,[t]),(function(e){var i=function(e){return e._readabilityDataTable},r="ul"===t||"ol"===t;if(!r){var n=0,a=this._getAllNodesWithTag(e,["ul","ol"]);this._forEachNode(a,(e=>n+=this._getInnerText(e).length)),r=n/this._getInnerText(e).length>.9}if("table"===t&&i(e))return!1;if(this._hasAncestorTag(e,"table",-1,i))return!1;if(this._hasAncestorTag(e,"code"))return!1;var s=this._getClassWeight(e);this.log("Cleaning Conditionally",e);if(s+0<0)return!0;if(this._getCharCount(e,",")<10){for(var o=e.getElementsByTagName("p").length,l=e.getElementsByTagName("img").length,c=e.getElementsByTagName("li").length-100,h=e.getElementsByTagName("input").length,d=this._getTextDensity(e,["h1","h2","h3","h4","h5","h6"]),g=0,u=this._getAllNodesWithTag(e,["object","embed","iframe"]),m=0;m1&&o/l<.5&&!this._hasAncestorTag(e,"figure")||!r&&c>o||h>Math.floor(o/3)||!r&&d<.9&&_<25&&(0===l||l>2)&&!this._hasAncestorTag(e,"figure")||!r&&s<25&&p>.2||s>=25&&p>.5||1===g&&_<75||g>1;if(r&&b){for(var N=0;N1)return b}if(l==e.getElementsByTagName("li").length)return!1}return b}return!1}))},_cleanMatchedNodes:function(e,t){for(var i=this._getNextNode(e,!0),r=this._getNextNode(e);r&&r!=i;)r=t.call(this,r,r.className+" "+r.id)?this._removeAndGetNext(r):this._getNextNode(r)},_cleanHeaders:function(e){let t=this._getAllNodesWithTag(e,["h1","h2"]);this._removeNodes(t,(function(e){let t=this._getClassWeight(e)<0;return t&&this.log("Removing header with low class weight:",e),t}))},_headerDuplicatesTitle:function(e){if("H1"!=e.tagName&&"H2"!=e.tagName)return!1;var t=this._getInnerText(e,!1);return this.log("Evaluating similarity of header:",t,this._articleTitle),this._textSimilarity(this._articleTitle,t)>.75},_flagIsActive:function(e){return(this._flags&e)>0},_removeFlag:function(e){this._flags=this._flags&~e},_isProbablyVisible:function(e){return(!e.style||"none"!=e.style.display)&&(!e.style||"hidden"!=e.style.visibility)&&!e.hasAttribute("hidden")&&(!e.hasAttribute("aria-hidden")||"true"!=e.getAttribute("aria-hidden")||e.className&&e.className.indexOf&&-1!==e.className.indexOf("fallback-image"))},parse:function(){if(this._maxElemsToParse>0){var e=this._doc.getElementsByTagName("*").length;if(e>this._maxElemsToParse)throw new Error("Aborting parsing document; "+e+" elements found")}this._unwrapNoscriptImages(this._doc);var t=this._disableJSONLD?{}:this._getJSONLD(this._doc);this._removeScripts(this._doc),this._prepDocument();var i=this._getArticleMetadata(t);this._articleTitle=i.title;var r=this._grabArticle();if(!r)return null;if(this.log("Grabbed: "+r.innerHTML),this._postProcessContent(r),!i.excerpt){var n=r.getElementsByTagName("p");n.length>0&&(i.excerpt=n[0].textContent.trim())}var a=r.textContent;return{title:this._articleTitle,byline:i.byline||this._articleByline,dir:this._articleDir,lang:this._articleLang,content:this._serializer(r),textContent:a,length:a.length,excerpt:i.excerpt,siteName:i.siteName||this._articleSiteName,publishedTime:i.publishedTime}}},e.exports=t}(c)),c.exports}var d,g,u,m={exports:{}};var f=function(){if(u)return g;u=1;var e=h(),t=(d||(d=1,function(){var e={unlikelyCandidates:/-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,okMaybeItsACandidate:/and|article|body|column|content|main|shadow/i};function t(e){return(!e.style||"none"!=e.style.display)&&!e.hasAttribute("hidden")&&(!e.hasAttribute("aria-hidden")||"true"!=e.getAttribute("aria-hidden")||e.className&&e.className.indexOf&&-1!==e.className.indexOf("fallback-image"))}m.exports=function(i,r={}){"function"==typeof r&&(r={visibilityChecker:r});var n={minScore:20,minContentLength:140,visibilityChecker:t};r=Object.assign(n,r);var a=i.querySelectorAll("p, pre, article"),s=i.querySelectorAll("div > br");if(s.length){var o=new Set(a);[].forEach.call(s,(function(e){o.add(e.parentNode)})),a=Array.from(o)}var l=0;return[].some.call(a,(function(t){if(!r.visibilityChecker(t))return!1;var i=t.className+" "+t.id;if(e.unlikelyCandidates.test(i)&&!e.okMaybeItsACandidate.test(i))return!1;if(t.matches("li p"))return!1;var n=t.textContent.trim().length;return!(nr.minScore}))}}()),m.exports);return g={Readability:e,isProbablyReaderable:t}}(),p=function(e,t,i,r){return new(i||(i=Promise))((function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((r=r.apply(e,t||[])).next())}))};const _=["you are human","are you human","i'm not a robot","recaptcha"],b=e=>p(void 0,[e],void 0,(function*({article:e,browser:t,filterWords:i,logger:n}){var a;try{const s=yield t.newPage();yield s.goto(e.link,{waitUntil:"networkidle2"});const o=yield s.evaluate((()=>document.documentElement.innerHTML)),l=null!==(a=yield s.evaluate((()=>{const e=document.querySelector('link[rel="icon"], link[rel="shortcut icon"]');return e?e.getAttribute("href"):""})))&&void 0!==a?a:"",c=new r.VirtualConsole;c.on("error",n.error);const h=new r.JSDOM(o,{url:e.link,virtualConsole:c});const d=new f.Readability(h.window.document).parse();if(!d||!d.textContent)return n.warn("Article content could not be parsed or is empty.",{article:e}),Object.assign(Object.assign({},e),{content:"",favicon:l});if(_.find((e=>d.textContent.toLowerCase().includes(e))))return n.warn("Article requires human verification.",{article:e}),Object.assign(Object.assign({},e),{content:"",favicon:l});const g=N(d.textContent,i);return g.split(" ").length<100?(n.warn("Article content is too short and likely not valuable.",{article:e}),Object.assign(Object.assign({},e),{content:"",favicon:l})):(n.info("SUCCESSFULLY SCRAPED ARTICLE CONTENT:",g),Object.assign(Object.assign({},e),{content:g,favicon:l}))}catch(t){return n.error(t),Object.assign(Object.assign({},e),{content:"",favicon:""})}})),N=(e,t)=>{const i=["subscribe now","sign up","newsletter","subscribe now","sign up for our newsletter","exclusive offer","limited time offer","free trial","download now","join now","register today","special promotion","promotional offer","discount code","early access","sneak peek","save now","don't miss out","act now","last chance","expires soon","giveaway","free access","premium access","unlock full access","buy now","learn more","click here","follow us on","share this article","connect with us","advertisement","sponsored content","partner content","affiliate links","click here","for more information","you may also like","we think you'll like","from our network",...t];return e.split("\n").map((e=>e.trim())).filter((e=>e.split(" ").length>4)).filter((e=>!i.some((t=>e.toLowerCase().includes(t))))).join("\n")};var v=function(e,t,i,r){return new(i||(i=Promise))((function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((r=r.apply(e,t||[])).next())}))};module.exports=t=>v(void 0,void 0,void 0,(function*(){var i,r;const n=Object.assign({prettyURLs:!0,getArticleContent:!1,puppeteerArgs:[],puppeteerHeadlessMode:!0,logLevel:"error",timeframe:"7d",queryVars:{},limit:99},t),s=o(n.logLevel),l=n.queryVars?Object.assign(Object.assign({},n.queryVars),{when:n.timeframe}):{when:n.timeframe};t.searchTerm&&(l.q=t.searchTerm);const c=null!==(h=l,i=0===Object.keys(h).length?"":Object.keys(h).reduce(((e,t,i)=>`${e}${0===i?"?":"&"}${t}=${h[t]}`),""))&&void 0!==i?i:"";var h;const d=`${null!==(r=n.baseUrl)&&void 0!==r?r:"https://news.google.com/search"}${c}`;s.info(`📰 SCRAPING NEWS FROM: ${d}`);const g={headless:t.puppeteerHeadlessMode,args:e.defaultArgs().concat(n.puppeteerArgs).filter(Boolean).concat(["--disable-extensions-except=/path/to/manifest/folder/","--load-extension=/path/to/manifest/folder/"])},u=yield e.launch(g),m=yield u.newPage();m.setViewport({width:1366,height:768}),m.setUserAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"),m.setRequestInterception(!0),m.on("request",(e=>{if(!e.isNavigationRequest())return void e.continue();const t=e.headers();t.Accept="text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",t["Accept-Encoding"]="gzip",t["Accept-Language"]="en-US,en;q=0.9,es;q=0.8",t["Upgrade-Insecure-Requests"]="1",t.Referer="https://www.google.com/",e.continue({headers:t})})),yield m.setCookie({name:"CONSENT",value:`YES+cb.${(new Date).toISOString().split("T")[0].replace(/-/g,"")}-04-p0.en-GB+FX+667`,domain:".google.com"}),yield m.goto(d,{waitUntil:"networkidle2"});try{yield m.$('[aria-label="Reject all"]'),yield Promise.all([m.click('[aria-label="Reject all"]'),m.waitForNavigation({waitUntil:"networkidle2"})])}catch(e){}const f=yield m.content(),_=a.load(f),N=_("article");let v=[];if(_(N).each((function(e){var t,i,r,n,a,s,o,l,c;const h=(null===(r=null===(i=null===(t=_(this))||void 0===t?void 0:t.find('a[href^="./article"]'))||void 0===i?void 0:i.attr("href"))||void 0===r?void 0:r.replace("./","https://news.google.com/"))||(null===(s=null===(a=null===(n=_(this))||void 0===n?void 0:n.find('a[href^="./read"]'))||void 0===a?void 0:a.attr("href"))||void 0===s?void 0:s.replace("./","https://news.google.com/"))||"",d=null===(o=_(this).find("figure").find("img").attr("srcset"))||void 0===o?void 0:o.split(" "),g=d&&d.length?d[d.length-2]:_(this).find("figure").find("img").attr("src"),u=(m=_(this)).find("h4").text()||m.find("div > div + div > div a").text()?"regular":m.find("figure").length?"topicFeatured":m.find("> a").text()?"topicSmall":"";var m;const f=((e,t)=>{var i,r;try{switch(t){case"regular":return e.find("h4").text()||e.find("div > div + div > div a").text()||"";case"topicFeatured":return e.find("a[target=_blank]").text()||(null===(i=e.find("button").attr("aria-label"))||void 0===i?void 0:i.replace("More - ",""))||"";case"topicSmall":return e.find("a[target=_blank]").text()||(null===(r=e.find("button").attr("aria-label"))||void 0===r?void 0:r.replace("More - ",""))||"";default:return""}}catch(e){return""}})(_(this),u),p={title:f,link:h,image:(null==g?void 0:g.startsWith("/"))?`https://news.google.com${g}`:g||"",source:_(this).find("div[data-n-tid]").text()||"",datetime:(null===(c=new Date((null===(l=_(this).find("div:last-child time"))||void 0===l?void 0:l.attr("datetime"))||""))||void 0===c?void 0:c.toISOString())||"",time:_(this).find("div:last-child time").text()||"",articleType:u};v.push(p)})),n.prettyURLs&&(v=yield Promise.all(v.map((e=>{const t=((e,t)=>{const i=e.match(/\/read\/([A-Za-z0-9-_]+)/);if(!i)return null;const r=i[1];try{const i=Buffer.from(r,"base64").toString("ascii"),n=/https?:\/\/[^\s"']+/g,a=(i.match(n)||[]).flatMap((e=>e.split(/(?e.trim().replace(/[^\w\-\/:.]+$/,"").replace(/\\x[0-9A-Fa-f]{2}/g,""))))),s=[...new Set(a)],o=s.length?s[0]:e;return t.info(o),o}catch(e){return t.error(e),null}})(e.link,s);return t&&(e.link=t),e})))),n.getArticleContent){const e=n.filterWords||[];v=yield(e=>p(void 0,[e],void 0,(function*({articles:e,browser:t,filterWords:i,logger:r}){try{const n=e.map((e=>b({article:e,browser:t,filterWords:i,logger:r})));return yield Promise.all(n)}catch(t){return r.error("getArticleContent ERROR:",t),e}})))({articles:v,browser:u,filterWords:e,logger:s})}yield m.close(),yield u.close();const E=v.filter((e=>e.title));return n.limiti.createLogger({levels:s.levels,format:i.format.combine(i.format.colorize(),i.format.simple()),transports:[new i.transports.Console],level:e});var l,c={exports:{}};function h(){return l||(l=1,function(e){function t(e,t){if(t&&t.documentElement)e=t,t=arguments[2];else if(!e||!e.documentElement)throw new Error("First argument to Readability constructor should be a document object.");if(t=t||{},this._doc=e,this._docJSDOMParser=this._doc.firstChild.__JSDOMParser__,this._articleTitle=null,this._articleByline=null,this._articleDir=null,this._articleSiteName=null,this._attempts=[],this._debug=!!t.debug,this._maxElemsToParse=t.maxElemsToParse||this.DEFAULT_MAX_ELEMS_TO_PARSE,this._nbTopCandidates=t.nbTopCandidates||this.DEFAULT_N_TOP_CANDIDATES,this._charThreshold=t.charThreshold||this.DEFAULT_CHAR_THRESHOLD,this._classesToPreserve=this.CLASSES_TO_PRESERVE.concat(t.classesToPreserve||[]),this._keepClasses=!!t.keepClasses,this._serializer=t.serializer||function(e){return e.innerHTML},this._disableJSONLD=!!t.disableJSONLD,this._allowedVideoRegex=t.allowedVideoRegex||this.REGEXPS.videos,this._flags=this.FLAG_STRIP_UNLIKELYS|this.FLAG_WEIGHT_CLASSES|this.FLAG_CLEAN_CONDITIONALLY,this._debug){let e=function(e){if(e.nodeType==e.TEXT_NODE)return`${e.nodeName} ("${e.textContent}")`;let t=Array.from(e.attributes||[],(function(e){return`${e.name}="${e.value}"`})).join(" ");return`<${e.localName} ${t}>`};this.log=function(){if("undefined"!=typeof console){let t=Array.from(arguments,(t=>t&&t.nodeType==this.ELEMENT_NODE?e(t):t));t.unshift("Reader: (Readability)"),console.log.apply(console,t)}else if("undefined"!=typeof dump){var t=Array.prototype.map.call(arguments,(function(t){return t&&t.nodeName?e(t):t})).join(" ");dump("Reader: (Readability) "+t+"\n")}}}else this.log=function(){}}t.prototype={FLAG_STRIP_UNLIKELYS:1,FLAG_WEIGHT_CLASSES:2,FLAG_CLEAN_CONDITIONALLY:4,ELEMENT_NODE:1,TEXT_NODE:3,DEFAULT_MAX_ELEMS_TO_PARSE:0,DEFAULT_N_TOP_CANDIDATES:5,DEFAULT_TAGS_TO_SCORE:"section,h2,h3,h4,h5,h6,p,td,pre".toUpperCase().split(","),DEFAULT_CHAR_THRESHOLD:500,REGEXPS:{unlikelyCandidates:/-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,okMaybeItsACandidate:/and|article|body|column|content|main|shadow/i,positive:/article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i,negative:/-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|foot|footer|footnote|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget/i,extraneous:/print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i,byline:/byline|author|dateline|writtenby|p-author/i,replaceFonts:/<(\/?)font[^>]*>/gi,normalize:/\s{2,}/g,videos:/\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i,shareElements:/(\b|_)(share|sharedaddy)(\b|_)/i,nextLink:/(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i,prevLink:/(prev|earl|old|new|<|«)/i,tokenize:/\W+/g,whitespace:/^\s*$/,hasContent:/\S$/,hashUrl:/^#.+/,srcsetUrl:/(\S+)(\s+[\d.]+[xw])?(\s*(?:,|$))/g,b64DataUrl:/^data:\s*([^\s;,]+)\s*;\s*base64\s*,/i,commas:/\u002C|\u060C|\uFE50|\uFE10|\uFE11|\u2E41|\u2E34|\u2E32|\uFF0C/g,jsonLdArticleTypes:/^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/},UNLIKELY_ROLES:["menu","menubar","complementary","navigation","alert","alertdialog","dialog"],DIV_TO_P_ELEMS:new Set(["BLOCKQUOTE","DL","DIV","IMG","OL","P","PRE","TABLE","UL"]),ALTER_TO_DIV_EXCEPTIONS:["DIV","ARTICLE","SECTION","P"],PRESENTATIONAL_ATTRIBUTES:["align","background","bgcolor","border","cellpadding","cellspacing","frame","hspace","rules","style","valign","vspace"],DEPRECATED_SIZE_ATTRIBUTE_ELEMS:["TABLE","TH","TD","HR","PRE"],PHRASING_ELEMS:["ABBR","AUDIO","B","BDO","BR","BUTTON","CITE","CODE","DATA","DATALIST","DFN","EM","EMBED","I","IMG","INPUT","KBD","LABEL","MARK","MATH","METER","NOSCRIPT","OBJECT","OUTPUT","PROGRESS","Q","RUBY","SAMP","SCRIPT","SELECT","SMALL","SPAN","STRONG","SUB","SUP","TEXTAREA","TIME","VAR","WBR"],CLASSES_TO_PRESERVE:["page"],HTML_ESCAPE_MAP:{lt:"<",gt:">",amp:"&",quot:'"',apos:"'"},_postProcessContent:function(e){this._fixRelativeUris(e),this._simplifyNestedElements(e),this._keepClasses||this._cleanClasses(e)},_removeNodes:function(e,t){if(this._docJSDOMParser&&e._isLiveNodeList)throw new Error("Do not pass live node lists to _removeNodes");for(var i=e.length-1;i>=0;i--){var r=e[i],n=r.parentNode;n&&(t&&!t.call(this,r,i,e)||n.removeChild(r))}},_replaceNodeTags:function(e,t){if(this._docJSDOMParser&&e._isLiveNodeList)throw new Error("Do not pass live node lists to _replaceNodeTags");for(const i of e)this._setNodeTag(i,t)},_forEachNode:function(e,t){Array.prototype.forEach.call(e,t,this)},_findNode:function(e,t){return Array.prototype.find.call(e,t,this)},_someNode:function(e,t){return Array.prototype.some.call(e,t,this)},_everyNode:function(e,t){return Array.prototype.every.call(e,t,this)},_concatNodeLists:function(){var e=Array.prototype.slice,t=e.call(arguments).map((function(t){return e.call(t)}));return Array.prototype.concat.apply([],t)},_getAllNodesWithTag:function(e,t){return e.querySelectorAll?e.querySelectorAll(t.join(",")):[].concat.apply([],t.map((function(t){var i=e.getElementsByTagName(t);return Array.isArray(i)?i:Array.from(i)})))},_cleanClasses:function(e){var t=this._classesToPreserve,i=(e.getAttribute("class")||"").split(/\s+/).filter((function(e){return-1!=t.indexOf(e)})).join(" ");for(i?e.setAttribute("class",i):e.removeAttribute("class"),e=e.firstElementChild;e;e=e.nextElementSibling)this._cleanClasses(e)},_fixRelativeUris:function(e){var t=this._doc.baseURI,i=this._doc.documentURI;function r(e){if(t==i&&"#"==e.charAt(0))return e;try{return new URL(e,t).href}catch(e){}return e}var n=this._getAllNodesWithTag(e,["a"]);this._forEachNode(n,(function(e){var t=e.getAttribute("href");if(t)if(0===t.indexOf("javascript:"))if(1===e.childNodes.length&&e.childNodes[0].nodeType===this.TEXT_NODE){var i=this._doc.createTextNode(e.textContent);e.parentNode.replaceChild(i,e)}else{for(var n=this._doc.createElement("span");e.firstChild;)n.appendChild(e.firstChild);e.parentNode.replaceChild(n,e)}else e.setAttribute("href",r(t))}));var a=this._getAllNodesWithTag(e,["img","picture","figure","video","audio","source"]);this._forEachNode(a,(function(e){var t=e.getAttribute("src"),i=e.getAttribute("poster"),n=e.getAttribute("srcset");if(t&&e.setAttribute("src",r(t)),i&&e.setAttribute("poster",r(i)),n){var a=n.replace(this.REGEXPS.srcsetUrl,(function(e,t,i,n){return r(t)+(i||"")+n}));e.setAttribute("srcset",a)}}))},_simplifyNestedElements:function(e){for(var t=e;t;){if(t.parentNode&&["DIV","SECTION"].includes(t.tagName)&&(!t.id||!t.id.startsWith("readability"))){if(this._isElementWithoutContent(t)){t=this._removeAndGetNext(t);continue}if(this._hasSingleTagInsideElement(t,"DIV")||this._hasSingleTagInsideElement(t,"SECTION")){for(var i=t.children[0],r=0;r»] /.test(t))r=/ [\\\/>»] /.test(t),n(t=i.replace(/(.*)[\|\-\\\/>»] .*/gi,"$1"))<3&&(t=i.replace(/[^\|\-\\\/>»]*[\|\-\\\/>»](.*)/gi,"$1"));else if(-1!==t.indexOf(": ")){var a=this._concatNodeLists(e.getElementsByTagName("h1"),e.getElementsByTagName("h2")),s=t.trim();this._someNode(a,(function(e){return e.textContent.trim()===s}))||(n(t=i.substring(i.lastIndexOf(":")+1))<3?t=i.substring(i.indexOf(":")+1):n(i.substr(0,i.indexOf(":")))>5&&(t=i))}else if(t.length>150||t.length<15){var o=e.getElementsByTagName("h1");1===o.length&&(t=this._getInnerText(o[0]))}var l=n(t=t.trim().replace(this.REGEXPS.normalize," "));return l<=4&&(!r||l!=n(i.replace(/[\|\-\\\/>»]+/g,""))-1)&&(t=i),t},_prepDocument:function(){var e=this._doc;this._removeNodes(this._getAllNodesWithTag(e,["style"])),e.body&&this._replaceBrs(e.body),this._replaceNodeTags(this._getAllNodesWithTag(e,["font"]),"SPAN")},_nextNode:function(e){for(var t=e;t&&t.nodeType!=this.ELEMENT_NODE&&this.REGEXPS.whitespace.test(t.textContent);)t=t.nextSibling;return t},_replaceBrs:function(e){this._forEachNode(this._getAllNodesWithTag(e,["br"]),(function(e){for(var t=e.nextSibling,i=!1;(t=this._nextNode(t))&&"BR"==t.tagName;){i=!0;var r=t.nextSibling;t.parentNode.removeChild(t),t=r}if(i){var n=this._doc.createElement("p");for(e.parentNode.replaceChild(n,e),t=n.nextSibling;t;){if("BR"==t.tagName){var a=this._nextNode(t.nextSibling);if(a&&"BR"==a.tagName)break}if(!this._isPhrasingContent(t))break;var s=t.nextSibling;n.appendChild(t),t=s}for(;n.lastChild&&this._isWhitespace(n.lastChild);)n.removeChild(n.lastChild);"P"===n.parentNode.tagName&&this._setNodeTag(n.parentNode,"DIV")}}))},_setNodeTag:function(e,t){if(this.log("_setNodeTag",e,t),this._docJSDOMParser)return e.localName=t.toLowerCase(),e.tagName=t.toUpperCase(),e;for(var i=e.ownerDocument.createElement(t);e.firstChild;)i.appendChild(e.firstChild);e.parentNode.replaceChild(i,e),e.readability&&(i.readability=e.readability);for(var r=0;r!i.includes(e))).join(" ").length/r.join(" ").length:0},_checkByline:function(e,t){if(this._articleByline)return!1;if(void 0!==e.getAttribute)var i=e.getAttribute("rel"),r=e.getAttribute("itemprop");return!(!("author"===i||r&&-1!==r.indexOf("author")||this.REGEXPS.byline.test(t))||!this._isValidByline(e.textContent))&&(this._articleByline=e.textContent.trim(),!0)},_getNodeAncestors:function(e,t){t=t||0;for(var i=0,r=[];e.parentNode&&(r.push(e.parentNode),!t||++i!==t);)e=e.parentNode;return r},_grabArticle:function(e){this.log("**** grabArticle ****");var t=this._doc,i=null!==e;if(!(e=e||this._doc.body))return this.log("No body found in document. Abort."),null;for(var r=e.innerHTML;;){this.log("Starting grabArticle loop");var n=this._flagIsActive(this.FLAG_STRIP_UNLIKELYS),a=[],s=this._doc.documentElement;let V=!0;for(;s;){"HTML"===s.tagName&&(this._articleLang=s.getAttribute("lang"));var o=s.className+" "+s.id;if(this._isProbablyVisible(s))if("true"!=s.getAttribute("aria-modal")||"dialog"!=s.getAttribute("role"))if(this._checkByline(s,o))s=this._removeAndGetNext(s);else if(V&&this._headerDuplicatesTitle(s))this.log("Removing header: ",s.textContent.trim(),this._articleTitle.trim()),V=!1,s=this._removeAndGetNext(s);else{if(n){if(this.REGEXPS.unlikelyCandidates.test(o)&&!this.REGEXPS.okMaybeItsACandidate.test(o)&&!this._hasAncestorTag(s,"table")&&!this._hasAncestorTag(s,"code")&&"BODY"!==s.tagName&&"A"!==s.tagName){this.log("Removing unlikely candidate - "+o),s=this._removeAndGetNext(s);continue}if(this.UNLIKELY_ROLES.includes(s.getAttribute("role"))){this.log("Removing content with role "+s.getAttribute("role")+" - "+o),s=this._removeAndGetNext(s);continue}}if("DIV"!==s.tagName&&"SECTION"!==s.tagName&&"HEADER"!==s.tagName&&"H1"!==s.tagName&&"H2"!==s.tagName&&"H3"!==s.tagName&&"H4"!==s.tagName&&"H5"!==s.tagName&&"H6"!==s.tagName||!this._isElementWithoutContent(s)){if(-1!==this.DEFAULT_TAGS_TO_SCORE.indexOf(s.tagName)&&a.push(s),"DIV"===s.tagName){for(var l=null,c=s.firstChild;c;){var h=c.nextSibling;if(this._isPhrasingContent(c))null!==l?l.appendChild(c):this._isWhitespace(c)||(l=t.createElement("p"),s.replaceChild(l,c),l.appendChild(c));else if(null!==l){for(;l.lastChild&&this._isWhitespace(l.lastChild);)l.removeChild(l.lastChild);l=null}c=h}if(this._hasSingleTagInsideElement(s,"P")&&this._getLinkDensity(s)<.25){var d=s.children[0];s.parentNode.replaceChild(d,s),s=d,a.push(s)}else this._hasChildBlockElement(s)||(s=this._setNodeTag(s,"P"),a.push(s))}s=this._getNextNode(s)}else s=this._removeAndGetNext(s)}else s=this._removeAndGetNext(s);else this.log("Removing hidden node - "+o),s=this._removeAndGetNext(s)}var g=[];this._forEachNode(a,(function(e){if(e.parentNode&&void 0!==e.parentNode.tagName){var t=this._getInnerText(e);if(!(t.length<25)){var i=this._getNodeAncestors(e,5);if(0!==i.length){var r=0;r+=1,r+=t.split(this.REGEXPS.commas).length,r+=Math.min(Math.floor(t.length/100),3),this._forEachNode(i,(function(e,t){if(e.tagName&&e.parentNode&&void 0!==e.parentNode.tagName){if(void 0===e.readability&&(this._initializeNode(e),g.push(e)),0===t)var i=1;else i=1===t?2:3*t;e.readability.contentScore+=r/i}}))}}}}));for(var u=[],m=0,f=g.length;mN.readability.contentScore){u.splice(b,0,p),u.length>this._nbTopCandidates&&u.pop();break}}}var v,E=u[0]||null,y=!1;if(null===E||"BODY"===E.tagName){for(E=t.createElement("DIV"),y=!0;e.firstChild;)this.log("Moving child out:",e.firstChild),E.appendChild(e.firstChild);e.appendChild(E),this._initializeNode(E)}else if(E){for(var T=[],A=1;A=.75&&T.push(this._getNodeAncestors(u[A]));if(T.length>=3)for(v=E.parentNode;"BODY"!==v.tagName;){for(var C=0,S=0;S=3){E=v;break}v=v.parentNode}E.readability||this._initializeNode(E),v=E.parentNode;for(var x=E.readability.contentScore,L=x/3;"BODY"!==v.tagName;)if(v.readability){var w=v.readability.contentScore;if(wx){E=v;break}x=v.readability.contentScore,v=v.parentNode}else v=v.parentNode;for(v=E.parentNode;"BODY"!=v.tagName&&1==v.children.length;)v=(E=v).parentNode;E.readability||this._initializeNode(E)}var I=t.createElement("DIV");i&&(I.id="readability-content");for(var R=Math.max(10,.2*E.readability.contentScore),O=(v=E.parentNode).children,D=0,P=O.length;D=R)B=!0;else if("P"===k.nodeName){var G=this._getLinkDensity(k),U=this._getInnerText(k),H=U.length;(H>80&&G<.25||H<80&&H>0&&0===G&&-1!==U.search(/\.( |$)/))&&(B=!0)}}B&&(this.log("Appending node:",k),-1===this.ALTER_TO_DIV_EXCEPTIONS.indexOf(k.nodeName)&&(this.log("Altering sibling:",k,"to div."),k=this._setNodeTag(k,"DIV")),I.appendChild(k),O=v.children,D-=1,P-=1)}if(this._debug&&this.log("Article content pre-prep: "+I.innerHTML),this._prepArticle(I),this._debug&&this.log("Article content post-prep: "+I.innerHTML),y)E.id="readability-page-1",E.className="page";else{var j=t.createElement("DIV");for(j.id="readability-page-1",j.className="page";I.firstChild;)j.appendChild(I.firstChild);I.appendChild(j)}this._debug&&this.log("Article content after paging: "+I.innerHTML);var W=!0,F=this._getInnerText(I,!0).length;if(F0&&e.length<100)},_unescapeHtmlEntities:function(e){if(!e)return e;var t=this.HTML_ESCAPE_MAP;return e.replace(/&(quot|amp|apos|lt|gt);/g,(function(e,i){return t[i]})).replace(/&#(?:x([0-9a-z]{1,4})|([0-9]{1,4}));/gi,(function(e,t,i){var r=parseInt(t||i,t?16:10);return String.fromCharCode(r)}))},_getJSONLD:function(e){var t,i=this._getAllNodesWithTag(e,["script"]);return this._forEachNode(i,(function(e){if(!t&&"application/ld+json"===e.getAttribute("type"))try{var i=e.textContent.replace(/^\s*\s*$/g,""),r=JSON.parse(i);if(!r["@context"]||!r["@context"].match(/^https?\:\/\/schema\.org$/))return;if(!r["@type"]&&Array.isArray(r["@graph"])&&(r=r["@graph"].find((function(e){return(e["@type"]||"").match(this.REGEXPS.jsonLdArticleTypes)}))),!r||!r["@type"]||!r["@type"].match(this.REGEXPS.jsonLdArticleTypes))return;if(t={},"string"==typeof r.name&&"string"==typeof r.headline&&r.name!==r.headline){var n=this._getArticleTitle(),a=this._textSimilarity(r.name,n)>.75,s=this._textSimilarity(r.headline,n)>.75;t.title=s&&!a?r.headline:r.name}else"string"==typeof r.name?t.title=r.name.trim():"string"==typeof r.headline&&(t.title=r.headline.trim());return r.author&&("string"==typeof r.author.name?t.byline=r.author.name.trim():Array.isArray(r.author)&&r.author[0]&&"string"==typeof r.author[0].name&&(t.byline=r.author.filter((function(e){return e&&"string"==typeof e.name})).map((function(e){return e.name.trim()})).join(", "))),"string"==typeof r.description&&(t.excerpt=r.description.trim()),r.publisher&&"string"==typeof r.publisher.name&&(t.siteName=r.publisher.name.trim()),void("string"==typeof r.datePublished&&(t.datePublished=r.datePublished.trim()))}catch(e){this.log(e.message)}})),t||{}},_getArticleMetadata:function(e){var t={},i={},r=this._doc.getElementsByTagName("meta"),n=/\s*(article|dc|dcterm|og|twitter)\s*:\s*(author|creator|description|published_time|title|site_name)\s*/gi,a=/^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|site_name)\s*$/i;return this._forEachNode(r,(function(e){var t=e.getAttribute("name"),r=e.getAttribute("property"),s=e.getAttribute("content");if(s){var o=null,l=null;r&&(o=r.match(n))&&(l=o[0].toLowerCase().replace(/\s/g,""),i[l]=s.trim()),!o&&t&&a.test(t)&&(l=t,s&&(l=l.toLowerCase().replace(/\s/g,"").replace(/\./g,":"),i[l]=s.trim()))}})),t.title=e.title||i["dc:title"]||i["dcterm:title"]||i["og:title"]||i["weibo:article:title"]||i["weibo:webpage:title"]||i.title||i["twitter:title"],t.title||(t.title=this._getArticleTitle()),t.byline=e.byline||i["dc:creator"]||i["dcterm:creator"]||i.author,t.excerpt=e.excerpt||i["dc:description"]||i["dcterm:description"]||i["og:description"]||i["weibo:article:description"]||i["weibo:webpage:description"]||i.description||i["twitter:description"],t.siteName=e.siteName||i["og:site_name"],t.publishedTime=e.datePublished||i["article:published_time"]||null,t.title=this._unescapeHtmlEntities(t.title),t.byline=this._unescapeHtmlEntities(t.byline),t.excerpt=this._unescapeHtmlEntities(t.excerpt),t.siteName=this._unescapeHtmlEntities(t.siteName),t.publishedTime=this._unescapeHtmlEntities(t.publishedTime),t},_isSingleImage:function(e){return"IMG"===e.tagName||1===e.children.length&&""===e.textContent.trim()&&this._isSingleImage(e.children[0])},_unwrapNoscriptImages:function(e){var t=Array.from(e.getElementsByTagName("img"));this._forEachNode(t,(function(e){for(var t=0;t0&&n>i)return!1;if(e.parentNode.tagName===t&&(!r||r(e.parentNode)))return!0;e=e.parentNode,n++}return!1},_getRowAndColumnCount:function(e){for(var t=0,i=0,r=e.getElementsByTagName("tr"),n=0;n0)r._readabilityDataTable=!0;else{if(["col","colgroup","tfoot","thead","th"].some((function(e){return!!r.getElementsByTagName(e)[0]})))this.log("Data table because found data-y descendant"),r._readabilityDataTable=!0;else if(r.getElementsByTagName("table")[0])r._readabilityDataTable=!1;else{var a=this._getRowAndColumnCount(r);a.rows>=10||a.columns>4?r._readabilityDataTable=!0:r._readabilityDataTable=a.rows*a.columns>10}}}else r._readabilityDataTable=!1;else r._readabilityDataTable=!1}},_fixLazyImages:function(e){this._forEachNode(this._getAllNodesWithTag(e,["img","picture","figure"]),(function(e){if(e.src&&this.REGEXPS.b64DataUrl.test(e.src)){if("image/svg+xml"===this.REGEXPS.b64DataUrl.exec(e.src)[1])return;for(var t=!1,i=0;ir+=this._getInnerText(e,!0).length)),r/i},_cleanConditionally:function(e,t){this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)&&this._removeNodes(this._getAllNodesWithTag(e,[t]),(function(e){var i=function(e){return e._readabilityDataTable},r="ul"===t||"ol"===t;if(!r){var n=0,a=this._getAllNodesWithTag(e,["ul","ol"]);this._forEachNode(a,(e=>n+=this._getInnerText(e).length)),r=n/this._getInnerText(e).length>.9}if("table"===t&&i(e))return!1;if(this._hasAncestorTag(e,"table",-1,i))return!1;if(this._hasAncestorTag(e,"code"))return!1;var s=this._getClassWeight(e);this.log("Cleaning Conditionally",e);if(s+0<0)return!0;if(this._getCharCount(e,",")<10){for(var o=e.getElementsByTagName("p").length,l=e.getElementsByTagName("img").length,c=e.getElementsByTagName("li").length-100,h=e.getElementsByTagName("input").length,d=this._getTextDensity(e,["h1","h2","h3","h4","h5","h6"]),g=0,u=this._getAllNodesWithTag(e,["object","embed","iframe"]),m=0;m1&&o/l<.5&&!this._hasAncestorTag(e,"figure")||!r&&c>o||h>Math.floor(o/3)||!r&&d<.9&&_<25&&(0===l||l>2)&&!this._hasAncestorTag(e,"figure")||!r&&s<25&&p>.2||s>=25&&p>.5||1===g&&_<75||g>1;if(r&&b){for(var N=0;N1)return b}if(l==e.getElementsByTagName("li").length)return!1}return b}return!1}))},_cleanMatchedNodes:function(e,t){for(var i=this._getNextNode(e,!0),r=this._getNextNode(e);r&&r!=i;)r=t.call(this,r,r.className+" "+r.id)?this._removeAndGetNext(r):this._getNextNode(r)},_cleanHeaders:function(e){let t=this._getAllNodesWithTag(e,["h1","h2"]);this._removeNodes(t,(function(e){let t=this._getClassWeight(e)<0;return t&&this.log("Removing header with low class weight:",e),t}))},_headerDuplicatesTitle:function(e){if("H1"!=e.tagName&&"H2"!=e.tagName)return!1;var t=this._getInnerText(e,!1);return this.log("Evaluating similarity of header:",t,this._articleTitle),this._textSimilarity(this._articleTitle,t)>.75},_flagIsActive:function(e){return(this._flags&e)>0},_removeFlag:function(e){this._flags=this._flags&~e},_isProbablyVisible:function(e){return(!e.style||"none"!=e.style.display)&&(!e.style||"hidden"!=e.style.visibility)&&!e.hasAttribute("hidden")&&(!e.hasAttribute("aria-hidden")||"true"!=e.getAttribute("aria-hidden")||e.className&&e.className.indexOf&&-1!==e.className.indexOf("fallback-image"))},parse:function(){if(this._maxElemsToParse>0){var e=this._doc.getElementsByTagName("*").length;if(e>this._maxElemsToParse)throw new Error("Aborting parsing document; "+e+" elements found")}this._unwrapNoscriptImages(this._doc);var t=this._disableJSONLD?{}:this._getJSONLD(this._doc);this._removeScripts(this._doc),this._prepDocument();var i=this._getArticleMetadata(t);this._articleTitle=i.title;var r=this._grabArticle();if(!r)return null;if(this.log("Grabbed: "+r.innerHTML),this._postProcessContent(r),!i.excerpt){var n=r.getElementsByTagName("p");n.length>0&&(i.excerpt=n[0].textContent.trim())}var a=r.textContent;return{title:this._articleTitle,byline:i.byline||this._articleByline,dir:this._articleDir,lang:this._articleLang,content:this._serializer(r),textContent:a,length:a.length,excerpt:i.excerpt,siteName:i.siteName||this._articleSiteName,publishedTime:i.publishedTime}}},e.exports=t}(c)),c.exports}var d,g,u,m={exports:{}};var f=function(){if(u)return g;u=1;var e=h(),t=(d||(d=1,function(){var e={unlikelyCandidates:/-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,okMaybeItsACandidate:/and|article|body|column|content|main|shadow/i};function t(e){return(!e.style||"none"!=e.style.display)&&!e.hasAttribute("hidden")&&(!e.hasAttribute("aria-hidden")||"true"!=e.getAttribute("aria-hidden")||e.className&&e.className.indexOf&&-1!==e.className.indexOf("fallback-image"))}m.exports=function(i,r={}){"function"==typeof r&&(r={visibilityChecker:r});var n={minScore:20,minContentLength:140,visibilityChecker:t};r=Object.assign(n,r);var a=i.querySelectorAll("p, pre, article"),s=i.querySelectorAll("div > br");if(s.length){var o=new Set(a);[].forEach.call(s,(function(e){o.add(e.parentNode)})),a=Array.from(o)}var l=0;return[].some.call(a,(function(t){if(!r.visibilityChecker(t))return!1;var i=t.className+" "+t.id;if(e.unlikelyCandidates.test(i)&&!e.okMaybeItsACandidate.test(i))return!1;if(t.matches("li p"))return!1;var n=t.textContent.trim().length;return!(nr.minScore}))}}()),m.exports);return g={Readability:e,isProbablyReaderable:t}}(),p=function(e,t,i,r){return new(i||(i=Promise))((function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((r=r.apply(e,t||[])).next())}))};const _=["you are human","are you human","i'm not a robot","recaptcha"],b=e=>p(void 0,[e],void 0,(function*({article:e,browser:t,filterWords:i,logger:n}){var a;try{const s=yield t.newPage();yield s.goto(e.link,{waitUntil:"networkidle2"});const o=yield s.evaluate((()=>document.documentElement.innerHTML)),l=null!==(a=yield s.evaluate((()=>{const e=document.querySelector('link[rel="icon"], link[rel="shortcut icon"]');return e?e.getAttribute("href"):""})))&&void 0!==a?a:"",c=new r.VirtualConsole;c.on("error",n.error);const h=new r.JSDOM(o,{url:e.link,virtualConsole:c});const d=new f.Readability(h.window.document).parse();if(!d||!d.textContent)return n.warn("Article content could not be parsed or is empty.",{article:e}),Object.assign(Object.assign({},e),{content:"",favicon:l});if(_.find((e=>d.textContent.toLowerCase().includes(e))))return n.warn("Article requires human verification.",{article:e}),Object.assign(Object.assign({},e),{content:"",favicon:l});const g=N(d.textContent,i);return g.split(" ").length<100?(n.warn("Article content is too short and likely not valuable.",{article:e}),Object.assign(Object.assign({},e),{content:"",favicon:l})):(n.info("SUCCESSFULLY SCRAPED ARTICLE CONTENT:",g),Object.assign(Object.assign({},e),{content:g,favicon:l}))}catch(t){return n.error(t),Object.assign(Object.assign({},e),{content:"",favicon:""})}})),N=(e,t)=>{const i=["subscribe now","sign up","newsletter","subscribe now","sign up for our newsletter","exclusive offer","limited time offer","free trial","download now","join now","register today","special promotion","promotional offer","discount code","early access","sneak peek","save now","don't miss out","act now","last chance","expires soon","giveaway","free access","premium access","unlock full access","buy now","learn more","click here","follow us on","share this article","connect with us","advertisement","sponsored content","partner content","affiliate links","click here","for more information","you may also like","we think you'll like","from our network",...t];return e.split("\n").map((e=>e.trim())).filter((e=>e.split(" ").length>4)).filter((e=>!i.some((t=>e.toLowerCase().includes(t))))).join("\n")};var v=function(e,t,i,r){return new(i||(i=Promise))((function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((r=r.apply(e,t||[])).next())}))};module.exports=t=>v(void 0,void 0,void 0,(function*(){var i,r;const n=Object.assign({prettyURLs:!0,getArticleContent:!1,puppeteerArgs:[],puppeteerHeadlessMode:!0,logLevel:"error",timeframe:"7d",queryVars:{},limit:99},t),s=o(n.logLevel),l=n.queryVars?Object.assign(Object.assign({},n.queryVars),{when:n.timeframe}):{when:n.timeframe};t.searchTerm&&(l.q=t.searchTerm);const c=null!==(h=l,i=0===Object.keys(h).length?"":Object.keys(h).reduce(((e,t,i)=>`${e}${0===i?"?":"&"}${t}=${h[t]}`),""))&&void 0!==i?i:"";var h;const d=`${null!==(r=n.baseUrl)&&void 0!==r?r:"https://news.google.com/search"}${c}`;s.info(`📰 SCRAPING NEWS FROM: ${d}`);const g={headless:t.puppeteerHeadlessMode,args:e.defaultArgs().concat(n.puppeteerArgs).filter(Boolean).concat(["--disable-extensions-except=/path/to/manifest/folder/","--load-extension=/path/to/manifest/folder/"])},u=yield e.launch(g),m=yield u.newPage();m.setViewport({width:1366,height:768}),m.setUserAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"),m.setRequestInterception(!0),m.on("request",(e=>{if(!e.isNavigationRequest())return void e.continue();const t=e.headers();t.Accept="text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",t["Accept-Encoding"]="gzip",t["Accept-Language"]="en-US,en;q=0.9,es;q=0.8",t["Upgrade-Insecure-Requests"]="1",t.Referer="https://www.google.com/",e.continue({headers:t})})),yield m.setCookie({name:"CONSENT",value:`YES+cb.${(new Date).toISOString().split("T")[0].replace(/-/g,"")}-04-p0.en-GB+FX+667`,domain:".google.com"}),yield m.goto(d,{waitUntil:"networkidle2"});try{yield m.$('[aria-label="Reject all"]'),yield Promise.all([m.click('[aria-label="Reject all"]'),m.waitForNavigation({waitUntil:"networkidle2"})])}catch(e){}const f=yield m.content(),_=a.load(f),N=_("article");let v=[];if(_(N).each((function(){var e,t,i,r,n,a,s,o,l;const c=(null===(i=null===(t=null===(e=_(this))||void 0===e?void 0:e.find('a[href^="./article"]'))||void 0===t?void 0:t.attr("href"))||void 0===i?void 0:i.replace("./","https://news.google.com/"))||(null===(a=null===(n=null===(r=_(this))||void 0===r?void 0:r.find('a[href^="./read"]'))||void 0===n?void 0:n.attr("href"))||void 0===a?void 0:a.replace("./","https://news.google.com/"))||"",h=null===(s=_(this).find("figure").find("img").attr("srcset"))||void 0===s?void 0:s.split(" "),d=h&&h.length?h[h.length-2]:_(this).find("figure").find("img").attr("src"),g=(u=_(this)).find("h4").text()||u.find("div > div + div > div a").text()?"regular":u.find("figure").length?"topicFeatured":u.find("> a").text()?"topicSmall":"";var u;const m=((e,t)=>{var i,r;try{switch(t){case"regular":return e.find("h4").text()||e.find("div > div + div > div a").text()||"";case"topicFeatured":return e.find("a[target=_blank]").text()||(null===(i=e.find("button").attr("aria-label"))||void 0===i?void 0:i.replace("More - ",""))||"";case"topicSmall":return e.find("a[target=_blank]").text()||(null===(r=e.find("button").attr("aria-label"))||void 0===r?void 0:r.replace("More - ",""))||"";default:return""}}catch(e){return""}})(_(this),g),f={title:m,link:c,image:(null==d?void 0:d.startsWith("/"))?`https://news.google.com${d}`:d||"",source:_(this).find("div[data-n-tid]").text()||"",datetime:(null===(l=new Date((null===(o=_(this).find("div:last-child time"))||void 0===o?void 0:o.attr("datetime"))||""))||void 0===l?void 0:l.toISOString())||"",time:_(this).find("div:last-child time").text()||"",articleType:g};v.push(f)})),n.prettyURLs&&(v=yield Promise.all(v.map((e=>{const t=(e=>{var t,i;try{let r=e.split("read/")[1].split("?")[0];r.startsWith("CB")&&(r=r.substring(2)),r=r.replace(/-/g,"+").replace(/_/g,"/"),r+="=".repeat((4-r.length%4)%4);const n=atob(r);let a=(null!==(i=null===(t=null==n?void 0:n.match(/[A-Za-z0-9\-_]+/g))||void 0===t?void 0:t.join(""))&&void 0!==i?i:"").replace(/-/g,"+").replace(/_/g,"/");a+="=".repeat((4-a.length%4)%4);const s=atob(a);return console.log("Final URL:",s),s}catch(e){return console.error("Error decoding URL:",e),null}})(e.link);return t&&(e.link=t),e})))),n.getArticleContent){const e=n.filterWords||[];v=yield(e=>p(void 0,[e],void 0,(function*({articles:e,browser:t,filterWords:i,logger:r}){try{const n=e.map((e=>b({article:e,browser:t,filterWords:i,logger:r})));return yield Promise.all(n)}catch(t){return r.error("getArticleContent ERROR:",t),e}})))({articles:v,browser:u,filterWords:e,logger:s})}yield m.close(),yield u.close();const E=v.filter((e=>e.title));return n.limit (winston.createLogger({\n levels: config.levels,\n format: winston.format.combine(winston.format.colorize(), winston.format.simple()),\n transports: [\n new winston.transports.Console()\n ],\n level\n}));\nexport default getLogger;\n","/*\n * Copyright (c) 2010 Arc90 Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*\n * This code is heavily based on Arc90's readability.js (1.7.1) script\n * available at: http://code.google.com/p/arc90labs-readability\n */\n\n/**\n * Public constructor.\n * @param {HTMLDocument} doc The document to parse.\n * @param {Object} options The options object.\n */\nfunction Readability(doc, options) {\n // In some older versions, people passed a URI as the first argument. Cope:\n if (options && options.documentElement) {\n doc = options;\n options = arguments[2];\n } else if (!doc || !doc.documentElement) {\n throw new Error(\"First argument to Readability constructor should be a document object.\");\n }\n options = options || {};\n\n this._doc = doc;\n this._docJSDOMParser = this._doc.firstChild.__JSDOMParser__;\n this._articleTitle = null;\n this._articleByline = null;\n this._articleDir = null;\n this._articleSiteName = null;\n this._attempts = [];\n\n // Configurable options\n this._debug = !!options.debug;\n this._maxElemsToParse = options.maxElemsToParse || this.DEFAULT_MAX_ELEMS_TO_PARSE;\n this._nbTopCandidates = options.nbTopCandidates || this.DEFAULT_N_TOP_CANDIDATES;\n this._charThreshold = options.charThreshold || this.DEFAULT_CHAR_THRESHOLD;\n this._classesToPreserve = this.CLASSES_TO_PRESERVE.concat(options.classesToPreserve || []);\n this._keepClasses = !!options.keepClasses;\n this._serializer = options.serializer || function(el) {\n return el.innerHTML;\n };\n this._disableJSONLD = !!options.disableJSONLD;\n this._allowedVideoRegex = options.allowedVideoRegex || this.REGEXPS.videos;\n\n // Start with all flags set\n this._flags = this.FLAG_STRIP_UNLIKELYS |\n this.FLAG_WEIGHT_CLASSES |\n this.FLAG_CLEAN_CONDITIONALLY;\n\n\n // Control whether log messages are sent to the console\n if (this._debug) {\n let logNode = function(node) {\n if (node.nodeType == node.TEXT_NODE) {\n return `${node.nodeName} (\"${node.textContent}\")`;\n }\n let attrPairs = Array.from(node.attributes || [], function(attr) {\n return `${attr.name}=\"${attr.value}\"`;\n }).join(\" \");\n return `<${node.localName} ${attrPairs}>`;\n };\n this.log = function () {\n if (typeof console !== \"undefined\") {\n let args = Array.from(arguments, arg => {\n if (arg && arg.nodeType == this.ELEMENT_NODE) {\n return logNode(arg);\n }\n return arg;\n });\n args.unshift(\"Reader: (Readability)\");\n console.log.apply(console, args);\n } else if (typeof dump !== \"undefined\") {\n /* global dump */\n var msg = Array.prototype.map.call(arguments, function(x) {\n return (x && x.nodeName) ? logNode(x) : x;\n }).join(\" \");\n dump(\"Reader: (Readability) \" + msg + \"\\n\");\n }\n };\n } else {\n this.log = function () {};\n }\n}\n\nReadability.prototype = {\n FLAG_STRIP_UNLIKELYS: 0x1,\n FLAG_WEIGHT_CLASSES: 0x2,\n FLAG_CLEAN_CONDITIONALLY: 0x4,\n\n // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\n ELEMENT_NODE: 1,\n TEXT_NODE: 3,\n\n // Max number of nodes supported by this parser. Default: 0 (no limit)\n DEFAULT_MAX_ELEMS_TO_PARSE: 0,\n\n // The number of top candidates to consider when analysing how\n // tight the competition is among candidates.\n DEFAULT_N_TOP_CANDIDATES: 5,\n\n // Element tags to score by default.\n DEFAULT_TAGS_TO_SCORE: \"section,h2,h3,h4,h5,h6,p,td,pre\".toUpperCase().split(\",\"),\n\n // The default number of chars an article must have in order to return a result\n DEFAULT_CHAR_THRESHOLD: 500,\n\n // All of the regular expressions in use within readability.\n // Defined up here so we don't instantiate them repeatedly in loops.\n REGEXPS: {\n // NOTE: These two regular expressions are duplicated in\n // Readability-readerable.js. Please keep both copies in sync.\n unlikelyCandidates: /-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,\n okMaybeItsACandidate: /and|article|body|column|content|main|shadow/i,\n\n positive: /article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i,\n negative: /-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|foot|footer|footnote|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget/i,\n extraneous: /print|archive|comment|discuss|e[\\-]?mail|share|reply|all|login|sign|single|utility/i,\n byline: /byline|author|dateline|writtenby|p-author/i,\n replaceFonts: /<(\\/?)font[^>]*>/gi,\n normalize: /\\s{2,}/g,\n videos: /\\/\\/(www\\.)?((dailymotion|youtube|youtube-nocookie|player\\.vimeo|v\\.qq)\\.com|(archive|upload\\.wikimedia)\\.org|player\\.twitch\\.tv)/i,\n shareElements: /(\\b|_)(share|sharedaddy)(\\b|_)/i,\n nextLink: /(next|weiter|continue|>([^\\|]|$)|»([^\\|]|$))/i,\n prevLink: /(prev|earl|old|new|<|«)/i,\n tokenize: /\\W+/g,\n whitespace: /^\\s*$/,\n hasContent: /\\S$/,\n hashUrl: /^#.+/,\n srcsetUrl: /(\\S+)(\\s+[\\d.]+[xw])?(\\s*(?:,|$))/g,\n b64DataUrl: /^data:\\s*([^\\s;,]+)\\s*;\\s*base64\\s*,/i,\n // Commas as used in Latin, Sindhi, Chinese and various other scripts.\n // see: https://en.wikipedia.org/wiki/Comma#Comma_variants\n commas: /\\u002C|\\u060C|\\uFE50|\\uFE10|\\uFE11|\\u2E41|\\u2E34|\\u2E32|\\uFF0C/g,\n // See: https://schema.org/Article\n jsonLdArticleTypes: /^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/\n },\n\n UNLIKELY_ROLES: [ \"menu\", \"menubar\", \"complementary\", \"navigation\", \"alert\", \"alertdialog\", \"dialog\" ],\n\n DIV_TO_P_ELEMS: new Set([ \"BLOCKQUOTE\", \"DL\", \"DIV\", \"IMG\", \"OL\", \"P\", \"PRE\", \"TABLE\", \"UL\" ]),\n\n ALTER_TO_DIV_EXCEPTIONS: [\"DIV\", \"ARTICLE\", \"SECTION\", \"P\"],\n\n PRESENTATIONAL_ATTRIBUTES: [ \"align\", \"background\", \"bgcolor\", \"border\", \"cellpadding\", \"cellspacing\", \"frame\", \"hspace\", \"rules\", \"style\", \"valign\", \"vspace\" ],\n\n DEPRECATED_SIZE_ATTRIBUTE_ELEMS: [ \"TABLE\", \"TH\", \"TD\", \"HR\", \"PRE\" ],\n\n // The commented out elements qualify as phrasing content but tend to be\n // removed by readability when put into paragraphs, so we ignore them here.\n PHRASING_ELEMS: [\n // \"CANVAS\", \"IFRAME\", \"SVG\", \"VIDEO\",\n \"ABBR\", \"AUDIO\", \"B\", \"BDO\", \"BR\", \"BUTTON\", \"CITE\", \"CODE\", \"DATA\",\n \"DATALIST\", \"DFN\", \"EM\", \"EMBED\", \"I\", \"IMG\", \"INPUT\", \"KBD\", \"LABEL\",\n \"MARK\", \"MATH\", \"METER\", \"NOSCRIPT\", \"OBJECT\", \"OUTPUT\", \"PROGRESS\", \"Q\",\n \"RUBY\", \"SAMP\", \"SCRIPT\", \"SELECT\", \"SMALL\", \"SPAN\", \"STRONG\", \"SUB\",\n \"SUP\", \"TEXTAREA\", \"TIME\", \"VAR\", \"WBR\"\n ],\n\n // These are the classes that readability sets itself.\n CLASSES_TO_PRESERVE: [ \"page\" ],\n\n // These are the list of HTML entities that need to be escaped.\n HTML_ESCAPE_MAP: {\n \"lt\": \"<\",\n \"gt\": \">\",\n \"amp\": \"&\",\n \"quot\": '\"',\n \"apos\": \"'\",\n },\n\n /**\n * Run any post-process modifications to article content as necessary.\n *\n * @param Element\n * @return void\n **/\n _postProcessContent: function(articleContent) {\n // Readability cannot open relative uris so we convert them to absolute uris.\n this._fixRelativeUris(articleContent);\n\n this._simplifyNestedElements(articleContent);\n\n if (!this._keepClasses) {\n // Remove classes.\n this._cleanClasses(articleContent);\n }\n },\n\n /**\n * Iterates over a NodeList, calls `filterFn` for each node and removes node\n * if function returned `true`.\n *\n * If function is not passed, removes all the nodes in node list.\n *\n * @param NodeList nodeList The nodes to operate on\n * @param Function filterFn the function to use as a filter\n * @return void\n */\n _removeNodes: function(nodeList, filterFn) {\n // Avoid ever operating on live node lists.\n if (this._docJSDOMParser && nodeList._isLiveNodeList) {\n throw new Error(\"Do not pass live node lists to _removeNodes\");\n }\n for (var i = nodeList.length - 1; i >= 0; i--) {\n var node = nodeList[i];\n var parentNode = node.parentNode;\n if (parentNode) {\n if (!filterFn || filterFn.call(this, node, i, nodeList)) {\n parentNode.removeChild(node);\n }\n }\n }\n },\n\n /**\n * Iterates over a NodeList, and calls _setNodeTag for each node.\n *\n * @param NodeList nodeList The nodes to operate on\n * @param String newTagName the new tag name to use\n * @return void\n */\n _replaceNodeTags: function(nodeList, newTagName) {\n // Avoid ever operating on live node lists.\n if (this._docJSDOMParser && nodeList._isLiveNodeList) {\n throw new Error(\"Do not pass live node lists to _replaceNodeTags\");\n }\n for (const node of nodeList) {\n this._setNodeTag(node, newTagName);\n }\n },\n\n /**\n * Iterate over a NodeList, which doesn't natively fully implement the Array\n * interface.\n *\n * For convenience, the current object context is applied to the provided\n * iterate function.\n *\n * @param NodeList nodeList The NodeList.\n * @param Function fn The iterate function.\n * @return void\n */\n _forEachNode: function(nodeList, fn) {\n Array.prototype.forEach.call(nodeList, fn, this);\n },\n\n /**\n * Iterate over a NodeList, and return the first node that passes\n * the supplied test function\n *\n * For convenience, the current object context is applied to the provided\n * test function.\n *\n * @param NodeList nodeList The NodeList.\n * @param Function fn The test function.\n * @return void\n */\n _findNode: function(nodeList, fn) {\n return Array.prototype.find.call(nodeList, fn, this);\n },\n\n /**\n * Iterate over a NodeList, return true if any of the provided iterate\n * function calls returns true, false otherwise.\n *\n * For convenience, the current object context is applied to the\n * provided iterate function.\n *\n * @param NodeList nodeList The NodeList.\n * @param Function fn The iterate function.\n * @return Boolean\n */\n _someNode: function(nodeList, fn) {\n return Array.prototype.some.call(nodeList, fn, this);\n },\n\n /**\n * Iterate over a NodeList, return true if all of the provided iterate\n * function calls return true, false otherwise.\n *\n * For convenience, the current object context is applied to the\n * provided iterate function.\n *\n * @param NodeList nodeList The NodeList.\n * @param Function fn The iterate function.\n * @return Boolean\n */\n _everyNode: function(nodeList, fn) {\n return Array.prototype.every.call(nodeList, fn, this);\n },\n\n /**\n * Concat all nodelists passed as arguments.\n *\n * @return ...NodeList\n * @return Array\n */\n _concatNodeLists: function() {\n var slice = Array.prototype.slice;\n var args = slice.call(arguments);\n var nodeLists = args.map(function(list) {\n return slice.call(list);\n });\n return Array.prototype.concat.apply([], nodeLists);\n },\n\n _getAllNodesWithTag: function(node, tagNames) {\n if (node.querySelectorAll) {\n return node.querySelectorAll(tagNames.join(\",\"));\n }\n return [].concat.apply([], tagNames.map(function(tag) {\n var collection = node.getElementsByTagName(tag);\n return Array.isArray(collection) ? collection : Array.from(collection);\n }));\n },\n\n /**\n * Removes the class=\"\" attribute from every element in the given\n * subtree, except those that match CLASSES_TO_PRESERVE and\n * the classesToPreserve array from the options object.\n *\n * @param Element\n * @return void\n */\n _cleanClasses: function(node) {\n var classesToPreserve = this._classesToPreserve;\n var className = (node.getAttribute(\"class\") || \"\")\n .split(/\\s+/)\n .filter(function(cls) {\n return classesToPreserve.indexOf(cls) != -1;\n })\n .join(\" \");\n\n if (className) {\n node.setAttribute(\"class\", className);\n } else {\n node.removeAttribute(\"class\");\n }\n\n for (node = node.firstElementChild; node; node = node.nextElementSibling) {\n this._cleanClasses(node);\n }\n },\n\n /**\n * Converts each and uri in the given element to an absolute URI,\n * ignoring #ref URIs.\n *\n * @param Element\n * @return void\n */\n _fixRelativeUris: function(articleContent) {\n var baseURI = this._doc.baseURI;\n var documentURI = this._doc.documentURI;\n function toAbsoluteURI(uri) {\n // Leave hash links alone if the base URI matches the document URI:\n if (baseURI == documentURI && uri.charAt(0) == \"#\") {\n return uri;\n }\n\n // Otherwise, resolve against base URI:\n try {\n return new URL(uri, baseURI).href;\n } catch (ex) {\n // Something went wrong, just return the original:\n }\n return uri;\n }\n\n var links = this._getAllNodesWithTag(articleContent, [\"a\"]);\n this._forEachNode(links, function(link) {\n var href = link.getAttribute(\"href\");\n if (href) {\n // Remove links with javascript: URIs, since\n // they won't work after scripts have been removed from the page.\n if (href.indexOf(\"javascript:\") === 0) {\n // if the link only contains simple text content, it can be converted to a text node\n if (link.childNodes.length === 1 && link.childNodes[0].nodeType === this.TEXT_NODE) {\n var text = this._doc.createTextNode(link.textContent);\n link.parentNode.replaceChild(text, link);\n } else {\n // if the link has multiple children, they should all be preserved\n var container = this._doc.createElement(\"span\");\n while (link.firstChild) {\n container.appendChild(link.firstChild);\n }\n link.parentNode.replaceChild(container, link);\n }\n } else {\n link.setAttribute(\"href\", toAbsoluteURI(href));\n }\n }\n });\n\n var medias = this._getAllNodesWithTag(articleContent, [\n \"img\", \"picture\", \"figure\", \"video\", \"audio\", \"source\"\n ]);\n\n this._forEachNode(medias, function(media) {\n var src = media.getAttribute(\"src\");\n var poster = media.getAttribute(\"poster\");\n var srcset = media.getAttribute(\"srcset\");\n\n if (src) {\n media.setAttribute(\"src\", toAbsoluteURI(src));\n }\n\n if (poster) {\n media.setAttribute(\"poster\", toAbsoluteURI(poster));\n }\n\n if (srcset) {\n var newSrcset = srcset.replace(this.REGEXPS.srcsetUrl, function(_, p1, p2, p3) {\n return toAbsoluteURI(p1) + (p2 || \"\") + p3;\n });\n\n media.setAttribute(\"srcset\", newSrcset);\n }\n });\n },\n\n _simplifyNestedElements: function(articleContent) {\n var node = articleContent;\n\n while (node) {\n if (node.parentNode && [\"DIV\", \"SECTION\"].includes(node.tagName) && !(node.id && node.id.startsWith(\"readability\"))) {\n if (this._isElementWithoutContent(node)) {\n node = this._removeAndGetNext(node);\n continue;\n } else if (this._hasSingleTagInsideElement(node, \"DIV\") || this._hasSingleTagInsideElement(node, \"SECTION\")) {\n var child = node.children[0];\n for (var i = 0; i < node.attributes.length; i++) {\n child.setAttribute(node.attributes[i].name, node.attributes[i].value);\n }\n node.parentNode.replaceChild(child, node);\n node = child;\n continue;\n }\n }\n\n node = this._getNextNode(node);\n }\n },\n\n /**\n * Get the article title as an H1.\n *\n * @return string\n **/\n _getArticleTitle: function() {\n var doc = this._doc;\n var curTitle = \"\";\n var origTitle = \"\";\n\n try {\n curTitle = origTitle = doc.title.trim();\n\n // If they had an element with id \"title\" in their HTML\n if (typeof curTitle !== \"string\")\n curTitle = origTitle = this._getInnerText(doc.getElementsByTagName(\"title\")[0]);\n } catch (e) {/* ignore exceptions setting the title. */}\n\n var titleHadHierarchicalSeparators = false;\n function wordCount(str) {\n return str.split(/\\s+/).length;\n }\n\n // If there's a separator in the title, first remove the final part\n if ((/ [\\|\\-\\\\\\/>»] /).test(curTitle)) {\n titleHadHierarchicalSeparators = / [\\\\\\/>»] /.test(curTitle);\n curTitle = origTitle.replace(/(.*)[\\|\\-\\\\\\/>»] .*/gi, \"$1\");\n\n // If the resulting title is too short (3 words or fewer), remove\n // the first part instead:\n if (wordCount(curTitle) < 3)\n curTitle = origTitle.replace(/[^\\|\\-\\\\\\/>»]*[\\|\\-\\\\\\/>»](.*)/gi, \"$1\");\n } else if (curTitle.indexOf(\": \") !== -1) {\n // Check if we have an heading containing this exact string, so we\n // could assume it's the full title.\n var headings = this._concatNodeLists(\n doc.getElementsByTagName(\"h1\"),\n doc.getElementsByTagName(\"h2\")\n );\n var trimmedTitle = curTitle.trim();\n var match = this._someNode(headings, function(heading) {\n return heading.textContent.trim() === trimmedTitle;\n });\n\n // If we don't, let's extract the title out of the original title string.\n if (!match) {\n curTitle = origTitle.substring(origTitle.lastIndexOf(\":\") + 1);\n\n // If the title is now too short, try the first colon instead:\n if (wordCount(curTitle) < 3) {\n curTitle = origTitle.substring(origTitle.indexOf(\":\") + 1);\n // But if we have too many words before the colon there's something weird\n // with the titles and the H tags so let's just use the original title instead\n } else if (wordCount(origTitle.substr(0, origTitle.indexOf(\":\"))) > 5) {\n curTitle = origTitle;\n }\n }\n } else if (curTitle.length > 150 || curTitle.length < 15) {\n var hOnes = doc.getElementsByTagName(\"h1\");\n\n if (hOnes.length === 1)\n curTitle = this._getInnerText(hOnes[0]);\n }\n\n curTitle = curTitle.trim().replace(this.REGEXPS.normalize, \" \");\n // If we now have 4 words or fewer as our title, and either no\n // 'hierarchical' separators (\\, /, > or ») were found in the original\n // title or we decreased the number of words by more than 1 word, use\n // the original title.\n var curTitleWordCount = wordCount(curTitle);\n if (curTitleWordCount <= 4 &&\n (!titleHadHierarchicalSeparators ||\n curTitleWordCount != wordCount(origTitle.replace(/[\\|\\-\\\\\\/>»]+/g, \"\")) - 1)) {\n curTitle = origTitle;\n }\n\n return curTitle;\n },\n\n /**\n * Prepare the HTML document for readability to scrape it.\n * This includes things like stripping javascript, CSS, and handling terrible markup.\n *\n * @return void\n **/\n _prepDocument: function() {\n var doc = this._doc;\n\n // Remove all style tags in head\n this._removeNodes(this._getAllNodesWithTag(doc, [\"style\"]));\n\n if (doc.body) {\n this._replaceBrs(doc.body);\n }\n\n this._replaceNodeTags(this._getAllNodesWithTag(doc, [\"font\"]), \"SPAN\");\n },\n\n /**\n * Finds the next node, starting from the given node, and ignoring\n * whitespace in between. If the given node is an element, the same node is\n * returned.\n */\n _nextNode: function (node) {\n var next = node;\n while (next\n && (next.nodeType != this.ELEMENT_NODE)\n && this.REGEXPS.whitespace.test(next.textContent)) {\n next = next.nextSibling;\n }\n return next;\n },\n\n /**\n * Replaces 2 or more successive
elements with a single

.\n * Whitespace between
elements are ignored. For example:\n *

foo
bar


abc
\n * will become:\n *
foo
bar

abc

\n */\n _replaceBrs: function (elem) {\n this._forEachNode(this._getAllNodesWithTag(elem, [\"br\"]), function(br) {\n var next = br.nextSibling;\n\n // Whether 2 or more
elements have been found and replaced with a\n //

block.\n var replaced = false;\n\n // If we find a
chain, remove the
s until we hit another node\n // or non-whitespace. This leaves behind the first
in the chain\n // (which will be replaced with a

later).\n while ((next = this._nextNode(next)) && (next.tagName == \"BR\")) {\n replaced = true;\n var brSibling = next.nextSibling;\n next.parentNode.removeChild(next);\n next = brSibling;\n }\n\n // If we removed a
chain, replace the remaining
with a

. Add\n // all sibling nodes as children of the

until we hit another
\n // chain.\n if (replaced) {\n var p = this._doc.createElement(\"p\");\n br.parentNode.replaceChild(p, br);\n\n next = p.nextSibling;\n while (next) {\n // If we've hit another

, we're done adding children to this

.\n if (next.tagName == \"BR\") {\n var nextElem = this._nextNode(next.nextSibling);\n if (nextElem && nextElem.tagName == \"BR\")\n break;\n }\n\n if (!this._isPhrasingContent(next))\n break;\n\n // Otherwise, make this node a child of the new

.\n var sibling = next.nextSibling;\n p.appendChild(next);\n next = sibling;\n }\n\n while (p.lastChild && this._isWhitespace(p.lastChild)) {\n p.removeChild(p.lastChild);\n }\n\n if (p.parentNode.tagName === \"P\")\n this._setNodeTag(p.parentNode, \"DIV\");\n }\n });\n },\n\n _setNodeTag: function (node, tag) {\n this.log(\"_setNodeTag\", node, tag);\n if (this._docJSDOMParser) {\n node.localName = tag.toLowerCase();\n node.tagName = tag.toUpperCase();\n return node;\n }\n\n var replacement = node.ownerDocument.createElement(tag);\n while (node.firstChild) {\n replacement.appendChild(node.firstChild);\n }\n node.parentNode.replaceChild(replacement, node);\n if (node.readability)\n replacement.readability = node.readability;\n\n for (var i = 0; i < node.attributes.length; i++) {\n try {\n replacement.setAttribute(node.attributes[i].name, node.attributes[i].value);\n } catch (ex) {\n /* it's possible for setAttribute() to throw if the attribute name\n * isn't a valid XML Name. Such attributes can however be parsed from\n * source in HTML docs, see https://github.com/whatwg/html/issues/4275,\n * so we can hit them here and then throw. We don't care about such\n * attributes so we ignore them.\n */\n }\n }\n return replacement;\n },\n\n /**\n * Prepare the article node for display. Clean out any inline styles,\n * iframes, forms, strip extraneous

tags, etc.\n *\n * @param Element\n * @return void\n **/\n _prepArticle: function(articleContent) {\n this._cleanStyles(articleContent);\n\n // Check for data tables before we continue, to avoid removing items in\n // those tables, which will often be isolated even though they're\n // visually linked to other content-ful elements (text, images, etc.).\n this._markDataTables(articleContent);\n\n this._fixLazyImages(articleContent);\n\n // Clean out junk from the article content\n this._cleanConditionally(articleContent, \"form\");\n this._cleanConditionally(articleContent, \"fieldset\");\n this._clean(articleContent, \"object\");\n this._clean(articleContent, \"embed\");\n this._clean(articleContent, \"footer\");\n this._clean(articleContent, \"link\");\n this._clean(articleContent, \"aside\");\n\n // Clean out elements with little content that have \"share\" in their id/class combinations from final top candidates,\n // which means we don't remove the top candidates even they have \"share\".\n\n var shareElementThreshold = this.DEFAULT_CHAR_THRESHOLD;\n\n this._forEachNode(articleContent.children, function (topCandidate) {\n this._cleanMatchedNodes(topCandidate, function (node, matchString) {\n return this.REGEXPS.shareElements.test(matchString) && node.textContent.length < shareElementThreshold;\n });\n });\n\n this._clean(articleContent, \"iframe\");\n this._clean(articleContent, \"input\");\n this._clean(articleContent, \"textarea\");\n this._clean(articleContent, \"select\");\n this._clean(articleContent, \"button\");\n this._cleanHeaders(articleContent);\n\n // Do these last as the previous stuff may have removed junk\n // that will affect these\n this._cleanConditionally(articleContent, \"table\");\n this._cleanConditionally(articleContent, \"ul\");\n this._cleanConditionally(articleContent, \"div\");\n\n // replace H1 with H2 as H1 should be only title that is displayed separately\n this._replaceNodeTags(this._getAllNodesWithTag(articleContent, [\"h1\"]), \"h2\");\n\n // Remove extra paragraphs\n this._removeNodes(this._getAllNodesWithTag(articleContent, [\"p\"]), function (paragraph) {\n var imgCount = paragraph.getElementsByTagName(\"img\").length;\n var embedCount = paragraph.getElementsByTagName(\"embed\").length;\n var objectCount = paragraph.getElementsByTagName(\"object\").length;\n // At this point, nasty iframes have been removed, only remain embedded video ones.\n var iframeCount = paragraph.getElementsByTagName(\"iframe\").length;\n var totalCount = imgCount + embedCount + objectCount + iframeCount;\n\n return totalCount === 0 && !this._getInnerText(paragraph, false);\n });\n\n this._forEachNode(this._getAllNodesWithTag(articleContent, [\"br\"]), function(br) {\n var next = this._nextNode(br.nextSibling);\n if (next && next.tagName == \"P\")\n br.parentNode.removeChild(br);\n });\n\n // Remove single-cell tables\n this._forEachNode(this._getAllNodesWithTag(articleContent, [\"table\"]), function(table) {\n var tbody = this._hasSingleTagInsideElement(table, \"TBODY\") ? table.firstElementChild : table;\n if (this._hasSingleTagInsideElement(tbody, \"TR\")) {\n var row = tbody.firstElementChild;\n if (this._hasSingleTagInsideElement(row, \"TD\")) {\n var cell = row.firstElementChild;\n cell = this._setNodeTag(cell, this._everyNode(cell.childNodes, this._isPhrasingContent) ? \"P\" : \"DIV\");\n table.parentNode.replaceChild(cell, table);\n }\n }\n });\n },\n\n /**\n * Initialize a node with the readability object. Also checks the\n * className/id for special names to add to its score.\n *\n * @param Element\n * @return void\n **/\n _initializeNode: function(node) {\n node.readability = {\"contentScore\": 0};\n\n switch (node.tagName) {\n case \"DIV\":\n node.readability.contentScore += 5;\n break;\n\n case \"PRE\":\n case \"TD\":\n case \"BLOCKQUOTE\":\n node.readability.contentScore += 3;\n break;\n\n case \"ADDRESS\":\n case \"OL\":\n case \"UL\":\n case \"DL\":\n case \"DD\":\n case \"DT\":\n case \"LI\":\n case \"FORM\":\n node.readability.contentScore -= 3;\n break;\n\n case \"H1\":\n case \"H2\":\n case \"H3\":\n case \"H4\":\n case \"H5\":\n case \"H6\":\n case \"TH\":\n node.readability.contentScore -= 5;\n break;\n }\n\n node.readability.contentScore += this._getClassWeight(node);\n },\n\n _removeAndGetNext: function(node) {\n var nextNode = this._getNextNode(node, true);\n node.parentNode.removeChild(node);\n return nextNode;\n },\n\n /**\n * Traverse the DOM from node to node, starting at the node passed in.\n * Pass true for the second parameter to indicate this node itself\n * (and its kids) are going away, and we want the next node over.\n *\n * Calling this in a loop will traverse the DOM depth-first.\n */\n _getNextNode: function(node, ignoreSelfAndKids) {\n // First check for kids if those aren't being ignored\n if (!ignoreSelfAndKids && node.firstElementChild) {\n return node.firstElementChild;\n }\n // Then for siblings...\n if (node.nextElementSibling) {\n return node.nextElementSibling;\n }\n // And finally, move up the parent chain *and* find a sibling\n // (because this is depth-first traversal, we will have already\n // seen the parent nodes themselves).\n do {\n node = node.parentNode;\n } while (node && !node.nextElementSibling);\n return node && node.nextElementSibling;\n },\n\n // compares second text to first one\n // 1 = same text, 0 = completely different text\n // works the way that it splits both texts into words and then finds words that are unique in second text\n // the result is given by the lower length of unique parts\n _textSimilarity: function(textA, textB) {\n var tokensA = textA.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean);\n var tokensB = textB.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean);\n if (!tokensA.length || !tokensB.length) {\n return 0;\n }\n var uniqTokensB = tokensB.filter(token => !tokensA.includes(token));\n var distanceB = uniqTokensB.join(\" \").length / tokensB.join(\" \").length;\n return 1 - distanceB;\n },\n\n _checkByline: function(node, matchString) {\n if (this._articleByline) {\n return false;\n }\n\n if (node.getAttribute !== undefined) {\n var rel = node.getAttribute(\"rel\");\n var itemprop = node.getAttribute(\"itemprop\");\n }\n\n if ((rel === \"author\" || (itemprop && itemprop.indexOf(\"author\") !== -1) || this.REGEXPS.byline.test(matchString)) && this._isValidByline(node.textContent)) {\n this._articleByline = node.textContent.trim();\n return true;\n }\n\n return false;\n },\n\n _getNodeAncestors: function(node, maxDepth) {\n maxDepth = maxDepth || 0;\n var i = 0, ancestors = [];\n while (node.parentNode) {\n ancestors.push(node.parentNode);\n if (maxDepth && ++i === maxDepth)\n break;\n node = node.parentNode;\n }\n return ancestors;\n },\n\n /***\n * grabArticle - Using a variety of metrics (content score, classname, element types), find the content that is\n * most likely to be the stuff a user wants to read. Then return it wrapped up in a div.\n *\n * @param page a document to run upon. Needs to be a full document, complete with body.\n * @return Element\n **/\n _grabArticle: function (page) {\n this.log(\"**** grabArticle ****\");\n var doc = this._doc;\n var isPaging = page !== null;\n page = page ? page : this._doc.body;\n\n // We can't grab an article if we don't have a page!\n if (!page) {\n this.log(\"No body found in document. Abort.\");\n return null;\n }\n\n var pageCacheHtml = page.innerHTML;\n\n while (true) {\n this.log(\"Starting grabArticle loop\");\n var stripUnlikelyCandidates = this._flagIsActive(this.FLAG_STRIP_UNLIKELYS);\n\n // First, node prepping. Trash nodes that look cruddy (like ones with the\n // class name \"comment\", etc), and turn divs into P tags where they have been\n // used inappropriately (as in, where they contain no other block level elements.)\n var elementsToScore = [];\n var node = this._doc.documentElement;\n\n let shouldRemoveTitleHeader = true;\n\n while (node) {\n\n if (node.tagName === \"HTML\") {\n this._articleLang = node.getAttribute(\"lang\");\n }\n\n var matchString = node.className + \" \" + node.id;\n\n if (!this._isProbablyVisible(node)) {\n this.log(\"Removing hidden node - \" + matchString);\n node = this._removeAndGetNext(node);\n continue;\n }\n\n // User is not able to see elements applied with both \"aria-modal = true\" and \"role = dialog\"\n if (node.getAttribute(\"aria-modal\") == \"true\" && node.getAttribute(\"role\") == \"dialog\") {\n node = this._removeAndGetNext(node);\n continue;\n }\n\n // Check to see if this node is a byline, and remove it if it is.\n if (this._checkByline(node, matchString)) {\n node = this._removeAndGetNext(node);\n continue;\n }\n\n if (shouldRemoveTitleHeader && this._headerDuplicatesTitle(node)) {\n this.log(\"Removing header: \", node.textContent.trim(), this._articleTitle.trim());\n shouldRemoveTitleHeader = false;\n node = this._removeAndGetNext(node);\n continue;\n }\n\n // Remove unlikely candidates\n if (stripUnlikelyCandidates) {\n if (this.REGEXPS.unlikelyCandidates.test(matchString) &&\n !this.REGEXPS.okMaybeItsACandidate.test(matchString) &&\n !this._hasAncestorTag(node, \"table\") &&\n !this._hasAncestorTag(node, \"code\") &&\n node.tagName !== \"BODY\" &&\n node.tagName !== \"A\") {\n this.log(\"Removing unlikely candidate - \" + matchString);\n node = this._removeAndGetNext(node);\n continue;\n }\n\n if (this.UNLIKELY_ROLES.includes(node.getAttribute(\"role\"))) {\n this.log(\"Removing content with role \" + node.getAttribute(\"role\") + \" - \" + matchString);\n node = this._removeAndGetNext(node);\n continue;\n }\n }\n\n // Remove DIV, SECTION, and HEADER nodes without any content(e.g. text, image, video, or iframe).\n if ((node.tagName === \"DIV\" || node.tagName === \"SECTION\" || node.tagName === \"HEADER\" ||\n node.tagName === \"H1\" || node.tagName === \"H2\" || node.tagName === \"H3\" ||\n node.tagName === \"H4\" || node.tagName === \"H5\" || node.tagName === \"H6\") &&\n this._isElementWithoutContent(node)) {\n node = this._removeAndGetNext(node);\n continue;\n }\n\n if (this.DEFAULT_TAGS_TO_SCORE.indexOf(node.tagName) !== -1) {\n elementsToScore.push(node);\n }\n\n // Turn all divs that don't have children block level elements into p's\n if (node.tagName === \"DIV\") {\n // Put phrasing content into paragraphs.\n var p = null;\n var childNode = node.firstChild;\n while (childNode) {\n var nextSibling = childNode.nextSibling;\n if (this._isPhrasingContent(childNode)) {\n if (p !== null) {\n p.appendChild(childNode);\n } else if (!this._isWhitespace(childNode)) {\n p = doc.createElement(\"p\");\n node.replaceChild(p, childNode);\n p.appendChild(childNode);\n }\n } else if (p !== null) {\n while (p.lastChild && this._isWhitespace(p.lastChild)) {\n p.removeChild(p.lastChild);\n }\n p = null;\n }\n childNode = nextSibling;\n }\n\n // Sites like http://mobile.slate.com encloses each paragraph with a DIV\n // element. DIVs with only a P element inside and no text content can be\n // safely converted into plain P elements to avoid confusing the scoring\n // algorithm with DIVs with are, in practice, paragraphs.\n if (this._hasSingleTagInsideElement(node, \"P\") && this._getLinkDensity(node) < 0.25) {\n var newNode = node.children[0];\n node.parentNode.replaceChild(newNode, node);\n node = newNode;\n elementsToScore.push(node);\n } else if (!this._hasChildBlockElement(node)) {\n node = this._setNodeTag(node, \"P\");\n elementsToScore.push(node);\n }\n }\n node = this._getNextNode(node);\n }\n\n /**\n * Loop through all paragraphs, and assign a score to them based on how content-y they look.\n * Then add their score to their parent node.\n *\n * A score is determined by things like number of commas, class names, etc. Maybe eventually link density.\n **/\n var candidates = [];\n this._forEachNode(elementsToScore, function(elementToScore) {\n if (!elementToScore.parentNode || typeof(elementToScore.parentNode.tagName) === \"undefined\")\n return;\n\n // If this paragraph is less than 25 characters, don't even count it.\n var innerText = this._getInnerText(elementToScore);\n if (innerText.length < 25)\n return;\n\n // Exclude nodes with no ancestor.\n var ancestors = this._getNodeAncestors(elementToScore, 5);\n if (ancestors.length === 0)\n return;\n\n var contentScore = 0;\n\n // Add a point for the paragraph itself as a base.\n contentScore += 1;\n\n // Add points for any commas within this paragraph.\n contentScore += innerText.split(this.REGEXPS.commas).length;\n\n // For every 100 characters in this paragraph, add another point. Up to 3 points.\n contentScore += Math.min(Math.floor(innerText.length / 100), 3);\n\n // Initialize and score ancestors.\n this._forEachNode(ancestors, function(ancestor, level) {\n if (!ancestor.tagName || !ancestor.parentNode || typeof(ancestor.parentNode.tagName) === \"undefined\")\n return;\n\n if (typeof(ancestor.readability) === \"undefined\") {\n this._initializeNode(ancestor);\n candidates.push(ancestor);\n }\n\n // Node score divider:\n // - parent: 1 (no division)\n // - grandparent: 2\n // - great grandparent+: ancestor level * 3\n if (level === 0)\n var scoreDivider = 1;\n else if (level === 1)\n scoreDivider = 2;\n else\n scoreDivider = level * 3;\n ancestor.readability.contentScore += contentScore / scoreDivider;\n });\n });\n\n // After we've calculated scores, loop through all of the possible\n // candidate nodes we found and find the one with the highest score.\n var topCandidates = [];\n for (var c = 0, cl = candidates.length; c < cl; c += 1) {\n var candidate = candidates[c];\n\n // Scale the final candidates score based on link density. Good content\n // should have a relatively small link density (5% or less) and be mostly\n // unaffected by this operation.\n var candidateScore = candidate.readability.contentScore * (1 - this._getLinkDensity(candidate));\n candidate.readability.contentScore = candidateScore;\n\n this.log(\"Candidate:\", candidate, \"with score \" + candidateScore);\n\n for (var t = 0; t < this._nbTopCandidates; t++) {\n var aTopCandidate = topCandidates[t];\n\n if (!aTopCandidate || candidateScore > aTopCandidate.readability.contentScore) {\n topCandidates.splice(t, 0, candidate);\n if (topCandidates.length > this._nbTopCandidates)\n topCandidates.pop();\n break;\n }\n }\n }\n\n var topCandidate = topCandidates[0] || null;\n var neededToCreateTopCandidate = false;\n var parentOfTopCandidate;\n\n // If we still have no top candidate, just use the body as a last resort.\n // We also have to copy the body node so it is something we can modify.\n if (topCandidate === null || topCandidate.tagName === \"BODY\") {\n // Move all of the page's children into topCandidate\n topCandidate = doc.createElement(\"DIV\");\n neededToCreateTopCandidate = true;\n // Move everything (not just elements, also text nodes etc.) into the container\n // so we even include text directly in the body:\n while (page.firstChild) {\n this.log(\"Moving child out:\", page.firstChild);\n topCandidate.appendChild(page.firstChild);\n }\n\n page.appendChild(topCandidate);\n\n this._initializeNode(topCandidate);\n } else if (topCandidate) {\n // Find a better top candidate node if it contains (at least three) nodes which belong to `topCandidates` array\n // and whose scores are quite closed with current `topCandidate` node.\n var alternativeCandidateAncestors = [];\n for (var i = 1; i < topCandidates.length; i++) {\n if (topCandidates[i].readability.contentScore / topCandidate.readability.contentScore >= 0.75) {\n alternativeCandidateAncestors.push(this._getNodeAncestors(topCandidates[i]));\n }\n }\n var MINIMUM_TOPCANDIDATES = 3;\n if (alternativeCandidateAncestors.length >= MINIMUM_TOPCANDIDATES) {\n parentOfTopCandidate = topCandidate.parentNode;\n while (parentOfTopCandidate.tagName !== \"BODY\") {\n var listsContainingThisAncestor = 0;\n for (var ancestorIndex = 0; ancestorIndex < alternativeCandidateAncestors.length && listsContainingThisAncestor < MINIMUM_TOPCANDIDATES; ancestorIndex++) {\n listsContainingThisAncestor += Number(alternativeCandidateAncestors[ancestorIndex].includes(parentOfTopCandidate));\n }\n if (listsContainingThisAncestor >= MINIMUM_TOPCANDIDATES) {\n topCandidate = parentOfTopCandidate;\n break;\n }\n parentOfTopCandidate = parentOfTopCandidate.parentNode;\n }\n }\n if (!topCandidate.readability) {\n this._initializeNode(topCandidate);\n }\n\n // Because of our bonus system, parents of candidates might have scores\n // themselves. They get half of the node. There won't be nodes with higher\n // scores than our topCandidate, but if we see the score going *up* in the first\n // few steps up the tree, that's a decent sign that there might be more content\n // lurking in other places that we want to unify in. The sibling stuff\n // below does some of that - but only if we've looked high enough up the DOM\n // tree.\n parentOfTopCandidate = topCandidate.parentNode;\n var lastScore = topCandidate.readability.contentScore;\n // The scores shouldn't get too low.\n var scoreThreshold = lastScore / 3;\n while (parentOfTopCandidate.tagName !== \"BODY\") {\n if (!parentOfTopCandidate.readability) {\n parentOfTopCandidate = parentOfTopCandidate.parentNode;\n continue;\n }\n var parentScore = parentOfTopCandidate.readability.contentScore;\n if (parentScore < scoreThreshold)\n break;\n if (parentScore > lastScore) {\n // Alright! We found a better parent to use.\n topCandidate = parentOfTopCandidate;\n break;\n }\n lastScore = parentOfTopCandidate.readability.contentScore;\n parentOfTopCandidate = parentOfTopCandidate.parentNode;\n }\n\n // If the top candidate is the only child, use parent instead. This will help sibling\n // joining logic when adjacent content is actually located in parent's sibling node.\n parentOfTopCandidate = topCandidate.parentNode;\n while (parentOfTopCandidate.tagName != \"BODY\" && parentOfTopCandidate.children.length == 1) {\n topCandidate = parentOfTopCandidate;\n parentOfTopCandidate = topCandidate.parentNode;\n }\n if (!topCandidate.readability) {\n this._initializeNode(topCandidate);\n }\n }\n\n // Now that we have the top candidate, look through its siblings for content\n // that might also be related. Things like preambles, content split by ads\n // that we removed, etc.\n var articleContent = doc.createElement(\"DIV\");\n if (isPaging)\n articleContent.id = \"readability-content\";\n\n var siblingScoreThreshold = Math.max(10, topCandidate.readability.contentScore * 0.2);\n // Keep potential top candidate's parent node to try to get text direction of it later.\n parentOfTopCandidate = topCandidate.parentNode;\n var siblings = parentOfTopCandidate.children;\n\n for (var s = 0, sl = siblings.length; s < sl; s++) {\n var sibling = siblings[s];\n var append = false;\n\n this.log(\"Looking at sibling node:\", sibling, sibling.readability ? (\"with score \" + sibling.readability.contentScore) : \"\");\n this.log(\"Sibling has score\", sibling.readability ? sibling.readability.contentScore : \"Unknown\");\n\n if (sibling === topCandidate) {\n append = true;\n } else {\n var contentBonus = 0;\n\n // Give a bonus if sibling nodes and top candidates have the example same classname\n if (sibling.className === topCandidate.className && topCandidate.className !== \"\")\n contentBonus += topCandidate.readability.contentScore * 0.2;\n\n if (sibling.readability &&\n ((sibling.readability.contentScore + contentBonus) >= siblingScoreThreshold)) {\n append = true;\n } else if (sibling.nodeName === \"P\") {\n var linkDensity = this._getLinkDensity(sibling);\n var nodeContent = this._getInnerText(sibling);\n var nodeLength = nodeContent.length;\n\n if (nodeLength > 80 && linkDensity < 0.25) {\n append = true;\n } else if (nodeLength < 80 && nodeLength > 0 && linkDensity === 0 &&\n nodeContent.search(/\\.( |$)/) !== -1) {\n append = true;\n }\n }\n }\n\n if (append) {\n this.log(\"Appending node:\", sibling);\n\n if (this.ALTER_TO_DIV_EXCEPTIONS.indexOf(sibling.nodeName) === -1) {\n // We have a node that isn't a common block level element, like a form or td tag.\n // Turn it into a div so it doesn't get filtered out later by accident.\n this.log(\"Altering sibling:\", sibling, \"to div.\");\n\n sibling = this._setNodeTag(sibling, \"DIV\");\n }\n\n articleContent.appendChild(sibling);\n // Fetch children again to make it compatible\n // with DOM parsers without live collection support.\n siblings = parentOfTopCandidate.children;\n // siblings is a reference to the children array, and\n // sibling is removed from the array when we call appendChild().\n // As a result, we must revisit this index since the nodes\n // have been shifted.\n s -= 1;\n sl -= 1;\n }\n }\n\n if (this._debug)\n this.log(\"Article content pre-prep: \" + articleContent.innerHTML);\n // So we have all of the content that we need. Now we clean it up for presentation.\n this._prepArticle(articleContent);\n if (this._debug)\n this.log(\"Article content post-prep: \" + articleContent.innerHTML);\n\n if (neededToCreateTopCandidate) {\n // We already created a fake div thing, and there wouldn't have been any siblings left\n // for the previous loop, so there's no point trying to create a new div, and then\n // move all the children over. Just assign IDs and class names here. No need to append\n // because that already happened anyway.\n topCandidate.id = \"readability-page-1\";\n topCandidate.className = \"page\";\n } else {\n var div = doc.createElement(\"DIV\");\n div.id = \"readability-page-1\";\n div.className = \"page\";\n while (articleContent.firstChild) {\n div.appendChild(articleContent.firstChild);\n }\n articleContent.appendChild(div);\n }\n\n if (this._debug)\n this.log(\"Article content after paging: \" + articleContent.innerHTML);\n\n var parseSuccessful = true;\n\n // Now that we've gone through the full algorithm, check to see if\n // we got any meaningful content. If we didn't, we may need to re-run\n // grabArticle with different flags set. This gives us a higher likelihood of\n // finding the content, and the sieve approach gives us a higher likelihood of\n // finding the -right- content.\n var textLength = this._getInnerText(articleContent, true).length;\n if (textLength < this._charThreshold) {\n parseSuccessful = false;\n page.innerHTML = pageCacheHtml;\n\n if (this._flagIsActive(this.FLAG_STRIP_UNLIKELYS)) {\n this._removeFlag(this.FLAG_STRIP_UNLIKELYS);\n this._attempts.push({articleContent: articleContent, textLength: textLength});\n } else if (this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) {\n this._removeFlag(this.FLAG_WEIGHT_CLASSES);\n this._attempts.push({articleContent: articleContent, textLength: textLength});\n } else if (this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) {\n this._removeFlag(this.FLAG_CLEAN_CONDITIONALLY);\n this._attempts.push({articleContent: articleContent, textLength: textLength});\n } else {\n this._attempts.push({articleContent: articleContent, textLength: textLength});\n // No luck after removing flags, just return the longest text we found during the different loops\n this._attempts.sort(function (a, b) {\n return b.textLength - a.textLength;\n });\n\n // But first check if we actually have something\n if (!this._attempts[0].textLength) {\n return null;\n }\n\n articleContent = this._attempts[0].articleContent;\n parseSuccessful = true;\n }\n }\n\n if (parseSuccessful) {\n // Find out text direction from ancestors of final top candidate.\n var ancestors = [parentOfTopCandidate, topCandidate].concat(this._getNodeAncestors(parentOfTopCandidate));\n this._someNode(ancestors, function(ancestor) {\n if (!ancestor.tagName)\n return false;\n var articleDir = ancestor.getAttribute(\"dir\");\n if (articleDir) {\n this._articleDir = articleDir;\n return true;\n }\n return false;\n });\n return articleContent;\n }\n }\n },\n\n /**\n * Check whether the input string could be a byline.\n * This verifies that the input is a string, and that the length\n * is less than 100 chars.\n *\n * @param possibleByline {string} - a string to check whether its a byline.\n * @return Boolean - whether the input string is a byline.\n */\n _isValidByline: function(byline) {\n if (typeof byline == \"string\" || byline instanceof String) {\n byline = byline.trim();\n return (byline.length > 0) && (byline.length < 100);\n }\n return false;\n },\n\n /**\n * Converts some of the common HTML entities in string to their corresponding characters.\n *\n * @param str {string} - a string to unescape.\n * @return string without HTML entity.\n */\n _unescapeHtmlEntities: function(str) {\n if (!str) {\n return str;\n }\n\n var htmlEscapeMap = this.HTML_ESCAPE_MAP;\n return str.replace(/&(quot|amp|apos|lt|gt);/g, function(_, tag) {\n return htmlEscapeMap[tag];\n }).replace(/&#(?:x([0-9a-z]{1,4})|([0-9]{1,4}));/gi, function(_, hex, numStr) {\n var num = parseInt(hex || numStr, hex ? 16 : 10);\n return String.fromCharCode(num);\n });\n },\n\n /**\n * Try to extract metadata from JSON-LD object.\n * For now, only Schema.org objects of type Article or its subtypes are supported.\n * @return Object with any metadata that could be extracted (possibly none)\n */\n _getJSONLD: function (doc) {\n var scripts = this._getAllNodesWithTag(doc, [\"script\"]);\n\n var metadata;\n\n this._forEachNode(scripts, function(jsonLdElement) {\n if (!metadata && jsonLdElement.getAttribute(\"type\") === \"application/ld+json\") {\n try {\n // Strip CDATA markers if present\n var content = jsonLdElement.textContent.replace(/^\\s*\\s*$/g, \"\");\n var parsed = JSON.parse(content);\n if (\n !parsed[\"@context\"] ||\n !parsed[\"@context\"].match(/^https?\\:\\/\\/schema\\.org$/)\n ) {\n return;\n }\n\n if (!parsed[\"@type\"] && Array.isArray(parsed[\"@graph\"])) {\n parsed = parsed[\"@graph\"].find(function(it) {\n return (it[\"@type\"] || \"\").match(\n this.REGEXPS.jsonLdArticleTypes\n );\n });\n }\n\n if (\n !parsed ||\n !parsed[\"@type\"] ||\n !parsed[\"@type\"].match(this.REGEXPS.jsonLdArticleTypes)\n ) {\n return;\n }\n\n metadata = {};\n\n if (typeof parsed.name === \"string\" && typeof parsed.headline === \"string\" && parsed.name !== parsed.headline) {\n // we have both name and headline element in the JSON-LD. They should both be the same but some websites like aktualne.cz\n // put their own name into \"name\" and the article title to \"headline\" which confuses Readability. So we try to check if either\n // \"name\" or \"headline\" closely matches the html title, and if so, use that one. If not, then we use \"name\" by default.\n\n var title = this._getArticleTitle();\n var nameMatches = this._textSimilarity(parsed.name, title) > 0.75;\n var headlineMatches = this._textSimilarity(parsed.headline, title) > 0.75;\n\n if (headlineMatches && !nameMatches) {\n metadata.title = parsed.headline;\n } else {\n metadata.title = parsed.name;\n }\n } else if (typeof parsed.name === \"string\") {\n metadata.title = parsed.name.trim();\n } else if (typeof parsed.headline === \"string\") {\n metadata.title = parsed.headline.trim();\n }\n if (parsed.author) {\n if (typeof parsed.author.name === \"string\") {\n metadata.byline = parsed.author.name.trim();\n } else if (Array.isArray(parsed.author) && parsed.author[0] && typeof parsed.author[0].name === \"string\") {\n metadata.byline = parsed.author\n .filter(function(author) {\n return author && typeof author.name === \"string\";\n })\n .map(function(author) {\n return author.name.trim();\n })\n .join(\", \");\n }\n }\n if (typeof parsed.description === \"string\") {\n metadata.excerpt = parsed.description.trim();\n }\n if (\n parsed.publisher &&\n typeof parsed.publisher.name === \"string\"\n ) {\n metadata.siteName = parsed.publisher.name.trim();\n }\n if (typeof parsed.datePublished === \"string\") {\n metadata.datePublished = parsed.datePublished.trim();\n }\n return;\n } catch (err) {\n this.log(err.message);\n }\n }\n });\n return metadata ? metadata : {};\n },\n\n /**\n * Attempts to get excerpt and byline metadata for the article.\n *\n * @param {Object} jsonld — object containing any metadata that\n * could be extracted from JSON-LD object.\n *\n * @return Object with optional \"excerpt\" and \"byline\" properties\n */\n _getArticleMetadata: function(jsonld) {\n var metadata = {};\n var values = {};\n var metaElements = this._doc.getElementsByTagName(\"meta\");\n\n // property is a space-separated list of values\n var propertyPattern = /\\s*(article|dc|dcterm|og|twitter)\\s*:\\s*(author|creator|description|published_time|title|site_name)\\s*/gi;\n\n // name is a single value\n var namePattern = /^\\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\\s*[\\.:]\\s*)?(author|creator|description|title|site_name)\\s*$/i;\n\n // Find description tags.\n this._forEachNode(metaElements, function(element) {\n var elementName = element.getAttribute(\"name\");\n var elementProperty = element.getAttribute(\"property\");\n var content = element.getAttribute(\"content\");\n if (!content) {\n return;\n }\n var matches = null;\n var name = null;\n\n if (elementProperty) {\n matches = elementProperty.match(propertyPattern);\n if (matches) {\n // Convert to lowercase, and remove any whitespace\n // so we can match below.\n name = matches[0].toLowerCase().replace(/\\s/g, \"\");\n // multiple authors\n values[name] = content.trim();\n }\n }\n if (!matches && elementName && namePattern.test(elementName)) {\n name = elementName;\n if (content) {\n // Convert to lowercase, remove any whitespace, and convert dots\n // to colons so we can match below.\n name = name.toLowerCase().replace(/\\s/g, \"\").replace(/\\./g, \":\");\n values[name] = content.trim();\n }\n }\n });\n\n // get title\n metadata.title = jsonld.title ||\n values[\"dc:title\"] ||\n values[\"dcterm:title\"] ||\n values[\"og:title\"] ||\n values[\"weibo:article:title\"] ||\n values[\"weibo:webpage:title\"] ||\n values[\"title\"] ||\n values[\"twitter:title\"];\n\n if (!metadata.title) {\n metadata.title = this._getArticleTitle();\n }\n\n // get author\n metadata.byline = jsonld.byline ||\n values[\"dc:creator\"] ||\n values[\"dcterm:creator\"] ||\n values[\"author\"];\n\n // get description\n metadata.excerpt = jsonld.excerpt ||\n values[\"dc:description\"] ||\n values[\"dcterm:description\"] ||\n values[\"og:description\"] ||\n values[\"weibo:article:description\"] ||\n values[\"weibo:webpage:description\"] ||\n values[\"description\"] ||\n values[\"twitter:description\"];\n\n // get site name\n metadata.siteName = jsonld.siteName ||\n values[\"og:site_name\"];\n\n // get article published time\n metadata.publishedTime = jsonld.datePublished ||\n values[\"article:published_time\"] || null;\n\n // in many sites the meta value is escaped with HTML entities,\n // so here we need to unescape it\n metadata.title = this._unescapeHtmlEntities(metadata.title);\n metadata.byline = this._unescapeHtmlEntities(metadata.byline);\n metadata.excerpt = this._unescapeHtmlEntities(metadata.excerpt);\n metadata.siteName = this._unescapeHtmlEntities(metadata.siteName);\n metadata.publishedTime = this._unescapeHtmlEntities(metadata.publishedTime);\n\n return metadata;\n },\n\n /**\n * Check if node is image, or if node contains exactly only one image\n * whether as a direct child or as its descendants.\n *\n * @param Element\n **/\n _isSingleImage: function(node) {\n if (node.tagName === \"IMG\") {\n return true;\n }\n\n if (node.children.length !== 1 || node.textContent.trim() !== \"\") {\n return false;\n }\n\n return this._isSingleImage(node.children[0]);\n },\n\n /**\n * Find all