Just code style (JS)

This commit is contained in:
nobody 2021-02-17 07:01:08 +01:00
parent 25a8a0499c
commit db398fadec
No known key found for this signature in database
GPG Key ID: 8F6DE3D614FCFD7A
26 changed files with 572 additions and 226 deletions

5
.eslintignore Normal file
View File

@ -0,0 +1,5 @@
_locales
icons
modules/noto-sans/*
modules/color-picker/*
resources

196
.eslintrc Normal file
View File

@ -0,0 +1,196 @@
{
"env": {
"browser": true,
"es6": true,
"webextensions": true
},
"extends": [
"eslint:recommended"
],
"globals": {
"Address": true,
"Environment": true,
"Header": true,
"MessageResponse": true,
"Resource": true,
"Setting": true,
"SettingDefaults": true,
"WebRequest": true,
"WebRequestType": true,
"Allowlist": true,
"BrowserType": true,
"IconType": true,
"Regex": true,
"Links": true,
"CDNs": true,
"IgnoredHost": true,
"EncodingTypes": true,
"fileGuard": true,
"files": true,
"helpers": true,
"interceptor": true,
"mappings": true,
"requestAnalyzer": true,
"requestSanitizer": true,
"resources": true,
"shorthands": true,
"stateManager": true,
"wrappers": true,
"storageManager": true,
"manipulateDOM": true,
"stats": true,
"targets": true,
"ruleGenerator": true,
},
"overrides": {
"files": [
"core/constants.js",
"core/files.js",
"core/mappings.js",
"core/resources.js",
"core/shorthands.js"
],
"rules": {
"no-unused-vars": "off"
}
},
"rules": {
"array-bracket-newline": "error",
"array-bracket-spacing": "error",
"arrow-body-style": "error",
"arrow-parens": "error",
"arrow-spacing": "error",
"block-spacing": "error",
"brace-style": "error",
"camelcase": "error",
"comma-spacing": "error",
"comma-style": "error",
"computed-property-spacing": "error",
"consistent-this": "error",
"curly": ["error", "multi-line"],
"eol-last": "error",
"eqeqeq": "error",
"func-call-spacing": "error",
"function-paren-newline": "error",
"generator-star-spacing": "error",
"indent": [
"error",
4
],
"key-spacing": "error",
"keyword-spacing": "error",
"linebreak-style": [
"error",
"unix"
],
"new-cap": "error",
"new-parens": "error",
"no-array-constructor": "error",
"no-bitwise": "error",
"no-confusing-arrow": "error",
"no-continue": "error",
"no-console": ["error", { allow: ["warn", "error", "log"] }],
"no-duplicate-imports": "error",
"no-eval": "error",
"no-extend-native": "error",
"no-implicit-coercion": "error",
"no-implied-eval": "error",
"no-invalid-this": "error",
"no-iterator": "error",
"no-label-var": "error",
"no-labels": "error",
"no-lone-blocks": "error",
"no-loop-func": "error",
"no-multi-spaces": "error",
"no-multi-str": "error",
"no-multiple-empty-lines": [
"error", {
"max": 2,
"maxEOF": 1,
"maxBOF": 0
}
],
"max-len": [
"error", {
"code": 120,
"ignoreUrls": true,
"ignoreStrings": true,
}
],
"one-var": [2, {
"var": "never",
"let": "always",
"const": "never"
}],
"no-new": "error",
"no-new-func": "error",
"no-new-object": "error",
"no-new-wrappers": "error",
"no-octal-escape": "error",
"no-proto": "error",
"no-return-assign": "error",
"no-return-await": "error",
"no-script-url": "error",
"no-self-compare": "error",
"no-sequences": "error",
"no-shadow-restricted-names": "error",
"no-tabs": "error",
"no-throw-literal": "error",
"no-trailing-spaces": "error",
"no-undef-init": "error",
"no-unmodified-loop-condition": "error",
"no-unused-expressions": "error",
"no-use-before-define": "error",
"no-useless-call": "error",
"no-useless-concat": "error",
"no-useless-constructor": "error",
"no-useless-rename": "error",
"no-useless-return": "error",
"no-void": "error",
"no-warning-comments": "warn",
"no-whitespace-before-property": "error",
"no-with": "error",
"object-curly-spacing": "error",
"object-shorthand": [
"error",
"consistent-as-needed"
],
"operator-assignment": "error",
"operator-linebreak": "error",
"prefer-numeric-literals": "error",
"prefer-promise-reject-errors": "error",
"quote-props": "error",
"prefer-rest-params": "error",
"prefer-spread": "error",
"prefer-template": "error",
"quotes": [
"error",
"single"
],
"rest-spread-spacing": "error",
"require-await": "error",
"semi": "error",
"semi-spacing": "error",
"semi-style": "error",
"space-before-blocks": "error",
"space-before-function-paren": "error",
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "error",
"strict": [
"error",
"global"
],
"switch-colon-spacing": "error",
"symbol-description": "error",
"template-curly-spacing": "error",
"template-tag-spacing": "error",
"unicode-bom": "error",
"vars-on-top": "error",
"wrap-regex": "error",
"yield-star-spacing": "error",
"yoda": "error",
}
}

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
test/**

View File

@ -21,7 +21,6 @@
/** /**
* Constants * Constants
*/ */
const Address = { const Address = {
'ANY': '*://*/*', 'ANY': '*://*/*',
'ANY_PATH': '/*', 'ANY_PATH': '/*',
@ -126,8 +125,8 @@ const Allowlist = {
}; };
const BrowserType = { const BrowserType = {
'CHROMIUM': chrome.runtime.getURL("/").startsWith("chrome-extension"), 'CHROMIUM': chrome.runtime.getURL('/').startsWith('chrome-extension'),
'FIREFOX': chrome.runtime.getURL("/").startsWith("moz-extension") 'FIREFOX': chrome.runtime.getURL('/').startsWith('moz-extension')
}; };
const IconType = { const IconType = {

View File

@ -16,12 +16,14 @@
'use strict'; 'use strict';
/** /**
* File Guard * File Guard
*/ */
var fileGuard = {}; var fileGuard = {};
/** /**
* Private Methods * Private Methods
*/ */
@ -47,6 +49,7 @@ fileGuard._verifyRequest = function (requestDetails) {
} }
}; };
/** /**
* Initializations * Initializations
*/ */

View File

@ -18,12 +18,14 @@
'use strict'; 'use strict';
/** /**
* Interceptor * Interceptor
*/ */
var interceptor = {}; var interceptor = {};
/** /**
* Public Methods * Public Methods
*/ */
@ -69,6 +71,7 @@ interceptor.handleRequest = function (requestDetails, tabIdentifier, tab) {
}; };
}; };
/** /**
* Private Methods * Private Methods
*/ */
@ -122,6 +125,7 @@ interceptor._handleStorageChanged = function (changes) {
} }
}; };
/** /**
* Initializations * Initializations
*/ */
@ -146,6 +150,7 @@ storageManager.type.get(interceptor.relatedSettings, function (items) {
interceptor.allowedDomainsGoogleFonts = items.allowedDomainsGoogleFonts || {}; interceptor.allowedDomainsGoogleFonts = items.allowedDomainsGoogleFonts || {};
}); });
/** /**
* Event Handlers * Event Handlers
*/ */

View File

