refactor: adjust the directory structure of messageListeners/ (#1066)

This commit is contained in:
Hakadao
2024-10-13 19:49:14 +08:00
committed by GitHub
parent 1260e689e7
commit 619dc034af
40 changed files with 114 additions and 98 deletions

51
src/utils/api.ts Normal file
View File

@@ -0,0 +1,51 @@
import type { API_COLLECTION } from '~/background/messageListeners/api'
type CamelCase<S extends string> = S extends `${infer P1}_${infer P2}${infer P3}`
? `${Lowercase<P1>}${Uppercase<P2>}${CamelCase<P3>}`
: Lowercase<S>
type APIFunction<T = typeof API_COLLECTION> = {
[K in keyof T as CamelCase<string & K>]: {
// @ts-expect-error allow params
[P in keyof T[K]]: T[K][P] extends Function ? T[K][P] : Lowercase<T[K][P]['_fetch']['method']> extends 'get' ? (options?: Partial<T[K][P]['params']>) => Promise<any> : (options?: Partial<T[K][P]['params'] & T[K][P]['_fetch']['body']>) => Promise<any>
}
}
// eslint-disable-next-line ts/no-unsafe-declaration-merging
export interface APIClient extends APIFunction<typeof API_COLLECTION> {
}
// eslint-disable-next-line ts/no-unsafe-declaration-merging
export class APIClient {
private readonly cache = new Map<string | symbol, any>()
constructor() {
// @ts-expect-error ignore
return new Proxy({}, {
get: (_, namespace) => { // namespace
if (this.cache.has(namespace)) {
return this.cache.get(namespace)
}
else {
const api = new Proxy({}, {
get(_, p) {
return (options?: object) => {
return browser.runtime.sendMessage({
contentScriptQuery: p,
...options,
})
}
},
})
this.cache.set(namespace, api)
return api
}
},
})
}
}
const api = new APIClient()
export default api

10
src/utils/tab.ts Normal file
View File

@@ -0,0 +1,10 @@
import browser from 'webextension-polyfill'
import { TAB_MESSAGE } from '~/background/messageListeners/tab'
export function openLinkInBackground(url: string) {
return browser.runtime.sendMessage({
contentScriptQuery: TAB_MESSAGE.OPEN_LINK_IN_BACKGROUND,
url,
})
}