szdl-utils-kit 0.3.19 → 0.3.20

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 CHANGED
@@ -8,7 +8,7 @@ var M = (y, t, e) => (Wt(y, t, "read from private field"), e ? e.call(y) : t.get
8
8
  if (t.has(y))
9
9
  throw TypeError("Cannot add the same private member more than once");
10
10
  t instanceof WeakSet ? t.add(y) : t.set(y, e);
11
- }, F = (y, t, e, r) => (Wt(y, t, "write to private field"), r ? r.call(y, e) : t.set(y, e), e);
11
+ }, x = (y, t, e, r) => (Wt(y, t, "write to private field"), r ? r.call(y, e) : t.set(y, e), e);
12
12
  var _ = (y, t, e) => (Wt(y, t, "access private method"), e);
13
13
  var pe = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
14
14
  function Ne(y) {
@@ -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, q = [], W = 0, x = 0, G, J, Y = {}, P;
523
+ var g, B = [], D, U, z = [], W = 0, F = 0, G, J, Y = {}, P;
524
524
  if (s === e)
525
525
  return D = a(this, m), D === e && (this._i = {
526
526
  year: -1,
@@ -536,16 +536,16 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
536
536
  if (U = o.charAt(W) + o.charAt(W + 1), E[U] !== e) {
537
537
  switch (G = 0, J = "", E[U].type) {
538
538
  case "number":
539
- for (; G < E[U].maxLength && x + G < s.length && !isNaN(Number(s.charAt(x + G))); )
540
- J += s.charAt(x + G), G += 1;
539
+ for (; G < E[U].maxLength && F + G < s.length && !isNaN(Number(s.charAt(F + G))); )
540
+ J += s.charAt(F + G), G += 1;
541
541
  break;
542
542
  case "word":
543
- for (; G < E[U].maxLength && x + G < s.length && /^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(s.charAt(x + G)); )
544
- J += s.charAt(x + G), G += 1;
543
+ for (; G < E[U].maxLength && F + G < s.length && /^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(s.charAt(F + G)); )
544
+ J += s.charAt(F + G), G += 1;
545
545
  break;
546
546
  case "string":
547
- for (; G < E[U].maxLength && x + G < s.length; )
548
- J += s.charAt(x + G), G += 1;
547
+ for (; G < E[U].maxLength && F + G < s.length; )
548
+ J += s.charAt(F + G), G += 1;
549
549
  break;
550
550
  }
551
551
  if (G < E[U].minLength)
@@ -558,9 +558,9 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
558
558
  seconds: -1,
559
559
  milliseconds: -1
560
560
  }), D;
561
- B.push(U), q.push(J), G -= 1, x += G, W += 1;
561
+ B.push(U), z.push(J), G -= 1, F += G, W += 1;
562
562
  }
563
- } else if (s.charAt(x) !== o.charAt(W))
563
+ } else if (s.charAt(F) !== o.charAt(W))
564
564
  return D = a(this, m), D === e && (this._i = {
565
565
  year: -1,
566
566
  month: -1,
@@ -570,10 +570,10 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
570
570
  seconds: -1,
571
571
  milliseconds: -1
572
572
  }), D;
573
- W += 1, x += 1;
573
+ W += 1, F += 1;
574
574
  }
575
575
  for (g in B)
576
- B.hasOwnProperty(g) && E.hasOwnProperty(B[g]) && (P = E[B[g]].parse(q[g]), Y = {
576
+ B.hasOwnProperty(g) && E.hasOwnProperty(B[g]) && (P = E[B[g]].parse(z[g]), Y = {
577
577
  year: P.year !== e ? P.year : Y.year,
578
578
  month: P.month !== e ? P.month : Y.month,
579
579
  day: P.day !== e ? P.day : Y.day,
@@ -712,7 +712,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
712
712
  }, n.noConflict = function() {
713
713
  return r.tempus = u, n;
714
714
  }, n.generate = function(s) {
715
- var o, m, g, B, D, U, q, W;
715
+ var o, m, g, B, D, U, z, W;
716
716
  if (typeof s.dateFrom != "number" && (s.dateFrom instanceof w ? o = s.dateFrom.utc() : o = n(s.dateFrom, s.formatFrom).utc()), typeof s.dateTo != "number" && (s.dateTo instanceof w ? 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,
@@ -734,10 +734,10 @@ 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([]), q = n(o).get()[s.groupBy]), W = function(J, Y, P) {
737
+ }), s.groupBy === e ? U = s.asObject === !0 ? {} : [] : (U = [], U.push([]), z = n(o).get()[s.groupBy]), W = function(J, Y, P) {
738
738
  return s.asObject === !0 ? s.format !== e ? J[n(Y).format(s.format)] = {} : J[n(Y).format("%F %H:%M:%S")] = {} : s.format !== e ? J.push(P ? null : n(Y).format(s.format)) : J.push(P ? null : n(Y)), J;
739
739
  }, s.groupBy !== e && s.fillNulls) {
740
- var x = {
740
+ var F = {
741
741
  year: D.year ? -D.year : e,
742
742
  month: D.month ? -D.month : e,
743
743
  day: D.day ? -D.day : e,
@@ -746,8 +746,8 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
746
746
  seconds: D.seconds ? -D.seconds : e,
747
747
  milliseconds: D.milliseconds ? -D.milliseconds : e
748
748
  };
749
- for (g = n(o).calc(x).utc(); n(g).get()[s.groupBy] === q; )
750
- W(U[U.length - 1], g, !0), g = n(g).calc(x).utc();
749
+ for (g = n(o).calc(F).utc(); n(g).get()[s.groupBy] === z; )
750
+ W(U[U.length - 1], g, !0), g = n(g).calc(F).utc();
751
751
  if (s.groupBy === "week") {
752
752
  var G = n(o).dayOfWeek();
753
753
  for (g = n(o).dayOfWeek(0).utc(); U[0].length < G && g < o; )
@@ -755,9 +755,9 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
755
755
  }
756
756
  }
757
757
  for (; o <= m; )
758
- s.groupBy === e ? W(U, o) : n(o).get()[s.groupBy] === q ? W(U[U.length - 1], o) : (U.push([]), W(U[U.length - 1], o), q = n(o).get()[s.groupBy]), o = n(o).calc(D).utc();
758
+ s.groupBy === e ? W(U, o) : n(o).get()[s.groupBy] === z ? W(U[U.length - 1], o) : (U.push([]), W(U[U.length - 1], o), z = n(o).get()[s.groupBy]), o = n(o).calc(D).utc();
759
759
  if (s.groupBy !== e && s.fillNulls)
760
- for (B = n(m).calc(D).utc(); n(B).get()[s.groupBy] === q; )
760
+ for (B = n(m).calc(D).utc(); n(B).get()[s.groupBy] === z; )
761
761
  W(U[U.length - 1], B, !0), B = n(B).calc(D).utc();
762
762
  return U;
763
763
  }, n.monthNames = function(s) {
@@ -810,8 +810,8 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
810
810
  }).call(pe);
811
811
  })(Xt, Xt.exports);
