2021-10-03 07:03:56 +00:00
|
|
|
import { EventEmitter } from "events";
|
2021-11-07 08:17:19 +00:00
|
|
|
import { Dispatch, SetStateAction, useEffect, useState } from "react";
|
2021-10-03 07:03:56 +00:00
|
|
|
|
|
|
|
export type Unpromisify<T> = T extends Promise<infer R> ? R : T;
|
|
|
|
export type Unarray<T> = T extends Array<infer R> ? R : T;
|
|
|
|
|
|
|
|
export type Tab = Unarray<Unpromisify<ReturnType<typeof browser.tabs.query>>>;
|
|
|
|
export type Request = Parameters<
|
|
|
|
Parameters<typeof browser.webRequest.onBeforeSendHeaders.addListener>[0]
|
|
|
|
>[0];
|
|
|
|
|
|
|
|
export function getshorthost(host: string) {
|
|
|
|
return host.split(".").slice(-2).join(".");
|
|
|
|
}
|
|
|
|
|
2021-11-07 08:17:19 +00:00
|
|
|
export function useEmitter(
|
|
|
|
e: EventEmitter
|
|
|
|
): [number, Dispatch<SetStateAction<number>>] {
|
2021-10-03 07:03:56 +00:00
|
|
|
const [counter, setCounter] = useState<number>(0);
|
|
|
|
useEffect(() => {
|
|
|
|
const callback = () => {
|
|
|
|
setCounter((counter) => counter + 1);
|
|
|
|
};
|
|
|
|
e.on("change", callback);
|
|
|
|
return () => {
|
|
|
|
e.removeListener("change", callback);
|
|
|
|
};
|
|
|
|
}, []);
|
2021-11-07 08:17:19 +00:00
|
|
|
return [counter, setCounter];
|
2021-10-03 07:03:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function parseCookie(cookie: string): Record<string, string> {
|
|
|
|
return cookie
|
|
|
|
.split(";")
|
|
|
|
.map((l) => l.split("="))
|
|
|
|
.reduce(
|
|
|
|
(acc, [key, value]) => ({
|
|
|
|
...acc,
|
|
|
|
[key]: value,
|
|
|
|
}),
|
|
|
|
{}
|
|
|
|
);
|
|
|
|
}
|
2021-11-06 20:48:25 +00:00
|
|
|
|
|
|
|
export async function getTabByID(id: number) {
|
|
|
|
const tabs = await browser.tabs.query({ currentWindow: true });
|
|
|
|
return tabs.find((tab) => tab.id == id);
|
|
|
|
}
|
2021-11-07 09:09:41 +00:00
|
|
|
|
|
|
|
export function parseToObject(str: unknown): Record<string, unknown> {
|
|
|
|
if (typeof str === "string") {
|
|
|
|
return JSON.parse(str);
|
|
|
|
} else if (typeof str == "object") {
|
|
|
|
return str as Record<string, unknown>;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function isJSONObject(
|
|
|
|
str: unknown
|
|
|
|
): str is Record<string, unknown> | string | number {
|
|
|
|
try {
|
|
|
|
return JSON.stringify(parseToObject(str))[0] == "{";
|
|
|
|
} catch (e) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function isURL(str: unknown): str is string {
|
|
|
|
try {
|
|
|
|
return !!(typeof str === "string" && new URL(str));
|
|
|
|
} catch (e) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function hyphenate(str: string): string {
|
|
|
|
return str.replace(/[_\[A-Z]/g, `${String.fromCharCode(173)}$&`);
|
|
|
|
}
|