From e5a9fd46eeb55153a4ba4ad23d4da2586d01fb6b Mon Sep 17 00:00:00 2001 From: DIYgod Date: Sat, 23 Mar 2024 02:03:55 +0800 Subject: [PATCH 01/24] feat: use ofetch imitate got --- lib/utils/got-deprecated.ts | 79 +++++++++++++++++++++ lib/utils/got.ts | 133 ++++++++++++++++-------------------- lib/utils/ofetch.ts | 17 +++++ package.json | 2 + pnpm-lock.yaml | 26 +++++++ 5 files changed, 181 insertions(+), 76 deletions(-) create mode 100644 lib/utils/got-deprecated.ts create mode 100644 lib/utils/ofetch.ts diff --git a/lib/utils/got-deprecated.ts b/lib/utils/got-deprecated.ts new file mode 100644 index 000000000..d99ddc3f6 --- /dev/null +++ b/lib/utils/got-deprecated.ts @@ -0,0 +1,79 @@ +import logger from '@/utils/logger'; +import { config } from '@/config'; +import got, { CancelableRequest, Response as GotResponse, OptionsInit, Options, Got } from 'got'; + +type Response = GotResponse & { + data: T; + status: number; +}; + +type GotRequestFunction = { + (url: string | URL, options?: Options): CancelableRequest>>; + (url: string | URL, options?: Options): CancelableRequest>; + (options: Options): CancelableRequest>>; + (options: Options): CancelableRequest>; +}; + +// @ts-expect-error got instance with custom response type +const custom: { + all?: (list: Array>) => Promise>; + get: GotRequestFunction; + post: GotRequestFunction; + put: GotRequestFunction; + patch: GotRequestFunction; + head: GotRequestFunction; + delete: GotRequestFunction; +} & GotRequestFunction & + Got = got.extend({ + retry: { + limit: config.requestRetry, + statusCodes: [400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 421, 422, 423, 424, 426, 428, 429, 431, 451, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511, 521, 522, 524], + }, + hooks: { + beforeRetry: [ + (err, count) => { + logger.error(`Request ${err.options.url} fail, retry attempt #${count}: ${err}`); + }, + ], + beforeRedirect: [ + (options, response) => { + logger.http(`Redirecting to ${options.url} for ${response.requestUrl}`); + }, + ], + afterResponse: [ + // @ts-expect-error custom response type + (response: Response>) => { + try { + response.data = typeof response.body === 'string' ? JSON.parse(response.body) : response.body; + } catch { + // @ts-expect-error for compatibility + response.data = response.body; + } + response.status = response.statusCode; + return response; + }, + ], + init: [ + ( + options: OptionsInit & { + data?: string; + } + ) => { + // compatible with axios api + if (options && options.data) { + options.body = options.body || options.data; + } + }, + ], + }, + headers: { + 'user-agent': config.ua, + }, + timeout: { + request: config.requestTimeout, + }, +}); +custom.all = (list) => Promise.all(list); + +export default custom; +export type { Response, Options } from 'got'; diff --git a/lib/utils/got.ts b/lib/utils/got.ts index d99ddc3f6..6701fd502 100644 --- a/lib/utils/got.ts +++ b/lib/utils/got.ts @@ -1,79 +1,60 @@ -import logger from '@/utils/logger'; -import { config } from '@/config'; -import got, { CancelableRequest, Response as GotResponse, OptionsInit, Options, Got } from 'got'; +import { destr } from 'destr'; +import ofetch from '@/utils/ofetch'; -type Response = GotResponse & { - data: T; - status: number; -}; - -type GotRequestFunction = { - (url: string | URL, options?: Options): CancelableRequest>>; - (url: string | URL, options?: Options): CancelableRequest>; - (options: Options): CancelableRequest>>; - (options: Options): CancelableRequest>; -}; - -// @ts-expect-error got instance with custom response type -const custom: { - all?: (list: Array>) => Promise>; - get: GotRequestFunction; - post: GotRequestFunction; - put: GotRequestFunction; - patch: GotRequestFunction; - head: GotRequestFunction; - delete: GotRequestFunction; -} & GotRequestFunction & - Got = got.extend({ - retry: { - limit: config.requestRetry, - statusCodes: [400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 421, 422, 423, 424, 426, 428, 429, 431, 451, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511, 521, 522, 524], - }, - hooks: { - beforeRetry: [ - (err, count) => { - logger.error(`Request ${err.options.url} fail, retry attempt #${count}: ${err}`); - }, - ], - beforeRedirect: [ - (options, response) => { - logger.http(`Redirecting to ${options.url} for ${response.requestUrl}`); - }, - ], - afterResponse: [ - // @ts-expect-error custom response type - (response: Response>) => { - try { - response.data = typeof response.body === 'string' ? JSON.parse(response.body) : response.body; - } catch { - // @ts-expect-error for compatibility - response.data = response.body; - } - response.status = response.statusCode; - return response; - }, - ], - init: [ - ( - options: OptionsInit & { - data?: string; - } - ) => { - // compatible with axios api - if (options && options.data) { - options.body = options.body || options.data; - } - }, - ], - }, - headers: { - 'user-agent': config.ua, - }, - timeout: { - request: config.requestTimeout, - }, +const gotofetch = ofetch.create({ + parseResponse: (responseText) => ({ + data: destr(responseText), + body: responseText, + }), }); -custom.all = (list) => Promise.all(list); -export default custom; -export type { Response, Options } from 'got'; +const getFakeGot = (defaultOptions?: any) => { + const fakeGot = (request, options) => { + if (options?.hooks?.beforeRequest) { + for (const hook of options.hooks.beforeRequest) { + hook(options); + } + } + if (!(typeof request === 'string' || request instanceof Request) && request.url) { + options = { + ...request, + ...options, + }; + request = request.url; + } + + options = { + ...defaultOptions, + ...options, + }; + + if (options?.json && !options.body) { + options.body = options.json; + } + if (options?.form && !options.body) { + const body = new FormData(); + for (const key in options.form) { + body.append(key, options.form[key]); + } + options.body = body; + if (!options.headers) { + options.headers = {}; + } + options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; + } + + return gotofetch(request, options); + }; + + fakeGot.get = (request, options) => fakeGot(request, { ...options, method: 'GET' }); + fakeGot.post = (request, options) => fakeGot(request, { ...options, method: 'POST' }); + fakeGot.put = (request, options) => fakeGot(request, { ...options, method: 'PUT' }); + fakeGot.patch = (request, options) => fakeGot(request, { ...options, method: 'PATCH' }); + fakeGot.head = (request, options) => fakeGot(request, { ...options, method: 'HEAD' }); + fakeGot.delete = (request, options) => fakeGot(request, { ...options, method: 'DELETE' }); + fakeGot.extend = (options) => getFakeGot(options); + + return fakeGot; +}; + +export default getFakeGot(); diff --git a/lib/utils/ofetch.ts b/lib/utils/ofetch.ts new file mode 100644 index 000000000..c02204862 --- /dev/null +++ b/lib/utils/ofetch.ts @@ -0,0 +1,17 @@ +import { ofetch } from 'ofetch'; +import { config } from '@/config'; +import logger from '@/utils/logger'; + +const rofetch = ofetch.create({ + retry: config.requestRetry, + retryDelay: 1000, + timeout: config.requestTimeout, + headers: { + 'user-agent': config.ua, + }, + onRequestError({ request, error }) { + logger.error(`Request ${request.url} fail: ${error}`); + }, +}); + +export default rofetch; diff --git a/package.json b/package.json index 81bae96ee..c27f74fc5 100644 --- a/package.json +++ b/package.json @@ -63,6 +63,7 @@ "crypto-js": "4.2.0", "currency-symbol-map": "5.1.0", "dayjs": "1.11.8", + "destr": "2.0.3", "directory-import": "3.2.1", "dotenv": "16.4.5", "entities": "4.5.0", @@ -89,6 +90,7 @@ "module-alias": "2.2.3", "notion-to-md": "3.1.1", "oauth-1.0a": "2.2.6", + "ofetch": "1.3.4", "otplib": "12.0.1", "pac-proxy-agent": "7.0.1", "proxy-chain": "2.4.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 387bc28e9..aa2ee63b0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -53,6 +53,9 @@ dependencies: dayjs: specifier: 1.11.8 version: 1.11.8 + destr: + specifier: 2.0.3 + version: 2.0.3 directory-import: specifier: 3.2.1 version: 3.2.1 @@ -131,6 +134,9 @@ dependencies: oauth-1.0a: specifier: 2.2.6 version: 2.2.6 + ofetch: + specifier: 1.3.4 + version: 1.3.4 otplib: specifier: 12.0.1 version: 12.0.1 @@ -4085,6 +4091,10 @@ packages: engines: {node: '>=6'} dev: true + /destr@2.0.3: + resolution: {integrity: sha512-2N3BOUU4gYMpTP24s5rF5iP7BDr7uNTCs4ozw3kf/eKfvWSIu93GEBi5m427YoyJoeOzQ5smuu4nNAPGb8idSQ==} + dev: false + /detect-libc@2.0.2: resolution: {integrity: sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==} engines: {node: '>=8'} @@ -6798,6 +6808,10 @@ packages: - supports-color dev: true + /node-fetch-native@1.6.4: + resolution: {integrity: sha512-IhOigYzAKHd244OC0JIMIUrjzctirCmPkaIfhDeGcEETWof5zKYUW7e7MYvChGWh/4CJeXEgsRyGzuF334rOOQ==} + dev: false + /node-fetch@2.7.0: resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==} engines: {node: 4.x || >=6.0.0} @@ -6920,6 +6934,14 @@ packages: /object-inspect@1.13.1: resolution: {integrity: sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==} + /ofetch@1.3.4: + resolution: {integrity: sha512-KLIET85ik3vhEfS+3fDlc/BAZiAp+43QEC/yCo5zkNoY2YaKvNkOaFr/6wCFgFH1kuYQM5pMNi0Tg8koiIemtw==} + dependencies: + destr: 2.0.3 + node-fetch-native: 1.6.4 + ufo: 1.5.3 + dev: false + /on-exit-leak-free@2.1.2: resolution: {integrity: sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==} engines: {node: '>=14.0.0'} @@ -8764,6 +8786,10 @@ packages: resolution: {integrity: sha512-Hhy+BhRBleFjpJ2vchUNN40qgkh0366FWJGqVLYBHev0vpHTrXSA0ryT+74UiW6KWsldNurQMKGqCm1M2zBciQ==} dev: true + /ufo@1.5.3: + resolution: {integrity: sha512-Y7HYmWaFwPUmkoQCUIAYpKqkOf+SbVj/2fJJZ4RJMCfZp0rTGwRbzQD+HghfnhKOjL9E01okqz+ncJskGYfBNw==} + dev: false + /uglify-js@3.4.10: resolution: {integrity: sha512-Y2VsbPVs0FIshJztycsO2SfPk7/KAF/T72qzv9u5EpQ4kB2hQoHlhNQTsNyy6ul7lQtqJN/AoWeS23OzEiEFxw==} engines: {node: '>=0.8.0'} From 81bf135e96b42ad449c648afa2aa42d18d976f36 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Mon, 25 Mar 2024 02:00:47 +0800 Subject: [PATCH 02/24] fix: ofetch searchParams and form --- lib/routes/pixiv/token.ts | 35 ++++++++++++++--------------------- lib/utils/got.ts | 20 +++++++++++++------- 2 files changed, 27 insertions(+), 28 deletions(-) diff --git a/lib/routes/pixiv/token.ts b/lib/routes/pixiv/token.ts index ac0d9e542..98356a057 100644 --- a/lib/routes/pixiv/token.ts +++ b/lib/routes/pixiv/token.ts @@ -15,34 +15,27 @@ const refreshToken = (tryGet) => tryGet( 'pixiv:accessToken', () => - got - .post('https://oauth.secure.pixiv.net/auth/token', { - form: { - ...authorizationInfo, - get_secure_url: 1, - grant_type: 'refresh_token', - refresh_token: config.pixiv.refreshToken, - }, - headers: { - ...maskHeader, - }, - responseType: 'json', - resolveBodyOnly: true, - }) - .catch((error) => { - logger.error('Pixiv refresh token failed.'); - logger.error(error); - }), + got.post('https://oauth.secure.pixiv.net/auth/token', { + form: { + ...authorizationInfo, + get_secure_url: 1, + grant_type: 'refresh_token', + refresh_token: config.pixiv.refreshToken, + }, + headers: { + ...maskHeader, + }, + }), 3600, false ); async function getToken(tryGet) { - const result = await refreshToken(tryGet); + const { data } = await refreshToken(tryGet); // let expireTime; - if (result && result.access_token) { + if (data && data.access_token) { logger.debug('Pixiv refresh token success.'); - token = result.access_token; + token = data.access_token; // expireTime = result.expires_in; } // } else { diff --git a/lib/utils/got.ts b/lib/utils/got.ts index 6701fd502..a602fab3a 100644 --- a/lib/utils/got.ts +++ b/lib/utils/got.ts @@ -9,12 +9,7 @@ const gotofetch = ofetch.create({ }); const getFakeGot = (defaultOptions?: any) => { - const fakeGot = (request, options) => { - if (options?.hooks?.beforeRequest) { - for (const hook of options.hooks.beforeRequest) { - hook(options); - } - } + const fakeGot = (request, options?: any) => { if (!(typeof request === 'string' || request instanceof Request) && request.url) { options = { ...request, @@ -22,6 +17,12 @@ const getFakeGot = (defaultOptions?: any) => { }; request = request.url; } + if (options?.hooks?.beforeRequest) { + for (const hook of options.hooks.beforeRequest) { + hook(options); + } + delete options.hooks; + } options = { ...defaultOptions, @@ -30,6 +31,7 @@ const getFakeGot = (defaultOptions?: any) => { if (options?.json && !options.body) { options.body = options.json; + delete options.json; } if (options?.form && !options.body) { const body = new FormData(); @@ -40,7 +42,11 @@ const getFakeGot = (defaultOptions?: any) => { if (!options.headers) { options.headers = {}; } - options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; + delete options.form; + } + if (options?.searchParams) { + request += '?' + new URLSearchParams(options.searchParams).toString(); + delete options.searchParams; } return gotofetch(request, options); From d190d9d7001c0afeccc5c5787fa3d1b6c503ba8e Mon Sep 17 00:00:00 2001 From: DIYgod Date: Tue, 26 Mar 2024 00:33:36 +0800 Subject: [PATCH 03/24] test: ofetch got --- lib/routes/bloomberg/utils.ts | 4 ++-- lib/routes/gov/chinatax/latest.ts | 2 +- lib/routes/line/utils.ts | 2 +- lib/routes/phoronix/index.ts | 2 +- lib/routes/wechat/feeddd.ts | 2 +- lib/routes/wfu/news.ts | 2 +- lib/utils/got.test.ts | 8 ++------ package.json | 2 +- pnpm-lock.yaml | 19 ++++++++----------- 9 files changed, 18 insertions(+), 25 deletions(-) diff --git a/lib/routes/bloomberg/utils.ts b/lib/routes/bloomberg/utils.ts index b48da1258..0bcbbefc7 100644 --- a/lib/routes/bloomberg/utils.ts +++ b/lib/routes/bloomberg/utils.ts @@ -99,7 +99,7 @@ const parseArticle = (item) => res = await got(apiUrl, { headers }); } catch (error) { // fallback - if (error.name && (error.name === 'HTTPError' || error.name === 'RequestError')) { + if (error.name && (error.name === 'HTTPError' || error.name === 'RequestError' || error.name === 'FetchError')) { try { res = await got(item.link, { headers }); } catch { @@ -214,7 +214,7 @@ const parseReactRendererPage = async (res, api, item) => { return await parseStoryJson(res.data, item); } catch (error) { // fallback - if (error.name && (error.name === 'HTTPError' || error.name === 'RequestError')) { + if (error.name && (error.name === 'HTTPError' || error.name === 'RequestError' || error.name === 'FetchError')) { return { title: item.title, link: item.link, diff --git a/lib/routes/gov/chinatax/latest.ts b/lib/routes/gov/chinatax/latest.ts index 6b54a4c73..9999b6e49 100644 --- a/lib/routes/gov/chinatax/latest.ts +++ b/lib/routes/gov/chinatax/latest.ts @@ -56,7 +56,7 @@ async function handler() { item.description = content('#fontzoom').html(); return item; } catch (error) { - if (error.name === 'HTTPError') { + if (error.name === 'HTTPError' || error.name === 'FetchError') { item.description = error.message; return item; } diff --git a/lib/routes/line/utils.ts b/lib/routes/line/utils.ts index e55c00d46..8d9712e48 100644 --- a/lib/routes/line/utils.ts +++ b/lib/routes/line/utils.ts @@ -29,7 +29,7 @@ const parseItems = (list, tryGet) => }); data = response.data; } catch (error) { - if (error instanceof got.HTTPError && error.response.statusCode === 404) { + if ((error.name === 'HTTPError' || error.name === 'FetchError') && error.response.statusCode === 404) { logger.error(`Error parsing article ${item.link}: ${error.message}`); return item; } diff --git a/lib/routes/phoronix/index.ts b/lib/routes/phoronix/index.ts index d4063906a..e4413fd4b 100644 --- a/lib/routes/phoronix/index.ts +++ b/lib/routes/phoronix/index.ts @@ -72,7 +72,7 @@ const webFetch = (url) => try { return webFetchCb(await got(url)); } catch (error) { - if (error.name === 'HTTPError' && error.response.statusCode === 404) { + if ((error.name === 'HTTPError' || error.name === 'FetchError') && error.response.statusCode === 404) { return '404'; } throw error; diff --git a/lib/routes/wechat/feeddd.ts b/lib/routes/wechat/feeddd.ts index d71c01a4f..97a4a52c3 100644 --- a/lib/routes/wechat/feeddd.ts +++ b/lib/routes/wechat/feeddd.ts @@ -13,7 +13,7 @@ export default async (ctx) => { try { response = await got(apiUrl); } catch (error) { - if (error.name === 'HTTPError' && error.response.statusCode === 404) { + if ((error.name === 'HTTPError' || error.name === 'FetchError') && error.response.statusCode === 404) { throw new Error('该公众号不存在,有关如何获取公众号 id,详见 https://docs.rsshub.app/routes/new-media#wei-xin-gong-zhong-hao-feeddd-lai-yuan'); } throw error; diff --git a/lib/routes/wfu/news.ts b/lib/routes/wfu/news.ts index eefca4f5b..b0bf76ff6 100644 --- a/lib/routes/wfu/news.ts +++ b/lib/routes/wfu/news.ts @@ -32,7 +32,7 @@ async function loadContent(link) { response = await got.get(link); } catch (error) { // 如果网络问题 直接出错 - if (error.name && (error.name === 'HTTPError' || error.name === 'RequestError')) { + if (error.name && (error.name === 'HTTPError' || error.name === 'RequestError' || error.name === 'FetchError')) { description = 'Page 404 Please Check!'; } return { description }; diff --git a/lib/utils/got.test.ts b/lib/utils/got.test.ts index 59d69c234..3b3453a18 100644 --- a/lib/utils/got.test.ts +++ b/lib/utils/got.test.ts @@ -34,7 +34,7 @@ describe('got', () => { try { await got.get('http://rsshub.test/testRerty'); } catch (error: any) { - expect(error.name).toBe('HTTPError'); + expect(error.name).toBe('FetchError'); } // retries @@ -52,11 +52,7 @@ describe('got', () => { test: 1, }, }); - expect(response1.statusCode).toBe(200); - // @ts-expect-error custom property - expect(response1.status).toBe(200); expect(response1.body).toBe('{"code": 0}'); - // @ts-expect-error custom property expect(response1.data.code).toBe(0); }); @@ -77,7 +73,7 @@ describe('got', () => { await got.get('http://rsshub.test/timeout'); throw new Error('Timeout Invalid'); } catch (error: any) { - expect(error.name).toBe('RequestError'); + expect(error.name).toBe('FetchError'); } expect(loggerSpy).toHaveBeenCalledWith(expect.stringContaining('http://rsshub.test/timeout')); diff --git a/package.json b/package.json index e4e3b7496..8b39596f5 100644 --- a/package.json +++ b/package.json @@ -164,7 +164,7 @@ "js-beautify": "1.15.1", "lint-staged": "15.2.2", "mockdate": "3.0.5", - "nock": "13.5.4", + "nock": "14.0.0-beta.5", "prettier": "3.2.5", "remark-parse": "11.0.0", "supertest": "6.3.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 004507bce..0fe2cbb25 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -344,8 +344,8 @@ devDependencies: specifier: 3.0.5 version: 3.0.5 nock: - specifier: 13.5.4 - version: 13.5.4 + specifier: 14.0.0-beta.5 + version: 14.0.0-beta.5 prettier: specifier: 3.2.5 version: 3.2.5 @@ -2072,7 +2072,7 @@ packages: engines: {node: '>= 14'} dependencies: eslint: 8.57.0 - jschardet: 3.1.0 + jschardet: 3.1.2 lodash: 4.17.21 utf8: 3.0.0 transitivePeerDependencies: @@ -5963,8 +5963,8 @@ packages: resolution: {integrity: sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==} dev: false - /jschardet@3.1.0: - resolution: {integrity: sha512-MND0yjRsoQ/3iFXce7lqV/iBmqH9oWGUTlty36obRBZjhFDWCLKjXgfxY75wYfwlW7EFqw52tyziy/q4WsQmrA==} + /jschardet@3.1.2: + resolution: {integrity: sha512-mw3CBZGzW8nUBPYhFU2ztZ/kJ6NClQUQVpyzvFMfznZsoC///ZQ30J2RCUanNsr5yF22LqhgYr/lj807/ZleWA==} engines: {node: '>=0.1.90'} dev: true @@ -6886,15 +6886,12 @@ packages: lower-case: 1.1.4 dev: false - /nock@13.5.4: - resolution: {integrity: sha512-yAyTfdeNJGGBFxWdzSKCBYxs5FxLbCg5X5Q4ets974hcQzG1+qCxvIyOo4j2Ry6MUlhWVMX4OoYDefAIIwupjw==} - engines: {node: '>= 10.13'} + /nock@14.0.0-beta.5: + resolution: {integrity: sha512-u255tf4DYvyErTlPZA9uTfXghiZZy+NflUOFONPVKZ5tP0yaHwKig28zyFOLhu8y5YcCRC+V5vDk4HHileh2iw==} + engines: {node: '>= 18'} dependencies: - debug: 4.3.4 json-stringify-safe: 5.0.1 propagate: 2.0.1 - transitivePeerDependencies: - - supports-color dev: true /node-fetch-native@1.6.4: From 07c891caa65cd776e918c6bcdbc0acdbe4b15407 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Tue, 26 Mar 2024 01:15:06 +0800 Subject: [PATCH 04/24] feat: remove timeout test --- lib/utils/got.test.ts | 26 -------------------------- lib/utils/ofetch.ts | 2 +- 2 files changed, 1 insertion(+), 27 deletions(-) diff --git a/lib/utils/got.test.ts b/lib/utils/got.test.ts index 3b3453a18..45a1be621 100644 --- a/lib/utils/got.test.ts +++ b/lib/utils/got.test.ts @@ -55,30 +55,4 @@ describe('got', () => { expect(response1.body).toBe('{"code": 0}'); expect(response1.data.code).toBe(0); }); - - it('timeout', async () => { - process.env.REQUEST_TIMEOUT = '500'; - - const { default: got } = await import('@/utils/got'); - nock('http://rsshub.test') - .get('/timeout') - .delay(600) - .reply(() => [200, '{"code": 0}']); - - const logger = (await import('@/utils/logger')).default; - // @ts-expect-error unused - const loggerSpy = vi.spyOn(logger, 'error').mockReturnValue({}); - - try { - await got.get('http://rsshub.test/timeout'); - throw new Error('Timeout Invalid'); - } catch (error: any) { - expect(error.name).toBe('FetchError'); - } - expect(loggerSpy).toHaveBeenCalledWith(expect.stringContaining('http://rsshub.test/timeout')); - - loggerSpy.mockRestore(); - - delete process.env.REQUEST_TIMEOUT; - }); }); diff --git a/lib/utils/ofetch.ts b/lib/utils/ofetch.ts index c02204862..d7a765e11 100644 --- a/lib/utils/ofetch.ts +++ b/lib/utils/ofetch.ts @@ -10,7 +10,7 @@ const rofetch = ofetch.create({ 'user-agent': config.ua, }, onRequestError({ request, error }) { - logger.error(`Request ${request.url} fail: ${error}`); + logger.error(`Request ${request} fail: ${error}`); }, }); From eec2a719534e9a832e92f350bc6aa295c1274686 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 27 Mar 2024 14:26:20 +0800 Subject: [PATCH 05/24] test: setup msw --- lib/config.test.ts | 6 -- lib/config.ts | 7 +- lib/setup.test.ts | 26 +++++++ package.json | 1 + pnpm-lock.yaml | 190 +++++++++++++++++++++++++++++++++++++++++++-- vitest.config.ts | 1 + 6 files changed, 215 insertions(+), 16 deletions(-) create mode 100644 lib/setup.test.ts diff --git a/lib/config.test.ts b/lib/config.test.ts index 1d59fd0f9..edf38055a 100644 --- a/lib/config.test.ts +++ b/lib/config.test.ts @@ -1,5 +1,4 @@ import { describe, expect, it, afterEach, vi } from 'vitest'; -import nock from 'nock'; afterEach(() => { vi.resetModules(); @@ -93,11 +92,6 @@ describe('config', () => { it('remote config', async () => { process.env.REMOTE_CONFIG = 'http://rsshub.test/config'; - nock(/rsshub\.test/) - .get('/config') - .reply(200, { - UA: 'test', - }); const { config } = await import('./config'); await new Promise((resolve) => setTimeout(resolve, 100)); expect(config.ua).toBe('test'); diff --git a/lib/config.ts b/lib/config.ts index d99935c45..2be41d9e5 100644 --- a/lib/config.ts +++ b/lib/config.ts @@ -1,6 +1,6 @@ import 'dotenv/config'; import randUserAgent from '@/utils/rand-user-agent'; -import got from 'got'; +import { ofetch } from 'ofetch'; let envs = process.env; @@ -634,9 +634,8 @@ const calculateValue = () => { calculateValue(); if (envs.REMOTE_CONFIG) { - got.get(envs.REMOTE_CONFIG) - .then(async (response) => { - const data = JSON.parse(response.body); + ofetch(envs.REMOTE_CONFIG) + .then(async (data) => { if (data) { envs = Object.assign(envs, data); calculateValue(); diff --git a/lib/setup.test.ts b/lib/setup.test.ts new file mode 100644 index 000000000..78a827a50 --- /dev/null +++ b/lib/setup.test.ts @@ -0,0 +1,26 @@ +import { beforeAll, afterAll, afterEach } from 'vitest'; +import { setupServer } from 'msw/node'; +import { http, HttpResponse } from 'msw'; + +const server = setupServer( + http.post(`https://api.openai.com/v1/chat/completions`, () => + HttpResponse.json({ + choices: [ + { + message: { + content: 'Summary of the article.', + }, + }, + ], + }) + ), + http.get(`http://rsshub.test/config`, () => + HttpResponse.json({ + UA: 'test', + }) + ) +); + +beforeAll(() => server.listen()); +afterAll(() => server.close()); +afterEach(() => server.resetHandlers()); diff --git a/package.json b/package.json index 8b39596f5..24a513b9f 100644 --- a/package.json +++ b/package.json @@ -164,6 +164,7 @@ "js-beautify": "1.15.1", "lint-staged": "15.2.2", "mockdate": "3.0.5", + "msw": "2.2.12", "nock": "14.0.0-beta.5", "prettier": "3.2.5", "remark-parse": "11.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0fe2cbb25..a950c73b7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -343,6 +343,9 @@ devDependencies: mockdate: specifier: 3.0.5 version: 3.0.5 + msw: + specifier: 2.2.12 + version: 2.2.12(typescript@5.4.3) nock: specifier: 14.0.0-beta.5 version: 14.0.0-beta.5 @@ -1664,6 +1667,18 @@ packages: resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==} dev: true + /@bundled-es-modules/cookie@2.0.0: + resolution: {integrity: sha512-Or6YHg/kamKHpxULAdSqhGqnWFneIXu1NKvvfBBzKGwpVsYuFIQ5aBPHDnnoR3ghW1nvSkALd+EF9iMtY7Vjxw==} + dependencies: + cookie: 0.5.0 + dev: true + + /@bundled-es-modules/statuses@1.0.1: + resolution: {integrity: sha512-yn7BklA5acgcBr+7w064fGV+SGIFySjCKpqjcWgBAIfrAkY+4GQTJJHQMeT3V/sgz23VTEVV8TtOmkvJAhFVfg==} + dependencies: + statuses: 2.0.1 + dev: true + /@colors/colors@1.6.0: resolution: {integrity: sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==} engines: {node: '>=0.1.90'} @@ -1966,6 +1981,39 @@ packages: lodash: 4.17.21 dev: true + /@inquirer/confirm@3.1.0: + resolution: {integrity: sha512-nH5mxoTEoqk6WpoBz80GMpDSm9jH5V9AF8n+JZAZfMzd9gHeEG9w1o3KawPRR72lfzpP+QxBHLkOKLEApwhDiQ==} + engines: {node: '>=18'} + dependencies: + '@inquirer/core': 7.1.0 + '@inquirer/type': 1.2.1 + dev: true + + /@inquirer/core@7.1.0: + resolution: {integrity: sha512-FRCiDiU54XHt5B/D8hX4twwZuzSP244ANHbu3R7CAsJfiv1dUOz24ePBgCZjygEjDUi6BWIJuk4eWLKJ7LATUw==} + engines: {node: '>=18'} + dependencies: + '@inquirer/type': 1.2.1 + '@types/mute-stream': 0.0.4 + '@types/node': 20.11.30 + '@types/wrap-ansi': 3.0.0 + ansi-escapes: 4.3.2 + chalk: 4.1.2 + cli-spinners: 2.9.2 + cli-width: 4.1.0 + figures: 3.2.0 + mute-stream: 1.0.0 + run-async: 3.0.0 + signal-exit: 4.1.0 + strip-ansi: 6.0.1 + wrap-ansi: 6.2.0 + dev: true + + /@inquirer/type@1.2.1: + resolution: {integrity: sha512-xwMfkPAxeo8Ji/IxfUSqzRi0/+F2GIqJmpc5/thelgMGsjNZcjDDRBO9TLXT1s/hdx/mK5QbVIvgoLIFgXhTMQ==} + engines: {node: '>=18'} + dev: true + /@ioredis/commands@1.2.0: resolution: {integrity: sha512-Sx1pU8EM64o2BrqNpEO1CNLtKQwyhuXuqyfH7oGKCk+1a33d2r5saW8zNwm3j6BTExtjrv2BxTgzzkMwts6vGg==} dev: false @@ -2079,6 +2127,23 @@ packages: - supports-color dev: true + /@mswjs/cookies@1.1.0: + resolution: {integrity: sha512-0ZcCVQxifZmhwNBoQIrystCb+2sWBY2Zw8lpfJBPCHGCA/HWqehITeCRVIv4VMy8MPlaHo2w2pTHFV2pFfqKPw==} + engines: {node: '>=18'} + dev: true + + /@mswjs/interceptors@0.26.13: + resolution: {integrity: sha512-1vsdtQfcd2ot01rGsxnbQn5fi3rY/Ien4zwacIrGi421UvYNBeoaVUg2qWYXt4S1t92K+vf46XjhUxC0+B9GtA==} + engines: {node: '>=18'} + dependencies: + '@open-draft/deferred-promise': 2.2.0 + '@open-draft/logger': 0.3.0 + '@open-draft/until': 2.1.0 + is-node-process: 1.2.0 + outvariant: 1.4.2 + strict-event-emitter: 0.5.1 + dev: true + /@nodelib/fs.scandir@2.1.5: resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} engines: {node: '>= 8'} @@ -2114,6 +2179,21 @@ packages: resolution: {integrity: sha512-XuySG1E38YScSJoMlqovLru4KTUNSjgVTIjyh7qMX6aNN5HY5Ct5LhRJdxO79JtTzKfzV/bnWpz+zquYrISsvw==} dev: true + /@open-draft/deferred-promise@2.2.0: + resolution: {integrity: sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA==} + dev: true + + /@open-draft/logger@0.3.0: + resolution: {integrity: sha512-X2g45fzhxH238HKO4xbSr7+wBS8Fvw6ixhTDuvLd5mqh6bJJCFAPwU9mPDxbcrRtfxv4u5IHCEH77BmxvXmmxQ==} + dependencies: + is-node-process: 1.2.0 + outvariant: 1.4.2 + dev: true + + /@open-draft/until@2.1.0: + resolution: {integrity: sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==} + dev: true + /@otplib/core@12.0.1: resolution: {integrity: sha512-4sGntwbA/AC+SbPhbsziRiD+jNDdIzsZ3JUyfZwjtKyc/wufl1pnSIaG4Uqx8ymPagujub0o92kgBnB89cuAMA==} dev: false @@ -2513,6 +2593,10 @@ packages: resolution: {integrity: sha512-V+pm3stv1Mvz8fSKJJod6CglNGVqEQ6OyuqitoDkWywEODM/eJd1eSuIp9xt6DrX8BWZ2eDSIzbw1tPCUTvGbQ==} dev: false + /@types/cookie@0.6.0: + resolution: {integrity: sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==} + dev: true + /@types/cookiejar@2.1.5: resolution: {integrity: sha512-he+DHOWReW0nghN24E1WUqM0efK4kI9oTqDm6XmK8ZPe2djZ90BSNdGnIyCLzCPw7/pogPlGbzI2wHGGmi4O/Q==} dev: true @@ -2641,6 +2725,12 @@ packages: /@types/ms@0.7.34: resolution: {integrity: sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==} + /@types/mute-stream@0.0.4: + resolution: {integrity: sha512-CPM9nzrCPPJHQNA9keH9CVkVI+WR5kMa+7XEs5jcGQ0VoAGnLv242w8lIVgwAEfmE4oufJRaTc9PNLQl0ioAow==} + dependencies: + '@types/node': 20.11.30 + dev: true + /@types/node-fetch@2.6.11: resolution: {integrity: sha512-24xFj9R5+rfQJLRyM56qh+wnVSYhyXC2tkoBndtY0U+vubqNsYXGjufB2nn8Q6gt0LrARwL6UBtMCSVCwl4B1g==} dependencies: @@ -2688,6 +2778,10 @@ packages: resolution: {integrity: sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ==} dev: true + /@types/statuses@2.0.5: + resolution: {integrity: sha512-jmIUGWrAiwu3dZpxntxieC+1n/5c3mjrImkmOSQ2NC5uP6cYO4aAZDdSmRcI5C1oiTmqlZGHC+/NmJrKogbP5A==} + dev: true + /@types/superagent@8.1.3: resolution: {integrity: sha512-R/CfN6w2XsixLb1Ii8INfn+BT9sGPvw74OavfkW4SwY+jeUcAwLZv2+bXLJkndnimxjEBm0RPHgcjW9pLCa8cw==} dependencies: @@ -2718,6 +2812,10 @@ packages: resolution: {integrity: sha512-dqId9J8K/vGi5Zr7oo212BGii5m3q5Hxlkwy3WpYuKPklmBEvsbMYYyLxAQpSffdLl/gdW0XUpKWFvYmyoWCoQ==} dev: true + /@types/wrap-ansi@3.0.0: + resolution: {integrity: sha512-ltIpx+kM7g/MLRZfkbL7EsCEjfzCcScLpkg37eXEtx5kmrAKBkTJwd1GIAjDSL8wTpM6Hzn5YO4pSb91BEwu1g==} + dev: true + /@types/yauzl@2.10.3: resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==} requiresBuild: true @@ -3731,6 +3829,11 @@ packages: engines: {node: '>= 10'} dev: true + /cli-width@4.1.0: + resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==} + engines: {node: '>= 12'} + dev: true + /clipboardy@1.2.2: resolution: {integrity: sha512-16KrBOV7bHmHdxcQiCvfUFYVFyEah4FI8vYT1Fr7CGSA4G+xBWMEfUEQJS1hxeHGtI9ju1Bzs9uXSbj5HZKArw==} engines: {node: '>=4'} @@ -3746,7 +3849,6 @@ packages: string-width: 4.2.3 strip-ansi: 6.0.1 wrap-ansi: 7.0.0 - dev: false /clone-deep@0.2.4: resolution: {integrity: sha512-we+NuQo2DHhSl+DP6jlUiAhyAjBQrYnpOk15rN6c6JSPScjiCLh8IbSU+VTcph6YS3o7mASE8a0+gbZ7ChLpgg==} @@ -3862,6 +3964,11 @@ packages: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} dev: true + /cookie@0.5.0: + resolution: {integrity: sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==} + engines: {node: '>= 0.6'} + dev: true + /cookiejar@2.1.4: resolution: {integrity: sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==} dev: true @@ -5119,7 +5226,6 @@ packages: /get-caller-file@2.0.5: resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} engines: {node: 6.* || 8.* || >= 10.*} - dev: false /get-east-asian-width@1.2.0: resolution: {integrity: sha512-2nk+7SIVb14QrgXFHcm84tD4bKQz0RxPuMT8Ag5KPOq7J5fEmAg0UbXdTOSHqNuHSU28k55qnceesxXRZGzKWA==} @@ -5347,6 +5453,11 @@ packages: resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} dev: true + /graphql@16.8.1: + resolution: {integrity: sha512-59LZHPdGZVh695Ud9lRzPBVTtlX9ZCV150Er2W43ro37wVof0ctenSaskPPjN7lVTIN8mSZt8PHUNKZuNQUuxw==} + engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0} + dev: true + /gtoken@7.1.0: resolution: {integrity: sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==} engines: {node: '>=14.0.0'} @@ -5421,6 +5532,10 @@ packages: hasBin: true dev: false + /headers-polyfill@4.0.3: + resolution: {integrity: sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ==} + dev: true + /heap@0.2.7: resolution: {integrity: sha512-2bsegYkkHO+h/9MGbn6KWcE45cHZgPANo5LXF7EvWdT0yT2EguSVO1nDgU5c8+ZOPwp2vMNa7YFsJhVcDR9Sdg==} dev: false @@ -5813,6 +5928,10 @@ packages: engines: {node: '>=0.10.0'} dev: false + /is-node-process@1.2.0: + resolution: {integrity: sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw==} + dev: true + /is-number@7.0.0: resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} engines: {node: '>=0.12.0'} @@ -6858,10 +6977,46 @@ packages: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} dev: false + /msw@2.2.12(typescript@5.4.3): + resolution: {integrity: sha512-thmjEipUvr+XGawcNOh4T8+T2TN3qKWPfF0Ewx6ub1HIATXBsjOhnjV6Wx2BmmFThKEtYYC+RygrvkpG4DzoZw==} + engines: {node: '>=18'} + hasBin: true + requiresBuild: true + peerDependencies: + typescript: '>= 4.7.x' + peerDependenciesMeta: + typescript: + optional: true + dependencies: + '@bundled-es-modules/cookie': 2.0.0 + '@bundled-es-modules/statuses': 1.0.1 + '@inquirer/confirm': 3.1.0 + '@mswjs/cookies': 1.1.0 + '@mswjs/interceptors': 0.26.13 + '@open-draft/until': 2.1.0 + '@types/cookie': 0.6.0 + '@types/statuses': 2.0.5 + chalk: 4.1.2 + graphql: 16.8.1 + headers-polyfill: 4.0.3 + is-node-process: 1.2.0 + outvariant: 1.4.2 + path-to-regexp: 6.2.1 + strict-event-emitter: 0.5.1 + type-fest: 4.14.0 + typescript: 5.4.3 + yargs: 17.7.2 + dev: true + /mute-stream@0.0.8: resolution: {integrity: sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==} dev: true + /mute-stream@1.0.0: + resolution: {integrity: sha512-avsJQhyd+680gKXyG/sQc0nXaC6rBkPOfyHYcFb9+hdkqQkR9bdnkJ0AMZhke0oesPqIO+mFFJ+IdBc7mst4IA==} + engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} + dev: true + /nanoid@3.3.7: resolution: {integrity: sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -7124,6 +7279,10 @@ packages: '@otplib/preset-v11': 12.0.1 dev: false + /outvariant@1.4.2: + resolution: {integrity: sha512-Ou3dJ6bA/UJ5GVHxah4LnqDwZRwAmWxrG3wtrHrbGnP4RnLCtA64A4F+ae7Y8ww660JaddSoArUR5HjipWSHAQ==} + dev: true + /p-cancelable@3.0.0: resolution: {integrity: sha512-mlVgR3PGuzlo0MmTdk4cXqXWlwQDLnONTAg6sm62XkMJEiRxN3GL3SffkYvqwonbkJBcrI7Uvv5Zh9yjvn2iUw==} engines: {node: '>=12.20'} @@ -7290,6 +7449,10 @@ packages: minipass: 5.0.0 dev: true + /path-to-regexp@6.2.1: + resolution: {integrity: sha512-JLyh7xT1kizaEvcaXOQwOc2/Yhw6KZOvPf1S8401UyLk86CU79LN3vl7ztXGm/pZ+YjoyAJ4rxmHwbkBXJX+yw==} + dev: true + /path-type@4.0.0: resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==} engines: {node: '>=8'} @@ -7908,7 +8071,6 @@ packages: /require-directory@2.1.1: resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} engines: {node: '>=0.10.0'} - dev: false /requires-port@1.0.0: resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==} @@ -8017,6 +8179,11 @@ packages: engines: {node: '>=0.12.0'} dev: true + /run-async@3.0.0: + resolution: {integrity: sha512-540WwVDOMxA6dN6We19EcT9sc3hkXPw5mzRNGM3FkdN/vtE9NFvj5lFAPNwUDmJjXidm3v7TC1cTE7t17Ulm1Q==} + engines: {node: '>=0.12.0'} + dev: true + /run-parallel@1.2.0: resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} dependencies: @@ -8341,6 +8508,11 @@ packages: resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==} dev: false + /statuses@2.0.1: + resolution: {integrity: sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==} + engines: {node: '>= 0.8'} + dev: true + /std-env@3.7.0: resolution: {integrity: sha512-JPbdCEQLj1w5GilpiHAx3qJvFndqybBysA3qUOnznweH4QbNYUsW/ea8QzSrnh0vNsezMMw5bcVool8lM0gwzg==} dev: true @@ -8369,6 +8541,10 @@ packages: bare-events: 2.2.0 dev: false + /strict-event-emitter@0.5.1: + resolution: {integrity: sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ==} + dev: true + /strict-uri-encode@2.0.0: resolution: {integrity: sha512-QwiXZgpRcKkhTj2Scnn++4PKtWsH0kpzZ62L2R6c/LUVYv7hVnZqcg2+sMuT6R7Jusu1vviK/MFsu6kNJfWlEQ==} engines: {node: '>=4'} @@ -8870,6 +9046,11 @@ packages: engines: {node: '>=14.16'} dev: true + /type-fest@4.14.0: + resolution: {integrity: sha512-on5/Cw89wwqGZQu+yWO0gGMGu8VNxsaW9SB2HE8yJjllEk7IDTwnSN1dUVldYILhYPN5HzD7WAaw2cc/jBfn0Q==} + engines: {node: '>=16'} + dev: true + /type@1.2.0: resolution: {integrity: sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg==} dev: false @@ -9434,7 +9615,6 @@ packages: /y18n@5.0.8: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} - dev: false /yaeti@0.0.6: resolution: {integrity: sha512-MvQa//+KcZCUkBTIC9blM+CU9J2GzuTytsOUwf2lidtvkx/6gnEp1QvJv34t9vdjhFmha/mUiNDbN0D0mJWdug==} @@ -9475,7 +9655,6 @@ packages: /yargs-parser@21.1.1: resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} engines: {node: '>=12'} - dev: false /yargs@17.7.2: resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==} @@ -9488,7 +9667,6 @@ packages: string-width: 4.2.3 y18n: 5.0.8 yargs-parser: 21.1.1 - dev: false /yauzl@2.10.0: resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==} diff --git a/vitest.config.ts b/vitest.config.ts index 2a4074bea..bc2deb5f5 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -10,5 +10,6 @@ export default defineConfig({ exclude: ['lib/routes/**', 'lib/routes-deprecated/**'], }, testTimeout: 10000, + setupFiles: ['./lib/setup.test.ts'], }, }); From 8c0534393f9eb4366a0cb048d55b05d77386b3f8 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 27 Mar 2024 14:40:42 +0800 Subject: [PATCH 06/24] feat: use ofetch in parameter common-config wechat-mp --- lib/middleware/parameter.ts | 11 +++++------ lib/utils/common-config.ts | 12 ++++++------ lib/utils/wechat-mp.ts | 14 ++++++-------- 3 files changed, 17 insertions(+), 20 deletions(-) diff --git a/lib/middleware/parameter.ts b/lib/middleware/parameter.ts index 193388912..025f6b405 100644 --- a/lib/middleware/parameter.ts +++ b/lib/middleware/parameter.ts @@ -1,7 +1,7 @@ import * as entities from 'entities'; import { load, type CheerioAPI, type Element } from 'cheerio'; import { simplecc } from 'simplecc-wasm'; -import got from '@/utils/got'; +import ofetch from '@/utils/ofetch'; import { config } from '@/config'; import { RE2JS } from 're2js'; import markdownit from 'markdown-it'; @@ -34,8 +34,9 @@ const resolveRelativeLink = ($: CheerioAPI, elem: Element, attr: string, baseUrl const summarizeArticle = async (articleText: string) => { const apiUrl = `${config.openai.endpoint}/chat/completions`; - const response = await got.post(apiUrl, { - json: { + const response = await ofetch(apiUrl, { + method: 'POST', + body: { model: config.openai.model, max_tokens: config.openai.maxTokens, messages: [ @@ -49,7 +50,6 @@ const summarizeArticle = async (articleText: string) => { }, }); - // @ts-expect-error custom field return response.data.choices[0].message.content; }; @@ -305,8 +305,7 @@ const middleware: MiddlewareHandler = async (ctx, next) => { if (link) { // if parser failed, return default description and not report error try { - // @ts-expect-error custom field - const { data: res } = await got(link); + const res = await ofetch(link); const $ = load(res); const result = await Parser.parse(link, { html: $.html(), diff --git a/lib/utils/common-config.ts b/lib/utils/common-config.ts index 65e84d209..74d1b7c2b 100644 --- a/lib/utils/common-config.ts +++ b/lib/utils/common-config.ts @@ -1,5 +1,5 @@ -import cheerio from 'cheerio'; -import got from '@/utils/got'; +import { load } from 'cheerio'; +import ofetch from '@/utils/ofetch'; import iconv from 'iconv-lite'; function transElemText($, prop) { @@ -37,8 +37,8 @@ function getProp(data, prop, $) { } async function buildData(data) { - const response = await got.get(data.url); - const contentType = response.headers['content-type'] || ''; + const response = await ofetch.raw(data.url); + const contentType = response.headers.get('content-type') || ''; // 若没有指定编码,则默认utf-8 let charset = 'utf-8'; for (const attr of contentType.split(';')) { @@ -47,8 +47,8 @@ async function buildData(data) { } } // @ts-expect-error custom property - const responseData = charset === 'utf-8' ? response.data : iconv.decode((await got.get({ url: data.url, responseType: 'buffer' })).data, charset); - const $ = cheerio.load(responseData); + const responseData = charset === 'utf-8' ? response._data : iconv.decode(await ofetch(data.url, { responseType: 'buffer' }), charset); + const $ = load(responseData); const $item = $(data.item.item); // 这里应该是可以通过参数注入一些代码的,不过应该无伤大雅 return { diff --git a/lib/utils/wechat-mp.ts b/lib/utils/wechat-mp.ts index ae03957b8..0615ab1c9 100644 --- a/lib/utils/wechat-mp.ts +++ b/lib/utils/wechat-mp.ts @@ -25,7 +25,7 @@ * For more details of these functions, please refer to the jsDoc in the source code. */ -import got from '@/utils/got'; +import ofetch from '@/utils/ofetch'; import { load, type Cheerio, type Element } from 'cheerio'; import { parseDate } from '@/utils/parse-date'; import cache from '@/utils/cache'; @@ -196,9 +196,8 @@ const normalizeUrl = (url, bypassHostCheck = false) => { const fetchArticle = (url, bypassHostCheck = false) => { url = normalizeUrl(url, bypassHostCheck); return cache.tryGet(url, async () => { - const response = await got(url); - // @ts-expect-error custom field - const $ = load(response.data); + const data = await ofetch(url); + const $ = load(data); const title = ($('meta[property="og:title"]').attr('content') || '').replaceAll('\\r', '').replaceAll('\\n', ' '); const author = $('meta[name=author]').attr('content'); @@ -209,9 +208,8 @@ const fetchArticle = (url, bypassHostCheck = false) => { const originalUrl = detectOriginalArticleUrl($); if (originalUrl) { // try to fetch the description from the original article - const originalResponse = await got(normalizeUrl(originalUrl, bypassHostCheck)); - // @ts-expect-error custom field - const original$ = load(originalResponse.data); + const data = await ofetch(normalizeUrl(originalUrl, bypassHostCheck)); + const original$ = load(data); description += fixArticleContent(original$('#js_content')); } @@ -230,7 +228,7 @@ const fetchArticle = (url, bypassHostCheck = false) => { let mpName = $('.profile_nickname').first().text(); mpName = mpName && mpName.trim(); - return { title, author, description, summary, pubDate, mpName, link: response.url }; + return { title, author, description, summary, pubDate, mpName, link: url }; }) as Promise<{ title: string; author: string; From 760f48b8cf499143859c6e15ce07f30f5171f440 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 27 Mar 2024 14:49:43 +0800 Subject: [PATCH 07/24] test: fix common-config test --- lib/setup.test.ts | 18 ++++++++++++++++-- lib/utils/common-config.test.ts | 18 ------------------ 2 files changed, 16 insertions(+), 20 deletions(-) diff --git a/lib/setup.test.ts b/lib/setup.test.ts index 78a827a50..df52b0f67 100644 --- a/lib/setup.test.ts +++ b/lib/setup.test.ts @@ -1,4 +1,4 @@ -import { beforeAll, afterAll, afterEach } from 'vitest'; +import { afterAll, afterEach } from 'vitest'; import { setupServer } from 'msw/node'; import { http, HttpResponse } from 'msw'; @@ -18,9 +18,23 @@ const server = setupServer( HttpResponse.json({ UA: 'test', }) + ), + http.get(`http://rsshub.test/buildData`, () => + HttpResponse.text(`
+
    +
  • + 1 +
    RSSHub1
    +
  • +
  • + 2 +
    RSSHub2
    +
  • +
