UserUtils

Library with various utilities for userscripts - register listeners for when CSS selectors exist, intercept events, create persistent & synchronous data stores, modify the DOM more easily and more

当前为 2024-08-28 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/472956/1436518/UserUtils.js

  1. // ==UserScript==
  2. // @namespace https://github.com/Sv443-Network/UserUtils
  3. // @exclude *
  4. // @author Sv443
  5. // @supportURL https://github.com/Sv443-Network/UserUtils/issues
  6. // @homepageURL https://github.com/Sv443-Network/UserUtils
  7.  
  8. // ==UserLibrary==
  9. // @name UserUtils
  10. // @description Library with various utilities for userscripts - register listeners for when CSS selectors exist, intercept events, create persistent & synchronous data stores, modify the DOM more easily and more
  11. // @version 7.2.1
  12. // @license MIT
  13. // @copyright Sv443 (https://github.com/Sv443)
  14.  
  15. // ==/UserScript==
  16. // ==/UserLibrary==
  17.  
  18. // ==OpenUserJS==
  19. // @author Sv443
  20. // ==/OpenUserJS==
  21.  
  22. var UserUtils = (function (exports) {
  23. var __defProp = Object.defineProperty;
  24. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  25. var __hasOwnProp = Object.prototype.hasOwnProperty;
  26. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  27. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  28. var __spreadValues = (a, b) => {
  29. for (var prop in b || (b = {}))
  30. if (__hasOwnProp.call(b, prop))
  31. __defNormalProp(a, prop, b[prop]);
  32. if (__getOwnPropSymbols)
  33. for (var prop of __getOwnPropSymbols(b)) {
  34. if (__propIsEnum.call(b, prop))
  35. __defNormalProp(a, prop, b[prop]);
  36. }
  37. return a;
  38. };
  39. var __objRest = (source, exclude) => {
  40. var target = {};
  41. for (var prop in source)
  42. if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
  43. target[prop] = source[prop];
  44. if (source != null && __getOwnPropSymbols)
  45. for (var prop of __getOwnPropSymbols(source)) {
  46. if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
  47. target[prop] = source[prop];
  48. }
  49. return target;
  50. };
  51. var __publicField = (obj, key, value) => {
  52. __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  53. return value;
  54. };
  55. var __async = (__this, __arguments, generator) => {
  56. return new Promise((resolve, reject) => {
  57. var fulfilled = (value) => {
  58. try {
  59. step(generator.next(value));
  60. } catch (e) {
  61. reject(e);
  62. }
  63. };
  64. var rejected = (value) => {
  65. try {
  66. step(generator.throw(value));
  67. } catch (e) {
  68. reject(e);
  69. }
  70. };
  71. var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
  72. step((generator = generator.apply(__this, __arguments)).next());
  73. });
  74. };
  75.  
  76. // lib/math.ts
  77. function clamp(value, min, max) {
  78. return Math.max(Math.min(value, max), min);
  79. }
  80. function mapRange(value, range1min, range1max, range2min, range2max) {
  81. if (Number(range1min) === 0 && Number(range2min) === 0)
  82. return value * (range2max / range1max);
  83. return (value - range1min) * ((range2max - range2min) / (range1max - range1min)) + range2min;
  84. }
  85. function randRange(...args) {
  86. let min, max;
  87. if (typeof args[0] === "number" && typeof args[1] === "number")
  88. [min, max] = args;
  89. else if (typeof args[0] === "number" && typeof args[1] !== "number") {
  90. min = 0;
  91. [max] = args;
  92. } else
  93. throw new TypeError(`Wrong parameter(s) provided - expected: "number" and "number|undefined", got: "${typeof args[0]}" and "${typeof args[1]}"`);
  94. min = Number(min);
  95. max = Number(max);
  96. if (isNaN(min) || isNaN(max))
  97. return NaN;
  98. if (min > max)
  99. throw new TypeError(`Parameter "min" can't be bigger than "max"`);
  100. return Math.floor(Math.random() * (max - min + 1)) + min;
  101. }
  102.  
  103. // lib/array.ts
  104. function randomItem(array) {
  105. return randomItemIndex(array)[0];
  106. }
  107. function randomItemIndex(array) {
  108. if (array.length === 0)
  109. return [void 0, void 0];
  110. const idx = randRange(array.length - 1);
  111. return [array[idx], idx];
  112. }
  113. function takeRandomItem(arr) {
  114. const [itm, idx] = randomItemIndex(arr);
  115. if (idx === void 0)
  116. return void 0;
  117. arr.splice(idx, 1);
  118. return itm;
  119. }
  120. function randomizeArray(array) {
  121. const retArray = [...array];
  122. if (array.length === 0)
  123. return retArray;
  124. for (let i = retArray.length - 1; i > 0; i--) {
  125. const j = Math.floor(randRange(0, 1e4) / 1e4 * (i + 1));
  126. [retArray[i], retArray[j]] = [retArray[j], retArray[i]];
  127. }
  128. return retArray;
  129. }
  130.  
  131. // lib/dom.ts
  132. function getUnsafeWindow() {
  133. try {
  134. return unsafeWindow;
  135. } catch (e) {
  136. return window;
  137. }
  138. }
  139. function addParent(element, newParent) {
  140. const oldParent = element.parentNode;
  141. if (!oldParent)
  142. throw new Error("Element doesn't have a parent node");
  143. oldParent.replaceChild(newParent, element);
  144. newParent.appendChild(element);
  145. return newParent;
  146. }
  147. function addGlobalStyle(style) {
  148. const styleElem = document.createElement("style");
  149. setInnerHtmlUnsafe(styleElem, style);
  150. document.head.appendChild(styleElem);
  151. return styleElem;
  152. }
  153. function preloadImages(srcUrls, rejects = false) {
  154. const promises = srcUrls.map((src) => new Promise((res, rej) => {
  155. const image = new Image();
  156. image.src = src;
  157. image.addEventListener("load", () => res(image));
  158. image.addEventListener("error", (evt) => rejects && rej(evt));
  159. }));
  160. return Promise.allSettled(promises);
  161. }
  162. function openInNewTab(href, background) {
  163. try {
  164. GM.openInTab(href, background);
  165. } catch (e) {
  166. const openElem = document.createElement("a");
  167. Object.assign(openElem, {
  168. className: "userutils-open-in-new-tab",
  169. target: "_blank",
  170. rel: "noopener noreferrer",
  171. href
  172. });
  173. openElem.style.display = "none";
  174. document.body.appendChild(openElem);
  175. openElem.click();
  176. setTimeout(openElem.remove, 50);
  177. }
  178. }
  179. function interceptEvent(eventObject, eventName, predicate = () => true) {
  180. Error.stackTraceLimit = Math.max(Error.stackTraceLimit, 100);
  181. if (isNaN(Error.stackTraceLimit))
  182. Error.stackTraceLimit = 100;
  183. (function(original) {
  184. eventObject.__proto__.addEventListener = function(...args) {
  185. var _a, _b;
  186. const origListener = typeof args[1] === "function" ? args[1] : (_b = (_a = args[1]) == null ? void 0 : _a.handleEvent) != null ? _b : () => void 0;
  187. args[1] = function(...a) {
  188. if (args[0] === eventName && predicate(Array.isArray(a) ? a[0] : a))
  189. return;
  190. else
  191. return origListener.apply(this, a);
  192. };
  193. original.apply(this, args);
  194. };
  195. })(eventObject.__proto__.addEventListener);
  196. }
  197. function interceptWindowEvent(eventName, predicate = () => true) {
  198. return interceptEvent(getUnsafeWindow(), eventName, predicate);
  199. }
  200. function isScrollable(element) {
  201. const { overflowX, overflowY } = getComputedStyle(element);
  202. return {
  203. vertical: (overflowY === "scroll" || overflowY === "auto") && element.scrollHeight > element.clientHeight,
  204. horizontal: (overflowX === "scroll" || overflowX === "auto") && element.scrollWidth > element.clientWidth
  205. };
  206. }
  207. function observeElementProp(element, property, callback) {
  208. const elementPrototype = Object.getPrototypeOf(element);
  209. if (elementPrototype.hasOwnProperty(property)) {
  210. const descriptor = Object.getOwnPropertyDescriptor(elementPrototype, property);
  211. Object.defineProperty(element, property, {
  212. get: function() {
  213. var _a;
  214. return (_a = descriptor == null ? void 0 : descriptor.get) == null ? void 0 : _a.apply(this, arguments);
  215. },
  216. set: function() {
  217. var _a;
  218. const oldValue = this[property];
  219. (_a = descriptor == null ? void 0 : descriptor.set) == null ? void 0 : _a.apply(this, arguments);
  220. const newValue = this[property];
  221. if (typeof callback === "function") {
  222. callback.bind(this, oldValue, newValue);
  223. }
  224. return newValue;
  225. }
  226. });
  227. }
  228. }
  229. function getSiblingsFrame(refElement, siblingAmount, refElementAlignment = "center-top", includeRef = true) {
  230. var _a, _b;
  231. const siblings = [...(_b = (_a = refElement.parentNode) == null ? void 0 : _a.childNodes) != null ? _b : []];
  232. const elemSiblIdx = siblings.indexOf(refElement);
  233. if (elemSiblIdx === -1)
  234. throw new Error("Element doesn't have a parent node");
  235. if (refElementAlignment === "top")
  236. return [...siblings.slice(elemSiblIdx + Number(!includeRef), elemSiblIdx + siblingAmount + Number(!includeRef))];
  237. else if (refElementAlignment.startsWith("center-")) {
  238. const halfAmount = (refElementAlignment === "center-bottom" ? Math.ceil : Math.floor)(siblingAmount / 2);
  239. const startIdx = Math.max(0, elemSiblIdx - halfAmount);
  240. const topOffset = Number(refElementAlignment === "center-top" && siblingAmount % 2 === 0 && includeRef);
  241. const btmOffset = Number(refElementAlignment === "center-bottom" && siblingAmount % 2 !== 0 && includeRef);
  242. const startIdxWithOffset = startIdx + topOffset + btmOffset;
  243. return [
  244. ...siblings.filter((_, idx) => includeRef || idx !== elemSiblIdx).slice(startIdxWithOffset, startIdxWithOffset + siblingAmount)
  245. ];
  246. } else if (refElementAlignment === "bottom")
  247. return [...siblings.slice(elemSiblIdx - siblingAmount + Number(includeRef), elemSiblIdx + Number(includeRef))];
  248. return [];
  249. }
  250. var ttPolicy;
  251. function setInnerHtmlUnsafe(element, html) {
  252. var _a, _b, _c;
  253. if (!ttPolicy && typeof ((_a = window == null ? void 0 : window.trustedTypes) == null ? void 0 : _a.createPolicy) === "function") {
  254. ttPolicy = window.trustedTypes.createPolicy("_uu_set_innerhtml_unsafe", {
  255. createHTML: (unsafeHtml) => unsafeHtml
  256. });
  257. }
  258. element.innerHTML = (_c = (_b = ttPolicy == null ? void 0 : ttPolicy.createHTML) == null ? void 0 : _b.call(ttPolicy, html)) != null ? _c : html;
  259. return element;
  260. }
  261.  
  262. // lib/crypto.ts
  263. function compress(input, compressionFormat, outputType = "string") {
  264. return __async(this, null, function* () {
  265. const byteArray = typeof input === "string" ? new TextEncoder().encode(input) : input;
  266. const comp = new CompressionStream(compressionFormat);
  267. const writer = comp.writable.getWriter();
  268. writer.write(byteArray);
  269. writer.close();
  270. const buf = yield new Response(comp.readable).arrayBuffer();
  271. return outputType === "arrayBuffer" ? buf : ab2str(buf);
  272. });
  273. }
  274. function decompress(input, compressionFormat, outputType = "string") {
  275. return __async(this, null, function* () {
  276. const byteArray = typeof input === "string" ? str2ab(input) : input;
  277. const decomp = new DecompressionStream(compressionFormat);
  278. const writer = decomp.writable.getWriter();
  279. writer.write(byteArray);
  280. writer.close();
  281. const buf = yield new Response(decomp.readable).arrayBuffer();
  282. return outputType === "arrayBuffer" ? buf : new TextDecoder().decode(buf);
  283. });
  284. }
  285. function ab2str(buf) {
  286. return getUnsafeWindow().btoa(
  287. new Uint8Array(buf).reduce((data, byte) => data + String.fromCharCode(byte), "")
  288. );
  289. }
  290. function str2ab(str) {
  291. return Uint8Array.from(getUnsafeWindow().atob(str), (c) => c.charCodeAt(0));
  292. }
  293. function computeHash(input, algorithm = "SHA-256") {
  294. return __async(this, null, function* () {
  295. let data;
  296. if (typeof input === "string") {
  297. const encoder = new TextEncoder();
  298. data = encoder.encode(input);
  299. } else
  300. data = input;
  301. const hashBuffer = yield crypto.subtle.digest(algorithm, data);
  302. const hashArray = Array.from(new Uint8Array(hashBuffer));
  303. const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
  304. return hashHex;
  305. });
  306. }
  307. function randomId(length = 16, radix = 16, enhancedEntropy = false) {
  308. if (enhancedEntropy) {
  309. const arr = new Uint8Array(length);
  310. crypto.getRandomValues(arr);
  311. return Array.from(
  312. arr,
  313. (v) => mapRange(v, 0, 255, 0, radix).toString(radix).substring(0, 1)
  314. ).join("");
  315. }
  316. return Array.from(
  317. { length },
  318. () => Math.floor(Math.random() * radix).toString(radix)
  319. ).join("");
  320. }
  321.  
  322. // lib/DataStore.ts
  323. var DataStore = class {
  324. /**
  325. * Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
  326. * Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
  327. *
  328. * ⚠️ Requires the directives `@grant GM.getValue` and `@grant GM.setValue` if the storageMethod is left as the default of `"GM"`
  329. * ⚠️ Make sure to call {@linkcode loadData()} at least once after creating an instance, or the returned data will be the same as `options.defaultData`
  330. *
  331. * @template TData The type of the data that is saved in persistent storage for the currently set format version (will be automatically inferred from `defaultData` if not provided) - **This has to be a JSON-compatible object!** (no undefined, circular references, etc.)
  332. * @param options The options for this DataStore instance
  333. */
  334. constructor(options) {
  335. __publicField(this, "id");
  336. __publicField(this, "formatVersion");
  337. __publicField(this, "defaultData");
  338. __publicField(this, "encodeData");
  339. __publicField(this, "decodeData");
  340. __publicField(this, "storageMethod");
  341. __publicField(this, "cachedData");
  342. __publicField(this, "migrations");
  343. var _a;
  344. this.id = options.id;
  345. this.formatVersion = options.formatVersion;
  346. this.defaultData = options.defaultData;
  347. this.cachedData = options.defaultData;
  348. this.migrations = options.migrations;
  349. this.storageMethod = (_a = options.storageMethod) != null ? _a : "GM";
  350. this.encodeData = options.encodeData;
  351. this.decodeData = options.decodeData;
  352. }
  353. //#region public
  354. /**
  355. * Loads the data saved in persistent storage into the in-memory cache and also returns it.
  356. * Automatically populates persistent storage with default data if it doesn't contain any data yet.
  357. * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
  358. */
  359. loadData() {
  360. return __async(this, null, function* () {
  361. try {
  362. const gmData = yield this.getValue(`_uucfg-${this.id}`, JSON.stringify(this.defaultData));
  363. let gmFmtVer = Number(yield this.getValue(`_uucfgver-${this.id}`, NaN));
  364. if (typeof gmData !== "string") {
  365. yield this.saveDefaultData();
  366. return __spreadValues({}, this.defaultData);
  367. }
  368. const isEncoded = Boolean(yield this.getValue(`_uucfgenc-${this.id}`, false));
  369. let saveData = false;
  370. if (isNaN(gmFmtVer)) {
  371. yield this.setValue(`_uucfgver-${this.id}`, gmFmtVer = this.formatVersion);
  372. saveData = true;
  373. }
  374. let parsed = yield this.deserializeData(gmData, isEncoded);
  375. if (gmFmtVer < this.formatVersion && this.migrations)
  376. parsed = yield this.runMigrations(parsed, gmFmtVer);
  377. if (saveData)
  378. yield this.setData(parsed);
  379. this.cachedData = __spreadValues({}, parsed);
  380. return this.cachedData;
  381. } catch (err) {
  382. console.warn("Error while parsing JSON data, resetting it to the default value.", err);
  383. yield this.saveDefaultData();
  384. return this.defaultData;
  385. }
  386. });
  387. }
  388. /**
  389. * Returns a copy of the data from the in-memory cache.
  390. * Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
  391. * @param deepCopy Whether to return a deep copy of the data (default: `false`) - only necessary if your data object is nested and may have a bigger performance impact if enabled
  392. */
  393. getData(deepCopy = false) {
  394. return deepCopy ? this.deepCopy(this.cachedData) : __spreadValues({}, this.cachedData);
  395. }
  396. /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
  397. setData(data) {
  398. this.cachedData = data;
  399. const useEncoding = this.encodingEnabled();
  400. return new Promise((resolve) => __async(this, null, function* () {
  401. yield Promise.all([
  402. this.setValue(`_uucfg-${this.id}`, yield this.serializeData(data, useEncoding)),
  403. this.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  404. this.setValue(`_uucfgenc-${this.id}`, useEncoding)
  405. ]);
  406. resolve();
  407. }));
  408. }
  409. /** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
  410. saveDefaultData() {
  411. return __async(this, null, function* () {
  412. this.cachedData = this.defaultData;
  413. const useEncoding = this.encodingEnabled();
  414. return new Promise((resolve) => __async(this, null, function* () {
  415. yield Promise.all([
  416. this.setValue(`_uucfg-${this.id}`, yield this.serializeData(this.defaultData, useEncoding)),
  417. this.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  418. this.setValue(`_uucfgenc-${this.id}`, useEncoding)
  419. ]);
  420. resolve();
  421. }));
  422. });
  423. }
  424. /**
  425. * Call this method to clear all persistently stored data associated with this DataStore instance.
  426. * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
  427. * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
  428. *
  429. * ⚠️ This requires the additional directive `@grant GM.deleteValue`
  430. */
  431. deleteData() {
  432. return __async(this, null, function* () {
  433. yield Promise.all([
  434. this.deleteValue(`_uucfg-${this.id}`),
  435. this.deleteValue(`_uucfgver-${this.id}`),
  436. this.deleteValue(`_uucfgenc-${this.id}`)
  437. ]);
  438. });
  439. }
  440. /** Returns whether encoding and decoding are enabled for this DataStore instance */
  441. encodingEnabled() {
  442. return Boolean(this.encodeData && this.decodeData);
  443. }
  444. //#region migrations
  445. /**
  446. * Runs all necessary migration functions consecutively and saves the result to the in-memory cache and persistent storage and also returns it.
  447. * This method is automatically called by {@linkcode loadData()} if the data format has changed since the last time the data was saved.
  448. * Though calling this method manually is not necessary, it can be useful if you want to run migrations for special occasions like a user importing potentially outdated data that has been previously exported.
  449. *
  450. * If one of the migrations fails, the data will be reset to the default value if `resetOnError` is set to `true` (default). Otherwise, an error will be thrown and no data will be saved.
  451. */
  452. runMigrations(oldData, oldFmtVer, resetOnError = true) {
  453. return __async(this, null, function* () {
  454. if (!this.migrations)
  455. return oldData;
  456. let newData = oldData;
  457. const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
  458. let lastFmtVer = oldFmtVer;
  459. for (const [fmtVer, migrationFunc] of sortedMigrations) {
  460. const ver = Number(fmtVer);
  461. if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
  462. try {
  463. const migRes = migrationFunc(newData);
  464. newData = migRes instanceof Promise ? yield migRes : migRes;
  465. lastFmtVer = oldFmtVer = ver;
  466. } catch (err) {
  467. if (!resetOnError)
  468. throw new Error(`Error while running migration function for format version '${fmtVer}'`);
  469. console.error(`Error while running migration function for format version '${fmtVer}' - resetting to the default value.`, err);
  470. yield this.saveDefaultData();
  471. return this.getData();
  472. }
  473. }
  474. }
  475. yield Promise.all([
  476. this.setValue(`_uucfg-${this.id}`, yield this.serializeData(newData)),
  477. this.setValue(`_uucfgver-${this.id}`, lastFmtVer),
  478. this.setValue(`_uucfgenc-${this.id}`, this.encodingEnabled())
  479. ]);
  480. return this.cachedData = __spreadValues({}, newData);
  481. });
  482. }
  483. //#region serialization
  484. /** Serializes the data using the optional this.encodeData() and returns it as a string */
  485. serializeData(data, useEncoding = true) {
  486. return __async(this, null, function* () {
  487. const stringData = JSON.stringify(data);
  488. if (!this.encodingEnabled() || !useEncoding)
  489. return stringData;
  490. const encRes = this.encodeData(stringData);
  491. if (encRes instanceof Promise)
  492. return yield encRes;
  493. return encRes;
  494. });
  495. }
  496. /** Deserializes the data using the optional this.decodeData() and returns it as a JSON object */
  497. deserializeData(data, useEncoding = true) {
  498. return __async(this, null, function* () {
  499. let decRes = this.encodingEnabled() && useEncoding ? this.decodeData(data) : void 0;
  500. if (decRes instanceof Promise)
  501. decRes = yield decRes;
  502. return JSON.parse(decRes != null ? decRes : data);
  503. });
  504. }
  505. //#region misc
  506. /** Copies a JSON-compatible object and loses all its internal references in the process */
  507. deepCopy(obj) {
  508. return JSON.parse(JSON.stringify(obj));
  509. }
  510. //#region storage
  511. /** Gets a value from persistent storage - can be overwritten in a subclass if you want to use something other than GM storage */
  512. getValue(name, defaultValue) {
  513. return __async(this, null, function* () {
  514. var _a, _b;
  515. switch (this.storageMethod) {
  516. case "localStorage":
  517. return (_a = localStorage.getItem(name)) != null ? _a : defaultValue;
  518. case "sessionStorage":
  519. return (_b = sessionStorage.getItem(name)) != null ? _b : defaultValue;
  520. default:
  521. return GM.getValue(name, defaultValue);
  522. }
  523. });
  524. }
  525. /**
  526. * Sets a value in persistent storage - can be overwritten in a subclass if you want to use something other than GM storage.
  527. * The default storage engines will stringify all passed values like numbers or booleans, so be aware of that.
  528. */
  529. setValue(name, value) {
  530. return __async(this, null, function* () {
  531. switch (this.storageMethod) {
  532. case "localStorage":
  533. return localStorage.setItem(name, String(value));
  534. case "sessionStorage":
  535. return sessionStorage.setItem(name, String(value));
  536. default:
  537. return GM.setValue(name, String(value));
  538. }
  539. });
  540. }
  541. /** Deletes a value from persistent storage - can be overwritten in a subclass if you want to use something other than GM storage */
  542. deleteValue(name) {
  543. return __async(this, null, function* () {
  544. switch (this.storageMethod) {
  545. case "localStorage":
  546. return localStorage.removeItem(name);
  547. case "sessionStorage":
  548. return sessionStorage.removeItem(name);
  549. default:
  550. return GM.deleteValue(name);
  551. }
  552. });
  553. }
  554. };
  555.  
  556. // lib/DataStoreSerializer.ts
  557. var DataStoreSerializer = class {
  558. constructor(stores, options = {}) {
  559. __publicField(this, "stores");
  560. __publicField(this, "options");
  561. if (!getUnsafeWindow().crypto || !getUnsafeWindow().crypto.subtle)
  562. throw new Error("DataStoreSerializer has to run in a secure context (HTTPS)!");
  563. this.stores = stores;
  564. this.options = __spreadValues({
  565. addChecksum: true,
  566. ensureIntegrity: true
  567. }, options);
  568. }
  569. /** Calculates the checksum of a string */
  570. calcChecksum(input) {
  571. return __async(this, null, function* () {
  572. return computeHash(input, "SHA-256");
  573. });
  574. }
  575. /** Serializes a DataStore instance */
  576. serializeStore(storeInst) {
  577. return __async(this, null, function* () {
  578. const data = storeInst.encodingEnabled() ? yield storeInst.encodeData(JSON.stringify(storeInst.getData())) : JSON.stringify(storeInst.getData());
  579. const checksum = this.options.addChecksum ? yield this.calcChecksum(data) : void 0;
  580. return {
  581. id: storeInst.id,
  582. data,
  583. formatVersion: storeInst.formatVersion,
  584. encoded: storeInst.encodingEnabled(),
  585. checksum
  586. };
  587. });
  588. }
  589. /** Serializes the data stores into a string */
  590. serialize() {
  591. return __async(this, null, function* () {
  592. const serData = [];
  593. for (const store of this.stores)
  594. serData.push(yield this.serializeStore(store));
  595. return JSON.stringify(serData);
  596. });
  597. }
  598. /**
  599. * Deserializes the data exported via {@linkcode serialize()} and imports it into the DataStore instances.
  600. * Also triggers the migration process if the data format has changed.
  601. */
  602. deserialize(serializedData) {
  603. return __async(this, null, function* () {
  604. const deserStores = JSON.parse(serializedData);
  605. for (const storeData of deserStores) {
  606. const storeInst = this.stores.find((s) => s.id === storeData.id);
  607. if (!storeInst)
  608. throw new Error(`DataStore instance with ID "${storeData.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);
  609. if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
  610. const checksum = yield this.calcChecksum(storeData.data);
  611. if (checksum !== storeData.checksum)
  612. throw new Error(`Checksum mismatch for DataStore with ID "${storeData.id}"!
  613. Expected: ${storeData.checksum}
  614. Has: ${checksum}`);
  615. }
  616. const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData(storeData.data) : storeData.data;
  617. if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
  618. yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
  619. else
  620. yield storeInst.setData(JSON.parse(decodedData));
  621. }
  622. });
  623. }
  624. };
  625.  
  626. // node_modules/nanoevents/index.js
  627. var createNanoEvents = () => ({
  628. emit(event, ...args) {
  629. for (let i = 0, callbacks = this.events[event] || [], length = callbacks.length; i < length; i++) {
  630. callbacks[i](...args);
  631. }
  632. },
  633. events: {},
  634. on(event, cb) {
  635. var _a;
  636. ((_a = this.events)[event] || (_a[event] = [])).push(cb);
  637. return () => {
  638. var _a2;
  639. this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
  640. };
  641. }
  642. });
  643.  
  644. // lib/NanoEmitter.ts
  645. var NanoEmitter = class {
  646. constructor(options = {}) {
  647. __publicField(this, "events", createNanoEvents());
  648. __publicField(this, "eventUnsubscribes", []);
  649. __publicField(this, "emitterOptions");
  650. this.emitterOptions = __spreadValues({
  651. publicEmit: false
  652. }, options);
  653. }
  654. /** Subscribes to an event - returns a function that unsubscribes the event listener */
  655. on(event, cb) {
  656. let unsub;
  657. const unsubProxy = () => {
  658. if (!unsub)
  659. return;
  660. unsub();
  661. this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => u !== unsub);
  662. };
  663. unsub = this.events.on(event, cb);
  664. this.eventUnsubscribes.push(unsub);
  665. return unsubProxy;
  666. }
  667. /** Subscribes to an event and calls the callback or resolves the Promise only once */
  668. once(event, cb) {
  669. return new Promise((resolve) => {
  670. let unsub;
  671. const onceProxy = (...args) => {
  672. unsub();
  673. cb == null ? void 0 : cb(...args);
  674. resolve(args);
  675. };
  676. unsub = this.on(event, onceProxy);
  677. });
  678. }
  679. /** Emits an event on this instance - Needs `publicEmit` to be set to true in the constructor! */
  680. emit(event, ...args) {
  681. if (this.emitterOptions.publicEmit) {
  682. this.events.emit(event, ...args);
  683. return true;
  684. }
  685. return false;
  686. }
  687. /** Unsubscribes all event listeners */
  688. unsubscribeAll() {
  689. for (const unsub of this.eventUnsubscribes)
  690. unsub();
  691. this.eventUnsubscribes = [];
  692. }
  693. };
  694.  
  695. // lib/Dialog.ts
  696. var defaultDialogCss = `.uu-no-select {
  697. user-select: none;
  698. }
  699.  
  700. .uu-dialog-bg {
  701. --uu-dialog-bg: #333333;
  702. --uu-dialog-bg-highlight: #252525;
  703. --uu-scroll-indicator-bg: rgba(10, 10, 10, 0.7);
  704. --uu-dialog-separator-color: #797979;
  705. --uu-dialog-border-radius: 10px;
  706. }
  707.  
  708. .uu-dialog-bg {
  709. display: block;
  710. position: fixed;
  711. width: 100%;
  712. height: 100%;
  713. top: 0;
  714. left: 0;
  715. z-index: 5;
  716. background-color: rgba(0, 0, 0, 0.6);
  717. }
  718.  
  719. .uu-dialog {
  720. --uu-calc-dialog-height: calc(min(100vh - 40px, var(--uu-dialog-height-max)));
  721. position: absolute;
  722. display: flex;
  723. flex-direction: column;
  724. width: calc(min(100% - 60px, var(--uu-dialog-width-max)));
  725. border-radius: var(--uu-dialog-border-radius);
  726. height: auto;
  727. max-height: var(--uu-calc-dialog-height);
  728. left: 50%;
  729. top: 50%;
  730. transform: translate(-50%, -50%);
  731. z-index: 6;
  732. color: #fff;
  733. background-color: var(--uu-dialog-bg);
  734. }
  735.  
  736. .uu-dialog.align-top {
  737. top: 0;
  738. transform: translate(-50%, 40px);
  739. }
  740.  
  741. .uu-dialog.align-bottom {
  742. top: 100%;
  743. transform: translate(-50%, -100%);
  744. }
  745.  
  746. .uu-dialog-body {
  747. font-size: 1.5rem;
  748. padding: 20px;
  749. }
  750.  
  751. .uu-dialog-body.small {
  752. padding: 15px;
  753. }
  754.  
  755. #uu-dialog-opts {
  756. display: flex;
  757. flex-direction: column;
  758. position: relative;
  759. padding: 30px 0px;
  760. overflow-y: auto;
  761. }
  762.  
  763. .uu-dialog-header {
  764. display: flex;
  765. justify-content: space-between;
  766. align-items: center;
  767. margin-bottom: 6px;
  768. padding: 15px 20px 15px 20px;
  769. background-color: var(--uu-dialog-bg);
  770. border: 2px solid var(--uu-dialog-separator-color);
  771. border-style: none none solid none !important;
  772. border-radius: var(--uu-dialog-border-radius) var(--uu-dialog-border-radius) 0px 0px;
  773. }
  774.  
  775. .uu-dialog-header.small {
  776. padding: 10px 15px;
  777. border-style: none none solid none !important;
  778. }
  779.  
  780. .uu-dialog-header-pad {
  781. content: " ";
  782. min-height: 32px;
  783. }
  784.  
  785. .uu-dialog-header-pad.small {
  786. min-height: 24px;
  787. }
  788.  
  789. .uu-dialog-titlecont {
  790. display: flex;
  791. align-items: center;
  792. }
  793.  
  794. .uu-dialog-titlecont-no-title {
  795. display: flex;
  796. justify-content: flex-end;
  797. align-items: center;
  798. }
  799.  
  800. .uu-dialog-title {
  801. position: relative;
  802. display: inline-block;
  803. font-size: 22px;
  804. }
  805.  
  806. .uu-dialog-close {
  807. cursor: pointer;
  808. }
  809.  
  810. .uu-dialog-header-img,
  811. .uu-dialog-close
  812. {
  813. width: 32px;
  814. height: 32px;
  815. }
  816.  
  817. .uu-dialog-header-img.small,
  818. .uu-dialog-close.small
  819. {
  820. width: 24px;
  821. height: 24px;
  822. }
  823.  
  824. .uu-dialog-footer {
  825. font-size: 17px;
  826. text-decoration: underline;
  827. }
  828.  
  829. .uu-dialog-footer.hidden {
  830. display: none;
  831. }
  832.  
  833. .uu-dialog-footer-cont {
  834. margin-top: 6px;
  835. padding: 15px 20px;
  836. background: var(--uu-dialog-bg);
  837. background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, var(--uu-dialog-bg) 30%, var(--uu-dialog-bg) 100%);
  838. border: 2px solid var(--uu-dialog-separator-color);
  839. border-style: solid none none none !important;
  840. border-radius: 0px 0px var(--uu-dialog-border-radius) var(--uu-dialog-border-radius);
  841. }
  842.  
  843. .uu-dialog-footer-buttons-cont button:not(:last-of-type) {
  844. margin-right: 15px;
  845. }`;
  846. exports.currentDialogId = null;
  847. var openDialogs = [];
  848. var defaultStrings = {
  849. closeDialogTooltip: "Click to close the dialog"
  850. };
  851. var Dialog = class _Dialog extends NanoEmitter {
  852. constructor(options) {
  853. super();
  854. /** Options passed to the dialog in the constructor */
  855. __publicField(this, "options");
  856. /** ID that gets added to child element IDs - has to be unique and conform to HTML ID naming rules! */
  857. __publicField(this, "id");
  858. /** Strings used in the dialog (used for translations) */
  859. __publicField(this, "strings");
  860. __publicField(this, "dialogOpen", false);
  861. __publicField(this, "dialogMounted", false);
  862. const _a = options, { strings } = _a, opts = __objRest(_a, ["strings"]);
  863. this.strings = __spreadValues(__spreadValues({}, defaultStrings), strings != null ? strings : {});
  864. this.options = __spreadValues({
  865. closeOnBgClick: true,
  866. closeOnEscPress: true,
  867. destroyOnClose: false,
  868. unmountOnClose: true,
  869. removeListenersOnDestroy: true,
  870. small: false,
  871. verticalAlign: "center"
  872. }, opts);
  873. this.id = opts.id;
  874. }
  875. //#region public
  876. /** Call after DOMContentLoaded to pre-render the dialog and invisibly mount it in the DOM */
  877. mount() {
  878. return __async(this, null, function* () {
  879. var _a;
  880. if (this.dialogMounted)
  881. return;
  882. this.dialogMounted = true;
  883. if (!document.querySelector("style.uu-dialog-css"))
  884. addGlobalStyle((_a = this.options.dialogCss) != null ? _a : defaultDialogCss).classList.add("uu-dialog-css");
  885. const bgElem = document.createElement("div");
  886. bgElem.id = `uu-${this.id}-dialog-bg`;
  887. bgElem.classList.add("uu-dialog-bg");
  888. if (this.options.closeOnBgClick)
  889. bgElem.ariaLabel = bgElem.title = this.getString("closeDialogTooltip");
  890. bgElem.style.setProperty("--uu-dialog-width-max", `${this.options.width}px`);
  891. bgElem.style.setProperty("--uu-dialog-height-max", `${this.options.height}px`);
  892. bgElem.style.visibility = "hidden";
  893. bgElem.style.display = "none";
  894. bgElem.inert = true;
  895. bgElem.appendChild(yield this.getDialogContent());
  896. document.body.appendChild(bgElem);
  897. this.attachListeners(bgElem);
  898. this.events.emit("render");
  899. return bgElem;
  900. });
  901. }
  902. /** Closes the dialog and clears all its contents (unmounts elements from the DOM) in preparation for a new rendering call */
  903. unmount() {
  904. var _a;
  905. this.close();
  906. this.dialogMounted = false;
  907. const clearSelectors = [
  908. `#uu-${this.id}-dialog-bg`,
  909. `#uu-style-dialog-${this.id}`
  910. ];
  911. for (const sel of clearSelectors)
  912. (_a = document.querySelector(sel)) == null ? void 0 : _a.remove();
  913. this.events.emit("clear");
  914. }
  915. /** Clears the DOM of the dialog and then renders it again */
  916. remount() {
  917. return __async(this, null, function* () {
  918. this.unmount();
  919. yield this.mount();
  920. });
  921. }
  922. /**
  923. * Opens the dialog - also mounts it if it hasn't been mounted yet
  924. * Prevents default action and immediate propagation of the passed event
  925. */
  926. open(e) {
  927. return __async(this, null, function* () {
  928. var _a;
  929. e == null ? void 0 : e.preventDefault();
  930. e == null ? void 0 : e.stopImmediatePropagation();
  931. if (this.isOpen())
  932. return;
  933. this.dialogOpen = true;
  934. if (openDialogs.includes(this.id))
  935. throw new Error(`A dialog with the same ID of '${this.id}' already exists and is open!`);
  936. if (!this.isMounted())
  937. yield this.mount();
  938. const dialogBg = document.querySelector(`#uu-${this.id}-dialog-bg`);
  939. if (!dialogBg)
  940. return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
  941. dialogBg.style.visibility = "visible";
  942. dialogBg.style.display = "block";
  943. dialogBg.inert = false;
  944. exports.currentDialogId = this.id;
  945. openDialogs.unshift(this.id);
  946. for (const dialogId of openDialogs)
  947. if (dialogId !== this.id)
  948. (_a = document.querySelector(`#uu-${dialogId}-dialog-bg`)) == null ? void 0 : _a.setAttribute("inert", "true");
  949. document.body.classList.remove("uu-no-select");
  950. document.body.setAttribute("inert", "true");
  951. this.events.emit("open");
  952. return dialogBg;
  953. });
  954. }
  955. /** Closes the dialog - prevents default action and immediate propagation of the passed event */
  956. close(e) {
  957. var _a, _b;
  958. e == null ? void 0 : e.preventDefault();
  959. e == null ? void 0 : e.stopImmediatePropagation();
  960. if (!this.isOpen())
  961. return;
  962. this.dialogOpen = false;
  963. const dialogBg = document.querySelector(`#uu-${this.id}-dialog-bg`);
  964. if (!dialogBg)
  965. return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
  966. dialogBg.style.visibility = "hidden";
  967. dialogBg.style.display = "none";
  968. dialogBg.inert = true;
  969. openDialogs.splice(openDialogs.indexOf(this.id), 1);
  970. exports.currentDialogId = (_a = openDialogs[0]) != null ? _a : null;
  971. if (exports.currentDialogId)
  972. (_b = document.querySelector(`#uu-${exports.currentDialogId}-dialog-bg`)) == null ? void 0 : _b.removeAttribute("inert");
  973. if (openDialogs.length === 0) {
  974. document.body.classList.add("uu-no-select");
  975. document.body.removeAttribute("inert");
  976. }
  977. this.events.emit("close");
  978. if (this.options.destroyOnClose)
  979. this.destroy();
  980. else if (this.options.unmountOnClose)
  981. this.unmount();
  982. }
  983. /** Returns true if the dialog is currently open */
  984. isOpen() {
  985. return this.dialogOpen;
  986. }
  987. /** Returns true if the dialog is currently mounted */
  988. isMounted() {
  989. return this.dialogMounted;
  990. }
  991. /** Clears the DOM of the dialog and removes all event listeners */
  992. destroy() {
  993. this.unmount();
  994. this.events.emit("destroy");
  995. this.options.removeListenersOnDestroy && this.unsubscribeAll();
  996. }
  997. //#region static
  998. /** Returns the ID of the top-most dialog (the dialog that has been opened last) */
  999. static getCurrentDialogId() {
  1000. return exports.currentDialogId;
  1001. }
  1002. /** Returns the IDs of all currently open dialogs, top-most first */
  1003. static getOpenDialogs() {
  1004. return openDialogs;
  1005. }
  1006. //#region protected
  1007. getString(key) {
  1008. var _a;
  1009. return (_a = this.strings[key]) != null ? _a : defaultStrings[key];
  1010. }
  1011. /** Called once to attach all generic event listeners */
  1012. attachListeners(bgElem) {
  1013. if (this.options.closeOnBgClick) {
  1014. bgElem.addEventListener("click", (e) => {
  1015. var _a;
  1016. if (this.isOpen() && ((_a = e.target) == null ? void 0 : _a.id) === `uu-${this.id}-dialog-bg`)
  1017. this.close(e);
  1018. });
  1019. }
  1020. if (this.options.closeOnEscPress) {
  1021. document.body.addEventListener("keydown", (e) => {
  1022. if (e.key === "Escape" && this.isOpen() && _Dialog.getCurrentDialogId() === this.id)
  1023. this.close(e);
  1024. });
  1025. }
  1026. }
  1027. //#region protected
  1028. /**
  1029. * Adds generic, accessible interaction listeners to the passed element.
  1030. * All listeners have the default behavior prevented and stop propagation (for keyboard events only as long as the captured key is valid).
  1031. * @param listenerOptions Provide a {@linkcode listenerOptions} object to configure the listeners
  1032. */
  1033. onInteraction(elem, listener, listenerOptions) {
  1034. const _a = listenerOptions != null ? listenerOptions : {}, { preventDefault = true, stopPropagation = true } = _a, listenerOpts = __objRest(_a, ["preventDefault", "stopPropagation"]);
  1035. const interactionKeys = ["Enter", " ", "Space"];
  1036. const proxListener = (e) => {
  1037. if (e instanceof KeyboardEvent) {
  1038. if (interactionKeys.includes(e.key)) {
  1039. preventDefault && e.preventDefault();
  1040. stopPropagation && e.stopPropagation();
  1041. } else
  1042. return;
  1043. } else if (e instanceof MouseEvent) {
  1044. preventDefault && e.preventDefault();
  1045. stopPropagation && e.stopPropagation();
  1046. }
  1047. (listenerOpts == null ? void 0 : listenerOpts.once) && e.type === "keydown" && elem.removeEventListener("click", proxListener, listenerOpts);
  1048. (listenerOpts == null ? void 0 : listenerOpts.once) && e.type === "click" && elem.removeEventListener("keydown", proxListener, listenerOpts);
  1049. listener(e);
  1050. };
  1051. elem.addEventListener("click", proxListener, listenerOpts);
  1052. elem.addEventListener("keydown", proxListener, listenerOpts);
  1053. }
  1054. /** Returns the dialog content element and all its children */
  1055. getDialogContent() {
  1056. return __async(this, null, function* () {
  1057. var _a, _b, _c, _d;
  1058. const header = (_b = (_a = this.options).renderHeader) == null ? void 0 : _b.call(_a);
  1059. const footer = (_d = (_c = this.options).renderFooter) == null ? void 0 : _d.call(_c);
  1060. const dialogWrapperEl = document.createElement("div");
  1061. dialogWrapperEl.id = `uu-${this.id}-dialog`;
  1062. dialogWrapperEl.classList.add("uu-dialog");
  1063. dialogWrapperEl.ariaLabel = dialogWrapperEl.title = "";
  1064. dialogWrapperEl.role = "dialog";
  1065. dialogWrapperEl.setAttribute("aria-labelledby", `uu-${this.id}-dialog-title`);
  1066. dialogWrapperEl.setAttribute("aria-describedby", `uu-${this.id}-dialog-body`);
  1067. if (this.options.verticalAlign !== "center")
  1068. dialogWrapperEl.classList.add(`align-${this.options.verticalAlign}`);
  1069. const headerWrapperEl = document.createElement("div");
  1070. headerWrapperEl.classList.add("uu-dialog-header");
  1071. this.options.small && headerWrapperEl.classList.add("small");
  1072. if (header) {
  1073. const headerTitleWrapperEl = document.createElement("div");
  1074. headerTitleWrapperEl.id = `uu-${this.id}-dialog-title`;
  1075. headerTitleWrapperEl.classList.add("uu-dialog-title-wrapper");
  1076. headerTitleWrapperEl.role = "heading";
  1077. headerTitleWrapperEl.ariaLevel = "1";
  1078. headerTitleWrapperEl.appendChild(header instanceof Promise ? yield header : header);
  1079. headerWrapperEl.appendChild(headerTitleWrapperEl);
  1080. } else {
  1081. const padEl = document.createElement("div");
  1082. padEl.classList.add("uu-dialog-header-pad", this.options.small ? "small" : "");
  1083. headerWrapperEl.appendChild(padEl);
  1084. }
  1085. if (this.options.renderCloseBtn) {
  1086. const closeBtnEl = yield this.options.renderCloseBtn();
  1087. closeBtnEl.classList.add("uu-dialog-close");
  1088. this.options.small && closeBtnEl.classList.add("small");
  1089. closeBtnEl.tabIndex = 0;
  1090. if (closeBtnEl.hasAttribute("alt"))
  1091. closeBtnEl.setAttribute("alt", this.getString("closeDialogTooltip"));
  1092. closeBtnEl.title = closeBtnEl.ariaLabel = this.getString("closeDialogTooltip");
  1093. this.onInteraction(closeBtnEl, () => this.close());
  1094. headerWrapperEl.appendChild(closeBtnEl);
  1095. }
  1096. dialogWrapperEl.appendChild(headerWrapperEl);
  1097. const dialogBodyElem = document.createElement("div");
  1098. dialogBodyElem.id = `uu-${this.id}-dialog-body`;
  1099. dialogBodyElem.classList.add("uu-dialog-body");
  1100. this.options.small && dialogBodyElem.classList.add("small");
  1101. const body = this.options.renderBody();
  1102. dialogBodyElem.appendChild(body instanceof Promise ? yield body : body);
  1103. dialogWrapperEl.appendChild(dialogBodyElem);
  1104. if (footer) {
  1105. const footerWrapper = document.createElement("div");
  1106. footerWrapper.classList.add("uu-dialog-footer-cont");
  1107. dialogWrapperEl.appendChild(footerWrapper);
  1108. footerWrapper.appendChild(footer instanceof Promise ? yield footer : footer);
  1109. }
  1110. return dialogWrapperEl;
  1111. });
  1112. }
  1113. };
  1114.  
  1115. // lib/misc.ts
  1116. function autoPlural(word, num) {
  1117. if (Array.isArray(num) || num instanceof NodeList)
  1118. num = num.length;
  1119. return `${word}${num === 1 ? "" : "s"}`;
  1120. }
  1121. function insertValues(input, ...values) {
  1122. return input.replace(/%\d/gm, (match) => {
  1123. var _a, _b;
  1124. const argIndex = Number(match.substring(1)) - 1;
  1125. return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
  1126. });
  1127. }
  1128. function pauseFor(time) {
  1129. return new Promise((res) => {
  1130. setTimeout(() => res(), time);
  1131. });
  1132. }
  1133. function debounce(func, timeout = 300, edge = "falling") {
  1134. let timer;
  1135. return function(...args) {
  1136. if (edge === "rising") {
  1137. if (!timer) {
  1138. func.apply(this, args);
  1139. timer = setTimeout(() => timer = void 0, timeout);
  1140. }
  1141. } else {
  1142. clearTimeout(timer);
  1143. timer = setTimeout(() => func.apply(this, args), timeout);
  1144. }
  1145. };
  1146. }
  1147. function fetchAdvanced(_0) {
  1148. return __async(this, arguments, function* (input, options = {}) {
  1149. const { timeout = 1e4 } = options;
  1150. let signalOpts = {}, id = void 0;
  1151. if (timeout >= 0) {
  1152. const controller = new AbortController();
  1153. id = setTimeout(() => controller.abort(), timeout);
  1154. signalOpts = { signal: controller.signal };
  1155. }
  1156. try {
  1157. const res = yield fetch(input, __spreadValues(__spreadValues({}, options), signalOpts));
  1158. id && clearTimeout(id);
  1159. return res;
  1160. } catch (err) {
  1161. id && clearTimeout(id);
  1162. throw err;
  1163. }
  1164. });
  1165. }
  1166.  
  1167. // lib/SelectorObserver.ts
  1168. var domLoaded = false;
  1169. document.addEventListener("DOMContentLoaded", () => domLoaded = true);
  1170. var SelectorObserver = class {
  1171. constructor(baseElement, options = {}) {
  1172. __publicField(this, "enabled", false);
  1173. __publicField(this, "baseElement");
  1174. __publicField(this, "observer");
  1175. __publicField(this, "observerOptions");
  1176. __publicField(this, "customOptions");
  1177. __publicField(this, "listenerMap");
  1178. this.baseElement = baseElement;
  1179. this.listenerMap = /* @__PURE__ */ new Map();
  1180. const _a = options, {
  1181. defaultDebounce,
  1182. defaultDebounceEdge,
  1183. disableOnNoListeners,
  1184. enableOnAddListener
  1185. } = _a, observerOptions = __objRest(_a, [
  1186. "defaultDebounce",
  1187. "defaultDebounceEdge",
  1188. "disableOnNoListeners",
  1189. "enableOnAddListener"
  1190. ]);
  1191. this.observerOptions = __spreadValues({
  1192. childList: true,
  1193. subtree: true
  1194. }, observerOptions);
  1195. this.customOptions = {
  1196. defaultDebounce: defaultDebounce != null ? defaultDebounce : 0,
  1197. defaultDebounceEdge: defaultDebounceEdge != null ? defaultDebounceEdge : "rising",
  1198. disableOnNoListeners: disableOnNoListeners != null ? disableOnNoListeners : false,
  1199. enableOnAddListener: enableOnAddListener != null ? enableOnAddListener : true
  1200. };
  1201. if (typeof this.customOptions.checkInterval !== "number") {
  1202. this.observer = new MutationObserver(() => this.checkAllSelectors());
  1203. } else {
  1204. this.checkAllSelectors();
  1205. setInterval(() => this.checkAllSelectors(), this.customOptions.checkInterval);
  1206. }
  1207. }
  1208. /** Call to check all selectors in the {@linkcode listenerMap} using {@linkcode checkSelector()} */
  1209. checkAllSelectors() {
  1210. if (!this.enabled || !domLoaded)
  1211. return;
  1212. for (const [selector, listeners] of this.listenerMap.entries())
  1213. this.checkSelector(selector, listeners);
  1214. }
  1215. /** Checks if the element(s) with the given {@linkcode selector} exist in the DOM and calls the respective {@linkcode listeners} accordingly */
  1216. checkSelector(selector, listeners) {
  1217. var _a;
  1218. if (!this.enabled)
  1219. return;
  1220. const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
  1221. if (!baseElement)
  1222. return;
  1223. const all = listeners.some((listener) => listener.all);
  1224. const one = listeners.some((listener) => !listener.all);
  1225. const allElements = all ? baseElement.querySelectorAll(selector) : null;
  1226. const oneElement = one ? baseElement.querySelector(selector) : null;
  1227. for (const options of listeners) {
  1228. if (options.all) {
  1229. if (allElements && allElements.length > 0) {
  1230. options.listener(allElements);
  1231. if (!options.continuous)
  1232. this.removeListener(selector, options);
  1233. }
  1234. } else {
  1235. if (oneElement) {
  1236. options.listener(oneElement);
  1237. if (!options.continuous)
  1238. this.removeListener(selector, options);
  1239. }
  1240. }
  1241. if (((_a = this.listenerMap.get(selector)) == null ? void 0 : _a.length) === 0)
  1242. this.listenerMap.delete(selector);
  1243. if (this.listenerMap.size === 0 && this.customOptions.disableOnNoListeners)
  1244. this.disable();
  1245. }
  1246. }
  1247. /**
  1248. * Starts observing the children of the base element for changes to the given {@linkcode selector} according to the set {@linkcode options}
  1249. * @param selector The selector to observe
  1250. * @param options Options for the selector observation
  1251. * @param options.listener Gets called whenever the selector was found in the DOM
  1252. * @param [options.all] Whether to use `querySelectorAll()` instead - default is false
  1253. * @param [options.continuous] Whether to call the listener continuously instead of just once - default is false
  1254. * @param [options.debounce] Whether to debounce the listener to reduce calls to `querySelector` or `querySelectorAll` - set undefined or <=0 to disable (default)
  1255. * @returns Returns a function that can be called to remove this listener more easily
  1256. */
  1257. addListener(selector, options) {
  1258. options = __spreadValues({
  1259. all: false,
  1260. continuous: false,
  1261. debounce: 0
  1262. }, options);
  1263. if (options.debounce && options.debounce > 0 || this.customOptions.defaultDebounce && this.customOptions.defaultDebounce > 0) {
  1264. options.listener = debounce(
  1265. options.listener,
  1266. options.debounce || this.customOptions.defaultDebounce,
  1267. options.debounceEdge || this.customOptions.defaultDebounceEdge
  1268. );
  1269. }
  1270. if (this.listenerMap.has(selector))
  1271. this.listenerMap.get(selector).push(options);
  1272. else
  1273. this.listenerMap.set(selector, [options]);
  1274. if (this.enabled === false && this.customOptions.enableOnAddListener)
  1275. this.enable();
  1276. this.checkSelector(selector, [options]);
  1277. return () => this.removeListener(selector, options);
  1278. }
  1279. /** Disables the observation of the child elements */
  1280. disable() {
  1281. var _a;
  1282. if (!this.enabled)
  1283. return;
  1284. this.enabled = false;
  1285. (_a = this.observer) == null ? void 0 : _a.disconnect();
  1286. }
  1287. /**
  1288. * Enables or reenables the observation of the child elements.
  1289. * @param immediatelyCheckSelectors Whether to immediately check if all previously registered selectors exist (default is true)
  1290. * @returns Returns true when the observation was enabled, false otherwise (e.g. when the base element wasn't found)
  1291. */
  1292. enable(immediatelyCheckSelectors = true) {
  1293. var _a;
  1294. const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
  1295. if (this.enabled || !baseElement)
  1296. return false;
  1297. this.enabled = true;
  1298. (_a = this.observer) == null ? void 0 : _a.observe(baseElement, this.observerOptions);
  1299. if (immediatelyCheckSelectors)
  1300. this.checkAllSelectors();
  1301. return true;
  1302. }
  1303. /** Returns whether the observation of the child elements is currently enabled */
  1304. isEnabled() {
  1305. return this.enabled;
  1306. }
  1307. /** Removes all listeners that have been registered with {@linkcode addListener()} */
  1308. clearListeners() {
  1309. this.listenerMap.clear();
  1310. }
  1311. /**
  1312. * Removes all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()}
  1313. * @returns Returns true when all listeners for the associated selector were found and removed, false otherwise
  1314. */
  1315. removeAllListeners(selector) {
  1316. return this.listenerMap.delete(selector);
  1317. }
  1318. /**
  1319. * Removes a single listener for the given {@linkcode selector} and {@linkcode options} that has been registered with {@linkcode addListener()}
  1320. * @returns Returns true when the listener was found and removed, false otherwise
  1321. */
  1322. removeListener(selector, options) {
  1323. const listeners = this.listenerMap.get(selector);
  1324. if (!listeners)
  1325. return false;
  1326. const index = listeners.indexOf(options);
  1327. if (index > -1) {
  1328. listeners.splice(index, 1);
  1329. return true;
  1330. }
  1331. return false;
  1332. }
  1333. /** Returns all listeners that have been registered with {@linkcode addListener()} */
  1334. getAllListeners() {
  1335. return this.listenerMap;
  1336. }
  1337. /** Returns all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()} */
  1338. getListeners(selector) {
  1339. return this.listenerMap.get(selector);
  1340. }
  1341. };
  1342.  
  1343. // lib/translation.ts
  1344. var trans = {};
  1345. var curLang;
  1346. function tr(key, ...args) {
  1347. var _a;
  1348. if (!curLang)
  1349. return key;
  1350. const trText = (_a = trans[curLang]) == null ? void 0 : _a[key];
  1351. if (!trText)
  1352. return key;
  1353. if (args.length > 0 && trText.match(/%\d/)) {
  1354. return insertValues(trText, ...args);
  1355. }
  1356. return trText;
  1357. }
  1358. tr.addLanguage = (language, translations) => {
  1359. trans[language] = translations;
  1360. };
  1361. tr.setLanguage = (language) => {
  1362. curLang = language;
  1363. };
  1364. tr.getLanguage = () => {
  1365. return curLang;
  1366. };
  1367.  
  1368. exports.DataStore = DataStore;
  1369. exports.DataStoreSerializer = DataStoreSerializer;
  1370. exports.Dialog = Dialog;
  1371. exports.NanoEmitter = NanoEmitter;
  1372. exports.SelectorObserver = SelectorObserver;
  1373. exports.addGlobalStyle = addGlobalStyle;
  1374. exports.addParent = addParent;
  1375. exports.autoPlural = autoPlural;
  1376. exports.clamp = clamp;
  1377. exports.compress = compress;
  1378. exports.computeHash = computeHash;
  1379. exports.debounce = debounce;
  1380. exports.decompress = decompress;
  1381. exports.defaultDialogCss = defaultDialogCss;
  1382. exports.defaultStrings = defaultStrings;
  1383. exports.fetchAdvanced = fetchAdvanced;
  1384. exports.getSiblingsFrame = getSiblingsFrame;
  1385. exports.getUnsafeWindow = getUnsafeWindow;
  1386. exports.insertValues = insertValues;
  1387. exports.interceptEvent = interceptEvent;
  1388. exports.interceptWindowEvent = interceptWindowEvent;
  1389. exports.isScrollable = isScrollable;
  1390. exports.mapRange = mapRange;
  1391. exports.observeElementProp = observeElementProp;
  1392. exports.openDialogs = openDialogs;
  1393. exports.openInNewTab = openInNewTab;
  1394. exports.pauseFor = pauseFor;
  1395. exports.preloadImages = preloadImages;
  1396. exports.randRange = randRange;
  1397. exports.randomId = randomId;
  1398. exports.randomItem = randomItem;
  1399. exports.randomItemIndex = randomItemIndex;
  1400. exports.randomizeArray = randomizeArray;
  1401. exports.setInnerHtmlUnsafe = setInnerHtmlUnsafe;
  1402. exports.takeRandomItem = takeRandomItem;
  1403. exports.tr = tr;
  1404.  
  1405. return exports;
  1406.  
  1407. })({});

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址