szdl-utils-kit 0.3.20 → 0.3.22
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 +180 -179
- package/dist/index.umd.cjs +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -239,7 +239,7 @@ var Xt = { exports: {} };
|
|
|
239
239
|
h[A].NOVEMBER_SHORT,
|
|
240
240
|
h[A].DECEMBER_SHORT
|
|
241
241
|
];
|
|
242
|
-
},
|
|
242
|
+
}, E = function() {
|
|
243
243
|
return [
|
|
244
244
|
h[A].SUNDAY_LONG,
|
|
245
245
|
h[A].MONDAY_LONG,
|
|
@@ -249,7 +249,7 @@ var Xt = { exports: {} };
|
|
|
249
249
|
h[A].FRIDAY_LONG,
|
|
250
250
|
h[A].SATURDAY_LONG
|
|
251
251
|
];
|
|
252
|
-
},
|
|
252
|
+
}, S = function() {
|
|
253
253
|
return [
|
|
254
254
|
h[A].SUNDAY_SHORT,
|
|
255
255
|
h[A].MONDAY_SHORT,
|
|
@@ -259,13 +259,13 @@ var Xt = { exports: {} };
|
|
|
259
259
|
h[A].FRIDAY_SHORT,
|
|
260
260
|
h[A].SATURDAY_SHORT
|
|
261
261
|
];
|
|
262
|
-
}, p,
|
|
262
|
+
}, p, R, C, N, I = function(s, o, m) {
|
|
263
263
|
var g;
|
|
264
264
|
r.XMLHttpRequest ? g = new XMLHttpRequest() : g = new ActiveXObject("Microsoft.XMLHTTP"), g.onreadystatechange = function() {
|
|
265
265
|
g.readyState === 4 && (g.status === 200 ? o && (r.JSON === e ? alert(`Please, include json2 into your project if you want use old browsers!
|
|
266
266
|
https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.parse(g.responseText))) : m && m(g));
|
|
267
267
|
}, g.open("GET", s, !1), g.send();
|
|
268
|
-
},
|
|
268
|
+
}, b = {
|
|
269
269
|
"%d": {
|
|
270
270
|
format: function(s) {
|
|
271
271
|
return i(s.day() || n.MIN_DAY, 2);
|
|
@@ -340,7 +340,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
340
340
|
"%b": {
|
|
341
341
|
format: function(s) {
|
|
342
342
|
var o = n.options("monthFromZero") ? s.month() : s.month() - 1;
|
|
343
|
-
return
|
|
343
|
+
return R[o !== e ? o : n.MIN_MONTH];
|
|
344
344
|
},
|
|
345
345
|
parse: function(s) {
|
|
346
346
|
var o = n.monthNames().indexOf(s) + (n.options("monthFromZero") ? 0 : 1);
|
|
@@ -442,11 +442,11 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
442
442
|
maxLength: 10,
|
|
443
443
|
type: "string"
|
|
444
444
|
}
|
|
445
|
-
},
|
|
445
|
+
}, w = {
|
|
446
446
|
useMilliseconds: !1,
|
|
447
447
|
monthFromZero: !1
|
|
448
|
-
},
|
|
449
|
-
|
|
448
|
+
}, k;
|
|
449
|
+
k = function(s, o, m) {
|
|
450
450
|
return this._d = /* @__PURE__ */ new Date(), this._i = {
|
|
451
451
|
year: !1,
|
|
452
452
|
month: !1,
|
|
@@ -456,55 +456,55 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
456
456
|
seconds: !1,
|
|
457
457
|
milliseconds: !1
|
|
458
458
|
}, s !== e && this.set(s, o, m), this;
|
|
459
|
-
},
|
|
459
|
+
}, k.fn = k.prototype, k.fn.dayCount = function() {
|
|
460
460
|
var s = this.month(), o = n.MAX_DAY_IN_MONTHS[s - (n.options("monthFromZero") ? 0 : 1)];
|
|
461
461
|
return this.leapYear() && s === (n.options("monthFromZero") ? 1 : 2) && (o += 1), o;
|
|
462
|
-
},
|
|
462
|
+
}, k.fn.year = function(s) {
|
|
463
463
|
if (arguments.length !== 0)
|
|
464
464
|
(typeof s == "number" || typeof s == "string") && !isNaN(Number(s)) ? Number(s) >= n.MIN_YEAR && Number(s) <= n.MAX_YEAR ? (this._d.setFullYear(Number(s)), this._i.year = !1) : this._i.year = Number(s) : (this._d.setFullYear(n.MIN_YEAR), this._i.year = !1);
|
|
465
465
|
else
|
|
466
466
|
return this._i.year === !1 ? this._d.getFullYear() : this._i.year;
|
|
467
467
|
return this;
|
|
468
|
-
},
|
|
468
|
+
}, k.fn.month = function(s) {
|
|
469
469
|
if (arguments.length !== 0)
|
|
470
470
|
(typeof s == "number" || typeof s == "string") && !isNaN(Number(s)) ? Number(s) >= n.MIN_MONTH && Number(s) <= n.MAX_MONTH ? (this._d.setMonth(n.options("monthFromZero") ? Number(s) : Number(s) - 1), this._i.month = !1) : this._i.month = Number(s) : (this._d.setMonth(n.options("monthFromZero") ? n.MIN_MONTH : n.MIN_MONTH - 1), this._i.month = !1);
|
|
471
471
|
else
|
|
472
472
|
return this._i.month === !1 ? n.options("monthFromZero") ? this._d.getMonth() : this._d.getMonth() + 1 : this._i.month;
|
|
473
473
|
return this;
|
|
474
|
-
},
|
|
474
|
+
}, k.fn.day = function(s) {
|
|
475
475
|
if (arguments.length !== 0)
|
|
476
476
|
(typeof s == "number" || typeof s == "string") && !isNaN(Number(s)) ? Number(s) >= n.MIN_DAY && Number(s) <= this.dayCount() ? (this._d.setDate(Number(s)), this._i.day = !1) : this._i.day = Number(s) : (this._d.setDate(n.MIN_DAY), this._i.day = !1);
|
|
477
477
|
else
|
|
478
478
|
return this._i.day === !1 ? this._d.getDate() : this._i.day;
|
|
479
479
|
return this;
|
|
480
|
-
},
|
|
480
|
+
}, k.fn.hours = function(s) {
|
|
481
481
|
if (arguments.length !== 0)
|
|
482
482
|
(typeof s == "number" || typeof s == "string") && !isNaN(Number(s)) ? Number(s) >= n.MIN_HOURS && Number(s) <= n.MAX_HOURS ? (this._d.setHours(Number(s)), this._i.hours = !1) : this._i.hours = Number(s) : (this._d.setHours(n.MIN_HOURS), this._i.hours = !1);
|
|
483
483
|
else
|
|
484
484
|
return this._i.hours === !1 ? this._d.getHours() : this._i.hours;
|
|
485
485
|
return this;
|
|
486
|
-
},
|
|
486
|
+
}, k.fn.minutes = function(s) {
|
|
487
487
|
if (arguments.length !== 0)
|
|
488
488
|
(typeof s == "number" || typeof s == "string") && !isNaN(Number(s)) ? Number(s) >= n.MIN_MINUTES && Number(s) <= n.MAX_MINUTES ? (this._d.setMinutes(Number(s)), this._i.minutes = !1) : this._i.minutes = Number(s) : (this._d.setMinutes(n.MIN_MINUTES), this._i.minutes = !1);
|
|
489
489
|
else
|
|
490
490
|
return this._i.minutes === !1 ? this._d.getMinutes() : this._i.minutes;
|
|
491
491
|
return this;
|
|
492
|
-
},
|
|
492
|
+
}, k.fn.seconds = function(s) {
|
|
493
493
|
if (arguments.length !== 0)
|
|
494
494
|
(typeof s == "number" || typeof s == "string") && !isNaN(Number(s)) ? Number(s) >= n.MIN_SECONDS && Number(s) <= n.MAX_SECONDS ? (this._d.setSeconds(Number(s)), this._i.seconds = !1) : this._i.seconds = Number(s) : (this._d.setSeconds(n.MIN_SECONDS), this._i.seconds = !1);
|
|
495
495
|
else
|
|
496
496
|
return this._i.seconds === !1 ? this._d.getSeconds() : this._i.seconds;
|
|
497
497
|
return this;
|
|
498
|
-
},
|
|
498
|
+
}, k.fn.milliseconds = function(s) {
|
|
499
499
|
if (arguments.length !== 0)
|
|
500
500
|
(typeof s == "number" || typeof s == "string") && !isNaN(Number(s)) ? Number(s) >= n.MIN_MILLISECONDS && Number(s) <= n.MAX_MILLISECONDS ? (this._d.setMilliseconds(Number(s)), this._i.milliseconds = !1) : this._i.milliseconds = Number(s) : (this._d.setMilliseconds(n.MIN_MILLISECONDS), this._i.milliseconds = !1);
|
|
501
501
|
else
|
|
502
502
|
return this._i.milliseconds === !1 ? this._d.getMilliseconds() : this._i.milliseconds;
|
|
503
503
|
return this;
|
|
504
|
-
},
|
|
504
|
+
}, k.fn.week = function() {
|
|
505
505
|
var s = new Date(this.year(), 0, 1), o = n(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc() * 1e3;
|
|
506
506
|
return Math.ceil(((o - s.getTime()) / 864e5 + s.getDay() + 1) / 7);
|
|
507
|
-
},
|
|
507
|
+
}, k.fn.set = function(s, o, m) {
|
|
508
508
|
if (this._i = {
|
|
509
509
|
year: !1,
|
|
510
510
|
month: !1,
|
|
@@ -520,7 +520,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
520
520
|
if (typeof s == "number")
|
|
521
521
|
return this._d = new Date(s * (n.options("useMilliseconds") ? 1 : 1e3)), this;
|
|
522
522
|
if (typeof s == "object" && (s instanceof Array ? (this.day(n.MIN_DAY), this.year(s[0]), this.month(s[1]), this.day(s[2]), this.hours(s[3]), this.minutes(s[4]), this.seconds(s[5]), this.milliseconds(s[6])) : (this.day(n.MIN_DAY), this.year(s.year), this.month(s.month), this.day(s.day), this.hours(s.hours), this.minutes(s.minutes), this.seconds(s.seconds), this.milliseconds(s.milliseconds))), typeof s == "string") {
|
|
523
|
-
var g, B = [], D, U, z = [], W = 0, F = 0, G, J,
|
|
523
|
+
var g, B = [], D, U, z = [], W = 0, F = 0, G, J, P = {}, Y;
|
|
524
524
|
if (s === e)
|
|
525
525
|
return D = a(this, m), D === e && (this._i = {
|
|
526
526
|
year: -1,
|
|
@@ -533,22 +533,22 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
533
533
|
}), D;
|
|
534
534
|
for (o === e && (o = n.detectFormat(s)); W < o.length; ) {
|
|
535
535
|
if (o.charAt(W) === "%") {
|
|
536
|
-
if (U = o.charAt(W) + o.charAt(W + 1),
|
|
537
|
-
switch (G = 0, J = "",
|
|
536
|
+
if (U = o.charAt(W) + o.charAt(W + 1), b[U] !== e) {
|
|
537
|
+
switch (G = 0, J = "", b[U].type) {
|
|
538
538
|
case "number":
|
|
539
|
-
for (; G <
|
|
539
|
+
for (; G < b[U].maxLength && F + G < s.length && !isNaN(Number(s.charAt(F + G))); )
|
|
540
540
|
J += s.charAt(F + G), G += 1;
|
|
541
541
|
break;
|
|
542
542
|
case "word":
|
|
543
|
-
for (; G <
|
|
543
|
+
for (; G < b[U].maxLength && F + G < s.length && /^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(s.charAt(F + G)); )
|
|
544
544
|
J += s.charAt(F + G), G += 1;
|
|
545
545
|
break;
|
|
546
546
|
case "string":
|
|
547
|
-
for (; G <
|
|
547
|
+
for (; G < b[U].maxLength && F + G < s.length; )
|
|
548
548
|
J += s.charAt(F + G), G += 1;
|
|
549
549
|
break;
|
|
550
550
|
}
|
|
551
|
-
if (G <
|
|
551
|
+
if (G < b[U].minLength)
|
|
552
552
|
return D = a(this, m), D === e && (this._i = {
|
|
553
553
|
year: -1,
|
|
554
554
|
month: -1,
|
|
@@ -573,25 +573,25 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
573
573
|
W += 1, F += 1;
|
|
574
574
|
}
|
|
575
575
|
for (g in B)
|
|
576
|
-
B.hasOwnProperty(g) &&
|
|
577
|
-
year:
|
|
578
|
-
month:
|
|
579
|
-
day:
|
|
580
|
-
hours:
|
|
581
|
-
minutes:
|
|
582
|
-
seconds:
|
|
576
|
+
B.hasOwnProperty(g) && b.hasOwnProperty(B[g]) && (Y = b[B[g]].parse(z[g]), P = {
|
|
577
|
+
year: Y.year !== e ? Y.year : P.year,
|
|
578
|
+
month: Y.month !== e ? Y.month : P.month,
|
|
579
|
+
day: Y.day !== e ? Y.day : P.day,
|
|
580
|
+
hours: Y.hours !== e ? Y.hours : P.hours,
|
|
581
|
+
minutes: Y.minutes !== e ? Y.minutes : P.minutes,
|
|
582
|
+
seconds: Y.seconds !== e ? Y.seconds : P.seconds
|
|
583
583
|
});
|
|
584
|
-
this.day(n.MIN_DAY), this.year(
|
|
584
|
+
this.day(n.MIN_DAY), this.year(P.year), this.month(P.month), this.day(P.day), this.hours(P.hours), this.minutes(P.minutes), this.seconds(P.seconds), this.milliseconds(P.milliseconds);
|
|
585
585
|
}
|
|
586
586
|
return this;
|
|
587
|
-
},
|
|
587
|
+
}, k.fn.leapYear = function() {
|
|
588
588
|
var s = this.year();
|
|
589
589
|
return s % 4 === 0 ? s % 100 === 0 ? s % 400 === 0 : !0 : !1;
|
|
590
|
-
},
|
|
590
|
+
}, k.fn.timestamp = function(s) {
|
|
591
591
|
return arguments.length !== 0 ? (this._d = new Date(Number(s) * (n.options("useMilliseconds") ? 1 : 1e3) + this._d.getTimezoneOffset() * 6e4), this) : n.options("useMilliseconds") ? this._d.getTime() - this._d.getTimezoneOffset() * 6e4 : Math.floor(this._d.getTime() / 1e3) - this._d.getTimezoneOffset() * 60;
|
|
592
|
-
},
|
|
592
|
+
}, k.fn.utc = function(s) {
|
|
593
593
|
return arguments.length !== 0 ? (this._d = new Date(Number(s) * (n.options("useMilliseconds") ? 1 : 1e3)), this) : n.options("useMilliseconds") ? this._d.getTime() : Math.floor(this._d.getTime() / 1e3);
|
|
594
|
-
},
|
|
594
|
+
}, k.fn.dayOfWeek = function(s) {
|
|
595
595
|
if (s === "long")
|
|
596
596
|
return C[this._d.getDay()];
|
|
597
597
|
if (s === "short")
|
|
@@ -612,7 +612,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
612
612
|
return this.calc({ day: (this.dayOfWeek() === 0 ? -2 : 5) - this.dayOfWeek() });
|
|
613
613
|
if (s === 6 || s === "Saturday")
|
|
614
614
|
return this.calc({ day: (this.dayOfWeek() === 0 ? -1 : 6) - this.dayOfWeek() });
|
|
615
|
-
},
|
|
615
|
+
}, k.fn.timezone = function(s) {
|
|
616
616
|
switch (s) {
|
|
617
617
|
case "hours":
|
|
618
618
|
return Math.floor(this._d.getTimezoneOffset() / 60);
|
|
@@ -621,7 +621,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
621
621
|
default:
|
|
622
622
|
return this._d.getTimezoneOffset() * 60;
|
|
623
623
|
}
|
|
624
|
-
},
|
|
624
|
+
}, k.fn.get = function(s) {
|
|
625
625
|
switch (s) {
|
|
626
626
|
case "Date":
|
|
627
627
|
return new Date(
|
|
@@ -670,15 +670,15 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
670
670
|
timestamp: this.timestamp()
|
|
671
671
|
};
|
|
672
672
|
}
|
|
673
|
-
},
|
|
673
|
+
}, k.fn.format = function(s) {
|
|
674
674
|
for (var o = 0, m = "", g; o < s.length; )
|
|
675
|
-
s.charAt(o) === "%" ? (g = s.charAt(o) + s.charAt(o + 1),
|
|
675
|
+
s.charAt(o) === "%" ? (g = s.charAt(o) + s.charAt(o + 1), b[g] !== e ? (m += b[g].format(this), o += 1) : m += "%") : m += s.charAt(o), o += 1;
|
|
676
676
|
return m;
|
|
677
|
-
},
|
|
677
|
+
}, k.fn.valid = function() {
|
|
678
678
|
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;
|
|
679
|
-
},
|
|
679
|
+
}, k.fn.errors = function() {
|
|
680
680
|
return this._i;
|
|
681
|
-
},
|
|
681
|
+
}, k.fn.between = function(s, o) {
|
|
682
682
|
var m = this.timestamp(), g = s.timestamp();
|
|
683
683
|
switch (o) {
|
|
684
684
|
case "year":
|
|
@@ -696,24 +696,24 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
696
696
|
default:
|
|
697
697
|
return e;
|
|
698
698
|
}
|
|
699
|
-
},
|
|
699
|
+
}, k.fn.calc = function(s) {
|
|
700
700
|
return s.year !== e && this._d.setFullYear(this._d.getFullYear() + s.year), s.month !== e && this._d.setMonth(this._d.getMonth() + s.month), s.day !== e && this._d.setDate(this._d.getDate() + s.day), s.hours !== e && this._d.setHours(this._d.getHours() + s.hours), s.minutes !== e && this._d.setMinutes(this._d.getMinutes() + s.minutes), s.seconds !== e && this._d.setSeconds(this._d.getSeconds() + s.seconds), s.milliseconds !== e && this._d.setMilliseconds(this._d.getMilliseconds() + s.milliseconds), this;
|
|
701
701
|
}, n = function(s, o, m) {
|
|
702
|
-
return new
|
|
702
|
+
return new k(s, o, m);
|
|
703
703
|
}, n.MIN_YEAR = 1e3, n.MAX_YEAR = 3e3, n.MIN_MONTH = 1, n.MAX_MONTH = 12, n.MIN_DAY = 1, n.MAX_DAY_IN_MONTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], n.MIN_DAY_OF_WEEK = 0, n.MAX_DAY_OF_WEEK = 6, n.MIN_HOURS = 0, n.MAX_HOURS = 23, n.MIN_MINUTES = 0, n.MAX_MINUTES = 59, n.MIN_SECONDS = 0, n.MAX_SECONDS = 59, n.MIN_MILLISECONDS = 0, n.MAX_MILLISECONDS = 999, n.VERSION = "0.2.18", n.options = function(s, o) {
|
|
704
704
|
if (s === e)
|
|
705
|
-
return
|
|
706
|
-
if (
|
|
705
|
+
return w;
|
|
706
|
+
if (w.hasOwnProperty(s)) {
|
|
707
707
|
if (o === e)
|
|
708
|
-
return
|
|
709
|
-
|
|
708
|
+
return w[s];
|
|
709
|
+
w[s] = o, s === "monthFromZero" && (n.MIN_MONTH = o ? 0 : 1, n.MAX_MONTH = o ? 11 : 12);
|
|
710
710
|
}
|
|
711
711
|
return e;
|
|
712
712
|
}, n.noConflict = function() {
|
|
713
713
|
return r.tempus = u, n;
|
|
714
714
|
}, n.generate = function(s) {
|
|
715
715
|
var o, m, g, B, D, U, z, W;
|
|
716
|
-
if (typeof s.dateFrom != "number" && (s.dateFrom instanceof
|
|
716
|
+
if (typeof s.dateFrom != "number" && (s.dateFrom instanceof k ? o = s.dateFrom.utc() : o = n(s.dateFrom, s.formatFrom).utc()), typeof s.dateTo != "number" && (s.dateTo instanceof k ? m = s.dateTo.utc() : m = n(s.dateTo, s.formatTo !== e ? s.formatTo : s.formatFrom).utc()), typeof s.period == "number" ? D = {
|
|
717
717
|
year: 0,
|
|
718
718
|
month: 0,
|
|
719
719
|
day: 0,
|
|
@@ -734,8 +734,8 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
734
734
|
hours: s.period.hours !== e ? s.period.hours : 0,
|
|
735
735
|
minutes: s.period.minutes !== e ? s.period.minutes : 0,
|
|
736
736
|
seconds: s.period.seconds !== e ? s.period.seconds : 0
|
|
737
|
-
}), s.groupBy === e ? U = s.asObject === !0 ? {} : [] : (U = [], U.push([]), z = n(o).get()[s.groupBy]), W = function(J,
|
|
738
|
-
return s.asObject === !0 ? s.format !== e ? J[n(
|
|
737
|
+
}), s.groupBy === e ? U = s.asObject === !0 ? {} : [] : (U = [], U.push([]), z = n(o).get()[s.groupBy]), W = function(J, P, Y) {
|
|
738
|
+
return s.asObject === !0 ? s.format !== e ? J[n(P).format(s.format)] = {} : J[n(P).format("%F %H:%M:%S")] = {} : s.format !== e ? J.push(Y ? null : n(P).format(s.format)) : J.push(Y ? null : n(P)), J;
|
|
739
739
|
}, s.groupBy !== e && s.fillNulls) {
|
|
740
740
|
var F = {
|
|
741
741
|
year: D.year ? -D.year : e,
|
|
@@ -765,7 +765,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
765
765
|
case "long":
|
|
766
766
|
return p;
|
|
767
767
|
default:
|
|
768
|
-
return
|
|
768
|
+
return R;
|
|
769
769
|
}
|
|
770
770
|
}, n.dayNames = function(s) {
|
|
771
771
|
switch (s) {
|
|
@@ -776,14 +776,14 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
776
776
|
}
|
|
777
777
|
}, n.lang = function(s) {
|
|
778
778
|
if (s !== e)
|
|
779
|
-
A = s, h[A] === e && (A = "en"), p = O(),
|
|
779
|
+
A = s, h[A] === e && (A = "en"), p = O(), R = T(), C = E(), N = S();
|
|
780
780
|
else
|
|
781
781
|
return A;
|
|
782
782
|
return e;
|
|
783
783
|
}, n.availableLangs = function() {
|
|
784
784
|
return Object.keys(h);
|
|
785
785
|
}, n.registerFormat = function(s, o, m, g, B, D) {
|
|
786
|
-
|
|
786
|
+
b[s] = {
|
|
787
787
|
format: o,
|
|
788
788
|
parse: m,
|
|
789
789
|
minLength: g,
|
|
@@ -791,12 +791,12 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
791
791
|
type: D
|
|
792
792
|
};
|
|
793
793
|
}, n.unregisterFormat = function(s) {
|
|
794
|
-
delete
|
|
794
|
+
delete b[s];
|
|
795
795
|
}, n.detectFormat = function(s) {
|
|
796
796
|
var o, m, g;
|
|
797
797
|
return o = l(s, 0), o !== "" && (g = 10), m = s.charAt(g), (m === "T" || m === " ") && (o += m, g += 1), o += c(s, g), o;
|
|
798
798
|
}, f = {
|
|
799
|
-
TempusDate:
|
|
799
|
+
TempusDate: k
|
|
800
800
|
}, n.classes = function(s, o) {
|
|
801
801
|
if (o === e)
|
|
802
802
|
return f[s];
|
|
@@ -806,7 +806,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
|
|
|
806
806
|
h = o;
|
|
807
807
|
}, function(o) {
|
|
808
808
|
});
|
|
809
|
-
}, A = (d.language || d.systemLanguage || d.userLanguage || "en").substr(0, 2).toLowerCase(), h[A] === e && (A = "en"), p = O(),
|
|
809
|
+
}, A = (d.language || d.systemLanguage || d.userLanguage || "en").substr(0, 2).toLowerCase(), h[A] === e && (A = "en"), p = O(), R = T(), C = E(), N = S(), y.exports && (t = y.exports = n), t.tempus = n;
|
|
810
810
|
}).call(pe);
|
|
811
811
|
})(Xt, Xt.exports);
|
|
812
812
|
var Oe = Xt.exports;
|
|
@@ -893,29 +893,30 @@ const j = class j {
|
|
|
893
893
|
return { percent: 0, allCount: 0, allTotal: 0 };
|
|
894
894
|
const t = this.totalBatchCommands || 0;
|
|
895
895
|
if (t > 0 && Array.isArray(this.batchCommandKeyOrder) && this.batchCommandKeyOrder.length && _(this, Tt, $t).call(this)) {
|
|
896
|
-
let
|
|
897
|
-
for (const
|
|
898
|
-
const
|
|
899
|
-
if (!
|
|
896
|
+
let u = 0;
|
|
897
|
+
for (const h of this.batchCommandKeyOrder) {
|
|
898
|
+
const O = this.progressData[h];
|
|
899
|
+
if (!O)
|
|
900
900
|
continue;
|
|
901
|
-
const
|
|
902
|
-
|
|
901
|
+
const T = Number(O.total) || 0, E = Number(O.count) || 0;
|
|
902
|
+
T === 0 && E === 0 ? u += 1 : T > 0 && (u += Math.min(1, E / T));
|
|
903
903
|
}
|
|
904
|
-
const
|
|
905
|
-
let
|
|
906
|
-
const
|
|
907
|
-
return { percent:
|
|
904
|
+
const n = u / t * 100;
|
|
905
|
+
let f = Math.max(0, Math.min(100, Math.floor(n)));
|
|
906
|
+
const d = t, A = Math.min(t, Math.floor(u));
|
|
907
|
+
return { percent: f, allCount: A, allTotal: d };
|
|
908
908
|
}
|
|
909
909
|
let e = 0, r = 0;
|
|
910
|
-
for (const
|
|
911
|
-
const { total:
|
|
912
|
-
e +=
|
|
910
|
+
for (const u of Object.values(this.progressData)) {
|
|
911
|
+
const { total: n, count: f } = u;
|
|
912
|
+
e += n ?? 0, r += f ?? 0;
|
|
913
913
|
}
|
|
914
914
|
const i = Number(this.chunkRate) || 0;
|
|
915
915
|
let a = 0;
|
|
916
|
-
e ? a = r / e * 100 * i + this.totalProgress : r === 0 && e === 0 ? a = 100 * i + this.totalProgress : a = 100, a = Math.max(0, Math.min(a, 100));
|
|
916
|
+
e ? a = r / e * 100 * i + this.totalProgress : r === 0 && e === 0 ? a = i < 1 ? this.totalProgress : 100 * i + this.totalProgress : a = 100, a = Math.max(0, Math.min(a, 100));
|
|
917
917
|
let c = Math.floor(a);
|
|
918
|
-
|
|
918
|
+
const l = Number(this.chunkRate) || 0;
|
|
919
|
+
return e > 0 && r >= e && l >= 1 && (c = 100), { percent: c, allCount: r, allTotal: e };
|
|
919
920
|
}
|
|
920
921
|
/**
|
|
921
922
|
* Обновление данных прогресса выполнения
|
|
@@ -933,13 +934,12 @@ const j = class j {
|
|
|
933
934
|
if (typeof e.total == "function") {
|
|
934
935
|
const T = e.total();
|
|
935
936
|
if (T != null && T !== "") {
|
|
936
|
-
const
|
|
937
|
-
Number.isFinite(
|
|
937
|
+
const E = Number(T);
|
|
938
|
+
Number.isFinite(E) && (c = E);
|
|
938
939
|
}
|
|
939
940
|
}
|
|
940
|
-
r === "count" && (c = a);
|
|
941
941
|
let l = 1;
|
|
942
|
-
i && (l = a), this.progressData || (this.progressData = {});
|
|
942
|
+
r === "count" ? (c || (c = a), l = c > 0 ? c : a > 0 ? a : 1) : i && (l = a), this.progressData || (this.progressData = {});
|
|
943
943
|
const u = ((h = this.progressData[t]) == null ? void 0 : h.total) ?? 0, n = ((O = this.progressData[t]) == null ? void 0 : O.count) ?? 0, f = l + n, d = Math.max(u, c ?? 0, f);
|
|
944
944
|
if (this.progressData[t] = {
|
|
945
945
|
total: d,
|
|
@@ -1222,20 +1222,20 @@ const j = class j {
|
|
|
1222
1222
|
for (const [u, n] of Object.entries(c)) {
|
|
1223
1223
|
if (!this.canContinue)
|
|
1224
1224
|
break;
|
|
1225
|
-
this.totalProgress = Math.round(Number(u) / c.length * 100);
|
|
1225
|
+
this.totalProgress = Math.round(Number(u) / c.length * 100), this.progressData = {}, this.lastProgressSnapshot = null;
|
|
1226
1226
|
const f = Number(u) === c.length - 1;
|
|
1227
1227
|
await _(this, tt, ht).call(this, n, async (d) => {
|
|
1228
|
-
var A, h, O, T,
|
|
1229
|
-
for (const [
|
|
1228
|
+
var A, h, O, T, E;
|
|
1229
|
+
for (const [S, p] of Object.entries(d)) {
|
|
1230
1230
|
if (!this.canContinue)
|
|
1231
1231
|
return;
|
|
1232
1232
|
if (p.error()) {
|
|
1233
|
-
const
|
|
1234
|
-
this.errors[
|
|
1233
|
+
const b = (h = (A = p.error()) == null ? void 0 : A.ex) == null ? void 0 : h.error, w = (T = (O = p.error()) == null ? void 0 : O.ex) == null ? void 0 : T.error_description;
|
|
1234
|
+
this.errors[S] = b && b.trim() || w && w.trim() || ((E = p.error()) == null ? void 0 : E.toString()) || "Неизвестная ошибка", r[S] = 0;
|
|
1235
1235
|
continue;
|
|
1236
1236
|
}
|
|
1237
|
-
const
|
|
1238
|
-
r[
|
|
1237
|
+
const R = this.getData(p.data()), C = Array.isArray(R) ? R.length : 0, I = typeof p.total == "function" && p.total() !== void 0 ? p.total() : C;
|
|
1238
|
+
r[S] = I, this.setProgressData({ key: S, value: p, type: "count" });
|
|
1239
1239
|
}
|
|
1240
1240
|
await _(this, $, lt).call(this, d, !f);
|
|
1241
1241
|
});
|
|
@@ -1335,19 +1335,19 @@ const j = class j {
|
|
|
1335
1335
|
const u = !!(i != null && i.disablePagination);
|
|
1336
1336
|
(async () => {
|
|
1337
1337
|
await _(this, tt, ht).call(this, t, async (f) => {
|
|
1338
|
-
var A, h, O, T,
|
|
1339
|
-
for (const [
|
|
1338
|
+
var A, h, O, T, E;
|
|
1339
|
+
for (const [S, p] of Object.entries(f)) {
|
|
1340
1340
|
if (!this.canContinue)
|
|
1341
1341
|
return;
|
|
1342
1342
|
if (p.error()) {
|
|
1343
1343
|
const g = (h = (A = p.error()) == null ? void 0 : A.ex) == null ? void 0 : h.error, B = (T = (O = p.error()) == null ? void 0 : O.ex) == null ? void 0 : T.error_description;
|
|
1344
|
-
this.errors[
|
|
1344
|
+
this.errors[S] = g && g.trim() || B && B.trim() || ((E = p.error()) == null ? void 0 : E.toString()) || "Неизвестная ошибка", l = !0;
|
|
1345
1345
|
}
|
|
1346
|
-
const
|
|
1347
|
-
e === "count" ? this.result[
|
|
1348
|
-
const
|
|
1346
|
+
const R = this.getData(p.data()), C = Array.isArray(R) ? R.length : 0, N = typeof p.total == "function" && p.total() !== void 0, I = N ? p.total() : C;
|
|
1347
|
+
e === "count" ? this.result[S] ? this.result[S] += C : this.result[S] = I : this.result[S] = R, this.setProgressData({ key: S, value: p, type: e });
|
|
1348
|
+
const b = t[S], w = Array.isArray(b) ? b[0] : b == null ? void 0 : b.method, k = typeof w == "string" && (w.includes(".list") || w === "user.get" || w === "entity.item.get"), s = e === "count" ? !N && C === this.limit : k ? C === this.limit : I > this.limit && I > C, o = e !== "count" && w === "entity.item.get" && C === this.limit && !s, m = s || o;
|
|
1349
1349
|
if (!u && (!this.canContinue || m)) {
|
|
1350
|
-
let g = t[
|
|
1350
|
+
let g = t[S];
|
|
1351
1351
|
if (Array.isArray(g)) {
|
|
1352
1352
|
const [B, D = {}] = g;
|
|
1353
1353
|
g = [B, D];
|
|
@@ -1356,7 +1356,7 @@ const j = class j {
|
|
|
1356
1356
|
g = [B, D];
|
|
1357
1357
|
}
|
|
1358
1358
|
c.push([
|
|
1359
|
-
|
|
1359
|
+
S,
|
|
1360
1360
|
g,
|
|
1361
1361
|
I,
|
|
1362
1362
|
{ entityItemGetScan: o }
|
|
@@ -1378,72 +1378,72 @@ const j = class j {
|
|
|
1378
1378
|
* @param {{oneBatch?: boolean}} [options] - Опции выполнения payload.
|
|
1379
1379
|
*/
|
|
1380
1380
|
async batchPayload(t, e, r = {}) {
|
|
1381
|
-
const i = !!(r != null && r.oneBatch), a = (O, T,
|
|
1381
|
+
const i = !!(r != null && r.oneBatch), a = (O, T, E, S) => {
|
|
1382
1382
|
let p = "ID";
|
|
1383
1383
|
this.result[O][this.result[O].length - 1].ID || (p = "id");
|
|
1384
|
-
let
|
|
1385
|
-
if (JSON.stringify(
|
|
1384
|
+
let R = `${p}`;
|
|
1385
|
+
if (JSON.stringify(S[1]).toLocaleLowerCase().includes('"id":"desc"') ? R = "<" + R : R = ">" + R, T === 1 || E.length === 0)
|
|
1386
1386
|
return {
|
|
1387
|
-
field:
|
|
1387
|
+
field: R,
|
|
1388
1388
|
id: this.result[O][this.result[O].length - 1][p]
|
|
1389
1389
|
};
|
|
1390
1390
|
let N = "";
|
|
1391
|
-
const [I,
|
|
1391
|
+
const [I, b] = S;
|
|
1392
1392
|
return (I === "tasks.task.list" || I === "task.item.list") && (N = "[tasks]"), ["crm.item.list", "crm.stagehistory.list"].includes(I) && (N = "[items]"), I === "crm.type.list" && (N = "[types]"), I === "socialnetwork.api.workgroup.list" && (N = "[workgroups]"), {
|
|
1393
|
-
field:
|
|
1393
|
+
field: R,
|
|
1394
1394
|
id: `$result[${[O, T - 1].join("__")}]${N}[49][${p}]`
|
|
1395
1395
|
};
|
|
1396
1396
|
}, c = (O, T) => {
|
|
1397
|
-
const [
|
|
1398
|
-
let p = JSON.parse(JSON.stringify(
|
|
1399
|
-
if (
|
|
1397
|
+
const [E, S] = O;
|
|
1398
|
+
let p = JSON.parse(JSON.stringify(S)), R;
|
|
1399
|
+
if (E === "task.item.list") {
|
|
1400
1400
|
p = [...p];
|
|
1401
|
-
const [C, N, I,
|
|
1402
|
-
return N[T.field] = T.id, [
|
|
1401
|
+
const [C, N, I, b] = p;
|
|
1402
|
+
return N[T.field] = T.id, [E, p];
|
|
1403
1403
|
}
|
|
1404
|
-
return ["user.get"].includes(
|
|
1404
|
+
return ["user.get"].includes(E) || p.FILTER ? (p.FILTER || (p.FILTER = {}), R = p.FILTER) : (p.filter || (p.filter = {}), R = p.filter), [
|
|
1405
1405
|
"socialnetwork.api.workgroup.list",
|
|
1406
1406
|
"tasks.task.list"
|
|
1407
|
-
].includes(
|
|
1407
|
+
].includes(E) ? R[">ID"] = T.id : R[T.field] = T.id, [E, { ...p, start: -1 }];
|
|
1408
1408
|
}, l = (O) => {
|
|
1409
|
-
Object.entries(O).forEach(([T,
|
|
1410
|
-
var
|
|
1411
|
-
const [
|
|
1412
|
-
if (Array.isArray(p) && (e === "count" ? this.result[
|
|
1413
|
-
const
|
|
1414
|
-
this.errors[
|
|
1409
|
+
Object.entries(O).forEach(([T, E]) => {
|
|
1410
|
+
var R, C, N, I, b;
|
|
1411
|
+
const [S] = T.split("__"), p = this.getData(E.data());
|
|
1412
|
+
if (Array.isArray(p) && (e === "count" ? this.result[S] += p.length : this.result[S].push(...p)), E.error()) {
|
|
1413
|
+
const w = (C = (R = E.error()) == null ? void 0 : R.ex) == null ? void 0 : C.error, k = (I = (N = E.error()) == null ? void 0 : N.ex) == null ? void 0 : I.error_description;
|
|
1414
|
+
this.errors[S] = w && w.trim() || k && k.trim() || ((b = E.error()) == null ? void 0 : b.toString()) || "Неизвестная ошибка";
|
|
1415
1415
|
}
|
|
1416
|
-
this.setProgressData({ key:
|
|
1416
|
+
this.setProgressData({ key: S, value: E, type: e });
|
|
1417
1417
|
});
|
|
1418
1418
|
}, u = (O, T) => {
|
|
1419
1419
|
if (!Array.isArray(O) || O.length === 0)
|
|
1420
1420
|
return null;
|
|
1421
|
-
const
|
|
1422
|
-
let
|
|
1423
|
-
|
|
1424
|
-
let p =
|
|
1425
|
-
return JSON.stringify(T[1]).toLocaleLowerCase().includes('"id":"desc"') ? p = "<" + p : p = ">" + p, { field: p, id:
|
|
1421
|
+
const E = O[O.length - 1];
|
|
1422
|
+
let S = "ID";
|
|
1423
|
+
E.ID || (S = "id");
|
|
1424
|
+
let p = S;
|
|
1425
|
+
return JSON.stringify(T[1]).toLocaleLowerCase().includes('"id":"desc"') ? p = "<" + p : p = ">" + p, { field: p, id: E[S] };
|
|
1426
1426
|
}, n = 1e4, f = async (O, T) => {
|
|
1427
|
-
var
|
|
1428
|
-
let
|
|
1429
|
-
for (let
|
|
1427
|
+
var S, p;
|
|
1428
|
+
let E = this.limit;
|
|
1429
|
+
for (let R = 1; this.canContinue && E === this.limit && R <= n; R++) {
|
|
1430
1430
|
const C = this.result[O], N = u(C, T);
|
|
1431
1431
|
if (!N)
|
|
1432
1432
|
break;
|
|
1433
|
-
const I = `${O}__eiscan_${
|
|
1434
|
-
let
|
|
1435
|
-
await _(this, tt, ht).call(this, { [I]:
|
|
1436
|
-
|
|
1433
|
+
const I = `${O}__eiscan_${R}`, b = c(T, N);
|
|
1434
|
+
let w = null;
|
|
1435
|
+
await _(this, tt, ht).call(this, { [I]: b }, async (m) => {
|
|
1436
|
+
w = m, l(m);
|
|
1437
1437
|
});
|
|
1438
|
-
const
|
|
1439
|
-
await _(this, $, lt).call(this,
|
|
1440
|
-
const s =
|
|
1441
|
-
if ((
|
|
1442
|
-
|
|
1438
|
+
const k = R < n;
|
|
1439
|
+
await _(this, $, lt).call(this, w, k), await this.delay();
|
|
1440
|
+
const s = w == null ? void 0 : w[I];
|
|
1441
|
+
if ((S = s == null ? void 0 : s.error) != null && S.call(s)) {
|
|
1442
|
+
E = 0;
|
|
1443
1443
|
break;
|
|
1444
1444
|
}
|
|
1445
1445
|
const o = this.getData((p = s == null ? void 0 : s.data) == null ? void 0 : p.call(s));
|
|
1446
|
-
|
|
1446
|
+
E = Array.isArray(o) ? o.length : 0;
|
|
1447
1447
|
}
|
|
1448
1448
|
};
|
|
1449
1449
|
let d = [], A = 0;
|
|
@@ -1453,21 +1453,21 @@ const j = class j {
|
|
|
1453
1453
|
for await (const O of t) {
|
|
1454
1454
|
if (!this.canContinue)
|
|
1455
1455
|
return;
|
|
1456
|
-
const [T,
|
|
1456
|
+
const [T, E, S, p = {}] = O;
|
|
1457
1457
|
if (p.entityItemGetScan) {
|
|
1458
1458
|
if (await h(!0))
|
|
1459
1459
|
return;
|
|
1460
1460
|
if (i)
|
|
1461
1461
|
continue;
|
|
1462
|
-
await f(T,
|
|
1462
|
+
await f(T, E);
|
|
1463
1463
|
continue;
|
|
1464
1464
|
}
|
|
1465
|
-
let
|
|
1466
|
-
for (;
|
|
1467
|
-
const C = [T,
|
|
1468
|
-
if (d.push([C, c(
|
|
1465
|
+
let R = 1;
|
|
1466
|
+
for (; S > R * this.limit; ) {
|
|
1467
|
+
const C = [T, R].join("__"), N = a(T, R, d, E);
|
|
1468
|
+
if (d.push([C, c(E, N)]), i && d.length === 49 && await h(!0) || d.length % 50 === 0 && await h(!0))
|
|
1469
1469
|
return;
|
|
1470
|
-
|
|
1470
|
+
R++;
|
|
1471
1471
|
}
|
|
1472
1472
|
}
|
|
1473
1473
|
await h(!1);
|
|
@@ -1665,7 +1665,7 @@ class re {
|
|
|
1665
1665
|
}
|
|
1666
1666
|
et = new WeakMap();
|
|
1667
1667
|
const xt = new re();
|
|
1668
|
-
var K, q, st, ot, ft, Z, X, rt, At, Dt, ie, mt, jt,
|
|
1668
|
+
var K, q, st, ot, ft, Z, X, rt, At, Dt, ie, mt, jt, kt, ne, wt, ae, Bt, oe;
|
|
1669
1669
|
class _e {
|
|
1670
1670
|
constructor() {
|
|
1671
1671
|
/** user.current — только при первом реальном использовании (сохранение лога, выгрузка). */
|
|
@@ -1674,8 +1674,8 @@ class _e {
|
|
|
1674
1674
|
* @param {'entity'} type - тип ошибки
|
|
1675
1675
|
*/
|
|
1676
1676
|
L(this, mt);
|
|
1677
|
-
L(this, wt);
|
|
1678
1677
|
L(this, kt);
|
|
1678
|
+
L(this, wt);
|
|
1679
1679
|
L(this, Bt);
|
|
1680
1680
|
L(this, K, "logger");
|
|
1681
1681
|
L(this, q, !1);
|
|
@@ -1770,7 +1770,7 @@ class _e {
|
|
|
1770
1770
|
console.error(`Не найдены данные логирования для ключа: ${t}`);
|
|
1771
1771
|
return;
|
|
1772
1772
|
}
|
|
1773
|
-
e && (a.errorList = e), r && (a.status = r), i && (a.answer = i), await _(this, Dt, ie).call(this), a.userInfo = M(this, ot), await _(this,
|
|
1773
|
+
e && (a.errorList = e), r && (a.status = r), i && (a.answer = i), await _(this, Dt, ie).call(this), a.userInfo = M(this, ot), await _(this, kt, ne).call(this), (c = a == null ? void 0 : a.data) != null && c.updateList && x(this, rt, !0), x(this, At, !1);
|
|
1774
1774
|
}
|
|
1775
1775
|
/**
|
|
1776
1776
|
* @param { ({percent}:{percent:number})=>{} } progressCall - коллбэк
|
|
@@ -1816,7 +1816,7 @@ class _e {
|
|
|
1816
1816
|
* Не вызывается из `init` — вызывайте явно (например, из настроек или планировщика).
|
|
1817
1817
|
*/
|
|
1818
1818
|
runStorageMaintenance() {
|
|
1819
|
-
return _(this,
|
|
1819
|
+
return _(this, wt, ae).call(this);
|
|
1820
1820
|
}
|
|
1821
1821
|
/** Выгрузка всех данных из хранилища в JSON-файл */
|
|
1822
1822
|
async downAllEntityJson() {
|
|
@@ -1858,7 +1858,7 @@ K = new WeakMap(), q = new WeakMap(), st = new WeakMap(), ot = new WeakMap(), ft
|
|
|
1858
1858
|
console.error("Хранилище для логгера не инициализировано");
|
|
1859
1859
|
}
|
|
1860
1860
|
});
|
|
1861
|
-
},
|
|
1861
|
+
}, kt = new WeakSet(), ne = async function() {
|
|
1862
1862
|
try {
|
|
1863
1863
|
let t = {}, e = new v(BX24.callBatch);
|
|
1864
1864
|
for (let [r, i] of M(this, st).entries())
|
|
@@ -1883,7 +1883,7 @@ K = new WeakMap(), q = new WeakMap(), st = new WeakMap(), ot = new WeakMap(), ft
|
|
|
1883
1883
|
} catch (t) {
|
|
1884
1884
|
return console.error("Ошибка при добавлении записей в хранилище:", t), !1;
|
|
1885
1885
|
}
|
|
1886
|
-
},
|
|
1886
|
+
}, wt = new WeakSet(), ae = async function() {
|
|
1887
1887
|
try {
|
|
1888
1888
|
let t = new v(BX24.callBatch), { serverTime: e } = await t.batch({
|
|
1889
1889
|
serverTime: { method: "server.time" }
|
|
@@ -1961,7 +1961,7 @@ function Kt(y) {
|
|
|
1961
1961
|
const t = Te();
|
|
1962
1962
|
return t ? (y.appConst.pathApp = t, t) : Zt(y.appConst.pathApp ?? "");
|
|
1963
1963
|
}
|
|
1964
|
-
var ct, _t, Ct, ce, dt, vt, Ut, le, Ht, he, Gt, ue, V, nt, gt, qt,
|
|
1964
|
+
var ct, _t, Ct, ce, dt, vt, Ut, le, Ht, he, Gt, ue, V, nt, gt, qt, Pt, fe, yt, zt, Yt, me;
|
|
1965
1965
|
class Ie {
|
|
1966
1966
|
/**
|
|
1967
1967
|
* @param {Object} appConst - Константы приложения
|
|
@@ -2002,7 +2002,7 @@ class Ie {
|
|
|
2002
2002
|
* @param {Array} updateList - Список обновлений для логирования (опционально)
|
|
2003
2003
|
* @returns {Object} Расширенный список ошибок
|
|
2004
2004
|
*/
|
|
2005
|
-
L(this,
|
|
2005
|
+
L(this, Pt);
|
|
2006
2006
|
/**
|
|
2007
2007
|
* Нормализует входные данные в массив объектов {placement, handler?}
|
|
2008
2008
|
* @private
|
|
@@ -2012,7 +2012,7 @@ class Ie {
|
|
|
2012
2012
|
* Находит встройки с устаревшим handler (не содержащим текущий pathApp)
|
|
2013
2013
|
* @private
|
|
2014
2014
|
*/
|
|
2015
|
-
L(this,
|
|
2015
|
+
L(this, Yt);
|
|
2016
2016
|
H(this, "domain", "");
|
|
2017
2017
|
H(this, "isAdmin", !1);
|
|
2018
2018
|
H(this, "appInfo", null);
|
|
@@ -2231,7 +2231,7 @@ class Ie {
|
|
|
2231
2231
|
i = i.filter(
|
|
2232
2232
|
(h) => h.placement !== "PAGE_BACKGROUND_WORKER" && h.placement !== "PAGE_BACKGROUND_WORKER_ALL"
|
|
2233
2233
|
);
|
|
2234
|
-
const a = _(this,
|
|
2234
|
+
const a = _(this, Yt, me).call(this, r), c = new Set(i.map((h) => h.placement));
|
|
2235
2235
|
for (const h of a)
|
|
2236
2236
|
c.has(h.placement) || i.push({ placement: h.placement });
|
|
2237
2237
|
if (i.length === 0)
|
|
@@ -2242,18 +2242,18 @@ class Ie {
|
|
|
2242
2242
|
for (const h of this.placeData)
|
|
2243
2243
|
d.has(h.placement) || d.set(h.placement, []), d.get(h.placement).push(h);
|
|
2244
2244
|
for (let h = 0; h < i.length; h++) {
|
|
2245
|
-
const O = i[h]
|
|
2246
|
-
if (
|
|
2247
|
-
(
|
|
2245
|
+
const { placement: O, options: T } = i[h], E = d.get(O) || [];
|
|
2246
|
+
if (E.some(
|
|
2247
|
+
(R) => R.handler === r
|
|
2248
2248
|
))
|
|
2249
2249
|
continue;
|
|
2250
|
-
const
|
|
2251
|
-
(
|
|
2250
|
+
const p = E.filter(
|
|
2251
|
+
(R) => R.handler !== r
|
|
2252
2252
|
);
|
|
2253
|
-
for (const
|
|
2253
|
+
for (const R of p)
|
|
2254
2254
|
f.push({
|
|
2255
2255
|
placement: O,
|
|
2256
|
-
handler:
|
|
2256
|
+
handler: R.handler
|
|
2257
2257
|
});
|
|
2258
2258
|
n[`bind_${h}`] = {
|
|
2259
2259
|
method: "placement.bind",
|
|
@@ -2266,7 +2266,8 @@ class Ie {
|
|
|
2266
2266
|
}
|
|
2267
2267
|
},
|
|
2268
2268
|
OPTIONS: {
|
|
2269
|
-
errorHandlerUrl: r
|
|
2269
|
+
errorHandlerUrl: r,
|
|
2270
|
+
...T && typeof T == "object" ? T : {}
|
|
2270
2271
|
}
|
|
2271
2272
|
}
|
|
2272
2273
|
};
|
|
@@ -2410,7 +2411,7 @@ ct = new WeakSet(), _t = function() {
|
|
|
2410
2411
|
data: t === "batch" ? { commandList: e, updateList: a } : { commandList: e }
|
|
2411
2412
|
}) : void 0;
|
|
2412
2413
|
try {
|
|
2413
|
-
const n = t === "batch" ? await l.batch(e, r, c) : await l.batchTotalCount(e, r), f = _(this,
|
|
2414
|
+
const n = t === "batch" ? await l.batch(e, r, c) : await l.batchTotalCount(e, r), f = _(this, Pt, fe).call(this, l, n, e, a);
|
|
2414
2415
|
return Object.keys(f).length ? (i && i(f), await _(this, V, nt).call(this, u, {
|
|
2415
2416
|
status: "fail",
|
|
2416
2417
|
errorList: f
|
|
@@ -2421,7 +2422,7 @@ ct = new WeakSet(), _t = function() {
|
|
|
2421
2422
|
errorList: { 0: n == null ? void 0 : n.toString() }
|
|
2422
2423
|
}), console.error(n), !1;
|
|
2423
2424
|
}
|
|
2424
|
-
},
|
|
2425
|
+
}, Pt = new WeakSet(), fe = function(t, e, r, i) {
|
|
2425
2426
|
let a = { ...t.errors };
|
|
2426
2427
|
if (Object.values(t.errors).some(
|
|
2427
2428
|
(l) => {
|
|
@@ -2458,7 +2459,7 @@ ct = new WeakSet(), _t = function() {
|
|
|
2458
2459
|
return Array.isArray(t) ? e = t.map(
|
|
2459
2460
|
(r) => typeof r == "string" ? { placement: r } : r
|
|
2460
2461
|
) : typeof t == "string" ? e = [{ placement: t }] : e = [t], e;
|
|
2461
|
-
},
|
|
2462
|
+
}, Yt = new WeakSet(), me = function(t) {
|
|
2462
2463
|
return this.placeData ? this.placeData.filter((e) => !(e.placement === "PAGE_BACKGROUND_WORKER" || !e.handler || e.handler.includes(t))) : [];
|
|
2463
2464
|
};
|
|
2464
2465
|
const de = "szdl-utils-kit|";
|
|
@@ -2816,15 +2817,15 @@ class Me {
|
|
|
2816
2817
|
);
|
|
2817
2818
|
}
|
|
2818
2819
|
async setBackgroundWorkerAll() {
|
|
2819
|
-
var
|
|
2820
|
-
if (!((
|
|
2820
|
+
var S, p, R, C;
|
|
2821
|
+
if (!((S = this.bx) != null && S.isAdmin)) {
|
|
2821
2822
|
console.log(
|
|
2822
2823
|
"BackgroundWorker: setBackgroundWorkerAll доступен только админам"
|
|
2823
2824
|
);
|
|
2824
2825
|
return;
|
|
2825
2826
|
}
|
|
2826
2827
|
(p = this.users) != null && p.length || await this.getEntityData(), Kt(this.bx);
|
|
2827
|
-
const t = _(this, pt, Qt).call(this, ((C = (
|
|
2828
|
+
const t = _(this, pt, Qt).call(this, ((C = (R = this.bx) == null ? void 0 : R.appConst) == null ? void 0 : C.pathApp) ?? "");
|
|
2828
2829
|
if (!t) {
|
|
2829
2830
|
console.error(
|
|
2830
2831
|
"BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена"
|
|
@@ -2839,46 +2840,46 @@ class Me {
|
|
|
2839
2840
|
if (N.placement !== "PAGE_BACKGROUND_WORKER")
|
|
2840
2841
|
return;
|
|
2841
2842
|
if (N.userId || N.handler && N.handler.includes("USER_ID=")) {
|
|
2842
|
-
const
|
|
2843
|
-
if (
|
|
2844
|
-
const
|
|
2845
|
-
r.set(
|
|
2843
|
+
const b = N.userId || (N.handler ? this.extractUserIdFromHandler(N.handler) : null);
|
|
2844
|
+
if (b) {
|
|
2845
|
+
const w = +b;
|
|
2846
|
+
r.set(w, N), i.has(w) || i.set(w, []), i.get(w).push(N);
|
|
2846
2847
|
}
|
|
2847
2848
|
} else
|
|
2848
2849
|
a = N;
|
|
2849
2850
|
});
|
|
2850
2851
|
const c = await this.resolveAdmins(), l = await this.getEligibleUsersForBackgroundWorker(c);
|
|
2851
2852
|
l.sort((N, I) => {
|
|
2852
|
-
const
|
|
2853
|
-
return (I.LAST_LOGIN ? new Date(I.LAST_LOGIN) : /* @__PURE__ */ new Date(0)) -
|
|
2853
|
+
const b = N.LAST_LOGIN ? new Date(N.LAST_LOGIN) : /* @__PURE__ */ new Date(0);
|
|
2854
|
+
return (I.LAST_LOGIN ? new Date(I.LAST_LOGIN) : /* @__PURE__ */ new Date(0)) - b;
|
|
2854
2855
|
});
|
|
2855
2856
|
const u = 10, n = l.slice(0, u), f = n.filter((N) => {
|
|
2856
2857
|
const I = r.get(+N.ID);
|
|
2857
2858
|
if (!I)
|
|
2858
2859
|
return !0;
|
|
2859
|
-
const
|
|
2860
|
-
return I.handler !==
|
|
2860
|
+
const b = `${t}?USER_ID=${N.ID}/`;
|
|
2861
|
+
return I.handler !== b;
|
|
2861
2862
|
}), d = [];
|
|
2862
2863
|
for (const [N] of r) {
|
|
2863
2864
|
const I = +N || 0;
|
|
2864
|
-
l.find((
|
|
2865
|
+
l.find((w) => +w.ID === I) || d.push(I);
|
|
2865
2866
|
}
|
|
2866
2867
|
for (const N of n) {
|
|
2867
2868
|
const I = r.get(+N.ID);
|
|
2868
2869
|
if (!I)
|
|
2869
2870
|
continue;
|
|
2870
|
-
const
|
|
2871
|
-
I.handler !==
|
|
2871
|
+
const b = `${t}?USER_ID=${N.ID}/`;
|
|
2872
|
+
I.handler !== b && d.push(+N.ID);
|
|
2872
2873
|
}
|
|
2873
2874
|
const A = [], h = [...new Set(d)];
|
|
2874
2875
|
for (const N of h) {
|
|
2875
2876
|
const I = i.get(+N) || [];
|
|
2876
|
-
for (const
|
|
2877
|
-
|
|
2877
|
+
for (const b of I)
|
|
2878
|
+
b != null && b.handler && A.push({
|
|
2878
2879
|
method: "placement.unbind",
|
|
2879
2880
|
params: {
|
|
2880
2881
|
PLACEMENT: "PAGE_BACKGROUND_WORKER",
|
|
2881
|
-
HANDLER:
|
|
2882
|
+
HANDLER: b.handler
|
|
2882
2883
|
}
|
|
2883
2884
|
});
|
|
2884
2885
|
}
|
|
@@ -2914,7 +2915,7 @@ class Me {
|
|
|
2914
2915
|
});
|
|
2915
2916
|
const T = A.filter(
|
|
2916
2917
|
(N) => N.method === "placement.unbind"
|
|
2917
|
-
),
|
|
2918
|
+
), E = A.filter(
|
|
2918
2919
|
(N) => N.method === "placement.bind"
|
|
2919
2920
|
);
|
|
2920
2921
|
T.length && await this.safeCall(
|
|
@@ -2923,10 +2924,10 @@ class Me {
|
|
|
2923
2924
|
T.map((N, I) => [`unbind_${I}`, N])
|
|
2924
2925
|
)
|
|
2925
2926
|
)
|
|
2926
|
-
),
|
|
2927
|
+
), E.length && await this.safeCall(
|
|
2927
2928
|
() => this.bx.batch(
|
|
2928
2929
|
Object.fromEntries(
|
|
2929
|
-
|
|
2930
|
+
E.map((N, I) => [`bind_${I}`, N])
|
|
2930
2931
|
)
|
|
2931
2932
|
)
|
|
2932
2933
|
), A.length || console.log("setBackgroundWorkerAll: Нет операций");
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Ie=Object.defineProperty;var Me=(B,C,Y)=>C in B?Ie(B,C,{enumerable:!0,configurable:!0,writable:!0,value:Y}):B[C]=Y;var P=(B,C,Y)=>(Me(B,typeof C!="symbol"?C+"":C,Y),Y),qt=(B,C,Y)=>{if(!C.has(B))throw TypeError("Cannot "+Y)};var M=(B,C,Y)=>(qt(B,C,"read from private field"),Y?Y.call(B):C.get(B)),L=(B,C,Y)=>{if(C.has(B))throw TypeError("Cannot add the same private member more than once");C instanceof WeakSet?C.add(B):C.set(B,Y)},j=(B,C,Y,ot)=>(qt(B,C,"write to private field"),ot?ot.call(B,Y):C.set(B,Y),Y);var O=(B,C,Y)=>(qt(B,C,"access private method"),Y);(function(B,C){typeof exports=="object"&&typeof module<"u"?C(exports):typeof define=="function"&&define.amd?define(["exports"],C):(B=typeof globalThis<"u"?globalThis:B||self,C(B["szdl-utils-kit"]={}))})(this,function(B){var bt,ae,Rt,Lt,St,It,At,Ft,Mt,oe,Dt,Ae,V,ut,st,Tt,rt,Et,kt,ce,dt,Qt,it,Q,Z,nt,ct,gt,$,J,at,lt,Bt,le,yt,Zt,wt,he,Ct,ue,Ht,fe,ht,Xt,Ut,me,pt,Vt,Gt,de,Pt,ge,Yt,ye,tt,ft,Nt,$t,Wt,pe,Ot,te,xt,Ne,_t,ee;"use strict";var C=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Y(
|
|
2
|
-
https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(g.responseText))):m&&m(g))},g.open("GET",t,!1),g.send()},E={"%d":{format:function(t){return i(t.day()||n.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 i(t.month()||n.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 i(t.year()||n.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()||n.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(t){var o=t.dayOfWeek();return p[o!==e?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var o=t.dayOfWeek();return U[o!==e?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(t){var o=n.options("monthFromZero")?t.month():t.month()-1;return S[o!==e?o:n.MIN_MONTH]},parse:function(t){var o=n.monthNames().indexOf(t)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var o=n.options("monthFromZero")?t.month():t.month()-1;return y[o!==e?o:n.MIN_MONTH]},parse:function(t){var o=n.monthNames(!0).indexOf(t)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(t){return i(t.hours()||n.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 i(t.minutes()||n.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 i(t.seconds()||n.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))?{}:n(Number(t)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(t){return i(t.year()||n.MIN_YEAR,4)+"-"+i(t.month()||n.MIN_MONTH,2)+"-"+i(t.day()||n.MIN_DAY,2)},parse:function(t){var o=Number(t.slice(0,4)),m=Number(t.slice(5,7)),g=Number(t.slice(8,10));return{year:o,month:m,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return i(t.month()||n.MIN_MONTH,2)+"/"+i(t.day()||n.MIN_DAY,2)+"/"+i(t.year()||n.MIN_YEAR,4)},parse:function(t){var o=Number(t.slice(0,2)),m=Number(t.slice(3,5)),g=Number(t.slice(6,10));return{year:g,month:o,day:m}},minLength:10,maxLength:10,type:"string"}},w={useMilliseconds:!1,monthFromZero:!1},k;k=function(t,o,m){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,m),this},k.fn=k.prototype,k.fn.dayCount=function(){var t=this.month(),o=n.MAX_DAY_IN_MONTHS[t-(n.options("monthFromZero")?0:1)];return this.leapYear()&&t===(n.options("monthFromZero")?1:2)&&(o+=1),o},k.fn.year=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_YEAR&&Number(t)<=n.MAX_YEAR?(this._d.setFullYear(Number(t)),this._i.year=!1):this._i.year=Number(t):(this._d.setFullYear(n.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},k.fn.month=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MONTH&&Number(t)<=n.MAX_MONTH?(this._d.setMonth(n.options("monthFromZero")?Number(t):Number(t)-1),this._i.month=!1):this._i.month=Number(t):(this._d.setMonth(n.options("monthFromZero")?n.MIN_MONTH:n.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?n.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},k.fn.day=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_DAY&&Number(t)<=this.dayCount()?(this._d.setDate(Number(t)),this._i.day=!1):this._i.day=Number(t):(this._d.setDate(n.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},k.fn.hours=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_HOURS&&Number(t)<=n.MAX_HOURS?(this._d.setHours(Number(t)),this._i.hours=!1):this._i.hours=Number(t):(this._d.setHours(n.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},k.fn.minutes=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MINUTES&&Number(t)<=n.MAX_MINUTES?(this._d.setMinutes(Number(t)),this._i.minutes=!1):this._i.minutes=Number(t):(this._d.setMinutes(n.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},k.fn.seconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_SECONDS&&Number(t)<=n.MAX_SECONDS?(this._d.setSeconds(Number(t)),this._i.seconds=!1):this._i.seconds=Number(t):(this._d.setSeconds(n.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},k.fn.milliseconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MILLISECONDS&&Number(t)<=n.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(t)),this._i.milliseconds=!1):this._i.milliseconds=Number(t):(this._d.setMilliseconds(n.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},k.fn.week=function(){var t=new Date(this.year(),0,1),o=n(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-t.getTime())/864e5+t.getDay()+1)/7)},k.fn.set=function(t,o,m){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*(n.options("useMilliseconds")?1:1e3)),this;if(typeof t=="object"&&(t instanceof Array?(this.day(n.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(n.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,H=[],D,G,et=[],X=0,K=0,W,v,x={},F;if(t===e)return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;for(o===e&&(o=n.detectFormat(t));X<o.length;){if(o.charAt(X)==="%"){if(G=o.charAt(X)+o.charAt(X+1),E[G]!==e){switch(W=0,v="",E[G].type){case"number":for(;W<E[G].maxLength&&K+W<t.length&&!isNaN(Number(t.charAt(K+W)));)v+=t.charAt(K+W),W+=1;break;case"word":for(;W<E[G].maxLength&&K+W<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(K+W));)v+=t.charAt(K+W),W+=1;break;case"string":for(;W<E[G].maxLength&&K+W<t.length;)v+=t.charAt(K+W),W+=1;break}if(W<E[G].minLength)return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;H.push(G),et.push(v),W-=1,K+=W,X+=1}}else if(t.charAt(K)!==o.charAt(X))return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;X+=1,K+=1}for(g in H)H.hasOwnProperty(g)&&E.hasOwnProperty(H[g])&&(F=E[H[g]].parse(et[g]),x={year:F.year!==e?F.year:x.year,month:F.month!==e?F.month:x.month,day:F.day!==e?F.day:x.day,hours:F.hours!==e?F.hours:x.hours,minutes:F.minutes!==e?F.minutes:x.minutes,seconds:F.seconds!==e?F.seconds:x.seconds});this.day(n.MIN_DAY),this.year(x.year),this.month(x.month),this.day(x.day),this.hours(x.hours),this.minutes(x.minutes),this.seconds(x.seconds),this.milliseconds(x.milliseconds)}return this},k.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},k.fn.timestamp=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(n.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):n.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},k.fn.utc=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(n.options("useMilliseconds")?1:1e3)),this):n.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},k.fn.dayOfWeek=function(t){if(t==="long")return U[this._d.getDay()];if(t==="short")return p[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()})},k.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}},k.fn.get=function(t){switch(t){case"Date":return new Date(this.year(),this.month()-(n.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()-(n.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()}}},k.fn.format=function(t){for(var o=0,m="",g;o<t.length;)t.charAt(o)==="%"?(g=t.charAt(o)+t.charAt(o+1),E[g]!==e?(m+=E[g].format(this),o+=1):m+="%"):m+=t.charAt(o),o+=1;return m},k.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},k.fn.errors=function(){return this._i},k.fn.between=function(t,o){var m=this.timestamp(),g=t.timestamp();switch(o){case"year":return Math.floor((g-m)/31556952);case"month":return Math.floor((g-m)/2629746);case"day":return Math.floor((g-m)/86400);case"hours":return Math.floor((g-m)/3600);case"minutes":return Math.floor((g-m)/60);case"seconds":return g-m;default:return e}},k.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},n=function(t,o,m){return new k(t,o,m)},n.MIN_YEAR=1e3,n.MAX_YEAR=3e3,n.MIN_MONTH=1,n.MAX_MONTH=12,n.MIN_DAY=1,n.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],n.MIN_DAY_OF_WEEK=0,n.MAX_DAY_OF_WEEK=6,n.MIN_HOURS=0,n.MAX_HOURS=23,n.MIN_MINUTES=0,n.MAX_MINUTES=59,n.MIN_SECONDS=0,n.MAX_SECONDS=59,n.MIN_MILLISECONDS=0,n.MAX_MILLISECONDS=999,n.VERSION="0.2.18",n.options=function(t,o){if(t===e)return w;if(w.hasOwnProperty(t)){if(o===e)return w[t];w[t]=o,t==="monthFromZero"&&(n.MIN_MONTH=o?0:1,n.MAX_MONTH=o?11:12)}return e},n.noConflict=function(){return r.tempus=u,n},n.generate=function(t){var o,m,g,H,D,G,et,X;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof k?o=t.dateFrom.utc():o=n(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof k?m=t.dateTo.utc():m=n(t.dateTo,t.formatTo!==e?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?D={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?D={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"&&(D={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?G=t.asObject===!0?{}:[]:(G=[],G.push([]),et=n(o).get()[t.groupBy]),X=function(v,x,F){return t.asObject===!0?t.format!==e?v[n(x).format(t.format)]={}:v[n(x).format("%F %H:%M:%S")]={}:t.format!==e?v.push(F?null:n(x).format(t.format)):v.push(F?null:n(x)),v},t.groupBy!==e&&t.fillNulls){var K={year:D.year?-D.year:e,month:D.month?-D.month:e,day:D.day?-D.day:e,hours:D.hours?-D.hours:e,minutes:D.minutes?-D.minutes:e,seconds:D.seconds?-D.seconds:e,milliseconds:D.milliseconds?-D.milliseconds:e};for(g=n(o).calc(K).utc();n(g).get()[t.groupBy]===et;)X(G[G.length-1],g,!0),g=n(g).calc(K).utc();if(t.groupBy==="week"){var W=n(o).dayOfWeek();for(g=n(o).dayOfWeek(0).utc();G[0].length<W&&g<o;)X(G[G.length-1],g,!0),g=n(g).calc(D).utc()}}for(;o<=m;)t.groupBy===e?X(G,o):n(o).get()[t.groupBy]===et?X(G[G.length-1],o):(G.push([]),X(G[G.length-1],o),et=n(o).get()[t.groupBy]),o=n(o).calc(D).utc();if(t.groupBy!==e&&t.fillNulls)for(H=n(m).calc(D).utc();n(H).get()[t.groupBy]===et;)X(G[G.length-1],H,!0),H=n(H).calc(D).utc();return G},n.monthNames=function(t){switch(t){case"long":return y;default:return S}},n.dayNames=function(t){switch(t){case"long":return U;default:return p}},n.lang=function(t){if(t!==e)A=t,h[A]===e&&(A="en"),y=N(),S=_(),U=b(),p=R();else return A;return e},n.availableLangs=function(){return Object.keys(h)},n.registerFormat=function(t,o,m,g,H,D){E[t]={format:o,parse:m,minLength:g,maxLength:H,type:D}},n.unregisterFormat=function(t){delete E[t]},n.detectFormat=function(t){var o,m,g;return o=l(t,0),o!==""&&(g=10),m=t.charAt(g),(m==="T"||m===" ")&&(o+=m,g+=1),o+=c(t,g),o},f={TempusDate:k},n.classes=function(t,o){if(o===e)return f[t];f[t]=o},n.loadTranslations=function(t){typeof t=="object"?h=t:typeof t=="string"&&I(t,function(o){h=o},function(o){})},A=(d.language||d.systemLanguage||d.userLanguage||"en").substr(0,2).toLowerCase(),h[A]===e&&(A="en"),y=N(),S=_(),U=b(),p=R(),T.exports&&(s=T.exports=n),s.tempus=n}).call(C)})(ot,ot.exports);var Oe=ot.exports;const mt=Y(Oe),q=class q{constructor(s){L(this,bt);L(this,At);L(this,Mt);L(this,Dt);L(this,V);L(this,st);L(this,rt);L(this,kt);L(this,dt);typeof s=="function"?(this.callBatch=s,this.callMethod=null):(this.callBatch=(s==null?void 0:s.callBatch)||null,this.callMethod=(s==null?void 0:s.callMethod)||null),this.result={},this.errors={},this.timeLimit={limit:!1,date:void 0,pauseMs:void 0},this.timeLimitListeners=new Set,this.canContinue=!0,this.progressCall="",this.progressData="",this.progressTimer="",this.lastProgressSnapshot=null,this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.filterChunkSize=50,this.limit=50,this.progressDelay=100,this.operatingThreshold=475,this.defaultPauseMs=12e4,this.callLimitPauseMs=3e4,this.requestTimeoutMs=6e4}get progressPercent(){if(!this.progressData)return{percent:0,allCount:0,allTotal:0};const s=this.totalBatchCommands||0;if(s>0&&Array.isArray(this.batchCommandKeyOrder)&&this.batchCommandKeyOrder.length&&O(this,bt,ae).call(this)){let l=0;for(const A of this.batchCommandKeyOrder){const h=this.progressData[A];if(!h)continue;const N=Number(h.total)||0,_=Number(h.count)||0;N===0&&_===0?l+=1:N>0&&(l+=Math.min(1,_/N))}const u=l/s*100;let n=Math.max(0,Math.min(100,Math.floor(u)));const f=s,d=Math.min(s,Math.floor(l));return{percent:n,allCount:d,allTotal:f}}let e=0,r=0;for(const l of Object.values(this.progressData)){const{total:u,count:n}=l;e+=u??0,r+=n??0}const i=Number(this.chunkRate)||0;let a=0;e?a=r/e*100*i+this.totalProgress:r===0&&e===0?a=100*i+this.totalProgress:a=100,a=Math.max(0,Math.min(a,100));let c=Math.floor(a);return e>0&&r>=e&&(c=100),{percent:c,allCount:r,allTotal:e}}setProgressData({key:s,value:e,type:r}){var h,N;if(!this.progressCall)return;const i=this.getData(e.data()),a=Array.isArray(i)?i.length:0;let c=a;if(typeof e.total=="function"){const _=e.total();if(_!=null&&_!==""){const b=Number(_);Number.isFinite(b)&&(c=b)}}r==="count"&&(c=a);let l=1;i&&(l=a),this.progressData||(this.progressData={});const u=((h=this.progressData[s])==null?void 0:h.total)??0,n=((N=this.progressData[s])==null?void 0:N.count)??0,f=l+n,d=Math.max(u,c??0,f);if(this.progressData[s]={total:d,count:Math.min(f,d)},typeof document<"u"&&(document==null?void 0:document.hidden)===!0){O(this,At,Ft).call(this);return}O(this,At,Ft).call(this),this.progressTimer||(this.progressTimer=setInterval(()=>{if(!this.progressCall){this.clearProgressData();return}O(this,At,Ft).call(this);const{percent:_}=this.progressPercent;_>=100&&(clearInterval(this.progressTimer),this.progressTimer="")},this.progressDelay))}getData(s){if(s==null)return s;let e=(s==null?void 0:s.items)??(s==null?void 0:s.tasks)??(s==null?void 0:s.types)??(s==null?void 0:s.type)??(s==null?void 0:s.fields)??(s==null?void 0:s.workgroups)??s;return e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.result)&&(e=e.result),e}setTimeLimitState(s,e,r){this.timeLimit.limit=!!s,this.timeLimit.date=s?e:void 0,s&&typeof r=="number"&&r>0?this.timeLimit.pauseMs=r:this.timeLimit.pauseMs=void 0,O(this,Dt,Ae).call(this)}subscribeTimeLimit(s){return typeof s!="function"?()=>{}:(this.timeLimitListeners.add(s),s({limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs}),()=>{this.timeLimitListeners.delete(s)})}splitLargeFilters(s,e){const{method:r,params:i}=e;if(!i)return[{key:s,request:e}];const a=i.filter||i.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:s,request:e}];for(const[c,l]of Object.entries(a))if(!String(c).trim().startsWith("!")&&Array.isArray(l)&&l.length>this.filterChunkSize){const u=[];for(let n=0;n<l.length;n+=this.filterChunkSize){const f=l.slice(n,n+this.filterChunkSize),d=n===0?s:`${s}__chunk_${Math.floor(n/this.filterChunkSize)}`,A={...i};i.filter?(A.filter={...a},A.filter[c]=f):i.FILTER&&(A.FILTER={...a},A.FILTER[c]=f),u.push({key:d,request:{method:r,params:A},originalKey:s,filterKey:c,chunkIndex:Math.floor(n/this.filterChunkSize)})}return u}return[{key:s,request:e}]}mergeSplitResults(s,e){const r=[],i=String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${i}(?:__chunk_\\d+)?$`),c=Object.keys(s).filter(l=>a.test(l)).sort((l,u)=>{const n=l.match(/__chunk_(\d+)$/),f=u.match(/__chunk_(\d+)$/);return n?f?parseInt(n[1])-parseInt(f[1]):1:-1});for(const l of c){const u=s[l];Array.isArray(u)?r.push(...u):u&&r.push(u)}return r}delay(){return typeof document<"u"&&(document==null?void 0:document.hidden)===!0?Promise.resolve():new Promise(e=>setTimeout(e,500))}callBatchWithTimeout(s,e){return new Promise((r,i)=>{let a=!1,c=null;const l=async n=>{if(!a){a=!0,c&&clearTimeout(c);try{await Promise.resolve(e(n)),r()}catch(f){console.error("Error in callBatch callback:",f),i(f)}}},u=async()=>{if(!a){a=!0,c&&clearTimeout(c),console.warn(`Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`);const n={};Object.keys(s).forEach(f=>{n[f]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 60 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(e(n)),r()}catch(f){console.error("Error in timeout callback:",f),r()}}};try{this.callBatch(s,async n=>{await l(n)})}catch(n){a||console.error("Error calling callBatch:",n)}c=setTimeout(async()=>{a||(console.warn(`Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`),await u())},this.requestTimeoutMs)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.lastProgressSnapshot=null}async batch(s,e,r={}){O(this,dt,Qt).call(this,e);const i={},a={},c={};for(const[f,d]of Object.entries(s)){const A=this.arrayChunk(d);if(!A)continue;const h=this.splitLargeFilters(f,A);if(h.length===1)a[f]=A;else{c[f]=[];for(const N of h)a[N.key]=N.request,c[f].push(N.key)}}this.batchCommandKeyOrder=Object.keys(a),this.totalBatchCommands=this.batchCommandKeyOrder.length,this.batchCommandMethods=this.batchCommandKeyOrder.map(f=>{var d;return String(((d=a[f])==null?void 0:d.method)||"")}),this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let l={},u=0;const n=Object.keys(a).length;for(const[f,d]of Object.entries(a)){if(!this.canContinue)break;if(l[f]=d,Object.keys(l).length>=this.limit||u+1===n){const A=u+1===n;await this.batchChunk(l,void 0,!A,{disablePagination:!1,oneBatch:!!(r!=null&&r.oneBatch)}),Object.entries(this.result).forEach(([h,N])=>{i[h]=N}),this.totalProgress=Math.round(u/n*100),l={}}u++}for(const[f,d]of Object.entries(c))if(d&&d.length>0){const A=this.mergeSplitResults(i,f);for(const h of d)delete i[h];i[f]=A}return Object.entries(this.errors).length&&(i.errorsList=this.errors),e&&e({percent:100}),Promise.resolve(i)}async batchTotalCount(s,e){O(this,dt,Qt).call(this,e);const r={},i={},a={};for(const[u,n]of Object.entries(s)){const f=this.arrayChunk(n);if(!f)continue;const d=this.splitLargeFilters(u,f);if(d.length===1)i[u]=f;else{a[u]=[];for(const A of d)i[A.key]=A.request,a[u].push(A.key)}}const c=[],l=Object.entries(i);for(let u=0;u<l.length;u+=this.limit){const n=l.slice(u,u+this.limit),f={};for(const[d,A]of n){if(!this.canContinue)break;f[d]=A}Object.keys(f).length>0&&c.push(f)}this.chunkRate=(1/c.length).toFixed(5);for(const[u,n]of Object.entries(c)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(u)/c.length*100);const f=Number(u)===c.length-1;await O(this,rt,Et).call(this,n,async d=>{var A,h,N,_,b;for(const[R,y]of Object.entries(d)){if(!this.canContinue)return;if(y.error()){const E=(h=(A=y.error())==null?void 0:A.ex)==null?void 0:h.error,w=(_=(N=y.error())==null?void 0:N.ex)==null?void 0:_.error_description;this.errors[R]=E&&E.trim()||w&&w.trim()||((b=y.error())==null?void 0:b.toString())||"Неизвестная ошибка",r[R]=0;continue}const S=this.getData(y.data()),U=Array.isArray(S)?S.length:0,I=typeof y.total=="function"&&y.total()!==void 0?y.total():U;r[R]=I,this.setProgressData({key:R,value:y,type:"count"})}await O(this,st,Tt).call(this,d,!f)})}for(const[u,n]of Object.entries(a))if(n&&n.length>0){let f=0;for(const d of n)r[d]!==void 0&&(f+=r[d]||0),delete r[d];r[u]=f}return Object.entries(this.errors).length&&(r.errorsList=this.errors,this.errorLogger()),e&&e({percent:100}),Promise.resolve(r)}async call({method:s,params:e={}}){var r,i,a,c,l,u,n;for(;;){const f=await O(this,kt,ce).call(this,s,e);if(!f){await O(this,V,ut).call(this,this.callLimitPauseMs);continue}const d={};if(f!=null&&f.answer)for(const[h,N]of Object.entries(f.answer))h!=="result"&&N&&(d[h]=N);if(f.error()){const h=((i=(r=f.error())==null?void 0:r.ex)==null?void 0:i.error)??"";if(["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT","TIMEOUT"].includes(h)){await O(this,V,ut).call(this,this.callLimitPauseMs);continue}const N=((a=f.error())==null?void 0:a.toString())||((l=(c=f.error())==null?void 0:c.ex)==null?void 0:l.error_description)||((n=(u=f.error())==null?void 0:u.ex)==null?void 0:n.error)||"Неизвестная ошибка";return{success:!1,data:!1,answer:d,error:N}}let A=f.data();return A!=null&&A.items&&(A=A.items),{success:!0,data:A,answer:d,error:null}}}arrayChunk(s){let e="",r={};if(Array.isArray(s)?[e]=s:(e=s.method,r=s.params),(e.includes("list")||e==="user.get"||e==="entity.item.get")&&e!=="task.item.list"){if(!r)r=e==="entity.item.get"?{SORT:{ID:"ASC"}}:{order:{ID:"ASC",id:"ASC"}};else{e==="entity.item.get"?(r.SORT||(r.SORT={ID:"ASC"}),Array.isArray(r.select)?r.select.includes("ID")||r.select.push("ID"):r.select=["ID"]):e==="tasks.task.list"?(r.order||(r.order={}),r.order.ID="asc"):e==="user.get"?(r.sort||(r.sort="ID"),r.order||(r.order="ASC")):r.order={ID:"ASC",id:"ASC"},Array.isArray(r.select)&&!r.select.includes("ID")&&r.select.push("ID");const i=e==="user.get"||e==="entity.item.get"?r.FILTER:r.filter;typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.entries(i).forEach(([a,c])=>{(r.start===void 0||r.start!==-1)&&["id","ID"].includes(a)&&(typeof c=="string"||Array.isArray(c)&&c.length<=50)&&(r.start=-1)})}e==="crm.type.list"&&r.order&&delete r.order.ID}if(e==="task.item.list")if(!r)r=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(r[0])&&(r[0]={});const[i,a,c,l]=r;i.ID="ASC",l[0]!==""&&l.includes("ID")||l.push("ID")}return{method:e,params:r}}async batchChunk(s,e,r=!0,i={}){return new Promise(a=>{const c=[];let l;const u=!!(i!=null&&i.disablePagination);(async()=>{await O(this,rt,Et).call(this,s,async f=>{var A,h,N,_,b;for(const[R,y]of Object.entries(f)){if(!this.canContinue)return;if(y.error()){const g=(h=(A=y.error())==null?void 0:A.ex)==null?void 0:h.error,H=(_=(N=y.error())==null?void 0:N.ex)==null?void 0:_.error_description;this.errors[R]=g&&g.trim()||H&&H.trim()||((b=y.error())==null?void 0:b.toString())||"Неизвестная ошибка",l=!0}const S=this.getData(y.data()),U=Array.isArray(S)?S.length:0,p=typeof y.total=="function"&&y.total()!==void 0,I=p?y.total():U;e==="count"?this.result[R]?this.result[R]+=U:this.result[R]=I:this.result[R]=S,this.setProgressData({key:R,value:y,type:e});const E=s[R],w=Array.isArray(E)?E[0]:E==null?void 0:E.method,k=typeof w=="string"&&(w.includes(".list")||w==="user.get"||w==="entity.item.get"),t=e==="count"?!p&&U===this.limit:k?U===this.limit:I>this.limit&&I>U,o=e!=="count"&&w==="entity.item.get"&&U===this.limit&&!t,m=t||o;if(!u&&(!this.canContinue||m)){let g=s[R];if(Array.isArray(g)){const[H,D={}]=g;g=[H,D]}else{const{method:H,params:D={}}=g;g=[H,D]}c.push([R,g,I,{entityItemGetScan:o}])}}l>0&&this.errorLogger();const d=c.length>0||r;await O(this,st,Tt).call(this,f,d),c.length?await this.batchPayload(c,e,i).then(()=>a(this.result)):a(this.result)})})()})}async batchPayload(s,e,r={}){const i=!!(r!=null&&r.oneBatch),a=(N,_,b,R)=>{let y="ID";this.result[N][this.result[N].length-1].ID||(y="id");let S=`${y}`;if(JSON.stringify(R[1]).toLocaleLowerCase().includes('"id":"desc"')?S="<"+S:S=">"+S,_===1||b.length===0)return{field:S,id:this.result[N][this.result[N].length-1][y]};let p="";const[I,E]=R;return(I==="tasks.task.list"||I==="task.item.list")&&(p="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(I)&&(p="[items]"),I==="crm.type.list"&&(p="[types]"),I==="socialnetwork.api.workgroup.list"&&(p="[workgroups]"),{field:S,id:`$result[${[N,_-1].join("__")}]${p}[49][${y}]`}},c=(N,_)=>{const[b,R]=N;let y=JSON.parse(JSON.stringify(R)),S;if(b==="task.item.list"){y=[...y];const[U,p,I,E]=y;return p[_.field]=_.id,[b,y]}return["user.get"].includes(b)||y.FILTER?(y.FILTER||(y.FILTER={}),S=y.FILTER):(y.filter||(y.filter={}),S=y.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(b)?S[">ID"]=_.id:S[_.field]=_.id,[b,{...y,start:-1}]},l=N=>{Object.entries(N).forEach(([_,b])=>{var S,U,p,I,E;const[R]=_.split("__"),y=this.getData(b.data());if(Array.isArray(y)&&(e==="count"?this.result[R]+=y.length:this.result[R].push(...y)),b.error()){const w=(U=(S=b.error())==null?void 0:S.ex)==null?void 0:U.error,k=(I=(p=b.error())==null?void 0:p.ex)==null?void 0:I.error_description;this.errors[R]=w&&w.trim()||k&&k.trim()||((E=b.error())==null?void 0:E.toString())||"Неизвестная ошибка"}this.setProgressData({key:R,value:b,type:e})})},u=(N,_)=>{if(!Array.isArray(N)||N.length===0)return null;const b=N[N.length-1];let R="ID";b.ID||(R="id");let y=R;return JSON.stringify(_[1]).toLocaleLowerCase().includes('"id":"desc"')?y="<"+y:y=">"+y,{field:y,id:b[R]}},n=1e4,f=async(N,_)=>{var R,y;let b=this.limit;for(let S=1;this.canContinue&&b===this.limit&&S<=n;S++){const U=this.result[N],p=u(U,_);if(!p)break;const I=`${N}__eiscan_${S}`,E=c(_,p);let w=null;await O(this,rt,Et).call(this,{[I]:E},async m=>{w=m,l(m)});const k=S<n;await O(this,st,Tt).call(this,w,k),await this.delay();const t=w==null?void 0:w[I];if((R=t==null?void 0:t.error)!=null&&R.call(t)){b=0;break}const o=this.getData((y=t==null?void 0:t.data)==null?void 0:y.call(t));b=Array.isArray(o)?o.length:0}};let d=[],A=0;const h=async(N=!0)=>d.length?(await O(this,rt,Et).call(this,Object.fromEntries(d),async _=>{l(_),await O(this,st,Tt).call(this,_,N)}),A++,d=[],i&&A>=1?!0:(await this.delay(),!1)):!1;for await(const N of s){if(!this.canContinue)return;const[_,b,R,y={}]=N;if(y.entityItemGetScan){if(await h(!0))return;if(i)continue;await f(_,b);continue}let S=1;for(;R>S*this.limit;){const U=[_,S].join("__"),p=a(_,S,d,b);if(d.push([U,c(b,p)]),i&&d.length===49&&await h(!0)||d.length%50===0&&await h(!0))return;S++}}await h(!1)}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([s,e])=>{e&&console.log(`[${s}]`,e.toString())}),console.groupEnd()}};bt=new WeakSet,ae=function(){const s=this.totalBatchCommands||0,e=this.batchCommandMethods;if(s<M(q,Rt)||!Array.isArray(e)||e.length!==s)return!1;if(e.filter(a=>a==="crm.deal.list").length>=M(q,Lt))return!0;const i=e.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=M(q,St)&&i/s>=M(q,It)},Rt=new WeakMap,Lt=new WeakMap,St=new WeakMap,It=new WeakMap,At=new WeakSet,Ft=function(){if(!this.progressCall||!this.progressData)return;const{percent:s,allCount:e,allTotal:r}=this.progressPercent,i={percent:s,allCount:e,allTotal:r};O(this,Mt,oe).call(this,i)&&(this.progressCall({data:this.progressData,percent:s,allCount:e,allTotal:r}),this.lastProgressSnapshot=i)},Mt=new WeakSet,oe=function(s){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==s.percent||this.lastProgressSnapshot.allCount!==s.allCount||this.lastProgressSnapshot.allTotal!==s.allTotal:!0},Dt=new WeakSet,Ae=function(){const s={limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs};for(const e of this.timeLimitListeners)try{e(s)}catch(r){console.warn("Batch timeLimit listener error:",r)}},V=new WeakSet,ut=async function(s=this.defaultPauseMs){this.setTimeLimitState(!0,new Date().toISOString(),s),await new Promise(e=>setTimeout(e,s)),this.setTimeLimitState(!1,void 0)},st=new WeakSet,Tt=async function(s,e=!0){if(!e)return 0;let r=0;if(!s||typeof s!="object")return 0;for(const i of Object.values(s))if(!(!i||typeof i!="object"))try{if(typeof i.time=="function"){const a=i.time();a&&typeof a.operating=="number"&&(r=Math.max(r,a.operating))}}catch{}r>=this.operatingThreshold&&await O(this,V,ut).call(this)},rt=new WeakSet,Et=async function(s,e){let r=!1,i=s;do r=!1,await this.callBatchWithTimeout(i,async a=>{var u,n;let c=!1;const l=new Set;for(const[f,d]of Object.entries(a||{})){if(!(d!=null&&d.error)||!d.error())continue;const A=((n=(u=d.error())==null?void 0:u.ex)==null?void 0:n.error)??"";if(A==="TIMEOUT"){c=!0;break}["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT"].includes(A)&&l.add(f)}if(c){r=!0,await O(this,V,ut).call(this);return}if(l.size>0){const f={};for(const[A,h]of Object.entries(a||{}))l.has(A)||(f[A]=h);Object.keys(f).length&&await e(f);const d={};for(const A of l)i[A]&&(d[A]=i[A]);i=d,Object.keys(i).length&&(r=!0,await O(this,V,ut).call(this));return}await e(a)});while(r)},kt=new WeakSet,ce=function(s,e){return new Promise(r=>{if(typeof this.callMethod!="function"){r(null);return}let i=!1;const a=setTimeout(()=>{i||(i=!0,r(null))},this.requestTimeoutMs);try{this.callMethod(s,e,c=>{i||(i=!0,clearTimeout(a),r(c))})}catch{i||(i=!0,clearTimeout(a),r(null))}})},dt=new WeakSet,Qt=function(s){this.clearProgressData(),this.progressCall=typeof s=="function"?s:"",this.canContinue=!0,this.result={},this.errors={},this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.setTimeLimitState(!1,void 0)},L(q,Rt,5),L(q,Lt,5),L(q,St,8),L(q,It,.65);let z=q;class jt{constructor(){L(this,it,{})}get hash(){return this.createHash(8)}createHash(s){let e="abcdefghijklmnopqrstuvwxyz0123456789",r="";s=s||6;for(let i=0;i<s;i++)r+=e.charAt(Math.floor(Math.random()*e.length));return r}actionFilter({keyTimer:s,duration:e=10,action:r}){M(this,it)[s]&&(clearTimeout(M(this,it)[s]),M(this,it)[s]=null),r&&(M(this,it)[s]=setTimeout(()=>{r()},e))}async noSleep(){let s=document.createElement("video");s.classList.add("no-sleep"),s.muted=!0,s.autoplay=!0,s.setAttribute("playsinline",""),s.addEventListener("loadeddata",()=>{s.style.position="fixed",s.style.left="-9999px",document.querySelector("body").append(s),s.play().catch(e=>{console.warn("noSleep: autoplay prevented",e)})}),s.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{s.play().catch(e=>{console.warn("noSleep: replay prevented",e)})}})}),s.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(s,e){let r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=i,a.download=`${e}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(i)},200)}}it=new WeakMap;const Jt=new jt;class se{constructor(){L(this,Bt);L(this,yt);L(this,wt);L(this,Ct);L(this,Ht);L(this,Q,"logger");L(this,Z,!1);L(this,nt,new Map);L(this,ct,{});L(this,gt,!1);L(this,$,null);L(this,J,null);L(this,at,!1);L(this,lt,!1);P(this,"periodClear",3)}async init(){try{let s=new z(BX24.callBatch),{entityList:e}=await s.batch({entityList:{method:"entity.get"}});if(e&&Array.isArray(e))if(e.find(i=>i.ENTITY==M(this,Q)))j(this,Z,!0);else{let{entityAdd:i}=await s.batch({entityAdd:{method:"entity.add",params:{ENTITY:M(this,Q),NAME:M(this,Q),ACCESS:{AU:"X"}}}});i&&j(this,Z,!0)}return M(this,Z)}catch(s){return console.error("Ошибка при инициализации логера:",s),!1}}enableBackworkerMode(){return j(this,Z,!0),!0}start({type:s,data:e}){if(!M(this,Z))return O(this,yt,Zt).call(this,"entity"),null;if(!s||!e)return console.error("Невалидные данные для логирования:",{type:s,data:e}),null;const r=Jt.hash,i={type:s,data:e,userInfo:null,errorList:{},status:"",answer:null,date:new Date().getTime()};return M(this,nt).set(r,i),j(this,lt,!0),r}async stop({key:s,errorList:e,status:r,answer:i}){var c;if(!M(this,lt))return;if(!M(this,Z)){O(this,yt,Zt).call(this,"entity");return}let a=M(this,nt).get(s);if(!a){console.error(`Не найдены данные логирования для ключа: ${s}`);return}e&&(a.errorList=e),r&&(a.status=r),i&&(a.answer=i),await O(this,Bt,le).call(this),a.userInfo=M(this,ct),await O(this,wt,he).call(this),(c=a==null?void 0:a.data)!=null&&c.updateList&&j(this,at,!0),j(this,lt,!1)}async getEntityList(s){var e;try{if((e=M(this,J))!=null&&e.length&&!M(this,at))return M(this,J);let r=new z(BX24.callBatch),{entityList:i}=await r.batch({entityList:{method:"entity.item.get",params:{ENTITY:M(this,Q),SORT:{ID:"DESC"}}}},s);return!i||!Array.isArray(i)?(console.warn("Получен невалидный список записей"),[]):(i=i.map(a=>{try{const{ID:c,DATE_CREATE:l,DETAIL_TEXT:u}=a;return{...JSON.parse(u),id:c,dateCreate:l}}catch(c){return console.error(`Ошибка парсинга записи ${a.ID}:`,c),null}}).filter(a=>a!==null),j(this,at,!1),j(this,J,i),i)}catch(r){return console.error("Ошибка при получении списка записей:",r),[]}}runStorageMaintenance(){return O(this,Ct,ue).call(this)}async downAllEntityJson(){try{if(M(this,J)||await this.getEntityList(),!M(this,J)||M(this,J).length===0)return console.warn("Нет данных для выгрузки"),!1;let s=mt().format("%Y-%m-%d");return Jt.downloadFileJson(M(this,J),`sdklogger-entity-data__${s}`),!0}catch(s){return console.error("Ошибка при выгрузке данных в JSON:",s),!1}}}Q=new WeakMap,Z=new WeakMap,nt=new WeakMap,ct=new WeakMap,gt=new WeakMap,$=new WeakMap,J=new WeakMap,at=new WeakMap,lt=new WeakMap,Bt=new WeakSet,le=async function(){if(!M(this,gt))return M(this,$)?M(this,$):(j(this,$,(async()=>{try{const s=new z(BX24.callBatch),e=BX24.isAdmin(),{curUser:r}=await s.batch({curUser:{method:"user.current"}});j(this,ct,{isAdmin:e,curUser:r})}catch(s){console.error("Ошибка при получении информации о пользователе:",s),j(this,ct,{isAdmin:!1,curUser:null})}finally{j(this,gt,!0),j(this,$,null)}})()),M(this,$))},yt=new WeakSet,Zt=function(s){s=="entity"&&Jt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},wt=new WeakSet,he=async function(){try{let s={},e=new z(BX24.callBatch);for(let[r,i]of M(this,nt).entries())if(i.status){const a=JSON.stringify(i);s[r]={method:"entity.item.add",params:{ENTITY:M(this,Q),NAME:M(this,Q),DETAIL_TEXT:a}}}if(Object.keys(s).length){let r=await e.batch(s),{errors:i}=e;for(let[a,c]of Object.entries({...r,...i}))M(this,nt).delete(a);return!0}return!1}catch(s){return console.error("Ошибка при добавлении записей в хранилище:",s),!1}},Ct=new WeakSet,ue=async function(){try{let s=new z(BX24.callBatch),{serverTime:e}=await s.batch({serverTime:{method:"server.time"}});if(!e){console.error("Не удалось получить время сервера");return}if(M(this,J)||await this.getEntityList(),!M(this,J)||M(this,J).length===0)return;let r=M(this,J).filter(i=>{try{let{dateCreate:a}=i;return a?mt(new Date(a)).between(mt(new Date(e)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});r.length>0&&(console.log(`Найдено ${r.length} записей для очистки (старше ${this.periodClear} месяцев)`),await O(this,Ht,fe).call(this,r))}catch(s){console.error("Ошибка при проверке периода очистки:",s)}},Ht=new WeakSet,fe=async function(s){try{if(!s||s.length===0)return!1;let e=new z(BX24.callBatch),r=s.filter(a=>a&&a.id).map(a=>{let{id:c}=a;return{method:"entity.item.delete",params:{ENTITY:M(this,Q),ID:c}}});if(r.length===0)return!1;const i=await e.batch(r);return console.log(`Успешно удалено ${r.length} записей`),j(this,at,!0),i}catch(e){return console.error("Ошибка при очистке устаревших записей:",e),!1}};function Kt(T){if(!T||typeof T!="string")return"";try{const s=new URL(T);s.search="",s.hash="";let e=s.toString();return e.endsWith("/")&&s.pathname!=="/"&&(e=e.slice(0,-1)),e}catch{return T.split("?")[0].split("#")[0].replace(/\/$/,"")}}function re(T){return!T||typeof T!="string"?!1:T.toLowerCase().includes("/marketplace/app")}function _e(){var s;if(typeof window>"u"||!((s=window.location)!=null&&s.href))return"";const T=Kt(window.location.href);return re(T)?"":T}function vt(T){if(!(T!=null&&T.appConst)||typeof T.appConst!="object")return"";const s=_e();return s?(T.appConst.pathApp=s,s):Kt(T.appConst.pathApp??"")}class Te{constructor(s){L(this,ht);L(this,Ut);L(this,pt);L(this,Gt);L(this,Pt);L(this,Yt);L(this,tt);L(this,Nt);L(this,Wt);L(this,Ot);L(this,xt);P(this,"domain","");P(this,"isAdmin",!1);P(this,"appInfo",null);P(this,"appConst",null);P(this,"userInfo",null);P(this,"placeData",null);P(this,"placeInfo",null);P(this,"logger",!1);P(this,"timeLimit",{limit:!1,date:void 0,pauseMs:void 0});P(this,"batchClient",null);this.appConst=s}subscribeTimeLimit(s){return O(this,ht,Xt).call(this).subscribeTimeLimit(s)}init(){return new Promise((s,e)=>{const i=setTimeout(()=>{clearInterval(a);const c=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(c),e(c)},3e4);let a=setInterval(()=>{window.BX24&&BX24.init(async()=>{clearInterval(a),clearTimeout(i),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info();const c=O(this,Gt,de).call(this);if(console.info(c?"init BX24 (background worker)":"init BX24"),this.appInfo=await O(this,Pt,ge).call(this),this.userInfo=await O(this,Yt,ye).call(this),vt(this),c)await O(this,pt,Vt).call(this,!1,{skipInit:!0});else{await O(this,pt,Vt).call(this,!0);const l=new jt;try{l.noSleep()}catch(u){console.warn("Failed to initialize noSleep:",u)}}s({isBackworker:c})})},100)})}userOption(s,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(s,e):BX24.userOption.get(s)}appOption(s,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(s,e):BX24.appOption.get(s)}async call({method:s,params:e,updateList:r}){let i;if(r&&(i=this.logger.start({type:"call",data:{method:s,params:e,updateList:r}})),e||(e={}),typeof BX24>"u"||!BX24.callMethod){const l=new Error("BX24 is not initialized");throw console.error(l),l}const c=await O(this,ht,Xt).call(this).call({method:s,params:e});return c.success?(await O(this,tt,ft).call(this,i,{answer:c.answer,status:"success"}),c.data):(console.error(c.error),await O(this,tt,ft).call(this,i,{answer:c.answer,status:"fail",errorList:{0:c.error||"Unknown call error"}}),!1)}async batch(s,e,{errorCall:r,updateList:i,batchOptions:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const c=new Error("BX24 is not initialized");return console.error(c),!1}return O(this,Nt,$t).call(this,{mode:"batch",commandList:s,progressCall:e,errorCall:r,updateList:i,batchOptions:a})}async batchTotalCount(s,e,{errorCall:r,updateList:i}={}){if(typeof BX24>"u"||!BX24.callBatch){const a=new Error("BX24 is not initialized");return console.error(a),!1}return O(this,Nt,$t).call(this,{mode:"batch-total-count",commandList:s,progressCall:e,errorCall:r,updateList:i})}async getPlacement(){const s=await this.call({method:"placement.get"});return this.placeData||(this.placeData=s),s}async placementBind(s){var A;if(!this.isAdmin||(this.placeData=await this.getPlacement(),!this.placeData))return;const{appName:e,pathApp:r}=this.appConst;let i=O(this,Ot,te).call(this,s);i=i.filter(h=>h.placement!=="PAGE_BACKGROUND_WORKER"&&h.placement!=="PAGE_BACKGROUND_WORKER_ALL");const a=O(this,xt,Ne).call(this,r),c=new Set(i.map(h=>h.placement));for(const h of a)c.has(h.placement)||i.push({placement:h.placement});if(i.length===0)return;let l=e;this.domain==="szdl.bitrix24.ru"&&((A=this.appInfo)!=null&&A.ID)&&(l=`${e}: #${this.appInfo.ID}`);const u=l.replace(" CRM",""),n={},f=[],d=new Map;for(const h of this.placeData)d.has(h.placement)||d.set(h.placement,[]),d.get(h.placement).push(h);for(let h=0;h<i.length;h++){const N=i[h].placement,_=d.get(N)||[];if(_.some(y=>y.handler===r))continue;const R=_.filter(y=>y.handler!==r);for(const y of R)f.push({placement:N,handler:y.handler});n[`bind_${h}`]={method:"placement.bind",params:{PLACEMENT:N,HANDLER:r,LANG_ALL:{ru:{TITLE:N==="USER_PROFILE_TOOLBAR"?u:l}},OPTIONS:{errorHandlerUrl:r}}}}f.length>0&&await this.placementUnBind(f),Object.keys(n).length>0&&(await this.batch(n),this.placeData=await this.getPlacement(),Object.values(n).forEach(h=>{console.log("Приложение успешно встроено в",h.params.PLACEMENT)}))}async placementUnBind(s){let e=O(this,Ot,te).call(this,s);if(e=e.filter(i=>i.placement!=="PAGE_BACKGROUND_WORKER"&&i.placement!=="PAGE_BACKGROUND_WORKER_ALL"),e.length===0)return;const r={};for(let i=0;i<e.length;i++){const a={PLACEMENT:e[i].placement};e[i].handler&&(a.HANDLER=e[i].handler),r[`unbind_${i}`]={method:"placement.unbind",params:a}}await this.batch(r),e.forEach(i=>{console.log("Встройка отвязана",i.placement)})}async getBotList(){const s=await this.call({method:"imbot.bot.list",params:{}}),e=Object.values(s);return console.log("chat-bot list:",e),e}async regBot({code:s,type:e,name:r}){const{appName:i,pathApp:a,chatBotLogo:c}=this.appConst,l=this.appInfo.ID,u=await this.call({method:"imbot.register",params:{CODE:s??this.appInfo.CODE,TYPE:e??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${r??i} - бот #${l}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:mt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:c??""}}});return console.log("Чат-бот добавлен",u),u}async unRegBot(s){const e=await this.call({method:"imbot.unregister",params:{BOT_ID:s}});return console.log("чат-бот удален",e),e}getLoggerList(s){return this.logger.getEntityList(s)}}ht=new WeakSet,Xt=function(){return this.batchClient||(this.batchClient=new z({callBatch:BX24.callBatch,callMethod:BX24.callMethod}),this.timeLimit=this.batchClient.timeLimit),this.batchClient},Ut=new WeakSet,me=function(){return{start:()=>{},stop:()=>{},getEntityList:()=>{}}},pt=new WeakSet,Vt=async function(s,{skipInit:e=!1}={}){this.logger?(this.logger=new se,e?this.logger.enableBackworkerMode():await this.logger.init(),s&&typeof this.logger.runStorageMaintenance=="function"&&this.logger.runStorageMaintenance()):this.logger=O(this,Ut,me).call(this)},Gt=new WeakSet,de=function(){var r,i,a;const s=(r=this.placeInfo)==null?void 0:r.placement,e=(a=(i=this.placeInfo)==null?void 0:i.options)==null?void 0:a.ID;return s==="PAGE_BACKGROUND_WORKER"||e==="PAGE_BACKGROUND_WORKER"},Pt=new WeakSet,ge=function(){return this.call({method:"app.info"})},Yt=new WeakSet,ye=function(){return this.call({method:"user.current"})},tt=new WeakSet,ft=async function(s,e){if(s)try{await this.logger.stop({key:s,...e})}catch(r){console.error("Logger error:",r)}},Nt=new WeakSet,$t=async function({mode:s,commandList:e,progressCall:r,errorCall:i,updateList:a,batchOptions:c}){const l=O(this,ht,Xt).call(this),u=a?this.logger.start({type:s,data:s==="batch"?{commandList:e,updateList:a}:{commandList:e}}):void 0;try{const n=s==="batch"?await l.batch(e,r,c):await l.batchTotalCount(e,r),f=O(this,Wt,pe).call(this,l,n,e,a);return Object.keys(f).length?(i&&i(f),await O(this,tt,ft).call(this,u,{status:"fail",errorList:f})):await O(this,tt,ft).call(this,u,{status:"success"}),n}catch(n){return await O(this,tt,ft).call(this,u,{status:"fail-runtime",errorList:{0:n==null?void 0:n.toString()}}),console.error(n),!1}},Wt=new WeakSet,pe=function(s,e,r,i){let a={...s.errors};if(Object.values(s.errors).some(l=>{if(typeof l!="string")return!1;const u=l.toUpperCase();return u==="TIMEOUT"||u==="OPERATION_TIME_LIMIT"||u.includes("TIMEOUT")||u.includes("OPERATION_TIME_LIMIT")})&&i){const l=e?Object.keys(e).filter(d=>d!=="errorsList"):[],u=new Set(Object.keys(s.errors||{})),n=new Set;if(e){for(const d of l)if(!u.has(d)){const A=e[d];A!=null&&n.add(d)}}const f=Object.values(s.errors).find(d=>{if(typeof d!="string")return!1;const A=d.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const d of Object.keys(r))!n.has(d)&&!s.errors[d]&&(a[d]=f||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a},Ot=new WeakSet,te=function(s){if(!s)return[];let e=[];return Array.isArray(s)?e=s.map(r=>typeof r=="string"?{placement:r}:r):typeof s=="string"?e=[{placement:s}]:e=[s],e},xt=new WeakSet,Ne=function(s){return this.placeData?this.placeData.filter(e=>!(e.placement==="PAGE_BACKGROUND_WORKER"||!e.handler||e.handler.includes(s))):[]};const ie="szdl-utils-kit|";function Ee(){if(typeof sessionStorage>"u")return`ephemeral-${Date.now()}-${Math.random().toString(16).slice(2)}`;let T=sessionStorage.getItem("szdl-cross-tab-instance-id");return T||(T=`${Date.now()}-${Math.random().toString(16).slice(2)}`,sessionStorage.setItem("szdl-cross-tab-instance-id",T)),T}function be(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}const zt=new Map;function Re(T="default"){if(typeof BroadcastChannel>"u")return null;const s=`${ie}bc:${T}`;return zt.has(s)||zt.set(s,new BroadcastChannel(s)),zt.get(s)}function ne(T,s){const e=Re(T);if(e)try{const r=s&&typeof s=="object"&&!Array.isArray(s)?s:{data:s};e.postMessage({...r,tabId:Ee(),ts:Date.now()})}catch{}}async function Le(T,s,e={}){const{ifAvailable:r=!1}=e,i=typeof T=="string"&&T.length>0?T:"default",a=`${ie}${i}`;return be()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!r},async c=>{if(r&&c==null)return{skipped:!0,coordination:"locks"};ne(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await s(),coordination:"locks"}}finally{ne(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await s(),coordination:"none"}}class Se{constructor(s){L(this,_t);P(this,"entityName","tabs");P(this,"maxTabs",20);P(this,"tabList",[]);P(this,"id",0);P(this,"hasStarted",!1);P(this,"heartbeat");P(this,"runHeartbeat");P(this,"activeMaxPause",10*1e3);P(this,"quickCleanupThreshold",2*60*1e3);P(this,"pollInterval",6*1e3+Math.floor(Math.random()*2e3));P(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);P(this,"continueCondition");P(this,"defaultContinueBackground",()=>!0);var c,l,u;if(!s){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:e,bx:r,users:i,continueBackground:a}=s;this.bx=r,this.appInit=e,this.users=i,vt(r),this.appPath=O(this,_t,ee).call(this,((c=r==null?void 0:r.appConst)==null?void 0:c.pathApp)??""),this.appName=((l=r==null?void 0:r.appConst)==null?void 0:l.appName)??"",this.appCodeName=((u=r==null?void 0:r.appConst)==null?void 0:u.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(),r=e&&+this.id==+e;await this.updateTabState(r),r&&!this.hasStarted&&await this.runAsLeader()}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var s;if(typeof BX24>"u"||!((s=BX24.placement)!=null&&s.info))return!1;try{const e=BX24.placement.info(),r=e==null?void 0:e.placement,i=(e==null?void 0:e.options)||{},a=(i==null?void 0:i.URI)||"",c=r==="PAGE_BACKGROUND_WORKER"||(i==null?void 0:i.ID)==="PAGE_BACKGROUND_WORKER",l=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!c||l}catch{return!1}}async checkEntity(){var r;const s=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((r=s==null?void 0:s.find)==null?void 0:r.call(s,i=>i.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 s=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(s)||!s.length?[]:s.map(e=>{if(!e)return{id:void 0,data:void 0};try{const r=JSON.parse(e.DETAIL_TEXT);return{id:+e.ID||0,data:r}}catch(r){return console.log("BackgroundWorker: parse tab error",r),{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 s={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId},e=await this.safeCall(()=>{var r;return this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(s)}})})||0;return this.id=+e||0,this.id}async updateTabState(s){if(!this.id)return;const e={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:s,sessionId:this.sessionId};await this.safeCall(()=>{var r;return this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(e)}})})}async deleteTabs(s=[]){if(!s.length)return;const e=s.map(r=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:r.id}}));await this.safeCall(()=>this.bx.batch(e))}async checkPlacementType(){var s,e;try{if(!((s=this.bx)!=null&&s.isAdmin))return!0;const r=await this.safeCall(()=>this.bx.getPlacement());if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),a=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),c=!a;if(!i)return!0;let l=!1;for(const u of r){if(u.placement!=="PAGE_BACKGROUND_WORKER"||!(u.userId||u.handler&&u.handler.includes("USER_ID=")))continue;const f=u.userId||(u.handler?this.extractUserIdFromHandler(u.handler):null);if(f&&+f===i){l=!0;break}}return a?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):c&&l?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}isIndividualPlacement(s){return!s||typeof s!="string"?!1:s.includes("USER_ID=")}extractUserIdFromHandler(s){if(!s||typeof s!="string")return null;const e=s.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(s){return console.error("BackgroundWorker: Ошибка в continueCondition",s),!1}}async refreshTabs(s=!1,e=this.activeMaxPause){const r=[],i=[],a=Date.now(),c=await this.getTabs();for(const l of c){if(!(l!=null&&l.data)){r.push(l);continue}if(a-new Date(l.data.lastActive||0).getTime()>e){r.push(l);continue}i.push(l)}return s&&r.length&&await this.deleteTabs(r),this.tabList=i,i}selectLeaderId(){var e;return this.tabList.length&&+((e=[...this.tabList].sort((r,i)=>{var l,u,n,f;const a=new Date(((l=r.data)==null?void 0:l.createdAt)||((u=r.data)==null?void 0:u.lastActive)||0).getTime(),c=new Date(((n=i.data)==null?void 0:n.createdAt)||((f=i.data)==null?void 0:f.lastActive)||0).getTime();return a===c?(+r.id||0)-(+i.id||0):a-c})[0])==null?void 0:e.id)||0}async runAsLeader(){var i,a;const s=String(((a=(i=this.bx)==null?void 0:i.userInfo)==null?void 0:a.ID)??"0"),e=`background-worker:${this.entityName}:${s}`;(await Le(e,async()=>{this.hasStarted=!0;const c=Math.min(this.activeMaxPause-1500,Math.max(2500,Math.floor(this.pollInterval/2)));this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(l=>console.error("BackgroundWorker: heartbeat update failed",l))},c);try{await this.appInit()}catch(l){console.error("BackgroundWorker: appInit failed",l)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)},{ifAvailable:!0})).skipped&&console.log("BackgroundWorker: runAsLeader пропущен — Web Lock у другой вкладки (тот же фоновый воркер)")}async setBackgroundWorkerAll(){var R,y,S,U;if(!((R=this.bx)!=null&&R.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(y=this.users)!=null&&y.length||await this.getEntityData(),vt(this.bx);const s=O(this,_t,ee).call(this,((U=(S=this.bx)==null?void 0:S.appConst)==null?void 0:U.pathApp)??"");if(!s){console.error("BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена");return}const e=await this.safeCall(()=>this.bx.getPlacement()),r=new Map,i=new Map;let a=null;(e||[]).forEach(p=>{if(p.placement!=="PAGE_BACKGROUND_WORKER")return;if(p.userId||p.handler&&p.handler.includes("USER_ID=")){const E=p.userId||(p.handler?this.extractUserIdFromHandler(p.handler):null);if(E){const w=+E;r.set(w,p),i.has(w)||i.set(w,[]),i.get(w).push(p)}}else a=p});const c=await this.resolveAdmins(),l=await this.getEligibleUsersForBackgroundWorker(c);l.sort((p,I)=>{const E=p.LAST_LOGIN?new Date(p.LAST_LOGIN):new Date(0);return(I.LAST_LOGIN?new Date(I.LAST_LOGIN):new Date(0))-E});const u=10,n=l.slice(0,u),f=n.filter(p=>{const I=r.get(+p.ID);if(!I)return!0;const E=`${s}?USER_ID=${p.ID}/`;return I.handler!==E}),d=[];for(const[p]of r){const I=+p||0;l.find(w=>+w.ID===I)||d.push(I)}for(const p of n){const I=r.get(+p.ID);if(!I)continue;const E=`${s}?USER_ID=${p.ID}/`;I.handler!==E&&d.push(+p.ID)}const A=[],h=[...new Set(d)];for(const p of h){const I=i.get(+p)||[];for(const E of I)E!=null&&E.handler&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:E.handler}})}const N=a&&(f.length>0||a.handler!==`${s}`);N&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:a.handler||`${s}`}});for(const p of f)A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${s}?USER_ID=${p.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${s}?USER_ID=${p.ID}/`},USER_ID:p.ID}});(!a||N)&&A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${s}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${s}`}}});const _=A.filter(p=>p.method==="placement.unbind"),b=A.filter(p=>p.method==="placement.bind");_.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(_.map((p,I)=>[`unbind_${I}`,p])))),b.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(b.map((p,I)=>[`bind_${I}`,p])))),A.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var s,e;try{const r=+(((s=this.bx.userInfo)==null?void 0:s.ID)??0),i=!!((e=this.bx)!=null&&e.isAdmin),a=await this.getAdminsList()||[];if(!i){if(r&&a.includes(+r)){const u=a.filter(n=>+n!=+r);return await this.saveAdminsList(u),u}return a}const c=new Set([...a||[]]);r&&c.add(+r);const l=[...c].filter(Boolean);return await this.saveAdminsList(l),l}catch(r){return console.error("BackgroundWorker: resolveAdmins error",r),[]}}async getEligibleUsersForBackgroundWorker(s=[]){const e=(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0),r=s.map(i=>+i||0).filter(Boolean);return e.filter(i=>r.includes(+i.ID||0))}async saveAdminsList(s=[]){try{BX24.appOption.set("adminsList",JSON.stringify(s))}catch(e){console.error("BackgroundWorker: saveAdminsList error",e)}}async getAdminsList(){try{const s=BX24.appOption.get("adminsList"),e=s?JSON.parse(s):[];return Array.isArray(e)?e.map(r=>+r||0).filter(Boolean):[]}catch(s){return console.error("BackgroundWorker: getAdminsList error",s),[]}}async getEntityData(){const s={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:e}=await this.safeCall(()=>this.bx.batch(s).then(r=>r?(Array.isArray(r.users)||(r.users=[]),r):{users:[]}));this.users=e}async ensureAdminPlacements(){var s,e;(s=this.bx)!=null&&s.isAdmin&&((e=this.users)!=null&&e.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(s=500,e){return new Promise(r=>{setTimeout(()=>{e&&e(),r(!0)},s)})}async safeCall(s){try{return await s()}catch(e){console.error("BackgroundWorker: safeCall error",e);return}}}_t=new WeakSet,ee=function(s){if(!s||typeof s!="string")return"";const e=Kt(s).replace(/\/+$/,"");return e?re(e)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):e:""},B.BackgroundWorker=Se,B.Batch=z,B.BxBoot=Te,B.BxHelper=jt,B.BxLogger=se,B.tempus=mt,Object.defineProperty(B,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
var Ie=Object.defineProperty;var Me=(B,C,Y)=>C in B?Ie(B,C,{enumerable:!0,configurable:!0,writable:!0,value:Y}):B[C]=Y;var P=(B,C,Y)=>(Me(B,typeof C!="symbol"?C+"":C,Y),Y),qt=(B,C,Y)=>{if(!C.has(B))throw TypeError("Cannot "+Y)};var M=(B,C,Y)=>(qt(B,C,"read from private field"),Y?Y.call(B):C.get(B)),L=(B,C,Y)=>{if(C.has(B))throw TypeError("Cannot add the same private member more than once");C instanceof WeakSet?C.add(B):C.set(B,Y)},j=(B,C,Y,ot)=>(qt(B,C,"write to private field"),ot?ot.call(B,Y):C.set(B,Y),Y);var O=(B,C,Y)=>(qt(B,C,"access private method"),Y);(function(B,C){typeof exports=="object"&&typeof module<"u"?C(exports):typeof define=="function"&&define.amd?define(["exports"],C):(B=typeof globalThis<"u"?globalThis:B||self,C(B["szdl-utils-kit"]={}))})(this,function(B){var bt,ae,Rt,Lt,St,It,At,Ft,Mt,oe,Dt,Ae,V,ut,st,Tt,rt,Et,kt,ce,dt,Qt,it,Q,Z,nt,ct,gt,$,J,at,lt,Bt,le,yt,Zt,wt,he,Ct,ue,Ht,fe,ht,Xt,Ut,me,pt,Vt,Gt,de,Pt,ge,Yt,ye,tt,ft,Nt,$t,Wt,pe,Ot,te,xt,Ne,_t,ee;"use strict";var C=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Y(b){return b&&b.__esModule&&Object.prototype.hasOwnProperty.call(b,"default")?b.default:b}var ot={exports:{}};(function(b,s){(function(e){Array.prototype.indexOf||(Array.prototype.indexOf=function(t,o){var m,g;for(m=o||0,g=this.length;m<g;m+=1)if(this[m]===t)return m;return-1});var r=this,i=function(t,o){for(var m=t.toString();m.length<o;)m="0"+m;return m},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},c=function(t,o){var m,g="";return m=t.slice(o,o+1),m!==""&&!isNaN(Number(m))&&(g+="%H"),m=t.charAt(o+2),m!==""&&m===":"&&(g+=m),m=t.slice(o+3,o+4),m!==""&&!isNaN(Number(m))&&(g+="%M"),m=t.charAt(o+5),m!==""&&m===":"&&(g+=m),m=t.slice(o+6,o+7),m!==""&&!isNaN(Number(m))&&(g+="%S"),g},l=function(t,o){var m,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)],H;return!isNaN(Number(g[0]))&&!isNaN(Number(g[2]))&&!isNaN(Number(g[4]))?(g[1]==="."&&g[3]==="."?m="%d.%m.%Y":g[1]==="-"&&g[3]==="-"?m="%m-%d-%Y":g[1]==="/"&&g[3]==="/"&&(m="%m/%d/%Y"),m):(H=[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(H[0]))&&!isNaN(Number(H[2]))&&!isNaN(Number(H[4]))?(H[1]==="-"&&H[3]==="-"&&(m="%Y-%m-%d"),m):"")},u=r.tempus,n,f,d=r.navigator||{},A="en",h={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[h[A].JANUARY_LONG,h[A].FEBRUARY_LONG,h[A].MARCH_LONG,h[A].APRIL_LONG,h[A].MAY_LONG,h[A].JUNE_LONG,h[A].JULY_LONG,h[A].AUGUST_LONG,h[A].SEPTEMBER_LONG,h[A].OCTOBER_LONG,h[A].NOVEMBER_LONG,h[A].DECEMBER_LONG]},_=function(){return[h[A].JANUARY_SHORT,h[A].FEBRUARY_SHORT,h[A].MARCH_SHORT,h[A].APRIL_SHORT,h[A].MAY_SHORT,h[A].JUNE_SHORT,h[A].JULY_SHORT,h[A].AUGUST_SHORT,h[A].SEPTEMBER_SHORT,h[A].OCTOBER_SHORT,h[A].NOVEMBER_SHORT,h[A].DECEMBER_SHORT]},T=function(){return[h[A].SUNDAY_LONG,h[A].MONDAY_LONG,h[A].TUESDAY_LONG,h[A].WEDNESDAY_LONG,h[A].THURSDAY_LONG,h[A].FRIDAY_LONG,h[A].SATURDAY_LONG]},S=function(){return[h[A].SUNDAY_SHORT,h[A].MONDAY_SHORT,h[A].TUESDAY_SHORT,h[A].WEDNESDAY_SHORT,h[A].THURSDAY_SHORT,h[A].FRIDAY_SHORT,h[A].SATURDAY_SHORT]},y,E,U,p,I=function(t,o,m){var g;r.XMLHttpRequest?g=new XMLHttpRequest:g=new ActiveXObject("Microsoft.XMLHTTP"),g.onreadystatechange=function(){g.readyState===4&&(g.status===200?o&&(r.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))):m&&m(g))},g.open("GET",t,!1),g.send()},R={"%d":{format:function(t){return i(t.day()||n.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 i(t.month()||n.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 i(t.year()||n.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()||n.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(t){var o=t.dayOfWeek();return p[o!==e?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var o=t.dayOfWeek();return U[o!==e?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(t){var o=n.options("monthFromZero")?t.month():t.month()-1;return E[o!==e?o:n.MIN_MONTH]},parse:function(t){var o=n.monthNames().indexOf(t)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var o=n.options("monthFromZero")?t.month():t.month()-1;return y[o!==e?o:n.MIN_MONTH]},parse:function(t){var o=n.monthNames(!0).indexOf(t)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(t){return i(t.hours()||n.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 i(t.minutes()||n.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 i(t.seconds()||n.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))?{}:n(Number(t)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(t){return i(t.year()||n.MIN_YEAR,4)+"-"+i(t.month()||n.MIN_MONTH,2)+"-"+i(t.day()||n.MIN_DAY,2)},parse:function(t){var o=Number(t.slice(0,4)),m=Number(t.slice(5,7)),g=Number(t.slice(8,10));return{year:o,month:m,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return i(t.month()||n.MIN_MONTH,2)+"/"+i(t.day()||n.MIN_DAY,2)+"/"+i(t.year()||n.MIN_YEAR,4)},parse:function(t){var o=Number(t.slice(0,2)),m=Number(t.slice(3,5)),g=Number(t.slice(6,10));return{year:g,month:o,day:m}},minLength:10,maxLength:10,type:"string"}},w={useMilliseconds:!1,monthFromZero:!1},k;k=function(t,o,m){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,m),this},k.fn=k.prototype,k.fn.dayCount=function(){var t=this.month(),o=n.MAX_DAY_IN_MONTHS[t-(n.options("monthFromZero")?0:1)];return this.leapYear()&&t===(n.options("monthFromZero")?1:2)&&(o+=1),o},k.fn.year=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_YEAR&&Number(t)<=n.MAX_YEAR?(this._d.setFullYear(Number(t)),this._i.year=!1):this._i.year=Number(t):(this._d.setFullYear(n.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},k.fn.month=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MONTH&&Number(t)<=n.MAX_MONTH?(this._d.setMonth(n.options("monthFromZero")?Number(t):Number(t)-1),this._i.month=!1):this._i.month=Number(t):(this._d.setMonth(n.options("monthFromZero")?n.MIN_MONTH:n.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?n.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},k.fn.day=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_DAY&&Number(t)<=this.dayCount()?(this._d.setDate(Number(t)),this._i.day=!1):this._i.day=Number(t):(this._d.setDate(n.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},k.fn.hours=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_HOURS&&Number(t)<=n.MAX_HOURS?(this._d.setHours(Number(t)),this._i.hours=!1):this._i.hours=Number(t):(this._d.setHours(n.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},k.fn.minutes=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MINUTES&&Number(t)<=n.MAX_MINUTES?(this._d.setMinutes(Number(t)),this._i.minutes=!1):this._i.minutes=Number(t):(this._d.setMinutes(n.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},k.fn.seconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_SECONDS&&Number(t)<=n.MAX_SECONDS?(this._d.setSeconds(Number(t)),this._i.seconds=!1):this._i.seconds=Number(t):(this._d.setSeconds(n.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},k.fn.milliseconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MILLISECONDS&&Number(t)<=n.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(t)),this._i.milliseconds=!1):this._i.milliseconds=Number(t):(this._d.setMilliseconds(n.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},k.fn.week=function(){var t=new Date(this.year(),0,1),o=n(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-t.getTime())/864e5+t.getDay()+1)/7)},k.fn.set=function(t,o,m){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*(n.options("useMilliseconds")?1:1e3)),this;if(typeof t=="object"&&(t instanceof Array?(this.day(n.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(n.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,H=[],D,G,et=[],X=0,K=0,W,v,x={},F;if(t===e)return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;for(o===e&&(o=n.detectFormat(t));X<o.length;){if(o.charAt(X)==="%"){if(G=o.charAt(X)+o.charAt(X+1),R[G]!==e){switch(W=0,v="",R[G].type){case"number":for(;W<R[G].maxLength&&K+W<t.length&&!isNaN(Number(t.charAt(K+W)));)v+=t.charAt(K+W),W+=1;break;case"word":for(;W<R[G].maxLength&&K+W<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(K+W));)v+=t.charAt(K+W),W+=1;break;case"string":for(;W<R[G].maxLength&&K+W<t.length;)v+=t.charAt(K+W),W+=1;break}if(W<R[G].minLength)return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;H.push(G),et.push(v),W-=1,K+=W,X+=1}}else if(t.charAt(K)!==o.charAt(X))return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;X+=1,K+=1}for(g in H)H.hasOwnProperty(g)&&R.hasOwnProperty(H[g])&&(F=R[H[g]].parse(et[g]),x={year:F.year!==e?F.year:x.year,month:F.month!==e?F.month:x.month,day:F.day!==e?F.day:x.day,hours:F.hours!==e?F.hours:x.hours,minutes:F.minutes!==e?F.minutes:x.minutes,seconds:F.seconds!==e?F.seconds:x.seconds});this.day(n.MIN_DAY),this.year(x.year),this.month(x.month),this.day(x.day),this.hours(x.hours),this.minutes(x.minutes),this.seconds(x.seconds),this.milliseconds(x.milliseconds)}return this},k.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},k.fn.timestamp=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(n.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):n.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},k.fn.utc=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(n.options("useMilliseconds")?1:1e3)),this):n.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},k.fn.dayOfWeek=function(t){if(t==="long")return U[this._d.getDay()];if(t==="short")return p[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()})},k.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}},k.fn.get=function(t){switch(t){case"Date":return new Date(this.year(),this.month()-(n.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()-(n.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()}}},k.fn.format=function(t){for(var o=0,m="",g;o<t.length;)t.charAt(o)==="%"?(g=t.charAt(o)+t.charAt(o+1),R[g]!==e?(m+=R[g].format(this),o+=1):m+="%"):m+=t.charAt(o),o+=1;return m},k.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},k.fn.errors=function(){return this._i},k.fn.between=function(t,o){var m=this.timestamp(),g=t.timestamp();switch(o){case"year":return Math.floor((g-m)/31556952);case"month":return Math.floor((g-m)/2629746);case"day":return Math.floor((g-m)/86400);case"hours":return Math.floor((g-m)/3600);case"minutes":return Math.floor((g-m)/60);case"seconds":return g-m;default:return e}},k.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},n=function(t,o,m){return new k(t,o,m)},n.MIN_YEAR=1e3,n.MAX_YEAR=3e3,n.MIN_MONTH=1,n.MAX_MONTH=12,n.MIN_DAY=1,n.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],n.MIN_DAY_OF_WEEK=0,n.MAX_DAY_OF_WEEK=6,n.MIN_HOURS=0,n.MAX_HOURS=23,n.MIN_MINUTES=0,n.MAX_MINUTES=59,n.MIN_SECONDS=0,n.MAX_SECONDS=59,n.MIN_MILLISECONDS=0,n.MAX_MILLISECONDS=999,n.VERSION="0.2.18",n.options=function(t,o){if(t===e)return w;if(w.hasOwnProperty(t)){if(o===e)return w[t];w[t]=o,t==="monthFromZero"&&(n.MIN_MONTH=o?0:1,n.MAX_MONTH=o?11:12)}return e},n.noConflict=function(){return r.tempus=u,n},n.generate=function(t){var o,m,g,H,D,G,et,X;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof k?o=t.dateFrom.utc():o=n(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof k?m=t.dateTo.utc():m=n(t.dateTo,t.formatTo!==e?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?D={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?D={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"&&(D={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?G=t.asObject===!0?{}:[]:(G=[],G.push([]),et=n(o).get()[t.groupBy]),X=function(v,x,F){return t.asObject===!0?t.format!==e?v[n(x).format(t.format)]={}:v[n(x).format("%F %H:%M:%S")]={}:t.format!==e?v.push(F?null:n(x).format(t.format)):v.push(F?null:n(x)),v},t.groupBy!==e&&t.fillNulls){var K={year:D.year?-D.year:e,month:D.month?-D.month:e,day:D.day?-D.day:e,hours:D.hours?-D.hours:e,minutes:D.minutes?-D.minutes:e,seconds:D.seconds?-D.seconds:e,milliseconds:D.milliseconds?-D.milliseconds:e};for(g=n(o).calc(K).utc();n(g).get()[t.groupBy]===et;)X(G[G.length-1],g,!0),g=n(g).calc(K).utc();if(t.groupBy==="week"){var W=n(o).dayOfWeek();for(g=n(o).dayOfWeek(0).utc();G[0].length<W&&g<o;)X(G[G.length-1],g,!0),g=n(g).calc(D).utc()}}for(;o<=m;)t.groupBy===e?X(G,o):n(o).get()[t.groupBy]===et?X(G[G.length-1],o):(G.push([]),X(G[G.length-1],o),et=n(o).get()[t.groupBy]),o=n(o).calc(D).utc();if(t.groupBy!==e&&t.fillNulls)for(H=n(m).calc(D).utc();n(H).get()[t.groupBy]===et;)X(G[G.length-1],H,!0),H=n(H).calc(D).utc();return G},n.monthNames=function(t){switch(t){case"long":return y;default:return E}},n.dayNames=function(t){switch(t){case"long":return U;default:return p}},n.lang=function(t){if(t!==e)A=t,h[A]===e&&(A="en"),y=N(),E=_(),U=T(),p=S();else return A;return e},n.availableLangs=function(){return Object.keys(h)},n.registerFormat=function(t,o,m,g,H,D){R[t]={format:o,parse:m,minLength:g,maxLength:H,type:D}},n.unregisterFormat=function(t){delete R[t]},n.detectFormat=function(t){var o,m,g;return o=l(t,0),o!==""&&(g=10),m=t.charAt(g),(m==="T"||m===" ")&&(o+=m,g+=1),o+=c(t,g),o},f={TempusDate:k},n.classes=function(t,o){if(o===e)return f[t];f[t]=o},n.loadTranslations=function(t){typeof t=="object"?h=t:typeof t=="string"&&I(t,function(o){h=o},function(o){})},A=(d.language||d.systemLanguage||d.userLanguage||"en").substr(0,2).toLowerCase(),h[A]===e&&(A="en"),y=N(),E=_(),U=T(),p=S(),b.exports&&(s=b.exports=n),s.tempus=n}).call(C)})(ot,ot.exports);var Oe=ot.exports;const mt=Y(Oe),q=class q{constructor(s){L(this,bt);L(this,At);L(this,Mt);L(this,Dt);L(this,V);L(this,st);L(this,rt);L(this,kt);L(this,dt);typeof s=="function"?(this.callBatch=s,this.callMethod=null):(this.callBatch=(s==null?void 0:s.callBatch)||null,this.callMethod=(s==null?void 0:s.callMethod)||null),this.result={},this.errors={},this.timeLimit={limit:!1,date:void 0,pauseMs:void 0},this.timeLimitListeners=new Set,this.canContinue=!0,this.progressCall="",this.progressData="",this.progressTimer="",this.lastProgressSnapshot=null,this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.filterChunkSize=50,this.limit=50,this.progressDelay=100,this.operatingThreshold=475,this.defaultPauseMs=12e4,this.callLimitPauseMs=3e4,this.requestTimeoutMs=6e4}get progressPercent(){if(!this.progressData)return{percent:0,allCount:0,allTotal:0};const s=this.totalBatchCommands||0;if(s>0&&Array.isArray(this.batchCommandKeyOrder)&&this.batchCommandKeyOrder.length&&O(this,bt,ae).call(this)){let u=0;for(const h of this.batchCommandKeyOrder){const N=this.progressData[h];if(!N)continue;const _=Number(N.total)||0,T=Number(N.count)||0;_===0&&T===0?u+=1:_>0&&(u+=Math.min(1,T/_))}const n=u/s*100;let f=Math.max(0,Math.min(100,Math.floor(n)));const d=s,A=Math.min(s,Math.floor(u));return{percent:f,allCount:A,allTotal:d}}let e=0,r=0;for(const u of Object.values(this.progressData)){const{total:n,count:f}=u;e+=n??0,r+=f??0}const i=Number(this.chunkRate)||0;let a=0;e?a=r/e*100*i+this.totalProgress:r===0&&e===0?a=i<1?this.totalProgress:100*i+this.totalProgress:a=100,a=Math.max(0,Math.min(a,100));let c=Math.floor(a);const l=Number(this.chunkRate)||0;return e>0&&r>=e&&l>=1&&(c=100),{percent:c,allCount:r,allTotal:e}}setProgressData({key:s,value:e,type:r}){var h,N;if(!this.progressCall)return;const i=this.getData(e.data()),a=Array.isArray(i)?i.length:0;let c=a;if(typeof e.total=="function"){const _=e.total();if(_!=null&&_!==""){const T=Number(_);Number.isFinite(T)&&(c=T)}}let l=1;r==="count"?(c||(c=a),l=c>0?c:a>0?a:1):i&&(l=a),this.progressData||(this.progressData={});const u=((h=this.progressData[s])==null?void 0:h.total)??0,n=((N=this.progressData[s])==null?void 0:N.count)??0,f=l+n,d=Math.max(u,c??0,f);if(this.progressData[s]={total:d,count:Math.min(f,d)},typeof document<"u"&&(document==null?void 0:document.hidden)===!0){O(this,At,Ft).call(this);return}O(this,At,Ft).call(this),this.progressTimer||(this.progressTimer=setInterval(()=>{if(!this.progressCall){this.clearProgressData();return}O(this,At,Ft).call(this);const{percent:_}=this.progressPercent;_>=100&&(clearInterval(this.progressTimer),this.progressTimer="")},this.progressDelay))}getData(s){if(s==null)return s;let e=(s==null?void 0:s.items)??(s==null?void 0:s.tasks)??(s==null?void 0:s.types)??(s==null?void 0:s.type)??(s==null?void 0:s.fields)??(s==null?void 0:s.workgroups)??s;return e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.result)&&(e=e.result),e}setTimeLimitState(s,e,r){this.timeLimit.limit=!!s,this.timeLimit.date=s?e:void 0,s&&typeof r=="number"&&r>0?this.timeLimit.pauseMs=r:this.timeLimit.pauseMs=void 0,O(this,Dt,Ae).call(this)}subscribeTimeLimit(s){return typeof s!="function"?()=>{}:(this.timeLimitListeners.add(s),s({limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs}),()=>{this.timeLimitListeners.delete(s)})}splitLargeFilters(s,e){const{method:r,params:i}=e;if(!i)return[{key:s,request:e}];const a=i.filter||i.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:s,request:e}];for(const[c,l]of Object.entries(a))if(!String(c).trim().startsWith("!")&&Array.isArray(l)&&l.length>this.filterChunkSize){const u=[];for(let n=0;n<l.length;n+=this.filterChunkSize){const f=l.slice(n,n+this.filterChunkSize),d=n===0?s:`${s}__chunk_${Math.floor(n/this.filterChunkSize)}`,A={...i};i.filter?(A.filter={...a},A.filter[c]=f):i.FILTER&&(A.FILTER={...a},A.FILTER[c]=f),u.push({key:d,request:{method:r,params:A},originalKey:s,filterKey:c,chunkIndex:Math.floor(n/this.filterChunkSize)})}return u}return[{key:s,request:e}]}mergeSplitResults(s,e){const r=[],i=String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${i}(?:__chunk_\\d+)?$`),c=Object.keys(s).filter(l=>a.test(l)).sort((l,u)=>{const n=l.match(/__chunk_(\d+)$/),f=u.match(/__chunk_(\d+)$/);return n?f?parseInt(n[1])-parseInt(f[1]):1:-1});for(const l of c){const u=s[l];Array.isArray(u)?r.push(...u):u&&r.push(u)}return r}delay(){return typeof document<"u"&&(document==null?void 0:document.hidden)===!0?Promise.resolve():new Promise(e=>setTimeout(e,500))}callBatchWithTimeout(s,e){return new Promise((r,i)=>{let a=!1,c=null;const l=async n=>{if(!a){a=!0,c&&clearTimeout(c);try{await Promise.resolve(e(n)),r()}catch(f){console.error("Error in callBatch callback:",f),i(f)}}},u=async()=>{if(!a){a=!0,c&&clearTimeout(c),console.warn(`Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`);const n={};Object.keys(s).forEach(f=>{n[f]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 60 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(e(n)),r()}catch(f){console.error("Error in timeout callback:",f),r()}}};try{this.callBatch(s,async n=>{await l(n)})}catch(n){a||console.error("Error calling callBatch:",n)}c=setTimeout(async()=>{a||(console.warn(`Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`),await u())},this.requestTimeoutMs)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.lastProgressSnapshot=null}async batch(s,e,r={}){O(this,dt,Qt).call(this,e);const i={},a={},c={};for(const[f,d]of Object.entries(s)){const A=this.arrayChunk(d);if(!A)continue;const h=this.splitLargeFilters(f,A);if(h.length===1)a[f]=A;else{c[f]=[];for(const N of h)a[N.key]=N.request,c[f].push(N.key)}}this.batchCommandKeyOrder=Object.keys(a),this.totalBatchCommands=this.batchCommandKeyOrder.length,this.batchCommandMethods=this.batchCommandKeyOrder.map(f=>{var d;return String(((d=a[f])==null?void 0:d.method)||"")}),this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let l={},u=0;const n=Object.keys(a).length;for(const[f,d]of Object.entries(a)){if(!this.canContinue)break;if(l[f]=d,Object.keys(l).length>=this.limit||u+1===n){const A=u+1===n;await this.batchChunk(l,void 0,!A,{disablePagination:!1,oneBatch:!!(r!=null&&r.oneBatch)}),Object.entries(this.result).forEach(([h,N])=>{i[h]=N}),this.totalProgress=Math.round(u/n*100),l={}}u++}for(const[f,d]of Object.entries(c))if(d&&d.length>0){const A=this.mergeSplitResults(i,f);for(const h of d)delete i[h];i[f]=A}return Object.entries(this.errors).length&&(i.errorsList=this.errors),e&&e({percent:100}),Promise.resolve(i)}async batchTotalCount(s,e){O(this,dt,Qt).call(this,e);const r={},i={},a={};for(const[u,n]of Object.entries(s)){const f=this.arrayChunk(n);if(!f)continue;const d=this.splitLargeFilters(u,f);if(d.length===1)i[u]=f;else{a[u]=[];for(const A of d)i[A.key]=A.request,a[u].push(A.key)}}const c=[],l=Object.entries(i);for(let u=0;u<l.length;u+=this.limit){const n=l.slice(u,u+this.limit),f={};for(const[d,A]of n){if(!this.canContinue)break;f[d]=A}Object.keys(f).length>0&&c.push(f)}this.chunkRate=(1/c.length).toFixed(5);for(const[u,n]of Object.entries(c)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(u)/c.length*100),this.progressData={},this.lastProgressSnapshot=null;const f=Number(u)===c.length-1;await O(this,rt,Et).call(this,n,async d=>{var A,h,N,_,T;for(const[S,y]of Object.entries(d)){if(!this.canContinue)return;if(y.error()){const R=(h=(A=y.error())==null?void 0:A.ex)==null?void 0:h.error,w=(_=(N=y.error())==null?void 0:N.ex)==null?void 0:_.error_description;this.errors[S]=R&&R.trim()||w&&w.trim()||((T=y.error())==null?void 0:T.toString())||"Неизвестная ошибка",r[S]=0;continue}const E=this.getData(y.data()),U=Array.isArray(E)?E.length:0,I=typeof y.total=="function"&&y.total()!==void 0?y.total():U;r[S]=I,this.setProgressData({key:S,value:y,type:"count"})}await O(this,st,Tt).call(this,d,!f)})}for(const[u,n]of Object.entries(a))if(n&&n.length>0){let f=0;for(const d of n)r[d]!==void 0&&(f+=r[d]||0),delete r[d];r[u]=f}return Object.entries(this.errors).length&&(r.errorsList=this.errors,this.errorLogger()),e&&e({percent:100}),Promise.resolve(r)}async call({method:s,params:e={}}){var r,i,a,c,l,u,n;for(;;){const f=await O(this,kt,ce).call(this,s,e);if(!f){await O(this,V,ut).call(this,this.callLimitPauseMs);continue}const d={};if(f!=null&&f.answer)for(const[h,N]of Object.entries(f.answer))h!=="result"&&N&&(d[h]=N);if(f.error()){const h=((i=(r=f.error())==null?void 0:r.ex)==null?void 0:i.error)??"";if(["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT","TIMEOUT"].includes(h)){await O(this,V,ut).call(this,this.callLimitPauseMs);continue}const N=((a=f.error())==null?void 0:a.toString())||((l=(c=f.error())==null?void 0:c.ex)==null?void 0:l.error_description)||((n=(u=f.error())==null?void 0:u.ex)==null?void 0:n.error)||"Неизвестная ошибка";return{success:!1,data:!1,answer:d,error:N}}let A=f.data();return A!=null&&A.items&&(A=A.items),{success:!0,data:A,answer:d,error:null}}}arrayChunk(s){let e="",r={};if(Array.isArray(s)?[e]=s:(e=s.method,r=s.params),(e.includes("list")||e==="user.get"||e==="entity.item.get")&&e!=="task.item.list"){if(!r)r=e==="entity.item.get"?{SORT:{ID:"ASC"}}:{order:{ID:"ASC",id:"ASC"}};else{e==="entity.item.get"?(r.SORT||(r.SORT={ID:"ASC"}),Array.isArray(r.select)?r.select.includes("ID")||r.select.push("ID"):r.select=["ID"]):e==="tasks.task.list"?(r.order||(r.order={}),r.order.ID="asc"):e==="user.get"?(r.sort||(r.sort="ID"),r.order||(r.order="ASC")):r.order={ID:"ASC",id:"ASC"},Array.isArray(r.select)&&!r.select.includes("ID")&&r.select.push("ID");const i=e==="user.get"||e==="entity.item.get"?r.FILTER:r.filter;typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.entries(i).forEach(([a,c])=>{(r.start===void 0||r.start!==-1)&&["id","ID"].includes(a)&&(typeof c=="string"||Array.isArray(c)&&c.length<=50)&&(r.start=-1)})}e==="crm.type.list"&&r.order&&delete r.order.ID}if(e==="task.item.list")if(!r)r=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(r[0])&&(r[0]={});const[i,a,c,l]=r;i.ID="ASC",l[0]!==""&&l.includes("ID")||l.push("ID")}return{method:e,params:r}}async batchChunk(s,e,r=!0,i={}){return new Promise(a=>{const c=[];let l;const u=!!(i!=null&&i.disablePagination);(async()=>{await O(this,rt,Et).call(this,s,async f=>{var A,h,N,_,T;for(const[S,y]of Object.entries(f)){if(!this.canContinue)return;if(y.error()){const g=(h=(A=y.error())==null?void 0:A.ex)==null?void 0:h.error,H=(_=(N=y.error())==null?void 0:N.ex)==null?void 0:_.error_description;this.errors[S]=g&&g.trim()||H&&H.trim()||((T=y.error())==null?void 0:T.toString())||"Неизвестная ошибка",l=!0}const E=this.getData(y.data()),U=Array.isArray(E)?E.length:0,p=typeof y.total=="function"&&y.total()!==void 0,I=p?y.total():U;e==="count"?this.result[S]?this.result[S]+=U:this.result[S]=I:this.result[S]=E,this.setProgressData({key:S,value:y,type:e});const R=s[S],w=Array.isArray(R)?R[0]:R==null?void 0:R.method,k=typeof w=="string"&&(w.includes(".list")||w==="user.get"||w==="entity.item.get"),t=e==="count"?!p&&U===this.limit:k?U===this.limit:I>this.limit&&I>U,o=e!=="count"&&w==="entity.item.get"&&U===this.limit&&!t,m=t||o;if(!u&&(!this.canContinue||m)){let g=s[S];if(Array.isArray(g)){const[H,D={}]=g;g=[H,D]}else{const{method:H,params:D={}}=g;g=[H,D]}c.push([S,g,I,{entityItemGetScan:o}])}}l>0&&this.errorLogger();const d=c.length>0||r;await O(this,st,Tt).call(this,f,d),c.length?await this.batchPayload(c,e,i).then(()=>a(this.result)):a(this.result)})})()})}async batchPayload(s,e,r={}){const i=!!(r!=null&&r.oneBatch),a=(N,_,T,S)=>{let y="ID";this.result[N][this.result[N].length-1].ID||(y="id");let E=`${y}`;if(JSON.stringify(S[1]).toLocaleLowerCase().includes('"id":"desc"')?E="<"+E:E=">"+E,_===1||T.length===0)return{field:E,id:this.result[N][this.result[N].length-1][y]};let p="";const[I,R]=S;return(I==="tasks.task.list"||I==="task.item.list")&&(p="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(I)&&(p="[items]"),I==="crm.type.list"&&(p="[types]"),I==="socialnetwork.api.workgroup.list"&&(p="[workgroups]"),{field:E,id:`$result[${[N,_-1].join("__")}]${p}[49][${y}]`}},c=(N,_)=>{const[T,S]=N;let y=JSON.parse(JSON.stringify(S)),E;if(T==="task.item.list"){y=[...y];const[U,p,I,R]=y;return p[_.field]=_.id,[T,y]}return["user.get"].includes(T)||y.FILTER?(y.FILTER||(y.FILTER={}),E=y.FILTER):(y.filter||(y.filter={}),E=y.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(T)?E[">ID"]=_.id:E[_.field]=_.id,[T,{...y,start:-1}]},l=N=>{Object.entries(N).forEach(([_,T])=>{var E,U,p,I,R;const[S]=_.split("__"),y=this.getData(T.data());if(Array.isArray(y)&&(e==="count"?this.result[S]+=y.length:this.result[S].push(...y)),T.error()){const w=(U=(E=T.error())==null?void 0:E.ex)==null?void 0:U.error,k=(I=(p=T.error())==null?void 0:p.ex)==null?void 0:I.error_description;this.errors[S]=w&&w.trim()||k&&k.trim()||((R=T.error())==null?void 0:R.toString())||"Неизвестная ошибка"}this.setProgressData({key:S,value:T,type:e})})},u=(N,_)=>{if(!Array.isArray(N)||N.length===0)return null;const T=N[N.length-1];let S="ID";T.ID||(S="id");let y=S;return JSON.stringify(_[1]).toLocaleLowerCase().includes('"id":"desc"')?y="<"+y:y=">"+y,{field:y,id:T[S]}},n=1e4,f=async(N,_)=>{var S,y;let T=this.limit;for(let E=1;this.canContinue&&T===this.limit&&E<=n;E++){const U=this.result[N],p=u(U,_);if(!p)break;const I=`${N}__eiscan_${E}`,R=c(_,p);let w=null;await O(this,rt,Et).call(this,{[I]:R},async m=>{w=m,l(m)});const k=E<n;await O(this,st,Tt).call(this,w,k),await this.delay();const t=w==null?void 0:w[I];if((S=t==null?void 0:t.error)!=null&&S.call(t)){T=0;break}const o=this.getData((y=t==null?void 0:t.data)==null?void 0:y.call(t));T=Array.isArray(o)?o.length:0}};let d=[],A=0;const h=async(N=!0)=>d.length?(await O(this,rt,Et).call(this,Object.fromEntries(d),async _=>{l(_),await O(this,st,Tt).call(this,_,N)}),A++,d=[],i&&A>=1?!0:(await this.delay(),!1)):!1;for await(const N of s){if(!this.canContinue)return;const[_,T,S,y={}]=N;if(y.entityItemGetScan){if(await h(!0))return;if(i)continue;await f(_,T);continue}let E=1;for(;S>E*this.limit;){const U=[_,E].join("__"),p=a(_,E,d,T);if(d.push([U,c(T,p)]),i&&d.length===49&&await h(!0)||d.length%50===0&&await h(!0))return;E++}}await h(!1)}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([s,e])=>{e&&console.log(`[${s}]`,e.toString())}),console.groupEnd()}};bt=new WeakSet,ae=function(){const s=this.totalBatchCommands||0,e=this.batchCommandMethods;if(s<M(q,Rt)||!Array.isArray(e)||e.length!==s)return!1;if(e.filter(a=>a==="crm.deal.list").length>=M(q,Lt))return!0;const i=e.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=M(q,St)&&i/s>=M(q,It)},Rt=new WeakMap,Lt=new WeakMap,St=new WeakMap,It=new WeakMap,At=new WeakSet,Ft=function(){if(!this.progressCall||!this.progressData)return;const{percent:s,allCount:e,allTotal:r}=this.progressPercent,i={percent:s,allCount:e,allTotal:r};O(this,Mt,oe).call(this,i)&&(this.progressCall({data:this.progressData,percent:s,allCount:e,allTotal:r}),this.lastProgressSnapshot=i)},Mt=new WeakSet,oe=function(s){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==s.percent||this.lastProgressSnapshot.allCount!==s.allCount||this.lastProgressSnapshot.allTotal!==s.allTotal:!0},Dt=new WeakSet,Ae=function(){const s={limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs};for(const e of this.timeLimitListeners)try{e(s)}catch(r){console.warn("Batch timeLimit listener error:",r)}},V=new WeakSet,ut=async function(s=this.defaultPauseMs){this.setTimeLimitState(!0,new Date().toISOString(),s),await new Promise(e=>setTimeout(e,s)),this.setTimeLimitState(!1,void 0)},st=new WeakSet,Tt=async function(s,e=!0){if(!e)return 0;let r=0;if(!s||typeof s!="object")return 0;for(const i of Object.values(s))if(!(!i||typeof i!="object"))try{if(typeof i.time=="function"){const a=i.time();a&&typeof a.operating=="number"&&(r=Math.max(r,a.operating))}}catch{}r>=this.operatingThreshold&&await O(this,V,ut).call(this)},rt=new WeakSet,Et=async function(s,e){let r=!1,i=s;do r=!1,await this.callBatchWithTimeout(i,async a=>{var u,n;let c=!1;const l=new Set;for(const[f,d]of Object.entries(a||{})){if(!(d!=null&&d.error)||!d.error())continue;const A=((n=(u=d.error())==null?void 0:u.ex)==null?void 0:n.error)??"";if(A==="TIMEOUT"){c=!0;break}["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT"].includes(A)&&l.add(f)}if(c){r=!0,await O(this,V,ut).call(this);return}if(l.size>0){const f={};for(const[A,h]of Object.entries(a||{}))l.has(A)||(f[A]=h);Object.keys(f).length&&await e(f);const d={};for(const A of l)i[A]&&(d[A]=i[A]);i=d,Object.keys(i).length&&(r=!0,await O(this,V,ut).call(this));return}await e(a)});while(r)},kt=new WeakSet,ce=function(s,e){return new Promise(r=>{if(typeof this.callMethod!="function"){r(null);return}let i=!1;const a=setTimeout(()=>{i||(i=!0,r(null))},this.requestTimeoutMs);try{this.callMethod(s,e,c=>{i||(i=!0,clearTimeout(a),r(c))})}catch{i||(i=!0,clearTimeout(a),r(null))}})},dt=new WeakSet,Qt=function(s){this.clearProgressData(),this.progressCall=typeof s=="function"?s:"",this.canContinue=!0,this.result={},this.errors={},this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.setTimeLimitState(!1,void 0)},L(q,Rt,5),L(q,Lt,5),L(q,St,8),L(q,It,.65);let z=q;class jt{constructor(){L(this,it,{})}get hash(){return this.createHash(8)}createHash(s){let e="abcdefghijklmnopqrstuvwxyz0123456789",r="";s=s||6;for(let i=0;i<s;i++)r+=e.charAt(Math.floor(Math.random()*e.length));return r}actionFilter({keyTimer:s,duration:e=10,action:r}){M(this,it)[s]&&(clearTimeout(M(this,it)[s]),M(this,it)[s]=null),r&&(M(this,it)[s]=setTimeout(()=>{r()},e))}async noSleep(){let s=document.createElement("video");s.classList.add("no-sleep"),s.muted=!0,s.autoplay=!0,s.setAttribute("playsinline",""),s.addEventListener("loadeddata",()=>{s.style.position="fixed",s.style.left="-9999px",document.querySelector("body").append(s),s.play().catch(e=>{console.warn("noSleep: autoplay prevented",e)})}),s.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{s.play().catch(e=>{console.warn("noSleep: replay prevented",e)})}})}),s.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(s,e){let r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=i,a.download=`${e}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(i)},200)}}it=new WeakMap;const Jt=new jt;class se{constructor(){L(this,Bt);L(this,yt);L(this,wt);L(this,Ct);L(this,Ht);L(this,Q,"logger");L(this,Z,!1);L(this,nt,new Map);L(this,ct,{});L(this,gt,!1);L(this,$,null);L(this,J,null);L(this,at,!1);L(this,lt,!1);P(this,"periodClear",3)}async init(){try{let s=new z(BX24.callBatch),{entityList:e}=await s.batch({entityList:{method:"entity.get"}});if(e&&Array.isArray(e))if(e.find(i=>i.ENTITY==M(this,Q)))j(this,Z,!0);else{let{entityAdd:i}=await s.batch({entityAdd:{method:"entity.add",params:{ENTITY:M(this,Q),NAME:M(this,Q),ACCESS:{AU:"X"}}}});i&&j(this,Z,!0)}return M(this,Z)}catch(s){return console.error("Ошибка при инициализации логера:",s),!1}}enableBackworkerMode(){return j(this,Z,!0),!0}start({type:s,data:e}){if(!M(this,Z))return O(this,yt,Zt).call(this,"entity"),null;if(!s||!e)return console.error("Невалидные данные для логирования:",{type:s,data:e}),null;const r=Jt.hash,i={type:s,data:e,userInfo:null,errorList:{},status:"",answer:null,date:new Date().getTime()};return M(this,nt).set(r,i),j(this,lt,!0),r}async stop({key:s,errorList:e,status:r,answer:i}){var c;if(!M(this,lt))return;if(!M(this,Z)){O(this,yt,Zt).call(this,"entity");return}let a=M(this,nt).get(s);if(!a){console.error(`Не найдены данные логирования для ключа: ${s}`);return}e&&(a.errorList=e),r&&(a.status=r),i&&(a.answer=i),await O(this,Bt,le).call(this),a.userInfo=M(this,ct),await O(this,wt,he).call(this),(c=a==null?void 0:a.data)!=null&&c.updateList&&j(this,at,!0),j(this,lt,!1)}async getEntityList(s){var e;try{if((e=M(this,J))!=null&&e.length&&!M(this,at))return M(this,J);let r=new z(BX24.callBatch),{entityList:i}=await r.batch({entityList:{method:"entity.item.get",params:{ENTITY:M(this,Q),SORT:{ID:"DESC"}}}},s);return!i||!Array.isArray(i)?(console.warn("Получен невалидный список записей"),[]):(i=i.map(a=>{try{const{ID:c,DATE_CREATE:l,DETAIL_TEXT:u}=a;return{...JSON.parse(u),id:c,dateCreate:l}}catch(c){return console.error(`Ошибка парсинга записи ${a.ID}:`,c),null}}).filter(a=>a!==null),j(this,at,!1),j(this,J,i),i)}catch(r){return console.error("Ошибка при получении списка записей:",r),[]}}runStorageMaintenance(){return O(this,Ct,ue).call(this)}async downAllEntityJson(){try{if(M(this,J)||await this.getEntityList(),!M(this,J)||M(this,J).length===0)return console.warn("Нет данных для выгрузки"),!1;let s=mt().format("%Y-%m-%d");return Jt.downloadFileJson(M(this,J),`sdklogger-entity-data__${s}`),!0}catch(s){return console.error("Ошибка при выгрузке данных в JSON:",s),!1}}}Q=new WeakMap,Z=new WeakMap,nt=new WeakMap,ct=new WeakMap,gt=new WeakMap,$=new WeakMap,J=new WeakMap,at=new WeakMap,lt=new WeakMap,Bt=new WeakSet,le=async function(){if(!M(this,gt))return M(this,$)?M(this,$):(j(this,$,(async()=>{try{const s=new z(BX24.callBatch),e=BX24.isAdmin(),{curUser:r}=await s.batch({curUser:{method:"user.current"}});j(this,ct,{isAdmin:e,curUser:r})}catch(s){console.error("Ошибка при получении информации о пользователе:",s),j(this,ct,{isAdmin:!1,curUser:null})}finally{j(this,gt,!0),j(this,$,null)}})()),M(this,$))},yt=new WeakSet,Zt=function(s){s=="entity"&&Jt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},wt=new WeakSet,he=async function(){try{let s={},e=new z(BX24.callBatch);for(let[r,i]of M(this,nt).entries())if(i.status){const a=JSON.stringify(i);s[r]={method:"entity.item.add",params:{ENTITY:M(this,Q),NAME:M(this,Q),DETAIL_TEXT:a}}}if(Object.keys(s).length){let r=await e.batch(s),{errors:i}=e;for(let[a,c]of Object.entries({...r,...i}))M(this,nt).delete(a);return!0}return!1}catch(s){return console.error("Ошибка при добавлении записей в хранилище:",s),!1}},Ct=new WeakSet,ue=async function(){try{let s=new z(BX24.callBatch),{serverTime:e}=await s.batch({serverTime:{method:"server.time"}});if(!e){console.error("Не удалось получить время сервера");return}if(M(this,J)||await this.getEntityList(),!M(this,J)||M(this,J).length===0)return;let r=M(this,J).filter(i=>{try{let{dateCreate:a}=i;return a?mt(new Date(a)).between(mt(new Date(e)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});r.length>0&&(console.log(`Найдено ${r.length} записей для очистки (старше ${this.periodClear} месяцев)`),await O(this,Ht,fe).call(this,r))}catch(s){console.error("Ошибка при проверке периода очистки:",s)}},Ht=new WeakSet,fe=async function(s){try{if(!s||s.length===0)return!1;let e=new z(BX24.callBatch),r=s.filter(a=>a&&a.id).map(a=>{let{id:c}=a;return{method:"entity.item.delete",params:{ENTITY:M(this,Q),ID:c}}});if(r.length===0)return!1;const i=await e.batch(r);return console.log(`Успешно удалено ${r.length} записей`),j(this,at,!0),i}catch(e){return console.error("Ошибка при очистке устаревших записей:",e),!1}};function Kt(b){if(!b||typeof b!="string")return"";try{const s=new URL(b);s.search="",s.hash="";let e=s.toString();return e.endsWith("/")&&s.pathname!=="/"&&(e=e.slice(0,-1)),e}catch{return b.split("?")[0].split("#")[0].replace(/\/$/,"")}}function re(b){return!b||typeof b!="string"?!1:b.toLowerCase().includes("/marketplace/app")}function _e(){var s;if(typeof window>"u"||!((s=window.location)!=null&&s.href))return"";const b=Kt(window.location.href);return re(b)?"":b}function vt(b){if(!(b!=null&&b.appConst)||typeof b.appConst!="object")return"";const s=_e();return s?(b.appConst.pathApp=s,s):Kt(b.appConst.pathApp??"")}class Te{constructor(s){L(this,ht);L(this,Ut);L(this,pt);L(this,Gt);L(this,Pt);L(this,Yt);L(this,tt);L(this,Nt);L(this,Wt);L(this,Ot);L(this,xt);P(this,"domain","");P(this,"isAdmin",!1);P(this,"appInfo",null);P(this,"appConst",null);P(this,"userInfo",null);P(this,"placeData",null);P(this,"placeInfo",null);P(this,"logger",!1);P(this,"timeLimit",{limit:!1,date:void 0,pauseMs:void 0});P(this,"batchClient",null);this.appConst=s}subscribeTimeLimit(s){return O(this,ht,Xt).call(this).subscribeTimeLimit(s)}init(){return new Promise((s,e)=>{const i=setTimeout(()=>{clearInterval(a);const c=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(c),e(c)},3e4);let a=setInterval(()=>{window.BX24&&BX24.init(async()=>{clearInterval(a),clearTimeout(i),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info();const c=O(this,Gt,de).call(this);if(console.info(c?"init BX24 (background worker)":"init BX24"),this.appInfo=await O(this,Pt,ge).call(this),this.userInfo=await O(this,Yt,ye).call(this),vt(this),c)await O(this,pt,Vt).call(this,!1,{skipInit:!0});else{await O(this,pt,Vt).call(this,!0);const l=new jt;try{l.noSleep()}catch(u){console.warn("Failed to initialize noSleep:",u)}}s({isBackworker:c})})},100)})}userOption(s,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(s,e):BX24.userOption.get(s)}appOption(s,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(s,e):BX24.appOption.get(s)}async call({method:s,params:e,updateList:r}){let i;if(r&&(i=this.logger.start({type:"call",data:{method:s,params:e,updateList:r}})),e||(e={}),typeof BX24>"u"||!BX24.callMethod){const l=new Error("BX24 is not initialized");throw console.error(l),l}const c=await O(this,ht,Xt).call(this).call({method:s,params:e});return c.success?(await O(this,tt,ft).call(this,i,{answer:c.answer,status:"success"}),c.data):(console.error(c.error),await O(this,tt,ft).call(this,i,{answer:c.answer,status:"fail",errorList:{0:c.error||"Unknown call error"}}),!1)}async batch(s,e,{errorCall:r,updateList:i,batchOptions:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const c=new Error("BX24 is not initialized");return console.error(c),!1}return O(this,Nt,$t).call(this,{mode:"batch",commandList:s,progressCall:e,errorCall:r,updateList:i,batchOptions:a})}async batchTotalCount(s,e,{errorCall:r,updateList:i}={}){if(typeof BX24>"u"||!BX24.callBatch){const a=new Error("BX24 is not initialized");return console.error(a),!1}return O(this,Nt,$t).call(this,{mode:"batch-total-count",commandList:s,progressCall:e,errorCall:r,updateList:i})}async getPlacement(){const s=await this.call({method:"placement.get"});return this.placeData||(this.placeData=s),s}async placementBind(s){var A;if(!this.isAdmin||(this.placeData=await this.getPlacement(),!this.placeData))return;const{appName:e,pathApp:r}=this.appConst;let i=O(this,Ot,te).call(this,s);i=i.filter(h=>h.placement!=="PAGE_BACKGROUND_WORKER"&&h.placement!=="PAGE_BACKGROUND_WORKER_ALL");const a=O(this,xt,Ne).call(this,r),c=new Set(i.map(h=>h.placement));for(const h of a)c.has(h.placement)||i.push({placement:h.placement});if(i.length===0)return;let l=e;this.domain==="szdl.bitrix24.ru"&&((A=this.appInfo)!=null&&A.ID)&&(l=`${e}: #${this.appInfo.ID}`);const u=l.replace(" CRM",""),n={},f=[],d=new Map;for(const h of this.placeData)d.has(h.placement)||d.set(h.placement,[]),d.get(h.placement).push(h);for(let h=0;h<i.length;h++){const{placement:N,options:_}=i[h],T=d.get(N)||[];if(T.some(E=>E.handler===r))continue;const y=T.filter(E=>E.handler!==r);for(const E of y)f.push({placement:N,handler:E.handler});n[`bind_${h}`]={method:"placement.bind",params:{PLACEMENT:N,HANDLER:r,LANG_ALL:{ru:{TITLE:N==="USER_PROFILE_TOOLBAR"?u:l}},OPTIONS:{errorHandlerUrl:r,..._&&typeof _=="object"?_:{}}}}}f.length>0&&await this.placementUnBind(f),Object.keys(n).length>0&&(await this.batch(n),this.placeData=await this.getPlacement(),Object.values(n).forEach(h=>{console.log("Приложение успешно встроено в",h.params.PLACEMENT)}))}async placementUnBind(s){let e=O(this,Ot,te).call(this,s);if(e=e.filter(i=>i.placement!=="PAGE_BACKGROUND_WORKER"&&i.placement!=="PAGE_BACKGROUND_WORKER_ALL"),e.length===0)return;const r={};for(let i=0;i<e.length;i++){const a={PLACEMENT:e[i].placement};e[i].handler&&(a.HANDLER=e[i].handler),r[`unbind_${i}`]={method:"placement.unbind",params:a}}await this.batch(r),e.forEach(i=>{console.log("Встройка отвязана",i.placement)})}async getBotList(){const s=await this.call({method:"imbot.bot.list",params:{}}),e=Object.values(s);return console.log("chat-bot list:",e),e}async regBot({code:s,type:e,name:r}){const{appName:i,pathApp:a,chatBotLogo:c}=this.appConst,l=this.appInfo.ID,u=await this.call({method:"imbot.register",params:{CODE:s??this.appInfo.CODE,TYPE:e??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${r??i} - бот #${l}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:mt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:c??""}}});return console.log("Чат-бот добавлен",u),u}async unRegBot(s){const e=await this.call({method:"imbot.unregister",params:{BOT_ID:s}});return console.log("чат-бот удален",e),e}getLoggerList(s){return this.logger.getEntityList(s)}}ht=new WeakSet,Xt=function(){return this.batchClient||(this.batchClient=new z({callBatch:BX24.callBatch,callMethod:BX24.callMethod}),this.timeLimit=this.batchClient.timeLimit),this.batchClient},Ut=new WeakSet,me=function(){return{start:()=>{},stop:()=>{},getEntityList:()=>{}}},pt=new WeakSet,Vt=async function(s,{skipInit:e=!1}={}){this.logger?(this.logger=new se,e?this.logger.enableBackworkerMode():await this.logger.init(),s&&typeof this.logger.runStorageMaintenance=="function"&&this.logger.runStorageMaintenance()):this.logger=O(this,Ut,me).call(this)},Gt=new WeakSet,de=function(){var r,i,a;const s=(r=this.placeInfo)==null?void 0:r.placement,e=(a=(i=this.placeInfo)==null?void 0:i.options)==null?void 0:a.ID;return s==="PAGE_BACKGROUND_WORKER"||e==="PAGE_BACKGROUND_WORKER"},Pt=new WeakSet,ge=function(){return this.call({method:"app.info"})},Yt=new WeakSet,ye=function(){return this.call({method:"user.current"})},tt=new WeakSet,ft=async function(s,e){if(s)try{await this.logger.stop({key:s,...e})}catch(r){console.error("Logger error:",r)}},Nt=new WeakSet,$t=async function({mode:s,commandList:e,progressCall:r,errorCall:i,updateList:a,batchOptions:c}){const l=O(this,ht,Xt).call(this),u=a?this.logger.start({type:s,data:s==="batch"?{commandList:e,updateList:a}:{commandList:e}}):void 0;try{const n=s==="batch"?await l.batch(e,r,c):await l.batchTotalCount(e,r),f=O(this,Wt,pe).call(this,l,n,e,a);return Object.keys(f).length?(i&&i(f),await O(this,tt,ft).call(this,u,{status:"fail",errorList:f})):await O(this,tt,ft).call(this,u,{status:"success"}),n}catch(n){return await O(this,tt,ft).call(this,u,{status:"fail-runtime",errorList:{0:n==null?void 0:n.toString()}}),console.error(n),!1}},Wt=new WeakSet,pe=function(s,e,r,i){let a={...s.errors};if(Object.values(s.errors).some(l=>{if(typeof l!="string")return!1;const u=l.toUpperCase();return u==="TIMEOUT"||u==="OPERATION_TIME_LIMIT"||u.includes("TIMEOUT")||u.includes("OPERATION_TIME_LIMIT")})&&i){const l=e?Object.keys(e).filter(d=>d!=="errorsList"):[],u=new Set(Object.keys(s.errors||{})),n=new Set;if(e){for(const d of l)if(!u.has(d)){const A=e[d];A!=null&&n.add(d)}}const f=Object.values(s.errors).find(d=>{if(typeof d!="string")return!1;const A=d.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const d of Object.keys(r))!n.has(d)&&!s.errors[d]&&(a[d]=f||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a},Ot=new WeakSet,te=function(s){if(!s)return[];let e=[];return Array.isArray(s)?e=s.map(r=>typeof r=="string"?{placement:r}:r):typeof s=="string"?e=[{placement:s}]:e=[s],e},xt=new WeakSet,Ne=function(s){return this.placeData?this.placeData.filter(e=>!(e.placement==="PAGE_BACKGROUND_WORKER"||!e.handler||e.handler.includes(s))):[]};const ie="szdl-utils-kit|";function Ee(){if(typeof sessionStorage>"u")return`ephemeral-${Date.now()}-${Math.random().toString(16).slice(2)}`;let b=sessionStorage.getItem("szdl-cross-tab-instance-id");return b||(b=`${Date.now()}-${Math.random().toString(16).slice(2)}`,sessionStorage.setItem("szdl-cross-tab-instance-id",b)),b}function be(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}const zt=new Map;function Re(b="default"){if(typeof BroadcastChannel>"u")return null;const s=`${ie}bc:${b}`;return zt.has(s)||zt.set(s,new BroadcastChannel(s)),zt.get(s)}function ne(b,s){const e=Re(b);if(e)try{const r=s&&typeof s=="object"&&!Array.isArray(s)?s:{data:s};e.postMessage({...r,tabId:Ee(),ts:Date.now()})}catch{}}async function Le(b,s,e={}){const{ifAvailable:r=!1}=e,i=typeof b=="string"&&b.length>0?b:"default",a=`${ie}${i}`;return be()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!r},async c=>{if(r&&c==null)return{skipped:!0,coordination:"locks"};ne(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await s(),coordination:"locks"}}finally{ne(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await s(),coordination:"none"}}class Se{constructor(s){L(this,_t);P(this,"entityName","tabs");P(this,"maxTabs",20);P(this,"tabList",[]);P(this,"id",0);P(this,"hasStarted",!1);P(this,"heartbeat");P(this,"runHeartbeat");P(this,"activeMaxPause",10*1e3);P(this,"quickCleanupThreshold",2*60*1e3);P(this,"pollInterval",6*1e3+Math.floor(Math.random()*2e3));P(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);P(this,"continueCondition");P(this,"defaultContinueBackground",()=>!0);var c,l,u;if(!s){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:e,bx:r,users:i,continueBackground:a}=s;this.bx=r,this.appInit=e,this.users=i,vt(r),this.appPath=O(this,_t,ee).call(this,((c=r==null?void 0:r.appConst)==null?void 0:c.pathApp)??""),this.appName=((l=r==null?void 0:r.appConst)==null?void 0:l.appName)??"",this.appCodeName=((u=r==null?void 0:r.appConst)==null?void 0:u.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(),r=e&&+this.id==+e;await this.updateTabState(r),r&&!this.hasStarted&&await this.runAsLeader()}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var s;if(typeof BX24>"u"||!((s=BX24.placement)!=null&&s.info))return!1;try{const e=BX24.placement.info(),r=e==null?void 0:e.placement,i=(e==null?void 0:e.options)||{},a=(i==null?void 0:i.URI)||"",c=r==="PAGE_BACKGROUND_WORKER"||(i==null?void 0:i.ID)==="PAGE_BACKGROUND_WORKER",l=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!c||l}catch{return!1}}async checkEntity(){var r;const s=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((r=s==null?void 0:s.find)==null?void 0:r.call(s,i=>i.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 s=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(s)||!s.length?[]:s.map(e=>{if(!e)return{id:void 0,data:void 0};try{const r=JSON.parse(e.DETAIL_TEXT);return{id:+e.ID||0,data:r}}catch(r){return console.log("BackgroundWorker: parse tab error",r),{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 s={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId},e=await this.safeCall(()=>{var r;return this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(s)}})})||0;return this.id=+e||0,this.id}async updateTabState(s){if(!this.id)return;const e={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:s,sessionId:this.sessionId};await this.safeCall(()=>{var r;return this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(e)}})})}async deleteTabs(s=[]){if(!s.length)return;const e=s.map(r=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:r.id}}));await this.safeCall(()=>this.bx.batch(e))}async checkPlacementType(){var s,e;try{if(!((s=this.bx)!=null&&s.isAdmin))return!0;const r=await this.safeCall(()=>this.bx.getPlacement());if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),a=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),c=!a;if(!i)return!0;let l=!1;for(const u of r){if(u.placement!=="PAGE_BACKGROUND_WORKER"||!(u.userId||u.handler&&u.handler.includes("USER_ID=")))continue;const f=u.userId||(u.handler?this.extractUserIdFromHandler(u.handler):null);if(f&&+f===i){l=!0;break}}return a?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):c&&l?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}isIndividualPlacement(s){return!s||typeof s!="string"?!1:s.includes("USER_ID=")}extractUserIdFromHandler(s){if(!s||typeof s!="string")return null;const e=s.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(s){return console.error("BackgroundWorker: Ошибка в continueCondition",s),!1}}async refreshTabs(s=!1,e=this.activeMaxPause){const r=[],i=[],a=Date.now(),c=await this.getTabs();for(const l of c){if(!(l!=null&&l.data)){r.push(l);continue}if(a-new Date(l.data.lastActive||0).getTime()>e){r.push(l);continue}i.push(l)}return s&&r.length&&await this.deleteTabs(r),this.tabList=i,i}selectLeaderId(){var e;return this.tabList.length&&+((e=[...this.tabList].sort((r,i)=>{var l,u,n,f;const a=new Date(((l=r.data)==null?void 0:l.createdAt)||((u=r.data)==null?void 0:u.lastActive)||0).getTime(),c=new Date(((n=i.data)==null?void 0:n.createdAt)||((f=i.data)==null?void 0:f.lastActive)||0).getTime();return a===c?(+r.id||0)-(+i.id||0):a-c})[0])==null?void 0:e.id)||0}async runAsLeader(){var i,a;const s=String(((a=(i=this.bx)==null?void 0:i.userInfo)==null?void 0:a.ID)??"0"),e=`background-worker:${this.entityName}:${s}`;(await Le(e,async()=>{this.hasStarted=!0;const c=Math.min(this.activeMaxPause-1500,Math.max(2500,Math.floor(this.pollInterval/2)));this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(l=>console.error("BackgroundWorker: heartbeat update failed",l))},c);try{await this.appInit()}catch(l){console.error("BackgroundWorker: appInit failed",l)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)},{ifAvailable:!0})).skipped&&console.log("BackgroundWorker: runAsLeader пропущен — Web Lock у другой вкладки (тот же фоновый воркер)")}async setBackgroundWorkerAll(){var S,y,E,U;if(!((S=this.bx)!=null&&S.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(y=this.users)!=null&&y.length||await this.getEntityData(),vt(this.bx);const s=O(this,_t,ee).call(this,((U=(E=this.bx)==null?void 0:E.appConst)==null?void 0:U.pathApp)??"");if(!s){console.error("BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена");return}const e=await this.safeCall(()=>this.bx.getPlacement()),r=new Map,i=new Map;let a=null;(e||[]).forEach(p=>{if(p.placement!=="PAGE_BACKGROUND_WORKER")return;if(p.userId||p.handler&&p.handler.includes("USER_ID=")){const R=p.userId||(p.handler?this.extractUserIdFromHandler(p.handler):null);if(R){const w=+R;r.set(w,p),i.has(w)||i.set(w,[]),i.get(w).push(p)}}else a=p});const c=await this.resolveAdmins(),l=await this.getEligibleUsersForBackgroundWorker(c);l.sort((p,I)=>{const R=p.LAST_LOGIN?new Date(p.LAST_LOGIN):new Date(0);return(I.LAST_LOGIN?new Date(I.LAST_LOGIN):new Date(0))-R});const u=10,n=l.slice(0,u),f=n.filter(p=>{const I=r.get(+p.ID);if(!I)return!0;const R=`${s}?USER_ID=${p.ID}/`;return I.handler!==R}),d=[];for(const[p]of r){const I=+p||0;l.find(w=>+w.ID===I)||d.push(I)}for(const p of n){const I=r.get(+p.ID);if(!I)continue;const R=`${s}?USER_ID=${p.ID}/`;I.handler!==R&&d.push(+p.ID)}const A=[],h=[...new Set(d)];for(const p of h){const I=i.get(+p)||[];for(const R of I)R!=null&&R.handler&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:R.handler}})}const N=a&&(f.length>0||a.handler!==`${s}`);N&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:a.handler||`${s}`}});for(const p of f)A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${s}?USER_ID=${p.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${s}?USER_ID=${p.ID}/`},USER_ID:p.ID}});(!a||N)&&A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${s}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${s}`}}});const _=A.filter(p=>p.method==="placement.unbind"),T=A.filter(p=>p.method==="placement.bind");_.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(_.map((p,I)=>[`unbind_${I}`,p])))),T.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(T.map((p,I)=>[`bind_${I}`,p])))),A.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var s,e;try{const r=+(((s=this.bx.userInfo)==null?void 0:s.ID)??0),i=!!((e=this.bx)!=null&&e.isAdmin),a=await this.getAdminsList()||[];if(!i){if(r&&a.includes(+r)){const u=a.filter(n=>+n!=+r);return await this.saveAdminsList(u),u}return a}const c=new Set([...a||[]]);r&&c.add(+r);const l=[...c].filter(Boolean);return await this.saveAdminsList(l),l}catch(r){return console.error("BackgroundWorker: resolveAdmins error",r),[]}}async getEligibleUsersForBackgroundWorker(s=[]){const e=(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0),r=s.map(i=>+i||0).filter(Boolean);return e.filter(i=>r.includes(+i.ID||0))}async saveAdminsList(s=[]){try{BX24.appOption.set("adminsList",JSON.stringify(s))}catch(e){console.error("BackgroundWorker: saveAdminsList error",e)}}async getAdminsList(){try{const s=BX24.appOption.get("adminsList"),e=s?JSON.parse(s):[];return Array.isArray(e)?e.map(r=>+r||0).filter(Boolean):[]}catch(s){return console.error("BackgroundWorker: getAdminsList error",s),[]}}async getEntityData(){const s={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:e}=await this.safeCall(()=>this.bx.batch(s).then(r=>r?(Array.isArray(r.users)||(r.users=[]),r):{users:[]}));this.users=e}async ensureAdminPlacements(){var s,e;(s=this.bx)!=null&&s.isAdmin&&((e=this.users)!=null&&e.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(s=500,e){return new Promise(r=>{setTimeout(()=>{e&&e(),r(!0)},s)})}async safeCall(s){try{return await s()}catch(e){console.error("BackgroundWorker: safeCall error",e);return}}}_t=new WeakSet,ee=function(s){if(!s||typeof s!="string")return"";const e=Kt(s).replace(/\/+$/,"");return e?re(e)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):e:""},B.BackgroundWorker=Se,B.Batch=z,B.BxBoot=Te,B.BxHelper=jt,B.BxLogger=se,B.tempus=mt,Object.defineProperty(B,Symbol.toStringTag,{value:"Module"})});
|