+
`) ) ); +server.listen(); -beforeAll(() => server.listen()); afterAll(() => server.close()); afterEach(() => server.resetHandlers()); diff --git a/lib/utils/common-config.test.ts b/lib/utils/common-config.test.ts index 84b4c15c9..57839fd38 100644 --- a/lib/utils/common-config.test.ts +++ b/lib/utils/common-config.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest'; import configUtils, { transElemText, replaceParams, getProp } from '@/utils/common-config'; -import nock from 'nock'; describe('index', () => { it('transElemText', () => { @@ -40,23 +39,6 @@ describe('index', () => { }); it('buildData', async () => { - nock('http://rsshub.test') - .get('/buildData') - .reply(() => [ - 200, - `
-
    -
  • - 1 -
    RSSHub1
    -
  • -
  • - 2 -
    RSSHub2
    -
  • -
-
`, - ]); const data = await configUtils({ link: 'http://rsshub.test/buildData', url: 'http://rsshub.test/buildData', From 3016a2f44fe2bd01857e18b2892415eb82f57cff Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 27 Mar 2024 14:53:43 +0800 Subject: [PATCH 08/24] test: fix wechat-mp test --- lib/setup.test.ts | 15 +++++++++++++++ lib/utils/wechat-mp.test.ts | 17 ----------------- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/lib/setup.test.ts b/lib/setup.test.ts index df52b0f67..a3120aca6 100644 --- a/lib/setup.test.ts +++ b/lib/setup.test.ts @@ -32,6 +32,21 @@ const server = setupServer( `) + ), + http.get(`https://mp.weixin.qq.com/rsshub_test/wechatMp_fetchArticle`, () => + HttpResponse.text( + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '
mpName
\n' + + '' + ) ) ); server.listen(); diff --git a/lib/utils/wechat-mp.test.ts b/lib/utils/wechat-mp.test.ts index b4811e84c..e700a6e42 100644 --- a/lib/utils/wechat-mp.test.ts +++ b/lib/utils/wechat-mp.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest'; import { load } from 'cheerio'; -import nock from 'nock'; import { fixArticleContent, fetchArticle, finishArticleItem, normalizeUrl } from '@/utils/wechat-mp'; // date from the cache will be an ISO8601 string, so we need to use this function @@ -91,22 +90,6 @@ describe('wechat-mp', () => { it('fetchArticle_&_finishArticleItem', async () => { const ct = 1_636_626_300; - const exampleMpArticlePage = - '\n' + - '\n' + - '\n' + - '\n' + - '\n' + - '\n' + - '
mpName
\n' + - ''; - - nock('https://mp.weixin.qq.com') - .get('/rsshub_test/wechatMp_fetchArticle') - .reply(() => [200, exampleMpArticlePage]); const httpsUrl = 'https://mp.weixin.qq.com/rsshub_test/wechatMp_fetchArticle'; const httpUrl = httpsUrl.replace(/^https:\/\//, 'http://'); From bcd5f6ff8bb488f37302070702e8728288e209aa Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 27 Mar 2024 15:37:51 +0800 Subject: [PATCH 09/24] test: rand-user-agent test --- lib/setup.test.ts | 5 +++++ lib/utils/rand-user-agent.test.ts | 23 ++++------------------- 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/lib/setup.test.ts b/lib/setup.test.ts index a3120aca6..8e19dfc2c 100644 --- a/lib/setup.test.ts +++ b/lib/setup.test.ts @@ -47,6 +47,11 @@ const server = setupServer( `var ct = "${1_636_626_300}";\n` + '' ) + ), + http.get(`http://rsshub.test/ua`, ({ request }) => + HttpResponse.json({ + ua: request.headers.get('user-agent'), + }) ) ); server.listen(); diff --git a/lib/utils/rand-user-agent.test.ts b/lib/utils/rand-user-agent.test.ts index 4ccea6ad9..91169f159 100644 --- a/lib/utils/rand-user-agent.test.ts +++ b/lib/utils/rand-user-agent.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from 'vitest'; import got from '@/utils/got'; import { config } from '@/config'; -import nock from 'nock'; import randUserAgent from '@/utils/rand-user-agent'; const mobileUa = randUserAgent({ browser: 'mobile safari', os: 'ios', device: 'mobile' }); @@ -23,30 +22,16 @@ describe('rand-user-agent', () => { }); it('should has default random ua', async () => { - nock('https://rsshub.test') - .get('/test') - .reply(function () { - expect(this.req.headers['user-agent']).toBe(config.ua); - expect(this.req.headers['user-agent']).not.toBe(mobileUa); - expect(this.req.headers['user-agent']).not.toBe('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'); - return [200, '']; - }); - await got('https://rsshub.test/test'); + const { data } = await got('http://rsshub.test/ua'); + expect(data.ua).toBe(config.ua); }); it('should match ua configurated', async () => { - nock('https://rsshub.test') - .get('/test') - .reply(function () { - return [200, { ua: this.req.headers['user-agent'] }]; - }); - - const resonse = await got('https://rsshub.test/test', { + const { data } = await got('http://rsshub.test/ua', { headers: { 'user-agent': mobileUa, }, }); - // @ts-expect-error custom field - expect(resonse.data.ua).toBe(mobileUa); + expect(data.ua).toBe(mobileUa); }); }); From a87ec364508f1b524241a8774c12d3244f26e8c2 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 27 Mar 2024 16:15:39 +0800 Subject: [PATCH 10/24] test: got test --- lib/setup.test.ts | 18 ++++++++++++- lib/utils/got.test.ts | 63 +++++++++++++++++++------------------------ 2 files changed, 45 insertions(+), 36 deletions(-) diff --git a/lib/setup.test.ts b/lib/setup.test.ts index 8e19dfc2c..2946cdd13 100644 --- a/lib/setup.test.ts +++ b/lib/setup.test.ts @@ -52,9 +52,25 @@ const server = setupServer( HttpResponse.json({ ua: request.headers.get('user-agent'), }) - ) + ), + http.post(`http://rsshub.test/form-post`, async ({ request }) => { + const formData = await request.formData(); + return HttpResponse.json({ + test: formData.get('test'), + }); + }), + http.post(`http://rsshub.test/json-post`, async ({ request }) => { + const jsonData = (await request.json()) as { + test: string; + }; + return HttpResponse.json({ + test: jsonData?.test, + }); + }) ); server.listen(); afterAll(() => server.close()); afterEach(() => server.resetHandlers()); + +export default server; diff --git a/lib/utils/got.test.ts b/lib/utils/got.test.ts index 45a1be621..5b65725fc 100644 --- a/lib/utils/got.test.ts +++ b/lib/utils/got.test.ts @@ -1,38 +1,26 @@ -import { describe, expect, it, afterEach, vi } from 'vitest'; -import nock from 'nock'; - -afterEach(() => { - vi.resetModules(); -}); +import { describe, expect, it, vi } from 'vitest'; +import { http, HttpResponse } from 'msw'; +import got from '@/utils/got'; +import { config } from '@/config'; describe('got', () => { it('headers', async () => { - const { default: got } = await import('@/utils/got'); - const { config } = await import('@/config'); - nock('http://rsshub.test') - .get('/test') - .reply(function () { - expect(this.req.headers['user-agent']).toBe(config.ua); - return [200, '']; - }); - - await got.get('http://rsshub.test/test'); + const { data } = await got('http://rsshub.test/ua'); + expect(data.ua).toBe(config.ua); }); it('retry', async () => { - const { default: got } = await import('@/utils/got'); - const { config } = await import('@/config'); const requestRun = vi.fn(); - nock('http://rsshub.test') - .get('/testRerty') - .times(config.requestRetry + 1) - .reply(() => { + const { default: server } = await import('@/setup.test'); + server.use( + http.get(`http://rsshub.test/retry-test`, () => { requestRun(); - return [503, '0']; - }); + return HttpResponse.error(); + }) + ); try { - await got.get('http://rsshub.test/testRerty'); + await got.get('http://rsshub.test/retry-test'); } catch (error: any) { expect(error.name).toBe('FetchError'); } @@ -41,18 +29,23 @@ describe('got', () => { expect(requestRun).toHaveBeenCalledTimes(config.requestRetry + 1); }); - it('axios', async () => { - const { default: got } = await import('@/utils/got'); - nock('http://rsshub.test') - .post('/post') - .reply(() => [200, '{"code": 0}']); - - const response1 = await got.post('http://rsshub.test/post', { + it('form-post', async () => { + const response = await got.post('http://rsshub.test/form-post', { form: { - test: 1, + test: 'rsshub', }, }); - expect(response1.body).toBe('{"code": 0}'); - expect(response1.data.code).toBe(0); + expect(response.body).toBe('{"test":"rsshub"}'); + expect(response.data.test).toBe('rsshub'); + }); + + it('json-post', async () => { + const response = await got.post('http://rsshub.test/json-post', { + json: { + test: 'rsshub', + }, + }); + expect(response.body).toBe('{"test":"rsshub"}'); + expect(response.data.test).toBe('rsshub'); }); }); From 2a366ef56dd1919143a3ed0d844b5045501ea737 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 27 Mar 2024 16:18:37 +0800 Subject: [PATCH 11/24] test: rss-parser test --- lib/setup.test.ts | 3 ++- lib/utils/rss-parser.test.ts | 16 ++++------------ 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/lib/setup.test.ts b/lib/setup.test.ts index 2946cdd13..4e39c68df 100644 --- a/lib/setup.test.ts +++ b/lib/setup.test.ts @@ -66,7 +66,8 @@ const server = setupServer( return HttpResponse.json({ test: jsonData?.test, }); - }) + }), + http.get(`http://rsshub.test/rss`, () => HttpResponse.text('')) ); server.listen(); diff --git a/lib/utils/rss-parser.test.ts b/lib/utils/rss-parser.test.ts index 20b6664b5..0b09b61ea 100644 --- a/lib/utils/rss-parser.test.ts +++ b/lib/utils/rss-parser.test.ts @@ -1,17 +1,9 @@ import { describe, expect, it } from 'vitest'; import parser from '@/utils/rss-parser'; -import { config } from '@/config'; -import nock from 'nock'; -describe('got', () => { - it('headers', async () => { - nock('http://rsshub.test') - .get('/test') - .reply(function () { - expect(this.req.headers['user-agent']).toBe(config.ua); - return [200, '']; - }); - - await parser.parseURL('http://rsshub.test/test'); +describe('rss-parser', () => { + it('rss', async () => { + const result = await parser.parseURL('http://rsshub.test/rss'); + expect(result).toBeTruthy(); }); }); From 23104cd1f69c2f16297cf1cdb1315c44888b6976 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Thu, 28 Mar 2024 02:42:24 +0800 Subject: [PATCH 12/24] feat: use undici --- lib/utils/ofetch.ts | 7 ++----- package.json | 1 + pnpm-lock.yaml | 8 ++++++++ 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/lib/utils/ofetch.ts b/lib/utils/ofetch.ts index d7a765e11..31e6574c8 100644 --- a/lib/utils/ofetch.ts +++ b/lib/utils/ofetch.ts @@ -1,14 +1,11 @@ -import { ofetch } from 'ofetch'; +import { createFetch } from 'ofetch'; import { config } from '@/config'; import logger from '@/utils/logger'; -const rofetch = ofetch.create({ +const rofetch = createFetch().create({ retry: config.requestRetry, retryDelay: 1000, timeout: config.requestTimeout, - headers: { - 'user-agent': config.ua, - }, onRequestError({ request, error }) { logger.error(`Request ${request} fail: ${error}`); }, diff --git a/package.json b/package.json index 24a513b9f..dce2339ee 100644 --- a/package.json +++ b/package.json @@ -117,6 +117,7 @@ "tough-cookie": "4.1.3", "tsx": "4.7.1", "twitter-api-v2": "1.16.1", + "undici": "6.10.2", "uuid": "9.0.1", "winston": "3.12.0", "xxhash-wasm": "1.0.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a950c73b7..cf4280dcf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -206,6 +206,9 @@ dependencies: twitter-api-v2: specifier: 1.16.1 version: 1.16.1 + undici: + specifier: 6.10.2 + version: 6.10.2 uuid: specifier: 9.0.1 version: 9.0.1 @@ -9101,6 +9104,11 @@ packages: /undici-types@5.26.5: resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==} + /undici@6.10.2: + resolution: {integrity: sha512-HcVuBy7ACaDejIMdwCzAvO22OsiE6ir6ziTIr9kAE0vB+PheVe29ZvRN8p7FXCO2uZHTjEoUs5bPiFpuc/hwwQ==} + engines: {node: '>=18.0'} + dev: false + /unicode-canonical-property-names-ecmascript@2.0.0: resolution: {integrity: sha512-yY5PpDlfVIU5+y/BSCxAJRBIS1Zc2dDG3Ujq+sR0U+JjUevW2JhocOF+soROYDSaAezOzOKuyyixhD6mBknSmQ==} engines: {node: '>=4'} From 759c03cd23547573eb68088bad422d600c17caee Mon Sep 17 00:00:00 2001 From: DIYgod Date: Thu, 28 Mar 2024 02:45:08 +0800 Subject: [PATCH 13/24] feat: intercept undici and use fetch dispatcher --- lib/app.tsx | 2 +- lib/utils/proxy/index.ts | 7 +++ lib/utils/request-interceptor.ts | 80 ++++++++++++++++++++++++++++++++ 3 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 lib/utils/request-interceptor.ts diff --git a/lib/app.tsx b/lib/app.tsx index c3b27ab41..f2a549eef 100644 --- a/lib/app.tsx +++ b/lib/app.tsx @@ -1,4 +1,4 @@ -import '@/utils/request-wrapper'; +import '@/utils/request-interceptor'; import { Hono } from 'hono'; diff --git a/lib/utils/proxy/index.ts b/lib/utils/proxy/index.ts index b49730693..016501b2a 100644 --- a/lib/utils/proxy/index.ts +++ b/lib/utils/proxy/index.ts @@ -2,6 +2,7 @@ import { config } from '@/config'; import { PacProxyAgent } from 'pac-proxy-agent'; import { HttpsProxyAgent } from 'https-proxy-agent'; import { SocksProxyAgent } from 'socks-proxy-agent'; +import { ProxyAgent } from 'undici'; const proxyIsPAC = config.pacUri || config.pacScript; @@ -24,11 +25,16 @@ if (proxyIsPAC) { } let agent: PacProxyAgent | HttpsProxyAgent | SocksProxyAgent | null = null; +let dispatcher: ProxyAgent | null = null; if (proxyIsPAC) { agent = new PacProxyAgent(`pac+${proxyUri}`); } else if (proxyUri) { if (proxyUri.startsWith('http')) { agent = new HttpsProxyAgent(proxyUri); + dispatcher = new ProxyAgent({ + uri: proxyUri, + token: proxyObj?.auth ? `Basic ${proxyObj.auth}` : undefined, + }); } else if (proxyUri.startsWith('socks')) { agent = new SocksProxyAgent(proxyUri); } @@ -36,6 +42,7 @@ if (proxyIsPAC) { export default { agent, + dispatcher, proxyUri, proxyObj, proxyUrlHandler, diff --git a/lib/utils/request-interceptor.ts b/lib/utils/request-interceptor.ts new file mode 100644 index 000000000..c85ba01cd --- /dev/null +++ b/lib/utils/request-interceptor.ts @@ -0,0 +1,80 @@ +import { setupServer } from 'msw/node'; +import { http, passthrough } from 'msw'; +import logger from '@/utils/logger'; +import { config } from '@/config'; +import { fetch, Headers, FormData, ProxyAgent, Request, RequestInfo, RequestInit, Response } from 'undici'; +import proxy from '@/utils/proxy'; +import type nodehttp from 'node:http'; + +class ExtendedRequest extends Request { + public dispatcher: ProxyAgent | undefined; + public agent: nodehttp.ClientRequestArgs['agent']; + + constructor(input: RequestInfo, init?: RequestInit & nodehttp.ClientRequestArgs) { + super(input, init); + this.dispatcher = init?.dispatcher; // fetch + this.agent = init?.agent; // http + } +} + +Object.defineProperties(globalThis, { + fetch: { value: fetch, writable: true }, + Headers: { value: Headers }, + FormData: { value: FormData }, + Request: { value: ExtendedRequest }, + Response: { value: Response }, +}); + +const handler = (request: ExtendedRequest) => { + request.headers.set('debug', '1'); + // ua + if (!request.headers.get('user-agent')) { + request.headers.set('user-agent', config.ua); + } + + // accept + if (!request.headers.get('accept')) { + request.headers.set('accept', '*/*'); + } + + // referer + if (!request.headers.get('referer')) { + try { + const urlHandler = new URL(request.url); + request.headers.set('referer', urlHandler.origin); + } catch { + // ignore + } + } + + // proxy + if (!request.dispatcher && !request.agent && proxy.dispatcher) { + const proxyRegex = new RegExp(proxy.proxyObj.url_regex); + let urlHandler; + try { + urlHandler = new URL(request.url); + } catch { + // ignore + } + + if (proxyRegex.test(request.url) && request.url.startsWith('http') && !(urlHandler && urlHandler.host === proxy.proxyUrlHandler?.host)) { + // fetch + request.dispatcher = proxy.dispatcher; + + // http + request.agent = proxy.agent || undefined; + if (proxy.proxyObj.auth) { + request.headers.set('Proxy-Authorization', `Basic ${proxy.proxyObj.auth}`); + } + } + } +}; + +const server = setupServer( + http.all('*', ({ request }) => { + logger.debug(`Outgoing request: ${request.method} ${request.url}`); + handler(request); + return passthrough(); + }) +); +server.listen(); From 176e77301309f7097c255fc96a820c52c5d4845d Mon Sep 17 00:00:00 2001 From: DIYgod Date: Thu, 28 Mar 2024 19:39:29 +0800 Subject: [PATCH 14/24] fix: setting dispatcher in options --- lib/utils/request-interceptor.ts | 39 ++++++++++---------------------- package.json | 2 +- pnpm-lock.yaml | 8 +++---- 3 files changed, 17 insertions(+), 32 deletions(-) diff --git a/lib/utils/request-interceptor.ts b/lib/utils/request-interceptor.ts index c85ba01cd..5125e7b48 100644 --- a/lib/utils/request-interceptor.ts +++ b/lib/utils/request-interceptor.ts @@ -1,32 +1,19 @@ import { setupServer } from 'msw/node'; -import { http, passthrough } from 'msw'; +import { http } from 'msw'; import logger from '@/utils/logger'; import { config } from '@/config'; -import { fetch, Headers, FormData, ProxyAgent, Request, RequestInfo, RequestInit, Response } from 'undici'; +import { fetch, Headers, FormData, Request, Response } from 'undici'; import proxy from '@/utils/proxy'; -import type nodehttp from 'node:http'; - -class ExtendedRequest extends Request { - public dispatcher: ProxyAgent | undefined; - public agent: nodehttp.ClientRequestArgs['agent']; - - constructor(input: RequestInfo, init?: RequestInit & nodehttp.ClientRequestArgs) { - super(input, init); - this.dispatcher = init?.dispatcher; // fetch - this.agent = init?.agent; // http - } -} Object.defineProperties(globalThis, { fetch: { value: fetch, writable: true }, Headers: { value: Headers }, FormData: { value: FormData }, - Request: { value: ExtendedRequest }, + Request: { value: Request }, Response: { value: Response }, }); -const handler = (request: ExtendedRequest) => { - request.headers.set('debug', '1'); +const handler = (request: globalThis.Request, options: NonNullable[1]>) => { // ua if (!request.headers.get('user-agent')) { request.headers.set('user-agent', config.ua); @@ -48,7 +35,7 @@ const handler = (request: ExtendedRequest) => { } // proxy - if (!request.dispatcher && !request.agent && proxy.dispatcher) { + if (!options.dispatcher && proxy.dispatcher) { const proxyRegex = new RegExp(proxy.proxyObj.url_regex); let urlHandler; try { @@ -59,22 +46,20 @@ const handler = (request: ExtendedRequest) => { if (proxyRegex.test(request.url) && request.url.startsWith('http') && !(urlHandler && urlHandler.host === proxy.proxyUrlHandler?.host)) { // fetch - request.dispatcher = proxy.dispatcher; - - // http - request.agent = proxy.agent || undefined; - if (proxy.proxyObj.auth) { - request.headers.set('Proxy-Authorization', `Basic ${proxy.proxyObj.auth}`); - } + options.dispatcher = proxy.dispatcher; } } }; const server = setupServer( + // @ts-expect-error http.all('*', ({ request }) => { logger.debug(`Outgoing request: ${request.method} ${request.url}`); - handler(request); - return passthrough(); + const requestClone = request.clone(); + const options = {}; + handler(requestClone, options); + // @ts-expect-error + return fetch(requestClone, options); }) ); server.listen(); diff --git a/package.json b/package.json index 77124348d..a78cdc794 100644 --- a/package.json +++ b/package.json @@ -167,7 +167,7 @@ "js-beautify": "1.15.1", "lint-staged": "15.2.2", "mockdate": "3.0.5", - "msw": "2.2.12", + "msw": "2.2.13", "nock": "14.0.0-beta.5", "prettier": "3.2.5", "remark-parse": "11.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9756e122f..2d1a2462e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -353,8 +353,8 @@ devDependencies: specifier: 3.0.5 version: 3.0.5 msw: - specifier: 2.2.12 - version: 2.2.12(typescript@5.4.3) + specifier: 2.2.13 + version: 2.2.13(typescript@5.4.3) nock: specifier: 14.0.0-beta.5 version: 14.0.0-beta.5 @@ -7187,8 +7187,8 @@ packages: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} dev: false - /msw@2.2.12(typescript@5.4.3): - resolution: {integrity: sha512-thmjEipUvr+XGawcNOh4T8+T2TN3qKWPfF0Ewx6ub1HIATXBsjOhnjV6Wx2BmmFThKEtYYC+RygrvkpG4DzoZw==} + /msw@2.2.13(typescript@5.4.3): + resolution: {integrity: sha512-ljFf1xZsU0b4zv1l7xzEmC6OZA6yD06hcx0H+dc8V0VypaP3HGYJa1rMLjQbBWl32ptGhcfwcPCWDB1wjmsftw==} engines: {node: '>=18'} hasBin: true requiresBuild: true From a828b3dd1ccf50281a879b0512c8043e9e148930 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Sat, 30 Mar 2024 18:21:14 +0800 Subject: [PATCH 15/24] feat: request rewriter --- lib/app.tsx | 2 +- lib/utils/proxy/index.ts | 3 + .../fetch.ts} | 33 ++---- lib/utils/request-rewriter/get.ts | 66 +++++++++++ lib/utils/request-rewriter/index.ts | 19 ++++ lib/utils/request-wrapper.ts | 105 ------------------ tsconfig.json | 2 +- 7 files changed, 99 insertions(+), 131 deletions(-) rename lib/utils/{request-interceptor.ts => request-rewriter/fetch.ts} (55%) create mode 100644 lib/utils/request-rewriter/get.ts create mode 100644 lib/utils/request-rewriter/index.ts delete mode 100644 lib/utils/request-wrapper.ts diff --git a/lib/app.tsx b/lib/app.tsx index f2a549eef..5615affc1 100644 --- a/lib/app.tsx +++ b/lib/app.tsx @@ -1,4 +1,4 @@ -import '@/utils/request-interceptor'; +import '@/utils/request-rewriter'; import { Hono } from 'hono'; diff --git a/lib/utils/proxy/index.ts b/lib/utils/proxy/index.ts index 016501b2a..bc04898fc 100644 --- a/lib/utils/proxy/index.ts +++ b/lib/utils/proxy/index.ts @@ -34,6 +34,9 @@ if (proxyIsPAC) { dispatcher = new ProxyAgent({ uri: proxyUri, token: proxyObj?.auth ? `Basic ${proxyObj.auth}` : undefined, + requestTls: { + rejectUnauthorized: process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0', + }, }); } else if (proxyUri.startsWith('socks')) { agent = new SocksProxyAgent(proxyUri); diff --git a/lib/utils/request-interceptor.ts b/lib/utils/request-rewriter/fetch.ts similarity index 55% rename from lib/utils/request-interceptor.ts rename to lib/utils/request-rewriter/fetch.ts index 5125e7b48..39b628a23 100644 --- a/lib/utils/request-interceptor.ts +++ b/lib/utils/request-rewriter/fetch.ts @@ -1,19 +1,14 @@ -import { setupServer } from 'msw/node'; -import { http } from 'msw'; import logger from '@/utils/logger'; import { config } from '@/config'; -import { fetch, Headers, FormData, Request, Response } from 'undici'; +import { fetch, Request, RequestInfo, RequestInit } from 'undici'; import proxy from '@/utils/proxy'; -Object.defineProperties(globalThis, { - fetch: { value: fetch, writable: true }, - Headers: { value: Headers }, - FormData: { value: FormData }, - Request: { value: Request }, - Response: { value: Response }, -}); +const wrappedFetch: typeof fetch = (input: RequestInfo, init?: RequestInit) => { + const request = new Request(input, init); + const options: RequestInit = {}; + + logger.debug(`Outgoing request: ${request.method} ${request.url}`); -const handler = (request: globalThis.Request, options: NonNullable[1]>) => { // ua if (!request.headers.get('user-agent')) { request.headers.set('user-agent', config.ua); @@ -45,21 +40,11 @@ const handler = (request: globalThis.Request, options: NonNullable { - logger.debug(`Outgoing request: ${request.method} ${request.url}`); - const requestClone = request.clone(); - const options = {}; - handler(requestClone, options); - // @ts-expect-error - return fetch(requestClone, options); - }) -); -server.listen(); +export default wrappedFetch; diff --git a/lib/utils/request-rewriter/get.ts b/lib/utils/request-rewriter/get.ts new file mode 100644 index 000000000..a69e5f1c0 --- /dev/null +++ b/lib/utils/request-rewriter/get.ts @@ -0,0 +1,66 @@ +import http from 'node:http'; +import https from 'node:https'; +import logger from '@/utils/logger'; +import { config } from '@/config'; +import proxy from '@/utils/proxy'; + +type Get = typeof http.get | typeof https.get | typeof http.request | typeof https.request; + +const getWrappedGet: (origin: T) => T = (origin) => + function (this: any, ...args: Parameters) { + let url: URL; + let options: http.RequestOptions = {}; + let callback: ((res: http.IncomingMessage) => void) | undefined; + if (typeof args[0] === 'string' || args[0] instanceof URL) { + url = new URL(args[0]); + if (typeof args[1] === 'object') { + options = args[1]; + callback = args[2]; + } else if (typeof args[1] === 'function') { + options = {}; + callback = args[1]; + } + } else { + options = args[0]; + url = new URL(options.href || `${options.protocol}//${options.hostname || options.host}${options.path}${options.search || (options.query ? `?${options.query}` : '')}`); + if (typeof args[1] === 'function') { + callback = args[1]; + } + } + + logger.debug(`Outgoing request: ${options.method || 'GET'} ${url}`); + + options.headers = options.headers || {}; + const headersLowerCaseKeys = new Set(Object.keys(options.headers).map((key) => key.toLowerCase())); + + // ua + if (!headersLowerCaseKeys.has('user-agent')) { + options.headers['user-agent'] = config.ua; + } + + // Accept + if (!headersLowerCaseKeys.has('accept')) { + options.headers.accept = '*/*'; + } + + // referer + if (!headersLowerCaseKeys.has('referer')) { + options.headers.referer = url.origin; + } + + // proxy + if (!options.agent && proxy.agent) { + const proxyRegex = new RegExp(proxy.proxyObj.url_regex); + + if (proxyRegex.test(url.toString()) && url.protocol.startsWith('http') && url.host !== proxy.proxyUrlHandler?.host) { + options.agent = proxy.agent; + if (proxy.proxyObj.auth) { + options.headers['Proxy-Authorization'] = `Basic ${proxy.proxyObj.auth}`; + } + } + } + + return Reflect.apply(origin, this, [url, options, callback]) as ReturnType; + }; + +export default getWrappedGet; diff --git a/lib/utils/request-rewriter/index.ts b/lib/utils/request-rewriter/index.ts new file mode 100644 index 000000000..74e793167 --- /dev/null +++ b/lib/utils/request-rewriter/index.ts @@ -0,0 +1,19 @@ +import { Headers, FormData, Request, Response } from 'undici'; +import http from 'node:http'; +import https from 'node:https'; + +import fetch from '@/utils/request-rewriter/fetch'; +import getWrappedGet from '@/utils/request-rewriter/get'; + +Object.defineProperties(globalThis, { + fetch: { value: fetch }, + Headers: { value: Headers }, + FormData: { value: FormData }, + Request: { value: Request }, + Response: { value: Response }, +}); + +http.get = getWrappedGet(http.get); +http.request = getWrappedGet(http.request); +https.get = getWrappedGet(https.get); +https.request = getWrappedGet(https.request); diff --git a/lib/utils/request-wrapper.ts b/lib/utils/request-wrapper.ts deleted file mode 100644 index 352f7d2db..000000000 --- a/lib/utils/request-wrapper.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { config } from '@/config'; -import logger from '@/utils/logger'; -import http, { type RequestOptions } from 'node:http'; -import https from 'node:https'; -import proxy from '@/utils/proxy'; - -let proxyWrapper: ( - url: string, - options: RequestOptions & { - headers: Record; - } -) => boolean = () => false; - -if (proxy.agent) { - const proxyRegex = new RegExp(proxy.proxyObj.url_regex); - const protocolMatch = (protocolLike?: string | null) => protocolLike?.toLowerCase().startsWith('http'); - - proxyWrapper = (url, options) => { - let urlHandler; - try { - urlHandler = new URL(url); - } catch { - // ignore - } - if (proxyRegex.test(url) && (protocolMatch(options.protocol) || protocolMatch(url)) && (!urlHandler || urlHandler.host !== proxy.proxyUrlHandler?.host)) { - options.agent = proxy.agent || false; - if (proxy.proxyObj.auth) { - options.headers['Proxy-Authorization'] = `Basic ${proxy.proxyObj.auth}`; - } - return true; - } - return false; - }; -} - -const requestWrapper = (url: string, options: http.RequestOptions = {}) => { - options.headers = options.headers || {}; - - const optionsWithHeaders = options as http.RequestOptions & { - headers: Record; - }; - const headersLowerCaseKeys = new Set(Object.keys(optionsWithHeaders.headers).map((key) => key.toLowerCase())); - - let prxied = false; - if (config.proxyStrategy === 'all') { - prxied = proxyWrapper(url, optionsWithHeaders); - } else if (config.proxyStrategy === 'on_retry' && (optionsWithHeaders as any).retryCount) { - // TODO - prxied = proxyWrapper(url, optionsWithHeaders); - } - if (prxied) { - logger.debug(`Proxy for ${url}`); - } else { - logger.debug(`Requesting ${url}`); - } - - // ua - if (!headersLowerCaseKeys.has('user-agent')) { - options.headers['user-agent'] = config.ua; - } - - // Accept - if (!headersLowerCaseKeys.has('accept')) { - options.headers.Accept = '*/*'; - } - - let urlHandler; - try { - urlHandler = new URL(url); - } catch { - // ignore - } - - if ( - urlHandler && // referer - !headersLowerCaseKeys.has('referer') - ) { - options.headers.referer = urlHandler.origin; - } -}; - -const httpWrap = (func: typeof http.request) => { - const origin = func; - const warpped: typeof http.request = function (...args) { - let url: string; - let options: http.RequestOptions; - if (args[0] instanceof URL || typeof args[0] === 'string') { - url = args[0].toString(); - options = args[1] as http.RequestOptions; - } else { - options = args[0] as http.RequestOptions; - url = `${options.protocol}//${options.hostname || options.host}${options.path}`; - } - requestWrapper(url, options); - - // @ts-expect-error apply - return origin.apply(this, args); - }; - return warpped; -}; - -http.get = httpWrap(http.get); -https.get = httpWrap(https.get); -http.request = httpWrap(http.request); -https.request = httpWrap(https.request); diff --git a/tsconfig.json b/tsconfig.json index 20bc58343..5ce6ad958 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "target": "ESNext", "module": "ESNext", - "moduleResolution": "node", + "moduleResolution": "bundler", "strict": true, "jsx": "react-jsx", "jsxImportSource": "hono/jsx", From bec0ba0705656f7c2416e4944b5f570eed9c9ca0 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Sat, 30 Mar 2024 18:29:38 +0800 Subject: [PATCH 16/24] test: request headers --- lib/setup.test.ts | 4 ++-- lib/utils/ofetch.ts | 3 +++ lib/utils/rand-user-agent.test.ts | 10 +++++----- package.json | 2 +- pnpm-lock.yaml | 31 ++++++++----------------------- 5 files changed, 19 insertions(+), 31 deletions(-) diff --git a/lib/setup.test.ts b/lib/setup.test.ts index 4e39c68df..90170e0c7 100644 --- a/lib/setup.test.ts +++ b/lib/setup.test.ts @@ -48,9 +48,9 @@ const server = setupServer( '' ) ), - http.get(`http://rsshub.test/ua`, ({ request }) => + http.get(`http://rsshub.test/headers`, ({ request }) => HttpResponse.json({ - ua: request.headers.get('user-agent'), + ...Object.fromEntries(request.headers.entries()), }) ), http.post(`http://rsshub.test/form-post`, async ({ request }) => { diff --git a/lib/utils/ofetch.ts b/lib/utils/ofetch.ts index 31e6574c8..06f77e379 100644 --- a/lib/utils/ofetch.ts +++ b/lib/utils/ofetch.ts @@ -9,6 +9,9 @@ const rofetch = createFetch().create({ onRequestError({ request, error }) { logger.error(`Request ${request} fail: ${error}`); }, + headers: { + 'user-agent': config.ua, + }, }); export default rofetch; diff --git a/lib/utils/rand-user-agent.test.ts b/lib/utils/rand-user-agent.test.ts index 91169f159..c459190dd 100644 --- a/lib/utils/rand-user-agent.test.ts +++ b/lib/utils/rand-user-agent.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import got from '@/utils/got'; +import ofetch from '@/utils/ofetch'; import { config } from '@/config'; import randUserAgent from '@/utils/rand-user-agent'; @@ -22,16 +22,16 @@ describe('rand-user-agent', () => { }); it('should has default random ua', async () => { - const { data } = await got('http://rsshub.test/ua'); - expect(data.ua).toBe(config.ua); + const response = await ofetch('http://rsshub.test/headers'); + expect(response['user-agent']).toBe(config.ua); }); it('should match ua configurated', async () => { - const { data } = await got('http://rsshub.test/ua', { + const response = await ofetch('http://rsshub.test/headers', { headers: { 'user-agent': mobileUa, }, }); - expect(data.ua).toBe(mobileUa); + expect(response['user-agent']).toBe(mobileUa); }); }); diff --git a/package.json b/package.json index a78cdc794..713dfbc7d 100644 --- a/package.json +++ b/package.json @@ -76,7 +76,6 @@ "form-data": "4.0.0", "git-rev-sync": "3.0.2", "googleapis": "134.0.0", - "got": "14.2.1", "hono": "4.1.4", "html-to-text": "9.0.5", "https-proxy-agent": "7.0.4", @@ -163,6 +162,7 @@ "eslint-plugin-unicorn": "51.0.1", "eslint-plugin-yml": "1.13.2", "fs-extra": "11.2.0", + "got": "14.2.1", "husky": "9.0.11", "js-beautify": "1.15.1", "lint-staged": "15.2.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2d1a2462e..c65df8125 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -83,9 +83,6 @@ dependencies: googleapis: specifier: 134.0.0 version: 134.0.0 - got: - specifier: 14.2.1 - version: 14.2.1 hono: specifier: 4.1.4 version: 4.1.4 @@ -340,6 +337,9 @@ devDependencies: fs-extra: specifier: 11.2.0 version: 11.2.0 + got: + specifier: 14.2.1 + version: 14.2.1 husky: specifier: 9.0.11 version: 9.0.11 @@ -2669,7 +2669,7 @@ packages: /@sindresorhus/is@6.2.0: resolution: {integrity: sha512-yM/IGPkVnYGblhDosFBwq0ZGdnVSBkNV4onUtipGMOjZd4kB6GAu3ys91aftSbyMHh6A2GPdt+KDI5NoWP63MQ==} engines: {node: '>=16'} - dev: false + dev: true /@stylistic/eslint-plugin-js@1.7.0(eslint@8.57.0): resolution: {integrity: sha512-PN6On/+or63FGnhhMKSQfYcWutRlzOiYlVdLM6yN7lquoBTqUJHYnl4TA4MHwiAt46X5gRxDr1+xPZ1lOLcL+Q==} @@ -2748,7 +2748,6 @@ packages: engines: {node: '>=14.16'} dependencies: defer-to-connect: 2.0.1 - dev: false /@tonyrl/rand-user-agent@2.0.56: resolution: {integrity: sha512-7C2zOyvJsU2BxYayw+w/KjtP/InxYHzRWOWUuPj3XP3SGfnUTpQjKvEuo5K0LB+0YqF62w65LjHGE7Aw1irtaA==} @@ -2829,7 +2828,6 @@ packages: /@types/http-cache-semantics@4.0.4: resolution: {integrity: sha512-1m0bIFVc7eJWyve9S0RnuRgcQqF/Xd5QsUZAZeQFr1Q3/p9JWoQQEqmVy+DPTNpGXwhgIetAoYF8JSc33q29QA==} - dev: false /@types/imapflow@1.0.18: resolution: {integrity: sha512-BoWZUoMktji2YJmkRY8z0KsjvyDNpBzeC/rLVMFKcHkPxaKp+SHBFfx/kj7ltKh3l010Lc9RZqnJs8KUMNhf6Q==} @@ -3742,7 +3740,6 @@ packages: /cacheable-lookup@7.0.0: resolution: {integrity: sha512-+qJyx4xiKra8mZrcwhjMRMUhD5NR1R8esPkzIYxX96JiecFoxAXFuz/GpR3+ev4PE1WamHip78wV0vcmPQtp8w==} engines: {node: '>=14.16'} - dev: false /cacheable-request@10.2.14: resolution: {integrity: sha512-zkDT5WAF4hSSoUgyfg5tFIxz8XQK+25W/TLVojJTMKBaxevLBBtLxgqguAuVQB8PVW79FVjHcU+GJ9tVbDZ9mQ==} @@ -3755,7 +3752,6 @@ packages: mimic-response: 4.0.0 normalize-url: 8.0.1 responselike: 3.0.0 - dev: false /call-bind@1.0.7: resolution: {integrity: sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==} @@ -4340,7 +4336,6 @@ packages: engines: {node: '>=10'} dependencies: mimic-response: 3.1.0 - dev: false /deep-eql@4.1.3: resolution: {integrity: sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==} @@ -4366,7 +4361,6 @@ packages: /defer-to-connect@2.0.1: resolution: {integrity: sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==} engines: {node: '>=10'} - dev: false /define-data-property@1.1.4: resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} @@ -5311,7 +5305,7 @@ packages: /form-data-encoder@4.0.2: resolution: {integrity: sha512-KQVhvhK8ZkWzxKxOr56CPulAhH3dobtuQ4+hNQ+HekH/Wp5gSOafqRAeTphQUJAIk0GBvHZgJ2ZGRWd5kphMuw==} engines: {node: '>= 18'} - dev: false + dev: true /form-data@2.3.3: resolution: {integrity: sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==} @@ -5466,11 +5460,11 @@ packages: /get-stream@6.0.1: resolution: {integrity: sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==} engines: {node: '>=10'} - dev: false /get-stream@8.0.1: resolution: {integrity: sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==} engines: {node: '>=16'} + dev: true /get-tsconfig@4.7.3: resolution: {integrity: sha512-ZvkrzoUA0PQZM6fy6+/Hce561s+faD1rsNwhnO5FelNjyy7EMGJ3Rz1AQ8GYDWjhRs/7dBLOEJvhK8MiEJOAFg==} @@ -5645,7 +5639,7 @@ packages: lowercase-keys: 3.0.0 p-cancelable: 4.0.1 responselike: 3.0.0 - dev: false + dev: true /graceful-fs@4.1.15: resolution: {integrity: sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==} @@ -5828,7 +5822,6 @@ packages: /http-cache-semantics@4.1.1: resolution: {integrity: sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==} - dev: false /http-proxy-agent@7.0.2: resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} @@ -5863,7 +5856,6 @@ packages: dependencies: quick-lru: 5.1.1 resolve-alpn: 1.2.1 - dev: false /https-proxy-agent@5.0.1: resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==} @@ -6682,7 +6674,6 @@ packages: /lowercase-keys@3.0.0: resolution: {integrity: sha512-ozCC6gdQ+glXOQsveKD0YsDy8DSQFjDTz4zyzEHNV5+JP5D62LmfDZ6o1cycFx9ouG940M5dE8C8CTewdj2YWQ==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - dev: false /lru-cache@10.2.0: resolution: {integrity: sha512-2bIM8x+VAf6JT4bKAljS1qUWgMsqZRPGJS6FSahIMPVvctcNhyVp7AJu7quxOW9jwkryBReKZY5tY5JYv2n/7Q==} @@ -7077,12 +7068,10 @@ packages: /mimic-response@3.1.0: resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==} engines: {node: '>=10'} - dev: false /mimic-response@4.0.0: resolution: {integrity: sha512-e5ISH9xMYU0DzrT+jl8q2ze9D6eWBto+I8CNpe+VI+K2J/F/k3PdkdTdz4wvGVH4NTpo+NRYTVIuMQEMMcsLqg==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - dev: false /min-indent@1.0.1: resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==} @@ -7327,7 +7316,6 @@ packages: /normalize-url@8.0.1: resolution: {integrity: sha512-IO9QvjUMWxPQQhs60oOu10CRkWCiZzSUkzbXGGV9pviYl1fXYcvkzQ5jV9z8Y6un8ARoVRl4EtC6v6jNqbaJ/w==} engines: {node: '>=14.16'} - dev: false /notion-to-md@3.1.1: resolution: {integrity: sha512-Zaa2P1B9Rx99bevFYTGuUMYbbfdHn2G1AZMsytYGDWIJjr6Ie1qp/8CorpwVUh1qrquES/V2PkEREqCuTu1zKA==} @@ -7501,7 +7489,7 @@ packages: /p-cancelable@4.0.1: resolution: {integrity: sha512-wBowNApzd45EIKdO1LaU+LrMBwAcjfPaYtVzV3lmfM3gf8Z4CHZsiIqlM8TZZ8okYvh5A1cP6gTfCRQtwUpaUg==} engines: {node: '>=14.16'} - dev: false + dev: true /p-finally@1.0.0: resolution: {integrity: sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==} @@ -8074,7 +8062,6 @@ packages: /quick-lru@5.1.1: resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==} engines: {node: '>=10'} - dev: false /re2js@0.4.1: resolution: {integrity: sha512-Kxb+OKXrEPowP4bXAF07NDXtgYX07S8HeVGgadx5/D/R41LzWg1kgTD2szIv2iHJM3vrAPnDKaBzfUE/7QWX9w==} @@ -8286,7 +8273,6 @@ packages: /resolve-alpn@1.2.1: resolution: {integrity: sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==} - dev: false /resolve-from@4.0.0: resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} @@ -8313,7 +8299,6 @@ packages: engines: {node: '>=14.16'} dependencies: lowercase-keys: 3.0.0 - dev: false /restore-cursor@3.1.0: resolution: {integrity: sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==} From 59631b2e9b6f11a3f5687b9e7ee91fd65032a5d2 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Sat, 30 Mar 2024 18:30:41 +0800 Subject: [PATCH 17/24] test: request-rewriter headers --- lib/utils/request-rewriter.test.ts | 123 ++++++++++ lib/utils/request-wrapper.test.ts | 365 ----------------------------- 2 files changed, 123 insertions(+), 365 deletions(-) create mode 100644 lib/utils/request-rewriter.test.ts delete mode 100644 lib/utils/request-wrapper.test.ts diff --git a/lib/utils/request-rewriter.test.ts b/lib/utils/request-rewriter.test.ts new file mode 100644 index 000000000..5ac366c49 --- /dev/null +++ b/lib/utils/request-rewriter.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, it, afterEach, vi } from 'vitest'; +import '@/utils/request-rewriter'; +import { config } from '@/config'; + +import ofetch from '@/utils/ofetch'; +import got from 'got'; + +afterEach(() => { + delete process.env.PROXY_URI; + delete process.env.PROXY_AUTH; + delete process.env.PROXY_URL_REGEX; + + vi.resetModules(); +}); + +describe('request-rewriter', () => { + it('ofetch', async () => { + const response = await ofetch('http://rsshub.test/headers'); + expect(response['user-agent']).toBe(config.ua); + expect(response.accept).toBe('*/*'); + expect(response.referer).toBe('http://rsshub.test'); + }); + + it('fetch', async () => { + const response = await (await fetch('http://rsshub.test/headers')).json(); + expect(response['user-agent']).toBe(config.ua); + expect(response.accept).toBe('*/*'); + expect(response.referer).toBe('http://rsshub.test'); + }); + + it('http', async () => { + const { config } = await import('@/config'); + await import('@/utils/request-rewriter'); + + const response = await got + .get('http://rsshub.test/headers', { + headers: { + 'user-agent': undefined, + accept: undefined, + }, + }) + .json(); + expect(response['user-agent']).toBe(config.ua); + expect(response.accept).toBe('*/*'); + expect(response.referer).toBe('http://rsshub.test'); + }); + + // it('proxy-uri http', async () => { + // process.env.PROXY_URI = 'http://user:pass@rsshub.proxy:2333'; + + // await import('@/utils/request-wrapper'); + // check = (request) => { + // expect(request.agent.constructor.name).toBe('HttpsProxyAgent'); + // expect(request.agent.proxy.protocol).toBe('http:'); + // expect(request.agent.proxy.username).toBe('user'); + // expect(request.agent.proxy.password).toBe('pass'); + // expect(request.agent.proxy.host).toBe('rsshub.proxy:2333'); + // expect(request.agent.proxy.hostname).toBe('rsshub.proxy'); + // expect(request.agent.proxy.port).toBe('2333'); + // }; + + // nock(/rsshub\.test/) + // .get('/proxy') + // .times(2) + // .reply(200, simpleResponse); + + // await got.get('http://rsshub.test/proxy'); + // await parser.parseURL('http://rsshub.test/proxy'); + // }); + + // it('auth', async () => { + // process.env.PROXY_AUTH = 'testtest'; + // process.env.PROXY_PROTOCOL = 'http'; // only http(s) proxies extract auth from Headers + // process.env.PROXY_HOST = 'rsshub.proxy'; + // process.env.PROXY_PORT = '2333'; + + // await import('@/utils/request-wrapper'); + + // nock(/rsshub\.test/) + // .get('/auth') + // .times(2) + // .reply(function () { + // expect(this.req.headers['proxy-authorization']).toBe('Basic testtest'); + // return [200, simpleResponse]; + // }); + + // await got.get('http://rsshub.test/auth'); + // await parser.parseURL('http://rsshub.test/auth'); + // }); + + // it('url_regex', async () => { + // process.env.PROXY_URL_REGEX = 'url_regex'; + // process.env.PROXY_PROTOCOL = 'socks'; + // process.env.PROXY_HOST = 'rsshub.proxy'; + // process.env.PROXY_PORT = '2333'; + + // await import('@/utils/request-wrapper'); + // check = (request) => { + // if (request.path === '/url_regex') { + // expect(request.agent.constructor.name).toBe('SocksProxyAgent'); + // expect(request.agent.proxy.host).toBe('rsshub.proxy'); + // expect(request.agent.proxy.port).toBe(2333); + // } else if (request.path === '/proxy') { + // expect(request.agent).toBe(undefined); + // } + // }; + + // nock(/rsshub\.test/) + // .get('/url_regex') + // .times(2) + // .reply(() => [200, simpleResponse]); + // nock(/rsshub\.test/) + // .get('/proxy') + // .times(2) + // .reply(() => [200, simpleResponse]); + + // await got.get('http://rsshub.test/url_regex'); + // await parser.parseURL('http://rsshub.test/url_regex'); + + // await got.get('http://rsshub.test/proxy'); + // await parser.parseURL('http://rsshub.test/proxy'); + // }); +}); diff --git a/lib/utils/request-wrapper.test.ts b/lib/utils/request-wrapper.test.ts deleted file mode 100644 index 1b126d506..000000000 --- a/lib/utils/request-wrapper.test.ts +++ /dev/null @@ -1,365 +0,0 @@ -import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'; - -import got from '@/utils/got'; -import parser from '@/utils/rss-parser'; -import nock from 'nock'; -import http from 'node:http'; - -let check: ( - request: Request & { - agent: any; - path: string; - } -) => void = () => {}; -const simpleResponse = ''; - -beforeEach(() => { - delete process.env.PAC_URI; - delete process.env.PAC_SCRIPT; -}); - -afterEach(() => { - delete process.env.PROXY_URI; - delete process.env.PROXY_PROTOCOL; - delete process.env.PROXY_HOST; - delete process.env.PROXY_PORT; - delete process.env.PROXY_AUTH; - delete process.env.PROXY_URL_REGEX; - - nock.restore(); - nock.activate(); - check = () => {}; - - const httpWrap = (func) => { - const origin = func; - return function (url, request) { - if (typeof url === 'object') { - if (url instanceof URL) { - check(request); - } else { - check(url); - } - } else { - check(request); - } - // @ts-expect-error any - // eslint-disable-next-line prefer-rest-params - return Reflect.apply(origin, this, arguments); - }; - }; - http.get = httpWrap(http.get); - http.request = httpWrap(http.request); - - vi.resetModules(); -}); - -describe('got', () => { - it('headers', async () => { - await import('@/utils/request-wrapper'); - - nock(/rsshub\.test/) - .get(/.*/) - .times(3) - .reply(function () { - expect(this.req.headers.referer).toBe('http://api.rsshub.test'); - expect(this.req.headers.host).toBe('api.rsshub.test'); - return [200, simpleResponse]; - }); - - await got.get('http://api.rsshub.test/test'); - await got.get('http://api.rsshub.test'); - - await parser.parseURL('http://api.rsshub.test/test'); - }); - - it('proxy-uri socks', async () => { - process.env.PROXY_URI = 'socks5://user:pass@rsshub.proxy:2333'; - - await import('@/utils/request-wrapper'); - check = (request) => { - expect(request.agent.constructor.name).toBe('SocksProxyAgent'); - expect(request.agent.proxy.host).toBe('rsshub.proxy'); - expect(request.agent.proxy.port).toBe(2333); - expect(request.agent.proxy.type).toBe(5); - }; - - nock(/rsshub\.test/) - .get('/proxy') - .times(2) - .reply(200, simpleResponse); - - await got.get('http://rsshub.test/proxy'); - await parser.parseURL('http://rsshub.test/proxy'); - }); - - it('proxy-uri http', async () => { - process.env.PROXY_URI = 'http://user:pass@rsshub.proxy:2333'; - - await import('@/utils/request-wrapper'); - check = (request) => { - expect(request.agent.constructor.name).toBe('HttpsProxyAgent'); - expect(request.agent.proxy.protocol).toBe('http:'); - expect(request.agent.proxy.username).toBe('user'); - expect(request.agent.proxy.password).toBe('pass'); - expect(request.agent.proxy.host).toBe('rsshub.proxy:2333'); - expect(request.agent.proxy.hostname).toBe('rsshub.proxy'); - expect(request.agent.proxy.port).toBe('2333'); - }; - - nock(/rsshub\.test/) - .get('/proxy') - .times(2) - .reply(200, simpleResponse); - - await got.get('http://rsshub.test/proxy'); - await parser.parseURL('http://rsshub.test/proxy'); - }); - - it('proxy-uri https', async () => { - process.env.PROXY_URI = 'https://rsshub.proxy:2333'; - - await import('@/utils/request-wrapper'); - check = (request) => { - expect(request.agent.constructor.name).toBe('HttpsProxyAgent'); - expect(request.agent.proxy.protocol).toBe('https:'); - expect(request.agent.proxy.host).toBe('rsshub.proxy:2333'); - expect(request.agent.proxy.hostname).toBe('rsshub.proxy'); - expect(request.agent.proxy.port).toBe('2333'); - }; - - nock(/rsshub\.test/) - .get('/proxy') - .times(2) - .reply(200, simpleResponse); - - await got.get('http://rsshub.test/proxy'); - await parser.parseURL('http://rsshub.test/proxy'); - }); - - it('proxy socks', async () => { - process.env.PROXY_PROTOCOL = 'socks'; - process.env.PROXY_HOST = 'rsshub.proxy'; - process.env.PROXY_PORT = '2333'; - - await import('@/utils/request-wrapper'); - check = (request) => { - expect(request.agent.constructor.name).toBe('SocksProxyAgent'); - expect(request.agent.proxy.host).toBe('rsshub.proxy'); - expect(request.agent.proxy.port).toBe(2333); - expect(request.agent.proxy.type).toBe(5); - }; - - nock(/rsshub\.test/) - .get('/proxy') - .times(2) - .reply(200, simpleResponse); - - await got.get('http://rsshub.test/proxy'); - await parser.parseURL('http://rsshub.test/proxy'); - }); - - it('proxy http', async () => { - process.env.PROXY_PROTOCOL = 'http'; - process.env.PROXY_HOST = 'rsshub.proxy'; - process.env.PROXY_PORT = '2333'; - - await import('@/utils/request-wrapper'); - check = (request) => { - expect(request.agent.constructor.name).toBe('HttpsProxyAgent'); - expect(request.agent.proxy.protocol).toBe('http:'); - expect(request.agent.proxy.host).toBe('rsshub.proxy:2333'); - expect(request.agent.proxy.hostname).toBe('rsshub.proxy'); - expect(request.agent.proxy.port).toBe('2333'); - }; - - nock(/rsshub\.test/) - .get('/proxy') - .times(2) - .reply(200, simpleResponse); - - await got.get('http://rsshub.test/proxy'); - await parser.parseURL('http://rsshub.test/proxy'); - }); - - it('proxy https', async () => { - process.env.PROXY_PROTOCOL = 'https'; - process.env.PROXY_HOST = 'rsshub.proxy'; - process.env.PROXY_PORT = '2333'; - - await import('@/utils/request-wrapper'); - check = (request) => { - expect(request.agent.constructor.name).toBe('HttpsProxyAgent'); - expect(request.agent.proxy.protocol).toBe('https:'); - expect(request.agent.proxy.host).toBe('rsshub.proxy:2333'); - expect(request.agent.proxy.hostname).toBe('rsshub.proxy'); - expect(request.agent.proxy.port).toBe('2333'); - }; - - nock(/rsshub\.test/) - .get('/proxy') - .times(2) - .reply(200, simpleResponse); - - await got.get('http://rsshub.test/proxy'); - await parser.parseURL('http://rsshub.test/proxy'); - }); - - it('pac-uri http', async () => { - process.env.PAC_URI = 'http://rsshub.proxy:2333'; - - await import('@/utils/request-wrapper'); - - check = (request) => { - expect(request.agent.constructor.name).toBe('PacProxyAgent'); - expect(request.agent.uri.protocol).toBe('http:'); - expect(request.agent.uri.host).toBe('rsshub.proxy:2333'); - expect(request.agent.uri.hostname).toBe('rsshub.proxy'); - expect(request.agent.uri.port).toBe('2333'); - }; - - nock(/rsshub\.test/) - .get('/proxy') - .times(2) - .reply(200, simpleResponse); - - await got.get('http://rsshub.test/proxy'); - await parser.parseURL('http://rsshub.test/proxy'); - }); - - it('pac-uri https', async () => { - process.env.PAC_URI = 'https://rsshub.proxy:2333'; - - await import('@/utils/request-wrapper'); - - check = (request) => { - expect(request.agent.constructor.name).toBe('PacProxyAgent'); - expect(request.agent.uri.protocol).toBe('https:'); - expect(request.agent.uri.host).toBe('rsshub.proxy:2333'); - expect(request.agent.uri.hostname).toBe('rsshub.proxy'); - expect(request.agent.uri.port).toBe('2333'); - }; - - nock(/rsshub\.test/) - .get('/proxy') - .times(2) - .reply(200, simpleResponse); - - await got.get('http://rsshub.test/proxy'); - await parser.parseURL('http://rsshub.test/proxy'); - }); - - it('pac-uri ftp', async () => { - process.env.PAC_URI = 'ftp://rsshub.proxy:2333'; - - await import('@/utils/request-wrapper'); - - check = (request) => { - expect(request.agent.constructor.name).toBe('PacProxyAgent'); - expect(request.agent.uri.protocol).toBe('ftp:'); - expect(request.agent.uri.host).toBe('rsshub.proxy:2333'); - expect(request.agent.uri.hostname).toBe('rsshub.proxy'); - expect(request.agent.uri.port).toBe('2333'); - }; - - nock(/rsshub\.test/) - .get('/proxy') - .times(2) - .reply(200, simpleResponse); - - await got.get('http://rsshub.test/proxy'); - await parser.parseURL('http://rsshub.test/proxy'); - }); - - it('pac-uri file', async () => { - process.env.PAC_URI = 'file:///D:/rsshub/proxy'; - - await import('@/utils/request-wrapper'); - - check = (request) => { - expect(request.agent.constructor.name).toBe('PacProxyAgent'); - expect(request.agent.uri.protocol).toBe('file:'); - expect(request.agent.uri.pathname).toBe('/D:/rsshub/proxy'); - }; - - nock(/rsshub\.test/) - .get('/proxy') - .times(2) - .reply(200, simpleResponse); - - await got.get('http://rsshub.test/proxy'); - await parser.parseURL('http://rsshub.test/proxy'); - }); - - it('pac-script data', async () => { - process.env.PAC_SCRIPT = "function FindProxyForURL(url,host){return 'DIRECT';}"; - - await import('@/utils/request-wrapper'); - - check = (request) => { - expect(request.agent.constructor.name).toBe('PacProxyAgent'); - expect(request.agent.uri.protocol).toBe('data:'); - expect(request.agent.uri.pathname).toBe("text/javascript;charset=utf-8,function%20FindProxyForURL(url%2Chost)%7Breturn%20'DIRECT'%3B%7D"); - }; - - nock(/rsshub\.test/) - .get('/proxy') - .times(2) - .reply(200, simpleResponse); - - await got.get('http://rsshub.test/proxy'); - await parser.parseURL('http://rsshub.test/proxy'); - }); - - it('auth', async () => { - process.env.PROXY_AUTH = 'testtest'; - process.env.PROXY_PROTOCOL = 'http'; // only http(s) proxies extract auth from Headers - process.env.PROXY_HOST = 'rsshub.proxy'; - process.env.PROXY_PORT = '2333'; - - await import('@/utils/request-wrapper'); - - nock(/rsshub\.test/) - .get('/auth') - .times(2) - .reply(function () { - expect(this.req.headers['proxy-authorization']).toBe('Basic testtest'); - return [200, simpleResponse]; - }); - - await got.get('http://rsshub.test/auth'); - await parser.parseURL('http://rsshub.test/auth'); - }); - - it('url_regex', async () => { - process.env.PROXY_URL_REGEX = 'url_regex'; - process.env.PROXY_PROTOCOL = 'socks'; - process.env.PROXY_HOST = 'rsshub.proxy'; - process.env.PROXY_PORT = '2333'; - - await import('@/utils/request-wrapper'); - check = (request) => { - if (request.path === '/url_regex') { - expect(request.agent.constructor.name).toBe('SocksProxyAgent'); - expect(request.agent.proxy.host).toBe('rsshub.proxy'); - expect(request.agent.proxy.port).toBe(2333); - } else if (request.path === '/proxy') { - expect(request.agent).toBe(undefined); - } - }; - - nock(/rsshub\.test/) - .get('/url_regex') - .times(2) - .reply(() => [200, simpleResponse]); - nock(/rsshub\.test/) - .get('/proxy') - .times(2) - .reply(() => [200, simpleResponse]); - - await got.get('http://rsshub.test/url_regex'); - await parser.parseURL('http://rsshub.test/url_regex'); - - await got.get('http://rsshub.test/proxy'); - await parser.parseURL('http://rsshub.test/proxy'); - }); -}); From d83c951d8cffa4af13461dc51814d71b6dceafb7 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Sun, 31 Mar 2024 02:28:26 +0800 Subject: [PATCH 18/24] fix: proxy auth --- lib/utils/proxy/index.ts | 8 ++++++-- lib/utils/request-rewriter/get.ts | 3 --- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/utils/proxy/index.ts b/lib/utils/proxy/index.ts index bc04898fc..aa0c5c9a7 100644 --- a/lib/utils/proxy/index.ts +++ b/lib/utils/proxy/index.ts @@ -30,10 +30,14 @@ if (proxyIsPAC) { agent = new PacProxyAgent(`pac+${proxyUri}`); } else if (proxyUri) { if (proxyUri.startsWith('http')) { - agent = new HttpsProxyAgent(proxyUri); + agent = new HttpsProxyAgent(proxyUri, { + headers: { + 'proxy-authorization': config.proxy?.auth ? `Basic ${config.proxy?.auth}` : undefined, + }, + }); dispatcher = new ProxyAgent({ uri: proxyUri, - token: proxyObj?.auth ? `Basic ${proxyObj.auth}` : undefined, + token: config.proxy?.auth ? `Basic ${config.proxy?.auth}` : undefined, requestTls: { rejectUnauthorized: process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0', }, diff --git a/lib/utils/request-rewriter/get.ts b/lib/utils/request-rewriter/get.ts index a69e5f1c0..181dd2adb 100644 --- a/lib/utils/request-rewriter/get.ts +++ b/lib/utils/request-rewriter/get.ts @@ -54,9 +54,6 @@ const getWrappedGet: (origin: T) => T = (origin) => if (proxyRegex.test(url.toString()) && url.protocol.startsWith('http') && url.host !== proxy.proxyUrlHandler?.host) { options.agent = proxy.agent; - if (proxy.proxyObj.auth) { - options.headers['Proxy-Authorization'] = `Basic ${proxy.proxyObj.auth}`; - } } } From 8c50e2f96f7bfdf954e6e29c3bc59c420bb2d6b3 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Sun, 31 Mar 2024 02:28:58 +0800 Subject: [PATCH 19/24] test: request-rewriter --- lib/utils/request-rewriter.test.ts | 226 +++++++++++++++------------- lib/utils/request-rewriter/fetch.ts | 6 +- 2 files changed, 123 insertions(+), 109 deletions(-) diff --git a/lib/utils/request-rewriter.test.ts b/lib/utils/request-rewriter.test.ts index 5ac366c49..44b1a37f4 100644 --- a/lib/utils/request-rewriter.test.ts +++ b/lib/utils/request-rewriter.test.ts @@ -1,123 +1,137 @@ -import { describe, expect, it, afterEach, vi } from 'vitest'; -import '@/utils/request-rewriter'; -import { config } from '@/config'; - -import ofetch from '@/utils/ofetch'; +import { describe, expect, it, vi } from 'vitest'; +import undici from 'undici'; import got from 'got'; +import http from 'node:http'; -afterEach(() => { - delete process.env.PROXY_URI; - delete process.env.PROXY_AUTH; - delete process.env.PROXY_URL_REGEX; +process.env.PROXY_URI = 'http://rsshub.proxy:2333/'; +process.env.PROXY_AUTH = 'rsshubtest'; +process.env.PROXY_URL_REGEX = 'headers'; - vi.resetModules(); -}); +await import('@/utils/request-rewriter'); +const { config } = await import('@/config'); +const { default: ofetch } = await import('@/utils/ofetch'); describe('request-rewriter', () => { - it('ofetch', async () => { - const response = await ofetch('http://rsshub.test/headers'); - expect(response['user-agent']).toBe(config.ua); - expect(response.accept).toBe('*/*'); - expect(response.referer).toBe('http://rsshub.test'); + it('fetch', async () => { + const fetchSpy = vi.spyOn(undici, 'fetch'); + + try { + await (await fetch('http://rsshub.test/headers')).json(); + } catch { + // ignore + } + + // headers + const headers: Headers = fetchSpy.mock.lastCall?.[0].headers; + expect(headers.get('user-agent')).toBe(config.ua); + expect(headers.get('accept')).toBe('*/*'); + expect(headers.get('referer')).toBe('http://rsshub.test'); + + // proxy + const options = fetchSpy.mock.lastCall?.[1]; + const agentKey = Object.getOwnPropertySymbols(options?.dispatcher).find((s) => s.description === 'proxy agent options'); + const agentUri = agentKey ? options?.dispatcher?.[agentKey].uri : null; + expect(agentUri).toBe(process.env.PROXY_URI); + + // proxy auth + const headersKey = Object.getOwnPropertySymbols(options?.dispatcher).find((s) => s.description === 'proxy headers'); + const agentHeaders = headersKey ? options?.dispatcher?.[headersKey] : null; + expect(agentHeaders['proxy-authorization']).toBe(`Basic ${process.env.PROXY_AUTH}`); + + // url regex not match + { + try { + await (await fetch('http://rsshub.test/rss')).json(); + } catch { + // ignore + } + const options = fetchSpy.mock.lastCall?.[1]; + expect(options?.dispatcher).toBeUndefined(); + } }); - it('fetch', async () => { - const response = await (await fetch('http://rsshub.test/headers')).json(); - expect(response['user-agent']).toBe(config.ua); - expect(response.accept).toBe('*/*'); - expect(response.referer).toBe('http://rsshub.test'); + it('ofetch', async () => { + const fetchSpy = vi.spyOn(undici, 'fetch'); + + try { + await ofetch('http://rsshub.test/headers', { + retry: 0, + }); + } catch { + // ignore + } + + // headers + const headers: Headers = fetchSpy.mock.lastCall?.[0].headers; + expect(headers.get('user-agent')).toBe(config.ua); + expect(headers.get('accept')).toBe('*/*'); + expect(headers.get('referer')).toBe('http://rsshub.test'); + + // proxy + const options = fetchSpy.mock.lastCall?.[1]; + const agentKey = Object.getOwnPropertySymbols(options?.dispatcher).find((s) => s.description === 'proxy agent options'); + const agentUri = agentKey ? options?.dispatcher?.[agentKey].uri : null; + expect(agentUri).toBe(process.env.PROXY_URI); + + // proxy auth + const headersKey = Object.getOwnPropertySymbols(options?.dispatcher).find((s) => s.description === 'proxy headers'); + const agentHeaders = headersKey ? options?.dispatcher?.[headersKey] : null; + expect(agentHeaders['proxy-authorization']).toBe(`Basic ${process.env.PROXY_AUTH}`); + + // url regex not match + { + try { + await ofetch('http://rsshub.test/rss', { + retry: 0, + }); + } catch { + // ignore + } + const options = fetchSpy.mock.lastCall?.[1]; + expect(options?.dispatcher).toBeUndefined(); + } }); it('http', async () => { - const { config } = await import('@/config'); - await import('@/utils/request-rewriter'); + const httpSpy = vi.spyOn(http, 'request'); - const response = await got - .get('http://rsshub.test/headers', { + try { + await got.get('http://rsshub.test/headers', { headers: { 'user-agent': undefined, accept: undefined, }, - }) - .json(); - expect(response['user-agent']).toBe(config.ua); - expect(response.accept).toBe('*/*'); - expect(response.referer).toBe('http://rsshub.test'); + }); + } catch { + // ignore + } + + // headers + const options = httpSpy.mock.lastCall?.[1]; + const headers = options?.headers; + expect(headers?.['user-agent']).toBe(config.ua); + expect(headers?.accept).toBe('*/*'); + expect(headers?.referer).toBe('http://rsshub.test'); + + // proxy + const agentUri = options?.agent?.proxy?.href; + expect(agentUri).toBe(process.env.PROXY_URI); + expect(options?.agent?.proxyHeaders['proxy-authorization']).toBe(`Basic ${process.env.PROXY_AUTH}`); + + // url regex not match + { + try { + await got.get('http://rsshub.test/rss', { + headers: { + 'user-agent': undefined, + accept: undefined, + }, + }); + } catch { + // ignore + } + const options = httpSpy.mock.lastCall?.[1]; + expect(options?.agent).toBeUndefined(); + } }); - - // it('proxy-uri http', async () => { - // process.env.PROXY_URI = 'http://user:pass@rsshub.proxy:2333'; - - // await import('@/utils/request-wrapper'); - // check = (request) => { - // expect(request.agent.constructor.name).toBe('HttpsProxyAgent'); - // expect(request.agent.proxy.protocol).toBe('http:'); - // expect(request.agent.proxy.username).toBe('user'); - // expect(request.agent.proxy.password).toBe('pass'); - // expect(request.agent.proxy.host).toBe('rsshub.proxy:2333'); - // expect(request.agent.proxy.hostname).toBe('rsshub.proxy'); - // expect(request.agent.proxy.port).toBe('2333'); - // }; - - // nock(/rsshub\.test/) - // .get('/proxy') - // .times(2) - // .reply(200, simpleResponse); - - // await got.get('http://rsshub.test/proxy'); - // await parser.parseURL('http://rsshub.test/proxy'); - // }); - - // it('auth', async () => { - // process.env.PROXY_AUTH = 'testtest'; - // process.env.PROXY_PROTOCOL = 'http'; // only http(s) proxies extract auth from Headers - // process.env.PROXY_HOST = 'rsshub.proxy'; - // process.env.PROXY_PORT = '2333'; - - // await import('@/utils/request-wrapper'); - - // nock(/rsshub\.test/) - // .get('/auth') - // .times(2) - // .reply(function () { - // expect(this.req.headers['proxy-authorization']).toBe('Basic testtest'); - // return [200, simpleResponse]; - // }); - - // await got.get('http://rsshub.test/auth'); - // await parser.parseURL('http://rsshub.test/auth'); - // }); - - // it('url_regex', async () => { - // process.env.PROXY_URL_REGEX = 'url_regex'; - // process.env.PROXY_PROTOCOL = 'socks'; - // process.env.PROXY_HOST = 'rsshub.proxy'; - // process.env.PROXY_PORT = '2333'; - - // await import('@/utils/request-wrapper'); - // check = (request) => { - // if (request.path === '/url_regex') { - // expect(request.agent.constructor.name).toBe('SocksProxyAgent'); - // expect(request.agent.proxy.host).toBe('rsshub.proxy'); - // expect(request.agent.proxy.port).toBe(2333); - // } else if (request.path === '/proxy') { - // expect(request.agent).toBe(undefined); - // } - // }; - - // nock(/rsshub\.test/) - // .get('/url_regex') - // .times(2) - // .reply(() => [200, simpleResponse]); - // nock(/rsshub\.test/) - // .get('/proxy') - // .times(2) - // .reply(() => [200, simpleResponse]); - - // await got.get('http://rsshub.test/url_regex'); - // await parser.parseURL('http://rsshub.test/url_regex'); - - // await got.get('http://rsshub.test/proxy'); - // await parser.parseURL('http://rsshub.test/proxy'); - // }); }); diff --git a/lib/utils/request-rewriter/fetch.ts b/lib/utils/request-rewriter/fetch.ts index 39b628a23..69861eb0b 100644 --- a/lib/utils/request-rewriter/fetch.ts +++ b/lib/utils/request-rewriter/fetch.ts @@ -1,9 +1,9 @@ import logger from '@/utils/logger'; import { config } from '@/config'; -import { fetch, Request, RequestInfo, RequestInit } from 'undici'; +import undici, { Request, RequestInfo, RequestInit } from 'undici'; import proxy from '@/utils/proxy'; -const wrappedFetch: typeof fetch = (input: RequestInfo, init?: RequestInit) => { +const wrappedFetch: typeof undici.fetch = (input: RequestInfo, init?: RequestInit) => { const request = new Request(input, init); const options: RequestInit = {}; @@ -44,7 +44,7 @@ const wrappedFetch: typeof fetch = (input: RequestInfo, init?: RequestInit) => { } } - return fetch(request, options); + return undici.fetch(request, options); }; export default wrappedFetch; From f7048d4c249978444b42b3f0454401e0f9cc2d12 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Sun, 31 Mar 2024 02:45:40 +0800 Subject: [PATCH 20/24] fix: ignore url parsing error --- lib/utils/request-rewriter/get.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/utils/request-rewriter/get.ts b/lib/utils/request-rewriter/get.ts index 181dd2adb..7a0b21e6f 100644 --- a/lib/utils/request-rewriter/get.ts +++ b/lib/utils/request-rewriter/get.ts @@ -8,7 +8,7 @@ type Get = typeof http.get | typeof https.get | typeof http.request | typeof htt const getWrappedGet: (origin: T) => T = (origin) => function (this: any, ...args: Parameters) { - let url: URL; + let url: URL | null; let options: http.RequestOptions = {}; let callback: ((res: http.IncomingMessage) => void) | undefined; if (typeof args[0] === 'string' || args[0] instanceof URL) { @@ -22,11 +22,18 @@ const getWrappedGet: (origin: T) => T = (origin) => } } else { options = args[0]; - url = new URL(options.href || `${options.protocol}//${options.hostname || options.host}${options.path}${options.search || (options.query ? `?${options.query}` : '')}`); + try { + url = new URL(options.href || `${options.protocol || 'http:'}//${options.hostname || options.host}${options.path}${options.search || (options.query ? `?${options.query}` : '')}`); + } catch { + url = null; + } if (typeof args[1] === 'function') { callback = args[1]; } } + if (!url) { + return Reflect.apply(origin, this, args) as ReturnType; + } logger.debug(`Outgoing request: ${options.method || 'GET'} ${url}`); From f5ced001eb202054bcde8043359131c1b1742fb6 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Sun, 31 Mar 2024 03:17:53 +0800 Subject: [PATCH 21/24] test: errors --- lib/errors/index.test.ts | 2 +- lib/errors/index.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/errors/index.test.ts b/lib/errors/index.test.ts index a89a84af6..f76af6219 100644 --- a/lib/errors/index.test.ts +++ b/lib/errors/index.test.ts @@ -22,7 +22,7 @@ describe('httperror', () => { it(`httperror`, async () => { const response = await request.get('/test/httperror'); expect(response.status).toBe(503); - expect(response.text).toMatch('Response code 404 (Not Found): target website might be blocking our access, you can host your own RSSHub instance for a better usability.'); + expect(response.text).toMatch('404 Not Found: target website might be blocking our access, you can host your own RSSHub instance for a better usability.'); }, 20000); }); diff --git a/lib/errors/index.tsx b/lib/errors/index.tsx index f2ff4bde7..913bd3b82 100644 --- a/lib/errors/index.tsx +++ b/lib/errors/index.tsx @@ -39,7 +39,7 @@ export const errorHandler: ErrorHandler = (error, ctx) => { } let message = ''; - if (error.name && (error.name === 'HTTPError' || error.name === 'RequestError')) { + if (error.name && (error.name === 'HTTPError' || error.name === 'RequestError' || error.name === 'FetchError')) { ctx.status(503); message = `${error.message}: target website might be blocking our access, you can host your own RSSHub instance for a better usability.`; } else if (error instanceof RequestInProgressError) { From bf4e5dd78ffcef07ac6e2cf2588c26dfbf9c38ee Mon Sep 17 00:00:00 2001 From: DIYgod Date: Sun, 31 Mar 2024 23:13:22 +0800 Subject: [PATCH 22/24] test: fix caces --- lib/middleware/cache.test.ts | 10 +++++----- lib/middleware/parameter.test.ts | 30 +++++++----------------------- lib/middleware/parameter.ts | 2 +- lib/setup.test.ts | 2 +- lib/utils/got.test.ts | 4 ++-- vitest.config.ts | 1 + 6 files changed, 17 insertions(+), 32 deletions(-) diff --git a/lib/middleware/cache.test.ts b/lib/middleware/cache.test.ts index 7edce9fc5..393d8153e 100644 --- a/lib/middleware/cache.test.ts +++ b/lib/middleware/cache.test.ts @@ -3,7 +3,7 @@ import Parser from 'rss-parser'; import wait from '@/utils/wait'; process.env.CACHE_EXPIRE = '1'; -process.env.CACHE_CONTENT_EXPIRE = '3'; +process.env.CACHE_CONTENT_EXPIRE = '2'; const parser = new Parser(); @@ -38,7 +38,7 @@ describe('cache', () => { expect(response3.headers).not.toHaveProperty('rsshub-cache-status'); const parsed3 = await parser.parseString(await response3.text()); - await wait(3 * 1000 + 100); + await wait(2 * 1000 + 100); const response4 = await app.request('/test/cache'); const parsed4 = await parser.parseString(await response4.text()); @@ -51,7 +51,7 @@ describe('cache', () => { await wait(1 * 1000 + 100); const response5 = await app.request('/test/refreshCache'); const parsed5 = await parser.parseString(await response5.text()); - await wait(2 * 1000 + 100); + await wait(1 * 1000 + 100); const response6 = await app.request('/test/refreshCache'); const parsed6 = await parser.parseString(await response6.text()); @@ -86,7 +86,7 @@ describe('cache', () => { expect(response3.headers).not.toHaveProperty('rsshub-cache-status'); const parsed3 = await parser.parseString(await response3.text()); - await wait(3 * 1000 + 100); + await wait(2 * 1000 + 100); const response4 = await app.request('/test/cache'); const parsed4 = await parser.parseString(await response4.text()); @@ -99,7 +99,7 @@ describe('cache', () => { await wait(1 * 1000 + 100); const response5 = await app.request('/test/refreshCache'); const parsed5 = await parser.parseString(await response5.text()); - await wait(2 * 1000 + 100); + await wait(1 * 1000 + 100); const response6 = await app.request('/test/refreshCache'); const parsed6 = await parser.parseString(await response6.text()); diff --git a/lib/middleware/parameter.test.ts b/lib/middleware/parameter.test.ts index 2a31436d3..6fb8788bb 100644 --- a/lib/middleware/parameter.test.ts +++ b/lib/middleware/parameter.test.ts @@ -1,8 +1,12 @@ import { describe, expect, it, vi } from 'vitest'; -import app from '@/app'; import Parser from 'rss-parser'; -import { config } from '@/config'; -import nock from 'nock'; + +process.env.OPENAI_API_KEY = 'sk-1234567890'; +process.env.OPENAI_API_ENDPOINT = 'https://api.openai.mock/v1'; + +vi.mock('@/utils/request-rewriter', () => ({ default: null })); +const { config } = await import('@/config'); +const { default: app } = await import('@/app'); const parser = new Parser(); @@ -424,26 +428,6 @@ describe('multi parameter', () => { describe('openai', () => { it(`chatgpt`, async () => { - vi.resetModules(); - - process.env.OPENAI_API_KEY = 'sk-1234567890'; - const app = (await import('@/app')).default; - const { config } = await import('@/config'); - nock(config.openai.endpoint) - .post('/chat/completions') - .reply(() => [ - 200, - { - choices: [ - { - message: { - content: 'Summary of the article.', - }, - }, - ], - }, - ]); - const responseWithGpt = await app.request('/test/gpt?chatgpt=true'); const responseNormal = await app.request('/test/gpt'); diff --git a/lib/middleware/parameter.ts b/lib/middleware/parameter.ts index 025f6b405..5985d4bd8 100644 --- a/lib/middleware/parameter.ts +++ b/lib/middleware/parameter.ts @@ -50,7 +50,7 @@ const summarizeArticle = async (articleText: string) => { }, }); - return response.data.choices[0].message.content; + return response.choices[0].message.content; }; const getAuthorString = (item) => { diff --git a/lib/setup.test.ts b/lib/setup.test.ts index 90170e0c7..192d9fe82 100644 --- a/lib/setup.test.ts +++ b/lib/setup.test.ts @@ -3,7 +3,7 @@ import { setupServer } from 'msw/node'; import { http, HttpResponse } from 'msw'; const server = setupServer( - http.post(`https://api.openai.com/v1/chat/completions`, () => + http.post(`https://api.openai.mock/v1/chat/completions`, () => HttpResponse.json({ choices: [ { diff --git a/lib/utils/got.test.ts b/lib/utils/got.test.ts index 5b65725fc..b09ff977e 100644 --- a/lib/utils/got.test.ts +++ b/lib/utils/got.test.ts @@ -5,8 +5,8 @@ import { config } from '@/config'; describe('got', () => { it('headers', async () => { - const { data } = await got('http://rsshub.test/ua'); - expect(data.ua).toBe(config.ua); + const { data } = await got('http://rsshub.test/headers'); + expect(data['user-agent']).toBe(config.ua); }); it('retry', async () => { diff --git a/vitest.config.ts b/vitest.config.ts index bc2deb5f5..883c92d55 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -11,5 +11,6 @@ export default defineConfig({ }, testTimeout: 10000, setupFiles: ['./lib/setup.test.ts'], + exclude: ['./lib/setup.test.ts'], }, }); From 4f44a8150d81a76768501f7ad88d1b94875948bb Mon Sep 17 00:00:00 2001 From: DIYgod Date: Sun, 31 Mar 2024 23:33:31 +0800 Subject: [PATCH 23/24] test: fix exclude --- vitest.config.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vitest.config.ts b/vitest.config.ts index 883c92d55..fa395d2b2 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,4 +1,4 @@ -import { defineConfig } from 'vitest/config'; +import { defineConfig, configDefaults } from 'vitest/config'; import tsconfigPaths from 'vite-tsconfig-paths'; export default defineConfig({ @@ -11,6 +11,6 @@ export default defineConfig({ }, testTimeout: 10000, setupFiles: ['./lib/setup.test.ts'], - exclude: ['./lib/setup.test.ts'], + exclude: [...configDefaults.exclude, './lib/setup.test.ts'], }, }); From 425a131083ac240606745d3f0f26fd5df0cf8822 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Mon, 1 Apr 2024 01:51:11 +0800 Subject: [PATCH 24/24] chore: remove nock --- package.json | 1 - pnpm-lock.yaml | 17 +---------------- 2 files changed, 1 insertion(+), 17 deletions(-) diff --git a/package.json b/package.json index 35ed9843e..7cd349712 100644 --- a/package.json +++ b/package.json @@ -168,7 +168,6 @@ "lint-staged": "15.2.2", "mockdate": "3.0.5", "msw": "2.2.13", - "nock": "14.0.0-beta.5", "prettier": "3.2.5", "remark-parse": "11.0.0", "supertest": "6.3.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b7d45e82e..55a499b44 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -355,9 +355,6 @@ devDependencies: msw: specifier: 2.2.13 version: 2.2.13(typescript@5.4.3) - nock: - specifier: 14.0.0-beta.5 - version: 14.0.0-beta.5 prettier: specifier: 3.2.5 version: 3.2.5 @@ -6361,6 +6358,7 @@ packages: /json-stringify-safe@5.0.1: resolution: {integrity: sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==} + dev: false /json5@2.2.3: resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} @@ -7240,14 +7238,6 @@ packages: lower-case: 1.1.4 dev: false - /nock@14.0.0-beta.5: - resolution: {integrity: sha512-u255tf4DYvyErTlPZA9uTfXghiZZy+NflUOFONPVKZ5tP0yaHwKig28zyFOLhu8y5YcCRC+V5vDk4HHileh2iw==} - engines: {node: '>= 18'} - dependencies: - json-stringify-safe: 5.0.1 - propagate: 2.0.1 - dev: true - /node-fetch-native@1.6.4: resolution: {integrity: sha512-IhOigYzAKHd244OC0JIMIUrjzctirCmPkaIfhDeGcEETWof5zKYUW7e7MYvChGWh/4CJeXEgsRyGzuF334rOOQ==} dev: false @@ -7817,11 +7807,6 @@ packages: engines: {node: '>=0.4.0'} dev: false - /propagate@2.0.1: - resolution: {integrity: sha512-vGrhOavPSTz4QVNuBNdcNXePNdNMaO1xj9yBeH1ScQPjk/rhg9sSlCXPhMkFuaNNW/syTvYqsnbIJxMBfRbbag==} - engines: {node: '>= 8'} - dev: true - /proto-list@1.2.4: resolution: {integrity: sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==} dev: true