812
812
  var Oe = Xt.exports;
813
- const pt = /* @__PURE__ */ Ne(Oe);
814
- var _t, Vt, Tt, Et, Rt, bt, at, Nt, Lt, $t, St, te, z, it, $, lt, tt, ht, It, ee, ut, Jt;
813
+ const Nt = /* @__PURE__ */ Ne(Oe);
814
+ var Tt, $t, Et, Rt, bt, Lt, at, Ot, St, te, It, ee, Q, it, $, lt, tt, ht, Mt, se, ut, Jt;
815
815
  const j = class j {
816
816
  constructor(t) {
817
817
  /**
@@ -820,7 +820,7 @@ const j = class j {
820
820
  * формула sum(count)/sum(total)×chunkRate (один длинный list, batchTotalCount, смешанные batch).
821
821
  * @returns {boolean}
822
822
  */
823
- L(this, _t);
823
+ L(this, Tt);
824
824
  /**
825
825
  * Одно обновление колбэка прогресса, если снимок изменился.
826
826
  * @returns {void}
@@ -832,13 +832,13 @@ const j = class j {
832
832
  * @param {{percent: number, allCount: number, allTotal: number}} snapshot - Текущий снимок прогресса.
833
833
  * @returns {boolean} `true`, если нужно отправить callback прогресса.
834
834
  */
835
- L(this, Lt);
835
+ L(this, St);
836
836
  /**
837
837
  * Уведомляет подписчиков о текущем состоянии лимита.
838
838
  *
839
839
  * @returns {void}
840
840
  */
841
- L(this, St);
841
+ L(this, It);
842
842
  /**
843
843
  * Включает состояние лимита, выдерживает паузу и затем выключает лимит.
844
844
  * Используется как единый "cooldown" перед повторной отправкой chunk.
@@ -846,7 +846,7 @@ const j = class j {
846
846
  * @param {number} [pauseMs=this.defaultPauseMs] - Длительность паузы; для batch по умолчанию 120 с, для `call()` — `callLimitPauseMs` (30 с).
847
847
  * @returns {Promise<void>}
848
848
  */
849
- L(this, z);
849
+ L(this, Q);
850
850
  /**
851
851
  * Проверяет operating-time в результате batch и ставит паузу,
852
852
  * если сервер приблизился к лимиту выполнения.
@@ -871,7 +871,7 @@ const j = class j {
871
871
  * @param {Object} params - Параметры REST-метода.
872
872
  * @returns {Promise<Object|null>} Raw-result BX24 или null при таймауте/ошибке вызова.
873
873
  */
874
- L(this, It);
874
+ L(this, Mt);
875
875
  /**
876
876
  * Resets mutable runtime state before each public batch run.
877
877
  * @param {Function} progressCall - Progress callback for current run.
@@ -892,7 +892,7 @@ const j = class j {
892
892
  if (!this.progressData)
893
893
  return { percent: 0, allCount: 0, allTotal: 0 };
894
894
  const t = this.totalBatchCommands || 0;
895
- if (t > 0 && Array.isArray(this.batchCommandKeyOrder) && this.batchCommandKeyOrder.length && _(this, _t, Vt).call(this)) {
895
+ if (t > 0 && Array.isArray(this.batchCommandKeyOrder) && this.batchCommandKeyOrder.length && _(this, Tt, $t).call(this)) {
896
896
  let l = 0;
897
897
  for (const A of this.batchCommandKeyOrder) {
898
898
  const h = this.progressData[A];
@@ -945,15 +945,15 @@ const j = class j {
945
945
  total: d,
946
946
  count: Math.min(f, d)
947
947
  }, typeof document < "u" && (document == null ? void 0 : document.hidden) === !0) {
948
- _(this, at, Nt).call(this);
948
+ _(this, at, Ot).call(this);
949
949
  return;
950
950
  }
951
- _(this, at, Nt).call(this), this.progressTimer || (this.progressTimer = setInterval(() => {
951
+ _(this, at, Ot).call(this), this.progressTimer || (this.progressTimer = setInterval(() => {
952
952
  if (!this.progressCall) {
953
953
  this.clearProgressData();
954
954
  return;
955
955
  }
956
- _(this, at, Nt).call(this);
956
+ _(this, at, Ot).call(this);
957
957
  const { percent: T } = this.progressPercent;
958
958
  T >= 100 && (clearInterval(this.progressTimer), this.progressTimer = "");
959
959
  }, this.progressDelay));
@@ -978,7 +978,7 @@ const j = class j {
978
978
  * @returns {void}
979
979
  */
980
980
  setTimeLimitState(t, e, r) {
981
- this.timeLimit.limit = !!t, this.timeLimit.date = t ? e : void 0, t && typeof r == "number" && r > 0 ? this.timeLimit.pauseMs = r : this.timeLimit.pauseMs = void 0, _(this, St, te).call(this);
981
+ this.timeLimit.limit = !!t, this.timeLimit.date = t ? e : void 0, t && typeof r == "number" && r > 0 ? this.timeLimit.pauseMs = r : this.timeLimit.pauseMs = void 0, _(this, It, ee).call(this);
982
982
  }
983
983
  /**
984
984
  * Подписывает внешний код на изменения состояния лимита.
@@ -1259,9 +1259,9 @@ const j = class j {
1259
1259
  async call({ method: t, params: e = {} }) {
1260
1260
  var r, i, a, c, l, u, n;
1261
1261
  for (; ; ) {
1262
- const f = await _(this, It, ee).call(this, t, e);
1262
+ const f = await _(this, Mt, se).call(this, t, e);
1263
1263
  if (!f) {
1264
- await _(this, z, it).call(this, this.callLimitPauseMs);
1264
+ await _(this, Q, it).call(this, this.callLimitPauseMs);
1265
1265
  continue;
1266
1266
  }
1267
1267
  const d = {};
@@ -1271,7 +1271,7 @@ const j = class j {
1271
1271
  if (f.error()) {
1272
1272
  const h = ((i = (r = f.error()) == null ? void 0 : r.ex) == null ? void 0 : i.error) ?? "";
1273
1273
  if (["QUERY_LIMIT_EXCEEDED", "OPERATION_TIME_LIMIT", "TIMEOUT"].includes(h)) {
1274
- await _(this, z, it).call(this, this.callLimitPauseMs);
1274
+ await _(this, Q, it).call(this, this.callLimitPauseMs);
1275
1275
  continue;
1276
1276
  }
1277
1277
  const O = ((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) || "Неизвестная ошибка";
@@ -1481,29 +1481,29 @@ const j = class j {
1481
1481
  }), console.groupEnd();
1482
1482
  }
1483
1483
  };
1484
- _t = new WeakSet(), Vt = function() {
1484
+ Tt = new WeakSet(), $t = function() {
1485
1485
  const t = this.totalBatchCommands || 0, e = this.batchCommandMethods;
1486
- if (t < M(j, Tt) || !Array.isArray(e) || e.length !== t)
1486
+ if (t < M(j, Et) || !Array.isArray(e) || e.length !== t)
1487
1487
  return !1;
1488
- if (e.filter((a) => a === "crm.deal.list").length >= M(j, Et))
1488
+ if (e.filter((a) => a === "crm.deal.list").length >= M(j, Rt))
1489
1489
  return !0;
1490
1490
  const i = e.filter(
1491
1491
  (a) => typeof a == "string" && a.includes(".list")
1492
1492
  ).length;
1493
- return i >= M(j, Rt) && i / t >= M(j, bt);
1494
- }, Tt = new WeakMap(), Et = new WeakMap(), Rt = new WeakMap(), bt = new WeakMap(), at = new WeakSet(), Nt = function() {
1493
+ return i >= M(j, bt) && i / t >= M(j, Lt);
1494
+ }, Et = new WeakMap(), Rt = new WeakMap(), bt = new WeakMap(), Lt = new WeakMap(), at = new WeakSet(), Ot = function() {
1495
1495
  if (!this.progressCall || !this.progressData)
1496
1496
  return;
1497
1497
  const { percent: t, allCount: e, allTotal: r } = this.progressPercent, i = { percent: t, allCount: e, allTotal: r };
1498
- _(this, Lt, $t).call(this, i) && (this.progressCall({
1498
+ _(this, St, te).call(this, i) && (this.progressCall({
1499
1499
  data: this.progressData,
1500
1500
  percent: t,
1501
1501
  allCount: e,
1502
1502
  allTotal: r
1503
1503
  }), this.lastProgressSnapshot = i);
1504
- }, Lt = new WeakSet(), $t = function(t) {
1504
+ }, St = new WeakSet(), te = function(t) {
1505
1505
  return this.lastProgressSnapshot ? this.lastProgressSnapshot.percent !== t.percent || this.lastProgressSnapshot.allCount !== t.allCount || this.lastProgressSnapshot.allTotal !== t.allTotal : !0;
1506
- }, St = new WeakSet(), te = function() {
1506
+ }, It = new WeakSet(), ee = function() {
1507
1507
  const t = {
1508
1508
  limit: this.timeLimit.limit,
1509
1509
  date: this.timeLimit.date,
@@ -1515,7 +1515,7 @@ _t = new WeakSet(), Vt = function() {
1515
1515
  } catch (r) {
1516
1516
  console.warn("Batch timeLimit listener error:", r);
1517
1517
  }
1518
- }, z = new WeakSet(), it = async function(t = this.defaultPauseMs) {
1518
+ }, Q = new WeakSet(), it = async function(t = this.defaultPauseMs) {
1519
1519
  this.setTimeLimitState(!0, (/* @__PURE__ */ new Date()).toISOString(), t), await new Promise((e) => setTimeout(e, t)), this.setTimeLimitState(!1, void 0);
