Skip to content

Commit

Permalink
style: enable all biomejs recommended rules (#7153)
Browse files Browse the repository at this point in the history
* Enable recomended correctness/noVoidTypeReturn

* Enable recomended rule correctness/useYield

* Enable recomended rule performance/noAccumulatingSpread

* Enable recomended rule performance/noDelete

* Enable recomended rule suspicious/noAsyncPromiseExecutor

* Enable recommended rule suspicious/noDoubleEquals

* Enable recommended rule suspicious/noDuplicateTestHooks

* Enable recommended rule suspicious/noExportsInTest

* Enable recommended rule suspicious/noFallthroughSwitchClause

* Enable recommended rule suspicious/noGlobalIsFinite

* Enable recommended rule suspicious/noGlobalIsNan

* Enable recommended rule suspicious/noPrototypeBuiltins

* Enable recommended rule suspicious/noShadowRestrictedNames

* Enable recommended rule suspicious/useDefaultSwitchClauseLast

* Enable recommended rule suspicious/useGetterReturn

* Enable recommended rule style/noUnusedTemplateLiteral

* Convert default case to unreachable code

* Enable recommended rule complexity/noForEach

* Enable recommended rule complexity/noThisInStatic

* Enable recommended rule complexity/useFlatMap

* Enable recommended rule complexity/useOptionalChain

* Enable recommended rule complexity/useRegexLiterals

* Reorganize the config structure

* Fix few typos

* Revert "Enable recomended rule performance/noDelete"

This reverts commit 6cc060b.

* Fix formatting

* Enable recommended rule style/noUselessElse

* Enable recommended rule complexity/useLiteralKeys

* Enable recommended rule complexity/useArrowFunction

* Fix few types

* Fix a test file

* Fix formatting

* Enable recommended rule suspicious/noImplicitAnyLet

* Enable recommended rule complexity/noUselessEmptyExport

* Fix types

* Fix unti tests

* Fix unit test

* Fix lint error

* Fix a unit test pattern

* Fix formatting
  • Loading branch information
nazarhussain authored and philknows committed Oct 18, 2024
1 parent 5e020e7 commit b8eeec6
Show file tree
Hide file tree
Showing 392 changed files with 1,852 additions and 1,919 deletions.
88 changes: 33 additions & 55 deletions biome.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -24,27 +24,8 @@
"enabled": true,
"rules": {
"recommended": true,
"complexity": {
"noForEach": "off",
"noStaticOnlyClass": "off",
"noThisInStatic": "off",
"noUselessEmptyExport": "off",
"noUselessTypeConstraint": "error",
"useArrowFunction": "off",
"useFlatMap": "off",
"useLiteralKeys": "off",
"useOptionalChain": "off",
"useRegexLiterals": "off",
"noBannedTypes": "error",
"noUselessThisAlias": "error"
},
"correctness": {
"noInvalidConstructorSuper": "off",
"noInvalidUseBeforeDeclaration": "off",
"noPrecisionLoss": "error",
"noUnusedVariables": "error",
"noVoidTypeReturn": "off",
"useYield": "off",
"useImportExtensions": {
"level": "error",
"options": {
Expand All @@ -57,33 +38,41 @@
}
},
"useArrayLiterals": "error",
"noUndeclaredDependencies": "off", // TODO: Need to see why this rule is not detecting monorepo packages
"noUndeclaredVariables": "error"
},
"performance": {
"noAccumulatingSpread": "off",
// This rule should be enabled but with considerations and careful review
"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",
"noUselessElse": "off",
"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",
// We use to import types and object without differentiating
"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 +183,14 @@
]
}
},
"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",
"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 +338,16 @@
{
"include": ["**/test/**/*.test.ts"],
"linter": {
"rules": {}
"rules": {
"complexity": {
// During tests we often need to use private/protected attributes, which is only possible with literal keys
"useLiteralKeys": "off"
},
"suspicious": {
// During tests it's quicker to define variables with `let` without specifying types
"noImplicitAnyLet": "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
3 changes: 1 addition & 2 deletions packages/api/src/utils/client/eventSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
export async function getEventSource(): Promise<typeof EventSource> {
if (globalThis.EventSource) {
return EventSource;
} else {
return (await import("eventsource")).default as unknown as typeof EventSource;
}
return (await import("eventsource")).default as unknown as typeof EventSource;
}
36 changes: 17 additions & 19 deletions packages/api/src/utils/client/httpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,12 +155,10 @@ export class HttpClient implements IHttpClient {

if (init.retries > 0) {
return this.requestWithRetries(definition, args, init);
} else {
return this.getRequestMethod(init)(definition, args, init);
}
} else {
return this.requestWithFallbacks(definition, args, localInit);
return this.getRequestMethod(init)(definition, args, init);
}
return this.requestWithFallbacks(definition, args, localInit);
}

/**
Expand Down Expand Up @@ -252,19 +250,16 @@ export class HttpClient implements IHttpClient {
});
if (res.ok) {
return res;
} else {
if (i >= this.urlsInits.length - 1) {
return res;
} else {
this.logger?.debug("Request error, retrying", {}, res.error() as Error);
}
}
if (i >= this.urlsInits.length - 1) {
return res;
}
this.logger?.debug("Request error, retrying", {}, res.error() as Error);
} catch (e) {
if (i >= this.urlsInits.length - 1) {
throw e;
} else {
this.logger?.debug("Request error, retrying", {}, e as Error);
}
this.logger?.debug("Request error, retrying", {}, e as Error);
}
}

Expand Down Expand Up @@ -352,7 +347,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 @@ -389,19 +386,20 @@ export class HttpClient implements IHttpClient {
if (isAbortedError(e)) {
if (abortSignals.some((s) => s?.aborted)) {
throw new ErrorAborted(`${routeId} request`);
} else if (controller.signal.aborted) {
}
if (controller.signal.aborted) {
throw new TimeoutError(`${routeId} request`);
} else {
throw Error("Unknown aborted error");
}
} else {
throw e;
throw Error("Unknown aborted error");
}
throw e;
} finally {
timer?.();

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

Expand Down
6 changes: 2 additions & 4 deletions packages/api/src/utils/client/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,8 @@ export class ApiResponse<E extends Endpoint> extends Response {
if (this.status === HttpStatusCode.NO_CONTENT) {
this._wireFormat = null;
return this._wireFormat;
} else {
throw Error("Content-Type header is required in response");
}
throw Error("Content-Type header is required in response");
}

const mediaType = parseContentTypeHeader(contentType);
Expand Down Expand Up @@ -197,9 +196,8 @@ export class ApiResponse<E extends Endpoint> extends Response {
return `${errJson.message}\n` + errJson.failures.map((e) => e.message).join("\n");
}
return errJson.message;
} else {
return errBody;
}
return errBody;
} catch (_e) {
return errBody || this.statusText;
}
Expand Down
6 changes: 3 additions & 3 deletions packages/api/src/utils/codecs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,11 @@ export const EmptyResponseCodec: ResponseCodec<EmptyResponseEndpoint> = {
export function ArrayOf<T>(elementType: Type<T>, limit = Infinity): ArrayType<Type<T>, unknown, unknown> {
if (isCompositeType(elementType)) {
return new ListCompositeType(elementType, limit) as unknown as ArrayType<Type<T>, unknown, unknown>;
} else if (isBasicType(elementType)) {
}
if (isBasicType(elementType)) {
return new ListBasicType(elementType, limit) as unknown as ArrayType<Type<T>, unknown, unknown>;
} else {
throw Error(`Unknown type ${elementType.typeName}`);
}
throw Error(`Unknown type ${elementType.typeName}`);
}

export function WithMeta<T, M extends {version: ForkName}>(getType: (m: M) => Type<T>): ResponseDataCodec<T, M> {
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
5 changes: 2 additions & 3 deletions packages/api/src/utils/serdes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ export function querySerializeProofPathsArr(paths: JsonPath[]): string[] {
export function queryParseProofPathsArr(pathStrs: string | string[]): JsonPath[] {
if (Array.isArray(pathStrs)) {
return pathStrs.map((pathStr) => queryParseProofPaths(pathStr));
} else {
return [queryParseProofPaths(pathStrs)];
}
return [queryParseProofPaths(pathStrs)];
}

/**
Expand Down Expand Up @@ -50,7 +49,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
6 changes: 3 additions & 3 deletions packages/api/test/unit/client/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import http from "node:http";
import {describe, it, expect, afterEach} from "vitest";
import {FetchError, FetchErrorType, fetch} from "../../../src/utils/client/fetch.js";

describe("FetchError", function () {
describe("FetchError", () => {
const port = 37421;
const randomHex = crypto.randomBytes(32).toString("hex");

Expand Down Expand Up @@ -87,7 +87,7 @@ describe("FetchError", function () {

const afterHooks: (() => Promise<void>)[] = [];

afterEach(async function () {
afterEach(async () => {
while (afterHooks.length) {
const afterHook = afterHooks.pop();
if (afterHook)
Expand All @@ -100,7 +100,7 @@ describe("FetchError", function () {
for (const testCase of testCases) {
const {id, url = `http://localhost:${port}`, requestListener, signalHandler} = testCase;

it(id, async function () {
it(id, async () => {
if (requestListener) {
const server = http.createServer(requestListener);
await new Promise<void>((resolve) => server.listen(port, resolve));
Expand Down
8 changes: 4 additions & 4 deletions packages/api/test/unit/client/httpClientFallback.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,12 @@ describe("httpClient fallback", () => {
// which is handled separately from network errors
// but the fallback logic should be the same
return new Response(null, {status: 500});
} else {
throw Error(`test_error_server_${i}`);
}
} else {
return new Response(null, {status: 200});

throw Error(`test_error_server_${i}`);
}

return new Response(null, {status: 200});
});
});

Expand Down
10 changes: 6 additions & 4 deletions packages/api/test/utils/checkAgainstSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,13 @@ export function runTestCheckAgainstSpec<Es extends Record<string, Endpoint>>(
}
});

it(`${operationId}_route`, function () {
it(`${operationId}_route`, () => {
expect(routeDef.method.toLowerCase()).toBe(routeSpec.method.toLowerCase());
expect(routeDef.url).toBe(routeSpec.url);
});

if (requestSchema != null) {
it(`${operationId}_request`, function () {
it(`${operationId}_request`, () => {
const reqJson = isRequestWithoutBody(routeDef)
? routeDef.req.writeReq(testData.args)
: (routeDef.req as RequestWithBodyCodec<Es[string]>).writeReqJson(testData.args);
Expand Down Expand Up @@ -135,7 +135,7 @@ export function runTestCheckAgainstSpec<Es extends Record<string, Endpoint>>(
}

if (responseOkSchema) {
it(`${operationId}_response`, function () {
it(`${operationId}_response`, () => {
const data = routeDef.resp.data.toJson(testData.res?.data, testData.res?.meta);
const metaJson = routeDef.resp.meta.toJson(testData.res?.meta);
const headers = parseHeaders(routeDef.resp.meta.toHeadersObject(testData.res?.meta));
Expand Down Expand Up @@ -218,7 +218,9 @@ type StringifiedProperty = string | StringifiedProperty[];
function stringifyProperty(value: unknown): StringifiedProperty {
if (typeof value === "number") {
return value.toString(10);
} else if (Array.isArray(value)) {
}

if (Array.isArray(value)) {
return value.map(stringifyProperty);
}
return String(value);
Expand Down
2 changes: 1 addition & 1 deletion packages/api/test/utils/parseOpenApiSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ function preprocessSchema(schema: JsonSchema): void {

// 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
Loading

0 comments on commit b8eeec6

Please sign in to comment.