Skip to content

Commit

Permalink
refactor: add eslint-plugin-unicorn
Browse files Browse the repository at this point in the history
  • Loading branch information
danielpza committed Aug 19, 2024
1 parent 1cddaac commit 44ad2e0
Show file tree
Hide file tree
Showing 21 changed files with 582 additions and 62 deletions.
17 changes: 17 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
// @ts-check
import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
import eslintPluginUnicorn from "eslint-plugin-unicorn";

export default [
{ files: ["**/*.{js,mjs,cjs,ts}"] },
{ ignores: ["**/dist/", "test/projects/"] },
{ languageOptions: { globals: globals.node } },
pluginJs.configs.recommended,
...tseslint.configs.recommended,
eslintPluginUnicorn.configs["flat/recommended"],
{
rules: {
"@typescript-eslint/no-empty-object-type": ["error", { allowInterfaces: "with-single-extends" }],
Expand All @@ -25,7 +28,21 @@ export default [
},
{
rules: {
// fix these warnings
"@typescript-eslint/no-explicit-any": "warn",
"unicorn/consistent-function-scoping": "warn",
"unicorn/explicit-length-check": "warn",
"unicorn/import-style": "warn",
"unicorn/no-array-reduce": "warn",
"unicorn/no-nested-ternary": "warn",
"unicorn/prefer-regexp-test": "warn",
"unicorn/prefer-string-slice": "warn",
// disable strict rules/not applicable
"unicorn/empty-brace-spaces": "off", // conflict with prettier
"unicorn/no-array-callback-reference": "off",
"unicorn/prefer-module": "off",
"unicorn/prefer-ternary": "off",
"unicorn/prevent-abbreviations": "off",
},
},
];
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
"@types/typescript-4.7": "npm:[email protected]",
"changelogen": "^0.5.5",
"eslint": "9.x",
"eslint-plugin-unicorn": "^55.0.0",
"globals": "^15.9.0",
"prettier": "^3.3.3",
"prettier-plugin-jsdoc": "^1.3.0",
Expand Down
12 changes: 8 additions & 4 deletions src/harmony/versions/four-seven.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export function handler(context: TsTransformPathsContext, prop: string | symbol)
const factory = context.tsFactory as unknown as TsFourSevenModule.NodeFactory;

switch (prop) {
case "updateImportDeclaration":
case "updateImportDeclaration": {
return function (
node: ImportDeclaration,
_modifiers: readonly Modifier[] | undefined,
Expand All @@ -70,7 +70,8 @@ export function handler(context: TsTransformPathsContext, prop: string | symbol)
dsAssertClause,
);
};
case "updateExportDeclaration":
}
case "updateExportDeclaration": {
return function (
node: ExportDeclaration,
_modifiers: readonly Modifier[] | undefined,
Expand All @@ -96,7 +97,8 @@ export function handler(context: TsTransformPathsContext, prop: string | symbol)
dsAssertClause,
);
};
case "updateModuleDeclaration":
}
case "updateModuleDeclaration": {
return function (
node: ModuleDeclaration,
_modifiers: readonly Modifier[] | undefined,
Expand All @@ -107,8 +109,10 @@ export function handler(context: TsTransformPathsContext, prop: string | symbol)

return factory.updateModuleDeclaration(dsNode, dsNode.decorators, dsNode.modifiers, dsName, dsBody);
};
default:
}
default: {
return (...args: any) => (<any>factory)[prop](...args);

Check warning on line 114 in src/harmony/versions/four-seven.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

Check warning on line 114 in src/harmony/versions/four-seven.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
}
}
}

Expand Down
21 changes: 14 additions & 7 deletions src/harmony/versions/three-eight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,10 @@ export function handler(context: TsTransformPathsContext, prop: string | symbol)
const ts = context.tsInstance as unknown as typeof TsThreeEightModule;

