Skip to content

Commit

Permalink
eslintrc package pnpm-lock configs connections fetch rule-provider ru…
Browse files Browse the repository at this point in the history
…les traffic version Rules About BackendErrorFallback GitHubIcon errors types
  • Loading branch information
haishanh committed Oct 6, 2023
1 parent def689d commit fb865d9
Show file tree
Hide file tree
Showing 16 changed files with 109 additions and 77 deletions.
15 changes: 13 additions & 2 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,13 @@ parserOptions:
project: tsconfig.json
sourceType: module

settings:
react:
version: detect

plugins:
- simple-import-sort
- unused-imports
- jsx-a11y

extends:
Expand All @@ -30,8 +35,14 @@ rules:
'@typescript-eslint/no-explicit-any': 'off'
'@typescript-eslint/camelcase': 'off'
'no-use-before-define': 'off'
'@typescript-eslint/no-unused-vars':
- 'error'
# '@typescript-eslint/no-unused-vars':
# - 'error'
# - argsIgnorePattern: '^_'
## disable '@typescript-eslint/no-unused-vars' and use 'unused-imports' plugin/rules instead
'@typescript-eslint/no-unused-vars': 'off'
'unused-imports/no-unused-imports': 'error'
'unused-imports/no-unused-vars':
- 'warn'
- argsIgnorePattern: '^_'
'@typescript-eslint/no-use-before-define':
- error
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
"eslint-plugin-react": "7.33.2",
"eslint-plugin-react-hooks": "4.6.0",
"eslint-plugin-simple-import-sort": "^10.0.0",
"eslint-plugin-unused-imports": "3.0.0",
"postcss": "8.4.31",
"postcss-import": "15.1.0",
"postcss-simple-vars": "^7.0.1",
Expand Down
23 changes: 23 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 13 additions & 3 deletions src/api/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,21 @@ import { getURLAndInit } from 'src/misc/request-helper';
import { ClashGeneralConfig } from 'src/store/types';
import { ClashAPIConfig } from 'src/types';

import { req } from './fetch';
import { handleFetchError, req, validateFetchResponse } from './fetch';

const endpoint = '/configs';

