types.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. import type { Emitter } from "nanoevents";
  2. import type * as consts from "./constants";
  3. import type { scriptInfo } from "./constants";
  4. import type { addSelectorListener } from "./observers";
  5. import type resources from "../assets/resources.json";
  6. import type locales from "../assets/locales.json";
  7. import type { getResourceUrl, getSessionId, getVideoTime, TrLocale, t, tp } from "./utils";
  8. import type { getFeatures, setFeatures } from "./config";
  9. import type { SiteEventsMap } from "./siteEvents";
  10. /** Custom CLI args passed to rollup */
  11. export type RollupArgs = Partial<{
  12. "config-mode": "development" | "production";
  13. "config-branch": "main" | "develop";
  14. "config-host": "greasyfork" | "github" | "openuserjs";
  15. "config-assetSource": "local" | "github";
  16. "config-suffix": string;
  17. }>;
  18. // I know TS enums are impure but it doesn't really matter here, plus they look cooler
  19. export enum LogLevel {
  20. Debug,
  21. Info,
  22. }
  23. /** Which domain this script is currently running on */
  24. export type Domain = "yt" | "ytm";
  25. /** A selection option between one of the supported domains, or all of them */
  26. export type SiteSelection = Domain | "all";
  27. /** A URL string that starts with "http://" or "https://" */
  28. export type HttpUrlString = `http://${string}` | `https://${string}`;
  29. /** Key of a resource in `assets/resources.json` and extra keys defined by `tools/post-build.ts` */
  30. export type ResourceKey = keyof typeof resources | `trans-${keyof typeof locales}` | "changelog";
  31. /** Describes a single hotkey */
  32. export type HotkeyObj = {
  33. code: string,
  34. shift: boolean,
  35. ctrl: boolean,
  36. alt: boolean,
  37. };
  38. export type LyricsCacheEntry = {
  39. artist: string;
  40. song: string;
  41. url: string;
  42. viewed: number;
  43. added: number;
  44. };
  45. //#region global
  46. // shim for the BYTM interface properties
  47. export type BytmObject =
  48. {
  49. [key: string]: unknown;
  50. locale: TrLocale;
  51. logLevel: LogLevel;
  52. }
  53. // information from the userscript header
  54. & typeof scriptInfo
  55. // certain variables from `src/constants.ts`
  56. & Pick<typeof consts, "mode" | "branch" | "host" | "buildNumber" | "compressionFormat">
  57. // global functions exposed through the interface in `src/interface.ts`
  58. & InterfaceFunctions
  59. // others
  60. & {
  61. // the entire UserUtils library
  62. UserUtils: typeof import("@sv443-network/userutils");
  63. };
  64. declare global {
  65. interface Window {
  66. // to see the expanded type, install the VS Code extension "MylesMurphy.prettify-ts" and hover over the property below
  67. // alternatively navigate with ctrl+click to find the types
  68. BYTM: BytmObject;
  69. }
  70. }
  71. //#region plugins
  72. /**
  73. * Intents (permissions) BYTM has to grant your plugin for it to be able to access certain features.
  74. * TODO: this feature is unfinished, but you should still specify the intents your plugin needs.
  75. */
  76. export enum PluginIntent {
  77. /** Plugin has access to hidden config values */
  78. HiddenConfigValues = 1,
  79. /** Plugin can write to the feature configuration */
  80. WriteFeatureConfig = 2,
  81. /** Plugin can write to the lyrics cache */
  82. WriteLyricsCache = 4,
  83. /** Plugin can add new translations and overwrite existing ones */
  84. WriteTranslations = 8,
  85. /** Plugin can create modal dialogs */
  86. CreateModalDialogs = 16,
  87. }
  88. /** Result of a plugin registration */
  89. export type PluginRegisterResult = {
  90. /** Public info about the registered plugin */
  91. info: PluginInfo;
  92. /** Emitter for plugin events - see {@linkcode PluginEventMap} for a list of events */
  93. events: Emitter<PluginEventMap>;
  94. }
  95. /** Minimal object that describes a plugin - this is all info the other installed plugins can see */
  96. export type PluginInfo = {
  97. /** Name of the plugin */
  98. name: string;
  99. /**
  100. * Adding the namespace and the name property makes the unique identifier for a plugin.
  101. * If one exists with the same name and namespace as this plugin, it may be overwritten at registration.
  102. * I recommend to set this value to a URL pointing to your homepage, or the author's username.
  103. */
  104. namespace: string;
  105. /** Version of the plugin as an array containing three whole numbers: `[major_version, minor_version, patch_version]` */
  106. version: [major: number, minor: number, patch: number];
  107. };
  108. /** Minimum part of the PluginDef object needed to make up the resolvable plugin identifier */
  109. export type PluginDefResolvable = PluginDef | { plugin: Pick<PluginDef["plugin"], "name" | "namespace"> };
  110. /** An object that describes a BYTM plugin */
  111. export type PluginDef = {
  112. plugin: PluginInfo & {
  113. /**
  114. * Descriptions of at least en_US and optionally any other locale supported by BYTM.
  115. * When an untranslated locale is set, the description will default to the value of en_US
  116. */
  117. description: Partial<Record<keyof typeof locales, string>> & {
  118. en_US: string;
  119. };
  120. /** URL to the plugin's icon - recommended size: 48x48 to 128x128 */
  121. iconUrl?: string;
  122. /** Homepage URLs for the plugin */
  123. homepage?: {
  124. /** URL to the plugin's GitHub repo */
  125. github?: string;
  126. /** URL to the plugin's GreasyFork page */
  127. greasyfork?: string;
  128. /** URL to the plugin's OpenUserJS page */
  129. openuserjs?: string;
  130. };
  131. };
  132. /** Intents (permissions) BYTM has to grant the plugin for it to work */
  133. intents?: Array<PluginIntent>;
  134. /** Info about the plugin contributors */
  135. contributors?: Array<{
  136. /** Name of this contributor */
  137. name: string;
  138. /** (optional) Email address of this contributor */
  139. email?: string;
  140. /** (optional) URL to this plugin contributor's homepage / GitHub profile */
  141. url?: string;
  142. }>;
  143. };
  144. /** All events that are dispatched to plugins individually, including everything in {@linkcode SiteEventsMap} - these don't have a prefix since they can't conflict with other events */
  145. export type PluginEventMap =
  146. & {
  147. /** Called when the plugin is registered on BYTM's side */
  148. pluginRegistered: (info: PluginInfo) => void;
  149. }
  150. & SiteEventsMap;
  151. /** A plugin in either the queue or registered map */
  152. export type PluginItem =
  153. & {
  154. def: PluginDef;
  155. }
  156. & Pick<PluginRegisterResult, "events">;
  157. /** All functions exposed by the interface on the global `BYTM` object */
  158. export type InterfaceFunctions = {
  159. /** Adds a listener to one of the already present SelectorObserver instances */
  160. addSelectorListener: typeof addSelectorListener;
  161. /**
  162. * Returns the URL of a resource as defined in `assets/resources.json`
  163. * There are also some resources like translation files that get added by `tools/post-build.ts`
  164. *
  165. * The returned URL is a `blob:` URL served up by the userscript extension
  166. * This makes the resource fast to fetch and also prevents CORS issues
  167. */
  168. getResourceUrl: typeof getResourceUrl;
  169. /** Returns the unique session ID for the current tab */
  170. getSessionId: typeof getSessionId;
  171. /**
  172. * Returns the current video time (on both YT and YTM)
  173. * In case it can't be determined on YT, mouse movement is simulated to bring up the video time
  174. * In order for that edge case not to error out, the function would need to be called in response to a user interaction event (e.g. click) due to the strict autoplay policy in browsers
  175. */
  176. getVideoTime: typeof getVideoTime;
  177. /** Returns the translation for the provided translation key and set locale (check the files in the folder `assets/translations`) */
  178. t: typeof t;
  179. /** Returns the translation for the provided translation key, including pluralization identifier and set locale (check the files in the folder `assets/translations`) */
  180. tp: typeof tp;
  181. /** Returns the current feature configuration */
  182. getFeatures: typeof getFeatures;
  183. /** Overwrites the feature configuration with the provided one */
  184. saveFeatures: typeof setFeatures;
  185. };
  186. //#region features
  187. export type FeatureKey = keyof FeatureConfig;
  188. export type FeatureCategory =
  189. | "layout"
  190. | "volume"
  191. | "songLists"
  192. | "behavior"
  193. | "input"
  194. | "lyrics"
  195. | "general";
  196. type SelectOption = {
  197. value: string | number;
  198. label: string;
  199. };
  200. type FeatureTypeProps = ({
  201. type: "toggle";
  202. default: boolean;
  203. } & FeatureFuncProps)
  204. | ({
  205. type: "number";
  206. default: number;
  207. min: number;
  208. max?: number;
  209. step?: number;
  210. unit?: string | ((val: number) => string);
  211. } & FeatureFuncProps)
  212. | ({
  213. type: "select";
  214. default: string | number;
  215. options: SelectOption[] | (() => SelectOption[]);
  216. } & FeatureFuncProps)
  217. | ({
  218. type: "slider";
  219. default: number;
  220. min: number;
  221. max: number;
  222. step?: number;
  223. unit?: string | ((val: number) => string);
  224. } & FeatureFuncProps)
  225. | ({
  226. type: "hotkey";
  227. default: HotkeyObj;
  228. } & FeatureFuncProps)
  229. | ({
  230. type: "text";
  231. default: string;
  232. normalize?: (val: string) => string;
  233. } & FeatureFuncProps)
  234. | {
  235. type: "button";
  236. default?: undefined;
  237. click: () => Promise<void> | void;
  238. }
  239. type FeatureFuncProps = (
  240. {
  241. /** Whether the feature requires a page reload to take effect */
  242. reloadRequired: false;
  243. /** Called to instantiate the feature on the page */
  244. enable: (featCfg: FeatureConfig) => void,
  245. }
  246. | {
  247. /** Whether the feature requires a page reload to take effect */
  248. reloadRequired?: true;
  249. /** Called to instantiate the feature on the page */
  250. enable?: undefined;
  251. }
  252. ) & (
  253. {
  254. /** Called to remove all traces of the feature from the page and memory (includes event listeners) */
  255. disable?: (feats: FeatureConfig) => void,
  256. }
  257. | {
  258. /** Called to update the feature's behavior when the config changes */
  259. change?: (feats: FeatureConfig) => void,
  260. }
  261. );
  262. /**
  263. * The feature info object that contains all properties necessary to construct the config menu and the feature config object.
  264. * Values are loosely typed so try to only use this with the `satisfies` keyword.
  265. * Use `typeof featInfo` (from `src/features/index.ts`) instead for full type safety.
  266. */
  267. export type FeatureInfo = Record<
  268. keyof FeatureConfig,
  269. {
  270. category: FeatureCategory;
  271. /**
  272. * HTML string that will be the help text for this feature
  273. * Specifying a function is useful for pluralizing or inserting values into the translation at runtime
  274. */
  275. helpText?: string | (() => string);
  276. /** Whether the value should be hidden in the config menu and from plugins */
  277. valueHidden?: boolean;
  278. /** Transformation function called before the value is rendered in the config menu */
  279. renderValue?: (value: string) => string | Promise<string>;
  280. /** HTML string that is appended to the end of a feature's text description */
  281. textAdornment?: () => (Promise<string | undefined> | string | undefined);
  282. /** Whether to only show this feature when advanced mode is activated (default false) */
  283. advanced?: boolean;
  284. }
  285. & FeatureTypeProps
  286. >;
  287. /** Feature configuration */
  288. export interface FeatureConfig {
  289. //#region layout
  290. /** Show a BetterYTM watermark under the YTM logo */
  291. watermarkEnabled: boolean;
  292. /** Remove the "si" tracking parameter from links in the share menu? */
  293. removeShareTrackingParam: boolean;
  294. /** On which sites to remove the "si" tracking parameter from links in the share menu */
  295. removeShareTrackingParamSites: SiteSelection;
  296. /** Enable skipping to a specific time in the video by pressing a number key (0-9) */
  297. numKeysSkipToTime: boolean;
  298. /** Fix spacing issues in the layout */
  299. fixSpacing: boolean;
  300. /** Remove the \"Upgrade\" / YT Music Premium tab */
  301. removeUpgradeTab: boolean;
  302. /** Where to show a thumbnail overlay over the video element and whether to show it at all */
  303. thumbnailOverlayBehavior: "never" | "videosOnly" | "songsOnly" | "always";
  304. /** Whether to show a button to toggle the thumbnail overlay in the media controls */
  305. thumbnailOverlayToggleBtnShown: boolean;
  306. /** Whether to show an indicator on the thumbnail overlay when it is active */
  307. thumbnailOverlayShowIndicator: boolean;
  308. /** The opacity of the thumbnail overlay indicator element */
  309. thumbnailOverlayIndicatorOpacity: number;
  310. /** How to fit the thumbnail overlay image */
  311. thumbnailOverlayImageFit: "cover" | "contain" | "fill";
  312. /** Hide the cursor when it's idling on the video element for a while */
  313. hideCursorOnIdle: boolean;
  314. /** Delay in seconds after which the cursor should be hidden */
  315. hideCursorOnIdleDelay: number;
  316. //#region volume
  317. /** Add a percentage label to the volume slider */
  318. volumeSliderLabel: boolean;
  319. /** The width of the volume slider in pixels */
  320. volumeSliderSize: number;
  321. /** Volume slider sensitivity - the smaller this number, the finer the volume control */
  322. volumeSliderStep: number;
  323. /** Volume slider scroll wheel sensitivity */
  324. volumeSliderScrollStep: number;
  325. /** Whether the volume should be locked to the same level across all tabs (changing in one changes in all others too) */
  326. volumeSharedBetweenTabs: boolean;
  327. /** Whether to set an initial volume level for each new session */
  328. setInitialTabVolume: boolean;
  329. /** The initial volume level to set for each new session */
  330. initialTabVolumeLevel: number;
  331. //#region song lists
  332. /** Add a button to each song in the queue to quickly open its lyrics page */
  333. lyricsQueueButton: boolean;
  334. /** Add a button to each song in the queue to quickly remove it */
  335. deleteFromQueueButton: boolean;
  336. /** Where to place the buttons in the queue */
  337. listButtonsPlacement: "queueOnly" | "everywhere";
  338. /** Add a button to the queue to scroll to the currently playing song */
  339. scrollToActiveSongBtn: boolean;
  340. //#region behavior
  341. /** Whether to completely disable the popup that sometimes appears before leaving the site */
  342. disableBeforeUnloadPopup: boolean;
  343. /** After how many milliseconds to close permanent toasts */
  344. closeToastsTimeout: number;
  345. /** Remember the last song's time when reloading or restoring the tab */
  346. rememberSongTime: boolean;
  347. /** Where to remember the song time */
  348. rememberSongTimeSites: SiteSelection;
  349. /** Time in seconds to remember the song time for */
  350. rememberSongTimeDuration: number;
  351. /** Time in seconds to subtract from the remembered song time */
  352. rememberSongTimeReduction: number;
  353. /** Minimum time in seconds the song needs to be played before it is remembered */
  354. rememberSongTimeMinPlayTime: number;
  355. //#region input
  356. /** Arrow keys skip forwards and backwards */
  357. arrowKeySupport: boolean;
  358. /** By how many seconds to skip when pressing the arrow keys */
  359. arrowKeySkipBy: number;
  360. /** Add a hotkey to switch between the YT and YTM sites on a video / song */
  361. switchBetweenSites: boolean;
  362. /** The hotkey that needs to be pressed to initiate the site switch */
  363. switchSitesHotkey: HotkeyObj;
  364. /** Make it so middle clicking a song to open it in a new tab (through thumbnail and song title) is easier */
  365. anchorImprovements: boolean;
  366. //#region lyrics
  367. /** Add a button to the media controls to open the current song's lyrics on genius.com in a new tab */
  368. geniusLyrics: boolean;
  369. /** Base URL to use for GeniURL */
  370. geniUrlBase: string;
  371. /** Token to use for GeniURL */
  372. geniUrlToken: string;
  373. /** Max size of lyrics cache */
  374. lyricsCacheMaxSize: number;
  375. /** Max TTL of lyrics cache entries, in ms */
  376. lyricsCacheTTL: number;
  377. /** Button to clear lyrics cache */
  378. clearLyricsCache: undefined;
  379. /** Whether to use advanced filtering when searching for lyrics (exact, exact-ish) */
  380. advancedLyricsFilter: boolean;
  381. //#region misc
  382. /** The locale to use for translations */
  383. locale: TrLocale;
  384. /** Whether to check for updates to the script */
  385. versionCheck: boolean;
  386. /** Button to check for updates */
  387. checkVersionNow: undefined;
  388. /** The console log level - 0 = Debug, 1 = Info */
  389. logLevel: LogLevel;
  390. /** Whether to show advanced settings in the config menu */
  391. advancedMode: boolean;
  392. }