switch (prop) {
case "updateCallExpression":
case "updateCallExpression": {
return (...args: any) => ts.updateCall.apply(void 0, args);
case "updateImportClause":
}
case "updateImportClause": {
return function (
node: ImportClause,
_isTypeOnly: boolean,
Expand All @@ -77,7 +78,8 @@ export function handler(context: TsTransformPathsContext, prop: string | symbol)
// @ts-expect-error TODO investigate type issue
return ts.updateImportClause.apply(void 0, downSample(node, name, namedBindings));
};
case "updateImportDeclaration":
}
case "updateImportDeclaration": {
return function (
node: ImportDeclaration,
_modifiers: readonly Modifier[] | undefined,
Expand All @@ -94,7 +96,8 @@ export function handler(context: TsTransformPathsContext, prop: string | symbol)
dsModuleSpecifier,
);
};
case "updateExportDeclaration":
}
case "updateExportDeclaration": {
return function (
node: ExportDeclaration,
_modifiers: readonly Modifier[] | undefined,
Expand All @@ -112,7 +115,8 @@ export function handler(context: TsTransformPathsContext, prop: string | symbol)
dsNode.isTypeOnly,
);
};
case "updateModuleDeclaration":
}
case "updateModuleDeclaration": {
return function (
node: ModuleDeclaration,
_modifiers: readonly Modifier[] | undefined,
Expand All @@ -123,7 +127,8 @@ export function handler(context: TsTransformPathsContext, prop: string | symbol)

return ts.updateModuleDeclaration(dsNode, dsNode.decorators, dsNode.modifiers, dsName, dsBody);
};
case "updateImportTypeNode":
}
case "updateImportTypeNode": {
return function (
node: ImportTypeNode,
argument: TypeNode,
Expand All @@ -136,8 +141,10 @@ export function handler(context: TsTransformPathsContext, prop: string | symbol)

return ts.updateImportTypeNode(dsNode, dsArgument, dsQualifier, dsTypeArguments, isTypeOf);
};
default:
}
default: {
return (...args: any) => (<any>ts)[prop](...args);
}
}
}

Expand Down
5 changes: 2 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import transformer from "./transformer";
export default transformer;

export type { TsTransformPathsConfig } from "./types";
export { register } from "./register";
export { nxTransformerPlugin } from "./plugins";

export { default } from "./transformer";
2 changes: 1 addition & 1 deletion src/plugins/nx-transformer-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@ export const before: NxTransformerFactory = (pluginConfig, program) =>
pluginConfig?.afterDeclarations ? voidTransformer : transformer(program, { ...pluginConfig });

