types.ts 16 KB

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