types.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. /** Key of a resource in `assets/resources.json` and extra keys defined by `tools/post-build.ts` */
  28. export type ResourceKey = keyof typeof resources | `trans-${keyof typeof locales}` | "changelog" | "css-bundle";
  29. /** Describes a single hotkey */
  30. export type HotkeyObj = {
  31. code: string,
  32. shift: boolean,
  33. ctrl: boolean,
  34. alt: boolean,
  35. };
  36. export type LyricsCacheEntry = {
  37. artist: string;
  38. song: string;
  39. url: string;
  40. viewed: number;
  41. added: number;
  42. };
  43. //#region global
  44. // shim for the BYTM interface properties
  45. export type BytmObject =
  46. {
  47. [key: string]: unknown;
  48. locale: TrLocale;
  49. logLevel: LogLevel;
  50. }
  51. // information from the userscript header
  52. & typeof scriptInfo
  53. // certain variables from `src/constants.ts`
  54. & Pick<typeof consts, "mode" | "branch" | "host" | "buildNumber" | "compressionFormat">
  55. // global functions exposed through the interface in `src/interface.ts`
  56. & InterfaceFunctions
  57. // others
  58. & {
  59. // the entire UserUtils library
  60. UserUtils: typeof import("@sv443-network/userutils");
  61. };
  62. declare global {
  63. interface Window {
  64. // to see the expanded type, install the VS Code extension "MylesMurphy.prettify-ts" and hover over the property below
  65. // alternatively navigate with ctrl+click to find the types
  66. BYTM: BytmObject;
  67. }
  68. }
  69. //#region plugins
  70. /**
  71. * Intents (permissions) BYTM has to grant your plugin for it to be able to access certain features.
  72. * TODO: this feature is unfinished, but you should still specify the intents your plugin needs.
  73. */
  74. export enum PluginIntent {
  75. /** Plugin has access to hidden config values */
  76. HiddenConfigValues = 1,
  77. /** Plugin can write to the feature configuration */
  78. WriteFeatureConfig = 2,
  79. /** Plugin can write to the lyrics cache */
  80. WriteLyricsCache = 4,
  81. /** Plugin can add new translations and overwrite existing ones */
  82. WriteTranslations = 8,
  83. /** Plugin can create modal dialogs */
  84. CreateModalDialogs = 16,
  85. }
  86. /** Result of a plugin registration */
  87. export type PluginRegisterResult = {
  88. /** Public info about the registered plugin */
  89. info: PluginInfo;
  90. /** Emitter for plugin events - see {@linkcode PluginEventMap} for a list of events */
  91. events: Emitter<PluginEventMap>;
  92. }
  93. /** Minimal object that describes a plugin - this is all info the other installed plugins can see */
  94. export type PluginInfo = {
  95. /** Name of the plugin */
  96. name: string;
  97. /**
  98. * Adding the namespace and the name property makes the unique identifier for a plugin.
  99. * If one exists with the same name and namespace as this plugin, it may be overwritten at registration.
  100. * I recommend to set this value to a URL pointing to your homepage, or the author's username.
  101. */
  102. namespace: string;
  103. /** Version of the plugin as an array containing three whole numbers: `[major_version, minor_version, patch_version]` */
  104. version: [major: number, minor: number, patch: number];
  105. };
  106. /** Minimum part of the PluginDef object needed to make up the resolvable plugin identifier */
  107. export type PluginDefResolvable = PluginDef | { plugin: Pick<PluginDef["plugin"], "name" | "namespace"> };
  108. /** An object that describes a BYTM plugin */
  109. export type PluginDef = {
  110. plugin: PluginInfo & {
  111. /**
  112. * Descriptions of at least en_US and optionally any other locale supported by BYTM.
  113. * When an untranslated locale is set, the description will default to the value of en_US
  114. */
  115. description: Partial<Record<keyof typeof locales, string>> & {
  116. en_US: string;
  117. };
  118. /** URL to the plugin's icon - recommended size: 48x48 to 128x128 */
  119. iconUrl?: string;
  120. /** Homepage URLs for the plugin */
  121. homepage?: {
  122. /** Any other homepage URL */
  123. other?: string;
  124. /** URL to the plugin's source code (i.e. Git repo) */
  125. source?: 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?: (key: FeatureKey, initialVal: number | boolean | Record<string, unknown>, newVal: number | boolean | Record<string, unknown>) => 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. * All 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. /** Whether to fix various issues in the layout when HDR is supported and active */
  317. fixHdrIssues: boolean;
  318. //#region volume
  319. /** Add a percentage label to the volume slider */
  320. volumeSliderLabel: boolean;
  321. /** The width of the volume slider in pixels */
  322. volumeSliderSize: number;
  323. /** Volume slider sensitivity - the smaller this number, the finer the volume control */
  324. volumeSliderStep: number;
  325. /** Volume slider scroll wheel sensitivity */
  326. volumeSliderScrollStep: number;
  327. /** Whether the volume should be locked to the same level across all tabs (changing in one changes in all others too) */
  328. volumeSharedBetweenTabs: boolean;
  329. /** Whether to set an initial volume level for each new session */
  330. setInitialTabVolume: boolean;
  331. /** The initial volume level to set for each new session */
  332. initialTabVolumeLevel: number;
  333. //#region song lists
  334. /** Add a button to each song in the queue to quickly open its lyrics page */
  335. lyricsQueueButton: boolean;
  336. /** Add a button to each song in the queue to quickly remove it */
  337. deleteFromQueueButton: boolean;
  338. /** Where to place the buttons in the queue */
  339. listButtonsPlacement: "queueOnly" | "everywhere";
  340. /** Add a button above the queue to scroll to the currently playing song */
  341. scrollToActiveSongBtn: boolean;
  342. /** Add a button above the queue to clear it */
  343. clearQueueBtn: boolean;
  344. //#region behavior
  345. /** Whether to completely disable the popup that sometimes appears before leaving the site */
  346. disableBeforeUnloadPopup: boolean;
  347. /** After how many milliseconds to close permanent toasts */
  348. closeToastsTimeout: number;
  349. /** Remember the last song's time when reloading or restoring the tab */
  350. rememberSongTime: boolean;
  351. /** Where to remember the song time */
  352. rememberSongTimeSites: SiteSelection;
  353. /** Time in seconds to remember the song time for */
  354. rememberSongTimeDuration: number;
  355. /** Time in seconds to subtract from the remembered song time */
  356. rememberSongTimeReduction: number;
  357. /** Minimum time in seconds the song needs to be played before it is remembered */
  358. rememberSongTimeMinPlayTime: number;
  359. //#region input
  360. /** Arrow keys skip forwards and backwards */
  361. arrowKeySupport: boolean;
  362. /** By how many seconds to skip when pressing the arrow keys */
  363. arrowKeySkipBy: number;
  364. /** Add a hotkey to switch between the YT and YTM sites on a video / song */
  365. switchBetweenSites: boolean;
  366. /** The hotkey that needs to be pressed to initiate the site switch */
  367. switchSitesHotkey: HotkeyObj;
  368. /** Make it so middle clicking a song to open it in a new tab (through thumbnail and song title) is easier */
  369. anchorImprovements: boolean;
  370. //#region lyrics
  371. /** Add a button to the media controls to open the current song's lyrics on genius.com in a new tab */
  372. geniusLyrics: boolean;
  373. /** Base URL to use for GeniURL */
  374. geniUrlBase: string;
  375. /** Token to use for GeniURL */
  376. geniUrlToken: string;
  377. /** Max size of lyrics cache */
  378. lyricsCacheMaxSize: number;
  379. /** Max TTL of lyrics cache entries, in ms */
  380. lyricsCacheTTL: number;
  381. /** Button to clear lyrics cache */
  382. clearLyricsCache: undefined;
  383. /** Whether to use advanced filtering when searching for lyrics (exact, exact-ish) */
  384. advancedLyricsFilter: boolean;
  385. //#region misc
  386. /** The locale to use for translations */
  387. locale: TrLocale;
  388. /** Whether to check for updates to the script */
  389. versionCheck: boolean;
  390. /** Button to check for updates */
  391. checkVersionNow: undefined;
  392. /** The console log level - 0 = Debug, 1 = Info */
  393. logLevel: LogLevel;
  394. /** Whether to show advanced settings in the config menu */
  395. advancedMode: boolean;
  396. }