UNPKG

@techmely/utils

Version:

Collection of helpful JavaScript / TypeScript utils

1,786 lines (1,749 loc) 50 kB
/*! * @techmely/utils * Copyright(c) 2021-2024 Techmely <techmely.creation@gmail.com> * MIT Licensed */ "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { CheckBoundary: () => CheckBoundary, CookieService: () => CookieService, DigitLength: () => DigitLength, Divide: () => Divide, EnableBoundaryChecking: () => EnableBoundaryChecking, Float2Fixed: () => Float2Fixed, HTTP_ACCEPTED: () => HTTP_ACCEPTED, HTTP_ALREADY_REPORTED: () => HTTP_ALREADY_REPORTED, HTTP_BAD_GATEWAY: () => HTTP_BAD_GATEWAY, HTTP_BAD_REQUEST: () => HTTP_BAD_REQUEST, HTTP_CF_A_TIMEOUT_OCCURRED: () => HTTP_CF_A_TIMEOUT_OCCURRED, HTTP_CF_CONNECTION_TIMED_OUT: () => HTTP_CF_CONNECTION_TIMED_OUT, HTTP_CF_INVALID_SSL_CERTIFICATE: () => HTTP_CF_INVALID_SSL_CERTIFICATE, HTTP_CF_ORIGIN_IS_UNREACHABLE: () => HTTP_CF_ORIGIN_IS_UNREACHABLE, HTTP_CF_RAILGUN_ERROR: () => HTTP_CF_RAILGUN_ERROR, HTTP_CF_SSL_HANDSHAKE_FAILED: () => HTTP_CF_SSL_HANDSHAKE_FAILED, HTTP_CF_UNKNOWN: () => HTTP_CF_UNKNOWN, HTTP_CF_WEB_SERVER_IS_DOWN: () => HTTP_CF_WEB_SERVER_IS_DOWN, HTTP_CONFLICT: () => HTTP_CONFLICT, HTTP_CONTINUE: () => HTTP_CONTINUE, HTTP_CREATED: () => HTTP_CREATED, HTTP_EARLY_HINTS: () => HTTP_EARLY_HINTS, HTTP_EXPECTATION_FAILED: () => HTTP_EXPECTATION_FAILED, HTTP_FAILED_DEPENDENCY: () => HTTP_FAILED_DEPENDENCY, HTTP_FORBIDDEN: () => HTTP_FORBIDDEN, HTTP_FOUND: () => HTTP_FOUND, HTTP_GATEWAY_TIMEOUT: () => HTTP_GATEWAY_TIMEOUT, HTTP_GONE: () => HTTP_GONE, HTTP_IM_USED: () => HTTP_IM_USED, HTTP_INSUFFICIENT_STORAGE: () => HTTP_INSUFFICIENT_STORAGE, HTTP_INTERNAL_SERVER_ERROR: () => HTTP_INTERNAL_SERVER_ERROR, HTTP_I_AM_A_TEAPOT: () => HTTP_I_AM_A_TEAPOT, HTTP_LENGTH_REQUIRED: () => HTTP_LENGTH_REQUIRED, HTTP_LOCKED: () => HTTP_LOCKED, HTTP_LOOP_DETECTED: () => HTTP_LOOP_DETECTED, HTTP_METHOD_NOT_ALLOWED: () => HTTP_METHOD_NOT_ALLOWED, HTTP_MISDIRECTED_REQUEST: () => HTTP_MISDIRECTED_REQUEST, HTTP_MOVED_PERMANENTLY: () => HTTP_MOVED_PERMANENTLY, HTTP_MULTIPLE_CHOICES: () => HTTP_MULTIPLE_CHOICES, HTTP_MULTI_STATUS: () => HTTP_MULTI_STATUS, HTTP_NETWORK_AUTHENTICATION_REQUIRED: () => HTTP_NETWORK_AUTHENTICATION_REQUIRED, HTTP_NON_AUTHORITATIVE_INFORMATION: () => HTTP_NON_AUTHORITATIVE_INFORMATION, HTTP_NOT_ACCEPTABLE: () => HTTP_NOT_ACCEPTABLE, HTTP_NOT_EXTENDED: () => HTTP_NOT_EXTENDED, HTTP_NOT_FOUND: () => HTTP_NOT_FOUND, HTTP_NOT_IMPLEMENTED: () => HTTP_NOT_IMPLEMENTED, HTTP_NOT_MODIFIED: () => HTTP_NOT_MODIFIED, HTTP_NO_CONTENT: () => HTTP_NO_CONTENT, HTTP_OK: () => HTTP_OK, HTTP_PARTIAL_CONTENT: () => HTTP_PARTIAL_CONTENT, HTTP_PAYMENT_REQUIRED: () => HTTP_PAYMENT_REQUIRED, HTTP_PERMANENTLY_REDIRECT: () => HTTP_PERMANENTLY_REDIRECT, HTTP_PRECONDITION_FAILED: () => HTTP_PRECONDITION_FAILED, HTTP_PRECONDITION_REQUIRED: () => HTTP_PRECONDITION_REQUIRED, HTTP_PROCESSING: () => HTTP_PROCESSING, HTTP_PROXY_AUTHENTICATION_REQUIRED: () => HTTP_PROXY_AUTHENTICATION_REQUIRED, HTTP_REQUESTED_RANGE_NOT_SATISFIABLE: () => HTTP_REQUESTED_RANGE_NOT_SATISFIABLE, HTTP_REQUEST_ENTITY_TOO_LARGE: () => HTTP_REQUEST_ENTITY_TOO_LARGE, HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE: () => HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, HTTP_REQUEST_TIMEOUT: () => HTTP_REQUEST_TIMEOUT, HTTP_REQUEST_URI_TOO_LONG: () => HTTP_REQUEST_URI_TOO_LONG, HTTP_RESERVED: () => HTTP_RESERVED, HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL: () => HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL, HTTP_RESET_CONTENT: () => HTTP_RESET_CONTENT, HTTP_SEE_OTHER: () => HTTP_SEE_OTHER, HTTP_SERVICE_UNAVAILABLE: () => HTTP_SERVICE_UNAVAILABLE, HTTP_SWITCHING_PROTOCOLS: () => HTTP_SWITCHING_PROTOCOLS, HTTP_TEMPORARY_REDIRECT: () => HTTP_TEMPORARY_REDIRECT, HTTP_TOO_MANY_REQUESTS: () => HTTP_TOO_MANY_REQUESTS, HTTP_UNAUTHORIZED: () => HTTP_UNAUTHORIZED, HTTP_UNAVAILABLE_FOR_LEGAL_REASONS: () => HTTP_UNAVAILABLE_FOR_LEGAL_REASONS, HTTP_UNPROCESSABLE_ENTITY: () => HTTP_UNPROCESSABLE_ENTITY, HTTP_UNSUPPORTED_MEDIA_TYPE: () => HTTP_UNSUPPORTED_MEDIA_TYPE, HTTP_UPGRADE_REQUIRED: () => HTTP_UPGRADE_REQUIRED, HTTP_USE_PROXY: () => HTTP_USE_PROXY, HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL: () => HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL, HTTP_VERSION_NOT_SUPPORTED: () => HTTP_VERSION_NOT_SUPPORTED, Minus: () => Minus, PCancelable: () => PCancelable, PDefer: () => PDefer, PQueue: () => PQueue, PTimeOut: () => PTimeOut, Plus: () => Plus, Round: () => Round, SortDirection: () => SortDirection, Strip: () => Strip, Times: () => Times, _process: () => _process, add: () => add, alphaHex: () => alphaHex, cacheStringFunction: () => cacheStringFunction, camel2snake: () => camel2snake, camelize: () => camelize, cancelIdleCallback: () => cancelIdleCallback, capitalizeFirst: () => capitalizeFirst, chunk: () => chunk, clamp: () => clamp, clearDelay: () => clearDelay, clockwise: () => clockwise, convertHrTime: () => convertHrTime, createCachedImport: () => createCachedImport, createDelay: () => createDelay, cutString: () => cutString, deepMerge: () => deepMerge, delay: () => delay, dist: () => dist, dist2: () => dist2, div: () => div, downloadByData: () => downloadByData, dpr: () => dpr, emailRegex: () => emailRegex, emitter: () => emitter, envs: () => envs, escapedSpaceCharactersRegex: () => escapedSpaceCharactersRegex, findLastIndex: () => findLastIndex, formatBytes: () => formatBytes, formatDecimals: () => formatDecimals, formatLot10Volume: () => formatLot10Volume, formatNumber: () => formatNumber, getQuarter: () => getQuarter, getRandomInt: () => getRandomInt, getRandomIntInclusive: () => getRandomIntInclusive, getRandomString: () => getRandomString, getStrokeRadius: () => getStrokeRadius, groupBy: () => groupBy, hexColor: () => hexColor, hyphenate: () => hyphenate, intToBuffer: () => intToBuffer, intToHex: () => intToHex, invariant: () => invariant, isAndroid: () => isAndroid, isArray: () => isArray, isBase64: () => isBase64, isBoolean: () => isBoolean, isBrowser: () => isBrowser, isCI: () => isCI, isCrawler: () => isCrawler, isDate: () => isDate, isDef: () => isDef, isEmpties: () => isEmpties, isEmpty: () => isEmpty, isEqual: () => isEqual, isFalsy: () => isFalsy, isFunction: () => isFunction, isHex: () => isHex, isKeyOf: () => isKeyOf, isLeft: () => isLeft, isLinux: () => isLinux, isMacOS: () => isMacOS, isMap: () => isMap, isMobile: () => isMobile, isNodeDev: () => isNodeDev, isNodeProd: () => isNodeProd, isNodeTest: () => isNodeTest, isNotEmpties: () => isNotEmpties, isNotEmpty: () => isNotEmpty, isNotNull: () => isNotNull, isNumber: () => isNumber, isObject: () => isObject, isPngImage: () => isPngImage, isPrimitive: () => isPrimitive, isPromise: () => isPromise, isSameMonth: () => isSameMonth, isSet: () => isSet, isStream: () => isStream, isString: () => isString, isSymbol: () => isSymbol, isToday: () => isToday, isUndef: () => isUndef, isValidEmail: () => isValidEmail, isValidUrl: () => isValidUrl, isValidVnPhone: () => isValidVnPhone, isWindows: () => isWindows, len: () => len, len2: () => len2, lerp: () => lerp, listenCookieChange: () => listenCookieChange, lrp: () => lrp, med: () => med, mul: () => mul, multilineCommentsRegex: () => multilineCommentsRegex, neg: () => neg, nodeENV: () => nodeENV, noop: () => noop, normalize: () => normalize, objectCamel2Snake: () => objectCamel2Snake, objectEntries: () => objectEntries, objectKeys: () => objectKeys, objectMap: () => objectMap, parseCookie: () => parseCookie, per: () => per, percentToHex: () => percentToHex, pick: () => pick, platform: () => platform, process: () => process2, rangeDelay: () => rangeDelay, remove: () => remove, removeEmptyObj: () => removeEmptyObj, removeUndefObj: () => removeUndefObj, requestIdleCallback: () => requestIdleCallback, rotAround: () => rotAround, sample: () => sample, serializeCookie: () => serializeCookie, shuffle: () => shuffle, singlelineCommentsRegex: () => singlelineCommentsRegex, singleton: () => singleton, sleep: () => sleep, slugify: () => slugify, snake2camel: () => snake2camel, sortByDate: () => sortByDate, sortData: () => sortData, streamAsyncIterable: () => streamAsyncIterable, sub: () => sub, suffixAmPm: () => suffixAmPm, sum: () => sum, take: () => take, timeSpan: () => timeSpan, timeSpanBr: () => timeSpanBr, toBoolean: () => toBoolean, toPointsArray: () => toPointsArray, uni: () => uni, unique: () => unique, uniqueObj: () => uniqueObj, urlRegex: () => urlRegex, vec: () => vec, vietnamPhoneRegex: () => vietnamPhoneRegex }); module.exports = __toCommonJS(src_exports); // src/array.ts function unique(array) { return [...new Set(array)]; } function uniqueObj(items, uniqueKey) { const map = /* @__PURE__ */ new Map(); for (const item of items) { const key = item[uniqueKey]; if (!map.has(key)) { map.set(key, item); } } return [...map.values()]; } function take(array, limit) { return array.slice(0, limit); } function findLastIndex(array, predicate) { let l = array.length; while (l--) { if (predicate(array[l], l, array)) { return l; } } return -1; } function groupBy(list, keyGetter) { const map = /* @__PURE__ */ new Map(); for (const item of list) { const key = keyGetter(item); const collection = map.get(key); if (collection) { collection.push(item); } else { map.set(key, [item]); } } return map; } function remove(arr, el) { const i = arr.indexOf(el); if (i > -1) { arr.splice(i, 1); } } function sample(arr, count) { return Array.from({ length: count }, (_) => arr[Math.round(Math.random() * (arr.length - 1))]); } function shuffle(array) { for (let i = array.length - 1; i > 0; i--) { const factor = Math.floor(Math.random() * (i + 1)); [array[i], array[factor]] = [array[factor], array[i]]; } return array; } function chunk(array, size = 1) { if (!array || array.length === 0) { return []; } const chunkLength = Math.ceil(array.length / size); return Array.from({ length: chunkLength }, (_v, i) => { const start = i * size; return array.slice(start, start + size); }); } function normalize(array, key) { if (!array || array.length === 0) return {}; return array.reduce((acc, cur) => { const keyValue = cur[key]; if (keyValue) { return Object.assign(acc, { [keyValue]: cur }); } return acc; }, {}); } // src/convert.ts function intToHex(integer) { if (integer < 0) { throw new Error("Invalid integer as argument, must be unsigned!"); } const hex = integer.toString(16); return hex.length % 2 ? `0${hex}` : hex; } function intToBuffer(integer) { const hex = intToHex(integer); return Buffer.from(hex, "hex"); } function toBoolean(val) { return val ? val !== "false" : false; } function convertHrTime(hrtime) { const nanoseconds = hrtime; const number = Number(nanoseconds); const milliseconds = number / 1e6; const seconds = number / 1e9; return { seconds, milliseconds, nanoseconds }; } // src/env.ts var import_meta = {}; var _envShim = /* @__PURE__ */ Object.create(null); var _getEnv = (useShim) => globalThis.process?.env || // Node.js/Bun import_meta.env || // Vite env globalThis.Deno?.env.toObject() || // Deno env globalThis.__env__ || // Custom env (useShim ? _envShim : globalThis); var envs = new Proxy(_envShim, { get(_, prop) { const env = _getEnv(); return env[prop] ?? _envShim[prop]; }, has(_, prop) { const env = _getEnv(); return prop in env || prop in _envShim; }, set(_, prop, value) { const env = _getEnv(true); env[prop] = value; return true; }, deleteProperty(_, prop) { if (!prop) { return false; } const env = _getEnv(true); delete env[prop]; return true; }, ownKeys() { const env = _getEnv(); return Object.keys(env); } }); var nodeENV = typeof process !== "undefined" && process.env && process.env.NODE_ENV || ""; // src/process.ts var _process = globalThis.process || /* @__PURE__ */ Object.create(null); var processShims = { versions: {} }; var process2 = new Proxy(_process, { get(target, prop) { if (prop === "env") { return envs; } if (prop in target) { return target[prop]; } if (prop in processShims) { return processShims[prop]; } } }); var platform = _process.platform || ""; // src/is.ts function isNotNull(v) { return v !== null; } function isArray(val) { return val && Array.isArray(val); } function isPrimitive(value) { if (value === null) { return true; } return !["array", "function", "object"].includes(typeof value); } var isDef = (val) => typeof val !== "undefined"; var isUndef = (val) => !isDef(val); var isBoolean = (val) => typeof val === "boolean"; var isFunction = (val) => typeof val === "function"; var isNumber = (val) => toString.call(val) === "[object Number]"; var isString = (val) => typeof val === "string"; var isObject = (val) => toString.call(val) === "[object Object]"; var isMap = (val) => toString.call(val) === "[object Map]"; var isSet = (val) => toString.call(val) === "[object Set]"; var isDate = (val) => toString.call(val) === "[object Date]"; var isSymbol = (val) => typeof val === "symbol"; var isPromise = (val) => { return isObject(val) && isFunction(val.then) && isFunction(val.catch); }; var isFalsy = (val) => isNotNull(val) && isDef(val) && isNotEmpty(val); var isStream = (val) => val !== null && typeof val === "object" && typeof val.pipe === "function"; var isBrowser = typeof window !== "undefined"; var isEmptyArr = (array) => array?.length === 0; function isEmpty(val) { if (!val) { return true; } if (isArray(val)) { return isEmptyArr(val); } if (isString(val)) { return val.trim().length === 0; } if (val instanceof Map || val instanceof Set) { return val.size === 0; } if (isObject(val)) { return Object.keys(val).length === 0; } return false; } function isNotEmpty(val) { return !isEmpty(val); } function isNotEmpties(...args) { if (args.length > 1) { return args.reduce((a, b) => a && isNotEmpty(b), true); } return false; } function isEmpties(...args) { if (args.length > 1) { return args.reduce((a, b) => a && isEmpty(b), true); } return false; } function isPngImage(buffer) { if (!buffer || buffer.length < 8) { return false; } return buffer[0] === 137 && buffer[1] === 80 && buffer[2] === 78 && buffer[3] === 71 && buffer[4] === 13 && buffer[5] === 10 && buffer[6] === 26 && buffer[7] === 10; } var isBase64 = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/; var isAndroid = isBrowser ? /(android)/i.test(navigator.userAgent) : false; var match = isBrowser ? window.matchMedia || window.msMatchMedia : void 0; var isMobile = isBrowser ? match?.("(pointer:coarse)")?.matches : false; var isCrawler = isBrowser && (!("onscroll" in window) || /(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent)); var isCI = toBoolean(envs.CI); var isNodeTest = nodeENV === "test" || toBoolean(envs.TEST); var isNodeProd = nodeENV === "production"; var isNodeDev = nodeENV === "dev" || nodeENV === "development"; var isWindows = /^win/i.test(platform); var isLinux = /^linux/i.test(platform); var isMacOS = /^darwin/i.test(platform); // src/browser.ts function requestIdleCallbackShim(cb) { const start = Date.now(); return setTimeout(() => { cb({ didTimeout: false, timeRemaining: () => Math.max(0, 50 - (Date.now() - start)) }); }, 1); } function cancelIdleCallbackShim(id) { clearTimeout(id); } var requestIdleCallback = isBrowser ? window.requestIdleCallback || requestIdleCallbackShim : requestIdleCallbackShim; var cancelIdleCallback = isBrowser ? window.cancelIdleCallback || cancelIdleCallbackShim : cancelIdleCallbackShim; // src/bytes.ts var formatBytes = (bytes, options) => { const sizes = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; const { numberOfDecimals = 0 } = options ?? {}; if (!bytes || bytes <= 0) { return "0 bytes"; } if (bytes === 1) { return "1 byte"; } const base = 1e3; const exponent = Math.trunc(Math.log(bytes) / Math.log(base)); const rawValue = bytes / base ** exponent; let [whole, partial = ""] = rawValue.toString().split("."); if (numberOfDecimals > 0) { const count = numberOfDecimals - partial.length; if (count > 0) { partial += "0".repeat(count); } whole += `.${partial.slice(0, numberOfDecimals)}`; } const abbreviationSuffix = sizes[exponent]; return `${whole} ${abbreviationSuffix}`; }; var formatDecimals = (bytes = 0) => bytes >= 1e9 ? 2 : 0; // src/calculate.ts function clamp(n, min, max) { return Math.min(max, Math.max(min, n)); } function sum(...args) { return [...args].flat(1).reduce((a, b) => a + b, 0); } function lerp(y1, y2, mu) { return y1 * (1 - mu) + y2 * mu; } // src/cache.ts var lazyImportCache = /* @__PURE__ */ new Map(); function createCachedImport(name, imp) { return () => { const cached = lazyImportCache.get(name); if (cached) return cached; const promise = imp().then((module2) => { lazyImportCache.set(name, module2); return module2; }); lazyImportCache.set(name, promise); return promise; }; } var cacheStringFunction = (fn) => { const cache = /* @__PURE__ */ Object.create(null); return (str) => { const hit = cache[str]; return hit || (cache[str] = fn(str)); }; }; // src/regex.ts var emailRegex = new RegExp( /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z-]+\.)+[A-Za-z]{2,}))$/ ); var isValidEmail = (email) => emailRegex.test(email); var vietnamPhoneRegex = new RegExp(/^0(\d{9})$/); var isValidVnPhone = (phone) => vietnamPhoneRegex.test(phone); var urlRegex = /(((^https?:(?:\/\/)?)(?:[\w$&+,:;=-]+@)?[\d.A-Za-z-]+(?::\d+)?|(?:www.|[\w$&+,:;=-]+@)[\d.A-Za-z-]+)((?:\/[\w%+./~-]*)?\??[\w%&+.;=@-]*(?:#\w*)?)?)$/; var isValidUrl = (path) => urlRegex.test(path); var hexColor = /^#(([\da-f]{2}){3,4})$/; var multilineCommentsRegex = /\/\*(.|[\r\n])*?\*\//gm; var singlelineCommentsRegex = /\/\/.*/g; var escapedSpaceCharactersRegex = /( |\\t|\\n|\\f|\\r)+/g; // src/colors.ts function isHex(hex) { return hexColor.test(hex); } function percentToHex(percent) { if (percent < 0 || percent > 100) { throw new Error("Value must in range [0, 100]"); } const intValue = Math.round(percent / 100 * 255); const hexValue = intValue.toString(16); return hexValue.padStart(2, "0").toUpperCase(); } var HEX_LENGTH = 6; var HEX_OPACITY_LENGTH = 8; function alphaHex(hex, alpha) { if (!hex) { throw new Error("Hex value is required"); } if (hex.length === HEX_OPACITY_LENGTH) { return `${hex.slice(0, HEX_LENGTH)}${percentToHex(alpha)}`; } return `${hex}${percentToHex(alpha)}`; } // src/cookie.ts var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; function parseCookie(str, options) { if (typeof str !== "string") { throw new TypeError("argument str must be a string"); } const obj = {}; const opt = options || {}; const dec = opt.decode || decode; let index = 0; while (index < str.length) { const eqIdx = str.indexOf("=", index); if (eqIdx === -1) { break; } let endIdx = str.indexOf(";", index); if (endIdx === -1) { endIdx = str.length; } else if (endIdx < eqIdx) { index = str.lastIndexOf(";", eqIdx - 1) + 1; continue; } const key = str.slice(index, eqIdx).trim(); if (obj[key] === void 0) { let val = str.slice(eqIdx + 1, endIdx).trim(); if (val.charCodeAt(0) === 34) { val = val.slice(1, -1); } obj[key] = tryDecode(val, dec); } index = endIdx + 1; } return obj; } function serializeCookie(name, value, options) { const opt = options || {}; const enc = opt.encode || encode; if (typeof enc !== "function") { throw new TypeError("option encode is invalid"); } if (!fieldContentRegExp.test(name)) { throw new TypeError("argument name is invalid"); } const encValue = enc(value); if (value && !fieldContentRegExp.test(value)) { throw new TypeError("argument val is invalid"); } let str = `${name}=${encValue}`; if (null != opt.maxAge) { const maxAge = opt.maxAge - 0; if (Number.isNaN(maxAge) || !Number.isFinite(maxAge)) { throw new TypeError("option maxAge is invalid"); } str += `; Max-Age=${Math.floor(maxAge)}`; } if (opt.domain) { if (!fieldContentRegExp.test(opt.domain)) { throw new TypeError("option domain is invalid"); } str += `; Domain=${opt.domain}`; } if (opt.path) { if (!fieldContentRegExp.test(opt.path)) { throw new TypeError("option path is invalid"); } str += `; Path=${opt.path}`; } if (opt.expires) { const expires = opt.expires; if (!isDate(expires) || Number.isNaN(expires.valueOf())) { throw new TypeError("option expires is invalid"); } str += `; Expires=${expires.toUTCString()}`; } if (opt.httpOnly) { str += "; HttpOnly"; } if (opt.secure) { str += "; Secure"; } if (opt.priority) { const priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority; switch (priority) { case "low": str += "; Priority=Low"; break; case "medium": str += "; Priority=Medium"; break; case "high": str += "; Priority=High"; break; default: throw new TypeError("option priority is invalid"); } } if (opt.sameSite) { const sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite; switch (sameSite) { case true: str += "; SameSite=Strict"; break; case "lax": str += "; SameSite=Lax"; break; case "strict": str += "; SameSite=Strict"; break; case "none": str += "; SameSite=None"; break; default: throw new TypeError("option sameSite is invalid"); } } return str; } function decode(str) { return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str; } function encode(val) { return encodeURIComponent(val); } function tryDecode(str, decode2) { try { return decode2(str); } catch (e) { return str; } } var listenCookieChange = (callback, interval = 500) => { let lastCookie = document.cookie; setInterval(() => { const { cookie } = document; if (cookie !== lastCookie) { try { callback({ oldCookie: parseCookie(lastCookie), newCookie: parseCookie(cookie) }); } finally { lastCookie = cookie; } } }, interval); }; var CookieService = class { constructor(nodeEnv, env, cookieDomain) { this.nodeEnv = nodeEnv; this.env = env; this.domain = cookieDomain; this.tokenName = `token_${this.env}`; } get(name, options) { if (typeof window === "undefined") return void 0; try { const cookies = parseCookie(document.cookie, options); return cookies[name]; } catch (error) { console.error({ error }); return void 0; } } set(key, value, options) { const defaultOptions = { secure: true, path: "/", domain: this.domain, priority: "Medium", httpOnly: false, ...options }; try { document.cookie = serializeCookie(key, value, defaultOptions); } catch (error) { console.error({ error }); } } setToken(token) { document.cookie = this.env === "development" ? `${this.tokenName}=${token}; path=/; Secure` : `${this.tokenName}=${token}; path=/; Domain=${this.domain}; Secure`; } getToken() { const token = this.get(this.tokenName); return token; } clearToken() { document.cookie = this.env === "development" ? `${this.tokenName}=; path=/; Secure` : `${this.tokenName}=; path=/; Domain=${this.domain}; Secure`; } }; // src/date.ts var isSameDay = (date1, date2) => { if (!(date1 && date2)) { return false; } return date1.getDate() === date2.getDate() && date1.getMonth() === date2.getMonth() && date1.getFullYear() === date2.getFullYear(); }; var isSameMonth = (date1, date2) => { if (!(date1 && date2)) { return false; } return date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth(); }; var isToday = (date) => isSameDay(date, /* @__PURE__ */ new Date()); var SortDirection = /* @__PURE__ */ ((SortDirection2) => { SortDirection2["ASC"] = "ASC"; SortDirection2["DESC"] = "DESC"; return SortDirection2; })(SortDirection || {}); function sortByDate(a, b, key, direction = "ASC" /* ASC */) { if (a[key] < b[key]) { return direction === "ASC" /* ASC */ ? 1 : -1; } if (a[key] > b[key]) { return direction === "ASC" /* ASC */ ? -1 : 1; } return 0; } function sortData(a, b, direction = "ASC" /* ASC */, options) { let result = 0; const { locale = "vi", shouldIgnoreZero = false } = options || {}; if (shouldIgnoreZero) { if (a === b) { return 0; } if (a === 0) { return 1; } if (b === 0) { return -1; } } if (isNumber(a) && isNumber(b)) { const aParsed = a?.toString() ?? ""; const bParsed = b?.toString() ?? ""; result = isNumber(a) && isNumber(b) ? a - b : aParsed.localeCompare(bParsed, locale); } return direction === "ASC" /* ASC */ ? result : -result; } var suffixAmPm = (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? "am" : "pm"}`; var getQuarter = (d = /* @__PURE__ */ new Date()) => Math.ceil((d.getMonth() + 1) / 3); // src/download.ts function downloadByData(data, filename, mime, bom) { const blobData = typeof bom !== "undefined" ? [bom, data] : [data]; const blob = new Blob(blobData, { type: mime || "application/octet-stream" }); const blobURL = window.URL.createObjectURL(blob); const tempLink = document.createElement("a"); tempLink.style.display = "none"; tempLink.href = blobURL; tempLink.setAttribute("download", filename); tempLink.dataset.testid = "link-download-blob-file"; if (typeof tempLink.download === "undefined") { tempLink.setAttribute("target", "_blank"); } document.body.append(tempLink); tempLink.click(); document.body.removeChild(tempLink); window.URL.revokeObjectURL(blobURL); } // src/emitter.ts function emitter(all) { const events = all || /* @__PURE__ */ new Map(); const getHandlers = (type) => events.get(type); function on(type, handler) { const handlers = getHandlers(type); if (handlers) { handlers.push(handler); } else { events.set(type, [handler]); } } function off(type, handler) { const handlers = getHandlers(type); if (handlers) { if (handler) { const indexHandler = handlers.indexOf(handler) >>> 0; handlers.splice(indexHandler, 1); } else { events.set(type, []); } } } function emit(type, event) { let handlers = getHandlers(type); if (handlers) { for (const handler of handlers) { if (event) handler(event); } } handlers = events.get("*"); if (handlers) { for (const handler of handlers) { if (event) handler(type, event); } } } return { events, on, off, emit }; } // src/generate.ts function getRandomIntInclusive(min, max) { const _min = Math.ceil(min); const _max = Math.floor(max); return Math.floor(Math.random() * (_max - _min + 1) + _min); } function getRandomInt(min, max) { const _min = Math.ceil(min); const _max = Math.floor(max); return Math.floor(Math.random() * (_max - _min) + _min); } // src/http.ts var HTTP_CONTINUE = 100; var HTTP_SWITCHING_PROTOCOLS = 101; var HTTP_PROCESSING = 102; var HTTP_EARLY_HINTS = 103; var HTTP_OK = 200; var HTTP_CREATED = 201; var HTTP_ACCEPTED = 202; var HTTP_NON_AUTHORITATIVE_INFORMATION = 203; var HTTP_NO_CONTENT = 204; var HTTP_RESET_CONTENT = 205; var HTTP_PARTIAL_CONTENT = 206; var HTTP_MULTI_STATUS = 207; var HTTP_ALREADY_REPORTED = 208; var HTTP_IM_USED = 226; var HTTP_MULTIPLE_CHOICES = 300; var HTTP_MOVED_PERMANENTLY = 301; var HTTP_FOUND = 302; var HTTP_SEE_OTHER = 303; var HTTP_NOT_MODIFIED = 304; var HTTP_USE_PROXY = 305; var HTTP_RESERVED = 306; var HTTP_TEMPORARY_REDIRECT = 307; var HTTP_PERMANENTLY_REDIRECT = 308; var HTTP_BAD_REQUEST = 400; var HTTP_UNAUTHORIZED = 401; var HTTP_PAYMENT_REQUIRED = 402; var HTTP_FORBIDDEN = 403; var HTTP_NOT_FOUND = 404; var HTTP_METHOD_NOT_ALLOWED = 405; var HTTP_NOT_ACCEPTABLE = 406; var HTTP_PROXY_AUTHENTICATION_REQUIRED = 407; var HTTP_REQUEST_TIMEOUT = 408; var HTTP_CONFLICT = 409; var HTTP_GONE = 410; var HTTP_LENGTH_REQUIRED = 411; var HTTP_PRECONDITION_FAILED = 412; var HTTP_REQUEST_ENTITY_TOO_LARGE = 413; var HTTP_REQUEST_URI_TOO_LONG = 414; var HTTP_UNSUPPORTED_MEDIA_TYPE = 415; var HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416; var HTTP_EXPECTATION_FAILED = 417; var HTTP_I_AM_A_TEAPOT = 418; var HTTP_MISDIRECTED_REQUEST = 421; var HTTP_UNPROCESSABLE_ENTITY = 422; var HTTP_LOCKED = 423; var HTTP_FAILED_DEPENDENCY = 424; var HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425; var HTTP_UPGRADE_REQUIRED = 426; var HTTP_PRECONDITION_REQUIRED = 428; var HTTP_TOO_MANY_REQUESTS = 429; var HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; var HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451; var HTTP_INTERNAL_SERVER_ERROR = 500; var HTTP_NOT_IMPLEMENTED = 501; var HTTP_BAD_GATEWAY = 502; var HTTP_SERVICE_UNAVAILABLE = 503; var HTTP_GATEWAY_TIMEOUT = 504; var HTTP_VERSION_NOT_SUPPORTED = 505; var HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; var HTTP_INSUFFICIENT_STORAGE = 507; var HTTP_LOOP_DETECTED = 508; var HTTP_NOT_EXTENDED = 510; var HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; var HTTP_CF_UNKNOWN = 520; var HTTP_CF_WEB_SERVER_IS_DOWN = 521; var HTTP_CF_CONNECTION_TIMED_OUT = 522; var HTTP_CF_ORIGIN_IS_UNREACHABLE = 523; var HTTP_CF_A_TIMEOUT_OCCURRED = 524; var HTTP_CF_SSL_HANDSHAKE_FAILED = 525; var HTTP_CF_INVALID_SSL_CERTIFICATE = 526; var HTTP_CF_RAILGUN_ERROR = 527; // src/invariant.ts var prefix = "Invariant failed"; function invariant(condition, message) { if (condition) { return; } if (typeof message === "string" || typeof message === "function") { const provided = typeof message === "function" ? message() : message; const value = provided ? `${prefix}: ${provided}` : prefix; throw new Error(value); } if (message) throw message; throw new Error(prefix); } // src/number.ts function formatNumber(num, precision = 0, defaultValue = "-") { if (!isNumber(num)) { return defaultValue; } return num.toLocaleString("en", { minimumFractionDigits: precision, maximumFractionDigits: precision }); } function formatLot10Volume(volume, precision = 0, defaultValue = "-") { if (!isNumber(volume)) { return defaultValue; } return (volume * 10)?.toLocaleString("en", { minimumFractionDigits: precision }).slice(0, -1); } function Strip(num, precision = 15) { return +parseFloat(Number(num).toPrecision(precision)); } function DigitLength(num) { const eSplit = num.toString().split(/[eE]/); const len3 = (eSplit[0].split(".")[1] || "").length - +(eSplit[1] || 0); return len3 > 0 ? len3 : 0; } function Float2Fixed(num) { if (num.toString().indexOf("e") === -1) { return Number(num.toString().replace(".", "")); } const dLen = DigitLength(num); const powDLen = 10 ** dLen; return dLen > 0 ? Strip(Number(num) * powDLen) : Number(num); } var _boundaryCheckingState = true; function CheckBoundary(num) { if (_boundaryCheckingState) { if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) { console.warn( `${num} is beyond boundary when transfer to integer, the results may not be accurate` ); } } } function npCreateOperation(operation) { return (...nums) => { const [first, ...others] = nums; return others.reduce((prev, next) => operation(prev, next), first); }; } var Times = npCreateOperation((num1, num2) => { const num1Changed = Float2Fixed(num1); const num2Changed = Float2Fixed(num2); const baseNum = DigitLength(num1) + DigitLength(num2); const leftValue = num1Changed * num2Changed; CheckBoundary(leftValue); const baseNumPow = 10 ** baseNum; return leftValue / baseNumPow; }); var Plus = npCreateOperation((num1, num2) => { const baseNum = 10 ** Math.max(DigitLength(num1), DigitLength(num2)); return (Times(num1, baseNum) + Times(num2, baseNum)) / baseNum; }); var Minus = npCreateOperation((num1, num2) => { const baseNum = 10 ** Math.max(DigitLength(num1), DigitLength(num2)); return (Times(num1, baseNum) - Times(num2, baseNum)) / baseNum; }); var Divide = npCreateOperation((num1, num2) => { const num1Changed = Float2Fixed(num1); const num2Changed = Float2Fixed(num2); CheckBoundary(num1Changed); CheckBoundary(num2Changed); return Times(num1Changed / num2Changed, Strip(10 ** (DigitLength(num2) - DigitLength(num1)))); }); function Round(num, decimal) { const base = 10 ** decimal; let result = Divide(Math.round(Math.abs(Times(num, base))), base); if (isNumber(num) && num < 0 && result !== 0) { result = Times(result, -1); } return result; } function EnableBoundaryChecking(flag = true) { _boundaryCheckingState = flag; } // src/string.ts var camelizeRE = /-(\w)/g; var camelize = cacheStringFunction((str) => { return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ""); }); var hyphenateRE = /\B([A-Z])/g; var hyphenate = cacheStringFunction( (str) => str.replace(hyphenateRE, "-$1").toLowerCase() ); var snake2camel = cacheStringFunction((str) => { return str.replace(/_([a-z])/g, (g) => g[1].toUpperCase()); }); var camel2snake = cacheStringFunction((str) => { return str.replace(/[A-Z0-9]/g, (char) => `_${char.toLocaleLowerCase()}`); }); var capitalizeFirst = cacheStringFunction((value) => { return value.replace(/^./, value[0].toUpperCase()); }); function slugify(text) { if (!text) { return ""; } return text.toString().normalize("NFKD").toLowerCase().trim().replace(/\s+/g, "-").replace(/[Đđ]/g, "d").replace(/[^\w-]+/g, "").replace(/--+/g, "-"); } function getRandomString(length, alphanumeric) { let str = ""; let i = 0; const min = alphanumeric === "a" ? 10 : 0; const max = alphanumeric === "n" ? 10 : 62; while (i++ < length) { let r = Math.trunc(Math.random() * (max - min) + min); str += String.fromCodePoint(r += r > 9 ? r < 36 ? 55 : 61 : 48); } return str; } function cutString(value, limit) { if (!value && typeof value !== "string") return void 0; if (value.length === 0) return value; return value.split("").slice(0, limit).join(""); } // src/object.ts function deepMerge(target, ...sources) { if (sources.length === 0) { return target; } const source = sources.shift(); if (source === void 0) { return target; } if (isMergeableObject(target) && isMergeableObject(source)) { const sourceKeys = Object.keys(source); for (const key of sourceKeys) { if (isMergeableObject(source[key])) { if (!target[key]) { target[key] = {}; } if (isMergeableObject(target[key])) { deepMerge(target[key], source[key]); } else { target[key] = source[key]; } } else { target[key] = source[key]; } } } return deepMerge(target, ...sources); } function isMergeableObject(item) { return isObject(item) && !isArray(item); } function removeEmptyObj(obj) { return Object.fromEntries( Object.entries(obj).filter(([_, v]) => isNotNull(v) && isDef(v) && isNotEmpty(v)) ); } function removeUndefObj(obj) { const keys = Object.keys(obj); for (const key of keys) { isUndef(obj[key]) ? obj[key] === void 0 : {}; } return obj; } function objectMap(obj, fn) { return Object.fromEntries( // @ts-expect-error ignore type check Object.entries(obj).map(([k, v]) => fn(k, v)).filter(isNotNull) ); } function isKeyOf(obj, k) { return k in obj; } function objectKeys(obj) { return Object.keys(obj); } function objectEntries(obj) { return Object.entries(obj); } function objectCamel2Snake(obj) { return Object.entries(obj).reduce( // biome-ignore lint/performance/noAccumulatingSpread: Ignore here (acc, cur) => ({ ...acc, [camel2snake(cur[0])]: cur[1] }), {} ); } function pick(state, paths) { if (Array.isArray(paths)) { return paths.reduce((acc, path) => { const _paths = path.split("."); return set(acc, _paths, get(state, _paths)); }, {}); } return get(state, paths.split(".")); } function get(state, paths) { return paths.reduce((acc, path) => acc?.[path], state); } var ProtoRE = /^(__proto__)$/; function set(state, paths, val) { const last = paths.at(-1); if (last === void 0) return state; const restPaths = paths.slice(0, -1); const result = restPaths.reduce((obj, p) => ProtoRE.test(p) ? {} : obj[p] ||= {}, state); result[last] = val; return state; } // src/p.cancelable.ts var CancelError = class extends Error { constructor(reason) { super(reason || "Promise was canceled"); this.name = "CancelError"; } get isCanceled() { return true; } }; var promiseState = Object.freeze({ pending: Symbol("pending"), canceled: Symbol("canceled"), resolved: Symbol("resolved"), rejected: Symbol("rejected") }); var PCancelable = class _PCancelable extends Promise { static fn(userFunction) { return (...arguments_) => new _PCancelable((resolve, reject, onCancel) => { arguments_.push(onCancel); userFunction(...arguments_).then(resolve, reject); }); } #cancelHandlers = []; #rejectOnCancel = true; #state = promiseState.pending; #promise; #reject = () => { }; constructor(executor) { super(executor); this.#promise = new Promise((resolve, reject) => { this.#reject = reject; const onCancel = (handler) => { if (this.#state !== promiseState.pending) { throw new Error( `The \`onCancel\` handler was attached after the promise ${this.#state.description}.` ); } this.#cancelHandlers.push(handler); }; const addedProperties = { shouldReject: { get: () => this.#rejectOnCancel, set: (boolean) => { this.#rejectOnCancel = boolean; } } }; objectDefProperties(onCancel, addedProperties); const onResolve = (value) => { if (this.#state !== promiseState.canceled || !onCancel.shouldReject) { resolve(value); this.#setState(promiseState.resolved); } }; const onReject = (error) => { if (this.#state !== promiseState.canceled || !onCancel.shouldReject) { reject(error); this.#setState(promiseState.rejected); } }; executor(onResolve, onReject, onCancel); }); } // @ts-expect-error Ignore then then(onFulfilled, onRejected) { return this.#promise.then(onFulfilled, onRejected); } catch(onRejected) { return this.#promise.catch(onRejected); } finally(onFinally) { return this.#promise.finally(onFinally); } cancel(reason) { if (this.#state !== promiseState.pending) { return; } this.#setState(promiseState.canceled); if (this.#cancelHandlers.length > 0) { try { for (const handler of this.#cancelHandlers) { handler(); } } catch (error) { this.#reject(error); return; } } if (this.#rejectOnCancel) { this.#reject(new CancelError(reason)); } } get isCanceled() { return this.#state === promiseState.canceled; } #setState(state) { if (this.#state === promiseState.pending) { this.#state = state; } } }; function objectDefProperties(obj, objAddendum) { Object.defineProperties(obj, objAddendum); } // src/p.defer.ts var PDefer = class { constructor() { this.placeholder = "dummy p-defer"; } }; // src/p.delay.ts var createAbortError = () => { const error = new Error("Delay aborted"); error.name = "AbortError"; return error; }; var clearMethods = /* @__PURE__ */ new WeakMap(); function delay(milliseconds, options) { return createDelay(milliseconds, options); } function createDelay(milliseconds, { value, signal } = {}) { if (signal?.aborted) { return Promise.reject(createAbortError()); } let timeoutId; let settle; let rejectFunction; const signalListener = () => { clearTimeout(timeoutId); rejectFunction(createAbortError()); }; const cleanup = () => { if (signal) { signal.removeEventListener("abort", signalListener); } }; const delayPromise = new Promise((resolve, reject) => { settle = () => { cleanup(); if (value) resolve(value); }; rejectFunction = reject; timeoutId = setTimeout(settle, milliseconds); }); if (signal) { signal.addEventListener("abort", signalListener, { once: true }); } clearMethods.set(delayPromise, () => { clearTimeout(timeoutId); timeoutId = void 0; settle(); }); return delayPromise; } async function rangeDelay(minimum, maximum, options = {}) { return delay(getRandomInt(minimum, maximum), options); } function clearDelay(promise) { clearMethods.get(promise)?.(); } // src/p.queue.ts var PQueue = class { constructor() { this.placeholder = "dummy p-queue"; } }; // src/p.timeout.ts var PTimeOut = class { constructor() { this.placeholder = "dummy p-timeout"; } }; // src/singleton.ts function singleton(name, valueFactory) { const g = global; g.__singletons ??= {}; g.__singletons[name] ??= valueFactory(); return g.__singletons[name]; } // src/sleep.ts function sleep(ms) { return new Promise((resolve) => { setTimeout(() => { resolve(); }, ms); }); } // src/stream.ts async function* streamAsyncIterable(stream) { const reader = stream.getReader(); try { while (true) { const { done, value } = await reader.read(); if (done) { return; } yield value; } } finally { reader.releaseLock(); } } // src/timeSpan.ts function timeSpan() { const start = process.hrtime.bigint(); const end = (type) => convertHrTime(process.hrtime.bigint() - start)[type]; const result = () => end("milliseconds"); result.toRounded = () => Math.round(end("milliseconds")); result.toSeconds = () => end("seconds"); result.toNanoseconds = () => end("nanoseconds"); return result; } // src/timeSpanBr.ts function timeSpanBr() { const start = performance.now(); const end = () => performance.now() - start; end.rounded = () => Math.round(end()); end.seconds = () => end() / 1e3; end.nanoseconds = () => end() * 1e6; return end; } // src/vector.ts function neg(A) { return [-A[0], -A[1]]; } function add(A, B) { return [A[0] + B[0], A[1] + B[1]]; } function sub(A, B) { return [A[0] - B[0], A[1] - B[1]]; } function vec(A, B) { return [B[0] - A[0], B[1] - A[1]]; } function mul(A, n) { return [A[0] * n, A[1] * n]; } function div(A, n) { return [A[0] / n, A[1] / n]; } function per(A) { return [A[1], -A[0]]; } function dpr(A, B) { return A[0] * B[0] + A[1] * B[1]; } function len(A) { return Math.hypot(A[0], A[1]); } function len2(A) { return A[0] * A[0] + A[1] * A[1]; } function dist2(A, B) { return len2(sub(A, B)); } function uni(A) { return div(A, len(A)); } function dist(A, B) { return Math.hypot(A[1] - B[1], A[0] - B[0]); } function med(A, B) { return mul(add(A, B), 0.5); } function rotAround(A, C, r) { const s = Math.sin(r); const c = Math.cos(r); const px = A[0] - C[0]; const py = A[1] - C[1]; const nx = px * c - py * s; const ny = px * s + py * c; return [nx + C[0], ny + C[1]]; } function lrp(A, B, t) { return add(A, mul(vec(A, B), t)); } function isLeft(p1, pc, p2) { return (pc[0] - p1[0]) * (p2[1] - p1[1]) - (p2[0] - p1[0]) * (pc[1] - p1[1]); } function clockwise(p1, pc, p2) { return isLeft(p1, pc, p2) > 0; } function isEqual(a, b) { return a[0] === b[0] && a[1] === b[1]; } function toPointsArray(points) { if (isArray(points[0])) { return points.map(([x, y, pressure = 0.5]) => [x, y, pressure]); } return points.map(({ x, y, pressure = 0.5 }) => [x, y, pressure]); } function getStrokeRadius(size, thinning, easing, pressure = 0.5) { if (!thinning) { return size / 2; } const newPressure = clamp(easing(pressure), 0, 1); return (thinning < 0 ? lerp(size, size + size * clamp(thinning, -0.95, -0.05), newPressure) : lerp(size - size * clamp(thinning, 0.05, 0.95), size, newPressure)) / 2; } // src/index.ts var noop = () => { }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { CheckBoundary, CookieService, DigitLength, Divide, EnableBoundaryChecking, Float2Fixed, HTTP_ACCEPTED, HTTP_ALREADY_REPORTED, HTTP_BAD_GATEWAY, HTTP_BAD_REQUEST, HTTP_CF_A_TIMEOUT_OCCURRED, HTTP_CF_CONNECTION_TIMED_OUT, HTTP_CF_INVALID_SSL_CERTIFICATE, HTTP_CF_ORIGIN_IS_UNREACHABLE, HTTP_CF_RAILGUN_ERROR, HTTP_CF_SSL_HANDSHAKE_FAILED, HTTP_CF_UNKNOWN, HTTP_CF_WEB_SERVER_IS_DOWN, HTTP_CONFLICT, HTTP_CONTINUE, HTTP_CREATED, HTTP_EARLY_HINTS, HTTP_EXPECTATION_FAILED, HTTP_FAILED_DEPENDENCY, HTTP_FORBIDDEN, HTTP_FOUND, HTTP_GATEWAY_TIMEOUT, HTTP_GONE, HTTP_IM_USED, HTTP_INSUFFICIENT_STORAGE, HTTP_INTERNAL_SERVER_ERROR, HTTP_I_AM_A_TEAPOT, HTTP_LENGTH_REQUIRED, HTTP_LOCKED, HTTP_LOOP_DETECTED, HTTP_METHOD_NOT_ALLOWED, HTTP_MISDIRECTED_REQUEST, HTTP_MOVED_PERMANENTLY, HTTP_MULTIPLE_CHOICES, HTTP_MULTI_STATUS, HTTP_NETWORK_AUTHENTICATION_REQUIRED, HTTP_NON_AUTHORITATIVE_INFORMATION, HTTP_NOT_ACCEPTABLE, HTTP_NOT_EXTENDED, HTTP_NOT_FOUND, HTTP_NOT_IMPLEMENTED, HTTP_NOT_MODIFIED, HTTP_NO_CONTENT, HTTP_OK, HTTP_PARTIAL_CONTENT, HTTP_PAYMENT_REQUIRED, HTTP_PERMANENTLY_REDIRECT, HTTP_PRECONDITION_FAILED, HTTP_PRECONDITION_REQUIRED, HTTP_PROCESSING, HTTP_PROXY_AUTHENTICATION_REQUIRED, HTTP_REQUESTED_RANGE_NOT_SATISFIABLE, HTTP_REQUEST_ENTITY_TOO_LARGE, HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, HTTP_REQUEST_TIMEOUT, HTTP_REQUEST_URI_TOO_LONG, HTTP_RESERVED, HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL, HTTP_RESET_CONTENT, HTTP_SEE_OTHER, HTTP_SERVICE_UNAVAILABLE, HTTP_SWITCHING_PROTOCOLS, HTTP_TEMPORARY_REDIRECT, HTTP_TOO_MANY_REQUESTS, HTTP_UNAUTHORIZED, HTTP_UNAVAILABLE_FOR_LEGAL_REASONS, HTTP_UNPROCESSABLE_ENTITY, HTTP_UNSUPPORTED_MEDIA_TYPE, HTTP_UPGRADE_REQUIRED, HTTP_USE_PROXY, HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL, HTTP_VERSION_NOT_SUPPORTED, Minus, PCancelable, PDefer, PQueue, PTimeOut, Plus, Round, SortDirection, Strip, Times, _process, add, alphaHex, cacheStringFunction, camel2snake, camelize, cancelIdleCallback, capitalizeFirst, chunk, clamp, clearDelay, clockwise, convertHrTime, createCachedImport, createDelay, cutString, deepMerge, delay, dist, dist2, div, downloadByData, dpr, emailRegex, emitter, envs, escapedSpaceCharactersRegex, findLastIndex, formatBytes, formatDecimals, formatLot10Volume, formatNumber, getQuarter, getRandomInt, getRandomIntInclusive, getRandomString, getStrokeRadius, groupBy, hexColor, hyphenate, intToBuffer, intToHex, invariant, isAndroid, isArray, isBase64, isBoolean, isBrowser, isCI, isCrawler, isDate, isDef, isEmpties, isEmpty, isEqual, isFalsy, isFunction, isHex, isKeyOf, isLeft, isLinux, isMacOS, isMap, isMobile, isNodeDev, isNodeProd, isNodeTest, isNotEmpties, isNotEmpty, isNotNull, isNumber, isObject, isPngImage, isPrimitive, isPromise, isSameMonth, isSet, isStream, isString, isSymbol, isToday, isUndef, isValidEmail, isValidUrl, isValidVnPhone, isWindows, len, len2, lerp, listenCookieChange, lrp, med, mul, multilineCommentsRegex, neg, nodeENV, noop, normalize, objectCamel2Snake, objectEntries, objectKeys, objectMap, parseCookie, per, percentToHex, pick, platform, process, rangeDelay, remove, removeEmptyObj, removeUndefObj, requestIdleCallback, rotAround, sample, serializeCookie, shuffle, singlelineCommentsRegex, singleton, sleep, slugify, snake2camel, sortByDate, sortData, streamAsyncIterable, sub, suffixAmPm, sum, take, timeSpan, timeSpanBr, toBoolean, toPointsArray, uni, unique, uniqueObj, urlRegex, vec, vietnamPhoneRegex });