Convert bg scripts, gulpfile, data templates to mjs/ems except pages

Update eslint package and rules.
This commit is contained in:
ilyaigpetrov 2022-10-04 20:58:06 +05:00
parent 97adb7f3f4
commit df8d1dfe0c
24 changed files with 803 additions and 1233 deletions

View File

@ -1,19 +1,18 @@
module.exports = {
extends: ['eslint:recommended', 'google'],
env: {
node: true,
browser: true,
worker: true,
webextensions: true,
es6: true
es2022: true,
},
globals: {
chrome: true
chrome: true,
},
parserOptions: {
sourceType: 'script',
ecmaVersion: 2017,
ecmaFeatures: {
impliedStrict: false
}
sourceType: 'module',
ecmaVersion: 2022,
},
rules: {
strict: ['error', 'global'],

View File

@ -1,16 +1,15 @@
'use strict';
import gulp from 'gulp';
import del from 'del';
import through from 'through2';
import PluginError from 'plugin-error';
const gulp = require('gulp');
const del = require('del');
const through = require('through2');
const PluginError = require('plugin-error');
const changed = require('gulp-changed');
import {contexts} from './src/templates-data';
const PluginName = 'Template literals';
const templatePlugin = (context) => through.obj(function(file, encoding, cb) {
const suffixes = ['.tmpl.json', 'tmpl.js'];
const suffixes = ['.tmpl.json', 'tmpl.js', 'tmpl.mjs', 'tmpl.html'];
if ( suffixes.some( (suff) => file.path.endsWith(suff) ) ) {
const originalPath = file.path;
@ -27,12 +26,12 @@ const templatePlugin = (context) => through.obj(function(file, encoding, cb) {
acc.values.push(value);
return acc;
}, { keys: [], values: [] });
}, {keys: [], values: []});
try {
file.contents = Buffer.from(
(new Function(...keys, 'return `' + String(file.contents) + '`;'))(...values)
(new Function(...keys, 'return `' + String(file.contents) + '`;'))(...values),
);
} catch(e) {
} catch (e) {
e.message += '\nIN FILE: ' + originalPath;
return cb(new PluginError(PluginName, e));
}
@ -51,57 +50,37 @@ const clean = function(cb) {
};
const contexts = require('./src/templates-data').contexts;
const excFolder = (name) => [`!./src/**/${name}`, `!./src/**/${name}/**/*`];
const excluded = [ ...excFolder('test') , ...excFolder('node_modules'), ...excFolder('src') ];
const excluded = [...excFolder('test'), ...excFolder('node_modules'), ...excFolder('src')];
const miniDst = './build/extension-mini';
const fullDst = './build/extension-full';
const betaDst = './build/extension-beta';
const firefoxDst = './build/extension-firefox';
const commonSrc = './src/extension-common/**/*';;
const commonSrc = './src/extension-common/**/*';
const miniSrc = './src/extension-mini/**/*';
const fullSrc = './src/extension-full/**/*';
const firefoxSrc = './src/extension-firefox/**/*';
const joinSrc = (...args) => [...args, ...excluded];
const copyMini = function(cb) {
gulp.src(joinSrc(commonSrc, miniSrc))
//.pipe(changed(miniDst))
.pipe(templatePlugin(contexts.mini))
.pipe(gulp.dest(miniDst))
.on('end', cb);
.pipe(templatePlugin(contexts.mini))
.pipe(gulp.dest(miniDst))
.on('end', cb);
};
const copyFull = function(cb) {
gulp.src(joinSrc(commonSrc, fullSrc))
//.pipe(changed(fullDst))
.pipe(templatePlugin(contexts.full))
.pipe(gulp.dest(fullDst))
.on('end', cb);
.pipe(templatePlugin(contexts.full))
.pipe(gulp.dest(fullDst))
.on('end', cb);
};
const copyBeta = function(cb) {
gulp.src(joinSrc(commonSrc, fullSrc))
//.pipe(changed(fullDst))
.pipe(templatePlugin(contexts.beta))
.pipe(gulp.dest(betaDst))
.on('end', cb);
};
const buildAll = gulp.series(clean, gulp.parallel(copyMini, copyFull, copyBeta));
const buildBeta = copyBeta;
module.exports = {
default: buildAll,
const buildAll = gulp.series(clean, gulp.parallel(copyMini, copyFull));
export {
buildAll as default,
buildAll,
buildBeta,
};

File diff suppressed because it is too large Load Diff

View File

@ -15,8 +15,9 @@
"license": "GPLv3",
"devDependencies": {
"chai": "^4.3.0",
"eslint": "^7.19.0",
"eslint": "^8.24.0",
"eslint-config-google": "^0.14.0",
"esm": "^3.2.25",
"gulp-changed": "^4.0.2",
"mocha": "^8.2.1",
"sinon-chrome": "^3.0.1",

View File

@ -1,5 +1,3 @@
'use strict';
console.log('Extension started.');
{
@ -11,8 +9,8 @@ console.log('Extension started.');
// I also don't remove logs for sake of client-side troubleshooting
// (though no one sent me logs so far).
['log', 'warn', 'error'].forEach( (meth) => {
const _meth = window.console[meth].bind(console);
window.console[meth] = function(...args) {
const _meth = globalThis.console[meth].bind(console);
globalThis.console[meth] = function(...args) {
_meth(...args.map((a) => '' + a));
@ -24,7 +22,7 @@ console.log('Extension started.');
requestToResponder: {},
};
const self = window.utils = {
const self = globalThis.utils = {
mandatory() {
@ -143,16 +141,16 @@ console.log('Extension started.');
key = prefix + key;
if (value === null) {
return window.localStorage.removeItem(key);
return globalThis.localStorage.removeItem(key);
}
if (value === undefined) {
const item = window.localStorage.getItem(key);
const item = globalThis.localStorage.getItem(key);
return item && JSON.parse(item);
}
if (value instanceof Date) {
throw new TypeError('Converting Date format to JSON is not supported.');
}
window.localStorage.setItem(key, JSON.stringify(value));
globalThis.localStorage.setItem(key, JSON.stringify(value));
};
@ -163,7 +161,7 @@ console.log('Extension started.');
return new Promise((resolve) => (
chrome.storage.local.get(
key,
window.utils.getOrDie((storage) => resolve(key ? storage[key] : storage)),
globalThis.utils.getOrDie((storage) => resolve(key ? storage[key] : storage)),
)
));
},
@ -265,7 +263,7 @@ console.log('Extension started.');
chrome.tabs.create(
{url: url},
(tab) => chrome.windows.update(tab.windowId, {focused: true})
(tab) => chrome.globalThiss.update(tab.globalThisId, {focused: true})
);
},
@ -280,7 +278,7 @@ console.log('Extension started.');
const compareVersions = (a, b) => versionToInt(a) - versionToInt(b);
window.apis = {
globalThis.apis = {
platform: {
ifFirefox: navigator.userAgent.toLowerCase().includes('firefox'),
},

View File

@ -1,15 +1,13 @@
'use strict';
{ // Private namespace
const timeouted = window.utils.timeouted;
const throwIfError = window.utils.throwIfError;
const timeouted = globalThis.utils.timeouted;
const throwIfError = globalThis.utils.throwIfError;
const errorJsonReplacer = function errorJsonReplacer(key, value) {
// fooWindow.ErrorEvent !== barWindow.ErrorEvent
if (value === window) {
return; // STUPID, because other window object may be passed.
// fooglobalThis.ErrorEvent !== barglobalThis.ErrorEvent
if (value === globalThis) {
return; // STUPID, because other globalThis object may be passed.
}
if (!( value && value.constructor
&& ['Error', 'Event'].some(
@ -55,18 +53,18 @@
const ifPrefix = 'if-on-';
const extName = chrome.runtime.getManifest().name;
const extVersion = window.apis.version.build;
const extVersion = globalThis.apis.version.build;
window.apis.errorHandlers = {
globalThis.apis.errorHandlers = {
state: window.utils.createStorage('handlers-'),
state: globalThis.utils.createStorage('handlers-'),
viewError(type = window.utils.mandatory(), err) {
viewError(type = globalThis.utils.mandatory(), err) {
const errors = err ? {[type]: err} : this.idToError;
const json = JSON.stringify(errors, errorJsonReplacer, 0);
window.utils.openAndFocus(
globalThis.utils.openAndFocus(
'https://rebrand.ly/ac-error/?json=' + encodeURIComponent(json) +
(type ? '&type=' + encodeURIComponent(type) : '') +
'&version=' + chrome.runtime.getManifest().version +
@ -111,10 +109,10 @@
isControllable(details) {
if (details) {
this.ifControllable = window.utils.areSettingsControllableFor(details);
this.ifControllable = globalThis.utils.areSettingsControllableFor(details);
if (this.ifControllable) {
this.ifControlled = window.utils.areSettingsControlledFor(details);
this.ifControlled = globalThis.utils.areSettingsControlledFor(details);
} else {
this.ifControlled = false;
}
@ -185,7 +183,7 @@
iconUrl: './icons/' + icon,
appIconMaskUrl: './icons/default-mask-128.png',
isClickable: true,
}, window.apis.platform.ifFirefox ? {} : { requireInteraction: ifSticky }),
}, globalThis.apis.platform.ifFirefox ? {} : { requireInteraction: ifSticky }),
);
},
@ -219,7 +217,7 @@
};
const handlers = window.apis.errorHandlers;
const handlers = globalThis.apis.errorHandlers;
// Initialization
// ==============
@ -233,15 +231,15 @@
chrome.notifications.clear(notId);
if(notId === 'no-control') {
return window.utils.openAndFocus(
window.utils.messages.searchSettingsForUrl('proxy')
return globalThis.utils.openAndFocus(
globalThis.utils.messages.searchSettingsForUrl('proxy')
);
}
handlers.viewError(notId);
}));
handlers.installListenersOn(window, 'BG');
handlers.installListenersOn(globalThis, 'BG');
(chrome.proxy.onProxyError || chrome.proxy.onError).addListener( timeouted( (details) => {

View File

@ -1,4 +1,3 @@
'use strict';
/*
* Error Library
* PURPOSE 1:
@ -17,9 +16,9 @@
**/
{
const mandatory = window.utils.mandatory;
const mandatory = globalThis.utils.mandatory;
const self = window.apis.errorsLib = {
const self = globalThis.apis.errorsLib = {
// I don't use Error class, because we don't need stack here.
Warning: class {

View File

@ -1,13 +1,11 @@
'use strict';
{
const mandatory = window.utils.mandatory;
const errorsLib = window.apis.errorsLib;
const mandatory = globalThis.utils.mandatory;
const errorsLib = globalThis.apis.errorsLib;
const checkCon = 'Что-то не так с сетью, проверьте соединение.';
window.apis.httpLib = {
globalThis.apis.httpLib = {
ifModifiedSince(
url,

View File

@ -1,12 +1,10 @@
'use strict';
if (window.apis.platform.ifFirefox) {
if (globalThis.apis.platform.ifFirefox) {
const prefix = 'firefox-only';
const originalSet = chrome.proxy.settings.set.bind( chrome.proxy.settings );
chrome.proxy.settings.set = function(details, cb) {
const pac = window.utils.getProp(details, 'value.pacScript') || {};
const pac = globalThis.utils.getProp(details, 'value.pacScript') || {};
if (!(pac && pac.data)) {
return originalSet(details, cb);
}
@ -18,26 +16,26 @@ if (window.apis.platform.ifFirefox) {
proxyType: 'autoConfig',
autoConfigUrl: blobUrl,
},
}, window.utils.chromified( async (err) => {
}, globalThis.utils.chromified( async (err) => {
if (err) {
window.utils.lastError = err;
globalThis.utils.lastError = err;
cb();
return;
}
await window.utils.promisedLocalStorage.set({ [`${prefix}-pac-data`]: pac.data });
await globalThis.utils.promisedLocalStorage.set({ [`${prefix}-pac-data`]: pac.data });
cb();
}));
};
const originalGet = chrome.proxy.settings.get.bind( chrome.proxy.settings );
chrome.proxy.settings.get = function(details, cb) {
originalGet(details, window.utils.chromified(async (err, originalDetails) => {
originalGet(details, globalThis.utils.chromified(async (err, originalDetails) => {
if (err) {
window.utils.lastError = err;
globalThis.utils.lastError = err;
cb(originalDetails);
return;
}
let pacData = await window.utils.promisedLocalStorage.get(`${prefix}-pac-data`);
let pacData = await globalThis.utils.promisedLocalStorage.get(`${prefix}-pac-data`);
if (!pacData || !Object.keys(pacData).length) {
cb(originalDetails);
return;
@ -58,7 +56,7 @@ if (window.apis.platform.ifFirefox) {
const originalClear = chrome.proxy.settings.clear.bind( chrome.proxy.settings );
chrome.proxy.settings.clear = async function(details, cb) {
await window.utils.promisedLocalStorage.remove(`${prefix}-pac-data`);
await globalThis.utils.promisedLocalStorage.remove(`${prefix}-pac-data`);
originalClear(details, cb);
};
}

View File

@ -1,19 +1,17 @@
'use strict';
{ // Private namespace starts.
const mandatory = window.utils.mandatory;
const throwIfError = window.utils.throwIfError;
const chromified = window.utils.chromified;
const timeouted = window.utils.timeouted;
const mandatory = globalThis.utils.mandatory;
const throwIfError = globalThis.utils.throwIfError;
const chromified = globalThis.utils.chromified;
const timeouted = globalThis.utils.timeouted;
const kitchenStartsMark = '\n\n//%#@@@@@@ PAC_KITCHEN_STARTS @@@@@@#%';
const kitchenState = window.utils.createStorage('pac-kitchen-');
const kitchenState = globalThis.utils.createStorage('pac-kitchen-');
const ifIncontinence = 'if-incontinence';
const modsKey = 'mods';
let proxyHostToCredsList = {};
const ifAuthSupported = chrome.webRequest && chrome.webRequest.onAuthRequired && !window.apis.version.ifMini;
const ifAuthSupported = chrome.webRequest && chrome.webRequest.onAuthRequired && !globalThis.apis.version.ifMini;
if (ifAuthSupported) {
const requestIdToTries = {};
@ -267,7 +265,7 @@
if (proxyScheme.includes('@')) {
const proxy = window.utils.parseProxyScheme(proxyScheme);
const proxy = globalThis.utils.parseProxyScheme(proxyScheme);
protectedProxies.push(proxy);
return `${proxy.type} ${proxy.hostname}:${proxy.port}`;
@ -345,7 +343,7 @@
};
window.apis.pacKitchen = {
globalThis.apis.pacKitchen = {
getPacMods: getCurrentConfigs,
getPacModsRaw: () => getCurrentConfigs(true),
@ -593,7 +591,7 @@ ${
if (
details && details.levelOfControl === 'controlled_by_this_extension'
) {
const pac = window.utils.getProp(details, 'value.pacScript');
const pac = globalThis.utils.getProp(details, 'value.pacScript');
if (pac && pac.data) {
return chrome.proxy.settings.set(details, chromified(cb));
}
@ -646,7 +644,7 @@ ${
return cb(null, res, ...accWarns);
}
const newHosts = (pacMods.customProxyArray || []).map( (ps) => ps.split(/\s+/)[1] );
window.utils.fireRequest(
globalThis.utils.fireRequest(
'ip-to-host-replace-all',
newHosts,
(err, res, ...moreWarns) =>
@ -668,23 +666,23 @@ ${
};
const pacKitchen = window.apis.pacKitchen;
const pacKitchen = globalThis.apis.pacKitchen;
const originalSet = chrome.proxy.settings.set.bind( chrome.proxy.settings );
chrome.proxy.settings.set = function(details, cb) {
const pac = window.utils.getProp(details, 'value.pacScript');
const pac = globalThis.utils.getProp(details, 'value.pacScript');
if (!(pac && pac.data)) {
return originalSet(details, window.utils.timeouted(cb));
return originalSet(details, globalThis.utils.timeouted(cb));
}
const pacMods = getCurrentConfigs();
pac.data = pacKitchen.cook( pac.data, pacMods );
originalSet({value: details.value}, window.utils.chromified((err) => {
originalSet({value: details.value}, globalThis.utils.chromified((err) => {
if (!err) {
kitchenState(ifIncontinence, null);
}
window.utils.lastError = err;
globalThis.utils.lastError = err;
cb && cb();
}));

View File

@ -1,5 +1,3 @@
'use strict';
/*
Task 1. Gets IPs for proxies of antizapret/anticenz via dns over https.
These IPs are used in block-informer to inform user when proxy is ON.
@ -9,8 +7,8 @@
*/
/*
In background scripts use window.apis.antiCensorRu public variables.
In pages window.apis.antiCensorRu is not accessible,
In background scripts use globalThis.apis.antiCensorRu public variables.
In pages globalThis.apis.antiCensorRu is not accessible,
use chrome.runtime.getBackgroundPage(..),
extension.getBackgroundPage is deprecated
@ -31,17 +29,17 @@
const ifRu = chrome.i18n.getMessage('@@ui_locale').startsWith('ru');
console.log('Russian?', ifRu);
const mandatory = window.utils.mandatory;
const throwIfError = window.utils.throwIfError;
const chromified = window.utils.chromified;
const timeouted = window.utils.timeouted;
const mandatory = globalThis.utils.mandatory;
const throwIfError = globalThis.utils.throwIfError;
const chromified = globalThis.utils.chromified;
const timeouted = globalThis.utils.timeouted;
const clarifyThen = window.apis.errorsLib.clarifyThen;
const clarify = window.apis.errorsLib.clarify;
const Warning = window.apis.errorsLib.Warning;
const clarifyThen = globalThis.apis.errorsLib.clarifyThen;
const clarify = globalThis.apis.errorsLib.clarify;
const Warning = globalThis.apis.errorsLib.Warning;
const httpLib = window.apis.httpLib;
const handlers = window.apis.errorHandlers;
const httpLib = globalThis.apis.httpLib;
const handlers = globalThis.apis.errorHandlers;
const asyncLogGroup = function asyncLogGroup(...args) {
@ -85,7 +83,7 @@
return res;
*/
return new Promise((resolve) =>
window.setTimeout(() => resolve(tryPromiseSeveralTimesAsync(createPromise, timeoutsInSec)), outSec*1000),
globalThis.setTimeout(() => resolve(tryPromiseSeveralTimesAsync(createPromise, timeoutsInSec)), outSec*1000),
);
},
);
@ -97,7 +95,7 @@
reject(getErr);
return;
}
const ifWeAreInControl = window.utils.areSettingsControlledFor(settings);
const ifWeAreInControl = globalThis.utils.areSettingsControlledFor(settings);
if (!ifWeAreInControl) {
resolve(createPromise());
return;
@ -138,9 +136,9 @@
if (err) {
if (err.message === 'proxy.settings requires private browsing permission.') {
// window.utils.openAndFocus('https://rebrand.ly/ac-allow-private-windows');
// globalThis.utils.openAndFocus('https://rebrand.ly/ac-allow-private-globalThiss');
clarifyThen(
chrome.i18n.getMessage('AllowExtensionToRunInPrivateWindows'),
chrome.i18n.getMessage('AllowExtensionToRunInPrivateglobalThiss'),
cb,
)(err);
return;
@ -153,7 +151,7 @@
console.warn('Failed, other extension is in control.');
return cb(
new Error( window.utils.messages.whichExtensionHtml() ),
new Error( globalThis.utils.messages.whichExtensionHtml() ),
);
}
@ -173,7 +171,7 @@
'Getting IPs for PAC hosts...',
cb,
);
window.utils.fireRequest('ip-to-host-update-all', cb);
globalThis.utils.fireRequest('ip-to-host-update-all', cb);
};
@ -194,7 +192,7 @@
if (provider.distinctKey === 'Anticensority') {
const pacMods = window.apis.pacKitchen.getPacMods();
const pacMods = globalThis.apis.pacKitchen.getPacMods();
if (!pacMods.filteredCustomsString) {
addWarning(
ifRu
@ -253,7 +251,7 @@
);
};
window.apis.antiCensorRu = {
globalThis.apis.antiCensorRu = {
version: chrome.runtime.getManifest().version,
@ -299,7 +297,7 @@
order: 1,
/*
Don't use in system configs! Because Windows does poor caching.
Don't use in system configs! Because globalThiss does poor caching.
Some urls are encoded to counter abuse.
Version: 0.17
*/
@ -343,7 +341,7 @@
const upDate = new Date(this.lastPacUpdateStamp).toLocaleString('ru-RU')
.replace(/:\\d+$/, '').replace(/\\.\\d{4}/, '');
chrome.browserAction.setTitle({
title: \`\${chrome.i18n.getMessage('Updated')} \${upDate} | \${chrome.i18n.getMessage('Version')} \${window.apis.version.build}\`,
title: \`\${chrome.i18n.getMessage('Updated')} \${upDate} | \${chrome.i18n.getMessage('Version')} \${globalThis.apis.version.build}\`,
});
},
@ -578,7 +576,7 @@
// ON EACH LAUNCH, STARTUP, RELOAD, UPDATE, ENABLE
(async () => {
let oldAntiCensorRu = await window.utils.promisedLocalStorage.get('antiCensorRu') || {};
let oldAntiCensorRu = await globalThis.utils.promisedLocalStorage.get('antiCensorRu') || {};
const otherKeys = [
'pac-kitchen-if-incontinence',
@ -590,28 +588,28 @@
];
if (!Object.keys(oldAntiCensorRu).length) {
const storage = await window.utils.promisedLocalStorage.get(null);
if (storage.version && window.apis.version.isLeq(storage.version, '0.0.1.48')) {
const storage = await globalThis.utils.promisedLocalStorage.get(null);
if (storage.version && globalThis.apis.version.isLeq(storage.version, '0.0.1.48')) {
const ffxPacData = storage['firefox-only-pac-data'];
delete storage['firefox-only-pac-data'];
await window.utils.promisedLocalStorage.clear();
await globalThis.utils.promisedLocalStorage.clear();
for(const key of otherKeys) {
await window.utils.promisedLocalStorage.set({ [key]: storage[key] });
await globalThis.utils.promisedLocalStorage.set({ [key]: storage[key] });
delete storage[key];
}
await window.utils.promisedLocalStorage.set({ antiCensorRu: storage });
await globalThis.utils.promisedLocalStorage.set({ antiCensorRu: storage });
oldAntiCensorRu = storage;
}
}
if (oldAntiCensorRu.version && window.apis.version.isLeq(oldAntiCensorRu.version, '0.0.1.49')) {
const modsMutated = window.apis.pacKitchen.getPacModsRaw();
if (oldAntiCensorRu.version && globalThis.apis.version.isLeq(oldAntiCensorRu.version, '0.0.1.49')) {
const modsMutated = globalThis.apis.pacKitchen.getPacModsRaw();
if (modsMutated && modsMutated.exceptions) {
modsMutated.exceptions = Object.entries(modsMutated.exceptions).reduce((acc, [host, ifProxy]) => {
acc[\`*.\${host}\`] = ifProxy;
return acc;
}, {});
await new Promise(
(resolve) => window.apis.pacKitchen.keepCookedNowAsync(modsMutated, resolve),
(resolve) => globalThis.apis.pacKitchen.keepCookedNowAsync(modsMutated, resolve),
);
}
}
@ -619,10 +617,10 @@
/*
Event handlers that ALWAYS work (even if installation is not done
or failed).
E.g. install window may fail to open or be closed by user accidentally.
E.g. install globalThis may fail to open or be closed by user accidentally.
In such case extension _should_ try to work on default parameters.
*/
const antiCensorRu = window.apis.antiCensorRu;
const antiCensorRu = globalThis.apis.antiCensorRu;
chrome.alarms.onAlarm.addListener(
timeouted( (alarm) => {
@ -639,7 +637,7 @@
);
console.log('Alarm listener installed. We won\\'t miss any PAC update.');
window.addEventListener('online', () => {
globalThis.addEventListener('online', () => {
console.log('We are online, checking periodic updates...');
antiCensorRu.setAlarms();
@ -647,7 +645,7 @@
});
console.log('Keep cooked...');
await new Promise((resolve) => window.apis.pacKitchen.keepCookedNowAsync(resolve));
await new Promise((resolve) => globalThis.apis.pacKitchen.keepCookedNowAsync(resolve));
//console.log('Storage on init:', oldAntiCensorRu);
antiCensorRu.ifFirstInstall = Object.keys(oldAntiCensorRu).length === 0;
@ -706,20 +704,20 @@
console.log('Updating from', oldAntiCensorRu.version, 'to', antiCensorRu.version);
try {
if (window.apis.version.isLeq(oldAntiCensorRu.version, '0.0.1.5')) {
if (globalThis.apis.version.isLeq(oldAntiCensorRu.version, '0.0.1.5')) {
// Change semicolons to semicolons followed by newlines in proxy string (raw).
const migrateProxies = (oldStr) => oldStr.replace(/;\\r?\\n?/g, ';\\n');
const modsMutated = window.apis.pacKitchen.getPacModsRaw();
const modsMutated = globalThis.apis.pacKitchen.getPacModsRaw();
if (modsMutated) {
modsMutated['customProxyStringRaw'] = migrateProxies(modsMutated['customProxyStringRaw']);
await new Promise(
(resolve) => window.apis.pacKitchen.keepCookedNowAsync(modsMutated, resolve),
(resolve) => globalThis.apis.pacKitchen.keepCookedNowAsync(modsMutated, resolve),
);
}
}
if (window.apis.version.isLeq(oldAntiCensorRu.version, '0.0.1.25')) {
if (globalThis.apis.version.isLeq(oldAntiCensorRu.version, '0.0.1.25')) {
console.log('Switch to Antizapret automatically, only from Anitcensority without own proxies.');
const provKey = antiCensorRu.getCurrentPacProviderKey();
@ -727,7 +725,7 @@
console.log('Current provider', provKey, '!== Anticensority or Antizapret');
return; // Not Anticensority.
}
const pacMods = window.apis.pacKitchen.getPacMods();
const pacMods = globalThis.apis.pacKitchen.getPacMods();
if (pacMods.filteredCustomsString) {
console.log('Proxies found:', pacMods.filteredCustomsString);
return; // Own proxies or Tor are used.

View File

@ -2,7 +2,7 @@
{
const chromified = window.utils.chromified;
const chromified = globalThis.utils.chromified;
let seqId = 0;
@ -33,7 +33,7 @@
};
window.apis.menus.getItemsAsArray().forEach((item) => {
globalThis.apis.menus.getItemsAsArray().forEach((item) => {
createMenuLinkEntry(
item.title,

View File

@ -0,0 +1,2 @@
<!DOCTYPE html>
<script src="./index.mjs" type="module"></script>;

View File

@ -0,0 +1,14 @@
import './00-init-apis.mjs';
${scripts_0x}
import './11-error-handlers-api.mjs';
import './12-errors-lib.mjs';
import './13-http-lib.mjs';
import './15-firefox-proxy-settings.mjs';
${scripts_2x}
import './35-pac-kitchen-api.mjs';
import './37-sync-pac-script-with-pac-provider-api.mjs';
import './70-menu-items.mjs';
import './75-context-menus.mjs';
import './76-hotkeys.mjs';
${scripts_8x}

View File

@ -19,7 +19,7 @@
, "tabs"
, "contextMenus"
, "notifications"
${extra_permissions}
${extraPermissions}
],
"minimum_chrome_version": "55.0.0.0",
"browser_specific_settings": {
@ -38,21 +38,7 @@
"background": {
${persistent}
"scripts": [
"00-init-apis.js"
${scripts_0x}
, "11-error-handlers-api.js"
, "12-errors-lib.js"
, "13-http-lib.js"
, "15-firefox-proxy-settings.js"
${scripts_2x}
, "35-pac-kitchen-api.js"
, "37-sync-pac-script-with-pac-provider-api.js"
, "70-menu-items.js"
, "75-context-menus.js"
, "76-hotkeys.js",
${scripts_8x}
]
"page": "./bg.html"
},
"browser_action": {

View File

@ -2,9 +2,9 @@
{
const mandatory = window.utils.mandatory;
const httpLib = window.apis.httpLib;
const clarify = window.apis.errorsLib.clarify;
const mandatory = globalThis.utils.mandatory;
const httpLib = globalThis.apis.httpLib;
const clarify = globalThis.apis.errorsLib.clarify;
// IP REGEX starts.
@ -50,7 +50,7 @@
// IP REGEX ends.
const _state = window.utils.createStorage('ip-to-host');
const _state = globalThis.utils.createStorage('ip-to-host');
const ip2host = '';
const privates = {};
@ -100,7 +100,7 @@
const generateRandomHexString = function generateRandomHexString(minLen, maxLen) {
return Array.from(window.crypto.getRandomValues(new Uint8Array(maxLen)))
return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(maxLen)))
.slice(minLen + Math.floor(Math.random()*(maxLen - minLen)))
.map((i) => i.toString(16)).join('');
@ -188,7 +188,7 @@
};
const self = window.apis.ipToHost = {
const self = globalThis.apis.ipToHost = {
persistData() {
@ -346,13 +346,13 @@
};
window.utils.addRequestResponder(
globalThis.utils.addRequestResponder(
'ip-to-host-update-all', (...args) => self.updateAllAsync(...args)
);
window.utils.addRequestResponder(
globalThis.utils.addRequestResponder(
'ip-to-host-replace-all', (...args) => self.replaceAllAsync(...args)
);
window.utils.addRequestResponder(
globalThis.utils.addRequestResponder(
'ip-to-host-reset-to-defaults', (cb) => {
self.resetToDefaults();
cb();

View File

@ -2,7 +2,7 @@
{
const timeouted = window.utils.timeouted;
const timeouted = globalThis.utils.timeouted;
const isProxied = (requestDetails) => false;
const isProxySideError = (details) =>

View File

@ -1,7 +1,7 @@
'use strict';
{
const chromified = window.utils.chromified;
const chromified = globalThis.utils.chromified;
const lastErrors = [];
const lastErrorsLength = 20;
@ -9,10 +9,10 @@
const IF_COLL_KEY = 'err-to-exc-if-coll';
const privates = {
ifCollecting: window.localStorage[IF_COLL_KEY] || false,
ifCollecting: globalThis.localStorage[IF_COLL_KEY] || false,
};
const that = window.apis.lastNetErrors = {
const that = globalThis.apis.lastNetErrors = {
get ifCollecting() {
return privates.ifCollecting;
@ -21,7 +21,7 @@
set ifCollecting(newValue) {
privates.ifCollecting = window.localStorage[IF_COLL_KEY] = newValue;
privates.ifCollecting = globalThis.localStorage[IF_COLL_KEY] = newValue;
},
get: () => lastErrors,

View File

@ -14,7 +14,7 @@
{
const chromified = window.utils.chromified;
const chromified = globalThis.utils.chromified;
const _tabCallbacks = {};
@ -136,7 +136,7 @@
const tryProxyAndInform = function tryProxyAndInform(requestDetails) {
const host = window.apis.ipToHost.get( requestDetails.ip );
const host = globalThis.apis.ipToHost.get( requestDetails.ip );
if (!host) {
return;
}

View File

@ -2,7 +2,7 @@
{
window.apis.version.ifMini = true;
globalThis.apis.version.ifMini = true;
chrome.browserAction.setBadgeText({text: 'M'});
}

View File

@ -1,71 +0,0 @@
'use strict';
const pacUrls = [
// GitHub.io (anticensority), cached:
'https://anticensority.github.io/generated-pac-scripts/anticensority.pac',
// GitHub repo (anticensority), cached:
'https://raw.githubusercontent.com/anticensority/generated-pac-scripts/master/anticensority.pac',
// First official, shortened, not cached:
'https://rebrand.ly/ac-chrome-anticensority-pac',
];
const commonContext = {
version: '1.57',
anticensorityPacUrls: [
...pacUrls,
],
};
exports.contexts = {};
const extra_permissions = ', "webRequest", "webRequestBlocking", "webNavigation"';
exports.contexts.full = Object.assign({}, commonContext, {
versionSuffix: '',
nameSuffixEn: '',
nameSuffixRu: '',
extra_permissions,
persistent: '',
scripts_0x: '',
scripts_2x: ', "20-ip-to-host-api.js"',
scripts_8x: '"80-error-menu.js", "83-last-errors.js", "85-block-informer.js"',
});
exports.contexts.mini = Object.assign({}, commonContext, {
versionSuffix: '-mini',
nameSuffixEn: ' MINI',
nameSuffixRu: ' МИНИ',
extra_permissions: '',
persistent: '"persistent": false,',
scripts_0x: '',
scripts_2x: ', "20-for-mini-only.js"',
scripts_8x: '',
});
exports.contexts.firefox = Object.assign({}, commonContext, {
versionSuffix: '',
nameSuffixEn: '',
nameSuffixRu: '',
extra_permissions,
persistent: '',
scripts_0x: ', "01-chrome-proxy-settings.js"',
scripts_2x: ', "20-ip-to-host-api.js"',
scripts_8x: ', "80-error-menu.js", "83-last-errors.js", "85-block-informer.js"',
});
exports.contexts.beta = Object.assign({}, commonContext, {
anticensorityPacUrls: [
'https://raw.githubusercontent.com/anticensority/for-testing/master/anticensority.pac',
'https://anticensority.github.io/for-testing/anticensority.pac',
'https://rebrand.ly/ac-beta-pac',
],
version: '1.14',
versionSuffix: '',
nameSuffixEn: ' FOR TESTING',
nameSuffixRu: ' ДЛЯ ТЕСТОВ',
extra_permissions,
persistent: '',
scripts_0x: '',
scripts_2x: ', "20-ip-to-host-api.js"',
scripts_8x: ', "80-error-menu.js", "83-last-errors.js", "85-block-informer.js"',
});

View File

@ -0,0 +1,47 @@
const pacUrls = [
// GitHub.io (anticensority), cached:
'https://anticensority.github.io/generated-pac-scripts/anticensority.pac',
// GitHub repo (anticensority), cached:
'https://raw.githubusercontent.com/anticensority/generated-pac-scripts/master/anticensority.pac',
// First official, shortened, not cached:
'https://rebrand.ly/ac-chrome-anticensority-pac',
];
const commonContext = {
version: '1.57',
anticensorityPacUrls: [
...pacUrls,
],
};
const contexts = {};
const extraPermissions = ', "webRequest", "webRequestBlocking", "webNavigation"';
contexts.full = Object.assign({}, commonContext, {
versionSuffix: '',
nameSuffixEn: '',
nameSuffixRu: '',
extraPermissions,
persistent: '',
scripts_0x: '',
scripts_2x: "import './20-ip-to-host-api.mjs';",
scripts_8x: `
import './80-error-menu.mjs';
import './83-last-errors.mjs';
import './85-block-informer.mjs';
`,
});
contexts.mini = Object.assign({}, commonContext, {
versionSuffix: '-mini',
nameSuffixEn: ' MINI',
nameSuffixRu: ' МИНИ',
extraPermissions: '',
persistent: '"persistent": false,',
scripts_0x: '',
scripts_2x: "import '20-for-mini-only.mjs';",
scripts_8x: '',
});
export {contexts};