lib:allfuncs

none

  1. // ==UserScript==
  2. // @name lib:allfuncs
  3. // @version 27
  4. // @description none
  5. // @run-at document-start
  6. // @author rssaromeo
  7. // @license GPLv3
  8. // @match *://*/*
  9. // @include *
  10. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAABICAMAAABiM0N1AAAAAXNSR0IB2cksfwAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAHJQTFRFAAAAEIijAo2yAI60BYyuF4WaFIifAY6zBI2wB4usGIaZEYigIoiZCIyrE4igG4iYD4mjEomhFoedCoqpDIqnDomlBYyvE4efEYmiDYqlA42xBoytD4mkCYqqGYSUFYidC4qoC4upAo6yCoupDYqmCYur4zowOQAAACZ0Uk5TAO////9vr////1+/D/+/L+/Pf/////+f3///////H4////////+5G91rAAACgUlEQVR4nM2Y22KjIBCGidg1264liZqDadK03X3/V2wNKHMC7MpF/xthHD5mgERAqZhWhfYqH6K+Qf2qNNf625hCoFj9/gblMUi5q5jLkXLCKudgyiRm0FMK82cWJp1fLbV5VmvJbCIc0GCYaFqqlDJgADdBjncqAXYobm1xh72aFMflbysteFfdy2Yi1XGOm5HGBzQ1dq7TzEoxjeNTjQZb7VA3e1c7+ImgasAgQ9+xusNVNZIo5xmOMgihIS2PbCQIiHEUdTvhxCcS/kPomfFI2zHy2PkWmA6aNatIJpKFJyekyy02xh5Y3DI9T4aOT6VhIUrsNTFp1pf79Z4SIIVDegl6IJO6cHiL/GimIZDhgTu/BlYWCQzHMl0zBWT/T3KAhtxOuUB9FtBrpsz0RV4xsjHmW+UCaffcSy/5viMGer0/6HdFNMZBq/vjJL38H9Dqx4Fuy0Em12DbZy+9pGtiDijbglwAehyj11n0tRD3WUBm+lwulE/8h4BuA+iWAQQnteg2Xm63WQLTpnMnpjdge0Mgu/GRPsV4xdjQ94Lfi624fabhDkfUqIKNrM64Q837v8yL0prasepCgrtvw1sJpoqanGEX7b5mQboNW8eawXaWXTMfMGxub472hzWzHSn6Sg2G9+6TAyRruE71s+zAzjWaknoyJCQzwxrghH2k5FDT4eqWunuNxyN9QCGcxVod5oADbYnIUkDTGZEf1xDJnSFteQ3KdsT8zYDMQXcHxsevcLH1TrsABzkNPyA/L7b0jg704viMMlpQI96WsHknCt/3YH0kOEo9zcGkwrFK39ck72rmoehmKqo2RKlilzSy/nJKEV45CT38myJp456fezktHjN5aeMAAAAASUVORK5CYII=
  11. // @grant none
  12. // @namespace https://greasyfork.org/users/1184528
  13. // ==/UserScript==
  14.  
  15. // fix gettype in test func
  16. /*
  17. // @noregex
  18. // @name remove ai comments
  19. // @regex (//) \.\.\..*
  20. // @replace
  21. // @endregex
  22. // @regex maketype\((\w+),
  23. // @replace $1 = maketype($1,
  24. // @endregex
  25. */
  26. /**
  27. * @typedef {Object} TestUtils
  28. * @property {function(...*): void} ifunset - Sets default values for undefined inputs.
  29. * @property {function(*): string} gettype - Checks the type of a value.
  30. * @property {function(number): void} pass - Validates that the current parameter is correct.
  31. * @property {function(): boolean} end - Validates that all parameters have been checked.
  32. * @property {function(*, Array<*>): boolean} isany - Checks if a value is in a list of options.
  33. * @property {function(string, RegExp): boolean} matchesregex - Checks if a value matches a regex pattern.
  34. * @property {function(*, *): boolean} issame - Checks if two values are strictly equal.
  35. * @property {function(number, Array<string>): boolean} trymaketype - Attempts to convert a value to one of the specified types.
  36. */
  37. /**
  38. * @callback TestFunction
  39. * @param {TestUtils} testUtils - An object containing utility functions for testing.
  40. * @returns {boolean} Returns true if all validations pass.
  41. */
  42. /**
  43. * @param {Function} func - The function to wrap in a test.
  44. * @param {TestFunction} testfunc - The function to test func against.
  45. * @returns {Function} - The wrapped function.
  46. */
  47.  
  48. ;(() => {
  49. function newfunc(func, testfunc) {
  50. var funcname = func.name || func.prototype.name
  51. var retfunc = function () {
  52. var i = 0
  53. var inputargs = [...arguments]
  54. return testfunc({
  55. funcname,
  56. args: inputargs,
  57. /**
  58. *
  59. * @param {*} thing - anything
  60. * @param {Array} _enum - list of posable things thing can be
  61. * @returns {Error|*}
  62. */
  63. makeenum: function makeenum(thing, _enum) {
  64. for (var thing2 of _enum) {
  65. if (thing == thing2) return thing2
  66. }
  67. throw new Error(
  68. `makeenum: in function ${this.funcname} input ${i} is invalid, should match enum [${_enum}] but is instead ${thing}`
  69. )
  70. }.bind(retfunc),
  71. trymakeenum: function trymakeenum(thing, _enum) {
  72. try {
  73. this.makeenum(thing, _enum)
  74. return true
  75. } catch (e) {
  76. return false
  77. }
  78. }.bind(retfunc),
  79. /**
  80. * Sets default values for input if they are undefined.
  81. * @param {...*} input - The default values to set.
  82. */
  83. ifunset: function ifunset(newinputs) {
  84. for (var i in newinputs) {
  85. if (inputargs[i] === undefined)
  86. inputargs[i] = newinputs[i]
  87. }
  88. }.bind(retfunc),
  89. /**
  90. *
  91. * @param {Number} i - tries to make thing become a type in types
  92. * @param {Array|string} types - array of types to try to be
  93. * @returns {boolean}
  94. */
  95. trymaketype: function trymaketype(thing, types) {
  96. try {
  97. this.maketype(thing, types)
  98. return true
  99. } catch (e) {
  100. return false
  101. }
  102. }.bind(retfunc),
  103. /**
  104. *
  105. * @param {Number} i - tries to make thing become a type in types
  106. * @param {Array|string} types - array of types to try to be
  107. * @returns {Error|true}
  108. */
  109. maketype: function maketype(thing, types) {
  110. // if (types.includes("any")) return true
  111. if (gt(thing, types)) return thing
  112. for (var type of types) {
  113. if (gt(thing, "string") && type == "number") {
  114. thing = Number(thing)
  115. }
  116. if (gt(thing, "number") && type == "string") {
  117. thing = String(thing)
  118. }
  119. if (gt(thing, "string") && type == "number") {
  120. thing = Number(thing)
  121. }
  122. if (gt(thing, "number") && type == "string") {
  123. thing = String(thing)
  124. }
  125. if (gt(thing, "boolean") && type == 1) {
  126. thing = true
  127. }
  128. if (type == "boolean" && (thing == 0 || thing == "")) {
  129. thing = false
  130. }
  131. if (gt(thing, type)) return thing
  132. }
  133. throw new Error(
  134. `trymaketype: in function ${
  135. this.funcname
  136. } input ${i} is invalid, should be type [${types}] but is instead type ${gt(
  137. thing
  138. )}`
  139. )
  140. }.bind(retfunc),
  141. /**
  142. *
  143. * @param {*} thing - the thing to get the type of
  144. * @param {string|Array|undefined} match - if set the type to check aganst or array of ytpes to check aganst
  145. * @returns {boolean|string}
  146. */
  147. trygettype: gt,
  148. gettype: function gettype(a, s) {
  149. if (gt(a, s)) return true
  150. throw new Error(
  151. `gettype: in function ${
  152. this.funcname
  153. } input ${i} is invalid, should be type [${s}] but is instead type ${gettype(
  154. a
  155. )}`
  156. )
  157. }.bind(retfunc),
  158. /**
  159. * tells that the test function has ended and to try and call the main function
  160. * @returns {boolean|undefined}
  161. */
  162. end: function end() {
  163. return func.call(func, ...inputargs)
  164. }.bind(retfunc),
  165. })
  166. }
  167. retfunc.name = retfunc.prototype.name =
  168. "strict " + (funcname ?? "function")
  169. retfunc.funcname = funcname
  170. return retfunc.bind(retfunc)
  171. /**
  172. *
  173. * @param {*} thing - the thing to get the type of
  174. * @param {string|Array|undefined} match - if set the type to check aganst or array of ytpes to check aganst
  175. * @returns {boolean|string}
  176. */
  177. function gt(thing, match) {
  178. if (
  179. !match ||
  180. (Object.prototype.toString
  181. .call(match)
  182. .toLowerCase()
  183. .match(/^\[[a-z]+ (.+)\]$/)[1] == "string" &&
  184. !match.includes("|"))
  185. ) {
  186. var type = Object.prototype.toString
  187. .call(thing)
  188. .toLowerCase()
  189. .match(/^\[[a-z]+ (.+)\]$/)[1]
  190. if (type !== "function") if (type == match) return true
  191. if (match == "normalfunction") return type == "function"
  192. if (type == "htmldocument" && match == "document") return true
  193. if (match == "body" && type == "htmlbodyelement") return true
  194. if (match && new RegExp(`^html${match}element$`).test(type))
  195. return true
  196. if (/^html\w+element$/.test(type)) type = "element"
  197. if (type == "htmldocument") type = "element"
  198. if (type == "asyncfunction") type = "function"
  199. if (type == "generatorfunction") type = "function"
  200. if (type == "regexp") type = "regex"
  201. if (match == "regexp") match = "regex"
  202. if (match == "element" && type == "window") return true
  203. if (match == "element" && type == "shadowroot") return true
  204. if (match == "event" && /\w+event$/.test(type)) return true
  205. if (/^(html|svg).*element$/.test(type)) type = "element"
  206. if (type == "function") {
  207. type = /^\s*class\s/.test(
  208. Function.prototype.toString.call(thing)
  209. )
  210. ? "class"
  211. : "function"
  212. }
  213. if (match == "none")
  214. return (
  215. type == "nan" || type == "undefined" || type == "null"
  216. )
  217. try {
  218. if (type === "number" && isNaN(thing) && match == "nan")
  219. return true
  220. } catch (e) {
  221. error(thing)
  222. }
  223. return match ? match === type : type
  224. } else {
  225. if (match.includes("|")) match = match.split("|")
  226. match = [...new Set(match)]
  227. return !!match.find((e) => gt(thing, e))
  228. }
  229. }
  230. }
  231. const a = {}
  232. var x = newfunc(
  233. function foreach(arr, func) {
  234. var type = a.gettype(arr)
  235. if (type == "array") arr.forEach(func)
  236. else if (type == "object") {
  237. Reflect.ownKeys(arr).forEach((e, i) => {
  238. func(e, arr[e], i)
  239. })
  240. } else {
  241. ;[arr].forEach(func)
  242. }
  243. },
  244. ({ args: [arr, func], end, maketype }) => {
  245. arr = maketype(arr, ["array", "object", "any"])
  246. func = maketype(func, ["function"])
  247. return end()
  248. }
  249. )
  250.  
  251. a.wait = newfunc(
  252. function wait(ms) {
  253. return new Promise(function (done) {
  254. var last = Date.now()
  255. setTimeout(() => done(Date.now() - last - ms), ms)
  256. })
  257. },
  258. function ({ ifunset, end, args: [ms], maketype }) {
  259. ifunset([0])
  260. ms = maketype(ms, ["number"])
  261. return end()
  262. }
  263. )
  264.  
  265. a.waituntil = newfunc(
  266. function waituntil(q, cb) {
  267. return new Promise((resolve) => {
  268. var last = Date.now()
  269. var int = setInterval(
  270. function (q, cb) {
  271. if (!!q()) {
  272. clearInterval(int)
  273. try {
  274. cb(Date.now() - last)
  275. } catch (e) {}
  276. resolve(Date.now() - last)
  277. }
  278. },
  279. 0,
  280. q,
  281. cb
  282. )
  283. })
  284. },
  285. function ({ end, args: [q, cb], maketype }) {
  286. q = maketype(q, ["function"])
  287. cb = maketype(cb, ["function", "undefined"])
  288. return end()
  289. }
  290. )
  291.  
  292. a.keeponlyone = newfunc(
  293. function keeponlyone(arr) {
  294. return [...new Set(arr)]
  295. },
  296. function ({ end, args: [arr], maketype }) {
  297. arr = maketype(arr, ["array"])
  298. return end()
  299. }
  300. )
  301.  
  302. a.matchall = newfunc(
  303. function matchall(x, y) {
  304. return [...x.matchAll(y)].map((e) =>
  305. e[1] !== undefined ? [...e] : e[0]
  306. )
  307. },
  308. function ({ args: [x, y], end, maketype }) {
  309. x = maketype(x, ["string"])
  310. y = maketype(y, ["regex"])
  311. return end()
  312. }
  313. )
  314.  
  315. a.randfrom = newfunc(
  316. function randfrom(min, max) {
  317. if (max === undefined)
  318. return min.length
  319. ? min[this(0, min.length - 1)]
  320. : this(0, min)
  321. if (min == max) return min
  322. if (max) return Math.round(Math.random() * (max - min)) + min
  323. return min[Math.round(Math.random() * (min.length - 1))]
  324. },
  325. function ({ args: [min, max], end, maketype }) {
  326. min = maketype(min, ["number", "array"])
  327. max = maketype(max, ["number", "undefined"])
  328. return end()
  329. }
  330. )
  331. a.foreach = newfunc(
  332. function foreach(
  333. //none
  334. arr, //array|object|any
  335. func //function
  336. ) {
  337. var type = a.gettype(arr)
  338. if (type == "array") arr.forEach(func)
  339. else if (type == "object") {
  340. Reflect.ownKeys(arr).forEach((e, i) => {
  341. func(e, arr[e], i)
  342. })
  343. } else {
  344. ;[arr].forEach(func)
  345. }
  346. },
  347. function ({ args: [arr, func], end, maketype }) {
  348. func = maketype(func, ["function"])
  349. return end()
  350. }
  351. )
  352. a.listen = newfunc(
  353. function listen(elem, type, cb, istrue = false) {
  354. var all = []
  355. if (a.gettype(elem, "array")) {
  356. return [...elem].map(listen).flat()
  357. } else {
  358. return listen(elem)
  359. }
  360. function listen(elem) {
  361. if (a.gettype(type, "array")) {
  362. var temp = {}
  363. a.foreach(type, (e) => (temp[e] = cb))
  364. type = temp
  365. }
  366. if (a.gettype(type, "object")) {
  367. istrue = cb
  368. a.foreach(type, function (type, cb) {
  369. if (a.gettype(type, "string"))
  370. type = a.matchall(type, /[a-z]+/g)
  371. type.forEach((type) => {
  372. const newcb = function (...e) {
  373. cb.call(elem, ...e)
  374. }
  375. elem.addEventListener(type, newcb, istrue)
  376. all.push([elem, type, newcb, istrue])
  377. })
  378. })
  379. } else if (a.gettype(type, "string")) {
  380. type = a.matchall(type, /[a-z]+/g)
  381. type.forEach((type) => {
  382. const newcb = function (e) {
  383. cb.call(elem, e, type)
  384. }
  385. elem.addEventListener(type, newcb, istrue)
  386. all.push([elem, type, newcb, istrue])
  387. })
  388. }
  389. return all
  390. }
  391. },
  392. function ({
  393. gettype,
  394. trygettype,
  395. args, //[elem, type, cb, istrue],
  396. end,
  397. maketype,
  398. }) {
  399. var [elem, type, cb, istrue] = args
  400. elem = maketype(elem, ["element", "window", "string", "array"])
  401. if (trygettype(elem, "string")) {
  402. elem = a.qs(elem)
  403. elem = maketype(elem, ["element"])
  404. args[0] = elem
  405. }
  406. type = maketype(type, ["array", "object", "string"])
  407. if (trygettype(type, ["array", "any"])) {
  408. for (var temp in type) gettype(temp, "string")
  409. } else if (trygettype(type, "object")) {
  410. for (var temp of Object.values(type))
  411. gettype(temp, "function")
  412. }
  413. if (trygettype(type, "object")) cb = maketype(cb, ["undefined"])
  414. else cb = maketype(cb, ["function"])
  415. istrue = maketype(istrue, ["boolean", "undefined"])
  416. return end()
  417. }
  418. )
  419. a.unlisten = newfunc(
  420. function listen(all) {
  421. for (var l of all) {
  422. l[0].removeEventListener(l[1], l[2], l[3])
  423. }
  424. },
  425. function ({ gettype, trygettype, args: [all], end, maketype }) {
  426. all = maketype(all, ["array"])
  427. return end()
  428. }
  429. )
  430.  
  431. a.toelem = newfunc(
  432. function toelem(elem, single) {
  433. if (a.gettype(elem, "element")) return elem
  434. switch (a.gettype(elem)) {
  435. case "string":
  436. return single ? a.qs(elem) : a.qsa(elem)
  437. case "array":
  438. return elem.map((elem) => {
  439. return a.toelem(elem, single)
  440. })
  441. case "object":
  442. var newobj = {
  443. ...elem,
  444. }
  445. if (single)
  446. return {
  447. [Object.keys(newobj)[0]]: a.toelem(
  448. newobj[Object.keys(newobj)[0]],
  449. single
  450. ),
  451. }
  452. a.foreach(newobj, function (a, s) {
  453. newobj[a] = a.toelem(s)
  454. })
  455. return newobj
  456. default:
  457. error(elem, "inside [toelem] - not an element?")
  458. return undefined
  459. }
  460. },
  461. function ({ ifunset, end, args: [elem, single], maketype }) {
  462. ifunset([undefined, false])
  463. elem = maketype(elem, ["element", "string", "array", "object"])
  464. single = maketype(single, ["boolean"])
  465. return end()
  466. }
  467. )
  468.  
  469. a.geturlperams = newfunc(
  470. function geturlperams(e = location.href) {
  471. var arr = {}
  472. ;[
  473. ...e.matchAll(/[?&]([^&\s]+?)(?:=([^&\s]*?))?(?=&|$|\s)/g),
  474. ].forEach((e) => {
  475. if (e[1].includes("#")) arr["#"] = e[1].match(/#(.*$)/)[1]
  476. if (e[2].includes("#")) arr["#"] = e[2].match(/#(.*$)/)[1]
  477. e[1] = e[1].replace(/#.*$/, "")
  478. e[2] = e[2].replace(/#.*$/, "")
  479. arr[decodeURIComponent(e[1]).replaceAll("+", " ")] =
  480. e[2] === undefined
  481. ? undefined
  482. : decodeURIComponent(e[2]).replaceAll("+", " ")
  483. })
  484. return arr
  485. },
  486. function ({ end, maketype, args: [e], ifunset }) {
  487. ifunset([location.href])
  488. e = maketype(e, ["string", "undefined"])
  489. return end()
  490. }
  491. )
  492.  
  493. a.updateurlperam = newfunc(
  494. function updateurlperam(key, value, cangoback) {
  495. var g = a.geturlperams()
  496. if (g[key] == value && !cangoback) return
  497. g[key] = value
  498. var k = ""
  499. var hash = ""
  500. a.foreach(g, function (key, value) {
  501. if (key == "#") return (hash = key + value)
  502. key = encodeURIComponent(key)
  503. value = encodeURIComponent(value)
  504. k += "&" + (value === undefined ? key : key + "=" + value)
  505. })
  506. k = k.replace("&", "?")
  507. k += hash
  508. cangoback
  509. ? history.pushState(null, null, k)
  510. : history.replaceState(null, null, k)
  511. return key
  512. },
  513. function ({
  514. ifunset,
  515. end,
  516. maketype,
  517. args: [key, value, cangoback],
  518. }) {
  519. ifunset([undefined, undefined, true])
  520. key = maketype(key, ["string"])
  521. value = maketype(value, ["string"])
  522. cangoback = maketype(cangoback, ["boolean"])
  523. return end()
  524. }
  525. )
  526.  
  527. a.rerange = newfunc(
  528. function rerange(val, low1, high1, low2, high2) {
  529. return ((val - low1) / (high1 - low1)) * (high2 - low2) + low2
  530. },
  531. function ({
  532. end,
  533. maketype,
  534. args: [val, low1, high1, low2, high2],
  535. }) {
  536. val = maketype(val, ["number"])
  537. low1 = maketype(low1, ["number"])
  538. high1 = maketype(high1, ["number"])
  539. low2 = maketype(low2, ["number"])
  540. high2 = maketype(high2, ["number"])
  541. return end()
  542. }
  543. )
  544.  
  545. a.destring = newfunc(
  546. function destring(inp) {
  547. var out = inp
  548. if (/^[\-0-9]+$/.test(inp)) return Number(inp)
  549. if (a.gettype((out = JSON.parse(inp)), "array")) return out
  550. if (
  551. a.gettype(
  552. (out = JSON.parse(
  553. inp.replaceAll("'", '"').replaceAll("`", '"')
  554. )),
  555. "object"
  556. )
  557. )
  558. return out
  559. if (inp == "true") return true
  560. if (inp == "false") return false
  561. if (inp == "undefined") return undefined
  562. if (inp == "NaN") return NaN
  563. return inp
  564. },
  565. function ({ end, maketype, args: [inp] }) {
  566. inp = maketype(inp, ["string"])
  567. return end()
  568. }
  569. )
  570.  
  571. a.eachelem = newfunc(
  572. function eachelem(arr1, cb) {
  573. var arr = []
  574. var elem = []
  575. if (a.gettype(arr1, "array")) {
  576. arr1.foreach((e) => {
  577. elem = [
  578. ...elem,
  579. ...(a.gettype(e, "string") ? a.qsa(e) : [e]),
  580. ]
  581. })
  582. } else {
  583. elem = a.gettype(arr1, "string") ? a.qsa(ar1) : [arr1]
  584. }
  585. elem = elem.filter((e) => {
  586. return e instanceof Element
  587. })
  588. elem.foreach(function (...a) {
  589. arr.push(cb(...a))
  590. })
  591. if (arr.length == 1) arr = arr[0]
  592. return arr
  593. },
  594. function ({ end, maketype, args: [arr1, cb] }) {
  595. arr1 = maketype(arr1, ["string", "array", "element"])
  596. cb = maketype(cb, ["function"])
  597. return end()
  598. }
  599. )
  600.  
  601. a.remove = newfunc(
  602. function remove(arr, idx, isidx) {
  603. arr = [...arr]
  604. idx = isidx ? idx : arr.indexOf(idx)
  605. if (idx < 0 || typeof idx !== "number") return arr
  606. arr.splice(idx, 1)
  607. return arr
  608. },
  609. function ({
  610. ifunset,
  611. gettype,
  612. end,
  613. maketype,
  614. trymaketype,
  615. trygettype,
  616. args: [arr, idx, isidx],
  617. }) {
  618. ifunset([undefined, undefined, true])
  619. isidx = maketype(isidx, ["boolean"])
  620. if (isidx) idx = maketype(idx, ["number"])
  621. arr = maketype(arr, ["array"])
  622. return end()
  623. }
  624. )
  625.  
  626. a.createelem = newfunc(
  627. function createelem(parent, elem, data = {}) {
  628. var type = elem
  629. var issvg =
  630. elem == "svg" || parent?.tagName?.toLowerCase?.() == "svg"
  631. elem = issvg
  632. ? document.createElementNS("http://www.w3.org/2000/svg", elem)
  633. : document.createElement(elem)
  634. if (data.class)
  635. data.class.split(" ").forEach((e) => {
  636. elem.classList.add(e)
  637. })
  638. if (data.options && type == "select")
  639. data.options = data.options.map((e) =>
  640. a.gettype(e, "array")
  641. ? a.createelem(elem, "option", {
  642. innerHTML: e[0],
  643. value: e[1],
  644. })
  645. : a.createelem(elem, "option", {
  646. innerHTML: e,
  647. value: e,
  648. })
  649. )
  650. if (type == "label" && "for" in data) {
  651. data.htmlFor = data.for
  652. }
  653. Object.assign(elem.style, data)
  654. if (type == "select") {
  655. a.foreach(data, function (a, s) {
  656. elem[a] = s
  657. })
  658. } else if (issvg) {
  659. Object.keys(data).forEach((e) => (elem[e] = data[e]))
  660. } else {
  661. Object.assign(elem, data)
  662. }
  663. if (parent !== null) {
  664. if (typeof parent == "string") parent = a.qs(parent)
  665. parent.appendChild(elem)
  666. }
  667. return elem
  668. },
  669. function ({
  670. ifunset,
  671. end,
  672. maketype,
  673. args: [parent, elem, data],
  674. }) {
  675. ifunset([undefined, undefined, {}])
  676. parent = maketype(parent, ["element", "none"])
  677. elem = maketype(elem, ["string"])
  678. data = maketype(data, ["object"])
  679. return end()
  680. }
  681. )
  682. a.newelem = newfunc(
  683. function newelem(type, data = {}, inside = []) {
  684. var parent = a.createelem(null, type, data)
  685. inside.forEach((elem) => {
  686. parent.appendChild(elem)
  687. })
  688. return parent
  689. },
  690. function ({
  691. ifunset,
  692. gettype,
  693. end,
  694. maketype,
  695. trymaketype,
  696. trygettype,
  697. args: [type, data, inside],
  698. }) {
  699. ifunset([null, {}, []])
  700. type = maketype(type, ["string"])
  701. data = maketype(data, ["object", "undefined", "null"])
  702. maketype(inside, ["array", "undefined", "null"])
  703. return end()
  704. }
  705. )
  706. a.gettype = newfunc(
  707. function gettype(thing, match) {
  708. if (
  709. !match ||
  710. (Object.prototype.toString
  711. .call(match)
  712. .toLowerCase()
  713. .match(/^\[[a-z]+ (.+)\]$/)[1] == "string" &&
  714. !match.includes("|"))
  715. ) {
  716. var type = Object.prototype.toString
  717. .call(thing)
  718. .toLowerCase()
  719. .match(/^\[[a-z]+ (.+)\]$/)[1]
  720. if (type !== "function") if (type == match) return true
  721. if (match == "normalfunction") return type == "function"
  722. if (type == "htmldocument" && match == "document") return true
  723. if (match == "body" && type == "htmlbodyelement") return true
  724. if (match && new RegExp(`^html${match}element$`).test(type))
  725. return true
  726. if (/^html\w+element$/.test(type)) type = "element"
  727. if (type == "htmldocument") type = "element"
  728. if (type == "asyncfunction") type = "function"
  729. if (type == "generatorfunction") type = "function"
  730. if (type == "regexp") type = "regex"
  731. if (match == "regexp") match = "regex"
  732. if (match == "element" && type == "window") return true
  733. if (match == "element" && type == "shadowroot") return true
  734. if (match == "event" && /\w+event$/.test(type)) return true
  735. if (/^(html|svg).*element$/.test(type)) type = "element"
  736. if (type == "function") {
  737. type = /^\s*class\s/.test(
  738. Function.prototype.toString.call(thing)
  739. )
  740. ? "class"
  741. : "function"
  742. }
  743. if (match == "none")
  744. return (
  745. type == "nan" || type == "undefined" || type == "null"
  746. )
  747. try {
  748. if (type === "number" && isNaN(thing) && match == "nan")
  749. return true
  750. } catch (e) {
  751. error(thing)
  752. }
  753. return match ? match === type : type
  754. } else {
  755. if (match.includes("|")) match = match.split("|")
  756. match = [...new Set(match)]
  757. return match.filter((e) => a.gettype(thing, e)).length > 0
  758. }
  759. },
  760. function ({
  761. ifunset,
  762. gettype,
  763. end,
  764. maketype,
  765. trymaketype,
  766. trygettype,
  767. args: [_thing, match],
  768. }) {
  769. // _thing = maketype(_thing, ["any"])
  770. match = maketype(match, ["array", "string", "none"])
  771. return end()
  772. }
  773. )
  774.  
  775. a.waitforelem = newfunc(
  776. async function waitforelem(selector) {
  777. if (a.gettype(selector, "string")) {
  778. selector = [selector]
  779. }
  780. await a.bodyload()
  781. var g = false
  782. return new Promise((resolve) => {
  783. var observer = new MutationObserver(check)
  784. observer.observe(document.body, {
  785. childList: true,
  786. subtree: true,
  787. attributes: true,
  788. characterData: false,
  789. })
  790. check()
  791. function check() {
  792. if (g) return
  793. if (selector.find((selector) => !a.qs(selector))) return
  794. observer.disconnect()
  795. resolve(
  796. selector.length == 1
  797. ? a.qs(selector[0])
  798. : selector.map((e) => a.qs(e))
  799. )
  800. }
  801. })
  802. },
  803. function ({ ifunset, end, args: [selector], maketype }) {
  804. ifunset([undefined])
  805. selector = maketype(selector, ["string", "array"])
  806. return end()
  807. }
  808. )
  809.  
  810. a.getallvars = newfunc(
  811. function getallvars() {
  812. var obj = {}
  813. var variables = []
  814. for (var name in this)
  815. if (
  816. !`window self document name location customElements history locationbar menubar personalbar scrollbars statusbar toolbar status closed frames length top opener parent frameElement navigator origin external screen innerWidth innerHeight scrollX pageXOffset scrollY pageYOffset visualViewport screenX screenY outerWidth outerHeight devicePixelRatio clientInformation screenLeft screenTop styleMedia onsearch isSecureContext trustedTypes performance onappinstalled onbeforeinstallprompt crypto indexedDB sessionStorage localStorage onbeforexrselect onabort onbeforeinput onblur oncancel oncanplay oncanplaythrough onchange onclick onclose oncontextlost oncontextmenu oncontextrestored oncuechange ondblclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop ondurationchange onemptied onended onerror onfocus onformdata oninput oninvalid onkeydown onkeypress onkeyup onload onloadeddata onloadedmetadata onloadstart onmousedown onmouseenter onmouseleave onmousemove onmouseout onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange onreset onresize onscroll onsecuritypolicyviolation onseeked onseeking onselect onslotchange onstalled onsubmit onsuspend ontimeupdate ontoggle onvolumechange onwaiting onwebkitanimationend onwebkitanimationiteration onwebkitanimationstart onwebkittransitionend onwheel onauxclick ongotpointercapture onlostpointercapture onpointerdown onpointermove onpointerrawupdate onpointerup onpointercancel onpointerover onpointerout onpointerenter onpointerleave onselectstart onselectionchange onanimationend onanimationiteration onanimationstart ontransitionrun ontransitionstart ontransitionend ontransitioncancel onafterprint onbeforeprint onbeforeunload onhashchange onlanguagechange onmessage onmessageerror onoffline ononline onpagehide onpageshow onpopstate onrejectionhandled onstorage onunhandledrejection onunload crossOriginIsolated scheduler alert atob blur btoa cancelAnimationFrame cancelIdleCallback captureEvents clearInterval clearTimeout close confirm createImageBitmap fetch find focus getComputedStyle getSelection matchMedia moveBy moveTo open postMessage print prompt queueMicrotask releaseEvents reportError requestAnimationFrame requestIdleCallback resizeBy resizeTo scroll scrollBy scrollTo setInterval setTimeout stop structuredClone webkitCancelAnimationFrame webkitRequestAnimationFrame originAgentCluster navigation webkitStorageInfo speechSynthesis oncontentvisibilityautostatechange openDatabase webkitRequestFileSystem webkitResolveLocalFileSystemURL chrome caches cookieStore ondevicemotion ondeviceorientation ondeviceorientationabsolute launchQueue onbeforematch getDigitalGoodsService getScreenDetails queryLocalFonts showDirectoryPicker showOpenFilePicker showSaveFilePicker TEMPORARY PERSISTENT addEventListener dispatchEvent removeEventListener`
  817. .split(" ")
  818. .includes(name)
  819. )
  820. variables.push(name)
  821. variables.forEach((e) => {
  822. var c = String(a.gettype(this[e]))
  823. if (c === "object") c = "variable"
  824. if (!obj[c]) obj[c] = []
  825. obj[c].push(e)
  826. })
  827. return obj
  828. },
  829. function ({ end }) {
  830. return end()
  831. }
  832. )
  833.  
  834. a.sha = newfunc(
  835. function sha(s = "", includesymbols) {
  836. var tab
  837. if (typeof includesymbols == "string") {
  838. tab = includesymbols
  839. } else if (includesymbols) {
  840. tab =
  841. "`~\\|[];',./{}:<>?\"!@#$%^&*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  842. } else {
  843. tab =
  844. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  845. }
  846. return binb2b64(core_sha1(str2binb(s), s.length * 8))
  847. function core_sha1(x, len) {
  848. x[len >> 5] |= 0x80 << (24 - len)
  849. x[(((len + 64) >> 9) << 4) + 15] = len
  850. var w = Array(80)
  851. var a = 1732584193
  852. var b = -271733879
  853. var c = -1732584194
  854. var d = 271733878
  855. var e = -1009589776
  856. for (var i = 0; i < x.length; i += 16) {
  857. var olda = a
  858. var oldb = b
  859. var oldc = c
  860. var oldd = d
  861. var olde = e
  862. for (var j = 0; j < 80; j++) {
  863. if (j < 16) w[j] = x[i + j]
  864. else
  865. w[j] = rol(
  866. w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16],
  867. 1
  868. )
  869. var t = safe_add(
  870. safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
  871. safe_add(safe_add(e, w[j]), sha1_kt(j))
  872. )
  873. e = d
  874. d = c
  875. c = rol(b, 30)
  876. b = a
  877. a = t
  878. }
  879. a = safe_add(a, olda)
  880. b = safe_add(b, oldb)
  881. c = safe_add(c, oldc)
  882. d = safe_add(d, oldd)
  883. e = safe_add(e, olde)
  884. }
  885. return Array(a, b, c, d, e)
  886. }
  887. function sha1_ft(t, b, c, d) {
  888. if (t < 20) return (b & c) | (~b & d)
  889. if (t < 40) return b ^ c ^ d
  890. if (t < 60) return (b & c) | (b & d) | (c & d)
  891. return b ^ c ^ d
  892. }
  893. function sha1_kt(t) {
  894. return t < 20
  895. ? 1518500249
  896. : t < 40
  897. ? 1859775393
  898. : t < 60
  899. ? -1894007588
  900. : -899497514
  901. }
  902. function safe_add(x, y) {
  903. var lsw = (x & 0xffff) + (y & 0xffff)
  904. var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
  905. return (msw << 16) | (lsw & 0xffff)
  906. }
  907. function rol(num, cnt) {
  908. return (num << cnt) | (num >>> (32 - cnt))
  909. }
  910. function str2binb(str) {
  911. var bin = Array()
  912. var mask = (1 << 8) - 1
  913. for (var i = 0; i < str.length * 8; i += 8)
  914. bin[i >> 5] |= (str.charCodeAt(i / 8) & mask) << (24 - i)
  915. return bin
  916. }
  917. function binb2b64(binarray) {
  918. var str = ""
  919. for (var i = 0; i < binarray.length * 4; i += 3) {
  920. var triplet =
  921. (((binarray[i >> 2] >> (8 * (3 - (i % 4)))) & 0xff) <<
  922. 16) |
  923. (((binarray[(i + 1) >> 2] >> (8 * (3 - ((i + 1) % 4)))) &
  924. 0xff) <<
  925. 8) |
  926. ((binarray[(i + 2) >> 2] >> (8 * (3 - ((i + 2) % 4)))) &
  927. 0xff)
  928. for (var j = 0; j < 4; j++) {
  929. if (i * 8 + j * 6 > binarray.length * 32) str += ""
  930. else str += tab.charAt((triplet >> (6 * (3 - j))) & 0x3f)
  931. }
  932. }
  933. return str
  934. }
  935. },
  936. function ({ ifunset, end, args: [s, includesymbols], maketype }) {
  937. ifunset([undefined, false])
  938. s = maketype(s, ["string"])
  939. includesymbols = maketype(includesymbols, ["boolean", "string"])
  940. return end()
  941. }
  942. )
  943.  
  944. a.qs = newfunc(
  945. function qs(text, parent = document) {
  946. return parent.querySelector(text)
  947. },
  948. function ({ end, args: [text, parent], maketype }) {
  949. parent = maketype(parent, ["element", "undefined"])
  950. text = maketype(text, ["string"])
  951. return end()
  952. }
  953. )
  954.  
  955. a.qsa = newfunc(
  956. function qsa(text, parent = document) {
  957. return Array.from(parent.querySelectorAll(text))
  958. },
  959. function ({ end, args: [text, parent], maketype }) {
  960. parent = maketype(parent, ["element", "undefined"])
  961. text = maketype(text, ["string"])
  962. return end()
  963. }
  964. )
  965.  
  966. a.csspath = newfunc(
  967. function csspath(el) {
  968. if (a.gettype(el, "array"))
  969. return a.map(el, (e) => a.csspath(e))
  970. if (!(el instanceof Element)) return
  971. var path = []
  972. while (el.nodeType === Node.ELEMENT_NODE) {
  973. var selector = el.nodeName.toLowerCase()
  974. if (el.id) {
  975. selector += "#" + el.id
  976. path.unshift(selector)
  977. break
  978. } else {
  979. var sib = el,
  980. nth = 1
  981. while ((sib = sib.previousElementSibling)) {
  982. if (sib.nodeName.toLowerCase() == selector) nth++
  983. }
  984. if (nth != 1) selector += ":nth-of-type(" + nth + ")"
  985. }
  986. path.unshift(selector)
  987. el = el.parentNode
  988. }
  989. return path.join(" > ")
  990. },
  991. function ({ end, args: [el], maketype }) {
  992. el = maketype(el, ["element", "array"])
  993. return end()
  994. }
  995. )
  996.  
  997. a.fromms = newfunc(
  998. function fromms(ms) {
  999. ms = Number(ms)
  1000. return {
  1001. years: Math.floor(ms / 1000 / 60 / 60 / 24 / 365),
  1002. days: Math.floor(ms / 1000 / 60 / 60 / 24) % 365,
  1003. hours: Math.floor(ms / 1000 / 60 / 60) % 24,
  1004. mins: Math.floor(ms / 1000 / 60) % 60,
  1005. secs: Math.floor(ms / 1000) % 60,
  1006. ms: Math.floor(ms) % 1000,
  1007. }
  1008. },
  1009. function ({ ifunset, end, args: [ms], maketype }) {
  1010. ifunset([0]) // Default value for ms
  1011. ms = maketype(ms, ["number"]) // Ensure ms is a number
  1012. return end()
  1013. }
  1014. )
  1015.  
  1016. a.fromms = newfunc(
  1017. function fromms(ms) {
  1018. ms = Number(ms)
  1019. return {
  1020. years: Math.floor(ms / 1000 / 60 / 60 / 24 / 365),
  1021. days: Math.floor(ms / 1000 / 60 / 60 / 24) % 365,
  1022. hours: Math.floor(ms / 1000 / 60 / 60) % 24,
  1023. mins: Math.floor(ms / 1000 / 60) % 60,
  1024. secs: Math.floor(ms / 1000) % 60,
  1025. ms: Math.floor(ms) % 1000,
  1026. }
  1027. },
  1028. function ({ ifunset, end, args: [ms], maketype }) {
  1029. ifunset([0]) // Default value for ms
  1030. ms = maketype(ms, ["number"]) // Ensure ms is a number
  1031. return end()
  1032. }
  1033. )
  1034.  
  1035. a.rect = newfunc(
  1036. function rect(e) {
  1037. if (a.gettype(e, "string")) e = a.qs(e)
  1038. var { x, y, width, height } = e.getBoundingClientRect().toJSON()
  1039. return {
  1040. x,
  1041. y,
  1042. w: width,
  1043. h: height,
  1044. }
  1045. },
  1046. function ({ end, args: [e], maketype }) {
  1047. e = maketype(e, ["element", "string"])
  1048. return end()
  1049. }
  1050. )
  1051.  
  1052. a.setelem = newfunc(
  1053. function setelem(elem, data) {
  1054. var issvg =
  1055. elem == "svg" || parent?.tagName?.toLowerCase?.() == "svg"
  1056. if (data.class)
  1057. data.class.split(" ").forEach((e) => {
  1058. elem.classList.add(e)
  1059. })
  1060. if (data.options && elem.tagName.toLowerCase() == "select")
  1061. data.options = data.options.map((e) =>
  1062. a.gettype(e, "array")
  1063. ? a.createelem(elem, "option", {
  1064. innerHTML: e[0],
  1065. value: e[1],
  1066. })
  1067. : a.createelem(elem, "option", {
  1068. innerHTML: e,
  1069. value: e,
  1070. })
  1071. )
  1072. if (elem.tagName.toLowerCase() == "label" && "for" in data) {
  1073. data.htmlFor = data.for
  1074. }
  1075. Object.assign(elem.style, data)
  1076. if (elem.tagName.toLowerCase() == "select") {
  1077. a.foreach(data, function (a, s) {
  1078. elem[a] = s
  1079. })
  1080. } else if (issvg) {
  1081. Object.keys(data).forEach((e) => (elem[e] = data[e]))
  1082. } else {
  1083. Object.assign(elem, data)
  1084. }
  1085. return elem
  1086. },
  1087. function ({ ifunset, end, args: [elem, data], maketype }) {
  1088. ifunset([undefined, {}]) // Default value for data
  1089. elem = maketype(elem, ["element", "string"]) // Ensure elem is an element or string
  1090. data = maketype(data, ["object"]) // Ensure data is an object
  1091. return end()
  1092. }
  1093. )
  1094.  
  1095. a.watchvar = newfunc(
  1096. function watchvar(varname, onset, onget, obj = window) {
  1097. obj = obj || window
  1098. obj[`_${varname}`] = undefined
  1099. obj[`${varname}`] = undefined
  1100. Object.defineProperty(obj, varname, {
  1101. configurable: false,
  1102. get() {
  1103. if (onget) return onget(obj[`_${varname}`])
  1104. return obj[`_${varname}`]
  1105. },
  1106. set(value) {
  1107. if (value === obj[`_${varname}`]) {
  1108. return
  1109. }
  1110. var s = onset(value, obj[`_${varname}`])
  1111. if (s) obj[`_${varname}`] = value
  1112. },
  1113. })
  1114. },
  1115. function ({
  1116. ifunset,
  1117. end,
  1118. args: [varname, onset, onget, obj],
  1119. maketype,
  1120. }) {
  1121. ifunset([undefined, () => {}, () => {}, window]) // Default values
  1122. varname = maketype(varname, ["string"]) // Ensure varname is a string
  1123. onset = maketype(onset, ["function"]) // Ensure onset is a function
  1124. onget = maketype(onget, ["function", "undefined"]) // Ensure onget is a function or undefined
  1125. obj = maketype(obj, ["object", "undefined"]) // Ensure obj is an object or undefined
  1126. return end()
  1127. }
  1128. )
  1129.  
  1130. a.randomizeorder = newfunc(
  1131. function randomizeorder(arr) {
  1132. arr = [...arr]
  1133. var arr2 = []
  1134. var count = arr.length
  1135. for (var i = 0; i < count; i++) {
  1136. var idx = a.randfrom(0, arr.length - 1)
  1137. arr2.push(arr[idx])
  1138. arr.splice(idx, 1)
  1139. }
  1140. return arr2
  1141. },
  1142. function ({ end, args: [arr], maketype }) {
  1143. arr = maketype(arr, ["array"]) // Ensure arr is an array
  1144. return end()
  1145. }
  1146. )
  1147.  
  1148. a.constrainvar = newfunc(
  1149. function constrainvar(varname, min, max) {
  1150. window[`_${varname}`] = undefined
  1151. window[`${varname}`] = undefined
  1152. Object.defineProperty(window, varname, {
  1153. configurable: false,
  1154. get() {
  1155. return window[`_${varname}`]
  1156. },
  1157. set(value) {
  1158. if (value === window[`_${varname}`]) {
  1159. return
  1160. }
  1161. if (value > max) value = max
  1162. if (value < min) value = min
  1163. window[`_${varname}`] = value
  1164. },
  1165. })
  1166. },
  1167. function ({ ifunset, end, args: [varname, min, max], maketype }) {
  1168. ifunset([undefined, -Infinity, Infinity]) // Default values for min and max
  1169. varname = maketype(varname, ["string"]) // Ensure varname is a string
  1170. min = maketype(min, ["number"]) // Ensure min is a number
  1171. max = maketype(max, ["number"]) // Ensure max is a number
  1172. return end()
  1173. }
  1174. )
  1175.  
  1176. a.isbetween = newfunc(
  1177. function isbetween(z, x, c) {
  1178. if (x == c) return false
  1179. var big, small
  1180. if (x > c) {
  1181. big = x
  1182. small = c
  1183. } else {
  1184. big = c
  1185. small = x
  1186. }
  1187. return z > big && z < small
  1188. },
  1189. function ({ args: [z, x, c], end, maketype }) {
  1190. z = maketype(z, ["number"])
  1191. x = maketype(x, ["number"])
  1192. c = maketype(c, ["number"])
  1193. return end()
  1194. }
  1195. )
  1196.  
  1197. a.indexsof = newfunc(
  1198. function indexsof(y, x) {
  1199. var i = 0
  1200. var arr = []
  1201. y.split(x).forEach((e, k) => {
  1202. i += e.length
  1203. arr.push(i + k)
  1204. })
  1205. arr.pop()
  1206. return arr
  1207. },
  1208. function ({ args: [y, x], end, maketype }) {
  1209. y = maketype(y, ["string"]) // Ensure y is a string
  1210. x = maketype(x, ["string"]) // Ensure x is a string
  1211. return end()
  1212. }
  1213. )
  1214.  
  1215. a._export = newfunc(
  1216. function _export() {
  1217. var s = []
  1218. a.qsa("input, textarea").foreach((e) => {
  1219. s.push({
  1220. path: a.csspath(e),
  1221. value: escape(e.value),
  1222. checked: e.checked,
  1223. })
  1224. })
  1225. return JSON.stringify(s)
  1226. },
  1227. function ({ end }) {
  1228. return end()
  1229. }
  1230. )
  1231.  
  1232. a._import = newfunc(
  1233. function _import(data) {
  1234. data.forEach((e) => {
  1235. var s = a.qs(e.path)
  1236. s.checked = e.checked
  1237. s.value = unescape(e.value)
  1238. })
  1239. return data
  1240. },
  1241. function ({ end, args: [data], maketype }) {
  1242. data = maketype(data, ["array"])
  1243. return end()
  1244. }
  1245. )
  1246.  
  1247. a.popup = newfunc(
  1248. function popup(data, x, y, w, h) {
  1249. if (x || x === 0) {
  1250. x = (screen.width / 100) * x
  1251. y = (screen.height / 100) * y
  1252. w = (screen.width / 100) * w
  1253. h = (screen.height / 100) * h
  1254. var win = open(
  1255. "",
  1256. "",
  1257. `left=${x}, top=${y} width=${w},height=${h}`
  1258. )
  1259. win.document.write(data)
  1260. return win
  1261. } else {
  1262. var win = open("")
  1263. win.document.write(data)
  1264. return win
  1265. }
  1266. },
  1267. function ({ end, maketype, args: [data, x, y, w, h] }) {
  1268. data = maketype(data, ["string"])
  1269. x = maketype(x, ["number"])
  1270. y = maketype(y, ["number"])
  1271. w = maketype(w, ["number"])
  1272. h = maketype(h, ["number"])
  1273. return end()
  1274. }
  1275. )
  1276.  
  1277. a.same = newfunc(
  1278. function same(...a) {
  1279. if (a.length == 1) a = a[0]
  1280. return (
  1281. [...new Set(a.map((e) => JSON.stringify(e)))].length === 1
  1282. )
  1283. },
  1284. function ({ end }) {
  1285. return end()
  1286. }
  1287. )
  1288.  
  1289. a.containsany = newfunc(
  1290. function containsany(arr1, arr2) {
  1291. return !!arr2.find((e) => arr1.includes(e))
  1292. },
  1293. function ({ end, args: [arr1, arr2], maketype }) {
  1294. arr1 = maketype(arr1, ["string", "array"])
  1295. arr2 = maketype(arr2, ["string", "array"])
  1296. return end()
  1297. }
  1298. )
  1299.  
  1300. a.getprops = newfunc(
  1301. function getprops(func, peramsonly) {
  1302. return peramsonly
  1303. ? getprops(func)
  1304. .vars.map((e) => e.var)
  1305. .filter((e) => e)
  1306. : getprops(func)
  1307. },
  1308. function ({ end, args: [func, peramsonly], maketype }) {
  1309. func = maketype(func, ["function"]) // Ensure func is a function
  1310. peramsonly = maketype(peramsonly, ["boolean", "undefined"]) // Ensure peramsonly is a boolean or undefined
  1311. return end()
  1312. }
  1313. )
  1314.  
  1315. a.bodyload = newfunc(
  1316. function bodyload() {
  1317. return new Promise((resolve) => {
  1318. if (document.body) resolve()
  1319. var observer = new MutationObserver(function () {
  1320. if (document.body) {
  1321. resolve()
  1322. observer.disconnect()
  1323. }
  1324. })
  1325. observer.observe(document.documentElement, {
  1326. childList: true,
  1327. })
  1328. })
  1329. },
  1330. function ({ end }) {
  1331. return end()
  1332. }
  1333. )
  1334.  
  1335. a.repeat = newfunc(
  1336. function repeat(func, count, delay, instantstart, waituntildone) {
  1337. if (delay || waituntildone)
  1338. return new Promise(async (resolve) => {
  1339. if (delay) {
  1340. var extra = 0
  1341. for (var i = 0; i < count; i++) {
  1342. if (instantstart)
  1343. waituntildone ? await func(i) : func(i)
  1344. extra = await a.wait(delay - extra)
  1345. if (!instantstart)
  1346. waituntildone ? await func(i) : func(i)
  1347. }
  1348. resolve()
  1349. } else
  1350. for (var i = 0; i < count; i++)
  1351. waituntildone ? await func(i) : func(i)
  1352. resolve()
  1353. })
  1354. for (var i = 0; i < count; i++) func(i)
  1355. return
  1356. },
  1357. function ({
  1358. end,
  1359. args: [func, count, delay, instantstart, waituntildone],
  1360. maketype,
  1361. }) {
  1362. func = maketype(func, ["function"]) // Ensure func is a function
  1363. count = maketype(count, ["number"]) // Ensure count is a number
  1364. delay = maketype(delay, ["number", "undefined"]) // Ensure delay is a number or undefined
  1365. instantstart = maketype(instantstart, ["boolean", "undefined"]) // Ensure instantstart is a boolean or undefined
  1366. waituntildone = maketype(waituntildone, [
  1367. "boolean",
  1368. "undefined",
  1369. ]) // Ensure waituntildone is a boolean or undefined
  1370. return end()
  1371. }
  1372. )
  1373.  
  1374. a.repeatuntil = newfunc(
  1375. function repeatuntil(
  1376. func,
  1377. donecheck,
  1378. delay,
  1379. instantstart,
  1380. waituntildone
  1381. ) {
  1382. return new Promise(async (resolve) => {
  1383. if (delay) {
  1384. var extra = 0
  1385. var i = 0
  1386. while (!donecheck()) {
  1387. i++
  1388. if (instantstart) {
  1389. waituntildone ? await func(i) : func(i)
  1390. }
  1391. extra = await a.wait(delay - extra)
  1392. if (!instantstart) {
  1393. waituntildone ? await func(i) : func(i)
  1394. }
  1395. }
  1396. resolve()
  1397. } else {
  1398. var i = 0
  1399. while (!donecheck()) {
  1400. i++
  1401. waituntildone ? await func(i) : func(i)
  1402. }
  1403. resolve()
  1404. }
  1405. })
  1406. },
  1407. function ({
  1408. end,
  1409. args: [func, donecheck, delay, instantstart, waituntildone],
  1410. maketype,
  1411. }) {
  1412. func = maketype(func, ["function"]) // Ensure func is a function
  1413. donecheck = maketype(donecheck, ["function"]) // Ensure donecheck is a function
  1414. delay = maketype(delay, ["number", "undefined"]) // Ensure delay is a number or undefined
  1415. instantstart = maketype(instantstart, ["boolean", "undefined"]) // Ensure instantstart is a boolean or undefined
  1416. waituntildone = maketype(waituntildone, [
  1417. "boolean",
  1418. "undefined",
  1419. ]) // Ensure waituntildone is a boolean or undefined
  1420. return end()
  1421. }
  1422. )
  1423.  
  1424. a.getfolderpath = newfunc(
  1425. async function getfolderpath(folder) {
  1426. async function parsedir(dir, x) {
  1427. if (!x) {
  1428. return [
  1429. {
  1430. name: dir.name,
  1431. inside: await parsedir(dir, true),
  1432. type: "folder",
  1433. handle: dir,
  1434. },
  1435. ]
  1436. } else var arr = []
  1437. for await (const [name, handle] of dir.entries()) {
  1438. arr.push(
  1439. a.gettype(handle, "filesystemdirectoryhandle")
  1440. ? {
  1441. type: "folder",
  1442. inside: await parsedir(handle, true),
  1443. name,
  1444. handle,
  1445. }
  1446. : { type: "file", handle, name }
  1447. )
  1448. }
  1449. return arr
  1450. }
  1451. return parsedir(folder)
  1452. },
  1453. function ({ end, args: [folder], maketype }) {
  1454. folder = maketype(folder, ["filesystemdirectoryhandle"])
  1455. return end()
  1456. }
  1457. )
  1458.  
  1459. a.getfiles = newfunc(
  1460. async function getfiles(
  1461. oldway,
  1462. multiple,
  1463. accept = [],
  1464. options = {}
  1465. ) {
  1466. const supportsFileSystemAccess =
  1467. "showOpenFilePicker" in window &&
  1468. (() => {
  1469. try {
  1470. return window.self === window.top
  1471. } catch {
  1472. return false
  1473. }
  1474. })()
  1475. if (!oldway) {
  1476. if (!supportsFileSystemAccess) throw new Error("no access")
  1477. let fileOrFiles = undefined
  1478. try {
  1479. const handles = await showOpenFilePicker({
  1480. types: [
  1481. {
  1482. accept: {
  1483. "*/*": accept,
  1484. },
  1485. },
  1486. ],
  1487. multiple,
  1488. ...options,
  1489. })
  1490. if (!multiple) {
  1491. fileOrFiles = handles[0]
  1492. } else {
  1493. fileOrFiles = await Promise.all(handles)
  1494. }
  1495. } catch (err) {
  1496. if (err.name !== "AbortError") {
  1497. error(err.name, err.message)
  1498. }
  1499. }
  1500. return fileOrFiles
  1501. }
  1502. return new Promise(async (resolve) => {
  1503. await a.bodyload()
  1504. const input = document.createElement("input")
  1505. input.style.display = "none"
  1506. input.type = "file"
  1507. if (accept) input.accept = accept
  1508. document.body.append(input)
  1509. if (multiple) {
  1510. input.multiple = true
  1511. }
  1512. input.addEventListener("change", () => {
  1513. input.remove()
  1514. resolve(multiple ? Array.from(input.files) : input.files[0])
  1515. })
  1516. if ("showPicker" in HTMLInputElement.prototype) {
  1517. input.showPicker()
  1518. } else {
  1519. input.click()
  1520. }
  1521. })
  1522. },
  1523. function ({
  1524. end,
  1525. args: [oldway, multiple, accept, options],
  1526. maketype,
  1527. ifunset,
  1528. }) {
  1529. ifunset(undefined, undefined, [], {})
  1530. oldway = maketype(oldway, ["boolean"]) // Ensure oldway is a boolean
  1531. multiple = maketype(multiple, ["boolean"]) // Ensure multiple is a boolean
  1532. accept = maketype(accept, ["array", "string", "undefined"]) // Ensure accept is an array or string
  1533. options = maketype(options, ["object", "undefined"])
  1534. return end()
  1535. }
  1536. )
  1537. a.getfolder = newfunc(
  1538. async function getfolder(write = false, options = {}) {
  1539. const supportsFileSystemAccess =
  1540. "showDirectoryPicker" in window &&
  1541. (() => {
  1542. try {
  1543. return window.self === window.top
  1544. } catch {
  1545. return false
  1546. }
  1547. })()
  1548. if (!supportsFileSystemAccess) throw new Error("no access")
  1549. try {
  1550. return await showDirectoryPicker({
  1551. mode: write ? "readwrite" : "read",
  1552. ...options,
  1553. })
  1554. } catch (err) {
  1555. if (err.name !== "AbortError") {
  1556. error(err.name, err.message)
  1557. }
  1558. }
  1559. return undefined
  1560. },
  1561. function ({ end, args: [write, options], maketype, ifunset }) {
  1562. ifunset(false, {})
  1563. write = maketype(write, ["boolean", "undefined"])
  1564. options = maketype(options, ["object", "undefined"])
  1565. return end()
  1566. }
  1567. )
  1568.  
  1569. a.map = newfunc(
  1570. function map(arr, func) {
  1571. var type = a.gettype(arr)
  1572. if (type == "array") return arr.map(func)
  1573. else if (type == "object") {
  1574. var temparr = {}
  1575. Reflect.ownKeys(arr).forEach((e, i) => {
  1576. temparr = {
  1577. ...temparr,
  1578. ...func(e, arr[e], i),
  1579. }
  1580. })
  1581. return temparr
  1582. } else {
  1583. return [arr].map(func)
  1584. }
  1585. },
  1586. function ({ end, args: [arr, func], maketype }) {
  1587. arr = maketype(arr, ["array", "object"]) // Ensure arr is an array or object
  1588. func = maketype(func, ["function"]) // Ensure func is a function
  1589. return end()
  1590. }
  1591. )
  1592.  
  1593. a.find = newfunc(
  1594. function find(arr, func) {
  1595. var type = a.gettype(arr)
  1596. if (type == "array") return arr.find(func)
  1597. else if (type == "object") {
  1598. return Reflect.ownKeys(arr).find((e, i) => {
  1599. return func(e, arr[e], i)
  1600. })
  1601. } else {
  1602. return [arr].find(func)
  1603. }
  1604. },
  1605. function ({ end, args: [arr, func], maketype }) {
  1606. arr = maketype(arr, ["array", "object"]) // Ensure arr is an array or object
  1607. func = maketype(func, ["function"]) // Ensure func is a function
  1608. return end()
  1609. }
  1610. )
  1611.  
  1612. a.filteridx = newfunc(
  1613. function filteridx(arr, func) {
  1614. if (a.gettype(arr, "object")) arr = [arr]
  1615. return a
  1616. .map(arr, (e, i) => (func(e, i) ? i : undefined))
  1617. .filter((e) => e !== undefined)
  1618. },
  1619. function ({ end, args: [arr, func], maketype }) {
  1620. arr = maketype(arr, ["array", "object"]) // Ensure arr is an array or object
  1621. func = maketype(func, ["function"]) // Ensure func is a function
  1622. return end()
  1623. }
  1624. )
  1625.  
  1626. a.filter = newfunc(
  1627. function filter(arr, func) {
  1628. var type = a.gettype(arr)
  1629. if (type == "array") return arr.filter(func)
  1630. else if (type == "object") {
  1631. var temparr = {}
  1632. Reflect.ownKeys(arr).forEach((e, i) => {
  1633. if (func(e, arr[e], i))
  1634. temparr = {
  1635. ...temparr,
  1636. [e]: arr[e],
  1637. }
  1638. })
  1639. return temparr
  1640. } else {
  1641. return [arr].filter(func)
  1642. }
  1643. },
  1644. function ({ end, args: [arr, func], maketype }) {
  1645. arr = maketype(arr, ["array", "object"]) // Ensure arr is an array or object
  1646. func = maketype(func, ["function"]) // Ensure func is a function
  1647. return end()
  1648. }
  1649. )
  1650.  
  1651. a.unique = newfunc(
  1652. function unique() /*object*/ {
  1653. return last || (last = different.new())
  1654. },
  1655. function ({ end }) {
  1656. return end()
  1657. }
  1658. )
  1659.  
  1660. a.tostring = newfunc(
  1661. function tostring(e) {
  1662. if (["object", "array"].includes(a.gettype(e)))
  1663. return JSON.stringify(e)
  1664. if (a.gettype(e, "element")) return a.csspath(e)
  1665. return String(e)
  1666. },
  1667. function ({ end, args: [e], maketype }) {
  1668. e = maketype(e, ["any"]) // Ensure e can be any type
  1669. return end()
  1670. }
  1671. )
  1672.  
  1673. a.toregex = newfunc(
  1674. function toregex(d, s) {
  1675. if (a.gettype(d, "array")) var temp = d
  1676. if (s) var temp = [d, s]
  1677. else if (String(d).match(/^\/(.*)\/(\w*)$/)) {
  1678. var m = String(d).match(/^\/(.*)\/(\w*)$/)
  1679. var temp = [m[1], m[2]]
  1680. } else var temp = [String(d), ""]
  1681. temp[1] = temp[1].toLowerCase()
  1682. if (temp[1].includes("w")) {
  1683. temp[1] = temp[1].replace("w", "")
  1684. temp[0] = `(?<=[^a-z0-9]|^)${temp[0]}(?=[^a-z0-9]|$)`
  1685. }
  1686. return new RegExp(
  1687. temp[0],
  1688. temp[1].replaceAll(/(.)(?=.*\1)/g, "")
  1689. )
  1690. },
  1691. function ({ end, args: [d, s], maketype }) {
  1692. d = maketype(d, ["string", "array"]) // Ensure d is a string or array
  1693. s = maketype(s, ["string", "undefined"]) // Ensure s is a string or undefined
  1694. return end()
  1695. }
  1696. )
  1697.  
  1698. a.isregex = newfunc(
  1699. function isregex(s) {
  1700. if (a.gettype(s, "regex")) return true
  1701. return (
  1702. /^\/.*(?<!\\)\/[gimusy]*$/.test(s) && !/^\/\*.*\*\/$/.test(s)
  1703. )
  1704. },
  1705. function ({ end, args: [s], maketype }) {
  1706. s = maketype(s, ["string"]) // Ensure s is a string
  1707. return end()
  1708. }
  1709. )
  1710.  
  1711. a.ispressed = newfunc(
  1712. function ispressed(e /*event*/, code) {
  1713. code = code.toLowerCase()
  1714. var temp =
  1715. e.shiftKey == code.includes("shift") &&
  1716. e.altKey == code.includes("alt") &&
  1717. e.ctrlKey == code.includes("ctrl") &&
  1718. e.metaKey == code.includes("meta") &&
  1719. e.key.toLowerCase() ==
  1720. code.replaceAll(/alt|ctrl|shift|meta/g, "").trim()
  1721. if (temp && !a) e.preventDefault()
  1722. return temp
  1723. },
  1724. function ({ end, args: [e, code], maketype }) {
  1725. e = maketype(e, ["object"]) // Ensure e is an event object
  1726. code = maketype(code, ["string"]) // Ensure code is a string
  1727. return end()
  1728. }
  1729. )
  1730.  
  1731. a.controller_vibrate = newfunc(
  1732. function controller_vibrate(
  1733. pad,
  1734. duration = 1000,
  1735. strongMagnitude = 0,
  1736. weakMagnitude = 0
  1737. ) {
  1738. getpad(pad).vibrationActuator.playEffect("dual-rumble", {
  1739. duration,
  1740. strongMagnitude,
  1741. weakMagnitude,
  1742. })
  1743. return pad
  1744. },
  1745. function ({
  1746. end,
  1747. args: [pad, duration, strongMagnitude, weakMagnitude],
  1748. maketype,
  1749. }) {
  1750. pad = maketype(pad, ["element"]) // Ensure pad is a valid element
  1751. duration = maketype(duration, ["number"]) // Ensure duration is a number
  1752. strongMagnitude = maketype(strongMagnitude, ["number"]) // Ensure strongMagnitude is a number
  1753. weakMagnitude = maketype(weakMagnitude, ["number"]) // Ensure weakMagnitude is a number
  1754. return end()
  1755. }
  1756. )
  1757.  
  1758. a.controller_getbutton = newfunc(
  1759. function controller_getbutton(pad, button) {
  1760. return button
  1761. ? getpad(pad).buttons[button].value
  1762. : getpad(pad).buttons.map((e) => e.value)
  1763. },
  1764. function ({ end, args: [pad, button], maketype }) {
  1765. pad = maketype(pad, ["element"]) // Ensure pad is a valid element
  1766. button = maketype(button, ["number", "undefined"]) // Ensure button is a number or undefined
  1767. return end()
  1768. }
  1769. )
  1770.  
  1771. a.controller_getaxes = newfunc(
  1772. function controller_getaxes(pad, axes) {
  1773. return axes ? getpad(pad).axes[axes] : getpad(pad).axes
  1774. },
  1775. function ({ end, args: [pad, axes], maketype }) {
  1776. pad = maketype(pad, ["element"]) // Ensure pad is a valid element
  1777. axes = maketype(axes, ["number", "undefined"]) // Ensure axes is a number or undefined
  1778. return end()
  1779. }
  1780. )
  1781.  
  1782. a.controller_exists = newfunc(
  1783. function controller_exists(pad) {
  1784. return pad === undefined
  1785. ? getpad().filter((e) => e).length
  1786. : !!getpad(pad)
  1787. },
  1788. function ({ end, args: [pad], maketype }) {
  1789. pad = maketype(pad, ["element", "undefined"]) // Ensure pad is a valid element or undefined
  1790. return end()
  1791. }
  1792. )
  1793.  
  1794. a.readfile = newfunc(
  1795. async function readfile(file, type = "Text") {
  1796. return new Promise(function (done, error) {
  1797. var f = new FileReader()
  1798. f.onerror = error
  1799. f.onload = () =>
  1800. done(type == "json" ? JSON.parse(f.result) : f.result)
  1801. f["readAs" + (type == "json" ? "Text" : type)](file)
  1802. })
  1803. },
  1804. function ({ end, args: [file, type], maketype, ifunset }) {
  1805. ifunset(undefined, "Text")
  1806. type = maketype(type, ["string", "undefined"]) // Ensure type is a string
  1807. return end()
  1808. }
  1809. )
  1810.  
  1811. a.writefile = newfunc(
  1812. async function writefile(file, text) {
  1813. var f = await file.createWritable()
  1814. await f.write(text)
  1815. await f.close()
  1816. return file
  1817. },
  1818. function ({ end, args: [file, text], maketype }) {
  1819. text = maketype(text, ["string"]) // Ensure text is a string
  1820. return end()
  1821. }
  1822. )
  1823.  
  1824. a.getfileperms = newfunc(
  1825. async function getfileperms(fileHandle, readWrite) {
  1826. const options = {}
  1827. if (readWrite) {
  1828. options.mode = "readwrite"
  1829. }
  1830. try {
  1831. return (
  1832. (await fileHandle.queryPermission(options)) === "granted" ||
  1833. (await fileHandle.requestPermission(options)) === "granted"
  1834. )
  1835. } catch (e) {
  1836. await a.waitforclick()
  1837. return (
  1838. (await fileHandle.queryPermission(options)) === "granted" ||
  1839. (await fileHandle.requestPermission(options)) === "granted"
  1840. )
  1841. }
  1842. },
  1843. function ({ end, args: [fileHandle, readWrite], maketype }) {
  1844. readWrite = maketype(readWrite, ["boolean", "undefined"]) // Ensure readWrite is a boolean or undefined
  1845. return end()
  1846. }
  1847. )
  1848. a.waitforclick = newfunc(
  1849. async function waitforclick(fileHandle, readWrite) {
  1850. return new Promise((resolve) => {
  1851. var listener = a.listen(
  1852. window,
  1853. "click",
  1854. () => {
  1855. a.unlisten(listener)
  1856. resolve()
  1857. },
  1858. true
  1859. )
  1860. })
  1861. },
  1862. function ({ end, args: [] }) {
  1863. return end()
  1864. }
  1865. )
  1866.  
  1867. a.indexeddb_set = newfunc(
  1868. async function indexeddb_set(place, obj) {
  1869. return new Promise((done, error) =>
  1870. place.put(
  1871. obj,
  1872. (e) => done(e),
  1873. (e) => error(e)
  1874. )
  1875. )
  1876. },
  1877. function ({ end, args: [place, obj], maketype }) {
  1878. place = maketype(place, ["object"]) // Ensure place is an object
  1879. obj = maketype(obj, ["object"]) // Ensure obj is an object
  1880. return end()
  1881. }
  1882. )
  1883.  
  1884. a.indexeddb_get = newfunc(
  1885. async function indexeddb_get(place, obj) {
  1886. return new Promise((done, error) =>
  1887. place.get(
  1888. obj,
  1889. (e) => done(e),
  1890. (e) => error(e)
  1891. )
  1892. )
  1893. },
  1894. function ({ end, args: [place, obj], maketype }) {
  1895. place = maketype(place, ["object"]) // Ensure place is an object
  1896. obj = maketype(obj, ["string"]) // Ensure obj is a string
  1897. return end()
  1898. }
  1899. )
  1900.  
  1901. a.indexeddb_getall = newfunc(
  1902. async function indexeddb_getall(place) {
  1903. return new Promise((done, error) =>
  1904. place.getAll(
  1905. (e) => done(e),
  1906. (e) => error(e)
  1907. )
  1908. )
  1909. },
  1910. function ({ end, args: [place], maketype }) {
  1911. place = maketype(place, ["object"]) // Ensure place is an object
  1912. return end()
  1913. }
  1914. )
  1915.  
  1916. a.indexeddb_clearall = newfunc(
  1917. async function indexeddb_clearall(place) {
  1918. return new Promise((done, error) =>
  1919. place.clear(
  1920. (e) => done(e),
  1921. (e) => error(e)
  1922. )
  1923. )
  1924. },
  1925. function ({ end, args: [place], maketype }) {
  1926. place = maketype(place, ["object"]) // Ensure place is an object
  1927. return end()
  1928. }
  1929. )
  1930.  
  1931. a.indexeddb_remove = newfunc(
  1932. async function indexeddb_remove(place, obj) {
  1933. return new Promise((done, error) =>
  1934. place.remove(
  1935. obj,
  1936. (e) => done(e),
  1937. (e) => error(e)
  1938. )
  1939. )
  1940. },
  1941. function ({ end, args: [place, obj], maketype }) {
  1942. place = maketype(place, ["object"]) // Ensure place is an object
  1943. obj = maketype(obj, ["string"]) // Ensure obj is a string
  1944. return end()
  1945. }
  1946. )
  1947.  
  1948. a.indexeddb_setup = newfunc(
  1949. async function indexeddb_setup(obj) {
  1950. return new Promise((e) => {
  1951. var x
  1952. obj = {
  1953. dbVersion: 1,
  1954. storeName: "tempstorename",
  1955. keyPath: "id",
  1956. autoIncrement: true,
  1957. ...obj,
  1958. onStoreReady() {
  1959. e(x)
  1960. },
  1961. }
  1962. if (!window.IDBStore) {
  1963. ;(function (p, h, k) {
  1964. "function" === typeof define
  1965. ? define(h)
  1966. : "undefined" !== typeof module && module.exports
  1967. ? (module.exports = h())
  1968. : (k[p] = h())
  1969. })(
  1970. "IDBStore",
  1971. function () {
  1972. function p(a, b) {
  1973. var c, d
  1974. for (c in b)
  1975. (d = b[c]), d !== u[c] && d !== a[c] && (a[c] = d)
  1976. return a
  1977. }
  1978. var h = function (a) {
  1979. throw a
  1980. },
  1981. k = function () {},
  1982. r = {
  1983. storeName: "Store",
  1984. storePrefix: "IDBWrapper-",
  1985. dbVersion: 1,
  1986. keyPath: "id",
  1987. autoIncrement: !0,
  1988. onStoreReady: function () {},
  1989. onError: h,
  1990. indexes: [],
  1991. implementationPreference: [
  1992. "indexedDB",
  1993. "webkitIndexedDB",
  1994. "mozIndexedDB",
  1995. "shimIndexedDB",
  1996. ],
  1997. },
  1998. q = function (a, b) {
  1999. "undefined" == typeof b &&
  2000. "function" == typeof a &&
  2001. (b = a)
  2002. "[object Object]" !=
  2003. Object.prototype.toString.call(a) && (a = {})
  2004. for (var c in r)
  2005. this[c] = "undefined" != typeof a[c] ? a[c] : r[c]
  2006. this.dbName = this.storePrefix + this.storeName
  2007. this.dbVersion = parseInt(this.dbVersion, 10) || 1
  2008. b && (this.onStoreReady = b)
  2009. var d = "object" == typeof window ? window : self
  2010. this.implementation =
  2011. this.implementationPreference.filter(function (
  2012. a
  2013. ) {
  2014. return a in d
  2015. })[0]
  2016. this.idb = d[this.implementation]
  2017. this.keyRange =
  2018. d.IDBKeyRange ||
  2019. d.webkitIDBKeyRange ||
  2020. d.mozIDBKeyRange
  2021. this.consts = {
  2022. READ_ONLY: "readonly",
  2023. READ_WRITE: "readwrite",
  2024. VERSION_CHANGE: "versionchange",
  2025. NEXT: "next",
  2026. NEXT_NO_DUPLICATE: "nextunique",
  2027. PREV: "prev",
  2028. PREV_NO_DUPLICATE: "prevunique",
  2029. }
  2030. this.openDB()
  2031. },
  2032. t = {
  2033. constructor: q,
  2034. version: "1.7.2",
  2035. db: null,
  2036. dbName: null,
  2037. dbVersion: null,
  2038. store: null,
  2039. storeName: null,
  2040. storePrefix: null,
  2041. keyPath: null,
  2042. autoIncrement: null,
  2043. indexes: null,
  2044. implementationPreference: null,
  2045. implementation: "",
  2046. onStoreReady: null,
  2047. onError: null,
  2048. _insertIdCount: 0,
  2049. openDB: function () {
  2050. var a = this.idb.open(
  2051. this.dbName,
  2052. this.dbVersion
  2053. ),
  2054. b = !1
  2055. a.onerror = function (a) {
  2056. var b
  2057. b =
  2058. "error" in a.target
  2059. ? "VersionError" == a.target.error.name
  2060. : "errorCode" in a.target
  2061. ? 12 == a.target.errorCode
  2062. : !1
  2063. if (b)
  2064. this.onError(
  2065. Error(
  2066. "The version number provided is lower than the existing one."
  2067. )
  2068. )
  2069. else
  2070. a.target.error
  2071. ? (a = a.target.error)
  2072. : ((b =
  2073. "IndexedDB unknown error occurred when opening DB " +
  2074. this.dbName +
  2075. " version " +
  2076. this.dbVersion),
  2077. "errorCode" in a.target &&
  2078. (b +=
  2079. " with error code " +
  2080. a.target.errorCode),
  2081. (a = Error(b))),
  2082. this.onError(a)
  2083. }.bind(this)
  2084. a.onsuccess = function (a) {
  2085. if (!b)
  2086. if (this.db) this.onStoreReady()
  2087. else if (
  2088. ((this.db = a.target.result),
  2089. "string" == typeof this.db.version)
  2090. )
  2091. this.onError(
  2092. Error(
  2093. "The IndexedDB implementation in this browser is outdated. Please upgrade your browser."
  2094. )
  2095. )
  2096. else if (
  2097. this.db.objectStoreNames.contains(
  2098. this.storeName
  2099. )
  2100. ) {
  2101. this.store = this.db
  2102. .transaction(
  2103. [this.storeName],
  2104. this.consts.READ_ONLY
  2105. )
  2106. .objectStore(this.storeName)
  2107. var d = Array.prototype.slice.call(
  2108. this.getIndexList()
  2109. )
  2110. this.indexes.forEach(function (a) {
  2111. var c = a.name
  2112. if (c)
  2113. if (
  2114. (this.normalizeIndexData(a),
  2115. this.hasIndex(c))
  2116. ) {
  2117. var g = this.store.index(c)
  2118. this.indexComplies(g, a) ||
  2119. ((b = !0),
  2120. this.onError(
  2121. Error(
  2122. 'Cannot modify index "' +
  2123. c +
  2124. '" for current version. Please bump version number to ' +
  2125. (this.dbVersion + 1) +
  2126. "."
  2127. )
  2128. ))
  2129. d.splice(d.indexOf(c), 1)
  2130. } else
  2131. (b = !0),
  2132. this.onError(
  2133. Error(
  2134. 'Cannot create new index "' +
  2135. c +
  2136. '" for current version. Please bump version number to ' +
  2137. (this.dbVersion + 1) +
  2138. "."
  2139. )
  2140. )
  2141. else
  2142. (b = !0),
  2143. this.onError(
  2144. Error(
  2145. "Cannot create index: No index name given."
  2146. )
  2147. )
  2148. }, this)
  2149. d.length &&
  2150. ((b = !0),
  2151. this.onError(
  2152. Error(
  2153. 'Cannot delete index(es) "' +
  2154. d.toString() +
  2155. '" for current version. Please bump version number to ' +
  2156. (this.dbVersion + 1) +
  2157. "."
  2158. )
  2159. ))
  2160. b || this.onStoreReady()
  2161. } else
  2162. this.onError(
  2163. Error("Object store couldn't be created.")
  2164. )
  2165. }.bind(this)
  2166. a.onupgradeneeded = function (a) {
  2167. this.db = a.target.result
  2168. this.db.objectStoreNames.contains(
  2169. this.storeName
  2170. )
  2171. ? (this.store =
  2172. a.target.transaction.objectStore(
  2173. this.storeName
  2174. ))
  2175. : ((a = {
  2176. autoIncrement: this.autoIncrement,
  2177. }),
  2178. null !== this.keyPath &&
  2179. (a.keyPath = this.keyPath),
  2180. (this.store = this.db.createObjectStore(
  2181. this.storeName,
  2182. a
  2183. )))
  2184. var d = Array.prototype.slice.call(
  2185. this.getIndexList()
  2186. )
  2187. this.indexes.forEach(function (a) {
  2188. var c = a.name
  2189. c ||
  2190. ((b = !0),
  2191. this.onError(
  2192. Error(
  2193. "Cannot create index: No index name given."
  2194. )
  2195. ))
  2196. this.normalizeIndexData(a)
  2197. if (this.hasIndex(c)) {
  2198. var g = this.store.index(c)
  2199. this.indexComplies(g, a) ||
  2200. (this.store.deleteIndex(c),
  2201. this.store.createIndex(c, a.keyPath, {
  2202. unique: a.unique,
  2203. multiEntry: a.multiEntry,
  2204. }))
  2205. d.splice(d.indexOf(c), 1)
  2206. } else
  2207. this.store.createIndex(c, a.keyPath, {
  2208. unique: a.unique,
  2209. multiEntry: a.multiEntry,
  2210. })
  2211. }, this)
  2212. d.length &&
  2213. d.forEach(function (a) {
  2214. this.store.deleteIndex(a)
  2215. }, this)
  2216. }.bind(this)
  2217. },
  2218. deleteDatabase: function (a, b) {
  2219. if (this.idb.deleteDatabase) {
  2220. this.db.close()
  2221. var c = this.idb.deleteDatabase(this.dbName)
  2222. c.onsuccess = a
  2223. c.onerror = b
  2224. } else
  2225. b(
  2226. Error(
  2227. "Browser does not support IndexedDB deleteDatabase!"
  2228. )
  2229. )
  2230. },
  2231. put: function (a, b, c, d) {
  2232. null !== this.keyPath &&
  2233. ((d = c), (c = b), (b = a))
  2234. d || (d = h)
  2235. c || (c = k)
  2236. var f = !1,
  2237. e = null,
  2238. g = this.db.transaction(
  2239. [this.storeName],
  2240. this.consts.READ_WRITE
  2241. )
  2242. g.oncomplete = function () {
  2243. ;(f ? c : d)(e)
  2244. }
  2245. g.onabort = d
  2246. g.onerror = d
  2247. null !== this.keyPath
  2248. ? (this._addIdPropertyIfNeeded(b),
  2249. (a = g.objectStore(this.storeName).put(
  2250. (() => {
  2251. function isFilesystemHandle(obj) {
  2252. return (
  2253. obj &&
  2254. (obj instanceof
  2255. FileSystemFileHandle ||
  2256. obj instanceof
  2257. FileSystemDirectoryHandle)
  2258. )
  2259. }
  2260. function replaceProxies(obj) {
  2261. if (isFilesystemHandle(obj)) {
  2262. return obj
  2263. }
  2264. if (
  2265. typeof obj !== "object" ||
  2266. obj === null
  2267. ) {
  2268. return obj
  2269. }
  2270. if (Array.isArray(obj)) {
  2271. return obj.map((item) =>
  2272. replaceProxies(item)
  2273. )
  2274. }
  2275. const result = {}
  2276. for (const key in obj) {
  2277. if (obj.hasOwnProperty(key)) {
  2278. result[key] = replaceProxies(
  2279. obj[key]
  2280. )
  2281. }
  2282. }
  2283. return result
  2284. }
  2285. return replaceProxies(b)
  2286. })()
  2287. )))
  2288. : (a = g.objectStore(this.storeName).put(b, a))
  2289. a.onsuccess = function (a) {
  2290. f = !0
  2291. e = a.target.result
  2292. }
  2293. a.onerror = d
  2294. return g
  2295. },
  2296. get: function (a, b, c) {
  2297. c || (c = h)
  2298. b || (b = k)
  2299. var d = !1,
  2300. f = null,
  2301. e = this.db.transaction(
  2302. [this.storeName],
  2303. this.consts.READ_ONLY
  2304. )
  2305. e.oncomplete = function () {
  2306. ;(d ? b : c)(f)
  2307. }
  2308. e.onabort = c
  2309. e.onerror = c
  2310. a = e.objectStore(this.storeName).get(a)
  2311. a.onsuccess = function (a) {
  2312. d = !0
  2313. f = a.target.result
  2314. }
  2315. a.onerror = c
  2316. return e
  2317. },
  2318. remove: function (a, b, c) {
  2319. c || (c = h)
  2320. b || (b = k)
  2321. var d = !1,
  2322. f = null,
  2323. e = this.db.transaction(
  2324. [this.storeName],
  2325. this.consts.READ_WRITE
  2326. )
  2327. e.oncomplete = function () {
  2328. ;(d ? b : c)(f)
  2329. }
  2330. e.onabort = c
  2331. e.onerror = c
  2332. a = e.objectStore(this.storeName)["delete"](a)
  2333. a.onsuccess = function (a) {
  2334. d = !0
  2335. f = a.target.result
  2336. }
  2337. a.onerror = c
  2338. return e
  2339. },
  2340. batch: function (a, b, c) {
  2341. c || (c = h)
  2342. b || (b = k)
  2343. if (
  2344. "[object Array]" !=
  2345. Object.prototype.toString.call(a)
  2346. )
  2347. c(
  2348. Error(
  2349. "dataArray argument must be of type Array."
  2350. )
  2351. )
  2352. else if (0 === a.length) return b(!0)
  2353. var d = a.length,
  2354. f = !1,
  2355. e = !1,
  2356. g = this.db.transaction(
  2357. [this.storeName],
  2358. this.consts.READ_WRITE
  2359. )
  2360. g.oncomplete = function () {
  2361. ;(e ? b : c)(e)
  2362. }
  2363. g.onabort = c
  2364. g.onerror = c
  2365. var l = function () {
  2366. d--
  2367. 0 !== d || f || (e = f = !0)
  2368. }
  2369. a.forEach(function (a) {
  2370. var b = a.type,
  2371. d = a.key,
  2372. e = a.value
  2373. a = function (a) {
  2374. g.abort()
  2375. f || ((f = !0), c(a, b, d))
  2376. }
  2377. "remove" == b
  2378. ? ((e = g
  2379. .objectStore(this.storeName)
  2380. ["delete"](d)),
  2381. (e.onsuccess = l),
  2382. (e.onerror = a))
  2383. : "put" == b &&
  2384. (null !== this.keyPath
  2385. ? (this._addIdPropertyIfNeeded(e),
  2386. (e = g
  2387. .objectStore(this.storeName)
  2388. .put(e)))
  2389. : (e = g
  2390. .objectStore(this.storeName)
  2391. .put(e, d)),
  2392. (e.onsuccess = l),
  2393. (e.onerror = a))
  2394. }, this)
  2395. return g
  2396. },
  2397. putBatch: function (a, b, c) {
  2398. a = a.map(function (a) {
  2399. return { type: "put", value: a }
  2400. })
  2401. return this.batch(a, b, c)
  2402. },
  2403. upsertBatch: function (a, b, c, d) {
  2404. "function" == typeof b && ((d = c = b), (b = {}))
  2405. d || (d = h)
  2406. c || (c = k)
  2407. b || (b = {})
  2408. "[object Array]" !=
  2409. Object.prototype.toString.call(a) &&
  2410. d(
  2411. Error(
  2412. "dataArray argument must be of type Array."
  2413. )
  2414. )
  2415. var f = b.keyField || this.keyPath,
  2416. e = a.length,
  2417. g = !1,
  2418. l = !1,
  2419. n = 0,
  2420. m = this.db.transaction(
  2421. [this.storeName],
  2422. this.consts.READ_WRITE
  2423. )
  2424. m.oncomplete = function () {
  2425. l ? c(a) : d(!1)
  2426. }
  2427. m.onabort = d
  2428. m.onerror = d
  2429. var v = function (b) {
  2430. a[n++][f] = b.target.result
  2431. e--
  2432. 0 !== e || g || (l = g = !0)
  2433. }
  2434. a.forEach(function (a) {
  2435. var b = a.key
  2436. null !== this.keyPath
  2437. ? (this._addIdPropertyIfNeeded(a),
  2438. (a = m.objectStore(this.storeName).put(a)))
  2439. : (a = m
  2440. .objectStore(this.storeName)
  2441. .put(a, b))
  2442. a.onsuccess = v
  2443. a.onerror = function (a) {
  2444. m.abort()
  2445. g || ((g = !0), d(a))
  2446. }
  2447. }, this)
  2448. return m
  2449. },
  2450. removeBatch: function (a, b, c) {
  2451. a = a.map(function (a) {
  2452. return { type: "remove", key: a }
  2453. })
  2454. return this.batch(a, b, c)
  2455. },
  2456. getBatch: function (a, b, c, d) {
  2457. c || (c = h)
  2458. b || (b = k)
  2459. d || (d = "sparse")
  2460. if (
  2461. "[object Array]" !=
  2462. Object.prototype.toString.call(a)
  2463. )
  2464. c(
  2465. Error(
  2466. "keyArray argument must be of type Array."
  2467. )
  2468. )
  2469. else if (0 === a.length) return b([])
  2470. var f = [],
  2471. e = a.length,
  2472. g = !1,
  2473. l = null,
  2474. n = this.db.transaction(
  2475. [this.storeName],
  2476. this.consts.READ_ONLY
  2477. )
  2478. n.oncomplete = function () {
  2479. ;(g ? b : c)(l)
  2480. }
  2481. n.onabort = c
  2482. n.onerror = c
  2483. var m = function (a) {
  2484. a.target.result || "dense" == d
  2485. ? f.push(a.target.result)
  2486. : "sparse" == d && f.length++
  2487. e--
  2488. 0 === e && ((g = !0), (l = f))
  2489. }
  2490. a.forEach(function (a) {
  2491. a = n.objectStore(this.storeName).get(a)
  2492. a.onsuccess = m
  2493. a.onerror = function (a) {
  2494. l = a
  2495. c(a)
  2496. n.abort()
  2497. }
  2498. }, this)
  2499. return n
  2500. },
  2501. getAll: function (a, b) {
  2502. b || (b = h)
  2503. a || (a = k)
  2504. var c = this.db.transaction(
  2505. [this.storeName],
  2506. this.consts.READ_ONLY
  2507. ),
  2508. d = c.objectStore(this.storeName)
  2509. d.getAll
  2510. ? this._getAllNative(c, d, a, b)
  2511. : this._getAllCursor(c, d, a, b)
  2512. return c
  2513. },
  2514. _getAllNative: function (a, b, c, d) {
  2515. var f = !1,
  2516. e = null
  2517. a.oncomplete = function () {
  2518. ;(f ? c : d)(e)
  2519. }
  2520. a.onabort = d
  2521. a.onerror = d
  2522. a = b.getAll()
  2523. a.onsuccess = function (a) {
  2524. f = !0
  2525. e = a.target.result
  2526. }
  2527. a.onerror = d
  2528. },
  2529. _getAllCursor: function (a, b, c, d) {
  2530. var f = [],
  2531. e = !1,
  2532. g = null
  2533. a.oncomplete = function () {
  2534. ;(e ? c : d)(g)
  2535. }
  2536. a.onabort = d
  2537. a.onerror = d
  2538. a = b.openCursor()
  2539. a.onsuccess = function (a) {
  2540. ;(a = a.target.result)
  2541. ? (f.push(a.value), a["continue"]())
  2542. : ((e = !0), (g = f))
  2543. }
  2544. a.onError = d
  2545. },
  2546. clear: function (a, b) {
  2547. b || (b = h)
  2548. a || (a = k)
  2549. var c = !1,
  2550. d = null,
  2551. f = this.db.transaction(
  2552. [this.storeName],
  2553. this.consts.READ_WRITE
  2554. )
  2555. f.oncomplete = function () {
  2556. ;(c ? a : b)(d)
  2557. }
  2558. f.onabort = b
  2559. f.onerror = b
  2560. var e = f.objectStore(this.storeName).clear()
  2561. e.onsuccess = function (a) {
  2562. c = !0
  2563. d = a.target.result
  2564. }
  2565. e.onerror = b
  2566. return f
  2567. },
  2568. _addIdPropertyIfNeeded: function (a) {
  2569. "undefined" == typeof a[this.keyPath] &&
  2570. (a[this.keyPath] =
  2571. this._insertIdCount++ + Date.now())
  2572. },
  2573. getIndexList: function () {
  2574. return this.store.indexNames
  2575. },
  2576. hasIndex: function (a) {
  2577. return this.store.indexNames.contains(a)
  2578. },
  2579. normalizeIndexData: function (a) {
  2580. a.keyPath = a.keyPath || a.name
  2581. a.unique = !!a.unique
  2582. a.multiEntry = !!a.multiEntry
  2583. },
  2584. indexComplies: function (a, b) {
  2585. return ["keyPath", "unique", "multiEntry"].every(
  2586. function (c) {
  2587. if (
  2588. "multiEntry" == c &&
  2589. void 0 === a[c] &&
  2590. !1 === b[c]
  2591. )
  2592. return !0
  2593. if (
  2594. "keyPath" == c &&
  2595. "[object Array]" ==
  2596. Object.prototype.toString.call(b[c])
  2597. ) {
  2598. c = b.keyPath
  2599. var d = a.keyPath
  2600. if ("string" == typeof d)
  2601. return c.toString() == d
  2602. if (
  2603. ("function" != typeof d.contains &&
  2604. "function" != typeof d.indexOf) ||
  2605. d.length !== c.length
  2606. )
  2607. return !1
  2608. for (var f = 0, e = c.length; f < e; f++)
  2609. if (
  2610. !(
  2611. (d.contains && d.contains(c[f])) ||
  2612. d.indexOf(-1 !== c[f])
  2613. )
  2614. )
  2615. return !1
  2616. return !0
  2617. }
  2618. return b[c] == a[c]
  2619. }
  2620. )
  2621. },
  2622. iterate: function (a, b) {
  2623. b = p(
  2624. {
  2625. index: null,
  2626. order: "ASC",
  2627. autoContinue: !0,
  2628. filterDuplicates: !1,
  2629. keyRange: null,
  2630. writeAccess: !1,
  2631. onEnd: null,
  2632. onError: h,
  2633. limit: Infinity,
  2634. offset: 0,
  2635. allowItemRejection: !1,
  2636. },
  2637. b || {}
  2638. )
  2639. var c =
  2640. "desc" == b.order.toLowerCase()
  2641. ? "PREV"
  2642. : "NEXT"
  2643. b.filterDuplicates && (c += "_NO_DUPLICATE")
  2644. var d = !1,
  2645. f = this.db.transaction(
  2646. [this.storeName],
  2647. this.consts[
  2648. b.writeAccess ? "READ_WRITE" : "READ_ONLY"
  2649. ]
  2650. ),
  2651. e = f.objectStore(this.storeName)
  2652. b.index && (e = e.index(b.index))
  2653. var g = 0
  2654. f.oncomplete = function () {
  2655. if (d)
  2656. if (b.onEnd) b.onEnd()
  2657. else a(null)
  2658. else b.onError(null)
  2659. }
  2660. f.onabort = b.onError
  2661. f.onerror = b.onError
  2662. c = e.openCursor(b.keyRange, this.consts[c])
  2663. c.onerror = b.onError
  2664. c.onsuccess = function (c) {
  2665. if ((c = c.target.result))
  2666. if (b.offset)
  2667. c.advance(b.offset), (b.offset = 0)
  2668. else {
  2669. var e = a(c.value, c, f)
  2670. ;(b.allowItemRejection && !1 === e) || g++
  2671. if (b.autoContinue)
  2672. if (g + b.offset < b.limit)
  2673. c["continue"]()
  2674. else d = !0
  2675. }
  2676. else d = !0
  2677. }
  2678. return f
  2679. },
  2680. query: function (a, b) {
  2681. var c = [],
  2682. d = 0
  2683. b = b || {}
  2684. b.autoContinue = !0
  2685. b.writeAccess = !1
  2686. b.allowItemRejection = !!b.filter
  2687. b.onEnd = function () {
  2688. a(c, d)
  2689. }
  2690. return this.iterate(function (a) {
  2691. d++
  2692. var e = b.filter ? b.filter(a) : !0
  2693. !1 !== e && c.push(a)
  2694. return e
  2695. }, b)
  2696. },
  2697. count: function (a, b) {
  2698. b = p({ index: null, keyRange: null }, b || {})
  2699. var c = b.onError || h,
  2700. d = !1,
  2701. f = null,
  2702. e = this.db.transaction(
  2703. [this.storeName],
  2704. this.consts.READ_ONLY
  2705. )
  2706. e.oncomplete = function () {
  2707. ;(d ? a : c)(f)
  2708. }
  2709. e.onabort = c
  2710. e.onerror = c
  2711. var g = e.objectStore(this.storeName)
  2712. b.index && (g = g.index(b.index))
  2713. g = g.count(b.keyRange)
  2714. g.onsuccess = function (a) {
  2715. d = !0
  2716. f = a.target.result
  2717. }
  2718. g.onError = c
  2719. return e
  2720. },
  2721. makeKeyRange: function (a) {
  2722. var b = "undefined" != typeof a.lower,
  2723. c = "undefined" != typeof a.upper,
  2724. d = "undefined" != typeof a.only
  2725. switch (!0) {
  2726. case d:
  2727. a = this.keyRange.only(a.only)
  2728. break
  2729. case b && c:
  2730. a = this.keyRange.bound(
  2731. a.lower,
  2732. a.upper,
  2733. a.excludeLower,
  2734. a.excludeUpper
  2735. )
  2736. break
  2737. case b:
  2738. a = this.keyRange.lowerBound(
  2739. a.lower,
  2740. a.excludeLower
  2741. )
  2742. break
  2743. case c:
  2744. a = this.keyRange.upperBound(
  2745. a.upper,
  2746. a.excludeUpper
  2747. )
  2748. break
  2749. default:
  2750. throw Error(
  2751. 'Cannot create KeyRange. Provide one or both of "lower" or "upper" value, or an "only" value.'
  2752. )
  2753. }
  2754. return a
  2755. },
  2756. },
  2757. u = {}
  2758. q.prototype = t
  2759. q.version = t.version
  2760. return q
  2761. },
  2762. unsafeWindow
  2763. )
  2764. }
  2765. x = new IDBStore(obj)
  2766. })
  2767. },
  2768. function ({
  2769. ifunset,
  2770. gettype,
  2771. end,
  2772. maketype,
  2773. makeenum,
  2774. trymaketype,
  2775. trymakeenum,
  2776. trygettype,
  2777. args: [obj],
  2778. }) {
  2779. obj = maketype(obj, ["object"])
  2780. return end()
  2781. }
  2782. )
  2783.  
  2784. a.readfileslow = newfunc(
  2785. function readfileslow(
  2786. file,
  2787. type = "Text",
  2788. cb1 = (e) => e,
  2789. cb2 = (e) => e
  2790. ) {
  2791. var fileSize = file.size
  2792. var chunkSize = 64 * 1024 * 50
  2793. var offset = 0
  2794. var chunkReaderBlock = null
  2795. var arr = []
  2796. var lastidx
  2797. var readEventHandler = function (evt, idx) {
  2798. if (evt.target.error == null) {
  2799. arr.push([idx, evt.target.result])
  2800. cb1(a.rerange(arr.length, 0, lastidx, 0, 100))
  2801. if (arr.length === lastidx)
  2802. cb2(arr.sort((e) => e[0]).map((e) => e[1]))
  2803. } else {
  2804. return error("Read error: " + evt.target.error)
  2805. }
  2806. }
  2807. chunkReaderBlock = function (_offset, length, _file, idx) {
  2808. var r = new FileReader()
  2809. var blob = _file.slice(_offset, length + _offset)
  2810. const zzz = idx + 1
  2811. r.onload = function (e) {
  2812. readEventHandler(e, zzz - 1)
  2813. }
  2814. r["readAs" + type](blob)
  2815. }
  2816. let idx = 0
  2817. while (offset < fileSize) {
  2818. idx++
  2819. chunkReaderBlock(offset, chunkSize, file, idx)
  2820. offset += chunkSize
  2821. }
  2822. lastidx = idx
  2823. },
  2824. function ({ end, args: [file, type, cb1, cb2], maketype }) {
  2825. file = maketype(file, ["object"]) // Ensure file is an object
  2826. type = maketype(type, ["string"]) // Ensure type is a string
  2827. cb1 = maketype(cb1, ["function"]) // Ensure cb1 is a function
  2828. cb2 = maketype(cb2, ["function"]) // Ensure cb2 is a function
  2829. return end()
  2830. }
  2831. )
  2832.  
  2833. a.cbtoasync = newfunc(
  2834. function cbtoasync(func, ...args) {
  2835. return new Promise(function (resolve) {
  2836. func(...args, resolve)
  2837. })
  2838. },
  2839. function ({ end, args: [func, ...args], maketype }) {
  2840. func = maketype(func, ["function"]) // Ensure func is a function
  2841. return end()
  2842. }
  2843. )
  2844.  
  2845. a.asynctocb = newfunc(
  2846. function asynctocb(func, ...args) {
  2847. var cb = args.pop()
  2848. return func(...args).then(cb)
  2849. },
  2850. function ({ end, args: [func, ...args], maketype }) {
  2851. func = maketype(func, ["function"]) // Ensure func is a function
  2852. return end()
  2853. }
  2854. )
  2855.  
  2856. a.randstr = newfunc(
  2857. function randstr({
  2858. lower = true,
  2859. upper = false,
  2860. number = false,
  2861. symbol = false,
  2862. length = 20,
  2863. }) {
  2864. var rand = ""
  2865. a.repeat(() => {
  2866. rand += a.randfrom(
  2867. `${lower ? "asdfghjklzxcvbnmqwertyuiop" : ""}${
  2868. upper ? "ASDFGHJKLQWERTYUIOPZXCVBNM" : ""
  2869. }${number ? "0123456789" : ""}${
  2870. symbol ? ",./;'[]-=\\`~!@#$%^&*()_+|{}:\"<>?" : ""
  2871. }`.split("")
  2872. )
  2873. }, length)
  2874. return rand
  2875. },
  2876. function ({ end, maketype, args: [options], ifunset }) {
  2877. ifunset([
  2878. {
  2879. lower: true,
  2880. upper: false,
  2881. number: false,
  2882. symbol: false,
  2883. length: 20,
  2884. },
  2885. ])
  2886. options = maketype(options, ["object", "undefined"]) // Ensure options is an object
  2887. return end()
  2888. }
  2889. )
  2890.  
  2891. a.toplaces = newfunc(
  2892. function toplaces(num, pre, post = 0, func = Math.round) {
  2893. num = String(num).split(".")
  2894. if (num.length == 1) num.push("")
  2895. if (pre !== undefined) {
  2896. num[0] = num[0].substring(num[0].length - pre, num[0].length)
  2897. while (num[0].length < pre) num[0] = "0" + num[0]
  2898. }
  2899. var temp = num[1].substring(post, post + 1) ?? 0
  2900. num[1] = num[1].substring(0, post)
  2901. while (num[1].length < post) num[1] += "0"
  2902. if (post > 0) {
  2903. temp = func(num[1].at(-1) + "." + temp)
  2904. num[1] = num[1].split("")
  2905. num[1].pop()
  2906. num[1].push(temp)
  2907. num[1] = num[1].join("")
  2908. num = num.join(".")
  2909. } else num = num[0]
  2910. return num
  2911. },
  2912. function ({ end, maketype, args: [num, pre, post, func] }) {
  2913. num = maketype(num, ["number"]) // Ensure num is a number
  2914. pre = maketype(pre, ["number", "undefined"]) // Ensure pre is a number
  2915. post = maketype(post, ["number"]) // Ensure post is a number
  2916. func = maketype(func, ["function", "undefined"]) // Ensure func is a function or undefined
  2917. return end()
  2918. }
  2919. )
  2920.  
  2921. a.fetch = newfunc(
  2922. async function fetch(url, type = "text", ...args) {
  2923. return await (await fetch(url, ...args))[type]()
  2924. },
  2925. function ({ end, maketype, args: [url, type], makeenum }) {
  2926. url = maketype(url, ["string"]) // Ensure url is a string
  2927. type = maketype(type, ["string"]) // Ensure type is a string
  2928. type = makeenum(type, ["text", "json"])
  2929. return end()
  2930. }
  2931. )
  2932.  
  2933. a.replaceall = newfunc(
  2934. function replaceall(text, regex, replacewith) {
  2935. return text.replaceAll(
  2936. a.toregex(String(a.toregex(regex)) + "g"),
  2937. replacewith
  2938. )
  2939. },
  2940. function ({
  2941. ifunset,
  2942. gettype,
  2943. end,
  2944. maketype,
  2945. makeenum,
  2946. trymaketype,
  2947. trymakeenum,
  2948. trygettype,
  2949. args: [text, regex, replacewith],
  2950. }) {
  2951. text = maketype(text, ["string"])
  2952. regex = maketype(regex, ["regex"])
  2953. replacewith = maketype(replacewith, ["string"])
  2954. return end()
  2955. }
  2956. )
  2957.  
  2958. a.setrange = newfunc(
  2959. function setrange(num, min, max) {
  2960. return num < min ? min : num > max ? max : num
  2961. },
  2962. function ({
  2963. ifunset,
  2964. gettype,
  2965. end,
  2966. maketype,
  2967. makeenum,
  2968. trymaketype,
  2969. trymakeenum,
  2970. trygettype,
  2971. args: [num, min, max],
  2972. }) {
  2973. num = maketype(num, ["number"])
  2974. min = maketype(min, ["number"])
  2975. max = maketype(max, ["number"])
  2976. return end()
  2977. }
  2978. )
  2979.  
  2980. a.ondrop = newfunc(
  2981. function ondrop(obj) {
  2982. if (!obj.types) obj.types = "all"
  2983. obj.types = a.toarray(obj.types)
  2984. if (!obj.func) throw new Error('object is missing "func"')
  2985. var oldelem = obj.elem
  2986. if (obj.elem) obj.elem = a.toelem(obj.elem, true)
  2987. if (obj.elem && !a.gettype(obj.elem, "element"))
  2988. throw new Error(
  2989. `elem is not an elem, ${oldelem} -> ${obj.elem}`
  2990. )
  2991. drops.push(obj)
  2992. return obj
  2993. },
  2994. function ({
  2995. ifunset,
  2996. gettype,
  2997. end,
  2998. maketype,
  2999. makeenum,
  3000. trymaketype,
  3001. trymakeenum,
  3002. trygettype,
  3003. args: [obj],
  3004. }) {
  3005. obj = maketype(obj, ["object"])
  3006. return end()
  3007. }
  3008. )
  3009. a.clamp = newfunc(
  3010. function clamp(num, min, max) {
  3011. if (min !== undefined && num < min) num = min
  3012. if (max !== undefined && num > max) num = max
  3013. return num
  3014. },
  3015. function ({
  3016. ifunset,
  3017. gettype,
  3018. end,
  3019. maketype,
  3020. makeenum,
  3021. trymaketype,
  3022. trymakeenum,
  3023. trygettype,
  3024. args: [num, min, max],
  3025. }) {
  3026. ifunset(undefined, undefined, undefined)
  3027. num = maketype(num, ["number"])
  3028. min = maketype(min, ["number", "undefined"])
  3029. max = maketype(max, ["number", "undefined"])
  3030. return end()
  3031. }
  3032. )
  3033. a.step = newfunc(
  3034. function step(num, step) {
  3035. return Math.round(num / step) * step
  3036. },
  3037. function ({
  3038. ifunset,
  3039. gettype,
  3040. end,
  3041. maketype,
  3042. makeenum,
  3043. trymaketype,
  3044. trymakeenum,
  3045. trygettype,
  3046. args: [num, step],
  3047. }) {
  3048. num = maketype(num, ["number"])
  3049. step = maketype(step, ["number"])
  3050. return end()
  3051. }
  3052. )
  3053. a.download = newfunc(
  3054. function download(
  3055. data, //string|file|blob
  3056. filename = "temp.txt", //string|undefined
  3057. type = "text/plain", //string|undefined
  3058. isurl = false //boolean|undefined
  3059. ) {
  3060. var url
  3061. if (isurl) {
  3062. url = data
  3063. } else {
  3064. if (a.gettype(data, "string"))
  3065. var file = new Blob([data], {
  3066. type,
  3067. })
  3068. else if (a.gettype(data, ["file", "blob"])) {
  3069. filename = data.name
  3070. var file = data
  3071. }
  3072. url = URL.createObjectURL(file)
  3073. }
  3074. var link = document.createElement("a")
  3075.  
  3076. link.href = url
  3077. link.download = filename
  3078. a.bodyload().then(() => {
  3079. document.body.appendChild(link)
  3080. link.click()
  3081. document.body.removeChild(link)
  3082. if (!isurl) URL.revokeObjectURL(url)
  3083. })
  3084. },
  3085. function ({
  3086. ifunset,
  3087. gettype,
  3088. end,
  3089. maketype,
  3090. makeenum,
  3091. trymaketype,
  3092. trymakeenum,
  3093. trygettype,
  3094. args: [data, filename, type, isurl],
  3095. }) {
  3096. ifunset(undefined, "temp.txt", "text/plain", false)
  3097. data = maketype(data, ["string", "blob", "file"])
  3098. filename = maketype(filename, ["string", "undefined"])
  3099. type = maketype(type, ["string", "undefined"])
  3100. isurl = maketype(isurl, ["boolean", "undefined"])
  3101. return end()
  3102. }
  3103. )
  3104. a.maketable = newfunc(
  3105. function maketable(tableData) {
  3106. const table = a.newelem("table", {}, [])
  3107. var tbody
  3108. var first = true
  3109. for (var tableRow of tableData) {
  3110. var tr = a.newelem("tr")
  3111. if (tbody) {
  3112. tbody.appendChild(tr)
  3113. } else {
  3114. table.appendChild(a.newelem("thead", {}, [tr]))
  3115. table.appendChild((tbody = a.newelem("tbody")))
  3116. }
  3117. for (var data of tableRow) {
  3118. var type = first ? "th" : "td"
  3119. if (data == null) {
  3120. var elem = a.newelem(type, {})
  3121. } else if (a.gettype(data, "string")) {
  3122. var elem = a.newelem(type, { innerHTML: data })
  3123. } else if (a.gettype(data, "object")) {
  3124. var elem = a.newelem(type, data)
  3125. } else if (a.gettype(data, "array")) {
  3126. var elem = a.newelem(type, {}, data)
  3127. } else if (a.gettype(data, "element")) {
  3128. var elem = a.newelem(type, {}, [data])
  3129. }
  3130. tr.appendChild(elem)
  3131. }
  3132. first = false
  3133. }
  3134. return table
  3135. },
  3136. function ({
  3137. ifunset,
  3138. gettype,
  3139. end,
  3140. maketype,
  3141. makeenum,
  3142. trymaketype,
  3143. trymakeenum,
  3144. trygettype,
  3145. args: [tableData],
  3146. }) {
  3147. tableData = maketype(tableData, ["array"])
  3148. return end()
  3149. }
  3150. )
  3151. loadlib("libloader").savelib("allfuncs", a)
  3152. })()