Skip to content

Commit

Permalink
chore: eslint update (#2567)
Browse files Browse the repository at this point in the history
* chore: add new linting file

* chore: remove old eslint file

* feat: add globals package

* feat: add globals

* chore: update eslint-security plugin

* chore: remove .eslintignore

* chore: update linters

* fix: errors

* chore: update rules

* chore: improve code quality
  • Loading branch information
Tuditi authored May 30, 2024
1 parent 4d8b6b7 commit 60e30ef
Show file tree
Hide file tree
Showing 26 changed files with 341 additions and 338 deletions.
4 changes: 2 additions & 2 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const eslintRules = {
semi: 'off', // OFF b/c we aren't using semicolons
'space-before-function-paren': 'off', // OFF b/c we aren't using spaces before function parameters / signatures
'spaced-comment': 'error',
'security/detect-object-injection': 'off',
}

const eslintRulesOnlyTypescript = {
Expand All @@ -78,7 +79,7 @@ const typescriptEslintRules = {
'@typescript-eslint/no-non-null-asserted-optional-chain': 'error',
'@typescript-eslint/no-non-null-assertion': 'error',
'@typescript-eslint/no-this-alias': 'error',
'@typescript-eslint/no-redundant-type-constituents': 'warn',
'@typescript-eslint/no-redundant-type-constituents': 'off', // OFF b/c this rule is broken
'@typescript-eslint/no-unnecessary-type-assertion': 'error',
'@typescript-eslint/no-unsafe-assignment': 'off', // OFF b/c used in Svelte components for UI logic
'@typescript-eslint/no-unsafe-call': 'off', // OFF b/c used in Svelte components for UI logic
Expand All @@ -87,7 +88,6 @@ const typescriptEslintRules = {
'@typescript-eslint/no-unsafe-argument': 'off', // OFF b/c ESlint resolves types of the absolute imports as any
'@typescript-eslint/unused-export-let': 'off', // OFF b/c used in Svelte components for UI logic
'@typescript-eslint/no-unused-vars': ['error', { varsIgnorePattern: '^_', argsIgnorePattern: '^_' }],

'@typescript-eslint/no-var-requires': 'error',
'@typescript-eslint/prefer-regexp-exec': 'error',
'@typescript-eslint/restrict-plus-operands': 'off', // OFF b/c not entirely accurate despite proper typings
Expand Down
12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@
"packages/shared"
],
"devDependencies": {
"@babel/eslint-parser": "7.24.1",
"@babel/eslint-parser": "7.24.6",
"@tsconfig/svelte": "5.0.2",
"@types/node": "18.15.11",
"@typescript-eslint/eslint-plugin": "6.21.0",
"@typescript-eslint/parser": "6.5.0",
"eslint": "8.42.0",
"@typescript-eslint/eslint-plugin": "7.11.0",
"@typescript-eslint/parser": "7.11.0",
"eslint": "9.3.0",
"eslint-plugin-security": "3.0.0",
"eslint-plugin-svelte": "2.38.0",
"eslint-plugin-svelte": "2.39.0",
"globals": "^15.3.0",
"husky": "7.0.4",
"lint-staged": "15.2.2",
"lint-staged": "15.2.5",
"patch-package": "8.0.0",
"prettier": "3.2.5",
"prettier-plugin-svelte": "3.0.3",
Expand Down
4 changes: 2 additions & 2 deletions packages/desktop/components/AccountSwitcher.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
}
let items: IMenuItem[] = []
function setItems(accounts: IAccountState[], selectedIndex) {
items = accounts.map((account) => {
function setItems(accounts: IAccountState[], selectedIndex: number | undefined): void {
items = accounts.map((account): IMenuItem => {
return {
title: account.name,
subtitle: formatCurrency($allAccountFiatBalances[account.index]),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
<script lang="ts">
import { Table } from '@bloomwalletio/ui'
import { localize } from '@core/i18n'
import { IParsedSmartContractData } from '@core/layer-2'
import { IParsedMethod, IParsedSmartContractData } from '@core/layer-2'
import { EvmNetworkId } from '@core/network'
import { EvmTransactionAlert } from '.'
export let parsedSmartContract: IParsedSmartContractData
export let networkId: EvmNetworkId
function getMethodSignature(parsedMethod) {
function getMethodSignature(parsedMethod: IParsedMethod): string {
const parameterSignatures = parsedMethod.inputs.map((input) => `${input.name} ${input.type}`)
return `${parsedMethod.name}(${parameterSignatures.join(', ')})`
}
Expand All @@ -26,7 +26,7 @@
collapsibleTitle={getMethodSignature(parsedSmartContract.parsedMethod)}
items={parsedSmartContract?.parsedMethod.inputs.map((input) => ({
key: input.name,
value: String(input.value) ?? localize('general.unknown'),
value: String(input.value ?? localize('general.unknown')),
}))}
/>
</EvmTransactionAlert>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@
const outputData = buildNftOutputBuilderParams(irc27Metadata, depositAddress)
const client = await getClient()
const preparedOutput = await client.buildNftOutput(outputData)
storageDeposit = Number(preparedOutput.amount) ?? 0
const amount = Number(preparedOutput.amount)
storageDeposit = isNaN(amount) ? 0 : amount
} catch (err) {
handleError(err)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@
const client = await getClient()
const preparedOutput = await client.buildNftOutput(outputData)
storageDeposit = Number(preparedOutput.amount) ?? 0
totalStorageDeposit = storageDeposit * quantity
storageDeposit = Number(preparedOutput.amount)
totalStorageDeposit = (isNaN(storageDeposit) ? 0 : storageDeposit) * quantity
} catch (err) {
handleError(err)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function bindSdkUtilsMethods(): IotaSdk.Utils {
const methods = {}

for (const name of methodNames) {
methods[name] = (...args) => IotaSdk.Utils[name](...args)
methods[name] = (...args): void => IotaSdk.Utils[name](...args)
}

return methods
Expand Down
18 changes: 12 additions & 6 deletions packages/desktop/views/components/Particles.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
export let maxSpeed = 7
let canvas: HTMLCanvasElement
let ctx: CanvasRenderingContext2D
let ctx: CanvasRenderingContext2D | null
let particles: Particle[] = []
let isCanvasReady: boolean = false
function randomInt(min, max) {
function randomInt(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min
}
Expand All @@ -29,8 +29,9 @@
color: string
constructor() {
if (!isCanvasReady) return
if (!isCanvasReady) {
throw new Error('Canvas is not ready!')
}
this.x = randomInt(0, canvas?.width || 0)
this.y = randomInt(0, canvas?.height || 0)
this.size = randomInt(1, maxParticleSize)
Expand All @@ -43,6 +44,9 @@
}
draw(): void {
if (!ctx) {
return
}
ctx.fillStyle = this.color
ctx.beginPath()
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2)
Expand All @@ -59,7 +63,7 @@
}
function animate(): void {
ctx.clearRect(0, 0, canvas?.width, canvas?.height)
ctx?.clearRect(0, 0, canvas?.width, canvas?.height)
for (let i = 0; i < particles.length; i++) {
particles[i].update()
Expand All @@ -83,7 +87,9 @@
onMount(() => {
ctx = canvas.getContext('2d')
if (!ctx) throw new Error('Context not found!')
if (!ctx) {
throw new Error('Context not found!')
}
window.addEventListener('resize', handleResize)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
let rowDivElement: HTMLDivElement
$: rowDivHeight = getRowDivHeight(rowDivElement?.clientHeight)
function getRowDivHeight(clientHeight: number | undefined) {
function getRowDivHeight(clientHeight: number | undefined): number {
if (!clientHeight) {
return rowDivHeight
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
let selectedCreateProfileType: CreateProfileType | undefined = undefined
function onProfileTypeClick(createProfileType: CreateProfileType): void {
if (createProfileType === selectedCreateProfileType) {
onContinueClick()
void onContinueClick()
} else {
selectedCreateProfileType = createProfileType
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
options.find((option) => option.value === $activeProfile?.settings.nfts.downloadPermissions?.toString()) ||
options[0]
$: selected && onNftDownloadPermissionChange(selected)
$: selected && void onNftDownloadPermissionChange(selected)
async function onNftDownloadPermissionChange(option: IOption): Promise<void> {
const nftDownloadPermissions = option.value
updateActiveProfileSettings({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import SettingsSection from '../SettingsSection.svelte'
const options: IOption[] = getMaxMediaSizeOptions()
let selected: IOption = options.find(
let selected: IOption | undefined = options.find(
(option) => option.value === $activeProfile?.settings.nfts.maxMediaSizeInMegaBytes?.toString()
)
Expand All @@ -19,11 +19,11 @@
const maxMediaSizeInMegaBytes = parseInt(option.value)
updateActiveProfileSettings({ nfts: { ...$activeProfile?.settings.nfts, maxMediaSizeInMegaBytes } })
const maxMediaSizeInBytes = maxMediaSizeInMegaBytes && maxMediaSizeInMegaBytes * 1024 * 1024
deleteOrDownloadNfts(maxMediaSizeInBytes)
void deleteOrDownloadNfts(maxMediaSizeInBytes)
}
}
function assignMaxMediaSizeOptionLabel(amount: number): string {
function assignMaxMediaSizeOptionLabel(amount: number | undefined): string {
return amount ? amount + ' MB' : localize('general.none')
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
title: localize('actions.refreshNftMedia.title'),
description: localize('actions.refreshNftMedia.description'),
onConfirm: () => {
refreshNftMedia()
void refreshNftMedia()
closePopup()
},
},
Expand All @@ -29,7 +29,9 @@
await stopDownloadingNftMediaFromQueue()
await Promise.all(
$selectedAccountNfts.map(async (nft) => {
await Platform.deleteFile(nft.downloadMetadata?.filePath)
if (nft.downloadMetadata?.filePath) {
await Platform.deleteFile(nft.downloadMetadata?.filePath)
}
updateNftForAllAccounts({ id: nft.id, isLoaded: false })
})
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
let selected: IOption =
options.find(
(option) =>
option.value === $activeProfile?.settings?.lockScreenTimeoutInMinutes.toString() ??
DEFAULT_PERSISTED_PROFILE_OBJECT.settings.lockScreenTimeoutInMinutes.toString()
option.value ===
($activeProfile?.settings?.lockScreenTimeoutInMinutes.toString() ??
DEFAULT_PERSISTED_PROFILE_OBJECT.settings.lockScreenTimeoutInMinutes.toString())
) ?? options[0]
$: onLockScreenTimeoutChange(selected)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
import SettingsSection from '../SettingsSection.svelte'
const options: IOption[] = getStrongholdPasswordTimeoutOptions()
let selected: IOption = options.find(
let selected: IOption | undefined = options.find(
(option) =>
option.value === $activeProfile?.settings?.strongholdPasswordTimeoutInMinutes.toString() ??
DEFAULT_PERSISTED_PROFILE_OBJECT.settings.strongholdPasswordTimeoutInMinutes.toString()
option.value ===
($activeProfile?.settings?.strongholdPasswordTimeoutInMinutes.toString() ??
DEFAULT_PERSISTED_PROFILE_OBJECT.settings.strongholdPasswordTimeoutInMinutes.toString())
)
$: onStrongholdPasswordTimeoutChange(selected)
function onStrongholdPasswordTimeoutChange(option: IOption): void {
function onStrongholdPasswordTimeoutChange(option: IOption | undefined): void {
if (option) {
const strongholdPasswordTimeoutInMinutes = parseInt(option.value)
updateActiveProfileSettings({ strongholdPasswordTimeoutInMinutes })
Expand Down Expand Up @@ -47,7 +48,7 @@
<SelectInput
label={localize('views.settings.strongholdTimeout.title')}
bind:selected
value={selected.value}
value={selected?.value}
{options}
hideValue
/>
Expand Down
4 changes: 2 additions & 2 deletions packages/shared/src/components/inputs/Selection.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
export let error: string | undefined = undefined
let allChecked = true
function onAllClick() {
function onAllClick(): void {
if (allChecked) {
selectionOptions = selectionOptions.map((option) => ({ ...option, checked: true }))
} else {
selectionOptions = selectionOptions.map((option) => ({ ...option, checked: false || option.required }))
selectionOptions = selectionOptions.map((option) => ({ ...option, checked: option.required }))
}
}
Expand Down
15 changes: 10 additions & 5 deletions packages/shared/src/components/modals/Modal.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@
}
function onClickOutside(): void {
if (disableOnClickOutside) return
if (disableOnClickOutside) {
return
}
close()
}
Expand All @@ -61,14 +64,14 @@
maxHeight = availableSpace - 10
}
function handleResize() {
updateMaxHeight()
function handleResize(): void {
void updateMaxHeight()
}
onMount(() => {
if (autoMaxHeight) {
window.addEventListener('resize', handleResize)
updateMaxHeight()
void updateMaxHeight()
}
})
Expand All @@ -78,7 +81,9 @@
}
})
$: if (show && autoMaxHeight) updateMaxHeight()
$: if (show && autoMaxHeight) {
void updateMaxHeight()
}
</script>

{#if show}
Expand Down
2 changes: 1 addition & 1 deletion packages/shared/src/components/molecules/NftGallery.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
let rowDivElement: HTMLDivElement
$: rowDivHeight = getRowDivHeight(rowDivElement?.clientHeight)
function getRowDivHeight(clientHeight: number | undefined) {
function getRowDivHeight(clientHeight: number | undefined): number {
if (!clientHeight) {
return rowDivHeight
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ export function checkNodeUrlValidity(
newUrl = newUrl.slice(0, -4)
}

/* eslint-disable @typescript-eslint/prefer-regexp-exec */
if (nodesList && nodesList.some(({ url }) => (url.endsWith(':443') ? url.slice(0, -4) : url).match(newUrl))) {
return 'error.node.duplicate'
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ function removeTrailingZero(amount: string): string {
}

function getGroupedStringAmount(value: string): string {
// eslint-disable-next-line security/detect-unsafe-regex
return value.replace(/\B(?=(\d{3})+(?!\d))/g, getGroupSeparator())
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ export function validateBech32Address(prefix: string, addr: string, addressType?
})
)
}
// eslint-disable-next-line security/detect-non-literal-regexp
if (!new RegExp(`^${prefix}1[02-9ac-hj-np-z]{59}$`).test(addr)) {
throw new Error(localize('error.send.wrongAddressFormat'))
}

const addressTypeLetter = addressType === undefined ? undefined : ADDRESS_TYPE_MAP[addressType]
// eslint-disable-next-line security/detect-non-literal-regexp
if (addressTypeLetter && !new RegExp(`^${prefix}1${addressTypeLetter}[02-9ac-hj-np-z]{58}$`).test(addr)) {
throw new Error(localize('error.address.wrongAddressType'))
}
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/lib/core/utils/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export function getInitials(name: string | undefined, maxChars?: number): string
}

// Extract initial characters of each word, considering emojis and ignoring other symbols
// eslint-disable-next-line security/detect-unsafe-regex
const regexEmoji = /\p{Emoji}\uFE0F?(?:\u200D\p{Emoji}\uFE0F?)*/gu
const regexLetterOrNumber = /[\p{L}\p{N}]/gu
const initialsArray = name
Expand Down
1 change: 1 addition & 0 deletions packages/shared/src/lib/core/utils/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { isHttpsUri, isUri, isWebUri } from 'valid-url'
import { PIN_LENGTH } from './constants'

export function isValidPin(pin: string): boolean {
// eslint-disable-next-line security/detect-non-literal-regexp
const REGEX = new RegExp(`^\\d{${PIN_LENGTH}}$`)
return REGEX.test(pin)
}
Expand Down
1 change: 0 additions & 1 deletion packages/shared/src/lib/features/features.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable no-undef */
import { IFeatures } from './interfaces'

// @ts-expect-error: This value is replaced by Webpack DefinePlugin
Expand Down
Loading

0 comments on commit 60e30ef

Please sign in to comment.