index.mjs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. function clamp(n, min, max) {
  2. return Math.min(max, Math.max(min, n));
  3. }
  4. function sum(...args) {
  5. return flattenArrayable(args).reduce((a, b) => a + b, 0);
  6. }
  7. function toArray(array) {
  8. array = array ?? [];
  9. return Array.isArray(array) ? array : [array];
  10. }
  11. function flattenArrayable(array) {
  12. return toArray(array).flat(1);
  13. }
  14. function mergeArrayable(...args) {
  15. return args.flatMap((i) => toArray(i));
  16. }
  17. function partition(array, ...filters) {
  18. const result = new Array(filters.length + 1).fill(null).map(() => []);
  19. array.forEach((e, idx, arr) => {
  20. let i = 0;
  21. for (const filter of filters) {
  22. if (filter(e, idx, arr)) {
  23. result[i].push(e);
  24. return;
  25. }
  26. i += 1;
  27. }
  28. result[i].push(e);
  29. });
  30. return result;
  31. }
  32. function uniq(array) {
  33. return Array.from(new Set(array));
  34. }
  35. function uniqueBy(array, equalFn) {
  36. return array.reduce((acc, cur) => {
  37. const index = acc.findIndex((item) => equalFn(cur, item));
  38. if (index === -1)
  39. acc.push(cur);
  40. return acc;
  41. }, []);
  42. }
  43. function last(array) {
  44. return at(array, -1);
  45. }
  46. function remove(array, value) {
  47. if (!array)
  48. return false;
  49. const index = array.indexOf(value);
  50. if (index >= 0) {
  51. array.splice(index, 1);
  52. return true;
  53. }
  54. return false;
  55. }
  56. function at(array, index) {
  57. const len = array.length;
  58. if (!len)
  59. return void 0;
  60. if (index < 0)
  61. index += len;
  62. return array[index];
  63. }
  64. function range(...args) {
  65. let start, stop, step;
  66. if (args.length === 1) {
  67. start = 0;
  68. step = 1;
  69. [stop] = args;
  70. } else {
  71. [start, stop, step = 1] = args;
  72. }
  73. const arr = [];
  74. let current = start;
  75. while (current < stop) {
  76. arr.push(current);
  77. current += step || 1;
  78. }
  79. return arr;
  80. }
  81. function move(arr, from, to) {
  82. arr.splice(to, 0, arr.splice(from, 1)[0]);
  83. return arr;
  84. }
  85. function clampArrayRange(n, arr) {
  86. return clamp(n, 0, arr.length - 1);
  87. }
  88. function sample(arr, count) {
  89. return Array.from({ length: count }, (_) => arr[Math.round(Math.random() * (arr.length - 1))]);
  90. }
  91. function shuffle(array) {
  92. for (let i = array.length - 1; i > 0; i--) {
  93. const j = Math.floor(Math.random() * (i + 1));
  94. [array[i], array[j]] = [array[j], array[i]];
  95. }
  96. return array;
  97. }
  98. const assert = (condition, message) => {
  99. if (!condition)
  100. throw new Error(message);
  101. };
  102. const toString = (v) => Object.prototype.toString.call(v);
  103. const getTypeName = (v) => {
  104. if (v === null)
  105. return "null";
  106. const type = toString(v).slice(8, -1).toLowerCase();
  107. return typeof v === "object" || typeof v === "function" ? type : typeof v;
  108. };
  109. const noop = () => {
  110. };
  111. function notNullish(v) {
  112. return v != null;
  113. }
  114. function noNull(v) {
  115. return v !== null;
  116. }
  117. function notUndefined(v) {
  118. return v !== void 0;
  119. }
  120. function isTruthy(v) {
  121. return Boolean(v);
  122. }
  123. const isDef = (val) => typeof val !== "undefined";
  124. const isBoolean = (val) => typeof val === "boolean";
  125. const isFunction = (val) => typeof val === "function";
  126. const isNumber = (val) => typeof val === "number";
  127. const isString = (val) => typeof val === "string";
  128. const isObject = (val) => toString(val) === "[object Object]";
  129. const isUndefined = (val) => toString(val) === "[object Undefined]";
  130. const isNull = (val) => toString(val) === "[object Null]";
  131. const isRegExp = (val) => toString(val) === "[object RegExp]";
  132. const isDate = (val) => toString(val) === "[object Date]";
  133. const isWindow = (val) => typeof window !== "undefined" && toString(val) === "[object Window]";
  134. const isBrowser = typeof window !== "undefined";
  135. function slash(str) {
  136. return str.replace(/\\/g, "/");
  137. }
  138. function ensurePrefix(prefix, str) {
  139. if (!str.startsWith(prefix))
  140. return prefix + str;
  141. return str;
  142. }
  143. function ensureSuffix(suffix, str) {
  144. if (!str.endsWith(suffix))
  145. return str + suffix;
  146. return str;
  147. }
  148. function template(str, ...args) {
  149. return str.replace(/{(\d+)}/g, (match, key) => {
  150. const index = Number(key);
  151. if (Number.isNaN(index))
  152. return match;
  153. return args[index];
  154. });
  155. }
  156. const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
  157. function randomStr(size = 16, dict = urlAlphabet) {
  158. let id = "";
  159. let i = size;
  160. const len = dict.length;
  161. while (i--)
  162. id += dict[Math.random() * len | 0];
  163. return id;
  164. }
  165. function capitalize(str) {
  166. return str[0].toUpperCase() + str.slice(1).toLowerCase();
  167. }
  168. const timestamp = () => +Date.now();
  169. function batchInvoke(functions) {
  170. functions.forEach((fn) => fn && fn());
  171. }
  172. function invoke(fn) {
  173. return fn();
  174. }
  175. function tap(value, callback) {
  176. callback(value);
  177. return value;
  178. }
  179. function objectMap(obj, fn) {
  180. return Object.fromEntries(
  181. Object.entries(obj).map(([k, v]) => fn(k, v)).filter(notNullish)
  182. );
  183. }
  184. function isKeyOf(obj, k) {
  185. return k in obj;
  186. }
  187. function objectKeys(obj) {
  188. return Object.keys(obj);
  189. }
  190. function objectEntries(obj) {
  191. return Object.entries(obj);
  192. }
  193. function deepMerge(target, ...sources) {
  194. if (!sources.length)
  195. return target;
  196. const source = sources.shift();
  197. if (source === void 0)
  198. return target;
  199. if (isMergableObject(target) && isMergableObject(source)) {
  200. objectKeys(source).forEach((key) => {
  201. if (isMergableObject(source[key])) {
  202. if (!target[key])
  203. target[key] = {};
  204. deepMerge(target[key], source[key]);
  205. } else {
  206. target[key] = source[key];
  207. }
  208. });
  209. }
  210. return deepMerge(target, ...sources);
  211. }
  212. function isMergableObject(item) {
  213. return isObject(item) && !Array.isArray(item);
  214. }
  215. function objectPick(obj, keys, omitUndefined = false) {
  216. return keys.reduce((n, k) => {
  217. if (k in obj) {
  218. if (!omitUndefined || obj[k] !== void 0)
  219. n[k] = obj[k];
  220. }
  221. return n;
  222. }, {});
  223. }
  224. function clearUndefined(obj) {
  225. Object.keys(obj).forEach((key) => obj[key] === void 0 ? delete obj[key] : {});
  226. return obj;
  227. }
  228. function hasOwnProperty(obj, v) {
  229. if (obj == null)
  230. return false;
  231. return Object.prototype.hasOwnProperty.call(obj, v);
  232. }
  233. function createSingletonPromise(fn) {
  234. let _promise;
  235. function wrapper() {
  236. if (!_promise)
  237. _promise = fn();
  238. return _promise;
  239. }
  240. wrapper.reset = async () => {
  241. const _prev = _promise;
  242. _promise = void 0;
  243. if (_prev)
  244. await _prev;
  245. };
  246. return wrapper;
  247. }
  248. function sleep(ms, callback) {
  249. return new Promise(
  250. (resolve) => setTimeout(async () => {
  251. await (callback == null ? void 0 : callback());
  252. resolve();
  253. }, ms)
  254. );
  255. }
  256. function createPromiseLock() {
  257. const locks = [];
  258. return {
  259. async run(fn) {
  260. const p = fn();
  261. locks.push(p);
  262. try {
  263. return await p;
  264. } finally {
  265. remove(locks, p);
  266. }
  267. },
  268. async wait() {
  269. await Promise.allSettled(locks);
  270. },
  271. isWaiting() {
  272. return Boolean(locks.length);
  273. },
  274. clear() {
  275. locks.length = 0;
  276. }
  277. };
  278. }
  279. function createControlledPromise() {
  280. let resolve, reject;
  281. const promise = new Promise((_resolve, _reject) => {
  282. resolve = _resolve;
  283. reject = _reject;
  284. });
  285. promise.resolve = resolve;
  286. promise.reject = reject;
  287. return promise;
  288. }
  289. /* eslint-disable no-undefined,no-param-reassign,no-shadow */
  290. /**
  291. * Throttle execution of a function. Especially useful for rate limiting
  292. * execution of handlers on events like resize and scroll.
  293. *
  294. * @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher)
  295. * are most useful.
  296. * @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through,
  297. * as-is, to `callback` when the throttled-function is executed.
  298. * @param {object} [options] - An object to configure options.
  299. * @param {boolean} [options.noTrailing] - Optional, defaults to false. If noTrailing is true, callback will only execute every `delay` milliseconds
  300. * while the throttled-function is being called. If noTrailing is false or unspecified, callback will be executed
  301. * one final time after the last throttled-function call. (After the throttled-function has not been called for
  302. * `delay` milliseconds, the internal counter is reset).
  303. * @param {boolean} [options.noLeading] - Optional, defaults to false. If noLeading is false, the first throttled-function call will execute callback
  304. * immediately. If noLeading is true, the first the callback execution will be skipped. It should be noted that
  305. * callback will never executed if both noLeading = true and noTrailing = true.
  306. * @param {boolean} [options.debounceMode] - If `debounceMode` is true (at begin), schedule `clear` to execute after `delay` ms. If `debounceMode` is
  307. * false (at end), schedule `callback` to execute after `delay` ms.
  308. *
  309. * @returns {Function} A new, throttled, function.
  310. */
  311. function throttle (delay, callback, options) {
  312. var _ref = options || {},
  313. _ref$noTrailing = _ref.noTrailing,
  314. noTrailing = _ref$noTrailing === void 0 ? false : _ref$noTrailing,
  315. _ref$noLeading = _ref.noLeading,
  316. noLeading = _ref$noLeading === void 0 ? false : _ref$noLeading,
  317. _ref$debounceMode = _ref.debounceMode,
  318. debounceMode = _ref$debounceMode === void 0 ? undefined : _ref$debounceMode;
  319. /*
  320. * After wrapper has stopped being called, this timeout ensures that
  321. * `callback` is executed at the proper times in `throttle` and `end`
  322. * debounce modes.
  323. */
  324. var timeoutID;
  325. var cancelled = false; // Keep track of the last time `callback` was executed.
  326. var lastExec = 0; // Function to clear existing timeout
  327. function clearExistingTimeout() {
  328. if (timeoutID) {
  329. clearTimeout(timeoutID);
  330. }
  331. } // Function to cancel next exec
  332. function cancel(options) {
  333. var _ref2 = options || {},
  334. _ref2$upcomingOnly = _ref2.upcomingOnly,
  335. upcomingOnly = _ref2$upcomingOnly === void 0 ? false : _ref2$upcomingOnly;
  336. clearExistingTimeout();
  337. cancelled = !upcomingOnly;
  338. }
  339. /*
  340. * The `wrapper` function encapsulates all of the throttling / debouncing
  341. * functionality and when executed will limit the rate at which `callback`
  342. * is executed.
  343. */
  344. function wrapper() {
  345. for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
  346. arguments_[_key] = arguments[_key];
  347. }
  348. var self = this;
  349. var elapsed = Date.now() - lastExec;
  350. if (cancelled) {
  351. return;
  352. } // Execute `callback` and update the `lastExec` timestamp.
  353. function exec() {
  354. lastExec = Date.now();
  355. callback.apply(self, arguments_);
  356. }
  357. /*
  358. * If `debounceMode` is true (at begin) this is used to clear the flag
  359. * to allow future `callback` executions.
  360. */
  361. function clear() {
  362. timeoutID = undefined;
  363. }
  364. if (!noLeading && debounceMode && !timeoutID) {
  365. /*
  366. * Since `wrapper` is being called for the first time and
  367. * `debounceMode` is true (at begin), execute `callback`
  368. * and noLeading != true.
  369. */
  370. exec();
  371. }
  372. clearExistingTimeout();
  373. if (debounceMode === undefined && elapsed > delay) {
  374. if (noLeading) {
  375. /*
  376. * In throttle mode with noLeading, if `delay` time has
  377. * been exceeded, update `lastExec` and schedule `callback`
  378. * to execute after `delay` ms.
  379. */
  380. lastExec = Date.now();
  381. if (!noTrailing) {
  382. timeoutID = setTimeout(debounceMode ? clear : exec, delay);
  383. }
  384. } else {
  385. /*
  386. * In throttle mode without noLeading, if `delay` time has been exceeded, execute
  387. * `callback`.
  388. */
  389. exec();
  390. }
  391. } else if (noTrailing !== true) {
  392. /*
  393. * In trailing throttle mode, since `delay` time has not been
  394. * exceeded, schedule `callback` to execute `delay` ms after most
  395. * recent execution.
  396. *
  397. * If `debounceMode` is true (at begin), schedule `clear` to execute
  398. * after `delay` ms.
  399. *
  400. * If `debounceMode` is false (at end), schedule `callback` to
  401. * execute after `delay` ms.
  402. */
  403. timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === undefined ? delay - elapsed : delay);
  404. }
  405. }
  406. wrapper.cancel = cancel; // Return the wrapper function.
  407. return wrapper;
  408. }
  409. /* eslint-disable no-undefined */
  410. /**
  411. * Debounce execution of a function. Debouncing, unlike throttling,
  412. * guarantees that a function is only executed a single time, either at the
  413. * very beginning of a series of calls, or at the very end.
  414. *
  415. * @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
  416. * @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,
  417. * to `callback` when the debounced-function is executed.
  418. * @param {object} [options] - An object to configure options.
  419. * @param {boolean} [options.atBegin] - Optional, defaults to false. If atBegin is false or unspecified, callback will only be executed `delay` milliseconds
  420. * after the last debounced-function call. If atBegin is true, callback will be executed only at the first debounced-function call.
  421. * (After the throttled-function has not been called for `delay` milliseconds, the internal counter is reset).
  422. *
  423. * @returns {Function} A new, debounced function.
  424. */
  425. function debounce (delay, callback, options) {
  426. var _ref = options || {},
  427. _ref$atBegin = _ref.atBegin,
  428. atBegin = _ref$atBegin === void 0 ? false : _ref$atBegin;
  429. return throttle(delay, callback, {
  430. debounceMode: atBegin !== false
  431. });
  432. }
  433. /*
  434. How it works:
  435. `this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.
  436. */
  437. class Node {
  438. value;
  439. next;
  440. constructor(value) {
  441. this.value = value;
  442. }
  443. }
  444. class Queue {
  445. #head;
  446. #tail;
  447. #size;
  448. constructor() {
  449. this.clear();
  450. }
  451. enqueue(value) {
  452. const node = new Node(value);
  453. if (this.#head) {
  454. this.#tail.next = node;
  455. this.#tail = node;
  456. } else {
  457. this.#head = node;
  458. this.#tail = node;
  459. }
  460. this.#size++;
  461. }
  462. dequeue() {
  463. const current = this.#head;
  464. if (!current) {
  465. return;
  466. }
  467. this.#head = this.#head.next;
  468. this.#size--;
  469. return current.value;
  470. }
  471. clear() {
  472. this.#head = undefined;
  473. this.#tail = undefined;
  474. this.#size = 0;
  475. }
  476. get size() {
  477. return this.#size;
  478. }
  479. * [Symbol.iterator]() {
  480. let current = this.#head;
  481. while (current) {
  482. yield current.value;
  483. current = current.next;
  484. }
  485. }
  486. }
  487. function pLimit(concurrency) {
  488. if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
  489. throw new TypeError('Expected `concurrency` to be a number from 1 and up');
  490. }
  491. const queue = new Queue();
  492. let activeCount = 0;
  493. const next = () => {
  494. activeCount--;
  495. if (queue.size > 0) {
  496. queue.dequeue()();
  497. }
  498. };
  499. const run = async (fn, resolve, args) => {
  500. activeCount++;
  501. const result = (async () => fn(...args))();
  502. resolve(result);
  503. try {
  504. await result;
  505. } catch {}
  506. next();
  507. };
  508. const enqueue = (fn, resolve, args) => {
  509. queue.enqueue(run.bind(undefined, fn, resolve, args));
  510. (async () => {
  511. // This function needs to wait until the next microtask before comparing
  512. // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
  513. // when the run function is dequeued and called. The comparison in the if-statement
  514. // needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
  515. await Promise.resolve();
  516. if (activeCount < concurrency && queue.size > 0) {
  517. queue.dequeue()();
  518. }
  519. })();
  520. };
  521. const generator = (fn, ...args) => new Promise(resolve => {
  522. enqueue(fn, resolve, args);
  523. });
  524. Object.defineProperties(generator, {
  525. activeCount: {
  526. get: () => activeCount,
  527. },
  528. pendingCount: {
  529. get: () => queue.size,
  530. },
  531. clearQueue: {
  532. value: () => {
  533. queue.clear();
  534. },
  535. },
  536. });
  537. return generator;
  538. }
  539. const VOID = Symbol("p-void");
  540. class PInstance extends Promise {
  541. constructor(items = [], options) {
  542. super(() => {
  543. });
  544. this.items = items;
  545. this.options = options;
  546. this.promises = /* @__PURE__ */ new Set();
  547. }
  548. get promise() {
  549. var _a;
  550. let batch;
  551. const items = [...Array.from(this.items), ...Array.from(this.promises)];
  552. if ((_a = this.options) == null ? void 0 : _a.concurrency) {
  553. const limit = pLimit(this.options.concurrency);
  554. batch = Promise.all(items.map((p2) => limit(() => p2)));
  555. } else {
  556. batch = Promise.all(items);
  557. }
  558. return batch.then((l) => l.filter((i) => i !== VOID));
  559. }
  560. add(...args) {
  561. args.forEach((i) => {
  562. this.promises.add(i);
  563. });
  564. }
  565. map(fn) {
  566. return new PInstance(
  567. Array.from(this.items).map(async (i, idx) => {
  568. const v = await i;
  569. if (v === VOID)
  570. return VOID;
  571. return fn(v, idx);
  572. }),
  573. this.options
  574. );
  575. }
  576. filter(fn) {
  577. return new PInstance(
  578. Array.from(this.items).map(async (i, idx) => {
  579. const v = await i;
  580. const r = await fn(v, idx);
  581. if (!r)
  582. return VOID;
  583. return v;
  584. }),
  585. this.options
  586. );
  587. }
  588. forEach(fn) {
  589. return this.map(fn).then();
  590. }
  591. reduce(fn, initialValue) {
  592. return this.promise.then((array) => array.reduce(fn, initialValue));
  593. }
  594. clear() {
  595. this.promises.clear();
  596. }
  597. then(fn) {
  598. const p2 = this.promise;
  599. if (fn)
  600. return p2.then(fn);
  601. else
  602. return p2;
  603. }
  604. catch(fn) {
  605. return this.promise.catch(fn);
  606. }
  607. finally(fn) {
  608. return this.promise.finally(fn);
  609. }
  610. }
  611. function p(items, options) {
  612. return new PInstance(items, options);
  613. }
  614. export { assert, at, batchInvoke, capitalize, clamp, clampArrayRange, clearUndefined, createControlledPromise, createPromiseLock, createSingletonPromise, debounce, deepMerge, ensurePrefix, ensureSuffix, flattenArrayable, getTypeName, hasOwnProperty, invoke, isBoolean, isBrowser, isDate, isDef, isFunction, isKeyOf, isNull, isNumber, isObject, isRegExp, isString, isTruthy, isUndefined, isWindow, last, mergeArrayable, move, noNull, noop, notNullish, notUndefined, objectEntries, objectKeys, objectMap, objectPick, p, partition, randomStr, range, remove, sample, shuffle, slash, sleep, sum, tap, template, throttle, timestamp, toArray, toString, uniq, uniqueBy };