lib:newallfuncs

none

当前为 2025-03-07 提交的版本,查看 最新版本

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

QingJ © 2025

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