@ -18,12 +18,14 @@
'use strict'; 'use strict';
/** /**
* Main * Main
*/ */
var main = {}; var main = {};
/** /**
* Private Methods * Private Methods
*/ */
@ -80,7 +82,7 @@ main._showReleaseNotes = function (details) {
if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) { if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) {
storageManager.type.set({ storageManager.type.set({
[Setting.LAST_MAPPING_UPDATE]: mappings.lastMappingUpdate [Setting.LAST_MAPPING_UPDATE]: mappings.lastMappingUpdate
}, function() { }, function () {
if (details.temporary !== true) { if (details.temporary !== true) {
chrome.tabs.create({ chrome.tabs.create({
'url': chrome.extension.getURL('pages/welcome/welcome.html'), 'url': chrome.extension.getURL('pages/welcome/welcome.html'),
@ -107,19 +109,20 @@ main._showReleaseNotes = function (details) {
storageManager.type.set(items); storageManager.type.set(items);
} }
if ( (mappingUpdate && items.updateNotification == 1) || items.updateNotification == 2 ) { if ((mappingUpdate && items.updateNotification === 1) || items.updateNotification === 2) {
chrome.tabs.create({ chrome.tabs.create({
'url': chrome.extension.getURL('pages/updates/updates.html?mappingupdate=' + mappingUpdate), 'url': chrome.extension.getURL(`pages/updates/updates.html?mappingupdate=${mappingUpdate}`),
'active': false 'active': false
}); });
} else { } else {
// No mappings.js update // No mappings.js update
return;
} }
}); });
} }
}; };
/** /**
* Initializations * Initializations
*/ */

View File

@ -28,27 +28,27 @@ var manipulateDOM = {};
manipulateDOM._removeCrossOriginAndIntegrityAttr = function (details) { manipulateDOM._removeCrossOriginAndIntegrityAttr = function (details) {
if(!BrowserType.FIREFOX) { if (!BrowserType.FIREFOX) {
// Chromium (and other) browsers do not support webRequest.filterResponseData // Chromium (and other) browsers do not support webRequest.filterResponseData
// https://bugs.chromium.org/p/chromium/issues/detail?id=487422 // https://bugs.chromium.org/p/chromium/issues/detail?id=487422
console.warn('[ LocalCDN ] browser.webRequest.filterResponseData not supported by your browser.'); console.warn('[ LocalCDN ] browser.webRequest.filterResponseData not supported by your browser.');
return; return;
} }
let initiatorDomain, listedToManipulateDOM, negateHtmlFilter, filtering; let initiatorDomain, listedToManipulateDOM, negateHtmlFilter, filtering, header;
initiatorDomain = helpers.extractDomainFromUrl(details.url, true) || Address.EXAMPLE; initiatorDomain = helpers.extractDomainFromUrl(details.url, true) || Address.EXAMPLE;
listedToManipulateDOM = stateManager._domainIsListed(initiatorDomain, "manipulate-dom"); listedToManipulateDOM = stateManager._domainIsListed(initiatorDomain, 'manipulate-dom');
negateHtmlFilter = stateManager.getInvertOption; negateHtmlFilter = stateManager.getInvertOption;
if( ( negateHtmlFilter || listedToManipulateDOM ) && !( negateHtmlFilter && listedToManipulateDOM ) ) { if ((negateHtmlFilter || listedToManipulateDOM) && !(negateHtmlFilter && listedToManipulateDOM)) {
filtering = true; filtering = true;
} else { } else {
filtering = false; filtering = false;
} }
// by Jaap (https://gitlab.com/Jaaap) // by Jaap (https://gitlab.com/Jaaap)
let header = details.responseHeaders.find(h => h.name.toLowerCase() === 'content-type'); header = details.responseHeaders.find((h) => h.name.toLowerCase() === 'content-type');
if (header && filtering) { if (header && filtering) {
@ -59,13 +59,13 @@ manipulateDOM._removeCrossOriginAndIntegrityAttr = function (details) {
if (!isAllowlisted && mimeType === 'text/html') { if (!isAllowlisted && mimeType === 'text/html') {
let asciiDecoder, decoder, encoder, charset, isFirstData, filter; let asciiDecoder, decoder, encoder, charset, isFirstData, filter, data;
charset = /charset\s*=/.test(header.value) && header.value.replace(/^.*?charset\s*=\s*/, '').replace(/["']?/g, ''); charset = (/charset\s*=/).test(header.value) && header.value.replace(/^.*?charset\s*=\s*/, '').replace(/["']?/g, '');
// Check if charset is supported by TextDecoder() // Check if charset is supported by TextDecoder()
if(/charset\s*=/.test(header.value) && !EncodingTypes[charset.toString().toLowerCase()]){ if (/charset\s*=/.test(header.value) && !EncodingTypes[charset.toString().toLowerCase()]) {
console.error('[ LocalCDN ] Unsupported charset: ' + charset); console.error(`[ LocalCDN ] Unsupported charset: ${charset}`);
return; return;
} }
@ -73,35 +73,40 @@ manipulateDOM._removeCrossOriginAndIntegrityAttr = function (details) {
encoder = new TextEncoder(); encoder = new TextEncoder();
isFirstData = true; isFirstData = true;
filter = browser.webRequest.filterResponseData(details.requestId); filter = browser.webRequest.filterResponseData(details.requestId);
let data = []; data = [];
header.value = 'text/html; charset=UTF-8'; header.value = 'text/html; charset=UTF-8';
// Note that should work if the '<script crossorigin="anonymous" src="dfgsfgd.com">' string is divided into two chunks. // NOTE: should work if 'script' string is divided into two chunks
filter.ondata = evt => { filter.ondata = (evt) => {
if (isFirstData) { if (isFirstData) {
if (!charset) { if (!charset) {
//content-type has no charset declared // content-type has no charset declared
let htmlHead = asciiDecoder.decode(evt.data, {stream: false}); let htmlHead, charsetMatch;
let charsetMatch = htmlHead.match(/<meta.*charset=["']?([^>"'\/]+)["'].*[>\/]/i);
charset = charsetMatch ? charsetMatch[1] : "UTF-8"; htmlHead = asciiDecoder.decode(evt.data, {'stream': false});
// eslint-disable-next-line no-useless-escape
charsetMatch = htmlHead.match(/<meta.*charset=["']?([^>"'\/]+)["'].*[>\/]/i);
charset = charsetMatch ? charsetMatch[1] : 'UTF-8';
} }
decoder = new TextDecoder(charset); decoder = new TextDecoder(charset);
} }
isFirstData = false; isFirstData = false;
data.push(evt.data); data.push(evt.data);
} };
filter.onstop = evt => { filter.onstop = () => {
let str = ''; let str = '';
for (let buffer of data) { for (let buffer of data) {
str += decoder.decode(buffer, {stream: true}); str += decoder.decode(buffer, {'stream': true});
} }
str += decoder.decode(); // end-of-stream str += decoder.decode(); // end-of-stream
//remove crossorigin and integrity attributes // remove crossorigin and integrity attributes
str = str.replace(/<(link|script)[^>]+>/ig, m => { str = str.replace(/<(link|script)[^>]+>/ig, (m) => {
// eslint-disable-next-line no-use-before-define
if (cdnDomainsRE.test(m)) { if (cdnDomainsRE.test(m)) {
return m.replace(/\s+(integrity|crossorigin)(="[^"]*"|='[^']*'|=[^"'`=>\s]+|)/ig, ''); return m.replace(/\s+(integrity|crossorigin)(="[^"]*"|='[^']*'|=[^"'`=>\s]+|)/ig, '');
} }
@ -109,9 +114,9 @@ manipulateDOM._removeCrossOriginAndIntegrityAttr = function (details) {
}); });
filter.write(encoder.encode(str)); filter.write(encoder.encode(str));
filter.close(); filter.close();
};
} }
} return {'responseHeaders': details.responseHeaders};
return {responseHeaders: details.responseHeaders};
} }
}; };
@ -121,13 +126,14 @@ manipulateDOM._removeCrossOriginAndIntegrityAttr = function (details) {
* Initializations * Initializations
*/ */
let allowlistedDomains = {}; /* eslint-disable one-var */
let cdnDomainsRE = new RegExp('//(' + Object.keys(mappings.cdn).map(m => m.replace(/\W/g, '\\$&')).join('|') + ')/'); let cdnDomainsRE = new RegExp(`//(${Object.keys(mappings.cdn).map((m) => m.replace(/\W/g, '\\$&')).join('|')})/`);
/* eslint-enable one-var */
/** /**
* Event Handlers * Event Handlers
*/ */
chrome.webRequest.onHeadersReceived.addListener( chrome.webRequest.onHeadersReceived.addListener(
manipulateDOM._removeCrossOriginAndIntegrityAttr, manipulateDOM._removeCrossOriginAndIntegrityAttr,

View File

@ -18,6 +18,7 @@
'use strict'; 'use strict';
/** /**
* Mappings * Mappings
*/ */
@ -490,7 +491,7 @@ mappings.cdn = {
'jquery-ui-dist@{version}/jquery-ui.js': resources.jQueryUI, 'jquery-ui-dist@{version}/jquery-ui.js': resources.jQueryUI,
'jquery-ui-dist@{version}/jquery-ui.min.js': resources.jQueryUI, 'jquery-ui-dist@{version}/jquery-ui.min.js': resources.jQueryUI,
'jquery-validation@{version}/dist/jquery.validate.': resources.jqueryValidationPlugin, 'jquery-validation@{version}/dist/jquery.validate.': resources.jqueryValidationPlugin,
'js-cookie@beta/dist/js.cookie.':resources.jscookie, 'js-cookie@beta/dist/js.cookie.': resources.jscookie,
'lodash@{version}/lodash.min.js': resources.lodashJS, 'lodash@{version}/lodash.min.js': resources.lodashJS,
'lozad': resources.lozad, 'lozad': resources.lozad,
'npm-modernizr@{version}/modernizr.': resources.modernizr, 'npm-modernizr@{version}/modernizr.': resources.modernizr,
@ -818,7 +819,7 @@ mappings.cdn = {
}, },
// Tencent Public Libraries // Tencent Public Libraries
'mat1.gtimg.com': { 'mat1.gtimg.com': {
'/libs/' :{ '/libs/': {
'angular.js/{version}/angular-animate.': resources.angularAnimate, 'angular.js/{version}/angular-animate.': resources.angularAnimate,
'angular.js/{version}/angular-aria.': resources.angularAria, 'angular.js/{version}/angular-aria.': resources.angularAria,
'angular.js/{version}/angular-cookies.': resources.angularCookies, 'angular.js/{version}/angular-cookies.': resources.angularCookies,
@ -966,7 +967,7 @@ mappings.cdn['sdn.geekzu.org'] = {
// USTC Linux User Group [Mirror] // USTC Linux User Group [Mirror]
mappings.cdn['ajax.proxy.ustclug.org'] = mappings.cdn['ajax.googleapis.com']; mappings.cdn['ajax.proxy.ustclug.org'] = mappings.cdn['ajax.googleapis.com'];
//UNPKG (Cloudflare) // UNPKG (Cloudflare)
mappings.cdn['unpkg.com'] = { mappings.cdn['unpkg.com'] = {
'/': mappings.cdn['cdn.jsdelivr.net']['/npm/'] '/': mappings.cdn['cdn.jsdelivr.net']['/npm/']
}; };
@ -990,7 +991,7 @@ mappings.cdn['fonts.loli.net'] = mappings.cdn['fonts.googleapis.com'];
// Qihoo 360 CDN [Mirror] // Qihoo 360 CDN [Mirror]
mappings.cdn['lib.baomitu.com'] = { mappings.cdn['lib.baomitu.com'] = {
'/': mappings.cdn['cdnjs.cloudflare.com']['/ajax/libs/'] '/': mappings.cdn['cdnjs.cloudflare.com']['/ajax/libs/']
} };
// Boot CDN New [Mirror] // Boot CDN New [Mirror]
mappings.cdn['cdn.bootcdn.net'] = mappings.cdn['cdnjs.cloudflare.com']; mappings.cdn['cdn.bootcdn.net'] = mappings.cdn['cdnjs.cloudflare.com'];

View File

@ -18,12 +18,14 @@
'use strict'; 'use strict';
/** /**
* Messenger * Messenger
*/ */
var messenger = {}; var messenger = {};
/** /**
* Private Methods * Private Methods
*/ */
@ -97,6 +99,7 @@ messenger._handleMessageReceived = function (message, sender, sendResponse) {
} }
}; };
/** /**
* Event Handlers * Event Handlers
*/ */

View File

@ -18,12 +18,14 @@
'use strict'; 'use strict';
/** /**
* Request Analyzer * Request Analyzer
*/ */
var requestAnalyzer = {}; var requestAnalyzer = {};
/** /**
* Public Methods * Public Methods
*/ */
@ -64,9 +66,10 @@ requestAnalyzer.isValidCandidate = function (requestDetails, tabDetails) {
}; };
requestAnalyzer.getLocalTarget = function (requestDetails) { requestAnalyzer.getLocalTarget = function (requestDetails) {
let destinationUrl, destinationHost, destinationPath, hostMappings, basePath, resourceMappings; let destinationUrl, destinationHost, destinationPath, hostMappings, basePath,
let destinationSearchString = ''; resourceMappings, destinationSearchString;
destinationSearchString = '';
destinationUrl = new URL(requestDetails.url); destinationUrl = new URL(requestDetails.url);
destinationHost = destinationUrl.host; destinationHost = destinationUrl.host;
@ -91,9 +94,11 @@ requestAnalyzer.getLocalTarget = function (requestDetails) {
} }
// Return either the local target's path or false. // Return either the local target's path or false.
// eslint-disable-next-line max-len
return requestAnalyzer._findLocalTarget(resourceMappings, basePath, destinationHost, destinationPath, destinationSearchString); return requestAnalyzer._findLocalTarget(resourceMappings, basePath, destinationHost, destinationPath, destinationSearchString);
}; };
/** /**
* Private Methods * Private Methods
*/ */
@ -108,6 +113,7 @@ requestAnalyzer._matchBasePath = function (hostMappings, channelPath) {
return false; return false;
}; };
// eslint-disable-next-line max-len
requestAnalyzer._findLocalTarget = function (resourceMappings, basePath, channelHost, channelPath, destinationSearchString) { requestAnalyzer._findLocalTarget = function (resourceMappings, basePath, channelHost, channelPath, destinationSearchString) {
let resourcePath, versionNumber, resourcePattern, filename, shorthandResource; let resourcePath, versionNumber, resourcePattern, filename, shorthandResource;
@ -119,7 +125,7 @@ requestAnalyzer._findLocalTarget = function (resourceMappings, basePath, channel
if (Resource.SINGLE_NUMBER_EXPRESSION.test(channelPath)) { if (Resource.SINGLE_NUMBER_EXPRESSION.test(channelPath)) {
versionNumber = channelPath.match(/\d/); versionNumber = channelPath.match(/\d/);
resourcePattern = resourcePath.replace(versionNumber, Resource.VERSION_PLACEHOLDER); resourcePattern = resourcePath.replace(versionNumber, Resource.VERSION_PLACEHOLDER);
versionNumber = [versionNumber + '.0']; versionNumber = [`${versionNumber}.0`];
} else { } else {
versionNumber = resourcePath.match(Resource.VERSION_EXPRESSION); versionNumber = resourcePath.match(Resource.VERSION_EXPRESSION);
resourcePattern = resourcePath.replace(versionNumber, Resource.VERSION_PLACEHOLDER); resourcePattern = resourcePath.replace(versionNumber, Resource.VERSION_PLACEHOLDER);
@ -128,14 +134,14 @@ requestAnalyzer._findLocalTarget = function (resourceMappings, basePath, channel
shorthandResource = shorthands.specialFiles(channelHost, channelPath, destinationSearchString); shorthandResource = shorthands.specialFiles(channelHost, channelPath, destinationSearchString);
if (shorthandResource) { if (shorthandResource) {
if (requestAnalyzer.logging) { if (requestAnalyzer.logging) {
console.log('[ LocalCDN ] Replaced resource: ' + shorthandResource.path); console.log(`[ LocalCDN ] Replaced resource: ${shorthandResource.path}`);
} }
return shorthandResource; return shorthandResource;
} }
for (let resourceMold of Object.keys(resourceMappings)) { for (let resourceMold of Object.keys(resourceMappings)) {
if (resourcePattern.startsWith(resourceMold)) { if (resourcePattern.startsWith(resourceMold)) {
let targetPath, versionDelivered, versionRequested; let targetPath, versionDelivered, versionRequested, bundle;
targetPath = resourceMappings[resourceMold].path; targetPath = resourceMappings[resourceMold].path;
targetPath = targetPath.replace(Resource.VERSION_PLACEHOLDER, versionNumber); targetPath = targetPath.replace(Resource.VERSION_PLACEHOLDER, versionNumber);
@ -154,15 +160,15 @@ requestAnalyzer._findLocalTarget = function (resourceMappings, basePath, channel
} }
// Get bundle name // Get bundle name
let bundle = targets.determineBundle(targetPath); bundle = targets.determineBundle(targetPath);
if (bundle !== '') { if (bundle !== '') {
filename = channelPath.split('/').pop(); filename = channelPath.split('/').pop();
targetPath = ( filename.endsWith('.js') ) ? targetPath + filename + 'm' : targetPath + filename; targetPath = (filename.endsWith('.js')) ? `${targetPath + filename}m` : targetPath + filename;
targetPath = helpers.formatFilename(targetPath); targetPath = helpers.formatFilename(targetPath);
} }
if (requestAnalyzer.logging) { if (requestAnalyzer.logging) {
console.log('[ LocalCDN ] Replaced resource: ' + targetPath); console.log(`[ LocalCDN ] Replaced resource: ${targetPath}`);
} }
// Prepare and return a local target. // Prepare and return a local target.
return { return {
@ -176,7 +182,7 @@ requestAnalyzer._findLocalTarget = function (resourceMappings, basePath, channel
} }
if (requestAnalyzer.logging && !IgnoredHost[channelHost]) { if (requestAnalyzer.logging && !IgnoredHost[channelHost]) {
console.warn('[ LocalCDN ] Missing resource: ' + channelHost + channelPath); console.warn(`[ LocalCDN ] Missing resource: ${channelHost}${channelPath}`);
} }
return false; return false;
}; };
@ -197,6 +203,7 @@ requestAnalyzer._applyAllowedDomainsGoogleFonts = function () {
}); });
}; };
/** /**
* Initializations * Initializations
*/ */
@ -209,6 +216,8 @@ requestAnalyzer._applyManipulateDOMDomains();
requestAnalyzer.domainsGoogleFonts = {}; requestAnalyzer.domainsGoogleFonts = {};
requestAnalyzer._applyAllowedDomainsGoogleFonts(); requestAnalyzer._applyAllowedDomainsGoogleFonts();
/** /**
* Event Handlers * Event Handlers
*/ */

View File

@ -13,12 +13,14 @@
'use strict'; 'use strict';
/** /**
* Request Sanitizer * Request Sanitizer
*/ */
var requestSanitizer = {}; var requestSanitizer = {};
/** /**
* Public Methods * Public Methods
*/ */
@ -41,6 +43,7 @@ requestSanitizer.disable = function () {
}, [WebRequest.BLOCKING, WebRequest.HEADERS]); }, [WebRequest.BLOCKING, WebRequest.HEADERS]);
}; };
/** /**
* Private Methods * Private Methods
*/ */
@ -69,6 +72,7 @@ requestSanitizer._stripMetadata = function (requestDetails) {
}; };
}; };
/** /**
* Initializations * Initializations
*/ */

View File

@ -18,6 +18,7 @@
'use strict'; 'use strict';
/** /**
* Resources * Resources
*/ */

View File

@ -18,6 +18,7 @@
'use strict'; 'use strict';
/** /**
* Shorthands * Shorthands
*/ */
@ -25,14 +26,17 @@
var shorthands = {}; var shorthands = {};
shorthands.specialFiles = function (channelHost, channelPath, searchString) { shorthands.specialFiles = function (channelHost, channelPath, searchString) {
let lastVersion;
/*
NOTE:
jsDelivr allows to load several files in one request
This is just a workaround. If there are more websites which use this, we will have to do crazy things here to find and redirect these files.
It's not possible to respond to a request with multiple redirections let lastVersion;
https://gitlab.com/nobody42/localcdn/-/issues/45
/**
* NOTE:
* jsDelivr allows to load several files in one request
* This is just a workaround. If there are more websites which use this,
* we will have to do crazy things here to find and redirect these files.
*
* It's not possible to respond to a request with multiple redirections
* https://gitlab.com/nobody42/localcdn/-/issues/45
*/ */
if (Regex.JSDELIVR_COMBINE.test(channelHost + channelPath)) { if (Regex.JSDELIVR_COMBINE.test(channelHost + channelPath)) {
@ -63,7 +67,7 @@ shorthands.specialFiles = function (channelHost, channelPath, searchString) {
return { return {
'source': channelHost, 'source': channelHost,
'versionDelivered': lastVersion, 'versionDelivered': lastVersion,
'path': 'resources/bootstrap-datepicker/' + lastVersion + '/bootstrap-datepicker3.standalone.min.css', 'path': `resources/bootstrap-datepicker/${lastVersion}/bootstrap-datepicker3.standalone.min.css`,
'bundle': '' 'bundle': ''
}; };
} else if (Regex.BOOTSTRAP_DATEPICKER.test(channelPath)) { } else if (Regex.BOOTSTRAP_DATEPICKER.test(channelPath)) {
@ -71,7 +75,7 @@ shorthands.specialFiles = function (channelHost, channelPath, searchString) {
return { return {
'source': channelHost, 'source': channelHost,
'versionDelivered': lastVersion, 'versionDelivered': lastVersion,
'path': 'resources/bootstrap-datepicker/' + lastVersion + '/bootstrap-datepicker.standalone.min.css', 'path': `resources/bootstrap-datepicker/${lastVersion}/bootstrap-datepicker.standalone.min.css`,
'bundle': '' 'bundle': ''
}; };
} else if (Regex.FONT_AWESOME.test(channelHost + channelPath)) { } else if (Regex.FONT_AWESOME.test(channelHost + channelPath)) {
@ -90,7 +94,7 @@ shorthands.specialFiles = function (channelHost, channelPath, searchString) {
'source': channelHost, 'source': channelHost,
'versionRequested': '4.6.3', 'versionRequested': '4.6.3',
'versionDelivered': lastVersion, 'versionDelivered': lastVersion,
'path': 'resources/webfont/fa-loader.' + fileExtension, 'path': `resources/webfont/fa-loader.${fileExtension}`,
'bundle': '' 'bundle': ''
}; };
} else if ((channelHost + channelPath) === 'cdn.jsdelivr.net/npm/vue') { } else if ((channelHost + channelPath) === 'cdn.jsdelivr.net/npm/vue') {
@ -99,7 +103,7 @@ shorthands.specialFiles = function (channelHost, channelPath, searchString) {
'source': channelHost, 'source': channelHost,
'versionRequested': 'latest', 'versionRequested': 'latest',
'versionDelivered': lastVersion, 'versionDelivered': lastVersion,
'path': 'resources/vue/' + lastVersion + '/vue.min.jsm', 'path': `resources/vue/${lastVersion}/vue.min.jsm`,
'bundle': '' 'bundle': ''
}; };
} else if ((channelHost + channelPath) === 'ajax.cloudflare.com/cdn-cgi/scripts/7089c43e/cloudflare-static/rocket-loader.min.js') { } else if ((channelHost + channelPath) === 'ajax.cloudflare.com/cdn-cgi/scripts/7089c43e/cloudflare-static/rocket-loader.min.js') {
@ -115,7 +119,7 @@ shorthands.specialFiles = function (channelHost, channelPath, searchString) {
'source': channelHost, 'source': channelHost,
'versionRequested': '4.1.1', 'versionRequested': '4.1.1',
'versionDelivered': lastVersion, 'versionDelivered': lastVersion,
'path': 'resources/object-assign/' + lastVersion + '/object-assign.min.jsm', 'path': `resources/object-assign/${lastVersion}/object-assign.min.jsm`,
'bundle': '' 'bundle': ''
}; };
} else if ((channelHost + channelPath) === 'netdna.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css') { } else if ((channelHost + channelPath) === 'netdna.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css') {
@ -124,7 +128,7 @@ shorthands.specialFiles = function (channelHost, channelPath, searchString) {
return { return {
'source': channelHost, 'source': channelHost,
'versionRequested': lastVersion, 'versionRequested': lastVersion,
'path': 'resources/font-awesome/' + lastVersion + '/css/font-awesome.min.css', 'path': `resources/font-awesome/${lastVersion}/css/font-awesome.min.css`,
'bundle': '' 'bundle': ''
}; };
} else if ((channelHost + channelPath) === 'cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.0.0-beta.2.4/owl.carousel.min.js') { } else if ((channelHost + channelPath) === 'cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.0.0-beta.2.4/owl.carousel.min.js') {
@ -144,7 +148,7 @@ shorthands.specialFiles = function (channelHost, channelPath, searchString) {
'source': channelHost, 'source': channelHost,
'versionDelivered': lastVersion, 'versionDelivered': lastVersion,
'versionRequested': '4.1.0-beta.1', 'versionRequested': '4.1.0-beta.1',
'path': 'resources/select2/' + lastVersion + '/' + helpers.extractFilenameFromPath(channelPath), 'path': `resources/select2/${lastVersion}/${helpers.extractFilenameFromPath(channelPath)}`,
'bundle': 'Select2' 'bundle': 'Select2'
}; };
} else if (channelHost + channelPath === 'cdn.jsdelivr.net/npm/anchor-js/anchor.min.js') { } else if (channelHost + channelPath === 'cdn.jsdelivr.net/npm/anchor-js/anchor.min.js') {
@ -154,13 +158,13 @@ shorthands.specialFiles = function (channelHost, channelPath, searchString) {
'source': channelHost, 'source': channelHost,
'versionDelivered': lastVersion, 'versionDelivered': lastVersion,
'versionRequested': lastVersion, 'versionRequested': lastVersion,
'path': 'resources/anchor-js/' + lastVersion + '/anchor.min.jsm', 'path': `resources/anchor-js/${lastVersion}/anchor.min.jsm`,
'bundle': '' 'bundle': ''
}; };
} else if (Regex.BOOTSTRAP_FONTS_ONLY.test(channelPath)) { } else if (Regex.BOOTSTRAP_FONTS_ONLY.test(channelPath)) {
return { return {
'source': channelHost, 'source': channelHost,
'path': 'resources/twitter-bootstrap/fonts/' + helpers.extractFilenameFromPath(channelPath), 'path': `resources/twitter-bootstrap/fonts/${helpers.extractFilenameFromPath(channelPath)}`,
'bundle': 'Bootstrap (Fonts)' 'bundle': 'Bootstrap (Fonts)'
}; };
} else if (channelHost + channelPath === 'cdn.jsdelivr.net/npm/js-cookie@beta/dist/js.cookie.min.js') { } else if (channelHost + channelPath === 'cdn.jsdelivr.net/npm/js-cookie@beta/dist/js.cookie.min.js') {

View File

@ -18,12 +18,14 @@
'use strict'; 'use strict';
/** /**
* State Manager * State Manager
*/ */
var stateManager = {}; var stateManager = {};
/** /**
* Public Methods * Public Methods
*/ */
@ -251,7 +253,7 @@ stateManager._domainIsListed = function (domain, listname) {
let allowlistRecord, isAllowlisted; let allowlistRecord, isAllowlisted;
if (listname === "manipulate-dom") { if (listname === 'manipulate-dom') {
allowlistRecord = requestAnalyzer.domainsManipulateDOM[domain]; allowlistRecord = requestAnalyzer.domainsManipulateDOM[domain];
isAllowlisted = Boolean(allowlistRecord); isAllowlisted = Boolean(allowlistRecord);
} else { } else {

View File

@ -14,12 +14,21 @@
'use strict'; 'use strict';
/**
* Constants
*/
const InvalidFile = 'Invalid file!';
/** /**
* Storage Manager * Storage Manager
*/ */
var storageManager = {}; var storageManager = {};
/** /**
* Public Methods * Public Methods
*/ */
@ -78,12 +87,12 @@ storageManager.migrateData = function (target) {
storageManager.export = function () { storageManager.export = function () {
let filename = new Date().toISOString(); let filename = new Date().toISOString();
filename = filename.substring(0, 10) + '_localcdn_backup.txt'; filename = `${filename.substring(0, 10)}_localcdn_backup.txt`;
storageManager.type.get(null, function (items) { storageManager.type.get(null, function (items) {
delete items['whitelistedDomains']; delete items['whitelistedDomains'];
let element = document.createElement('a'); let element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(items, null, ' '))); element.setAttribute('href', `data:text/plain;charset=utf-8,${encodeURIComponent(JSON.stringify(items, null, ' '))}`);
element.setAttribute('download', filename); element.setAttribute('download', filename);
element.style.display = 'none'; element.style.display = 'none';
document.body.appendChild(element); document.body.appendChild(element);
@ -169,13 +178,13 @@ storageManager._validation = function (content) {
// Set default if not existing in file // Set default if not existing in file
imported[key] = value; imported[key] = value;
} else { } else {
alert(chrome.i18n.getMessage('dialogImportFailed') + '\n\n' + key + ': ' + content[key]); alert(`${chrome.i18n.getMessage('dialogImportFailed')}\n\n${key}: ${content[key]}`);
throw 'Invalid file!'; throw InvalidFile;
} }
} }
// set values directly // set values directly
wrappers.setIcon({ path: imported['selectedIcon'] }, 'Enabled'); wrappers.setIcon({'path': imported['selectedIcon']}, 'Enabled');
storageManager.amountInjected = imported['amountInjected']; storageManager.amountInjected = imported['amountInjected'];
storageManager.statistics = imported['internalStatisticsData']; storageManager.statistics = imported['internalStatisticsData'];
@ -187,13 +196,15 @@ storageManager._validation = function (content) {
storageManager._validateDomainsAndStatistics = function (type, obj) { storageManager._validateDomainsAndStatistics = function (type, obj) {
let valid = {}; let valid = {};
if (type === 'allowedDomainsGoogleFonts' || type === 'domainsManipulateDOM' || type === 'allowlistedDomains') { if (type === 'allowedDomainsGoogleFonts' || type === 'domainsManipulateDOM' || type === 'allowlistedDomains') {
for (const [key, value] of Object.entries(obj)) { for (const [key, value] of Object.entries(obj)) {
// eslint-disable-next-line no-useless-escape
if ((/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,24}/.test(key) || key === '') && value === true) { if ((/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,24}/.test(key) || key === '') && value === true) {
valid[key] = value; valid[key] = value;
} else { } else {
alert(chrome.i18n.getMessage('dialogImportFailed') + ': ' + key); alert(`${chrome.i18n.getMessage('dialogImportFailed')}: ${key}`);
throw 'Invalid file!'; throw InvalidFile;
} }
} }
} else if (type === 'internalStatisticsData') { } else if (type === 'internalStatisticsData') {
@ -202,32 +213,34 @@ storageManager._validateDomainsAndStatistics = function (type, obj) {
for (const [types, category] of Object.entries(values)) { for (const [types, category] of Object.entries(values)) {
if (types === 'frameworks') { if (types === 'frameworks') {
for (const [name, counter] of Object.entries(category)) { for (const [name, counter] of Object.entries(category)) {
if (!/resources\/[0-9a-z.-]+\/((?:\d{1,2}\.){1,3}\d{1,2})?.*\.(css|jsm)/.test(name) && !storageManager._validateNumbers(counter)) { // eslint-disable-next-line max-len
alert(chrome.i18n.getMessage('dialogImportFailed') + ': ' + name); if (!(/resources\/[0-9a-z.-]+\/((?:\d{1,2}\.){1,3}\d{1,2})?.*\.(css|jsm)/).test(name) && !storageManager._validateNumbers(counter)) {
throw 'Invalid file!'; alert(`${chrome.i18n.getMessage('dialogImportFailed')}: ${name}`);
throw InvalidFile;
} }
} }
} else if (types === 'cdns') { } else if (types === 'cdns') {
for (const [name, counter] of Object.entries(category)) { for (const [name, counter] of Object.entries(category)) {
if (!/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,24}/.test(name) && !storageManager._validateNumbers(counter)) { // eslint-disable-next-line no-useless-escape, max-len
alert(chrome.i18n.getMessage('dialogImportFailed') + ': ' + name); if (!(/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,24}/).test(name) && !storageManager._validateNumbers(counter)) {
throw 'Invalid file!'; alert(`${chrome.i18n.getMessage('dialogImportFailed')}: ${name}`);
throw InvalidFile;
} }
} }
} else { } else {
alert(chrome.i18n.getMessage('dialogImportFailed') + ': ' + type); alert(`${chrome.i18n.getMessage('dialogImportFailed')}: ${type}`);
throw 'Invalid file!'; throw InvalidFile;
} }
} }
} else { } else {
alert(chrome.i18n.getMessage('dialogImportFailed') + ': ' + date); alert(`${chrome.i18n.getMessage('dialogImportFailed')}: ${date}`);
throw 'Invalid file!'; throw InvalidFile;
} }
} }
valid = obj; valid = obj;
} else { } else {
alert(chrome.i18n.getMessage('dialogImportFailed') + ': ' + type); alert(`${chrome.i18n.getMessage('dialogImportFailed')}: ${type}`);
throw 'Invalid file!'; throw InvalidFile;
} }
return valid; return valid;
}; };
@ -252,6 +265,11 @@ storageManager._validateNumbers = function (value) {
return isNaN(value) ? 0 : value; return isNaN(value) ? 0 : value;
}; };
/**
* Initializations
*/
storageManager.data = {}; storageManager.data = {};
storageManager.type = chrome.storage.local; storageManager.type = chrome.storage.local;
storageManager.amountInjected = 0; storageManager.amountInjected = 0;

View File

@ -18,12 +18,14 @@
'use strict'; 'use strict';
/** /**
* Helpers * Helpers
*/ */
var helpers = {}; var helpers = {};
/** /**
* Public Methods * Public Methods
*/ */
@ -73,10 +75,10 @@ helpers.languageIsFullySupported = function (language) {
languageSupported = false; languageSupported = false;
supportedLanguages = [ supportedLanguages = [
'ar','bg','cs','da','de','el','en','en_CA','en_US','eo','es','et','fi', 'ar', 'bg', 'cs', 'da', 'de', 'el', 'en', 'en_CA', 'en_US', 'eo', 'es', 'et', 'fi',
'fr','he','hr','hu','id','is','it','ja','kn','ko','lb','lt', 'fr', 'he', 'hr', 'hu', 'id', 'is', 'it', 'ja', 'kn', 'ko', 'lb', 'lt',
'nb_NO','nl','pl','pt','pt_BR','pt_PT','ro','ru','sk','sr','sv','tl', 'nb_NO', 'nl', 'pl', 'pt', 'pt_BR', 'pt_PT', 'ro', 'ru', 'sk', 'sr', 'sv', 'tl',
'tr','zh_Hans','zh_Hant' 'tr', 'zh_Hans', 'zh_Hant'
]; ];
for (let supportedLanguage of supportedLanguages) { for (let supportedLanguage of supportedLanguages) {
@ -120,8 +122,8 @@ helpers.extractDomainFromUrl = function (url, normalize) {
return extractedDomain; return extractedDomain;
}; };
helpers.getWildcard = function(initiatorDomain) { helpers.getWildcard = function (initiatorDomain) {
let domain = initiatorDomain.split("."); let domain = initiatorDomain.split('.');
if (domain.length > 2) { if (domain.length > 2) {
domain[0] = '*'; domain[0] = '*';
@ -131,7 +133,7 @@ helpers.getWildcard = function(initiatorDomain) {
}; };
helpers.checkAllowlisted = function(domain) { helpers.checkAllowlisted = function (domain) {
let domainWithoutPrefix, wildcard, list; let domainWithoutPrefix, wildcard, list;
if (domain.startsWith(Address.WWW_PREFIX)) { if (domain.startsWith(Address.WWW_PREFIX)) {
@ -213,8 +215,12 @@ helpers.compareVersion = function (v1, v2) {
for (let i = 0; i < k; ++i) { for (let i = 0; i < k; ++i) {
v1[i] = parseInt(v1[i], 10); v1[i] = parseInt(v1[i], 10);
v2[i] = parseInt(v2[i], 10); v2[i] = parseInt(v2[i], 10);
if (v1[i] > v2[i]) return true; if (v1[i] > v2[i]) {
if (v1[i] < v2[i]) return false; return true;
} }
return v1.length == v2.length ? true : v1.length < v2.length ? false : true; if (v1[i] < v2[i]) {
return false;
}
}
return v1.length === v2.length ? true : v1.length < v2.length ? false : true;
}; };

View File

@ -14,16 +14,19 @@
'use strict'; 'use strict';
/** /**
* Updates * Updates
*/ */
var ruleGenerator = {}; var ruleGenerator = {};
/** /**
* Public Methods * Public Methods
*/ */
ruleGenerator.openRuleSet = function ({ target }) {
ruleGenerator.openRuleSet = function ({target}) {
let urls, key, textArea, btnCopy, content; let urls, key, textArea, btnCopy, content;
urls = mappings.cdn; urls = mappings.cdn;
@ -35,14 +38,14 @@ ruleGenerator.openRuleSet = function ({ target }) {
textArea.style.display = 'block'; textArea.style.display = 'block';
btnCopy.style.display = 'block'; btnCopy.style.display = 'block';
for (var domain in urls) { for (const domain in urls) {
if (key === 'uMatrix') { if (key === 'uMatrix') {
content += '* ' + domain + ' script allow' + '\n'; content += `* ${domain} script allow\n`;
content += '* ' + domain + ' css allow' + '\n'; content += `* ${domain} css allow\n`;
} else if (key === 'uBlock') { } else if (key === 'uBlock') {
content += '* ' + domain + ' * noop' + '\n'; content += `* ${domain} * noop\n`;
} else if (key === 'AdGuard') { } else if (key === 'AdGuard') {
content += '@@||' + domain + '^\n'; content += `@@||${domain}^\n`;
} }
} }
textArea.value = content.replace(/\n+$/, ''); textArea.value = content.replace(/\n+$/, '');

View File

@ -15,11 +15,18 @@
'use strict'; 'use strict';
/** /**
* Stats * Stats
*/ */
var stats = {}; var stats = {};
/**
* Public Methods
*/
stats.setStats = function (injection) { stats.setStats = function (injection) {
let data, today, cdn, framework, newEntry, pathSegments; let data, today, cdn, framework, newEntry, pathSegments;
@ -29,7 +36,7 @@ stats.setStats = function (injection) {
if (injection.bundle !== '') { if (injection.bundle !== '') {
pathSegments = injection.path.split('/'); pathSegments = injection.path.split('/');
framework = pathSegments[0] + '/' + pathSegments[1] + '/' + pathSegments[2] + '/'; framework = `${pathSegments[0]}/${pathSegments[1]}/${pathSegments[2]}/`;
} else { } else {
framework = injection.path; framework = injection.path;
} }
@ -38,15 +45,15 @@ stats.setStats = function (injection) {
if (cdn in data[today]['cdns']) { if (cdn in data[today]['cdns']) {
data[today]['cdns'][cdn] = ++data[today]['cdns'][cdn]; data[today]['cdns'][cdn] = ++data[today]['cdns'][cdn];
} else { } else {
Object.assign(data[today]['cdns'], { [cdn]: 1 }); Object.assign(data[today]['cdns'], {[cdn]: 1});
} }
if (framework in data[today]['frameworks']) { if (framework in data[today]['frameworks']) {
data[today]['frameworks'][framework] = ++data[today]['frameworks'][framework]; data[today]['frameworks'][framework] = ++data[today]['frameworks'][framework];
} else { } else {
Object.assign(data[today]['frameworks'], { [framework]: 1 }); Object.assign(data[today]['frameworks'], {[framework]: 1});
} }
} else { } else {
newEntry = { frameworks: { [framework]: 1 }, cdns: { [cdn]: 1 } }; newEntry = {'frameworks': {[framework]: 1}, 'cdns': {[cdn]: 1}};
data[today] = newEntry; data[today] = newEntry;
} }

View File

@ -14,12 +14,14 @@
'use strict'; 'use strict';
/** /**
* Targets * Targets
*/ */
var targets = {}; var targets = {};
/** /**
* Public Methods * Public Methods
*/ */
@ -49,7 +51,7 @@ targets.determineBundle = function (path) {
val = 'Bootstrap (Fonts)'; val = 'Bootstrap (Fonts)';
} }
return val === '' ? val : val + ' (Bundle)'; return val === '' ? val : `${val} (Bundle)`;
}; };
targets.setLastVersion = function (type, version) { targets.setLastVersion = function (type, version) {
@ -189,7 +191,7 @@ targets.setLastVersion = function (type, version) {
return '2.25.6'; return '2.25.6';
} else if (type.startsWith('/dayjs/1.')) { } else if (type.startsWith('/dayjs/1.')) {
return '1.10.4'; return '1.10.4';
} else if (type.startsWith('/dexie/3.') || type.startsWith('/dexie/latest') ) { } else if (type.startsWith('/dexie/3.') || type.startsWith('/dexie/latest')) {
return '3.0.3'; return '3.0.3';
} else if (type.startsWith('/docsearch.js/2.')) { } else if (type.startsWith('/docsearch.js/2.')) {
return '2.6.3'; return '2.6.3';
@ -499,6 +501,7 @@ targets.setLastVersion = function (type, version) {
}; };
targets.determineResourceName = function (filename) { targets.determineResourceName = function (filename) {
// eslint-disable-next-line no-use-before-define
return ListOfFiles[filename] || 'Unknown'; return ListOfFiles[filename] || 'Unknown';
}; };

View File

@ -17,12 +17,14 @@
'use strict'; 'use strict';
/** /**
* Wrappers * Wrappers
*/ */
var wrappers = {}; var wrappers = {};
/** /**
* Public Methods * Public Methods
*/ */
@ -64,6 +66,6 @@ storageManager.type.get([Setting.BADGE_COLOR, Setting.BADGE_TEXT_COLOR], functio
wrappers.textColor = items.badgeTextColor || '#FFFFFF'; wrappers.textColor = items.badgeTextColor || '#FFFFFF';
wrappers.backgroundColor = items.badgeColor || '#4A826C'; wrappers.backgroundColor = items.badgeColor || '#4A826C';
wrappers.setBadgeTextColor({color: wrappers.textColor}); wrappers.setBadgeTextColor({'color': wrappers.textColor});
wrappers.setBadgeBackgroundColor({color: wrappers.backgroundColor}); wrappers.setBadgeBackgroundColor({'color': wrappers.backgroundColor});
}); });

View File

@ -14,12 +14,18 @@
'use strict'; 'use strict';
/** /**
* Help * Help
*/ */
var help = {}; var help = {};
/**
* Private Methods
*/
help._onDocumentLoaded = function () { help._onDocumentLoaded = function () {
let language = navigator.language; let language = navigator.language;
@ -29,4 +35,9 @@ help._onDocumentLoaded = function () {
helpers.insertI18nContentIntoDocument(document); helpers.insertI18nContentIntoDocument(document);
}; };
/**
* Initializations
*/
document.addEventListener('DOMContentLoaded', help._onDocumentLoaded); document.addEventListener('DOMContentLoaded', help._onDocumentLoaded);

View File

@ -18,12 +18,14 @@
'use strict'; 'use strict';
/** /**
* Options * Options
*/ */
var options = {}; var options = {};
/** /**
* Private Methods * Private Methods
*/ */
@ -55,9 +57,10 @@ options._renderContents = function () {
}; };
options._renderOptionsPanel = function () { options._renderOptionsPanel = function () {
let allowlistedDomains, domainAllowlist, elements, htmlFilterDomains, domainHtmlFilter, googleFontsDomains, domainAllowedGoogleFonts, url, bgColor, txtColor; let allowlistedDomains, domainAllowlist, elements, htmlFilterDomains, domainHtmlFilter,
googleFontsDomains, domainAllowedGoogleFonts, url, bgColor, txtColor;
Object.assign(options._optionValues, { [Setting.INTERNAL_STATISTICS]: options._internalStatistics }); Object.assign(options._optionValues, {[Setting.INTERNAL_STATISTICS]: options._internalStatistics});
allowlistedDomains = options._optionValues.allowlistedDomains; allowlistedDomains = options._optionValues.allowlistedDomains;
domainAllowlist = options._serializeAllowlistedDomains(allowlistedDomains); domainAllowlist = options._serializeAllowlistedDomains(allowlistedDomains);
@ -69,9 +72,9 @@ options._renderOptionsPanel = function () {
domainAllowedGoogleFonts = options._serializeAllowlistedDomains(googleFontsDomains); domainAllowedGoogleFonts = options._serializeAllowlistedDomains(googleFontsDomains);
elements = options._optionElements; elements = options._optionElements;
Object.assign(elements, { [Setting.INTERNAL_STATISTICS]: document.getElementById('checkbox-internal-statistics') }); Object.assign(elements, {[Setting.INTERNAL_STATISTICS]: document.getElementById('checkbox-internal-statistics')});
Object.assign(elements, { [Setting.SELECTED_ICON]: document.getElementsByName('selected-icon') }); Object.assign(elements, {[Setting.SELECTED_ICON]: document.getElementsByName('selected-icon')});
elements.showIconBadge.checked = options._optionValues.showIconBadge; elements.showIconBadge.checked = options._optionValues.showIconBadge;
elements.blockMissing.checked = options._optionValues.blockMissing; elements.blockMissing.checked = options._optionValues.blockMissing;
@ -111,14 +114,16 @@ options._renderOptionsPanel = function () {
} }
if (options._platformSupportIcons) { if (options._platformSupportIcons) {
if (options._optionValues.selectedIcon === 'Default') { let selectedIcon = options._optionValues.selectedIcon;
if (selectedIcon === 'Default') {
document.getElementById('icon-default').checked = true; document.getElementById('icon-default').checked = true;
} else if (options._optionValues.selectedIcon === 'Grey') { } else if (selectedIcon === 'Grey') {
document.getElementById('icon-grey').checked = true; document.getElementById('icon-grey').checked = true;
} else if (options._optionValues.selectedIcon === 'Light') { } else if (selectedIcon === 'Light') {
document.getElementById('icon-light').checked = true; document.getElementById('icon-light').checked = true;
} }
url = chrome.runtime.getURL('icons/action/' + options._optionValues.selectedIcon.toLowerCase() + '/icon38-default.png'); url = chrome.runtime.getURL(`icons/action/${selectedIcon.toLowerCase()}/icon38-default.png`);
document.getElementById('icon-badge-preview').src = url; document.getElementById('icon-badge-preview').src = url;
bgColor = options._optionValues.badgeColor || '#4A826C'; bgColor = options._optionValues.badgeColor || '#4A826C';
@ -133,15 +138,31 @@ options._renderOptionsPanel = function () {
document.getElementById('badged-text-color').value = txtColor; document.getElementById('badged-text-color').value = txtColor;
} }
document.getElementById('last-mapping-update').textContent += ' ' + mappings.lastMappingUpdate; document.getElementById('last-mapping-update').textContent += ` ${mappings.lastMappingUpdate}`;
document.getElementById('negate-html-filter-list-warning').addEventListener('click', function () { options._onLinkClick(Links.CODEBERG_HTML_FILTER); }); document.getElementById('negate-html-filter-list-warning').addEventListener('click', function () {
document.getElementById('link-welcome-page').addEventListener('click', function () { options._onLinkClick(Links.WELCOME); }); options._onLinkClick(Links.CODEBERG_HTML_FILTER);
document.getElementById('link-changelog').addEventListener('click', function () { options._onLinkClick(Links.CHANGELOG); }); });
document.getElementById('link-donate').addEventListener('click', function () { options._onLinkClick(Links.DONATE); }); document.getElementById('link-welcome-page').addEventListener('click', function () {
document.getElementById('link-faq').addEventListener('click', function () { options._onLinkClick(Links.FAQ);}); options._onLinkClick(Links.WELCOME);
document.getElementById('ruleset-help').addEventListener('click', function () { options._onLinkClick(Links.CODEBERG_RULESET); }); });
document.getElementById('sync-help').addEventListener('click', function () { options._onLinkClick(Links.FAQ + '#sync'); }); document.getElementById('link-changelog').addEventListener('click', function () {
document.getElementById('link-statistic').addEventListener('click', function () { options._onLinkClick(Links.STATISTICS); }); options._onLinkClick(Links.CHANGELOG);
});
document.getElementById('link-donate').addEventListener('click', function () {
options._onLinkClick(Links.DONATE);
});
document.getElementById('link-faq').addEventListener('click', function () {
options._onLinkClick(Links.FAQ);
});
document.getElementById('ruleset-help').addEventListener('click', function () {
options._onLinkClick(Links.CODEBERG_RULESET);
});
document.getElementById('sync-help').addEventListener('click', function () {
options._onLinkClick(`${Links.FAQ}#sync`);
});
document.getElementById('link-statistic').addEventListener('click', function () {
options._onLinkClick(Links.STATISTICS);
});
document.getElementById('btn-general-tab').addEventListener('click', options._changeTab); document.getElementById('btn-general-tab').addEventListener('click', options._changeTab);
document.getElementById('btn-advanced-tab').addEventListener('click', options._changeTab); document.getElementById('btn-advanced-tab').addEventListener('click', options._changeTab);
@ -265,13 +286,15 @@ options._configureLinkPrefetching = function (value) {
chrome.privacy.network.networkPredictionEnabled.clear({}); chrome.privacy.network.networkPredictionEnabled.clear({});
} else { } else {
chrome.privacy.network.networkPredictionEnabled.set({ chrome.privacy.network.networkPredictionEnabled.set({
value: false, 'value': false,
}); });
} }
}; };
options._serializeAllowlistedDomains = function (allowlistedDomains) { options._serializeAllowlistedDomains = function (allowlistedDomains) {
if (allowlistedDomains === undefined) return ''; if (allowlistedDomains === undefined) {
return '';
}
let domainAllowlist, allowlistedDomainKeys; let domainAllowlist, allowlistedDomainKeys;
@ -334,7 +357,7 @@ options._renderInfoPanel = function () {
btnFrameworks.value += Object.keys(options._listOfFrameworks).length - unsupportedFrameworks; btnFrameworks.value += Object.keys(options._listOfFrameworks).length - unsupportedFrameworks;
}; };
options._btnCreateList = function ({ target }) { options._btnCreateList = function ({target}) {
if (target.id === 'cdn') { if (target.id === 'cdn') {
document.getElementById('cdn').classList.add('btns-active'); document.getElementById('cdn').classList.add('btns-active');
document.getElementById('framework').classList.remove('btns-active'); document.getElementById('framework').classList.remove('btns-active');
@ -361,53 +384,56 @@ options._createList = function (type) {
list.forEach((elem) => { list.forEach((elem) => {
if (!(BrowserType.CHROMIUM && (elem === 'fontawesome' || elem === 'google-material-design-icons'))) { if (!(BrowserType.CHROMIUM && (elem === 'fontawesome' || elem === 'google-material-design-icons'))) {
textArea.value += elem + '\n'; textArea.value += `${elem}\n`;
} }
}); });
}; };
options._colorPicker = function () { options._colorPicker = function () {
/* eslint-disable no-undef, no-invalid-this */
const badgeBackgroundColor = new CP(document.getElementById('badged-background-color')); const badgeBackgroundColor = new CP(document.getElementById('badged-background-color'));
badgeBackgroundColor.on('change', function(r, g, b) { badgeBackgroundColor.on('change', function (r, g, b) {
this.source.value = this.color(r, g, b); this.source.value = this.color(r, g, b);
}); });
badgeBackgroundColor.on('drag', function(r, g, b) { badgeBackgroundColor.on('drag', function (r, g, b) {
options._backgroundColor = this.color(r, g, b); options._backgroundColor = this.color(r, g, b);
this.source.value = options._backgroundColor this.source.value = options._backgroundColor;
wrappers.setBadgeBackgroundColor({color: options._backgroundColor}); wrappers.setBadgeBackgroundColor({'color': options._backgroundColor});
document.getElementById('counter-preview-badge').style.backgroundColor = options._backgroundColor; document.getElementById('counter-preview-badge').style.backgroundColor = options._backgroundColor;
document.getElementById('pre-badged-background-color').style.backgroundColor = options._backgroundColor; document.getElementById('pre-badged-background-color').style.backgroundColor = options._backgroundColor;
}); });
const badgeTextColor = new CP(document.getElementById('badged-text-color')); const badgeTextColor = new CP(document.getElementById('badged-text-color'));
badgeTextColor.on('change', function(r, g, b) { badgeTextColor.on('change', function (r, g, b) {
this.source.value = this.color(r, g, b); this.source.value = this.color(r, g, b);
}); });
badgeTextColor.on('drag', function(r, g, b) { badgeTextColor.on('drag', function (r, g, b) {
options._textColor = this.color(r, g, b); options._textColor = this.color(r, g, b);
this.source.value = options._textColor this.source.value = options._textColor;
wrappers.setBadgeTextColor({color: options._textColor}); wrappers.setBadgeTextColor({'color': options._textColor});
document.getElementById('counter-preview-badge').style.color = options._textColor; document.getElementById('counter-preview-badge').style.color = options._textColor;
document.getElementById('pre-badged-text-color').style.backgroundColor = options._textColor; document.getElementById('pre-badged-text-color').style.backgroundColor = options._textColor;
}); });
/* eslint-enable no-undef, no-invalid-this */
}; };
options._setDefaultColor = function ({ target }) { options._setDefaultColor = function ({target}) {
if (target.id === 'restore-text-color') { if (target.id === 'restore-text-color') {
options._textColor = '#FFFFFF'; options._textColor = '#FFFFFF';
wrappers.setBadgeTextColor({color: options._textColor}); wrappers.setBadgeTextColor({'color': options._textColor});
document.getElementById('counter-preview-badge').style.color = options._textColor; document.getElementById('counter-preview-badge').style.color = options._textColor;
document.getElementById('pre-badged-text-color').style.backgroundColor = options._textColor; document.getElementById('pre-badged-text-color').style.backgroundColor = options._textColor;
document.getElementById('badged-text-color').value = options._textColor; document.getElementById('badged-text-color').value = options._textColor;
} else if (target.id === 'restore-background-color') { } else if (target.id === 'restore-background-color') {
options._backgroundColor = '#4A826C'; options._backgroundColor = '#4A826C';
wrappers.setBadgeBackgroundColor({color: options._backgroundColor}); wrappers.setBadgeBackgroundColor({'color': options._backgroundColor});
document.getElementById('counter-preview-badge').style.backgroundColor = options._backgroundColor; document.getElementById('counter-preview-badge').style.backgroundColor = options._backgroundColor;
document.getElementById('pre-badged-background-color').style.backgroundColor = options._backgroundColor; document.getElementById('pre-badged-background-color').style.backgroundColor = options._backgroundColor;
document.getElementById('badged-background-color').value = options._backgroundColor; document.getElementById('badged-background-color').value = options._backgroundColor;
} }
}; };
/** /**
* Event Handlers * Event Handlers
*/ */
@ -423,7 +449,7 @@ options._onDocumentLoaded = function () {
options._renderContents(); options._renderContents();
}; };
options._onOptionChanged = function ({ target }) { options._onOptionChanged = function ({target}) {
let optionKey, optionType, optionValue; let optionKey, optionType, optionValue;
optionKey = target.getAttribute('data-option'); optionKey = target.getAttribute('data-option');
@ -451,7 +477,10 @@ options._onOptionChanged = function ({ target }) {
options._configureLinkPrefetching(optionValue); options._configureLinkPrefetching(optionValue);
} }
if (optionKey === Setting.ALLOWLISTED_DOMAINS || optionKey === Setting.DOMAINS_MANIPULATE_DOM || optionKey === Setting.ALLOWED_DOMAINS_GOOGLE_FONTS) { if (optionKey === Setting.ALLOWLISTED_DOMAINS ||
optionKey === Setting.DOMAINS_MANIPULATE_DOM ||
optionKey === Setting.ALLOWED_DOMAINS_GOOGLE_FONTS) {
optionValue = options._parseDomainAllowlist(optionValue); optionValue = options._parseDomainAllowlist(optionValue);
} }
@ -474,8 +503,8 @@ options._onOptionChanged = function ({ target }) {
} }
if (optionKey === Setting.SELECTED_ICON) { if (optionKey === Setting.SELECTED_ICON) {
wrappers.setIcon({ path: optionValue }, 'Enabled'); wrappers.setIcon({'path': optionValue}, 'Enabled');
let url = chrome.runtime.getURL('icons/action/' + optionValue.toLowerCase() + '/icon38-default.png'); let url = chrome.runtime.getURL(`icons/action/${optionValue.toLowerCase()}/icon38-default.png`);
document.getElementById('icon-badge-preview').src = url; document.getElementById('icon-badge-preview').src = url;
} }
storageManager.type.set({ storageManager.type.set({
@ -483,7 +512,7 @@ options._onOptionChanged = function ({ target }) {
}); });
}; };
options._onStorageOptionChanged = function ({ target }) { options._onStorageOptionChanged = function ({target}) {
chrome.storage.local.set({ chrome.storage.local.set({
[Setting.STORAGE_TYPE]: target.value, [Setting.STORAGE_TYPE]: target.value,
}); });
@ -496,12 +525,12 @@ options._onStorageOptionChanged = function ({ target }) {
options._onLinkClick = function (url) { options._onLinkClick = function (url) {
chrome.tabs.create({ chrome.tabs.create({
url: url, 'url': url,
active: true 'active': true
}); });
}; };
options._changeTab = function ({ target }) { options._changeTab = function ({target}) {
let tabContent, tabButton, optionKey; let tabContent, tabButton, optionKey;
optionKey = target.getAttribute('data-option'); optionKey = target.getAttribute('data-option');
@ -519,17 +548,17 @@ options._changeTab = function ({ target }) {
} }
}; };
options._onChangedHexColor = function ({ target }) { options._onChangedHexColor = function ({target}) {
if (/#([a-f0-9]{3}){1,2}\b/i.test(target.value)) { if (/#([a-f0-9]{3}){1,2}\b/i.test(target.value)) {
target.classList.remove('color-error'); target.classList.remove('color-error');
if (target.id === 'badged-text-color') { if (target.id === 'badged-text-color') {
options._textColor = target.value; options._textColor = target.value;
wrappers.setBadgeTextColor({color: options._textColor}); wrappers.setBadgeTextColor({'color': options._textColor});
document.getElementById('counter-preview-badge').style.color = options._textColor; document.getElementById('counter-preview-badge').style.color = options._textColor;
document.getElementById('pre-badged-text-color').style.backgroundColor = options._textColor; document.getElementById('pre-badged-text-color').style.backgroundColor = options._textColor;
} else { } else {
options._backgroundColor = target.value; options._backgroundColor = target.value;
wrappers.setBadgeBackgroundColor({color: options._backgroundColor}); wrappers.setBadgeBackgroundColor({'color': options._backgroundColor});
document.getElementById('counter-preview-badge').style.backgroundColor = options._backgroundColor; document.getElementById('counter-preview-badge').style.backgroundColor = options._backgroundColor;
document.getElementById('pre-badged-background-color').style.backgroundColor = options._backgroundColor; document.getElementById('pre-badged-background-color').style.backgroundColor = options._backgroundColor;
} }
@ -556,6 +585,7 @@ options._updatesDomainLists = function (changes) {
} }
}; };
/** /**
* Initializations * Initializations
*/ */

View File

@ -18,14 +18,18 @@
'use strict'; 'use strict';
/** /**
* Popup * Popup
*/ */
var popup = {}; var popup = {};
/** /**
* Private Methods * Private Methods
*/ */
popup._renderContents = function () { popup._renderContents = function () {
helpers.insertI18nContentIntoDocument(document); helpers.insertI18nContentIntoDocument(document);
helpers.insertI18nTitlesIntoDocument(document); helpers.insertI18nTitlesIntoDocument(document);
@ -49,7 +53,8 @@ popup._renderContents = function () {
}; };
popup._renderNonContextualContents = function () { popup._renderNonContextualContents = function () {
let versionLabelElement, nameLabelElement, counterElement, testingUtilityLinkElement, optionsButtonElement, donationButtonElement, infoButtonLabel; let versionLabelElement, nameLabelElement, counterElement, testingUtilityLinkElement,
optionsButtonElement, donationButtonElement, infoButtonLabel;
versionLabelElement = document.getElementById('version-label'); versionLabelElement = document.getElementById('version-label');
nameLabelElement = document.getElementById('name-label'); nameLabelElement = document.getElementById('name-label');
@ -86,7 +91,8 @@ popup._renderContextualContents = function () {
}; };
popup._renderDomainAllowlistPanel = function () { popup._renderDomainAllowlistPanel = function () {
let websiteContextElement, protectionToggleElement, domainIndicatorElement, manipulateDOMToggleElement, manipulateDOMToggleStyle; let websiteContextElement, protectionToggleElement, domainIndicatorElement,
manipulateDOMToggleElement, manipulateDOMToggleStyle;
websiteContextElement = document.getElementById('website-context'); websiteContextElement = document.getElementById('website-context');
protectionToggleElement = document.getElementById('protection-toggle-switch'); protectionToggleElement = document.getElementById('protection-toggle-switch');
@ -139,8 +145,8 @@ popup._renderInjectionPanel = function (groupedInjections) {
popup._enableProtection = function () { popup._enableProtection = function () {
let message = { let message = {
topic: 'allowlist:remove-domain', 'topic': 'allowlist:remove-domain',
value: popup._domain, 'value': popup._domain,
}; };
chrome.runtime.sendMessage(message, function () { chrome.runtime.sendMessage(message, function () {
@ -150,8 +156,8 @@ popup._enableProtection = function () {
popup._disableProtection = function () { popup._disableProtection = function () {
let message = { let message = {
topic: 'allowlist:add-domain', 'topic': 'allowlist:add-domain',
value: popup._domain, 'value': popup._domain,
}; };
chrome.runtime.sendMessage(message, function () { chrome.runtime.sendMessage(message, function () {
@ -161,8 +167,8 @@ popup._disableProtection = function () {
popup._enableManipulateDOM = function () { popup._enableManipulateDOM = function () {
let message = { let message = {
topic: 'manipulateDOM:add-domain', 'topic': 'manipulateDOM:add-domain',
value: popup._domain, 'value': popup._domain,
}; };
chrome.runtime.sendMessage(message, function () { chrome.runtime.sendMessage(message, function () {
@ -172,8 +178,8 @@ popup._enableManipulateDOM = function () {
popup._disableManipulateDOM = function () { popup._disableManipulateDOM = function () {
let message = { let message = {
topic: 'manipulateDOM:remove-domain', 'topic': 'manipulateDOM:remove-domain',
value: popup._domain, 'value': popup._domain,
}; };
chrome.runtime.sendMessage(message, function () { chrome.runtime.sendMessage(message, function () {
@ -184,8 +190,8 @@ popup._disableManipulateDOM = function () {
popup._determineDomainAllowlistStatus = function () { popup._determineDomainAllowlistStatus = function () {
return new Promise((resolve) => { return new Promise((resolve) => {
let message = { let message = {
topic: 'domain:fetch-is-allowlisted', 'topic': 'domain:fetch-is-allowlisted',
value: popup._domain, 'value': popup._domain,
}; };
if (popup._domain === null) { if (popup._domain === null) {
@ -202,8 +208,8 @@ popup._determineDomainAllowlistStatus = function () {
popup._determineStatusManipulateDOM = function () { popup._determineStatusManipulateDOM = function () {
return new Promise((resolve) => { return new Promise((resolve) => {
let message = { let message = {
topic: 'domain:fetch-is-manipulateDOM', 'topic': 'domain:fetch-is-manipulateDOM',
value: popup._domain, 'value': popup._domain,
}; };
chrome.runtime.sendMessage(message, function (response) { chrome.runtime.sendMessage(message, function (response) {
@ -216,8 +222,8 @@ popup._determineStatusManipulateDOM = function () {
popup._determineResourceInjections = function () { popup._determineResourceInjections = function () {
return new Promise((resolve) => { return new Promise((resolve) => {
let message = { let message = {
topic: 'tab:fetch-injections', 'topic': 'tab:fetch-injections',
value: popup._targetTab.id, 'value': popup._targetTab.id,
}; };
chrome.runtime.sendMessage(message, function (response) { chrome.runtime.sendMessage(message, function (response) {
@ -231,7 +237,7 @@ popup._determineResourceInjections = function () {
popup._determineTargetTab = function () { popup._determineTargetTab = function () {
return new Promise((resolve) => { return new Promise((resolve) => {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { chrome.tabs.query({'active': true, 'currentWindow': true}, function (tabs) {
popup._targetTab = tabs[0]; popup._targetTab = tabs[0];
popup._domain = helpers.extractDomainFromUrl(tabs[0].url, true); popup._domain = helpers.extractDomainFromUrl(tabs[0].url, true);
@ -271,7 +277,7 @@ popup._groupResourceInjections = function (injections) {
let groupedInjections = {}; let groupedInjections = {};
for (let index in injections) { for (let index in injections) {
let { source } = injections[index]; let {source} = injections[index];
groupedInjections[source] = groupedInjections[source] || []; groupedInjections[source] = groupedInjections[source] || [];
groupedInjections[source].push(injections[index]); groupedInjections[source].push(injections[index]);
@ -320,14 +326,14 @@ popup._createInjectionGroupHeaderElement = function (source, cdn) {
}; };
popup._createInjectionGroupElement = function (source, cdn) { popup._createInjectionGroupElement = function (source, cdn) {
let injectionGroupElement; let injectionGroupElement, bundle, filtered;
// Filter duplicates // Filter duplicates
let bundle = []; bundle = [];
for (let injection of cdn) { for (let injection of cdn) {
bundle.push(injection); bundle.push(injection);
} }
let filtered = popup._filterDuplicates(bundle, 'bundle'); filtered = popup._filterDuplicates(bundle, 'bundle');
injectionGroupElement = document.createElement('ul'); injectionGroupElement = document.createElement('ul');
injectionGroupElement.setAttribute('class', 'sublist'); injectionGroupElement.setAttribute('class', 'sublist');
@ -352,7 +358,7 @@ popup._createInjectionElement = function (injection) {
if (injection.bundle === '') { if (injection.bundle === '') {
name = targets.determineResourceName(filename); name = targets.determineResourceName(filename);
} else { } else {
name = injection.bundle + ' (Bundle)'; name = `${injection.bundle} (Bundle)`;
} }
nameTextNode = document.createTextNode(`- ${name}`); nameTextNode = document.createTextNode(`- ${name}`);
@ -393,7 +399,9 @@ popup._filterDuplicates = function (array, key) {
*/ */
let filtered = array let filtered = array
.map((e) => e[key]) .map((e) => e[key])
.map((value, index, newArray) => (value != '' ? newArray.indexOf(value) === index && index : index)) .map(function (value, index, newArray) {
return value !== '' ? newArray.indexOf(value) === index && index : index;
})
.filter((e) => array[e]) .filter((e) => array[e])
.map((e) => array[e]); .map((e) => array[e]);
@ -414,10 +422,10 @@ popup._renderLocaleNotice = function () {
}; };
/** /**
* Event Handlers * Event Handlers
*/ */
popup._onDocumentLoaded = function () { popup._onDocumentLoaded = function () {
let manifest, language; let manifest, language;
@ -436,8 +444,8 @@ popup._onDocumentLoaded = function () {
popup._onTestingUtilityLinkClicked = function (event) { popup._onTestingUtilityLinkClicked = function (event) {
if (event.button === 0 || event.button === 1) { if (event.button === 0 || event.button === 1) {
chrome.tabs.create({ chrome.tabs.create({
url: Links.LOCALCDN_TEST_WEBSITE + popup._targetTab.url, 'url': Links.LOCALCDN_TEST_WEBSITE + popup._targetTab.url,
active: event.button === 0, 'active': event.button === 0,
}); });
} }
@ -454,8 +462,8 @@ popup._onOptionsButtonClicked = function () {
popup._onDonationButtonClicked = function () { popup._onDonationButtonClicked = function () {
if (event.button === 0 || event.button === 1) { if (event.button === 0 || event.button === 1) {
chrome.tabs.create({ chrome.tabs.create({
url: Links.DONATE, 'url': Links.DONATE,
active: event.button === 0, 'active': event.button === 0,
}); });
} }
@ -467,7 +475,7 @@ popup._onDonationButtonClicked = function () {
popup._onToggled = function () { popup._onToggled = function () {
let bypassCache = typeof browser === 'undefined'; let bypassCache = typeof browser === 'undefined';
chrome.tabs.reload(popup._targetTab.id, { bypassCache }); chrome.tabs.reload(popup._targetTab.id, {bypassCache});
setTimeout(function () { setTimeout(function () {
popup._close(); popup._close();
}, 200); }, 200);
@ -488,8 +496,8 @@ popup._close = function () {
popup._onInfoButtonClicked = function () { popup._onInfoButtonClicked = function () {
if (event.button === 0 || event.button === 1) { if (event.button === 0 || event.button === 1) {
chrome.tabs.create({ chrome.tabs.create({
url: Links.FAQ_HTML_FILTER, 'url': Links.FAQ_HTML_FILTER,
active: event.button === 0, 'active': event.button === 0,
}); });
} }
@ -501,8 +509,8 @@ popup._onInfoButtonClicked = function () {
popup._onIncompleteTranslation = function () { popup._onIncompleteTranslation = function () {
if (event.button === 0 || event.button === 1) { if (event.button === 0 || event.button === 1) {
chrome.tabs.create({ chrome.tabs.create({
url: Links.Weblate, 'url': Links.Weblate,
active: event.button === 0, 'active': event.button === 0,
}); });
} }
@ -514,8 +522,8 @@ popup._onIncompleteTranslation = function () {
popup._onStatisticsButtonClicked = function () { popup._onStatisticsButtonClicked = function () {
if (event.button === 0 || event.button === 1) { if (event.button === 0 || event.button === 1) {
chrome.tabs.create({ chrome.tabs.create({
url: Links.STATISTICS, 'url': Links.STATISTICS,
active: event.button === 0, 'active': event.button === 0,
}); });
} }
if (event.button === 0) { if (event.button === 0) {
@ -523,9 +531,11 @@ popup._onStatisticsButtonClicked = function () {
} }
}; };
/** /**
* Initializations * Initializations
*/ */
popup.negateHtmlFilterList = false; popup.negateHtmlFilterList = false;
popup._statisticsStatus = false; popup._statisticsStatus = false;

View File

@ -14,14 +14,18 @@
'use strict'; 'use strict';
/** /**
* Statistic * Statistic
*/ */
var statistics = {}; var statistics = {};
/** /**
* Private Methods * Private Methods
*/ */
statistics._onDocumentLoaded = function () { statistics._onDocumentLoaded = function () {
helpers.insertI18nContentIntoDocument(document); helpers.insertI18nContentIntoDocument(document);
helpers.insertI18nTitlesIntoDocument(document); helpers.insertI18nTitlesIntoDocument(document);
@ -63,7 +67,7 @@ statistics._generateTable = function (data, type) {
valueColumn.appendChild(document.createTextNode(value[1])); valueColumn.appendChild(document.createTextNode(value[1]));
row.appendChild(valueColumn); row.appendChild(valueColumn);
document.getElementById('tbody-' + type).appendChild(row); document.getElementById(`tbody-${type}`).appendChild(row);
} }
}; };
@ -92,7 +96,7 @@ statistics._mergeObjects = function (obj, arr) {
let bundle = targets.determineBundle(key); let bundle = targets.determineBundle(key);
if (bundle !== '') { if (bundle !== '') {
bundle = key.split('/'); bundle = key.split('/');
key = bundle[0] + '/' + bundle[1] + '/' + bundle[2] + '/'; key = `${bundle[0]}/${bundle[1]}/${bundle[2]}/`;
} }
// If CDN/Framework exists, add it, otherwise create new one // If CDN/Framework exists, add it, otherwise create new one
if (arr[key]) { if (arr[key]) {
@ -125,9 +129,11 @@ statistics._setDateRange = function () {
if (days > 1) { if (days > 1) {
for (let i = 0; i < days; i++) { for (let i = 0; i < days; i++) {
let diff, day;
// NOTE: setDate/getDate is buggy over day/month/year boundaries // NOTE: setDate/getDate is buggy over day/month/year boundaries
let diff = 24 * 3600000 * i; diff = 24 * 3600000 * i;
let day = from.setTime(today.getTime() - diff); day = from.setTime(today.getTime() - diff);
statistics._dateRange.push(new Date(day).toISOString().slice(0, 10)); statistics._dateRange.push(new Date(day).toISOString().slice(0, 10));
} }
} }
@ -194,12 +200,12 @@ statistics._displayNameOfFramework = function (str, type) {
if (filename === 'Unknown') { if (filename === 'Unknown') {
filename = targets.determineBundle(str); filename = targets.determineBundle(str);
if (filename === '' && str.startsWith('resources/font-awesome/')) { if (filename === '' && str.startsWith('resources/font-awesome/')) {
filename = 'Font Awesome (Fonts)' filename = 'Font Awesome (Fonts)';
} }
} }
version = str.match(Resource.VERSION_EXPRESSION); version = str.match(Resource.VERSION_EXPRESSION);
if (version !== null && version.length > 0) { if (version !== null && version.length > 0) {
version = version[0] === 'latest' ? version[0] : 'v' + version[0]; version = version[0] === 'latest' ? version[0] : `v${version[0]}`;
} else { } else {
version = ''; version = '';
} }
@ -215,7 +221,7 @@ statistics._displayNameOfFramework = function (str, type) {
return document.createTextNode(str); return document.createTextNode(str);
}; };
statistics._handlerDateRange = function ({ target }) { statistics._handlerDateRange = function ({target}) {
let type = target.value; let type = target.value;
if (type === 'day' || type === 'week' || type === 'month' || type === 'year') { if (type === 'day' || type === 'week' || type === 'month' || type === 'year') {
statistics._dateUnit = type; statistics._dateUnit = type;
@ -231,20 +237,22 @@ statistics._deleteStatistic = function () {
chrome.storage.local.set({ chrome.storage.local.set({
[Setting.INTERNAL_STATISTICS_DATA]: {} [Setting.INTERNAL_STATISTICS_DATA]: {}
}); });
chrome.runtime.sendMessage({ topic: 'deleteStatistic' }); chrome.runtime.sendMessage({'topic': 'deleteStatistic'});
} }
}; };
statistics._registerListener = function () { statistics._registerListener = function () {
document.getElementById('date-range').addEventListener('change', statistics._handlerDateRange); document.getElementById('date-range').addEventListener('change', statistics._handlerDateRange);
document.getElementById('btn-delete').addEventListener('click', function () { document.getElementById('btn-delete').addEventListener('click', function () {
statistics._handlerDateRange({ target: { value: 'delete' } }); statistics._handlerDateRange({'target': {'value': 'delete'}});
}); });
}; };
/** /**
* Initializations * Initializations
*/ */
statistics._data = {}; statistics._data = {};
statistics._dataSortedCDNs = {}; statistics._dataSortedCDNs = {};
statistics._dataSortedFrameworks = {}; statistics._dataSortedFrameworks = {};

View File

@ -15,19 +15,23 @@
'use strict'; 'use strict';
/** /**
* Updates * Updates
*/ */
var updates = {}; var updates = {};
/** /**
* Private Methods * Private Methods
*/ */
updates._openHistoryReleaseNotes = function () { updates._openHistoryReleaseNotes = function () {
let container = document.getElementById('history-release-notes'); let container, toggle;
let toggle = document.getElementById('history-indicator');
container = document.getElementById('history-release-notes');
toggle = document.getElementById('history-indicator');
if (container.style.display === 'none') { if (container.style.display === 'none') {
container.style.display = 'block'; container.style.display = 'block';
@ -39,11 +43,13 @@ updates._openHistoryReleaseNotes = function () {
}; };
updates._onDocumentLoaded = function () { updates._onDocumentLoaded = function () {
let updateElements, urlParams;
document.getElementById('generate-ublock-rules').checked = false; document.getElementById('generate-ublock-rules').checked = false;
document.getElementById('generate-umatrix-rules').checked = false; document.getElementById('generate-umatrix-rules').checked = false;
document.getElementById('generate-adguard-rules').checked = false; document.getElementById('generate-adguard-rules').checked = false;
let updateElements = { updateElements = {
['ruleSets']: document.getElementsByName('rule-sets'), ['ruleSets']: document.getElementsByName('rule-sets'),
['copyRuleSet']: document.getElementById('button-copy-rule-set'), ['copyRuleSet']: document.getElementById('button-copy-rule-set'),
}; };
@ -57,7 +63,7 @@ updates._onDocumentLoaded = function () {
document.getElementById('history').addEventListener('click', updates._openHistoryReleaseNotes); document.getElementById('history').addEventListener('click', updates._openHistoryReleaseNotes);
// GET parameter to display the rule set generator // GET parameter to display the rule set generator
let urlParams = new URLSearchParams(window.location.search); urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('mappingupdate') === 'true') { if (urlParams.get('mappingupdate') === 'true') {
document.getElementById('generator-section').style.display = 'block'; document.getElementById('generator-section').style.display = 'block';
} }