export const afterDeclarations: NxTransformerFactory = (pluginConfig, program) =>
!pluginConfig?.afterDeclarations ? voidTransformer : transformer(program, { ...pluginConfig });
pluginConfig?.afterDeclarations ? transformer(program, { ...pluginConfig }) : voidTransformer;
4 changes: 2 additions & 2 deletions src/transformer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import path from "path";
import path from "node:path";
import ts, { CompilerOptions } from "typescript";
import { RunMode, TsNodeState, TsTransformPathsConfig, TsTransformPathsContext, VisitorContext } from "./types";
import { nodeVisitor } from "./visitor";
Expand Down Expand Up @@ -52,7 +52,7 @@ function getTsProperties(args: Parameters<typeof transformer>) {
tsNodeState === TsNodeState.Full
? compilerOptions!
: {
...(program?.getCompilerOptions() ?? {}),
...program?.getCompilerOptions(),
...tsNodeProps!.compilerOptions,
};
} else {
Expand Down
4 changes: 2 additions & 2 deletions src/utils/general-utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import url from "url";
import path from "path";
import url from "node:url";
import path from "node:path";

/* ****************************************************************************************************************** *
* General Utilities & Helpers
Expand Down
8 changes: 4 additions & 4 deletions src/utils/get-relative-path.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import fs from "fs";
import * as os from "os";
import path from "path";
import fs from "node:fs";
import * as os from "node:os";
import path from "node:path";

/* ****************************************************************************************************************** */
// region: Locals
Expand All @@ -21,7 +21,7 @@ function tryRmFile(fileName: string) {
}

function getIsFsCaseSensitive() {
if (isCaseSensitiveFilesystem != null) return isCaseSensitiveFilesystem;
if (isCaseSensitiveFilesystem != undefined) return isCaseSensitiveFilesystem;

for (let i = 0; i < 1000; i++) {
const tmpFileName = path.join(os.tmpdir(), `tstp~${i}.tmp`);
Expand Down
4 changes: 2 additions & 2 deletions src/utils/resolve-module-name.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { VisitorContext } from "../types";
import { isBaseDir, isURL, maybeAddRelativeLocalPrefix } from "./general-utils";
import * as path from "path";
import * as path from "node:path";
import { removeFileExtension, removeSuffix, ResolvedModuleFull, SourceFile } from "typescript";
import { getOutputDirForSourceFile } from "./ts-helpers";
import { getRelativePath } from "./get-relative-path";
Expand Down Expand Up @@ -32,7 +32,7 @@ function getPathDetail(moduleName: string, resolvedModule: ResolvedModuleFull) {
const resolvedBaseNameNoExtension = resolvedBaseName && removeFileExtension(resolvedBaseName);
const resolvedExtName = resolvedBaseName && path.extname(resolvedFileName);

let baseName = !implicitPackageIndex ? path.basename(moduleName) : void 0;
let baseName = implicitPackageIndex ? void 0 : path.basename(moduleName);
let baseNameNoExtension = baseName && removeFileExtension(baseName);
let extName = baseName && path.extname(moduleName);

Expand Down
8 changes: 4 additions & 4 deletions src/utils/resolve-path-update-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ export function resolvePathAndUpdateNode(

// Accommodate direct override via @transform-path tag
if (tags.overridePath) {
const transformedPath = !isURL(tags.overridePath)
? maybeAddRelativeLocalPrefix(normalizePath(tags.overridePath))
: tags.overridePath;
const transformedPath = isURL(tags.overridePath)
? tags.overridePath
: maybeAddRelativeLocalPrefix(normalizePath(tags.overridePath));
return updaterFn(factory.createStringLiteral(transformedPath));
}

Expand Down Expand Up @@ -63,7 +63,7 @@ export function resolvePathAndUpdateNode(
if (targetNode.pos >= 0) {
try {
const trivia = targetNode.getFullText(sourceFile).slice(0, targetNode.getLeadingTriviaWidth(sourceFile));
const regex = /^\s*\/\/\/?\s*@(transform-path|no-transform-path)(?:[^\S\r\n](.+?))?$/gim;
const regex = /^\s*\/{2,3}\s*@(transform-path|no-transform-path)(?:[^\S\n\r](.+?))?$/gim;

for (let match = regex.exec(trivia); match; match = regex.exec(trivia))
if (match[1]) commentTags.set(match[1], match[2]);
Expand Down
6 changes: 3 additions & 3 deletions src/utils/ts-helpers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ts, { GetCanonicalFileName, SourceFile } from "typescript";
import path from "path";
import path from "node:path";
import { VisitorContext } from "../types";
import type { REGISTER_INSTANCE } from "ts-node";

Expand Down Expand Up @@ -78,10 +78,10 @@ export function getTsNodeRegistrationProperties(tsInstance: typeof ts) {
// eslint-disable-next-line @typescript-eslint/no-require-imports
tsNodeSymbol = require("ts-node")?.["REGISTER_INSTANCE"];
} catch {
return undefined;
return;
}

if (!global.process[tsNodeSymbol]) return undefined;
if (!global.process[tsNodeSymbol]) return;

const { config, options } = global.process[tsNodeSymbol]!;

Expand Down
6 changes: 3 additions & 3 deletions test/config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import ts from "typescript";
import tsThree from "typescript-3";
import tsFourSeven from "typescript-4.7";
import path from "path";

export { ts };
import path from "node:path";

export const tsModules = <const>[
["3.6.5", tsThree, "typescript-3"],
Expand All @@ -16,3 +14,5 @@ export const transformerPath = require.resolve("typescript-transform-paths");
export const builtTransformerPath = require.resolve("typescript-transform-paths");

Error.stackTraceLimit = 120;

export { default as ts } from "typescript";
2 changes: 1 addition & 1 deletion test/jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { JestConfigWithTsJest } from "ts-jest";
const config: JestConfigWithTsJest = {
testEnvironment: "node",
preset: "ts-jest",
testRegex: ".*(test|spec)\\.tsx?$",
testRegex: String.raw`.*(test|spec)\.tsx?$`,
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
};

Expand Down
4 changes: 2 additions & 2 deletions test/tests/extras.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { createTsProgram, getEmitResultFromProgram, ModuleNotFoundError } from "../utils";
import { projectsPaths } from "../config";
import path from "path";
import path from "node:path";
import ts from "typescript";
import * as config from "../config";
import { execSync } from "child_process";
import { execSync } from "node:child_process";

/* ****************************************************************************************************************** *
* Tests
Expand Down
2 changes: 1 addition & 1 deletion test/tests/project-ref.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// noinspection ES6UnusedImports
import * as path from "path";
import * as path from "node:path";
import { createTsSolutionBuilder, EmittedFiles } from "../utils";
import { projectsPaths, ts } from "../config";

Expand Down
19 changes: 11 additions & 8 deletions test/tests/register.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ const configs = {
const configMap = Object.entries(configs).map(([label, cfg]) => {
let hasBefore: boolean = false;
let hasAfterDeclarations: boolean = false;
const transformers = [cfg]
.flat()
.map((c) => {
const transformers = [
...[cfg].flat().map((c) => {
if ((<any>c).before || !(<any>c).afterDeclarations) hasBefore = true;
if ((<any>c).afterDeclarations) hasAfterDeclarations = true;
return { transform: "typescript-transform-paths", ...c, ...pluginOptions } as PluginConfig;
})
.concat([otherTransformer]);
}),
otherTransformer,
] as PluginConfig[];

return { label, transformers, hasBefore, hasAfterDeclarations };
});
Expand Down Expand Up @@ -140,14 +140,17 @@ describe(`Register script`, () => {

let existingTransformers: CustomTransformers | ((p: Program) => CustomTransformers) | undefined;
switch (configKind) {
case "Existing Transformer Config Factory":
case "Existing Transformer Config Factory": {
existingTransformers = transformerFactoryFn;
break;
case "Existing Transformer Config":
}
case "Existing Transformer Config": {
existingTransformers = { ...fakeTransformerConfig };
break;
case "No Existing Transformers":
}
case "No Existing Transformers": {
existingTransformers = void 0;
}
}

describe.each(configMap)(`$label`, ({ transformers, hasBefore, hasAfterDeclarations }) => {
Expand Down
6 changes: 3 additions & 3 deletions test/tests/transformer/general.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// noinspection ES6UnusedImports
import * as path from "path";
import * as path from "node:path";
import { createTsProgram, EmittedFiles, getEmitResultFromProgram } from "../../utils";
import { ts, tsModules, projectsPaths } from "../../config";

Expand All @@ -15,8 +15,8 @@ const makeRelative = (tsInstance: typeof ts, fileName: string, p: string, rootDi

const getExpected = (tsInstance: typeof ts, fileName: string, original: string, rootDir: string): string =>
original
.replace(/"@(.*)"/g, (_, p) => makeRelative(tsInstance, fileName, p, rootDir))
.replace(/"#utils\/(.*)"/g, (_, p) =>
.replaceAll(/"@(.*)"/g, (_, p) => makeRelative(tsInstance, fileName, p, rootDir))
.replaceAll(/"#utils\/(.*)"/g, (_, p) =>
makeRelative(tsInstance, fileName, path.join(p === "hello" ? "secondary" : "utils", p), rootDir),
)
.replace('"path"', '"https://external.url/path.js"')
Expand Down
Loading

0 comments on commit 44ad2e0

Please sign in to comment.