From 4426beadd30e7391b3afae211f9201c3c6db0b4d Mon Sep 17 00:00:00 2001 From: Jonathan Kingston Date: Mon, 24 Jul 2023 13:54:03 +0000 Subject: [PATCH] Remove * import warnings (#2113) --- .eslintrc | 2 +- shared/js/background/devbuild-reloader.js | 15 +++++------ shared/js/background/devbuild.js | 7 +++-- shared/js/background/dnr-config-rulesets.js | 16 ++++++------ shared/js/background/dnr-session-rule-id.js | 6 ++--- .../events/privacy-icon-indicator.js | 6 ++--- shared/js/background/newtab-tracker-stats.js | 10 +++---- shared/js/background/tracker-utils.js | 26 +++++++++---------- shared/js/background/utils.js | 10 +++---- shared/js/newtab/newtab.js | 10 +++---- unit-test/legacy/declarative-net-request.js | 7 +++++ 11 files changed, 62 insertions(+), 53 deletions(-) diff --git a/.eslintrc b/.eslintrc index 5c193cb8b9..a265affb8a 100644 --- a/.eslintrc +++ b/.eslintrc @@ -4,7 +4,7 @@ "indent": ["error", 4], "no-shadow": ["error"], "no-restricted-syntax": [ - "warn", + "error", { "selector": ":matches(ImportNamespaceSpecifier, ExportAllDeclaration, ExportNamespaceSpecifier)", "message": "Prefer explicit named imports over wildcard (import * as x)" diff --git a/shared/js/background/devbuild-reloader.js b/shared/js/background/devbuild-reloader.js index 8a493335eb..483ce4e7be 100644 --- a/shared/js/background/devbuild-reloader.js +++ b/shared/js/background/devbuild-reloader.js @@ -4,12 +4,11 @@ */ import browser from 'webextension-polyfill' -// TODO: Only import `createAlarm`, `getFromSessionStorage` and `setToSessionStorage` here -import * as browserWrapper from './wrapper' +import { createAlarm, getFromSessionStorage, setToSessionStorage } from './wrapper' export default function initReloader () { - function createAlarm () { - browserWrapper.createAlarm('checkBuildTime', { when: Date.now() + 5000 }) + function createAlarmTimer () { + createAlarm('checkBuildTime', { when: Date.now() + 5000 }) } browser.alarms.onAlarm.addListener(async alarmEvent => { @@ -25,16 +24,16 @@ export default function initReloader () { } catch (e) { } if (buildTime) { - const previousBuildTime = await browserWrapper.getFromSessionStorage('buildTime') + const previousBuildTime = await getFromSessionStorage('buildTime') if (!previousBuildTime) { - await browserWrapper.setToSessionStorage('buildTime', buildTime) + await setToSessionStorage('buildTime', buildTime) } else if (buildTime !== previousBuildTime) { browser.runtime.reload() } } - createAlarm() + createAlarmTimer() }) - createAlarm() + createAlarmTimer() } diff --git a/shared/js/background/devbuild.js b/shared/js/background/devbuild.js index af8a6c3338..03b4259476 100644 --- a/shared/js/background/devbuild.js +++ b/shared/js/background/devbuild.js @@ -2,7 +2,7 @@ * This exposes some modules we use for testing via the background page console. * NOTE this is not added to the release version of the extension */ -import * as startup from './startup' +import { onStartup, ready } from './startup' import Companies from './companies' import atb from './atb' import tds from './storage/tds' @@ -21,7 +21,10 @@ export default function initDebugBuild () { // @ts-ignore - dbg is not a standard property of self. self.dbg = { settings, - startup, + startup: { + ready, + onStartup + }, tabManager, Tab, TabState, diff --git a/shared/js/background/dnr-config-rulesets.js b/shared/js/background/dnr-config-rulesets.js index c9cbb46fc5..cce78c2115 100644 --- a/shared/js/background/dnr-config-rulesets.js +++ b/shared/js/background/dnr-config-rulesets.js @@ -1,8 +1,8 @@ -import * as browserWrapper from './wrapper' +import { getExtensionVersion, getManifestVersion } from './wrapper' import settings from './settings' import tdsStorage from './storage/tds' import trackers from './trackers' -import * as startup from './startup' +import { ready as startupReady } from './startup' import { isFeatureEnabled } from './utils' import { ensureServiceWorkerInitiatedRequestExceptions @@ -181,7 +181,7 @@ async function updateConfigRules ( * @returns {Promise<>} */ export async function updateExtensionConfigRules (etag = null, configValue = null) { - const extensionVersion = browserWrapper.getExtensionVersion() + const extensionVersion = getExtensionVersion() const denylistedDomains = await getDenylistedDomains() const latestState = { @@ -228,7 +228,7 @@ export async function updateExtensionConfigRules (etag = null, configValue = nul } export async function updateCombinedConfigBlocklistRules () { - const extensionVersion = browserWrapper.getExtensionVersion() + const extensionVersion = getExtensionVersion() const denylistedDomains = await getDenylistedDomains() const tdsEtag = settings.getSetting('tds-etag') const combinedState = { @@ -261,7 +261,7 @@ let ruleUpdateLock = Promise.resolve() * @returns {Promise} */ export async function onConfigUpdate (configName, etag, configValue) { - const extensionVersion = browserWrapper.getExtensionVersion() + const extensionVersion = getExtensionVersion() // Run an async lock on all blocklist updates so the latest update is always processed last ruleUpdateLock = ruleUpdateLock.then(async () => { // TDS (aka the block list). @@ -272,8 +272,8 @@ export async function onConfigUpdate (configName, etag, configValue) { return } - await startup.ready() - // @ts-ignore: Once startup.ready() has finished, surrogateList will be + await startupReady() + // @ts-ignore: Once startupReady() has finished, surrogateList will be // assigned. const supportedSurrogates = new Set(Object.keys(trackers.surrogateList)) @@ -299,7 +299,7 @@ export async function onConfigUpdate (configName, etag, configValue) { await ruleUpdateLock } -if (browserWrapper.getManifestVersion() === 3) { +if (getManifestVersion() === 3) { tdsStorage.onUpdate('config', onConfigUpdate) tdsStorage.onUpdate('tds', onConfigUpdate) } diff --git a/shared/js/background/dnr-session-rule-id.js b/shared/js/background/dnr-session-rule-id.js index 518206055c..712e47124a 100644 --- a/shared/js/background/dnr-session-rule-id.js +++ b/shared/js/background/dnr-session-rule-id.js @@ -2,14 +2,14 @@ * For managing dynamically created MV3 session rules * getNextSessionRuleId will return the next unique session rule id to use when creating new session rules **/ -import * as browserWrapper from './wrapper' +import { getFromSessionStorage, setToSessionStorage } from './wrapper' const SESSION_RULE_ID_START = 100000 const SESSION_RULE_STORAGE_KEY = 'sessionRuleOffset' let sessionRuleOffset = 0 let ready = false export async function setSessionRuleOffsetFromStorage () { - const offset = await browserWrapper.getFromSessionStorage(SESSION_RULE_STORAGE_KEY) + const offset = await getFromSessionStorage(SESSION_RULE_STORAGE_KEY) if (offset) { sessionRuleOffset = offset } @@ -28,7 +28,7 @@ export function getNextSessionRuleId () { const nextRuleId = SESSION_RULE_ID_START + sessionRuleOffset sessionRuleOffset += 1 - browserWrapper.setToSessionStorage(SESSION_RULE_STORAGE_KEY, sessionRuleOffset) + setToSessionStorage(SESSION_RULE_STORAGE_KEY, sessionRuleOffset) return nextRuleId } diff --git a/shared/js/background/events/privacy-icon-indicator.js b/shared/js/background/events/privacy-icon-indicator.js index 6dc53f543d..3e0cdad578 100644 --- a/shared/js/background/events/privacy-icon-indicator.js +++ b/shared/js/background/events/privacy-icon-indicator.js @@ -1,4 +1,4 @@ -import * as constants from '../../../data/constants' +import { iconPaths } from '../../../data/constants' import { setActionIcon } from '../wrapper' /** @@ -20,8 +20,8 @@ export function updateActionIcon (site, tabId) { // Enabled: regular icon // Disabled: special state, greyed-out Dax const nextIcon = protectionsEnabled - ? constants.iconPaths.regular - : constants.iconPaths.withSpecialState + ? iconPaths.regular + : iconPaths.withSpecialState // now call out to the browser wrapper to actually change the icon return setActionIcon(nextIcon, tabId) diff --git a/shared/js/background/newtab-tracker-stats.js b/shared/js/background/newtab-tracker-stats.js index e62635e7ac..f84f8db8b2 100644 --- a/shared/js/background/newtab-tracker-stats.js +++ b/shared/js/background/newtab-tracker-stats.js @@ -1,6 +1,6 @@ import browser from 'webextension-polyfill' import constants from '../../data/constants' -import * as browserWrapper from './wrapper.js' +import { getManifestVersion, createAlarm, syncToStorage, getFromStorage } from './wrapper.js' import tdsStorage from './storage/tds' import { emitter, TrackerBlockedEvent } from './before-request.js' import { generateDNRRule } from '@duckduckgo/ddg2dnr/lib/utils' @@ -74,7 +74,7 @@ export class NewTabTrackerStats { * place for this module. */ register () { - const manifestVersion = browserWrapper.getManifestVersion() + const manifestVersion = getManifestVersion() if (manifestVersion === 3) { mv3Redirect() } else { @@ -111,7 +111,7 @@ export class NewTabTrackerStats { * For now, we're pruning data every 10 min */ const pruneAlarmName = 'pruneNewTabData' - browserWrapper.createAlarm(pruneAlarmName, { periodInMinutes: 10 }) + createAlarm(pruneAlarmName, { periodInMinutes: 10 }) browser.alarms.onAlarm.addListener(async alarmEvent => { if (alarmEvent.name === pruneAlarmName) { this._handlePruneAlarm() @@ -206,7 +206,7 @@ export class NewTabTrackerStats { stats: serializedData } } - browserWrapper.syncToStorage(toSync) + syncToStorage(toSync) } /** @@ -215,7 +215,7 @@ export class NewTabTrackerStats { */ async restoreFromStorage () { try { - const prev = await browserWrapper.getFromStorage(NewTabTrackerStats.storageKey) + const prev = await getFromStorage(NewTabTrackerStats.storageKey) if (prev) { this.stats.deserialize(prev.stats) } diff --git a/shared/js/background/tracker-utils.js b/shared/js/background/tracker-utils.js index 98c3466bb0..1070ebcfab 100644 --- a/shared/js/background/tracker-utils.js +++ b/shared/js/background/tracker-utils.js @@ -1,7 +1,7 @@ // Utility functions for dealing with tracker information -import * as utils from './utils' +import { extractHostFromURL, isSafeListed, extractLimitedDomainFromURL, brokenListIndex, isSameTopLevelDomain } from './utils' import trackers from './trackers' -import * as tldts from 'tldts' +import { parse as tldtsParse } from 'tldts' import tdsStorage from './storage/tds' export function hasTrackerListLoaded () { @@ -11,12 +11,12 @@ export function hasTrackerListLoaded () { // Determine if two URL's belong to the same entity. export function isSameEntity (url1, url2) { try { - const domain1 = tldts.parse(url1).domain - const domain2 = tldts.parse(url2).domain + const domain1 = tldtsParse(url1).domain + const domain2 = tldtsParse(url2).domain if (domain1 === domain2) return true - const entity1 = trackers.findWebsiteOwner({ siteUrlSplit: utils.extractHostFromURL(url1).split('.') }) - const entity2 = trackers.findWebsiteOwner({ siteUrlSplit: utils.extractHostFromURL(url2).split('.') }) + const entity1 = trackers.findWebsiteOwner({ siteUrlSplit: extractHostFromURL(url1).split('.') }) + const entity2 = trackers.findWebsiteOwner({ siteUrlSplit: extractHostFromURL(url2).split('.') }) if (entity1 === undefined && entity2 === undefined) return false return entity1 === entity2 } catch (e) { @@ -28,7 +28,7 @@ export function isSameEntity (url1, url2) { // return true if URL is in our tracker list export function isTracker (url) { const data = { - urlToCheckSplit: utils.extractHostFromURL(url).split('.') + urlToCheckSplit: extractHostFromURL(url).split('.') } const tracker = trackers.findTracker(data) return !!tracker @@ -51,7 +51,7 @@ export function truncateReferrer (referrer, target) { return undefined } - if (utils.isSafeListed(referrer) || utils.isSafeListed(target)) { + if (isSafeListed(referrer) || isSafeListed(target)) { return undefined } @@ -63,13 +63,13 @@ export function truncateReferrer (referrer, target) { } const exceptionList = tdsStorage.config.features.referrer.exceptions - if (utils.brokenListIndex(referrer, exceptionList) !== -1 || utils.brokenListIndex(target, exceptionList) !== -1) { + if (brokenListIndex(referrer, exceptionList) !== -1 || brokenListIndex(target, exceptionList) !== -1) { return undefined } // If extractLimitedDomainFromURL fails (for instance, invalid referrer URL), it // returns undefined, (in practice, don't modify the referrer), so sometimes this value could be undefined. - return utils.extractLimitedDomainFromURL(referrer, { keepSubdomains: true }) + return extractLimitedDomainFromURL(referrer, { keepSubdomains: true }) } /** @@ -82,14 +82,14 @@ export function isFirstPartyByEntity (trackerUrl, siteUrl) { const cnameResolution = trackers.resolveCname(trackerUrl) trackerUrl = cnameResolution.finalURL - if (utils.isSameTopLevelDomain(trackerUrl, siteUrl)) { + if (isSameTopLevelDomain(trackerUrl, siteUrl)) { return true } - const trackerDomain = tldts.parse(trackerUrl).domain + const trackerDomain = tldtsParse(trackerUrl).domain if (!trackerDomain) return false const trackerOwner = trackers.findTrackerOwner(trackerDomain) - const websiteOwner = trackers.findWebsiteOwner({ siteUrlSplit: utils.extractHostFromURL(siteUrl).split('.') }) + const websiteOwner = trackers.findWebsiteOwner({ siteUrlSplit: extractHostFromURL(siteUrl).split('.') }) return (trackerOwner && websiteOwner) ? trackerOwner === websiteOwner : false } diff --git a/shared/js/background/utils.js b/shared/js/background/utils.js index 6162a9df2e..20ebe101df 100644 --- a/shared/js/background/utils.js +++ b/shared/js/background/utils.js @@ -2,7 +2,7 @@ import browser from 'webextension-polyfill' import { getExtensionVersion, getFromSessionStorage, setToSessionStorage } from './wrapper' import tdsStorage from './storage/tds' import settings from './settings' -import * as tldts from 'tldts' +import { parse as tldtsParse } from 'tldts' import parseUserAgentString from '../shared-utils/parse-user-agent-string' import sha1 from '../shared-utils/sha1' const browserInfo = parseUserAgentString() @@ -52,7 +52,7 @@ export async function sendAllTabsMessage (message, details) { * @returns {string | null} etld plus one of the URL */ export function getBaseDomain (urlString) { - const parsedUrl = tldts.parse(urlString, { allowPrivateDomains: true }) + const parsedUrl = tldtsParse(urlString, { allowPrivateDomains: true }) if (parsedUrl.hostname === 'localhost' || parsedUrl.hostname?.endsWith('.localhost') || parsedUrl.isIp) { return parsedUrl.hostname } @@ -68,7 +68,7 @@ export function extractHostFromURL (url, shouldKeepWWW) { url = 'about://' + url.substr(6) } - const urlObj = tldts.parse(url) + const urlObj = tldtsParse(url) let hostname = urlObj.hostname || '' if (!shouldKeepWWW) { @@ -84,7 +84,7 @@ export function extractLimitedDomainFromURL (url, { keepSubdomains } = {}) { if (!url) return undefined try { const parsedURL = new URL(url) - const tld = tldts.parse(url) + const tld = tldtsParse(url) if (!parsedURL || !tld) return '' // tld.domain is null if this is an IP or the domain does not use a known TLD (e.g. localhost) // in that case use the hostname (no truncation) @@ -256,7 +256,7 @@ export function getEnabledFeatures (url) { } export function brokenListIndex (url, list) { - const parsedDomain = tldts.parse(url) + const parsedDomain = tldtsParse(url) const hostname = parsedDomain.hostname || url // If root domain in temp unprotected list, return true diff --git a/shared/js/newtab/newtab.js b/shared/js/newtab/newtab.js index ebb127f18e..24fd50a7ff 100644 --- a/shared/js/newtab/newtab.js +++ b/shared/js/newtab/newtab.js @@ -1,5 +1,5 @@ import constants from '../../data/constants' -import * as schema from './schema' +import { incoming, outgoing } from './schema' const { events, allowedOrigin, clientPortName } = constants.trackerStats /** @@ -74,11 +74,11 @@ window.addEventListener('message', (e) => { * This allows developers to come here and read the schemas to figure out what data * will be sent. * - * @param {import("zod").infer} msg + * @param {import("zod").infer} msg */ function sendToNewTabPage (msg) { // try to validate the message - const parsed = schema.outgoing.safeParse(msg) + const parsed = outgoing.safeParse(msg) if (!parsed.success) { console.warn('not forwarding as validation failed on', msg) return console.error(parsed.error) @@ -100,7 +100,7 @@ function sendToNewTabPage (msg) { * so we take a straight-forward approach to errors. Any communication error found here * will result in the NTP receiving a 'disconnect' message so that it can remove its UI * - * @param {import("zod").infer} msg + * @param {import("zod").infer} msg */ let port = null function sendToChromeRuntime (msg) { @@ -113,7 +113,7 @@ function sendToChromeRuntime (msg) { } // now ensure the event is valid - const parsed = schema.incoming.safeParse(msg) + const parsed = incoming.safeParse(msg) if (!parsed.success) { console.warn('not forwarding to the chrome runtime because validation failed for:', msg) return console.error(parsed.error) diff --git a/unit-test/legacy/declarative-net-request.js b/unit-test/legacy/declarative-net-request.js index d54a5f9e36..4b165ccf2e 100644 --- a/unit-test/legacy/declarative-net-request.js +++ b/unit-test/legacy/declarative-net-request.js @@ -1,9 +1,16 @@ import '../helpers/mock-browser-api' +// TODO remove the * imports +// eslint-disable-next-line no-restricted-syntax import * as allowlistedTrackers from '@duckduckgo/privacy-reference-tests/tracker-radar-tests/TR-domain-matching/tracker_allowlist_reference.json' +// eslint-disable-next-line no-restricted-syntax import * as tds from '../data/tds.json' +// eslint-disable-next-line no-restricted-syntax import * as browserWrapper from '../../shared/js/background/wrapper' +// eslint-disable-next-line no-restricted-syntax import * as testConfig from '../data/extension-config.json' +// eslint-disable-next-line no-restricted-syntax import * as tdsStorageStub from '../helpers/tds' +// eslint-disable-next-line no-restricted-syntax import * as startup from '../../shared/js/background/startup' import settings from '../../shared/js/background/settings' import tabManager from '../../shared/js/background/tab-manager'