szdl-utils-kit 0.3.28 → 0.3.29

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
@@ -1,6 +1,6 @@
1
1
  var ke = Object.defineProperty;
2
- var we = (d, e, t) => e in d ? ke(d, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : d[e] = t;
3
- var w = (d, e, t) => (we(d, typeof e != "symbol" ? e + "" : e, t), t), Qt = (d, e, t) => {
2
+ var Ce = (d, e, t) => e in d ? ke(d, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : d[e] = t;
3
+ var C = (d, e, t) => (Ce(d, typeof e != "symbol" ? e + "" : e, t), t), Qt = (d, e, t) => {
4
4
  if (!e.has(d))
5
5
  throw TypeError("Cannot " + t);
6
6
  };
@@ -10,7 +10,7 @@ var b = (d, e, t) => (Qt(d, e, "read from private field"), t ? t.call(d) : e.get
10
10
  e instanceof WeakSet ? e.add(d) : e.set(d, t);
11
11
  }, x = (d, e, t, r) => (Qt(d, e, "write to private field"), r ? r.call(d, t) : e.set(d, t), t);
12
12
  var p = (d, e, t) => (Qt(d, e, "access private method"), t);
13
- var Ce = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
13
+ var we = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
14
14
  function Be(d) {
15
15
  return d && d.__esModule && Object.prototype.hasOwnProperty.call(d, "default") ? d.default : d;
16
16
  }
@@ -239,7 +239,7 @@ var $t = { exports: {} };
239
239
  c[A].NOVEMBER_SHORT,
240
240
  c[A].DECEMBER_SHORT
241
241
  ];
242
- }, R = function() {
242
+ }, L = function() {
243
243
  return [
244
244
  c[A].SUNDAY_LONG,
245
245
  c[A].MONDAY_LONG,
@@ -259,7 +259,7 @@ var $t = { exports: {} };
259
259
  c[A].FRIDAY_SHORT,
260
260
  c[A].SATURDAY_SHORT
261
261
  ];
262
- }, T, L, G, O, S = function(s, o, m) {
262
+ }, T, R, G, O, S = function(s, o, m) {
263
263
  var y;
264
264
  r.XMLHttpRequest ? y = new XMLHttpRequest() : y = new ActiveXObject("Microsoft.XMLHTTP"), y.onreadystatechange = function() {
265
265
  y.readyState === 4 && (y.status === 200 ? o && (r.JSON === t ? alert(`Please, include json2 into your project if you want use old browsers!
@@ -340,7 +340,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
340
340
  "%b": {
341
341
  format: function(s) {
342
342
  var o = n.options("monthFromZero") ? s.month() : s.month() - 1;
343
- return L[o !== t ? o : n.MIN_MONTH];
343
+ return R[o !== t ? o : n.MIN_MONTH];
344
344
  },
345
345
  parse: function(s) {
346
346
  var o = n.monthNames().indexOf(s) + (n.options("monthFromZero") ? 0 : 1);
@@ -520,7 +520,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
520
520
  if (typeof s == "number")
521
521
  return this._d = new Date(s * (n.options("useMilliseconds") ? 1 : 1e3)), this;
522
522
  if (typeof s == "object" && (s instanceof Array ? (this.day(n.MIN_DAY), this.year(s[0]), this.month(s[1]), this.day(s[2]), this.hours(s[3]), this.minutes(s[4]), this.seconds(s[5]), this.milliseconds(s[6])) : (this.day(n.MIN_DAY), this.year(s.year), this.month(s.month), this.day(s.day), this.hours(s.hours), this.minutes(s.minutes), this.seconds(s.seconds), this.milliseconds(s.milliseconds))), typeof s == "string") {
523
- var y, H = [], D, C, Q = [], W = 0, F = 0, U, X, P = {}, Y;
523
+ var y, H = [], D, w, Q = [], W = 0, F = 0, U, X, P = {}, Y;
524
524
  if (s === t)
525
525
  return D = a(this, m), D === t && (this._i = {
526
526
  year: -1,
@@ -533,22 +533,22 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
533
533
  }), D;
534
534
  for (o === t && (o = n.detectFormat(s)); W < o.length; ) {
535
535
  if (o.charAt(W) === "%") {
536
- if (C = o.charAt(W) + o.charAt(W + 1), I[C] !== t) {
537
- switch (U = 0, X = "", I[C].type) {
536
+ if (w = o.charAt(W) + o.charAt(W + 1), I[w] !== t) {
537
+ switch (U = 0, X = "", I[w].type) {
538
538
  case "number":
539
- for (; U < I[C].maxLength && F + U < s.length && !isNaN(Number(s.charAt(F + U))); )
539
+ for (; U < I[w].maxLength && F + U < s.length && !isNaN(Number(s.charAt(F + U))); )
540
540
  X += s.charAt(F + U), U += 1;
541
541
  break;
542
542
  case "word":
543
- for (; U < I[C].maxLength && F + U < s.length && /^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(s.charAt(F + U)); )
543
+ for (; U < I[w].maxLength && F + U < s.length && /^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(s.charAt(F + U)); )
544
544
  X += s.charAt(F + U), U += 1;
545
545
  break;
546
546
  case "string":
547
- for (; U < I[C].maxLength && F + U < s.length; )
547
+ for (; U < I[w].maxLength && F + U < s.length; )
548
548
  X += s.charAt(F + U), U += 1;
549
549
  break;
550
550
  }
551
- if (U < I[C].minLength)
551
+ if (U < I[w].minLength)
552
552
  return D = a(this, m), D === t && (this._i = {
553
553
  year: -1,
554
554
  month: -1,
@@ -558,7 +558,7 @@ 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
- H.push(C), Q.push(X), U -= 1, F += U, W += 1;
561
+ H.push(w), Q.push(X), U -= 1, F += U, W += 1;
562
562
  }
563
563
  } else if (s.charAt(F) !== o.charAt(W))
564
564
  return D = a(this, m), D === t && (this._i = {
@@ -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, y, H, D, C, Q, W;
715
+ var o, m, y, H, D, w, Q, W;
716
716
  if (typeof s.dateFrom != "number" && (s.dateFrom instanceof M ? o = s.dateFrom.utc() : o = n(s.dateFrom, s.formatFrom).utc()), typeof s.dateTo != "number" && (s.dateTo instanceof M ? m = s.dateTo.utc() : m = n(s.dateTo, s.formatTo !== t ? s.formatTo : s.formatFrom).utc()), typeof s.period == "number" ? D = {
717
717
  year: 0,
718
718
  month: 0,
@@ -734,7 +734,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
734
734
  hours: s.period.hours !== t ? s.period.hours : 0,
735
735
  minutes: s.period.minutes !== t ? s.period.minutes : 0,
736
736
  seconds: s.period.seconds !== t ? s.period.seconds : 0
737
- }), s.groupBy === t ? C = s.asObject === !0 ? {} : [] : (C = [], C.push([]), Q = n(o).get()[s.groupBy]), W = function(X, P, Y) {
737
+ }), s.groupBy === t ? w = s.asObject === !0 ? {} : [] : (w = [], w.push([]), Q = n(o).get()[s.groupBy]), W = function(X, P, Y) {
738
738
  return s.asObject === !0 ? s.format !== t ? X[n(P).format(s.format)] = {} : X[n(P).format("%F %H:%M:%S")] = {} : s.format !== t ? X.push(Y ? null : n(P).format(s.format)) : X.push(Y ? null : n(P)), X;
739
739
  }, s.groupBy !== t && s.fillNulls) {
740
740
  var F = {
@@ -747,25 +747,25 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
747
747
  milliseconds: D.milliseconds ? -D.milliseconds : t
748
748
  };
749
749
  for (y = n(o).calc(F).utc(); n(y).get()[s.groupBy] === Q; )
750
- W(C[C.length - 1], y, !0), y = n(y).calc(F).utc();
750
+ W(w[w.length - 1], y, !0), y = n(y).calc(F).utc();
751
751
  if (s.groupBy === "week") {
752
752
  var U = n(o).dayOfWeek();
753
- for (y = n(o).dayOfWeek(0).utc(); C[0].length < U && y < o; )
754
- W(C[C.length - 1], y, !0), y = n(y).calc(D).utc();
753
+ for (y = n(o).dayOfWeek(0).utc(); w[0].length < U && y < o; )
754
+ W(w[w.length - 1], y, !0), y = n(y).calc(D).utc();
755
755
  }
756
756
  }
757
757
  for (; o <= m; )
758
- s.groupBy === t ? W(C, o) : n(o).get()[s.groupBy] === Q ? W(C[C.length - 1], o) : (C.push([]), W(C[C.length - 1], o), Q = n(o).get()[s.groupBy]), o = n(o).calc(D).utc();
758
+ s.groupBy === t ? W(w, o) : n(o).get()[s.groupBy] === Q ? W(w[w.length - 1], o) : (w.push([]), W(w[w.length - 1], o), Q = n(o).get()[s.groupBy]), o = n(o).calc(D).utc();
759
759
  if (s.groupBy !== t && s.fillNulls)
760
760
  for (H = n(m).calc(D).utc(); n(H).get()[s.groupBy] === Q; )
761
- W(C[C.length - 1], H, !0), H = n(H).calc(D).utc();
762
- return C;
761
+ W(w[w.length - 1], H, !0), H = n(H).calc(D).utc();
762
+ return w;
763
763
  }, n.monthNames = function(s) {
764
764
  switch (s) {
765
765
  case "long":
766
766
  return T;
767
767
  default:
768
- return L;
768
+ return R;
769
769
  }
770
770
  }, n.dayNames = function(s) {
771
771
  switch (s) {
@@ -776,7 +776,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
776
776
  }
777
777
  }, n.lang = function(s) {
778
778
  if (s !== t)
779
- A = s, c[A] === t && (A = "en"), T = N(), L = _(), G = R(), O = k();
779
+ A = s, c[A] === t && (A = "en"), T = N(), R = _(), G = L(), O = k();
780
780
  else
781
781
  return A;
782
782
  return t;
@@ -806,12 +806,12 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
806
806
  c = o;
807
807
  }, function(o) {
808
808
  });
809
- }, A = (f.language || f.systemLanguage || f.userLanguage || "en").substr(0, 2).toLowerCase(), c[A] === t && (A = "en"), T = N(), L = _(), G = R(), O = k(), d.exports && (e = d.exports = n), e.tempus = n;
810
- }).call(Ce);
809
+ }, A = (f.language || f.systemLanguage || f.userLanguage || "en").substr(0, 2).toLowerCase(), c[A] === t && (A = "en"), T = N(), R = _(), G = L(), O = k(), d.exports && (e = d.exports = n), e.tempus = n;
810
+ }).call(we);
811
811
  })($t, $t.exports);
812
812
  var He = $t.exports;
813
813
  const Lt = /* @__PURE__ */ Be(He);
814
- var It, he, Dt, kt, wt, Ct, ot, bt, Bt, ue, Ht, fe, $, ut, tt, ft, gt, te, et, dt, Ut, de, Pt, me, At, Mt, yt, ee, pt, se;
814
+ var It, he, Dt, kt, Ct, wt, ot, bt, Bt, ue, Ht, fe, $, ut, tt, ft, gt, te, et, dt, Ut, de, Pt, me, At, Mt, yt, ee, pt, se;
815
815
  const J = class J {
816
816
  constructor(e) {
817
817
  /**
@@ -923,8 +923,8 @@ const J = class J {
923
923
  const N = this.progressData[c];
924
924
  if (!N)
925
925
  continue;
926
- const _ = Number(N.total) || 0, R = Number(N.count) || 0;
927
- _ === 0 && R === 0 ? u += 1 : _ > 0 && (u += Math.min(1, R / _));
926
+ const _ = Number(N.total) || 0, L = Number(N.count) || 0;
927
+ _ === 0 && L === 0 ? u += 1 : _ > 0 && (u += Math.min(1, L / _));
928
928
  }
929
929
  const n = u / e * 100;
930
930
  let g = Math.max(0, Math.min(100, Math.floor(n)));
@@ -959,8 +959,8 @@ const J = class J {
959
959
  if (typeof t.total == "function") {
960
960
  const _ = t.total();
961
961
  if (_ != null && _ !== "") {
962
- const R = Number(_);
963
- Number.isFinite(R) && (l = R);
962
+ const L = Number(_);
963
+ Number.isFinite(L) && (l = L);
964
964
  }
965
965
  }
966
966
  let h = 1;
@@ -1329,14 +1329,14 @@ const J = class J {
1329
1329
  */
1330
1330
  arrayChunk(e) {
1331
1331
  let t = "", r = {};
1332
- if (Array.isArray(e) ? [t] = e : (t = e.method, r = e.params), (t.includes("list") || t === "user.get" || t === "entity.item.get") && t !== "task.item.list") {
1332
+ if (Array.isArray(e) ? [t] = e : (t = e.method, r = e.params), (t.includes("list") || t === "user.get" || t === "entity.item.get" || t === "sonet_group.get") && t !== "task.item.list") {
1333
1333
  if (!r)
1334
- r = t === "entity.item.get" ? { SORT: { ID: "ASC" } } : {
1334
+ r = t === "entity.item.get" ? { SORT: { ID: "ASC" } } : t === "sonet_group.get" ? { ORDER: { ID: "ASC" } } : {
1335
1335
  order: { ID: "ASC", id: "ASC" }
1336
1336
  };
1337
1337
  else {
1338
- t === "entity.item.get" ? (r.SORT || (r.SORT = { ID: "ASC" }), Array.isArray(r.select) ? r.select.includes("ID") || r.select.push("ID") : r.select = ["ID"]) : t === "tasks.task.list" ? (r.order || (r.order = {}), r.order.ID = "asc") : t === "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");
1339
- const i = t === "user.get" || t === "entity.item.get" ? r.FILTER : r.filter;
1338
+ t === "entity.item.get" ? (r.SORT || (r.SORT = { ID: "ASC" }), Array.isArray(r.select) ? r.select.includes("ID") || r.select.push("ID") : r.select = ["ID"]) : t === "sonet_group.get" ? r.ORDER ? !r.ORDER.ID && !r.ORDER.id && (r.ORDER.ID = "ASC") : r.ORDER = { ID: "ASC" } : t === "tasks.task.list" ? (r.order || (r.order = {}), r.order.ID = "asc") : t === "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");
1339
+ const i = t === "user.get" || t === "entity.item.get" || t === "sonet_group.get" ? r.FILTER : r.filter;
1340
1340
  typeof i == "object" && i !== null && !Array.isArray(i) && Object.entries(i).forEach(([a, l]) => {
1341
1341
  (r.start === void 0 || r.start !== -1) && ["id", "ID"].includes(a) && (typeof l == "string" || Array.isArray(l) && l.length <= 50) && (r.start = -1);
1342
1342
  });
@@ -1370,9 +1370,9 @@ const J = class J {
1370
1370
  if (!this.canContinue)
1371
1371
  return;
1372
1372
  c.error() && (p(this, At, Mt).call(this, A, c), h = !0);
1373
- const N = this.getData(c.data()), _ = Array.isArray(N) ? N.length : 0, R = typeof c.total == "function" && c.total() !== void 0, k = R ? c.total() : _;
1373
+ const N = this.getData(c.data()), _ = Array.isArray(N) ? N.length : 0, L = typeof c.total == "function" && c.total() !== void 0, k = L ? c.total() : _;
1374
1374
  t === "count" ? this.result[A] ? this.result[A] += _ : this.result[A] = k : this.result[A] = N, this.setProgressData({ key: A, value: c, type: t });
1375
- const T = e[A], L = Array.isArray(T) ? T[0] : T == null ? void 0 : T.method, G = typeof L == "string" && (L.includes(".list") || L === "user.get" || L === "entity.item.get"), O = t === "count" ? !R && _ === this.limit : G ? _ === this.limit : k > this.limit && k > _, S = t !== "count" && L === "entity.item.get" && _ === this.limit && !O, I = O || S;
1375
+ const T = e[A], R = Array.isArray(T) ? T[0] : T == null ? void 0 : T.method, G = typeof R == "string" && (R.includes(".list") || R === "user.get" || R === "entity.item.get" || R === "sonet_group.get"), O = t === "count" ? !L && _ === this.limit : G ? _ === this.limit : k > this.limit && k > _, S = t !== "count" && R === "entity.item.get" && _ === this.limit && !O, I = O || S;
1376
1376
  if (!u && (!this.canContinue || I)) {
1377
1377
  let B = e[A];
1378
1378
  if (Array.isArray(B)) {
@@ -1405,67 +1405,67 @@ const J = class J {
1405
1405
  * @param {{oneBatch?: boolean}} [options] - Опции выполнения payload.
1406
1406
  */
1407
1407
  async batchPayload(e, t, r = {}) {
1408
- const i = !!(r != null && r.oneBatch), a = (N, _, R, k) => {
1408
+ const i = !!(r != null && r.oneBatch), a = (N, _, L, k) => {
1409
1409
  let T = "ID";
1410
1410
  this.result[N][this.result[N].length - 1].ID || (T = "id");
1411
- let L = `${T}`;
1412
- if (JSON.stringify(k[1]).toLocaleLowerCase().includes('"id":"desc"') ? L = "<" + L : L = ">" + L, _ === 1 || R.length === 0)
1411
+ let R = `${T}`;
1412
+ if (JSON.stringify(k[1]).toLocaleLowerCase().includes('"id":"desc"') ? R = "<" + R : R = ">" + R, _ === 1 || L.length === 0)
1413
1413
  return {
1414
- field: L,
1414
+ field: R,
1415
1415
  id: this.result[N][this.result[N].length - 1][T]
1416
1416
  };
1417
1417
  let O = "";
1418
1418
  const [S, I] = k;
1419
1419
  return (S === "tasks.task.list" || S === "task.item.list") && (O = "[tasks]"), ["crm.item.list", "crm.stagehistory.list"].includes(S) && (O = "[items]"), S === "crm.type.list" && (O = "[types]"), S === "socialnetwork.api.workgroup.list" && (O = "[workgroups]"), {
1420
- field: L,
1420
+ field: R,
1421
1421
  id: `$result[${[N, _ - 1].join("__")}]${O}[49][${T}]`
1422
1422
  };
1423
1423
  }, l = (N, _) => {
1424
- const [R, k] = N;
1425
- let T = JSON.parse(JSON.stringify(k)), L;
1426
- if (R === "task.item.list") {
1424
+ const [L, k] = N;
1425
+ let T = JSON.parse(JSON.stringify(k)), R;
1426
+ if (L === "task.item.list") {
1427
1427
  T = [...T];
1428
1428
  const [G, O, S, I] = T;
1429
- return O[_.field] = _.id, [R, T];
1429
+ return O[_.field] = _.id, [L, T];
1430
1430
  }
1431
- return ["user.get"].includes(R) || T.FILTER ? (T.FILTER || (T.FILTER = {}), L = T.FILTER) : (T.filter || (T.filter = {}), L = T.filter), [
1431
+ return ["user.get", "sonet_group.get"].includes(L) || T.FILTER ? (T.FILTER || (T.FILTER = {}), R = T.FILTER) : (T.filter || (T.filter = {}), R = T.filter), [
1432
1432
  "socialnetwork.api.workgroup.list",
1433
1433
  "tasks.task.list"
1434
- ].includes(R) ? L[">ID"] = _.id : L[_.field] = _.id, [R, { ...T, start: -1 }];
1434
+ ].includes(L) ? R[">ID"] = _.id : R[_.field] = _.id, [L, { ...T, start: -1 }];
1435
1435
  }, h = (N) => {
1436
- Object.entries(N).forEach(([_, R]) => {
1437
- const [k] = _.split("__"), T = this.getData(R.data());
1438
- Array.isArray(T) && (t === "count" ? this.result[k] += T.length : this.result[k].push(...T)), R.error() && p(this, At, Mt).call(this, k, R), this.setProgressData({ key: k, value: R, type: t });
1436
+ Object.entries(N).forEach(([_, L]) => {
1437
+ const [k] = _.split("__"), T = this.getData(L.data());
1438
+ Array.isArray(T) && (t === "count" ? this.result[k] += T.length : this.result[k].push(...T)), L.error() && p(this, At, Mt).call(this, k, L), this.setProgressData({ key: k, value: L, type: t });
1439
1439
  });
1440
1440
  }, u = (N, _) => {
1441
1441
  if (!Array.isArray(N) || N.length === 0)
1442
1442
  return null;
1443
- const R = N[N.length - 1];
1443
+ const L = N[N.length - 1];
1444
1444
  let k = "ID";
1445
- R.ID || (k = "id");
1445
+ L.ID || (k = "id");
1446
1446
  let T = k;
1447
- return JSON.stringify(_[1]).toLocaleLowerCase().includes('"id":"desc"') ? T = "<" + T : T = ">" + T, { field: T, id: R[k] };
1447
+ return JSON.stringify(_[1]).toLocaleLowerCase().includes('"id":"desc"') ? T = "<" + T : T = ">" + T, { field: T, id: L[k] };
1448
1448
  }, n = 1e4, g = async (N, _) => {
1449
1449
  var k, T;
1450
- let R = this.limit;
1451
- for (let L = 1; this.canContinue && R === this.limit && L <= n; L++) {
1450
+ let L = this.limit;
1451
+ for (let R = 1; this.canContinue && L === this.limit && R <= n; R++) {
1452
1452
  const G = this.result[N], O = u(G, _);
1453
1453
  if (!O)
1454
1454
  break;
1455
- const S = `${N}__eiscan_${L}`, I = l(_, O);
1455
+ const S = `${N}__eiscan_${R}`, I = l(_, O);
1456
1456
  let B = null;
1457
1457
  await p(this, et, dt).call(this, { [S]: I }, async (m) => {
1458
1458
  B = m, h(m);
1459
1459
  });
1460
- const M = L < n;
1460
+ const M = R < n;
1461
1461
  await p(this, tt, ft).call(this, B, M), await this.delay();
1462
1462
  const s = B == null ? void 0 : B[S];
1463
1463
  if ((k = s == null ? void 0 : s.error) != null && k.call(s)) {
1464
- R = 0;
1464
+ L = 0;
1465
1465
  break;
1466
1466
  }
1467
1467
  const o = this.getData((T = s == null ? void 0 : s.data) == null ? void 0 : T.call(s));
1468
- R = Array.isArray(o) ? o.length : 0;
1468
+ L = Array.isArray(o) ? o.length : 0;
1469
1469
  }
1470
1470
  };
1471
1471
  let f = [], A = 0;
@@ -1475,21 +1475,21 @@ const J = class J {
1475
1475
  for await (const N of e) {
1476
1476
  if (!this.canContinue)
1477
1477
  return;
1478
- const [_, R, k, T = {}] = N;
1478
+ const [_, L, k, T = {}] = N;
1479
1479
  if (T.entityItemGetScan) {
1480
1480
  if (await c(!0))
1481
1481
  return;
1482
1482
  if (i)
1483
1483
  continue;
1484
- await g(_, R);
1484
+ await g(_, L);
1485
1485
  continue;
1486
1486
  }
1487
- let L = 1;
1488
- for (; k > L * this.limit; ) {
1489
- const G = [_, L].join("__"), O = a(_, L, f, R);
1490
- if (f.push([G, l(R, O)]), i && f.length === 49 && await c(!0) || f.length % 50 === 0 && await c(!0))
1487
+ let R = 1;
1488
+ for (; k > R * this.limit; ) {
1489
+ const G = [_, R].join("__"), O = a(_, R, f, L);
1490
+ if (f.push([G, l(L, O)]), i && f.length === 49 && await c(!0) || f.length % 50 === 0 && await c(!0))
1491
1491
  return;
1492
- L++;
1492
+ R++;
1493
1493
  }
1494
1494
  }
1495
1495
  await c(!1);
@@ -1512,8 +1512,8 @@ It = new WeakSet(), he = function() {
1512
1512
  const i = t.filter(
1513
1513
  (a) => typeof a == "string" && a.includes(".list")
1514
1514
  ).length;
1515
- return i >= b(J, wt) && i / e >= b(J, Ct);
1516
- }, Dt = new WeakMap(), kt = new WeakMap(), wt = new WeakMap(), Ct = new WeakMap(), ot = new WeakSet(), bt = function() {
1515
+ return i >= b(J, Ct) && i / e >= b(J, wt);
1516
+ }, Dt = new WeakMap(), kt = new WeakMap(), Ct = new WeakMap(), wt = new WeakMap(), ot = new WeakSet(), bt = function() {
1517
1517
  if (!this.progressCall || !this.progressData)
1518
1518
  return;
1519
1519
  const { percent: e, allCount: t, allTotal: r } = this.progressPercent, i = { percent: e, allCount: t, allTotal: r };
@@ -1673,7 +1673,7 @@ It = new WeakSet(), he = function() {
1673
1673
  }, /** Не включать вес по командам для совсем маленьких batch. */
1674
1674
  E(J, Dt, 5), /** Явный сигнал: много отдельных выборок сделок по фильтрам. */
1675
1675
  E(J, kt, 5), /** Достаточно «list»-методов в пачке и доля list от всех команд. */
1676
- E(J, wt, 8), E(J, Ct, 0.65);
1676
+ E(J, Ct, 8), E(J, wt, 0.65);
1677
1677
  let K = J;
1678
1678
  var st;
1679
1679
  class ge {
@@ -1769,7 +1769,7 @@ class Ue {
1769
1769
  E(this, it, !1);
1770
1770
  E(this, ct, !1);
1771
1771
  /** Очистка хранилища элементов старше 'N' месяцев */
1772
- w(this, "periodClear", 3);
1772
+ C(this, "periodClear", 3);
1773
1773
  }
1774
1774
  /** Инициализация логера */
1775
1775
  async init() {
@@ -2095,20 +2095,20 @@ class Je {
2095
2095
  * @private
2096
2096
  */
2097
2097
  E(this, Kt);
2098
- w(this, "domain", "");
2099
- w(this, "isAdmin", !1);
2100
- w(this, "appInfo", null);
2101
- w(this, "appConst", null);
2102
- w(this, "userInfo", null);
2103
- w(this, "placeData", null);
2104
- w(this, "placeInfo", null);
2105
- w(this, "logger", !1);
2106
- w(this, "timeLimit", {
2098
+ C(this, "domain", "");
2099
+ C(this, "isAdmin", !1);
2100
+ C(this, "appInfo", null);
2101
+ C(this, "appConst", null);
2102
+ C(this, "userInfo", null);
2103
+ C(this, "placeData", null);
2104
+ C(this, "placeInfo", null);
2105
+ C(this, "logger", !1);
2106
+ C(this, "timeLimit", {
2107
2107
  limit: !1,
2108
2108
  date: void 0,
2109
2109
  pauseMs: void 0
2110
2110
  });
2111
- w(this, "batchClient", null);
2111
+ C(this, "batchClient", null);
2112
2112
  this.appConst = e;
2113
2113
  }
2114
2114
  /**
@@ -2324,18 +2324,18 @@ class Je {
2324
2324
  for (const c of this.placeData)
2325
2325
  f.has(c.placement) || f.set(c.placement, []), f.get(c.placement).push(c);
2326
2326
  for (let c = 0; c < i.length; c++) {
2327
- const { placement: N, options: _ } = i[c], R = f.get(N) || [];
2328
- if (R.some(
2329
- (L) => L.handler === r
2327
+ const { placement: N, options: _ } = i[c], L = f.get(N) || [];
2328
+ if (L.some(
2329
+ (R) => R.handler === r
2330
2330
  ))
2331
2331
  continue;
2332
- const T = R.filter(
2333
- (L) => L.handler !== r
2332
+ const T = L.filter(
2333
+ (R) => R.handler !== r
2334
2334
  );
2335
- for (const L of T)
2335
+ for (const R of T)
2336
2336
  g.push({
2337
2337
  placement: N,
2338
- handler: L.handler
2338
+ handler: R.handler
2339
2339
  });
2340
2340
  n[`bind_${c}`] = {
2341
2341
  method: "placement.bind",
@@ -2645,28 +2645,28 @@ class je {
2645
2645
  E(this, nt);
2646
2646
  /** Имя Web Lock для подтверждения лидерства. */
2647
2647
  E(this, zt);
2648
- w(this, "entityName", "tabs");
2649
- w(this, "maxTabs", 20);
2650
- w(this, "tabList", []);
2651
- w(this, "id", 0);
2652
- w(this, "hasStarted", !1);
2653
- w(this, "heartbeat");
2654
- w(this, "runHeartbeat");
2655
- w(this, "startDelay", 0);
2656
- w(this, "activeMaxPause", q.activeMaxPauseMs);
2657
- w(this, "quickCleanupThreshold", q.quickCleanupThresholdMs);
2658
- w(this, "pollInterval", q.pollIntervalMs);
2659
- w(this, "pollIntervalBase", q.pollIntervalMs);
2660
- w(this, "pollIntervalJitter", q.pollIntervalJitterMs);
2661
- w(this, "leaderConfirmDelay", q.leaderConfirmDelayMs);
2662
- w(this, "leaderHeartbeatMs", null);
2663
- w(this, "sessionId", `${Date.now()}-${Math.random().toString(16).slice(2)}`);
2664
- w(this, "continueCondition");
2665
- w(this, "defaultContinueBackground", () => !0);
2648
+ C(this, "entityName", "tabs");
2649
+ C(this, "maxTabs", 20);
2650
+ C(this, "tabList", []);
2651
+ C(this, "id", 0);
2652
+ C(this, "hasStarted", !1);
2653
+ C(this, "heartbeat");
2654
+ C(this, "runHeartbeat");
2655
+ C(this, "startDelay", 0);
2656
+ C(this, "activeMaxPause", q.activeMaxPauseMs);
2657
+ C(this, "quickCleanupThreshold", q.quickCleanupThresholdMs);
2658
+ C(this, "pollInterval", q.pollIntervalMs);
2659
+ C(this, "pollIntervalBase", q.pollIntervalMs);
2660
+ C(this, "pollIntervalJitter", q.pollIntervalJitterMs);
2661
+ C(this, "leaderConfirmDelay", q.leaderConfirmDelayMs);
2662
+ C(this, "leaderHeartbeatMs", null);
2663
+ C(this, "sessionId", `${Date.now()}-${Math.random().toString(16).slice(2)}`);
2664
+ C(this, "continueCondition");
2665
+ C(this, "defaultContinueBackground", () => !0);
2666
2666
  /** @type {'user' | 'portal'} */
2667
- w(this, "coordinationScope", "user");
2667
+ C(this, "coordinationScope", "user");
2668
2668
  /** Привязывать общую встройку PAGE_BACKGROUND_WORKER без USER_ID. @default true */
2669
- w(this, "bindGeneralPlacement", !0);
2669
+ C(this, "bindGeneralPlacement", !0);
2670
2670
  var n, g, f;
2671
2671
  if (!e) {
2672
2672
  console.error("BackgroundWorker: Нет опций конструктора");
@@ -2967,7 +2967,7 @@ class je {
2967
2967
  );
2968
2968
  }
2969
2969
  async setBackgroundWorkerAll() {
2970
- var k, T, L, G;
2970
+ var k, T, R, G;
2971
2971
  if (!((k = this.bx) != null && k.isAdmin)) {
2972
2972
  console.log(
2973
2973
  "BackgroundWorker: setBackgroundWorkerAll доступен только админам"
@@ -2975,7 +2975,7 @@ class je {
2975
2975
  return;
2976
2976
  }
2977
2977
  (T = this.users) != null && T.length || await this.getEntityData(), ie(this.bx);
2978
- const e = p(this, Rt, Ae).call(this, ((G = (L = this.bx) == null ? void 0 : L.appConst) == null ? void 0 : G.pathApp) ?? "");
2978
+ const e = p(this, Rt, Ae).call(this, ((G = (R = this.bx) == null ? void 0 : R.appConst) == null ? void 0 : G.pathApp) ?? "");
2979
2979
  if (!e) {
2980
2980
  console.error(
2981
2981
  "BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена"
@@ -3065,7 +3065,7 @@ class je {
3065
3065
  });
3066
3066
  const _ = A.filter(
3067
3067
  (O) => O.method === "placement.unbind"
3068
- ), R = A.filter(
3068
+ ), L = A.filter(
3069
3069
  (O) => O.method === "placement.bind"
3070
3070
  );
3071
3071
  _.length && await this.safeCall(
@@ -3074,10 +3074,10 @@ class je {
3074
3074
  _.map((O, S) => [`unbind_${S}`, O])
3075
3075
  )
3076
3076
  )
3077
- ), R.length && await this.safeCall(
3077
+ ), L.length && await this.safeCall(
3078
3078
  () => this.bx.batch(
3079
3079
  Object.fromEntries(
3080
- R.map((O, S) => [`bind_${S}`, O])
3080
+ L.map((O, S) => [`bind_${S}`, O])
3081
3081
  )
3082
3082
  )
3083
3083
  ), A.length || console.log("setBackgroundWorkerAll: Нет операций");
@@ -1,2 +1,2 @@
1
- var Je=Object.defineProperty;var je=(M,C,P)=>C in M?Je(M,C,{enumerable:!0,configurable:!0,writable:!0,value:P}):M[C]=P;var w=(M,C,P)=>(je(M,typeof C!="symbol"?C+"":C,P),P),ne=(M,C,P)=>{if(!C.has(M))throw TypeError("Cannot "+P)};var b=(M,C,P)=>(ne(M,C,"read from private field"),P?P.call(M):C.get(M)),E=(M,C,P)=>{if(C.has(M))throw TypeError("Cannot add the same private member more than once");C instanceof WeakSet?C.add(M):C.set(M,P)},X=(M,C,P,lt)=>(ne(M,C,"write to private field"),lt?lt.call(M,P):C.set(M,P),P);var y=(M,C,P)=>(ne(M,C,"access private method"),P);(function(M,C){typeof exports=="object"&&typeof module<"u"?C(exports):typeof define=="function"&&define.amd?define(["exports"],C):(M=typeof globalThis<"u"?globalThis:M||self,C(M["szdl-utils-kit"]={}))})(this,function(M){var Dt,Ne,kt,Bt,wt,Ct,ct,Zt,Ht,Oe,Ut,_e,st,bt,rt,Mt,yt,ae,it,St,Pt,Te,Gt,Ee,ht,Vt,pt,oe,Nt,Ae,nt,Z,V,at,ut,Ot,$,J,ot,ft,Yt,Re,_t,le,Wt,Le,xt,be,Ft,Me,dt,$t,vt,Se,Tt,ce,Xt,Ie,Jt,De,jt,ke,tt,mt,Et,he,Kt,Be,Rt,ue,qt,we,zt,Ce,Lt,fe,At,It,Qt,He;"use strict";var C=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function P(_){return _&&_.__esModule&&Object.prototype.hasOwnProperty.call(_,"default")?_.default:_}var lt={exports:{}};(function(_,e){(function(t){Array.prototype.indexOf||(Array.prototype.indexOf=function(s,o){var d,g;for(d=o||0,g=this.length;d<g;d+=1)if(this[d]===s)return d;return-1});var r=this,i=function(s,o){for(var d=s.toString();d.length<o;)d="0"+d;return d},a=function(s,o){return o!==t?(s.year(o.year()||o.year),s.month(o.month()||o.month),s.day(o.day()||o.day),s.hours(o.hours()||o.hours),s.minutes(o.minutes()||o.minutes),s.seconds(o.seconds()||o.seconds),s.milliseconds(o.milliseconds()||o.milliseconds),s):t},l=function(s,o){var d,g="";return d=s.slice(o,o+1),d!==""&&!isNaN(Number(d))&&(g+="%H"),d=s.charAt(o+2),d!==""&&d===":"&&(g+=d),d=s.slice(o+3,o+4),d!==""&&!isNaN(Number(d))&&(g+="%M"),d=s.charAt(o+5),d!==""&&d===":"&&(g+=d),d=s.slice(o+6,o+7),d!==""&&!isNaN(Number(d))&&(g+="%S"),g},h=function(s,o){var d,g=[s.slice(o,o+1),s.charAt(o+2),s.slice(o+3,o+4),s.charAt(o+5),s.slice(o+6,o+9)],G;return!isNaN(Number(g[0]))&&!isNaN(Number(g[2]))&&!isNaN(Number(g[4]))?(g[1]==="."&&g[3]==="."?d="%d.%m.%Y":g[1]==="-"&&g[3]==="-"?d="%m-%d-%Y":g[1]==="/"&&g[3]==="/"&&(d="%m/%d/%Y"),d):(G=[s.slice(o,o+3),s.charAt(o+4),s.slice(o+5,o+6),s.charAt(o+7),s.slice(o+8,o+9)],!isNaN(Number(G[0]))&&!isNaN(Number(G[2]))&&!isNaN(Number(G[4]))?(G[1]==="-"&&G[3]==="-"&&(d="%Y-%m-%d"),d):"")},u=r.tempus,n,m,f=r.navigator||{},A="en",c={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"}},p=function(){return[c[A].JANUARY_LONG,c[A].FEBRUARY_LONG,c[A].MARCH_LONG,c[A].APRIL_LONG,c[A].MAY_LONG,c[A].JUNE_LONG,c[A].JULY_LONG,c[A].AUGUST_LONG,c[A].SEPTEMBER_LONG,c[A].OCTOBER_LONG,c[A].NOVEMBER_LONG,c[A].DECEMBER_LONG]},O=function(){return[c[A].JANUARY_SHORT,c[A].FEBRUARY_SHORT,c[A].MARCH_SHORT,c[A].APRIL_SHORT,c[A].MAY_SHORT,c[A].JUNE_SHORT,c[A].JULY_SHORT,c[A].AUGUST_SHORT,c[A].SEPTEMBER_SHORT,c[A].OCTOBER_SHORT,c[A].NOVEMBER_SHORT,c[A].DECEMBER_SHORT]},R=function(){return[c[A].SUNDAY_LONG,c[A].MONDAY_LONG,c[A].TUESDAY_LONG,c[A].WEDNESDAY_LONG,c[A].THURSDAY_LONG,c[A].FRIDAY_LONG,c[A].SATURDAY_LONG]},B=function(){return[c[A].SUNDAY_SHORT,c[A].MONDAY_SHORT,c[A].TUESDAY_SHORT,c[A].WEDNESDAY_SHORT,c[A].THURSDAY_SHORT,c[A].FRIDAY_SHORT,c[A].SATURDAY_SHORT]},T,L,x,N,I=function(s,o,d){var g;r.XMLHttpRequest?g=new XMLHttpRequest:g=new ActiveXObject("Microsoft.XMLHTTP"),g.onreadystatechange=function(){g.readyState===4&&(g.status===200?o&&(r.JSON===t?alert(`Please, include json2 into your project if you want use old browsers!
2
- https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(g.responseText))):d&&d(g))},g.open("GET",s,!1),g.send()},D={"%d":{format:function(s){return i(s.day()||n.MIN_DAY,2)},parse:function(s){var o=Number(s);return{day:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(s){return i(s.month()||n.MIN_MONTH,2)},parse:function(s){var o=Number(s);return{month:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(s){return i(s.year()||n.MIN_YEAR,4)},parse:function(s){var o=Number(s);return{year:isNaN(o)?t:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(s){return s.dayOfWeek()||n.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(s){var o=s.dayOfWeek();return N[o!==t?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(s){var o=s.dayOfWeek();return x[o!==t?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(s){var o=n.options("monthFromZero")?s.month():s.month()-1;return L[o!==t?o:n.MIN_MONTH]},parse:function(s){var o=n.monthNames().indexOf(s)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:t}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(s){var o=n.options("monthFromZero")?s.month():s.month()-1;return T[o!==t?o:n.MIN_MONTH]},parse:function(s){var o=n.monthNames(!0).indexOf(s)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:t}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(s){return i(s.hours()||n.MIN_HOURS,2)},parse:function(s){var o=Number(s);return{hours:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(s){return i(s.minutes()||n.MIN_MINUTES,2)},parse:function(s){var o=Number(s);return{minutes:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(s){return i(s.seconds()||n.MIN_SECONDS,2)},parse:function(s){var o=Number(s);return{seconds:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(s){return s.timestamp()},parse:function(s){return isNaN(Number(s))?{}:n(Number(s)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(s){return i(s.year()||n.MIN_YEAR,4)+"-"+i(s.month()||n.MIN_MONTH,2)+"-"+i(s.day()||n.MIN_DAY,2)},parse:function(s){var o=Number(s.slice(0,4)),d=Number(s.slice(5,7)),g=Number(s.slice(8,10));return{year:o,month:d,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(s){return i(s.month()||n.MIN_MONTH,2)+"/"+i(s.day()||n.MIN_DAY,2)+"/"+i(s.year()||n.MIN_YEAR,4)},parse:function(s){var o=Number(s.slice(0,2)),d=Number(s.slice(3,5)),g=Number(s.slice(6,10));return{year:g,month:o,day:d}},minLength:10,maxLength:10,type:"string"}},U={useMilliseconds:!1,monthFromZero:!1},S;S=function(s,o,d){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},s!==t&&this.set(s,o,d),this},S.fn=S.prototype,S.fn.dayCount=function(){var s=this.month(),o=n.MAX_DAY_IN_MONTHS[s-(n.options("monthFromZero")?0:1)];return this.leapYear()&&s===(n.options("monthFromZero")?1:2)&&(o+=1),o},S.fn.year=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_YEAR&&Number(s)<=n.MAX_YEAR?(this._d.setFullYear(Number(s)),this._i.year=!1):this._i.year=Number(s):(this._d.setFullYear(n.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},S.fn.month=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MONTH&&Number(s)<=n.MAX_MONTH?(this._d.setMonth(n.options("monthFromZero")?Number(s):Number(s)-1),this._i.month=!1):this._i.month=Number(s):(this._d.setMonth(n.options("monthFromZero")?n.MIN_MONTH:n.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?n.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},S.fn.day=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_DAY&&Number(s)<=this.dayCount()?(this._d.setDate(Number(s)),this._i.day=!1):this._i.day=Number(s):(this._d.setDate(n.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},S.fn.hours=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_HOURS&&Number(s)<=n.MAX_HOURS?(this._d.setHours(Number(s)),this._i.hours=!1):this._i.hours=Number(s):(this._d.setHours(n.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},S.fn.minutes=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MINUTES&&Number(s)<=n.MAX_MINUTES?(this._d.setMinutes(Number(s)),this._i.minutes=!1):this._i.minutes=Number(s):(this._d.setMinutes(n.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},S.fn.seconds=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_SECONDS&&Number(s)<=n.MAX_SECONDS?(this._d.setSeconds(Number(s)),this._i.seconds=!1):this._i.seconds=Number(s):(this._d.setSeconds(n.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},S.fn.milliseconds=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MILLISECONDS&&Number(s)<=n.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(s)),this._i.milliseconds=!1):this._i.milliseconds=Number(s):(this._d.setMilliseconds(n.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},S.fn.week=function(){var s=new Date(this.year(),0,1),o=n(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-s.getTime())/864e5+s.getDay()+1)/7)},S.fn.set=function(s,o,d){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},s===t)return this._d=new Date,this;if(s instanceof Date)return this._d=s,this;if(typeof s=="number")return this._d=new Date(s*(n.options("useMilliseconds")?1:1e3)),this;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"){var g,G=[],k,H,et=[],v=0,j=0,Y,K,W={},F;if(s===t)return k=a(this,d),k===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),k;for(o===t&&(o=n.detectFormat(s));v<o.length;){if(o.charAt(v)==="%"){if(H=o.charAt(v)+o.charAt(v+1),D[H]!==t){switch(Y=0,K="",D[H].type){case"number":for(;Y<D[H].maxLength&&j+Y<s.length&&!isNaN(Number(s.charAt(j+Y)));)K+=s.charAt(j+Y),Y+=1;break;case"word":for(;Y<D[H].maxLength&&j+Y<s.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(s.charAt(j+Y));)K+=s.charAt(j+Y),Y+=1;break;case"string":for(;Y<D[H].maxLength&&j+Y<s.length;)K+=s.charAt(j+Y),Y+=1;break}if(Y<D[H].minLength)return k=a(this,d),k===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),k;G.push(H),et.push(K),Y-=1,j+=Y,v+=1}}else if(s.charAt(j)!==o.charAt(v))return k=a(this,d),k===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),k;v+=1,j+=1}for(g in G)G.hasOwnProperty(g)&&D.hasOwnProperty(G[g])&&(F=D[G[g]].parse(et[g]),W={year:F.year!==t?F.year:W.year,month:F.month!==t?F.month:W.month,day:F.day!==t?F.day:W.day,hours:F.hours!==t?F.hours:W.hours,minutes:F.minutes!==t?F.minutes:W.minutes,seconds:F.seconds!==t?F.seconds:W.seconds});this.day(n.MIN_DAY),this.year(W.year),this.month(W.month),this.day(W.day),this.hours(W.hours),this.minutes(W.minutes),this.seconds(W.seconds),this.milliseconds(W.milliseconds)}return this},S.fn.leapYear=function(){var s=this.year();return s%4===0?s%100===0?s%400===0:!0:!1},S.fn.timestamp=function(s){return arguments.length!==0?(this._d=new Date(Number(s)*(n.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):n.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},S.fn.utc=function(s){return arguments.length!==0?(this._d=new Date(Number(s)*(n.options("useMilliseconds")?1:1e3)),this):n.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},S.fn.dayOfWeek=function(s){if(s==="long")return x[this._d.getDay()];if(s==="short")return N[this._d.getDay()];if(s===t)return this._d.getDay();if(s===0||s==="Sunday")return this.calc({day:-this.dayOfWeek()});if(s===1||s==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(s===2||s==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(s===3||s==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(s===4||s==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(s===5||s==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(s===6||s==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},S.fn.timezone=function(s){switch(s){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},S.fn.get=function(s){switch(s){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()}}},S.fn.format=function(s){for(var o=0,d="",g;o<s.length;)s.charAt(o)==="%"?(g=s.charAt(o)+s.charAt(o+1),D[g]!==t?(d+=D[g].format(this),o+=1):d+="%"):d+=s.charAt(o),o+=1;return d},S.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},S.fn.errors=function(){return this._i},S.fn.between=function(s,o){var d=this.timestamp(),g=s.timestamp();switch(o){case"year":return Math.floor((g-d)/31556952);case"month":return Math.floor((g-d)/2629746);case"day":return Math.floor((g-d)/86400);case"hours":return Math.floor((g-d)/3600);case"minutes":return Math.floor((g-d)/60);case"seconds":return g-d;default:return t}},S.fn.calc=function(s){return s.year!==t&&this._d.setFullYear(this._d.getFullYear()+s.year),s.month!==t&&this._d.setMonth(this._d.getMonth()+s.month),s.day!==t&&this._d.setDate(this._d.getDate()+s.day),s.hours!==t&&this._d.setHours(this._d.getHours()+s.hours),s.minutes!==t&&this._d.setMinutes(this._d.getMinutes()+s.minutes),s.seconds!==t&&this._d.setSeconds(this._d.getSeconds()+s.seconds),s.milliseconds!==t&&this._d.setMilliseconds(this._d.getMilliseconds()+s.milliseconds),this},n=function(s,o,d){return new S(s,o,d)},n.MIN_YEAR=1e3,n.MAX_YEAR=3e3,n.MIN_MONTH=1,n.MAX_MONTH=12,n.MIN_DAY=1,n.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],n.MIN_DAY_OF_WEEK=0,n.MAX_DAY_OF_WEEK=6,n.MIN_HOURS=0,n.MAX_HOURS=23,n.MIN_MINUTES=0,n.MAX_MINUTES=59,n.MIN_SECONDS=0,n.MAX_SECONDS=59,n.MIN_MILLISECONDS=0,n.MAX_MILLISECONDS=999,n.VERSION="0.2.18",n.options=function(s,o){if(s===t)return U;if(U.hasOwnProperty(s)){if(o===t)return U[s];U[s]=o,s==="monthFromZero"&&(n.MIN_MONTH=o?0:1,n.MAX_MONTH=o?11:12)}return t},n.noConflict=function(){return r.tempus=u,n},n.generate=function(s){var o,d,g,G,k,H,et,v;if(typeof s.dateFrom!="number"&&(s.dateFrom instanceof S?o=s.dateFrom.utc():o=n(s.dateFrom,s.formatFrom).utc()),typeof s.dateTo!="number"&&(s.dateTo instanceof S?d=s.dateTo.utc():d=n(s.dateTo,s.formatTo!==t?s.formatTo:s.formatFrom).utc()),typeof s.period=="number"?k={year:0,month:0,day:0,hours:0,minutes:0,seconds:s.period}:typeof s.period=="string"?k={year:s.period==="year"?1:0,month:s.period==="month"?1:0,day:s.period==="day"?1:0,hours:s.period==="hours"?1:0,minutes:s.period==="minutes"?1:0,seconds:s.period==="seconds"?1:0}:typeof s.period=="object"&&(k={year:s.period.year!==t?s.period.year:0,month:s.period.month!==t?s.period.month:0,day:s.period.day!==t?s.period.day:0,hours:s.period.hours!==t?s.period.hours:0,minutes:s.period.minutes!==t?s.period.minutes:0,seconds:s.period.seconds!==t?s.period.seconds:0}),s.groupBy===t?H=s.asObject===!0?{}:[]:(H=[],H.push([]),et=n(o).get()[s.groupBy]),v=function(K,W,F){return s.asObject===!0?s.format!==t?K[n(W).format(s.format)]={}:K[n(W).format("%F %H:%M:%S")]={}:s.format!==t?K.push(F?null:n(W).format(s.format)):K.push(F?null:n(W)),K},s.groupBy!==t&&s.fillNulls){var j={year:k.year?-k.year:t,month:k.month?-k.month:t,day:k.day?-k.day:t,hours:k.hours?-k.hours:t,minutes:k.minutes?-k.minutes:t,seconds:k.seconds?-k.seconds:t,milliseconds:k.milliseconds?-k.milliseconds:t};for(g=n(o).calc(j).utc();n(g).get()[s.groupBy]===et;)v(H[H.length-1],g,!0),g=n(g).calc(j).utc();if(s.groupBy==="week"){var Y=n(o).dayOfWeek();for(g=n(o).dayOfWeek(0).utc();H[0].length<Y&&g<o;)v(H[H.length-1],g,!0),g=n(g).calc(k).utc()}}for(;o<=d;)s.groupBy===t?v(H,o):n(o).get()[s.groupBy]===et?v(H[H.length-1],o):(H.push([]),v(H[H.length-1],o),et=n(o).get()[s.groupBy]),o=n(o).calc(k).utc();if(s.groupBy!==t&&s.fillNulls)for(G=n(d).calc(k).utc();n(G).get()[s.groupBy]===et;)v(H[H.length-1],G,!0),G=n(G).calc(k).utc();return H},n.monthNames=function(s){switch(s){case"long":return T;default:return L}},n.dayNames=function(s){switch(s){case"long":return x;default:return N}},n.lang=function(s){if(s!==t)A=s,c[A]===t&&(A="en"),T=p(),L=O(),x=R(),N=B();else return A;return t},n.availableLangs=function(){return Object.keys(c)},n.registerFormat=function(s,o,d,g,G,k){D[s]={format:o,parse:d,minLength:g,maxLength:G,type:k}},n.unregisterFormat=function(s){delete D[s]},n.detectFormat=function(s){var o,d,g;return o=h(s,0),o!==""&&(g=10),d=s.charAt(g),(d==="T"||d===" ")&&(o+=d,g+=1),o+=l(s,g),o},m={TempusDate:S},n.classes=function(s,o){if(o===t)return m[s];m[s]=o},n.loadTranslations=function(s){typeof s=="object"?c=s:typeof s=="string"&&I(s,function(o){c=o},function(o){})},A=(f.language||f.systemLanguage||f.userLanguage||"en").substr(0,2).toLowerCase(),c[A]===t&&(A="en"),T=p(),L=O(),x=R(),N=B(),_.exports&&(e=_.exports=n),e.tempus=n}).call(C)})(lt,lt.exports);var Ue=lt.exports;const gt=P(Ue),Q=class Q{constructor(e){E(this,Dt);E(this,ct);E(this,Ht);E(this,Ut);E(this,st);E(this,rt);E(this,yt);E(this,it);E(this,Pt);E(this,Gt);E(this,ht);E(this,pt);E(this,Nt);typeof e=="function"?(this.callBatch=e,this.callMethod=null):(this.callBatch=(e==null?void 0:e.callBatch)||null,this.callMethod=(e==null?void 0:e.callMethod)||null),this.result={},this.errors={},this.errorMessages={},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 e=this.totalBatchCommands||0;if(e>0&&Array.isArray(this.batchCommandKeyOrder)&&this.batchCommandKeyOrder.length&&y(this,Dt,Ne).call(this)){let u=0;for(const c of this.batchCommandKeyOrder){const p=this.progressData[c];if(!p)continue;const O=Number(p.total)||0,R=Number(p.count)||0;O===0&&R===0?u+=1:O>0&&(u+=Math.min(1,R/O))}const n=u/e*100;let m=Math.max(0,Math.min(100,Math.floor(n)));const f=e,A=Math.min(e,Math.floor(u));return{percent:m,allCount:A,allTotal:f}}let t=0,r=0;for(const u of Object.values(this.progressData)){const{total:n,count:m}=u;t+=n??0,r+=m??0}const i=Number(this.chunkRate)||0;let a=0;t?a=r/t*100*i+this.totalProgress:r===0&&t===0?a=i<1?this.totalProgress:100*i+this.totalProgress:a=100,a=Math.max(0,Math.min(a,100));let l=Math.floor(a);const h=Number(this.chunkRate)||0;return t>0&&r>=t&&h>=1&&(l=100),{percent:l,allCount:r,allTotal:t}}setProgressData({key:e,value:t,type:r}){var c,p;if(!this.progressCall)return;const i=this.getData(t.data()),a=Array.isArray(i)?i.length:0;let l=a;if(typeof t.total=="function"){const O=t.total();if(O!=null&&O!==""){const R=Number(O);Number.isFinite(R)&&(l=R)}}let h=1;r==="count"?(l||(l=a),h=l>0?l:a>0?a:1):i&&(h=a),this.progressData||(this.progressData={});const u=((c=this.progressData[e])==null?void 0:c.total)??0,n=((p=this.progressData[e])==null?void 0:p.count)??0,m=h+n,f=Math.max(u,l??0,m);if(this.progressData[e]={total:f,count:Math.min(m,f)},typeof document<"u"&&(document==null?void 0:document.hidden)===!0){y(this,ct,Zt).call(this);return}y(this,ct,Zt).call(this),this.progressTimer||(this.progressTimer=setInterval(()=>{if(!this.progressCall){this.clearProgressData();return}y(this,ct,Zt).call(this);const{percent:O}=this.progressPercent;O>=100&&(clearInterval(this.progressTimer),this.progressTimer="")},this.progressDelay))}getData(e){if(e==null)return e;let t=(e==null?void 0:e.items)??(e==null?void 0:e.tasks)??(e==null?void 0:e.types)??(e==null?void 0:e.type)??(e==null?void 0:e.fields)??(e==null?void 0:e.workgroups)??e;return t&&typeof t=="object"&&!Array.isArray(t)&&Array.isArray(t.result)&&(t=t.result),t}setTimeLimitState(e,t,r){this.timeLimit.limit=!!e,this.timeLimit.date=e?t:void 0,e&&typeof r=="number"&&r>0?this.timeLimit.pauseMs=r:this.timeLimit.pauseMs=void 0,y(this,Ut,_e).call(this)}subscribeTimeLimit(e){return typeof e!="function"?()=>{}:(this.timeLimitListeners.add(e),e({limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs}),()=>{this.timeLimitListeners.delete(e)})}splitLargeFilters(e,t){const{method:r,params:i}=t;if(!i)return[{key:e,request:t}];const a=i.filter||i.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:e,request:t}];for(const[l,h]of Object.entries(a))if(!String(l).trim().startsWith("!")&&Array.isArray(h)&&h.length>this.filterChunkSize){const u=[];for(let n=0;n<h.length;n+=this.filterChunkSize){const m=h.slice(n,n+this.filterChunkSize),f=n===0?e:`${e}__chunk_${Math.floor(n/this.filterChunkSize)}`,A={...i};i.filter?(A.filter={...a},A.filter[l]=m):i.FILTER&&(A.FILTER={...a},A.FILTER[l]=m),u.push({key:f,request:{method:r,params:A},originalKey:e,filterKey:l,chunkIndex:Math.floor(n/this.filterChunkSize)})}return u}return[{key:e,request:t}]}mergeSplitResults(e,t){const r=[],i=String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${i}(?:__chunk_\\d+)?$`),l=Object.keys(e).filter(h=>a.test(h)).sort((h,u)=>{const n=h.match(/__chunk_(\d+)$/),m=u.match(/__chunk_(\d+)$/);return n?m?parseInt(n[1])-parseInt(m[1]):1:-1});for(const h of l){const u=e[h];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(t=>setTimeout(t,500))}callBatchWithTimeout(e,t,r={}){const{onLateResponse:i}=r;return new Promise((a,l)=>{let h=!1,u=null;const n=async f=>{if(h)typeof i=="function"&&i(f);else{h=!0,u&&clearTimeout(u);try{await Promise.resolve(t(f)),a()}catch(A){console.error("Error in callBatch callback:",A),l(A)}}},m=async()=>{if(!h){h=!0,u&&clearTimeout(u),console.warn(`Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`);const f={};Object.keys(e).forEach(A=>{f[A]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 60 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(t(f)),a()}catch(A){console.error("Error in timeout callback:",A),a()}}};try{this.callBatch(e,async f=>{await n(f)})}catch(f){h||console.error("Error calling callBatch:",f)}u=setTimeout(async()=>{h||(console.warn(`Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`),await m())},this.requestTimeoutMs)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.lastProgressSnapshot=null}async batch(e,t,r={}){y(this,Nt,Ae).call(this,t);const i={},a={},l={};for(const[m,f]of Object.entries(e)){const A=this.arrayChunk(f);if(!A)continue;const c=this.splitLargeFilters(m,A);if(c.length===1)a[m]=A;else{l[m]=[];for(const p of c)a[p.key]=p.request,l[m].push(p.key)}}this.batchCommandKeyOrder=Object.keys(a),this.totalBatchCommands=this.batchCommandKeyOrder.length,this.batchCommandMethods=this.batchCommandKeyOrder.map(m=>{var f;return String(((f=a[m])==null?void 0:f.method)||"")}),this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let h={},u=0;const n=Object.keys(a).length;for(const[m,f]of Object.entries(a)){if(!this.canContinue)break;if(h[m]=f,Object.keys(h).length>=this.limit||u+1===n){const A=u+1===n;await this.batchChunk(h,void 0,!A,{disablePagination:!1,oneBatch:!!(r!=null&&r.oneBatch)}),Object.entries(this.result).forEach(([c,p])=>{i[c]=p}),this.totalProgress=Math.round(u/n*100),h={}}u++}for(const[m,f]of Object.entries(l))if(f&&f.length>0){const A=this.mergeSplitResults(i,m);for(const c of f)delete i[c];i[m]=A}return y(this,pt,oe).call(this,i),t&&t({percent:100}),Promise.resolve(i)}async batchTotalCount(e,t){y(this,Nt,Ae).call(this,t);const r={},i={},a={};for(const[u,n]of Object.entries(e)){const m=this.arrayChunk(n);if(!m)continue;const f=this.splitLargeFilters(u,m);if(f.length===1)i[u]=m;else{a[u]=[];for(const A of f)i[A.key]=A.request,a[u].push(A.key)}}const l=[],h=Object.entries(i);for(let u=0;u<h.length;u+=this.limit){const n=h.slice(u,u+this.limit),m={};for(const[f,A]of n){if(!this.canContinue)break;m[f]=A}Object.keys(m).length>0&&l.push(m)}this.chunkRate=(1/l.length).toFixed(5);for(const[u,n]of Object.entries(l)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(u)/l.length*100),this.progressData={},this.lastProgressSnapshot=null;const m=Number(u)===l.length-1;await y(this,it,St).call(this,n,async f=>{for(const[A,c]of Object.entries(f)){if(!this.canContinue)return;if(c.error()){y(this,ht,Vt).call(this,A,c),r[A]=0;continue}const p=this.getData(c.data()),O=Array.isArray(p)?p.length:0,B=typeof c.total=="function"&&c.total()!==void 0?c.total():O;r[A]=B,this.setProgressData({key:A,value:c,type:"count"})}await y(this,rt,Mt).call(this,f,!m)})}for(const[u,n]of Object.entries(a))if(n&&n.length>0){let m=0;for(const f of n)r[f]!==void 0&&(m+=r[f]||0),delete r[f];r[u]=m}return Object.entries(this.errors).length&&(y(this,pt,oe).call(this,r),this.errorLogger()),t&&t({percent:100}),Promise.resolve(r)}async call({method:e,params:t={}}){var i,a,l,h,u,n,m;const r=y(this,yt,ae).call(this,this.callLimitPauseMs);for(;;){let f=await y(this,Pt,Te).call(this,e,t,{onLateResponse:p=>r.notifyLateResponse(p)});if(!f)if(r.inRetryCycle=!0,await r.waitForLateOrLimit(),r.lateResult)f=r.lateResult,r.resetLateResult(),r.inRetryCycle=!1;else continue;const A={};if(f!=null&&f.answer)for(const[p,O]of Object.entries(f.answer))p!=="result"&&O&&(A[p]=O);if(f.error()){const p=((a=(i=f.error())==null?void 0:i.ex)==null?void 0:a.error)??"";if(["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT","TIMEOUT"].includes(p)){await y(this,st,bt).call(this,this.callLimitPauseMs);continue}const O=((l=f.error())==null?void 0:l.toString())||((u=(h=f.error())==null?void 0:h.ex)==null?void 0:u.error_description)||((m=(n=f.error())==null?void 0:n.ex)==null?void 0:m.error)||"Неизвестная ошибка";return{success:!1,data:!1,answer:A,error:O}}let c=f.data();return c!=null&&c.items&&(c=c.items),r.inRetryCycle=!1,{success:!0,data:c,answer:A,error:null}}}arrayChunk(e){let t="",r={};if(Array.isArray(e)?[t]=e:(t=e.method,r=e.params),(t.includes("list")||t==="user.get"||t==="entity.item.get")&&t!=="task.item.list"){if(!r)r=t==="entity.item.get"?{SORT:{ID:"ASC"}}:{order:{ID:"ASC",id:"ASC"}};else{t==="entity.item.get"?(r.SORT||(r.SORT={ID:"ASC"}),Array.isArray(r.select)?r.select.includes("ID")||r.select.push("ID"):r.select=["ID"]):t==="tasks.task.list"?(r.order||(r.order={}),r.order.ID="asc"):t==="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=t==="user.get"||t==="entity.item.get"?r.FILTER:r.filter;typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.entries(i).forEach(([a,l])=>{(r.start===void 0||r.start!==-1)&&["id","ID"].includes(a)&&(typeof l=="string"||Array.isArray(l)&&l.length<=50)&&(r.start=-1)})}t==="crm.type.list"&&r.order&&delete r.order.ID}if(t==="task.item.list")if(!r)r=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(r[0])&&(r[0]={});const[i,a,l,h]=r;i.ID="ASC",h[0]!==""&&h.includes("ID")||h.push("ID")}return{method:t,params:r}}async batchChunk(e,t,r=!0,i={}){return new Promise(a=>{const l=[];let h;const u=!!(i!=null&&i.disablePagination);(async()=>{await y(this,it,St).call(this,e,async m=>{for(const[A,c]of Object.entries(m)){if(!this.canContinue)return;c.error()&&(y(this,ht,Vt).call(this,A,c),h=!0);const p=this.getData(c.data()),O=Array.isArray(p)?p.length:0,R=typeof c.total=="function"&&c.total()!==void 0,B=R?c.total():O;t==="count"?this.result[A]?this.result[A]+=O:this.result[A]=B:this.result[A]=p,this.setProgressData({key:A,value:c,type:t});const T=e[A],L=Array.isArray(T)?T[0]:T==null?void 0:T.method,x=typeof L=="string"&&(L.includes(".list")||L==="user.get"||L==="entity.item.get"),N=t==="count"?!R&&O===this.limit:x?O===this.limit:B>this.limit&&B>O,I=t!=="count"&&L==="entity.item.get"&&O===this.limit&&!N,D=N||I;if(!u&&(!this.canContinue||D)){let U=e[A];if(Array.isArray(U)){const[S,s={}]=U;U=[S,s]}else{const{method:S,params:s={}}=U;U=[S,s]}l.push([A,U,B,{entityItemGetScan:I}])}}h>0&&this.errorLogger();const f=l.length>0||r;await y(this,rt,Mt).call(this,m,f),l.length?await this.batchPayload(l,t,i).then(()=>a(this.result)):a(this.result)})})()})}async batchPayload(e,t,r={}){const i=!!(r!=null&&r.oneBatch),a=(p,O,R,B)=>{let T="ID";this.result[p][this.result[p].length-1].ID||(T="id");let L=`${T}`;if(JSON.stringify(B[1]).toLocaleLowerCase().includes('"id":"desc"')?L="<"+L:L=">"+L,O===1||R.length===0)return{field:L,id:this.result[p][this.result[p].length-1][T]};let N="";const[I,D]=B;return(I==="tasks.task.list"||I==="task.item.list")&&(N="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(I)&&(N="[items]"),I==="crm.type.list"&&(N="[types]"),I==="socialnetwork.api.workgroup.list"&&(N="[workgroups]"),{field:L,id:`$result[${[p,O-1].join("__")}]${N}[49][${T}]`}},l=(p,O)=>{const[R,B]=p;let T=JSON.parse(JSON.stringify(B)),L;if(R==="task.item.list"){T=[...T];const[x,N,I,D]=T;return N[O.field]=O.id,[R,T]}return["user.get"].includes(R)||T.FILTER?(T.FILTER||(T.FILTER={}),L=T.FILTER):(T.filter||(T.filter={}),L=T.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(R)?L[">ID"]=O.id:L[O.field]=O.id,[R,{...T,start:-1}]},h=p=>{Object.entries(p).forEach(([O,R])=>{const[B]=O.split("__"),T=this.getData(R.data());Array.isArray(T)&&(t==="count"?this.result[B]+=T.length:this.result[B].push(...T)),R.error()&&y(this,ht,Vt).call(this,B,R),this.setProgressData({key:B,value:R,type:t})})},u=(p,O)=>{if(!Array.isArray(p)||p.length===0)return null;const R=p[p.length-1];let B="ID";R.ID||(B="id");let T=B;return JSON.stringify(O[1]).toLocaleLowerCase().includes('"id":"desc"')?T="<"+T:T=">"+T,{field:T,id:R[B]}},n=1e4,m=async(p,O)=>{var B,T;let R=this.limit;for(let L=1;this.canContinue&&R===this.limit&&L<=n;L++){const x=this.result[p],N=u(x,O);if(!N)break;const I=`${p}__eiscan_${L}`,D=l(O,N);let U=null;await y(this,it,St).call(this,{[I]:D},async d=>{U=d,h(d)});const S=L<n;await y(this,rt,Mt).call(this,U,S),await this.delay();const s=U==null?void 0:U[I];if((B=s==null?void 0:s.error)!=null&&B.call(s)){R=0;break}const o=this.getData((T=s==null?void 0:s.data)==null?void 0:T.call(s));R=Array.isArray(o)?o.length:0}};let f=[],A=0;const c=async(p=!0)=>f.length?(await y(this,it,St).call(this,Object.fromEntries(f),async O=>{h(O),await y(this,rt,Mt).call(this,O,p)}),A++,f=[],i&&A>=1?!0:(await this.delay(),!1)):!1;for await(const p of e){if(!this.canContinue)return;const[O,R,B,T={}]=p;if(T.entityItemGetScan){if(await c(!0))return;if(i)continue;await m(O,R);continue}let L=1;for(;B>L*this.limit;){const x=[O,L].join("__"),N=a(O,L,f,R);if(f.push([x,l(R,N)]),i&&f.length===49&&await c(!0)||f.length%50===0&&await c(!0))return;L++}}await c(!1)}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([e,t])=>{t&&console.log(`[${e}]`,t.toString())}),console.groupEnd()}};Dt=new WeakSet,Ne=function(){const e=this.totalBatchCommands||0,t=this.batchCommandMethods;if(e<b(Q,kt)||!Array.isArray(t)||t.length!==e)return!1;if(t.filter(a=>a==="crm.deal.list").length>=b(Q,Bt))return!0;const i=t.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=b(Q,wt)&&i/e>=b(Q,Ct)},kt=new WeakMap,Bt=new WeakMap,wt=new WeakMap,Ct=new WeakMap,ct=new WeakSet,Zt=function(){if(!this.progressCall||!this.progressData)return;const{percent:e,allCount:t,allTotal:r}=this.progressPercent,i={percent:e,allCount:t,allTotal:r};y(this,Ht,Oe).call(this,i)&&(this.progressCall({data:this.progressData,percent:e,allCount:t,allTotal:r}),this.lastProgressSnapshot=i)},Ht=new WeakSet,Oe=function(e){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==e.percent||this.lastProgressSnapshot.allCount!==e.allCount||this.lastProgressSnapshot.allTotal!==e.allTotal:!0},Ut=new WeakSet,_e=function(){const e={limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs};for(const t of this.timeLimitListeners)try{t(e)}catch(r){console.warn("Batch timeLimit listener error:",r)}},st=new WeakSet,bt=async function(e=this.defaultPauseMs){this.setTimeLimitState(!0,new Date().toISOString(),e),await new Promise(t=>setTimeout(t,e)),this.setTimeLimitState(!1,void 0)},rt=new WeakSet,Mt=async function(e,t=!0){if(!t)return 0;let r=0;if(!e||typeof e!="object")return 0;for(const i of Object.values(e))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 y(this,st,bt).call(this)},yt=new WeakSet,ae=function(e=this.defaultPauseMs){const t=this;return{inRetryCycle:!1,inTimeoutWait:!1,lateResult:null,lateWaiters:[],notifyLateResponse(i){if(!(!this.inRetryCycle&&!this.inTimeoutWait)){this.lateResult=i;for(const a of this.lateWaiters)a(i);this.lateWaiters=[]}},waitForLateOrLimit(){var a;this.inTimeoutWait=!0;const i=new Promise(l=>{if(this.lateResult){l(this.lateResult);return}this.lateWaiters.push(l)});return Promise.race([y(a=t,st,bt).call(a,e),i]).finally(()=>{this.inTimeoutWait=!1})},resetLateResult(){this.lateResult=null}}},it=new WeakSet,St=async function(e,t){let r=!1,i=e;const a=y(this,yt,ae).call(this);do r=!1,await this.callBatchWithTimeout(i,async l=>{var n,m;let h=!1;const u=new Set;for(const[f,A]of Object.entries(l||{})){if(!(A!=null&&A.error)||!A.error())continue;const c=((m=(n=A.error())==null?void 0:n.ex)==null?void 0:m.error)??"";if(c==="TIMEOUT"){h=!0;break}["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT"].includes(c)&&u.add(f)}if(h){if(a.inRetryCycle=!0,r=!0,await a.waitForLateOrLimit(),a.lateResult){r=!1,a.inRetryCycle=!1;const f=a.lateResult;a.resetLateResult(),await t(f)}return}if(u.size>0){const f={};for(const[c,p]of Object.entries(l||{}))u.has(c)||(f[c]=p);Object.keys(f).length&&await t(f);const A={};for(const c of u)i[c]&&(A[c]=i[c]);i=A,Object.keys(i).length&&(r=!0,await y(this,st,bt).call(this));return}a.inRetryCycle=!1,await t(l)},{onLateResponse:l=>a.notifyLateResponse(l)});while(r)},Pt=new WeakSet,Te=function(e,t,r={}){const{onLateResponse:i}=r;return new Promise(a=>{if(typeof this.callMethod!="function"){a(null);return}let l=!1;const h=setTimeout(()=>{l||(l=!0,a(null))},this.requestTimeoutMs);try{this.callMethod(e,t,u=>{l?typeof i=="function"&&i(u):(l=!0,clearTimeout(h),a(u))})}catch{l||(l=!0,clearTimeout(h),a(null))}})},Gt=new WeakSet,Ee=function(e){const t=typeof(e==null?void 0:e.error)=="function"?e.error():null,r=(t==null?void 0:t.ex)||{},i=String(r.error||"").trim(),a=String(r.error_description||"").trim(),l=typeof(t==null?void 0:t.toString)=="function"?String(t.toString()).trim():"";let h=a;return!h&&l&&l!==i&&(h=l),h||(h=i||"Неизвестная ошибка"),{code:i||h,message:h}},ht=new WeakSet,Vt=function(e,t){const{code:r,message:i}=y(this,Gt,Ee).call(this,t);this.errors[e]=r,this.errorMessages[e]=i},pt=new WeakSet,oe=function(e){Object.entries(this.errors).length&&(e.errorsList={...this.errors},Object.entries(this.errorMessages).length&&(e.errorsListMessages={...this.errorMessages}))},Nt=new WeakSet,Ae=function(e){this.clearProgressData(),this.progressCall=typeof e=="function"?e:"",this.canContinue=!0,this.result={},this.errors={},this.errorMessages={},this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.setTimeLimitState(!1,void 0)},E(Q,kt,5),E(Q,Bt,5),E(Q,wt,8),E(Q,Ct,.65);let q=Q;class te{constructor(){E(this,nt,{})}get hash(){return this.createHash(8)}createHash(e){let t="abcdefghijklmnopqrstuvwxyz0123456789",r="";e=e||6;for(let i=0;i<e;i++)r+=t.charAt(Math.floor(Math.random()*t.length));return r}actionFilter({keyTimer:e,duration:t=10,action:r}){b(this,nt)[e]&&(clearTimeout(b(this,nt)[e]),b(this,nt)[e]=null),r&&(b(this,nt)[e]=setTimeout(()=>{r()},t))}async noSleep(){let e=document.createElement("video");e.classList.add("no-sleep"),e.muted=!0,e.autoplay=!0,e.setAttribute("playsinline",""),e.addEventListener("loadeddata",()=>{e.style.position="fixed",e.style.left="-9999px",document.querySelector("body").append(e),e.play().catch(t=>{console.warn("noSleep: autoplay prevented",t)})}),e.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{e.play().catch(t=>{console.warn("noSleep: replay prevented",t)})}})}),e.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(e,t){let r=new Blob([JSON.stringify(e)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=i,a.download=`${t}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(i)},200)}}nt=new WeakMap;const ee=new te;class de{constructor(){E(this,Yt);E(this,_t);E(this,Wt);E(this,xt);E(this,Ft);E(this,Z,"logger");E(this,V,!1);E(this,at,new Map);E(this,ut,{});E(this,Ot,!1);E(this,$,null);E(this,J,null);E(this,ot,!1);E(this,ft,!1);w(this,"periodClear",3)}async init(){try{let e=new q(BX24.callBatch),{entityList:t}=await e.batch({entityList:{method:"entity.get"}});if(t&&Array.isArray(t))if(t.find(i=>i.ENTITY==b(this,Z)))X(this,V,!0);else{let{entityAdd:i}=await e.batch({entityAdd:{method:"entity.add",params:{ENTITY:b(this,Z),NAME:b(this,Z),ACCESS:{AU:"X"}}}});i&&X(this,V,!0)}return b(this,V)}catch(e){return console.error("Ошибка при инициализации логера:",e),!1}}enableBackworkerMode(){return X(this,V,!0),!0}start({type:e,data:t}){if(!b(this,V))return y(this,_t,le).call(this,"entity"),null;if(!e||!t)return console.error("Невалидные данные для логирования:",{type:e,data:t}),null;const r=ee.hash,i={type:e,data:t,userInfo:null,errorList:{},status:"",answer:null,date:new Date().getTime()};return b(this,at).set(r,i),X(this,ft,!0),r}async stop({key:e,errorList:t,status:r,answer:i}){var l;if(!b(this,ft))return;if(!b(this,V)){y(this,_t,le).call(this,"entity");return}let a=b(this,at).get(e);if(!a){console.error(`Не найдены данные логирования для ключа: ${e}`);return}t&&(a.errorList=t),r&&(a.status=r),i&&(a.answer=i),await y(this,Yt,Re).call(this),a.userInfo=b(this,ut),await y(this,Wt,Le).call(this),(l=a==null?void 0:a.data)!=null&&l.updateList&&X(this,ot,!0),X(this,ft,!1)}async getEntityList(e){var t;try{if((t=b(this,J))!=null&&t.length&&!b(this,ot))return b(this,J);let r=new q(BX24.callBatch),{entityList:i}=await r.batch({entityList:{method:"entity.item.get",params:{ENTITY:b(this,Z),SORT:{ID:"DESC"}}}},e);return!i||!Array.isArray(i)?(console.warn("Получен невалидный список записей"),[]):(i=i.map(a=>{try{const{ID:l,DATE_CREATE:h,DETAIL_TEXT:u}=a;return{...JSON.parse(u),id:l,dateCreate:h}}catch(l){return console.error(`Ошибка парсинга записи ${a.ID}:`,l),null}}).filter(a=>a!==null),X(this,ot,!1),X(this,J,i),i)}catch(r){return console.error("Ошибка при получении списка записей:",r),[]}}runStorageMaintenance(){return y(this,xt,be).call(this)}async downAllEntityJson(){try{if(b(this,J)||await this.getEntityList(),!b(this,J)||b(this,J).length===0)return console.warn("Нет данных для выгрузки"),!1;let e=gt().format("%Y-%m-%d");return ee.downloadFileJson(b(this,J),`sdklogger-entity-data__${e}`),!0}catch(e){return console.error("Ошибка при выгрузке данных в JSON:",e),!1}}}Z=new WeakMap,V=new WeakMap,at=new WeakMap,ut=new WeakMap,Ot=new WeakMap,$=new WeakMap,J=new WeakMap,ot=new WeakMap,ft=new WeakMap,Yt=new WeakSet,Re=async function(){if(!b(this,Ot))return b(this,$)?b(this,$):(X(this,$,(async()=>{try{const e=new q(BX24.callBatch),t=BX24.isAdmin(),{curUser:r}=await e.batch({curUser:{method:"user.current"}});X(this,ut,{isAdmin:t,curUser:r})}catch(e){console.error("Ошибка при получении информации о пользователе:",e),X(this,ut,{isAdmin:!1,curUser:null})}finally{X(this,Ot,!0),X(this,$,null)}})()),b(this,$))},_t=new WeakSet,le=function(e){e=="entity"&&ee.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},Wt=new WeakSet,Le=async function(){try{let e={},t=new q(BX24.callBatch);for(let[r,i]of b(this,at).entries())if(i.status){const a=JSON.stringify(i);e[r]={method:"entity.item.add",params:{ENTITY:b(this,Z),NAME:b(this,Z),DETAIL_TEXT:a}}}if(Object.keys(e).length){let r=await t.batch(e),{errors:i}=t;for(let[a,l]of Object.entries({...r,...i}))b(this,at).delete(a);return!0}return!1}catch(e){return console.error("Ошибка при добавлении записей в хранилище:",e),!1}},xt=new WeakSet,be=async function(){try{let e=new q(BX24.callBatch),{serverTime:t}=await e.batch({serverTime:{method:"server.time"}});if(!t){console.error("Не удалось получить время сервера");return}if(b(this,J)||await this.getEntityList(),!b(this,J)||b(this,J).length===0)return;let r=b(this,J).filter(i=>{try{let{dateCreate:a}=i;return a?gt(new Date(a)).between(gt(new Date(t)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});r.length>0&&(console.log(`Найдено ${r.length} записей для очистки (старше ${this.periodClear} месяцев)`),await y(this,Ft,Me).call(this,r))}catch(e){console.error("Ошибка при проверке периода очистки:",e)}},Ft=new WeakSet,Me=async function(e){try{if(!e||e.length===0)return!1;let t=new q(BX24.callBatch),r=e.filter(a=>a&&a.id).map(a=>{let{id:l}=a;return{method:"entity.item.delete",params:{ENTITY:b(this,Z),ID:l}}});if(r.length===0)return!1;const i=await t.batch(r);return console.log(`Успешно удалено ${r.length} записей`),X(this,ot,!0),i}catch(t){return console.error("Ошибка при очистке устаревших записей:",t),!1}};function se(_){if(!_||typeof _!="string")return"";try{const e=new URL(_);e.search="",e.hash="";let t=e.toString();return t.endsWith("/")&&e.pathname!=="/"&&(t=t.slice(0,-1)),t}catch{return _.split("?")[0].split("#")[0].replace(/\/$/,"")}}function me(_){return!_||typeof _!="string"?!1:_.toLowerCase().includes("/marketplace/app")}function Pe(){var e;if(typeof window>"u"||!((e=window.location)!=null&&e.href))return"";const _=se(window.location.href);return me(_)?"":_}function re(_){if(!(_!=null&&_.appConst)||typeof _.appConst!="object")return"";const e=Pe();return e?(_.appConst.pathApp=e,e):se(_.appConst.pathApp??"")}class Ge{constructor(e){E(this,dt);E(this,vt);E(this,Tt);E(this,Xt);E(this,Jt);E(this,jt);E(this,tt);E(this,Et);E(this,Kt);E(this,Rt);E(this,qt);w(this,"domain","");w(this,"isAdmin",!1);w(this,"appInfo",null);w(this,"appConst",null);w(this,"userInfo",null);w(this,"placeData",null);w(this,"placeInfo",null);w(this,"logger",!1);w(this,"timeLimit",{limit:!1,date:void 0,pauseMs:void 0});w(this,"batchClient",null);this.appConst=e}subscribeTimeLimit(e){return y(this,dt,$t).call(this).subscribeTimeLimit(e)}init(){return new Promise((e,t)=>{const i=setTimeout(()=>{clearInterval(a);const l=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(l),t(l)},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 l=y(this,Xt,Ie).call(this);if(console.info(l?"init BX24 (background worker)":"init BX24"),this.appInfo=await y(this,Jt,De).call(this),this.userInfo=await y(this,jt,ke).call(this),re(this),l)await y(this,Tt,ce).call(this,!1,{skipInit:!0});else{await y(this,Tt,ce).call(this,!0);const h=new te;try{h.noSleep()}catch(u){console.warn("Failed to initialize noSleep:",u)}}e({isBackworker:l})})},100)})}userOption(e,t){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return t!==void 0?BX24.userOption.set(e,t):BX24.userOption.get(e)}appOption(e,t){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return t!==void 0?BX24.appOption.set(e,t):BX24.appOption.get(e)}async call({method:e,params:t,updateList:r}){let i;if(r&&(i=this.logger.start({type:"call",data:{method:e,params:t,updateList:r}})),t||(t={}),typeof BX24>"u"||!BX24.callMethod){const h=new Error("BX24 is not initialized");throw console.error(h),h}const l=await y(this,dt,$t).call(this).call({method:e,params:t});return l.success?(await y(this,tt,mt).call(this,i,{answer:l.answer,status:"success"}),l.data):(console.error(l.error),await y(this,tt,mt).call(this,i,{answer:l.answer,status:"fail",errorList:{0:l.error||"Unknown call error"}}),!1)}async batch(e,t,{errorCall:r,updateList:i,batchOptions:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const l=new Error("BX24 is not initialized");return console.error(l),!1}return y(this,Et,he).call(this,{mode:"batch",commandList:e,progressCall:t,errorCall:r,updateList:i,batchOptions:a})}async batchTotalCount(e,t,{errorCall:r,updateList:i}={}){if(typeof BX24>"u"||!BX24.callBatch){const a=new Error("BX24 is not initialized");return console.error(a),!1}return y(this,Et,he).call(this,{mode:"batch-total-count",commandList:e,progressCall:t,errorCall:r,updateList:i})}async getPlacement(){const e=await this.call({method:"placement.get"});return this.placeData||(this.placeData=e),e}async placementBind(e){var A;if(!this.isAdmin||(this.placeData=await this.getPlacement(),!this.placeData))return;const{appName:t,pathApp:r}=this.appConst;let i=y(this,Rt,ue).call(this,e);i=i.filter(c=>c.placement!=="PAGE_BACKGROUND_WORKER"&&c.placement!=="PAGE_BACKGROUND_WORKER_ALL");const a=y(this,qt,we).call(this,r),l=new Set(i.map(c=>c.placement));for(const c of a)l.has(c.placement)||i.push({placement:c.placement});if(i.length===0)return;let h=t;this.domain==="szdl.bitrix24.ru"&&((A=this.appInfo)!=null&&A.ID)&&(h=`${t}: #${this.appInfo.ID}`);const u=h.replace(" CRM",""),n={},m=[],f=new Map;for(const c of this.placeData)f.has(c.placement)||f.set(c.placement,[]),f.get(c.placement).push(c);for(let c=0;c<i.length;c++){const{placement:p,options:O}=i[c],R=f.get(p)||[];if(R.some(L=>L.handler===r))continue;const T=R.filter(L=>L.handler!==r);for(const L of T)m.push({placement:p,handler:L.handler});n[`bind_${c}`]={method:"placement.bind",params:{PLACEMENT:p,HANDLER:r,LANG_ALL:{ru:{TITLE:p==="USER_PROFILE_TOOLBAR"?u:h}},OPTIONS:{errorHandlerUrl:r,...O&&typeof O=="object"?O:{}}}}}m.length>0&&await this.placementUnBind(m),Object.keys(n).length>0&&(await this.batch(n),this.placeData=await this.getPlacement(),Object.values(n).forEach(c=>{console.log("Приложение успешно встроено в",c.params.PLACEMENT)}))}async placementUnBind(e){let t=y(this,Rt,ue).call(this,e);if(t=t.filter(i=>i.placement!=="PAGE_BACKGROUND_WORKER"&&i.placement!=="PAGE_BACKGROUND_WORKER_ALL"),t.length===0)return;const r={};for(let i=0;i<t.length;i++){const a={PLACEMENT:t[i].placement};t[i].handler&&(a.HANDLER=t[i].handler),r[`unbind_${i}`]={method:"placement.unbind",params:a}}await this.batch(r),t.forEach(i=>{console.log("Встройка отвязана",i.placement)})}async getBotList(){const e=await this.call({method:"imbot.bot.list",params:{}}),t=Object.values(e);return console.log("chat-bot list:",t),t}async regBot({code:e,type:t,name:r}){const{appName:i,pathApp:a,chatBotLogo:l}=this.appConst,h=this.appInfo.ID,u=await this.call({method:"imbot.register",params:{CODE:e??this.appInfo.CODE,TYPE:t??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${r??i} - бот #${h}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:gt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:l??""}}});return console.log("Чат-бот добавлен",u),u}async unRegBot(e){const t=await this.call({method:"imbot.unregister",params:{BOT_ID:e}});return console.log("чат-бот удален",t),t}getLoggerList(e){return this.logger.getEntityList(e)}}dt=new WeakSet,$t=function(){return this.batchClient||(this.batchClient=new q({callBatch:BX24.callBatch,callMethod:BX24.callMethod}),this.timeLimit=this.batchClient.timeLimit),this.batchClient},vt=new WeakSet,Se=function(){return{start:()=>{},stop:()=>{},getEntityList:()=>{}}},Tt=new WeakSet,ce=async function(e,{skipInit:t=!1}={}){this.logger?(this.logger=new de,t?this.logger.enableBackworkerMode():await this.logger.init(),e&&typeof this.logger.runStorageMaintenance=="function"&&this.logger.runStorageMaintenance()):this.logger=y(this,vt,Se).call(this)},Xt=new WeakSet,Ie=function(){var r,i,a;const e=(r=this.placeInfo)==null?void 0:r.placement,t=(a=(i=this.placeInfo)==null?void 0:i.options)==null?void 0:a.ID;return e==="PAGE_BACKGROUND_WORKER"||t==="PAGE_BACKGROUND_WORKER"},Jt=new WeakSet,De=function(){return this.call({method:"app.info"})},jt=new WeakSet,ke=function(){return this.call({method:"user.current"})},tt=new WeakSet,mt=async function(e,t){if(e)try{await this.logger.stop({key:e,...t})}catch(r){console.error("Logger error:",r)}},Et=new WeakSet,he=async function({mode:e,commandList:t,progressCall:r,errorCall:i,updateList:a,batchOptions:l}){const h=y(this,dt,$t).call(this),u=a?this.logger.start({type:e,data:e==="batch"?{commandList:t,updateList:a}:{commandList:t}}):void 0;try{const n=e==="batch"?await h.batch(t,r,l):await h.batchTotalCount(t,r),m=y(this,Kt,Be).call(this,h,n,t,a);return Object.keys(m).length?(i&&i(m),await y(this,tt,mt).call(this,u,{status:"fail",errorList:m})):await y(this,tt,mt).call(this,u,{status:"success"}),n}catch(n){return await y(this,tt,mt).call(this,u,{status:"fail-runtime",errorList:{0:n==null?void 0:n.toString()}}),console.error(n),!1}},Kt=new WeakSet,Be=function(e,t,r,i){let a={...e.errors};if(Object.values(e.errors).some(h=>{if(typeof h!="string")return!1;const u=h.toUpperCase();return u==="TIMEOUT"||u==="OPERATION_TIME_LIMIT"||u.includes("TIMEOUT")||u.includes("OPERATION_TIME_LIMIT")})&&i){const h=t?Object.keys(t).filter(f=>f!=="errorsList"&&f!=="errorsListMessages"):[],u=new Set(Object.keys(e.errors||{})),n=new Set;if(t){for(const f of h)if(!u.has(f)){const A=t[f];A!=null&&n.add(f)}}const m=Object.values(e.errors).find(f=>{if(typeof f!="string")return!1;const A=f.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const f of Object.keys(r))!n.has(f)&&!e.errors[f]&&(a[f]=m||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a},Rt=new WeakSet,ue=function(e){if(!e)return[];let t=[];return Array.isArray(e)?t=e.map(r=>typeof r=="string"?{placement:r}:r):typeof e=="string"?t=[{placement:e}]:t=[e],t},qt=new WeakSet,we=function(e){return this.placeData?this.placeData.filter(t=>!(t.placement==="PAGE_BACKGROUND_WORKER"||!t.handler||t.handler.includes(e))):[]};const ge="szdl-utils-kit|";function Ye(){if(typeof sessionStorage>"u")return`ephemeral-${Date.now()}-${Math.random().toString(16).slice(2)}`;let _=sessionStorage.getItem("szdl-cross-tab-instance-id");return _||(_=`${Date.now()}-${Math.random().toString(16).slice(2)}`,sessionStorage.setItem("szdl-cross-tab-instance-id",_)),_}function We(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}const ie=new Map;function xe(_="default"){if(typeof BroadcastChannel>"u")return null;const e=`${ge}bc:${_}`;return ie.has(e)||ie.set(e,new BroadcastChannel(e)),ie.get(e)}function ye(_,e){const t=xe(_);if(t)try{const r=e&&typeof e=="object"&&!Array.isArray(e)?e:{data:e};t.postMessage({...r,tabId:Ye(),ts:Date.now()})}catch{}}async function Fe(_,e,t={}){const{ifAvailable:r=!1}=t,i=typeof _=="string"&&_.length>0?_:"default",a=`${ge}${i}`;return We()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!r},async l=>{if(r&&l==null)return{skipped:!0,coordination:"locks"};ye(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await e(),coordination:"locks"}}finally{ye(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await e(),coordination:"none"}}const z={startDelayMs:0,pollIntervalMs:60*1e3,pollIntervalJitterMs:30*1e3,leaderConfirmDelayMs:60*1e3,activeMaxPauseMs:3*60*1e3,quickCleanupThresholdMs:5*60*1e3,leaderHeartbeatMs:null};function ve(_){return _==null?"user":_==="user"||_==="portal"?_:(console.warn(`BackgroundWorker: coordinationScope должен быть 'user' или 'portal', получено ${JSON.stringify(_)} — используется 'user'`),"user")}function pe(_={}){const e={...z,..._};for(const t of Object.keys(z)){if(t==="leaderHeartbeatMs"){const i=_==null?void 0:_.leaderHeartbeatMs;if(i==null){e.leaderHeartbeatMs=null;continue}const a=Number(i);e.leaderHeartbeatMs=Number.isFinite(a)&&a>=0?a:null;continue}const r=Number(e[t]);e[t]=Number.isFinite(r)&&r>=0?r:z[t]}return e}class Xe{constructor(e){E(this,zt);E(this,Lt);E(this,At);E(this,Qt);w(this,"entityName","tabs");w(this,"maxTabs",20);w(this,"tabList",[]);w(this,"id",0);w(this,"hasStarted",!1);w(this,"heartbeat");w(this,"runHeartbeat");w(this,"startDelay",0);w(this,"activeMaxPause",z.activeMaxPauseMs);w(this,"quickCleanupThreshold",z.quickCleanupThresholdMs);w(this,"pollInterval",z.pollIntervalMs);w(this,"pollIntervalBase",z.pollIntervalMs);w(this,"pollIntervalJitter",z.pollIntervalJitterMs);w(this,"leaderConfirmDelay",z.leaderConfirmDelayMs);w(this,"leaderHeartbeatMs",null);w(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);w(this,"continueCondition");w(this,"defaultContinueBackground",()=>!0);w(this,"coordinationScope","user");w(this,"bindGeneralPlacement",!0);var n,m,f;if(!e){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:t,bx:r,users:i,continueBackground:a,timing:l,coordinationScope:h,bindGeneralPlacement:u}=e;this.bx=r,this.appInit=t,this.users=i,this.coordinationScope=ve(h),this.bindGeneralPlacement=u!==!1,y(this,zt,Ce).call(this,l),re(r),this.appPath=y(this,Lt,fe).call(this,((n=r==null?void 0:r.appConst)==null?void 0:n.pathApp)??""),this.appName=((m=r==null?void 0:r.appConst)==null?void 0:m.appName)??"",this.appCodeName=((f=r==null?void 0:r.appConst)==null?void 0:f.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.startDelay>0&&(console.log(`BackgroundWorker: старт отложен на ${this.startDelay} мс`),await this.pause(this.startDelay)),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(t=>{console.error("BackgroundWorker: backgroundTick failed",t)})},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 t=this.selectLeaderId(),r=t&&+this.id==+t;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 e;if(typeof BX24>"u"||!((e=BX24.placement)!=null&&e.info))return!1;try{const t=BX24.placement.info(),r=t==null?void 0:t.placement,i=(t==null?void 0:t.options)||{},a=(i==null?void 0:i.URI)||"",l=r==="PAGE_BACKGROUND_WORKER"||(i==null?void 0:i.ID)==="PAGE_BACKGROUND_WORKER",h=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!l||h}catch{return!1}}async checkEntity(){var r;const e=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((r=e==null?void 0:e.find)==null?void 0:r.call(e,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 e=y(this,At,It).call(this),t=await this.safeCall(()=>this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:e},SORT:{DATE_CREATE:"DESC"}}}));return!Array.isArray(t)||!t.length?[]:t.map(r=>{if(!r)return{id:void 0,data:void 0};try{const i=JSON.parse(r.DETAIL_TEXT);return{id:+r.ID||0,data:i}}catch(i){return console.log("BackgroundWorker: parse tab error",i),{id:+r.ID||0,data:void 0}}})}async ensureTabRegistered(){var r,i;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 e={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId,userId:(i=(r=this.bx)==null?void 0:r.userInfo)==null?void 0:i.ID},t=await this.safeCall(()=>this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:y(this,At,It).call(this),DETAIL_TEXT:JSON.stringify(e)}}))||0;return this.id=+t||0,this.id}async updateTabState(e){var r,i;if(!this.id)return;const t={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:e,sessionId:this.sessionId,userId:(i=(r=this.bx)==null?void 0:r.userInfo)==null?void 0:i.ID};await this.safeCall(()=>this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:y(this,At,It).call(this),DETAIL_TEXT:JSON.stringify(t)}}))}async deleteTabs(e=[]){if(!e.length)return;const t=e.map(r=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:r.id}}));await this.safeCall(()=>this.bx.batch(t))}async checkPlacementType(){var e,t;try{if(!((e=this.bx)!=null&&e.isAdmin))return!0;const r=await this.safeCall(()=>this.bx.getPlacement());if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((t=this.bx.userInfo)==null?void 0:t.ID)??0),a=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),l=!a;if(!i)return!0;let h=!1;for(const u of r){if(u.placement!=="PAGE_BACKGROUND_WORKER"||!(u.userId||u.handler&&u.handler.includes("USER_ID=")))continue;const m=u.userId||(u.handler?this.extractUserIdFromHandler(u.handler):null);if(m&&+m===i){h=!0;break}}return a?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):l&&h?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}isIndividualPlacement(e){return!e||typeof e!="string"?!1:e.includes("USER_ID=")}extractUserIdFromHandler(e){if(!e||typeof e!="string")return null;const t=e.match(/USER_ID=(\d+)/);return t?+t[1]:null}async continueBackground(){try{const t=!!await Promise.resolve(this.continueCondition(this));return console.log(t?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),t}catch(e){return console.error("BackgroundWorker: Ошибка в continueCondition",e),!1}}async refreshTabs(e=!1,t=this.activeMaxPause){const r=[],i=[],a=Date.now(),l=await this.getTabs();for(const h of l){if(!(h!=null&&h.data)){r.push(h);continue}if(a-new Date(h.data.lastActive||0).getTime()>t){r.push(h);continue}i.push(h)}return e&&r.length&&await this.deleteTabs(r),this.tabList=i,i}selectLeaderId(){var t;return this.tabList.length&&+((t=[...this.tabList].sort((r,i)=>{var h,u,n,m;const a=new Date(((h=r.data)==null?void 0:h.createdAt)||((u=r.data)==null?void 0:u.lastActive)||0).getTime(),l=new Date(((n=i.data)==null?void 0:n.createdAt)||((m=i.data)==null?void 0:m.lastActive)||0).getTime();return a===l?(+r.id||0)-(+i.id||0):a-l})[0])==null?void 0:t.id)||0}async confirmLeaderAfterLock(){await this.refreshTabs(!0);const e=this.selectLeaderId();return!!(e&&+this.id==+e)}async runAsLeader(){const e=y(this,Qt,He).call(this);(await Fe(e,async()=>{if(await this.updateTabState(!0),console.log(`BackgroundWorker: захват лидерства, пауза ${this.leaderConfirmDelay} мс перед запуском`),await this.pause(this.leaderConfirmDelay),!await this.confirmLeaderAfterLock()){console.log("BackgroundWorker: запуск отменён — после паузы лидером оказалась другая вкладка"),await this.updateTabState(!1);return}this.hasStarted=!0;const i=this.leaderHeartbeatMs??Math.min(this.activeMaxPause-1500,Math.max(2500,Math.floor(this.pollInterval/2)));this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(a=>console.error("BackgroundWorker: heartbeat update failed",a))},i);try{await this.appInit()}catch(a){console.error("BackgroundWorker: appInit failed",a)}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 B,T,L,x;if(!((B=this.bx)!=null&&B.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(T=this.users)!=null&&T.length||await this.getEntityData(),re(this.bx);const e=y(this,Lt,fe).call(this,((x=(L=this.bx)==null?void 0:L.appConst)==null?void 0:x.pathApp)??"");if(!e){console.error("BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена");return}const t=await this.safeCall(()=>this.bx.getPlacement()),r=new Map,i=new Map;let a=null;(t||[]).forEach(N=>{if(N.placement!=="PAGE_BACKGROUND_WORKER")return;if(N.userId||N.handler&&N.handler.includes("USER_ID=")){const D=N.userId||(N.handler?this.extractUserIdFromHandler(N.handler):null);if(D){const U=+D;r.set(U,N),i.has(U)||i.set(U,[]),i.get(U).push(N)}}else a=N});const l=await this.resolveAdmins(),h=await this.getEligibleUsersForBackgroundWorker(l);h.sort((N,I)=>{const D=N.LAST_LOGIN?new Date(N.LAST_LOGIN):new Date(0);return(I.LAST_LOGIN?new Date(I.LAST_LOGIN):new Date(0))-D});const u=10,n=h.slice(0,u),m=n.filter(N=>{const I=r.get(+N.ID);if(!I)return!0;const D=`${e}?USER_ID=${N.ID}/`;return I.handler!==D}),f=[];for(const[N]of r){const I=+N||0;h.find(U=>+U.ID===I)||f.push(I)}for(const N of n){const I=r.get(+N.ID);if(!I)continue;const D=`${e}?USER_ID=${N.ID}/`;I.handler!==D&&f.push(+N.ID)}const A=[],c=[...new Set(f)];for(const N of c){const I=i.get(+N)||[];for(const D of I)D!=null&&D.handler&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:D.handler}})}const p=a&&(!this.bindGeneralPlacement||m.length>0||a.handler!==`${e}`);p&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:a.handler||`${e}`}});for(const N of m)A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}?USER_ID=${N.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}?USER_ID=${N.ID}/`},USER_ID:N.ID}});this.bindGeneralPlacement&&(!a||p)&&A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}`}}});const O=A.filter(N=>N.method==="placement.unbind"),R=A.filter(N=>N.method==="placement.bind");O.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(O.map((N,I)=>[`unbind_${I}`,N])))),R.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(R.map((N,I)=>[`bind_${I}`,N])))),A.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var e,t;try{const r=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),i=!!((t=this.bx)!=null&&t.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 l=new Set([...a||[]]);r&&l.add(+r);const h=[...l].filter(Boolean);return await this.saveAdminsList(h),h}catch(r){return console.error("BackgroundWorker: resolveAdmins error",r),[]}}async getEligibleUsersForBackgroundWorker(e=[]){const t=(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0),r=e.map(i=>+i||0).filter(Boolean);return t.filter(i=>r.includes(+i.ID||0))}async saveAdminsList(e=[]){try{BX24.appOption.set("adminsList",JSON.stringify(e))}catch(t){console.error("BackgroundWorker: saveAdminsList error",t)}}async getAdminsList(){try{const e=BX24.appOption.get("adminsList"),t=e?JSON.parse(e):[];return Array.isArray(t)?t.map(r=>+r||0).filter(Boolean):[]}catch(e){return console.error("BackgroundWorker: getAdminsList error",e),[]}}async getEntityData(){const e={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:t}=await this.safeCall(()=>this.bx.batch(e).then(r=>r?(Array.isArray(r.users)||(r.users=[]),r):{users:[]}));this.users=t}async ensureAdminPlacements(){var e,t;(e=this.bx)!=null&&e.isAdmin&&((t=this.users)!=null&&t.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(e=500,t){return new Promise(r=>{setTimeout(()=>{t&&t(),r(!0)},e)})}async safeCall(e){try{return await e()}catch(t){console.error("BackgroundWorker: safeCall error",t);return}}}zt=new WeakSet,Ce=function(e){const t=pe(e);this.startDelay=t.startDelayMs,this.leaderConfirmDelay=t.leaderConfirmDelayMs,this.activeMaxPause=t.activeMaxPauseMs,this.quickCleanupThreshold=t.quickCleanupThresholdMs,this.pollIntervalBase=t.pollIntervalMs,this.pollIntervalJitter=t.pollIntervalJitterMs,this.pollInterval=t.pollIntervalMs+(t.pollIntervalJitterMs>0?Math.floor(Math.random()*t.pollIntervalJitterMs):0),this.leaderHeartbeatMs=t.leaderHeartbeatMs;const r=t.pollIntervalMs+t.pollIntervalJitterMs+t.leaderConfirmDelayMs;t.activeMaxPauseMs<r&&console.warn(`BackgroundWorker: activeMaxPauseMs (${t.activeMaxPauseMs}) меньше poll+jitter+leaderConfirm (${r}) — «живые» вкладки могут удаляться раньше следующего тика`)},Lt=new WeakSet,fe=function(e){if(!e||typeof e!="string")return"";const t=se(e).replace(/\/+$/,"");return t?me(t)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):t:""},At=new WeakSet,It=function(){var e,t;return this.coordinationScope==="portal"?`${this.appCodeName||"app"}:portal`:String(((t=(e=this.bx)==null?void 0:e.userInfo)==null?void 0:t.ID)??"")},Qt=new WeakSet,He=function(){return`background-worker:${this.entityName}:${y(this,At,It).call(this)}`},M.BackgroundWorker=Xe,M.Batch=q,M.BxBoot=Ge,M.BxHelper=te,M.BxLogger=de,M.DEFAULT_BACKGROUND_WORKER_TIMING=z,M.resolveBackgroundWorkerTiming=pe,M.tempus=gt,Object.defineProperty(M,Symbol.toStringTag,{value:"Module"})});
1
+ var Je=Object.defineProperty;var je=(M,w,P)=>w in M?Je(M,w,{enumerable:!0,configurable:!0,writable:!0,value:P}):M[w]=P;var C=(M,w,P)=>(je(M,typeof w!="symbol"?w+"":w,P),P),ne=(M,w,P)=>{if(!w.has(M))throw TypeError("Cannot "+P)};var b=(M,w,P)=>(ne(M,w,"read from private field"),P?P.call(M):w.get(M)),E=(M,w,P)=>{if(w.has(M))throw TypeError("Cannot add the same private member more than once");w instanceof WeakSet?w.add(M):w.set(M,P)},X=(M,w,P,lt)=>(ne(M,w,"write to private field"),lt?lt.call(M,P):w.set(M,P),P);var y=(M,w,P)=>(ne(M,w,"access private method"),P);(function(M,w){typeof exports=="object"&&typeof module<"u"?w(exports):typeof define=="function"&&define.amd?define(["exports"],w):(M=typeof globalThis<"u"?globalThis:M||self,w(M["szdl-utils-kit"]={}))})(this,function(M){var Dt,Ne,kt,Bt,Ct,wt,ct,Zt,Ht,Oe,Ut,_e,st,bt,rt,Mt,yt,ae,it,St,Pt,Te,Gt,Ee,ht,Vt,pt,oe,Nt,Ae,nt,Z,V,at,ut,Ot,$,J,ot,ft,Yt,Re,_t,le,Wt,Le,xt,be,Ft,Me,dt,$t,vt,Se,Tt,ce,Xt,Ie,Jt,De,jt,ke,tt,mt,Et,he,Kt,Be,Rt,ue,qt,Ce,zt,we,Lt,fe,At,It,Qt,He;"use strict";var w=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function P(_){return _&&_.__esModule&&Object.prototype.hasOwnProperty.call(_,"default")?_.default:_}var lt={exports:{}};(function(_,e){(function(t){Array.prototype.indexOf||(Array.prototype.indexOf=function(s,o){var d,g;for(d=o||0,g=this.length;d<g;d+=1)if(this[d]===s)return d;return-1});var r=this,i=function(s,o){for(var d=s.toString();d.length<o;)d="0"+d;return d},a=function(s,o){return o!==t?(s.year(o.year()||o.year),s.month(o.month()||o.month),s.day(o.day()||o.day),s.hours(o.hours()||o.hours),s.minutes(o.minutes()||o.minutes),s.seconds(o.seconds()||o.seconds),s.milliseconds(o.milliseconds()||o.milliseconds),s):t},l=function(s,o){var d,g="";return d=s.slice(o,o+1),d!==""&&!isNaN(Number(d))&&(g+="%H"),d=s.charAt(o+2),d!==""&&d===":"&&(g+=d),d=s.slice(o+3,o+4),d!==""&&!isNaN(Number(d))&&(g+="%M"),d=s.charAt(o+5),d!==""&&d===":"&&(g+=d),d=s.slice(o+6,o+7),d!==""&&!isNaN(Number(d))&&(g+="%S"),g},h=function(s,o){var d,g=[s.slice(o,o+1),s.charAt(o+2),s.slice(o+3,o+4),s.charAt(o+5),s.slice(o+6,o+9)],G;return!isNaN(Number(g[0]))&&!isNaN(Number(g[2]))&&!isNaN(Number(g[4]))?(g[1]==="."&&g[3]==="."?d="%d.%m.%Y":g[1]==="-"&&g[3]==="-"?d="%m-%d-%Y":g[1]==="/"&&g[3]==="/"&&(d="%m/%d/%Y"),d):(G=[s.slice(o,o+3),s.charAt(o+4),s.slice(o+5,o+6),s.charAt(o+7),s.slice(o+8,o+9)],!isNaN(Number(G[0]))&&!isNaN(Number(G[2]))&&!isNaN(Number(G[4]))?(G[1]==="-"&&G[3]==="-"&&(d="%Y-%m-%d"),d):"")},u=r.tempus,n,m,f=r.navigator||{},A="en",c={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"}},p=function(){return[c[A].JANUARY_LONG,c[A].FEBRUARY_LONG,c[A].MARCH_LONG,c[A].APRIL_LONG,c[A].MAY_LONG,c[A].JUNE_LONG,c[A].JULY_LONG,c[A].AUGUST_LONG,c[A].SEPTEMBER_LONG,c[A].OCTOBER_LONG,c[A].NOVEMBER_LONG,c[A].DECEMBER_LONG]},O=function(){return[c[A].JANUARY_SHORT,c[A].FEBRUARY_SHORT,c[A].MARCH_SHORT,c[A].APRIL_SHORT,c[A].MAY_SHORT,c[A].JUNE_SHORT,c[A].JULY_SHORT,c[A].AUGUST_SHORT,c[A].SEPTEMBER_SHORT,c[A].OCTOBER_SHORT,c[A].NOVEMBER_SHORT,c[A].DECEMBER_SHORT]},L=function(){return[c[A].SUNDAY_LONG,c[A].MONDAY_LONG,c[A].TUESDAY_LONG,c[A].WEDNESDAY_LONG,c[A].THURSDAY_LONG,c[A].FRIDAY_LONG,c[A].SATURDAY_LONG]},B=function(){return[c[A].SUNDAY_SHORT,c[A].MONDAY_SHORT,c[A].TUESDAY_SHORT,c[A].WEDNESDAY_SHORT,c[A].THURSDAY_SHORT,c[A].FRIDAY_SHORT,c[A].SATURDAY_SHORT]},T,R,x,N,I=function(s,o,d){var g;r.XMLHttpRequest?g=new XMLHttpRequest:g=new ActiveXObject("Microsoft.XMLHTTP"),g.onreadystatechange=function(){g.readyState===4&&(g.status===200?o&&(r.JSON===t?alert(`Please, include json2 into your project if you want use old browsers!
2
+ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(g.responseText))):d&&d(g))},g.open("GET",s,!1),g.send()},D={"%d":{format:function(s){return i(s.day()||n.MIN_DAY,2)},parse:function(s){var o=Number(s);return{day:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(s){return i(s.month()||n.MIN_MONTH,2)},parse:function(s){var o=Number(s);return{month:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(s){return i(s.year()||n.MIN_YEAR,4)},parse:function(s){var o=Number(s);return{year:isNaN(o)?t:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(s){return s.dayOfWeek()||n.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(s){var o=s.dayOfWeek();return N[o!==t?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(s){var o=s.dayOfWeek();return x[o!==t?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(s){var o=n.options("monthFromZero")?s.month():s.month()-1;return R[o!==t?o:n.MIN_MONTH]},parse:function(s){var o=n.monthNames().indexOf(s)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:t}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(s){var o=n.options("monthFromZero")?s.month():s.month()-1;return T[o!==t?o:n.MIN_MONTH]},parse:function(s){var o=n.monthNames(!0).indexOf(s)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:t}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(s){return i(s.hours()||n.MIN_HOURS,2)},parse:function(s){var o=Number(s);return{hours:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(s){return i(s.minutes()||n.MIN_MINUTES,2)},parse:function(s){var o=Number(s);return{minutes:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(s){return i(s.seconds()||n.MIN_SECONDS,2)},parse:function(s){var o=Number(s);return{seconds:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(s){return s.timestamp()},parse:function(s){return isNaN(Number(s))?{}:n(Number(s)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(s){return i(s.year()||n.MIN_YEAR,4)+"-"+i(s.month()||n.MIN_MONTH,2)+"-"+i(s.day()||n.MIN_DAY,2)},parse:function(s){var o=Number(s.slice(0,4)),d=Number(s.slice(5,7)),g=Number(s.slice(8,10));return{year:o,month:d,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(s){return i(s.month()||n.MIN_MONTH,2)+"/"+i(s.day()||n.MIN_DAY,2)+"/"+i(s.year()||n.MIN_YEAR,4)},parse:function(s){var o=Number(s.slice(0,2)),d=Number(s.slice(3,5)),g=Number(s.slice(6,10));return{year:g,month:o,day:d}},minLength:10,maxLength:10,type:"string"}},U={useMilliseconds:!1,monthFromZero:!1},S;S=function(s,o,d){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},s!==t&&this.set(s,o,d),this},S.fn=S.prototype,S.fn.dayCount=function(){var s=this.month(),o=n.MAX_DAY_IN_MONTHS[s-(n.options("monthFromZero")?0:1)];return this.leapYear()&&s===(n.options("monthFromZero")?1:2)&&(o+=1),o},S.fn.year=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_YEAR&&Number(s)<=n.MAX_YEAR?(this._d.setFullYear(Number(s)),this._i.year=!1):this._i.year=Number(s):(this._d.setFullYear(n.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},S.fn.month=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MONTH&&Number(s)<=n.MAX_MONTH?(this._d.setMonth(n.options("monthFromZero")?Number(s):Number(s)-1),this._i.month=!1):this._i.month=Number(s):(this._d.setMonth(n.options("monthFromZero")?n.MIN_MONTH:n.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?n.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},S.fn.day=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_DAY&&Number(s)<=this.dayCount()?(this._d.setDate(Number(s)),this._i.day=!1):this._i.day=Number(s):(this._d.setDate(n.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},S.fn.hours=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_HOURS&&Number(s)<=n.MAX_HOURS?(this._d.setHours(Number(s)),this._i.hours=!1):this._i.hours=Number(s):(this._d.setHours(n.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},S.fn.minutes=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MINUTES&&Number(s)<=n.MAX_MINUTES?(this._d.setMinutes(Number(s)),this._i.minutes=!1):this._i.minutes=Number(s):(this._d.setMinutes(n.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},S.fn.seconds=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_SECONDS&&Number(s)<=n.MAX_SECONDS?(this._d.setSeconds(Number(s)),this._i.seconds=!1):this._i.seconds=Number(s):(this._d.setSeconds(n.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},S.fn.milliseconds=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MILLISECONDS&&Number(s)<=n.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(s)),this._i.milliseconds=!1):this._i.milliseconds=Number(s):(this._d.setMilliseconds(n.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},S.fn.week=function(){var s=new Date(this.year(),0,1),o=n(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-s.getTime())/864e5+s.getDay()+1)/7)},S.fn.set=function(s,o,d){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},s===t)return this._d=new Date,this;if(s instanceof Date)return this._d=s,this;if(typeof s=="number")return this._d=new Date(s*(n.options("useMilliseconds")?1:1e3)),this;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"){var g,G=[],k,H,et=[],v=0,j=0,Y,K,W={},F;if(s===t)return k=a(this,d),k===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),k;for(o===t&&(o=n.detectFormat(s));v<o.length;){if(o.charAt(v)==="%"){if(H=o.charAt(v)+o.charAt(v+1),D[H]!==t){switch(Y=0,K="",D[H].type){case"number":for(;Y<D[H].maxLength&&j+Y<s.length&&!isNaN(Number(s.charAt(j+Y)));)K+=s.charAt(j+Y),Y+=1;break;case"word":for(;Y<D[H].maxLength&&j+Y<s.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(s.charAt(j+Y));)K+=s.charAt(j+Y),Y+=1;break;case"string":for(;Y<D[H].maxLength&&j+Y<s.length;)K+=s.charAt(j+Y),Y+=1;break}if(Y<D[H].minLength)return k=a(this,d),k===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),k;G.push(H),et.push(K),Y-=1,j+=Y,v+=1}}else if(s.charAt(j)!==o.charAt(v))return k=a(this,d),k===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),k;v+=1,j+=1}for(g in G)G.hasOwnProperty(g)&&D.hasOwnProperty(G[g])&&(F=D[G[g]].parse(et[g]),W={year:F.year!==t?F.year:W.year,month:F.month!==t?F.month:W.month,day:F.day!==t?F.day:W.day,hours:F.hours!==t?F.hours:W.hours,minutes:F.minutes!==t?F.minutes:W.minutes,seconds:F.seconds!==t?F.seconds:W.seconds});this.day(n.MIN_DAY),this.year(W.year),this.month(W.month),this.day(W.day),this.hours(W.hours),this.minutes(W.minutes),this.seconds(W.seconds),this.milliseconds(W.milliseconds)}return this},S.fn.leapYear=function(){var s=this.year();return s%4===0?s%100===0?s%400===0:!0:!1},S.fn.timestamp=function(s){return arguments.length!==0?(this._d=new Date(Number(s)*(n.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):n.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},S.fn.utc=function(s){return arguments.length!==0?(this._d=new Date(Number(s)*(n.options("useMilliseconds")?1:1e3)),this):n.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},S.fn.dayOfWeek=function(s){if(s==="long")return x[this._d.getDay()];if(s==="short")return N[this._d.getDay()];if(s===t)return this._d.getDay();if(s===0||s==="Sunday")return this.calc({day:-this.dayOfWeek()});if(s===1||s==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(s===2||s==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(s===3||s==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(s===4||s==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(s===5||s==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(s===6||s==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},S.fn.timezone=function(s){switch(s){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},S.fn.get=function(s){switch(s){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()}}},S.fn.format=function(s){for(var o=0,d="",g;o<s.length;)s.charAt(o)==="%"?(g=s.charAt(o)+s.charAt(o+1),D[g]!==t?(d+=D[g].format(this),o+=1):d+="%"):d+=s.charAt(o),o+=1;return d},S.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},S.fn.errors=function(){return this._i},S.fn.between=function(s,o){var d=this.timestamp(),g=s.timestamp();switch(o){case"year":return Math.floor((g-d)/31556952);case"month":return Math.floor((g-d)/2629746);case"day":return Math.floor((g-d)/86400);case"hours":return Math.floor((g-d)/3600);case"minutes":return Math.floor((g-d)/60);case"seconds":return g-d;default:return t}},S.fn.calc=function(s){return s.year!==t&&this._d.setFullYear(this._d.getFullYear()+s.year),s.month!==t&&this._d.setMonth(this._d.getMonth()+s.month),s.day!==t&&this._d.setDate(this._d.getDate()+s.day),s.hours!==t&&this._d.setHours(this._d.getHours()+s.hours),s.minutes!==t&&this._d.setMinutes(this._d.getMinutes()+s.minutes),s.seconds!==t&&this._d.setSeconds(this._d.getSeconds()+s.seconds),s.milliseconds!==t&&this._d.setMilliseconds(this._d.getMilliseconds()+s.milliseconds),this},n=function(s,o,d){return new S(s,o,d)},n.MIN_YEAR=1e3,n.MAX_YEAR=3e3,n.MIN_MONTH=1,n.MAX_MONTH=12,n.MIN_DAY=1,n.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],n.MIN_DAY_OF_WEEK=0,n.MAX_DAY_OF_WEEK=6,n.MIN_HOURS=0,n.MAX_HOURS=23,n.MIN_MINUTES=0,n.MAX_MINUTES=59,n.MIN_SECONDS=0,n.MAX_SECONDS=59,n.MIN_MILLISECONDS=0,n.MAX_MILLISECONDS=999,n.VERSION="0.2.18",n.options=function(s,o){if(s===t)return U;if(U.hasOwnProperty(s)){if(o===t)return U[s];U[s]=o,s==="monthFromZero"&&(n.MIN_MONTH=o?0:1,n.MAX_MONTH=o?11:12)}return t},n.noConflict=function(){return r.tempus=u,n},n.generate=function(s){var o,d,g,G,k,H,et,v;if(typeof s.dateFrom!="number"&&(s.dateFrom instanceof S?o=s.dateFrom.utc():o=n(s.dateFrom,s.formatFrom).utc()),typeof s.dateTo!="number"&&(s.dateTo instanceof S?d=s.dateTo.utc():d=n(s.dateTo,s.formatTo!==t?s.formatTo:s.formatFrom).utc()),typeof s.period=="number"?k={year:0,month:0,day:0,hours:0,minutes:0,seconds:s.period}:typeof s.period=="string"?k={year:s.period==="year"?1:0,month:s.period==="month"?1:0,day:s.period==="day"?1:0,hours:s.period==="hours"?1:0,minutes:s.period==="minutes"?1:0,seconds:s.period==="seconds"?1:0}:typeof s.period=="object"&&(k={year:s.period.year!==t?s.period.year:0,month:s.period.month!==t?s.period.month:0,day:s.period.day!==t?s.period.day:0,hours:s.period.hours!==t?s.period.hours:0,minutes:s.period.minutes!==t?s.period.minutes:0,seconds:s.period.seconds!==t?s.period.seconds:0}),s.groupBy===t?H=s.asObject===!0?{}:[]:(H=[],H.push([]),et=n(o).get()[s.groupBy]),v=function(K,W,F){return s.asObject===!0?s.format!==t?K[n(W).format(s.format)]={}:K[n(W).format("%F %H:%M:%S")]={}:s.format!==t?K.push(F?null:n(W).format(s.format)):K.push(F?null:n(W)),K},s.groupBy!==t&&s.fillNulls){var j={year:k.year?-k.year:t,month:k.month?-k.month:t,day:k.day?-k.day:t,hours:k.hours?-k.hours:t,minutes:k.minutes?-k.minutes:t,seconds:k.seconds?-k.seconds:t,milliseconds:k.milliseconds?-k.milliseconds:t};for(g=n(o).calc(j).utc();n(g).get()[s.groupBy]===et;)v(H[H.length-1],g,!0),g=n(g).calc(j).utc();if(s.groupBy==="week"){var Y=n(o).dayOfWeek();for(g=n(o).dayOfWeek(0).utc();H[0].length<Y&&g<o;)v(H[H.length-1],g,!0),g=n(g).calc(k).utc()}}for(;o<=d;)s.groupBy===t?v(H,o):n(o).get()[s.groupBy]===et?v(H[H.length-1],o):(H.push([]),v(H[H.length-1],o),et=n(o).get()[s.groupBy]),o=n(o).calc(k).utc();if(s.groupBy!==t&&s.fillNulls)for(G=n(d).calc(k).utc();n(G).get()[s.groupBy]===et;)v(H[H.length-1],G,!0),G=n(G).calc(k).utc();return H},n.monthNames=function(s){switch(s){case"long":return T;default:return R}},n.dayNames=function(s){switch(s){case"long":return x;default:return N}},n.lang=function(s){if(s!==t)A=s,c[A]===t&&(A="en"),T=p(),R=O(),x=L(),N=B();else return A;return t},n.availableLangs=function(){return Object.keys(c)},n.registerFormat=function(s,o,d,g,G,k){D[s]={format:o,parse:d,minLength:g,maxLength:G,type:k}},n.unregisterFormat=function(s){delete D[s]},n.detectFormat=function(s){var o,d,g;return o=h(s,0),o!==""&&(g=10),d=s.charAt(g),(d==="T"||d===" ")&&(o+=d,g+=1),o+=l(s,g),o},m={TempusDate:S},n.classes=function(s,o){if(o===t)return m[s];m[s]=o},n.loadTranslations=function(s){typeof s=="object"?c=s:typeof s=="string"&&I(s,function(o){c=o},function(o){})},A=(f.language||f.systemLanguage||f.userLanguage||"en").substr(0,2).toLowerCase(),c[A]===t&&(A="en"),T=p(),R=O(),x=L(),N=B(),_.exports&&(e=_.exports=n),e.tempus=n}).call(w)})(lt,lt.exports);var Ue=lt.exports;const gt=P(Ue),Q=class Q{constructor(e){E(this,Dt);E(this,ct);E(this,Ht);E(this,Ut);E(this,st);E(this,rt);E(this,yt);E(this,it);E(this,Pt);E(this,Gt);E(this,ht);E(this,pt);E(this,Nt);typeof e=="function"?(this.callBatch=e,this.callMethod=null):(this.callBatch=(e==null?void 0:e.callBatch)||null,this.callMethod=(e==null?void 0:e.callMethod)||null),this.result={},this.errors={},this.errorMessages={},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 e=this.totalBatchCommands||0;if(e>0&&Array.isArray(this.batchCommandKeyOrder)&&this.batchCommandKeyOrder.length&&y(this,Dt,Ne).call(this)){let u=0;for(const c of this.batchCommandKeyOrder){const p=this.progressData[c];if(!p)continue;const O=Number(p.total)||0,L=Number(p.count)||0;O===0&&L===0?u+=1:O>0&&(u+=Math.min(1,L/O))}const n=u/e*100;let m=Math.max(0,Math.min(100,Math.floor(n)));const f=e,A=Math.min(e,Math.floor(u));return{percent:m,allCount:A,allTotal:f}}let t=0,r=0;for(const u of Object.values(this.progressData)){const{total:n,count:m}=u;t+=n??0,r+=m??0}const i=Number(this.chunkRate)||0;let a=0;t?a=r/t*100*i+this.totalProgress:r===0&&t===0?a=i<1?this.totalProgress:100*i+this.totalProgress:a=100,a=Math.max(0,Math.min(a,100));let l=Math.floor(a);const h=Number(this.chunkRate)||0;return t>0&&r>=t&&h>=1&&(l=100),{percent:l,allCount:r,allTotal:t}}setProgressData({key:e,value:t,type:r}){var c,p;if(!this.progressCall)return;const i=this.getData(t.data()),a=Array.isArray(i)?i.length:0;let l=a;if(typeof t.total=="function"){const O=t.total();if(O!=null&&O!==""){const L=Number(O);Number.isFinite(L)&&(l=L)}}let h=1;r==="count"?(l||(l=a),h=l>0?l:a>0?a:1):i&&(h=a),this.progressData||(this.progressData={});const u=((c=this.progressData[e])==null?void 0:c.total)??0,n=((p=this.progressData[e])==null?void 0:p.count)??0,m=h+n,f=Math.max(u,l??0,m);if(this.progressData[e]={total:f,count:Math.min(m,f)},typeof document<"u"&&(document==null?void 0:document.hidden)===!0){y(this,ct,Zt).call(this);return}y(this,ct,Zt).call(this),this.progressTimer||(this.progressTimer=setInterval(()=>{if(!this.progressCall){this.clearProgressData();return}y(this,ct,Zt).call(this);const{percent:O}=this.progressPercent;O>=100&&(clearInterval(this.progressTimer),this.progressTimer="")},this.progressDelay))}getData(e){if(e==null)return e;let t=(e==null?void 0:e.items)??(e==null?void 0:e.tasks)??(e==null?void 0:e.types)??(e==null?void 0:e.type)??(e==null?void 0:e.fields)??(e==null?void 0:e.workgroups)??e;return t&&typeof t=="object"&&!Array.isArray(t)&&Array.isArray(t.result)&&(t=t.result),t}setTimeLimitState(e,t,r){this.timeLimit.limit=!!e,this.timeLimit.date=e?t:void 0,e&&typeof r=="number"&&r>0?this.timeLimit.pauseMs=r:this.timeLimit.pauseMs=void 0,y(this,Ut,_e).call(this)}subscribeTimeLimit(e){return typeof e!="function"?()=>{}:(this.timeLimitListeners.add(e),e({limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs}),()=>{this.timeLimitListeners.delete(e)})}splitLargeFilters(e,t){const{method:r,params:i}=t;if(!i)return[{key:e,request:t}];const a=i.filter||i.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:e,request:t}];for(const[l,h]of Object.entries(a))if(!String(l).trim().startsWith("!")&&Array.isArray(h)&&h.length>this.filterChunkSize){const u=[];for(let n=0;n<h.length;n+=this.filterChunkSize){const m=h.slice(n,n+this.filterChunkSize),f=n===0?e:`${e}__chunk_${Math.floor(n/this.filterChunkSize)}`,A={...i};i.filter?(A.filter={...a},A.filter[l]=m):i.FILTER&&(A.FILTER={...a},A.FILTER[l]=m),u.push({key:f,request:{method:r,params:A},originalKey:e,filterKey:l,chunkIndex:Math.floor(n/this.filterChunkSize)})}return u}return[{key:e,request:t}]}mergeSplitResults(e,t){const r=[],i=String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${i}(?:__chunk_\\d+)?$`),l=Object.keys(e).filter(h=>a.test(h)).sort((h,u)=>{const n=h.match(/__chunk_(\d+)$/),m=u.match(/__chunk_(\d+)$/);return n?m?parseInt(n[1])-parseInt(m[1]):1:-1});for(const h of l){const u=e[h];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(t=>setTimeout(t,500))}callBatchWithTimeout(e,t,r={}){const{onLateResponse:i}=r;return new Promise((a,l)=>{let h=!1,u=null;const n=async f=>{if(h)typeof i=="function"&&i(f);else{h=!0,u&&clearTimeout(u);try{await Promise.resolve(t(f)),a()}catch(A){console.error("Error in callBatch callback:",A),l(A)}}},m=async()=>{if(!h){h=!0,u&&clearTimeout(u),console.warn(`Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`);const f={};Object.keys(e).forEach(A=>{f[A]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 60 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(t(f)),a()}catch(A){console.error("Error in timeout callback:",A),a()}}};try{this.callBatch(e,async f=>{await n(f)})}catch(f){h||console.error("Error calling callBatch:",f)}u=setTimeout(async()=>{h||(console.warn(`Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`),await m())},this.requestTimeoutMs)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.lastProgressSnapshot=null}async batch(e,t,r={}){y(this,Nt,Ae).call(this,t);const i={},a={},l={};for(const[m,f]of Object.entries(e)){const A=this.arrayChunk(f);if(!A)continue;const c=this.splitLargeFilters(m,A);if(c.length===1)a[m]=A;else{l[m]=[];for(const p of c)a[p.key]=p.request,l[m].push(p.key)}}this.batchCommandKeyOrder=Object.keys(a),this.totalBatchCommands=this.batchCommandKeyOrder.length,this.batchCommandMethods=this.batchCommandKeyOrder.map(m=>{var f;return String(((f=a[m])==null?void 0:f.method)||"")}),this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let h={},u=0;const n=Object.keys(a).length;for(const[m,f]of Object.entries(a)){if(!this.canContinue)break;if(h[m]=f,Object.keys(h).length>=this.limit||u+1===n){const A=u+1===n;await this.batchChunk(h,void 0,!A,{disablePagination:!1,oneBatch:!!(r!=null&&r.oneBatch)}),Object.entries(this.result).forEach(([c,p])=>{i[c]=p}),this.totalProgress=Math.round(u/n*100),h={}}u++}for(const[m,f]of Object.entries(l))if(f&&f.length>0){const A=this.mergeSplitResults(i,m);for(const c of f)delete i[c];i[m]=A}return y(this,pt,oe).call(this,i),t&&t({percent:100}),Promise.resolve(i)}async batchTotalCount(e,t){y(this,Nt,Ae).call(this,t);const r={},i={},a={};for(const[u,n]of Object.entries(e)){const m=this.arrayChunk(n);if(!m)continue;const f=this.splitLargeFilters(u,m);if(f.length===1)i[u]=m;else{a[u]=[];for(const A of f)i[A.key]=A.request,a[u].push(A.key)}}const l=[],h=Object.entries(i);for(let u=0;u<h.length;u+=this.limit){const n=h.slice(u,u+this.limit),m={};for(const[f,A]of n){if(!this.canContinue)break;m[f]=A}Object.keys(m).length>0&&l.push(m)}this.chunkRate=(1/l.length).toFixed(5);for(const[u,n]of Object.entries(l)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(u)/l.length*100),this.progressData={},this.lastProgressSnapshot=null;const m=Number(u)===l.length-1;await y(this,it,St).call(this,n,async f=>{for(const[A,c]of Object.entries(f)){if(!this.canContinue)return;if(c.error()){y(this,ht,Vt).call(this,A,c),r[A]=0;continue}const p=this.getData(c.data()),O=Array.isArray(p)?p.length:0,B=typeof c.total=="function"&&c.total()!==void 0?c.total():O;r[A]=B,this.setProgressData({key:A,value:c,type:"count"})}await y(this,rt,Mt).call(this,f,!m)})}for(const[u,n]of Object.entries(a))if(n&&n.length>0){let m=0;for(const f of n)r[f]!==void 0&&(m+=r[f]||0),delete r[f];r[u]=m}return Object.entries(this.errors).length&&(y(this,pt,oe).call(this,r),this.errorLogger()),t&&t({percent:100}),Promise.resolve(r)}async call({method:e,params:t={}}){var i,a,l,h,u,n,m;const r=y(this,yt,ae).call(this,this.callLimitPauseMs);for(;;){let f=await y(this,Pt,Te).call(this,e,t,{onLateResponse:p=>r.notifyLateResponse(p)});if(!f)if(r.inRetryCycle=!0,await r.waitForLateOrLimit(),r.lateResult)f=r.lateResult,r.resetLateResult(),r.inRetryCycle=!1;else continue;const A={};if(f!=null&&f.answer)for(const[p,O]of Object.entries(f.answer))p!=="result"&&O&&(A[p]=O);if(f.error()){const p=((a=(i=f.error())==null?void 0:i.ex)==null?void 0:a.error)??"";if(["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT","TIMEOUT"].includes(p)){await y(this,st,bt).call(this,this.callLimitPauseMs);continue}const O=((l=f.error())==null?void 0:l.toString())||((u=(h=f.error())==null?void 0:h.ex)==null?void 0:u.error_description)||((m=(n=f.error())==null?void 0:n.ex)==null?void 0:m.error)||"Неизвестная ошибка";return{success:!1,data:!1,answer:A,error:O}}let c=f.data();return c!=null&&c.items&&(c=c.items),r.inRetryCycle=!1,{success:!0,data:c,answer:A,error:null}}}arrayChunk(e){let t="",r={};if(Array.isArray(e)?[t]=e:(t=e.method,r=e.params),(t.includes("list")||t==="user.get"||t==="entity.item.get"||t==="sonet_group.get")&&t!=="task.item.list"){if(!r)r=t==="entity.item.get"?{SORT:{ID:"ASC"}}:t==="sonet_group.get"?{ORDER:{ID:"ASC"}}:{order:{ID:"ASC",id:"ASC"}};else{t==="entity.item.get"?(r.SORT||(r.SORT={ID:"ASC"}),Array.isArray(r.select)?r.select.includes("ID")||r.select.push("ID"):r.select=["ID"]):t==="sonet_group.get"?r.ORDER?!r.ORDER.ID&&!r.ORDER.id&&(r.ORDER.ID="ASC"):r.ORDER={ID:"ASC"}:t==="tasks.task.list"?(r.order||(r.order={}),r.order.ID="asc"):t==="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=t==="user.get"||t==="entity.item.get"||t==="sonet_group.get"?r.FILTER:r.filter;typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.entries(i).forEach(([a,l])=>{(r.start===void 0||r.start!==-1)&&["id","ID"].includes(a)&&(typeof l=="string"||Array.isArray(l)&&l.length<=50)&&(r.start=-1)})}t==="crm.type.list"&&r.order&&delete r.order.ID}if(t==="task.item.list")if(!r)r=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(r[0])&&(r[0]={});const[i,a,l,h]=r;i.ID="ASC",h[0]!==""&&h.includes("ID")||h.push("ID")}return{method:t,params:r}}async batchChunk(e,t,r=!0,i={}){return new Promise(a=>{const l=[];let h;const u=!!(i!=null&&i.disablePagination);(async()=>{await y(this,it,St).call(this,e,async m=>{for(const[A,c]of Object.entries(m)){if(!this.canContinue)return;c.error()&&(y(this,ht,Vt).call(this,A,c),h=!0);const p=this.getData(c.data()),O=Array.isArray(p)?p.length:0,L=typeof c.total=="function"&&c.total()!==void 0,B=L?c.total():O;t==="count"?this.result[A]?this.result[A]+=O:this.result[A]=B:this.result[A]=p,this.setProgressData({key:A,value:c,type:t});const T=e[A],R=Array.isArray(T)?T[0]:T==null?void 0:T.method,x=typeof R=="string"&&(R.includes(".list")||R==="user.get"||R==="entity.item.get"||R==="sonet_group.get"),N=t==="count"?!L&&O===this.limit:x?O===this.limit:B>this.limit&&B>O,I=t!=="count"&&R==="entity.item.get"&&O===this.limit&&!N,D=N||I;if(!u&&(!this.canContinue||D)){let U=e[A];if(Array.isArray(U)){const[S,s={}]=U;U=[S,s]}else{const{method:S,params:s={}}=U;U=[S,s]}l.push([A,U,B,{entityItemGetScan:I}])}}h>0&&this.errorLogger();const f=l.length>0||r;await y(this,rt,Mt).call(this,m,f),l.length?await this.batchPayload(l,t,i).then(()=>a(this.result)):a(this.result)})})()})}async batchPayload(e,t,r={}){const i=!!(r!=null&&r.oneBatch),a=(p,O,L,B)=>{let T="ID";this.result[p][this.result[p].length-1].ID||(T="id");let R=`${T}`;if(JSON.stringify(B[1]).toLocaleLowerCase().includes('"id":"desc"')?R="<"+R:R=">"+R,O===1||L.length===0)return{field:R,id:this.result[p][this.result[p].length-1][T]};let N="";const[I,D]=B;return(I==="tasks.task.list"||I==="task.item.list")&&(N="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(I)&&(N="[items]"),I==="crm.type.list"&&(N="[types]"),I==="socialnetwork.api.workgroup.list"&&(N="[workgroups]"),{field:R,id:`$result[${[p,O-1].join("__")}]${N}[49][${T}]`}},l=(p,O)=>{const[L,B]=p;let T=JSON.parse(JSON.stringify(B)),R;if(L==="task.item.list"){T=[...T];const[x,N,I,D]=T;return N[O.field]=O.id,[L,T]}return["user.get","sonet_group.get"].includes(L)||T.FILTER?(T.FILTER||(T.FILTER={}),R=T.FILTER):(T.filter||(T.filter={}),R=T.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(L)?R[">ID"]=O.id:R[O.field]=O.id,[L,{...T,start:-1}]},h=p=>{Object.entries(p).forEach(([O,L])=>{const[B]=O.split("__"),T=this.getData(L.data());Array.isArray(T)&&(t==="count"?this.result[B]+=T.length:this.result[B].push(...T)),L.error()&&y(this,ht,Vt).call(this,B,L),this.setProgressData({key:B,value:L,type:t})})},u=(p,O)=>{if(!Array.isArray(p)||p.length===0)return null;const L=p[p.length-1];let B="ID";L.ID||(B="id");let T=B;return JSON.stringify(O[1]).toLocaleLowerCase().includes('"id":"desc"')?T="<"+T:T=">"+T,{field:T,id:L[B]}},n=1e4,m=async(p,O)=>{var B,T;let L=this.limit;for(let R=1;this.canContinue&&L===this.limit&&R<=n;R++){const x=this.result[p],N=u(x,O);if(!N)break;const I=`${p}__eiscan_${R}`,D=l(O,N);let U=null;await y(this,it,St).call(this,{[I]:D},async d=>{U=d,h(d)});const S=R<n;await y(this,rt,Mt).call(this,U,S),await this.delay();const s=U==null?void 0:U[I];if((B=s==null?void 0:s.error)!=null&&B.call(s)){L=0;break}const o=this.getData((T=s==null?void 0:s.data)==null?void 0:T.call(s));L=Array.isArray(o)?o.length:0}};let f=[],A=0;const c=async(p=!0)=>f.length?(await y(this,it,St).call(this,Object.fromEntries(f),async O=>{h(O),await y(this,rt,Mt).call(this,O,p)}),A++,f=[],i&&A>=1?!0:(await this.delay(),!1)):!1;for await(const p of e){if(!this.canContinue)return;const[O,L,B,T={}]=p;if(T.entityItemGetScan){if(await c(!0))return;if(i)continue;await m(O,L);continue}let R=1;for(;B>R*this.limit;){const x=[O,R].join("__"),N=a(O,R,f,L);if(f.push([x,l(L,N)]),i&&f.length===49&&await c(!0)||f.length%50===0&&await c(!0))return;R++}}await c(!1)}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([e,t])=>{t&&console.log(`[${e}]`,t.toString())}),console.groupEnd()}};Dt=new WeakSet,Ne=function(){const e=this.totalBatchCommands||0,t=this.batchCommandMethods;if(e<b(Q,kt)||!Array.isArray(t)||t.length!==e)return!1;if(t.filter(a=>a==="crm.deal.list").length>=b(Q,Bt))return!0;const i=t.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=b(Q,Ct)&&i/e>=b(Q,wt)},kt=new WeakMap,Bt=new WeakMap,Ct=new WeakMap,wt=new WeakMap,ct=new WeakSet,Zt=function(){if(!this.progressCall||!this.progressData)return;const{percent:e,allCount:t,allTotal:r}=this.progressPercent,i={percent:e,allCount:t,allTotal:r};y(this,Ht,Oe).call(this,i)&&(this.progressCall({data:this.progressData,percent:e,allCount:t,allTotal:r}),this.lastProgressSnapshot=i)},Ht=new WeakSet,Oe=function(e){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==e.percent||this.lastProgressSnapshot.allCount!==e.allCount||this.lastProgressSnapshot.allTotal!==e.allTotal:!0},Ut=new WeakSet,_e=function(){const e={limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs};for(const t of this.timeLimitListeners)try{t(e)}catch(r){console.warn("Batch timeLimit listener error:",r)}},st=new WeakSet,bt=async function(e=this.defaultPauseMs){this.setTimeLimitState(!0,new Date().toISOString(),e),await new Promise(t=>setTimeout(t,e)),this.setTimeLimitState(!1,void 0)},rt=new WeakSet,Mt=async function(e,t=!0){if(!t)return 0;let r=0;if(!e||typeof e!="object")return 0;for(const i of Object.values(e))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 y(this,st,bt).call(this)},yt=new WeakSet,ae=function(e=this.defaultPauseMs){const t=this;return{inRetryCycle:!1,inTimeoutWait:!1,lateResult:null,lateWaiters:[],notifyLateResponse(i){if(!(!this.inRetryCycle&&!this.inTimeoutWait)){this.lateResult=i;for(const a of this.lateWaiters)a(i);this.lateWaiters=[]}},waitForLateOrLimit(){var a;this.inTimeoutWait=!0;const i=new Promise(l=>{if(this.lateResult){l(this.lateResult);return}this.lateWaiters.push(l)});return Promise.race([y(a=t,st,bt).call(a,e),i]).finally(()=>{this.inTimeoutWait=!1})},resetLateResult(){this.lateResult=null}}},it=new WeakSet,St=async function(e,t){let r=!1,i=e;const a=y(this,yt,ae).call(this);do r=!1,await this.callBatchWithTimeout(i,async l=>{var n,m;let h=!1;const u=new Set;for(const[f,A]of Object.entries(l||{})){if(!(A!=null&&A.error)||!A.error())continue;const c=((m=(n=A.error())==null?void 0:n.ex)==null?void 0:m.error)??"";if(c==="TIMEOUT"){h=!0;break}["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT"].includes(c)&&u.add(f)}if(h){if(a.inRetryCycle=!0,r=!0,await a.waitForLateOrLimit(),a.lateResult){r=!1,a.inRetryCycle=!1;const f=a.lateResult;a.resetLateResult(),await t(f)}return}if(u.size>0){const f={};for(const[c,p]of Object.entries(l||{}))u.has(c)||(f[c]=p);Object.keys(f).length&&await t(f);const A={};for(const c of u)i[c]&&(A[c]=i[c]);i=A,Object.keys(i).length&&(r=!0,await y(this,st,bt).call(this));return}a.inRetryCycle=!1,await t(l)},{onLateResponse:l=>a.notifyLateResponse(l)});while(r)},Pt=new WeakSet,Te=function(e,t,r={}){const{onLateResponse:i}=r;return new Promise(a=>{if(typeof this.callMethod!="function"){a(null);return}let l=!1;const h=setTimeout(()=>{l||(l=!0,a(null))},this.requestTimeoutMs);try{this.callMethod(e,t,u=>{l?typeof i=="function"&&i(u):(l=!0,clearTimeout(h),a(u))})}catch{l||(l=!0,clearTimeout(h),a(null))}})},Gt=new WeakSet,Ee=function(e){const t=typeof(e==null?void 0:e.error)=="function"?e.error():null,r=(t==null?void 0:t.ex)||{},i=String(r.error||"").trim(),a=String(r.error_description||"").trim(),l=typeof(t==null?void 0:t.toString)=="function"?String(t.toString()).trim():"";let h=a;return!h&&l&&l!==i&&(h=l),h||(h=i||"Неизвестная ошибка"),{code:i||h,message:h}},ht=new WeakSet,Vt=function(e,t){const{code:r,message:i}=y(this,Gt,Ee).call(this,t);this.errors[e]=r,this.errorMessages[e]=i},pt=new WeakSet,oe=function(e){Object.entries(this.errors).length&&(e.errorsList={...this.errors},Object.entries(this.errorMessages).length&&(e.errorsListMessages={...this.errorMessages}))},Nt=new WeakSet,Ae=function(e){this.clearProgressData(),this.progressCall=typeof e=="function"?e:"",this.canContinue=!0,this.result={},this.errors={},this.errorMessages={},this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.setTimeLimitState(!1,void 0)},E(Q,kt,5),E(Q,Bt,5),E(Q,Ct,8),E(Q,wt,.65);let q=Q;class te{constructor(){E(this,nt,{})}get hash(){return this.createHash(8)}createHash(e){let t="abcdefghijklmnopqrstuvwxyz0123456789",r="";e=e||6;for(let i=0;i<e;i++)r+=t.charAt(Math.floor(Math.random()*t.length));return r}actionFilter({keyTimer:e,duration:t=10,action:r}){b(this,nt)[e]&&(clearTimeout(b(this,nt)[e]),b(this,nt)[e]=null),r&&(b(this,nt)[e]=setTimeout(()=>{r()},t))}async noSleep(){let e=document.createElement("video");e.classList.add("no-sleep"),e.muted=!0,e.autoplay=!0,e.setAttribute("playsinline",""),e.addEventListener("loadeddata",()=>{e.style.position="fixed",e.style.left="-9999px",document.querySelector("body").append(e),e.play().catch(t=>{console.warn("noSleep: autoplay prevented",t)})}),e.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{e.play().catch(t=>{console.warn("noSleep: replay prevented",t)})}})}),e.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(e,t){let r=new Blob([JSON.stringify(e)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=i,a.download=`${t}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(i)},200)}}nt=new WeakMap;const ee=new te;class de{constructor(){E(this,Yt);E(this,_t);E(this,Wt);E(this,xt);E(this,Ft);E(this,Z,"logger");E(this,V,!1);E(this,at,new Map);E(this,ut,{});E(this,Ot,!1);E(this,$,null);E(this,J,null);E(this,ot,!1);E(this,ft,!1);C(this,"periodClear",3)}async init(){try{let e=new q(BX24.callBatch),{entityList:t}=await e.batch({entityList:{method:"entity.get"}});if(t&&Array.isArray(t))if(t.find(i=>i.ENTITY==b(this,Z)))X(this,V,!0);else{let{entityAdd:i}=await e.batch({entityAdd:{method:"entity.add",params:{ENTITY:b(this,Z),NAME:b(this,Z),ACCESS:{AU:"X"}}}});i&&X(this,V,!0)}return b(this,V)}catch(e){return console.error("Ошибка при инициализации логера:",e),!1}}enableBackworkerMode(){return X(this,V,!0),!0}start({type:e,data:t}){if(!b(this,V))return y(this,_t,le).call(this,"entity"),null;if(!e||!t)return console.error("Невалидные данные для логирования:",{type:e,data:t}),null;const r=ee.hash,i={type:e,data:t,userInfo:null,errorList:{},status:"",answer:null,date:new Date().getTime()};return b(this,at).set(r,i),X(this,ft,!0),r}async stop({key:e,errorList:t,status:r,answer:i}){var l;if(!b(this,ft))return;if(!b(this,V)){y(this,_t,le).call(this,"entity");return}let a=b(this,at).get(e);if(!a){console.error(`Не найдены данные логирования для ключа: ${e}`);return}t&&(a.errorList=t),r&&(a.status=r),i&&(a.answer=i),await y(this,Yt,Re).call(this),a.userInfo=b(this,ut),await y(this,Wt,Le).call(this),(l=a==null?void 0:a.data)!=null&&l.updateList&&X(this,ot,!0),X(this,ft,!1)}async getEntityList(e){var t;try{if((t=b(this,J))!=null&&t.length&&!b(this,ot))return b(this,J);let r=new q(BX24.callBatch),{entityList:i}=await r.batch({entityList:{method:"entity.item.get",params:{ENTITY:b(this,Z),SORT:{ID:"DESC"}}}},e);return!i||!Array.isArray(i)?(console.warn("Получен невалидный список записей"),[]):(i=i.map(a=>{try{const{ID:l,DATE_CREATE:h,DETAIL_TEXT:u}=a;return{...JSON.parse(u),id:l,dateCreate:h}}catch(l){return console.error(`Ошибка парсинга записи ${a.ID}:`,l),null}}).filter(a=>a!==null),X(this,ot,!1),X(this,J,i),i)}catch(r){return console.error("Ошибка при получении списка записей:",r),[]}}runStorageMaintenance(){return y(this,xt,be).call(this)}async downAllEntityJson(){try{if(b(this,J)||await this.getEntityList(),!b(this,J)||b(this,J).length===0)return console.warn("Нет данных для выгрузки"),!1;let e=gt().format("%Y-%m-%d");return ee.downloadFileJson(b(this,J),`sdklogger-entity-data__${e}`),!0}catch(e){return console.error("Ошибка при выгрузке данных в JSON:",e),!1}}}Z=new WeakMap,V=new WeakMap,at=new WeakMap,ut=new WeakMap,Ot=new WeakMap,$=new WeakMap,J=new WeakMap,ot=new WeakMap,ft=new WeakMap,Yt=new WeakSet,Re=async function(){if(!b(this,Ot))return b(this,$)?b(this,$):(X(this,$,(async()=>{try{const e=new q(BX24.callBatch),t=BX24.isAdmin(),{curUser:r}=await e.batch({curUser:{method:"user.current"}});X(this,ut,{isAdmin:t,curUser:r})}catch(e){console.error("Ошибка при получении информации о пользователе:",e),X(this,ut,{isAdmin:!1,curUser:null})}finally{X(this,Ot,!0),X(this,$,null)}})()),b(this,$))},_t=new WeakSet,le=function(e){e=="entity"&&ee.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},Wt=new WeakSet,Le=async function(){try{let e={},t=new q(BX24.callBatch);for(let[r,i]of b(this,at).entries())if(i.status){const a=JSON.stringify(i);e[r]={method:"entity.item.add",params:{ENTITY:b(this,Z),NAME:b(this,Z),DETAIL_TEXT:a}}}if(Object.keys(e).length){let r=await t.batch(e),{errors:i}=t;for(let[a,l]of Object.entries({...r,...i}))b(this,at).delete(a);return!0}return!1}catch(e){return console.error("Ошибка при добавлении записей в хранилище:",e),!1}},xt=new WeakSet,be=async function(){try{let e=new q(BX24.callBatch),{serverTime:t}=await e.batch({serverTime:{method:"server.time"}});if(!t){console.error("Не удалось получить время сервера");return}if(b(this,J)||await this.getEntityList(),!b(this,J)||b(this,J).length===0)return;let r=b(this,J).filter(i=>{try{let{dateCreate:a}=i;return a?gt(new Date(a)).between(gt(new Date(t)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});r.length>0&&(console.log(`Найдено ${r.length} записей для очистки (старше ${this.periodClear} месяцев)`),await y(this,Ft,Me).call(this,r))}catch(e){console.error("Ошибка при проверке периода очистки:",e)}},Ft=new WeakSet,Me=async function(e){try{if(!e||e.length===0)return!1;let t=new q(BX24.callBatch),r=e.filter(a=>a&&a.id).map(a=>{let{id:l}=a;return{method:"entity.item.delete",params:{ENTITY:b(this,Z),ID:l}}});if(r.length===0)return!1;const i=await t.batch(r);return console.log(`Успешно удалено ${r.length} записей`),X(this,ot,!0),i}catch(t){return console.error("Ошибка при очистке устаревших записей:",t),!1}};function se(_){if(!_||typeof _!="string")return"";try{const e=new URL(_);e.search="",e.hash="";let t=e.toString();return t.endsWith("/")&&e.pathname!=="/"&&(t=t.slice(0,-1)),t}catch{return _.split("?")[0].split("#")[0].replace(/\/$/,"")}}function me(_){return!_||typeof _!="string"?!1:_.toLowerCase().includes("/marketplace/app")}function Pe(){var e;if(typeof window>"u"||!((e=window.location)!=null&&e.href))return"";const _=se(window.location.href);return me(_)?"":_}function re(_){if(!(_!=null&&_.appConst)||typeof _.appConst!="object")return"";const e=Pe();return e?(_.appConst.pathApp=e,e):se(_.appConst.pathApp??"")}class Ge{constructor(e){E(this,dt);E(this,vt);E(this,Tt);E(this,Xt);E(this,Jt);E(this,jt);E(this,tt);E(this,Et);E(this,Kt);E(this,Rt);E(this,qt);C(this,"domain","");C(this,"isAdmin",!1);C(this,"appInfo",null);C(this,"appConst",null);C(this,"userInfo",null);C(this,"placeData",null);C(this,"placeInfo",null);C(this,"logger",!1);C(this,"timeLimit",{limit:!1,date:void 0,pauseMs:void 0});C(this,"batchClient",null);this.appConst=e}subscribeTimeLimit(e){return y(this,dt,$t).call(this).subscribeTimeLimit(e)}init(){return new Promise((e,t)=>{const i=setTimeout(()=>{clearInterval(a);const l=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(l),t(l)},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 l=y(this,Xt,Ie).call(this);if(console.info(l?"init BX24 (background worker)":"init BX24"),this.appInfo=await y(this,Jt,De).call(this),this.userInfo=await y(this,jt,ke).call(this),re(this),l)await y(this,Tt,ce).call(this,!1,{skipInit:!0});else{await y(this,Tt,ce).call(this,!0);const h=new te;try{h.noSleep()}catch(u){console.warn("Failed to initialize noSleep:",u)}}e({isBackworker:l})})},100)})}userOption(e,t){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return t!==void 0?BX24.userOption.set(e,t):BX24.userOption.get(e)}appOption(e,t){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return t!==void 0?BX24.appOption.set(e,t):BX24.appOption.get(e)}async call({method:e,params:t,updateList:r}){let i;if(r&&(i=this.logger.start({type:"call",data:{method:e,params:t,updateList:r}})),t||(t={}),typeof BX24>"u"||!BX24.callMethod){const h=new Error("BX24 is not initialized");throw console.error(h),h}const l=await y(this,dt,$t).call(this).call({method:e,params:t});return l.success?(await y(this,tt,mt).call(this,i,{answer:l.answer,status:"success"}),l.data):(console.error(l.error),await y(this,tt,mt).call(this,i,{answer:l.answer,status:"fail",errorList:{0:l.error||"Unknown call error"}}),!1)}async batch(e,t,{errorCall:r,updateList:i,batchOptions:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const l=new Error("BX24 is not initialized");return console.error(l),!1}return y(this,Et,he).call(this,{mode:"batch",commandList:e,progressCall:t,errorCall:r,updateList:i,batchOptions:a})}async batchTotalCount(e,t,{errorCall:r,updateList:i}={}){if(typeof BX24>"u"||!BX24.callBatch){const a=new Error("BX24 is not initialized");return console.error(a),!1}return y(this,Et,he).call(this,{mode:"batch-total-count",commandList:e,progressCall:t,errorCall:r,updateList:i})}async getPlacement(){const e=await this.call({method:"placement.get"});return this.placeData||(this.placeData=e),e}async placementBind(e){var A;if(!this.isAdmin||(this.placeData=await this.getPlacement(),!this.placeData))return;const{appName:t,pathApp:r}=this.appConst;let i=y(this,Rt,ue).call(this,e);i=i.filter(c=>c.placement!=="PAGE_BACKGROUND_WORKER"&&c.placement!=="PAGE_BACKGROUND_WORKER_ALL");const a=y(this,qt,Ce).call(this,r),l=new Set(i.map(c=>c.placement));for(const c of a)l.has(c.placement)||i.push({placement:c.placement});if(i.length===0)return;let h=t;this.domain==="szdl.bitrix24.ru"&&((A=this.appInfo)!=null&&A.ID)&&(h=`${t}: #${this.appInfo.ID}`);const u=h.replace(" CRM",""),n={},m=[],f=new Map;for(const c of this.placeData)f.has(c.placement)||f.set(c.placement,[]),f.get(c.placement).push(c);for(let c=0;c<i.length;c++){const{placement:p,options:O}=i[c],L=f.get(p)||[];if(L.some(R=>R.handler===r))continue;const T=L.filter(R=>R.handler!==r);for(const R of T)m.push({placement:p,handler:R.handler});n[`bind_${c}`]={method:"placement.bind",params:{PLACEMENT:p,HANDLER:r,LANG_ALL:{ru:{TITLE:p==="USER_PROFILE_TOOLBAR"?u:h}},OPTIONS:{errorHandlerUrl:r,...O&&typeof O=="object"?O:{}}}}}m.length>0&&await this.placementUnBind(m),Object.keys(n).length>0&&(await this.batch(n),this.placeData=await this.getPlacement(),Object.values(n).forEach(c=>{console.log("Приложение успешно встроено в",c.params.PLACEMENT)}))}async placementUnBind(e){let t=y(this,Rt,ue).call(this,e);if(t=t.filter(i=>i.placement!=="PAGE_BACKGROUND_WORKER"&&i.placement!=="PAGE_BACKGROUND_WORKER_ALL"),t.length===0)return;const r={};for(let i=0;i<t.length;i++){const a={PLACEMENT:t[i].placement};t[i].handler&&(a.HANDLER=t[i].handler),r[`unbind_${i}`]={method:"placement.unbind",params:a}}await this.batch(r),t.forEach(i=>{console.log("Встройка отвязана",i.placement)})}async getBotList(){const e=await this.call({method:"imbot.bot.list",params:{}}),t=Object.values(e);return console.log("chat-bot list:",t),t}async regBot({code:e,type:t,name:r}){const{appName:i,pathApp:a,chatBotLogo:l}=this.appConst,h=this.appInfo.ID,u=await this.call({method:"imbot.register",params:{CODE:e??this.appInfo.CODE,TYPE:t??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${r??i} - бот #${h}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:gt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:l??""}}});return console.log("Чат-бот добавлен",u),u}async unRegBot(e){const t=await this.call({method:"imbot.unregister",params:{BOT_ID:e}});return console.log("чат-бот удален",t),t}getLoggerList(e){return this.logger.getEntityList(e)}}dt=new WeakSet,$t=function(){return this.batchClient||(this.batchClient=new q({callBatch:BX24.callBatch,callMethod:BX24.callMethod}),this.timeLimit=this.batchClient.timeLimit),this.batchClient},vt=new WeakSet,Se=function(){return{start:()=>{},stop:()=>{},getEntityList:()=>{}}},Tt=new WeakSet,ce=async function(e,{skipInit:t=!1}={}){this.logger?(this.logger=new de,t?this.logger.enableBackworkerMode():await this.logger.init(),e&&typeof this.logger.runStorageMaintenance=="function"&&this.logger.runStorageMaintenance()):this.logger=y(this,vt,Se).call(this)},Xt=new WeakSet,Ie=function(){var r,i,a;const e=(r=this.placeInfo)==null?void 0:r.placement,t=(a=(i=this.placeInfo)==null?void 0:i.options)==null?void 0:a.ID;return e==="PAGE_BACKGROUND_WORKER"||t==="PAGE_BACKGROUND_WORKER"},Jt=new WeakSet,De=function(){return this.call({method:"app.info"})},jt=new WeakSet,ke=function(){return this.call({method:"user.current"})},tt=new WeakSet,mt=async function(e,t){if(e)try{await this.logger.stop({key:e,...t})}catch(r){console.error("Logger error:",r)}},Et=new WeakSet,he=async function({mode:e,commandList:t,progressCall:r,errorCall:i,updateList:a,batchOptions:l}){const h=y(this,dt,$t).call(this),u=a?this.logger.start({type:e,data:e==="batch"?{commandList:t,updateList:a}:{commandList:t}}):void 0;try{const n=e==="batch"?await h.batch(t,r,l):await h.batchTotalCount(t,r),m=y(this,Kt,Be).call(this,h,n,t,a);return Object.keys(m).length?(i&&i(m),await y(this,tt,mt).call(this,u,{status:"fail",errorList:m})):await y(this,tt,mt).call(this,u,{status:"success"}),n}catch(n){return await y(this,tt,mt).call(this,u,{status:"fail-runtime",errorList:{0:n==null?void 0:n.toString()}}),console.error(n),!1}},Kt=new WeakSet,Be=function(e,t,r,i){let a={...e.errors};if(Object.values(e.errors).some(h=>{if(typeof h!="string")return!1;const u=h.toUpperCase();return u==="TIMEOUT"||u==="OPERATION_TIME_LIMIT"||u.includes("TIMEOUT")||u.includes("OPERATION_TIME_LIMIT")})&&i){const h=t?Object.keys(t).filter(f=>f!=="errorsList"&&f!=="errorsListMessages"):[],u=new Set(Object.keys(e.errors||{})),n=new Set;if(t){for(const f of h)if(!u.has(f)){const A=t[f];A!=null&&n.add(f)}}const m=Object.values(e.errors).find(f=>{if(typeof f!="string")return!1;const A=f.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const f of Object.keys(r))!n.has(f)&&!e.errors[f]&&(a[f]=m||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a},Rt=new WeakSet,ue=function(e){if(!e)return[];let t=[];return Array.isArray(e)?t=e.map(r=>typeof r=="string"?{placement:r}:r):typeof e=="string"?t=[{placement:e}]:t=[e],t},qt=new WeakSet,Ce=function(e){return this.placeData?this.placeData.filter(t=>!(t.placement==="PAGE_BACKGROUND_WORKER"||!t.handler||t.handler.includes(e))):[]};const ge="szdl-utils-kit|";function Ye(){if(typeof sessionStorage>"u")return`ephemeral-${Date.now()}-${Math.random().toString(16).slice(2)}`;let _=sessionStorage.getItem("szdl-cross-tab-instance-id");return _||(_=`${Date.now()}-${Math.random().toString(16).slice(2)}`,sessionStorage.setItem("szdl-cross-tab-instance-id",_)),_}function We(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}const ie=new Map;function xe(_="default"){if(typeof BroadcastChannel>"u")return null;const e=`${ge}bc:${_}`;return ie.has(e)||ie.set(e,new BroadcastChannel(e)),ie.get(e)}function ye(_,e){const t=xe(_);if(t)try{const r=e&&typeof e=="object"&&!Array.isArray(e)?e:{data:e};t.postMessage({...r,tabId:Ye(),ts:Date.now()})}catch{}}async function Fe(_,e,t={}){const{ifAvailable:r=!1}=t,i=typeof _=="string"&&_.length>0?_:"default",a=`${ge}${i}`;return We()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!r},async l=>{if(r&&l==null)return{skipped:!0,coordination:"locks"};ye(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await e(),coordination:"locks"}}finally{ye(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await e(),coordination:"none"}}const z={startDelayMs:0,pollIntervalMs:60*1e3,pollIntervalJitterMs:30*1e3,leaderConfirmDelayMs:60*1e3,activeMaxPauseMs:3*60*1e3,quickCleanupThresholdMs:5*60*1e3,leaderHeartbeatMs:null};function ve(_){return _==null?"user":_==="user"||_==="portal"?_:(console.warn(`BackgroundWorker: coordinationScope должен быть 'user' или 'portal', получено ${JSON.stringify(_)} — используется 'user'`),"user")}function pe(_={}){const e={...z,..._};for(const t of Object.keys(z)){if(t==="leaderHeartbeatMs"){const i=_==null?void 0:_.leaderHeartbeatMs;if(i==null){e.leaderHeartbeatMs=null;continue}const a=Number(i);e.leaderHeartbeatMs=Number.isFinite(a)&&a>=0?a:null;continue}const r=Number(e[t]);e[t]=Number.isFinite(r)&&r>=0?r:z[t]}return e}class Xe{constructor(e){E(this,zt);E(this,Lt);E(this,At);E(this,Qt);C(this,"entityName","tabs");C(this,"maxTabs",20);C(this,"tabList",[]);C(this,"id",0);C(this,"hasStarted",!1);C(this,"heartbeat");C(this,"runHeartbeat");C(this,"startDelay",0);C(this,"activeMaxPause",z.activeMaxPauseMs);C(this,"quickCleanupThreshold",z.quickCleanupThresholdMs);C(this,"pollInterval",z.pollIntervalMs);C(this,"pollIntervalBase",z.pollIntervalMs);C(this,"pollIntervalJitter",z.pollIntervalJitterMs);C(this,"leaderConfirmDelay",z.leaderConfirmDelayMs);C(this,"leaderHeartbeatMs",null);C(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);C(this,"continueCondition");C(this,"defaultContinueBackground",()=>!0);C(this,"coordinationScope","user");C(this,"bindGeneralPlacement",!0);var n,m,f;if(!e){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:t,bx:r,users:i,continueBackground:a,timing:l,coordinationScope:h,bindGeneralPlacement:u}=e;this.bx=r,this.appInit=t,this.users=i,this.coordinationScope=ve(h),this.bindGeneralPlacement=u!==!1,y(this,zt,we).call(this,l),re(r),this.appPath=y(this,Lt,fe).call(this,((n=r==null?void 0:r.appConst)==null?void 0:n.pathApp)??""),this.appName=((m=r==null?void 0:r.appConst)==null?void 0:m.appName)??"",this.appCodeName=((f=r==null?void 0:r.appConst)==null?void 0:f.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.startDelay>0&&(console.log(`BackgroundWorker: старт отложен на ${this.startDelay} мс`),await this.pause(this.startDelay)),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(t=>{console.error("BackgroundWorker: backgroundTick failed",t)})},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 t=this.selectLeaderId(),r=t&&+this.id==+t;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 e;if(typeof BX24>"u"||!((e=BX24.placement)!=null&&e.info))return!1;try{const t=BX24.placement.info(),r=t==null?void 0:t.placement,i=(t==null?void 0:t.options)||{},a=(i==null?void 0:i.URI)||"",l=r==="PAGE_BACKGROUND_WORKER"||(i==null?void 0:i.ID)==="PAGE_BACKGROUND_WORKER",h=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!l||h}catch{return!1}}async checkEntity(){var r;const e=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((r=e==null?void 0:e.find)==null?void 0:r.call(e,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 e=y(this,At,It).call(this),t=await this.safeCall(()=>this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:e},SORT:{DATE_CREATE:"DESC"}}}));return!Array.isArray(t)||!t.length?[]:t.map(r=>{if(!r)return{id:void 0,data:void 0};try{const i=JSON.parse(r.DETAIL_TEXT);return{id:+r.ID||0,data:i}}catch(i){return console.log("BackgroundWorker: parse tab error",i),{id:+r.ID||0,data:void 0}}})}async ensureTabRegistered(){var r,i;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 e={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId,userId:(i=(r=this.bx)==null?void 0:r.userInfo)==null?void 0:i.ID},t=await this.safeCall(()=>this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:y(this,At,It).call(this),DETAIL_TEXT:JSON.stringify(e)}}))||0;return this.id=+t||0,this.id}async updateTabState(e){var r,i;if(!this.id)return;const t={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:e,sessionId:this.sessionId,userId:(i=(r=this.bx)==null?void 0:r.userInfo)==null?void 0:i.ID};await this.safeCall(()=>this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:y(this,At,It).call(this),DETAIL_TEXT:JSON.stringify(t)}}))}async deleteTabs(e=[]){if(!e.length)return;const t=e.map(r=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:r.id}}));await this.safeCall(()=>this.bx.batch(t))}async checkPlacementType(){var e,t;try{if(!((e=this.bx)!=null&&e.isAdmin))return!0;const r=await this.safeCall(()=>this.bx.getPlacement());if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((t=this.bx.userInfo)==null?void 0:t.ID)??0),a=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),l=!a;if(!i)return!0;let h=!1;for(const u of r){if(u.placement!=="PAGE_BACKGROUND_WORKER"||!(u.userId||u.handler&&u.handler.includes("USER_ID=")))continue;const m=u.userId||(u.handler?this.extractUserIdFromHandler(u.handler):null);if(m&&+m===i){h=!0;break}}return a?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):l&&h?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}isIndividualPlacement(e){return!e||typeof e!="string"?!1:e.includes("USER_ID=")}extractUserIdFromHandler(e){if(!e||typeof e!="string")return null;const t=e.match(/USER_ID=(\d+)/);return t?+t[1]:null}async continueBackground(){try{const t=!!await Promise.resolve(this.continueCondition(this));return console.log(t?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),t}catch(e){return console.error("BackgroundWorker: Ошибка в continueCondition",e),!1}}async refreshTabs(e=!1,t=this.activeMaxPause){const r=[],i=[],a=Date.now(),l=await this.getTabs();for(const h of l){if(!(h!=null&&h.data)){r.push(h);continue}if(a-new Date(h.data.lastActive||0).getTime()>t){r.push(h);continue}i.push(h)}return e&&r.length&&await this.deleteTabs(r),this.tabList=i,i}selectLeaderId(){var t;return this.tabList.length&&+((t=[...this.tabList].sort((r,i)=>{var h,u,n,m;const a=new Date(((h=r.data)==null?void 0:h.createdAt)||((u=r.data)==null?void 0:u.lastActive)||0).getTime(),l=new Date(((n=i.data)==null?void 0:n.createdAt)||((m=i.data)==null?void 0:m.lastActive)||0).getTime();return a===l?(+r.id||0)-(+i.id||0):a-l})[0])==null?void 0:t.id)||0}async confirmLeaderAfterLock(){await this.refreshTabs(!0);const e=this.selectLeaderId();return!!(e&&+this.id==+e)}async runAsLeader(){const e=y(this,Qt,He).call(this);(await Fe(e,async()=>{if(await this.updateTabState(!0),console.log(`BackgroundWorker: захват лидерства, пауза ${this.leaderConfirmDelay} мс перед запуском`),await this.pause(this.leaderConfirmDelay),!await this.confirmLeaderAfterLock()){console.log("BackgroundWorker: запуск отменён — после паузы лидером оказалась другая вкладка"),await this.updateTabState(!1);return}this.hasStarted=!0;const i=this.leaderHeartbeatMs??Math.min(this.activeMaxPause-1500,Math.max(2500,Math.floor(this.pollInterval/2)));this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(a=>console.error("BackgroundWorker: heartbeat update failed",a))},i);try{await this.appInit()}catch(a){console.error("BackgroundWorker: appInit failed",a)}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 B,T,R,x;if(!((B=this.bx)!=null&&B.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(T=this.users)!=null&&T.length||await this.getEntityData(),re(this.bx);const e=y(this,Lt,fe).call(this,((x=(R=this.bx)==null?void 0:R.appConst)==null?void 0:x.pathApp)??"");if(!e){console.error("BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена");return}const t=await this.safeCall(()=>this.bx.getPlacement()),r=new Map,i=new Map;let a=null;(t||[]).forEach(N=>{if(N.placement!=="PAGE_BACKGROUND_WORKER")return;if(N.userId||N.handler&&N.handler.includes("USER_ID=")){const D=N.userId||(N.handler?this.extractUserIdFromHandler(N.handler):null);if(D){const U=+D;r.set(U,N),i.has(U)||i.set(U,[]),i.get(U).push(N)}}else a=N});const l=await this.resolveAdmins(),h=await this.getEligibleUsersForBackgroundWorker(l);h.sort((N,I)=>{const D=N.LAST_LOGIN?new Date(N.LAST_LOGIN):new Date(0);return(I.LAST_LOGIN?new Date(I.LAST_LOGIN):new Date(0))-D});const u=10,n=h.slice(0,u),m=n.filter(N=>{const I=r.get(+N.ID);if(!I)return!0;const D=`${e}?USER_ID=${N.ID}/`;return I.handler!==D}),f=[];for(const[N]of r){const I=+N||0;h.find(U=>+U.ID===I)||f.push(I)}for(const N of n){const I=r.get(+N.ID);if(!I)continue;const D=`${e}?USER_ID=${N.ID}/`;I.handler!==D&&f.push(+N.ID)}const A=[],c=[...new Set(f)];for(const N of c){const I=i.get(+N)||[];for(const D of I)D!=null&&D.handler&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:D.handler}})}const p=a&&(!this.bindGeneralPlacement||m.length>0||a.handler!==`${e}`);p&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:a.handler||`${e}`}});for(const N of m)A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}?USER_ID=${N.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}?USER_ID=${N.ID}/`},USER_ID:N.ID}});this.bindGeneralPlacement&&(!a||p)&&A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}`}}});const O=A.filter(N=>N.method==="placement.unbind"),L=A.filter(N=>N.method==="placement.bind");O.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(O.map((N,I)=>[`unbind_${I}`,N])))),L.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(L.map((N,I)=>[`bind_${I}`,N])))),A.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var e,t;try{const r=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),i=!!((t=this.bx)!=null&&t.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 l=new Set([...a||[]]);r&&l.add(+r);const h=[...l].filter(Boolean);return await this.saveAdminsList(h),h}catch(r){return console.error("BackgroundWorker: resolveAdmins error",r),[]}}async getEligibleUsersForBackgroundWorker(e=[]){const t=(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0),r=e.map(i=>+i||0).filter(Boolean);return t.filter(i=>r.includes(+i.ID||0))}async saveAdminsList(e=[]){try{BX24.appOption.set("adminsList",JSON.stringify(e))}catch(t){console.error("BackgroundWorker: saveAdminsList error",t)}}async getAdminsList(){try{const e=BX24.appOption.get("adminsList"),t=e?JSON.parse(e):[];return Array.isArray(t)?t.map(r=>+r||0).filter(Boolean):[]}catch(e){return console.error("BackgroundWorker: getAdminsList error",e),[]}}async getEntityData(){const e={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:t}=await this.safeCall(()=>this.bx.batch(e).then(r=>r?(Array.isArray(r.users)||(r.users=[]),r):{users:[]}));this.users=t}async ensureAdminPlacements(){var e,t;(e=this.bx)!=null&&e.isAdmin&&((t=this.users)!=null&&t.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(e=500,t){return new Promise(r=>{setTimeout(()=>{t&&t(),r(!0)},e)})}async safeCall(e){try{return await e()}catch(t){console.error("BackgroundWorker: safeCall error",t);return}}}zt=new WeakSet,we=function(e){const t=pe(e);this.startDelay=t.startDelayMs,this.leaderConfirmDelay=t.leaderConfirmDelayMs,this.activeMaxPause=t.activeMaxPauseMs,this.quickCleanupThreshold=t.quickCleanupThresholdMs,this.pollIntervalBase=t.pollIntervalMs,this.pollIntervalJitter=t.pollIntervalJitterMs,this.pollInterval=t.pollIntervalMs+(t.pollIntervalJitterMs>0?Math.floor(Math.random()*t.pollIntervalJitterMs):0),this.leaderHeartbeatMs=t.leaderHeartbeatMs;const r=t.pollIntervalMs+t.pollIntervalJitterMs+t.leaderConfirmDelayMs;t.activeMaxPauseMs<r&&console.warn(`BackgroundWorker: activeMaxPauseMs (${t.activeMaxPauseMs}) меньше poll+jitter+leaderConfirm (${r}) — «живые» вкладки могут удаляться раньше следующего тика`)},Lt=new WeakSet,fe=function(e){if(!e||typeof e!="string")return"";const t=se(e).replace(/\/+$/,"");return t?me(t)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):t:""},At=new WeakSet,It=function(){var e,t;return this.coordinationScope==="portal"?`${this.appCodeName||"app"}:portal`:String(((t=(e=this.bx)==null?void 0:e.userInfo)==null?void 0:t.ID)??"")},Qt=new WeakSet,He=function(){return`background-worker:${this.entityName}:${y(this,At,It).call(this)}`},M.BackgroundWorker=Xe,M.Batch=q,M.BxBoot=Ge,M.BxHelper=te,M.BxLogger=de,M.DEFAULT_BACKGROUND_WORKER_TIMING=z,M.resolveBackgroundWorkerTiming=pe,M.tempus=gt,Object.defineProperty(M,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.28",
5
+ "version": "0.3.29",
6
6
  "type": "module",
7
7
  "author": "Stanislav Ovv",
8
8
  "license": "BSD",