style: update eslint rules (#21207)

* style: update eslint rules

* style: fix prefer-object-spread

* style: fix no-lonely-if

* fix: typescript-eslint/no-unnecessary-template-expression

* fix: sort import

* style: apply file filtering to config presets

* revert: changes on pkg

* style: revert

* style: use defineConfig

* style: reorder js plugin in eslint config

* chore: remove obsolete override

* style: fix CodeQL initialization to ensure language matrix is used
This commit is contained in:
Tony
2026-02-23 08:17:37 +08:00
committed by GitHub
parent f7bea67c63
commit 7785a7bde4
19 changed files with 715 additions and 147 deletions
+1 -1
View File
@@ -55,13 +55,13 @@ jobs:
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
languages: ${{ matrix.language }}
# Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift).
# If this step fails, then you should remove it and run the build manually (see below)
+4 -1
View File
@@ -5,5 +5,8 @@
"singleQuote": true,
"trailingComma": "es5",
"arrowParens": "always",
"ignorePatterns": ["lib/routes-deprecated", "lib/router.js", "babel.config.js", "scripts/docker/minify-docker.js", "dist", "pnpm-lock.yaml"]
"ignorePatterns": ["lib/routes-deprecated", "lib/router.js", "babel.config.js", "scripts/docker/minify-docker.js", "dist", "pnpm-lock.yaml"],
"experimentalSortPackageJson": {
"sortScripts": true
}
}
+53 -43
View File
@@ -1,23 +1,21 @@
import { FlatCompat } from '@eslint/eslintrc';
import js from '@eslint/js';
import stylistic from '@stylistic/eslint-plugin';
import typescriptEslint from '@typescript-eslint/eslint-plugin';
import tsParser from '@typescript-eslint/parser';
import { defineConfig } from 'eslint/config';
import github from 'eslint-plugin-github';
import { importX } from 'eslint-plugin-import-x';
import n from 'eslint-plugin-n';
import simpleImportSort from 'eslint-plugin-simple-import-sort';
import unicorn from 'eslint-plugin-unicorn';
import eslintPluginYml from 'eslint-plugin-yml';
import globals from 'globals';
// import nsfwFlagPlugin from './eslint-plugins/nsfw-flag.js';
const __dirname = import.meta.dirname;
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
});
const SOURCE_FILES_GLOB = '**/*.?([cm])[jt]s?(x)';
export default [
export default defineConfig([
// {
// plugins: {
// '@rsshub/nsfw-flag': nsfwFlagPlugin,
@@ -27,17 +25,19 @@ export default [
// },
// },
{
ignores: ['**/coverage', '**/.vscode', '**/docker-compose.yml', '!.github', 'assets/build', 'lib/routes-deprecated', 'lib/router.js', '**/babel.config.js', 'scripts/docker/minify-docker.js', 'dist', 'dist-lib'],
ignores: ['**/coverage', '**/.vscode', '**/docker-compose.yml', '!.github', 'assets/build', 'lib/routes-deprecated', 'lib/router.js', 'dist', 'dist-lib', 'dist-worker'],
},
...compat.extends('eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/stylistic'),
n.configs['flat/recommended-script'],
unicorn.configs.recommended,
...eslintPluginYml.configs.recommended,
{
files: [SOURCE_FILES_GLOB],
plugins: {
'@stylistic': stylistic,
'@typescript-eslint': typescriptEslint,
github,
js,
n,
unicorn,
},
extends: [js.configs.recommended, typescriptEslint.configs['flat/recommended'], typescriptEslint.configs['flat/stylistic'], n.configs['flat/recommended-script'], unicorn.configs.recommended],
languageOptions: {
globals: {
@@ -51,7 +51,7 @@ export default [
},
rules: {
// possible problems
// #region possible problems
'array-callback-return': [
'error',
{
@@ -62,8 +62,9 @@ export default [
'no-await-in-loop': 'error',
'no-control-regex': 'off',
'no-prototype-builtins': 'off',
// #endregion
// suggestions
// #region suggestions
'arrow-body-style': 'error',
'block-scoped-var': 'error',
curly: 'error',
@@ -95,9 +96,9 @@ export default [
'no-implicit-globals': 'error',
'no-labels': 'error',
'no-lonely-if': 'error',
'no-multi-str': 'error',
'no-new-func': 'error',
'no-restricted-imports': 'error',
'no-restricted-syntax': [
'error',
@@ -136,7 +137,6 @@ export default [
'prefer-arrow-callback': 'error',
'prefer-const': 'error',
'prefer-object-has-own': 'error',
'no-useless-escape': 'warn',
'prefer-regex-literals': [
'error',
@@ -146,8 +146,9 @@ export default [
],
'require-await': 'error',
// #endregion
// typescript
// #region typescript
'@typescript-eslint/array-type': ['error', { default: 'array-simple' }],
'@typescript-eslint/ban-ts-comment': 'off',
@@ -177,8 +178,9 @@ export default [
],
'@typescript-eslint/prefer-for-of': 'error',
// #endregion
// unicorn
// #region unicorn
'unicorn/consistent-function-scoping': 'warn',
'unicorn/explicit-length-check': 'off',
@@ -265,8 +267,9 @@ export default [
'unicorn/switch-case-braces': ['error', 'avoid'],
'unicorn/text-encoding-identifier-case': 'off',
'unicorn/number-literal-case': 'off',
// #endregion
// formatting rules
// #region stylistic
'@stylistic/arrow-parens': 'error',
'@stylistic/arrow-spacing': 'error',
'@stylistic/comma-spacing': 'error',
@@ -291,9 +294,9 @@ export default [
'@stylistic/space-infix-ops': 'error',
'@stylistic/space-unary-ops': 'error',
'@stylistic/spaced-comment': 'error',
// #endregion
// https://github.com/eslint-community/eslint-plugin-n
// node specific rules
// #region node specific rules
'n/no-extraneous-require': 'error',
'n/no-deprecated-api': 'warn',
@@ -317,6 +320,10 @@ export default [
ignores: [],
},
],
// #endregion
// github
'github/no-then': 'warn',
},
},
{
@@ -325,9 +332,33 @@ export default [
'@typescript-eslint/no-require-imports': 'off',
},
},
{
files: [SOURCE_FILES_GLOB],
plugins: {
'simple-import-sort': simpleImportSort,
'import-x': importX,
},
rules: {
'sort-imports': 'off',
'import-x/order': 'off',
'simple-import-sort/imports': 'error',
'simple-import-sort/exports': 'error',
'import-x/first': 'error',
'import-x/newline-after-import': 'error',
'no-duplicate-imports': 'off',
'import-x/no-duplicates': 'error',
'@typescript-eslint/consistent-type-imports': 'error',
'import-x/consistent-type-specifier-style': ['error', 'prefer-top-level'],
},
},
{
files: ['**/*.yaml', '**/*.yml'],
ignores: ['pnpm-lock.yaml'],
plugins: {
yml: eslintPluginYml,
},
language: 'yml/yaml',
rules: {
'lines-around-comment': [
@@ -355,25 +386,4 @@ export default [
],
},
},
{
files: ['**/*.?([cm])[jt]s?(x)'],
plugins: {
'simple-import-sort': simpleImportSort,
'import-x': importX,
},
rules: {
'sort-imports': 'off',
'import-x/order': 'off',
'simple-import-sort/imports': 'error',
'simple-import-sort/exports': 'error',
'import-x/first': 'error',
'import-x/newline-after-import': 'error',
'no-duplicate-imports': 'off',
'import-x/no-duplicates': 'error',
'@typescript-eslint/consistent-type-imports': 'error',
'import-x/consistent-type-specifier-style': ['error', 'prefer-top-level'],
},
},
];
]);
+1 -1
View File
@@ -72,7 +72,7 @@ async function handler(ctx) {
const chapterResult = await processApiItems(chapterApiUrl);
const result = {};
const chapterNum = index + 1;
result.title = `第${String(chapterNum)}話 ${item.name === '' ? `${String(chapterNum)}` : item.name}`;
result.title = `第${chapterNum}話 ${item.name === '' ? chapterNum : item.name}`;
result.link = `${rootUrl}/photo/${item.id}`;
result.guid = `${rootUrl}/photo/${item.id}`;
result.updated = new Date(chapterResult.addtime * 1000);
+1 -6
View File
@@ -133,12 +133,7 @@ const ProcessItems = async (ctx) => {
images = images.length === 0 ? [detail.work_image] : images;
return {
title: `${
discountRate
? `${discountRate}% OFF
${` ${discountEndDate ? `${dayjs(discountEndDate).format('YYYY-MM-DD HH:mm')} まで` : ''}`}`
: ' '
}${title}`,
title: `${discountRate ? `${discountRate}% OFF ${discountEndDate ? `${dayjs(discountEndDate).format('YYYY-MM-DD HH:mm')} まで` : ''}` : ' '}${title}`,
link,
pubDate,
author: authors.map((a) => a.name).join(' / '),
+1 -1
View File
@@ -70,7 +70,7 @@ const ProcessFeed = (list, caches) => {
const other = await caches.tryGet(itemUrl, () => loadContent(itemUrl));
// 合并解析后的结果集作为该篇文章最终的输出结果
return Object.assign({}, single, other);
return { ...single, ...other };
},
{ concurrency: 2 }
); // 设置并发请求数量为 2
+2 -2
View File
@@ -48,7 +48,7 @@ const bakeFilterSearchParams = (filterPairs, pairKey, isApi = false) => {
const key = keys[0];
const pairs = filterPairs[key];
const originalFilters = Object.assign({}, filterPairs);
const originalFilters = { ...filterPairs };
delete originalFilters[key];
filterSearchParams.append(getFilterKeyForSearchParams(key, isApi), pairs.map((pair) => (Object.hasOwn(pair, pairKey) ? pair[pairKey] : pair)).join(','));
@@ -121,7 +121,7 @@ const bakeFiltersWithPair = async (filters) => {
const key = keys[0];
const keywords = filters[key];
const originalFilters = Object.assign({}, filters);
const originalFilters = { ...filters };
delete originalFilters[key];
return bakeFilters(originalFilters, {
+15 -17
View File
@@ -98,25 +98,23 @@ async function handler(ctx) {
} else {
description = item.find('a').text(); // 忽略获取吹风会的全文
}
} else {
if (contentUrl.includes('content')) {
fullTextGet = await got.get(contentUrl);
fullTextData = load(fullTextGet.data);
const $1 = fullTextData.html();
pubDate = timezone(parseDate(fullTextData('meta[name="firstpublishedtime"]').attr('content'), 'YYYY-MM-DD HH:mm:ss'), 8);
author = fullTextData('meta[name="author"]').attr('content');
category = fullTextData('meta[name="keywords"]').attr('content').split(/[,;]/);
if (/zhengceku/g.test(contentUrl)) {
// 政策文件库
description = fullTextData('.pages_content').html();
} else {
fullTextData('.shuzi').remove(); // 移除videobg的图片
fullTextData('#myFlash').remove(); // 移除flash
description = /UCAP-CONTENT/g.test($1) ? fullTextData('#UCAP-CONTENT').html() : fullTextData('body').html();
}
} else if (contentUrl.includes('content')) {
fullTextGet = await got.get(contentUrl);
fullTextData = load(fullTextGet.data);
const $1 = fullTextData.html();
pubDate = timezone(parseDate(fullTextData('meta[name="firstpublishedtime"]').attr('content'), 'YYYY-MM-DD HH:mm:ss'), 8);
author = fullTextData('meta[name="author"]').attr('content');
category = fullTextData('meta[name="keywords"]').attr('content').split(/[,;]/);
if (/zhengceku/g.test(contentUrl)) {
// 政策文件库
description = fullTextData('.pages_content').html();
} else {
description = item.find('a').text(); // 忽略获取吹风会的全文
fullTextData('.shuzi').remove(); // 移除videobg的图片
fullTextData('#myFlash').remove(); // 移除flash
description = /UCAP-CONTENT/g.test($1) ? fullTextData('#UCAP-CONTENT').html() : fullTextData('body').html();
}
} else {
description = item.find('a').text(); // 忽略获取吹风会的全文
}
return {
title: item.find('a').text(),
+6 -8
View File
@@ -92,15 +92,13 @@ async function handler(ctx) {
if (/^https?:\/\//i.test(src)) {
// 已经是完整 URL
$e.attr('src', src);
} else {
} else if (src.startsWith('/')) {
// 处理以 / 开头的绝对路径
if (src.startsWith('/')) {
$e.attr('src', `${item.link}/resolve/main/` + src);
} else {
// 处理相对路径(如 ./images/pic.png 或 images/pic.png)
const baseUrl = item.link + '/resolve/main/';
$e.attr('src', baseUrl + src.replace(/^\.\//, ''));
}
$e.attr('src', `${item.link}/resolve/main/` + src);
} else {
// 处理相对路径(如 ./images/pic.png 或 images/pic.png)
const baseUrl = item.link + '/resolve/main/';
$e.attr('src', baseUrl + src.replace(/^\.\//, ''));
}
});
item.description = $Out.html();
+6 -8
View File
@@ -74,15 +74,13 @@ async function handler(ctx) {
path = `forum-${categoryId[category][0]}.html`;
title = `看雪论坛最新主题 - ${categoryId[category][1]}`;
}
} else {
} else if (category === 'digest') {
// category未知时则获取全站最新帖
if (category === 'digest') {
path = 'new-digest.htm';
title = '看雪论坛精华主题';
} else {
path = 'new-tid.htm';
title = '看雪论坛最新主题';
}
path = 'new-digest.htm';
title = '看雪论坛精华主题';
} else {
path = 'new-tid.htm';
title = '看雪论坛最新主题';
}
const response = await got({
+1 -1
View File
@@ -88,7 +88,7 @@ query ($take: Int, $skip: Int, $orderBy: [PostOrderByInput!]!, $filter: PostWher
title: e.title,
pubDate: parseDate(e.publishedDate),
category: [...(e.sections ?? []).map((_) => `section:${_.name}`), ...(e.categories ?? []).map((_) => `category:${_.name}`)],
link: `${rootUrl}/${'story'}/${e.slug}`,
link: `${rootUrl}/story/${e.slug}`,
}));
const list = await Promise.all(items.map((item) => getArticle(item)));
+1 -1
View File
@@ -49,7 +49,7 @@ async function handler(ctx) {
pubDate: timezone(parseDate(time), +8),
};
const other = await loadContent(String(itemUrl));
return Object.assign({}, single, other);
return { ...single, ...other };
})
);
return {
+6 -8
View File
@@ -90,15 +90,13 @@ async function handler(ctx) {
if (moment.reposted_moment.topic.footer_images) {
description += imagePost(moment.reposted_moment.topic.footer_images);
}
} else {
if (moment.topic.pin_video) {
description += videoPost(moment.topic.pin_video);
if (moment.topic.footer_images?.images) {
description += imagePost(moment.topic.footer_images.images);
}
} else {
description = await topicPost(appId, topicId, lang);
} else if (moment.topic.pin_video) {
description += videoPost(moment.topic.pin_video);
if (moment.topic.footer_images?.images) {
description += imagePost(moment.topic.footer_images.images);
}
} else {
description = await topicPost(appId, topicId, lang);
}
return {
title,
+1 -1
View File
@@ -49,7 +49,7 @@ const postTask = async (flowToken: string, subtaskId: string, subtaskInput: Reco
headers,
json: {
flow_token: flowToken,
subtask_inputs: [Object.assign({ subtask_id: subtaskId }, subtaskInput)],
subtask_inputs: [{ subtask_id: subtaskId, ...subtaskInput }],
},
});
+5 -7
View File
@@ -19,13 +19,11 @@ export async function getPostItems(params: {
}): Promise<DataItem[]> {
const baseUrl = 'https://9oyi4rk426.execute-api.ca-central-1.amazonaws.com/production/post';
const url = new URL(baseUrl);
const finalSearchParams = Object.assign(
{
limit: 20,
offset: 0,
},
params
);
const finalSearchParams = {
limit: 20,
offset: 0,
...params,
};
if (finalSearchParams.time_range !== undefined) {
finalSearchParams.time_range = finalSearchParams.time_range.toUpperCase();
if (!TimeRangeParam.options.some((option) => option.value === finalSearchParams.time_range)) {
+15 -17
View File
@@ -104,23 +104,21 @@ async function handler(ctx) {
}
}
}
} else {
if (item.price) {
description += `平台: ${platformInfo.desc}<br/>`;
if (item.heybox_price) {
description += `当前价格: ${item.price.current} ${getHeyboxPriceDesc(item.heybox_price)} ${getLowestDesc(item.price, item.heybox_price.super_lowest)}<br/>`;
} else if (item.price.current) {
description += `当前价格: ${item.price.current} ${getLowestDesc(item.price)}<br/>`;
}
if (item.price.initial) {
description += `原价: ${item.price.initial}<br/>`;
}
if (item.price.discount && item.price.discount > 0) {
description += `折扣力度: ${getDiscountDesc(item.price.discount)}<br/>`;
}
if (item.price.deadline_date) {
description += `截止时间: ${item.price.deadline_date}<br/>`;
}
} else if (item.price) {
description += `平台: ${platformInfo.desc}<br/>`;
if (item.heybox_price) {
description += `当前价格: ${item.price.current} ${getHeyboxPriceDesc(item.heybox_price)} ${getLowestDesc(item.price, item.heybox_price.super_lowest)}<br/>`;
} else if (item.price.current) {
description += `当前价格: ${item.price.current} ${getLowestDesc(item.price)}<br/>`;
}
if (item.price.initial) {
description += `原价: ${item.price.initial}<br/>`;
}
if (item.price.discount && item.price.discount > 0) {
description += `折扣力度: ${getDiscountDesc(item.price.discount)}<br/>`;
}
if (item.price.deadline_date) {
description += `截止时间: ${item.price.deadline_date}<br/>`;
}
}
if (item.score) {
+20 -9
View File
@@ -30,12 +30,7 @@
"build:docs": "npm run build:routes && tsx scripts/workflow/build-docs.ts",
"build:lib": "npm run build:routes && tsdown --config ./tsdown-lib.config.ts",
"build:routes": "cross-env NODE_ENV=dev tsx scripts/workflow/build-routes.ts",
"vercel-build": "npm run build:routes && tsdown --config ./tsdown-vercel.config.ts",
"build:routes:worker": "cross-env NODE_ENV=dev WORKER_BUILD=true tsx scripts/workflow/build-routes.ts",
"worker-build": "npm run build:routes:worker && tsdown --config ./tsdown-worker.config.ts",
"worker-dev": "npm run worker-build && wrangler dev",
"worker-deploy": "npm run worker-build && wrangler deploy",
"worker-test": "npm run worker-build && vitest run lib/worker.worker.test.ts",
"container-build": "tsdown --config ./tsdown-container.config.ts",
"container-deploy": "npm run container-build && wrangler deploy --config wrangler-container.toml --containers-rollout=immediate",
"dev": "cross-env NODE_ENV=dev NODE_OPTIONS='--max-http-header-size=32768' tsx watch --inspect --clear-screen=false lib/index.ts",
@@ -49,10 +44,15 @@
"profiling": "cross-env NODE_ENV=production tsx --prof lib/index.ts",
"start": "cross-env NODE_ENV=production NODE_OPTIONS='--max-http-header-size=32768' node dist/index.mjs",
"test": "npm run format:check && npm run vitest:coverage",
"vercel-build": "npm run build:routes && tsdown --config ./tsdown-vercel.config.ts",
"vitest": "cross-env NODE_ENV=test vitest",
"vitest:coverage": "cross-env NODE_ENV=test vitest --coverage.enabled --reporter=junit",
"vitest:fullroutes": "cross-env NODE_ENV=test FULL_ROUTES_TEST=true vitest --reporter=json --reporter=default --outputFile=\"./assets/build/test-full-routes.json\" routes",
"vitest:watch": "cross-env NODE_ENV=test vitest --watch"
"vitest:watch": "cross-env NODE_ENV=test vitest --watch",
"worker-build": "npm run build:routes:worker && tsdown --config ./tsdown-worker.config.ts",
"worker-deploy": "npm run worker-build && wrangler deploy",
"worker-dev": "npm run worker-build && wrangler dev",
"worker-test": "npm run worker-build && vitest run lib/worker.worker.test.ts"
},
"dependencies": {
"@bbob/html": "4.3.1",
@@ -174,6 +174,7 @@
"domhandler": "5.0.3",
"eslint": "10.0.0",
"eslint-nibble": "9.1.1",
"eslint-plugin-github": "6.0.0",
"eslint-plugin-import-x": "4.16.1",
"eslint-plugin-n": "17.24.0",
"eslint-plugin-simple-import-sort": "12.1.1",
@@ -212,7 +213,7 @@
"engines": {
"node": "^22.20.0 || ^24"
},
"packageManager": "pnpm@10.29.3+sha512.498e1fb4cca5aa06c1dcf2611e6fafc50972ffe7189998c409e90de74566444298ffe43e6cd2acdc775ba1aa7cc5e092a8b7054c811ba8c5770f84693d33d2dc",
"packageManager": "pnpm@10.30.1+sha512.3590e550d5384caa39bd5c7c739f72270234b2f6059e13018f975c313b1eb9fefcc09714048765d4d9efe961382c312e624572c0420762bdc5d5940cdf9be73a",
"pnpm": {
"onlyBuiltDependencies": [
"bufferutil",
@@ -234,6 +235,10 @@
"wrangler"
],
"overrides": {
"array-includes": "npm:@nolyfill/array-includes@^1",
"array.prototype.findlastindex": "npm:@nolyfill/array.prototype.findlastindex@^1",
"array.prototype.flat": "npm:@nolyfill/array.prototype.flat@^1",
"array.prototype.flatmap": "npm:@nolyfill/array.prototype.flatmap@^1",
"difflib": "https://codeload.github.com/postlight/difflib.js/tar.gz/32e8e38c7fcd935241b9baab71bb432fd9b166ed",
"es-set-tostringtag": "npm:@nolyfill/es-set-tostringtag@^1",
"google-play-scraper>got": "^14.6.4",
@@ -241,12 +246,18 @@
"google-play-scraper>tough-cookie": "^6.0.0",
"hasown": "npm:@nolyfill/hasown@^1",
"is-core-module": "npm:@nolyfill/is-core-module@^1",
"js-beautify@1.15.4>glob": "^10.5.0",
"object.assign": "npm:@nolyfill/object.assign@^1",
"object.fromentries": "npm:@nolyfill/object.fromentries@^1",
"object.groupby": "npm:@nolyfill/object.groupby@^1",
"object.values": "npm:@nolyfill/object.values@^1",
"rss-parser@3.13.0>entities": "^7.0.0",
"rss-parser@3.13.0>xml2js": "^0.6.2",
"safe-buffer": "npm:@nolyfill/safe-buffer@^1",
"safe-regex-test": "npm:@nolyfill/safe-regex-test@^1",
"safer-buffer": "npm:@nolyfill/safer-buffer@^1",
"side-channel": "npm:@nolyfill/side-channel@^1"
"side-channel": "npm:@nolyfill/side-channel@^1",
"string.prototype.includes": "npm:@nolyfill/string.prototype.includes@^1",
"string.prototype.trimend": "npm:@nolyfill/string.prototype.trimend@^1"
},
"patchedDependencies": {
"rss-parser@3.13.0": "patches/rss-parser@3.13.0.patch"
+573 -14
View File
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -1,7 +1,9 @@
/* eslint-disable no-console */
import fs from 'fs-extra';
import path from 'node:path';
import { nodeFileTrace } from '@vercel/nft';
import fs from 'fs-extra';
const __dirname = import.meta.dirname;
// !!! if any new dependencies are added, update the Dockerfile !!!