@techmely/utils
Version:
Collection of helpful JavaScript / TypeScript utils
1,836 lines (1,706 loc) • 91.5 kB
JavaScript
/*!
* @techmely/utils
* Copyright(c) 2021-2024 Techmely <techmely.creation@gmail.com>
* MIT Licensed
*/
import {
findLastIndex
} from "./chunk-5Z5ETKJZ.js";
import {
invariant,
isArray
} from "./chunk-XMT5IFPR.js";
import {
isStream
} from "./chunk-4ZFOS5HW.js";
// src/RopeSequence/RopeSequence.ts
var RopeSequence = class _RopeSequence {
static empty;
values;
// Create a rope representing the given array, or return the rope
// itself if a rope was given.
static from(values) {
if (values instanceof _RopeSequence) return values;
return values?.length ? new Leaf(values) : _RopeSequence.empty;
}
leafAppend(other) {
return void 0;
}
leafPrepend(other) {
return void 0;
}
sliceInner(from, to) {
return new Leaf([]);
}
getInner(index) {
return void 0;
}
forEachInner(f, from, to, start) {
}
forEachInvertedInner(f, from, to, start) {
}
/**
* Append an array or other rope to this one, returning a new rope.
*/
append(other) {
if (!other.length) return this;
other = _RopeSequence.from(other);
return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other);
}
// :: (union<[T], RopeSequence<T>>) → RopeSequence<T>
// Prepend an array or other rope to this one, returning a new rope.
prepend(other) {
if (!other.length) return this;
return _RopeSequence.from(other).append(this);
}
appendInner(other) {
return new Append(this, other);
}
/**
* Create a rope representing a sub-sequence of this rope.
*/
slice(from = 0, to = _RopeSequence.length) {
if (from >= to) return _RopeSequence.empty;
return this.sliceInner(Math.max(0, from), Math.min(this.length, to));
}
// :: (number) → T
// Retrieve the element at the given position from this rope.
get(i) {
if (i < 0 || i >= _RopeSequence.length) return void 0;
return this.getInner(i);
}
// :: ((element: T, index: number) → ?bool, ?number, ?number)
// Call the given function for each element between the given
// indices. This tends to be more efficient than looping over the
// indices and calling `get`, because it doesn't have to descend the
// tree for every element.
forEach(f, from = 0, to = _RopeSequence.length) {
if (from <= to) this.forEachInner(f, from, to, 0);
else this.forEachInvertedInner(f, from, to, 0);
}
// Map the given functions over the elements of the rope, producing
// a flat array.
map(f, from = 0, to = _RopeSequence.length) {
const result = [];
this.forEach((elt, i) => result.push(f(elt, i)), from, to);
return result;
}
set length(v) {
this.length = v;
}
get length() {
return this.values.length;
}
};
var GOOD_LEAF_SIZE = 200;
var Leaf = class _Leaf extends RopeSequence {
values;
constructor(values) {
super();
this.values = values;
}
flatten() {
return this.values;
}
sliceInner(from, to) {
if (from === 0 && to === this.length) return this;
return new _Leaf(this.values.slice(from, to));
}
getInner(i) {
return this.values[i];
}
forEachInner(f, from, to, start) {
for (let i = from; i < to; i++) if (f(this.values[i], start + i) === false) return false;
}
forEachInvertedInner(f, from, to, start) {
for (let i = from - 1; i >= to; i--) if (f(this.values[i], start + i) === false) return false;
}
leafAppend(other) {
if (this.length + other.length <= GOOD_LEAF_SIZE)
return new _Leaf(this.values.concat(other.flatten()));
}
leafPrepend(other) {
if (this.length + other.length <= GOOD_LEAF_SIZE)
return new _Leaf(other.flatten().concat(this.values));
}
set length(v) {
this.length = v;
}
get length() {
return this.values.length;
}
get depth() {
return 0;
}
};
RopeSequence.empty = new Leaf([]);
var Append = class _Append extends RopeSequence {
left;
right;
depth;
constructor(left, right) {
super();
this.left = left;
this.right = right;
this.length = left.length + right.length;
this.depth = Math.max(left.depth, right.depth) + 1;
}
flatten() {
return this.left.flatten().concat(this.right.flatten());
}
getInner(i) {
return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length);
}
forEachInner(f, from, to, start) {
const leftLen = this.left.length;
if (from < leftLen && this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false)
return false;
if (to > leftLen && this.right.forEachInner(
f,
Math.max(from - leftLen, 0),
Math.min(this.length, to) - leftLen,
start + leftLen
) === false)
return false;
}
forEachInvertedInner(f, from, to, start) {
const leftLen = this.left.length;
if (from > leftLen && this.right.forEachInvertedInner(
f,
from - leftLen,
Math.max(to, leftLen) - leftLen,
start + leftLen
) === false)
return false;
if (to < leftLen && this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false)
return false;
}
sliceInner(from, to) {
if (from === 0 && to === this.length) return this;
const leftLen = this.left.length;
if (to <= leftLen) return this.left.slice(from, to);
if (from >= leftLen) return this.right.slice(from - leftLen, to - leftLen);
return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen));
}
leafAppend(other) {
const inner = this.right.leafAppend(other);
if (inner) return new _Append(this.left, inner);
}
leafPrepend(other) {
const inner = this.left.leafPrepend(other);
if (inner) return new _Append(inner, this.right);
}
appendInner(other) {
if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1)
return new _Append(this.left, new _Append(this.right, other));
return new _Append(this, other);
}
};
// src/isServer.ts
function isServer() {
return typeof window === "undefined";
}
// src/alias.ts
function $(tag, _targer) {
if (isServer()) return null;
const target = _targer || document;
return document.querySelector.call(target, tag);
}
function $$(tag, _targer) {
if (isServer()) return null;
const target = _targer || document;
return document.querySelectorAll.call(target, tag);
}
// src/percentToHex.ts
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();
}
// src/alphaHex.ts
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/cacheImportModule.ts
var lazyImportCache = /* @__PURE__ */ new Map();
function createCachedImport(name, imp) {
return () => {
const cached = lazyImportCache.get(name);
if (cached) return cached;
const promise = imp().then((module) => {
lazyImportCache.set(name, module);
return module;
});
lazyImportCache.set(name, promise);
return promise;
};
}
// src/cacheStringFunc.ts
function cacheStringFunction(fn) {
const cache2 = /* @__PURE__ */ Object.create(null);
return (str) => {
const hit = cache2[str];
return hit || (cache2[str] = fn(str));
};
}
// src/calculateFrequencies/index.ts
function calculateFrequencies(arr) {
return arr.reduce((acc, curr) => {
acc[curr] = (acc[curr] ?? 0) + 1;
return acc;
}, {});
}
// src/isBrowser.ts
function isBrowser() {
return typeof window !== "undefined";
}
// src/calculateScrollPercentage/index.ts
function calculateScrollPercentage() {
invariant(isBrowser());
const scrollPosition = window.scrollY || window.scrollY || document.documentElement.scrollTop;
const totalHeight = document.documentElement.scrollHeight - window.innerHeight;
const scrollPercentage = scrollPosition / totalHeight * 100;
return scrollPercentage;
}
// src/isFunction.ts
function isFunction2(val) {
return typeof val === "function";
}
// src/callOrReturn.ts
function callOrReturn(value, context = void 0, ...props) {
if (isFunction2(value)) {
if (context) {
return value.bind(context)(...props);
}
return value(...props);
}
return value;
}
// src/camel2Snake.ts
var camel2snake = cacheStringFunction((str) => {
return str.replace(/[A-Z0-9]/g, (char) => `_${char.toLocaleLowerCase()}`);
});
// src/camel2SnakeObject.ts
function camel2SnakeObject(obj) {
return Object.entries(obj).reduce(
// biome-ignore lint/performance/noAccumulatingSpread: Ignore here
(acc, cur) => ({ ...acc, [camel2snake(cur[0])]: cur[1] }),
{}
);
}
// src/camelize.ts
var camelizeRE = /-(\w)/g;
var camelize = cacheStringFunction((str) => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : "");
});
// src/cancelIdleCallback.ts
function cancelIdleCallbackShim(id) {
clearTimeout(id);
}
var cancelIdleCallback = typeof window !== "undefined" ? window.cancelIdleCallback || cancelIdleCallbackShim : cancelIdleCallbackShim;
// src/capitalizeFirst.ts
var capitalizeFirst = cacheStringFunction((value) => {
return value.replace(/^./, value[0].toUpperCase());
});
// src/isEdgeBrowser.ts
function isEdgeBrowser() {
return typeof navigator !== "undefined" && navigator.userAgent.indexOf("Edg") > -1;
}
// src/isOpera.ts
function isOpera() {
return typeof window !== "undefined" && typeof window.opr !== "undefined";
}
// src/isChrome.ts
function isChrome() {
if (typeof window === "undefined") return false;
const isChromium = window.chrome;
const vendor = window.navigator.vendor;
return isChromium !== null && typeof isChromium !== "undefined" && vendor === "Google Inc." && isOpera() === false && isEdgeBrowser() === false;
}
// src/chromeVersion.ts
function chromeVersion() {
if (isChrome()) {
const segments = /Chrome\/(\d+)/.exec(navigator.userAgent) || [0, 0];
return +segments[1];
}
return 0;
}
// src/chunkArray.ts
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);
});
}
// src/clamp.ts
function clamp(n, min, max) {
return Math.min(max, Math.max(min, n));
}
// src/convertHrTime.ts
function convertHrTime(hrtime) {
const nanoseconds = hrtime;
const number = Number(nanoseconds);
const milliseconds = number / 1e6;
const seconds = number / 1e9;
return {
seconds,
milliseconds,
nanoseconds
};
}
// src/isDate.ts
function isDate(val) {
return toString.call(val) === "[object Date]";
}
// 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 {
nodeEnv;
env;
domain;
tokenName;
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/createElement/createElement.ts
function createElement(tag, ...children) {
invariant(isBrowser(), "Not in browser environment");
let element = tag;
if (typeof element === "string") element = document.createElement(element);
let i = 1;
const next = arguments[1];
if (next && typeof next === "object" && !next.nodeType && !Array.isArray(next)) {
for (const name in next) {
const value = next?.[name];
if (typeof value === "string") element.setAttribute(name, value);
if (value) element[name] = value;
}
i++;
}
for (; i < arguments.length; i++) add(element, arguments[i]);
return element;
}
function add(element, child) {
if (!child) return;
if (typeof child === "string") {
element.appendChild(document.createTextNode(child));
} else if (child.nodeType !== null) {
element.appendChild(child);
} else if (Array.isArray(child)) {
for (const c of child) {
add(element, c);
}
}
}
// src/createStyleTag/index.ts
function createStyleTag(style, options) {
invariant(isBrowser());
const { id, ...rest } = options;
const styleTag = document.querySelector(`style[#${id}]`);
if (styleTag) return styleTag;
const styleNode = document.createElement("style");
const values = Object.entries(rest);
for (const [k, v] of values) {
styleNode.setAttribute(k, v);
}
styleNode.setAttribute("id", id);
styleNode.innerHTML = style;
document.getElementsByTagName("head")[0].appendChild(styleNode);
return styleNode;
}
// src/cutString.ts
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/debounce/index.ts
function debounce(func, delay2, immediate = false) {
let timeoutId;
return function(...args) {
const callNow = immediate && !timeoutId;
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
timeoutId = null;
if (!immediate) {
func.apply(this, args);
}
}, delay2);
if (callNow) {
func.apply(this, args);
}
};
}
// src/delaySignal/index.ts
async function delaySignal(ms, { signal }) {
return new Promise((resolve, reject) => {
if (signal) {
signal.throwIfAborted();
signal.addEventListener("abort", abortHandler, { once: true });
}
function abortHandler() {
clearTimeout(timeoutId);
reject(signal?.reason);
}
const timeoutId = setTimeout(() => {
signal?.removeEventListener("abort", abortHandler);
resolve();
}, ms);
});
}
// src/deleteProps.ts
function deleteProps(obj, propOrProps) {
const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps;
return Object.keys(obj).reduce((newObj, prop) => {
if (!props.includes(prop)) {
newObj[prop] = obj[prop];
}
return newObj;
}, {});
}
// src/downloadByData.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.appendChild(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/env.ts
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);
function envShims() {
return 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);
}
});
}
// src/escapeRegex.ts
function escapeRegExp(val) {
return val.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// src/filterArrays/index.ts
function filterArrays(arr1, arr2, filterCondition) {
const set2 = new Set(arr2);
const result = [];
for (const a of arr1) {
for (const b of set2) {
if (filterCondition(a, b)) {
result.push(a);
break;
}
}
}
return result;
}
// src/findDuplicates.ts
function findDuplicates(items) {
const filtered = items.filter((el, index) => items.indexOf(el) !== index);
return [...new Set(filtered)];
}
// src/findFirstDefined.ts
function findFirstDefined(...args) {
return args.find((arg) => arg !== void 0);
}
// src/firstUniqueArray.ts
function firstUniqueArr(array) {
if (!array || array?.length === 0) return void 0;
const arrLength = array.length;
if (array.length === 1) return array[0];
for (let i = 0; i < arrLength; i++) {
const element = array[i];
if (array.indexOf(element) === array.lastIndexOf(element)) return element;
}
return void 0;
}
// src/firstUniqueChar.ts
function firstUniqueChar(value) {
if (!value) return void 0;
const charLength = value.length;
for (let i = 0; i < charLength; i++) {
const letter = value[i];
if (value.indexOf(letter) === value.lastIndexOf(letter)) return letter;
}
return void 0;
}
// src/flattenObject/index.ts
function flattenObject(obj, prefix = "", result = {}) {
for (const key in obj) {
const newKey = prefix ? `${prefix}.${key}` : key;
if (typeof obj[key] === "object" && obj[key] !== null && !Array.isArray(obj[key])) {
flattenObject(obj[key], newKey, result);
} else {
result[newKey] = obj[key];
}
}
return result;
}
// src/formatBytes.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}`;
};
// src/isNumber.ts
function isNumber(val) {
return toString.call(val) === "[object Number]";
}
// src/formatLot10Volume.ts
function formatLot10Volume(volume, precision = 0, defaultValue = "-") {
if (!isNumber(volume)) {
return defaultValue;
}
return (volume * 10)?.toLocaleString("en", { minimumFractionDigits: precision }).slice(0, -1);
}
// src/formatNumber.ts
function formatNumber(num, precision = 0, defaultValue = "-") {
if (!isNumber(num)) {
return defaultValue;
}
return num.toLocaleString("en", {
minimumFractionDigits: precision,
maximumFractionDigits: precision
});
}
// src/freeMainThread/index.ts
function freezeMainThread(duration) {
const start = Date.now();
while (Date.now() - start < duration) {
}
}
// src/fromString2Primitive.ts
function fromStringToPrimitives(value) {
if (typeof value !== "string") {
return value;
}
if (value.match(/^[+-]?(?:\d*\.)?\d+$/)) {
return Number(value);
}
if (value === "true") {
return true;
}
if (value === "false") {
return false;
}
return value;
}
// src/fullScreen.ts
function requestFullscreen(mode = true, el = "body") {
if (isServer()) return;
if (mode) document.querySelector(el)?.requestFullscreen();
else document.exitFullscreen();
}
// src/generateSampleArray.ts
function generateSample(arr, count) {
return Array.from({ length: count }, (_) => arr[Math.round(Math.random() * (arr.length - 1))]);
}
// src/get/index.ts
function get(from, selector) {
return selector.replace(/\[([^\[\]]*)\]/g, ".$1.").split(".").filter((t) => t !== "").reduce((acc, curr) => acc?.[curr], from);
}
// src/getQuarter.ts
function getQuarter(d = /* @__PURE__ */ new Date()) {
return Math.ceil((d.getMonth() + 1) / 3);
}
// src/getRandomInt.ts
function getRandomInt(min, max) {
const _min = Math.ceil(min);
const _max = Math.floor(max);
return Math.floor(Math.random() * (_max - _min) + _min);
}
// src/getRandomIntInclusive.ts
function getRandomIntInclusive(min, max) {
const _min = Math.ceil(min);
const _max = Math.floor(max);
return Math.floor(Math.random() * (_max - _min + 1) + _min);
}
// src/getRandomString.ts
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;
}
// src/lerp.ts
function lerp(y1, y2, mu) {
return y1 * (1 - mu) + y2 * mu;
}
// src/getStrokeRadius.ts
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/getEnvVar/index.ts
var cache = {};
var getEnvVar = (variableName, defaultValue) => {
if (!(variableName in envShims())) {
if (defaultValue || defaultValue === "" || defaultValue === 0) return defaultValue;
console.error(`Cannot find ${variableName} in environment variables. Died.`);
process.exit(1);
}
if (cache[variableName]) return cache[variableName];
cache[variableName] = process.env[variableName];
return cache[variableName];
};
// src/groupBy.ts
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;
}
// src/hasDuplicates/index.ts
function hasDuplicates(arr) {
return arr.length !== new Set(arr).size;
}
// src/isDeepEqual/index.ts
function isDeepEqual(obj1, obj2) {
if (obj1 === obj2) {
return true;
}
if (typeof obj1 === "object" && obj1 !== null && typeof obj2 === "object" && obj2 !== null) {
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
for (const key of keys1) {
if (!Object.hasOwn(obj2, key)) {
return false;
}
if (!isDeepEqual(obj1[key], obj2[key])) {
return false;
}
}
return true;
}
return false;
}
// src/haveSameElement/index.ts
function haveSameElement(arr1, arr2) {
for (let i = 0; i < arr1.length; i++) {
const el = arr1[i];
if (arr2.some((e) => isDeepEqual(e, el))) {
return true;
}
}
return false;
}
// src/hyphenate.ts
var hyphenateRE = /\B([A-Z])/g;
var hyphenate = cacheStringFunction(
(str) => str.replace(hyphenateRE, "-$1").toLowerCase()
);
// src/intHex.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;
}
// src/intBuffer.ts
function intToBuffer(integer) {
const hex = intToHex(integer);
return Buffer.from(hex, "hex");
}
// src/isAndroid.ts
function isAndroid() {
return typeof navigator !== "undefined" ? /(android)/i.test(navigator.userAgent) : false;
}
// src/isAppleDevice/index.ts
function isAppleDevice() {
if (typeof navigator === "undefined") return false;
return /(Mac|iPhone|iPod|iPad)/i.test(navigator.userAgent);
}
// src/isBase64.ts
function isBase64(base) {
return /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/.test(base);
}
// src/isBoolean.ts
function isBoolean(val) {
return typeof val === "boolean";
}
// src/isBot.ts
var botPatterns = [
" daum[ /]",
" deusu/",
" yadirectfetcher",
"(?:^| )site",
"(?:^|[^g])news",
"(?<! (?:channel/|google/))google(?!(app|/google| pixel))",
"(?<! cu)bot(?:[^\\w]|_|$)",
"(?<! ya(?:yandex)?)search",
"(?<!(?:lib))http",
"(?<![hg]m)score",
"@[a-z]",
"\\(at\\)[a-z]",
"\\[at\\][a-z]",
"^12345",
"^<",
"^[\\w \\.\\-\\(?:\\):]+(?:/v?\\d+(\\.\\d+)?(?:\\.\\d{1,10})?)?(?:,|$)",
"^[^ ]{50,}$",
"^active",
"^ad muncher",
"^amaya",
"^anglesharp/",
"^avsdevicesdk/",
"^bidtellect/",
"^biglotron",
"^bot",
"^btwebclient/",
"^clamav[ /]",
"^client/",
"^cobweb/",
"^coccoc",
"^custom",
"^ddg[_-]android",
"^discourse",
"^dispatch/\\d",
"^downcast/",
"^duckduckgo",
"^facebook",
"^fdm[ /]\\d",
"^getright/",
"^gozilla/",
"^hatena",
"^hobbit",
"^hotzonu",
"^hwcdn/",
"^jeode/",
"^jetty/",
"^jigsaw",
"^linkdex",
"^metauri",
"^microsoft bits",
"^movabletype",
"^mozilla/\\d\\.\\d \\(compatible;?\\)$",
"^mozilla/\\d\\.\\d \\w*$",
"^navermailapp",
"^netsurf",
"^nuclei",
"^offline explorer",
"^php",
"^postman",
"^postrank",
"^python",
"^rank",
"^read",
"^reed",
"^rest",
"^serf",
"^snapchat",
"^space bison",
"^svn",
"^swcd ",
"^taringa",
"^thumbor/",
"^tumblr/",
"^user-agent:",
"^valid",
"^venus/fedoraplanet",
"^w3c",
"^webbandit/",
"^webcopier",
"^wget",
"^whatsapp",
"^xenu link sleuth",
"^yahoo",
"^yandex",
"^zdm/\\d",
"^zoom marketplace/",
"^{{.*}}$",
"adbeat\\.com",
"appinsights",
"archive",
"ask jeeves/teoma",
"bit\\.ly/",
"bluecoat drtr",
"browsex",
"burpcollaborator",
"capture",
"catch",
"check",
"chrome-lighthouse",
"chromeframe",
"classifier",
"cloud",
"crawl",
"cryptoapi",
"dareboost",
"datanyze",
"dataprovider",
"dejaclick",
"dmbrowser",
"download",
"evc-batch/",
"feed",
"firephp",
"freesafeip",
"gomezagent",
"headless",
"httrack",
"hubspot marketing grader",
"hydra",
"ibisbrowser",
"images",
"inspect",
"iplabel",
"ips-agent",
"java(?!;)",
"library",
"mail\\.ru/",
"manager",
"monitor",
"neustar wpm",
"nutch",
"offbyone",
"optimize",
"pageburst",
"parser",
"perl",
"phantom",
"pingdom",
"powermarks",
"preview",
"proxy",
"ptst[ /]\\d",
"reader",
"reputation",
"resolver",
"retriever",
"rexx;",
"rigor",
"robot",
"rss",
"scan",
"scrape",
"server",
"sogou",
"sparkler/",
"speedcurve",
"spider",
"splash",
"statuscake",
"stumbleupon\\.com",
"supercleaner",
"synapse",
"synthetic",
"torrent",
"trace",
"transcoder",
"twingly recon",
"url",
"virtuoso",
"wappalyzer",
"webglance",
"webkit2png",
"whatcms/",
"wordpress",
"zgrab"
];
var botFullPattern = " daum[ /]| deusu/| yadirectfetcher|(?:^| )site|(?:^|[^g])news|(?<! (?:channel/|google/))google(?!(app|/google| pixel))|(?<! cu)bot(?:[^\\w]|_|$)|(?<! ya(?:yandex)?)search|(?<!(?:lib))http|(?<![hg]m)score|@[a-z]|\\(at\\)[a-z]|\\[at\\][a-z]|^12345|^<|^[\\w \\.\\-\\(?:\\):]+(?:/v?\\d+(\\.\\d+)?(?:\\.\\d{1,10})?)?(?:,|$)|^[^ ]{50,}$|^active|^ad muncher|^amaya|^anglesharp/|^avsdevicesdk/|^bidtellect/|^biglotron|^bot|^btwebclient/|^clamav[ /]|^client/|^cobweb/|^coccoc|^custom|^ddg[_-]android|^discourse|^dispatch/\\d|^downcast/|^duckduckgo|^facebook|^fdm[ /]\\d|^getright/|^gozilla/|^hatena|^hobbit|^hotzonu|^hwcdn/|^jeode/|^jetty/|^jigsaw|^linkdex|^metauri|^microsoft bits|^movabletype|^mozilla/\\d\\.\\d \\(compatible;?\\)$|^mozilla/\\d\\.\\d \\w*$|^navermailapp|^netsurf|^nuclei|^offline explorer|^php|^postman|^postrank|^python|^rank|^read|^reed|^rest|^serf|^snapchat|^space bison|^svn|^swcd |^taringa|^thumbor/|^tumblr/|^user-agent:|^valid|^venus/fedoraplanet|^w3c|^webbandit/|^webcopier|^wget|^whatsapp|^xenu link sleuth|^yahoo|^yandex|^zdm/\\d|^zoom marketplace/|^{{.*}}$|adbeat\\.com|appinsights|archive|ask jeeves/teoma|bit\\.ly/|bluecoat drtr|browsex|burpcollaborator|capture|catch|check|chrome-lighthouse|chromeframe|classifier|cloud|crawl|cryptoapi|dareboost|datanyze|dataprovider|dejaclick|dmbrowser|download|evc-batch/|feed|firephp|freesafeip|gomezagent|headless|httrack|hubspot marketing grader|hydra|ibisbrowser|images|inspect|iplabel|ips-agent|java(?!;)|library|mail\\.ru/|manager|monitor|neustar wpm|nutch|offbyone|optimize|pageburst|parser|perl|phantom|pingdom|powermarks|preview|proxy|ptst[ /]\\d|reader|reputation|resolver|retriever|rexx;|rigor|robot|rss|scan|scrape|server|sogou|sparkler/|speedcurve|spider|splash|statuscake|stumbleupon\\.com|supercleaner|synapse|synthetic|torrent|trace|transcoder|twingly recon|url|virtuoso|wappalyzer|webglance|webkit2png|whatcms/|wordpress|zgrab";
var regularExpression = / daum[ /]| deusu\/| yadirectfetcher|(?:^| )site|(?:^|[^g])news|(?<! (?:channel\/|google\/))google(?!(app|\/google| pixel))|(?<! cu)bot(?:[^\w]|_|$)|(?<! ya(?:yandex)?)search|(?<!(?:lib))http|(?<![hg]m)score|@[a-z]|\(at\)[a-z]|\[at\][a-z]|^12345|^<|^[\w \.\-\(?:\):]+(?:\/v?\d+(\.\d+)?(?:\.\d{1,10})?)?(?:,|$)|^[^ ]{50,}$|^active|^ad muncher|^amaya|^anglesharp\/|^avsdevicesdk\/|^bidtellect\/|^biglotron|^bot|^btwebclient\/|^clamav[ /]|^client\/|^cobweb\/|^coccoc|^custom|^ddg[_-]android|^discourse|^dispatch\/\d|^downcast\/|^duckduckgo|^facebook|^fdm[ /]\d|^getright\/|^gozilla\/|^hatena|^hobbit|^hotzonu|^hwcdn\/|^jeode\/|^jetty\/|^jigsaw|^linkdex|^metauri|^microsoft bits|^movabletype|^mozilla\/\d\.\d \(compatible;?\)$|^mozilla\/\d\.\d \w*$|^navermailapp|^netsurf|^nuclei|^offline explorer|^php|^postman|^postrank|^python|^rank|^read|^reed|^rest|^serf|^snapchat|^space bison|^svn|^swcd |^taringa|^thumbor\/|^tumblr\/|^user-agent:|^valid|^venus\/fedoraplanet|^w3c|^webbandit\/|^webcopier|^wget|^whatsapp|^xenu link sleuth|^yahoo|^yandex|^zdm\/\d|^zoom marketplace\/|^{{.*}}$|adbeat\.com|appinsights|archive|ask jeeves\/teoma|bit\.ly\/|bluecoat drtr|browsex|burpcollaborator|capture|catch|check|chrome-lighthouse|chromeframe|classifier|cloud|crawl|cryptoapi|dareboost|datanyze|dataprovider|dejaclick|dmbrowser|download|evc-batch\/|feed|firephp|freesafeip|gomezagent|headless|httrack|hubspot marketing grader|hydra|ibisbrowser|images|inspect|iplabel|ips-agent|java(?!;)|library|mail\.ru\/|manager|monitor|neustar wpm|nutch|offbyone|optimize|pageburst|parser|perl|phantom|pingdom|powermarks|preview|proxy|ptst[ /]\d|reader|reputation|resolver|retriever|rexx;|rigor|robot|rss|scan|scrape|server|sogou|sparkler\/|speedcurve|spider|splash|statuscake|stumbleupon\.com|supercleaner|synapse|synthetic|torrent|trace|transcoder|twingly recon|url|virtuoso|wappalyzer|webglance|webkit2png|whatcms\/|wordpress|zgrab/i;
var naivePattern = /bot|spider|crawl|http|lighthouse/i;
var botRegPattern = regularExpression;
function isBotNaive(userAgent) {
return naivePattern.test(userAgent || "");
}
var usedPattern;
function isBot(userAgent) {
if (typeof usedPattern === "undefined") {
try {
usedPattern = new RegExp(botFullPattern, "i");
} catch (error) {
usedPattern = naivePattern;
}
}
return usedPattern.test(userAgent || "");
}
function createIsBot(customPattern) {
return (userAgent) => {
return customPattern.test(userAgent || "");
};
}
function createIsBotFromList(list) {
const pattern = new RegExp(list.join("|"), "i");
return (userAgent) => {
return pattern.test(userAgent || "");
};
}
function isBotMatch(userAgent) {
return userAgent?.match(botRegPattern)?.[0] ?? null;
}
function isBotMatches(userAgent) {
if (!userAgent) return [];
return botPatterns.map((part) => {
const matched = userAgent.match(new RegExp(part, "i"));
if (!matched) return "";
return matched[0];
}).filter(Boolean);
}
function isBotPattern(userAgent) {
return userAgent ? botPatterns.find((pattern) => new RegExp(pattern, "i").test(userAgent)) ?? null : null;
}
function isBotPatterns(userAgent) {
return userAgent ? botPatterns.filter((pattern) => new RegExp(pattern, "i").test(userAgent)) : [];
}
// src/isChromeIOS.ts
function isIOSChrome() {
return typeof navigator !== "undefined" && navigator.userAgent.match("CriOS");
}
// src/isCrawler.ts
function isCrawler() {
return typeof window !== "undefined" && (!("onscroll" in window) || /(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent));
}
// src/isDefined.ts
function isDefined(val) {
return typeof val !== "undefined";
}
// src/isDistinctArray/index.ts
function isDistinctArray(arr) {
return arr.length === new Set(arr).size;
}
// src/isEmptyArray.ts
function isEmptyArr(array) {
return Array.isArray(array) && array?.length === 0;
}
// src/isObject.ts
function isObject2(val) {
return toString.call(val) === "[object Object]" && !Array.isArray(val);
}
// src/isString.ts
function isString(val) {
return typeof val === "string";
}
// src/isEmpty.ts
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 (isObject2(val)) {
return Object.keys(val).length === 0;
}
return false;
}
// src/isEmpties.ts
function isEmpties(...args) {
if (args.length > 1) {
return args.reduce((a, b) => a && isEmpty(b), true);
}
return false;
}
// src/isGecko.ts
function isGecko() {
return typeof navigator !== "undefined" && /gecko\/(\d+)/i.test(navigator.userAgent);
}
// src/isHexColor.ts
var hexColor = /^#(([\da-f]{2}){3,4})$/;
function isHex(hex) {
return hexColor.test(hex);
}
// src/isIOS.ts
function isIOS() {
return typeof navigator !== "undefined" ? ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"].includes(
navigator.platform
) || // iPad on iOS 13 detection
navigator.userAgent.includes("Mac") && "ontouchend" in document : false;
}
// src/isISOString/index.ts
function isISOString(val) {
const d = new Date(val);
return !Number.isNaN(d.valueOf()) && d.toISOString() === val;
}
// src/toISOStringTimezone/index.ts
var pad = (n) => `${Math.floor(Math.abs(n))}`.padStart(2, "0");
var getTimezoneOffset = (date) => {
const tzOffset = -date.getTimezoneOffset();
const diff = tzOffset >= 0 ? "+" : "-";
return `${diff + pad(tzOffset / 60)}:${pad(tzOffset % 60)}`;
};
function toISOStringTimezone(date) {
return `${date.getFullYear()}
-${pad(date.getMonth() + 1)}
-${pad(date.getDate())}
T${pad(date.getHours())}
:${pad(date.getMinutes())}
:${pad(date.getSeconds())}
${getTimezoneOffset(date)}`;
}
// src/isISOStringTimeZone/index.ts
function isISOStringWithTimezone(val) {
const d = new Date(val);
return !Number.isNaN(d.valueOf()) && toISOStringTimezone(d) === val;
}
// src/isKeyof.ts
function isKeyOf(obj, k) {
return k in obj;
}
// src/process.ts
var _process = globalThis.process || /* @__PURE__ */ Object.create(null);
var processShims = {
versions: {}
};
var globProcess = new Proxy(_process, {
get(target, prop) {
if (prop === "env") {
return envShims();
}
if (prop in target) {
return target[prop];
}
if (prop in processShims) {
return processShims[prop];
}
}
});
// src/isLinux.ts
function isLinux() {
return /^linux/i.test(globProcess.platform || "");
}
// src/isMacOs.ts
function isMacOS() {
return /^darwin/i.test(globProcess.platform || "");
}
// src/matchMedia.ts
function windowMatchMedia() {
return typeof window !== "undefined" ? window.matchMedia || window.msMatchMedia : void 0;
}
// src/isMobile.ts
function isMobile() {
return typeof window !== "undefined" ? windowMatchMedia()?.("(pointer:coarse)")?.matches : false;
}
// src/toBoolean.ts
function toBoolean(val) {
return val ? val !== "false" : false;
}
// src/isNodeProd.ts
function isNodeProd() {
return globProcess.env.NODE_ENV === "production" || toBoolean(envShims().PRODUCTION);
}
// src/isNodeTest.ts
function isNodeTest() {
return globProcess.env.NODE_ENV === "test" || toBoolean(envShims().TEST);
}
// src/isNotEmpty.ts
function isNotEmpty(val) {
return !isEmpty(val);
}
// src/isNotEmpties.ts
function isNotEmpties(...args) {
if (args.length > 1) {
return args.reduce((a, b) => a && isNotEmpty(b), true);
}
return false;
}
// src/isNotNull.ts
function isNotNull(v) {
return v !== null;
}
// src/isNotNullish.ts
function isNotNullish(v) {
return v != null;
}
// src/isNullOrUndef/index.ts
function isNullOrUndefined(value) {
return value === null || value === void 0;
}
// src/isPlainObject/index.ts
function isPlainObject(value) {
if (!isObjectLike(value) || getTag(value) !== "[object Object]") {
return false;
}
if (Object.getPrototypeOf(value) === null) {
return true;
}
let proto = value;
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto);
}
return Object.getPrototypeOf(value) === proto;
}
function isObjectLike(value) {
return typeof value === "object" && value !== null;
}
function getTag(value) {
if (value == null) {
return value === void 0 ? "[object Undefined]" : "[object Null]";
}
return Object.prototype.toString.call(value);
}
// src/isPngImage.ts
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;
}
// src/isPrefersReducedMotion.ts
function isPrefersReducedMotion() {
const mediaQuery = windowMatchMedia()?.("(prefers-reduced-motion: reduce)");
return typeof window !== "undefined" ? mediaQuery?.matches : false;
}
// src/isPrimitive.ts
function isPrimitive(value) {
if (value === null) {
return true;
}
return !["array", "function", "object"].includes(typeof value);
}
// src/isPromise.ts
function isPromise(val) {
return isObject(val) && isFunction(val.then) && isFunction(val.catch);
}
// src/isRegexp.ts
function isRegExp(value) {
return Object.prototype.toString.call(value) === "[object RegExp]";
}
// src/isSafari.ts
function isSafari() {
return typeof navigator !== "undefined" && navigator.vendor.indexOf("Apple") > -1 && navigator.userAgent.indexOf("CriOS") === -1 && navigator.userAgent.indexOf("FxiOS") === -1;
}
// src/isSameDay.ts
function isSameDay(date1, date2) {
if (!(date1 && date2)) {
return false;
}
return date1.getDate() === date2.getDate() && date1.getMonth() === date2.getMonth() && date1.getFullYear() === date2.getFullYear();
}
// src/isSameMonth.ts
function isSameMonth(date1, date2) {
if (!(date1 && date2)) {
return false;
}
return date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth();
}
// src/isSet.ts
function isSet(val) {
return toString.call(val) === "[object Set]";
}
// src/isSlowConnection.ts
function isSlowConnection() {
if (isServer()) {
return;
}
const cn = navigator.connection;
if (cn && (cn.saveData || /2g/.test(cn.effectiveType))) {
return true;
}
return false;
}
// src/isSupportAbortController/index.ts
function isSupportsAbortController() {
return typeof globalThis.AbortController === "function";
}
// src/isSupportsFormData/index.ts
function isSupportsFormData() {
return typeof globalThis.FormData === "function";
}
// src/isSupportsRequestStreams/index.ts
function isSupportsRequestStreams() {
let duplexAccessed = false;
let hasContentType = false;
const supportsReadableStream = typeof globalThis.ReadableStream === "function";
const supportsRequest = typeof globalThis.Request === "function";
if (supportsReadableStream && supportsRequest) {
hasContentType = new globalThis.Request("https://empty.invalid", {
body: new globalThis.ReadableStream(),
method: "POST",
// @ts-expect-error - Types are outdated.
get duplex() {
duplexAccessed = true;
return "half";
}
}).headers.has("Content-Type");
}
return duplexAccessed && !hasContentType;
}
// src/isSupportsResponseStreams/index.ts
function isSupportsResponseStreams() {
return typeof globalThis.ReadableStream === "function";
}
// src/jsonLd/set.ld.ts
function genAuthorInfo(author) {
if (typeof author === "string") {
return { "@type": "Person", name: author };
}
return { "@type": author?.type ?? "Person", name: author.name, url: author?.url };
}
function setAuthorJsonLd(author) {
if (Array.isArray(author)) {
return author.map((author2) => genAuthorInfo(author2));
}
return genAuthorInfo(author);
}
function setPublisherJsonLd(name, logo) {
if (!name && !logo) {
return void 0;
}
return {
"@type": "Organization",
name,
logo: { "@type": "ImageObject", url: logo }
};
}
function setProvider(provider) {
if (provider) {
return {
"@type": provider.type || "Organization",
name: provider.name,
sameAs: provider.url
};
}
return void 0;
}
// src/jsonLd/article.ld.ts
function getNewsArticleJsonLd({
scriptId,
type = "NewsArticle",
keyOverride,
url,
title,
images,
section,
dateCreated,
datePublished,
dateModified,
authorName,
publisherName,
publisherLogo,
body,
...rest
}) {
const data = {
...rest,
mainEntityOfPage: {
"@type": "WebPage",
"@id": url
},
headline: title,
image: images,
articleSection: section,
dateCreated: dateCreated || datePublished,
datePublished,
dateModified: dateModified || datePublished,
author: setAuthorJsonLd(authorName),
publisher: setPublisherJsonLd(publisherName, publisherLogo),
articleBody: body
};
return toJsonLd("NewsArticle", { ...data });
}
// src/jsonLd/blogPost.ld.ts
function getBlogAuthorJsonLd(props) {
const data = {
mainEntityOfPage: {
"@type": "WebPage",
"@id": props.canonical
},
headline: props.title,
description: props.description,
author: setAuthorJsonLd(props.author),
publisher: setPublisherJsonLd(props.publisher.name, props.publisher.logo),
datePublished: props.datePublished,
image: props.image
};
if (props.thumbnail) {
data.image = props.thumbnail;
}
return toJsonLd("BlogPosting", data);
}
// src/jsonLd/breadcrumb.ld.ts
function setItemListElementsJson(items) {
if (items && items.length > 0) {
return items.map((item) => ({
"@type": "ListItem",
position: item.position,
item: {
"@id": item.item,
name: item.name
}
}));
}
return void 0;
}
function getBreadcrumbJsonLd(items) {
return toJsonLd("BreadcrumbList", {
itemListElement: setItemListElementsJson(items)
});
}
// src/jsonLd/course.ld.ts
function getCourseJsonLd(name, provider, props) {
const data = {
...props,
name,
provider: setProvider(provider)
};
return toJsonLd("Course", data);
}
// src/jsonLd/index.ts
function toJsonLd(type, jsonLd) {
const { id = void 0 } = jsonLd;
const updated = {
...id ? { "@id": jsonLd.id } : {},
...jsonLd
};
delete updated.id;
return JSON.stringify({
"@context": "https://schema.org",
"@type": type,
...updated
});
}
// src/isSymbol.ts
function isSymbol(val) {
return typeof val === "symbol";
}
// src/isToday.ts
function isToday(date) {
return isSameDay(date, /* @__PURE__ */ new Date());
}
// src/isUndefined.ts
function isUndefined(val) {
return typeof val === "undefined";
}
// src/isWebkit.ts
function isWebkit() {
return typeof document !== "undefined" && "webkitFontSmoothing" in document.documentElement.style;
}
// src/isWindow.ts
function isWindows() {
return /^win/i.test(globProcess.platform || "");
}
// src/kebabize/index.ts
function kebabize(value) {
return value.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($2, ofs) => (ofs ? "-" : "") + $2.toLowerCase());
}
// src/listify/index.ts
function listify(obj, mapFn) {
return Object.entries(obj).reduce((acc, [key, value]) => {
acc.push(mapFn(key, value));
return acc;
}, []);
}
// src/lookupMineType/index.ts
var MIME_TYPES = {
"3g2": "video/3gpp2",