@dxtmisha/functional-basic
Version:
Core functional utility library for modern web development without framework dependencies
1,764 lines • 159 kB
JavaScript
var Rt = Object.defineProperty;
var Pt = (i, t, e) => t in i ? Rt(i, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[t] = e;
var c = (i, t, e) => Pt(i, typeof t != "symbol" ? t + "" : t, e);
import { geo as Wt } from "@dxtmisha/media";
function L(i, t) {
return t ? Object.assign({}, i, t) : Object.assign({}, i);
}
function m(i) {
return !!(i && typeof i == "object");
}
function g(i, t) {
if (m(i)) {
const e = [];
return i instanceof Map ? i.forEach((s, n) => e.push(t(s, n, i))) : Array.isArray(i) ? i.forEach((s, n) => e.push(t(s, n, i))) : Object.entries(i).forEach(
([s, n]) => e.push(t(n, s, i))
), e.filter((s) => s !== void 0);
}
return [];
}
function kt(i, t = "=", e = "&") {
return g(
i,
(s, n) => `${n}${t}${encodeURIComponent(String(s).trim())}`
).sort().join(e);
}
function q(i) {
return i == null;
}
function D(i, t) {
if (i) {
if (t && i === "0")
return !0;
switch (typeof i) {
case "bigint":
case "number":
return i !== 0;
case "boolean":
return i;
case "function":
case "symbol":
return !0;
case "object":
return Array.isArray(i) ? i.length > 0 : Object.values(i).some((e) => !q(e));
case "string":
return !["", "undefined", "null", "0", "false", "[]"].includes(i);
case "undefined":
return !1;
default:
return !!i;
}
}
return !1;
}
function C(i) {
return m(i) && !Array.isArray(i);
}
function z(i) {
return typeof i == "string";
}
function j(i) {
return JSON.parse(JSON.stringify(i));
}
function l() {
return typeof window != "undefined" && !!window.document;
}
function at(i) {
switch (typeof i) {
case "number":
return !0;
case "string":
return !!i.match(/^[0-9]+$/);
default:
return !1;
}
}
function k(i) {
if (typeof i == "number")
return i;
if (!i)
return 0;
let t = i.replace(/[^\d., ]+/ig, "");
return t.match(/( [0-9]{3}[ ,.]|[0-9] [0-9])/ig) ? t = t.replace(/ /ig, "").replace(/,/ig, ".") : t.match(/,[0-9]{3}[,.]/ig) ? t = t.replace(/,/ig, "") : t.match(/[.][0-9]{3}[,.]/ig) ? t = t.replace(/[.]/ig, "").replace(/,/ig, ".") : t = t.replace(/,/ig, "."), parseFloat(t);
}
function it(i, t) {
return q(i) ? !1 : Array.isArray(t) ? t.includes(i) : at(i) && at(t) ? k(i) === k(t) : i === t;
}
function Ct(i) {
return i instanceof Function || typeof i == "function";
}
function E(i) {
return Ct(i) ? i() : i;
}
const T = {};
let ct = "ui-storage";
class O {
/**
* Constructor
* @param name value name/ название значения
* @param isSession should we use a session/ использовать ли сессию
*/
constructor(t, e = !1) {
c(this, "value");
c(this, "age");
this.name = t, this.isSession = e;
const s = `${e ? "session" : "storage"}#${t}`;
if (s in T)
return T[s];
this.make(), T[s] = this;
}
/**
* Changing the prefix in key names. Should be called at the beginning of the code.
*
* Изменение префикса в названиях ключей. Вызывать нужно в начале кода.
* @param newPrefix new prefix/ новый префикс
*/
static setPrefix(t) {
ct = t;
}
/**
* Getting data from local storage.
*
* Получение данных из локального хранилища.
* @param defaultValue default value/ значение по умолчанию
* @param cache cache time/ время кэширования
*/
get(t, e) {
if (this.value !== null && this.value !== void 0 && this.isCache(e))
return this.value;
if (t !== void 0)
return this.set(t);
}
/**
* Changing data in storage.
*
* Изменение данных в хранилище.
* @param value new values/ новые значения
*/
set(t) {
var e;
return this.value = E(t), this.age = (/* @__PURE__ */ new Date()).getTime(), this.value === void 0 ? this.remove() : (e = this.getMethod()) == null || e.setItem(this.getIndex(), JSON.stringify({
value: this.value,
age: this.age
})), this.value;
}
/**
* Removing data from storage.
*
* Удаление данных из хранилища.
*/
remove() {
var t;
return (t = this.getMethod()) == null || t.removeItem(this.getIndex()), this;
}
/**
* Clearing all data from storage.
*
* Очистка всех данных из хранилища.
*/
update() {
return this.make(), this;
}
/**
* Checks for storage time limit.
*
* Проверяет на лимит времени хранения.
* @param cache cache time/ время кэширования
*/
isCache(t) {
return q(t) || this.age && this.age + t * 1e3 >= (/* @__PURE__ */ new Date()).getTime();
}
/**
* Returns an object for working with storage.
*
* Возвращает объект для работы с хранилищем.
*/
getMethod() {
if (l()) {
const t = this.isSession ? window == null ? void 0 : window.sessionStorage : window == null ? void 0 : window.localStorage;
if (t)
return t;
}
}
/**
* Getting the storage key name.
*
* Получение имени ключа в хранилище.
*/
getIndex() {
return `${ct}__${this.name}`;
}
/**
* Getting data from storage.
*
* Получение данных из хранилища.
*/
getValue() {
var e;
const t = (e = this.getMethod()) == null ? void 0 : e.getItem(this.getIndex());
if (t)
try {
return JSON.parse(t);
} catch (s) {
console.error("DataStorage", s);
}
}
/**
* Filling in the data from storage.
*
* Заполнение данными из хранилища.
*/
make() {
const t = this.getValue();
return t ? (this.value = t.value, this.age = t.age) : (this.value = void 0, this.age = void 0), this;
}
}
const jt = "geo-code", p = class p {
/**
* Information about the current country.
*
* Информация об текущей стране.
*/
static get() {
return this.item;
}
/**
* Current country.
*
* Текущая страна.
*/
static getCountry() {
return this.item.country;
}
/**
* Current language.
*
* Текущий язык.
*/
static getLanguage() {
return this.language;
}
/**
* Full format according to the standard.
*
* Полный формат согласно стандарту.
*/
static getStandard() {
return this.item.standard;
}
/**
* Returns the first day of the week.
*
* Возвращает первый день недели.
*/
static getFirstDay() {
return this.item.firstDay;
}
/**
* Full format.
*
* Полный формат.
*/
static getLocation() {
return this.location;
}
/**
* Obtaining processed data.
*
* Получение обработанных данных.
*/
static getItem() {
return L(this.item, {
language: this.language
});
}
/**
* Returns the full list of countries.
*
* Возвращает полный список стран.
*/
static getList() {
return Wt;
}
/**
* Returns the data about the country by its full code.
*
* Возвращает данные о стране по ее полному коду.
* @param code country code, full form language-country or one of them/
* код страны, полный вид язык-страна или один из них
*/
static getByCode(t) {
let e;
return t && (t.match(/([A-Z]{2}-[a-z]{2})|([a-z]{2}-[A-Z]{2})/) && (e = this.getByCodeFull(t)), !e && t.match(/[A-Z]{2}/) && (e = this.getByCountry(this.toCountry(t))), !e && t.match(/[a-z]{2}/) && (e = this.getByLanguage(this.toLanguage(t)))), this.toFull(j(e != null ? e : this.getList()[0]));
}
/**
* Returns the full data by language and country.
*
* Возвращает полные данные по языку и стране.
* @param code string in the form of language-country/ строка в виде язык-страна
*/
static getByCodeFull(t) {
return this.getList().find(
(e) => it(t, [
`${e.language}-${e.country}`,
`${e.country}-${e.language}`
])
);
}
/**
* Returns the full data by country.
*
* Возвращает полные данные по стране.
* @param country country/ страна
*/
static getByCountry(t) {
return this.getList().find((e) => {
var s;
return e.country === t || ((s = e == null ? void 0 : e.countryAlternative) == null ? void 0 : s.find((n) => n === t));
});
}
/**
* Returns the full data by language.
*
* Возвращает полные данные по языку.
* @param language language/ язык
*/
static getByLanguage(t) {
return this.getList().find((e) => {
var s;
return e.language === t || ((s = e == null ? void 0 : e.languageAlternative) == null ? void 0 : s.find((n) => n === t));
});
}
/**
* Retrieving the default timezone.
*
* Получение временной зоны по умолчанию
*/
static getTimezone() {
return this.timezone;
}
/**
* Retrieving the default timezone (formatted view).
*
* Получение временной зоны по умолчанию (отформатированный вид).
*/
static getTimezoneFormat() {
const t = Math.abs(Math.trunc(this.timezone / 60)).toString().padStart(2, "0"), e = Math.abs(this.timezone % 60).toString().padStart(2, "0");
return this.timezone >= 0 ? `-${t}:${e}` : `+${t}:${e}`;
}
/**
* Determines the current country by its full name.
*
* Определяет текущую страну по ее полному названию.
* @param code country code, full form language-country or one of them/
* код страны, полный вид язык-страна или один из них
*/
static find(t) {
return this.getByCode(t);
}
/**
* Returns a complete string with the country code and language.
*
* Возвращает полную строку с кодом страны и языка.
* @param item object with data about the current country/
* объект с данными об текущей стране
*/
static toStandard(t) {
return `${t.language}-${t.country}`;
}
/**
* Changes the data by the full code.
*
* Изменяет данные по полному коду.
* @param code country code, full form language-country or one of them/
* код страны, полный вид язык-страна или один из них
* @param save save the result/ сохранить результат
*/
static set(t, e) {
this.location = t, this.item = this.getByCode(this.location), this.language = this.findLanguage(this.location), e && this.storage.set(this.location);
}
/**
* Changing the default timezone for transmitted dates.
*
* Изменение временной зоны по умолчанию для отправляемых дат
* @param timezone new time zone/ новая временная зона
*/
static setTimezone(t) {
this.timezone = t;
}
/**
* Determines the current location.
*
* Определяет текущую локацию.
*/
static findLocation() {
var t;
return l() && (this.storage.get() || ((t = document.querySelector("html")) == null ? void 0 : t.lang) || navigator.language || navigator.languages[0] || "en-GB") || "en-GB";
}
/**
* Determines the current language.
*
* Определяет текущий язык.
* @param code country code, full form language-country or one of them/
* код страны, полный вид язык-страна или один из них
*/
static findLanguage(t) {
return t && t.match(/[a-z]{2}/) ? this.toLanguage(t) : this.item.language;
}
/**
* Returns the country code by its full language-country.
*
* Возвращает код страны по ее полному язык-страна.
* @param code country code/ код страна
*/
static toCountry(t) {
return t.replace(/[^A-Z]+/g, "");
}
/**
* Returns the language code by its full language-country.<br>
* Возвращает код языка по его полному язык-страна.
* @param code country code/ код страна
*/
static toLanguage(t) {
return t.replace(/[^a-z]+/g, "");
}
/**
* Adding missing data.<br>
* Добавление недостающих данных.
* @param item object with data about the current country/
* объект с данными об текущей стране
*/
static toFull(t) {
return L(t, {
standard: this.toStandard(t),
firstDay: (t == null ? void 0 : t.firstDay) || "Mo"
});
}
};
c(p, "storage", new O(jt)), c(p, "location"), c(p, "item"), c(p, "language"), c(p, "timezone", (/* @__PURE__ */ new Date()).getTimezoneOffset()), p.location = p.findLocation(), p.language = p.findLanguage(p.location), p.item = p.getByCode(p.location);
let b = p;
function At(i) {
return l() && i === window;
}
function A(i) {
var t;
if (l())
return At(i) ? document.body : z(i) ? (t = document.querySelector(i)) != null ? t : void 0 : i;
}
function ut(i) {
return At(i) ? i : A(i);
}
function Ut(i) {
var t;
return !!((t = A(i)) != null && t.closest("html"));
}
function H(i) {
return Array.isArray(i) ? i : [i];
}
class ht {
/**
* Classes Constructor
* @param elementSelector element/ элемент
* @param type type/ тип
* @param listener the object that receives a notification (an object that implements the
* Event interface) when an event of the specified type occurs/ объект, который принимает
* уведомление, когда событие указанного типа произошло
* @param options object that specifies characteristics/ объект options
* @param detail an event-dependent value associated with the event/ зависимое от события
* значение, связанное с событием
*/
constructor(t, e = ["click"], s, n, o) {
/**
* Element.
*
* Элемент.
*/
c(this, "element");
/**
* Element for checking. If the element is missing in the DOM, the event is turned off.
*
* Элемент для проверки. Если элемент отсутствует в DOM, событие выключается.
*/
c(this, "elementControl");
c(this, "elementControlEdit");
/**
* A case-sensitive string representing the event type to listen for.
*
* Чувствительная к регистру строка, представляющая тип обрабатываемого события.
*/
c(this, "type");
/**
* The object that receives a notification (an object that implements the Event interface)
* when an event of the specified type occurs. This must be null, an object with a
* handleEvent() method, or a JavaScript function.
*
* Объект, который принимает уведомление, когда событие указанного типа произошло.
* Это должен быть объект, реализующий интерфейс EventListener или просто функция JavaScript.
*/
c(this, "listenerRecent", (t) => {
var e, s;
Ut(this.elementControl) ? ((e = this.listener) == null || e.call(this.element, t, this.detail), m(this.options) && ((s = this.options) != null && s.once) && this.stop()) : this.stop();
});
/**
* Event states.
*
* Состояния события.
*/
c(this, "activity", !1);
c(this, "activityItems", []);
this.listener = s, this.options = n, this.detail = o, this.element = ut(t), this.elementControl = A(t), this.type = H(e);
}
/**
* Checks whether event listening is currently enabled.
*
* Проверяет, включено ли сейчас прослушивание события.
*/
isActive() {
return this.activity;
}
getElement() {
return this.element;
}
/**
* Change of an element for tracking.
*
* Изменение элемента для прослеживания.
* @param elementSelector element/ элемент
*/
setElement(t) {
const e = ut(t);
return this.elementControlEdit || (this.elementControl = A(t)), this.element = e, this.reset(), this;
}
/**
* Modifies the object that receives the notification.
*
* Модифицирует объект, который получает уведомление.
* @param elementSelector element/ элемент
*/
setElementControl(t) {
return this.elementControl = A(t), this.elementControlEdit = !q(this.elementControl), this.elementControlEdit || (this.elementControl = A(this.element)), this;
}
/**
* Changes the type of the handled event.
*
* Изменяет тип обрабатываемого события.
* @param type type/ тип
*/
setType(t) {
return this.type = H(t), this.reset(), this;
}
/**
* Modifies the object that receives the notification.
*
* Модифицирует объект, который получает уведомление.
* @param listener
*/
setListener(t) {
return this.listener = t, this;
}
/**
* Modifying the options object that defines the characteristics of an object.
*
* Изменение объекта options, который определяет характеристики объекта.
* @param options
*/
setOptions(t) {
return this.options = t, this.reset(), this;
}
/**
* Modifying a dependent value for the dispatch method.
*
* Изменение зависимого значения для метода dispatch.
* @param detail
*/
setDetail(t) {
return this.detail = t, this;
}
/**
* The method of the EventTarget sends an Event to the object, (synchronously) invoking
* the affected EventListeners in the appropriate order.
*
* Отправляет событие в общую систему событий. Это событие подчиняется тем же правилам
* поведения "Захвата" и "Всплывания" как и непосредственно инициированные события.
* @param detail an event-dependent value associated with the event/ зависимое от события
* значение, связанное с событием
*/
dispatch(t = this.detail) {
return this.type.forEach(
(e) => {
var s;
return (s = this.element) == null ? void 0 : s.dispatchEvent(new CustomEvent(e, { detail: t }));
}
), this;
}
/**
* Starting event listening.
*
* Запуск прослушивания события.
*/
start() {
return this.activity || (this.activity = !0, this.activityItems = [], this.type.forEach((t) => {
this.element && !(t === "resize" && this.makeResize()) && !(t === "scroll-sync" && this.makeScroll()) && (this.element.addEventListener(t, this.listenerRecent, this.options), this.activityItems.push({
element: this.element,
type: t
}));
})), this;
}
/**
* Stopping event listening.
*
* Остановка прослушивания события.
*/
stop() {
return this.activity && (this.activity = !1, this.activityItems.forEach(({
element: t,
type: e,
listener: s,
observer: n
}) => {
n ? n.disconnect() : s ? t == null || t.removeEventListener(e, s) : t == null || t.removeEventListener(e, this.listenerRecent);
})), this;
}
/**
* Toggling event handler state.
*
* Переключение состояния работы события.
* @param activity event activation/ активация события
*/
toggle(t) {
return t ? this.start() : this.stop();
}
/**
* Overloads the listening events.
*
* Перегружает события прослушивания.
*/
reset() {
return this.activity && (this.stop(), this.start()), this;
}
/**
* Checks if the ResizeObserver object exists.
*
* Проверяет, существует ли объект ResizeObserver.
*/
isObserver() {
return "ResizeObserver" in window;
}
/**
* The implementation of the resize event for an element.
*
* Реализация события изменения размера для элемента.
*/
makeResize() {
if (this.element && this.element instanceof HTMLElement && this.element !== document.body && this.isObserver()) {
const t = new ResizeObserver(
(e) => this.listenerRecent(e == null ? void 0 : e[0])
);
return t.observe(this.element), this.activityItems.push({
element: this.element,
type: "resize",
observer: t
}), !0;
}
return !1;
}
/**
* Implementation of the scroll event for an element.
*
* Реализация события изменения положения скролла для элемента.
*/
makeScroll() {
if (this.element) {
let t = !1;
const e = (s) => {
t || (t = !0, requestAnimationFrame(() => {
this.listenerRecent(s), t = !1;
}));
};
return this.element.addEventListener("scroll", e, this.options), this.element.addEventListener("resize", e, this.options), this.activityItems.push(
{
element: this.element,
type: "scroll",
listener: e
},
{
element: this.element,
type: "resize",
listener: e
}
), !0;
}
return !1;
}
}
const lt = "ui-loading", K = class K {
/**
* Check if the loader is active now.
*
* Проверить, активен ли сейчас загрузчик.
*/
static is() {
return this.value > 0;
}
/**
* Shows the loader.
*
* Показывает загрузчик.
*/
static show() {
this.value++, this.dispatch();
}
/**
* Hides the loader.
*
* Скрывает загрузчик.
*/
static hide() {
this.is() && (this.value--, this.dispatch());
}
/**
* Event registration to listen for data changes.
*
* Регистрация события для прослушивания изменений данных.
* @param listener the object that receives a notification (an object that implements the
* Event interface) when an event of the specified type occurs/ объект, который принимает
* уведомление, когда событие указанного типа произошло
* @param element element/ элемент
*/
static registrationEvent(t, e) {
l() && new ht(window, lt, t).setElementControl(e).start();
}
/**
* Calls the event listener.
*
* Вызывает слушателя событий.
*/
static dispatch() {
var t;
(t = this.event) == null || t.dispatch({ loading: this.is() });
}
};
c(K, "value", 0), c(K, "event"), l() && (K.event = new ht(window, lt));
let x = K;
class zt {
constructor() {
/** Default headers/ Заголовки по умолчанию */
c(this, "headers", {});
}
/**
* Getting the header for the request.
*
* Получение заголовка для запроса.
* @param value list of headers/ список заголовков
* @param type type of request/ тип запроса
*/
get(t, e = "application/json;charset=UTF-8") {
if (t !== null) {
const s = L(
this.headers,
t
);
return D(e) && (s["Content-Type"] = e), s;
}
}
/**
* Modifies the default header data.
*
* Изменяет данные заголовка по умолчанию.
*/
set(t) {
return C(t) && (this.headers = t), this;
}
}
var S = /* @__PURE__ */ ((i) => (i.get = "GET", i.post = "POST", i.put = "PUT", i.delete = "DELETE", i))(S || {});
class Ht {
constructor() {
/** Default request data/ Данные запроса по умолчанию */
c(this, "value");
}
/**
* Checks if default request data exists.
*
* Проверяет, существуют ли данные запроса по умолчанию.
*/
is() {
return !!this.value;
}
/**
* Gets the default request data.
*
* Получает данные запроса по умолчанию.
*/
get() {
return this.value;
}
/**
* Adds default data to the request.
*
* Добавляет данные по умолчанию к запросу.
* @param request request data/ данные запроса
*/
request(t) {
const e = this.get();
if (e) {
if (t instanceof FormData)
this.addByFormData(t, e);
else if (C(t))
return L(e, t);
}
return t;
}
/**
* Modifies the default request data.
*
* Изменяет данные запроса по умолчанию.
*/
set(t) {
this.value = t;
}
/**
* Adds default data to FormData request.
*
* Добавляет данные по умолчанию к запросу FormData.
* @param request FormData request/ запрос FormData
* @param value default values/ значения по умолчанию
*/
addByFormData(t, e) {
for (const s in e)
t.has(s) || t.set(s, e[s]);
}
}
class Zt {
constructor() {
c(this, "value");
}
/**
* Last response data
*
* Данные последнего ответа
*/
get() {
return this.value;
}
/**
* Returns the execution status code.
*
* Возвращает код статуса выполнения.
*/
getStatus() {
var t;
return (t = this.get()) == null ? void 0 : t.status;
}
/**
* Returns the execution status text.
*
* Возвращает текст статуса выполнения.
*/
getStatusText() {
var t;
return (t = this.get()) == null ? void 0 : t.statusText;
}
/**
* Returns the script execution error.
*
* Возвращает ошибку выполнения скрипта.
*/
getError() {
var t;
return (t = this.get()) == null ? void 0 : t.error;
}
/**
* Returns the data of the last request.
*
* Возвращает данные последнего запроса.
*/
getResponse() {
var t;
return (t = this.get()) == null ? void 0 : t.lastResponse;
}
/**
* Returns messages from the last request.
*
* Возвращает сообщения от последнего запроса.
*/
getMessage() {
var t;
return ((t = this.get()) == null ? void 0 : t.lastMessage) || "";
}
/**
* Sets the status item data.
*
* Устанавливает данные элемента статуса.
* @param data status item data/ данные элемента статуса
*/
set(t) {
return "status" in t && this.setValue("status", t.status), "statusText" in t && this.setValue("statusText", t.statusText), "error" in t && this.setValue("error", t.error), "lastResponse" in t && this.setValue("lastResponse", t.lastResponse), "lastMessage" in t && this.setValue("lastMessage", t.lastMessage), this;
}
/**
* Sets the status code and optional status text.
*
* Устанавливает код статуса и необязательный текст статуса.
* @param status status code/ код статуса
* @param statusText optional status text/ необязательный текст статуса
*/
setStatus(t, e) {
return this.set({
status: t,
statusText: e
}), this;
}
/**
* Sets the error message.
*
* Устанавливает сообщение об ошибке.
* @param error error message/ сообщение об ошибке
*/
setError(t) {
return this.set({ error: t }), this;
}
/**
* Sets the data of the last response.
*
* Устанавливает данные последнего ответа.
* @param response response data/ данные ответа
*/
setLastResponse(t) {
return t && C(t) && "message" in t && this.setLastMessage(String(t.message)), this.set({ lastResponse: t }), this;
}
/**
* Sets messages from the last request.
*
* Устанавливает сообщения от последнего запроса.
* @param message message text/ текст сообщения
*/
setLastMessage(t) {
return this.set({ lastMessage: t }), this;
}
/**
* Sets a specific field in the status item.
*
* Устанавливает конкретное поле в элементе статуса.
* @param name field name/ название поля
* @param value field value/ значение поля
*/
setValue(t, e) {
this.value || (this.value = {}), this.value[t] = e;
}
}
async function Kt(i) {
const t = E(i);
return t instanceof Promise ? await t : t;
}
function Y(i, t) {
return Math.floor(Math.random() * (t - i + 1) + i);
}
const dt = "d-response-loading";
class Vt {
/**
* Constructor
* @param requestDefault default request processor/ процессор запросов по умолчанию
*/
constructor(t) {
/** List of first-time API requests/ Список первичных API запросов */
c(this, "first", []);
/** Cached responses/ Кешированные ответы */
c(this, "response", []);
/** Loading instance/ Экземпляр загрузки */
c(this, "loading");
/** Developer mode flag/ Флаг режима разработчика */
c(this, "devMode", !1);
this.requestDefault = t;
}
/**
* Checks if there is a global cached request, if there is, returns it.
*
* Проверяет, есть ли глобальный кешированный запрос, если есть, возвращает его.
* @param path link to the request/ ссылка на запрос
* @param method request method/ метод запроса
* @param request data for the request/ данные для запроса
* @param devMode is it developer mode/ является ли режим разработчика
*/
get(t = "", e, s, n) {
return this.response.find((o) => !this.isDisable(o) && this.isPath(o, t) && e === o.method && this.isFirst(o, n) && this.isResponse(o, s) ? (this.isDevMode(n) && console.warn(`Response type: ${o.path}`), this.first.push(o), !0) : !1);
}
/**
* Returns a list of data about the emulator.
*
* Возвращает список данных об эмуляторе.
*/
getList() {
return this.response.filter((t) => t.isForGlobal !== !0);
}
/**
* Adding cached requests.
*
* Добавление кешированных запросов.
* @param response data for caching/ данные для кеширования
*/
add(t) {
return this.response.push(...H(t)), this;
}
/**
* Sets developer mode.
*
* Устанавливает режим разработчика.
* @param devMode is it developer mode/ является ли режим разработчика
*/
setDevMode(t) {
return this.devMode = t, this;
}
/**
* Выполнение эмулятора, если доступно
* @param apiFetch property of the request/ свойство запроса
*/
async emulator(t) {
const {
path: e = "",
method: s = S.get,
global: n = s === S.get,
devMode: o = !1
} = t;
if (n || this.isDevMode(o)) {
const a = this.requestDefault.request(t.request), u = this.get(e, s, a, o);
if (u) {
const h = await this.fetch(u, a);
return this.isDevMode(o) && console.warn("Response data:", e, a, h), h;
}
}
}
/**
* Checks if the cached item is disabled.
*
* Проверяет, отключен ли кешированный элемент.
* @param item cached item/ кешированный элемент
*/
isDisable(t) {
return !!E(t == null ? void 0 : t.disable);
}
/**
* Checks if the path matches the cached one.
*
* Проверяет, совпадает ли путь с кешированным.
* @param item cached item/ кешированный элемент
* @param path request path/ путь запроса
*/
isPath(t, e) {
return e === t.path || !!(t.path instanceof RegExp && e.match(t.path));
}
/**
* Checks if it is developer mode.
*
* Проверяет, является ли режимом разработчика.
* @param devMode is it developer mode/ является ли режим разработчика
*/
isDevMode(t) {
return t || this.devMode;
}
/**
* Checks if this is the first request.
*
* Проверяет, является ли это первым запросом.
* @param item cached item/ кешированный элемент
* @param devMode is it developer mode/ является ли режим разработчика
*/
isFirst(t, e) {
return this.first.indexOf(t) === -1 || this.isDevMode(e);
}
/**
* Checks if the request matches the cached one.
*
* Проверяет, совпадает ли запрос с кешированным.
* @param item cached item/ кешированный элемент
* @param request request data/ данные запроса
*/
isResponse(t, e) {
const s = this.requestDefault.request(t == null ? void 0 : t.request);
return e === s || s === "*any" || D(e) && D(s) && C(e) && C(s) && !(e instanceof FormData) && !(s instanceof FormData) && Object.values(e).length === Object.values(s).length && Object.entries(s).reduce(
(n, [o, a]) => n && (a === (e == null ? void 0 : e[o]) || a === "*any"),
!0
);
}
/**
* Emulates an execution request.
*
* Эмулирует запрос выполнения.
* @param response Data for pre-request/ Данные для пред-запроса
* @param request data for the request/ данные для запроса
*/
fetch(t, e) {
return this.startResponseLoading(), new Promise((s) => {
Kt(
Ct(t.response) ? t.response(e) : t.response
).then((n) => {
t != null && t.lag ? (x.show(), setTimeout(() => {
this.stopResponseLoading(), s(n), x.hide();
}, Y(0, 2e3))) : (this.stopResponseLoading(), s(n));
});
});
}
/**
* Enable loading for request emulation.
*
* Включить загрузку для эмуляции запроса.
*/
startResponseLoading() {
this.loading && clearTimeout(this.loading), l() && document.body.classList.add(dt);
}
/**
* Disable loading for request emulation.
*
* Отключить загрузку для эмуляции запроса.
*/
stopResponseLoading() {
this.loading = setTimeout(() => {
this.loading = void 0, l() && document.body.classList.remove(dt);
}, 1200);
}
}
class Yt {
constructor() {
/** Function for call before the request/ Функция для вызова перед запросом */
c(this, "callback");
/** Function for call after the request/ Функция для вызова после запроса */
c(this, "callbackEnd");
/** Is the preparation in progress/ Идет ли подготовка */
c(this, "loading", !1);
}
/**
* Preparation before executing the request.
*
* Подготовка перед выполнением запроса.
* @param active is preparation active/ активна ли подготовка
*/
async make(t) {
if (t && this.callback)
return this.go();
}
/**
* Analysis of the request after execution.
*
* Анализ запроса после выполнения.
* @param active is preparation active/ активна ли подготовка
* @param query data received in the request/ данные, полученные в запросе
*/
async makeEnd(t, e) {
let s = {};
return t && this.callbackEnd && (s = await this.callbackEnd(e)), s;
}
/**
* The function is modified for a call before the request.
*
* Изменить функцию перед запросом.
* @param callback function for call/ функция для вызова
*/
set(t) {
return this.callback = t, this;
}
/**
* Modify the function after the request.
*
* Изменить функцию после запроса.
* @param callback function for call/ функция для вызова
*/
setEnd(t) {
return this.callbackEnd = t, this;
}
/**
* To execute preparation.
*
* Выполнить подготовку.
*/
async go() {
return new Promise((t) => {
this.loading ? setTimeout(() => this.go().then(t), 160) : this.callback ? (this.loading = !0, this.callback().then(() => {
this.loading = !1, t();
})) : t();
});
}
/**
* Analysis of the request after execution.
*
* Анализ запроса после выполнения.
* @param query data received in the request/ данные, полученные в запросе
*/
async end(t) {
let e = {};
return this.callbackEnd && (e = await this.callbackEnd(t)), e;
}
}
const w = class w {
/**
* Is the server local.
*
* Является ли сервер локальный.
*/
static isLocalhost() {
return typeof location == "undefined" || location.hostname === "localhost";
}
/**
* Returns the status of the last request.
*
* Возвращает статус последнего запроса.
*/
static getStatus() {
return this.status;
}
/**
* Getting the response handler.
*
* Получение обработчика ответа.
*/
static getResponse() {
return this.response;
}
/**
* Getting the full path to the request script.
*
* Получение полного пути к скрипту запроса.
* @param path path to the script/ путь к скрипту
* @param api adding a path to the site’s API/ добавление пути к API сайта
*/
static getUrl(t, e = !0) {
return `${e ? this.url : ""}${t}`.replace("{locale}", b.getLocation()).replace("{country}", b.getCountry()).replace("{language}", b.getLanguage());
}
/**
* Getting data for the body.
*
* Получение данных для тела.
* @param request this request/ данный запрос
* @param method method for request/ метод запрос
*/
static getBody(t = {}, e = S.get) {
if (t instanceof FormData)
return t;
if (e !== S.get && D(t))
return z(t) ? t : JSON.stringify(t);
}
/**
* Getting data for the body of the get method.
*
* Получение данных для тела метода get.
* @param request this request/ данный запрос
* @param path path to request/ путь к запрос
* @param method method for request/ метод запрос
*/
static getBodyForGet(t, e = "", s = S.get) {
if (s === S.get) {
const n = e.match(/\?/) ? "&" : "?", o = typeof t == "object" ? kt(t) : t;
if (D(o))
return `${n}${o}`;
}
return "";
}
/**
* Modifies the default header data.
*
* Изменяет данные заголовка по умолчанию.
*/
static setHeaders(t) {
return this.headers.set(t), w;
}
/**
* Modifies the default request data.
*
* Изменяет данные запроса по умолчанию.
*/
static setRequestDefault(t) {
return this.requestDefault.set(t), w;
}
/**
* Change the base path to the script.
*
* Изменить базовый путь к скрипту.
* @param url path to the script/ путь к скрипту
*/
static setUrl(t) {
return this.url = t, w;
}
/**
* The function is modified for a call before the request.
*
* Изменить функцию перед запросом.
* @param callback function for call/ функция для вызова
*/
static setPreparation(t) {
return this.preparation.set(t), w;
}
/**
* Modify the function after the request.
*
* Изменить функцию после запроса.
* @param callback function for call/ функция для вызова
*/
static setEnd(t) {
return this.preparation.setEnd(t), w;
}
/**
* To execute a request.
*
* Выполнить запрос.
* @param pathRequest query string or list of parameters/ строка запроса или список параметров
*/
static async request(t) {
return z(t) ? await this.fetch({
path: t
}) : await this.fetch(t);
}
/**
* Sends a get method request.
*
* Отправляет запрос метода get.
* @param request list of parameters/ список параметров
*/
static get(t) {
return this.request(L(t, {
method: S.get
}));
}
/**
* Sends a post method request.
*
* Отправляет запрос метода post.
* @param request list of parameters/ список параметров
*/
static post(t) {
return this.request(L(t, {
method: S.post
}));
}
/**
* Sends a put method request.
*
* Отправляет запрос метода put.
* @param request list of parameters/ список параметров
*/
static put(t) {
return this.request(L(t, {
method: S.put
}));
}
/**
* Sends a delete method request.
*
* Отправляет запрос метода delete.
* @param request list of parameters/ список параметров
*/
static delete(t) {
return this.request(L(t, {
method: S.delete
}));
}
/**
* To execute a request.
*
* Выполнить запрос.
* @param apiFetch property of the request/ свойство запроса
*/
static async fetch(t) {
const {
toData: e = !0,
hideError: s = !1,
queryReturn: n = void 0,
globalPreparation: o = !0,
globalEnd: a = !0
} = t, u = await this.response.emulator(t);
if (u)
return u;
let h = {};
x.show();
try {
await this.preparation.make(o);
const f = await this.makeQuery(t), d = await this.preparation.makeEnd(a, f);
if (this.status.setStatus(
f.status,
f.statusText
), d != null && d.reset)
return x.hide(), await this.fetch(t);
h = await this.readData(
f,
n,
d
);
} catch (f) {
s || console.error("Api: ", f), this.status.setError(String(f));
}
return x.hide(), this.makeData(h, e);
}
/**
* Reading data from the response.
*
* Чтение данных из ответа.
* @param query response from the server/ ответ от сервера
* @param queryReturn custom function for reading data/ кастомная функция для чтения данных
* @param end finalization data/ данные финализации
*/
static async readData(t, e, s) {
var n;
return e ? await e(t) : "data" in s ? s.data : ((n = t.headers.get("Content-Type")) != null ? n : "").match("application/json") ? await t.json() : { data: await t.text() };
}
/**
* Executing the request.
*
* Выполнение запроса.
* @param apiFetch property of the request/ свойство запроса
*/
static async makeQuery(t) {
const e = this.requestDefault.request(t.request), {
api: s = !0,
path: n = "",
pathFull: o = void 0,
method: a = S.get,
headers: u = {},
type: h = "application/json;charset=UTF-8",
init: f = {}
} = t, d = o != null ? o : this.getUrl(n, s), I = `${d}${this.getBodyForGet(e, d, a)}`, Q = this.headers.get(u, h), X = L(f, {
method: a,
body: this.getBody(e, a)
});
return Q && (X.headers = Q), await fetch(I, X);
}
/**
* Transforms data if needed.
*
* Преобразует данные, если нужно.
* @param data data for transformation/ данные для преобразования
* @param toData is it necessary to process the data/ нужно ли обрабатывать данные
*/
static makeData(t, e) {
if (this.status.setLastResponse(t), t && e && C(t) && "data" in t) {
if (C(t.data)) {
const s = L(t.data);
return "success" in t && (s.success = t.success), s;
}
return t.data;
}
return t;
}
};
c(w, "url", "/api/"), c(w, "headers", new zt()), c(w, "requestDefault", new Ht()), c(w, "status", new Zt()), c(w, "response", new Vt(w.requestDefault)), c(w, "preparation", new Yt());
let U = w;
class Se {
/**
* Constructor
* @param name channel name/ название канала
* @param callback callback on message received/ колбэк на получение сообщения
*/
constructor(t, e) {
c(this, "channel");
/**
* Update state on message received.
*
* Обновление состояния при получении сообщения.
* @param event message event/ событие сообщения
*/
c(this, "update", (t) => {
var e;
return (e = this.callback) == null || e.call(this, t), this;
});
if (this.callback = e, l())
try {
this.channel = new BroadcastChannel(`${qt()}__${t}`), this.channel.onmessage = this.update;
} catch (s) {
console.error(`BroadcastMessage ${t}:`, s);
}
}
/**
* Send a message to the channel.
*
* Отправить сообщение в канал.
* @param message message to send/ сообщение для отправки
*/
post(t) {
var e;
return (e = this.channel) == null || e.postMessage(t), this;
}
/**
* Set the callback function to be called when a message is received.
*
* Установить функцию колбэка, которая будет вызвана при получении сообщения.
* @param callback callback function/ функция колбэка
*/
setCallback(t) {
return this.callback = t, this;
}
}
const qt = () => new O("__broadcast-name").get(() => `name_${Y(1e6, 9999999)}`);
class Jt {
/**
* Constructor
* @param callback function for the cache/ функция для кэша
*/
constructor(t) {
c(this, "cache");
c(this, "cacheOld");
c(this, "comparisons", []);
this.callback = t;
}
/**
* Getting data for the cache, and if there is no cache, it performs a function to save the cache.
*
* Получение данных для кэша, и если нет кэша, выполняет функцию для сохранения кэша.
* @param comparison additional data for comparison/ дополнительные данные для сравнения
*/
getCache(t) {
return this.isUpdate(t) && (this.cacheOld = this.cache, this.setCache()), this.cache;
}
/**
* Getting the previous value of the cache.
*
* Получение предыдущего значения кэша.
*/
getCacheOld() {
return this.cacheOld;
}
/**
* Getting data for the cache, and if there is no cache, it performs a function to save the cache (Async).
*
* Получение данных для кэша, и если нет кэша, выполняет функцию для сохранения кэша (Async).
* @param comparison additional data for comparison/ дополнительные данные для сравнения
*/
async getCacheAsync(t) {
return this.isUpdate(t) && (this.cacheOld = this.cache, await this.setCacheAsync()), this.cache;
}
/**
* Overwrites or adds new values for the cache.
*
* Перезаписывает или добавляет новые значения для кэша.
*/
setCache() {
this.cache = this.callback();
}
/**
* Overwrites or adds new values for the cache (Async).
*
* Перезаписывает или добавляет новые значения для кэша (Async).
*/
async setCacheAsync() {
this.cache = await this.callback();
}
/**
* Checking additional data.
*
* Проверка дополнительных данных.
* @param comparison additional data for comparison/ дополнительные данные для сравнения
*/
isUpdate(t) {
return this.cache === void 0 || this.comparisons.length !== t.length || this.comparisons.findIndex((e, s) => e !== t[s]) >= 0 ? (this.comparisons = [...t], !0) : !1;
}
}
class Qt {
constructor() {
c(this, "cache", {});
}
/**
* Getting data for the cache, and if there is no cache, it performs a function to save the cache.
*
* Получение данных для кэша, и если нет кэша, выполняет функцию для сохранения кэша.
* @param name cache name/ название кэша
* @param callback function for the cache/ функция для кэша
* @param comparison additional data for comparison/ дополнительные данные для сравнения
*/
get(t, e, s) {
return this.getCacheItem(t, e).getCache(s != null ? s : []);
}
/**
* Getting data for the cache, and if there is no cache, it performs a function to save the cache (Async).
*
* Получение данных для кэша, и если нет кэша, выполняет функцию для сохранения кэша (Async).
* @param name cache name/ название кэша
* @param callback function for the cache/ функция для кэша
* @param comparison additional data for comparison/ дополнительные данные для сравнения
*/
async getAsync(t, e, s) {
return await this.getCacheItem(t, e).getCacheAsync(s != null ? s : []);
}
/**
* Returns an instance of the object for working with the cache element.
*
* Возвращает экземпляр объекта для работы с элементом кэша.
* @param name cache name/ название кэша
* @param callback function for the cache/ функция для кэша
*/
getCacheItem(t, e) {
return t in this.cache || (this.cache[t] = new Jt(e)), this.cache[t];
}
}
const _ = class _ {
/**
* Getting data for the cache, and if there is no cache, it performs a function to save the cache.
*
* Получение данных для кэша, и если нет кэша, выполняет функцию для сохранения кэша.
* @param name cache name/ название кэша
* @param callback function for the cache/ функция для кэша
* @param comparison additional data for comparison/ дополнительные данные для сравнения
*/
static get(t, e, s) {
return this.cache.get(t, e, s);
}
};
c(_, "cache"), _.cache = new Qt();
let gt = _;
function Nt(i, t = !1) {
if (typeof i == "string") {
const e = i.trim();
switch (e) {
case "undefined":
return;
case "null":
return null;
case "true":
return !0;
case "false":
return !1;
default:
if (/^[{[]/.exec(e))
try {
return JSON.parse(e);
} catch (s) {
console.error("transformation: JSON error", s);
}
else {
if (/^[0-9]+\.[0-9.]+$/.exec(e))
return parseFloat(e);
if (/^[0-9]+$/.exec(e))
return parseInt(e, 10);
if (t && l() && typeof (window == null ? void 0 : window[e]) == "function")
return window[e];
}
}
}
return i;
}
const Xt = "cookie-block";
class Et {
/**
* Obtaining status.
*
* Получение статуса.
*/
static get() {
var t;
return (t = this.storage.get()) != null ? t : !1;
}
/**
* Changing status.
*
* Изменение статуса.
* @param value value to be changed/ значение, на которое будет изменен
*/
static set(t) {
this.storage.set(t);
}
}
c(Et, "storage", new O(Xt));
const M = {}, ot = class ot {
constructor(t) {
c(this, "value");
c(this, "options", {});
if (this.name = t, t in G)
return G[t];
this.value = M == null ? void 0 : M[t], G[t] = this;
}
/**
* Get data or update if none.
*
* Получает данные или обновляет, если их нет.
* @param defaultValue value or function to change data/ значение или функция для изменения данных
* @param options additional parameters/ дополнительные параметры
*/
get(t, e) {
return this.value === void 0 && t && this.set(t, e), this.value;
}
/**
* Updates cookie data.
*
* Обновляет данные cookie.
* @param value value or function to change data/ значение или функция для изменения данных
* @param options additional parameters/ дополнительные параметры
*/
set(t, e) {
this.value = E(t), Object.assign(this.options, e), this.update();
}
/**
* Delete cookie data.
*
* Удаление данных из cookie.
*/
remove() {
this.set("");
}
/**
* Returns cache time.
*
* Возвращает время кэширования.
*/
getAge() {
var t, e;
return (e = (t = this.options) == null ? void 0 : t.age) != null ? e : 10080 * 60;
}
/**
* Update cookie data.
*
* Обновление данных cookie.
*/
update() {
var t, e, s, n, o;
if (l() && !Et.get()) {
const a = String((t = this.value) != null ? t : "");
document.cookie = [
`${encodeURIComponent(this.name)}=${encodeURIComponent(a)}`,
`max-age=${a === "" ? "-1" : this.getAge()}`,
`SameSite=${(s = (e = this.options) == null ? void 0 : e.sameSite) != null ? s : "strict"}`,
...(o = (n = this.options) == null ? void 0 : n.arguments) != null ? o : []
].join("; ");
}
}
/**
* Update data from cookies.
*
* Обновляет данные из cookies.
*/
static updateData() {
for (const t of document.cookie.split(";")) {
const [e, s] = t.trim().split("=");
e && D(s) && (M[e] = Nt(s));
}
}
};
l() && ot.updateData();
let ft = ot;
const G = {};
function B(i) {
var n, o, a, u, h, f, d, I;
if (i instanceof Date)
return i;
if (q(i))
return /* @__PURE__ */ new Date();
if (typeof i == "number")
return new Date(i);
let t = i, e = b.getTimezoneFormat();
i.replace(/^([\s\S]+)([-+]\d{2}:?\d{2})$/, (Q, X, xt) => (t = X, e = xt, Q));
const s = (I = (d = (f = (h = (u = (a = (o = (n = /^\d{4}\d{2}\d{2}$/.exec(t) && `${t.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3")}T00:00:00`) != null ? n : /^\d{4}\d{2}$/.exec(t) && `${t.replace(/^(\d{4})(\d{2})$/, "$1-$2")}-01T00:00:00`) != null ? o : /^\d{4}\d{2}\d{2} \d{2}:\d{2}:\d{2}$/.exec(t) && t.replace(/^(\d{4})(\d{2})(\d{2}) (\d{2}):(\d{2}):(\d{2})$/, "$1-$2-$3T$4:$5:$6")) != null ? a : /^\d{4}-\d{2}-\d{2}$/.exec(t) && `${t}T00:00:00`) != null ? u : /^\d{4}-\d{2}$/.exec(t) && `${t}-01T00:00:00`) != null ? h : /^\d{4}$/.exec(t) && `${t}-01-01T00:00:00`) != null ? f : /^\d{2}:\d{2}$/.exec(t) && `2000-01-01T${t}:00`) != null ? d : /^\d{2}:\d{2}:\d{2}$/.exec(t) && `2000-01-01T${t}`) != null ? I : t.replace(" ", "T");
return /* @__PURE__ */ new Date(`${s}${e}`);
}
function Mt(i, t) {
return g(i, (e) => e == null ? void 0 : e[t]);
}
class J {
/**
* Constructor
* @param code country code, full form language-country or one of them/
* код страны, полный вид язык-страна или один из них
*/
constructor(t = b.getLocation()) {
c(this, "geo");
this.geo = b.find(t);
const e = this.getLocation();
if (e in tt)
return tt[e];
tt[e] = this;
}
/**
* Returns an instance of the class according to the specified country code.
*
* Возвращает экземпляр класса по указа