1520
1520
  }, $ = new WeakSet(), lt = async function(t, e = !0) {
1521
1521
  if (!e)
@@ -1532,7 +1532,7 @@ _t = new WeakSet(), Vt = function() {
1532
1532
  }
1533
1533
  } catch {
1534
1534
  }
1535
- r >= this.operatingThreshold && await _(this, z, it).call(this);
1535
+ r >= this.operatingThreshold && await _(this, Q, it).call(this);
1536
1536
  }, tt = new WeakSet(), ht = async function(t, e) {
1537
1537
  let r = !1, i = t;
1538
1538
  do
@@ -1551,7 +1551,7 @@ _t = new WeakSet(), Vt = function() {
1551
1551
  ["QUERY_LIMIT_EXCEEDED", "OPERATION_TIME_LIMIT"].includes(A) && l.add(f);
1552
1552
  }
1553
1553
  if (c) {
1554
- r = !0, await _(this, z, it).call(this);
1554
+ r = !0, await _(this, Q, it).call(this);
1555
1555
  return;
1556
1556
  }
1557
1557
  if (l.size > 0) {
@@ -1562,13 +1562,13 @@ _t = new WeakSet(), Vt = function() {
1562
1562
  const d = {};
1563
1563
  for (const A of l)
1564
1564
  i[A] && (d[A] = i[A]);
1565
- i = d, Object.keys(i).length && (r = !0, await _(this, z, it).call(this));
1565
+ i = d, Object.keys(i).length && (r = !0, await _(this, Q, it).call(this));
1566
1566
  return;
1567
1567
  }
1568
1568
  await e(a);
1569
1569
  });
1570
1570
  while (r);
