Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

style: enable all biomejs recommended rules #7153

Merged
merged 41 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
bc6ea37
Enable recomended correctness/noVoidTypeReturn
nazarhussain Oct 11, 2024
ab71719
Enable recomended rule correctness/useYield
nazarhussain Oct 11, 2024
91f6054
Enable recomended rule performance/noAccumulatingSpread
nazarhussain Oct 11, 2024
6cc060b
Enable recomended rule performance/noDelete
nazarhussain Oct 11, 2024
07f7cd4
Enable recomended rule suspicious/noAsyncPromiseExecutor
nazarhussain Oct 11, 2024
edd44b1
Enable recommended rule suspicious/noDoubleEquals
nazarhussain Oct 11, 2024
3cf245a
Enable recommended rule suspicious/noDuplicateTestHooks
nazarhussain Oct 11, 2024
3d67f6a
Enable recommended rule suspicious/noExportsInTest
nazarhussain Oct 11, 2024
24ebdc0
Enable recommended rule suspicious/noFallthroughSwitchClause
nazarhussain Oct 11, 2024
f2756df
Enable recommended rule suspicious/noGlobalIsFinite
nazarhussain Oct 11, 2024
d6b4206
Enable recommended rule suspicious/noGlobalIsNan
nazarhussain Oct 11, 2024
019c3de
Enable recommended rule suspicious/noPrototypeBuiltins
nazarhussain Oct 11, 2024
2630c5e
Enable recommended rule suspicious/noShadowRestrictedNames
nazarhussain Oct 11, 2024
04a1138
Enable recommended rule suspicious/useDefaultSwitchClauseLast
nazarhussain Oct 11, 2024
65a9d2a
Enable recommended rule suspicious/useGetterReturn
nazarhussain Oct 11, 2024
224a439
Enable recommended rule style/noUnusedTemplateLiteral
nazarhussain Oct 11, 2024
2a5b647
Convert default case to unreachable code
nazarhussain Oct 11, 2024
51c6048
Enable recommended rule complexity/noForEach
nazarhussain Oct 11, 2024
9f526e7
Enable recommended rule complexity/noThisInStatic
nazarhussain Oct 11, 2024
630ce11
Enable recommended rule complexity/useFlatMap
nazarhussain Oct 11, 2024
a0045ea
Enable recommended rule complexity/useOptionalChain
nazarhussain Oct 11, 2024
7a7b367
Enable recommended rule complexity/useRegexLiterals
nazarhussain Oct 11, 2024
7e3d613
Reorganize the config structure
nazarhussain Oct 11, 2024
d96b4d6
Fix few typos
nazarhussain Oct 14, 2024
69b7fa6
Merge branch 'unstable' into nh/biome-rules
nazarhussain Oct 14, 2024
4578725
Revert "Enable recomended rule performance/noDelete"
nazarhussain Oct 14, 2024
a04912c
Fix formatting
nazarhussain Oct 14, 2024
655a4d1
Enable recommended rule style/noUselessElse
nazarhussain Oct 14, 2024
ff5bb90
Enable recommended rule complexity/useLiteralKeys
nazarhussain Oct 14, 2024
dff8184
Enable recommended rule complexity/useArrowFunction
nazarhussain Oct 14, 2024
2309803
Fix few types
nazarhussain Oct 14, 2024
d67458d
Fix a test file
nazarhussain Oct 14, 2024
7cfc88e
Fix formatting
nazarhussain Oct 14, 2024
6472918
Enable recommended rule suspicious/noImplicitAnyLet
nazarhussain Oct 14, 2024
b3243c1
Enable recommended rule complexity/noUselessEmptyExport
nazarhussain Oct 14, 2024
38e0c50
Fix types
nazarhussain Oct 14, 2024
a6531c7
Fix unti tests
nazarhussain Oct 14, 2024
b103cf5
Fix unit test
nazarhussain Oct 14, 2024
384b5cb
Fix lint error
nazarhussain Oct 14, 2024
d449d16
Fix a unit test pattern
nazarhussain Oct 14, 2024
4f31ed9
Fix formatting
nazarhussain Oct 14, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 33 additions & 52 deletions biome.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -25,26 +25,15 @@
"rules": {
"recommended": true,
"complexity": {
"noForEach": "off",
"noStaticOnlyClass": "off",
"noThisInStatic": "off",
// We need couple of empty exports to make those files as esm modules
wemeetagain marked this conversation as resolved.
Show resolved Hide resolved
"noUselessEmptyExport": "off",
"noUselessTypeConstraint": "error",
// We use normal functions for to ease with debugging context
wemeetagain marked this conversation as resolved.
Show resolved Hide resolved
"useArrowFunction": "off",
"useFlatMap": "off",
"useLiteralKeys": "off",
"useOptionalChain": "off",
"useRegexLiterals": "off",
"noBannedTypes": "error",
"noUselessThisAlias": "error"
// This pattern is used a lot earlier in code so disabling this rule
wemeetagain marked this conversation as resolved.
Show resolved Hide resolved
"useLiteralKeys": "off"
},
"correctness": {
"noInvalidConstructorSuper": "off",
"noInvalidUseBeforeDeclaration": "off",
"noPrecisionLoss": "error",
"noUnusedVariables": "error",
"noVoidTypeReturn": "off",
"useYield": "off",
"useImportExtensions": {
"level": "error",
"options": {
Expand All @@ -57,33 +46,39 @@
}
},
"useArrayLiterals": "error",
"noUndeclaredDependencies": "off", // TODO: Need to see why this rule is not detecting monorepo packages
"noUndeclaredVariables": "error"
},
"performance": {
"noAccumulatingSpread": "off",
"noDelete": "off"
},
"style": {
// The code usage looks suspicious so it should be enabled in a separate PR
"noCommaOperator": "off",
"noInferrableTypes": "off",
"noNonNullAssertion": "error",
// There are a lot of places we mutate params, should be fixed in an independent PR.
"noParameterAssign": "off",
"noRestrictedGlobals": {
"level": "error",
"options": {
"deniedGlobals": ["fetch"]
}
},
"noUnusedTemplateLiteral": "off",
// There are a lot of places we mutate params, should be fixed in an independent PR.
nazarhussain marked this conversation as resolved.
Show resolved Hide resolved
"noUselessElse": "off",
wemeetagain marked this conversation as resolved.
Show resolved Hide resolved
"noVar": "error",
"useConst": "error",
"useEnumInitializers": "off",
// We prefer to use `Math.pow` over `**` operator
"useExponentiationOperator": "off",
// In some cases the enums are initialized with values of other enums
"useLiteralEnumMembers": "off",
// We prefer to have multiple declarations lines
"useSingleVarDeclarator": "off",
// We use `+` operator for string concatenation a lot
"useTemplate": "off",
// We use to export types and object without differentiating
"useExportType": "off",
wemeetagain marked this conversation as resolved.
Show resolved Hide resolved
// We use to export types and object without differentiating
nazarhussain marked this conversation as resolved.
Show resolved Hide resolved
"useImportType": "off",
"useLiteralEnumMembers": "off",
// It's nice to use `Number` namespace but should be done in a separate PR
"useNumberNamespace": "off",
// We prefer to auto-initialize enums
"useEnumInitializers": "off",
"noVar": "error",
"useConst": "error",
"useNamingConvention": {
"level": "error",
"options": {
Expand Down Expand Up @@ -194,34 +189,16 @@
]
}
},
"useNumberNamespace": "off",
"useSingleVarDeclarator": "off",
"useTemplate": "off",
"noNamespace": "error",
"useAsConstAssertion": "error"
"noNamespace": "error"
},
"suspicious": {
"noAssignInExpressions": "error",
"noAsyncPromiseExecutor": "off",
// `void` as type is useful in our case when used as generic constraint e.g. K extends number | void
"noConfusingVoidType": "off",
"noConsoleLog": "error",
"noDoubleEquals": "off",
"noDuplicateTestHooks": "off",
"noExplicitAny": "error",
"noExportsInTest": "off",
"noFallthroughSwitchClause": "off",
"noGlobalIsFinite": "off",
"noGlobalIsNan": "off",
// There are lot of cases in our code that need a separate PR to enable this rule
wemeetagain marked this conversation as resolved.
Show resolved Hide resolved
"noImplicitAnyLet": "off",
"noPrototypeBuiltins": "off",
"noRedundantUseStrict": "off",
"noShadowRestrictedNames": "off",
"useDefaultSwitchClauseLast": "off",
"useGetterReturn": "off",
"noExtraNonNullAssertion": "error",
"noMisleadingInstantiator": "error",
"noUnsafeDeclarationMerging": "error",
"noEmptyBlockStatements": "off" // There is a lot of empty code blocks, should be enabled and clean up separately.
// There is a lot of empty code blocks, should be enabled and clean up separately.
"noEmptyBlockStatements": "off",
"noConsoleLog": "error"
},
"nursery": {
"useConsistentMemberAccessibility": {
Expand Down Expand Up @@ -369,7 +346,11 @@
{
"include": ["**/test/**/*.test.ts"],
"linter": {
"rules": {}
"rules": {
"complexity": {
"useArrowFunction": "off"
}
}
}
}
]
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/beacon/server/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ export function getRoutes(config: ChainForkConfig, methods: ApplicationMethods<E
try {
// Add injected headers from other plugins. This is required for fastify-cors for example
// From: https://github.com/NodeFactoryIo/fastify-sse-v2/blob/b1686a979fbf655fb9936c0560294a0c094734d4/src/plugin.ts
Object.entries(res.getHeaders()).forEach(([key, value]) => {
for (const [key, value] of Object.entries(res.getHeaders())) {
if (value !== undefined) res.raw.setHeader(key, value);
});
}

res.raw.setHeader("Content-Type", "text/event-stream");
res.raw.setHeader("Cache-Control", "no-cache,no-transform");
Expand Down
8 changes: 6 additions & 2 deletions packages/api/src/utils/client/httpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,9 @@ export class HttpClient implements IHttpClient {

// Attach global/local signal to this request's controller
const onSignalAbort = (): void => controller.abort();
abortSignals.forEach((s) => s?.addEventListener("abort", onSignalAbort));
for (const s of abortSignals) {
s?.addEventListener("abort", onSignalAbort);
}

const routeId = definition.operationId;
const {printableUrl, requestWireFormat, responseWireFormat} = init;
Expand Down Expand Up @@ -401,7 +403,9 @@ export class HttpClient implements IHttpClient {
timer?.();

clearTimeout(timeout);
abortSignals.forEach((s) => s?.removeEventListener("abort", onSignalAbort));
for (const s of abortSignals) {
s?.removeEventListener("abort", onSignalAbort);
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/utils/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export function parseAcceptHeader(accept?: string, supported = SUPPORTED_MEDIA_T
}

const qvalue = +weight.replace("q=", "");
if (isNaN(qvalue) || qvalue > 1 || qvalue <= 0) {
if (Number.isNaN(qvalue) || qvalue > 1 || qvalue <= 0) {
// If we can't convert the qvalue to a valid number, move on
return best;
}
Expand Down
2 changes: 0 additions & 2 deletions packages/api/src/utils/httpStatusCode.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
"use strict";

/**
* Hypertext Transfer Protocol (HTTP) response status codes.
* @see {@link https://www.rfc-editor.org/rfc/rfc7231#section-6}
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/utils/serdes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export type U64Str = string;

export function fromU64Str(u64Str: U64Str): number {
const u64 = parseInt(u64Str, 10);
if (!isFinite(u64)) {
if (!Number.isFinite(u64)) {
throw Error(`Invalid uin64 ${u64Str}`);
}
return u64;
Expand Down
2 changes: 1 addition & 1 deletion packages/api/test/utils/checkAgainstSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ function validateSchema(schema: Parameters<typeof ajv.compile>[0], json: unknown
if (!valid) {
// Remove descriptions, for better clarity in rendering on errors
applyRecursively(schema, (obj) => {
delete obj.description;
obj.description = undefined;
});

throw Error(
Expand Down
6 changes: 3 additions & 3 deletions packages/api/test/utils/parseOpenApiSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,19 +139,19 @@ function preprocessSchema(schema: JsonSchema): void {

// Remove nullable
applyRecursively(schema, (obj) => {
delete obj.nullable;
obj.nullable = undefined;
});

// Remove required: false
applyRecursively(schema, (obj) => {
if (typeof obj.required === "boolean") {
delete obj.required;
obj.required = undefined;
}
});

// Remove non-intersecting allOf enum
applyRecursively(schema, (obj) => {
if (obj.allOf && obj.allOf.every((s) => s.enum)) {
if (obj.allOf?.every((s) => s.enum)) {
obj.allOf = [obj.allOf[0]];
}
});
Expand Down
2 changes: 1 addition & 1 deletion packages/api/test/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function getTestServer(): {server: FastifyInstance; start: () => Promise<
const start = (): Promise<string> =>
new Promise<string>((resolve, reject) => {
server.listen({port: 0}, function (err, address) {
if (err !== null && err != undefined) {
if (err !== null && err !== undefined) {
nazarhussain marked this conversation as resolved.
Show resolved Hide resolved
reject(err);
} else {
resolve(address);
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/api/impl/beacon/blocks/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export function resolveBlockId(forkChoice: IForkChoice, blockId: routes.beacon.B

// block id must be slot
const blockSlot = parseInt(blockId, 10);
if (isNaN(blockSlot) && isNaN(blockSlot - 0)) {
if (Number.isNaN(blockSlot) && Number.isNaN(blockSlot - 0)) {
throw new ValidationError(`Invalid block id '${blockId}'`, "blockId");
}
return blockSlot;
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/api/impl/beacon/state/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export function resolveStateId(

// id must be slot
const blockSlot = parseInt(String(stateId), 10);
if (isNaN(blockSlot) && isNaN(blockSlot - 0)) {
if (Number.isNaN(blockSlot) && Number.isNaN(blockSlot - 0)) {
throw new ValidationError(`Invalid block id '${stateId}'`, "blockId");
}

Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/chain/balancesCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export class CheckpointBalancesCache {
const epochBoundaryRoot =
epochBoundarySlot === state.slot ? blockRootHex : toRootHex(getBlockRootAtSlot(state, epochBoundarySlot));

const index = this.items.findIndex((item) => item.epoch === epoch && item.rootHex == epochBoundaryRoot);
const index = this.items.findIndex((item) => item.epoch === epoch && item.rootHex === epochBoundaryRoot);
if (index === -1) {
if (this.items.length === MAX_BALANCE_CACHE_SIZE) {
this.items.shift();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ async function maybeValidateBlobs(
case BlockInputType.outOfRangeData:
return {dataAvailabilityStatus: DataAvailabilityStatus.OutOfRange, availableBlockInput: blockInput};

// biome-ignore lint/suspicious/noFallthroughSwitchClause: We need fall-through behavior here
case BlockInputType.availableData:
if (opts.validBlobSidecars === BlobSidecarValidation.Full) {
return {dataAvailabilityStatus: DataAvailabilityStatus.Available, availableBlockInput: blockInput};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export async function writeBlockInputToDb(this: BeaconChain, blocksInput: BlockI

if (blockInput.type === BlockInputType.availableData || blockInput.type === BlockInputType.dataPromise) {
const blobSidecars =
blockInput.type == BlockInputType.availableData
blockInput.type === BlockInputType.availableData
? blockInput.blockData.blobs
: // At this point of import blobs are available and can be safely awaited
(await blockInput.cachedData.availabilityPromise).blobs;
Expand Down
3 changes: 2 additions & 1 deletion packages/beacon-node/src/chain/bls/multithread/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,8 @@ export class BlsMultiThreadWorkerPool implements IBlsVerifier {
this.workers[0].status.code === WorkerStatusCode.initializationError &&
this.workers.every((worker) => worker.status.code === WorkerStatusCode.initializationError)
) {
return job.reject(this.workers[0].status.error);
job.reject(this.workers[0].status.error);
return;
}

// Append batchable sets to `bufferedJobs`, starting a timeout to push them into `jobs`.
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/chain/lightClient/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,7 @@ export class LightClientServer {
if (
attestedData.isFinalized &&
finalizedHeaderAttested &&
computeSyncPeriodAtSlot(finalizedHeaderAttested.beacon.slot) == syncPeriod
computeSyncPeriodAtSlot(finalizedHeaderAttested.beacon.slot) === syncPeriod
) {
isFinalized = true;
finalityBranch = attestedData.finalityBranch;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const CHECKPOINT_FILE_NAME_LENGTH = 82;
export class FileCPStateDatastore implements CPStateDatastore {
private readonly folderPath: string;

constructor(parentDir: string = ".") {
constructor(parentDir = ".") {
// by default use the beacon folder `/beacon/checkpoint_states`
this.folderPath = path.join(parentDir, CHECKPOINT_STATES_FOLDER);
}
Expand Down
4 changes: 2 additions & 2 deletions packages/beacon-node/src/db/buckets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ export enum Bucket {

export function getBucketNameByValue<T extends Bucket>(enumValue: T): keyof typeof Bucket {
const keys = Object.keys(Bucket).filter((x) => {
if (isNaN(parseInt(x))) {
return Bucket[x as keyof typeof Bucket] == enumValue;
if (Number.isNaN(parseInt(x))) {
return Bucket[x as keyof typeof Bucket] === enumValue;
} else {
return false;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/db/repositories/blockArchive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export class BlockArchiveRepository extends Repository<Slot, SignedBeaconBlock>
async *valuesStream(opts?: BlockFilterOptions): AsyncIterable<SignedBeaconBlock> {
const firstSlot = this.getFirstSlot(opts);
const valuesStream = super.valuesStream(opts);
const step = (opts && opts.step) ?? 1;
const step = opts?.step ?? 1;

for await (const value of valuesStream) {
if ((value.message.slot - firstSlot) % step === 0) {
Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/eth1/eth1DataCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ export class Eth1DataCache {

async getHighestCachedBlockNumber(): Promise<number | null> {
const highestEth1Data = await this.db.eth1Data.lastValue();
return highestEth1Data && highestEth1Data.blockNumber;
return highestEth1Data?.blockNumber || null;
nazarhussain marked this conversation as resolved.
Show resolved Hide resolved
}
}
4 changes: 2 additions & 2 deletions packages/beacon-node/src/eth1/eth1DepositsCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,14 @@ export class Eth1DepositsCache {
*/
async getHighestDepositEventBlockNumber(): Promise<number | null> {
const latestEvent = await this.db.depositEvent.lastValue();
return latestEvent && latestEvent.blockNumber;
return latestEvent?.blockNumber || null;
}

/**
* Returns the lowest blockNumber stored in DB if any
*/
async getLowestDepositEventBlockNumber(): Promise<number | null> {
const firstEvent = await this.db.depositEvent.firstValue();
return firstEvent && firstEvent.blockNumber;
return firstEvent?.blockNumber || null;
}
}
2 changes: 1 addition & 1 deletion packages/beacon-node/src/eth1/eth1MergeBlockTracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ export class Eth1MergeBlockTracker {
// Persist found merge block here to affect both caller paths:
// - internal searcher
// - external caller if STOPPED
if (mergeBlock && this.status.code != StatusCode.FOUND) {
if (mergeBlock && this.status.code !== StatusCode.FOUND) {
if (this.status.code === StatusCode.SEARCHING) {
this.close();
}
Expand Down
4 changes: 2 additions & 2 deletions packages/beacon-node/src/eth1/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,11 @@ export class Eth1ForBlockProduction implements IEth1ForBlockProduction {
}

startPollingMergeBlock(): void {
return this.eth1MergeBlockTracker.startPollingMergeBlock();
this.eth1MergeBlockTracker.startPollingMergeBlock();
}

stopPollingEth1Data(): void {
return this.eth1DepositDataTracker?.stopPollingEth1Data();
this.eth1DepositDataTracker?.stopPollingEth1Data();
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/eth1/provider/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export function numToQuantity(num: number | bigint): QUANTITY {
*/
export function quantityToNum(hex: QUANTITY, id = ""): number {
const num = parseInt(hex, 16);
if (isNaN(num) || num < 0) throw Error(`Invalid hex decimal ${id} '${hex}'`);
if (Number.isNaN(num) || num < 0) throw Error(`Invalid hex decimal ${id} '${hex}'`);
return num;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/beacon-node/src/network/gossip/gossipsub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ export class Eth2Gossipsub extends GossipSub {
// TODO: figure out a way to dynamically transition to the size
dataTransform: new DataTransformSnappy(
gossipTopicCache,
isFinite(config.BELLATRIX_FORK_EPOCH) ? GOSSIP_MAX_SIZE_BELLATRIX : GOSSIP_MAX_SIZE
Number.isFinite(config.BELLATRIX_FORK_EPOCH) ? GOSSIP_MAX_SIZE_BELLATRIX : GOSSIP_MAX_SIZE
),
metricsRegister: metricsRegister as MetricsRegister | null,
metricsTopicStrToLabel: metricsRegister
Expand Down
Loading
Loading