import { EventEmitter } from "events"; import { Dispatch, SetStateAction, useEffect, useState } from "react"; import Memory from "./memory"; export type Unpromisify = T extends Promise ? R : T; export type Unarray = T extends Array ? R : T; export type Tab = Unarray>>; export type Request = Parameters< Parameters[0] >[0]; export function getshorthost(host: string) { return host.split(".").slice(-2).join("."); } export function useEmitter( e: EventEmitter ): [number, Dispatch>] { const [counter, setCounter] = useState(0); useEffect(() => { const callback = () => { setCounter((counter) => counter + 1); }; e.on("change", callback); return () => { e.removeListener("change", callback); }; }, []); return [counter, setCounter]; } export function parseCookie(cookie: string): Record { return cookie .split(";") .map((l) => l.split("=")) .reduce( (acc, [key, value]) => ({ ...acc, [key]: value, }), {} ); } export async function getTabByID(id: number) { const tabs = await browser.tabs.query({ currentWindow: true }); return tabs.find((tab) => tab.id == id); } export function parseToObject(str: unknown): Record { if (typeof str === "string") { return JSON.parse(str); } else if (typeof str == "object") { return str as Record; } } export function isJSONObject( str: unknown ): str is Record | 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)}$&`); } export function getMemory(): Memory { return (browser.extension.getBackgroundPage().window as any).memory as Memory; }