Greasy Fork 还支持 简体中文。

Basic Functions (For userscripts)

Useful functions for myself

目前為 2025-02-01 提交的版本,檢視 最新版本

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