1571
- }, It = new WeakSet(), ee = function(t, e) {
1571
+ }, Mt = new WeakSet(), se = function(t, e) {
1572
1572
  return new Promise((r) => {
1573
1573
  if (typeof this.callMethod != "function") {
1574
1574
  r(null);
@@ -1589,12 +1589,12 @@ _t = new WeakSet(), Vt = function() {
1589
1589
  }, ut = new WeakSet(), Jt = function(t) {
1590
1590
  this.clearProgressData(), this.progressCall = typeof t == "function" ? t : "", 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);
1591
1591
  }, /** Не включать вес по командам для совсем маленьких batch. */
1592
- L(j, Tt, 5), /** Явный сигнал: много отдельных выборок сделок по фильтрам. */
1593
- L(j, Et, 5), /** Достаточно «list»-методов в пачке и доля list от всех команд. */
1594
- L(j, Rt, 8), L(j, bt, 0.65);
1592
+ L(j, Et, 5), /** Явный сигнал: много отдельных выборок сделок по фильтрам. */
1593
+ L(j, Rt, 5), /** Достаточно «list»-методов в пачке и доля list от всех команд. */
1594
+ L(j, bt, 8), L(j, Lt, 0.65);
1595
1595
  let v = j;
1596
1596
  var et;
1597
- class se {
1597
+ class re {
1598
1598
  constructor() {
1599
1599
  L(this, et, {});
1600
1600
  }
@@ -1664,21 +1664,21 @@ class se {
1664
1664
  }
1665
1665
  }
1666
1666
  et = new WeakMap();
1667
- const xt = new se();
1668
- var K, Q, st, ot, ft, Z, X, rt, At, Mt, re, mt, jt, Dt, ie, wt, ne, kt, ae;
1667
+ const xt = new re();
1668
+ var K, q, st, ot, ft, Z, X, rt, At, Dt, ie, mt, jt, wt, ne, kt, ae, Bt, oe;
1669
1669
  class _e {
1670
1670
  constructor() {
1671
1671
  /** user.current — только при первом реальном использовании (сохранение лога, выгрузка). */
1672
- L(this, Mt);
1672
+ L(this, Dt);
1673
1673
  /** Вывод ошибок логера
1674
1674
  * @param {'entity'} type - тип ошибки
1675
1675
  */
1676
1676
  L(this, mt);
1677
- L(this, Dt);
1678
1677
  L(this, wt);
1679
1678
  L(this, kt);
1679
+ L(this, Bt);
1680
1680
  L(this, K, "logger");
1681
- L(this, Q, !1);
1681
+ L(this, q, !1);
1682
1682
  L(this, st, /* @__PURE__ */ new Map());
1683
1683
  L(this, ot, {});
1684
1684
  L(this, ft, !1);
@@ -1699,7 +1699,7 @@ class _e {
1699
1699
  if (e.find(
1700
1700
  (i) => i.ENTITY == M(this, K)
1701
1701
  ))
1702
- F(this, Q, !0);
1702
+ x(this, q, !0);
1703
1703
  else {
1704
1704
  let { entityAdd: i } = await t.batch({
1705
1705
  entityAdd: {
@@ -1711,13 +1711,20 @@ class _e {
1711
1711
  }
1712
1712
  }
1713
1713
  });
1714
- i && F(this, Q, !0);
1714
+ i && x(this, q, !0);
1715
1715
  }
1716
- return M(this, Q);
1716
+ return M(this, q);
1717
1717
  } catch (t) {
1718
1718
  return console.error("Ошибка при инициализации логера:", t), !1;
1719
1719
  }
1720
1720
  }
1721
+ /**
1722
+ * Разрешает работу start/stop без init().
1723
+ * Используется в PAGE_BACKGROUND_WORKER, где не нужно делать entity.get/entity.add.
1724
+ */
1725
+ enableBackworkerMode() {
1726
+ return x(this, q, !0), !0;
1727
+ }
1721
1728
  /**
1722
1729
  * @param {{ type: 'call'|'batch'|'batch-total-count';
1723
1730
  * data: {
@@ -1728,7 +1735,7 @@ class _e {
1728
1735
  * @returns {string|null}
1729
1736
  */
1730
1737
  start({ type: t, data: e }) {
1731
- if (!M(this, Q))
1738
+ if (!M(this, q))
1732
1739
  return _(this, mt, jt).call(this, "entity"), null;
1733
1740
  if (!t || !e)
1734
1741
  return console.error("Невалидные данные для логирования:", { type: t, data: e }), null;
@@ -1741,7 +1748,7 @@ class _e {
1741
1748
  answer: null,
1742
1749
  date: (/* @__PURE__ */ new Date()).getTime()
1743
1750
  };
1744
- return M(this, st).set(r, i), F(this, At, !0), r;
1751
+ return M(this, st).set(r, i), x(this, At, !0), r;
1745
1752
  }
1746
1753
  /**
1747
1754
  * @param {{
@@ -1754,7 +1761,7 @@ class _e {
1754
1761
  var c;
1755
1762
  if (!M(this, At))
1756
1763
  return;
1757
- if (!M(this, Q)) {
1764
+ if (!M(this, q)) {
1758
1765
  _(this, mt, jt).call(this, "entity");
1759
1766
  return;
1760
1767
  }
@@ -1763,7 +1770,7 @@ class _e {
1763
1770
  console.error(`Не найдены данные логирования для ключа: ${t}`);
1764
1771
  return;
1765
1772
  }
1766
- e && (a.errorList = e), r && (a.status = r), i && (a.answer = i), await _(this, Mt, re).call(this), a.userInfo = M(this, ot), await _(this, Dt, ie).call(this), (c = a == null ? void 0 : a.data) != null && c.updateList && F(this, rt, !0), F(this, At, !1);
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, wt, ne).call(this), (c = a == null ? void 0 : a.data) != null && c.updateList && x(this, rt, !0), x(this, At, !1);
1767
1774
  }
1768
1775
  /**
1769
1776
  * @param { ({percent}:{percent:number})=>{} } progressCall - коллбэк
@@ -1799,7 +1806,7 @@ class _e {
1799
1806
  c
1800
1807
  ), null;
1801
1808
  }
1802
- }).filter((a) => a !== null), F(this, rt, !1), F(this, X, i), i);
1809
+ }).filter((a) => a !== null), x(this, rt, !1), x(this, X, i), i);
1803
1810
  } catch (r) {
1804
1811
  return console.error("Ошибка при получении списка записей:", r), [];
1805
1812
  }
@@ -1809,14 +1816,14 @@ class _e {
1809
1816
  * Не вызывается из `init` — вызывайте явно (например, из настроек или планировщика).
1810
1817
  */
1811
1818
  runStorageMaintenance() {
1812
- return _(this, wt, ne).call(this);
1819
+ return _(this, kt, ae).call(this);
1813
1820
  }
1814
1821
  /** Выгрузка всех данных из хранилища в JSON-файл */
1815
1822
  async downAllEntityJson() {
1816
1823
  try {
1817
1824
  if (M(this, X) || await this.getEntityList(), !M(this, X) || M(this, X).length === 0)
1818
1825
  return console.warn("Нет данных для выгрузки"), !1;
1819
- let t = pt().format("%Y-%m-%d");
1826
+ let t = Nt().format("%Y-%m-%d");
1820
1827
  return xt.downloadFileJson(
1821
1828
  M(this, X),
1822
1829
  `sdklogger-entity-data__${t}`
@@ -1826,21 +1833,21 @@ class _e {
1826
1833
  }
1827
1834
  }
1828
1835
  }
1829
- K = new WeakMap(), Q = new WeakMap(), st = new WeakMap(), ot = new WeakMap(), ft = new WeakMap(), Z = new WeakMap(), X = new WeakMap(), rt = new WeakMap(), At = new WeakMap(), Mt = new WeakSet(), re = async function() {
1836
+ K = new WeakMap(), q = new WeakMap(), st = new WeakMap(), ot = new WeakMap(), ft = new WeakMap(), Z = new WeakMap(), X = new WeakMap(), rt = new WeakMap(), At = new WeakMap(), Dt = new WeakSet(), ie = async function() {
1830
1837
  if (!M(this, ft))
1831
- return M(this, Z) ? M(this, Z) : (F(this, Z, (async () => {
1838
+ return M(this, Z) ? M(this, Z) : (x(this, Z, (async () => {
1832
1839
  try {
1833
1840
  const t = new v(BX24.callBatch), e = BX24.isAdmin(), { curUser: r } = await t.batch({
1834
1841
  curUser: { method: "user.current" }
1835
1842
  });
1836
- F(this, ot, { isAdmin: e, curUser: r });
1843
+ x(this, ot, { isAdmin: e, curUser: r });
1837
1844
  } catch (t) {
1838
1845
  console.error(
1839
1846
  "Ошибка при получении информации о пользователе:",
1840
1847
  t
1841
- ), F(this, ot, { isAdmin: !1, curUser: null });
1848
+ ), x(this, ot, { isAdmin: !1, curUser: null });
1842
1849
  } finally {
1843
- F(this, ft, !0), F(this, Z, null);
1850
+ x(this, ft, !0), x(this, Z, null);
1844
1851
  }
1845
1852
  })()), M(this, Z));
1846
1853
  }, mt = new WeakSet(), jt = function(t) {
@@ -1851,7 +1858,7 @@ K = new WeakMap(), Q = new WeakMap(), st = new WeakMap(), ot = new WeakMap(), ft
1851
1858
  console.error("Хранилище для логгера не инициализировано");
1852
1859
  }
1853
1860
  });
1854
- }, Dt = new WeakSet(), ie = async function() {
1861
+ }, wt = new WeakSet(), ne = async function() {
1855
1862
  try {
1856
1863
  let t = {}, e = new v(BX24.callBatch);
1857
1864
  for (let [r, i] of M(this, st).entries())
@@ -1876,7 +1883,7 @@ K = new WeakMap(), Q = new WeakMap(), st = new WeakMap(), ot = new WeakMap(), ft
1876
1883
  } catch (t) {
1877
1884
  return console.error("Ошибка при добавлении записей в хранилище:", t), !1;
1878
1885
  }
1879
- }, wt = new WeakSet(), ne = async function() {
1886
+ }, kt = new WeakSet(), ae = async function() {
1880
1887
  try {
1881
1888
  let t = new v(BX24.callBatch), { serverTime: e } = await t.batch({
1882
1889
  serverTime: { method: "server.time" }
@@ -1890,8 +1897,8 @@ K = new WeakMap(), Q = new WeakMap(), st = new WeakMap(), ot = new WeakMap(), ft
1890
1897
  let r = M(this, X).filter((i) => {
1891
1898
  try {
1892
1899
  let { dateCreate: a } = i;
1893
- return a ? pt(new Date(a)).between(
1894
- pt(new Date(e)),
1900
+ return a ? Nt(new Date(a)).between(
1901
+ Nt(new Date(e)),
1895
1902
  "month"
1896
1903
  ) >= this.periodClear : !1;
1897
1904
  } catch (a) {
@@ -1900,11 +1907,11 @@ K = new WeakMap(), Q = new WeakMap(), st = new WeakMap(), ot = new WeakMap(), ft
1900
1907
  });
1901
1908
  r.length > 0 && (console.log(
1902
1909
  `Найдено ${r.length} записей для очистки (старше ${this.periodClear} месяцев)`
1903
- ), await _(this, kt, ae).call(this, r));
1910
+ ), await _(this, Bt, oe).call(this, r));
1904
1911
  } catch (t) {
1905
1912
  console.error("Ошибка при проверке периода очистки:", t);
1906
1913
  }
1907
- }, kt = new WeakSet(), ae = async function(t) {
1914
+ }, Bt = new WeakSet(), oe = async function(t) {
1908
1915
  try {
1909
1916
  if (!t || t.length === 0)
1910
1917
  return !1;
@@ -1921,12 +1928,12 @@ K = new WeakMap(), Q = new WeakMap(), st = new WeakMap(), ot = new WeakMap(), ft
1921
1928
  if (r.length === 0)
1922
1929
  return !1;
1923
1930
  const i = await e.batch(r);
1924
- return console.log(`Успешно удалено ${r.length} записей`), F(this, rt, !0), i;
1931
+ return console.log(`Успешно удалено ${r.length} записей`), x(this, rt, !0), i;
1925
1932
  } catch (e) {
1926
1933
  return console.error("Ошибка при очистке устаревших записей:", e), !1;
1927
1934
  }
1928
1935
  };
1929
- function Qt(y) {
1936
+ function Zt(y) {
1930
1937
  if (!y || typeof y != "string")
1931
1938
  return "";
1932
1939
  try {
@@ -1938,23 +1945,23 @@ function Qt(y) {
1938
1945
  return y.split("?")[0].split("#")[0].replace(/\/$/, "");
1939
1946
  }
1940
1947
  }
1941
- function oe(y) {
1948
+ function Ae(y) {
1942
1949
  return !y || typeof y != "string" ? !1 : y.toLowerCase().includes("/marketplace/app");
1943
1950
  }
1944
1951
  function Te() {
1945
1952
  var t;
1946
1953
  if (typeof window > "u" || !((t = window.location) != null && t.href))
1947
1954
  return "";
1948
- const y = Qt(window.location.href);
1949
- return oe(y) ? "" : y;
1955
+ const y = Zt(window.location.href);
1956
+ return Ae(y) ? "" : y;
1950
1957
  }
1951
1958
  function Kt(y) {
1952
1959
  if (!(y != null && y.appConst) || typeof y.appConst != "object")
1953
1960
  return "";
1954
1961
  const t = Te();
1955
- return t ? (y.appConst.pathApp = t, t) : Qt(y.appConst.pathApp ?? "");
1962
+ return t ? (y.appConst.pathApp = t, t) : Zt(y.appConst.pathApp ?? "");
1956
1963
  }
1957
- var ct, Ot, Bt, Ae, Ct, ce, Ut, le, Ht, he, Gt, ue, V, nt, dt, vt, Yt, fe, gt, qt, Pt, me;
1964
+ var ct, _t, Ct, ce, dt, vt, Ut, le, Ht, he, Gt, ue, V, nt, gt, qt, Yt, fe, yt, zt, Pt, me;
1958
1965
  class Ie {
1959
1966
  /**
1960
1967
  * @param {Object} appConst - Константы приложения
@@ -1969,13 +1976,13 @@ class Ie {
1969
1976
  * @returns {Batch} Shared Batch instance.
1970
1977
  */
1971
1978
  L(this, ct);
1972
- L(this, Bt);
1979
+ L(this, Ct);
1973
1980
  /**
1974
1981
  * `this.logger === true` → `BxLogger` + лёгкий `init` (сущность хранилища, без полной выгрузки);
1975
1982
  * иначе — заглушка.
1976
1983
  * @param {boolean} runLoggerMaintenance
1977
1984
  */
1978
- L(this, Ct);
1985
+ L(this, dt);
1979
1986
  /**
1980
1987
  * @returns {boolean}
1981
1988
  */
@@ -1985,7 +1992,7 @@ class Ie {
1985
1992
  /** Запрос данных о текущем пользователе */
1986
1993
  L(this, Gt);
1987
1994
  L(this, V);
1988
- L(this, dt);
1995
+ L(this, gt);
1989
1996
  /**
1990
1997
  * Расширяет errorList для случаев TIMEOUT и LIMIT
1991
1998
  * Если есть ошибки TIMEOUT или LIMIT, добавляет все необработанные сущности из commandList
@@ -2000,7 +2007,7 @@ class Ie {
2000
2007
  * Нормализует входные данные в массив объектов {placement, handler?}
2001
2008
  * @private
2002
2009
  */
2003
- L(this, gt);
2010
+ L(this, yt);
2004
2011
  /**
2005
2012
  * Находит встройки с устаревшим handler (не содержащим текущий pathApp)
2006
2013
  * @private
@@ -2029,7 +2036,7 @@ class Ie {
2029
2036
  * @returns {() => void} Функция отписки.
2030
2037
  */
2031
2038
  subscribeTimeLimit(t) {
2032
- return _(this, ct, Ot).call(this).subscribeTimeLimit(t);
2039
+ return _(this, ct, _t).call(this).subscribeTimeLimit(t);
2033
2040
  }
2034
2041
  /**
2035
2042
  * Единая инициализация: внутри автоматически выбирается ветка обычного приложения или
@@ -2056,9 +2063,13 @@ class Ie {
2056
2063
  const c = _(this, Ut, le).call(this);
2057
2064
  if (console.info(
2058
2065
  c ? "init BX24 (background worker)" : "init BX24"
2059
- ), this.appInfo = await _(this, Ht, he).call(this), this.userInfo = await _(this, Gt, ue).call(this), Kt(this), !c) {
2060
- await _(this, Ct, ce).call(this, !0);
2061
- const l = new se();
2066
+ ), this.appInfo = await _(this, Ht, he).call(this), this.userInfo = await _(this, Gt, ue).call(this), Kt(this), c)
2067
+ await _(this, dt, vt).call(this, !1, {
2068
+ skipInit: !0
2069
+ });
2070
+ else {
2071
+ await _(this, dt, vt).call(this, !0);
2072
+ const l = new re();
2062
2073
  try {
2063
2074
  l.noSleep();
2064
2075
  } catch (u) {
@@ -2124,7 +2135,7 @@ class Ie {
2124
2135
  const l = new Error("BX24 is not initialized");
2125
2136
  throw console.error(l), l;
2126
2137
  }
2127
- const c = await _(this, ct, Ot).call(this).call({ method: t, params: e });
2138
+ const c = await _(this, ct, _t).call(this).call({ method: t, params: e });
2128
2139
  return c.success ? (await _(this, V, nt).call(this, i, {
2129
2140
  answer: c.answer,
2130
2141
  status: "success"
@@ -2158,7 +2169,7 @@ class Ie {
2158
2169
  const c = new Error("BX24 is not initialized");
2159
2170
  return console.error(c), !1;
2160
2171
  }
2161
- return _(this, dt, vt).call(this, {
2172
+ return _(this, gt, qt).call(this, {
2162
2173
  mode: "batch",
2163
2174
  commandList: t,
2164
2175
  progressCall: e,
@@ -2194,7 +2205,7 @@ class Ie {
2194
2205
  const a = new Error("BX24 is not initialized");
2195
2206
  return console.error(a), !1;
2196
2207
  }
2197
- return _(this, dt, vt).call(this, {
2208
+ return _(this, gt, qt).call(this, {
2198
2209
  mode: "batch-total-count",
2199
2210
  commandList: t,
2200
2211
  progressCall: e,
@@ -2216,7 +2227,7 @@ class Ie {
2216
2227
  if (!this.isAdmin || (this.placeData = await this.getPlacement(), !this.placeData))
2217
2228
  return;
2218
2229
  const { appName: e, pathApp: r } = this.appConst;
2219
- let i = _(this, gt, qt).call(this, t);
2230
+ let i = _(this, yt, zt).call(this, t);
2220
2231
  i = i.filter(
2221
2232
  (h) => h.placement !== "PAGE_BACKGROUND_WORKER" && h.placement !== "PAGE_BACKGROUND_WORKER_ALL"
2222
2233
  );
@@ -2269,7 +2280,7 @@ class Ie {
2269
2280
  * @param {string|string[]|Object|Object[]} place - Место или массив мест для отвязки
2270
2281
  */
2271
2282
  async placementUnBind(t) {
2272
- let e = _(this, gt, qt).call(this, t);
2283
+ let e = _(this, yt, zt).call(this, t);
2273
2284
  if (e = e.filter(
2274
2285
  (i) => i.placement !== "PAGE_BACKGROUND_WORKER" && i.placement !== "PAGE_BACKGROUND_WORKER_ALL"
2275
2286
  ), e.length === 0)
@@ -2322,7 +2333,7 @@ class Ie {
2322
2333
  // Цвет чат-бота для мобильного приложения RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
2323
2334
  EMAIL: "",
2324
2335
  // E-mail для связи. НЕЛЬЗЯ использовать e-mail, дублирующий e-mail реальных пользователей
2325
- PERSONAL_BIRTHDAY: pt().format("%Y-%m-%d"),
2336
+ PERSONAL_BIRTHDAY: Nt().format("%Y-%m-%d"),
2326
2337
  // День рождения в формате YYYY-mm-dd
2327
2338
  WORK_POSITION: "Почтальон",
2328
2339
  // Занимаемая должность, используется как описание чат-бота
@@ -2352,12 +2363,12 @@ class Ie {
2352
2363
  return this.logger.getEntityList(t);
2353
2364
  }
2354
2365
  }
2355
- ct = new WeakSet(), Ot = function() {
2366
+ ct = new WeakSet(), _t = function() {
2356
2367
  return this.batchClient || (this.batchClient = new v({
2357
2368
  callBatch: BX24.callBatch,
2358
2369
  callMethod: BX24.callMethod
2359
2370
  }), this.timeLimit = this.batchClient.timeLimit), this.batchClient;
2360
- }, Bt = new WeakSet(), Ae = function() {
2371
+ }, Ct = new WeakSet(), ce = function() {
2361
2372
  return {
2362
2373
  start: () => {
2363
2374
  },
@@ -2366,8 +2377,8 @@ ct = new WeakSet(), Ot = function() {
2366
2377
  getEntityList: () => {
2367
2378
  }
2368
2379
  };
2369
- }, Ct = new WeakSet(), ce = async function(t) {
2370
- this.logger ? (this.logger = new _e(), await this.logger.init(), t && typeof this.logger.runStorageMaintenance == "function" && this.logger.runStorageMaintenance()) : this.logger = _(this, Bt, Ae).call(this);
2380
+ }, dt = new WeakSet(), vt = async function(t, { skipInit: e = !1 } = {}) {
2381
+ this.logger ? (this.logger = new _e(), e ? this.logger.enableBackworkerMode() : await this.logger.init(), t && typeof this.logger.runStorageMaintenance == "function" && this.logger.runStorageMaintenance()) : this.logger = _(this, Ct, ce).call(this);
2371
2382
  }, Ut = new WeakSet(), le = function() {
2372
2383
  var r, i, a;
2373
2384
  const t = (r = this.placeInfo) == null ? void 0 : r.placement, e = (a = (i = this.placeInfo) == null ? void 0 : i.options) == null ? void 0 : a.ID;
@@ -2386,7 +2397,7 @@ ct = new WeakSet(), Ot = function() {
2386
2397
  } catch (r) {
2387
2398
  console.error("Logger error:", r);
2388
2399
  }
2389
- }, dt = new WeakSet(), vt = async function({
2400
+ }, gt = new WeakSet(), qt = async function({
2390
2401
  mode: t,
2391
2402
  commandList: e,
2392
2403
  progressCall: r,
@@ -2394,7 +2405,7 @@ ct = new WeakSet(), Ot = function() {
2394
2405
  updateList: a,
2395
2406
  batchOptions: c
2396
2407
  }) {
2397
- const l = _(this, ct, Ot).call(this), u = a ? this.logger.start({
2408
+ const l = _(this, ct, _t).call(this), u = a ? this.logger.start({
2398
2409
  type: t,
2399
2410
  data: t === "batch" ? { commandList: e, updateList: a } : { commandList: e }
2400
2411
  }) : void 0;
@@ -2440,7 +2451,7 @@ ct = new WeakSet(), Ot = function() {
2440
2451
  !n.has(d) && !t.errors[d] && (a[d] = f || "TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан");
2441
2452
  }
2442
2453
  return a;
2443
- }, gt = new WeakSet(), qt = function(t) {
2454
+ }, yt = new WeakSet(), zt = function(t) {
2444
2455
  if (!t)
2445
2456
  return [];
2446
2457
  let e = [];
@@ -2467,7 +2478,7 @@ function be(y = "default") {
2467
2478
  const t = `${de}bc:${y}`;
2468
2479
  return Ft.has(t) || Ft.set(t, new BroadcastChannel(t)), Ft.get(t);
2469
2480
  }
2470
- function Zt(y, t) {
2481
+ function Vt(y, t) {
2471
2482
  const e = be(y);
2472
2483
  if (e)
2473
2484
  try {
@@ -2488,23 +2499,23 @@ async function Le(y, t, e = {}) {
2488
2499
  async (c) => {
2489
2500
  if (r && c == null)
2490
2501
  return { skipped: !0, coordination: "locks" };
2491
- Zt(i, { type: "lock-acquired", resource: i });
2502
+ Vt(i, { type: "lock-acquired", resource: i });
2492
2503
  try {
2493
2504
  return { skipped: !1, result: await t(), coordination: "locks" };
2494
2505
  } finally {
2495
- Zt(i, { type: "lock-released", resource: i });
2506
+ Vt(i, { type: "lock-released", resource: i });
2496
2507
  }
2497
2508
  }
2498
2509
  ) : { skipped: !1, result: await t(), coordination: "none" };
2499
2510
  }
2500
- var yt, zt;
2511
+ var pt, Qt;
2501
2512
  class Me {
2502
2513
  constructor(t) {
2503
2514
  /**
2504
2515
  * Канонический base URL для placement (без завершающего `/`).
2505
2516
  * Пустая строка — не биндить (некорректный или marketplace URL).
2506
2517
  */
2507
- L(this, yt);
2518
+ L(this, pt);
2508
2519
  H(this, "entityName", "tabs");
2509
2520
  H(this, "maxTabs", 20);
2510
2521
  H(this, "tabList", []);
@@ -2528,7 +2539,7 @@ class Me {
2528
2539
  return;
2529
2540
  }
2530
2541
  const { appFunc: e, bx: r, users: i, continueBackground: a } = t;
2531
- this.bx = r, this.appInit = e, this.users = i, Kt(r), this.appPath = _(this, yt, zt).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 = /* @__PURE__ */ new Date(), this.continueCondition = typeof a == "function" ? a : this.defaultContinueBackground;
2542
+ this.bx = r, this.appInit = e, this.users = i, Kt(r), this.appPath = _(this, pt, Qt).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 = /* @__PURE__ */ new Date(), this.continueCondition = typeof a == "function" ? a : this.defaultContinueBackground;
2532
2543
  }
2533
2544
  async init() {
2534
2545
  if (!this.appInit) {
@@ -2813,7 +2824,7 @@ class Me {
2813
2824
  return;
2814
2825
  }
2815
2826
  (p = this.users) != null && p.length || await this.getEntityData(), Kt(this.bx);
2816
- const t = _(this, yt, zt).call(this, ((C = (S = this.bx) == null ? void 0 : S.appConst) == null ? void 0 : C.pathApp) ?? "");
2827
+ const t = _(this, pt, Qt).call(this, ((C = (S = this.bx) == null ? void 0 : S.appConst) == null ? void 0 : C.pathApp) ?? "");
2817
2828
  if (!t) {
2818
2829
  console.error(
2819
2830
  "BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена"
@@ -2994,11 +3005,11 @@ class Me {
2994
3005
  }
2995
3006
  }
2996
3007
  }
2997
- yt = new WeakSet(), zt = function(t) {
3008
+ pt = new WeakSet(), Qt = function(t) {
2998
3009
  if (!t || typeof t != "string")
2999
3010
  return "";
3000
- const e = Qt(t).replace(/\/+$/, "");
3001
- return e ? oe(e) ? (console.error(
3011
+ const e = Zt(t).replace(/\/+$/, "");
3012
+ return e ? Ae(e) ? (console.error(
3002
3013
  "BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."
3003
3014
  ), "") : e : "";
3004
3015
  };
@@ -3006,7 +3017,7 @@ export {
3006
3017
  Me as BackgroundWorker,
3007
3018
  v as Batch,
3008
3019
  Ie as BxBoot,
3009
- se as BxHelper,
3020
+ re as BxHelper,
3010
3021
  _e as BxLogger,
3011
- pt as tempus
3022
+ Nt as tempus
3012
3023
  };
@@ -1,2 +1,2 @@
1
- var Ie=Object.defineProperty;var Me=(k,C,Y)=>C in k?Ie(k,C,{enumerable:!0,configurable:!0,writable:!0,value:Y}):k[C]=Y;var P=(k,C,Y)=>(Me(k,typeof C!="symbol"?C+"":C,Y),Y),qt=(k,C,Y)=>{if(!C.has(k))throw TypeError("Cannot "+Y)};var M=(k,C,Y)=>(qt(k,C,"read from private field"),Y?Y.call(k):C.get(k)),L=(k,C,Y)=>{if(C.has(k))throw TypeError("Cannot add the same private member more than once");C instanceof WeakSet?C.add(k):C.set(k,Y)},K=(k,C,Y,ot)=>(qt(k,C,"write to private field"),ot?ot.call(k,Y):C.set(k,Y),Y);var O=(k,C,Y)=>(qt(k,C,"access private method"),Y);(function(k,C){typeof exports=="object"&&typeof module<"u"?C(exports):typeof define=="function"&&define.amd?define(["exports"],C):(k=typeof globalThis<"u"?globalThis:k||self,C(k["szdl-utils-kit"]={}))})(this,function(k){var Et,ne,bt,Rt,Lt,St,At,Ft,It,ae,Mt,oe,Z,ut,st,_t,rt,Tt,Dt,Ae,dt,Qt,it,Q,V,nt,ct,gt,$,j,at,lt,Bt,ce,yt,Zt,kt,le,wt,he,Ct,ue,ht,Xt,Ht,fe,Ut,me,Gt,de,Pt,ge,Yt,ye,tt,ft,pt,Vt,Wt,pe,Nt,$t,xt,Ne,Ot,te;"use strict";var C=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Y(T){return T&&T.__esModule&&Object.prototype.hasOwnProperty.call(T,"default")?T.default:T}var ot={exports:{}};(function(T,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]},b=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]},R=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,S,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()},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},B;B=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},B.fn=B.prototype,B.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},B.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},B.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},B.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},B.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},B.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},B.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},B.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},B.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)},B.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,J=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&&J+W<t.length&&!isNaN(Number(t.charAt(J+W)));)v+=t.charAt(J+W),W+=1;break;case"word":for(;W<E[G].maxLength&&J+W<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(J+W));)v+=t.charAt(J+W),W+=1;break;case"string":for(;W<E[G].maxLength&&J+W<t.length;)v+=t.charAt(J+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,J+=W,X+=1}}else if(t.charAt(J)!==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,J+=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},B.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},B.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},B.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)},B.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()})},B.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}},B.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()}}},B.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},B.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},B.fn.errors=function(){return this._i},B.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}},B.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 B(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 B?o=t.dateFrom.utc():o=n(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof B?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 J={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(J).utc();n(g).get()[t.groupBy]===et;)X(G[G.length-1],g,!0),g=n(g).calc(J).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:B},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,Et);L(this,At);L(this,It);L(this,Mt);L(this,Z);L(this,st);L(this,rt);L(this,Dt);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,Et,ne).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,Mt,oe).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,Tt).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,_t).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,Dt,Ae).call(this,s,e);if(!f){await O(this,Z,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,Z,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,Tt).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,B=typeof w=="string"&&(w.includes(".list")||w==="user.get"||w==="entity.item.get"),t=e==="count"?!p&&U===this.limit:B?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,_t).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,B=(I=(p=b.error())==null?void 0:p.ex)==null?void 0:I.error_description;this.errors[R]=w&&w.trim()||B&&B.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,Tt).call(this,{[I]:E},async m=>{w=m,l(m)});const B=S<n;await O(this,st,_t).call(this,w,B),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,Tt).call(this,Object.fromEntries(d),async _=>{l(_),await O(this,st,_t).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()}};Et=new WeakSet,ne=function(){const s=this.totalBatchCommands||0,e=this.batchCommandMethods;if(s<M(q,bt)||!Array.isArray(e)||e.length!==s)return!1;if(e.filter(a=>a==="crm.deal.list").length>=M(q,Rt))return!0;const i=e.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=M(q,Lt)&&i/s>=M(q,St)},bt=new WeakMap,Rt=new WeakMap,Lt=new WeakMap,St=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,It,ae).call(this,i)&&(this.progressCall({data:this.progressData,percent:s,allCount:e,allTotal:r}),this.lastProgressSnapshot=i)},It=new WeakSet,ae=function(s){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==s.percent||this.lastProgressSnapshot.allCount!==s.allCount||this.lastProgressSnapshot.allTotal!==s.allTotal:!0},Mt=new WeakSet,oe=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)}},Z=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,_t=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,Z,ut).call(this)},rt=new WeakSet,Tt=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,Z,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,Z,ut).call(this));return}await e(a)});while(r)},Dt=new WeakSet,Ae=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,bt,5),L(q,Rt,5),L(q,Lt,8),L(q,St,.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 ee{constructor(){L(this,Bt);L(this,yt);L(this,kt);L(this,wt);L(this,Ct);L(this,Q,"logger");L(this,V,!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)))K(this,V,!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&&K(this,V,!0)}return M(this,V)}catch(s){return console.error("Ошибка при инициализации логера:",s),!1}}start({type:s,data:e}){if(!M(this,V))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),K(this,lt,!0),r}async stop({key:s,errorList:e,status:r,answer:i}){var c;if(!M(this,lt))return;if(!M(this,V)){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,ce).call(this),a.userInfo=M(this,ct),await O(this,kt,le).call(this),(c=a==null?void 0:a.data)!=null&&c.updateList&&K(this,at,!0),K(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),K(this,at,!1),K(this,j,i),i)}catch(r){return console.error("Ошибка при получении списка записей:",r),[]}}runStorageMaintenance(){return O(this,wt,he).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,V=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,ce=async function(){if(!M(this,gt))return M(this,$)?M(this,$):(K(this,$,(async()=>{try{const s=new z(BX24.callBatch),e=BX24.isAdmin(),{curUser:r}=await s.batch({curUser:{method:"user.current"}});K(this,ct,{isAdmin:e,curUser:r})}catch(s){console.error("Ошибка при получении информации о пользователе:",s),K(this,ct,{isAdmin:!1,curUser:null})}finally{K(this,gt,!0),K(this,$,null)}})()),M(this,$))},yt=new WeakSet,Zt=function(s){s=="entity"&&Jt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},kt=new WeakSet,le=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}},wt=new WeakSet,he=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,Ct,ue).call(this,r))}catch(s){console.error("Ошибка при проверке периода очистки:",s)}},Ct=new WeakSet,ue=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} записей`),K(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 se(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 se(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,Ht);L(this,Ut);L(this,Gt);L(this,Pt);L(this,Yt);L(this,tt);L(this,pt);L(this,Wt);L(this,Nt);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,Ut,me).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,pt,Vt).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,pt,Vt).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,Nt,$t).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,Nt,$t).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},Ht=new WeakSet,fe=function(){return{start:()=>{},stop:()=>{},getEntityList:()=>{}}},Ut=new WeakSet,me=async function(s){this.logger?(this.logger=new ee,await this.logger.init(),s&&typeof this.logger.runStorageMaintenance=="function"&&this.logger.runStorageMaintenance()):this.logger=O(this,Ht,fe).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)}},pt=new WeakSet,Vt=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},Nt=new WeakSet,$t=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 re="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=`${re}bc:${T}`;return zt.has(s)||zt.set(s,new BroadcastChannel(s)),zt.get(s)}function ie(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=`${re}${i}`;return be()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!r},async c=>{if(r&&c==null)return{skipped:!0,coordination:"locks"};ie(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await s(),coordination:"locks"}}finally{ie(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await s(),coordination:"none"}}class Se{constructor(s){L(this,Ot);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,Ot,te).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,Ot,te).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}}}Ot=new WeakSet,te=function(s){if(!s||typeof s!="string")return"";const e=Kt(s).replace(/\/+$/,"");return e?se(e)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):e:""},k.BackgroundWorker=Se,k.Batch=z,k.BxBoot=Te,k.BxHelper=jt,k.BxLogger=ee,k.tempus=mt,Object.defineProperty(k,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(T){return T&&T.__esModule&&Object.prototype.hasOwnProperty.call(T,"default")?T.default:T}var ot={exports:{}};(function(T,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]},b=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]},R=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,S,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()},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"})});
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "szdl-utils-kit",
3
3
  "description": "utils-kit library",
4
4
  "private": false,
5
- "version": "0.3.19",
5
+ "version": "0.3.20",
6
6
  "type": "module",
7
7
  "author": "Stanislav Ovv",
8
8
  "license": "BSD",