Basic Functions (For userscripts)

Useful functions for myself

As of 2025-01-25. See the latest version.

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/456034/1526615/Basic%20Functions%20%28For%20userscripts%29.js

  1. // ==UserScript==
  2. // @name Basic Functions (For userscripts)
  3. // @name:zh-CN 常用函数(用户脚本)
  4. // @name:en Basic Functions (For userscripts)
  5. // @namespace PY-DNG Userscripts
  6. // @version 1.1
  7. // @description Useful functions for myself
  8. // @description:zh-CN 自用函数
  9. // @description:en Useful functions for myself
  10. // @author PY-DNG
  11. // @license GPL-3.0-or-later
  12. // ==/UserScript==
  13.  
  14. /* eslint-disable no-multi-spaces */
  15. /* eslint-disable no-return-assign */
  16.  
  17. // Note: version 0.8.2.1 is modified just the license and it's not uploaded to GF yet 23-11-26 15:03
  18. // Note: version 0.8.3.1 is added just the description of parseArgs and has not uploaded to GF yet 24-02-03 18:55
  19.  
  20. let [
  21. // Console & Debug
  22. LogLevel, DoLog, Err, Assert,
  23.  
  24. // DOM
  25. $, $All, $CrE, $AEL, $$CrE, addStyle, detectDom, destroyEvent,
  26.  
  27. // Data
  28. copyProp, copyProps, parseArgs, escJsStr, replaceText,
  29.  
  30. // Environment & Browser
  31. getUrlArgv, dl_browser, dl_GM,
  32.  
  33. // Logic & Task
  34. AsyncManager, queueTask, FunctionLoader, loadFuncs, require, isLoaded
  35. ] = (function() {
  36. const [LogLevel, DoLog] = (function() {
  37. /**
  38. * level defination for DoLog function, bigger ones has higher possibility to be printed in console
  39. * @typedef {Object} LogLevel
  40. * @property {0} None - 0
  41. * @property {1} Error - 1
  42. * @property {2} Success - 2
  43. * @property {3} Warning - 3
  44. * @property {4} Info - 4
  45. */
  46. /** @type {LogLevel} */
  47. const LogLevel = {
  48. None: 0,
  49. Error: 1,
  50. Success: 2,
  51. Warning: 3,
  52. Info: 4,
  53. };
  54.  
  55. return [LogLevel, DoLog];
  56.  
  57. /**
  58. * @overload
  59. * @param {String} content - log content
  60. */
  61. /**
  62. * @overload
  63. * @param {Number} level - level specified in LogLevel object
  64. * @param {String} content - log content
  65. */
  66. /**
  67. * Logger with level and logger function specification
  68. * @overload
  69. * @param {Number} level - level specified in LogLevel object
  70. * @param {String} content - log content
  71. * @param {String} logger - which log function to use (in window.console[logger])
  72. */
  73. function DoLog() {
  74. // Get window
  75. const win = (typeof(unsafeWindow) === 'object' && unsafeWindow !== null) ? unsafeWindow : window;
  76.  
  77. const LogLevelMap = {};
  78. LogLevelMap[LogLevel.None] = {
  79. prefix: '',
  80. color: 'color:#ffffff'
  81. }
  82. LogLevelMap[LogLevel.Error] = {
  83. prefix: '[Error]',
  84. color: 'color:#ff0000'
  85. }
  86. LogLevelMap[LogLevel.Success] = {
  87. prefix: '[Success]',
  88. color: 'color:#00aa00'
  89. }
  90. LogLevelMap[LogLevel.Warning] = {
  91. prefix: '[Warning]',
  92. color: 'color:#ffa500'
  93. }
  94. LogLevelMap[LogLevel.Info] = {
  95. prefix: '[Info]',
  96. color: 'color:#888888'
  97. }
  98. LogLevelMap[LogLevel.Elements] = {
  99. prefix: '[Elements]',
  100. color: 'color:#000000'
  101. }
  102.  
  103. // Current log level
  104. DoLog.logLevel = (win.isPY_DNG && win.userscriptDebugging) ? LogLevel.Info : LogLevel.Warning; // Info Warning Success Error
  105.  
  106. // Log counter
  107. DoLog.logCount === undefined && (DoLog.logCount = 0);
  108.  
  109. // Get args
  110. let [level, logContent, logger] = parseArgs([...arguments], [
  111. [2],
  112. [1,2],
  113. [1,2,3]
  114. ], [LogLevel.Info, 'DoLog initialized.', 'log']);
  115.  
  116. let msg = '%c' + LogLevelMap[level].prefix + (typeof GM_info === 'object' ? `[${GM_info.script.name}]` : '') + (LogLevelMap[level].prefix ? ' ' : '');
  117. let subst = LogLevelMap[level].color;
  118.  
  119. switch (typeof(logContent)) {
  120. case 'string':
  121. msg += '%s';
  122. break;
  123. case 'number':
  124. msg += '%d';
  125. break;
  126. default:
  127. msg += '%o';
  128. break;
  129. }
  130.  
  131. // Log when log level permits
  132. if (level <= DoLog.logLevel) {
  133. // Log to console when log level permits
  134. if (level <= DoLog.logLevel) {
  135. if (++DoLog.logCount > 512) {
  136. console.clear();
  137. DoLog.logCount = 0;
  138. }
  139. console[logger](msg, subst, logContent);
  140. }
  141. }
  142. }
  143. }) ();
  144.  
  145. /**
  146. * Throw an error
  147. * @param {String} msg - the error message
  148. * @param {Error} [ErrorConstructor=Error] - which error constructor to use, defaulting to Error()
  149. */
  150. function Err(msg, ErrorConstructor=Error) {
  151. throw new ErrorConstructor((typeof GM_info === 'object' ? `[${GM_info.script.name}]` : '') + msg);
  152. }
  153.  
  154. /**
  155. * Assert given condition is true-like, otherwise throws given error
  156. * @param {*} condition
  157. * @param {string} errmsg
  158. * @param {Error} [ErrorConstructor=Error]
  159. */
  160. function Assert(condition, errmsg, ErrorConstructor=Error) {
  161. condition || Err(errmsg, ErrorConstructor);
  162. }
  163.  
  164. /**
  165. * Convenient function to querySelector
  166. * @overload
  167. * @param {Element|Document|DocumentFragment} [root] - which target to call querySelector on
  168. * @param {string} selector - querySelector selector
  169. * @returns
  170. */
  171. function $() {
  172. switch(arguments.length) {
  173. case 2:
  174. return arguments[0].querySelector(arguments[1]);
  175. break;
  176. default:
  177. return document.querySelector(arguments[0]);
  178. }
  179. }
  180. /**
  181. * Convenient function to querySelectorAll
  182. * @overload
  183. * @param {Element|Document|DocumentFragment} [root] - which target to call querySelectorAll on
  184. * @param {string} selector - querySelectorAll selector
  185. * @returns
  186. */
  187. function $All() {
  188. switch(arguments.length) {
  189. case 2:
  190. return arguments[0].querySelectorAll(arguments[1]);
  191. break;
  192. default:
  193. return document.querySelectorAll(arguments[0]);
  194. }
  195. }
  196. /**
  197. * Convenient function to querySelectorAll
  198. * @overload
  199. * @param {Document} [root] - which document to call createElement on
  200. * @param {string} tagName
  201. */
  202. function $CrE() {
  203. switch(arguments.length) {
  204. case 2:
  205. return arguments[0].createElement(arguments[1]);
  206. break;
  207. default:
  208. return document.createElement(arguments[0]);
  209. }
  210. }
  211. /**
  212. * Convenient function to addEventListener
  213. * @overload
  214. * @param {EventTarget} target - which target to call addEventListener on
  215. * @param {string} type
  216. * @param {EventListenerOrEventListenerObject | null} callback
  217. * @param {AddEventListenerOptions | boolean} [options]
  218. */
  219. function $AEL(...args) {
  220. /** @type {EventTarget} */
  221. const target = args.shift();
  222. return target.addEventListener.apply(target, args);
  223. }
  224. /**
  225. * @typedef {[type: string, callback: EventListenerOrEventListenerObject | null, options: AddEventListenerOptions | boolean]} $AEL_Arguments
  226. */
  227. /**
  228. * @typedef {Object} $$CrE_Options
  229. * @property {string} tagName
  230. * @property {object} [props] - properties set by `element[prop] = value;`
  231. * @property {object} [attrs] - attributes set by `element.setAttribute(attr, value);`
  232. * @property {string | string[]} [classes] - class names to be set
  233. * @property {object} [styles] - styles set by `element[style_name] = style_value;`
  234. * @property {$AEL_Arguments[]} [listeners] - event listeners added by `$AEL(element, ...listener);`
  235. */
  236. /**
  237. * @overload
  238. * @param {$$CrE_Options} options
  239. */
  240. /**
  241. * Create configorated element
  242. * @overload
  243. * @param {string} tagName
  244. * @param {object} [props] - properties set by `element[prop] = value;`
  245. * @param {object} [attrs] - attributes set by `element.setAttribute(attr, value);`
  246. * @param {string | string[]} [classes] - class names to be set
  247. * @param {object} [styles] - styles set by `element[style_name] = style_value;`
  248. * @param {$AEL_Arguments[]} [listeners] - event listeners added by `$AEL(element, ...listener);`
  249. * @returns {HTMLElement}
  250. */
  251. function $$CrE() {
  252. const [tagName, props, attrs, classes, styles, listeners] = parseArgs([...arguments], [
  253. function(args, defaultValues) {
  254. const arg = args[0];
  255. return {
  256. 'string': () => [arg, ...defaultValues.filter((arg, i) => i > 0)],
  257. 'object': () => ['tagName', 'props', 'attrs', 'classes', 'styles', 'listeners'].map((prop, i) => arg.hasOwnProperty(prop) ? arg[prop] : defaultValues[i])
  258. }[typeof arg]();
  259. },
  260. [1,2],
  261. [1,2,3],
  262. [1,2,3,4],
  263. [1,2,3,4,5]
  264. ], ['div', {}, {}, [], {}, []]);
  265. const elm = $CrE(tagName);
  266. for (const [name, val] of Object.entries(props)) {
  267. elm[name] = val;
  268. }
  269. for (const [name, val] of Object.entries(attrs)) {
  270. elm.setAttribute(name, val);
  271. }
  272. for (const cls of Array.isArray(classes) ? classes : [classes]) {
  273. elm.classList.add(cls);
  274. }
  275. for (const [name, val] of Object.entries(styles)) {
  276. elm.style[name] = val;
  277. }
  278. for (const listener of listeners) {
  279. $AEL(elm, ...listener);
  280. }
  281. return elm;
  282. }
  283.  
  284. /**
  285. * @overload
  286. * @param {string} css - css content
  287. * @returns {HTMLStyleElement}
  288. */
  289. /**
  290. * @overload
  291. * @param {string} css - css content
  292. * @param {string} id - `id` attribute for <style> element
  293. * @returns {HTMLStyleElement}
  294. */
  295. /**
  296. * Append a style text to document(<head>) with a <style> element \
  297. * removes existing <style> elements with same id if id provided, so style updates can be done by using one same id
  298. *
  299. * Uses `GM_addElement` if `GM_addElement` exists and param `id` not specified. (`GM_addElement` uses id attribute, so specifing id manually when using `GM_addElement` takes no effect) \
  300. * In another case `GM_addStyle` instead of `GM_addElement` exists, and both `id` and `parentElement` not specified, `GM_addStyle` will be used. \
  301. * `document.createElement('style')` will be used otherwise.
  302. * @overload
  303. * @param {HTMLElement} parentElement - parent element to place <style> element
  304. * @param {string} css - css content
  305. * @param {string} id - `id` attribute for <style> element
  306. * @returns {HTMLStyleElement}
  307. */
  308. function addStyle() {
  309. // Get arguments
  310. const [parentElement, css, id] = parseArgs([...arguments], [
  311. [2],
  312. [2,3],
  313. [1,2,3]
  314. ], [null, '', null]);
  315.  
  316. if (typeof GM_addElement === 'function' && id === null) {
  317. return GM_addElement(parentElement, 'style', { textContent: css });
  318. } else if (typeof GM_addStyle === 'function' && parentElement === null && id === null) {
  319. return GM_addStyle(css);
  320. } else {
  321. // Make <style>
  322. const style = $CrE('style');
  323. style.innerText = css;
  324. id !== null && (style.id = id);
  325. id !== null && Array.from($All(`style#${id}`)).forEach(elm => elm.remove());
  326.  
  327. // Append to parentElement
  328. (parentElement ?? document.head).appendChild(style);
  329. return style;
  330. }
  331. }
  332.  
  333. /**
  334. * @typedef {Object} detectDom_options
  335. * @property {Node} root - root target to observe on
  336. * @property {string | string[]} [selector] - selector(s) to observe for, be aware that in options object it is named selector, but is named selectors in param
  337. * @property {boolean} [attributes] - whether to observe existing elements' attribute changes
  338. * @property {function} [callback] - if provided, use callback instead of Promise when selector element found
  339. */
  340. /**
  341. * @overload
  342. * @param {detectDom_options} options
  343. * @returns {MutationObserver}
  344. */
  345. /**
  346. * Get callback / resolve promise when specific dom/element appearce in document \
  347. * uses MutationObserver for implementation \
  348. * This behavior is different from versions that equals to or older than 0.8.4.2, so be careful when using it.
  349. * @overload
  350. * @param {Node} root - root target to observe on
  351. * @param {string | string[]} [selectors] - selector(s) to observe for
  352. * @param {boolean} [attributes] - whether to observe existing elements' attribute changes
  353. * @param {function} [callback] - if provided, use callback instead of Promise when selector element found
  354. * @returns {MutationObserver}
  355. */
  356. function detectDom() {
  357. let [selectors, root, attributes, callback] = parseArgs([...arguments], [
  358. function(args, defaultValues) {
  359. const arg = args[0];
  360. return {
  361. 'string': () => [arg, ...defaultValues.filter((arg, i) => i > 0)],
  362. 'object': () => ['selector', 'root', 'attributes', 'callback'].map((prop, i) => arg.hasOwnProperty(prop) ? arg[prop] : defaultValues[i])
  363. }[typeof arg]();
  364. },
  365. [2,1],
  366. [2,1,3],
  367. [2,1,3,4],
  368. ], [[''], document, false, null]);
  369. !Array.isArray(selectors) && (selectors = [selectors]);
  370.  
  371. if (select(root, selectors)) {
  372. for (const elm of selectAll(root, selectors)) {
  373. if (callback) {
  374. setTimeout(callback.bind(null, elm));
  375. } else {
  376. return Promise.resolve(elm);
  377. }
  378. }
  379. }
  380.  
  381. const observer = new MutationObserver(mCallback);
  382. observer.observe(root, {
  383. childList: true,
  384. subtree: true,
  385. attributes,
  386. });
  387.  
  388. let isPromise = !callback;
  389. return callback ? observer : new Promise((resolve, reject) => callback = resolve);
  390.  
  391. function mCallback(mutationList, observer) {
  392. const addedNodes = mutationList.reduce((an, mutation) => {
  393. switch (mutation.type) {
  394. case 'childList':
  395. an.push(...mutation.addedNodes);
  396. break;
  397. case 'attributes':
  398. an.push(mutation.target);
  399. break;
  400. }
  401. return an;
  402. }, []);
  403. const addedSelectorNodes = addedNodes.reduce((nodes, anode) => {
  404. if (anode.matches && match(anode, selectors)) {
  405. nodes.add(anode);
  406. }
  407. const childMatches = anode.querySelectorAll ? selectAll(anode, selectors) : [];
  408. for (const cm of childMatches) {
  409. nodes.add(cm);
  410. }
  411. return nodes;
  412. }, new Set());
  413. for (const node of addedSelectorNodes) {
  414. callback(node);
  415. isPromise && observer.disconnect();
  416. }
  417. }
  418.  
  419. function selectAll(elm, selectors) {
  420. !Array.isArray(selectors) && (selectors = [selectors]);
  421. return selectors.map(selector => [...$All(elm, selector)]).reduce((all, arr) => {
  422. all.push(...arr);
  423. return all;
  424. }, []);
  425. }
  426.  
  427. function select(elm, selectors) {
  428. const all = selectAll(elm, selectors);
  429. return all.length ? all[0] : null;
  430. }
  431.  
  432. function match(elm, selectors) {
  433. return !!elm.matches && selectors.some(selector => elm.matches(selector));
  434. }
  435. }
  436.  
  437. /**
  438. * Just stopPropagation and preventDefault
  439. * @param {Event} e
  440. */
  441. function destroyEvent(e) {
  442. if (!e) {return false;};
  443. if (!e instanceof Event) {return false;};
  444. e.stopPropagation();
  445. e.preventDefault();
  446. }
  447.  
  448. /**
  449. * copy property value from obj1 to obj2 if exists
  450. * @param {object} obj1
  451. * @param {object} obj2
  452. * @param {string|Symbol} prop
  453. */
  454. function copyProp(obj1, obj2, prop) {obj1.hasOwnProperty(prop) && (obj2[prop] = obj1[prop]);}
  455. /**
  456. * copy property values from obj1 to obj2 if exists
  457. * @param {object} obj1
  458. * @param {object} obj2
  459. * @param {string|Symbol} [props] - properties to copy, copy all enumerable properties if not specified
  460. */
  461. function copyProps(obj1, obj2, props) {(props ?? Object.keys(obj1)).forEach((prop) => (copyProp(obj1, obj2, prop)));}
  462.  
  463. /**
  464. * Argument parser with sorting and defaultValue support \
  465. * See use cases in other functions
  466. * @param {Array} args - original arguments' value to be parsed
  467. * @param {(number[]|function)[]} rules - rules to sort arguments or custom function to parse arguments
  468. * @param {Array} defaultValues - default values for arguments not provided a value
  469. * @returns {Array}
  470. */
  471. function parseArgs(args, rules, defaultValues=[]) {
  472. // args and rules should be array, but not just iterable (string is also iterable)
  473. if (!Array.isArray(args) || !Array.isArray(rules)) {
  474. throw new TypeError('parseArgs: args and rules should be array')
  475. }
  476.  
  477. // fill rules[0]
  478. (!Array.isArray(rules[0]) || rules[0].length === 1) && rules.splice(0, 0, []);
  479.  
  480. // max arguments length
  481. const count = rules.length - 1;
  482.  
  483. // args.length must <= count
  484. if (args.length > count) {
  485. throw new TypeError(`parseArgs: args has more elements(${args.length}) longer than ruless'(${count})`);
  486. }
  487.  
  488. // rules[i].length should be === i if rules[i] is an array, otherwise it should be a function
  489. for (let i = 1; i <= count; i++) {
  490. const rule = rules[i];
  491. if (Array.isArray(rule)) {
  492. if (rule.length !== i) {
  493. throw new TypeError(`parseArgs: rules[${i}](${rule}) should have ${i} numbers, but given ${rules[i].length}`);
  494. }
  495. if (!rule.every((num) => (typeof num === 'number' && num <= count))) {
  496. throw new TypeError(`parseArgs: rules[${i}](${rule}) should contain numbers smaller than count(${count}) only`);
  497. }
  498. } else if (typeof rule !== 'function') {
  499. throw new TypeError(`parseArgs: rules[${i}](${rule}) should be an array or a function.`)
  500. }
  501. }
  502.  
  503. // Parse
  504. const rule = rules[args.length];
  505. let parsed;
  506. if (Array.isArray(rule)) {
  507. parsed = [...defaultValues];
  508. for (let i = 0; i < rule.length; i++) {
  509. parsed[rule[i]-1] = args[i];
  510. }
  511. } else {
  512. parsed = rule(args, defaultValues);
  513. }
  514. return parsed;
  515. }
  516.  
  517. /**
  518. * escape str into javascript written format
  519. * @param {string} str
  520. * @param {string} [quote]
  521. * @returns
  522. */
  523. function escJsStr(str, quote='"') {
  524. str = str.replaceAll('\\', '\\\\').replaceAll(quote, '\\' + quote).replaceAll('\t', '\\t');
  525. str = quote === '`' ? str.replaceAll(/(\$\{[^\}]*\})/g, '\\$1') : str.replaceAll('\r', '\\r').replaceAll('\n', '\\n');
  526. return quote + str + quote;
  527. }
  528. /**
  529. * Replace given text with no mismatching of replacing replaced text
  530. *
  531. * e.g. replaceText('aaaabbbbccccdddd', {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e'}) === 'bbbbccccddddeeee' \
  532. * replaceText('abcdAABBAA', {'BB': 'AA', 'AAAAAA': 'This is a trap!'}) === 'abcdAAAAAA' \
  533. * replaceText('abcd{AAAA}BB}', {'{AAAA}': '{BB', '{BBBB}': 'This is a trap!'}) === 'abcd{BBBB}' \
  534. * replaceText('abcd', {}) === 'abcd'
  535. *
  536. * **Note**: \
  537. * replaceText will replace in sort of replacer's iterating sort \
  538. * e.g. currently replaceText('abcdAABBAA', {'BBAA': 'TEXT', 'AABB': 'TEXT'}) === 'abcdAATEXT' \
  539. * but remember: (As MDN Web Doc said,) Although the keys of an ordinary Object are ordered now, this was \
  540. * not always the case, and the order is complex. As a result, it's best not to rely on property order. \
  541. * So, don't expect replaceText will treat replacer key-values in any specific sort. Use replaceText to \
  542. * replace irrelevance replacer keys only.
  543. * @param {string} text
  544. * @param {object} replacer
  545. * @returns {string}
  546. */
  547. function replaceText(text, replacer) {
  548. if (Object.entries(replacer).length === 0) {return text;}
  549. const [models, targets] = Object.entries(replacer);
  550. const len = models.length;
  551. let text_arr = [{text: text, replacable: true}];
  552. for (const [model, target] of Object.entries(replacer)) {
  553. text_arr = replace(text_arr, model, target);
  554. }
  555. return text_arr.map((text_obj) => (text_obj.text)).join('');
  556.  
  557. function replace(text_arr, model, target) {
  558. const result_arr = [];
  559. for (const text_obj of text_arr) {
  560. if (text_obj.replacable) {
  561. const splited = text_obj.text.split(model);
  562. for (const part of splited) {
  563. result_arr.push({text: part, replacable: true});
  564. result_arr.push({text: target, replacable: false});
  565. }
  566. result_arr.pop();
  567. } else {
  568. result_arr.push(text_obj);
  569. }
  570. }
  571. return result_arr;
  572. }
  573. }
  574.  
  575. /**
  576. * @typedef {Object} getUrlArgv_options
  577. * @property {string} name
  578. * @property {string} [url]
  579. * @property {string} [defaultValue]
  580. * @property {function} [dealFunc] - function that inputs original getUrlArgv result and outputs final return value
  581. */
  582. /**
  583. * @overload
  584. * @param {Object} getUrlArgv_options
  585. * @returns
  586. */
  587. /**
  588. * Get a url argument from location.href
  589. * @param {string} name
  590. * @param {string} [url]
  591. * @param {string} [defaultValue]
  592. * @param {function} [dealFunc] - function that inputs original getUrlArgv result and outputs final return value
  593. */
  594. function getUrlArgv() {
  595. const [name, url, defaultValue, dealFunc] = parseArgs([...arguments], [
  596. function(args, defaultValues) {
  597. const arg = args[0];
  598. return {
  599. 'string': () => [arg, ...defaultValues.filter((arg, i) => i > 0)],
  600. 'object': () => ['name', 'url', 'defaultValue', 'dealFunc'].map((prop, i) => arg.hasOwnProperty(prop) ? arg[prop] : defaultValues[i])
  601. }[typeof arg]();
  602. },
  603. [2,1],
  604. [2,1,3],
  605. [2,1,3,4]
  606. ], [null, location.href, null, a => a]);
  607.  
  608. if (name === null) { return null; }
  609.  
  610. const search = new URL(url).search;
  611. const objSearch = new URLSearchParams(search);
  612. const raw = objSearch.has(name) ? objSearch.get(name) : defaultValue;
  613. const argv = dealFunc(raw);
  614.  
  615. return argv;
  616. }
  617.  
  618. /**
  619. * download file from given url by simulating <a download="..." href=""></a> clicks\
  620. * a common use case is to download Blob objects as file from `URL.createObjectURL`
  621. * @param {string} url
  622. * @param {string} filename
  623. */
  624. function dl_browser(url, filename) {
  625. const a = document.createElement('a');
  626. a.href = url;
  627. a.download = filename;
  628. a.click();
  629. }
  630.  
  631. /**
  632. * File download function\
  633. * details looks like the detail of GM_xmlhttpRequest\
  634. * onload function will be called after file saved to disk
  635. * @param {object} details
  636. */
  637. function dl_GM(details) {
  638. if (!details.url || !details.name) {return false;};
  639.  
  640. // Configure request object
  641. const requestObj = {
  642. url: details.url,
  643. responseType: 'blob',
  644. onload: function(e) {
  645. // Save file
  646. dl_browser(URL.createObjectURL(e.response), details.name);
  647.  
  648. // onload callback
  649. details.onload ? details.onload(e) : function() {};
  650. }
  651. }
  652. if (details.onloadstart ) {requestObj.onloadstart = details.onloadstart;};
  653. if (details.onprogress ) {requestObj.onprogress = details.onprogress;};
  654. if (details.onerror ) {requestObj.onerror = details.onerror;};
  655. if (details.onabort ) {requestObj.onabort = details.onabort;};
  656. if (details.onreadystatechange) {requestObj.onreadystatechange = details.onreadystatechange;};
  657. if (details.ontimeout ) {requestObj.ontimeout = details.ontimeout;};
  658.  
  659. // Send request
  660. Assert(typeof GM_xmlhttpRequest === 'function', 'GM_xmlhttpRequest should be provided in order to use dl_GM', TypeError);
  661. GM_xmlhttpRequest(requestObj);
  662. }
  663.  
  664. /**
  665. * Manager to manager async tasks\
  666. * This was written when I haven't learnt Promise, so for fluent promise users, just ignore it:)
  667. *
  668. * # Usage
  669. * ```javascript
  670. * // This simulates a async task, it can be a XMLHttpRequest, some file reading, or so on...
  671. * function someAsyncTask(callback, duration) {
  672. * const result = Math.random();
  673. * setTimeout(() => callback(result), duration);
  674. * }
  675. *
  676. * // Do 10 async tasks, and log all results when all async tasks finished
  677. * const AM = new AsyncManager();
  678. * const results = [];
  679. * AM.onfinish = function() {
  680. * console.log('All tasks finished!');
  681. * console.log(results);
  682. * }
  683. *
  684. * for (let i = 0; i < 10; i++) {
  685. * AM.add();
  686. * const duration = (Math.random() * 5 + 5) * 1000;
  687. * const index = i;
  688. * someAsyncTask(result => {
  689. * console.log(`Task ${index} finished after ${duration}ms!`);
  690. * results[index] = result;
  691. * }, duration);
  692. * console.log(`Task ${index} started!`);
  693. * }
  694. *
  695. * // Set AM.finishEvent to true after all tasks added, allowing AsyncManager to call onfinish callback
  696. * ```
  697. * @constructor
  698. */
  699. function AsyncManager() {
  700. const AM = this;
  701.  
  702. // Ongoing tasks count
  703. this.taskCount = 0;
  704.  
  705. // Whether generate finish events
  706. let finishEvent = false;
  707. Object.defineProperty(this, 'finishEvent', {
  708. configurable: true,
  709. enumerable: true,
  710. get: () => (finishEvent),
  711. set: (b) => {
  712. finishEvent = b;
  713. b && AM.taskCount === 0 && AM.onfinish && AM.onfinish();
  714. }
  715. });
  716.  
  717. // Add one task
  718. this.add = () => (++AM.taskCount);
  719.  
  720. // Finish one task
  721. this.finish = () => ((--AM.taskCount === 0 && AM.finishEvent && AM.onfinish && AM.onfinish(), AM.taskCount));
  722. }
  723.  
  724. /**
  725. * Put tasks in specific queue and order their execution
  726. * Set `queueTask[queueId].max`, `queueTask[queueId].sleep` to custom queue's max ongoing tasks and sleep time between tasks
  727. * @param {function} task - task function to run
  728. * @param {string | Symbol} queueId - identifier to specify a target queue. if provided, given task will be added into specified queue.
  729. * @returns
  730. */
  731. function queueTask(task, queueId='default') {
  732. init();
  733.  
  734. return new Promise((resolve, reject) => {
  735. queueTask.hasOwnProperty(queueId) || (queueTask[queueId] = { tasks: [], ongoing: 0 });
  736. queueTask[queueId].tasks.push({task, resolve, reject});
  737. checkTask(queueId);
  738. });
  739.  
  740. function init() {
  741. if (!queueTask[queueId]?.initialized) {
  742. queueTask[queueId] = {
  743. // defaults
  744. tasks: [],
  745. ongoing: 0,
  746. max: 3,
  747. sleep: 500,
  748.  
  749. // user's pre-sets
  750. ...(queueTask[queueId] || {}),
  751.  
  752. // initialized flag
  753. initialized: true
  754. }
  755. };
  756. }
  757.  
  758. function checkTask() {
  759. const queue = queueTask[queueId];
  760. setTimeout(() => {
  761. if (queue.ongoing < queue.max && queue.tasks.length) {
  762. const task = queue.tasks.shift();
  763. queue.ongoing++;
  764. setTimeout(
  765. () => task.task().then(v => {
  766. queue.ongoing--;
  767. task.resolve(v);
  768. checkTask(queueId);
  769. }).catch(e => {
  770. queue.ongoing--;
  771. task.reject(e);
  772. checkTask(queueId);
  773. }),
  774. queue.sleep
  775. );
  776. }
  777. });
  778. }
  779. }
  780.  
  781. const [FunctionLoader, loadFuncs, require, isLoaded] = (function() {
  782. /**
  783. * 一般用作函数对象oFunc的加载条件,检测当前环境是否适合/需要该oFunc加载
  784. * @typedef {Object} checker_func
  785. * @property {string} type - checker's identifier
  786. * @property {function} func - actual internal judgement implementation
  787. */
  788. /**
  789. * 一般用作函数对象oFunc的加载条件,检测当前环境是否适合/需要该oFunc加载
  790. * @typedef {Object} checker
  791. * @property {string} type - checker's identifier
  792. * @property {*} value - param that goes into checker function
  793. */
  794. /**
  795. * 被加载函数对象的func函数
  796. * @callback oFuncBody
  797. * @param {oFunc} oFunc
  798. * @returns {*|Promise<*>}
  799. */
  800. /**
  801. * 被加载执行的函数对象
  802. * @typedef {Object} oFunc
  803. * @property {string} id - 每次load(每个FuncPool实例)内唯一的标识符
  804. * @property {checker[]|checker} [checkers] - oFunc执行的条件
  805. * @property {string[]|string} [detectDom] - 如果提供,开始checker检查前会首先等待其中所有css选择器对应的元素在document中出现
  806. * @property {string[]|string} [dependencies] - 如果提供,应为其他函数对象的id或者id列表;开始checker检查前会首先等待其中所有指定的函数对象加载完毕
  807. * @property {boolean} [readonly] - 指定该函数的返回值是否应该被Proxy保护为不可修改对象
  808. * @property {oFuncBody} func - 实际实现了功能的函数
  809. * @property {boolean} [STOP] - [调试用] 指定不执行此函数对象
  810. */
  811.  
  812. const registered_checkers = {
  813. switch: value => value,
  814. url: value => location.href === value,
  815. path: value => location.pathname === value,
  816. regurl: value => !!location.href.match(value),
  817. regpath: value => !!location.pathname.match(value),
  818. starturl: value => location.href.startsWith(value),
  819. startpath: value => location.pathname.startsWith(value),
  820. func: value => value()
  821. };
  822.  
  823. class FuncPool extends EventTarget {
  824. static #STILL_LOADING = Symbol('oFunc still loading');
  825. static FunctionNotFound = Symbol('Function not found');
  826. static FunctionNotLoaded = Symbol('Function not loaded');
  827.  
  828. /** @typedef {symbol|*} return_value */
  829. /** @type {Map<oFunc, return_value>} */
  830. #oFuncs = new Map();
  831.  
  832. /**
  833. * 创建新函数池,并加载提供的函数对象
  834. * @param {oFunc[]|oFunc} [oFuncs] - 可选,需要加载的函数对象或其数组,不提供时默认为空数组
  835. * @returns {FuncPool}
  836. */
  837. constructor(oFuncs=[]) {
  838. super();
  839. this.load(oFuncs);
  840. }
  841.  
  842. /**
  843. * 加载提供的一个或多个函数对象,并将其加入到函数池中
  844. * @param {oFunc[]|oFunc} [oFuncs] - 可选,需要加载的函数对象或其数组,不提供时默认为空数组
  845. */
  846. load(oFuncs=[]) {
  847. oFuncs = Array.isArray(oFuncs) ? oFuncs : [oFuncs];
  848. for (const oFunc of oFuncs) {
  849. this.#load(oFunc);
  850. }
  851. }
  852.  
  853. /**
  854. * 加载一个函数对象,并将其加入到函数池中
  855. * 当id重复时,直接报错RedeclarationError
  856. * 异步函数,当彻底load完毕/checkers确定不加载时resolve
  857. * 当加载完毕时,广播load事件;如果全部加载完毕,还广播all_load事件
  858. * @param {oFunc} oFunc
  859. * @returns {Promise<undefined>}
  860. */
  861. async #load(oFunc) {
  862. const that = this;
  863.  
  864. // 已经在函数池中的函数对象,不重复load
  865. if (this.#oFuncs.has(oFunc)) {
  866. return;
  867. }
  868.  
  869. // 检查有无重复id
  870. for (const o of this.#oFuncs.keys()) {
  871. if (o.id === oFunc.id) {
  872. throw new RedeclarationError(`Attempts to load oFunc with id already in use: ${oFunc.id}`);
  873. }
  874. }
  875.  
  876. // 设置当前返回值为STILL_LOADING
  877. this.#oFuncs.set(oFunc, FuncPool.#STILL_LOADING);
  878.  
  879. // 加载依赖
  880. const dependencies = Array.isArray(oFunc.dependencies) ? oFunc.dependencies : ( oFunc.dependencies ? [oFunc.dependencies] : [] );
  881. const promise_deps = Promise.all(dependencies.map(id => new Promise((resolve, reject) => {
  882. $AEL(that, 'load', e => e.detail.oFunc.id === id && resolve());
  883. })));
  884.  
  885. // 检测detectDOM中css选择器指定的元素出现
  886. const selectors = Array.isArray(oFunc.detectDom) ? oFunc.detectDom : ( oFunc.detectDom ? [oFunc.detectDom] : [] );
  887. const promise_css = Promise.all(selectors.map(selector => detectDom(selector)));
  888.  
  889. // 等待上述两项完成
  890. await Promise.all([promise_deps, promise_css]);
  891.  
  892. // 检测checkers加载条件
  893. const checkers = Array.isArray(oFunc.checkers) ? oFunc.checkers : ( oFunc.checkers ? [oFunc.checkers] : [] );
  894. if (!testCheckers(checkers)) {
  895. return;
  896. }
  897.  
  898. // 执行函数对象
  899. const raw_return_value = oFunc.func(oFunc);
  900. const return_value = await Promise.resolve(raw_return_value);
  901.  
  902. // 设置返回值
  903. this.#oFuncs.set(oFunc, return_value);
  904.  
  905. // 广播事件
  906. this.dispatchEvent(new CustomEvent('load', {
  907. detail: {
  908. oFunc, id: oFunc.id, return_value
  909. }
  910. }));
  911. Array.from(this.#oFuncs.values()).every(v => v !== FuncPool.#STILL_LOADING) &&
  912. this.dispatchEvent(new CustomEvent('all_load', {}));
  913. }
  914.  
  915. /**
  916. * 获取指定函数对象的返回值
  917. * 如果指定的函数对象不存在,返回FunctionNotFound
  918. * 如果指定的函数对象存在但尚未加载,返回FunctionNotLoaded
  919. * 如果函数对象指定了readonly为真值,则返回前用Proxy包装返回值,使其不可修改
  920. * @param {string} id - 函数对象的id
  921. * @returns {*}
  922. */
  923. require(id) {
  924. for (const [oFunc, return_value] of this.#oFuncs.entries()) {
  925. if (oFunc.id === id) {
  926. if (return_value === FuncPool.#STILL_LOADING) {
  927. return FuncPool.FunctionNotLoaded;
  928. } else {
  929. return oFunc.readonly ? FuncPool.#MakeReadonlyObj(return_value) : return_value;
  930. }
  931. }
  932. }
  933. return FuncPool.FunctionNotFound;
  934. }
  935.  
  936. isLoaded(id) {
  937. for (const [oFunc, return_value] of this.#oFuncs.entries()) {
  938. if (oFunc.id === id) {
  939. if (return_value === FuncPool.#STILL_LOADING) {
  940. return false;
  941. } else {
  942. return true;
  943. }
  944. }
  945. return false;
  946. }
  947. }
  948.  
  949. /**
  950. * 以Proxy包装value,使其属性只读
  951. * 如果传入的不是obj,则直接返回value
  952. * @param {Object} val
  953. * @returns {Proxy}
  954. */
  955. static #MakeReadonlyObj(val) {
  956. return isObject(val) ? new Proxy(val, {
  957. get: function(target, property, receiver) {
  958. return FuncPool.#MakeReadonlyObj(target[property]);
  959. },
  960. set: function(target, property, value, receiver) {},
  961. has: function(target, prop) {},
  962. setPrototypeOf(target, newProto) {
  963. return false;
  964. },
  965. defineProperty(target, property, descriptor) {
  966. return true;
  967. },
  968. deleteProperty(target, property) {
  969. return false;
  970. },
  971. preventExtensions(target) {
  972. return false;
  973. }
  974. }) : val;
  975.  
  976. function isObject(value) {
  977. return ['object', 'function'].includes(typeof value) && value !== null;
  978. }
  979. }
  980. }
  981. class RedeclarationError extends TypeError {}
  982. class CircularDependencyError extends ReferenceError {}
  983.  
  984.  
  985. // 预置的函数池
  986. const default_pool = new FuncPool();
  987.  
  988. /**
  989. * 在预置的函数池中加载函数对象或其数组
  990. * @param {oFunc[]|oFunc} oFuncs - 需要执行的函数对象
  991. * @returns {FuncPool}
  992. */
  993. function loadFuncs(oFuncs) {
  994. default_pool.load(oFuncs);
  995. return default_pool;
  996. }
  997.  
  998. /**
  999. * 在预置的函数池中获取函数对象的返回值
  1000. * @param {string} id - 函数对象的字符串id
  1001. * @returns {*}
  1002. */
  1003. function require(id) {
  1004. return default_pool.require(id);
  1005. }
  1006.  
  1007. /**
  1008. * 在预置的函数池中检查指定函数对象是否已经加载完毕(有返回值可用)
  1009. * @param {string} id - 函数对象的字符串id
  1010. * @returns {boolean}
  1011. */
  1012. function isLoaded(id) {
  1013. return default_pool.isLoaded(id);
  1014. }
  1015.  
  1016. /**
  1017. * 测试给定checker是否检测通过
  1018. * 给定多个checker时,checkers之间是 或 关系,有一个checker通过即算作整体通过
  1019. * 注意此函数设计和旧版testChecker的设计不同,旧版中一个checker可以有多个值,还可通过checker.all指定多值之间的关系为 与 还是 或
  1020. * @param {checker[]|checker} [checkers] - 需要检测的checkers
  1021. * @returns {boolean}
  1022. */
  1023. function testCheckers(checkers=[]) {
  1024. checkers = Array.isArray(checkers) ? checkers : [checkers];
  1025. return checkers.length === 0 || checkers.some(checker => !!registered_checkers[checker.type]?.(checker.value));
  1026. }
  1027.  
  1028. /**
  1029. * 注册新checker
  1030. * 如果给定type已经被其他checker占用,则会报错RedeclarationError
  1031. * @param {string} type - checker类名
  1032. * @param {function} func - checker implementation
  1033. */
  1034. function registerChecker(type, func) {
  1035. if (registered_checkers.hasOwnProperty(type)) {
  1036. throw RedeclarationError(`Attempts to register checker with type already in use: ${type}`);
  1037. }
  1038. registered_checkers[type] = func;
  1039. }
  1040.  
  1041. const FunctionLoader = {
  1042. FuncPool,
  1043. testCheckers,
  1044. registerChecker,
  1045. get checkers() {
  1046. return Object.assign({}, registered_checkers);
  1047. },
  1048. Error: {
  1049. RedeclarationError,
  1050. CircularDependencyError
  1051. }
  1052. };
  1053. return [FunctionLoader, loadFuncs, require, isLoaded];
  1054. }) ();
  1055.  
  1056. return [
  1057. // Console & Debug
  1058. LogLevel, DoLog, Err, Assert,
  1059.  
  1060. // DOM
  1061. $, $All, $CrE, $AEL, $$CrE, addStyle, detectDom, destroyEvent,
  1062.  
  1063. // Data
  1064. copyProp, copyProps, parseArgs, escJsStr, replaceText,
  1065.  
  1066. // Environment & Browser
  1067. getUrlArgv, dl_browser, dl_GM,
  1068.  
  1069. // Logic & Task
  1070. AsyncManager, queueTask, FunctionLoader, loadFuncs, require, isLoaded
  1071. ];
  1072. }) ();