Skip to content

Commit

Permalink
Update ESLint config (#5813)
Browse files Browse the repository at this point in the history
  • Loading branch information
sosnovsky authored Aug 13, 2024
1 parent 308b444 commit 748b960
Show file tree
Hide file tree
Showing 63 changed files with 123 additions and 147 deletions.
1 change: 1 addition & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ export default [
'extension/types/**',
'extension/js/common/core/types/**',
'test/source/core/types/**',
'test/source/tests/**/*.js',
],
},
pluginJs.configs.recommended,
Expand Down
2 changes: 1 addition & 1 deletion extension/chrome/elements/attachment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ export class AttachmentDownloadView extends View {
try {
const googleDriveFileId = url.split('/').pop()?.split('?').shift(); // try and catch any errors below if structure is not as expected
url = googleDriveFileId ? `https://drive.google.com/uc?export=download&id=${googleDriveFileId}` : url; // attempt to get length headers from Google Drive file if available
} catch (e) {
} catch {
// leave url as is
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class ComposeErrModule extends ViewModule<ComposeView> {
} else if (typeof e === 'object' && e && typeof (e as { stack: string }).stack === 'undefined') {
try {
(e as { stack: string }).stack = `[compose action: ${couldNotDoWhat}]`;
} catch (e) {
} catch {
// no need
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ export class ComposeQuoteModule extends ViewModule<ComposeView> {
const from = Str.parseEmail(this.messageToReplyOrForward.headers.from || '').email;
const date = new Date(String(this.messageToReplyOrForward.headers.date));
const dateStr = Str.fromDate(date).replace(' ', ' at ');
const rtl = text.match(new RegExp('[' + Str.rtlChars + ']'));
const rtl = new RegExp('[' + Str.rtlChars + ']').exec(text);
const dirAttr = `dir="${rtl ? 'rtl' : 'ltr'}"`;
const escapedText = this.convertLineBreakToBr(Xss.escape(text), method === 'reply');
if (method === 'reply') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ export class ComposeRenderModule extends ViewModule<ComposeView> {
let normalizedPub: string;
try {
normalizedPub = await keyImportUi.checkPub(textData);
} catch (e) {
} catch {
return; // key is invalid
}
const key = await KeyUtil.parse(normalizedPub);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ export class ComposeSendBtnModule extends ViewModule<ComposeView> {
let mimeType;
let data = '';
const parts = src.split(/[:;,]/);
if (parts.length === 4 && parts[0] === 'data' && parts[1].match(/^image\/\w+/) && parts[2] === 'base64') {
if (parts.length === 4 && parts[0] === 'data' && /^image\/\w+/.exec(parts[1]) && parts[2] === 'base64') {
mimeType = parts[1];
data = parts[3];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export class ComposeStorageModule extends ViewModule<ComposeView> {
try {
// no valid keys found, query synchronously, then return result
await this.updateLocalPubkeysFromRemote(storedContact?.sortedPubkeys || [], email);
} catch (e) {
} catch {
return PUBKEY_LOOKUP_RESULT_FAIL;
}
// re-query the storage, which is now updated
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,9 @@ export class GeneralMailFormatter {
`Could not sign this encrypted message. The sender email ${view.senderModule.getSender()} isn't present in the signing key's user ids`
);
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const msg = await new SignedMsgMailFormatter(view).sendableMsg(newMsgData, signingKey.key);

return {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
senderKi: signingKey.keyInfo,
msgs: [msg],
renderSentMessage: { recipients: msg.recipients, attachments: msg.attachments },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ export class InboxMenuModule extends ViewModule<InboxView> {

private renderFolder = (labelEl: HTMLSpanElement) => {
for (const cls of labelEl.classList) {
const labelId = (cls.match(/^label_([a-zA-Z0-9_]+)$/) || [])[1];
const labelId = (/^label_([a-zA-Z0-9_]+)$/.exec(cls) || [])[1];
if (labelId) {
this.view.redirectToUrl({ acctEmail: this.view.acctEmail, labelId });
return;
Expand Down
3 changes: 0 additions & 3 deletions extension/chrome/settings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ View.run(
const uncheckedUrlParams = Url.parse(['acctEmail', 'page', 'pageUrlParams', 'advanced', 'addNewAcct']);
this.acctEmail = Assert.urlParamRequire.optionalString(uncheckedUrlParams, 'acctEmail');
this.page = Assert.urlParamRequire.optionalString(uncheckedUrlParams, 'page');
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (this.page && !/^(\/chrome|modules)/.test(this.page)) {
Ui.modal.error('An unexpected value was found for the page parameter').catch((err: unknown) => {
console.log(err);
Expand Down Expand Up @@ -244,7 +243,6 @@ View.run(
$('#status-row #status_local_store').on(
'click',
this.setHandler(async () => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
await Settings.renderSubPage(this.acctEmail, this.tabId, 'modules/debug_api.htm', { which: 'local_store' });
})
);
Expand Down Expand Up @@ -391,7 +389,6 @@ View.run(
);
statusContainer.empty().append(authNeededLink); // xss-direct
$('#status-row #status_flowcrypt').text(`fc:auth`).addClass('bad');
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
Settings.offerToLoginWithPopupShowModalOnErr(this.acctEmail, () => {
window.location.reload();
});
Expand Down
2 changes: 1 addition & 1 deletion extension/chrome/settings/modules/contacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ View.run(
const pubkey = await KeyUtil.parse(armoredPubkey);
await ContactStore.update(undefined, email, { pubkey, lastUse: Date.now() });
await this.loadAndRenderContactList();
} catch (e) {
} catch {
await Ui.modal.warning('Cannot recognize a valid public key, please try again. ' + Lang.general.contactIfNeedAssistance(!!this.fesUrl));
$('#edit_contact .input_pubkey').val('').trigger('focus');
}
Expand Down
3 changes: 1 addition & 2 deletions extension/chrome/settings/modules/my_key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ import { Xss } from '../../../js/common/platform/xss.js';
import { FlowCryptWebsite } from '../../../js/common/api/flowcrypt-website.js';

declare class ClipboardJS {
// eslint-disable-next-line @typescript-eslint/ban-types
public constructor(selector: string, options: {});
public constructor(selector: string, options: unknown);
}

View.run(
Expand Down
2 changes: 1 addition & 1 deletion extension/chrome/settings/setup/setup-recover-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export class SetupRecoverKeyModule {
const backups = await this.view.gmail.fetchKeyBackups();
this.view.fetchedKeyBackups = backups.keyinfos.backups;
this.view.fetchedKeyBackupsUniqueLongids = backups.longids.backups;
} catch (e) {
} catch {
window.location.href = Url.create('modules/add_key.htm', {
acctEmail: this.view.acctEmail,
parentTabId: this.view.parentTabId,
Expand Down
4 changes: 1 addition & 3 deletions extension/chrome/settings/setup/setup-render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export class SetupRenderModule {
public renderInitial = async (): Promise<void> => {
$('.email-address').text(this.view.acctEmail);
$('#button-go-back').css('visibility', 'hidden');
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (this.view.storage.email_provider === 'gmail') {
// show alternative account addresses in setup form + save them for later
try {
Expand All @@ -40,7 +39,7 @@ export class SetupRenderModule {
return;
}
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion

if (this.view.storage.setup_done && this.view.action !== 'update_from_ekm') {
if (this.view.action !== 'add_key') {
await this.renderSetupDone();
Expand Down Expand Up @@ -142,7 +141,6 @@ export class SetupRenderModule {
if (!this.view.clientConfiguration.canBackupKeys()) {
// they already have a key recorded on attester, but no backups allowed on the domain. They should enter their prv manually
this.displayBlock('step_2b_manual_enter');
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
} else if (this.view.storage.email_provider === 'gmail') {
try {
const backups = await this.view.gmail.fetchKeyBackups();
Expand Down
6 changes: 2 additions & 4 deletions extension/js/common/api/authentication/google/google-oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ import { ConfiguredIdpOAuth } from '../configured-idp-oauth.js';
// eslint-disable-next-line @typescript-eslint/naming-convention
type GoogleTokenInfo = { email: string; scope: string; expires_in: number; token_type: string };

/* eslint-enable @typescript-eslint/naming-convention */

export class GoogleOAuth extends OAuth {
public static defaultScopes(group: 'default' | 'contacts' = 'default') {
const { readContacts, readOtherContacts, compose, modify, openid, email, profile } = this.GOOGLE_OAUTH_CONFIG.scopes;
Expand Down Expand Up @@ -97,7 +95,7 @@ export class GoogleOAuth extends OAuth {
};

try {
return performAjaxRequest(req);
return await performAjaxRequest(req);
} catch (firstAttemptErr) {
if (ApiErr.isAuthErr(firstAttemptErr)) {
// force refresh token
Expand Down Expand Up @@ -209,7 +207,7 @@ export class GoogleOAuth extends OAuth {
if (authWindowResult.error) {
return { acctEmail, result: 'Denied', error: authWindowResult.error, id_token: undefined };
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion

const uncheckedUrlParams = Url.parse(['scope', 'code', 'state'], authWindowResult.url);
const allowedScopes = Assert.urlParamRequire.string(uncheckedUrlParams, 'scope');
const code = Assert.urlParamRequire.optionalString(uncheckedUrlParams, 'code');
Expand Down
6 changes: 3 additions & 3 deletions extension/js/common/api/email-provider/gmail/gmail-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@ export namespace GmailRes {
resultSizeEstimate: number;
};
export type GmailDraftCreate = { id: string };
export type GmailDraftDelete = {}; // eslint-disable-line @typescript-eslint/ban-types
export type GmailDraftUpdate = {}; // eslint-disable-line @typescript-eslint/ban-types
export type GmailDraftDelete = object;
export type GmailDraftUpdate = object;
export type GmailDraftGet = { id: string; message: GmailMsg };
export type GmailDraftMeta = { id: string; message: { id: string; threadId: string } };
export type GmailDraftList = { drafts: GmailDraftMeta[]; nextPageToken: string };
export type GmailDraftSend = {}; // eslint-disable-line @typescript-eslint/ban-types
export type GmailDraftSend = object;
export type GmailAliases = { sendAs: GmailAliases$sendAs[] };
type GmailAliases$sendAs = {
sendAsEmail: string;
Expand Down
4 changes: 2 additions & 2 deletions extension/js/common/api/email-provider/gmail/gmail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ export class Gmail extends EmailProviderApi implements EmailProviderInterface {
try {
resolve(Buf.fromBase64UrlStr(parsedJsonDataField));
return;
} catch (e) {
} catch {
// the chunk of data may have been cut at an inconvenient index
// shave off up to 50 trailing characters until it can be decoded
parsedJsonDataField = parsedJsonDataField.slice(0, -1);
Expand Down Expand Up @@ -312,7 +312,7 @@ export class Gmail extends EmailProviderApi implements EmailProviderInterface {
.map(bigNeedle => {
const email = Str.parseEmail(bigNeedle);
if (email?.email) {
const match = email.email.match(/^(.*@.+)\.[^@]+?$/);
const match = /^(.*@.+)\.[^@]+?$/.exec(email.email);
if (match) bigNeedle = match[1]; // omit the top-level domain
}
return bigNeedle.split('.').filter(v => !['com', 'org', 'net'].includes(v));
Expand Down
1 change: 0 additions & 1 deletion extension/js/common/api/email-provider/sendable-msg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,6 @@ export class SendableMsg {
this.headers['Reply-To'] = this.replyTo;
}
for (const [recipientType, value] of Object.entries(this.recipients)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (value?.length) {
// todo - properly escape/encode this header using emailjs
this.headers[recipientType[0].toUpperCase() + recipientType.slice(1)] = value
Expand Down
2 changes: 1 addition & 1 deletion extension/js/common/api/key-server/sks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class Sks extends Api {
.map(l => l.trim())
.filter(l => !l.startsWith(Sks.MR_VERSION_1))) {
if (line.startsWith('pub:')) {
const match = line.match(/^pub:[A-F0-9]{24}([A-F0-9]{16}):[0-9:]+:$/); // in particular cannot end with :r, meaning revoked
const match = /^pub:[A-F0-9]{24}([A-F0-9]{16}):[0-9:]+:$/.exec(line); // in particular cannot end with :r, meaning revoked
if (!match) {
currentLongid = '';
} else {
Expand Down
2 changes: 1 addition & 1 deletion extension/js/common/api/key-server/wkd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export class Wkd extends Api {
private urlLookup = async (methodUrlBase: string, userPart: string, timeout: number): Promise<{ hasPolicy: boolean; buf?: Buf }> => {
try {
await Wkd.download(`${methodUrlBase}/policy`, undefined, timeout);
} catch (e) {
} catch {
return { hasPolicy: false };
}
try {
Expand Down
10 changes: 5 additions & 5 deletions extension/js/common/api/shared/api-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ abstract class ApiCallErr extends Error {
if (typeof req.data === 'string') {
try {
return Object.keys(JSON.parse(req.data) as string).join(',');
} catch (e) {
} catch {
return 'not-a-json';
}
} else if (req.data && typeof req.data === 'object') {
Expand Down Expand Up @@ -111,7 +111,7 @@ export class AjaxErr extends ApiCallErr {
let parsedRes: unknown;
try {
parsedRes = JSON.parse(responseText);
} catch (e) {
} catch {
return {};
}
try {
Expand All @@ -128,7 +128,7 @@ export class AjaxErr extends ApiCallErr {
if (typeof resCode === 'number') {
returnable.resCode = resCode;
}
} catch (e) {
} catch {
// skip
}
try {
Expand All @@ -145,7 +145,7 @@ export class AjaxErr extends ApiCallErr {
if (typeof resCode === 'number') {
returnable.resCode = resCode;
}
} catch (e) {
} catch {
// skip
}
return returnable;
Expand Down Expand Up @@ -230,7 +230,7 @@ export class ApiErr {
const jsonErrorDesc = (json as { error_description: string }).error_description;
return jsonErrorDesc === 'Bad Request' || jsonErrorDesc === 'Token has been expired or revoked.';
}
} catch (e) {
} catch {
return false;
}
}
Expand Down
2 changes: 1 addition & 1 deletion extension/js/common/assert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export class Assert {
// eg expected string or optional string, and got string
return values[name];
}
if (actualType === 'undefined' && expectedType.match(/\?$/)) {
if (actualType === 'undefined' && /\?$/.exec(expectedType)) {
// optional type, got undefined: ok
return values[name];
}
Expand Down
1 change: 0 additions & 1 deletion extension/js/common/browser/browser-msg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,6 @@ export class BrowserMsg {
await handleClickEvent(tabId, account.name, msgId);
}
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
}
});
}
Expand Down
3 changes: 1 addition & 2 deletions extension/js/common/browser/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class Env {
const extensionUrl = chrome.runtime.getURL('');
// Check if the current page URL is different from the extension's base URL (i.e., it's not an extension page)
return !window.location.href.startsWith(extensionUrl);
} catch (e) {
} catch {
// In case of any errors (which shouldn't happen in a proper extension context), assume it's not a content script
return false;
}
Expand All @@ -55,7 +55,6 @@ export class Env {
return { a: 97, r: 114, A: 65, R: 82, f: 102, F: 70, backspace: 8, tab: 9, enter: 13, comma: 188 };
}

// eslint-disable-next-line @typescript-eslint/require-await
public static async webmails(): Promise<WebMailName[]> {
return ['gmail']; // async because storage may be involved in the future
}
Expand Down
2 changes: 1 addition & 1 deletion extension/js/common/browser/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export class Ui {
Catch.reportErr(e);
}
},
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type, @typescript-eslint/no-unnecessary-type-parameters
prevent: <THIS extends HTMLElement | void>(
evName: PreventableEventName,
cb: (el: HTMLElement, event: Event | undefined, resetTimer: () => void) => void | Promise<void>,
Expand Down
4 changes: 2 additions & 2 deletions extension/js/common/core/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ export class Str {

public static is7bit = (content: string | Uint8Array): boolean => {
for (let i = 0; i < content.length; i++) {
const code = typeof content === 'string' ? content.charCodeAt(i) : content[i] ?? 0;
const code = typeof content === 'string' ? content.charCodeAt(i) : (content[i] ?? 0);
if (!(code >= 0 && code <= 127)) {
return false;
}
Expand Down Expand Up @@ -234,7 +234,7 @@ export class Str {
public static htmlAttrDecode = (encoded: string): unknown => {
try {
return JSON.parse(Str.base64urlUtfDecode(encoded));
} catch (e) {
} catch {
return undefined;
}
};
Expand Down
4 changes: 2 additions & 2 deletions extension/js/common/core/crypto/pgp/openpgp-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export class OpenPGPKey {
let lastModified: undefined | number;
try {
lastModified = await OpenPGPKey.getLastSigTime(keyWithoutWeakPackets);
} catch (e) {
} catch {
// never had any valid signature
}
const fingerprint = keyWithoutWeakPackets.getFingerprint();
Expand Down Expand Up @@ -583,7 +583,7 @@ export class OpenPGPKey {
await signatures[i].verify(primaryKey, signatureType, dataToVerify);
signature = signatures[i];
}
} catch (e) {
} catch {
// skip signature with failed verification
}
}
Expand Down
6 changes: 3 additions & 3 deletions extension/js/common/core/crypto/pgp/pgp-armor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export class PgpArmor {
};

public static isEncryptedMsg(msg: string): boolean {
return !!msg.match(new RegExp(`${PgpArmor.ARMOR_HEADER_DICT.encryptedMsg.begin}.*${PgpArmor.ARMOR_HEADER_DICT.encryptedMsg.end}`));
return !!new RegExp(`${PgpArmor.ARMOR_HEADER_DICT.encryptedMsg.begin}.*${PgpArmor.ARMOR_HEADER_DICT.encryptedMsg.end}`).exec(msg);
}

public static clipIncomplete(text: string): string | undefined {
Expand Down Expand Up @@ -112,10 +112,10 @@ export class PgpArmor {
// check for and fix missing a mandatory empty line
if (lines.length > 5 && lines[0].includes(h.begin) && lines[lines.length - 1].includes(String(h.end)) && !lines.includes('')) {
for (let i = 1; i < 5; i++) {
if (lines[i].match(/^[a-zA-Z0-9\-_. ]+: .+$/)) {
if (/^[a-zA-Z0-9\-_. ]+: .+$/.exec(lines[i])) {
continue; // skip comment lines, looking for first data line
}
if (lines[i].match(/^[a-zA-Z0-9\/+]{32,77}$/)) {
if (/^[a-zA-Z0-9\/+]{32,77}$/.exec(lines[i])) {
// insert empty line before first data line
armored = `${lines.slice(0, i).join('\n')}\n\n${lines.slice(i).join('\n')}`;
break;
Expand Down
Loading

0 comments on commit 748b960

Please sign in to comment.