export async function fetchConfigs2(ctx: { queryKey: readonly [string, ClashAPIConfig] }) {
const endpoint = ctx.queryKey[0];
const apiConfig = ctx.queryKey[1];
const { url, init } = getURLAndInit(apiConfig);
const res = await fetch(url + endpoint, init);
let res: Response;
try {
res = await req(url + endpoint, init);
} catch (err) {
handleFetchError(err, { endpoint, apiConfig });
}
validateFetchResponse(res, { endpoint, apiConfig });
if (!res.ok) {
throw new Error('TODO');
}
Expand All @@ -27,7 +33,11 @@ export function updateConfigs(apiConfig: ClashAPIConfig) {

export async function fetchConfigs(apiConfig: ClashAPIConfig) {
const { url, init } = getURLAndInit(apiConfig);
return await req(url + endpoint, init);
try {
return await req(url + endpoint, init);
} catch (err) {
handleFetchError(err, { endpoint, apiConfig });
}
}

// TODO support PUT /configs
Expand Down
4 changes: 2 additions & 2 deletions src/api/connections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,13 @@ export function fetchData(apiConfig: ClashAPIConfig, listener?: unknown): Unsubs
if (ws && ws.readyState <= WebSocket.OPEN) {
if (listener) return subscribe(listener);
return;
};
}

const url = buildWebSocketURL(apiConfig, endpoint);
ws = new WebSocket(url);

const onFrozen = () => {
if (ws.readyState <= WebSocket.OPEN) ws.close()
if (ws.readyState <= WebSocket.OPEN) ws.close();
};
const onResume = () => {
if (ws.readyState <= WebSocket.OPEN) return;
Expand Down
25 changes: 24 additions & 1 deletion src/api/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import isNetworkError from 'is-network-error';

import { YacdBackendUnauthorizedError, YacdFetchNetworkError } from '$src/misc/errors';
import { FetchCtx } from '$src/types';
import { getURLAndInit } from '$src/misc/request-helper';
import { ClashAPIConfig, FetchCtx } from '$src/types';

export type QueryCtx = {
queryKey: readonly [string, ClashAPIConfig];
};

export function req(url: string, init: RequestInit) {
if (import.meta.env.DEV) {
Expand All @@ -10,6 +15,24 @@ export function req(url: string, init: RequestInit) {
return fetch(url, init);
}

export async function query(ctx: QueryCtx) {
const endpoint = ctx.queryKey[0];
const apiConfig = ctx.queryKey[1];
const { url, init } = getURLAndInit(apiConfig);

let res: Response;
try {
res = await req(url + endpoint, init);
} catch (err) {
handleFetchError(err, { endpoint, apiConfig });
}
validateFetchResponse(res, { endpoint, apiConfig });
if (res.ok) {
return await res.json();
}
// can return undefined
}

export function handleFetchError(err: unknown, ctx: FetchCtx) {
if (isNetworkError(err)) throw new YacdFetchNetworkError('', ctx);
throw err;
Expand Down
19 changes: 4 additions & 15 deletions src/api/rule-provider.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { getURLAndInit } from 'src/misc/request-helper';
import { ClashAPIConfig } from 'src/types';

import { query, QueryCtx } from './fetch';

export type RuleProvider = RuleProviderAPIItem & { idx: number };

export type RuleProviderAPIItem = {
Expand Down Expand Up @@ -31,21 +33,8 @@ function normalizeAPIResponse(data: RuleProviderAPIData) {
return { byName, names };
}

export async function fetchRuleProviders(ctx: { queryKey: readonly [string, ClashAPIConfig] }) {
const endpoint = ctx.queryKey[0];
const apiConfig = ctx.queryKey[1];
const { url, init } = getURLAndInit(apiConfig);
let data = { providers: {} };
try {
const res = await fetch(url + endpoint, init);
if (res.ok) {
data = await res.json();
}
} catch (err) {
// log and ignore
// eslint-disable-next-line no-console
console.log('failed to GET /providers/rules', err);
}
export async function fetchRuleProviders(ctx: QueryCtx) {
const data = (await query(ctx)) || { providers: {} };
return normalizeAPIResponse(data);
}

Expand Down
19 changes: 2 additions & 17 deletions src/api/rules.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import invariant from 'invariant';
import { getURLAndInit } from 'src/misc/request-helper';
import { ClashAPIConfig } from 'src/types';
import { handleFetchError, req, validateFetchResponse } from './fetch';

// const endpoint = '/rules';
import { query } from './fetch';

type RuleItem = RuleAPIItem & { id: number };

Expand All @@ -24,19 +22,6 @@ function normalizeAPIResponse(json: { rules: Array<RuleAPIItem> }): Array<RuleIt
}

export async function fetchRules(ctx: { queryKey: readonly [string, ClashAPIConfig] }) {
const endpoint = ctx.queryKey[0];
const apiConfig = ctx.queryKey[1];
const { url, init } = getURLAndInit(apiConfig);
let json = { rules: [] };
let res: Response;
try {
res = await req(url + endpoint, init);
} catch (err) {
handleFetchError(err, { endpoint, apiConfig });
}
validateFetchResponse(res, { endpoint, apiConfig });
if (res.ok) {
json = await res.json();
}
const json = (await query(ctx)) || { rules: [] };
return normalizeAPIResponse(json);
}
6 changes: 3 additions & 3 deletions src/api/traffic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export function fetchData(apiConfig: ClashAPIConfig) {
ws = new WebSocket(url);

const onFrozen = () => {
if (ws.readyState <= WebSocket.OPEN) ws.close()
if (ws.readyState <= WebSocket.OPEN) ws.close();
};

const onResume = () => {
Expand All @@ -68,12 +68,12 @@ export function fetchData(apiConfig: ClashAPIConfig) {
document.addEventListener('freeze', onFrozen, { capture: true, once: true });
document.addEventListener('resume', onResume, { capture: true, once: true });

ws.addEventListener('error', function(_ev) {
ws.addEventListener('error', function (_ev) {
console.log('error', _ev);
//
});
// ws.addEventListener('close', (_ev) => {});
ws.addEventListener('message', function(event) {
ws.addEventListener('message', function (event) {
parseAndAppend(event.data);
});
return traffic;
Expand Down
21 changes: 3 additions & 18 deletions src/api/version.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,11 @@
import { getURLAndInit } from 'src/misc/request-helper';
import { ClashAPIConfig } from 'src/types';
import { query, QueryCtx } from './fetch';

type VersionData = {
version?: string;
premium?: boolean;
};

export async function fetchVersion(
endpoint: string,
apiConfig: ClashAPIConfig,
): Promise<VersionData> {
let json = {};
try {
const { url, init } = getURLAndInit(apiConfig);
const res = await fetch(url + endpoint, init);
if (res.ok) {
json = await res.json();
}
} catch (err) {
// log and ignore
// eslint-disable-next-line no-console
console.log(`failed to fetch ${endpoint}`, err);
}
export async function fetchVersion(ctx: QueryCtx): Promise<VersionData> {
const json = (await query(ctx)) || {};
return json;
}
2 changes: 0 additions & 2 deletions src/components/Rules.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import * as React from 'react';
import { useTranslation } from 'react-i18next';
import { areEqual, VariableSizeList } from 'react-window';
import { toast } from 'sonner';

import { RuleProviderItem } from '$src/components/rules/RuleProviderItem';
import { useRuleAndProvider } from '$src/components/rules/rules.hooks';
Expand All @@ -15,7 +14,6 @@ import useRemainingViewPortHeight from '../hooks/useRemainingViewPortHeight';
import ContentHeader from './ContentHeader';
import Rule from './Rule';
import s from './Rules.module.scss';
import { useNavigate } from 'react-router';

const { memo } = React;

Expand Down
4 changes: 1 addition & 3 deletions src/components/about/About.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ function Version({ name, link, version }: { name: string; link: string; version:

export function About() {
const apiConfig = useApiConfig();
const { data: version } = useQuery(['/version', apiConfig], () =>
fetchVersion('/version', apiConfig),
);
const { data: version } = useQuery(['/version', apiConfig], fetchVersion);
return (
<>
<ContentHeader title="About" />
Expand Down
10 changes: 5 additions & 5 deletions src/components/error/BackendErrorFallback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ export function BackendUnauthorizedErrorFallback(props: {
return (
<ErrorFallbackLayout>
<p>Unauthorized to connect to the backend {ctx.apiConfig.baseURL}</p>
{
ctx.apiConfig.secret ?
<p>You might using a wrong secret</p>
: <p>You probably need to provide a secret</p>
}
{ctx.apiConfig.secret ? (
<p>You might using a wrong secret</p>
) : (
<p>You probably need to provide a secret</p>
)}
<Sep />
<Button onClick={onClick}>{t('switch_backend')}</Button>
</ErrorFallbackLayout>
Expand Down
7 changes: 5 additions & 2 deletions src/components/icon/GitHubIcon.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import React from 'react';

export function GitHubIcon(props: { width?: number; height?: number; size?: number; }) {
export function GitHubIcon(props: { width?: number; height?: number; size?: number }) {
const width = props.width || props.size || 16;
const height = props.height || props.size || 16;
return (
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" width={width} height={height}>
<path fill="currentColor" d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
<path
fill="currentColor"
d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"
/>
</svg>
);
}
12 changes: 9 additions & 3 deletions src/misc/errors.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ClashAPIConfig } from "$src/types";
import { ClashAPIConfig } from '$src/types';

export const DOES_NOT_SUPPORT_FETCH = 0;

Expand All @@ -12,13 +12,19 @@ export class YacdError extends Error {
}

export class YacdFetchNetworkError extends Error {
constructor(public message: string, public ctx: { endpoint: string; apiConfig: ClashAPIConfig; }) {
constructor(
public message: string,
public ctx: { endpoint: string; apiConfig: ClashAPIConfig },
) {
super(message);
}
}

export class YacdBackendUnauthorizedError extends Error {
constructor(public message: string, public ctx: { endpoint: string; apiConfig: ClashAPIConfig; }) {
constructor(
public message: string,
public ctx: { endpoint: string; apiConfig: ClashAPIConfig },
) {
super(message);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ export type RuleType = { id?: number; type?: string; payload?: string; proxy?: s
export type FetchCtx = {
endpoint: string;
apiConfig: ClashAPIConfig;
}
};

0 comments on commit fb865d9

Please sign in to comment.