szdl-utils-kit 0.3.13 → 0.3.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +54 -51
- package/dist/index.umd.cjs +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -259,7 +259,7 @@ var lt = { exports: {} };
|
|
|
259
259
|
u[A].FRIDAY_SHORT,
|
|
260
260
|
u[A].SATURDAY_SHORT
|
|
261
261
|
];
|
|
262
|
-
},
|
|
262
|
+
}, b, M, D, B, F = function(t, a, d) {
|
|
263
263
|
var g;
|
|
264
264
|
i.XMLHttpRequest ? g = new XMLHttpRequest() : g = new ActiveXObject("Microsoft.XMLHTTP"), g.onreadystatechange = function() {
|
|
265
265
|
g.readyState === 4 && (g.status === 200 ? a && (i.JSON === e ? alert(`Please, include json2 into your project if you want use old browsers!
|
|
@@ -353,7 +353,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
|
|
|
353
353
|
"%B": {
|
|
354
354
|
format: function(t) {
|
|
355
355
|
var a = s.options("monthFromZero") ? t.month() : t.month() - 1;
|
|
356
|
-
return
|
|
356
|
+
return b[a !== e ? a : s.MIN_MONTH];
|
|
357
357
|
},
|
|
358
358
|
parse: function(t) {
|
|
359
359
|
var a = s.monthNames(!0).indexOf(t) + (s.options("monthFromZero") ? 0 : 1);
|
|
@@ -520,7 +520,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
|
|
|
520
520
|
if (typeof t == "number")
|
|
521
521
|
return this._d = new Date(t * (s.options("useMilliseconds") ? 1 : 1e3)), this;
|
|
522
522
|
if (typeof t == "object" && (t instanceof Array ? (this.day(s.MIN_DAY), this.year(t[0]), this.month(t[1]), this.day(t[2]), this.hours(t[3]), this.minutes(t[4]), this.seconds(t[5]), this.milliseconds(t[6])) : (this.day(s.MIN_DAY), this.year(t.year), this.month(t.month), this.day(t.day), this.hours(t.hours), this.minutes(t.minutes), this.seconds(t.seconds), this.milliseconds(t.milliseconds))), typeof t == "string") {
|
|
523
|
-
var g, k = [], E,
|
|
523
|
+
var g, k = [], E, L, v = [], Y = 0, G = 0, C, x, w = {}, H;
|
|
524
524
|
if (t === e)
|
|
525
525
|
return E = o(this, d), E === e && (this._i = {
|
|
526
526
|
year: -1,
|
|
@@ -533,22 +533,22 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
|
|
|
533
533
|
}), E;
|
|
534
534
|
for (a === e && (a = s.detectFormat(t)); Y < a.length; ) {
|
|
535
535
|
if (a.charAt(Y) === "%") {
|
|
536
|
-
if (
|
|
537
|
-
switch (C = 0, x = "", S[
|
|
536
|
+
if (L = a.charAt(Y) + a.charAt(Y + 1), S[L] !== e) {
|
|
537
|
+
switch (C = 0, x = "", S[L].type) {
|
|
538
538
|
case "number":
|
|
539
|
-
for (; C < S[
|
|
539
|
+
for (; C < S[L].maxLength && G + C < t.length && !isNaN(Number(t.charAt(G + C))); )
|
|
540
540
|
x += t.charAt(G + C), C += 1;
|
|
541
541
|
break;
|
|
542
542
|
case "word":
|
|
543
|
-
for (; C < S[
|
|
543
|
+
for (; C < S[L].maxLength && G + C < t.length && /^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(G + C)); )
|
|
544
544
|
x += t.charAt(G + C), C += 1;
|
|
545
545
|
break;
|
|
546
546
|
case "string":
|
|
547
|
-
for (; C < S[
|
|
547
|
+
for (; C < S[L].maxLength && G + C < t.length; )
|
|
548
548
|
x += t.charAt(G + C), C += 1;
|
|
549
549
|
break;
|
|
550
550
|
}
|
|
551
|
-
if (C < S[
|
|
551
|
+
if (C < S[L].minLength)
|
|
552
552
|
return E = o(this, d), E === e && (this._i = {
|
|
553
553
|
year: -1,
|
|
554
554
|
month: -1,
|
|
@@ -558,7 +558,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
|
|
|
558
558
|
seconds: -1,
|
|
559
559
|
milliseconds: -1
|
|
560
560
|
}), E;
|
|
561
|
-
k.push(
|
|
561
|
+
k.push(L), v.push(x), C -= 1, G += C, Y += 1;
|
|
562
562
|
}
|
|
563
563
|
} else if (t.charAt(G) !== a.charAt(Y))
|
|
564
564
|
return E = o(this, d), E === e && (this._i = {
|
|
@@ -712,7 +712,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
|
|
|
712
712
|
}, s.noConflict = function() {
|
|
713
713
|
return i.tempus = h, s;
|
|
714
714
|
}, s.generate = function(t) {
|
|
715
|
-
var a, d, g, k, E,
|
|
715
|
+
var a, d, g, k, E, L, v, Y;
|
|
716
716
|
if (typeof t.dateFrom != "number" && (t.dateFrom instanceof O ? a = t.dateFrom.utc() : a = s(t.dateFrom, t.formatFrom).utc()), typeof t.dateTo != "number" && (t.dateTo instanceof O ? d = t.dateTo.utc() : d = s(t.dateTo, t.formatTo !== e ? t.formatTo : t.formatFrom).utc()), typeof t.period == "number" ? E = {
|
|
717
717
|
year: 0,
|
|
718
718
|
month: 0,
|
|
@@ -734,7 +734,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
|
|
|
734
734
|
hours: t.period.hours !== e ? t.period.hours : 0,
|
|
735
735
|
minutes: t.period.minutes !== e ? t.period.minutes : 0,
|
|
736
736
|
seconds: t.period.seconds !== e ? t.period.seconds : 0
|
|
737
|
-
}), t.groupBy === e ?
|
|
737
|
+
}), t.groupBy === e ? L = t.asObject === !0 ? {} : [] : (L = [], L.push([]), v = s(a).get()[t.groupBy]), Y = function(x, w, H) {
|
|
738
738
|
return t.asObject === !0 ? t.format !== e ? x[s(w).format(t.format)] = {} : x[s(w).format("%F %H:%M:%S")] = {} : t.format !== e ? x.push(H ? null : s(w).format(t.format)) : x.push(H ? null : s(w)), x;
|
|
739
739
|
}, t.groupBy !== e && t.fillNulls) {
|
|
740
740
|
var G = {
|
|
@@ -747,23 +747,23 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
|
|
|
747
747
|
milliseconds: E.milliseconds ? -E.milliseconds : e
|
|
748
748
|
};
|
|
749
749
|
for (g = s(a).calc(G).utc(); s(g).get()[t.groupBy] === v; )
|
|
750
|
-
Y(
|
|
750
|
+
Y(L[L.length - 1], g, !0), g = s(g).calc(G).utc();
|
|
751
751
|
if (t.groupBy === "week") {
|
|
752
752
|
var C = s(a).dayOfWeek();
|
|
753
|
-
for (g = s(a).dayOfWeek(0).utc();
|
|
754
|
-
Y(
|
|
753
|
+
for (g = s(a).dayOfWeek(0).utc(); L[0].length < C && g < a; )
|
|
754
|
+
Y(L[L.length - 1], g, !0), g = s(g).calc(E).utc();
|
|
755
755
|
}
|
|
756
756
|
}
|
|
757
757
|
for (; a <= d; )
|
|
758
|
-
t.groupBy === e ? Y(
|
|
758
|
+
t.groupBy === e ? Y(L, a) : s(a).get()[t.groupBy] === v ? Y(L[L.length - 1], a) : (L.push([]), Y(L[L.length - 1], a), v = s(a).get()[t.groupBy]), a = s(a).calc(E).utc();
|
|
759
759
|
if (t.groupBy !== e && t.fillNulls)
|
|
760
760
|
for (k = s(d).calc(E).utc(); s(k).get()[t.groupBy] === v; )
|
|
761
|
-
Y(
|
|
762
|
-
return
|
|
761
|
+
Y(L[L.length - 1], k, !0), k = s(k).calc(E).utc();
|
|
762
|
+
return L;
|
|
763
763
|
}, s.monthNames = function(t) {
|
|
764
764
|
switch (t) {
|
|
765
765
|
case "long":
|
|
766
|
-
return
|
|
766
|
+
return b;
|
|
767
767
|
default:
|
|
768
768
|
return M;
|
|
769
769
|
}
|
|
@@ -776,7 +776,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
|
|
|
776
776
|
}
|
|
777
777
|
}, s.lang = function(t) {
|
|
778
778
|
if (t !== e)
|
|
779
|
-
A = t, u[A] === e && (A = "en"),
|
|
779
|
+
A = t, u[A] === e && (A = "en"), b = N(), M = y(), D = p(), B = R();
|
|
780
780
|
else
|
|
781
781
|
return A;
|
|
782
782
|
return e;
|
|
@@ -806,7 +806,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
|
|
|
806
806
|
u = a;
|
|
807
807
|
}, function(a) {
|
|
808
808
|
});
|
|
809
|
-
}, A = (m.language || m.systemLanguage || m.userLanguage || "en").substr(0, 2).toLowerCase(), u[A] === e && (A = "en"),
|
|
809
|
+
}, A = (m.language || m.systemLanguage || m.userLanguage || "en").substr(0, 2).toLowerCase(), u[A] === e && (A = "en"), b = N(), M = y(), D = p(), B = R(), _.exports && (r = _.exports = s), r.tempus = s;
|
|
810
810
|
}).call(Tt);
|
|
811
811
|
})(lt, lt.exports);
|
|
812
812
|
var Lt = lt.exports;
|
|
@@ -1073,14 +1073,14 @@ class K {
|
|
|
1073
1073
|
if (!this.canContinue)
|
|
1074
1074
|
break;
|
|
1075
1075
|
this.totalProgress = Math.round(Number(s) / c.length * 100), await this.callBatchWithTimeout(f, async (m) => {
|
|
1076
|
-
var A, u, N, y, p, R,
|
|
1076
|
+
var A, u, N, y, p, R, b;
|
|
1077
1077
|
for (const [M, D] of Object.entries(m)) {
|
|
1078
1078
|
if (!this.canContinue)
|
|
1079
1079
|
return;
|
|
1080
1080
|
if (D.error()) {
|
|
1081
1081
|
const O = (u = (A = D.error()) == null ? void 0 : A.ex) == null ? void 0 : u.error, t = (y = (N = D.error()) == null ? void 0 : N.ex) == null ? void 0 : y.error_description;
|
|
1082
1082
|
this.errors[M] = O && O.trim() || t && t.trim() || ((p = D.error()) == null ? void 0 : p.toString()) || "Неизвестная ошибка", n[M] = 0;
|
|
1083
|
-
const a = ((
|
|
1083
|
+
const a = ((b = (R = D.error()) == null ? void 0 : R.ex) == null ? void 0 : b.error) ?? "";
|
|
1084
1084
|
let d = "";
|
|
1085
1085
|
const g = f[M];
|
|
1086
1086
|
switch (Array.isArray(g) ? [d] = g : g != null && g.method && (d = g.method), a) {
|
|
@@ -1173,9 +1173,9 @@ class K {
|
|
|
1173
1173
|
break;
|
|
1174
1174
|
}
|
|
1175
1175
|
}
|
|
1176
|
-
const p = this.getData(y.data()), R = Array.isArray(p) ? p.length : 0,
|
|
1176
|
+
const p = this.getData(y.data()), R = Array.isArray(p) ? p.length : 0, b = typeof y.total == "function" && y.total() !== void 0, M = b ? y.total() : R;
|
|
1177
1177
|
e === "count" ? this.result[N] ? this.result[N] += R : this.result[N] = M : this.result[N] = p, this.setProgressData({ key: N, value: y, type: e });
|
|
1178
|
-
const D = e === "count" ? !
|
|
1178
|
+
const D = e === "count" ? !b && R === this.limit : M > this.limit && M > R;
|
|
1179
1179
|
if (!this.canContinue || D) {
|
|
1180
1180
|
let B = r[N];
|
|
1181
1181
|
if (Array.isArray(B)) {
|
|
@@ -1228,12 +1228,12 @@ class K {
|
|
|
1228
1228
|
].includes(f) ? u[">ID"] = s.id : u[s.field] = s.id, [f, { ...A, start: -1 }];
|
|
1229
1229
|
}, l = (h) => {
|
|
1230
1230
|
Object.entries(h).forEach(([s, f]) => {
|
|
1231
|
-
var u, N, y, p, R,
|
|
1231
|
+
var u, N, y, p, R, b, M;
|
|
1232
1232
|
const [m] = s.split("__"), A = this.getData(f.data());
|
|
1233
1233
|
if (Array.isArray(A) && (e === "count" ? this.result[m] += A.length : this.result[m].push(...A)), f.error()) {
|
|
1234
1234
|
const D = (N = (u = f.error()) == null ? void 0 : u.ex) == null ? void 0 : N.error, B = (p = (y = f.error()) == null ? void 0 : y.ex) == null ? void 0 : p.error_description;
|
|
1235
1235
|
this.errors[m] = D && D.trim() || B && B.trim() || ((R = f.error()) == null ? void 0 : R.toString()) || "Неизвестная ошибка";
|
|
1236
|
-
const F = ((M = (
|
|
1236
|
+
const F = ((M = (b = f.error()) == null ? void 0 : b.ex) == null ? void 0 : M.error) ?? "", S = i.get(m);
|
|
1237
1237
|
switch (F) {
|
|
1238
1238
|
case "OPERATION_TIME_LIMIT":
|
|
1239
1239
|
S && (this.skipList.add(S), this.limitCall && this.limitCall(m));
|
|
@@ -1940,11 +1940,11 @@ class It {
|
|
|
1940
1940
|
for (let m = 0; m < i.length; m++) {
|
|
1941
1941
|
const u = i[m].placement, N = o;
|
|
1942
1942
|
if (this.placeData.find(
|
|
1943
|
-
(
|
|
1943
|
+
(b) => b.placement === u && b.handler === N
|
|
1944
1944
|
))
|
|
1945
1945
|
continue;
|
|
1946
1946
|
const p = this.placeData.find(
|
|
1947
|
-
(
|
|
1947
|
+
(b) => b.placement === u && b.handler !== N
|
|
1948
1948
|
);
|
|
1949
1949
|
p && s.push({
|
|
1950
1950
|
placement: u,
|
|
@@ -2162,7 +2162,7 @@ class Mt {
|
|
|
2162
2162
|
return;
|
|
2163
2163
|
}
|
|
2164
2164
|
await this.refreshTabs(!0), await this.ensureTabRegistered();
|
|
2165
|
-
const e = this.selectLeaderId(), i = e && this.id
|
|
2165
|
+
const e = this.selectLeaderId(), i = e && +this.id == +e;
|
|
2166
2166
|
await this.updateTabState(i), i && !this.hasStarted && (this.hasStarted = !0, await this.runAsLeader());
|
|
2167
2167
|
}
|
|
2168
2168
|
stopTimers() {
|
|
@@ -2217,15 +2217,15 @@ class Mt {
|
|
|
2217
2217
|
return { id: void 0, data: void 0 };
|
|
2218
2218
|
try {
|
|
2219
2219
|
const i = JSON.parse(e.DETAIL_TEXT);
|
|
2220
|
-
return { id: e.ID, data: i };
|
|
2220
|
+
return { id: +e.ID || 0, data: i };
|
|
2221
2221
|
} catch (i) {
|
|
2222
|
-
return console.log("BackgroundWorker: parse tab error", i), { id: e.ID, data: void 0 };
|
|
2222
|
+
return console.log("BackgroundWorker: parse tab error", i), { id: +e.ID || 0, data: void 0 };
|
|
2223
2223
|
}
|
|
2224
2224
|
});
|
|
2225
2225
|
}
|
|
2226
2226
|
async ensureTabRegistered() {
|
|
2227
2227
|
if (this.id)
|
|
2228
|
-
return this.id;
|
|
2228
|
+
return +this.id || 0;
|
|
2229
2229
|
if (this.tabList.length >= this.maxTabs && await this.refreshTabs(!0, this.quickCleanupThreshold), this.tabList.length >= this.maxTabs)
|
|
2230
2230
|
return console.log(
|
|
2231
2231
|
"BackgroundWorker: Достигнут лимит вкладок даже после быстрой очистки, не регистрируемся"
|
|
@@ -2248,7 +2248,7 @@ class Mt {
|
|
|
2248
2248
|
});
|
|
2249
2249
|
}
|
|
2250
2250
|
) || 0;
|
|
2251
|
-
return this.id = e,
|
|
2251
|
+
return this.id = +e || 0, this.id;
|
|
2252
2252
|
}
|
|
2253
2253
|
async updateTabState(r) {
|
|
2254
2254
|
if (!this.id)
|
|
@@ -2333,7 +2333,7 @@ class Mt {
|
|
|
2333
2333
|
if (!r || typeof r != "string")
|
|
2334
2334
|
return null;
|
|
2335
2335
|
const e = r.match(/USER_ID=(\d+)/);
|
|
2336
|
-
return e ? e[1] : null;
|
|
2336
|
+
return e ? +e[1] : null;
|
|
2337
2337
|
}
|
|
2338
2338
|
async continueBackground() {
|
|
2339
2339
|
try {
|
|
@@ -2365,14 +2365,14 @@ class Mt {
|
|
|
2365
2365
|
}
|
|
2366
2366
|
selectLeaderId() {
|
|
2367
2367
|
var e;
|
|
2368
|
-
return this.tabList.length && ((e = [...this.tabList].sort((i, n) => {
|
|
2368
|
+
return this.tabList.length && +((e = [...this.tabList].sort((i, n) => {
|
|
2369
2369
|
var c, h, s, f;
|
|
2370
2370
|
const o = new Date(
|
|
2371
2371
|
((c = i.data) == null ? void 0 : c.createdAt) || ((h = i.data) == null ? void 0 : h.lastActive) || 0
|
|
2372
2372
|
).getTime(), l = new Date(
|
|
2373
2373
|
((s = n.data) == null ? void 0 : s.createdAt) || ((f = n.data) == null ? void 0 : f.lastActive) || 0
|
|
2374
2374
|
).getTime();
|
|
2375
|
-
return o === l ? i.id - n.id : o - l;
|
|
2375
|
+
return o === l ? (+i.id || 0) - (+n.id || 0) : o - l;
|
|
2376
2376
|
})[0]) == null ? void 0 : e.id) || 0;
|
|
2377
2377
|
}
|
|
2378
2378
|
async runAsLeader() {
|
|
@@ -2411,21 +2411,23 @@ class Mt {
|
|
|
2411
2411
|
if (p.placement !== "PAGE_BACKGROUND_WORKER")
|
|
2412
2412
|
return;
|
|
2413
2413
|
if (p.userId || p.handler && p.handler.includes("USER_ID=")) {
|
|
2414
|
-
const
|
|
2415
|
-
|
|
2414
|
+
const b = p.userId || (p.handler ? this.extractUserIdFromHandler(p.handler) : null);
|
|
2415
|
+
b && e.set(+b, p);
|
|
2416
2416
|
} else
|
|
2417
2417
|
i = p;
|
|
2418
2418
|
});
|
|
2419
2419
|
const n = await this.resolveAdmins(), o = await this.getEligibleUsersForBackgroundWorker(n);
|
|
2420
2420
|
o.sort((p, R) => {
|
|
2421
|
-
const
|
|
2422
|
-
return (R.LAST_LOGIN ? new Date(R.LAST_LOGIN) : /* @__PURE__ */ new Date(0)) -
|
|
2421
|
+
const b = p.LAST_LOGIN ? new Date(p.LAST_LOGIN) : /* @__PURE__ */ new Date(0);
|
|
2422
|
+
return (R.LAST_LOGIN ? new Date(R.LAST_LOGIN) : /* @__PURE__ */ new Date(0)) - b;
|
|
2423
2423
|
});
|
|
2424
2424
|
const l = 10, h = o.slice(0, l).filter(
|
|
2425
2425
|
(p) => !e.has(+p.ID)
|
|
2426
2426
|
), s = [];
|
|
2427
|
-
for (const [p] of e)
|
|
2428
|
-
|
|
2427
|
+
for (const [p] of e) {
|
|
2428
|
+
const R = +p || 0;
|
|
2429
|
+
o.find((M) => +M.ID === R) || s.push(R);
|
|
2430
|
+
}
|
|
2429
2431
|
const f = [];
|
|
2430
2432
|
for (const p of s)
|
|
2431
2433
|
this.appPath && f.push({
|
|
@@ -2489,16 +2491,16 @@ class Mt {
|
|
|
2489
2491
|
try {
|
|
2490
2492
|
const i = +(((r = this.bx.userInfo) == null ? void 0 : r.ID) ?? 0), n = !!((e = this.bx) != null && e.isAdmin), o = await this.getAdminsList() || [];
|
|
2491
2493
|
if (!n) {
|
|
2492
|
-
if (i && o.includes(i)) {
|
|
2494
|
+
if (i && o.includes(+i)) {
|
|
2493
2495
|
const h = o.filter(
|
|
2494
|
-
(s) => s
|
|
2496
|
+
(s) => +s != +i
|
|
2495
2497
|
);
|
|
2496
2498
|
return await this.saveAdminsList(h), h;
|
|
2497
2499
|
}
|
|
2498
2500
|
return o;
|
|
2499
2501
|
}
|
|
2500
2502
|
const l = /* @__PURE__ */ new Set([...o || []]);
|
|
2501
|
-
i && l.add(i);
|
|
2503
|
+
i && l.add(+i);
|
|
2502
2504
|
const c = [...l].filter(Boolean);
|
|
2503
2505
|
return await this.saveAdminsList(c), c;
|
|
2504
2506
|
} catch (i) {
|
|
@@ -2506,9 +2508,10 @@ class Mt {
|
|
|
2506
2508
|
}
|
|
2507
2509
|
}
|
|
2508
2510
|
async getEligibleUsersForBackgroundWorker(r = []) {
|
|
2509
|
-
|
|
2510
|
-
(
|
|
2511
|
-
).
|
|
2511
|
+
const e = (this.users ?? []).filter(
|
|
2512
|
+
(n) => n.ACTIVE === "Y" || n.ACTIVE === !0
|
|
2513
|
+
), i = r.map((n) => +n || 0).filter(Boolean);
|
|
2514
|
+
return e.filter((n) => i.includes(+n.ID || 0));
|
|
2512
2515
|
}
|
|
2513
2516
|
async saveAdminsList(r = []) {
|
|
2514
2517
|
try {
|
|
@@ -2519,8 +2522,8 @@ class Mt {
|
|
|
2519
2522
|
}
|
|
2520
2523
|
async getAdminsList() {
|
|
2521
2524
|
try {
|
|
2522
|
-
const r = BX24.appOption.get("adminsList");
|
|
2523
|
-
return
|
|
2525
|
+
const r = BX24.appOption.get("adminsList"), e = r ? JSON.parse(r) : [];
|
|
2526
|
+
return Array.isArray(e) ? e.map((i) => +i || 0).filter(Boolean) : [];
|
|
2524
2527
|
} catch (r) {
|
|
2525
2528
|
return console.error("BackgroundWorker: getAdminsList error", r), [];
|
|
2526
2529
|
}
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var It=Object.defineProperty;var Mt=(_,L,C)=>L in _?It(_,L,{enumerable:!0,configurable:!0,writable:!0,value:C}):_[L]=C;var M=(_,L,C)=>(Mt(_,typeof L!="symbol"?L+"":L,C),C),dt=(_,L,C)=>{if(!L.has(_))throw TypeError("Cannot "+C)};var T=(_,L,C)=>(dt(_,L,"read from private field"),C?C.call(_):L.get(_)),Y=(_,L,C)=>{if(L.has(_))throw TypeError("Cannot add the same private member more than once");L instanceof WeakSet?L.add(_):L.set(_,C)},v=(_,L,C,et)=>(dt(_,L,"write to private field"),et?et.call(_,C):L.set(_,C),C);var K=(_,L,C)=>(dt(_,L,"access private method"),C);(function(_,L){typeof exports=="object"&&typeof module<"u"?L(exports):typeof define=="function"&&define.amd?define(["exports"],L):(_=typeof globalThis<"u"?globalThis:_||self,L(_["szdl-utils-kit"]={}))})(this,function(_){var q,Q,Z,$,rt,W,tt,st,at,Nt,nt,gt,At,Ot,ct,_t,ht,Et,lt,Tt,ut,Rt,ot,pt;"use strict";var L=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function C(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x.default:x}var et={exports:{}};(function(x,r){(function(e){Array.prototype.indexOf||(Array.prototype.indexOf=function(t,o){var d,g;for(d=o||0,g=this.length;d<g;d+=1)if(this[d]===t)return d;return-1});var i=this,n=function(t,o){for(var d=t.toString();d.length<o;)d="0"+d;return d},a=function(t,o){return o!==e?(t.year(o.year()||o.year),t.month(o.month()||o.month),t.day(o.day()||o.day),t.hours(o.hours()||o.hours),t.minutes(o.minutes()||o.minutes),t.seconds(o.seconds()||o.seconds),t.milliseconds(o.milliseconds()||o.milliseconds),t):e},l=function(t,o){var d,g="";return d=t.slice(o,o+1),d!==""&&!isNaN(Number(d))&&(g+="%H"),d=t.charAt(o+2),d!==""&&d===":"&&(g+=d),d=t.slice(o+3,o+4),d!==""&&!isNaN(Number(d))&&(g+="%M"),d=t.charAt(o+5),d!==""&&d===":"&&(g+=d),d=t.slice(o+6,o+7),d!==""&&!isNaN(Number(d))&&(g+="%S"),g},c=function(t,o){var d,g=[t.slice(o,o+1),t.charAt(o+2),t.slice(o+3,o+4),t.charAt(o+5),t.slice(o+6,o+9)],w;return!isNaN(Number(g[0]))&&!isNaN(Number(g[2]))&&!isNaN(Number(g[4]))?(g[1]==="."&&g[3]==="."?d="%d.%m.%Y":g[1]==="-"&&g[3]==="-"?d="%m-%d-%Y":g[1]==="/"&&g[3]==="/"&&(d="%m/%d/%Y"),d):(w=[t.slice(o,o+3),t.charAt(o+4),t.slice(o+5,o+6),t.charAt(o+7),t.slice(o+8,o+9)],!isNaN(Number(w[0]))&&!isNaN(Number(w[2]))&&!isNaN(Number(w[4]))?(w[1]==="-"&&w[3]==="-"&&(d="%Y-%m-%d"),d):"")},h=i.tempus,s,f,m=i.navigator||{},A="en",u={en:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"Mar",APRIL_SHORT:"Apr",MAY_SHORT:"May",JUNE_SHORT:"Jun",JULY_SHORT:"Jul",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sep",OCTOBER_SHORT:"Oct",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dec",JANUARY_LONG:"January",FEBRUARY_LONG:"February",MARCH_LONG:"March",APRIL_LONG:"April",MAY_LONG:"May",JUNE_LONG:"June",JULY_LONG:"July",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"October",NOVEMBER_LONG:"November",DECEMBER_LONG:"December",SUNDAY_SHORT:"Sun",MONDAY_SHORT:"Mon",TUESDAY_SHORT:"Tue",WEDNESDAY_SHORT:"Wed",THURSDAY_SHORT:"Thu",FRIDAY_SHORT:"Fri",SATURDAY_SHORT:"Sat",SUNDAY_LONG:"Sunday",MONDAY_LONG:"Monday",TUESDAY_LONG:"Tuesday",WEDNESDAY_LONG:"Wednesday",THURSDAY_LONG:"Thursday",FRIDAY_LONG:"Friday",SATURDAY_LONG:"Saturday"},ru:{JANUARY_SHORT:"Янв",FEBRUARY_SHORT:"Фев",MARCH_SHORT:"Мар",APRIL_SHORT:"Апр",MAY_SHORT:"Май",JUNE_SHORT:"Июн",JULY_SHORT:"Июл",AUGUST_SHORT:"Авг",SEPTEMBER_SHORT:"Сен",OCTOBER_SHORT:"Окт",NOVEMBER_SHORT:"Ноя",DECEMBER_SHORT:"Дек",JANUARY_LONG:"Январь",FEBRUARY_LONG:"Февраль",MARCH_LONG:"Март",APRIL_LONG:"Апрель",MAY_LONG:"Май",JUNE_LONG:"Июнь",JULY_LONG:"Июль",AUGUST_LONG:"Август",SEPTEMBER_LONG:"Сентябрь",OCTOBER_LONG:"Октябрь",NOVEMBER_LONG:"Ноябрь",DECEMBER_LONG:"Декабрь",SUNDAY_SHORT:"Вс",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Воскресенье",MONDAY_LONG:"Понедельник",TUESDAY_LONG:"Вторник",WEDNESDAY_LONG:"Среда",THURSDAY_LONG:"Четверг",FRIDAY_LONG:"Пятница",SATURDAY_LONG:"Суббота"},ua:{JANUARY_SHORT:"Січ",FEBRUARY_SHORT:"Лют",MARCH_SHORT:"Берез",APRIL_SHORT:"Квіт",MAY_SHORT:"Трав",JUNE_SHORT:"Черв",JULY_SHORT:"Лип",AUGUST_SHORT:"Серп",SEPTEMBER_SHORT:"Верес",OCTOBER_SHORT:"Жовт",NOVEMBER_SHORT:"Листоп",DECEMBER_SHORT:"Груд",JANUARY_LONG:"Січень",FEBRUARY_LONG:"Лютий",MARCH_LONG:"Березень",APRIL_LONG:"Квітень",MAY_LONG:"Травень",JUNE_LONG:"Червень",JULY_LONG:"Липень",AUGUST_LONG:"Серпень",SEPTEMBER_LONG:"Вересень",OCTOBER_LONG:"Жовтень",NOVEMBER_LONG:"Листопад",DECEMBER_LONG:"Грудень",SUNDAY_SHORT:"Нд",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Неділя",MONDAY_LONG:"Понеділок",TUESDAY_LONG:"Вівторок",WEDNESDAY_LONG:"Середа",THURSDAY_LONG:"Четвер",FRIDAY_LONG:"П’ятниця",SATURDAY_LONG:"Субота"},de:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"März",APRIL_SHORT:"Apr",MAY_SHORT:"Mai",JUNE_SHORT:"Juni",JULY_SHORT:"Juli",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sept",OCTOBER_SHORT:"Okt",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dez",JANUARY_LONG:"Januar",FEBRUARY_LONG:"Februar",MARCH_LONG:"März",APRIL_LONG:"April",MAY_LONG:"Mai",JUNE_LONG:"Juni",JULY_LONG:"Juli",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"Oktober",NOVEMBER_LONG:"November",DECEMBER_LONG:"Dezember",SUNDAY_SHORT:"So",MONDAY_SHORT:"Mo",TUESDAY_SHORT:"Di",WEDNESDAY_SHORT:"Mi",THURSDAY_SHORT:"Do",FRIDAY_SHORT:"Fr",SATURDAY_SHORT:"Sa",SUNDAY_LONG:"Sonntag",MONDAY_LONG:"Montag",TUESDAY_LONG:"Dienstag",WEDNESDAY_LONG:"Mittwoch",THURSDAY_LONG:"Donnerstag",FRIDAY_LONG:"Freitag",SATURDAY_LONG:"Samstag"}},N=function(){return[u[A].JANUARY_LONG,u[A].FEBRUARY_LONG,u[A].MARCH_LONG,u[A].APRIL_LONG,u[A].MAY_LONG,u[A].JUNE_LONG,u[A].JULY_LONG,u[A].AUGUST_LONG,u[A].SEPTEMBER_LONG,u[A].OCTOBER_LONG,u[A].NOVEMBER_LONG,u[A].DECEMBER_LONG]},y=function(){return[u[A].JANUARY_SHORT,u[A].FEBRUARY_SHORT,u[A].MARCH_SHORT,u[A].APRIL_SHORT,u[A].MAY_SHORT,u[A].JUNE_SHORT,u[A].JULY_SHORT,u[A].AUGUST_SHORT,u[A].SEPTEMBER_SHORT,u[A].OCTOBER_SHORT,u[A].NOVEMBER_SHORT,u[A].DECEMBER_SHORT]},p=function(){return[u[A].SUNDAY_LONG,u[A].MONDAY_LONG,u[A].TUESDAY_LONG,u[A].WEDNESDAY_LONG,u[A].THURSDAY_LONG,u[A].FRIDAY_LONG,u[A].SATURDAY_LONG]},R=function(){return[u[A].SUNDAY_SHORT,u[A].MONDAY_SHORT,u[A].TUESDAY_SHORT,u[A].WEDNESDAY_SHORT,u[A].THURSDAY_SHORT,u[A].FRIDAY_SHORT,u[A].SATURDAY_SHORT]},
|
|
2
|
-
https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(g.responseText))):d&&d(g))},g.open("GET",t,!1),g.send()},I={"%d":{format:function(t){return n(t.day()||s.MIN_DAY,2)},parse:function(t){var o=Number(t);return{day:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(t){return n(t.month()||s.MIN_MONTH,2)},parse:function(t){var o=Number(t);return{month:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(t){return n(t.year()||s.MIN_YEAR,4)},parse:function(t){var o=Number(t);return{year:isNaN(o)?e:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(t){return t.dayOfWeek()||s.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(t){var o=t.dayOfWeek();return k[o!==e?o:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var o=t.dayOfWeek();return B[o!==e?o:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(t){var o=s.options("monthFromZero")?t.month():t.month()-1;return D[o!==e?o:s.MIN_MONTH]},parse:function(t){var o=s.monthNames().indexOf(t)+(s.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var o=s.options("monthFromZero")?t.month():t.month()-1;return b[o!==e?o:s.MIN_MONTH]},parse:function(t){var o=s.monthNames(!0).indexOf(t)+(s.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(t){return n(t.hours()||s.MIN_HOURS,2)},parse:function(t){var o=Number(t);return{hours:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(t){return n(t.minutes()||s.MIN_MINUTES,2)},parse:function(t){var o=Number(t);return{minutes:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(t){return n(t.seconds()||s.MIN_SECONDS,2)},parse:function(t){var o=Number(t);return{seconds:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(t){return t.timestamp()},parse:function(t){return isNaN(Number(t))?{}:s(Number(t)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(t){return n(t.year()||s.MIN_YEAR,4)+"-"+n(t.month()||s.MIN_MONTH,2)+"-"+n(t.day()||s.MIN_DAY,2)},parse:function(t){var o=Number(t.slice(0,4)),d=Number(t.slice(5,7)),g=Number(t.slice(8,10));return{year:o,month:d,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return n(t.month()||s.MIN_MONTH,2)+"/"+n(t.day()||s.MIN_DAY,2)+"/"+n(t.year()||s.MIN_YEAR,4)},parse:function(t){var o=Number(t.slice(0,2)),d=Number(t.slice(3,5)),g=Number(t.slice(6,10));return{year:g,month:o,day:d}},minLength:10,maxLength:10,type:"string"}},X={useMilliseconds:!1,monthFromZero:!1},O;O=function(t,o,d){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t!==e&&this.set(t,o,d),this},O.fn=O.prototype,O.fn.dayCount=function(){var t=this.month(),o=s.MAX_DAY_IN_MONTHS[t-(s.options("monthFromZero")?0:1)];return this.leapYear()&&t===(s.options("monthFromZero")?1:2)&&(o+=1),o},O.fn.year=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_YEAR&&Number(t)<=s.MAX_YEAR?(this._d.setFullYear(Number(t)),this._i.year=!1):this._i.year=Number(t):(this._d.setFullYear(s.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},O.fn.month=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MONTH&&Number(t)<=s.MAX_MONTH?(this._d.setMonth(s.options("monthFromZero")?Number(t):Number(t)-1),this._i.month=!1):this._i.month=Number(t):(this._d.setMonth(s.options("monthFromZero")?s.MIN_MONTH:s.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?s.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},O.fn.day=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_DAY&&Number(t)<=this.dayCount()?(this._d.setDate(Number(t)),this._i.day=!1):this._i.day=Number(t):(this._d.setDate(s.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},O.fn.hours=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_HOURS&&Number(t)<=s.MAX_HOURS?(this._d.setHours(Number(t)),this._i.hours=!1):this._i.hours=Number(t):(this._d.setHours(s.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},O.fn.minutes=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MINUTES&&Number(t)<=s.MAX_MINUTES?(this._d.setMinutes(Number(t)),this._i.minutes=!1):this._i.minutes=Number(t):(this._d.setMinutes(s.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},O.fn.seconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_SECONDS&&Number(t)<=s.MAX_SECONDS?(this._d.setSeconds(Number(t)),this._i.seconds=!1):this._i.seconds=Number(t):(this._d.setSeconds(s.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},O.fn.milliseconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MILLISECONDS&&Number(t)<=s.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(t)),this._i.milliseconds=!1):this._i.milliseconds=Number(t):(this._d.setMilliseconds(s.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},O.fn.week=function(){var t=new Date(this.year(),0,1),o=s(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-t.getTime())/864e5+t.getDay()+1)/7)},O.fn.set=function(t,o,d){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t===e)return this._d=new Date,this;if(t instanceof Date)return this._d=t,this;if(typeof t=="number")return this._d=new Date(t*(s.options("useMilliseconds")?1:1e3)),this;if(typeof t=="object"&&(t instanceof Array?(this.day(s.MIN_DAY),this.year(t[0]),this.month(t[1]),this.day(t[2]),this.hours(t[3]),this.minutes(t[4]),this.seconds(t[5]),this.milliseconds(t[6])):(this.day(s.MIN_DAY),this.year(t.year),this.month(t.month),this.day(t.day),this.hours(t.hours),this.minutes(t.minutes),this.seconds(t.seconds),this.milliseconds(t.milliseconds))),typeof t=="string"){var g,w=[],E,S,V=[],P=0,F=0,U,j,H={},G;if(t===e)return E=a(this,d),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;for(o===e&&(o=s.detectFormat(t));P<o.length;){if(o.charAt(P)==="%"){if(S=o.charAt(P)+o.charAt(P+1),I[S]!==e){switch(U=0,j="",I[S].type){case"number":for(;U<I[S].maxLength&&F+U<t.length&&!isNaN(Number(t.charAt(F+U)));)j+=t.charAt(F+U),U+=1;break;case"word":for(;U<I[S].maxLength&&F+U<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(F+U));)j+=t.charAt(F+U),U+=1;break;case"string":for(;U<I[S].maxLength&&F+U<t.length;)j+=t.charAt(F+U),U+=1;break}if(U<I[S].minLength)return E=a(this,d),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;w.push(S),V.push(j),U-=1,F+=U,P+=1}}else if(t.charAt(F)!==o.charAt(P))return E=a(this,d),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;P+=1,F+=1}for(g in w)w.hasOwnProperty(g)&&I.hasOwnProperty(w[g])&&(G=I[w[g]].parse(V[g]),H={year:G.year!==e?G.year:H.year,month:G.month!==e?G.month:H.month,day:G.day!==e?G.day:H.day,hours:G.hours!==e?G.hours:H.hours,minutes:G.minutes!==e?G.minutes:H.minutes,seconds:G.seconds!==e?G.seconds:H.seconds});this.day(s.MIN_DAY),this.year(H.year),this.month(H.month),this.day(H.day),this.hours(H.hours),this.minutes(H.minutes),this.seconds(H.seconds),this.milliseconds(H.milliseconds)}return this},O.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},O.fn.timestamp=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(s.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):s.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},O.fn.utc=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(s.options("useMilliseconds")?1:1e3)),this):s.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},O.fn.dayOfWeek=function(t){if(t==="long")return B[this._d.getDay()];if(t==="short")return k[this._d.getDay()];if(t===e)return this._d.getDay();if(t===0||t==="Sunday")return this.calc({day:-this.dayOfWeek()});if(t===1||t==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(t===2||t==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(t===3||t==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(t===4||t==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(t===5||t==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(t===6||t==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},O.fn.timezone=function(t){switch(t){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},O.fn.get=function(t){switch(t){case"Date":return new Date(this.year(),this.month()-(s.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds());case"DateUTC":return new Date(Date.UTC(this.year(),this.month()-(s.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()));case"Array":return[this.year(),this.month(),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()];default:return{year:this.year(),month:this.month(),week:this.week(),day:this.day(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds(),utc:this.utc(),dayOfWeek:this.dayOfWeek(),dayOfWeekShort:this.dayOfWeek("short"),dayOfWeekLong:this.dayOfWeek("long"),timestamp:this.timestamp()}}},O.fn.format=function(t){for(var o=0,d="",g;o<t.length;)t.charAt(o)==="%"?(g=t.charAt(o)+t.charAt(o+1),I[g]!==e?(d+=I[g].format(this),o+=1):d+="%"):d+=t.charAt(o),o+=1;return d},O.fn.valid=function(){return this._i.year===!1&&this._i.month===!1&&this._i.day===!1&&this._i.hours===!1&&this._i.minutes===!1&&this._i.seconds===!1&&this._i.milliseconds===!1},O.fn.errors=function(){return this._i},O.fn.between=function(t,o){var d=this.timestamp(),g=t.timestamp();switch(o){case"year":return Math.floor((g-d)/31556952);case"month":return Math.floor((g-d)/2629746);case"day":return Math.floor((g-d)/86400);case"hours":return Math.floor((g-d)/3600);case"minutes":return Math.floor((g-d)/60);case"seconds":return g-d;default:return e}},O.fn.calc=function(t){return t.year!==e&&this._d.setFullYear(this._d.getFullYear()+t.year),t.month!==e&&this._d.setMonth(this._d.getMonth()+t.month),t.day!==e&&this._d.setDate(this._d.getDate()+t.day),t.hours!==e&&this._d.setHours(this._d.getHours()+t.hours),t.minutes!==e&&this._d.setMinutes(this._d.getMinutes()+t.minutes),t.seconds!==e&&this._d.setSeconds(this._d.getSeconds()+t.seconds),t.milliseconds!==e&&this._d.setMilliseconds(this._d.getMilliseconds()+t.milliseconds),this},s=function(t,o,d){return new O(t,o,d)},s.MIN_YEAR=1e3,s.MAX_YEAR=3e3,s.MIN_MONTH=1,s.MAX_MONTH=12,s.MIN_DAY=1,s.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],s.MIN_DAY_OF_WEEK=0,s.MAX_DAY_OF_WEEK=6,s.MIN_HOURS=0,s.MAX_HOURS=23,s.MIN_MINUTES=0,s.MAX_MINUTES=59,s.MIN_SECONDS=0,s.MAX_SECONDS=59,s.MIN_MILLISECONDS=0,s.MAX_MILLISECONDS=999,s.VERSION="0.2.18",s.options=function(t,o){if(t===e)return X;if(X.hasOwnProperty(t)){if(o===e)return X[t];X[t]=o,t==="monthFromZero"&&(s.MIN_MONTH=o?0:1,s.MAX_MONTH=o?11:12)}return e},s.noConflict=function(){return i.tempus=h,s},s.generate=function(t){var o,d,g,w,E,S,V,P;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof O?o=t.dateFrom.utc():o=s(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof O?d=t.dateTo.utc():d=s(t.dateTo,t.formatTo!==e?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?E={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?E={year:t.period==="year"?1:0,month:t.period==="month"?1:0,day:t.period==="day"?1:0,hours:t.period==="hours"?1:0,minutes:t.period==="minutes"?1:0,seconds:t.period==="seconds"?1:0}:typeof t.period=="object"&&(E={year:t.period.year!==e?t.period.year:0,month:t.period.month!==e?t.period.month:0,day:t.period.day!==e?t.period.day:0,hours:t.period.hours!==e?t.period.hours:0,minutes:t.period.minutes!==e?t.period.minutes:0,seconds:t.period.seconds!==e?t.period.seconds:0}),t.groupBy===e?S=t.asObject===!0?{}:[]:(S=[],S.push([]),V=s(o).get()[t.groupBy]),P=function(j,H,G){return t.asObject===!0?t.format!==e?j[s(H).format(t.format)]={}:j[s(H).format("%F %H:%M:%S")]={}:t.format!==e?j.push(G?null:s(H).format(t.format)):j.push(G?null:s(H)),j},t.groupBy!==e&&t.fillNulls){var F={year:E.year?-E.year:e,month:E.month?-E.month:e,day:E.day?-E.day:e,hours:E.hours?-E.hours:e,minutes:E.minutes?-E.minutes:e,seconds:E.seconds?-E.seconds:e,milliseconds:E.milliseconds?-E.milliseconds:e};for(g=s(o).calc(F).utc();s(g).get()[t.groupBy]===V;)P(S[S.length-1],g,!0),g=s(g).calc(F).utc();if(t.groupBy==="week"){var U=s(o).dayOfWeek();for(g=s(o).dayOfWeek(0).utc();S[0].length<U&&g<o;)P(S[S.length-1],g,!0),g=s(g).calc(E).utc()}}for(;o<=d;)t.groupBy===e?P(S,o):s(o).get()[t.groupBy]===V?P(S[S.length-1],o):(S.push([]),P(S[S.length-1],o),V=s(o).get()[t.groupBy]),o=s(o).calc(E).utc();if(t.groupBy!==e&&t.fillNulls)for(w=s(d).calc(E).utc();s(w).get()[t.groupBy]===V;)P(S[S.length-1],w,!0),w=s(w).calc(E).utc();return S},s.monthNames=function(t){switch(t){case"long":return b;default:return D}},s.dayNames=function(t){switch(t){case"long":return B;default:return k}},s.lang=function(t){if(t!==e)A=t,u[A]===e&&(A="en"),b=N(),D=y(),B=p(),k=R();else return A;return e},s.availableLangs=function(){return Object.keys(u)},s.registerFormat=function(t,o,d,g,w,E){I[t]={format:o,parse:d,minLength:g,maxLength:w,type:E}},s.unregisterFormat=function(t){delete I[t]},s.detectFormat=function(t){var o,d,g;return o=c(t,0),o!==""&&(g=10),d=t.charAt(g),(d==="T"||d===" ")&&(o+=d,g+=1),o+=l(t,g),o},f={TempusDate:O},s.classes=function(t,o){if(o===e)return f[t];f[t]=o},s.loadTranslations=function(t){typeof t=="object"?u=t:typeof t=="string"&&J(t,function(o){u=o},function(o){})},A=(m.language||m.systemLanguage||m.userLanguage||"en").substr(0,2).toLowerCase(),u[A]===e&&(A="en"),b=N(),D=y(),B=p(),k=R(),x.exports&&(r=x.exports=s),r.tempus=s}).call(L)})(et,et.exports);var Lt=et.exports;const it=C(Lt);class z{constructor(r){this.callBatch=r,this.result={},this.errors={},this.limit=50,this.canContinue=!0,this.progressCall="",this.limitCall="",this.progressData="",this.progressTimer="",this.progressDelay=100,this.oldPercent="no",this.chunkRate=1,this.totalProgress=0,this.skipList=new Set,this.filterChunkSize=50}getData(r){return(r==null?void 0:r.items)??(r==null?void 0:r.tasks)??(r==null?void 0:r.types)??(r==null?void 0:r.type)??(r==null?void 0:r.fields)??(r==null?void 0:r.workgroups)??r}splitLargeFilters(r,e){const{method:i,params:n}=e;if(!n)return[{key:r,request:e}];const a=n.filter||n.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:r,request:e}];for(const[l,c]of Object.entries(a))if(Array.isArray(c)&&c.length>this.filterChunkSize){const h=[];for(let s=0;s<c.length;s+=this.filterChunkSize){const f=c.slice(s,s+this.filterChunkSize),m=s===0?r:`${r}__chunk_${Math.floor(s/this.filterChunkSize)}`,A={...n};n.filter?(A.filter={...a},A.filter[l]=f):n.FILTER&&(A.FILTER={...a},A.FILTER[l]=f),h.push({key:m,request:{method:i,params:A},originalKey:r,filterKey:l,chunkIndex:Math.floor(s/this.filterChunkSize)})}return h}return[{key:r,request:e}]}mergeSplitResults(r,e){const i=[],n=Object.keys(r).filter(a=>a.startsWith(e)).sort((a,l)=>{const c=a.match(/__chunk_(\d+)$/),h=l.match(/__chunk_(\d+)$/);return c?h?parseInt(c[1])-parseInt(h[1]):1:-1});for(const a of n){const l=r[a];Array.isArray(l)?i.push(...l):l&&i.push(l)}return i}get progressPercent(){let r=0;if(!this.progressData)return{percent:Math.round(r),allCount:0,allTotal:0};let e=0,i=0;return Object.values(this.progressData).forEach(n=>{const{total:a,count:l}=n;e+=a??0,i+=l??0}),e?r=i/e*100*this.chunkRate+this.totalProgress:i===0&&e===0?r=100*this.chunkRate+this.totalProgress:r=100,{percent:Math.round(r),allCount:i,allTotal:e}}setProgressData({key:r,value:e,type:i}){const n=this.getData(e.data()),a=Array.isArray(n)?n.length:0;let l=e.total()||a;i==="count"&&(l=a);let c=1;n&&(c=a),this.progressCall&&(this.progressData||(this.progressData={}),this.progressData[r]&&this.progressData[r].count&&(c+=this.progressData[r].count),this.progressData[r]?this.progressData[r].count=c:this.progressData[r]={total:l,count:c},this.progressTimer||(this.progressTimer=setInterval(()=>{const{percent:h,allCount:s,allTotal:f}=this.progressPercent;(this.oldPercent==="no"||this.oldPercent<this.progressPercent.percent)&&(this.progressCall({data:this.progressData,percent:h,allCount:s,allTotal:f}),this.oldPercent=this.progressPercent.percent),h>=100&&this.clearProgressData()},this.progressDelay)))}delay(){return new Promise(r=>setTimeout(r,500))}callBatchWithTimeout(r,e){return new Promise((i,n)=>{let a=!1;const l=6e4;let c=!1,h=!1,s=!1,f=null,m=null;const A=async(y,p)=>{if(!a){a=!0,f&&clearTimeout(f),m&&clearTimeout(m);try{await Promise.resolve(e(y)),i()}catch(R){console.error(`Error in callBatch callback (attempt ${p}):`,R),n(R)}}},u=async()=>{if(!a){a=!0,f&&clearTimeout(f),m&&clearTimeout(m),console.warn(`Batch request timeout after ${l}ms on both attempts. This may indicate a CORS or network error.`);const y={};Object.keys(r).forEach(p=>{y[p]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 30 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(e(y)),i()}catch(p){console.error("Error in timeout callback:",p),i()}}},N=y=>{try{this.callBatch(r,async p=>{y===1&&!c&&!a?(c=!0,await A(p,1)):y===2&&!s&&!a&&(s=!0,await A(p,2))})}catch(p){a||console.error(`Error calling callBatch (attempt ${y}):`,p)}};N(1),f=setTimeout(async()=>{!c&&!a&&!h&&(console.warn(`First batch request attempt timeout after ${l}ms. Starting second attempt...`),h=!0,N(2),m=setTimeout(async()=>{!c&&!s&&!a&&await u()},l))},l)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.limitCall="",this.oldPercent="no"}async batch(r,e,i){this.progressTimer&&this.clearProgressData(),e&&(this.progressCall=e),i&&(this.limitCall=i),this.canContinue=!0,this.result={},this.errors={};const n={},a={},l={};for(const[f,m]of Object.entries(r)){const A=this.arrayChunk(m);if(!A)continue;const u=this.splitLargeFilters(f,A);if(u.length===1)a[f]=A;else{l[f]=[];for(const N of u)a[N.key]=N.request,l[f].push(N.key)}}this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let c={},h=0;const s=Object.keys(a).length;for(const[f,m]of Object.entries(a)){if(!this.canContinue)break;c[f]=m,(Object.keys(c).length>=50||h+1===s)&&(await this.batchChunk(c),Object.entries(this.result).forEach(([A,u])=>{n[A]=u}),this.totalProgress=Math.round(h/s*100),c={}),h++}for(const[f,m]of Object.entries(l))if(m&&m.length>0){const A=this.mergeSplitResults(n,f);for(const u of m)delete n[u];n[f]=A}return Object.entries(this.errors).length&&(n.errorsList=this.errors),e&&e({percent:100}),Promise.resolve(n)}async batchTotalCount(r,e,i){this.progressTimer&&this.clearProgressData(),e&&(this.progressCall=e),i&&(this.limitCall=i),this.canContinue=!0,this.result={},this.errors={};const n={},a={},l={};for(const[s,f]of Object.entries(r)){const m=this.arrayChunk(f);if(!m)continue;const A=this.splitLargeFilters(s,m);if(A.length===1)a[s]=m;else{l[s]=[];for(const u of A)a[u.key]=u.request,l[s].push(u.key)}}const c=[],h=Object.entries(a);for(let s=0;s<h.length;s+=this.limit){const f=h.slice(s,s+this.limit),m={};for(const[A,u]of f){if(!this.canContinue)break;m[A]=u}Object.keys(m).length>0&&c.push(m)}this.chunkRate=(1/c.length).toFixed(5);for(const[s,f]of Object.entries(c)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(s)/c.length*100),await this.callBatchWithTimeout(f,async m=>{var A,u,N,y,p,R,b;for(const[D,B]of Object.entries(m)){if(!this.canContinue)return;if(B.error()){const O=(u=(A=B.error())==null?void 0:A.ex)==null?void 0:u.error,t=(y=(N=B.error())==null?void 0:N.ex)==null?void 0:y.error_description;this.errors[D]=O&&O.trim()||t&&t.trim()||((p=B.error())==null?void 0:p.toString())||"Неизвестная ошибка",n[D]=0;const o=((b=(R=B.error())==null?void 0:R.ex)==null?void 0:b.error)??"";let d="";const g=f[D];switch(Array.isArray(g)?[d]=g:g!=null&&g.method&&(d=g.method),o){case"OPERATION_TIME_LIMIT":d&&this.skipList.add(d),this.limitCall&&this.limitCall(D);break;case"ACCESS_DENIED":d&&this.skipList.add(d);break;case"TIMEOUT":d&&this.skipList.add(d),this.limitCall&&this.limitCall(D);break}continue}const k=this.getData(B.data()),J=Array.isArray(k)?k.length:0,X=typeof B.total=="function"&&B.total()!==void 0?B.total():J;n[D]=X,this.setProgressData({key:D,value:B,type:"count"})}})}for(const[s,f]of Object.entries(l))if(f&&f.length>0){let m=0;for(const A of f)n[A]!==void 0&&(m+=n[A]||0),delete n[A];n[s]=m}return Object.entries(this.errors).length&&(n.errorsList=this.errors,this.errorLogger()),e&&e({percent:100}),Promise.resolve(n)}arrayChunk(r){let e="",i={};if(Array.isArray(r)?[e]=r:(e=r.method,i=r.params),this.skipList.has(e))return!1;if((e.includes("list")||e==="user.get")&&e!=="task.item.list"){if(!i)i={order:{ID:"ASC",id:"ASC"}};else{e==="tasks.task.list"?(i.order||(i.order={}),i.order.ID="asc"):e==="user.get"?(i.sort||(i.sort="ID"),i.order||(i.order="ASC")):i.order={ID:"ASC",id:"ASC"},Array.isArray(i.select)&&!i.select.includes("ID")&&i.select.push("ID");const n=e==="user.get"?i.FILTER:i.filter;typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.entries(n).forEach(([a,l])=>{(i.start===void 0||i.start!==-1)&&["id","ID"].includes(a)&&(typeof l=="string"||Array.isArray(l)&&l.length<=50)&&(i.start=-1)})}e==="crm.type.list"&&i.order&&delete i.order.ID}if(e==="task.item.list")if(!i)i=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(i[0])&&(i[0]={});const[n,a,l,c]=i;n.ID="ASC",c[0]!==""&&c.includes("ID")||c.push("ID")}return{method:e,params:i}}async batchChunk(r,e){return new Promise(i=>{const n=[];let a;this.callBatchWithTimeout(r,async l=>{var c,h,s,f,m,A,u;for(const[N,y]of Object.entries(l)){if(!this.canContinue)return;if(y.error()){const k=(h=(c=y.error())==null?void 0:c.ex)==null?void 0:h.error,J=(f=(s=y.error())==null?void 0:s.ex)==null?void 0:f.error_description;switch(this.errors[N]=k&&k.trim()||J&&J.trim()||((m=y.error())==null?void 0:m.toString())||"Неизвестная ошибка",a=!0,((u=(A=y.error())==null?void 0:A.ex)==null?void 0:u.error)??""){case"OPERATION_TIME_LIMIT":this.skipList.add(r[N].method),this.limitCall&&this.limitCall(N);break;case"ACCESS_DENIED":this.skipList.add(r[N].method);break;case"TIMEOUT":let X=r[N],O="";Array.isArray(X)?[O]=X:X!=null&&X.method&&(O=X.method),O&&this.skipList.add(O),this.limitCall&&this.limitCall(N);break}}const p=this.getData(y.data()),R=Array.isArray(p)?p.length:0,b=typeof y.total=="function"&&y.total()!==void 0,D=b?y.total():R;e==="count"?this.result[N]?this.result[N]+=R:this.result[N]=D:this.result[N]=p,this.setProgressData({key:N,value:y,type:e});const B=e==="count"?!b&&R===this.limit:D>this.limit&&D>R;if(!this.canContinue||B){let k=r[N];if(Array.isArray(k)){const[J,I={}]=k;k=[J,I]}else{const{method:J,params:I={}}=k;k=[J,I]}n.push([N,k,D])}}a>0&&this.errorLogger(),n.length?await this.batchPayload(n,e).then(()=>i(this.result)):i(this.result)})})}async batchPayload(r,e){const i=new Map,n=(h,s,f,m)=>{let A="ID";this.result[h][this.result[h].length-1].ID||(A="id");let u=`${A}`;if(JSON.stringify(m[1]).toLocaleLowerCase().includes('"id":"desc"')?u="<"+u:u=">"+u,s===1||f.length===0)return{field:u,id:this.result[h][this.result[h].length-1][A]};let y="";const[p,R]=m;return(p==="tasks.task.list"||p==="task.item.list")&&(y="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(p)&&(y="[items]"),p==="crm.type.list"&&(y="[types]"),p==="socialnetwork.api.workgroup.list"&&(y="[workgroups]"),{field:u,id:`$result[${[h,s-1].join("__")}]${y}[49][${A}]`}},a=(h,s)=>{const[f,m]=h;let A=JSON.parse(JSON.stringify(m)),u;if(f==="task.item.list"){A=[...A];const[N,y,p,R]=A;return y[s.field]=s.id,[f,A]}return["user.get"].includes(f)||A.FILTER?(A.FILTER||(A.FILTER={}),u=A.FILTER):(A.filter||(A.filter={}),u=A.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(f)?u[">ID"]=s.id:u[s.field]=s.id,[f,{...A,start:-1}]},l=h=>{Object.entries(h).forEach(([s,f])=>{var u,N,y,p,R,b,D;const[m]=s.split("__"),A=this.getData(f.data());if(Array.isArray(A)&&(e==="count"?this.result[m]+=A.length:this.result[m].push(...A)),f.error()){const B=(N=(u=f.error())==null?void 0:u.ex)==null?void 0:N.error,k=(p=(y=f.error())==null?void 0:y.ex)==null?void 0:p.error_description;this.errors[m]=B&&B.trim()||k&&k.trim()||((R=f.error())==null?void 0:R.toString())||"Неизвестная ошибка";const J=((D=(b=f.error())==null?void 0:b.ex)==null?void 0:D.error)??"",I=i.get(m);switch(J){case"OPERATION_TIME_LIMIT":I&&(this.skipList.add(I),this.limitCall&&this.limitCall(m));break;case"QUERY_LIMIT_EXCEEDED":this.canContinue=!1;break;case"ACCESS_DENIED":I&&this.skipList.add(I);break;case"TIMEOUT":I&&(this.skipList.add(I),this.limitCall&&this.limitCall(m));break}}this.setProgressData({key:m,value:f,type:e})})};let c=[];for await(const[h,s,f]of r){if(!this.canContinue)return;const[m]=s;if(i.set(h,m),this.skipList.has(m))continue;let A=1;for(;f>A*50&&!this.skipList.has(m);){const u=[h,A].join("__"),N=n(h,A,c,s);c.push([u,a(s,N)]),c.length%50===0&&(await this.callBatchWithTimeout(Object.fromEntries(c),y=>{l(y)}),c=[],await this.delay()),A++}}c.length&&(await this.callBatchWithTimeout(Object.fromEntries(c),h=>{l(h)}),await this.delay())}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([r,e])=>{e&&console.log(`[${r}]`,e.toString())}),console.groupEnd()}}class ft{constructor(){Y(this,q,{})}get hash(){return this.createHash(8)}createHash(r){let e="abcdefghijklmnopqrstuvwxyz0123456789",i="";r=r||6;for(let n=0;n<r;n++)i+=e.charAt(Math.floor(Math.random()*e.length));return i}actionFilter({keyTimer:r,duration:e=10,action:i}){T(this,q)[r]&&(clearTimeout(T(this,q)[r]),T(this,q)[r]=null),i&&(T(this,q)[r]=setTimeout(()=>{i()},e))}async noSleep(){let r=document.createElement("video");r.classList.add("no-sleep"),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.addEventListener("loadeddata",()=>{r.style.position="fixed",r.style.left="-9999px",document.querySelector("body").append(r),r.play().catch(e=>{console.warn("noSleep: autoplay prevented",e)})}),r.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{r.play().catch(e=>{console.warn("noSleep: replay prevented",e)})}})}),r.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(r,e){let i=new Blob([JSON.stringify(r)],{type:"application/json"}),n=URL.createObjectURL(i),a=document.createElement("a");a.style.display="none",a.href=n,a.download=`${e}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(n)},200)}}q=new WeakMap;const mt=new ft;class yt{constructor(){Y(this,at);Y(this,nt);Y(this,At);Y(this,ct);Y(this,ht);Y(this,Q,"logger");Y(this,Z,!1);Y(this,$,new Map);Y(this,rt,{});Y(this,W,null);Y(this,tt,!1);Y(this,st,!1);M(this,"periodClear",3);K(this,at,Nt).call(this)}async init(){try{let r=new z(BX24.callBatch),{entityList:e}=await r.batch({entityList:{method:"entity.get"}});if(e&&Array.isArray(e))if(e.find(n=>n.ENTITY==T(this,Q)))v(this,Z,!0);else{let{entityAdd:n}=await r.batch({entityAdd:{method:"entity.add",params:{ENTITY:T(this,Q),NAME:T(this,Q),ACCESS:{AU:"X"}}}});n&&v(this,Z,!0)}return K(this,ct,_t).call(this).catch(i=>{console.error("Ошибка при проверке периода очистки:",i)}),T(this,Z)}catch(r){return console.error("Ошибка при инициализации логера:",r),!1}}start({type:r,data:e}){if(!T(this,Z))return K(this,nt,gt).call(this,"entity"),null;if(!r||!e)return console.error("Невалидные данные для логирования:",{type:r,data:e}),null;const i=mt.hash,n={type:r,data:e,userInfo:T(this,rt),errorList:{},status:"",answer:null,date:new Date().getTime()};return T(this,$).set(i,n),v(this,st,!0),i}async stop({key:r,errorList:e,status:i,answer:n}){var l;if(!T(this,st))return;if(!T(this,Z)){K(this,nt,gt).call(this,"entity");return}let a=T(this,$).get(r);if(!a){console.error(`Не найдены данные логирования для ключа: ${r}`);return}e&&(a.errorList=e),i&&(a.status=i),n&&(a.answer=n),await K(this,At,Ot).call(this),(l=a==null?void 0:a.data)!=null&&l.updateList&&v(this,tt,!0),v(this,st,!1)}async getEntityList(r){var e;try{if((e=T(this,W))!=null&&e.length&&!T(this,tt))return T(this,W);let i=new z(BX24.callBatch),{entityList:n}=await i.batch({entityList:{method:"entity.item.get",params:{ENTITY:T(this,Q),SORT:{ID:"DESC"}}}},r);return!n||!Array.isArray(n)?(console.warn("Получен невалидный список записей"),[]):(n=n.map(a=>{try{const{ID:l,DATE_CREATE:c,DETAIL_TEXT:h}=a;return{...JSON.parse(h),id:l,dateCreate:c}}catch(l){return console.error(`Ошибка парсинга записи ${a.ID}:`,l),null}}).filter(a=>a!==null),v(this,tt,!1),v(this,W,n),n)}catch(i){return console.error("Ошибка при получении списка записей:",i),[]}}async downAllEntityJson(){try{if(T(this,W)||await this.getEntityList(),!T(this,W)||T(this,W).length===0)return console.warn("Нет данных для выгрузки"),!1;let r=it().format("%Y-%m-%d");return mt.downloadFileJson(T(this,W),`sdklogger-entity-data__${r}`),!0}catch(r){return console.error("Ошибка при выгрузке данных в JSON:",r),!1}}}Q=new WeakMap,Z=new WeakMap,$=new WeakMap,rt=new WeakMap,W=new WeakMap,tt=new WeakMap,st=new WeakMap,at=new WeakSet,Nt=async function(){try{const r=new z(BX24.callBatch),e=BX24.isAdmin(),{curUser:i}=await r.batch({curUser:{method:"user.current"}});v(this,rt,{isAdmin:e,curUser:i})}catch(r){console.error("Ошибка при получении информации о пользователе:",r),v(this,rt,{isAdmin:!1,curUser:null})}},nt=new WeakSet,gt=function(r){r=="entity"&&mt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},At=new WeakSet,Ot=async function(){try{let r={},e=new z(BX24.callBatch);for(let[i,n]of T(this,$).entries())if(n.status){const a=JSON.stringify(n);r[i]={method:"entity.item.add",params:{ENTITY:T(this,Q),NAME:T(this,Q),DETAIL_TEXT:a}}}if(Object.keys(r).length){let i=await e.batch(r),{errors:n}=e;for(let[a,l]of Object.entries({...i,...n}))T(this,$).delete(a);return!0}return!1}catch(r){return console.error("Ошибка при добавлении записей в хранилище:",r),!1}},ct=new WeakSet,_t=async function(){try{let r=new z(BX24.callBatch),{serverTime:e}=await r.batch({serverTime:{method:"server.time"}});if(!e){console.error("Не удалось получить время сервера");return}if(T(this,W)||await this.getEntityList(),!T(this,W)||T(this,W).length===0)return;let i=T(this,W).filter(n=>{try{let{dateCreate:a}=n;return a?it(new Date(a)).between(it(new Date(e)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});i.length>0&&(console.log(`Найдено ${i.length} записей для очистки (старше ${this.periodClear} месяцев)`),await K(this,ht,Et).call(this,i))}catch(r){console.error("Ошибка при проверке периода очистки:",r)}},ht=new WeakSet,Et=async function(r){try{if(!r||r.length===0)return!1;let e=new z(BX24.callBatch),i=r.filter(a=>a&&a.id).map(a=>{let{id:l}=a;return{method:"entity.item.delete",params:{ENTITY:T(this,Q),ID:l}}});if(i.length===0)return!1;const n=await e.batch(i);return console.log(`Успешно удалено ${i.length} записей`),v(this,tt,!0),n}catch(e){return console.error("Ошибка при очистке устаревших записей:",e),!1}};class bt{constructor(r){Y(this,lt);Y(this,ut);Y(this,ot);M(this,"domain","");M(this,"isAdmin",!1);M(this,"appInfo",null);M(this,"appConst",null);M(this,"userInfo",null);M(this,"placeData",null);M(this,"placeInfo",null);M(this,"logger",!1);this.appConst=r}init(){return new Promise((r,e)=>{let n=setInterval(()=>{window.BX24&&BX24.init(async()=>{console.info("init BX24"),clearInterval(n),clearTimeout(a),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info(),this.logger?(this.logger=new yt,await this.logger.init()):this.logger={start:()=>{},stop:()=>{},getEntityList:()=>{}};const[l,c]=await Promise.all([K(this,lt,Tt).call(this),K(this,ut,Rt).call(this)]);this.appInfo=l,this.userInfo=c;let h=new ft;try{h.noSleep()}catch(s){console.warn("Failed to initialize noSleep:",s)}r(!0)})},100);const a=setTimeout(()=>{clearInterval(n);const l=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(l),e(l)},3e4)})}userOption(r,e){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.userOption.set(r,e):BX24.userOption.get(r)}appOption(r,e){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.appOption.set(r,e):BX24.appOption.get(r)}async call({method:r,params:e,updateList:i}){let n;if(i&&(n=this.logger.start({type:"call",data:{method:r,params:e,updateList:i}})),e||(e={}),typeof BX24>"u"||!BX24.callMethod){const a=new Error("BX24 is not initialized");throw console.error(a),a}return new Promise((a,l)=>{BX24.callMethod(r,e,async c=>{let h={};if(c!=null&&c.answer)for(let[s,f]of Object.entries(c.answer))s!=="result"&&f&&(h[s]=f);if(c.error()){let s=c.error();if(console.error(s),n)try{await this.logger.stop({answer:h,key:n,status:"fail",errorList:{0:s.toString()}})}catch(f){console.error("Logger error:",f)}a(!1)}else{let s=c.data();if(s!=null&&s.items&&(s=s.items),n)try{await this.logger.stop({answer:h,key:n,status:"success"})}catch(f){console.error("Logger error:",f)}a(s)}})})}async batch(r,e,{errorCall:i,limitCommandSerial:n,updateList:a,limitCall:l}={}){if(typeof BX24>"u"||!BX24.callBatch){const s=new Error("BX24 is not initialized");return console.error(s),!1}let c=new z(BX24.callBatch),h;a&&(h=this.logger.start({type:"batch",data:{commandList:r,updateList:a}})),n&&console.warn("limitCommandSerial is deprecated and not used in current Batch implementation");try{let s=await c.batch(r,e,l);const f=K(this,ot,pt).call(this,c,s,r,a);if(Object.keys(f).length){if(i&&i(f),h)try{await this.logger.stop({key:h,status:"fail",errorList:f})}catch(m){console.error("Logger error:",m)}}else if(h)try{await this.logger.stop({key:h,status:"success"})}catch(m){console.error("Logger error:",m)}return s}catch(s){if(h)try{await this.logger.stop({key:h,status:"fail-runtime",errorList:{0:s==null?void 0:s.toString()}})}catch(f){console.error("Logger error:",f)}return console.error(s),!1}}async batchTotalCount(r,e,{errorCall:i,updateList:n,limitCall:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const h=new Error("BX24 is not initialized");return console.error(h),!1}let l=new z(BX24.callBatch),c;n&&(c=this.logger.start({type:"batch-total-count",data:{commandList:r}}));try{let h=await l.batchTotalCount(r,e,a);const s=K(this,ot,pt).call(this,l,h,r,n);if(Object.keys(s).length){if(i&&i(s),c)try{await this.logger.stop({key:c,status:"fail",errorList:s})}catch(f){console.error("Logger error:",f)}}else if(c)try{await this.logger.stop({key:c,status:"success"})}catch(f){console.error("Logger error:",f)}return h}catch(h){if(c)try{await this.logger.stop({key:c,status:"fail-runtime",errorList:{0:h==null?void 0:h.toString()}})}catch(s){console.error("Logger error:",s)}return console.error(h),!1}}async getPlacement(){return await this.call({method:"placement.get"}).then(r=>(this.placeData||(this.placeData=r),r))}async placementBind(r,e=!0){var f;if(!this.isAdmin)return;e&&await this.placementCheck();let i=[];if(Array.isArray(r)?i=r.map(m=>typeof m=="string"?{placement:m}:m):typeof r=="string"?i=[{placement:r}]:i=[r],i=i.filter(m=>m.placement!=="PAGE_BACKGROUND_WORKER"&&m.placement!=="PAGE_BACKGROUND_WORKER_ALL"),this.placeData=await this.getPlacement(),!this.placeData)return;const{appName:n,pathApp:a}=this.appConst;let l=n;this.domain==="szdl.bitrix24.ru"&&((f=this.appInfo)!=null&&f.ID)&&(l=`${n}: #${this.appInfo.ID}`);const c=l.replace(" CRM",""),h={},s=[];for(let m=0;m<i.length;m++){const u=i[m].placement,N=a;if(this.placeData.find(b=>b.placement===u&&b.handler===N))continue;const p=this.placeData.find(b=>b.placement===u&&b.handler!==N);p&&s.push({placement:u,handler:p.handler});const R={PLACEMENT:u,HANDLER:N,LANG_ALL:{ru:{TITLE:u==="USER_PROFILE_TOOLBAR"?c:l}},OPTIONS:{errorHandlerUrl:N}};h[`bind_${m}`]={method:"placement.bind",params:R}}s.length>0&&await this.placementUnBind(s),Object.keys(h).length>0&&await this.batch(h),Object.keys(h).length>0&&(this.placeData=await this.getPlacement(),Object.values(h).forEach(m=>{console.log("Приложение успешно встроено в",m.params.PLACEMENT)}))}async placementUnBind(r){let e=[];Array.isArray(r)?e=r.map(n=>typeof n=="string"?{placement:n}:n):typeof r=="string"?e=[{placement:r}]:e=[r],e=e.filter(n=>n.placement!=="PAGE_BACKGROUND_WORKER"&&n.placement!=="PAGE_BACKGROUND_WORKER_ALL");const i={};for(let n=0;n<e.length;n++){const a=e[n],l=a.placement,c=a.handler,h={PLACEMENT:l};c&&(h.HANDLER=c),i[`unbind_${n}`]={method:"placement.unbind",params:h}}Object.keys(i).length>0&&(await this.batch(i),e.forEach(n=>{console.log("Встройка отвязана",n.placement)}))}async placementCheck(){if(this.placeData=await this.getPlacement(),!this.placeData)return;const{pathApp:r}=this.appConst,e=[],i=[];for(const n of this.placeData){if(n.placement==="PAGE_BACKGROUND_WORKER"||!n.handler||n.handler.includes(r))continue;const{placement:a,handler:l,userId:c}=n;e.push({placement:a,handler:l}),i.push({placement:a,userId:c})}e.length>0&&await this.placementUnBind(e),i.length>0&&await this.placementBind(i,!1)}getBotList(){return this.call({method:"imbot.bot.list",params:{}}).then(r=>{let e=Object.values(r);return console.log("chat-bot list:",e),e})}regBot({code:r,type:e,name:i}){const{appName:n,pathApp:a,chatBotLogo:l}=this.appConst,c=this.appInfo.ID;return this.call({method:"imbot.register",params:{CODE:r??this.appInfo.CODE,TYPE:e??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${i??n} - бот #${c}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:it().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:l??""}}}).then(h=>(console.log("Чат-бот добавлен",h),h))}unRegBot(r){return this.call({method:"imbot.unregister",params:{BOT_ID:r}}).then(e=>(console.log("чат-бот удален",e),e))}getLoggerList(r){return this.logger.getEntityList(r)}}lt=new WeakSet,Tt=function(){return this.call({method:"app.info"})},ut=new WeakSet,Rt=function(){return this.call({method:"user.current"})},ot=new WeakSet,pt=function(r,e,i,n){let a={...r.errors};if(Object.values(r.errors).some(c=>{if(typeof c!="string")return!1;const h=c.toUpperCase();return h==="TIMEOUT"||h==="OPERATION_TIME_LIMIT"||h.includes("TIMEOUT")||h.includes("OPERATION_TIME_LIMIT")})&&n){const c=e?Object.keys(e).filter(m=>m!=="errorsList"):[],h=new Set(Object.keys(r.errors||{})),s=new Set;if(e){for(const m of c)if(!h.has(m)){const A=e[m];A!=null&&s.add(m)}}const f=Object.values(r.errors).find(m=>{if(typeof m!="string")return!1;const A=m.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const m of Object.keys(i))!s.has(m)&&!r.errors[m]&&(a[m]=f||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a};class St{constructor(r){M(this,"entityName","tabs");M(this,"maxTabs",20);M(this,"tabList",[]);M(this,"id",0);M(this,"hasStarted",!1);M(this,"heartbeat");M(this,"runHeartbeat");M(this,"random",this.getRandomNum());M(this,"activeMaxPause",5*60*1e3+this.random);M(this,"quickCleanupThreshold",2*60*1e3);M(this,"pollInterval",(60+this.random)*1e3);M(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);M(this,"continueCondition");M(this,"defaultContinueBackground",()=>!0);var l,c,h;if(!r){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:e,bx:i,users:n,continueBackground:a}=r;this.bx=i,this.appInit=e,this.users=n,this.appPath=((l=i==null?void 0:i.appConst)==null?void 0:l.pathApp)??"",this.appName=((c=i==null?void 0:i.appConst)==null?void 0:c.appName)??"",this.appCodeName=((h=i==null?void 0:i.appConst)==null?void 0:h.appCodeName)??"",this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("BackgroundWorker: appInit не передан");return}if(!this.bx){console.error("BackgroundWorker: bx не передан");return}if(this.isAppPage()){console.log("BackgroundWorker: Страница приложения, фоновый воркер не запускается");return}await this.checkPlacementType()&&await this.continueBackground()&&(await this.checkEntity(),await this.refreshTabs(!0),await this.ensureTabRegistered(),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(e=>{console.error("BackgroundWorker: backgroundTick failed",e)})},this.pollInterval),await this.backgroundTick())}async backgroundTick(){if(!await this.continueBackground()){this.stopTimers(),console.log("BackgroundWorker: Остановка backgroundTick - условие не выполнено");return}await this.refreshTabs(!0),await this.ensureTabRegistered();const e=this.selectLeaderId(),i=e&&this.id===e;await this.updateTabState(i),i&&!this.hasStarted&&(this.hasStarted=!0,await this.runAsLeader())}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var r;if(typeof BX24>"u"||!((r=BX24.placement)!=null&&r.info))return!1;try{const e=BX24.placement.info(),i=e==null?void 0:e.placement,n=(e==null?void 0:e.options)||{},a=(n==null?void 0:n.URI)||"",l=i==="PAGE_BACKGROUND_WORKER"||(n==null?void 0:n.ID)==="PAGE_BACKGROUND_WORKER",c=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!l||c}catch{return!1}}async checkEntity(){var i;const r=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((i=r==null?void 0:r.find)==null?void 0:i.call(r,n=>n.ENTITY===this.entityName))||await this.safeCall(()=>this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}}))}async getTabs(){const r=await this.safeCall(()=>{var e;return this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:(e=this.bx.userInfo)==null?void 0:e.ID},SORT:{DATE_CREATE:"DESC"}}})});return!Array.isArray(r)||!r.length?[]:r.map(e=>{if(!e)return{id:void 0,data:void 0};try{const i=JSON.parse(e.DETAIL_TEXT);return{id:e.ID,data:i}}catch(i){return console.log("BackgroundWorker: parse tab error",i),{id:e.ID,data:void 0}}})}async ensureTabRegistered(){if(this.id)return this.id;if(this.tabList.length>=this.maxTabs&&await this.refreshTabs(!0,this.quickCleanupThreshold),this.tabList.length>=this.maxTabs)return console.log("BackgroundWorker: Достигнут лимит вкладок даже после быстрой очистки, не регистрируемся"),0;const r={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId},e=await this.safeCall(()=>{var i;return this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(i=this.bx.userInfo)==null?void 0:i.ID,DETAIL_TEXT:JSON.stringify(r)}})})||0;return this.id=e,e}async updateTabState(r){if(!this.id)return;const e={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:r,sessionId:this.sessionId};await this.safeCall(()=>{var i;return this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(i=this.bx.userInfo)==null?void 0:i.ID,DETAIL_TEXT:JSON.stringify(e)}})})}async deleteTabs(r=[]){if(!r.length)return;const e=r.map(i=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:i.id}}));await this.safeCall(()=>this.bx.batch(e))}getRandomNum(){const r=Math.round(Number(Math.random().toFixed(2))*30);return Math.round(Math.random())?r:-r}async checkPlacementType(){var r;try{const e=await this.safeCall(()=>this.bx.getPlacement());if(!e||!Array.isArray(e))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((r=this.bx.userInfo)==null?void 0:r.ID)??0),n=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),a=!n;if(!i)return!0;let l=!1;for(const c of e){if(c.placement!=="PAGE_BACKGROUND_WORKER"||!(c.userId||c.handler&&c.handler.includes("USER_ID=")))continue;const s=c.userId||(c.handler?this.extractUserIdFromHandler(c.handler):null);if(s&&+s===i){l=!0;break}}return n?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):a&&l?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(e){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",e),!0}}isIndividualPlacement(r){return!r||typeof r!="string"?!1:r.includes("USER_ID=")}extractUserIdFromHandler(r){if(!r||typeof r!="string")return null;const e=r.match(/USER_ID=(\d+)/);return e?e[1]:null}async continueBackground(){try{const e=!!await Promise.resolve(this.continueCondition(this));return console.log(e?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),e}catch(r){return console.error("BackgroundWorker: Ошибка в continueCondition",r),!1}}async refreshTabs(r=!1,e=this.activeMaxPause){const i=[],n=[],a=Date.now(),l=await this.getTabs();for(const c of l){if(!(c!=null&&c.data)){i.push(c);continue}if(a-new Date(c.data.lastActive||0).getTime()>e){i.push(c);continue}n.push(c)}return r&&i.length&&await this.deleteTabs(i),this.tabList=n,n}selectLeaderId(){var e;return this.tabList.length&&((e=[...this.tabList].sort((i,n)=>{var c,h,s,f;const a=new Date(((c=i.data)==null?void 0:c.createdAt)||((h=i.data)==null?void 0:h.lastActive)||0).getTime(),l=new Date(((s=n.data)==null?void 0:s.createdAt)||((f=n.data)==null?void 0:f.lastActive)||0).getTime();return a===l?i.id-n.id:a-l})[0])==null?void 0:e.id)||0}async runAsLeader(){this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(r=>console.error("BackgroundWorker: heartbeat update failed",r))},Math.max(20*1e3,Math.floor(this.pollInterval/2)));try{await this.appInit()}catch(r){console.error("BackgroundWorker: appInit failed",r)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)}async setBackgroundWorkerAll(){var N,y;if(!((N=this.bx)!=null&&N.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(y=this.users)!=null&&y.length||await this.getEntityData();const r=await this.safeCall(()=>this.bx.getPlacement()),e=new Map;let i=null;(r||[]).forEach(p=>{if(p.placement!=="PAGE_BACKGROUND_WORKER")return;if(p.userId||p.handler&&p.handler.includes("USER_ID=")){const b=p.userId||(p.handler?this.extractUserIdFromHandler(p.handler):null);b&&e.set(+b,p)}else i=p});const n=await this.resolveAdmins(),a=await this.getEligibleUsersForBackgroundWorker(n);a.sort((p,R)=>{const b=p.LAST_LOGIN?new Date(p.LAST_LOGIN):new Date(0);return(R.LAST_LOGIN?new Date(R.LAST_LOGIN):new Date(0))-b});const l=10,h=a.slice(0,l).filter(p=>!e.has(+p.ID)),s=[];for(const[p]of e)a.find(b=>+b.ID===p)||s.push(p);const f=[];for(const p of s)this.appPath&&f.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${p}/`}});const m=i&&h.length>0;m&&this.appPath&&f.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:i.handler||`${this.appPath}`}});for(const p of h)this.appPath&&f.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${p.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}?USER_ID=${p.ID}/`},USER_ID:p.ID}});(!i||m)&&this.appPath&&f.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}`}}});const A=f.filter(p=>p.method==="placement.unbind"),u=f.filter(p=>p.method==="placement.bind");A.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(A.map((p,R)=>[`unbind_${R}`,p])))),u.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(u.map((p,R)=>[`bind_${R}`,p])))),f.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var r,e;try{const i=+(((r=this.bx.userInfo)==null?void 0:r.ID)??0),n=!!((e=this.bx)!=null&&e.isAdmin),a=await this.getAdminsList()||[];if(!n){if(i&&a.includes(i)){const h=a.filter(s=>s!==i);return await this.saveAdminsList(h),h}return a}const l=new Set([...a||[]]);i&&l.add(i);const c=[...l].filter(Boolean);return await this.saveAdminsList(c),c}catch(i){return console.error("BackgroundWorker: resolveAdmins error",i),[]}}async getEligibleUsersForBackgroundWorker(r=[]){return(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0).filter(i=>r.includes(+i.ID))}async saveAdminsList(r=[]){try{BX24.appOption.set("adminsList",JSON.stringify(r))}catch(e){console.error("BackgroundWorker: saveAdminsList error",e)}}async getAdminsList(){try{const r=BX24.appOption.get("adminsList");return r?JSON.parse(r):[]}catch(r){return console.error("BackgroundWorker: getAdminsList error",r),[]}}async getEntityData(){const r={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:e}=await this.safeCall(()=>this.bx.batch(r).then(i=>i?(Array.isArray(i.users)||(i.users=[]),i):{users:[]}));this.users=e}async ensureAdminPlacements(){var r,e;(r=this.bx)!=null&&r.isAdmin&&((e=this.users)!=null&&e.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(r=500,e){return new Promise(i=>{setTimeout(()=>{e&&e(),i(!0)},r)})}async safeCall(r){try{return await r()}catch(e){console.error("BackgroundWorker: safeCall error",e);return}}}_.BackgroundWorker=St,_.Batch=z,_.BxBoot=bt,_.BxHelper=ft,_.BxLogger=yt,_.tempus=it,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
var It=Object.defineProperty;var Mt=(_,L,C)=>L in _?It(_,L,{enumerable:!0,configurable:!0,writable:!0,value:C}):_[L]=C;var M=(_,L,C)=>(Mt(_,typeof L!="symbol"?L+"":L,C),C),dt=(_,L,C)=>{if(!L.has(_))throw TypeError("Cannot "+C)};var T=(_,L,C)=>(dt(_,L,"read from private field"),C?C.call(_):L.get(_)),Y=(_,L,C)=>{if(L.has(_))throw TypeError("Cannot add the same private member more than once");L instanceof WeakSet?L.add(_):L.set(_,C)},v=(_,L,C,et)=>(dt(_,L,"write to private field"),et?et.call(_,C):L.set(_,C),C);var K=(_,L,C)=>(dt(_,L,"access private method"),C);(function(_,L){typeof exports=="object"&&typeof module<"u"?L(exports):typeof define=="function"&&define.amd?define(["exports"],L):(_=typeof globalThis<"u"?globalThis:_||self,L(_["szdl-utils-kit"]={}))})(this,function(_){var q,Q,Z,$,rt,W,tt,st,at,Nt,nt,gt,At,Ot,ct,_t,ht,Et,lt,Tt,ut,Rt,ot,pt;"use strict";var L=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function C(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x.default:x}var et={exports:{}};(function(x,r){(function(e){Array.prototype.indexOf||(Array.prototype.indexOf=function(t,o){var d,g;for(d=o||0,g=this.length;d<g;d+=1)if(this[d]===t)return d;return-1});var i=this,n=function(t,o){for(var d=t.toString();d.length<o;)d="0"+d;return d},a=function(t,o){return o!==e?(t.year(o.year()||o.year),t.month(o.month()||o.month),t.day(o.day()||o.day),t.hours(o.hours()||o.hours),t.minutes(o.minutes()||o.minutes),t.seconds(o.seconds()||o.seconds),t.milliseconds(o.milliseconds()||o.milliseconds),t):e},l=function(t,o){var d,g="";return d=t.slice(o,o+1),d!==""&&!isNaN(Number(d))&&(g+="%H"),d=t.charAt(o+2),d!==""&&d===":"&&(g+=d),d=t.slice(o+3,o+4),d!==""&&!isNaN(Number(d))&&(g+="%M"),d=t.charAt(o+5),d!==""&&d===":"&&(g+=d),d=t.slice(o+6,o+7),d!==""&&!isNaN(Number(d))&&(g+="%S"),g},c=function(t,o){var d,g=[t.slice(o,o+1),t.charAt(o+2),t.slice(o+3,o+4),t.charAt(o+5),t.slice(o+6,o+9)],w;return!isNaN(Number(g[0]))&&!isNaN(Number(g[2]))&&!isNaN(Number(g[4]))?(g[1]==="."&&g[3]==="."?d="%d.%m.%Y":g[1]==="-"&&g[3]==="-"?d="%m-%d-%Y":g[1]==="/"&&g[3]==="/"&&(d="%m/%d/%Y"),d):(w=[t.slice(o,o+3),t.charAt(o+4),t.slice(o+5,o+6),t.charAt(o+7),t.slice(o+8,o+9)],!isNaN(Number(w[0]))&&!isNaN(Number(w[2]))&&!isNaN(Number(w[4]))?(w[1]==="-"&&w[3]==="-"&&(d="%Y-%m-%d"),d):"")},h=i.tempus,s,f,m=i.navigator||{},A="en",u={en:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"Mar",APRIL_SHORT:"Apr",MAY_SHORT:"May",JUNE_SHORT:"Jun",JULY_SHORT:"Jul",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sep",OCTOBER_SHORT:"Oct",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dec",JANUARY_LONG:"January",FEBRUARY_LONG:"February",MARCH_LONG:"March",APRIL_LONG:"April",MAY_LONG:"May",JUNE_LONG:"June",JULY_LONG:"July",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"October",NOVEMBER_LONG:"November",DECEMBER_LONG:"December",SUNDAY_SHORT:"Sun",MONDAY_SHORT:"Mon",TUESDAY_SHORT:"Tue",WEDNESDAY_SHORT:"Wed",THURSDAY_SHORT:"Thu",FRIDAY_SHORT:"Fri",SATURDAY_SHORT:"Sat",SUNDAY_LONG:"Sunday",MONDAY_LONG:"Monday",TUESDAY_LONG:"Tuesday",WEDNESDAY_LONG:"Wednesday",THURSDAY_LONG:"Thursday",FRIDAY_LONG:"Friday",SATURDAY_LONG:"Saturday"},ru:{JANUARY_SHORT:"Янв",FEBRUARY_SHORT:"Фев",MARCH_SHORT:"Мар",APRIL_SHORT:"Апр",MAY_SHORT:"Май",JUNE_SHORT:"Июн",JULY_SHORT:"Июл",AUGUST_SHORT:"Авг",SEPTEMBER_SHORT:"Сен",OCTOBER_SHORT:"Окт",NOVEMBER_SHORT:"Ноя",DECEMBER_SHORT:"Дек",JANUARY_LONG:"Январь",FEBRUARY_LONG:"Февраль",MARCH_LONG:"Март",APRIL_LONG:"Апрель",MAY_LONG:"Май",JUNE_LONG:"Июнь",JULY_LONG:"Июль",AUGUST_LONG:"Август",SEPTEMBER_LONG:"Сентябрь",OCTOBER_LONG:"Октябрь",NOVEMBER_LONG:"Ноябрь",DECEMBER_LONG:"Декабрь",SUNDAY_SHORT:"Вс",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Воскресенье",MONDAY_LONG:"Понедельник",TUESDAY_LONG:"Вторник",WEDNESDAY_LONG:"Среда",THURSDAY_LONG:"Четверг",FRIDAY_LONG:"Пятница",SATURDAY_LONG:"Суббота"},ua:{JANUARY_SHORT:"Січ",FEBRUARY_SHORT:"Лют",MARCH_SHORT:"Берез",APRIL_SHORT:"Квіт",MAY_SHORT:"Трав",JUNE_SHORT:"Черв",JULY_SHORT:"Лип",AUGUST_SHORT:"Серп",SEPTEMBER_SHORT:"Верес",OCTOBER_SHORT:"Жовт",NOVEMBER_SHORT:"Листоп",DECEMBER_SHORT:"Груд",JANUARY_LONG:"Січень",FEBRUARY_LONG:"Лютий",MARCH_LONG:"Березень",APRIL_LONG:"Квітень",MAY_LONG:"Травень",JUNE_LONG:"Червень",JULY_LONG:"Липень",AUGUST_LONG:"Серпень",SEPTEMBER_LONG:"Вересень",OCTOBER_LONG:"Жовтень",NOVEMBER_LONG:"Листопад",DECEMBER_LONG:"Грудень",SUNDAY_SHORT:"Нд",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Неділя",MONDAY_LONG:"Понеділок",TUESDAY_LONG:"Вівторок",WEDNESDAY_LONG:"Середа",THURSDAY_LONG:"Четвер",FRIDAY_LONG:"П’ятниця",SATURDAY_LONG:"Субота"},de:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"März",APRIL_SHORT:"Apr",MAY_SHORT:"Mai",JUNE_SHORT:"Juni",JULY_SHORT:"Juli",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sept",OCTOBER_SHORT:"Okt",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dez",JANUARY_LONG:"Januar",FEBRUARY_LONG:"Februar",MARCH_LONG:"März",APRIL_LONG:"April",MAY_LONG:"Mai",JUNE_LONG:"Juni",JULY_LONG:"Juli",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"Oktober",NOVEMBER_LONG:"November",DECEMBER_LONG:"Dezember",SUNDAY_SHORT:"So",MONDAY_SHORT:"Mo",TUESDAY_SHORT:"Di",WEDNESDAY_SHORT:"Mi",THURSDAY_SHORT:"Do",FRIDAY_SHORT:"Fr",SATURDAY_SHORT:"Sa",SUNDAY_LONG:"Sonntag",MONDAY_LONG:"Montag",TUESDAY_LONG:"Dienstag",WEDNESDAY_LONG:"Mittwoch",THURSDAY_LONG:"Donnerstag",FRIDAY_LONG:"Freitag",SATURDAY_LONG:"Samstag"}},N=function(){return[u[A].JANUARY_LONG,u[A].FEBRUARY_LONG,u[A].MARCH_LONG,u[A].APRIL_LONG,u[A].MAY_LONG,u[A].JUNE_LONG,u[A].JULY_LONG,u[A].AUGUST_LONG,u[A].SEPTEMBER_LONG,u[A].OCTOBER_LONG,u[A].NOVEMBER_LONG,u[A].DECEMBER_LONG]},y=function(){return[u[A].JANUARY_SHORT,u[A].FEBRUARY_SHORT,u[A].MARCH_SHORT,u[A].APRIL_SHORT,u[A].MAY_SHORT,u[A].JUNE_SHORT,u[A].JULY_SHORT,u[A].AUGUST_SHORT,u[A].SEPTEMBER_SHORT,u[A].OCTOBER_SHORT,u[A].NOVEMBER_SHORT,u[A].DECEMBER_SHORT]},p=function(){return[u[A].SUNDAY_LONG,u[A].MONDAY_LONG,u[A].TUESDAY_LONG,u[A].WEDNESDAY_LONG,u[A].THURSDAY_LONG,u[A].FRIDAY_LONG,u[A].SATURDAY_LONG]},R=function(){return[u[A].SUNDAY_SHORT,u[A].MONDAY_SHORT,u[A].TUESDAY_SHORT,u[A].WEDNESDAY_SHORT,u[A].THURSDAY_SHORT,u[A].FRIDAY_SHORT,u[A].SATURDAY_SHORT]},S,D,B,k,J=function(t,o,d){var g;i.XMLHttpRequest?g=new XMLHttpRequest:g=new ActiveXObject("Microsoft.XMLHTTP"),g.onreadystatechange=function(){g.readyState===4&&(g.status===200?o&&(i.JSON===e?alert(`Please, include json2 into your project if you want use old browsers!
|
|
2
|
+
https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(g.responseText))):d&&d(g))},g.open("GET",t,!1),g.send()},I={"%d":{format:function(t){return n(t.day()||s.MIN_DAY,2)},parse:function(t){var o=Number(t);return{day:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(t){return n(t.month()||s.MIN_MONTH,2)},parse:function(t){var o=Number(t);return{month:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(t){return n(t.year()||s.MIN_YEAR,4)},parse:function(t){var o=Number(t);return{year:isNaN(o)?e:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(t){return t.dayOfWeek()||s.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(t){var o=t.dayOfWeek();return k[o!==e?o:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var o=t.dayOfWeek();return B[o!==e?o:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(t){var o=s.options("monthFromZero")?t.month():t.month()-1;return D[o!==e?o:s.MIN_MONTH]},parse:function(t){var o=s.monthNames().indexOf(t)+(s.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var o=s.options("monthFromZero")?t.month():t.month()-1;return S[o!==e?o:s.MIN_MONTH]},parse:function(t){var o=s.monthNames(!0).indexOf(t)+(s.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(t){return n(t.hours()||s.MIN_HOURS,2)},parse:function(t){var o=Number(t);return{hours:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(t){return n(t.minutes()||s.MIN_MINUTES,2)},parse:function(t){var o=Number(t);return{minutes:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(t){return n(t.seconds()||s.MIN_SECONDS,2)},parse:function(t){var o=Number(t);return{seconds:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(t){return t.timestamp()},parse:function(t){return isNaN(Number(t))?{}:s(Number(t)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(t){return n(t.year()||s.MIN_YEAR,4)+"-"+n(t.month()||s.MIN_MONTH,2)+"-"+n(t.day()||s.MIN_DAY,2)},parse:function(t){var o=Number(t.slice(0,4)),d=Number(t.slice(5,7)),g=Number(t.slice(8,10));return{year:o,month:d,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return n(t.month()||s.MIN_MONTH,2)+"/"+n(t.day()||s.MIN_DAY,2)+"/"+n(t.year()||s.MIN_YEAR,4)},parse:function(t){var o=Number(t.slice(0,2)),d=Number(t.slice(3,5)),g=Number(t.slice(6,10));return{year:g,month:o,day:d}},minLength:10,maxLength:10,type:"string"}},X={useMilliseconds:!1,monthFromZero:!1},O;O=function(t,o,d){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t!==e&&this.set(t,o,d),this},O.fn=O.prototype,O.fn.dayCount=function(){var t=this.month(),o=s.MAX_DAY_IN_MONTHS[t-(s.options("monthFromZero")?0:1)];return this.leapYear()&&t===(s.options("monthFromZero")?1:2)&&(o+=1),o},O.fn.year=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_YEAR&&Number(t)<=s.MAX_YEAR?(this._d.setFullYear(Number(t)),this._i.year=!1):this._i.year=Number(t):(this._d.setFullYear(s.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},O.fn.month=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MONTH&&Number(t)<=s.MAX_MONTH?(this._d.setMonth(s.options("monthFromZero")?Number(t):Number(t)-1),this._i.month=!1):this._i.month=Number(t):(this._d.setMonth(s.options("monthFromZero")?s.MIN_MONTH:s.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?s.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},O.fn.day=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_DAY&&Number(t)<=this.dayCount()?(this._d.setDate(Number(t)),this._i.day=!1):this._i.day=Number(t):(this._d.setDate(s.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},O.fn.hours=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_HOURS&&Number(t)<=s.MAX_HOURS?(this._d.setHours(Number(t)),this._i.hours=!1):this._i.hours=Number(t):(this._d.setHours(s.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},O.fn.minutes=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MINUTES&&Number(t)<=s.MAX_MINUTES?(this._d.setMinutes(Number(t)),this._i.minutes=!1):this._i.minutes=Number(t):(this._d.setMinutes(s.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},O.fn.seconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_SECONDS&&Number(t)<=s.MAX_SECONDS?(this._d.setSeconds(Number(t)),this._i.seconds=!1):this._i.seconds=Number(t):(this._d.setSeconds(s.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},O.fn.milliseconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MILLISECONDS&&Number(t)<=s.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(t)),this._i.milliseconds=!1):this._i.milliseconds=Number(t):(this._d.setMilliseconds(s.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},O.fn.week=function(){var t=new Date(this.year(),0,1),o=s(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-t.getTime())/864e5+t.getDay()+1)/7)},O.fn.set=function(t,o,d){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t===e)return this._d=new Date,this;if(t instanceof Date)return this._d=t,this;if(typeof t=="number")return this._d=new Date(t*(s.options("useMilliseconds")?1:1e3)),this;if(typeof t=="object"&&(t instanceof Array?(this.day(s.MIN_DAY),this.year(t[0]),this.month(t[1]),this.day(t[2]),this.hours(t[3]),this.minutes(t[4]),this.seconds(t[5]),this.milliseconds(t[6])):(this.day(s.MIN_DAY),this.year(t.year),this.month(t.month),this.day(t.day),this.hours(t.hours),this.minutes(t.minutes),this.seconds(t.seconds),this.milliseconds(t.milliseconds))),typeof t=="string"){var g,w=[],E,b,V=[],P=0,F=0,U,j,H={},G;if(t===e)return E=a(this,d),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;for(o===e&&(o=s.detectFormat(t));P<o.length;){if(o.charAt(P)==="%"){if(b=o.charAt(P)+o.charAt(P+1),I[b]!==e){switch(U=0,j="",I[b].type){case"number":for(;U<I[b].maxLength&&F+U<t.length&&!isNaN(Number(t.charAt(F+U)));)j+=t.charAt(F+U),U+=1;break;case"word":for(;U<I[b].maxLength&&F+U<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(F+U));)j+=t.charAt(F+U),U+=1;break;case"string":for(;U<I[b].maxLength&&F+U<t.length;)j+=t.charAt(F+U),U+=1;break}if(U<I[b].minLength)return E=a(this,d),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;w.push(b),V.push(j),U-=1,F+=U,P+=1}}else if(t.charAt(F)!==o.charAt(P))return E=a(this,d),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;P+=1,F+=1}for(g in w)w.hasOwnProperty(g)&&I.hasOwnProperty(w[g])&&(G=I[w[g]].parse(V[g]),H={year:G.year!==e?G.year:H.year,month:G.month!==e?G.month:H.month,day:G.day!==e?G.day:H.day,hours:G.hours!==e?G.hours:H.hours,minutes:G.minutes!==e?G.minutes:H.minutes,seconds:G.seconds!==e?G.seconds:H.seconds});this.day(s.MIN_DAY),this.year(H.year),this.month(H.month),this.day(H.day),this.hours(H.hours),this.minutes(H.minutes),this.seconds(H.seconds),this.milliseconds(H.milliseconds)}return this},O.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},O.fn.timestamp=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(s.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):s.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},O.fn.utc=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(s.options("useMilliseconds")?1:1e3)),this):s.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},O.fn.dayOfWeek=function(t){if(t==="long")return B[this._d.getDay()];if(t==="short")return k[this._d.getDay()];if(t===e)return this._d.getDay();if(t===0||t==="Sunday")return this.calc({day:-this.dayOfWeek()});if(t===1||t==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(t===2||t==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(t===3||t==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(t===4||t==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(t===5||t==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(t===6||t==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},O.fn.timezone=function(t){switch(t){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},O.fn.get=function(t){switch(t){case"Date":return new Date(this.year(),this.month()-(s.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds());case"DateUTC":return new Date(Date.UTC(this.year(),this.month()-(s.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()));case"Array":return[this.year(),this.month(),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()];default:return{year:this.year(),month:this.month(),week:this.week(),day:this.day(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds(),utc:this.utc(),dayOfWeek:this.dayOfWeek(),dayOfWeekShort:this.dayOfWeek("short"),dayOfWeekLong:this.dayOfWeek("long"),timestamp:this.timestamp()}}},O.fn.format=function(t){for(var o=0,d="",g;o<t.length;)t.charAt(o)==="%"?(g=t.charAt(o)+t.charAt(o+1),I[g]!==e?(d+=I[g].format(this),o+=1):d+="%"):d+=t.charAt(o),o+=1;return d},O.fn.valid=function(){return this._i.year===!1&&this._i.month===!1&&this._i.day===!1&&this._i.hours===!1&&this._i.minutes===!1&&this._i.seconds===!1&&this._i.milliseconds===!1},O.fn.errors=function(){return this._i},O.fn.between=function(t,o){var d=this.timestamp(),g=t.timestamp();switch(o){case"year":return Math.floor((g-d)/31556952);case"month":return Math.floor((g-d)/2629746);case"day":return Math.floor((g-d)/86400);case"hours":return Math.floor((g-d)/3600);case"minutes":return Math.floor((g-d)/60);case"seconds":return g-d;default:return e}},O.fn.calc=function(t){return t.year!==e&&this._d.setFullYear(this._d.getFullYear()+t.year),t.month!==e&&this._d.setMonth(this._d.getMonth()+t.month),t.day!==e&&this._d.setDate(this._d.getDate()+t.day),t.hours!==e&&this._d.setHours(this._d.getHours()+t.hours),t.minutes!==e&&this._d.setMinutes(this._d.getMinutes()+t.minutes),t.seconds!==e&&this._d.setSeconds(this._d.getSeconds()+t.seconds),t.milliseconds!==e&&this._d.setMilliseconds(this._d.getMilliseconds()+t.milliseconds),this},s=function(t,o,d){return new O(t,o,d)},s.MIN_YEAR=1e3,s.MAX_YEAR=3e3,s.MIN_MONTH=1,s.MAX_MONTH=12,s.MIN_DAY=1,s.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],s.MIN_DAY_OF_WEEK=0,s.MAX_DAY_OF_WEEK=6,s.MIN_HOURS=0,s.MAX_HOURS=23,s.MIN_MINUTES=0,s.MAX_MINUTES=59,s.MIN_SECONDS=0,s.MAX_SECONDS=59,s.MIN_MILLISECONDS=0,s.MAX_MILLISECONDS=999,s.VERSION="0.2.18",s.options=function(t,o){if(t===e)return X;if(X.hasOwnProperty(t)){if(o===e)return X[t];X[t]=o,t==="monthFromZero"&&(s.MIN_MONTH=o?0:1,s.MAX_MONTH=o?11:12)}return e},s.noConflict=function(){return i.tempus=h,s},s.generate=function(t){var o,d,g,w,E,b,V,P;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof O?o=t.dateFrom.utc():o=s(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof O?d=t.dateTo.utc():d=s(t.dateTo,t.formatTo!==e?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?E={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?E={year:t.period==="year"?1:0,month:t.period==="month"?1:0,day:t.period==="day"?1:0,hours:t.period==="hours"?1:0,minutes:t.period==="minutes"?1:0,seconds:t.period==="seconds"?1:0}:typeof t.period=="object"&&(E={year:t.period.year!==e?t.period.year:0,month:t.period.month!==e?t.period.month:0,day:t.period.day!==e?t.period.day:0,hours:t.period.hours!==e?t.period.hours:0,minutes:t.period.minutes!==e?t.period.minutes:0,seconds:t.period.seconds!==e?t.period.seconds:0}),t.groupBy===e?b=t.asObject===!0?{}:[]:(b=[],b.push([]),V=s(o).get()[t.groupBy]),P=function(j,H,G){return t.asObject===!0?t.format!==e?j[s(H).format(t.format)]={}:j[s(H).format("%F %H:%M:%S")]={}:t.format!==e?j.push(G?null:s(H).format(t.format)):j.push(G?null:s(H)),j},t.groupBy!==e&&t.fillNulls){var F={year:E.year?-E.year:e,month:E.month?-E.month:e,day:E.day?-E.day:e,hours:E.hours?-E.hours:e,minutes:E.minutes?-E.minutes:e,seconds:E.seconds?-E.seconds:e,milliseconds:E.milliseconds?-E.milliseconds:e};for(g=s(o).calc(F).utc();s(g).get()[t.groupBy]===V;)P(b[b.length-1],g,!0),g=s(g).calc(F).utc();if(t.groupBy==="week"){var U=s(o).dayOfWeek();for(g=s(o).dayOfWeek(0).utc();b[0].length<U&&g<o;)P(b[b.length-1],g,!0),g=s(g).calc(E).utc()}}for(;o<=d;)t.groupBy===e?P(b,o):s(o).get()[t.groupBy]===V?P(b[b.length-1],o):(b.push([]),P(b[b.length-1],o),V=s(o).get()[t.groupBy]),o=s(o).calc(E).utc();if(t.groupBy!==e&&t.fillNulls)for(w=s(d).calc(E).utc();s(w).get()[t.groupBy]===V;)P(b[b.length-1],w,!0),w=s(w).calc(E).utc();return b},s.monthNames=function(t){switch(t){case"long":return S;default:return D}},s.dayNames=function(t){switch(t){case"long":return B;default:return k}},s.lang=function(t){if(t!==e)A=t,u[A]===e&&(A="en"),S=N(),D=y(),B=p(),k=R();else return A;return e},s.availableLangs=function(){return Object.keys(u)},s.registerFormat=function(t,o,d,g,w,E){I[t]={format:o,parse:d,minLength:g,maxLength:w,type:E}},s.unregisterFormat=function(t){delete I[t]},s.detectFormat=function(t){var o,d,g;return o=c(t,0),o!==""&&(g=10),d=t.charAt(g),(d==="T"||d===" ")&&(o+=d,g+=1),o+=l(t,g),o},f={TempusDate:O},s.classes=function(t,o){if(o===e)return f[t];f[t]=o},s.loadTranslations=function(t){typeof t=="object"?u=t:typeof t=="string"&&J(t,function(o){u=o},function(o){})},A=(m.language||m.systemLanguage||m.userLanguage||"en").substr(0,2).toLowerCase(),u[A]===e&&(A="en"),S=N(),D=y(),B=p(),k=R(),x.exports&&(r=x.exports=s),r.tempus=s}).call(L)})(et,et.exports);var Lt=et.exports;const it=C(Lt);class z{constructor(r){this.callBatch=r,this.result={},this.errors={},this.limit=50,this.canContinue=!0,this.progressCall="",this.limitCall="",this.progressData="",this.progressTimer="",this.progressDelay=100,this.oldPercent="no",this.chunkRate=1,this.totalProgress=0,this.skipList=new Set,this.filterChunkSize=50}getData(r){return(r==null?void 0:r.items)??(r==null?void 0:r.tasks)??(r==null?void 0:r.types)??(r==null?void 0:r.type)??(r==null?void 0:r.fields)??(r==null?void 0:r.workgroups)??r}splitLargeFilters(r,e){const{method:i,params:n}=e;if(!n)return[{key:r,request:e}];const a=n.filter||n.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:r,request:e}];for(const[l,c]of Object.entries(a))if(Array.isArray(c)&&c.length>this.filterChunkSize){const h=[];for(let s=0;s<c.length;s+=this.filterChunkSize){const f=c.slice(s,s+this.filterChunkSize),m=s===0?r:`${r}__chunk_${Math.floor(s/this.filterChunkSize)}`,A={...n};n.filter?(A.filter={...a},A.filter[l]=f):n.FILTER&&(A.FILTER={...a},A.FILTER[l]=f),h.push({key:m,request:{method:i,params:A},originalKey:r,filterKey:l,chunkIndex:Math.floor(s/this.filterChunkSize)})}return h}return[{key:r,request:e}]}mergeSplitResults(r,e){const i=[],n=Object.keys(r).filter(a=>a.startsWith(e)).sort((a,l)=>{const c=a.match(/__chunk_(\d+)$/),h=l.match(/__chunk_(\d+)$/);return c?h?parseInt(c[1])-parseInt(h[1]):1:-1});for(const a of n){const l=r[a];Array.isArray(l)?i.push(...l):l&&i.push(l)}return i}get progressPercent(){let r=0;if(!this.progressData)return{percent:Math.round(r),allCount:0,allTotal:0};let e=0,i=0;return Object.values(this.progressData).forEach(n=>{const{total:a,count:l}=n;e+=a??0,i+=l??0}),e?r=i/e*100*this.chunkRate+this.totalProgress:i===0&&e===0?r=100*this.chunkRate+this.totalProgress:r=100,{percent:Math.round(r),allCount:i,allTotal:e}}setProgressData({key:r,value:e,type:i}){const n=this.getData(e.data()),a=Array.isArray(n)?n.length:0;let l=e.total()||a;i==="count"&&(l=a);let c=1;n&&(c=a),this.progressCall&&(this.progressData||(this.progressData={}),this.progressData[r]&&this.progressData[r].count&&(c+=this.progressData[r].count),this.progressData[r]?this.progressData[r].count=c:this.progressData[r]={total:l,count:c},this.progressTimer||(this.progressTimer=setInterval(()=>{const{percent:h,allCount:s,allTotal:f}=this.progressPercent;(this.oldPercent==="no"||this.oldPercent<this.progressPercent.percent)&&(this.progressCall({data:this.progressData,percent:h,allCount:s,allTotal:f}),this.oldPercent=this.progressPercent.percent),h>=100&&this.clearProgressData()},this.progressDelay)))}delay(){return new Promise(r=>setTimeout(r,500))}callBatchWithTimeout(r,e){return new Promise((i,n)=>{let a=!1;const l=6e4;let c=!1,h=!1,s=!1,f=null,m=null;const A=async(y,p)=>{if(!a){a=!0,f&&clearTimeout(f),m&&clearTimeout(m);try{await Promise.resolve(e(y)),i()}catch(R){console.error(`Error in callBatch callback (attempt ${p}):`,R),n(R)}}},u=async()=>{if(!a){a=!0,f&&clearTimeout(f),m&&clearTimeout(m),console.warn(`Batch request timeout after ${l}ms on both attempts. This may indicate a CORS or network error.`);const y={};Object.keys(r).forEach(p=>{y[p]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 30 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(e(y)),i()}catch(p){console.error("Error in timeout callback:",p),i()}}},N=y=>{try{this.callBatch(r,async p=>{y===1&&!c&&!a?(c=!0,await A(p,1)):y===2&&!s&&!a&&(s=!0,await A(p,2))})}catch(p){a||console.error(`Error calling callBatch (attempt ${y}):`,p)}};N(1),f=setTimeout(async()=>{!c&&!a&&!h&&(console.warn(`First batch request attempt timeout after ${l}ms. Starting second attempt...`),h=!0,N(2),m=setTimeout(async()=>{!c&&!s&&!a&&await u()},l))},l)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.limitCall="",this.oldPercent="no"}async batch(r,e,i){this.progressTimer&&this.clearProgressData(),e&&(this.progressCall=e),i&&(this.limitCall=i),this.canContinue=!0,this.result={},this.errors={};const n={},a={},l={};for(const[f,m]of Object.entries(r)){const A=this.arrayChunk(m);if(!A)continue;const u=this.splitLargeFilters(f,A);if(u.length===1)a[f]=A;else{l[f]=[];for(const N of u)a[N.key]=N.request,l[f].push(N.key)}}this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let c={},h=0;const s=Object.keys(a).length;for(const[f,m]of Object.entries(a)){if(!this.canContinue)break;c[f]=m,(Object.keys(c).length>=50||h+1===s)&&(await this.batchChunk(c),Object.entries(this.result).forEach(([A,u])=>{n[A]=u}),this.totalProgress=Math.round(h/s*100),c={}),h++}for(const[f,m]of Object.entries(l))if(m&&m.length>0){const A=this.mergeSplitResults(n,f);for(const u of m)delete n[u];n[f]=A}return Object.entries(this.errors).length&&(n.errorsList=this.errors),e&&e({percent:100}),Promise.resolve(n)}async batchTotalCount(r,e,i){this.progressTimer&&this.clearProgressData(),e&&(this.progressCall=e),i&&(this.limitCall=i),this.canContinue=!0,this.result={},this.errors={};const n={},a={},l={};for(const[s,f]of Object.entries(r)){const m=this.arrayChunk(f);if(!m)continue;const A=this.splitLargeFilters(s,m);if(A.length===1)a[s]=m;else{l[s]=[];for(const u of A)a[u.key]=u.request,l[s].push(u.key)}}const c=[],h=Object.entries(a);for(let s=0;s<h.length;s+=this.limit){const f=h.slice(s,s+this.limit),m={};for(const[A,u]of f){if(!this.canContinue)break;m[A]=u}Object.keys(m).length>0&&c.push(m)}this.chunkRate=(1/c.length).toFixed(5);for(const[s,f]of Object.entries(c)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(s)/c.length*100),await this.callBatchWithTimeout(f,async m=>{var A,u,N,y,p,R,S;for(const[D,B]of Object.entries(m)){if(!this.canContinue)return;if(B.error()){const O=(u=(A=B.error())==null?void 0:A.ex)==null?void 0:u.error,t=(y=(N=B.error())==null?void 0:N.ex)==null?void 0:y.error_description;this.errors[D]=O&&O.trim()||t&&t.trim()||((p=B.error())==null?void 0:p.toString())||"Неизвестная ошибка",n[D]=0;const o=((S=(R=B.error())==null?void 0:R.ex)==null?void 0:S.error)??"";let d="";const g=f[D];switch(Array.isArray(g)?[d]=g:g!=null&&g.method&&(d=g.method),o){case"OPERATION_TIME_LIMIT":d&&this.skipList.add(d),this.limitCall&&this.limitCall(D);break;case"ACCESS_DENIED":d&&this.skipList.add(d);break;case"TIMEOUT":d&&this.skipList.add(d),this.limitCall&&this.limitCall(D);break}continue}const k=this.getData(B.data()),J=Array.isArray(k)?k.length:0,X=typeof B.total=="function"&&B.total()!==void 0?B.total():J;n[D]=X,this.setProgressData({key:D,value:B,type:"count"})}})}for(const[s,f]of Object.entries(l))if(f&&f.length>0){let m=0;for(const A of f)n[A]!==void 0&&(m+=n[A]||0),delete n[A];n[s]=m}return Object.entries(this.errors).length&&(n.errorsList=this.errors,this.errorLogger()),e&&e({percent:100}),Promise.resolve(n)}arrayChunk(r){let e="",i={};if(Array.isArray(r)?[e]=r:(e=r.method,i=r.params),this.skipList.has(e))return!1;if((e.includes("list")||e==="user.get")&&e!=="task.item.list"){if(!i)i={order:{ID:"ASC",id:"ASC"}};else{e==="tasks.task.list"?(i.order||(i.order={}),i.order.ID="asc"):e==="user.get"?(i.sort||(i.sort="ID"),i.order||(i.order="ASC")):i.order={ID:"ASC",id:"ASC"},Array.isArray(i.select)&&!i.select.includes("ID")&&i.select.push("ID");const n=e==="user.get"?i.FILTER:i.filter;typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.entries(n).forEach(([a,l])=>{(i.start===void 0||i.start!==-1)&&["id","ID"].includes(a)&&(typeof l=="string"||Array.isArray(l)&&l.length<=50)&&(i.start=-1)})}e==="crm.type.list"&&i.order&&delete i.order.ID}if(e==="task.item.list")if(!i)i=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(i[0])&&(i[0]={});const[n,a,l,c]=i;n.ID="ASC",c[0]!==""&&c.includes("ID")||c.push("ID")}return{method:e,params:i}}async batchChunk(r,e){return new Promise(i=>{const n=[];let a;this.callBatchWithTimeout(r,async l=>{var c,h,s,f,m,A,u;for(const[N,y]of Object.entries(l)){if(!this.canContinue)return;if(y.error()){const k=(h=(c=y.error())==null?void 0:c.ex)==null?void 0:h.error,J=(f=(s=y.error())==null?void 0:s.ex)==null?void 0:f.error_description;switch(this.errors[N]=k&&k.trim()||J&&J.trim()||((m=y.error())==null?void 0:m.toString())||"Неизвестная ошибка",a=!0,((u=(A=y.error())==null?void 0:A.ex)==null?void 0:u.error)??""){case"OPERATION_TIME_LIMIT":this.skipList.add(r[N].method),this.limitCall&&this.limitCall(N);break;case"ACCESS_DENIED":this.skipList.add(r[N].method);break;case"TIMEOUT":let X=r[N],O="";Array.isArray(X)?[O]=X:X!=null&&X.method&&(O=X.method),O&&this.skipList.add(O),this.limitCall&&this.limitCall(N);break}}const p=this.getData(y.data()),R=Array.isArray(p)?p.length:0,S=typeof y.total=="function"&&y.total()!==void 0,D=S?y.total():R;e==="count"?this.result[N]?this.result[N]+=R:this.result[N]=D:this.result[N]=p,this.setProgressData({key:N,value:y,type:e});const B=e==="count"?!S&&R===this.limit:D>this.limit&&D>R;if(!this.canContinue||B){let k=r[N];if(Array.isArray(k)){const[J,I={}]=k;k=[J,I]}else{const{method:J,params:I={}}=k;k=[J,I]}n.push([N,k,D])}}a>0&&this.errorLogger(),n.length?await this.batchPayload(n,e).then(()=>i(this.result)):i(this.result)})})}async batchPayload(r,e){const i=new Map,n=(h,s,f,m)=>{let A="ID";this.result[h][this.result[h].length-1].ID||(A="id");let u=`${A}`;if(JSON.stringify(m[1]).toLocaleLowerCase().includes('"id":"desc"')?u="<"+u:u=">"+u,s===1||f.length===0)return{field:u,id:this.result[h][this.result[h].length-1][A]};let y="";const[p,R]=m;return(p==="tasks.task.list"||p==="task.item.list")&&(y="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(p)&&(y="[items]"),p==="crm.type.list"&&(y="[types]"),p==="socialnetwork.api.workgroup.list"&&(y="[workgroups]"),{field:u,id:`$result[${[h,s-1].join("__")}]${y}[49][${A}]`}},a=(h,s)=>{const[f,m]=h;let A=JSON.parse(JSON.stringify(m)),u;if(f==="task.item.list"){A=[...A];const[N,y,p,R]=A;return y[s.field]=s.id,[f,A]}return["user.get"].includes(f)||A.FILTER?(A.FILTER||(A.FILTER={}),u=A.FILTER):(A.filter||(A.filter={}),u=A.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(f)?u[">ID"]=s.id:u[s.field]=s.id,[f,{...A,start:-1}]},l=h=>{Object.entries(h).forEach(([s,f])=>{var u,N,y,p,R,S,D;const[m]=s.split("__"),A=this.getData(f.data());if(Array.isArray(A)&&(e==="count"?this.result[m]+=A.length:this.result[m].push(...A)),f.error()){const B=(N=(u=f.error())==null?void 0:u.ex)==null?void 0:N.error,k=(p=(y=f.error())==null?void 0:y.ex)==null?void 0:p.error_description;this.errors[m]=B&&B.trim()||k&&k.trim()||((R=f.error())==null?void 0:R.toString())||"Неизвестная ошибка";const J=((D=(S=f.error())==null?void 0:S.ex)==null?void 0:D.error)??"",I=i.get(m);switch(J){case"OPERATION_TIME_LIMIT":I&&(this.skipList.add(I),this.limitCall&&this.limitCall(m));break;case"QUERY_LIMIT_EXCEEDED":this.canContinue=!1;break;case"ACCESS_DENIED":I&&this.skipList.add(I);break;case"TIMEOUT":I&&(this.skipList.add(I),this.limitCall&&this.limitCall(m));break}}this.setProgressData({key:m,value:f,type:e})})};let c=[];for await(const[h,s,f]of r){if(!this.canContinue)return;const[m]=s;if(i.set(h,m),this.skipList.has(m))continue;let A=1;for(;f>A*50&&!this.skipList.has(m);){const u=[h,A].join("__"),N=n(h,A,c,s);c.push([u,a(s,N)]),c.length%50===0&&(await this.callBatchWithTimeout(Object.fromEntries(c),y=>{l(y)}),c=[],await this.delay()),A++}}c.length&&(await this.callBatchWithTimeout(Object.fromEntries(c),h=>{l(h)}),await this.delay())}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([r,e])=>{e&&console.log(`[${r}]`,e.toString())}),console.groupEnd()}}class ft{constructor(){Y(this,q,{})}get hash(){return this.createHash(8)}createHash(r){let e="abcdefghijklmnopqrstuvwxyz0123456789",i="";r=r||6;for(let n=0;n<r;n++)i+=e.charAt(Math.floor(Math.random()*e.length));return i}actionFilter({keyTimer:r,duration:e=10,action:i}){T(this,q)[r]&&(clearTimeout(T(this,q)[r]),T(this,q)[r]=null),i&&(T(this,q)[r]=setTimeout(()=>{i()},e))}async noSleep(){let r=document.createElement("video");r.classList.add("no-sleep"),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.addEventListener("loadeddata",()=>{r.style.position="fixed",r.style.left="-9999px",document.querySelector("body").append(r),r.play().catch(e=>{console.warn("noSleep: autoplay prevented",e)})}),r.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{r.play().catch(e=>{console.warn("noSleep: replay prevented",e)})}})}),r.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(r,e){let i=new Blob([JSON.stringify(r)],{type:"application/json"}),n=URL.createObjectURL(i),a=document.createElement("a");a.style.display="none",a.href=n,a.download=`${e}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(n)},200)}}q=new WeakMap;const mt=new ft;class yt{constructor(){Y(this,at);Y(this,nt);Y(this,At);Y(this,ct);Y(this,ht);Y(this,Q,"logger");Y(this,Z,!1);Y(this,$,new Map);Y(this,rt,{});Y(this,W,null);Y(this,tt,!1);Y(this,st,!1);M(this,"periodClear",3);K(this,at,Nt).call(this)}async init(){try{let r=new z(BX24.callBatch),{entityList:e}=await r.batch({entityList:{method:"entity.get"}});if(e&&Array.isArray(e))if(e.find(n=>n.ENTITY==T(this,Q)))v(this,Z,!0);else{let{entityAdd:n}=await r.batch({entityAdd:{method:"entity.add",params:{ENTITY:T(this,Q),NAME:T(this,Q),ACCESS:{AU:"X"}}}});n&&v(this,Z,!0)}return K(this,ct,_t).call(this).catch(i=>{console.error("Ошибка при проверке периода очистки:",i)}),T(this,Z)}catch(r){return console.error("Ошибка при инициализации логера:",r),!1}}start({type:r,data:e}){if(!T(this,Z))return K(this,nt,gt).call(this,"entity"),null;if(!r||!e)return console.error("Невалидные данные для логирования:",{type:r,data:e}),null;const i=mt.hash,n={type:r,data:e,userInfo:T(this,rt),errorList:{},status:"",answer:null,date:new Date().getTime()};return T(this,$).set(i,n),v(this,st,!0),i}async stop({key:r,errorList:e,status:i,answer:n}){var l;if(!T(this,st))return;if(!T(this,Z)){K(this,nt,gt).call(this,"entity");return}let a=T(this,$).get(r);if(!a){console.error(`Не найдены данные логирования для ключа: ${r}`);return}e&&(a.errorList=e),i&&(a.status=i),n&&(a.answer=n),await K(this,At,Ot).call(this),(l=a==null?void 0:a.data)!=null&&l.updateList&&v(this,tt,!0),v(this,st,!1)}async getEntityList(r){var e;try{if((e=T(this,W))!=null&&e.length&&!T(this,tt))return T(this,W);let i=new z(BX24.callBatch),{entityList:n}=await i.batch({entityList:{method:"entity.item.get",params:{ENTITY:T(this,Q),SORT:{ID:"DESC"}}}},r);return!n||!Array.isArray(n)?(console.warn("Получен невалидный список записей"),[]):(n=n.map(a=>{try{const{ID:l,DATE_CREATE:c,DETAIL_TEXT:h}=a;return{...JSON.parse(h),id:l,dateCreate:c}}catch(l){return console.error(`Ошибка парсинга записи ${a.ID}:`,l),null}}).filter(a=>a!==null),v(this,tt,!1),v(this,W,n),n)}catch(i){return console.error("Ошибка при получении списка записей:",i),[]}}async downAllEntityJson(){try{if(T(this,W)||await this.getEntityList(),!T(this,W)||T(this,W).length===0)return console.warn("Нет данных для выгрузки"),!1;let r=it().format("%Y-%m-%d");return mt.downloadFileJson(T(this,W),`sdklogger-entity-data__${r}`),!0}catch(r){return console.error("Ошибка при выгрузке данных в JSON:",r),!1}}}Q=new WeakMap,Z=new WeakMap,$=new WeakMap,rt=new WeakMap,W=new WeakMap,tt=new WeakMap,st=new WeakMap,at=new WeakSet,Nt=async function(){try{const r=new z(BX24.callBatch),e=BX24.isAdmin(),{curUser:i}=await r.batch({curUser:{method:"user.current"}});v(this,rt,{isAdmin:e,curUser:i})}catch(r){console.error("Ошибка при получении информации о пользователе:",r),v(this,rt,{isAdmin:!1,curUser:null})}},nt=new WeakSet,gt=function(r){r=="entity"&&mt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},At=new WeakSet,Ot=async function(){try{let r={},e=new z(BX24.callBatch);for(let[i,n]of T(this,$).entries())if(n.status){const a=JSON.stringify(n);r[i]={method:"entity.item.add",params:{ENTITY:T(this,Q),NAME:T(this,Q),DETAIL_TEXT:a}}}if(Object.keys(r).length){let i=await e.batch(r),{errors:n}=e;for(let[a,l]of Object.entries({...i,...n}))T(this,$).delete(a);return!0}return!1}catch(r){return console.error("Ошибка при добавлении записей в хранилище:",r),!1}},ct=new WeakSet,_t=async function(){try{let r=new z(BX24.callBatch),{serverTime:e}=await r.batch({serverTime:{method:"server.time"}});if(!e){console.error("Не удалось получить время сервера");return}if(T(this,W)||await this.getEntityList(),!T(this,W)||T(this,W).length===0)return;let i=T(this,W).filter(n=>{try{let{dateCreate:a}=n;return a?it(new Date(a)).between(it(new Date(e)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});i.length>0&&(console.log(`Найдено ${i.length} записей для очистки (старше ${this.periodClear} месяцев)`),await K(this,ht,Et).call(this,i))}catch(r){console.error("Ошибка при проверке периода очистки:",r)}},ht=new WeakSet,Et=async function(r){try{if(!r||r.length===0)return!1;let e=new z(BX24.callBatch),i=r.filter(a=>a&&a.id).map(a=>{let{id:l}=a;return{method:"entity.item.delete",params:{ENTITY:T(this,Q),ID:l}}});if(i.length===0)return!1;const n=await e.batch(i);return console.log(`Успешно удалено ${i.length} записей`),v(this,tt,!0),n}catch(e){return console.error("Ошибка при очистке устаревших записей:",e),!1}};class bt{constructor(r){Y(this,lt);Y(this,ut);Y(this,ot);M(this,"domain","");M(this,"isAdmin",!1);M(this,"appInfo",null);M(this,"appConst",null);M(this,"userInfo",null);M(this,"placeData",null);M(this,"placeInfo",null);M(this,"logger",!1);this.appConst=r}init(){return new Promise((r,e)=>{let n=setInterval(()=>{window.BX24&&BX24.init(async()=>{console.info("init BX24"),clearInterval(n),clearTimeout(a),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info(),this.logger?(this.logger=new yt,await this.logger.init()):this.logger={start:()=>{},stop:()=>{},getEntityList:()=>{}};const[l,c]=await Promise.all([K(this,lt,Tt).call(this),K(this,ut,Rt).call(this)]);this.appInfo=l,this.userInfo=c;let h=new ft;try{h.noSleep()}catch(s){console.warn("Failed to initialize noSleep:",s)}r(!0)})},100);const a=setTimeout(()=>{clearInterval(n);const l=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(l),e(l)},3e4)})}userOption(r,e){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.userOption.set(r,e):BX24.userOption.get(r)}appOption(r,e){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.appOption.set(r,e):BX24.appOption.get(r)}async call({method:r,params:e,updateList:i}){let n;if(i&&(n=this.logger.start({type:"call",data:{method:r,params:e,updateList:i}})),e||(e={}),typeof BX24>"u"||!BX24.callMethod){const a=new Error("BX24 is not initialized");throw console.error(a),a}return new Promise((a,l)=>{BX24.callMethod(r,e,async c=>{let h={};if(c!=null&&c.answer)for(let[s,f]of Object.entries(c.answer))s!=="result"&&f&&(h[s]=f);if(c.error()){let s=c.error();if(console.error(s),n)try{await this.logger.stop({answer:h,key:n,status:"fail",errorList:{0:s.toString()}})}catch(f){console.error("Logger error:",f)}a(!1)}else{let s=c.data();if(s!=null&&s.items&&(s=s.items),n)try{await this.logger.stop({answer:h,key:n,status:"success"})}catch(f){console.error("Logger error:",f)}a(s)}})})}async batch(r,e,{errorCall:i,limitCommandSerial:n,updateList:a,limitCall:l}={}){if(typeof BX24>"u"||!BX24.callBatch){const s=new Error("BX24 is not initialized");return console.error(s),!1}let c=new z(BX24.callBatch),h;a&&(h=this.logger.start({type:"batch",data:{commandList:r,updateList:a}})),n&&console.warn("limitCommandSerial is deprecated and not used in current Batch implementation");try{let s=await c.batch(r,e,l);const f=K(this,ot,pt).call(this,c,s,r,a);if(Object.keys(f).length){if(i&&i(f),h)try{await this.logger.stop({key:h,status:"fail",errorList:f})}catch(m){console.error("Logger error:",m)}}else if(h)try{await this.logger.stop({key:h,status:"success"})}catch(m){console.error("Logger error:",m)}return s}catch(s){if(h)try{await this.logger.stop({key:h,status:"fail-runtime",errorList:{0:s==null?void 0:s.toString()}})}catch(f){console.error("Logger error:",f)}return console.error(s),!1}}async batchTotalCount(r,e,{errorCall:i,updateList:n,limitCall:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const h=new Error("BX24 is not initialized");return console.error(h),!1}let l=new z(BX24.callBatch),c;n&&(c=this.logger.start({type:"batch-total-count",data:{commandList:r}}));try{let h=await l.batchTotalCount(r,e,a);const s=K(this,ot,pt).call(this,l,h,r,n);if(Object.keys(s).length){if(i&&i(s),c)try{await this.logger.stop({key:c,status:"fail",errorList:s})}catch(f){console.error("Logger error:",f)}}else if(c)try{await this.logger.stop({key:c,status:"success"})}catch(f){console.error("Logger error:",f)}return h}catch(h){if(c)try{await this.logger.stop({key:c,status:"fail-runtime",errorList:{0:h==null?void 0:h.toString()}})}catch(s){console.error("Logger error:",s)}return console.error(h),!1}}async getPlacement(){return await this.call({method:"placement.get"}).then(r=>(this.placeData||(this.placeData=r),r))}async placementBind(r,e=!0){var f;if(!this.isAdmin)return;e&&await this.placementCheck();let i=[];if(Array.isArray(r)?i=r.map(m=>typeof m=="string"?{placement:m}:m):typeof r=="string"?i=[{placement:r}]:i=[r],i=i.filter(m=>m.placement!=="PAGE_BACKGROUND_WORKER"&&m.placement!=="PAGE_BACKGROUND_WORKER_ALL"),this.placeData=await this.getPlacement(),!this.placeData)return;const{appName:n,pathApp:a}=this.appConst;let l=n;this.domain==="szdl.bitrix24.ru"&&((f=this.appInfo)!=null&&f.ID)&&(l=`${n}: #${this.appInfo.ID}`);const c=l.replace(" CRM",""),h={},s=[];for(let m=0;m<i.length;m++){const u=i[m].placement,N=a;if(this.placeData.find(S=>S.placement===u&&S.handler===N))continue;const p=this.placeData.find(S=>S.placement===u&&S.handler!==N);p&&s.push({placement:u,handler:p.handler});const R={PLACEMENT:u,HANDLER:N,LANG_ALL:{ru:{TITLE:u==="USER_PROFILE_TOOLBAR"?c:l}},OPTIONS:{errorHandlerUrl:N}};h[`bind_${m}`]={method:"placement.bind",params:R}}s.length>0&&await this.placementUnBind(s),Object.keys(h).length>0&&await this.batch(h),Object.keys(h).length>0&&(this.placeData=await this.getPlacement(),Object.values(h).forEach(m=>{console.log("Приложение успешно встроено в",m.params.PLACEMENT)}))}async placementUnBind(r){let e=[];Array.isArray(r)?e=r.map(n=>typeof n=="string"?{placement:n}:n):typeof r=="string"?e=[{placement:r}]:e=[r],e=e.filter(n=>n.placement!=="PAGE_BACKGROUND_WORKER"&&n.placement!=="PAGE_BACKGROUND_WORKER_ALL");const i={};for(let n=0;n<e.length;n++){const a=e[n],l=a.placement,c=a.handler,h={PLACEMENT:l};c&&(h.HANDLER=c),i[`unbind_${n}`]={method:"placement.unbind",params:h}}Object.keys(i).length>0&&(await this.batch(i),e.forEach(n=>{console.log("Встройка отвязана",n.placement)}))}async placementCheck(){if(this.placeData=await this.getPlacement(),!this.placeData)return;const{pathApp:r}=this.appConst,e=[],i=[];for(const n of this.placeData){if(n.placement==="PAGE_BACKGROUND_WORKER"||!n.handler||n.handler.includes(r))continue;const{placement:a,handler:l,userId:c}=n;e.push({placement:a,handler:l}),i.push({placement:a,userId:c})}e.length>0&&await this.placementUnBind(e),i.length>0&&await this.placementBind(i,!1)}getBotList(){return this.call({method:"imbot.bot.list",params:{}}).then(r=>{let e=Object.values(r);return console.log("chat-bot list:",e),e})}regBot({code:r,type:e,name:i}){const{appName:n,pathApp:a,chatBotLogo:l}=this.appConst,c=this.appInfo.ID;return this.call({method:"imbot.register",params:{CODE:r??this.appInfo.CODE,TYPE:e??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${i??n} - бот #${c}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:it().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:l??""}}}).then(h=>(console.log("Чат-бот добавлен",h),h))}unRegBot(r){return this.call({method:"imbot.unregister",params:{BOT_ID:r}}).then(e=>(console.log("чат-бот удален",e),e))}getLoggerList(r){return this.logger.getEntityList(r)}}lt=new WeakSet,Tt=function(){return this.call({method:"app.info"})},ut=new WeakSet,Rt=function(){return this.call({method:"user.current"})},ot=new WeakSet,pt=function(r,e,i,n){let a={...r.errors};if(Object.values(r.errors).some(c=>{if(typeof c!="string")return!1;const h=c.toUpperCase();return h==="TIMEOUT"||h==="OPERATION_TIME_LIMIT"||h.includes("TIMEOUT")||h.includes("OPERATION_TIME_LIMIT")})&&n){const c=e?Object.keys(e).filter(m=>m!=="errorsList"):[],h=new Set(Object.keys(r.errors||{})),s=new Set;if(e){for(const m of c)if(!h.has(m)){const A=e[m];A!=null&&s.add(m)}}const f=Object.values(r.errors).find(m=>{if(typeof m!="string")return!1;const A=m.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const m of Object.keys(i))!s.has(m)&&!r.errors[m]&&(a[m]=f||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a};class St{constructor(r){M(this,"entityName","tabs");M(this,"maxTabs",20);M(this,"tabList",[]);M(this,"id",0);M(this,"hasStarted",!1);M(this,"heartbeat");M(this,"runHeartbeat");M(this,"random",this.getRandomNum());M(this,"activeMaxPause",5*60*1e3+this.random);M(this,"quickCleanupThreshold",2*60*1e3);M(this,"pollInterval",(60+this.random)*1e3);M(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);M(this,"continueCondition");M(this,"defaultContinueBackground",()=>!0);var l,c,h;if(!r){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:e,bx:i,users:n,continueBackground:a}=r;this.bx=i,this.appInit=e,this.users=n,this.appPath=((l=i==null?void 0:i.appConst)==null?void 0:l.pathApp)??"",this.appName=((c=i==null?void 0:i.appConst)==null?void 0:c.appName)??"",this.appCodeName=((h=i==null?void 0:i.appConst)==null?void 0:h.appCodeName)??"",this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("BackgroundWorker: appInit не передан");return}if(!this.bx){console.error("BackgroundWorker: bx не передан");return}if(this.isAppPage()){console.log("BackgroundWorker: Страница приложения, фоновый воркер не запускается");return}await this.checkPlacementType()&&await this.continueBackground()&&(await this.checkEntity(),await this.refreshTabs(!0),await this.ensureTabRegistered(),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(e=>{console.error("BackgroundWorker: backgroundTick failed",e)})},this.pollInterval),await this.backgroundTick())}async backgroundTick(){if(!await this.continueBackground()){this.stopTimers(),console.log("BackgroundWorker: Остановка backgroundTick - условие не выполнено");return}await this.refreshTabs(!0),await this.ensureTabRegistered();const e=this.selectLeaderId(),i=e&&+this.id==+e;await this.updateTabState(i),i&&!this.hasStarted&&(this.hasStarted=!0,await this.runAsLeader())}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var r;if(typeof BX24>"u"||!((r=BX24.placement)!=null&&r.info))return!1;try{const e=BX24.placement.info(),i=e==null?void 0:e.placement,n=(e==null?void 0:e.options)||{},a=(n==null?void 0:n.URI)||"",l=i==="PAGE_BACKGROUND_WORKER"||(n==null?void 0:n.ID)==="PAGE_BACKGROUND_WORKER",c=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!l||c}catch{return!1}}async checkEntity(){var i;const r=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((i=r==null?void 0:r.find)==null?void 0:i.call(r,n=>n.ENTITY===this.entityName))||await this.safeCall(()=>this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}}))}async getTabs(){const r=await this.safeCall(()=>{var e;return this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:(e=this.bx.userInfo)==null?void 0:e.ID},SORT:{DATE_CREATE:"DESC"}}})});return!Array.isArray(r)||!r.length?[]:r.map(e=>{if(!e)return{id:void 0,data:void 0};try{const i=JSON.parse(e.DETAIL_TEXT);return{id:+e.ID||0,data:i}}catch(i){return console.log("BackgroundWorker: parse tab error",i),{id:+e.ID||0,data:void 0}}})}async ensureTabRegistered(){if(this.id)return+this.id||0;if(this.tabList.length>=this.maxTabs&&await this.refreshTabs(!0,this.quickCleanupThreshold),this.tabList.length>=this.maxTabs)return console.log("BackgroundWorker: Достигнут лимит вкладок даже после быстрой очистки, не регистрируемся"),0;const r={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId},e=await this.safeCall(()=>{var i;return this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(i=this.bx.userInfo)==null?void 0:i.ID,DETAIL_TEXT:JSON.stringify(r)}})})||0;return this.id=+e||0,this.id}async updateTabState(r){if(!this.id)return;const e={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:r,sessionId:this.sessionId};await this.safeCall(()=>{var i;return this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(i=this.bx.userInfo)==null?void 0:i.ID,DETAIL_TEXT:JSON.stringify(e)}})})}async deleteTabs(r=[]){if(!r.length)return;const e=r.map(i=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:i.id}}));await this.safeCall(()=>this.bx.batch(e))}getRandomNum(){const r=Math.round(Number(Math.random().toFixed(2))*30);return Math.round(Math.random())?r:-r}async checkPlacementType(){var r;try{const e=await this.safeCall(()=>this.bx.getPlacement());if(!e||!Array.isArray(e))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((r=this.bx.userInfo)==null?void 0:r.ID)??0),n=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),a=!n;if(!i)return!0;let l=!1;for(const c of e){if(c.placement!=="PAGE_BACKGROUND_WORKER"||!(c.userId||c.handler&&c.handler.includes("USER_ID=")))continue;const s=c.userId||(c.handler?this.extractUserIdFromHandler(c.handler):null);if(s&&+s===i){l=!0;break}}return n?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):a&&l?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(e){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",e),!0}}isIndividualPlacement(r){return!r||typeof r!="string"?!1:r.includes("USER_ID=")}extractUserIdFromHandler(r){if(!r||typeof r!="string")return null;const e=r.match(/USER_ID=(\d+)/);return e?+e[1]:null}async continueBackground(){try{const e=!!await Promise.resolve(this.continueCondition(this));return console.log(e?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),e}catch(r){return console.error("BackgroundWorker: Ошибка в continueCondition",r),!1}}async refreshTabs(r=!1,e=this.activeMaxPause){const i=[],n=[],a=Date.now(),l=await this.getTabs();for(const c of l){if(!(c!=null&&c.data)){i.push(c);continue}if(a-new Date(c.data.lastActive||0).getTime()>e){i.push(c);continue}n.push(c)}return r&&i.length&&await this.deleteTabs(i),this.tabList=n,n}selectLeaderId(){var e;return this.tabList.length&&+((e=[...this.tabList].sort((i,n)=>{var c,h,s,f;const a=new Date(((c=i.data)==null?void 0:c.createdAt)||((h=i.data)==null?void 0:h.lastActive)||0).getTime(),l=new Date(((s=n.data)==null?void 0:s.createdAt)||((f=n.data)==null?void 0:f.lastActive)||0).getTime();return a===l?(+i.id||0)-(+n.id||0):a-l})[0])==null?void 0:e.id)||0}async runAsLeader(){this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(r=>console.error("BackgroundWorker: heartbeat update failed",r))},Math.max(20*1e3,Math.floor(this.pollInterval/2)));try{await this.appInit()}catch(r){console.error("BackgroundWorker: appInit failed",r)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)}async setBackgroundWorkerAll(){var N,y;if(!((N=this.bx)!=null&&N.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(y=this.users)!=null&&y.length||await this.getEntityData();const r=await this.safeCall(()=>this.bx.getPlacement()),e=new Map;let i=null;(r||[]).forEach(p=>{if(p.placement!=="PAGE_BACKGROUND_WORKER")return;if(p.userId||p.handler&&p.handler.includes("USER_ID=")){const S=p.userId||(p.handler?this.extractUserIdFromHandler(p.handler):null);S&&e.set(+S,p)}else i=p});const n=await this.resolveAdmins(),a=await this.getEligibleUsersForBackgroundWorker(n);a.sort((p,R)=>{const S=p.LAST_LOGIN?new Date(p.LAST_LOGIN):new Date(0);return(R.LAST_LOGIN?new Date(R.LAST_LOGIN):new Date(0))-S});const l=10,h=a.slice(0,l).filter(p=>!e.has(+p.ID)),s=[];for(const[p]of e){const R=+p||0;a.find(D=>+D.ID===R)||s.push(R)}const f=[];for(const p of s)this.appPath&&f.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${p}/`}});const m=i&&h.length>0;m&&this.appPath&&f.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:i.handler||`${this.appPath}`}});for(const p of h)this.appPath&&f.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${p.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}?USER_ID=${p.ID}/`},USER_ID:p.ID}});(!i||m)&&this.appPath&&f.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}`}}});const A=f.filter(p=>p.method==="placement.unbind"),u=f.filter(p=>p.method==="placement.bind");A.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(A.map((p,R)=>[`unbind_${R}`,p])))),u.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(u.map((p,R)=>[`bind_${R}`,p])))),f.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var r,e;try{const i=+(((r=this.bx.userInfo)==null?void 0:r.ID)??0),n=!!((e=this.bx)!=null&&e.isAdmin),a=await this.getAdminsList()||[];if(!n){if(i&&a.includes(+i)){const h=a.filter(s=>+s!=+i);return await this.saveAdminsList(h),h}return a}const l=new Set([...a||[]]);i&&l.add(+i);const c=[...l].filter(Boolean);return await this.saveAdminsList(c),c}catch(i){return console.error("BackgroundWorker: resolveAdmins error",i),[]}}async getEligibleUsersForBackgroundWorker(r=[]){const e=(this.users??[]).filter(n=>n.ACTIVE==="Y"||n.ACTIVE===!0),i=r.map(n=>+n||0).filter(Boolean);return e.filter(n=>i.includes(+n.ID||0))}async saveAdminsList(r=[]){try{BX24.appOption.set("adminsList",JSON.stringify(r))}catch(e){console.error("BackgroundWorker: saveAdminsList error",e)}}async getAdminsList(){try{const r=BX24.appOption.get("adminsList"),e=r?JSON.parse(r):[];return Array.isArray(e)?e.map(i=>+i||0).filter(Boolean):[]}catch(r){return console.error("BackgroundWorker: getAdminsList error",r),[]}}async getEntityData(){const r={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:e}=await this.safeCall(()=>this.bx.batch(r).then(i=>i?(Array.isArray(i.users)||(i.users=[]),i):{users:[]}));this.users=e}async ensureAdminPlacements(){var r,e;(r=this.bx)!=null&&r.isAdmin&&((e=this.users)!=null&&e.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(r=500,e){return new Promise(i=>{setTimeout(()=>{e&&e(),i(!0)},r)})}async safeCall(r){try{return await r()}catch(e){console.error("BackgroundWorker: safeCall error",e);return}}}_.BackgroundWorker=St,_.Batch=z,_.BxBoot=bt,_.BxHelper=ft,_.BxLogger=yt,_.tempus=it,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"})});
|