index.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __export = (target, all) => {
  9. for (var name in all)
  10. __defProp(target, name, { get: all[name], enumerable: true });
  11. };
  12. var __copyProps = (to, from, except, desc) => {
  13. if (from && typeof from === "object" || typeof from === "function") {
  14. for (let key of __getOwnPropNames(from))
  15. if (!__hasOwnProp.call(to, key) && key !== except)
  16. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  17. }
  18. return to;
  19. };
  20. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  21. // If the importer is in node compatibility mode or this is not an ESM
  22. // file that has been converted to a CommonJS file using a Babel-
  23. // compatible transform (i.e. "__esModule" has not been set), then set
  24. // "default" to the CommonJS "module.exports" for node compatibility.
  25. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  26. mod
  27. ));
  28. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  29. // src/index.ts
  30. var src_exports = {};
  31. __export(src_exports, {
  32. ASYNC_STATUS: () => ASYNC_STATUS,
  33. DAY: () => DAY,
  34. HOUR: () => HOUR,
  35. MINUTE: () => MINUTE,
  36. MONTH: () => MONTH,
  37. Types: () => types_exports,
  38. WEEK: () => WEEK,
  39. YEAR: () => YEAR,
  40. capitalize: () => capitalize,
  41. ceil: () => ceil,
  42. clamp: () => clamp,
  43. cleanUpObject: () => cleanUpObject,
  44. cleanupHTML: () => cleanupHTML,
  45. cleanupNumericString: () => cleanupNumericString,
  46. cleanupURI: () => cleanupURI,
  47. conditional: () => conditional,
  48. copyToClipboard: () => copyToClipboard,
  49. cors: () => cors,
  50. createArray: () => createArray,
  51. demethodize: () => demethodize,
  52. floor: () => floor,
  53. formatBoolean: () => formatBoolean,
  54. formatCPF: () => formatCPF,
  55. formatDateLocale: () => formatDateLocale,
  56. formatMoney: () => formatMoney,
  57. formatPhoneBR: () => formatPhoneBR,
  58. formatPhoneUS: () => formatPhoneUS,
  59. formatPostalCodeBR: () => formatPostalCodeBR,
  60. getDataType: () => getDataType,
  61. getInitials: () => getInitials,
  62. getNestedProperty: () => getNestedProperty,
  63. getRandomItem: () => getRandomItem,
  64. invariant: () => invariant,
  65. invertKeys: () => invertKeys,
  66. isDarkMode: () => isDarkMode,
  67. isIsoDate: () => isIsoDate,
  68. isJSON: () => isJSON,
  69. isRequired: () => isRequired,
  70. isTouchDevice: () => isTouchDevice,
  71. isValidCPF: () => isValidCPF,
  72. isValidDate: () => isValidDate,
  73. isValidEmail: () => isValidEmail,
  74. isoDate: () => isoDate,
  75. keyMirror: () => keyMirror,
  76. logger: () => logger,
  77. mean: () => mean,
  78. measureExecutionTime: () => measureExecutionTime,
  79. median: () => median,
  80. mergeProps: () => mergeProps,
  81. mode: () => mode,
  82. noop: () => noop,
  83. now: () => now,
  84. nullify: () => nullify,
  85. objectEntries: () => objectEntries,
  86. objectKeys: () => objectKeys,
  87. objectToArray: () => objectToArray,
  88. omit: () => omit,
  89. once: () => once,
  90. pad: () => pad,
  91. pick: () => pick,
  92. pipe: () => pipe,
  93. pluralize: () => pluralize,
  94. poll: () => poll,
  95. popupCenter: () => popupCenter,
  96. prefersReducedMotion: () => prefersReducedMotion,
  97. px: () => px,
  98. queryStringFormat: () => queryStringFormat,
  99. queryStringParse: () => queryStringParse,
  100. quickSort: () => quickSort,
  101. randomNumber: () => randomNumber,
  102. removeAccents: () => removeAccents,
  103. removeDuplicates: () => removeDuplicates,
  104. removeEmojis: () => removeEmojis,
  105. removeEmptyTags: () => removeEmptyTags,
  106. removeNonPrintableCharacters: () => removeNonPrintableCharacters,
  107. removeTags: () => removeTags,
  108. removeWhitespace: () => removeWhitespace,
  109. request: () => request,
  110. round: () => round,
  111. shuffle: () => shuffle,
  112. sleep: () => sleep,
  113. slugify: () => slugify,
  114. sortByLocaleCompare: () => sortByLocaleCompare,
  115. sortByPrimitive: () => sortByPrimitive,
  116. sortComparator: () => sortComparator,
  117. sortObjectKeys: () => sortObjectKeys,
  118. splitIntoChunks: () => splitIntoChunks,
  119. timeSince: () => timeSince,
  120. timestamp: () => timestamp,
  121. unique: () => unique,
  122. uuid: () => uuid,
  123. validatePassword: () => validatePassword
  124. });
  125. module.exports = __toCommonJS(src_exports);
  126. // src/arrays.ts
  127. function createArray(size, start = 1) {
  128. return Array.from({ length: size }, (_, index) => index + start);
  129. }
  130. function getRandomItem(input) {
  131. return input[Math.floor(Math.random() * input.length)];
  132. }
  133. function quickSort(input, comparator = sortComparator) {
  134. const output = [...input];
  135. const recursiveSort = (start, end) => {
  136. if (end - start < 1) {
  137. return;
  138. }
  139. const pivotValue = output[end];
  140. let splitIndex = start;
  141. for (let index = start; index < end; index++) {
  142. const sort = comparator(output[index], pivotValue);
  143. if (sort === -1) {
  144. if (splitIndex !== index) {
  145. const temp = output[splitIndex];
  146. output[splitIndex] = output[index];
  147. output[index] = temp;
  148. }
  149. splitIndex++;
  150. }
  151. }
  152. output[end] = output[splitIndex];
  153. output[splitIndex] = pivotValue;
  154. recursiveSort(start, splitIndex - 1);
  155. recursiveSort(splitIndex + 1, end);
  156. };
  157. recursiveSort(0, input.length - 1);
  158. return output;
  159. }
  160. function removeDuplicates(input) {
  161. return [...new Set(input)];
  162. }
  163. function shuffle(input) {
  164. let currentIndex = input.length;
  165. let randomIndex;
  166. let temporaryValue;
  167. const output = [...input];
  168. while (currentIndex) {
  169. randomIndex = Math.floor(Math.random() * currentIndex--);
  170. temporaryValue = output[currentIndex];
  171. output[currentIndex] = output[randomIndex];
  172. output[randomIndex] = temporaryValue;
  173. }
  174. return output;
  175. }
  176. function sortByLocaleCompare(key, options = {}) {
  177. const { descending, ...compareOptions } = options;
  178. if (key) {
  179. if (descending) {
  180. return (left, right) => right[key].toLowerCase().localeCompare(left[key].toLowerCase(), void 0, compareOptions);
  181. }
  182. return (left, right) => left[key].toLowerCase().localeCompare(right[key].toLowerCase(), void 0, compareOptions);
  183. }
  184. if (descending) {
  185. return (left, right) => right.toLowerCase().localeCompare(left.toLowerCase(), void 0, compareOptions);
  186. }
  187. return (left, right) => left.toLowerCase().localeCompare(right.toLowerCase(), void 0, compareOptions);
  188. }
  189. function sortByPrimitive(key, descending = false) {
  190. const firstComparator = descending ? 1 : -1;
  191. const secondComparator = descending ? -1 : 1;
  192. if (key) {
  193. return (left, right) => {
  194. if (left[key] === right[key]) {
  195. return 0;
  196. }
  197. return left[key] < right[key] ? firstComparator : secondComparator;
  198. };
  199. }
  200. return (left, right) => {
  201. if (left === right) {
  202. return 0;
  203. }
  204. return left < right ? firstComparator : secondComparator;
  205. };
  206. }
  207. function sortComparator(left, right) {
  208. if (left < right) {
  209. return -1;
  210. }
  211. if (left > right) {
  212. return 1;
  213. }
  214. return 0;
  215. }
  216. function splitIntoChunks(input, chunkSize = 25) {
  217. if (!Array.isArray(input)) {
  218. throw new TypeError("expected an array for the first argument");
  219. }
  220. const chunks = [];
  221. for (let index = 0; index < Math.ceil(input.length / chunkSize); index++) {
  222. chunks.push(input.slice(index * chunkSize, (index + 1) * chunkSize));
  223. }
  224. return chunks;
  225. }
  226. // src/async.ts
  227. var import_is_lite = __toESM(require("is-lite"));
  228. var ASYNC_STATUS = {
  229. IDLE: "IDLE",
  230. PENDING: "PENDING",
  231. SUCCESS: "SUCCESS",
  232. ERROR: "ERROR"
  233. };
  234. function cors(data, statusCodeOrOptions = 200) {
  235. const {
  236. allowCredentials = true,
  237. allowedHeaders = [],
  238. methods = ["GET"],
  239. origin = "*",
  240. responseHeaders = void 0,
  241. statusCode = 200
  242. } = import_is_lite.default.number(statusCodeOrOptions) ? { statusCode: statusCodeOrOptions } : statusCodeOrOptions;
  243. const allowMethods = [...methods, "OPTIONS"];
  244. const allowHeaders = [
  245. .../* @__PURE__ */ new Set([
  246. "Accept-Version",
  247. "Accept",
  248. "Authorization",
  249. "Content-Length",
  250. "Content-MD5",
  251. "Content-Type",
  252. "Date",
  253. "x-amz-date",
  254. "x-amz-security-token",
  255. "X-Api-Version",
  256. "X-CSRF-Token",
  257. "X-Requested-With",
  258. ...allowedHeaders
  259. ])
  260. ];
  261. let exposedHeaders;
  262. if (responseHeaders) {
  263. exposedHeaders = {
  264. "Access-Control-Expose-Headers": Object.keys(responseHeaders).join(","),
  265. ...responseHeaders
  266. };
  267. }
  268. return {
  269. body: JSON.stringify(data),
  270. headers: {
  271. "Access-Control-Allow-Origin": origin,
  272. "Access-Control-Allow-Credentials": allowCredentials,
  273. "Access-Control-Allow-Methods": allowMethods.join(","),
  274. "Access-Control-Allow-Headers": allowHeaders.join(","),
  275. ...exposedHeaders
  276. },
  277. statusCode
  278. };
  279. }
  280. async function poll(condition, options = {}) {
  281. const { delay = 1, maxRetries = 5 } = options;
  282. let retries = 0;
  283. while (!condition() && retries <= maxRetries) {
  284. await sleep(delay);
  285. retries++;
  286. }
  287. if (retries >= maxRetries) {
  288. throw new Error("Timeout");
  289. }
  290. }
  291. async function request(url, options = {}) {
  292. const { body, headers, method = "GET" } = options;
  293. if (!url) {
  294. throw new Error("URL is required");
  295. }
  296. const params = {
  297. headers: {
  298. Accept: "application/json",
  299. "Content-Type": "application/json",
  300. ...headers
  301. },
  302. method
  303. };
  304. if (body) {
  305. params.body = import_is_lite.default.plainObject(body) ? JSON.stringify(body) : body;
  306. }
  307. return fetch(url, params).then(async (response) => {
  308. const text = await response.text();
  309. let content;
  310. try {
  311. content = JSON.parse(text);
  312. } catch {
  313. content = text;
  314. }
  315. if (response.status > 299) {
  316. const error = new Error(response.statusText);
  317. error.status = response.status;
  318. error.response = content;
  319. throw error;
  320. } else {
  321. return content;
  322. }
  323. });
  324. }
  325. function sleep(seconds = 1) {
  326. return new Promise((resolve) => {
  327. setTimeout(resolve, seconds * 1e3);
  328. });
  329. }
  330. // src/date.ts
  331. var import_is_lite2 = __toESM(require("is-lite"));
  332. // src/strings.ts
  333. function capitalize(input) {
  334. return input.charAt(0).toLocaleUpperCase() + input.slice(1).toLocaleLowerCase();
  335. }
  336. function cleanupHTML(input) {
  337. return removeWhitespace(removeEmptyTags(input));
  338. }
  339. function cleanupNumericString(value = "") {
  340. return value.replace(/\D+/g, "");
  341. }
  342. function cleanupURI(input) {
  343. return input.replace(/[$&+,/:;=?@]/g, "");
  344. }
  345. function getInitials(input) {
  346. if (!input) {
  347. return "";
  348. }
  349. const names = input.trim().split(" ");
  350. if (names.length === 1) {
  351. return `${names[0].charAt(0)}`;
  352. }
  353. return `${names[0].charAt(0)}${names[names.length - 1].charAt(0)}`;
  354. }
  355. function pluralize(quantity, singular, plural) {
  356. if (quantity === 1) {
  357. return singular;
  358. }
  359. return plural || `${singular}s`;
  360. }
  361. function removeAccents(input) {
  362. const removalMap = {
  363. A: /[AÀÁÂÃÄÅĀĂĄǍǞǠǺȀȂȦḀẠẢẤẦẨẪẬẮẰẲẴẶⒶA]/g,
  364. AA: /Ꜳ/g,
  365. AE: /[ÆǢǼ]/g,
  366. AO: /Ꜵ/g,
  367. AU: /Ꜷ/g,
  368. AV: /[ꜸꜺ]/g,
  369. AY: /Ꜽ/g,
  370. B: /[BƁƂɃḂḄḆⒷB]/g,
  371. C: /[CÇĆĈĊČƇȻḈⒸꜾC]/g,
  372. D: /[DĎĐƉƊƋḊḌḎḐḒⒹꝹD]/g,
  373. DZ: /[DŽDZ]/g,
  374. Dz: /[DžDz]/g,
  375. E: /[EÈÉÊËĒĔĖĘĚƎƐȄȆȨḔḖḘḚḜẸẺẼẾỀỂỄỆⒺE]/g,
  376. F: /[FƑḞⒻꝻF]/g,
  377. G: /[GĜĞĠĢƓǤǦǴḠⒼꝽꝾꞠG]/g,
  378. H: /[HĤĦȞḢḤḦḨḪⒽⱧⱵꞍH]/g,
  379. I: /[IÌÍÎÏĨĪĬĮİƗǏȈȊḬḮỈỊⒾI]/g,
  380. J: /[JĴɈⒿJ]/g,
  381. K: /[KĶƘǨḰḲḴⓀⱩꝀꝂꝄꞢK]/g,
  382. L: /[LĹĻĽĿŁȽḶḸḺḼⓁⱠⱢꝆꝈꞀL]/g,
  383. LJ: /LJ/g,
  384. Lj: /Lj/g,
  385. M: /[MƜḾṀṂⓂⱮM]/g,
  386. N: /[NÑŃŅŇƝǸȠṄṆṈṊⓃꞐꞤN]/g,
  387. NJ: /NJ/g,
  388. Nj: /Nj/g,
  389. O: /[OÒÓÔÕÖØŌŎŐƆƟƠǑǪǬǾȌȎȪȬȮȰṌṎṐṒỌỎỐỒỔỖỘỚỜỞỠỢⓄꝊꝌO]/g,
  390. OI: /Ƣ/g,
  391. OO: /Ꝏ/g,
  392. OU: /Ȣ/g,
  393. P: /[PƤṔṖⓅⱣꝐꝒꝔP]/g,
  394. Q: /[QɊⓆꝖꝘQ]/g,
  395. R: /[RŔŖŘȐȒɌṘṚṜṞⓇⱤꝚꞂꞦR]/g,
  396. S: /[SŚŜŞŠȘṠṢṤṦṨẞⓈⱾꞄꞨS]/g,
  397. T: /[TŢŤŦƬƮȚȾṪṬṮṰⓉꞆT]/g,
  398. TZ: /Ꜩ/g,
  399. U: /[UÙÚÛÜŨŪŬŮŰŲƯǓǕǗǙǛȔȖɄṲṴṶṸṺỤỦỨỪỬỮỰⓊU]/g,
  400. V: /[VƲɅṼṾⓋꝞV]/g,
  401. VY: /Ꝡ/g,
  402. W: /[WŴẀẂẄẆẈⓌⱲW]/g,
  403. X: /[XẊẌⓍX]/g,
  404. Y: /[YÝŶŸƳȲɎẎỲỴỶỸỾⓎY]/g,
  405. Z: /[ZŹŻŽƵȤẐẒẔⓏⱫⱿꝢZ]/g,
  406. a: /[aàáâãäåāăąǎǟǡǻȁȃȧɐḁẚạảấầẩẫậắằẳẵặⓐⱥa]/g,
  407. aa: /ꜳ/g,
  408. ae: /[æǣǽ]/g,
  409. ao: /ꜵ/g,
  410. au: /ꜷ/g,
  411. av: /[ꜹꜻ]/g,
  412. ay: /ꜽ/g,
  413. b: /[bƀƃɓḃḅḇⓑb]/g,
  414. c: /[cçćĉċčƈȼḉↄⓒꜿc]/g,
  415. d: /[dďđƌɖɗḋḍḏḑḓⓓꝺd]/g,
  416. dz: /[dždz]/g,
  417. e: /[eèéêëēĕėęěǝȅȇȩɇɛḕḗḙḛḝẹẻẽếềểễệⓔe]/g,
  418. f: /[fƒḟⓕꝼf]/g,
  419. g: /[gĝğġģǥǧǵɠᵹḡⓖꝿꞡg]/g,
  420. h: /[hĥħȟɥḣḥḧḩḫẖⓗⱨⱶh]/g,
  421. hv: /ƕ/g,
  422. i: /[iìíîïĩīĭįıǐȉȋɨḭḯỉịⓘi]/g,
  423. j: /[jĵǰɉⓙj]/g,
  424. k: /[kķƙǩḱḳḵⓚⱪꝁꝃꝅꞣk]/g,
  425. l: /[lĺļľŀłſƚɫḷḹḻḽⓛⱡꝇꝉꞁl]/g,
  426. lj: /lj/g,
  427. m: /[mɯɱḿṁṃⓜm]/g,
  428. n: /[nñńņňʼnƞǹɲṅṇṉṋⓝꞑꞥn]/g,
  429. nj: /nj/g,
  430. o: /[oòóôõöøōŏőơǒǫǭǿȍȏȫȭȯȱɔɵṍṏṑṓọỏốồổỗộớờởỡợⓞꝋꝍo]/g,
  431. oi: /ƣ/g,
  432. ou: /ȣ/g,
  433. oo: /ꝏ/g,
  434. p: /[pƥᵽṕṗⓟꝑꝓꝕp]/g,
  435. q: /[qɋⓠꝗꝙq]/g,
  436. r: /[rŕŗřȑȓɍɽṙṛṝṟⓡꝛꞃꞧr]/g,
  437. s: /[sßśŝşšșȿṡṣṥṧṩẛⓢꞅꞩs]/g,
  438. t: /[tţťŧƭțʈṫṭṯṱẗⓣⱦꞇt]/g,
  439. tz: /ꜩ/g,
  440. u: /[uùúûüũūŭůűųưǔǖǘǚǜȕȗʉṳṵṷṹṻụủứừửữựⓤu]/g,
  441. v: /[vʋʌṽṿⓥꝟv]/g,
  442. vy: /ꝡ/g,
  443. w: /[wŵẁẃẅẇẉẘⓦⱳw]/g,
  444. x: /[xẋẍⓧx]/g,
  445. y: /[yýÿŷƴȳɏẏẙỳỵỷỹỿⓨy]/g,
  446. z: /[zźżžƶȥɀẑẓẕⓩⱬꝣz]/g
  447. };
  448. let parsedString = input;
  449. Object.entries(removalMap).forEach(([key, value]) => {
  450. parsedString = parsedString.replace(value, key);
  451. });
  452. return parsedString;
  453. }
  454. function removeEmojis(input) {
  455. const baseEmojiRegex = /[\u2700-\u27bf]|\ud83c[\udde6-\uddff]{2}|[\ud800-\udbff][\udc00-\udfff]/;
  456. const variationSelectorRegex = /[\ufe0e\ufe0f]?/;
  457. const modifierRegex = /[\u0300-\u036f\u20d0-\u20f0\ufe20-\ufe23]|\ud83c[\udffb-\udfff]/;
  458. const zeroWidthJoinerRegex = /\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\u20d0-\u20f0\ufe20-\ufe23]|\ud83c[\udffb-\udfff])?/;
  459. const emojiRegex = new RegExp(
  460. `(?:${baseEmojiRegex.source})${variationSelectorRegex.source}(?:${modifierRegex.source})?(?:${zeroWidthJoinerRegex.source})*`,
  461. "g"
  462. );
  463. return input.replace(emojiRegex, "").trim();
  464. }
  465. function removeEmptyTags(input) {
  466. return input.replace(/<[^/>][^>]*>\s*<\/[^>]+>/gi, "");
  467. }
  468. function removeNonPrintableCharacters(input) {
  469. return input.replace(/[^\x20-\x7E´\u00C0-\u00FFˆ˜]+/g, "");
  470. }
  471. function removeTags(input) {
  472. return input.replace(/(<([^>]+)>)/gi, "");
  473. }
  474. function removeWhitespace(input) {
  475. return input.replace(/\r\n|\r|\n|\t/g, "").replace(/ +/g, " ");
  476. }
  477. function slugify(input) {
  478. return removeAccents(input).replace(/[\u0300-\u036f]/g, "").replace(/[()]/g, "").replace(/ /g, "-").replace(/["%<>\\^`{|}]/g, "").toLowerCase();
  479. }
  480. // src/date.ts
  481. var MINUTE = 60;
  482. var HOUR = MINUTE * 60;
  483. var DAY = HOUR * 24;
  484. var WEEK = DAY * 7;
  485. var MONTH = DAY * 30;
  486. var YEAR = 365 * DAY;
  487. function isIsoDate(input) {
  488. if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(input)) {
  489. return false;
  490. }
  491. const date = new Date(input);
  492. return date.toISOString() === input;
  493. }
  494. function isoDate(input) {
  495. if (typeof input !== "undefined") {
  496. return new Date(input).toISOString();
  497. }
  498. return (/* @__PURE__ */ new Date()).toISOString();
  499. }
  500. function isValidDate(input) {
  501. const date = import_is_lite2.default.date(input) ? input : new Date(input);
  502. return !Number.isNaN(date.getTime());
  503. }
  504. function now() {
  505. return Math.floor(Date.now() / 1e3);
  506. }
  507. function timeSince(input, options) {
  508. const {
  509. day = "day",
  510. days,
  511. hour = "hour",
  512. hours,
  513. minute = "minute",
  514. minutes,
  515. month = "month",
  516. months,
  517. prefix,
  518. second = "second",
  519. seconds,
  520. skipWeeks = false,
  521. suffix = "ago",
  522. week = "week",
  523. weeks,
  524. year = "year",
  525. years
  526. } = options || {};
  527. const date = typeof input === "number" ? input : timestamp(input);
  528. const diff = now() - date;
  529. let quantity = Math.floor(diff / YEAR);
  530. const output = (value, caption) => {
  531. let result = `${value} ${caption}`;
  532. if (prefix) {
  533. result = `${prefix} ${result}`;
  534. }
  535. if (suffix) {
  536. result = `${result} ${suffix}`;
  537. }
  538. return result;
  539. };
  540. if (quantity >= 1) {
  541. return output(quantity, pluralize(quantity, year, years));
  542. }
  543. quantity = Math.floor(diff / MONTH);
  544. if (quantity > 1) {
  545. return output(quantity, pluralize(quantity, month, months));
  546. }
  547. if (!skipWeeks) {
  548. quantity = Math.floor(diff / WEEK);
  549. if (quantity > 1) {
  550. return output(quantity, pluralize(quantity, week, weeks));
  551. }
  552. }
  553. quantity = Math.floor(diff / DAY);
  554. if (quantity >= 1) {
  555. return output(quantity, pluralize(quantity, day, days));
  556. }
  557. quantity = Math.floor(diff / HOUR);
  558. if (quantity >= 1) {
  559. return output(quantity, pluralize(quantity, hour, hours));
  560. }
  561. quantity = Math.floor(diff / MINUTE);
  562. if (quantity > 1) {
  563. return output(quantity, pluralize(quantity, minute, minutes));
  564. }
  565. return output(Math.floor(diff), pluralize(diff, second, seconds));
  566. }
  567. function timestamp(input) {
  568. if (!input) {
  569. return now();
  570. }
  571. const date = typeof input === "string" ? new Date(input) : input;
  572. return Math.floor(date.getTime() / 1e3);
  573. }
  574. // src/devices.ts
  575. function isDarkMode() {
  576. return !!window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
  577. }
  578. function isTouchDevice() {
  579. return !!window.matchMedia && window.matchMedia("(pointer: coarse)").matches;
  580. }
  581. function prefersReducedMotion() {
  582. return !!window.matchMedia && window.matchMedia("prefers-reduced-motion").matches;
  583. }
  584. // src/formatters.ts
  585. function formatBoolean(input) {
  586. return input ? "Yes" : "No";
  587. }
  588. function formatCPF(value) {
  589. const clearValue = cleanupNumericString(value);
  590. if (clearValue.length >= 10) {
  591. return `${clearValue.slice(0, 3)}.${clearValue.slice(3, 6)}.${clearValue.slice(
  592. 6,
  593. 9
  594. )}-${clearValue.slice(9, 11)}`;
  595. } else if (clearValue.length >= 7) {
  596. return `${clearValue.slice(0, 3)}.${clearValue.slice(3, 6)}.${clearValue.slice(6, 9)}`;
  597. } else if (clearValue.length >= 4) {
  598. return `${clearValue.slice(0, 3)}.${clearValue.slice(3, 6)}`;
  599. }
  600. return clearValue;
  601. }
  602. function formatDateLocale(input, options = {}) {
  603. const { locale = "en-GB", showTime = false } = options;
  604. const formatOptions = {
  605. year: "2-digit",
  606. month: "2-digit",
  607. day: "2-digit"
  608. };
  609. if (showTime) {
  610. formatOptions.hour = "2-digit";
  611. formatOptions.minute = "2-digit";
  612. }
  613. return new Date(input).toLocaleDateString(locale, formatOptions);
  614. }
  615. function formatMoney(input, options = {}) {
  616. const { decimalChar = ".", showCents = false, symbol = "$", thousandsChar = "," } = options;
  617. const isNegative = input < 0;
  618. const value = Math.abs(input);
  619. const [amount, cents] = value.toFixed(2).split(".");
  620. const padStart = amount.length > 3 ? amount.length % 3 : 0;
  621. const initial = amount.slice(0, padStart);
  622. const remain = amount.slice(padStart).replace(/(\d{3})(?=\d)/g, `$1${thousandsChar}`);
  623. let formatted = `${remain}`;
  624. if (initial) {
  625. formatted = `${initial}${thousandsChar}${remain}`;
  626. }
  627. if (cents !== "00" || showCents) {
  628. formatted += `${decimalChar}${cents}`;
  629. }
  630. return `${isNegative ? "-" : ""}${symbol}${formatted}`;
  631. }
  632. function formatPhoneBR(input) {
  633. const phone = input.replace(/\D/g, "");
  634. if (phone.length === 8) {
  635. return phone.replace(/^(\d{4})(\d{4}).*/, "$1-$2");
  636. }
  637. if (phone.length === 9) {
  638. return phone.replace(/^(\d{5})(\d{4}).*/, "$1-$2");
  639. }
  640. if (phone.length === 10 || phone.length === 11) {
  641. return phone.replace(/^(\d{2})(\d{4,5})(\d{4}).*/, "($1) $2-$3");
  642. }
  643. return phone;
  644. }
  645. function formatPhoneUS(input) {
  646. const phone = input.replace(/\D/g, "");
  647. if (phone.length === 10) {
  648. return phone.replace(/^(\d{3})(\d{3})(\d{4}).*/, "($1) $2-$3");
  649. }
  650. if (phone.length === 11 && phone.startsWith("1")) {
  651. return phone.replace(/^1(\d{3})(\d{3})(\d{4}).*/, "+1 ($1) $2-$3");
  652. }
  653. return phone;
  654. }
  655. function formatPostalCodeBR(value) {
  656. const clearValue = cleanupNumericString(value);
  657. if (clearValue.length >= 6) {
  658. return `${clearValue.slice(0, 5)}-${clearValue.slice(5, 8)}`;
  659. }
  660. return clearValue;
  661. }
  662. // src/functions.ts
  663. function demethodize(fn) {
  664. return (parameter, ...rest) => fn.apply(parameter, rest);
  665. }
  666. async function measureExecutionTime(callback) {
  667. const start = performance.now();
  668. const result = await callback();
  669. const end = performance.now();
  670. const total = end - start;
  671. console.log(`Completed in ${Math.ceil(total)} milliseconds`);
  672. return result;
  673. }
  674. function noop() {
  675. return void 0;
  676. }
  677. function once(fn) {
  678. let done = false;
  679. let result;
  680. return function Fn(...arguments_) {
  681. if (!done) {
  682. done = true;
  683. result = fn(...arguments_);
  684. }
  685. return result;
  686. };
  687. }
  688. function pipe(...fns) {
  689. return (input) => fns.reduce((previousValue, fn) => fn(previousValue), input);
  690. }
  691. // src/misc.ts
  692. var import_is_lite3 = __toESM(require("is-lite"));
  693. // src/numbers.ts
  694. function ceil(input, digits = 2) {
  695. const factor = 10 ** digits;
  696. return Math.ceil(input * factor) / factor;
  697. }
  698. function clamp(value, min = 0, max = 100) {
  699. return Math.min(Math.max(value, min), max);
  700. }
  701. function floor(input, digits = 2) {
  702. const factor = 10 ** digits;
  703. return Math.floor(input * factor) / factor;
  704. }
  705. function pad(input, length = 2) {
  706. return `${input}`.padStart(length, "0");
  707. }
  708. function randomNumber(min = 0, max = 10) {
  709. if (min >= max) {
  710. return max;
  711. }
  712. return Math.floor(Math.random() * (max - min + 1) + min);
  713. }
  714. function round(input, digits = 2) {
  715. const factor = 10 ** digits;
  716. return Math.round(input * factor) / factor;
  717. }
  718. // src/misc.ts
  719. function conditional(cases, defaultCase) {
  720. for (const [expression, callback] of cases) {
  721. if (expression) {
  722. return callback();
  723. }
  724. }
  725. return defaultCase?.();
  726. }
  727. async function copyToClipboard(input) {
  728. try {
  729. await navigator.clipboard.writeText(input);
  730. } catch {
  731. return false;
  732. }
  733. return true;
  734. }
  735. function getDataType(input, toLowerCase = false) {
  736. const dataTypeName = Object.prototype.toString.call(input).slice(8, -1);
  737. let output = dataTypeName;
  738. if (/HTML\w+Element/.test(dataTypeName)) {
  739. output = "HTMLElement";
  740. }
  741. return toLowerCase ? output.toLowerCase() : output;
  742. }
  743. function invariant(condition, message) {
  744. if (condition) {
  745. return;
  746. }
  747. const value = import_is_lite3.default.function(message) ? message() : message;
  748. throw new Error(value);
  749. }
  750. function isJSON(input) {
  751. try {
  752. JSON.parse(input);
  753. } catch {
  754. return false;
  755. }
  756. return true;
  757. }
  758. function isRequired(input = "parameter", Constructable = TypeError) {
  759. throw new Constructable(`"${input}" is required`);
  760. }
  761. function logger(type, title, data, options = {}) {
  762. const { collapsed = true, hideTimestamp = false, skip = false, typeColor = "gray" } = options;
  763. const groupMethod = collapsed ? console.groupCollapsed : console.group;
  764. const date = /* @__PURE__ */ new Date();
  765. const parts = [`%c ${type}`];
  766. const styles = [`color: ${typeColor}; font-weight: lighter;`, "color: inherit;"];
  767. if (!hideTimestamp) {
  768. styles.push("color: gray; font-weight: lighter;");
  769. }
  770. const time = `${pad(date.getHours(), 2)}:${pad(date.getMinutes(), 2)}:${pad(
  771. date.getSeconds(),
  772. 2
  773. )}`;
  774. parts.push(`%c${title}`);
  775. if (!hideTimestamp) {
  776. parts.push(`%c@ ${time}`);
  777. }
  778. if (!skip) {
  779. groupMethod(parts.join(" "), ...styles);
  780. console.log(data);
  781. console.groupEnd();
  782. }
  783. }
  784. function nullify(value) {
  785. return value ?? null;
  786. }
  787. function popupCenter(url, title, width, height) {
  788. const { screen, screenLeft, screenTop } = window;
  789. let screenWidth = window.innerWidth;
  790. let screenHeight = window.innerHeight;
  791. if (!screenWidth) {
  792. screenWidth = document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
  793. }
  794. if (!screenHeight) {
  795. screenHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
  796. }
  797. const left = screenWidth / 2 - width / 2 + screenLeft;
  798. const top = screenHeight / 2 - height / 2 + screenTop;
  799. const popup = window.open(
  800. url,
  801. title,
  802. `menubar=no,location=no,resizable=no,scrollbars=yees,status=no,width=${width},height=${height},top=${top}, left=${left}`
  803. );
  804. if (popup) {
  805. popup.focus();
  806. }
  807. return popup;
  808. }
  809. function px(value) {
  810. return import_is_lite3.default.number(value) || import_is_lite3.default.numericString(value) ? `${value}px` : value;
  811. }
  812. function unique(length = 8, options = {}) {
  813. const {
  814. includeLowercase = true,
  815. includeNumbers = true,
  816. includeSymbols = false,
  817. includeUppercase = true
  818. } = options;
  819. const lowercase = "abcdefghijklmnopqrstuvwxyz";
  820. const uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  821. const numbers = "0123456789";
  822. const symbols = "!?@#$%^&*+_-=:.~";
  823. let characters = "";
  824. if (includeLowercase) {
  825. characters += lowercase;
  826. }
  827. if (includeUppercase) {
  828. characters += uppercase;
  829. }
  830. if (includeNumbers) {
  831. characters += numbers;
  832. }
  833. if (includeSymbols) {
  834. characters += symbols;
  835. }
  836. let result = "";
  837. for (let index = length; index > 0; --index) {
  838. result += characters[Math.round(Math.random() * (characters.length - 1))];
  839. }
  840. return result;
  841. }
  842. function uuid() {
  843. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
  844. const r = Math.random() * 16 | 0;
  845. const v = c === "x" ? r : r & 3 | 8;
  846. return v.toString(16);
  847. });
  848. }
  849. // src/objects.ts
  850. var import_is_lite4 = __toESM(require("is-lite"));
  851. function cleanUpObject(input) {
  852. const output = {};
  853. for (const key in input) {
  854. if (input[key] !== void 0) {
  855. output[key] = input[key];
  856. }
  857. }
  858. return output;
  859. }
  860. function getNestedProperty(input, path) {
  861. if (!import_is_lite4.default.plainObject(input) && !import_is_lite4.default.array(input) || !path) {
  862. return input;
  863. }
  864. const segments = path.split(".");
  865. const { length } = segments;
  866. let output = input;
  867. for (let index = 0; index < length; index++) {
  868. const currentSegment = segments[index];
  869. const remainingSegments = segments.slice(index + 1);
  870. if (currentSegment === "+" && import_is_lite4.default.array(output) && remainingSegments.length === 1) {
  871. return output.map((d) => d[remainingSegments.join(".")]);
  872. }
  873. try {
  874. output = output[currentSegment];
  875. } catch {
  876. }
  877. }
  878. return output;
  879. }
  880. function invertKeys(input) {
  881. if (!import_is_lite4.default.plainObject(input)) {
  882. throw new TypeError("Expected an object");
  883. }
  884. const result = {};
  885. for (const [key, value] of Object.entries(input)) {
  886. result[value] = key;
  887. }
  888. return result;
  889. }
  890. function keyMirror(input) {
  891. if (!import_is_lite4.default.plainObject(input)) {
  892. throw new TypeError("Expected an object");
  893. }
  894. const output = {};
  895. for (const key in input) {
  896. if (!Object.prototype.hasOwnProperty.call(output, key)) {
  897. output[key] = key;
  898. }
  899. }
  900. return output;
  901. }
  902. function mergeProps(defaultProps, props) {
  903. const cleanProps = cleanUpObject(props);
  904. return { ...defaultProps, ...cleanProps };
  905. }
  906. function objectEntries(input) {
  907. return Object.entries(input);
  908. }
  909. function objectKeys(input) {
  910. return Object.keys(input);
  911. }
  912. function objectToArray(input, includeOnly) {
  913. if (!import_is_lite4.default.plainObject(input)) {
  914. throw new TypeError("Expected an object");
  915. }
  916. return Object.entries(input).filter(([, value]) => includeOnly ? typeof value === `${includeOnly}` : true).map(([key, value]) => ({ [key]: value }));
  917. }
  918. function omit(input, ...filter) {
  919. if (!import_is_lite4.default.plainObject(input)) {
  920. throw new TypeError("Expected an object");
  921. }
  922. const output = {};
  923. for (const key in input) {
  924. if ({}.hasOwnProperty.call(input, key)) {
  925. if (!filter.includes(key)) {
  926. output[key] = input[key];
  927. }
  928. }
  929. }
  930. return output;
  931. }
  932. function pick(input, ...filter) {
  933. if (!import_is_lite4.default.plainObject(input)) {
  934. throw new TypeError("Expected an object");
  935. }
  936. if (!filter.length) {
  937. return input;
  938. }
  939. const output = {};
  940. for (const key in input) {
  941. if ({}.hasOwnProperty.call(input, key)) {
  942. if (filter.includes(key)) {
  943. output[key] = input[key];
  944. }
  945. }
  946. }
  947. return output;
  948. }
  949. function queryStringFormat(input, options = {}) {
  950. const { addPrefix = false, encoder = encodeURIComponent, encodeValuesOnly = true } = options;
  951. if (!import_is_lite4.default.plainObject(input)) {
  952. throw new TypeError("input type isn't supported");
  953. }
  954. const isValidInput = Object.values(input).every((item) => {
  955. if (import_is_lite4.default.array(item)) {
  956. return item.every((d) => import_is_lite4.default.string(d) || import_is_lite4.default.number(d));
  957. }
  958. return import_is_lite4.default.string(item);
  959. });
  960. if (!isValidInput) {
  961. throw new TypeError("input format isn't supported");
  962. }
  963. const output = Object.entries(input).map(([key, value]) => {
  964. const nextKey = encodeValuesOnly ? key : encoder(key);
  965. const nextValue = import_is_lite4.default.array(value) ? value.map(encoder).join(",") : encoder(`${value}`);
  966. return `${nextKey}=${nextValue}`;
  967. }).join("&");
  968. return `${addPrefix ? "?" : ""}${output}`;
  969. }
  970. function queryStringParse(input) {
  971. let search = input;
  972. if (input.slice(0, 1) === "?") {
  973. search = input.slice(1);
  974. }
  975. return search.split("&").reduce((acc, d) => {
  976. const [key, value] = d.split("=");
  977. acc[decodeURIComponent(key)] = decodeURIComponent(value);
  978. return acc;
  979. }, {});
  980. }
  981. function sortObjectKeys(input) {
  982. return objectKeys(input).sort().reduce((acc, key) => {
  983. acc[key] = input[key];
  984. return acc;
  985. }, {});
  986. }
  987. // src/statistics.ts
  988. var import_is_lite5 = __toESM(require("is-lite"));
  989. function mean(input, precision) {
  990. const output = input.reduce((sum, value) => sum + value, 0) / input.length;
  991. if (import_is_lite5.default.number(precision)) {
  992. return round(output, precision);
  993. }
  994. return output;
  995. }
  996. function median(input) {
  997. const sorted = [...input].sort((a, b) => a - b);
  998. const middle = Math.floor(sorted.length / 2);
  999. if (sorted.length % 2 === 0) {
  1000. return (sorted[middle - 1] + sorted[middle]) / 2;
  1001. }
  1002. return sorted[middle];
  1003. }
  1004. function mode(input) {
  1005. const count = /* @__PURE__ */ new Map();
  1006. for (const value of input) {
  1007. const current = count.get(value) ?? 0;
  1008. count.set(value, current + 1);
  1009. }
  1010. const sorted = [...count.entries()].sort((a, b) => b[1] - a[1]);
  1011. return sorted[0][0];
  1012. }
  1013. // src/validators.ts
  1014. function isValidCPF(value) {
  1015. if (!value) {
  1016. return false;
  1017. }
  1018. const newValue = value.replace(/[.-]/g, "");
  1019. let sum = 0;
  1020. let rest;
  1021. if (/^(\d)\1+$/.test(newValue)) {
  1022. return false;
  1023. }
  1024. for (let index = 1; index <= 9; index++) {
  1025. sum += parseInt(newValue.substring(index - 1, index), 10) * (11 - index);
  1026. }
  1027. rest = sum * 10 % 11;
  1028. if (rest === 10 || rest === 11) {
  1029. rest = 0;
  1030. }
  1031. if (rest !== parseInt(newValue.substring(9, 10), 10)) {
  1032. return false;
  1033. }
  1034. sum = 0;
  1035. for (let index = 1; index <= 10; index++) {
  1036. sum += parseInt(newValue.substring(index - 1, index), 10) * (12 - index);
  1037. }
  1038. rest = sum * 10 % 11;
  1039. if (rest === 10 || rest === 11) {
  1040. rest = 0;
  1041. }
  1042. return rest === parseInt(newValue.substring(10, 11), 10);
  1043. }
  1044. function isValidEmail(value) {
  1045. return /^[\w%+.-]+@[\d.a-z-]+\.[a-z]{2,}$/i.test(value);
  1046. }
  1047. function validatePassword(password, options) {
  1048. const {
  1049. maxLength = 64,
  1050. maxLengthMessage = "Password must be a maximum of 64 characters",
  1051. minLength = 6,
  1052. minLengthMessage = "Password must be at least 6 characters long",
  1053. regex = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!#$%&*?@^]).*$/,
  1054. requiredCharactersMessage = "Password must have at least 1 number, 1 lowercase, 1 uppercase and 1 special character"
  1055. } = options || {};
  1056. if (password.length < minLength) {
  1057. throw new Error(minLengthMessage);
  1058. }
  1059. if (password.length > maxLength) {
  1060. throw new Error(maxLengthMessage);
  1061. }
  1062. if (!regex.test(password)) {
  1063. throw new Error(requiredCharactersMessage);
  1064. }
  1065. return true;
  1066. }
  1067. // src/types.ts
  1068. var types_exports = {};
  1069. // Annotate the CommonJS export names for ESM import in node:
  1070. 0 && (module.exports = {
  1071. ASYNC_STATUS,
  1072. DAY,
  1073. HOUR,
  1074. MINUTE,
  1075. MONTH,
  1076. Types,
  1077. WEEK,
  1078. YEAR,
  1079. capitalize,
  1080. ceil,
  1081. clamp,
  1082. cleanUpObject,
  1083. cleanupHTML,
  1084. cleanupNumericString,
  1085. cleanupURI,
  1086. conditional,
  1087. copyToClipboard,
  1088. cors,
  1089. createArray,
  1090. demethodize,
  1091. floor,
  1092. formatBoolean,
  1093. formatCPF,
  1094. formatDateLocale,
  1095. formatMoney,
  1096. formatPhoneBR,
  1097. formatPhoneUS,
  1098. formatPostalCodeBR,
  1099. getDataType,
  1100. getInitials,
  1101. getNestedProperty,
  1102. getRandomItem,
  1103. invariant,
  1104. invertKeys,
  1105. isDarkMode,
  1106. isIsoDate,
  1107. isJSON,
  1108. isRequired,
  1109. isTouchDevice,
  1110. isValidCPF,
  1111. isValidDate,
  1112. isValidEmail,
  1113. isoDate,
  1114. keyMirror,
  1115. logger,
  1116. mean,
  1117. measureExecutionTime,
  1118. median,
  1119. mergeProps,
  1120. mode,
  1121. noop,
  1122. now,
  1123. nullify,
  1124. objectEntries,
  1125. objectKeys,
  1126. objectToArray,
  1127. omit,
  1128. once,
  1129. pad,
  1130. pick,
  1131. pipe,
  1132. pluralize,
  1133. poll,
  1134. popupCenter,
  1135. prefersReducedMotion,
  1136. px,
  1137. queryStringFormat,
  1138. queryStringParse,
  1139. quickSort,
  1140. randomNumber,
  1141. removeAccents,
  1142. removeDuplicates,
  1143. removeEmojis,
  1144. removeEmptyTags,
  1145. removeNonPrintableCharacters,
  1146. removeTags,
  1147. removeWhitespace,
  1148. request,
  1149. round,
  1150. shuffle,
  1151. sleep,
  1152. slugify,
  1153. sortByLocaleCompare,
  1154. sortByPrimitive,
  1155. sortComparator,
  1156. sortObjectKeys,
  1157. splitIntoChunks,
  1158. timeSince,
  1159. timestamp,
  1160. unique,
  1161. uuid,
  1162. validatePassword
  1163. });
  1164. //# sourceMappingURL=index.js.map