szdl-utils-kit 0.3.20 → 0.3.21

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
@@ -239,7 +239,7 @@ var Xt = { exports: {} };
239
239
  h[A].NOVEMBER_SHORT,
240
240
  h[A].DECEMBER_SHORT
241
241
  ];
242
- }, R = function() {
242
+ }, b = function() {
243
243
  return [
244
244
  h[A].SUNDAY_LONG,
245
245
  h[A].MONDAY_LONG,
@@ -249,7 +249,7 @@ var Xt = { exports: {} };
249
249
  h[A].FRIDAY_LONG,
250
250
  h[A].SATURDAY_LONG
251
251
  ];
252
- }, b = function() {
252
+ }, S = function() {
253
253
  return [
254
254
  h[A].SUNDAY_SHORT,
255
255
  h[A].MONDAY_SHORT,
@@ -259,13 +259,13 @@ var Xt = { exports: {} };
259
259
  h[A].FRIDAY_SHORT,
260
260
  h[A].SATURDAY_SHORT
261
261
  ];
262
- }, p, S, C, N, I = function(s, o, m) {
262
+ }, p, E, C, N, I = function(s, o, m) {
263
263
  var g;
264
264
  r.XMLHttpRequest ? g = new XMLHttpRequest() : g = new ActiveXObject("Microsoft.XMLHTTP"), g.onreadystatechange = function() {
265
265
  g.readyState === 4 && (g.status === 200 ? o && (r.JSON === e ? alert(`Please, include json2 into your project if you want use old browsers!
266
266
  https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.parse(g.responseText))) : m && m(g));
267
267
  }, g.open("GET", s, !1), g.send();
268
- }, E = {
268
+ }, R = {
269
269
  "%d": {
270
270
  format: function(s) {
271
271
  return i(s.day() || n.MIN_DAY, 2);
@@ -340,7 +340,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
340
340
  "%b": {
341
341
  format: function(s) {
342
342
  var o = n.options("monthFromZero") ? s.month() : s.month() - 1;
343
- return S[o !== e ? o : n.MIN_MONTH];
343
+ return E[o !== e ? o : n.MIN_MONTH];
344
344
  },
345
345
  parse: function(s) {
346
346
  var o = n.monthNames().indexOf(s) + (n.options("monthFromZero") ? 0 : 1);
@@ -533,22 +533,22 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
533
533
  }), D;
534
534
  for (o === e && (o = n.detectFormat(s)); W < o.length; ) {
535
535
  if (o.charAt(W) === "%") {
536
- if (U = o.charAt(W) + o.charAt(W + 1), E[U] !== e) {
537
- switch (G = 0, J = "", E[U].type) {
536
+ if (U = o.charAt(W) + o.charAt(W + 1), R[U] !== e) {
537
+ switch (G = 0, J = "", R[U].type) {
538
538
  case "number":
539
- for (; G < E[U].maxLength && F + G < s.length && !isNaN(Number(s.charAt(F + G))); )
539
+ for (; G < R[U].maxLength && F + G < s.length && !isNaN(Number(s.charAt(F + G))); )
540
540
  J += s.charAt(F + G), G += 1;
541
541
  break;
542
542
  case "word":
543
- for (; G < E[U].maxLength && F + G < s.length && /^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(s.charAt(F + G)); )
543
+ for (; G < R[U].maxLength && F + G < s.length && /^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(s.charAt(F + G)); )
544
544
  J += s.charAt(F + G), G += 1;
545
545
  break;
546
546
  case "string":
547
- for (; G < E[U].maxLength && F + G < s.length; )
547
+ for (; G < R[U].maxLength && F + G < s.length; )
548
548
  J += s.charAt(F + G), G += 1;
549
549
  break;
550
550
  }
551
- if (G < E[U].minLength)
551
+ if (G < R[U].minLength)
552
552
  return D = a(this, m), D === e && (this._i = {
553
553
  year: -1,
554
554
  month: -1,
@@ -573,7 +573,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
573
573
  W += 1, F += 1;
574
574
  }
575
575
  for (g in B)
576
- B.hasOwnProperty(g) && E.hasOwnProperty(B[g]) && (P = E[B[g]].parse(z[g]), Y = {
576
+ B.hasOwnProperty(g) && R.hasOwnProperty(B[g]) && (P = R[B[g]].parse(z[g]), Y = {
577
577
  year: P.year !== e ? P.year : Y.year,
578
578
  month: P.month !== e ? P.month : Y.month,
579
579
  day: P.day !== e ? P.day : Y.day,
@@ -672,7 +672,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
672
672
  }
673
673
  }, w.fn.format = function(s) {
674
674
  for (var o = 0, m = "", g; o < s.length; )
675
- s.charAt(o) === "%" ? (g = s.charAt(o) + s.charAt(o + 1), E[g] !== e ? (m += E[g].format(this), o += 1) : m += "%") : m += s.charAt(o), o += 1;
675
+ s.charAt(o) === "%" ? (g = s.charAt(o) + s.charAt(o + 1), R[g] !== e ? (m += R[g].format(this), o += 1) : m += "%") : m += s.charAt(o), o += 1;
676
676
  return m;
677
677
  }, w.fn.valid = function() {
678
678
  return this._i.year === !1 && this._i.month === !1 && this._i.day === !1 && this._i.hours === !1 && this._i.minutes === !1 && this._i.seconds === !1 && this._i.milliseconds === !1;
@@ -765,7 +765,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
765
765
  case "long":
766
766
  return p;
767
767
  default:
768
- return S;
768
+ return E;
769
769
  }
770
770
  }, n.dayNames = function(s) {
771
771
  switch (s) {
@@ -776,14 +776,14 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
776
776
  }
777
777
  }, n.lang = function(s) {
778
778
  if (s !== e)
779
- A = s, h[A] === e && (A = "en"), p = O(), S = T(), C = R(), N = b();
779
+ A = s, h[A] === e && (A = "en"), p = O(), E = T(), C = b(), N = S();
780
780
  else
781
781
  return A;
782
782
  return e;
783
783
  }, n.availableLangs = function() {
784
784
  return Object.keys(h);
785
785
  }, n.registerFormat = function(s, o, m, g, B, D) {
786
- E[s] = {
786
+ R[s] = {
787
787
  format: o,
788
788
  parse: m,
789
789
  minLength: g,
@@ -791,7 +791,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
791
791
  type: D
792
792
  };
793
793
  }, n.unregisterFormat = function(s) {
794
- delete E[s];
794
+ delete R[s];
795
795
  }, n.detectFormat = function(s) {
796
796
  var o, m, g;
797
797
  return o = l(s, 0), o !== "" && (g = 10), m = s.charAt(g), (m === "T" || m === " ") && (o += m, g += 1), o += c(s, g), o;
@@ -806,12 +806,12 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : o(JSON.pars
806
806
  h = o;
807
807
  }, function(o) {
808
808
  });
809
- }, A = (d.language || d.systemLanguage || d.userLanguage || "en").substr(0, 2).toLowerCase(), h[A] === e && (A = "en"), p = O(), S = T(), C = R(), N = b(), y.exports && (t = y.exports = n), t.tempus = n;
809
+ }, A = (d.language || d.systemLanguage || d.userLanguage || "en").substr(0, 2).toLowerCase(), h[A] === e && (A = "en"), p = O(), E = T(), C = b(), N = S(), y.exports && (t = y.exports = n), t.tempus = n;
810
810
  }).call(pe);
811
811
  })(Xt, Xt.exports);
812
812
  var Oe = Xt.exports;
813
813
  const Nt = /* @__PURE__ */ Ne(Oe);
814
- var Tt, $t, Et, Rt, bt, Lt, at, Ot, St, te, It, ee, Q, it, $, lt, tt, ht, Mt, se, ut, Jt;
814
+ var Tt, $t, Et, bt, Rt, Lt, at, Ot, St, te, It, ee, Q, it, $, lt, tt, ht, Mt, se, ut, Jt;
815
815
  const j = class j {
816
816
  constructor(t) {
817
817
  /**
@@ -933,8 +933,8 @@ const j = class j {
933
933
  if (typeof e.total == "function") {
934
934
  const T = e.total();
935
935
  if (T != null && T !== "") {
936
- const R = Number(T);
937
- Number.isFinite(R) && (c = R);
936
+ const b = Number(T);
937
+ Number.isFinite(b) && (c = b);
938
938
  }
939
939
  }
940
940
  r === "count" && (c = a);
@@ -1225,17 +1225,17 @@ const j = class j {
1225
1225
  this.totalProgress = Math.round(Number(u) / c.length * 100);
1226
1226
  const f = Number(u) === c.length - 1;
1227
1227
  await _(this, tt, ht).call(this, n, async (d) => {
1228
- var A, h, O, T, R;
1229
- for (const [b, p] of Object.entries(d)) {
1228
+ var A, h, O, T, b;
1229
+ for (const [S, p] of Object.entries(d)) {
1230
1230
  if (!this.canContinue)
1231
1231
  return;
1232
1232
  if (p.error()) {
1233
- const E = (h = (A = p.error()) == null ? void 0 : A.ex) == null ? void 0 : h.error, k = (T = (O = p.error()) == null ? void 0 : O.ex) == null ? void 0 : T.error_description;
1234
- this.errors[b] = E && E.trim() || k && k.trim() || ((R = p.error()) == null ? void 0 : R.toString()) || "Неизвестная ошибка", r[b] = 0;
1233
+ const R = (h = (A = p.error()) == null ? void 0 : A.ex) == null ? void 0 : h.error, k = (T = (O = p.error()) == null ? void 0 : O.ex) == null ? void 0 : T.error_description;
1234
+ this.errors[S] = R && R.trim() || k && k.trim() || ((b = p.error()) == null ? void 0 : b.toString()) || "Неизвестная ошибка", r[S] = 0;
1235
1235
  continue;
1236
1236
  }
1237
- const S = this.getData(p.data()), C = Array.isArray(S) ? S.length : 0, I = typeof p.total == "function" && p.total() !== void 0 ? p.total() : C;
1238
- r[b] = I, this.setProgressData({ key: b, value: p, type: "count" });
1237
+ const E = this.getData(p.data()), C = Array.isArray(E) ? E.length : 0, I = typeof p.total == "function" && p.total() !== void 0 ? p.total() : C;
1238
+ r[S] = I, this.setProgressData({ key: S, value: p, type: "count" });
1239
1239
  }
1240
1240
  await _(this, $, lt).call(this, d, !f);
1241
1241
  });
@@ -1335,19 +1335,19 @@ const j = class j {
1335
1335
  const u = !!(i != null && i.disablePagination);
1336
1336
  (async () => {
1337
1337
  await _(this, tt, ht).call(this, t, async (f) => {
1338
- var A, h, O, T, R;
1339
- for (const [b, p] of Object.entries(f)) {
1338
+ var A, h, O, T, b;
1339
+ for (const [S, p] of Object.entries(f)) {
1340
1340
  if (!this.canContinue)
1341
1341
  return;
1342
1342
  if (p.error()) {
1343
1343
  const g = (h = (A = p.error()) == null ? void 0 : A.ex) == null ? void 0 : h.error, B = (T = (O = p.error()) == null ? void 0 : O.ex) == null ? void 0 : T.error_description;
1344
- this.errors[b] = g && g.trim() || B && B.trim() || ((R = p.error()) == null ? void 0 : R.toString()) || "Неизвестная ошибка", l = !0;
1344
+ this.errors[S] = g && g.trim() || B && B.trim() || ((b = p.error()) == null ? void 0 : b.toString()) || "Неизвестная ошибка", l = !0;
1345
1345
  }
1346
- const S = this.getData(p.data()), C = Array.isArray(S) ? S.length : 0, N = typeof p.total == "function" && p.total() !== void 0, I = N ? p.total() : C;
1347
- e === "count" ? this.result[b] ? this.result[b] += C : this.result[b] = I : this.result[b] = S, this.setProgressData({ key: b, value: p, type: e });
1348
- const E = t[b], k = Array.isArray(E) ? E[0] : E == null ? void 0 : E.method, w = typeof k == "string" && (k.includes(".list") || k === "user.get" || k === "entity.item.get"), s = e === "count" ? !N && C === this.limit : w ? C === this.limit : I > this.limit && I > C, o = e !== "count" && k === "entity.item.get" && C === this.limit && !s, m = s || o;
1346
+ const E = this.getData(p.data()), C = Array.isArray(E) ? E.length : 0, N = typeof p.total == "function" && p.total() !== void 0, I = N ? p.total() : C;
1347
+ e === "count" ? this.result[S] ? this.result[S] += C : this.result[S] = I : this.result[S] = E, this.setProgressData({ key: S, value: p, type: e });
1348
+ const R = t[S], k = Array.isArray(R) ? R[0] : R == null ? void 0 : R.method, w = typeof k == "string" && (k.includes(".list") || k === "user.get" || k === "entity.item.get"), s = e === "count" ? !N && C === this.limit : w ? C === this.limit : I > this.limit && I > C, o = e !== "count" && k === "entity.item.get" && C === this.limit && !s, m = s || o;
1349
1349
  if (!u && (!this.canContinue || m)) {
1350
- let g = t[b];
1350
+ let g = t[S];
1351
1351
  if (Array.isArray(g)) {
1352
1352
  const [B, D = {}] = g;
1353
1353
  g = [B, D];
@@ -1356,7 +1356,7 @@ const j = class j {
1356
1356
  g = [B, D];
1357
1357
  }
1358
1358
  c.push([
1359
- b,
1359
+ S,
1360
1360
  g,
1361
1361
  I,
1362
1362
  { entityItemGetScan: o }
@@ -1378,72 +1378,72 @@ const j = class j {
1378
1378
  * @param {{oneBatch?: boolean}} [options] - Опции выполнения payload.
1379
1379
  */
1380
1380
  async batchPayload(t, e, r = {}) {
1381
- const i = !!(r != null && r.oneBatch), a = (O, T, R, b) => {
1381
+ const i = !!(r != null && r.oneBatch), a = (O, T, b, S) => {
1382
1382
  let p = "ID";
1383
1383
  this.result[O][this.result[O].length - 1].ID || (p = "id");
1384
- let S = `${p}`;
1385
- if (JSON.stringify(b[1]).toLocaleLowerCase().includes('"id":"desc"') ? S = "<" + S : S = ">" + S, T === 1 || R.length === 0)
1384
+ let E = `${p}`;
1385
+ if (JSON.stringify(S[1]).toLocaleLowerCase().includes('"id":"desc"') ? E = "<" + E : E = ">" + E, T === 1 || b.length === 0)
1386
1386
  return {
1387
- field: S,
1387
+ field: E,
1388
1388
  id: this.result[O][this.result[O].length - 1][p]
1389
1389
  };
1390
1390
  let N = "";
1391
- const [I, E] = b;
1391
+ const [I, R] = S;
1392
1392
  return (I === "tasks.task.list" || I === "task.item.list") && (N = "[tasks]"), ["crm.item.list", "crm.stagehistory.list"].includes(I) && (N = "[items]"), I === "crm.type.list" && (N = "[types]"), I === "socialnetwork.api.workgroup.list" && (N = "[workgroups]"), {
1393
- field: S,
1393
+ field: E,
1394
1394
  id: `$result[${[O, T - 1].join("__")}]${N}[49][${p}]`
1395
1395
  };
1396
1396
  }, c = (O, T) => {
1397
- const [R, b] = O;
1398
- let p = JSON.parse(JSON.stringify(b)), S;
1399
- if (R === "task.item.list") {
1397
+ const [b, S] = O;
1398
+ let p = JSON.parse(JSON.stringify(S)), E;
1399
+ if (b === "task.item.list") {
1400
1400
  p = [...p];
1401
- const [C, N, I, E] = p;
1402
- return N[T.field] = T.id, [R, p];
1401
+ const [C, N, I, R] = p;
1402
+ return N[T.field] = T.id, [b, p];
1403
1403
  }
1404
- return ["user.get"].includes(R) || p.FILTER ? (p.FILTER || (p.FILTER = {}), S = p.FILTER) : (p.filter || (p.filter = {}), S = p.filter), [
1404
+ return ["user.get"].includes(b) || p.FILTER ? (p.FILTER || (p.FILTER = {}), E = p.FILTER) : (p.filter || (p.filter = {}), E = p.filter), [
1405
1405
  "socialnetwork.api.workgroup.list",
1406
1406
  "tasks.task.list"
1407
- ].includes(R) ? S[">ID"] = T.id : S[T.field] = T.id, [R, { ...p, start: -1 }];
1407
+ ].includes(b) ? E[">ID"] = T.id : E[T.field] = T.id, [b, { ...p, start: -1 }];
1408
1408
  }, l = (O) => {
1409
- Object.entries(O).forEach(([T, R]) => {
1410
- var S, C, N, I, E;
1411
- const [b] = T.split("__"), p = this.getData(R.data());
1412
- if (Array.isArray(p) && (e === "count" ? this.result[b] += p.length : this.result[b].push(...p)), R.error()) {
1413
- const k = (C = (S = R.error()) == null ? void 0 : S.ex) == null ? void 0 : C.error, w = (I = (N = R.error()) == null ? void 0 : N.ex) == null ? void 0 : I.error_description;
1414
- this.errors[b] = k && k.trim() || w && w.trim() || ((E = R.error()) == null ? void 0 : E.toString()) || "Неизвестная ошибка";
1409
+ Object.entries(O).forEach(([T, b]) => {
1410
+ var E, C, N, I, R;
1411
+ const [S] = T.split("__"), p = this.getData(b.data());
1412
+ if (Array.isArray(p) && (e === "count" ? this.result[S] += p.length : this.result[S].push(...p)), b.error()) {
1413
+ const k = (C = (E = b.error()) == null ? void 0 : E.ex) == null ? void 0 : C.error, w = (I = (N = b.error()) == null ? void 0 : N.ex) == null ? void 0 : I.error_description;
1414
+ this.errors[S] = k && k.trim() || w && w.trim() || ((R = b.error()) == null ? void 0 : R.toString()) || "Неизвестная ошибка";
1415
1415
  }
1416
- this.setProgressData({ key: b, value: R, type: e });
1416
+ this.setProgressData({ key: S, value: b, type: e });
1417
1417
  });
1418
1418
  }, u = (O, T) => {
1419
1419
  if (!Array.isArray(O) || O.length === 0)
1420
1420
  return null;
1421
- const R = O[O.length - 1];
1422
- let b = "ID";
1423
- R.ID || (b = "id");
1424
- let p = b;
1425
- return JSON.stringify(T[1]).toLocaleLowerCase().includes('"id":"desc"') ? p = "<" + p : p = ">" + p, { field: p, id: R[b] };
1421
+ const b = O[O.length - 1];
1422
+ let S = "ID";
1423
+ b.ID || (S = "id");
1424
+ let p = S;
1425
+ return JSON.stringify(T[1]).toLocaleLowerCase().includes('"id":"desc"') ? p = "<" + p : p = ">" + p, { field: p, id: b[S] };
1426
1426
  }, n = 1e4, f = async (O, T) => {
1427
- var b, p;
1428
- let R = this.limit;
1429
- for (let S = 1; this.canContinue && R === this.limit && S <= n; S++) {
1427
+ var S, p;
1428
+ let b = this.limit;
1429
+ for (let E = 1; this.canContinue && b === this.limit && E <= n; E++) {
1430
1430
  const C = this.result[O], N = u(C, T);
1431
1431
  if (!N)
1432
1432
  break;
1433
- const I = `${O}__eiscan_${S}`, E = c(T, N);
1433
+ const I = `${O}__eiscan_${E}`, R = c(T, N);
1434
1434
  let k = null;
1435
- await _(this, tt, ht).call(this, { [I]: E }, async (m) => {
1435
+ await _(this, tt, ht).call(this, { [I]: R }, async (m) => {
1436
1436
  k = m, l(m);
1437
1437
  });
1438
- const w = S < n;
1438
+ const w = E < n;
1439
1439
  await _(this, $, lt).call(this, k, w), await this.delay();
1440
1440
  const s = k == null ? void 0 : k[I];
1441
- if ((b = s == null ? void 0 : s.error) != null && b.call(s)) {
1442
- R = 0;
1441
+ if ((S = s == null ? void 0 : s.error) != null && S.call(s)) {
1442
+ b = 0;
1443
1443
  break;
1444
1444
  }
1445
1445
  const o = this.getData((p = s == null ? void 0 : s.data) == null ? void 0 : p.call(s));
1446
- R = Array.isArray(o) ? o.length : 0;
1446
+ b = Array.isArray(o) ? o.length : 0;
1447
1447
  }
1448
1448
  };
1449
1449
  let d = [], A = 0;
@@ -1453,21 +1453,21 @@ const j = class j {
1453
1453
  for await (const O of t) {
1454
1454
  if (!this.canContinue)
1455
1455
  return;
1456
- const [T, R, b, p = {}] = O;
1456
+ const [T, b, S, p = {}] = O;
1457
1457
  if (p.entityItemGetScan) {
1458
1458
  if (await h(!0))
1459
1459
  return;
1460
1460
  if (i)
1461
1461
  continue;
1462
- await f(T, R);
1462
+ await f(T, b);
1463
1463
  continue;
1464
1464
  }
1465
- let S = 1;
1466
- for (; b > S * this.limit; ) {
1467
- const C = [T, S].join("__"), N = a(T, S, d, R);
1468
- if (d.push([C, c(R, N)]), i && d.length === 49 && await h(!0) || d.length % 50 === 0 && await h(!0))
1465
+ let E = 1;
1466
+ for (; S > E * this.limit; ) {
1467
+ const C = [T, E].join("__"), N = a(T, E, d, b);
1468
+ if (d.push([C, c(b, N)]), i && d.length === 49 && await h(!0) || d.length % 50 === 0 && await h(!0))
1469
1469
  return;
1470
- S++;
1470
+ E++;
1471
1471
  }
1472
1472
  }
1473
1473
  await h(!1);
@@ -1485,13 +1485,13 @@ Tt = new WeakSet(), $t = function() {
1485
1485
  const t = this.totalBatchCommands || 0, e = this.batchCommandMethods;
1486
1486
  if (t < M(j, Et) || !Array.isArray(e) || e.length !== t)
1487
1487
  return !1;
1488
- if (e.filter((a) => a === "crm.deal.list").length >= M(j, Rt))
1488
+ if (e.filter((a) => a === "crm.deal.list").length >= M(j, bt))
1489
1489
  return !0;
1490
1490
  const i = e.filter(
1491
1491
  (a) => typeof a == "string" && a.includes(".list")
1492
1492
  ).length;
1493
- return i >= M(j, bt) && i / t >= M(j, Lt);
1494
- }, Et = new WeakMap(), Rt = new WeakMap(), bt = new WeakMap(), Lt = new WeakMap(), at = new WeakSet(), Ot = function() {
1493
+ return i >= M(j, Rt) && i / t >= M(j, Lt);
1494
+ }, Et = new WeakMap(), bt = new WeakMap(), Rt = new WeakMap(), Lt = new WeakMap(), at = new WeakSet(), Ot = function() {
1495
1495
  if (!this.progressCall || !this.progressData)
1496
1496
  return;
1497
1497
  const { percent: t, allCount: e, allTotal: r } = this.progressPercent, i = { percent: t, allCount: e, allTotal: r };
@@ -1590,8 +1590,8 @@ Tt = new WeakSet(), $t = function() {
1590
1590
  this.clearProgressData(), this.progressCall = typeof t == "function" ? t : "", this.canContinue = !0, this.result = {}, this.errors = {}, this.chunkRate = 1, this.totalProgress = 0, this.batchCommandKeyOrder = [], this.totalBatchCommands = 0, this.batchCommandMethods = [], this.setTimeLimitState(!1, void 0);
1591
1591
  }, /** Не включать вес по командам для совсем маленьких batch. */
1592
1592
  L(j, Et, 5), /** Явный сигнал: много отдельных выборок сделок по фильтрам. */
1593
- L(j, Rt, 5), /** Достаточно «list»-методов в пачке и доля list от всех команд. */
1594
- L(j, bt, 8), L(j, Lt, 0.65);
1593
+ L(j, bt, 5), /** Достаточно «list»-методов в пачке и доля list от всех команд. */
1594
+ L(j, Rt, 8), L(j, Lt, 0.65);
1595
1595
  let v = j;
1596
1596
  var et;
1597
1597
  class re {
@@ -2242,18 +2242,18 @@ class Ie {
2242
2242
  for (const h of this.placeData)
2243
2243
  d.has(h.placement) || d.set(h.placement, []), d.get(h.placement).push(h);
2244
2244
  for (let h = 0; h < i.length; h++) {
2245
- const O = i[h].placement, T = d.get(O) || [];
2246
- if (T.some(
2247
- (p) => p.handler === r
2245
+ const { placement: O, options: T } = i[h], b = d.get(O) || [];
2246
+ if (b.some(
2247
+ (E) => E.handler === r
2248
2248
  ))
2249
2249
  continue;
2250
- const b = T.filter(
2251
- (p) => p.handler !== r
2250
+ const p = b.filter(
2251
+ (E) => E.handler !== r
2252
2252
  );
2253
- for (const p of b)
2253
+ for (const E of p)
2254
2254
  f.push({
2255
2255
  placement: O,
2256
- handler: p.handler
2256
+ handler: E.handler
2257
2257
  });
2258
2258
  n[`bind_${h}`] = {
2259
2259
  method: "placement.bind",
@@ -2266,7 +2266,8 @@ class Ie {
2266
2266
  }
2267
2267
  },
2268
2268
  OPTIONS: {
2269
- errorHandlerUrl: r
2269
+ errorHandlerUrl: r,
2270
+ ...T && typeof T == "object" ? T : {}
2270
2271
  }
2271
2272
  }
2272
2273
  };
@@ -2468,18 +2469,18 @@ function Ee() {
2468
2469
  let y = sessionStorage.getItem("szdl-cross-tab-instance-id");
2469
2470
  return y || (y = `${Date.now()}-${Math.random().toString(16).slice(2)}`, sessionStorage.setItem("szdl-cross-tab-instance-id", y)), y;
2470
2471
  }
2471
- function Re() {
2472
+ function be() {
2472
2473
  return typeof navigator < "u" && typeof navigator.locks < "u" && typeof navigator.locks.request == "function";
2473
2474
  }
2474
2475
  const Ft = /* @__PURE__ */ new Map();
2475
- function be(y = "default") {
2476
+ function Re(y = "default") {
2476
2477
  if (typeof BroadcastChannel > "u")
2477
2478
  return null;
2478
2479
  const t = `${de}bc:${y}`;
2479
2480
  return Ft.has(t) || Ft.set(t, new BroadcastChannel(t)), Ft.get(t);
2480
2481
  }
2481
2482
  function Vt(y, t) {
2482
- const e = be(y);
2483
+ const e = Re(y);
2483
2484
  if (e)
2484
2485
  try {
2485
2486
  const r = t && typeof t == "object" && !Array.isArray(t) ? t : { data: t };
@@ -2493,7 +2494,7 @@ function Vt(y, t) {
2493
2494
  }
2494
2495
  async function Le(y, t, e = {}) {
2495
2496
  const { ifAvailable: r = !1 } = e, i = typeof y == "string" && y.length > 0 ? y : "default", a = `${de}${i}`;
2496
- return Re() ? navigator.locks.request(
2497
+ return be() ? navigator.locks.request(
2497
2498
  a,
2498
2499
  { mode: "exclusive", ifAvailable: !!r },
2499
2500
  async (c) => {
@@ -2816,15 +2817,15 @@ class Me {
2816
2817
  );
2817
2818
  }
2818
2819
  async setBackgroundWorkerAll() {
2819
- var b, p, S, C;
2820
- if (!((b = this.bx) != null && b.isAdmin)) {
2820
+ var S, p, E, C;
2821
+ if (!((S = this.bx) != null && S.isAdmin)) {
2821
2822
  console.log(
2822
2823
  "BackgroundWorker: setBackgroundWorkerAll доступен только админам"
2823
2824
  );
2824
2825
  return;
2825
2826
  }
2826
2827
  (p = this.users) != null && p.length || await this.getEntityData(), Kt(this.bx);
2827
- const t = _(this, pt, Qt).call(this, ((C = (S = this.bx) == null ? void 0 : S.appConst) == null ? void 0 : C.pathApp) ?? "");
2828
+ const t = _(this, pt, Qt).call(this, ((C = (E = this.bx) == null ? void 0 : E.appConst) == null ? void 0 : C.pathApp) ?? "");
2828
2829
  if (!t) {
2829
2830
  console.error(
2830
2831
  "BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена"
@@ -2839,9 +2840,9 @@ class Me {
2839
2840
  if (N.placement !== "PAGE_BACKGROUND_WORKER")
2840
2841
  return;
2841
2842
  if (N.userId || N.handler && N.handler.includes("USER_ID=")) {
2842
- const E = N.userId || (N.handler ? this.extractUserIdFromHandler(N.handler) : null);
2843
- if (E) {
2844
- const k = +E;
2843
+ const R = N.userId || (N.handler ? this.extractUserIdFromHandler(N.handler) : null);
2844
+ if (R) {
2845
+ const k = +R;
2845
2846
  r.set(k, N), i.has(k) || i.set(k, []), i.get(k).push(N);
2846
2847
  }
2847
2848
  } else
@@ -2849,15 +2850,15 @@ class Me {
2849
2850
  });
2850
2851
  const c = await this.resolveAdmins(), l = await this.getEligibleUsersForBackgroundWorker(c);
2851
2852
  l.sort((N, I) => {
2852
- const E = N.LAST_LOGIN ? new Date(N.LAST_LOGIN) : /* @__PURE__ */ new Date(0);
2853
- return (I.LAST_LOGIN ? new Date(I.LAST_LOGIN) : /* @__PURE__ */ new Date(0)) - E;
2853
+ const R = N.LAST_LOGIN ? new Date(N.LAST_LOGIN) : /* @__PURE__ */ new Date(0);
2854
+ return (I.LAST_LOGIN ? new Date(I.LAST_LOGIN) : /* @__PURE__ */ new Date(0)) - R;
2854
2855
  });
2855
2856
  const u = 10, n = l.slice(0, u), f = n.filter((N) => {
2856
2857
  const I = r.get(+N.ID);
2857
2858
  if (!I)
2858
2859
  return !0;
2859
- const E = `${t}?USER_ID=${N.ID}/`;
2860
- return I.handler !== E;
2860
+ const R = `${t}?USER_ID=${N.ID}/`;
2861
+ return I.handler !== R;
2861
2862
  }), d = [];
2862
2863
  for (const [N] of r) {
2863
2864
  const I = +N || 0;
@@ -2867,18 +2868,18 @@ class Me {
2867
2868
  const I = r.get(+N.ID);
2868
2869
  if (!I)
2869
2870
  continue;
2870
- const E = `${t}?USER_ID=${N.ID}/`;
2871
- I.handler !== E && d.push(+N.ID);
2871
+ const R = `${t}?USER_ID=${N.ID}/`;
2872
+ I.handler !== R && d.push(+N.ID);
2872
2873
  }
2873
2874
  const A = [], h = [...new Set(d)];
2874
2875
  for (const N of h) {
2875
2876
  const I = i.get(+N) || [];
2876
- for (const E of I)
2877
- E != null && E.handler && A.push({
2877
+ for (const R of I)
2878
+ R != null && R.handler && A.push({
2878
2879
  method: "placement.unbind",
2879
2880
  params: {
2880
2881
  PLACEMENT: "PAGE_BACKGROUND_WORKER",
2881
- HANDLER: E.handler
2882
+ HANDLER: R.handler
2882
2883
  }
2883
2884
  });
2884
2885
  }
@@ -2914,7 +2915,7 @@ class Me {
2914
2915
  });
2915
2916
  const T = A.filter(
2916
2917
  (N) => N.method === "placement.unbind"
2917
- ), R = A.filter(
2918
+ ), b = A.filter(
2918
2919
  (N) => N.method === "placement.bind"
2919
2920
  );
2920
2921
  T.length && await this.safeCall(
@@ -2923,10 +2924,10 @@ class Me {
2923
2924
  T.map((N, I) => [`unbind_${I}`, N])
2924
2925
  )
2925
2926
  )
2926
- ), R.length && await this.safeCall(
2927
+ ), b.length && await this.safeCall(
2927
2928
  () => this.bx.batch(
2928
2929
  Object.fromEntries(
2929
- R.map((N, I) => [`bind_${I}`, N])
2930
+ b.map((N, I) => [`bind_${I}`, N])
2930
2931
  )
2931
2932
  )
2932
2933
  ), A.length || console.log("setBackgroundWorkerAll: Нет операций");
@@ -1,2 +1,2 @@
1
- var Ie=Object.defineProperty;var Me=(B,C,Y)=>C in B?Ie(B,C,{enumerable:!0,configurable:!0,writable:!0,value:Y}):B[C]=Y;var P=(B,C,Y)=>(Me(B,typeof C!="symbol"?C+"":C,Y),Y),qt=(B,C,Y)=>{if(!C.has(B))throw TypeError("Cannot "+Y)};var M=(B,C,Y)=>(qt(B,C,"read from private field"),Y?Y.call(B):C.get(B)),L=(B,C,Y)=>{if(C.has(B))throw TypeError("Cannot add the same private member more than once");C instanceof WeakSet?C.add(B):C.set(B,Y)},j=(B,C,Y,ot)=>(qt(B,C,"write to private field"),ot?ot.call(B,Y):C.set(B,Y),Y);var O=(B,C,Y)=>(qt(B,C,"access private method"),Y);(function(B,C){typeof exports=="object"&&typeof module<"u"?C(exports):typeof define=="function"&&define.amd?define(["exports"],C):(B=typeof globalThis<"u"?globalThis:B||self,C(B["szdl-utils-kit"]={}))})(this,function(B){var bt,ae,Rt,Lt,St,It,At,Ft,Mt,oe,Dt,Ae,V,ut,st,Tt,rt,Et,kt,ce,dt,Qt,it,Q,Z,nt,ct,gt,$,J,at,lt,Bt,le,yt,Zt,wt,he,Ct,ue,Ht,fe,ht,Xt,Ut,me,pt,Vt,Gt,de,Pt,ge,Yt,ye,tt,ft,Nt,$t,Wt,pe,Ot,te,xt,Ne,_t,ee;"use strict";var C=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Y(T){return T&&T.__esModule&&Object.prototype.hasOwnProperty.call(T,"default")?T.default:T}var ot={exports:{}};(function(T,s){(function(e){Array.prototype.indexOf||(Array.prototype.indexOf=function(t,o){var m,g;for(m=o||0,g=this.length;m<g;m+=1)if(this[m]===t)return m;return-1});var r=this,i=function(t,o){for(var m=t.toString();m.length<o;)m="0"+m;return m},a=function(t,o){return o!==e?(t.year(o.year()||o.year),t.month(o.month()||o.month),t.day(o.day()||o.day),t.hours(o.hours()||o.hours),t.minutes(o.minutes()||o.minutes),t.seconds(o.seconds()||o.seconds),t.milliseconds(o.milliseconds()||o.milliseconds),t):e},c=function(t,o){var m,g="";return m=t.slice(o,o+1),m!==""&&!isNaN(Number(m))&&(g+="%H"),m=t.charAt(o+2),m!==""&&m===":"&&(g+=m),m=t.slice(o+3,o+4),m!==""&&!isNaN(Number(m))&&(g+="%M"),m=t.charAt(o+5),m!==""&&m===":"&&(g+=m),m=t.slice(o+6,o+7),m!==""&&!isNaN(Number(m))&&(g+="%S"),g},l=function(t,o){var m,g=[t.slice(o,o+1),t.charAt(o+2),t.slice(o+3,o+4),t.charAt(o+5),t.slice(o+6,o+9)],H;return!isNaN(Number(g[0]))&&!isNaN(Number(g[2]))&&!isNaN(Number(g[4]))?(g[1]==="."&&g[3]==="."?m="%d.%m.%Y":g[1]==="-"&&g[3]==="-"?m="%m-%d-%Y":g[1]==="/"&&g[3]==="/"&&(m="%m/%d/%Y"),m):(H=[t.slice(o,o+3),t.charAt(o+4),t.slice(o+5,o+6),t.charAt(o+7),t.slice(o+8,o+9)],!isNaN(Number(H[0]))&&!isNaN(Number(H[2]))&&!isNaN(Number(H[4]))?(H[1]==="-"&&H[3]==="-"&&(m="%Y-%m-%d"),m):"")},u=r.tempus,n,f,d=r.navigator||{},A="en",h={en:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"Mar",APRIL_SHORT:"Apr",MAY_SHORT:"May",JUNE_SHORT:"Jun",JULY_SHORT:"Jul",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sep",OCTOBER_SHORT:"Oct",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dec",JANUARY_LONG:"January",FEBRUARY_LONG:"February",MARCH_LONG:"March",APRIL_LONG:"April",MAY_LONG:"May",JUNE_LONG:"June",JULY_LONG:"July",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"October",NOVEMBER_LONG:"November",DECEMBER_LONG:"December",SUNDAY_SHORT:"Sun",MONDAY_SHORT:"Mon",TUESDAY_SHORT:"Tue",WEDNESDAY_SHORT:"Wed",THURSDAY_SHORT:"Thu",FRIDAY_SHORT:"Fri",SATURDAY_SHORT:"Sat",SUNDAY_LONG:"Sunday",MONDAY_LONG:"Monday",TUESDAY_LONG:"Tuesday",WEDNESDAY_LONG:"Wednesday",THURSDAY_LONG:"Thursday",FRIDAY_LONG:"Friday",SATURDAY_LONG:"Saturday"},ru:{JANUARY_SHORT:"Янв",FEBRUARY_SHORT:"Фев",MARCH_SHORT:"Мар",APRIL_SHORT:"Апр",MAY_SHORT:"Май",JUNE_SHORT:"Июн",JULY_SHORT:"Июл",AUGUST_SHORT:"Авг",SEPTEMBER_SHORT:"Сен",OCTOBER_SHORT:"Окт",NOVEMBER_SHORT:"Ноя",DECEMBER_SHORT:"Дек",JANUARY_LONG:"Январь",FEBRUARY_LONG:"Февраль",MARCH_LONG:"Март",APRIL_LONG:"Апрель",MAY_LONG:"Май",JUNE_LONG:"Июнь",JULY_LONG:"Июль",AUGUST_LONG:"Август",SEPTEMBER_LONG:"Сентябрь",OCTOBER_LONG:"Октябрь",NOVEMBER_LONG:"Ноябрь",DECEMBER_LONG:"Декабрь",SUNDAY_SHORT:"Вс",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Воскресенье",MONDAY_LONG:"Понедельник",TUESDAY_LONG:"Вторник",WEDNESDAY_LONG:"Среда",THURSDAY_LONG:"Четверг",FRIDAY_LONG:"Пятница",SATURDAY_LONG:"Суббота"},ua:{JANUARY_SHORT:"Січ",FEBRUARY_SHORT:"Лют",MARCH_SHORT:"Берез",APRIL_SHORT:"Квіт",MAY_SHORT:"Трав",JUNE_SHORT:"Черв",JULY_SHORT:"Лип",AUGUST_SHORT:"Серп",SEPTEMBER_SHORT:"Верес",OCTOBER_SHORT:"Жовт",NOVEMBER_SHORT:"Листоп",DECEMBER_SHORT:"Груд",JANUARY_LONG:"Січень",FEBRUARY_LONG:"Лютий",MARCH_LONG:"Березень",APRIL_LONG:"Квітень",MAY_LONG:"Травень",JUNE_LONG:"Червень",JULY_LONG:"Липень",AUGUST_LONG:"Серпень",SEPTEMBER_LONG:"Вересень",OCTOBER_LONG:"Жовтень",NOVEMBER_LONG:"Листопад",DECEMBER_LONG:"Грудень",SUNDAY_SHORT:"Нд",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Неділя",MONDAY_LONG:"Понеділок",TUESDAY_LONG:"Вівторок",WEDNESDAY_LONG:"Середа",THURSDAY_LONG:"Четвер",FRIDAY_LONG:"П’ятниця",SATURDAY_LONG:"Субота"},de:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"März",APRIL_SHORT:"Apr",MAY_SHORT:"Mai",JUNE_SHORT:"Juni",JULY_SHORT:"Juli",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sept",OCTOBER_SHORT:"Okt",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dez",JANUARY_LONG:"Januar",FEBRUARY_LONG:"Februar",MARCH_LONG:"März",APRIL_LONG:"April",MAY_LONG:"Mai",JUNE_LONG:"Juni",JULY_LONG:"Juli",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"Oktober",NOVEMBER_LONG:"November",DECEMBER_LONG:"Dezember",SUNDAY_SHORT:"So",MONDAY_SHORT:"Mo",TUESDAY_SHORT:"Di",WEDNESDAY_SHORT:"Mi",THURSDAY_SHORT:"Do",FRIDAY_SHORT:"Fr",SATURDAY_SHORT:"Sa",SUNDAY_LONG:"Sonntag",MONDAY_LONG:"Montag",TUESDAY_LONG:"Dienstag",WEDNESDAY_LONG:"Mittwoch",THURSDAY_LONG:"Donnerstag",FRIDAY_LONG:"Freitag",SATURDAY_LONG:"Samstag"}},N=function(){return[h[A].JANUARY_LONG,h[A].FEBRUARY_LONG,h[A].MARCH_LONG,h[A].APRIL_LONG,h[A].MAY_LONG,h[A].JUNE_LONG,h[A].JULY_LONG,h[A].AUGUST_LONG,h[A].SEPTEMBER_LONG,h[A].OCTOBER_LONG,h[A].NOVEMBER_LONG,h[A].DECEMBER_LONG]},_=function(){return[h[A].JANUARY_SHORT,h[A].FEBRUARY_SHORT,h[A].MARCH_SHORT,h[A].APRIL_SHORT,h[A].MAY_SHORT,h[A].JUNE_SHORT,h[A].JULY_SHORT,h[A].AUGUST_SHORT,h[A].SEPTEMBER_SHORT,h[A].OCTOBER_SHORT,h[A].NOVEMBER_SHORT,h[A].DECEMBER_SHORT]},b=function(){return[h[A].SUNDAY_LONG,h[A].MONDAY_LONG,h[A].TUESDAY_LONG,h[A].WEDNESDAY_LONG,h[A].THURSDAY_LONG,h[A].FRIDAY_LONG,h[A].SATURDAY_LONG]},R=function(){return[h[A].SUNDAY_SHORT,h[A].MONDAY_SHORT,h[A].TUESDAY_SHORT,h[A].WEDNESDAY_SHORT,h[A].THURSDAY_SHORT,h[A].FRIDAY_SHORT,h[A].SATURDAY_SHORT]},y,S,U,p,I=function(t,o,m){var g;r.XMLHttpRequest?g=new XMLHttpRequest:g=new ActiveXObject("Microsoft.XMLHTTP"),g.onreadystatechange=function(){g.readyState===4&&(g.status===200?o&&(r.JSON===e?alert(`Please, include json2 into your project if you want use old browsers!
2
- https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(g.responseText))):m&&m(g))},g.open("GET",t,!1),g.send()},E={"%d":{format:function(t){return i(t.day()||n.MIN_DAY,2)},parse:function(t){var o=Number(t);return{day:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(t){return i(t.month()||n.MIN_MONTH,2)},parse:function(t){var o=Number(t);return{month:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(t){return i(t.year()||n.MIN_YEAR,4)},parse:function(t){var o=Number(t);return{year:isNaN(o)?e:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(t){return t.dayOfWeek()||n.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(t){var o=t.dayOfWeek();return p[o!==e?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var o=t.dayOfWeek();return U[o!==e?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(t){var o=n.options("monthFromZero")?t.month():t.month()-1;return S[o!==e?o:n.MIN_MONTH]},parse:function(t){var o=n.monthNames().indexOf(t)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var o=n.options("monthFromZero")?t.month():t.month()-1;return y[o!==e?o:n.MIN_MONTH]},parse:function(t){var o=n.monthNames(!0).indexOf(t)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(t){return i(t.hours()||n.MIN_HOURS,2)},parse:function(t){var o=Number(t);return{hours:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(t){return i(t.minutes()||n.MIN_MINUTES,2)},parse:function(t){var o=Number(t);return{minutes:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(t){return i(t.seconds()||n.MIN_SECONDS,2)},parse:function(t){var o=Number(t);return{seconds:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(t){return t.timestamp()},parse:function(t){return isNaN(Number(t))?{}:n(Number(t)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(t){return i(t.year()||n.MIN_YEAR,4)+"-"+i(t.month()||n.MIN_MONTH,2)+"-"+i(t.day()||n.MIN_DAY,2)},parse:function(t){var o=Number(t.slice(0,4)),m=Number(t.slice(5,7)),g=Number(t.slice(8,10));return{year:o,month:m,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return i(t.month()||n.MIN_MONTH,2)+"/"+i(t.day()||n.MIN_DAY,2)+"/"+i(t.year()||n.MIN_YEAR,4)},parse:function(t){var o=Number(t.slice(0,2)),m=Number(t.slice(3,5)),g=Number(t.slice(6,10));return{year:g,month:o,day:m}},minLength:10,maxLength:10,type:"string"}},w={useMilliseconds:!1,monthFromZero:!1},k;k=function(t,o,m){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t!==e&&this.set(t,o,m),this},k.fn=k.prototype,k.fn.dayCount=function(){var t=this.month(),o=n.MAX_DAY_IN_MONTHS[t-(n.options("monthFromZero")?0:1)];return this.leapYear()&&t===(n.options("monthFromZero")?1:2)&&(o+=1),o},k.fn.year=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_YEAR&&Number(t)<=n.MAX_YEAR?(this._d.setFullYear(Number(t)),this._i.year=!1):this._i.year=Number(t):(this._d.setFullYear(n.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},k.fn.month=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MONTH&&Number(t)<=n.MAX_MONTH?(this._d.setMonth(n.options("monthFromZero")?Number(t):Number(t)-1),this._i.month=!1):this._i.month=Number(t):(this._d.setMonth(n.options("monthFromZero")?n.MIN_MONTH:n.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?n.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},k.fn.day=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_DAY&&Number(t)<=this.dayCount()?(this._d.setDate(Number(t)),this._i.day=!1):this._i.day=Number(t):(this._d.setDate(n.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},k.fn.hours=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_HOURS&&Number(t)<=n.MAX_HOURS?(this._d.setHours(Number(t)),this._i.hours=!1):this._i.hours=Number(t):(this._d.setHours(n.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},k.fn.minutes=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MINUTES&&Number(t)<=n.MAX_MINUTES?(this._d.setMinutes(Number(t)),this._i.minutes=!1):this._i.minutes=Number(t):(this._d.setMinutes(n.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},k.fn.seconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_SECONDS&&Number(t)<=n.MAX_SECONDS?(this._d.setSeconds(Number(t)),this._i.seconds=!1):this._i.seconds=Number(t):(this._d.setSeconds(n.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},k.fn.milliseconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MILLISECONDS&&Number(t)<=n.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(t)),this._i.milliseconds=!1):this._i.milliseconds=Number(t):(this._d.setMilliseconds(n.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},k.fn.week=function(){var t=new Date(this.year(),0,1),o=n(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-t.getTime())/864e5+t.getDay()+1)/7)},k.fn.set=function(t,o,m){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t===e)return this._d=new Date,this;if(t instanceof Date)return this._d=t,this;if(typeof t=="number")return this._d=new Date(t*(n.options("useMilliseconds")?1:1e3)),this;if(typeof t=="object"&&(t instanceof Array?(this.day(n.MIN_DAY),this.year(t[0]),this.month(t[1]),this.day(t[2]),this.hours(t[3]),this.minutes(t[4]),this.seconds(t[5]),this.milliseconds(t[6])):(this.day(n.MIN_DAY),this.year(t.year),this.month(t.month),this.day(t.day),this.hours(t.hours),this.minutes(t.minutes),this.seconds(t.seconds),this.milliseconds(t.milliseconds))),typeof t=="string"){var g,H=[],D,G,et=[],X=0,K=0,W,v,x={},F;if(t===e)return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;for(o===e&&(o=n.detectFormat(t));X<o.length;){if(o.charAt(X)==="%"){if(G=o.charAt(X)+o.charAt(X+1),E[G]!==e){switch(W=0,v="",E[G].type){case"number":for(;W<E[G].maxLength&&K+W<t.length&&!isNaN(Number(t.charAt(K+W)));)v+=t.charAt(K+W),W+=1;break;case"word":for(;W<E[G].maxLength&&K+W<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(K+W));)v+=t.charAt(K+W),W+=1;break;case"string":for(;W<E[G].maxLength&&K+W<t.length;)v+=t.charAt(K+W),W+=1;break}if(W<E[G].minLength)return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;H.push(G),et.push(v),W-=1,K+=W,X+=1}}else if(t.charAt(K)!==o.charAt(X))return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;X+=1,K+=1}for(g in H)H.hasOwnProperty(g)&&E.hasOwnProperty(H[g])&&(F=E[H[g]].parse(et[g]),x={year:F.year!==e?F.year:x.year,month:F.month!==e?F.month:x.month,day:F.day!==e?F.day:x.day,hours:F.hours!==e?F.hours:x.hours,minutes:F.minutes!==e?F.minutes:x.minutes,seconds:F.seconds!==e?F.seconds:x.seconds});this.day(n.MIN_DAY),this.year(x.year),this.month(x.month),this.day(x.day),this.hours(x.hours),this.minutes(x.minutes),this.seconds(x.seconds),this.milliseconds(x.milliseconds)}return this},k.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},k.fn.timestamp=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(n.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):n.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},k.fn.utc=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(n.options("useMilliseconds")?1:1e3)),this):n.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},k.fn.dayOfWeek=function(t){if(t==="long")return U[this._d.getDay()];if(t==="short")return p[this._d.getDay()];if(t===e)return this._d.getDay();if(t===0||t==="Sunday")return this.calc({day:-this.dayOfWeek()});if(t===1||t==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(t===2||t==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(t===3||t==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(t===4||t==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(t===5||t==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(t===6||t==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},k.fn.timezone=function(t){switch(t){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},k.fn.get=function(t){switch(t){case"Date":return new Date(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds());case"DateUTC":return new Date(Date.UTC(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()));case"Array":return[this.year(),this.month(),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()];default:return{year:this.year(),month:this.month(),week:this.week(),day:this.day(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds(),utc:this.utc(),dayOfWeek:this.dayOfWeek(),dayOfWeekShort:this.dayOfWeek("short"),dayOfWeekLong:this.dayOfWeek("long"),timestamp:this.timestamp()}}},k.fn.format=function(t){for(var o=0,m="",g;o<t.length;)t.charAt(o)==="%"?(g=t.charAt(o)+t.charAt(o+1),E[g]!==e?(m+=E[g].format(this),o+=1):m+="%"):m+=t.charAt(o),o+=1;return m},k.fn.valid=function(){return this._i.year===!1&&this._i.month===!1&&this._i.day===!1&&this._i.hours===!1&&this._i.minutes===!1&&this._i.seconds===!1&&this._i.milliseconds===!1},k.fn.errors=function(){return this._i},k.fn.between=function(t,o){var m=this.timestamp(),g=t.timestamp();switch(o){case"year":return Math.floor((g-m)/31556952);case"month":return Math.floor((g-m)/2629746);case"day":return Math.floor((g-m)/86400);case"hours":return Math.floor((g-m)/3600);case"minutes":return Math.floor((g-m)/60);case"seconds":return g-m;default:return e}},k.fn.calc=function(t){return t.year!==e&&this._d.setFullYear(this._d.getFullYear()+t.year),t.month!==e&&this._d.setMonth(this._d.getMonth()+t.month),t.day!==e&&this._d.setDate(this._d.getDate()+t.day),t.hours!==e&&this._d.setHours(this._d.getHours()+t.hours),t.minutes!==e&&this._d.setMinutes(this._d.getMinutes()+t.minutes),t.seconds!==e&&this._d.setSeconds(this._d.getSeconds()+t.seconds),t.milliseconds!==e&&this._d.setMilliseconds(this._d.getMilliseconds()+t.milliseconds),this},n=function(t,o,m){return new k(t,o,m)},n.MIN_YEAR=1e3,n.MAX_YEAR=3e3,n.MIN_MONTH=1,n.MAX_MONTH=12,n.MIN_DAY=1,n.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],n.MIN_DAY_OF_WEEK=0,n.MAX_DAY_OF_WEEK=6,n.MIN_HOURS=0,n.MAX_HOURS=23,n.MIN_MINUTES=0,n.MAX_MINUTES=59,n.MIN_SECONDS=0,n.MAX_SECONDS=59,n.MIN_MILLISECONDS=0,n.MAX_MILLISECONDS=999,n.VERSION="0.2.18",n.options=function(t,o){if(t===e)return w;if(w.hasOwnProperty(t)){if(o===e)return w[t];w[t]=o,t==="monthFromZero"&&(n.MIN_MONTH=o?0:1,n.MAX_MONTH=o?11:12)}return e},n.noConflict=function(){return r.tempus=u,n},n.generate=function(t){var o,m,g,H,D,G,et,X;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof k?o=t.dateFrom.utc():o=n(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof k?m=t.dateTo.utc():m=n(t.dateTo,t.formatTo!==e?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?D={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?D={year:t.period==="year"?1:0,month:t.period==="month"?1:0,day:t.period==="day"?1:0,hours:t.period==="hours"?1:0,minutes:t.period==="minutes"?1:0,seconds:t.period==="seconds"?1:0}:typeof t.period=="object"&&(D={year:t.period.year!==e?t.period.year:0,month:t.period.month!==e?t.period.month:0,day:t.period.day!==e?t.period.day:0,hours:t.period.hours!==e?t.period.hours:0,minutes:t.period.minutes!==e?t.period.minutes:0,seconds:t.period.seconds!==e?t.period.seconds:0}),t.groupBy===e?G=t.asObject===!0?{}:[]:(G=[],G.push([]),et=n(o).get()[t.groupBy]),X=function(v,x,F){return t.asObject===!0?t.format!==e?v[n(x).format(t.format)]={}:v[n(x).format("%F %H:%M:%S")]={}:t.format!==e?v.push(F?null:n(x).format(t.format)):v.push(F?null:n(x)),v},t.groupBy!==e&&t.fillNulls){var K={year:D.year?-D.year:e,month:D.month?-D.month:e,day:D.day?-D.day:e,hours:D.hours?-D.hours:e,minutes:D.minutes?-D.minutes:e,seconds:D.seconds?-D.seconds:e,milliseconds:D.milliseconds?-D.milliseconds:e};for(g=n(o).calc(K).utc();n(g).get()[t.groupBy]===et;)X(G[G.length-1],g,!0),g=n(g).calc(K).utc();if(t.groupBy==="week"){var W=n(o).dayOfWeek();for(g=n(o).dayOfWeek(0).utc();G[0].length<W&&g<o;)X(G[G.length-1],g,!0),g=n(g).calc(D).utc()}}for(;o<=m;)t.groupBy===e?X(G,o):n(o).get()[t.groupBy]===et?X(G[G.length-1],o):(G.push([]),X(G[G.length-1],o),et=n(o).get()[t.groupBy]),o=n(o).calc(D).utc();if(t.groupBy!==e&&t.fillNulls)for(H=n(m).calc(D).utc();n(H).get()[t.groupBy]===et;)X(G[G.length-1],H,!0),H=n(H).calc(D).utc();return G},n.monthNames=function(t){switch(t){case"long":return y;default:return S}},n.dayNames=function(t){switch(t){case"long":return U;default:return p}},n.lang=function(t){if(t!==e)A=t,h[A]===e&&(A="en"),y=N(),S=_(),U=b(),p=R();else return A;return e},n.availableLangs=function(){return Object.keys(h)},n.registerFormat=function(t,o,m,g,H,D){E[t]={format:o,parse:m,minLength:g,maxLength:H,type:D}},n.unregisterFormat=function(t){delete E[t]},n.detectFormat=function(t){var o,m,g;return o=l(t,0),o!==""&&(g=10),m=t.charAt(g),(m==="T"||m===" ")&&(o+=m,g+=1),o+=c(t,g),o},f={TempusDate:k},n.classes=function(t,o){if(o===e)return f[t];f[t]=o},n.loadTranslations=function(t){typeof t=="object"?h=t:typeof t=="string"&&I(t,function(o){h=o},function(o){})},A=(d.language||d.systemLanguage||d.userLanguage||"en").substr(0,2).toLowerCase(),h[A]===e&&(A="en"),y=N(),S=_(),U=b(),p=R(),T.exports&&(s=T.exports=n),s.tempus=n}).call(C)})(ot,ot.exports);var Oe=ot.exports;const mt=Y(Oe),q=class q{constructor(s){L(this,bt);L(this,At);L(this,Mt);L(this,Dt);L(this,V);L(this,st);L(this,rt);L(this,kt);L(this,dt);typeof s=="function"?(this.callBatch=s,this.callMethod=null):(this.callBatch=(s==null?void 0:s.callBatch)||null,this.callMethod=(s==null?void 0:s.callMethod)||null),this.result={},this.errors={},this.timeLimit={limit:!1,date:void 0,pauseMs:void 0},this.timeLimitListeners=new Set,this.canContinue=!0,this.progressCall="",this.progressData="",this.progressTimer="",this.lastProgressSnapshot=null,this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.filterChunkSize=50,this.limit=50,this.progressDelay=100,this.operatingThreshold=475,this.defaultPauseMs=12e4,this.callLimitPauseMs=3e4,this.requestTimeoutMs=6e4}get progressPercent(){if(!this.progressData)return{percent:0,allCount:0,allTotal:0};const s=this.totalBatchCommands||0;if(s>0&&Array.isArray(this.batchCommandKeyOrder)&&this.batchCommandKeyOrder.length&&O(this,bt,ae).call(this)){let l=0;for(const A of this.batchCommandKeyOrder){const h=this.progressData[A];if(!h)continue;const N=Number(h.total)||0,_=Number(h.count)||0;N===0&&_===0?l+=1:N>0&&(l+=Math.min(1,_/N))}const u=l/s*100;let n=Math.max(0,Math.min(100,Math.floor(u)));const f=s,d=Math.min(s,Math.floor(l));return{percent:n,allCount:d,allTotal:f}}let e=0,r=0;for(const l of Object.values(this.progressData)){const{total:u,count:n}=l;e+=u??0,r+=n??0}const i=Number(this.chunkRate)||0;let a=0;e?a=r/e*100*i+this.totalProgress:r===0&&e===0?a=100*i+this.totalProgress:a=100,a=Math.max(0,Math.min(a,100));let c=Math.floor(a);return e>0&&r>=e&&(c=100),{percent:c,allCount:r,allTotal:e}}setProgressData({key:s,value:e,type:r}){var h,N;if(!this.progressCall)return;const i=this.getData(e.data()),a=Array.isArray(i)?i.length:0;let c=a;if(typeof e.total=="function"){const _=e.total();if(_!=null&&_!==""){const b=Number(_);Number.isFinite(b)&&(c=b)}}r==="count"&&(c=a);let l=1;i&&(l=a),this.progressData||(this.progressData={});const u=((h=this.progressData[s])==null?void 0:h.total)??0,n=((N=this.progressData[s])==null?void 0:N.count)??0,f=l+n,d=Math.max(u,c??0,f);if(this.progressData[s]={total:d,count:Math.min(f,d)},typeof document<"u"&&(document==null?void 0:document.hidden)===!0){O(this,At,Ft).call(this);return}O(this,At,Ft).call(this),this.progressTimer||(this.progressTimer=setInterval(()=>{if(!this.progressCall){this.clearProgressData();return}O(this,At,Ft).call(this);const{percent:_}=this.progressPercent;_>=100&&(clearInterval(this.progressTimer),this.progressTimer="")},this.progressDelay))}getData(s){if(s==null)return s;let e=(s==null?void 0:s.items)??(s==null?void 0:s.tasks)??(s==null?void 0:s.types)??(s==null?void 0:s.type)??(s==null?void 0:s.fields)??(s==null?void 0:s.workgroups)??s;return e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.result)&&(e=e.result),e}setTimeLimitState(s,e,r){this.timeLimit.limit=!!s,this.timeLimit.date=s?e:void 0,s&&typeof r=="number"&&r>0?this.timeLimit.pauseMs=r:this.timeLimit.pauseMs=void 0,O(this,Dt,Ae).call(this)}subscribeTimeLimit(s){return typeof s!="function"?()=>{}:(this.timeLimitListeners.add(s),s({limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs}),()=>{this.timeLimitListeners.delete(s)})}splitLargeFilters(s,e){const{method:r,params:i}=e;if(!i)return[{key:s,request:e}];const a=i.filter||i.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:s,request:e}];for(const[c,l]of Object.entries(a))if(!String(c).trim().startsWith("!")&&Array.isArray(l)&&l.length>this.filterChunkSize){const u=[];for(let n=0;n<l.length;n+=this.filterChunkSize){const f=l.slice(n,n+this.filterChunkSize),d=n===0?s:`${s}__chunk_${Math.floor(n/this.filterChunkSize)}`,A={...i};i.filter?(A.filter={...a},A.filter[c]=f):i.FILTER&&(A.FILTER={...a},A.FILTER[c]=f),u.push({key:d,request:{method:r,params:A},originalKey:s,filterKey:c,chunkIndex:Math.floor(n/this.filterChunkSize)})}return u}return[{key:s,request:e}]}mergeSplitResults(s,e){const r=[],i=String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${i}(?:__chunk_\\d+)?$`),c=Object.keys(s).filter(l=>a.test(l)).sort((l,u)=>{const n=l.match(/__chunk_(\d+)$/),f=u.match(/__chunk_(\d+)$/);return n?f?parseInt(n[1])-parseInt(f[1]):1:-1});for(const l of c){const u=s[l];Array.isArray(u)?r.push(...u):u&&r.push(u)}return r}delay(){return typeof document<"u"&&(document==null?void 0:document.hidden)===!0?Promise.resolve():new Promise(e=>setTimeout(e,500))}callBatchWithTimeout(s,e){return new Promise((r,i)=>{let a=!1,c=null;const l=async n=>{if(!a){a=!0,c&&clearTimeout(c);try{await Promise.resolve(e(n)),r()}catch(f){console.error("Error in callBatch callback:",f),i(f)}}},u=async()=>{if(!a){a=!0,c&&clearTimeout(c),console.warn(`Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`);const n={};Object.keys(s).forEach(f=>{n[f]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 60 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(e(n)),r()}catch(f){console.error("Error in timeout callback:",f),r()}}};try{this.callBatch(s,async n=>{await l(n)})}catch(n){a||console.error("Error calling callBatch:",n)}c=setTimeout(async()=>{a||(console.warn(`Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`),await u())},this.requestTimeoutMs)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.lastProgressSnapshot=null}async batch(s,e,r={}){O(this,dt,Qt).call(this,e);const i={},a={},c={};for(const[f,d]of Object.entries(s)){const A=this.arrayChunk(d);if(!A)continue;const h=this.splitLargeFilters(f,A);if(h.length===1)a[f]=A;else{c[f]=[];for(const N of h)a[N.key]=N.request,c[f].push(N.key)}}this.batchCommandKeyOrder=Object.keys(a),this.totalBatchCommands=this.batchCommandKeyOrder.length,this.batchCommandMethods=this.batchCommandKeyOrder.map(f=>{var d;return String(((d=a[f])==null?void 0:d.method)||"")}),this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let l={},u=0;const n=Object.keys(a).length;for(const[f,d]of Object.entries(a)){if(!this.canContinue)break;if(l[f]=d,Object.keys(l).length>=this.limit||u+1===n){const A=u+1===n;await this.batchChunk(l,void 0,!A,{disablePagination:!1,oneBatch:!!(r!=null&&r.oneBatch)}),Object.entries(this.result).forEach(([h,N])=>{i[h]=N}),this.totalProgress=Math.round(u/n*100),l={}}u++}for(const[f,d]of Object.entries(c))if(d&&d.length>0){const A=this.mergeSplitResults(i,f);for(const h of d)delete i[h];i[f]=A}return Object.entries(this.errors).length&&(i.errorsList=this.errors),e&&e({percent:100}),Promise.resolve(i)}async batchTotalCount(s,e){O(this,dt,Qt).call(this,e);const r={},i={},a={};for(const[u,n]of Object.entries(s)){const f=this.arrayChunk(n);if(!f)continue;const d=this.splitLargeFilters(u,f);if(d.length===1)i[u]=f;else{a[u]=[];for(const A of d)i[A.key]=A.request,a[u].push(A.key)}}const c=[],l=Object.entries(i);for(let u=0;u<l.length;u+=this.limit){const n=l.slice(u,u+this.limit),f={};for(const[d,A]of n){if(!this.canContinue)break;f[d]=A}Object.keys(f).length>0&&c.push(f)}this.chunkRate=(1/c.length).toFixed(5);for(const[u,n]of Object.entries(c)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(u)/c.length*100);const f=Number(u)===c.length-1;await O(this,rt,Et).call(this,n,async d=>{var A,h,N,_,b;for(const[R,y]of Object.entries(d)){if(!this.canContinue)return;if(y.error()){const E=(h=(A=y.error())==null?void 0:A.ex)==null?void 0:h.error,w=(_=(N=y.error())==null?void 0:N.ex)==null?void 0:_.error_description;this.errors[R]=E&&E.trim()||w&&w.trim()||((b=y.error())==null?void 0:b.toString())||"Неизвестная ошибка",r[R]=0;continue}const S=this.getData(y.data()),U=Array.isArray(S)?S.length:0,I=typeof y.total=="function"&&y.total()!==void 0?y.total():U;r[R]=I,this.setProgressData({key:R,value:y,type:"count"})}await O(this,st,Tt).call(this,d,!f)})}for(const[u,n]of Object.entries(a))if(n&&n.length>0){let f=0;for(const d of n)r[d]!==void 0&&(f+=r[d]||0),delete r[d];r[u]=f}return Object.entries(this.errors).length&&(r.errorsList=this.errors,this.errorLogger()),e&&e({percent:100}),Promise.resolve(r)}async call({method:s,params:e={}}){var r,i,a,c,l,u,n;for(;;){const f=await O(this,kt,ce).call(this,s,e);if(!f){await O(this,V,ut).call(this,this.callLimitPauseMs);continue}const d={};if(f!=null&&f.answer)for(const[h,N]of Object.entries(f.answer))h!=="result"&&N&&(d[h]=N);if(f.error()){const h=((i=(r=f.error())==null?void 0:r.ex)==null?void 0:i.error)??"";if(["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT","TIMEOUT"].includes(h)){await O(this,V,ut).call(this,this.callLimitPauseMs);continue}const N=((a=f.error())==null?void 0:a.toString())||((l=(c=f.error())==null?void 0:c.ex)==null?void 0:l.error_description)||((n=(u=f.error())==null?void 0:u.ex)==null?void 0:n.error)||"Неизвестная ошибка";return{success:!1,data:!1,answer:d,error:N}}let A=f.data();return A!=null&&A.items&&(A=A.items),{success:!0,data:A,answer:d,error:null}}}arrayChunk(s){let e="",r={};if(Array.isArray(s)?[e]=s:(e=s.method,r=s.params),(e.includes("list")||e==="user.get"||e==="entity.item.get")&&e!=="task.item.list"){if(!r)r=e==="entity.item.get"?{SORT:{ID:"ASC"}}:{order:{ID:"ASC",id:"ASC"}};else{e==="entity.item.get"?(r.SORT||(r.SORT={ID:"ASC"}),Array.isArray(r.select)?r.select.includes("ID")||r.select.push("ID"):r.select=["ID"]):e==="tasks.task.list"?(r.order||(r.order={}),r.order.ID="asc"):e==="user.get"?(r.sort||(r.sort="ID"),r.order||(r.order="ASC")):r.order={ID:"ASC",id:"ASC"},Array.isArray(r.select)&&!r.select.includes("ID")&&r.select.push("ID");const i=e==="user.get"||e==="entity.item.get"?r.FILTER:r.filter;typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.entries(i).forEach(([a,c])=>{(r.start===void 0||r.start!==-1)&&["id","ID"].includes(a)&&(typeof c=="string"||Array.isArray(c)&&c.length<=50)&&(r.start=-1)})}e==="crm.type.list"&&r.order&&delete r.order.ID}if(e==="task.item.list")if(!r)r=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(r[0])&&(r[0]={});const[i,a,c,l]=r;i.ID="ASC",l[0]!==""&&l.includes("ID")||l.push("ID")}return{method:e,params:r}}async batchChunk(s,e,r=!0,i={}){return new Promise(a=>{const c=[];let l;const u=!!(i!=null&&i.disablePagination);(async()=>{await O(this,rt,Et).call(this,s,async f=>{var A,h,N,_,b;for(const[R,y]of Object.entries(f)){if(!this.canContinue)return;if(y.error()){const g=(h=(A=y.error())==null?void 0:A.ex)==null?void 0:h.error,H=(_=(N=y.error())==null?void 0:N.ex)==null?void 0:_.error_description;this.errors[R]=g&&g.trim()||H&&H.trim()||((b=y.error())==null?void 0:b.toString())||"Неизвестная ошибка",l=!0}const S=this.getData(y.data()),U=Array.isArray(S)?S.length:0,p=typeof y.total=="function"&&y.total()!==void 0,I=p?y.total():U;e==="count"?this.result[R]?this.result[R]+=U:this.result[R]=I:this.result[R]=S,this.setProgressData({key:R,value:y,type:e});const E=s[R],w=Array.isArray(E)?E[0]:E==null?void 0:E.method,k=typeof w=="string"&&(w.includes(".list")||w==="user.get"||w==="entity.item.get"),t=e==="count"?!p&&U===this.limit:k?U===this.limit:I>this.limit&&I>U,o=e!=="count"&&w==="entity.item.get"&&U===this.limit&&!t,m=t||o;if(!u&&(!this.canContinue||m)){let g=s[R];if(Array.isArray(g)){const[H,D={}]=g;g=[H,D]}else{const{method:H,params:D={}}=g;g=[H,D]}c.push([R,g,I,{entityItemGetScan:o}])}}l>0&&this.errorLogger();const d=c.length>0||r;await O(this,st,Tt).call(this,f,d),c.length?await this.batchPayload(c,e,i).then(()=>a(this.result)):a(this.result)})})()})}async batchPayload(s,e,r={}){const i=!!(r!=null&&r.oneBatch),a=(N,_,b,R)=>{let y="ID";this.result[N][this.result[N].length-1].ID||(y="id");let S=`${y}`;if(JSON.stringify(R[1]).toLocaleLowerCase().includes('"id":"desc"')?S="<"+S:S=">"+S,_===1||b.length===0)return{field:S,id:this.result[N][this.result[N].length-1][y]};let p="";const[I,E]=R;return(I==="tasks.task.list"||I==="task.item.list")&&(p="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(I)&&(p="[items]"),I==="crm.type.list"&&(p="[types]"),I==="socialnetwork.api.workgroup.list"&&(p="[workgroups]"),{field:S,id:`$result[${[N,_-1].join("__")}]${p}[49][${y}]`}},c=(N,_)=>{const[b,R]=N;let y=JSON.parse(JSON.stringify(R)),S;if(b==="task.item.list"){y=[...y];const[U,p,I,E]=y;return p[_.field]=_.id,[b,y]}return["user.get"].includes(b)||y.FILTER?(y.FILTER||(y.FILTER={}),S=y.FILTER):(y.filter||(y.filter={}),S=y.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(b)?S[">ID"]=_.id:S[_.field]=_.id,[b,{...y,start:-1}]},l=N=>{Object.entries(N).forEach(([_,b])=>{var S,U,p,I,E;const[R]=_.split("__"),y=this.getData(b.data());if(Array.isArray(y)&&(e==="count"?this.result[R]+=y.length:this.result[R].push(...y)),b.error()){const w=(U=(S=b.error())==null?void 0:S.ex)==null?void 0:U.error,k=(I=(p=b.error())==null?void 0:p.ex)==null?void 0:I.error_description;this.errors[R]=w&&w.trim()||k&&k.trim()||((E=b.error())==null?void 0:E.toString())||"Неизвестная ошибка"}this.setProgressData({key:R,value:b,type:e})})},u=(N,_)=>{if(!Array.isArray(N)||N.length===0)return null;const b=N[N.length-1];let R="ID";b.ID||(R="id");let y=R;return JSON.stringify(_[1]).toLocaleLowerCase().includes('"id":"desc"')?y="<"+y:y=">"+y,{field:y,id:b[R]}},n=1e4,f=async(N,_)=>{var R,y;let b=this.limit;for(let S=1;this.canContinue&&b===this.limit&&S<=n;S++){const U=this.result[N],p=u(U,_);if(!p)break;const I=`${N}__eiscan_${S}`,E=c(_,p);let w=null;await O(this,rt,Et).call(this,{[I]:E},async m=>{w=m,l(m)});const k=S<n;await O(this,st,Tt).call(this,w,k),await this.delay();const t=w==null?void 0:w[I];if((R=t==null?void 0:t.error)!=null&&R.call(t)){b=0;break}const o=this.getData((y=t==null?void 0:t.data)==null?void 0:y.call(t));b=Array.isArray(o)?o.length:0}};let d=[],A=0;const h=async(N=!0)=>d.length?(await O(this,rt,Et).call(this,Object.fromEntries(d),async _=>{l(_),await O(this,st,Tt).call(this,_,N)}),A++,d=[],i&&A>=1?!0:(await this.delay(),!1)):!1;for await(const N of s){if(!this.canContinue)return;const[_,b,R,y={}]=N;if(y.entityItemGetScan){if(await h(!0))return;if(i)continue;await f(_,b);continue}let S=1;for(;R>S*this.limit;){const U=[_,S].join("__"),p=a(_,S,d,b);if(d.push([U,c(b,p)]),i&&d.length===49&&await h(!0)||d.length%50===0&&await h(!0))return;S++}}await h(!1)}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([s,e])=>{e&&console.log(`[${s}]`,e.toString())}),console.groupEnd()}};bt=new WeakSet,ae=function(){const s=this.totalBatchCommands||0,e=this.batchCommandMethods;if(s<M(q,Rt)||!Array.isArray(e)||e.length!==s)return!1;if(e.filter(a=>a==="crm.deal.list").length>=M(q,Lt))return!0;const i=e.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=M(q,St)&&i/s>=M(q,It)},Rt=new WeakMap,Lt=new WeakMap,St=new WeakMap,It=new WeakMap,At=new WeakSet,Ft=function(){if(!this.progressCall||!this.progressData)return;const{percent:s,allCount:e,allTotal:r}=this.progressPercent,i={percent:s,allCount:e,allTotal:r};O(this,Mt,oe).call(this,i)&&(this.progressCall({data:this.progressData,percent:s,allCount:e,allTotal:r}),this.lastProgressSnapshot=i)},Mt=new WeakSet,oe=function(s){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==s.percent||this.lastProgressSnapshot.allCount!==s.allCount||this.lastProgressSnapshot.allTotal!==s.allTotal:!0},Dt=new WeakSet,Ae=function(){const s={limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs};for(const e of this.timeLimitListeners)try{e(s)}catch(r){console.warn("Batch timeLimit listener error:",r)}},V=new WeakSet,ut=async function(s=this.defaultPauseMs){this.setTimeLimitState(!0,new Date().toISOString(),s),await new Promise(e=>setTimeout(e,s)),this.setTimeLimitState(!1,void 0)},st=new WeakSet,Tt=async function(s,e=!0){if(!e)return 0;let r=0;if(!s||typeof s!="object")return 0;for(const i of Object.values(s))if(!(!i||typeof i!="object"))try{if(typeof i.time=="function"){const a=i.time();a&&typeof a.operating=="number"&&(r=Math.max(r,a.operating))}}catch{}r>=this.operatingThreshold&&await O(this,V,ut).call(this)},rt=new WeakSet,Et=async function(s,e){let r=!1,i=s;do r=!1,await this.callBatchWithTimeout(i,async a=>{var u,n;let c=!1;const l=new Set;for(const[f,d]of Object.entries(a||{})){if(!(d!=null&&d.error)||!d.error())continue;const A=((n=(u=d.error())==null?void 0:u.ex)==null?void 0:n.error)??"";if(A==="TIMEOUT"){c=!0;break}["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT"].includes(A)&&l.add(f)}if(c){r=!0,await O(this,V,ut).call(this);return}if(l.size>0){const f={};for(const[A,h]of Object.entries(a||{}))l.has(A)||(f[A]=h);Object.keys(f).length&&await e(f);const d={};for(const A of l)i[A]&&(d[A]=i[A]);i=d,Object.keys(i).length&&(r=!0,await O(this,V,ut).call(this));return}await e(a)});while(r)},kt=new WeakSet,ce=function(s,e){return new Promise(r=>{if(typeof this.callMethod!="function"){r(null);return}let i=!1;const a=setTimeout(()=>{i||(i=!0,r(null))},this.requestTimeoutMs);try{this.callMethod(s,e,c=>{i||(i=!0,clearTimeout(a),r(c))})}catch{i||(i=!0,clearTimeout(a),r(null))}})},dt=new WeakSet,Qt=function(s){this.clearProgressData(),this.progressCall=typeof s=="function"?s:"",this.canContinue=!0,this.result={},this.errors={},this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.setTimeLimitState(!1,void 0)},L(q,Rt,5),L(q,Lt,5),L(q,St,8),L(q,It,.65);let z=q;class jt{constructor(){L(this,it,{})}get hash(){return this.createHash(8)}createHash(s){let e="abcdefghijklmnopqrstuvwxyz0123456789",r="";s=s||6;for(let i=0;i<s;i++)r+=e.charAt(Math.floor(Math.random()*e.length));return r}actionFilter({keyTimer:s,duration:e=10,action:r}){M(this,it)[s]&&(clearTimeout(M(this,it)[s]),M(this,it)[s]=null),r&&(M(this,it)[s]=setTimeout(()=>{r()},e))}async noSleep(){let s=document.createElement("video");s.classList.add("no-sleep"),s.muted=!0,s.autoplay=!0,s.setAttribute("playsinline",""),s.addEventListener("loadeddata",()=>{s.style.position="fixed",s.style.left="-9999px",document.querySelector("body").append(s),s.play().catch(e=>{console.warn("noSleep: autoplay prevented",e)})}),s.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{s.play().catch(e=>{console.warn("noSleep: replay prevented",e)})}})}),s.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(s,e){let r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=i,a.download=`${e}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(i)},200)}}it=new WeakMap;const Jt=new jt;class se{constructor(){L(this,Bt);L(this,yt);L(this,wt);L(this,Ct);L(this,Ht);L(this,Q,"logger");L(this,Z,!1);L(this,nt,new Map);L(this,ct,{});L(this,gt,!1);L(this,$,null);L(this,J,null);L(this,at,!1);L(this,lt,!1);P(this,"periodClear",3)}async init(){try{let s=new z(BX24.callBatch),{entityList:e}=await s.batch({entityList:{method:"entity.get"}});if(e&&Array.isArray(e))if(e.find(i=>i.ENTITY==M(this,Q)))j(this,Z,!0);else{let{entityAdd:i}=await s.batch({entityAdd:{method:"entity.add",params:{ENTITY:M(this,Q),NAME:M(this,Q),ACCESS:{AU:"X"}}}});i&&j(this,Z,!0)}return M(this,Z)}catch(s){return console.error("Ошибка при инициализации логера:",s),!1}}enableBackworkerMode(){return j(this,Z,!0),!0}start({type:s,data:e}){if(!M(this,Z))return O(this,yt,Zt).call(this,"entity"),null;if(!s||!e)return console.error("Невалидные данные для логирования:",{type:s,data:e}),null;const r=Jt.hash,i={type:s,data:e,userInfo:null,errorList:{},status:"",answer:null,date:new Date().getTime()};return M(this,nt).set(r,i),j(this,lt,!0),r}async stop({key:s,errorList:e,status:r,answer:i}){var c;if(!M(this,lt))return;if(!M(this,Z)){O(this,yt,Zt).call(this,"entity");return}let a=M(this,nt).get(s);if(!a){console.error(`Не найдены данные логирования для ключа: ${s}`);return}e&&(a.errorList=e),r&&(a.status=r),i&&(a.answer=i),await O(this,Bt,le).call(this),a.userInfo=M(this,ct),await O(this,wt,he).call(this),(c=a==null?void 0:a.data)!=null&&c.updateList&&j(this,at,!0),j(this,lt,!1)}async getEntityList(s){var e;try{if((e=M(this,J))!=null&&e.length&&!M(this,at))return M(this,J);let r=new z(BX24.callBatch),{entityList:i}=await r.batch({entityList:{method:"entity.item.get",params:{ENTITY:M(this,Q),SORT:{ID:"DESC"}}}},s);return!i||!Array.isArray(i)?(console.warn("Получен невалидный список записей"),[]):(i=i.map(a=>{try{const{ID:c,DATE_CREATE:l,DETAIL_TEXT:u}=a;return{...JSON.parse(u),id:c,dateCreate:l}}catch(c){return console.error(`Ошибка парсинга записи ${a.ID}:`,c),null}}).filter(a=>a!==null),j(this,at,!1),j(this,J,i),i)}catch(r){return console.error("Ошибка при получении списка записей:",r),[]}}runStorageMaintenance(){return O(this,Ct,ue).call(this)}async downAllEntityJson(){try{if(M(this,J)||await this.getEntityList(),!M(this,J)||M(this,J).length===0)return console.warn("Нет данных для выгрузки"),!1;let s=mt().format("%Y-%m-%d");return Jt.downloadFileJson(M(this,J),`sdklogger-entity-data__${s}`),!0}catch(s){return console.error("Ошибка при выгрузке данных в JSON:",s),!1}}}Q=new WeakMap,Z=new WeakMap,nt=new WeakMap,ct=new WeakMap,gt=new WeakMap,$=new WeakMap,J=new WeakMap,at=new WeakMap,lt=new WeakMap,Bt=new WeakSet,le=async function(){if(!M(this,gt))return M(this,$)?M(this,$):(j(this,$,(async()=>{try{const s=new z(BX24.callBatch),e=BX24.isAdmin(),{curUser:r}=await s.batch({curUser:{method:"user.current"}});j(this,ct,{isAdmin:e,curUser:r})}catch(s){console.error("Ошибка при получении информации о пользователе:",s),j(this,ct,{isAdmin:!1,curUser:null})}finally{j(this,gt,!0),j(this,$,null)}})()),M(this,$))},yt=new WeakSet,Zt=function(s){s=="entity"&&Jt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},wt=new WeakSet,he=async function(){try{let s={},e=new z(BX24.callBatch);for(let[r,i]of M(this,nt).entries())if(i.status){const a=JSON.stringify(i);s[r]={method:"entity.item.add",params:{ENTITY:M(this,Q),NAME:M(this,Q),DETAIL_TEXT:a}}}if(Object.keys(s).length){let r=await e.batch(s),{errors:i}=e;for(let[a,c]of Object.entries({...r,...i}))M(this,nt).delete(a);return!0}return!1}catch(s){return console.error("Ошибка при добавлении записей в хранилище:",s),!1}},Ct=new WeakSet,ue=async function(){try{let s=new z(BX24.callBatch),{serverTime:e}=await s.batch({serverTime:{method:"server.time"}});if(!e){console.error("Не удалось получить время сервера");return}if(M(this,J)||await this.getEntityList(),!M(this,J)||M(this,J).length===0)return;let r=M(this,J).filter(i=>{try{let{dateCreate:a}=i;return a?mt(new Date(a)).between(mt(new Date(e)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});r.length>0&&(console.log(`Найдено ${r.length} записей для очистки (старше ${this.periodClear} месяцев)`),await O(this,Ht,fe).call(this,r))}catch(s){console.error("Ошибка при проверке периода очистки:",s)}},Ht=new WeakSet,fe=async function(s){try{if(!s||s.length===0)return!1;let e=new z(BX24.callBatch),r=s.filter(a=>a&&a.id).map(a=>{let{id:c}=a;return{method:"entity.item.delete",params:{ENTITY:M(this,Q),ID:c}}});if(r.length===0)return!1;const i=await e.batch(r);return console.log(`Успешно удалено ${r.length} записей`),j(this,at,!0),i}catch(e){return console.error("Ошибка при очистке устаревших записей:",e),!1}};function Kt(T){if(!T||typeof T!="string")return"";try{const s=new URL(T);s.search="",s.hash="";let e=s.toString();return e.endsWith("/")&&s.pathname!=="/"&&(e=e.slice(0,-1)),e}catch{return T.split("?")[0].split("#")[0].replace(/\/$/,"")}}function re(T){return!T||typeof T!="string"?!1:T.toLowerCase().includes("/marketplace/app")}function _e(){var s;if(typeof window>"u"||!((s=window.location)!=null&&s.href))return"";const T=Kt(window.location.href);return re(T)?"":T}function vt(T){if(!(T!=null&&T.appConst)||typeof T.appConst!="object")return"";const s=_e();return s?(T.appConst.pathApp=s,s):Kt(T.appConst.pathApp??"")}class Te{constructor(s){L(this,ht);L(this,Ut);L(this,pt);L(this,Gt);L(this,Pt);L(this,Yt);L(this,tt);L(this,Nt);L(this,Wt);L(this,Ot);L(this,xt);P(this,"domain","");P(this,"isAdmin",!1);P(this,"appInfo",null);P(this,"appConst",null);P(this,"userInfo",null);P(this,"placeData",null);P(this,"placeInfo",null);P(this,"logger",!1);P(this,"timeLimit",{limit:!1,date:void 0,pauseMs:void 0});P(this,"batchClient",null);this.appConst=s}subscribeTimeLimit(s){return O(this,ht,Xt).call(this).subscribeTimeLimit(s)}init(){return new Promise((s,e)=>{const i=setTimeout(()=>{clearInterval(a);const c=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(c),e(c)},3e4);let a=setInterval(()=>{window.BX24&&BX24.init(async()=>{clearInterval(a),clearTimeout(i),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info();const c=O(this,Gt,de).call(this);if(console.info(c?"init BX24 (background worker)":"init BX24"),this.appInfo=await O(this,Pt,ge).call(this),this.userInfo=await O(this,Yt,ye).call(this),vt(this),c)await O(this,pt,Vt).call(this,!1,{skipInit:!0});else{await O(this,pt,Vt).call(this,!0);const l=new jt;try{l.noSleep()}catch(u){console.warn("Failed to initialize noSleep:",u)}}s({isBackworker:c})})},100)})}userOption(s,e){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.userOption.set(s,e):BX24.userOption.get(s)}appOption(s,e){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.appOption.set(s,e):BX24.appOption.get(s)}async call({method:s,params:e,updateList:r}){let i;if(r&&(i=this.logger.start({type:"call",data:{method:s,params:e,updateList:r}})),e||(e={}),typeof BX24>"u"||!BX24.callMethod){const l=new Error("BX24 is not initialized");throw console.error(l),l}const c=await O(this,ht,Xt).call(this).call({method:s,params:e});return c.success?(await O(this,tt,ft).call(this,i,{answer:c.answer,status:"success"}),c.data):(console.error(c.error),await O(this,tt,ft).call(this,i,{answer:c.answer,status:"fail",errorList:{0:c.error||"Unknown call error"}}),!1)}async batch(s,e,{errorCall:r,updateList:i,batchOptions:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const c=new Error("BX24 is not initialized");return console.error(c),!1}return O(this,Nt,$t).call(this,{mode:"batch",commandList:s,progressCall:e,errorCall:r,updateList:i,batchOptions:a})}async batchTotalCount(s,e,{errorCall:r,updateList:i}={}){if(typeof BX24>"u"||!BX24.callBatch){const a=new Error("BX24 is not initialized");return console.error(a),!1}return O(this,Nt,$t).call(this,{mode:"batch-total-count",commandList:s,progressCall:e,errorCall:r,updateList:i})}async getPlacement(){const s=await this.call({method:"placement.get"});return this.placeData||(this.placeData=s),s}async placementBind(s){var A;if(!this.isAdmin||(this.placeData=await this.getPlacement(),!this.placeData))return;const{appName:e,pathApp:r}=this.appConst;let i=O(this,Ot,te).call(this,s);i=i.filter(h=>h.placement!=="PAGE_BACKGROUND_WORKER"&&h.placement!=="PAGE_BACKGROUND_WORKER_ALL");const a=O(this,xt,Ne).call(this,r),c=new Set(i.map(h=>h.placement));for(const h of a)c.has(h.placement)||i.push({placement:h.placement});if(i.length===0)return;let l=e;this.domain==="szdl.bitrix24.ru"&&((A=this.appInfo)!=null&&A.ID)&&(l=`${e}: #${this.appInfo.ID}`);const u=l.replace(" CRM",""),n={},f=[],d=new Map;for(const h of this.placeData)d.has(h.placement)||d.set(h.placement,[]),d.get(h.placement).push(h);for(let h=0;h<i.length;h++){const N=i[h].placement,_=d.get(N)||[];if(_.some(y=>y.handler===r))continue;const R=_.filter(y=>y.handler!==r);for(const y of R)f.push({placement:N,handler:y.handler});n[`bind_${h}`]={method:"placement.bind",params:{PLACEMENT:N,HANDLER:r,LANG_ALL:{ru:{TITLE:N==="USER_PROFILE_TOOLBAR"?u:l}},OPTIONS:{errorHandlerUrl:r}}}}f.length>0&&await this.placementUnBind(f),Object.keys(n).length>0&&(await this.batch(n),this.placeData=await this.getPlacement(),Object.values(n).forEach(h=>{console.log("Приложение успешно встроено в",h.params.PLACEMENT)}))}async placementUnBind(s){let e=O(this,Ot,te).call(this,s);if(e=e.filter(i=>i.placement!=="PAGE_BACKGROUND_WORKER"&&i.placement!=="PAGE_BACKGROUND_WORKER_ALL"),e.length===0)return;const r={};for(let i=0;i<e.length;i++){const a={PLACEMENT:e[i].placement};e[i].handler&&(a.HANDLER=e[i].handler),r[`unbind_${i}`]={method:"placement.unbind",params:a}}await this.batch(r),e.forEach(i=>{console.log("Встройка отвязана",i.placement)})}async getBotList(){const s=await this.call({method:"imbot.bot.list",params:{}}),e=Object.values(s);return console.log("chat-bot list:",e),e}async regBot({code:s,type:e,name:r}){const{appName:i,pathApp:a,chatBotLogo:c}=this.appConst,l=this.appInfo.ID,u=await this.call({method:"imbot.register",params:{CODE:s??this.appInfo.CODE,TYPE:e??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${r??i} - бот #${l}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:mt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:c??""}}});return console.log("Чат-бот добавлен",u),u}async unRegBot(s){const e=await this.call({method:"imbot.unregister",params:{BOT_ID:s}});return console.log("чат-бот удален",e),e}getLoggerList(s){return this.logger.getEntityList(s)}}ht=new WeakSet,Xt=function(){return this.batchClient||(this.batchClient=new z({callBatch:BX24.callBatch,callMethod:BX24.callMethod}),this.timeLimit=this.batchClient.timeLimit),this.batchClient},Ut=new WeakSet,me=function(){return{start:()=>{},stop:()=>{},getEntityList:()=>{}}},pt=new WeakSet,Vt=async function(s,{skipInit:e=!1}={}){this.logger?(this.logger=new se,e?this.logger.enableBackworkerMode():await this.logger.init(),s&&typeof this.logger.runStorageMaintenance=="function"&&this.logger.runStorageMaintenance()):this.logger=O(this,Ut,me).call(this)},Gt=new WeakSet,de=function(){var r,i,a;const s=(r=this.placeInfo)==null?void 0:r.placement,e=(a=(i=this.placeInfo)==null?void 0:i.options)==null?void 0:a.ID;return s==="PAGE_BACKGROUND_WORKER"||e==="PAGE_BACKGROUND_WORKER"},Pt=new WeakSet,ge=function(){return this.call({method:"app.info"})},Yt=new WeakSet,ye=function(){return this.call({method:"user.current"})},tt=new WeakSet,ft=async function(s,e){if(s)try{await this.logger.stop({key:s,...e})}catch(r){console.error("Logger error:",r)}},Nt=new WeakSet,$t=async function({mode:s,commandList:e,progressCall:r,errorCall:i,updateList:a,batchOptions:c}){const l=O(this,ht,Xt).call(this),u=a?this.logger.start({type:s,data:s==="batch"?{commandList:e,updateList:a}:{commandList:e}}):void 0;try{const n=s==="batch"?await l.batch(e,r,c):await l.batchTotalCount(e,r),f=O(this,Wt,pe).call(this,l,n,e,a);return Object.keys(f).length?(i&&i(f),await O(this,tt,ft).call(this,u,{status:"fail",errorList:f})):await O(this,tt,ft).call(this,u,{status:"success"}),n}catch(n){return await O(this,tt,ft).call(this,u,{status:"fail-runtime",errorList:{0:n==null?void 0:n.toString()}}),console.error(n),!1}},Wt=new WeakSet,pe=function(s,e,r,i){let a={...s.errors};if(Object.values(s.errors).some(l=>{if(typeof l!="string")return!1;const u=l.toUpperCase();return u==="TIMEOUT"||u==="OPERATION_TIME_LIMIT"||u.includes("TIMEOUT")||u.includes("OPERATION_TIME_LIMIT")})&&i){const l=e?Object.keys(e).filter(d=>d!=="errorsList"):[],u=new Set(Object.keys(s.errors||{})),n=new Set;if(e){for(const d of l)if(!u.has(d)){const A=e[d];A!=null&&n.add(d)}}const f=Object.values(s.errors).find(d=>{if(typeof d!="string")return!1;const A=d.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const d of Object.keys(r))!n.has(d)&&!s.errors[d]&&(a[d]=f||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a},Ot=new WeakSet,te=function(s){if(!s)return[];let e=[];return Array.isArray(s)?e=s.map(r=>typeof r=="string"?{placement:r}:r):typeof s=="string"?e=[{placement:s}]:e=[s],e},xt=new WeakSet,Ne=function(s){return this.placeData?this.placeData.filter(e=>!(e.placement==="PAGE_BACKGROUND_WORKER"||!e.handler||e.handler.includes(s))):[]};const ie="szdl-utils-kit|";function Ee(){if(typeof sessionStorage>"u")return`ephemeral-${Date.now()}-${Math.random().toString(16).slice(2)}`;let T=sessionStorage.getItem("szdl-cross-tab-instance-id");return T||(T=`${Date.now()}-${Math.random().toString(16).slice(2)}`,sessionStorage.setItem("szdl-cross-tab-instance-id",T)),T}function be(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}const zt=new Map;function Re(T="default"){if(typeof BroadcastChannel>"u")return null;const s=`${ie}bc:${T}`;return zt.has(s)||zt.set(s,new BroadcastChannel(s)),zt.get(s)}function ne(T,s){const e=Re(T);if(e)try{const r=s&&typeof s=="object"&&!Array.isArray(s)?s:{data:s};e.postMessage({...r,tabId:Ee(),ts:Date.now()})}catch{}}async function Le(T,s,e={}){const{ifAvailable:r=!1}=e,i=typeof T=="string"&&T.length>0?T:"default",a=`${ie}${i}`;return be()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!r},async c=>{if(r&&c==null)return{skipped:!0,coordination:"locks"};ne(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await s(),coordination:"locks"}}finally{ne(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await s(),coordination:"none"}}class Se{constructor(s){L(this,_t);P(this,"entityName","tabs");P(this,"maxTabs",20);P(this,"tabList",[]);P(this,"id",0);P(this,"hasStarted",!1);P(this,"heartbeat");P(this,"runHeartbeat");P(this,"activeMaxPause",10*1e3);P(this,"quickCleanupThreshold",2*60*1e3);P(this,"pollInterval",6*1e3+Math.floor(Math.random()*2e3));P(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);P(this,"continueCondition");P(this,"defaultContinueBackground",()=>!0);var c,l,u;if(!s){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:e,bx:r,users:i,continueBackground:a}=s;this.bx=r,this.appInit=e,this.users=i,vt(r),this.appPath=O(this,_t,ee).call(this,((c=r==null?void 0:r.appConst)==null?void 0:c.pathApp)??""),this.appName=((l=r==null?void 0:r.appConst)==null?void 0:l.appName)??"",this.appCodeName=((u=r==null?void 0:r.appConst)==null?void 0:u.appCodeName)??"",this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("BackgroundWorker: appInit не передан");return}if(!this.bx){console.error("BackgroundWorker: bx не передан");return}if(this.isAppPage()){console.log("BackgroundWorker: Страница приложения, фоновый воркер не запускается");return}await this.checkPlacementType()&&await this.continueBackground()&&(await this.checkEntity(),await this.refreshTabs(!0),await this.ensureTabRegistered(),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(e=>{console.error("BackgroundWorker: backgroundTick failed",e)})},this.pollInterval),await this.backgroundTick())}async backgroundTick(){if(!await this.continueBackground()){this.stopTimers(),console.log("BackgroundWorker: Остановка backgroundTick - условие не выполнено");return}await this.refreshTabs(!0),await this.ensureTabRegistered();const e=this.selectLeaderId(),r=e&&+this.id==+e;await this.updateTabState(r),r&&!this.hasStarted&&await this.runAsLeader()}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var s;if(typeof BX24>"u"||!((s=BX24.placement)!=null&&s.info))return!1;try{const e=BX24.placement.info(),r=e==null?void 0:e.placement,i=(e==null?void 0:e.options)||{},a=(i==null?void 0:i.URI)||"",c=r==="PAGE_BACKGROUND_WORKER"||(i==null?void 0:i.ID)==="PAGE_BACKGROUND_WORKER",l=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!c||l}catch{return!1}}async checkEntity(){var r;const s=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((r=s==null?void 0:s.find)==null?void 0:r.call(s,i=>i.ENTITY===this.entityName))||await this.safeCall(()=>this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}}))}async getTabs(){const s=await this.safeCall(()=>{var e;return this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:(e=this.bx.userInfo)==null?void 0:e.ID},SORT:{DATE_CREATE:"DESC"}}})});return!Array.isArray(s)||!s.length?[]:s.map(e=>{if(!e)return{id:void 0,data:void 0};try{const r=JSON.parse(e.DETAIL_TEXT);return{id:+e.ID||0,data:r}}catch(r){return console.log("BackgroundWorker: parse tab error",r),{id:+e.ID||0,data:void 0}}})}async ensureTabRegistered(){if(this.id)return+this.id||0;if(this.tabList.length>=this.maxTabs&&await this.refreshTabs(!0,this.quickCleanupThreshold),this.tabList.length>=this.maxTabs)return console.log("BackgroundWorker: Достигнут лимит вкладок даже после быстрой очистки, не регистрируемся"),0;const s={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId},e=await this.safeCall(()=>{var r;return this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(s)}})})||0;return this.id=+e||0,this.id}async updateTabState(s){if(!this.id)return;const e={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:s,sessionId:this.sessionId};await this.safeCall(()=>{var r;return this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(e)}})})}async deleteTabs(s=[]){if(!s.length)return;const e=s.map(r=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:r.id}}));await this.safeCall(()=>this.bx.batch(e))}async checkPlacementType(){var s,e;try{if(!((s=this.bx)!=null&&s.isAdmin))return!0;const r=await this.safeCall(()=>this.bx.getPlacement());if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),a=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),c=!a;if(!i)return!0;let l=!1;for(const u of r){if(u.placement!=="PAGE_BACKGROUND_WORKER"||!(u.userId||u.handler&&u.handler.includes("USER_ID=")))continue;const f=u.userId||(u.handler?this.extractUserIdFromHandler(u.handler):null);if(f&&+f===i){l=!0;break}}return a?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):c&&l?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}isIndividualPlacement(s){return!s||typeof s!="string"?!1:s.includes("USER_ID=")}extractUserIdFromHandler(s){if(!s||typeof s!="string")return null;const e=s.match(/USER_ID=(\d+)/);return e?+e[1]:null}async continueBackground(){try{const e=!!await Promise.resolve(this.continueCondition(this));return console.log(e?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),e}catch(s){return console.error("BackgroundWorker: Ошибка в continueCondition",s),!1}}async refreshTabs(s=!1,e=this.activeMaxPause){const r=[],i=[],a=Date.now(),c=await this.getTabs();for(const l of c){if(!(l!=null&&l.data)){r.push(l);continue}if(a-new Date(l.data.lastActive||0).getTime()>e){r.push(l);continue}i.push(l)}return s&&r.length&&await this.deleteTabs(r),this.tabList=i,i}selectLeaderId(){var e;return this.tabList.length&&+((e=[...this.tabList].sort((r,i)=>{var l,u,n,f;const a=new Date(((l=r.data)==null?void 0:l.createdAt)||((u=r.data)==null?void 0:u.lastActive)||0).getTime(),c=new Date(((n=i.data)==null?void 0:n.createdAt)||((f=i.data)==null?void 0:f.lastActive)||0).getTime();return a===c?(+r.id||0)-(+i.id||0):a-c})[0])==null?void 0:e.id)||0}async runAsLeader(){var i,a;const s=String(((a=(i=this.bx)==null?void 0:i.userInfo)==null?void 0:a.ID)??"0"),e=`background-worker:${this.entityName}:${s}`;(await Le(e,async()=>{this.hasStarted=!0;const c=Math.min(this.activeMaxPause-1500,Math.max(2500,Math.floor(this.pollInterval/2)));this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(l=>console.error("BackgroundWorker: heartbeat update failed",l))},c);try{await this.appInit()}catch(l){console.error("BackgroundWorker: appInit failed",l)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)},{ifAvailable:!0})).skipped&&console.log("BackgroundWorker: runAsLeader пропущен — Web Lock у другой вкладки (тот же фоновый воркер)")}async setBackgroundWorkerAll(){var R,y,S,U;if(!((R=this.bx)!=null&&R.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(y=this.users)!=null&&y.length||await this.getEntityData(),vt(this.bx);const s=O(this,_t,ee).call(this,((U=(S=this.bx)==null?void 0:S.appConst)==null?void 0:U.pathApp)??"");if(!s){console.error("BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена");return}const e=await this.safeCall(()=>this.bx.getPlacement()),r=new Map,i=new Map;let a=null;(e||[]).forEach(p=>{if(p.placement!=="PAGE_BACKGROUND_WORKER")return;if(p.userId||p.handler&&p.handler.includes("USER_ID=")){const E=p.userId||(p.handler?this.extractUserIdFromHandler(p.handler):null);if(E){const w=+E;r.set(w,p),i.has(w)||i.set(w,[]),i.get(w).push(p)}}else a=p});const c=await this.resolveAdmins(),l=await this.getEligibleUsersForBackgroundWorker(c);l.sort((p,I)=>{const E=p.LAST_LOGIN?new Date(p.LAST_LOGIN):new Date(0);return(I.LAST_LOGIN?new Date(I.LAST_LOGIN):new Date(0))-E});const u=10,n=l.slice(0,u),f=n.filter(p=>{const I=r.get(+p.ID);if(!I)return!0;const E=`${s}?USER_ID=${p.ID}/`;return I.handler!==E}),d=[];for(const[p]of r){const I=+p||0;l.find(w=>+w.ID===I)||d.push(I)}for(const p of n){const I=r.get(+p.ID);if(!I)continue;const E=`${s}?USER_ID=${p.ID}/`;I.handler!==E&&d.push(+p.ID)}const A=[],h=[...new Set(d)];for(const p of h){const I=i.get(+p)||[];for(const E of I)E!=null&&E.handler&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:E.handler}})}const N=a&&(f.length>0||a.handler!==`${s}`);N&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:a.handler||`${s}`}});for(const p of f)A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${s}?USER_ID=${p.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${s}?USER_ID=${p.ID}/`},USER_ID:p.ID}});(!a||N)&&A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${s}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${s}`}}});const _=A.filter(p=>p.method==="placement.unbind"),b=A.filter(p=>p.method==="placement.bind");_.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(_.map((p,I)=>[`unbind_${I}`,p])))),b.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(b.map((p,I)=>[`bind_${I}`,p])))),A.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var s,e;try{const r=+(((s=this.bx.userInfo)==null?void 0:s.ID)??0),i=!!((e=this.bx)!=null&&e.isAdmin),a=await this.getAdminsList()||[];if(!i){if(r&&a.includes(+r)){const u=a.filter(n=>+n!=+r);return await this.saveAdminsList(u),u}return a}const c=new Set([...a||[]]);r&&c.add(+r);const l=[...c].filter(Boolean);return await this.saveAdminsList(l),l}catch(r){return console.error("BackgroundWorker: resolveAdmins error",r),[]}}async getEligibleUsersForBackgroundWorker(s=[]){const e=(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0),r=s.map(i=>+i||0).filter(Boolean);return e.filter(i=>r.includes(+i.ID||0))}async saveAdminsList(s=[]){try{BX24.appOption.set("adminsList",JSON.stringify(s))}catch(e){console.error("BackgroundWorker: saveAdminsList error",e)}}async getAdminsList(){try{const s=BX24.appOption.get("adminsList"),e=s?JSON.parse(s):[];return Array.isArray(e)?e.map(r=>+r||0).filter(Boolean):[]}catch(s){return console.error("BackgroundWorker: getAdminsList error",s),[]}}async getEntityData(){const s={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:e}=await this.safeCall(()=>this.bx.batch(s).then(r=>r?(Array.isArray(r.users)||(r.users=[]),r):{users:[]}));this.users=e}async ensureAdminPlacements(){var s,e;(s=this.bx)!=null&&s.isAdmin&&((e=this.users)!=null&&e.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(s=500,e){return new Promise(r=>{setTimeout(()=>{e&&e(),r(!0)},s)})}async safeCall(s){try{return await s()}catch(e){console.error("BackgroundWorker: safeCall error",e);return}}}_t=new WeakSet,ee=function(s){if(!s||typeof s!="string")return"";const e=Kt(s).replace(/\/+$/,"");return e?re(e)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):e:""},B.BackgroundWorker=Se,B.Batch=z,B.BxBoot=Te,B.BxHelper=jt,B.BxLogger=se,B.tempus=mt,Object.defineProperty(B,Symbol.toStringTag,{value:"Module"})});
1
+ var Ie=Object.defineProperty;var Me=(B,C,Y)=>C in B?Ie(B,C,{enumerable:!0,configurable:!0,writable:!0,value:Y}):B[C]=Y;var P=(B,C,Y)=>(Me(B,typeof C!="symbol"?C+"":C,Y),Y),qt=(B,C,Y)=>{if(!C.has(B))throw TypeError("Cannot "+Y)};var M=(B,C,Y)=>(qt(B,C,"read from private field"),Y?Y.call(B):C.get(B)),L=(B,C,Y)=>{if(C.has(B))throw TypeError("Cannot add the same private member more than once");C instanceof WeakSet?C.add(B):C.set(B,Y)},j=(B,C,Y,ot)=>(qt(B,C,"write to private field"),ot?ot.call(B,Y):C.set(B,Y),Y);var O=(B,C,Y)=>(qt(B,C,"access private method"),Y);(function(B,C){typeof exports=="object"&&typeof module<"u"?C(exports):typeof define=="function"&&define.amd?define(["exports"],C):(B=typeof globalThis<"u"?globalThis:B||self,C(B["szdl-utils-kit"]={}))})(this,function(B){var bt,ae,Rt,Lt,St,It,At,Ft,Mt,oe,Dt,Ae,V,ut,st,Tt,rt,Et,kt,ce,dt,Qt,it,Q,Z,nt,ct,gt,$,J,at,lt,Bt,le,yt,Zt,wt,he,Ct,ue,Ht,fe,ht,Xt,Ut,me,pt,Vt,Gt,de,Pt,ge,Yt,ye,tt,ft,Nt,$t,Wt,pe,Ot,te,xt,Ne,_t,ee;"use strict";var C=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Y(E){return E&&E.__esModule&&Object.prototype.hasOwnProperty.call(E,"default")?E.default:E}var ot={exports:{}};(function(E,s){(function(e){Array.prototype.indexOf||(Array.prototype.indexOf=function(t,o){var m,g;for(m=o||0,g=this.length;m<g;m+=1)if(this[m]===t)return m;return-1});var r=this,i=function(t,o){for(var m=t.toString();m.length<o;)m="0"+m;return m},a=function(t,o){return o!==e?(t.year(o.year()||o.year),t.month(o.month()||o.month),t.day(o.day()||o.day),t.hours(o.hours()||o.hours),t.minutes(o.minutes()||o.minutes),t.seconds(o.seconds()||o.seconds),t.milliseconds(o.milliseconds()||o.milliseconds),t):e},c=function(t,o){var m,g="";return m=t.slice(o,o+1),m!==""&&!isNaN(Number(m))&&(g+="%H"),m=t.charAt(o+2),m!==""&&m===":"&&(g+=m),m=t.slice(o+3,o+4),m!==""&&!isNaN(Number(m))&&(g+="%M"),m=t.charAt(o+5),m!==""&&m===":"&&(g+=m),m=t.slice(o+6,o+7),m!==""&&!isNaN(Number(m))&&(g+="%S"),g},l=function(t,o){var m,g=[t.slice(o,o+1),t.charAt(o+2),t.slice(o+3,o+4),t.charAt(o+5),t.slice(o+6,o+9)],H;return!isNaN(Number(g[0]))&&!isNaN(Number(g[2]))&&!isNaN(Number(g[4]))?(g[1]==="."&&g[3]==="."?m="%d.%m.%Y":g[1]==="-"&&g[3]==="-"?m="%m-%d-%Y":g[1]==="/"&&g[3]==="/"&&(m="%m/%d/%Y"),m):(H=[t.slice(o,o+3),t.charAt(o+4),t.slice(o+5,o+6),t.charAt(o+7),t.slice(o+8,o+9)],!isNaN(Number(H[0]))&&!isNaN(Number(H[2]))&&!isNaN(Number(H[4]))?(H[1]==="-"&&H[3]==="-"&&(m="%Y-%m-%d"),m):"")},u=r.tempus,n,f,d=r.navigator||{},A="en",h={en:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"Mar",APRIL_SHORT:"Apr",MAY_SHORT:"May",JUNE_SHORT:"Jun",JULY_SHORT:"Jul",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sep",OCTOBER_SHORT:"Oct",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dec",JANUARY_LONG:"January",FEBRUARY_LONG:"February",MARCH_LONG:"March",APRIL_LONG:"April",MAY_LONG:"May",JUNE_LONG:"June",JULY_LONG:"July",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"October",NOVEMBER_LONG:"November",DECEMBER_LONG:"December",SUNDAY_SHORT:"Sun",MONDAY_SHORT:"Mon",TUESDAY_SHORT:"Tue",WEDNESDAY_SHORT:"Wed",THURSDAY_SHORT:"Thu",FRIDAY_SHORT:"Fri",SATURDAY_SHORT:"Sat",SUNDAY_LONG:"Sunday",MONDAY_LONG:"Monday",TUESDAY_LONG:"Tuesday",WEDNESDAY_LONG:"Wednesday",THURSDAY_LONG:"Thursday",FRIDAY_LONG:"Friday",SATURDAY_LONG:"Saturday"},ru:{JANUARY_SHORT:"Янв",FEBRUARY_SHORT:"Фев",MARCH_SHORT:"Мар",APRIL_SHORT:"Апр",MAY_SHORT:"Май",JUNE_SHORT:"Июн",JULY_SHORT:"Июл",AUGUST_SHORT:"Авг",SEPTEMBER_SHORT:"Сен",OCTOBER_SHORT:"Окт",NOVEMBER_SHORT:"Ноя",DECEMBER_SHORT:"Дек",JANUARY_LONG:"Январь",FEBRUARY_LONG:"Февраль",MARCH_LONG:"Март",APRIL_LONG:"Апрель",MAY_LONG:"Май",JUNE_LONG:"Июнь",JULY_LONG:"Июль",AUGUST_LONG:"Август",SEPTEMBER_LONG:"Сентябрь",OCTOBER_LONG:"Октябрь",NOVEMBER_LONG:"Ноябрь",DECEMBER_LONG:"Декабрь",SUNDAY_SHORT:"Вс",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Воскресенье",MONDAY_LONG:"Понедельник",TUESDAY_LONG:"Вторник",WEDNESDAY_LONG:"Среда",THURSDAY_LONG:"Четверг",FRIDAY_LONG:"Пятница",SATURDAY_LONG:"Суббота"},ua:{JANUARY_SHORT:"Січ",FEBRUARY_SHORT:"Лют",MARCH_SHORT:"Берез",APRIL_SHORT:"Квіт",MAY_SHORT:"Трав",JUNE_SHORT:"Черв",JULY_SHORT:"Лип",AUGUST_SHORT:"Серп",SEPTEMBER_SHORT:"Верес",OCTOBER_SHORT:"Жовт",NOVEMBER_SHORT:"Листоп",DECEMBER_SHORT:"Груд",JANUARY_LONG:"Січень",FEBRUARY_LONG:"Лютий",MARCH_LONG:"Березень",APRIL_LONG:"Квітень",MAY_LONG:"Травень",JUNE_LONG:"Червень",JULY_LONG:"Липень",AUGUST_LONG:"Серпень",SEPTEMBER_LONG:"Вересень",OCTOBER_LONG:"Жовтень",NOVEMBER_LONG:"Листопад",DECEMBER_LONG:"Грудень",SUNDAY_SHORT:"Нд",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Неділя",MONDAY_LONG:"Понеділок",TUESDAY_LONG:"Вівторок",WEDNESDAY_LONG:"Середа",THURSDAY_LONG:"Четвер",FRIDAY_LONG:"П’ятниця",SATURDAY_LONG:"Субота"},de:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"März",APRIL_SHORT:"Apr",MAY_SHORT:"Mai",JUNE_SHORT:"Juni",JULY_SHORT:"Juli",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sept",OCTOBER_SHORT:"Okt",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dez",JANUARY_LONG:"Januar",FEBRUARY_LONG:"Februar",MARCH_LONG:"März",APRIL_LONG:"April",MAY_LONG:"Mai",JUNE_LONG:"Juni",JULY_LONG:"Juli",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"Oktober",NOVEMBER_LONG:"November",DECEMBER_LONG:"Dezember",SUNDAY_SHORT:"So",MONDAY_SHORT:"Mo",TUESDAY_SHORT:"Di",WEDNESDAY_SHORT:"Mi",THURSDAY_SHORT:"Do",FRIDAY_SHORT:"Fr",SATURDAY_SHORT:"Sa",SUNDAY_LONG:"Sonntag",MONDAY_LONG:"Montag",TUESDAY_LONG:"Dienstag",WEDNESDAY_LONG:"Mittwoch",THURSDAY_LONG:"Donnerstag",FRIDAY_LONG:"Freitag",SATURDAY_LONG:"Samstag"}},N=function(){return[h[A].JANUARY_LONG,h[A].FEBRUARY_LONG,h[A].MARCH_LONG,h[A].APRIL_LONG,h[A].MAY_LONG,h[A].JUNE_LONG,h[A].JULY_LONG,h[A].AUGUST_LONG,h[A].SEPTEMBER_LONG,h[A].OCTOBER_LONG,h[A].NOVEMBER_LONG,h[A].DECEMBER_LONG]},_=function(){return[h[A].JANUARY_SHORT,h[A].FEBRUARY_SHORT,h[A].MARCH_SHORT,h[A].APRIL_SHORT,h[A].MAY_SHORT,h[A].JUNE_SHORT,h[A].JULY_SHORT,h[A].AUGUST_SHORT,h[A].SEPTEMBER_SHORT,h[A].OCTOBER_SHORT,h[A].NOVEMBER_SHORT,h[A].DECEMBER_SHORT]},b=function(){return[h[A].SUNDAY_LONG,h[A].MONDAY_LONG,h[A].TUESDAY_LONG,h[A].WEDNESDAY_LONG,h[A].THURSDAY_LONG,h[A].FRIDAY_LONG,h[A].SATURDAY_LONG]},S=function(){return[h[A].SUNDAY_SHORT,h[A].MONDAY_SHORT,h[A].TUESDAY_SHORT,h[A].WEDNESDAY_SHORT,h[A].THURSDAY_SHORT,h[A].FRIDAY_SHORT,h[A].SATURDAY_SHORT]},y,T,U,p,I=function(t,o,m){var g;r.XMLHttpRequest?g=new XMLHttpRequest:g=new ActiveXObject("Microsoft.XMLHTTP"),g.onreadystatechange=function(){g.readyState===4&&(g.status===200?o&&(r.JSON===e?alert(`Please, include json2 into your project if you want use old browsers!
2
+ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(g.responseText))):m&&m(g))},g.open("GET",t,!1),g.send()},R={"%d":{format:function(t){return i(t.day()||n.MIN_DAY,2)},parse:function(t){var o=Number(t);return{day:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(t){return i(t.month()||n.MIN_MONTH,2)},parse:function(t){var o=Number(t);return{month:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(t){return i(t.year()||n.MIN_YEAR,4)},parse:function(t){var o=Number(t);return{year:isNaN(o)?e:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(t){return t.dayOfWeek()||n.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(t){var o=t.dayOfWeek();return p[o!==e?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var o=t.dayOfWeek();return U[o!==e?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(t){var o=n.options("monthFromZero")?t.month():t.month()-1;return T[o!==e?o:n.MIN_MONTH]},parse:function(t){var o=n.monthNames().indexOf(t)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var o=n.options("monthFromZero")?t.month():t.month()-1;return y[o!==e?o:n.MIN_MONTH]},parse:function(t){var o=n.monthNames(!0).indexOf(t)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(t){return i(t.hours()||n.MIN_HOURS,2)},parse:function(t){var o=Number(t);return{hours:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(t){return i(t.minutes()||n.MIN_MINUTES,2)},parse:function(t){var o=Number(t);return{minutes:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(t){return i(t.seconds()||n.MIN_SECONDS,2)},parse:function(t){var o=Number(t);return{seconds:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(t){return t.timestamp()},parse:function(t){return isNaN(Number(t))?{}:n(Number(t)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(t){return i(t.year()||n.MIN_YEAR,4)+"-"+i(t.month()||n.MIN_MONTH,2)+"-"+i(t.day()||n.MIN_DAY,2)},parse:function(t){var o=Number(t.slice(0,4)),m=Number(t.slice(5,7)),g=Number(t.slice(8,10));return{year:o,month:m,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return i(t.month()||n.MIN_MONTH,2)+"/"+i(t.day()||n.MIN_DAY,2)+"/"+i(t.year()||n.MIN_YEAR,4)},parse:function(t){var o=Number(t.slice(0,2)),m=Number(t.slice(3,5)),g=Number(t.slice(6,10));return{year:g,month:o,day:m}},minLength:10,maxLength:10,type:"string"}},w={useMilliseconds:!1,monthFromZero:!1},k;k=function(t,o,m){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t!==e&&this.set(t,o,m),this},k.fn=k.prototype,k.fn.dayCount=function(){var t=this.month(),o=n.MAX_DAY_IN_MONTHS[t-(n.options("monthFromZero")?0:1)];return this.leapYear()&&t===(n.options("monthFromZero")?1:2)&&(o+=1),o},k.fn.year=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_YEAR&&Number(t)<=n.MAX_YEAR?(this._d.setFullYear(Number(t)),this._i.year=!1):this._i.year=Number(t):(this._d.setFullYear(n.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},k.fn.month=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MONTH&&Number(t)<=n.MAX_MONTH?(this._d.setMonth(n.options("monthFromZero")?Number(t):Number(t)-1),this._i.month=!1):this._i.month=Number(t):(this._d.setMonth(n.options("monthFromZero")?n.MIN_MONTH:n.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?n.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},k.fn.day=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_DAY&&Number(t)<=this.dayCount()?(this._d.setDate(Number(t)),this._i.day=!1):this._i.day=Number(t):(this._d.setDate(n.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},k.fn.hours=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_HOURS&&Number(t)<=n.MAX_HOURS?(this._d.setHours(Number(t)),this._i.hours=!1):this._i.hours=Number(t):(this._d.setHours(n.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},k.fn.minutes=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MINUTES&&Number(t)<=n.MAX_MINUTES?(this._d.setMinutes(Number(t)),this._i.minutes=!1):this._i.minutes=Number(t):(this._d.setMinutes(n.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},k.fn.seconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_SECONDS&&Number(t)<=n.MAX_SECONDS?(this._d.setSeconds(Number(t)),this._i.seconds=!1):this._i.seconds=Number(t):(this._d.setSeconds(n.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},k.fn.milliseconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MILLISECONDS&&Number(t)<=n.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(t)),this._i.milliseconds=!1):this._i.milliseconds=Number(t):(this._d.setMilliseconds(n.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},k.fn.week=function(){var t=new Date(this.year(),0,1),o=n(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-t.getTime())/864e5+t.getDay()+1)/7)},k.fn.set=function(t,o,m){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t===e)return this._d=new Date,this;if(t instanceof Date)return this._d=t,this;if(typeof t=="number")return this._d=new Date(t*(n.options("useMilliseconds")?1:1e3)),this;if(typeof t=="object"&&(t instanceof Array?(this.day(n.MIN_DAY),this.year(t[0]),this.month(t[1]),this.day(t[2]),this.hours(t[3]),this.minutes(t[4]),this.seconds(t[5]),this.milliseconds(t[6])):(this.day(n.MIN_DAY),this.year(t.year),this.month(t.month),this.day(t.day),this.hours(t.hours),this.minutes(t.minutes),this.seconds(t.seconds),this.milliseconds(t.milliseconds))),typeof t=="string"){var g,H=[],D,G,et=[],X=0,K=0,W,v,x={},F;if(t===e)return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;for(o===e&&(o=n.detectFormat(t));X<o.length;){if(o.charAt(X)==="%"){if(G=o.charAt(X)+o.charAt(X+1),R[G]!==e){switch(W=0,v="",R[G].type){case"number":for(;W<R[G].maxLength&&K+W<t.length&&!isNaN(Number(t.charAt(K+W)));)v+=t.charAt(K+W),W+=1;break;case"word":for(;W<R[G].maxLength&&K+W<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(K+W));)v+=t.charAt(K+W),W+=1;break;case"string":for(;W<R[G].maxLength&&K+W<t.length;)v+=t.charAt(K+W),W+=1;break}if(W<R[G].minLength)return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;H.push(G),et.push(v),W-=1,K+=W,X+=1}}else if(t.charAt(K)!==o.charAt(X))return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;X+=1,K+=1}for(g in H)H.hasOwnProperty(g)&&R.hasOwnProperty(H[g])&&(F=R[H[g]].parse(et[g]),x={year:F.year!==e?F.year:x.year,month:F.month!==e?F.month:x.month,day:F.day!==e?F.day:x.day,hours:F.hours!==e?F.hours:x.hours,minutes:F.minutes!==e?F.minutes:x.minutes,seconds:F.seconds!==e?F.seconds:x.seconds});this.day(n.MIN_DAY),this.year(x.year),this.month(x.month),this.day(x.day),this.hours(x.hours),this.minutes(x.minutes),this.seconds(x.seconds),this.milliseconds(x.milliseconds)}return this},k.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},k.fn.timestamp=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(n.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):n.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},k.fn.utc=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(n.options("useMilliseconds")?1:1e3)),this):n.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},k.fn.dayOfWeek=function(t){if(t==="long")return U[this._d.getDay()];if(t==="short")return p[this._d.getDay()];if(t===e)return this._d.getDay();if(t===0||t==="Sunday")return this.calc({day:-this.dayOfWeek()});if(t===1||t==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(t===2||t==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(t===3||t==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(t===4||t==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(t===5||t==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(t===6||t==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},k.fn.timezone=function(t){switch(t){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},k.fn.get=function(t){switch(t){case"Date":return new Date(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds());case"DateUTC":return new Date(Date.UTC(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()));case"Array":return[this.year(),this.month(),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()];default:return{year:this.year(),month:this.month(),week:this.week(),day:this.day(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds(),utc:this.utc(),dayOfWeek:this.dayOfWeek(),dayOfWeekShort:this.dayOfWeek("short"),dayOfWeekLong:this.dayOfWeek("long"),timestamp:this.timestamp()}}},k.fn.format=function(t){for(var o=0,m="",g;o<t.length;)t.charAt(o)==="%"?(g=t.charAt(o)+t.charAt(o+1),R[g]!==e?(m+=R[g].format(this),o+=1):m+="%"):m+=t.charAt(o),o+=1;return m},k.fn.valid=function(){return this._i.year===!1&&this._i.month===!1&&this._i.day===!1&&this._i.hours===!1&&this._i.minutes===!1&&this._i.seconds===!1&&this._i.milliseconds===!1},k.fn.errors=function(){return this._i},k.fn.between=function(t,o){var m=this.timestamp(),g=t.timestamp();switch(o){case"year":return Math.floor((g-m)/31556952);case"month":return Math.floor((g-m)/2629746);case"day":return Math.floor((g-m)/86400);case"hours":return Math.floor((g-m)/3600);case"minutes":return Math.floor((g-m)/60);case"seconds":return g-m;default:return e}},k.fn.calc=function(t){return t.year!==e&&this._d.setFullYear(this._d.getFullYear()+t.year),t.month!==e&&this._d.setMonth(this._d.getMonth()+t.month),t.day!==e&&this._d.setDate(this._d.getDate()+t.day),t.hours!==e&&this._d.setHours(this._d.getHours()+t.hours),t.minutes!==e&&this._d.setMinutes(this._d.getMinutes()+t.minutes),t.seconds!==e&&this._d.setSeconds(this._d.getSeconds()+t.seconds),t.milliseconds!==e&&this._d.setMilliseconds(this._d.getMilliseconds()+t.milliseconds),this},n=function(t,o,m){return new k(t,o,m)},n.MIN_YEAR=1e3,n.MAX_YEAR=3e3,n.MIN_MONTH=1,n.MAX_MONTH=12,n.MIN_DAY=1,n.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],n.MIN_DAY_OF_WEEK=0,n.MAX_DAY_OF_WEEK=6,n.MIN_HOURS=0,n.MAX_HOURS=23,n.MIN_MINUTES=0,n.MAX_MINUTES=59,n.MIN_SECONDS=0,n.MAX_SECONDS=59,n.MIN_MILLISECONDS=0,n.MAX_MILLISECONDS=999,n.VERSION="0.2.18",n.options=function(t,o){if(t===e)return w;if(w.hasOwnProperty(t)){if(o===e)return w[t];w[t]=o,t==="monthFromZero"&&(n.MIN_MONTH=o?0:1,n.MAX_MONTH=o?11:12)}return e},n.noConflict=function(){return r.tempus=u,n},n.generate=function(t){var o,m,g,H,D,G,et,X;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof k?o=t.dateFrom.utc():o=n(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof k?m=t.dateTo.utc():m=n(t.dateTo,t.formatTo!==e?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?D={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?D={year:t.period==="year"?1:0,month:t.period==="month"?1:0,day:t.period==="day"?1:0,hours:t.period==="hours"?1:0,minutes:t.period==="minutes"?1:0,seconds:t.period==="seconds"?1:0}:typeof t.period=="object"&&(D={year:t.period.year!==e?t.period.year:0,month:t.period.month!==e?t.period.month:0,day:t.period.day!==e?t.period.day:0,hours:t.period.hours!==e?t.period.hours:0,minutes:t.period.minutes!==e?t.period.minutes:0,seconds:t.period.seconds!==e?t.period.seconds:0}),t.groupBy===e?G=t.asObject===!0?{}:[]:(G=[],G.push([]),et=n(o).get()[t.groupBy]),X=function(v,x,F){return t.asObject===!0?t.format!==e?v[n(x).format(t.format)]={}:v[n(x).format("%F %H:%M:%S")]={}:t.format!==e?v.push(F?null:n(x).format(t.format)):v.push(F?null:n(x)),v},t.groupBy!==e&&t.fillNulls){var K={year:D.year?-D.year:e,month:D.month?-D.month:e,day:D.day?-D.day:e,hours:D.hours?-D.hours:e,minutes:D.minutes?-D.minutes:e,seconds:D.seconds?-D.seconds:e,milliseconds:D.milliseconds?-D.milliseconds:e};for(g=n(o).calc(K).utc();n(g).get()[t.groupBy]===et;)X(G[G.length-1],g,!0),g=n(g).calc(K).utc();if(t.groupBy==="week"){var W=n(o).dayOfWeek();for(g=n(o).dayOfWeek(0).utc();G[0].length<W&&g<o;)X(G[G.length-1],g,!0),g=n(g).calc(D).utc()}}for(;o<=m;)t.groupBy===e?X(G,o):n(o).get()[t.groupBy]===et?X(G[G.length-1],o):(G.push([]),X(G[G.length-1],o),et=n(o).get()[t.groupBy]),o=n(o).calc(D).utc();if(t.groupBy!==e&&t.fillNulls)for(H=n(m).calc(D).utc();n(H).get()[t.groupBy]===et;)X(G[G.length-1],H,!0),H=n(H).calc(D).utc();return G},n.monthNames=function(t){switch(t){case"long":return y;default:return T}},n.dayNames=function(t){switch(t){case"long":return U;default:return p}},n.lang=function(t){if(t!==e)A=t,h[A]===e&&(A="en"),y=N(),T=_(),U=b(),p=S();else return A;return e},n.availableLangs=function(){return Object.keys(h)},n.registerFormat=function(t,o,m,g,H,D){R[t]={format:o,parse:m,minLength:g,maxLength:H,type:D}},n.unregisterFormat=function(t){delete R[t]},n.detectFormat=function(t){var o,m,g;return o=l(t,0),o!==""&&(g=10),m=t.charAt(g),(m==="T"||m===" ")&&(o+=m,g+=1),o+=c(t,g),o},f={TempusDate:k},n.classes=function(t,o){if(o===e)return f[t];f[t]=o},n.loadTranslations=function(t){typeof t=="object"?h=t:typeof t=="string"&&I(t,function(o){h=o},function(o){})},A=(d.language||d.systemLanguage||d.userLanguage||"en").substr(0,2).toLowerCase(),h[A]===e&&(A="en"),y=N(),T=_(),U=b(),p=S(),E.exports&&(s=E.exports=n),s.tempus=n}).call(C)})(ot,ot.exports);var Oe=ot.exports;const mt=Y(Oe),q=class q{constructor(s){L(this,bt);L(this,At);L(this,Mt);L(this,Dt);L(this,V);L(this,st);L(this,rt);L(this,kt);L(this,dt);typeof s=="function"?(this.callBatch=s,this.callMethod=null):(this.callBatch=(s==null?void 0:s.callBatch)||null,this.callMethod=(s==null?void 0:s.callMethod)||null),this.result={},this.errors={},this.timeLimit={limit:!1,date:void 0,pauseMs:void 0},this.timeLimitListeners=new Set,this.canContinue=!0,this.progressCall="",this.progressData="",this.progressTimer="",this.lastProgressSnapshot=null,this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.filterChunkSize=50,this.limit=50,this.progressDelay=100,this.operatingThreshold=475,this.defaultPauseMs=12e4,this.callLimitPauseMs=3e4,this.requestTimeoutMs=6e4}get progressPercent(){if(!this.progressData)return{percent:0,allCount:0,allTotal:0};const s=this.totalBatchCommands||0;if(s>0&&Array.isArray(this.batchCommandKeyOrder)&&this.batchCommandKeyOrder.length&&O(this,bt,ae).call(this)){let l=0;for(const A of this.batchCommandKeyOrder){const h=this.progressData[A];if(!h)continue;const N=Number(h.total)||0,_=Number(h.count)||0;N===0&&_===0?l+=1:N>0&&(l+=Math.min(1,_/N))}const u=l/s*100;let n=Math.max(0,Math.min(100,Math.floor(u)));const f=s,d=Math.min(s,Math.floor(l));return{percent:n,allCount:d,allTotal:f}}let e=0,r=0;for(const l of Object.values(this.progressData)){const{total:u,count:n}=l;e+=u??0,r+=n??0}const i=Number(this.chunkRate)||0;let a=0;e?a=r/e*100*i+this.totalProgress:r===0&&e===0?a=100*i+this.totalProgress:a=100,a=Math.max(0,Math.min(a,100));let c=Math.floor(a);return e>0&&r>=e&&(c=100),{percent:c,allCount:r,allTotal:e}}setProgressData({key:s,value:e,type:r}){var h,N;if(!this.progressCall)return;const i=this.getData(e.data()),a=Array.isArray(i)?i.length:0;let c=a;if(typeof e.total=="function"){const _=e.total();if(_!=null&&_!==""){const b=Number(_);Number.isFinite(b)&&(c=b)}}r==="count"&&(c=a);let l=1;i&&(l=a),this.progressData||(this.progressData={});const u=((h=this.progressData[s])==null?void 0:h.total)??0,n=((N=this.progressData[s])==null?void 0:N.count)??0,f=l+n,d=Math.max(u,c??0,f);if(this.progressData[s]={total:d,count:Math.min(f,d)},typeof document<"u"&&(document==null?void 0:document.hidden)===!0){O(this,At,Ft).call(this);return}O(this,At,Ft).call(this),this.progressTimer||(this.progressTimer=setInterval(()=>{if(!this.progressCall){this.clearProgressData();return}O(this,At,Ft).call(this);const{percent:_}=this.progressPercent;_>=100&&(clearInterval(this.progressTimer),this.progressTimer="")},this.progressDelay))}getData(s){if(s==null)return s;let e=(s==null?void 0:s.items)??(s==null?void 0:s.tasks)??(s==null?void 0:s.types)??(s==null?void 0:s.type)??(s==null?void 0:s.fields)??(s==null?void 0:s.workgroups)??s;return e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.result)&&(e=e.result),e}setTimeLimitState(s,e,r){this.timeLimit.limit=!!s,this.timeLimit.date=s?e:void 0,s&&typeof r=="number"&&r>0?this.timeLimit.pauseMs=r:this.timeLimit.pauseMs=void 0,O(this,Dt,Ae).call(this)}subscribeTimeLimit(s){return typeof s!="function"?()=>{}:(this.timeLimitListeners.add(s),s({limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs}),()=>{this.timeLimitListeners.delete(s)})}splitLargeFilters(s,e){const{method:r,params:i}=e;if(!i)return[{key:s,request:e}];const a=i.filter||i.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:s,request:e}];for(const[c,l]of Object.entries(a))if(!String(c).trim().startsWith("!")&&Array.isArray(l)&&l.length>this.filterChunkSize){const u=[];for(let n=0;n<l.length;n+=this.filterChunkSize){const f=l.slice(n,n+this.filterChunkSize),d=n===0?s:`${s}__chunk_${Math.floor(n/this.filterChunkSize)}`,A={...i};i.filter?(A.filter={...a},A.filter[c]=f):i.FILTER&&(A.FILTER={...a},A.FILTER[c]=f),u.push({key:d,request:{method:r,params:A},originalKey:s,filterKey:c,chunkIndex:Math.floor(n/this.filterChunkSize)})}return u}return[{key:s,request:e}]}mergeSplitResults(s,e){const r=[],i=String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${i}(?:__chunk_\\d+)?$`),c=Object.keys(s).filter(l=>a.test(l)).sort((l,u)=>{const n=l.match(/__chunk_(\d+)$/),f=u.match(/__chunk_(\d+)$/);return n?f?parseInt(n[1])-parseInt(f[1]):1:-1});for(const l of c){const u=s[l];Array.isArray(u)?r.push(...u):u&&r.push(u)}return r}delay(){return typeof document<"u"&&(document==null?void 0:document.hidden)===!0?Promise.resolve():new Promise(e=>setTimeout(e,500))}callBatchWithTimeout(s,e){return new Promise((r,i)=>{let a=!1,c=null;const l=async n=>{if(!a){a=!0,c&&clearTimeout(c);try{await Promise.resolve(e(n)),r()}catch(f){console.error("Error in callBatch callback:",f),i(f)}}},u=async()=>{if(!a){a=!0,c&&clearTimeout(c),console.warn(`Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`);const n={};Object.keys(s).forEach(f=>{n[f]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 60 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(e(n)),r()}catch(f){console.error("Error in timeout callback:",f),r()}}};try{this.callBatch(s,async n=>{await l(n)})}catch(n){a||console.error("Error calling callBatch:",n)}c=setTimeout(async()=>{a||(console.warn(`Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`),await u())},this.requestTimeoutMs)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.lastProgressSnapshot=null}async batch(s,e,r={}){O(this,dt,Qt).call(this,e);const i={},a={},c={};for(const[f,d]of Object.entries(s)){const A=this.arrayChunk(d);if(!A)continue;const h=this.splitLargeFilters(f,A);if(h.length===1)a[f]=A;else{c[f]=[];for(const N of h)a[N.key]=N.request,c[f].push(N.key)}}this.batchCommandKeyOrder=Object.keys(a),this.totalBatchCommands=this.batchCommandKeyOrder.length,this.batchCommandMethods=this.batchCommandKeyOrder.map(f=>{var d;return String(((d=a[f])==null?void 0:d.method)||"")}),this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let l={},u=0;const n=Object.keys(a).length;for(const[f,d]of Object.entries(a)){if(!this.canContinue)break;if(l[f]=d,Object.keys(l).length>=this.limit||u+1===n){const A=u+1===n;await this.batchChunk(l,void 0,!A,{disablePagination:!1,oneBatch:!!(r!=null&&r.oneBatch)}),Object.entries(this.result).forEach(([h,N])=>{i[h]=N}),this.totalProgress=Math.round(u/n*100),l={}}u++}for(const[f,d]of Object.entries(c))if(d&&d.length>0){const A=this.mergeSplitResults(i,f);for(const h of d)delete i[h];i[f]=A}return Object.entries(this.errors).length&&(i.errorsList=this.errors),e&&e({percent:100}),Promise.resolve(i)}async batchTotalCount(s,e){O(this,dt,Qt).call(this,e);const r={},i={},a={};for(const[u,n]of Object.entries(s)){const f=this.arrayChunk(n);if(!f)continue;const d=this.splitLargeFilters(u,f);if(d.length===1)i[u]=f;else{a[u]=[];for(const A of d)i[A.key]=A.request,a[u].push(A.key)}}const c=[],l=Object.entries(i);for(let u=0;u<l.length;u+=this.limit){const n=l.slice(u,u+this.limit),f={};for(const[d,A]of n){if(!this.canContinue)break;f[d]=A}Object.keys(f).length>0&&c.push(f)}this.chunkRate=(1/c.length).toFixed(5);for(const[u,n]of Object.entries(c)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(u)/c.length*100);const f=Number(u)===c.length-1;await O(this,rt,Et).call(this,n,async d=>{var A,h,N,_,b;for(const[S,y]of Object.entries(d)){if(!this.canContinue)return;if(y.error()){const R=(h=(A=y.error())==null?void 0:A.ex)==null?void 0:h.error,w=(_=(N=y.error())==null?void 0:N.ex)==null?void 0:_.error_description;this.errors[S]=R&&R.trim()||w&&w.trim()||((b=y.error())==null?void 0:b.toString())||"Неизвестная ошибка",r[S]=0;continue}const T=this.getData(y.data()),U=Array.isArray(T)?T.length:0,I=typeof y.total=="function"&&y.total()!==void 0?y.total():U;r[S]=I,this.setProgressData({key:S,value:y,type:"count"})}await O(this,st,Tt).call(this,d,!f)})}for(const[u,n]of Object.entries(a))if(n&&n.length>0){let f=0;for(const d of n)r[d]!==void 0&&(f+=r[d]||0),delete r[d];r[u]=f}return Object.entries(this.errors).length&&(r.errorsList=this.errors,this.errorLogger()),e&&e({percent:100}),Promise.resolve(r)}async call({method:s,params:e={}}){var r,i,a,c,l,u,n;for(;;){const f=await O(this,kt,ce).call(this,s,e);if(!f){await O(this,V,ut).call(this,this.callLimitPauseMs);continue}const d={};if(f!=null&&f.answer)for(const[h,N]of Object.entries(f.answer))h!=="result"&&N&&(d[h]=N);if(f.error()){const h=((i=(r=f.error())==null?void 0:r.ex)==null?void 0:i.error)??"";if(["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT","TIMEOUT"].includes(h)){await O(this,V,ut).call(this,this.callLimitPauseMs);continue}const N=((a=f.error())==null?void 0:a.toString())||((l=(c=f.error())==null?void 0:c.ex)==null?void 0:l.error_description)||((n=(u=f.error())==null?void 0:u.ex)==null?void 0:n.error)||"Неизвестная ошибка";return{success:!1,data:!1,answer:d,error:N}}let A=f.data();return A!=null&&A.items&&(A=A.items),{success:!0,data:A,answer:d,error:null}}}arrayChunk(s){let e="",r={};if(Array.isArray(s)?[e]=s:(e=s.method,r=s.params),(e.includes("list")||e==="user.get"||e==="entity.item.get")&&e!=="task.item.list"){if(!r)r=e==="entity.item.get"?{SORT:{ID:"ASC"}}:{order:{ID:"ASC",id:"ASC"}};else{e==="entity.item.get"?(r.SORT||(r.SORT={ID:"ASC"}),Array.isArray(r.select)?r.select.includes("ID")||r.select.push("ID"):r.select=["ID"]):e==="tasks.task.list"?(r.order||(r.order={}),r.order.ID="asc"):e==="user.get"?(r.sort||(r.sort="ID"),r.order||(r.order="ASC")):r.order={ID:"ASC",id:"ASC"},Array.isArray(r.select)&&!r.select.includes("ID")&&r.select.push("ID");const i=e==="user.get"||e==="entity.item.get"?r.FILTER:r.filter;typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.entries(i).forEach(([a,c])=>{(r.start===void 0||r.start!==-1)&&["id","ID"].includes(a)&&(typeof c=="string"||Array.isArray(c)&&c.length<=50)&&(r.start=-1)})}e==="crm.type.list"&&r.order&&delete r.order.ID}if(e==="task.item.list")if(!r)r=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(r[0])&&(r[0]={});const[i,a,c,l]=r;i.ID="ASC",l[0]!==""&&l.includes("ID")||l.push("ID")}return{method:e,params:r}}async batchChunk(s,e,r=!0,i={}){return new Promise(a=>{const c=[];let l;const u=!!(i!=null&&i.disablePagination);(async()=>{await O(this,rt,Et).call(this,s,async f=>{var A,h,N,_,b;for(const[S,y]of Object.entries(f)){if(!this.canContinue)return;if(y.error()){const g=(h=(A=y.error())==null?void 0:A.ex)==null?void 0:h.error,H=(_=(N=y.error())==null?void 0:N.ex)==null?void 0:_.error_description;this.errors[S]=g&&g.trim()||H&&H.trim()||((b=y.error())==null?void 0:b.toString())||"Неизвестная ошибка",l=!0}const T=this.getData(y.data()),U=Array.isArray(T)?T.length:0,p=typeof y.total=="function"&&y.total()!==void 0,I=p?y.total():U;e==="count"?this.result[S]?this.result[S]+=U:this.result[S]=I:this.result[S]=T,this.setProgressData({key:S,value:y,type:e});const R=s[S],w=Array.isArray(R)?R[0]:R==null?void 0:R.method,k=typeof w=="string"&&(w.includes(".list")||w==="user.get"||w==="entity.item.get"),t=e==="count"?!p&&U===this.limit:k?U===this.limit:I>this.limit&&I>U,o=e!=="count"&&w==="entity.item.get"&&U===this.limit&&!t,m=t||o;if(!u&&(!this.canContinue||m)){let g=s[S];if(Array.isArray(g)){const[H,D={}]=g;g=[H,D]}else{const{method:H,params:D={}}=g;g=[H,D]}c.push([S,g,I,{entityItemGetScan:o}])}}l>0&&this.errorLogger();const d=c.length>0||r;await O(this,st,Tt).call(this,f,d),c.length?await this.batchPayload(c,e,i).then(()=>a(this.result)):a(this.result)})})()})}async batchPayload(s,e,r={}){const i=!!(r!=null&&r.oneBatch),a=(N,_,b,S)=>{let y="ID";this.result[N][this.result[N].length-1].ID||(y="id");let T=`${y}`;if(JSON.stringify(S[1]).toLocaleLowerCase().includes('"id":"desc"')?T="<"+T:T=">"+T,_===1||b.length===0)return{field:T,id:this.result[N][this.result[N].length-1][y]};let p="";const[I,R]=S;return(I==="tasks.task.list"||I==="task.item.list")&&(p="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(I)&&(p="[items]"),I==="crm.type.list"&&(p="[types]"),I==="socialnetwork.api.workgroup.list"&&(p="[workgroups]"),{field:T,id:`$result[${[N,_-1].join("__")}]${p}[49][${y}]`}},c=(N,_)=>{const[b,S]=N;let y=JSON.parse(JSON.stringify(S)),T;if(b==="task.item.list"){y=[...y];const[U,p,I,R]=y;return p[_.field]=_.id,[b,y]}return["user.get"].includes(b)||y.FILTER?(y.FILTER||(y.FILTER={}),T=y.FILTER):(y.filter||(y.filter={}),T=y.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(b)?T[">ID"]=_.id:T[_.field]=_.id,[b,{...y,start:-1}]},l=N=>{Object.entries(N).forEach(([_,b])=>{var T,U,p,I,R;const[S]=_.split("__"),y=this.getData(b.data());if(Array.isArray(y)&&(e==="count"?this.result[S]+=y.length:this.result[S].push(...y)),b.error()){const w=(U=(T=b.error())==null?void 0:T.ex)==null?void 0:U.error,k=(I=(p=b.error())==null?void 0:p.ex)==null?void 0:I.error_description;this.errors[S]=w&&w.trim()||k&&k.trim()||((R=b.error())==null?void 0:R.toString())||"Неизвестная ошибка"}this.setProgressData({key:S,value:b,type:e})})},u=(N,_)=>{if(!Array.isArray(N)||N.length===0)return null;const b=N[N.length-1];let S="ID";b.ID||(S="id");let y=S;return JSON.stringify(_[1]).toLocaleLowerCase().includes('"id":"desc"')?y="<"+y:y=">"+y,{field:y,id:b[S]}},n=1e4,f=async(N,_)=>{var S,y;let b=this.limit;for(let T=1;this.canContinue&&b===this.limit&&T<=n;T++){const U=this.result[N],p=u(U,_);if(!p)break;const I=`${N}__eiscan_${T}`,R=c(_,p);let w=null;await O(this,rt,Et).call(this,{[I]:R},async m=>{w=m,l(m)});const k=T<n;await O(this,st,Tt).call(this,w,k),await this.delay();const t=w==null?void 0:w[I];if((S=t==null?void 0:t.error)!=null&&S.call(t)){b=0;break}const o=this.getData((y=t==null?void 0:t.data)==null?void 0:y.call(t));b=Array.isArray(o)?o.length:0}};let d=[],A=0;const h=async(N=!0)=>d.length?(await O(this,rt,Et).call(this,Object.fromEntries(d),async _=>{l(_),await O(this,st,Tt).call(this,_,N)}),A++,d=[],i&&A>=1?!0:(await this.delay(),!1)):!1;for await(const N of s){if(!this.canContinue)return;const[_,b,S,y={}]=N;if(y.entityItemGetScan){if(await h(!0))return;if(i)continue;await f(_,b);continue}let T=1;for(;S>T*this.limit;){const U=[_,T].join("__"),p=a(_,T,d,b);if(d.push([U,c(b,p)]),i&&d.length===49&&await h(!0)||d.length%50===0&&await h(!0))return;T++}}await h(!1)}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([s,e])=>{e&&console.log(`[${s}]`,e.toString())}),console.groupEnd()}};bt=new WeakSet,ae=function(){const s=this.totalBatchCommands||0,e=this.batchCommandMethods;if(s<M(q,Rt)||!Array.isArray(e)||e.length!==s)return!1;if(e.filter(a=>a==="crm.deal.list").length>=M(q,Lt))return!0;const i=e.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=M(q,St)&&i/s>=M(q,It)},Rt=new WeakMap,Lt=new WeakMap,St=new WeakMap,It=new WeakMap,At=new WeakSet,Ft=function(){if(!this.progressCall||!this.progressData)return;const{percent:s,allCount:e,allTotal:r}=this.progressPercent,i={percent:s,allCount:e,allTotal:r};O(this,Mt,oe).call(this,i)&&(this.progressCall({data:this.progressData,percent:s,allCount:e,allTotal:r}),this.lastProgressSnapshot=i)},Mt=new WeakSet,oe=function(s){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==s.percent||this.lastProgressSnapshot.allCount!==s.allCount||this.lastProgressSnapshot.allTotal!==s.allTotal:!0},Dt=new WeakSet,Ae=function(){const s={limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs};for(const e of this.timeLimitListeners)try{e(s)}catch(r){console.warn("Batch timeLimit listener error:",r)}},V=new WeakSet,ut=async function(s=this.defaultPauseMs){this.setTimeLimitState(!0,new Date().toISOString(),s),await new Promise(e=>setTimeout(e,s)),this.setTimeLimitState(!1,void 0)},st=new WeakSet,Tt=async function(s,e=!0){if(!e)return 0;let r=0;if(!s||typeof s!="object")return 0;for(const i of Object.values(s))if(!(!i||typeof i!="object"))try{if(typeof i.time=="function"){const a=i.time();a&&typeof a.operating=="number"&&(r=Math.max(r,a.operating))}}catch{}r>=this.operatingThreshold&&await O(this,V,ut).call(this)},rt=new WeakSet,Et=async function(s,e){let r=!1,i=s;do r=!1,await this.callBatchWithTimeout(i,async a=>{var u,n;let c=!1;const l=new Set;for(const[f,d]of Object.entries(a||{})){if(!(d!=null&&d.error)||!d.error())continue;const A=((n=(u=d.error())==null?void 0:u.ex)==null?void 0:n.error)??"";if(A==="TIMEOUT"){c=!0;break}["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT"].includes(A)&&l.add(f)}if(c){r=!0,await O(this,V,ut).call(this);return}if(l.size>0){const f={};for(const[A,h]of Object.entries(a||{}))l.has(A)||(f[A]=h);Object.keys(f).length&&await e(f);const d={};for(const A of l)i[A]&&(d[A]=i[A]);i=d,Object.keys(i).length&&(r=!0,await O(this,V,ut).call(this));return}await e(a)});while(r)},kt=new WeakSet,ce=function(s,e){return new Promise(r=>{if(typeof this.callMethod!="function"){r(null);return}let i=!1;const a=setTimeout(()=>{i||(i=!0,r(null))},this.requestTimeoutMs);try{this.callMethod(s,e,c=>{i||(i=!0,clearTimeout(a),r(c))})}catch{i||(i=!0,clearTimeout(a),r(null))}})},dt=new WeakSet,Qt=function(s){this.clearProgressData(),this.progressCall=typeof s=="function"?s:"",this.canContinue=!0,this.result={},this.errors={},this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.setTimeLimitState(!1,void 0)},L(q,Rt,5),L(q,Lt,5),L(q,St,8),L(q,It,.65);let z=q;class jt{constructor(){L(this,it,{})}get hash(){return this.createHash(8)}createHash(s){let e="abcdefghijklmnopqrstuvwxyz0123456789",r="";s=s||6;for(let i=0;i<s;i++)r+=e.charAt(Math.floor(Math.random()*e.length));return r}actionFilter({keyTimer:s,duration:e=10,action:r}){M(this,it)[s]&&(clearTimeout(M(this,it)[s]),M(this,it)[s]=null),r&&(M(this,it)[s]=setTimeout(()=>{r()},e))}async noSleep(){let s=document.createElement("video");s.classList.add("no-sleep"),s.muted=!0,s.autoplay=!0,s.setAttribute("playsinline",""),s.addEventListener("loadeddata",()=>{s.style.position="fixed",s.style.left="-9999px",document.querySelector("body").append(s),s.play().catch(e=>{console.warn("noSleep: autoplay prevented",e)})}),s.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{s.play().catch(e=>{console.warn("noSleep: replay prevented",e)})}})}),s.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(s,e){let r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=i,a.download=`${e}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(i)},200)}}it=new WeakMap;const Jt=new jt;class se{constructor(){L(this,Bt);L(this,yt);L(this,wt);L(this,Ct);L(this,Ht);L(this,Q,"logger");L(this,Z,!1);L(this,nt,new Map);L(this,ct,{});L(this,gt,!1);L(this,$,null);L(this,J,null);L(this,at,!1);L(this,lt,!1);P(this,"periodClear",3)}async init(){try{let s=new z(BX24.callBatch),{entityList:e}=await s.batch({entityList:{method:"entity.get"}});if(e&&Array.isArray(e))if(e.find(i=>i.ENTITY==M(this,Q)))j(this,Z,!0);else{let{entityAdd:i}=await s.batch({entityAdd:{method:"entity.add",params:{ENTITY:M(this,Q),NAME:M(this,Q),ACCESS:{AU:"X"}}}});i&&j(this,Z,!0)}return M(this,Z)}catch(s){return console.error("Ошибка при инициализации логера:",s),!1}}enableBackworkerMode(){return j(this,Z,!0),!0}start({type:s,data:e}){if(!M(this,Z))return O(this,yt,Zt).call(this,"entity"),null;if(!s||!e)return console.error("Невалидные данные для логирования:",{type:s,data:e}),null;const r=Jt.hash,i={type:s,data:e,userInfo:null,errorList:{},status:"",answer:null,date:new Date().getTime()};return M(this,nt).set(r,i),j(this,lt,!0),r}async stop({key:s,errorList:e,status:r,answer:i}){var c;if(!M(this,lt))return;if(!M(this,Z)){O(this,yt,Zt).call(this,"entity");return}let a=M(this,nt).get(s);if(!a){console.error(`Не найдены данные логирования для ключа: ${s}`);return}e&&(a.errorList=e),r&&(a.status=r),i&&(a.answer=i),await O(this,Bt,le).call(this),a.userInfo=M(this,ct),await O(this,wt,he).call(this),(c=a==null?void 0:a.data)!=null&&c.updateList&&j(this,at,!0),j(this,lt,!1)}async getEntityList(s){var e;try{if((e=M(this,J))!=null&&e.length&&!M(this,at))return M(this,J);let r=new z(BX24.callBatch),{entityList:i}=await r.batch({entityList:{method:"entity.item.get",params:{ENTITY:M(this,Q),SORT:{ID:"DESC"}}}},s);return!i||!Array.isArray(i)?(console.warn("Получен невалидный список записей"),[]):(i=i.map(a=>{try{const{ID:c,DATE_CREATE:l,DETAIL_TEXT:u}=a;return{...JSON.parse(u),id:c,dateCreate:l}}catch(c){return console.error(`Ошибка парсинга записи ${a.ID}:`,c),null}}).filter(a=>a!==null),j(this,at,!1),j(this,J,i),i)}catch(r){return console.error("Ошибка при получении списка записей:",r),[]}}runStorageMaintenance(){return O(this,Ct,ue).call(this)}async downAllEntityJson(){try{if(M(this,J)||await this.getEntityList(),!M(this,J)||M(this,J).length===0)return console.warn("Нет данных для выгрузки"),!1;let s=mt().format("%Y-%m-%d");return Jt.downloadFileJson(M(this,J),`sdklogger-entity-data__${s}`),!0}catch(s){return console.error("Ошибка при выгрузке данных в JSON:",s),!1}}}Q=new WeakMap,Z=new WeakMap,nt=new WeakMap,ct=new WeakMap,gt=new WeakMap,$=new WeakMap,J=new WeakMap,at=new WeakMap,lt=new WeakMap,Bt=new WeakSet,le=async function(){if(!M(this,gt))return M(this,$)?M(this,$):(j(this,$,(async()=>{try{const s=new z(BX24.callBatch),e=BX24.isAdmin(),{curUser:r}=await s.batch({curUser:{method:"user.current"}});j(this,ct,{isAdmin:e,curUser:r})}catch(s){console.error("Ошибка при получении информации о пользователе:",s),j(this,ct,{isAdmin:!1,curUser:null})}finally{j(this,gt,!0),j(this,$,null)}})()),M(this,$))},yt=new WeakSet,Zt=function(s){s=="entity"&&Jt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},wt=new WeakSet,he=async function(){try{let s={},e=new z(BX24.callBatch);for(let[r,i]of M(this,nt).entries())if(i.status){const a=JSON.stringify(i);s[r]={method:"entity.item.add",params:{ENTITY:M(this,Q),NAME:M(this,Q),DETAIL_TEXT:a}}}if(Object.keys(s).length){let r=await e.batch(s),{errors:i}=e;for(let[a,c]of Object.entries({...r,...i}))M(this,nt).delete(a);return!0}return!1}catch(s){return console.error("Ошибка при добавлении записей в хранилище:",s),!1}},Ct=new WeakSet,ue=async function(){try{let s=new z(BX24.callBatch),{serverTime:e}=await s.batch({serverTime:{method:"server.time"}});if(!e){console.error("Не удалось получить время сервера");return}if(M(this,J)||await this.getEntityList(),!M(this,J)||M(this,J).length===0)return;let r=M(this,J).filter(i=>{try{let{dateCreate:a}=i;return a?mt(new Date(a)).between(mt(new Date(e)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});r.length>0&&(console.log(`Найдено ${r.length} записей для очистки (старше ${this.periodClear} месяцев)`),await O(this,Ht,fe).call(this,r))}catch(s){console.error("Ошибка при проверке периода очистки:",s)}},Ht=new WeakSet,fe=async function(s){try{if(!s||s.length===0)return!1;let e=new z(BX24.callBatch),r=s.filter(a=>a&&a.id).map(a=>{let{id:c}=a;return{method:"entity.item.delete",params:{ENTITY:M(this,Q),ID:c}}});if(r.length===0)return!1;const i=await e.batch(r);return console.log(`Успешно удалено ${r.length} записей`),j(this,at,!0),i}catch(e){return console.error("Ошибка при очистке устаревших записей:",e),!1}};function Kt(E){if(!E||typeof E!="string")return"";try{const s=new URL(E);s.search="",s.hash="";let e=s.toString();return e.endsWith("/")&&s.pathname!=="/"&&(e=e.slice(0,-1)),e}catch{return E.split("?")[0].split("#")[0].replace(/\/$/,"")}}function re(E){return!E||typeof E!="string"?!1:E.toLowerCase().includes("/marketplace/app")}function _e(){var s;if(typeof window>"u"||!((s=window.location)!=null&&s.href))return"";const E=Kt(window.location.href);return re(E)?"":E}function vt(E){if(!(E!=null&&E.appConst)||typeof E.appConst!="object")return"";const s=_e();return s?(E.appConst.pathApp=s,s):Kt(E.appConst.pathApp??"")}class Te{constructor(s){L(this,ht);L(this,Ut);L(this,pt);L(this,Gt);L(this,Pt);L(this,Yt);L(this,tt);L(this,Nt);L(this,Wt);L(this,Ot);L(this,xt);P(this,"domain","");P(this,"isAdmin",!1);P(this,"appInfo",null);P(this,"appConst",null);P(this,"userInfo",null);P(this,"placeData",null);P(this,"placeInfo",null);P(this,"logger",!1);P(this,"timeLimit",{limit:!1,date:void 0,pauseMs:void 0});P(this,"batchClient",null);this.appConst=s}subscribeTimeLimit(s){return O(this,ht,Xt).call(this).subscribeTimeLimit(s)}init(){return new Promise((s,e)=>{const i=setTimeout(()=>{clearInterval(a);const c=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(c),e(c)},3e4);let a=setInterval(()=>{window.BX24&&BX24.init(async()=>{clearInterval(a),clearTimeout(i),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info();const c=O(this,Gt,de).call(this);if(console.info(c?"init BX24 (background worker)":"init BX24"),this.appInfo=await O(this,Pt,ge).call(this),this.userInfo=await O(this,Yt,ye).call(this),vt(this),c)await O(this,pt,Vt).call(this,!1,{skipInit:!0});else{await O(this,pt,Vt).call(this,!0);const l=new jt;try{l.noSleep()}catch(u){console.warn("Failed to initialize noSleep:",u)}}s({isBackworker:c})})},100)})}userOption(s,e){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.userOption.set(s,e):BX24.userOption.get(s)}appOption(s,e){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.appOption.set(s,e):BX24.appOption.get(s)}async call({method:s,params:e,updateList:r}){let i;if(r&&(i=this.logger.start({type:"call",data:{method:s,params:e,updateList:r}})),e||(e={}),typeof BX24>"u"||!BX24.callMethod){const l=new Error("BX24 is not initialized");throw console.error(l),l}const c=await O(this,ht,Xt).call(this).call({method:s,params:e});return c.success?(await O(this,tt,ft).call(this,i,{answer:c.answer,status:"success"}),c.data):(console.error(c.error),await O(this,tt,ft).call(this,i,{answer:c.answer,status:"fail",errorList:{0:c.error||"Unknown call error"}}),!1)}async batch(s,e,{errorCall:r,updateList:i,batchOptions:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const c=new Error("BX24 is not initialized");return console.error(c),!1}return O(this,Nt,$t).call(this,{mode:"batch",commandList:s,progressCall:e,errorCall:r,updateList:i,batchOptions:a})}async batchTotalCount(s,e,{errorCall:r,updateList:i}={}){if(typeof BX24>"u"||!BX24.callBatch){const a=new Error("BX24 is not initialized");return console.error(a),!1}return O(this,Nt,$t).call(this,{mode:"batch-total-count",commandList:s,progressCall:e,errorCall:r,updateList:i})}async getPlacement(){const s=await this.call({method:"placement.get"});return this.placeData||(this.placeData=s),s}async placementBind(s){var A;if(!this.isAdmin||(this.placeData=await this.getPlacement(),!this.placeData))return;const{appName:e,pathApp:r}=this.appConst;let i=O(this,Ot,te).call(this,s);i=i.filter(h=>h.placement!=="PAGE_BACKGROUND_WORKER"&&h.placement!=="PAGE_BACKGROUND_WORKER_ALL");const a=O(this,xt,Ne).call(this,r),c=new Set(i.map(h=>h.placement));for(const h of a)c.has(h.placement)||i.push({placement:h.placement});if(i.length===0)return;let l=e;this.domain==="szdl.bitrix24.ru"&&((A=this.appInfo)!=null&&A.ID)&&(l=`${e}: #${this.appInfo.ID}`);const u=l.replace(" CRM",""),n={},f=[],d=new Map;for(const h of this.placeData)d.has(h.placement)||d.set(h.placement,[]),d.get(h.placement).push(h);for(let h=0;h<i.length;h++){const{placement:N,options:_}=i[h],b=d.get(N)||[];if(b.some(T=>T.handler===r))continue;const y=b.filter(T=>T.handler!==r);for(const T of y)f.push({placement:N,handler:T.handler});n[`bind_${h}`]={method:"placement.bind",params:{PLACEMENT:N,HANDLER:r,LANG_ALL:{ru:{TITLE:N==="USER_PROFILE_TOOLBAR"?u:l}},OPTIONS:{errorHandlerUrl:r,..._&&typeof _=="object"?_:{}}}}}f.length>0&&await this.placementUnBind(f),Object.keys(n).length>0&&(await this.batch(n),this.placeData=await this.getPlacement(),Object.values(n).forEach(h=>{console.log("Приложение успешно встроено в",h.params.PLACEMENT)}))}async placementUnBind(s){let e=O(this,Ot,te).call(this,s);if(e=e.filter(i=>i.placement!=="PAGE_BACKGROUND_WORKER"&&i.placement!=="PAGE_BACKGROUND_WORKER_ALL"),e.length===0)return;const r={};for(let i=0;i<e.length;i++){const a={PLACEMENT:e[i].placement};e[i].handler&&(a.HANDLER=e[i].handler),r[`unbind_${i}`]={method:"placement.unbind",params:a}}await this.batch(r),e.forEach(i=>{console.log("Встройка отвязана",i.placement)})}async getBotList(){const s=await this.call({method:"imbot.bot.list",params:{}}),e=Object.values(s);return console.log("chat-bot list:",e),e}async regBot({code:s,type:e,name:r}){const{appName:i,pathApp:a,chatBotLogo:c}=this.appConst,l=this.appInfo.ID,u=await this.call({method:"imbot.register",params:{CODE:s??this.appInfo.CODE,TYPE:e??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${r??i} - бот #${l}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:mt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:c??""}}});return console.log("Чат-бот добавлен",u),u}async unRegBot(s){const e=await this.call({method:"imbot.unregister",params:{BOT_ID:s}});return console.log("чат-бот удален",e),e}getLoggerList(s){return this.logger.getEntityList(s)}}ht=new WeakSet,Xt=function(){return this.batchClient||(this.batchClient=new z({callBatch:BX24.callBatch,callMethod:BX24.callMethod}),this.timeLimit=this.batchClient.timeLimit),this.batchClient},Ut=new WeakSet,me=function(){return{start:()=>{},stop:()=>{},getEntityList:()=>{}}},pt=new WeakSet,Vt=async function(s,{skipInit:e=!1}={}){this.logger?(this.logger=new se,e?this.logger.enableBackworkerMode():await this.logger.init(),s&&typeof this.logger.runStorageMaintenance=="function"&&this.logger.runStorageMaintenance()):this.logger=O(this,Ut,me).call(this)},Gt=new WeakSet,de=function(){var r,i,a;const s=(r=this.placeInfo)==null?void 0:r.placement,e=(a=(i=this.placeInfo)==null?void 0:i.options)==null?void 0:a.ID;return s==="PAGE_BACKGROUND_WORKER"||e==="PAGE_BACKGROUND_WORKER"},Pt=new WeakSet,ge=function(){return this.call({method:"app.info"})},Yt=new WeakSet,ye=function(){return this.call({method:"user.current"})},tt=new WeakSet,ft=async function(s,e){if(s)try{await this.logger.stop({key:s,...e})}catch(r){console.error("Logger error:",r)}},Nt=new WeakSet,$t=async function({mode:s,commandList:e,progressCall:r,errorCall:i,updateList:a,batchOptions:c}){const l=O(this,ht,Xt).call(this),u=a?this.logger.start({type:s,data:s==="batch"?{commandList:e,updateList:a}:{commandList:e}}):void 0;try{const n=s==="batch"?await l.batch(e,r,c):await l.batchTotalCount(e,r),f=O(this,Wt,pe).call(this,l,n,e,a);return Object.keys(f).length?(i&&i(f),await O(this,tt,ft).call(this,u,{status:"fail",errorList:f})):await O(this,tt,ft).call(this,u,{status:"success"}),n}catch(n){return await O(this,tt,ft).call(this,u,{status:"fail-runtime",errorList:{0:n==null?void 0:n.toString()}}),console.error(n),!1}},Wt=new WeakSet,pe=function(s,e,r,i){let a={...s.errors};if(Object.values(s.errors).some(l=>{if(typeof l!="string")return!1;const u=l.toUpperCase();return u==="TIMEOUT"||u==="OPERATION_TIME_LIMIT"||u.includes("TIMEOUT")||u.includes("OPERATION_TIME_LIMIT")})&&i){const l=e?Object.keys(e).filter(d=>d!=="errorsList"):[],u=new Set(Object.keys(s.errors||{})),n=new Set;if(e){for(const d of l)if(!u.has(d)){const A=e[d];A!=null&&n.add(d)}}const f=Object.values(s.errors).find(d=>{if(typeof d!="string")return!1;const A=d.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const d of Object.keys(r))!n.has(d)&&!s.errors[d]&&(a[d]=f||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a},Ot=new WeakSet,te=function(s){if(!s)return[];let e=[];return Array.isArray(s)?e=s.map(r=>typeof r=="string"?{placement:r}:r):typeof s=="string"?e=[{placement:s}]:e=[s],e},xt=new WeakSet,Ne=function(s){return this.placeData?this.placeData.filter(e=>!(e.placement==="PAGE_BACKGROUND_WORKER"||!e.handler||e.handler.includes(s))):[]};const ie="szdl-utils-kit|";function Ee(){if(typeof sessionStorage>"u")return`ephemeral-${Date.now()}-${Math.random().toString(16).slice(2)}`;let E=sessionStorage.getItem("szdl-cross-tab-instance-id");return E||(E=`${Date.now()}-${Math.random().toString(16).slice(2)}`,sessionStorage.setItem("szdl-cross-tab-instance-id",E)),E}function be(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}const zt=new Map;function Re(E="default"){if(typeof BroadcastChannel>"u")return null;const s=`${ie}bc:${E}`;return zt.has(s)||zt.set(s,new BroadcastChannel(s)),zt.get(s)}function ne(E,s){const e=Re(E);if(e)try{const r=s&&typeof s=="object"&&!Array.isArray(s)?s:{data:s};e.postMessage({...r,tabId:Ee(),ts:Date.now()})}catch{}}async function Le(E,s,e={}){const{ifAvailable:r=!1}=e,i=typeof E=="string"&&E.length>0?E:"default",a=`${ie}${i}`;return be()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!r},async c=>{if(r&&c==null)return{skipped:!0,coordination:"locks"};ne(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await s(),coordination:"locks"}}finally{ne(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await s(),coordination:"none"}}class Se{constructor(s){L(this,_t);P(this,"entityName","tabs");P(this,"maxTabs",20);P(this,"tabList",[]);P(this,"id",0);P(this,"hasStarted",!1);P(this,"heartbeat");P(this,"runHeartbeat");P(this,"activeMaxPause",10*1e3);P(this,"quickCleanupThreshold",2*60*1e3);P(this,"pollInterval",6*1e3+Math.floor(Math.random()*2e3));P(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);P(this,"continueCondition");P(this,"defaultContinueBackground",()=>!0);var c,l,u;if(!s){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:e,bx:r,users:i,continueBackground:a}=s;this.bx=r,this.appInit=e,this.users=i,vt(r),this.appPath=O(this,_t,ee).call(this,((c=r==null?void 0:r.appConst)==null?void 0:c.pathApp)??""),this.appName=((l=r==null?void 0:r.appConst)==null?void 0:l.appName)??"",this.appCodeName=((u=r==null?void 0:r.appConst)==null?void 0:u.appCodeName)??"",this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("BackgroundWorker: appInit не передан");return}if(!this.bx){console.error("BackgroundWorker: bx не передан");return}if(this.isAppPage()){console.log("BackgroundWorker: Страница приложения, фоновый воркер не запускается");return}await this.checkPlacementType()&&await this.continueBackground()&&(await this.checkEntity(),await this.refreshTabs(!0),await this.ensureTabRegistered(),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(e=>{console.error("BackgroundWorker: backgroundTick failed",e)})},this.pollInterval),await this.backgroundTick())}async backgroundTick(){if(!await this.continueBackground()){this.stopTimers(),console.log("BackgroundWorker: Остановка backgroundTick - условие не выполнено");return}await this.refreshTabs(!0),await this.ensureTabRegistered();const e=this.selectLeaderId(),r=e&&+this.id==+e;await this.updateTabState(r),r&&!this.hasStarted&&await this.runAsLeader()}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var s;if(typeof BX24>"u"||!((s=BX24.placement)!=null&&s.info))return!1;try{const e=BX24.placement.info(),r=e==null?void 0:e.placement,i=(e==null?void 0:e.options)||{},a=(i==null?void 0:i.URI)||"",c=r==="PAGE_BACKGROUND_WORKER"||(i==null?void 0:i.ID)==="PAGE_BACKGROUND_WORKER",l=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!c||l}catch{return!1}}async checkEntity(){var r;const s=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((r=s==null?void 0:s.find)==null?void 0:r.call(s,i=>i.ENTITY===this.entityName))||await this.safeCall(()=>this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}}))}async getTabs(){const s=await this.safeCall(()=>{var e;return this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:(e=this.bx.userInfo)==null?void 0:e.ID},SORT:{DATE_CREATE:"DESC"}}})});return!Array.isArray(s)||!s.length?[]:s.map(e=>{if(!e)return{id:void 0,data:void 0};try{const r=JSON.parse(e.DETAIL_TEXT);return{id:+e.ID||0,data:r}}catch(r){return console.log("BackgroundWorker: parse tab error",r),{id:+e.ID||0,data:void 0}}})}async ensureTabRegistered(){if(this.id)return+this.id||0;if(this.tabList.length>=this.maxTabs&&await this.refreshTabs(!0,this.quickCleanupThreshold),this.tabList.length>=this.maxTabs)return console.log("BackgroundWorker: Достигнут лимит вкладок даже после быстрой очистки, не регистрируемся"),0;const s={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId},e=await this.safeCall(()=>{var r;return this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(s)}})})||0;return this.id=+e||0,this.id}async updateTabState(s){if(!this.id)return;const e={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:s,sessionId:this.sessionId};await this.safeCall(()=>{var r;return this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(e)}})})}async deleteTabs(s=[]){if(!s.length)return;const e=s.map(r=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:r.id}}));await this.safeCall(()=>this.bx.batch(e))}async checkPlacementType(){var s,e;try{if(!((s=this.bx)!=null&&s.isAdmin))return!0;const r=await this.safeCall(()=>this.bx.getPlacement());if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),a=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),c=!a;if(!i)return!0;let l=!1;for(const u of r){if(u.placement!=="PAGE_BACKGROUND_WORKER"||!(u.userId||u.handler&&u.handler.includes("USER_ID=")))continue;const f=u.userId||(u.handler?this.extractUserIdFromHandler(u.handler):null);if(f&&+f===i){l=!0;break}}return a?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):c&&l?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}isIndividualPlacement(s){return!s||typeof s!="string"?!1:s.includes("USER_ID=")}extractUserIdFromHandler(s){if(!s||typeof s!="string")return null;const e=s.match(/USER_ID=(\d+)/);return e?+e[1]:null}async continueBackground(){try{const e=!!await Promise.resolve(this.continueCondition(this));return console.log(e?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),e}catch(s){return console.error("BackgroundWorker: Ошибка в continueCondition",s),!1}}async refreshTabs(s=!1,e=this.activeMaxPause){const r=[],i=[],a=Date.now(),c=await this.getTabs();for(const l of c){if(!(l!=null&&l.data)){r.push(l);continue}if(a-new Date(l.data.lastActive||0).getTime()>e){r.push(l);continue}i.push(l)}return s&&r.length&&await this.deleteTabs(r),this.tabList=i,i}selectLeaderId(){var e;return this.tabList.length&&+((e=[...this.tabList].sort((r,i)=>{var l,u,n,f;const a=new Date(((l=r.data)==null?void 0:l.createdAt)||((u=r.data)==null?void 0:u.lastActive)||0).getTime(),c=new Date(((n=i.data)==null?void 0:n.createdAt)||((f=i.data)==null?void 0:f.lastActive)||0).getTime();return a===c?(+r.id||0)-(+i.id||0):a-c})[0])==null?void 0:e.id)||0}async runAsLeader(){var i,a;const s=String(((a=(i=this.bx)==null?void 0:i.userInfo)==null?void 0:a.ID)??"0"),e=`background-worker:${this.entityName}:${s}`;(await Le(e,async()=>{this.hasStarted=!0;const c=Math.min(this.activeMaxPause-1500,Math.max(2500,Math.floor(this.pollInterval/2)));this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(l=>console.error("BackgroundWorker: heartbeat update failed",l))},c);try{await this.appInit()}catch(l){console.error("BackgroundWorker: appInit failed",l)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)},{ifAvailable:!0})).skipped&&console.log("BackgroundWorker: runAsLeader пропущен — Web Lock у другой вкладки (тот же фоновый воркер)")}async setBackgroundWorkerAll(){var S,y,T,U;if(!((S=this.bx)!=null&&S.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(y=this.users)!=null&&y.length||await this.getEntityData(),vt(this.bx);const s=O(this,_t,ee).call(this,((U=(T=this.bx)==null?void 0:T.appConst)==null?void 0:U.pathApp)??"");if(!s){console.error("BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена");return}const e=await this.safeCall(()=>this.bx.getPlacement()),r=new Map,i=new Map;let a=null;(e||[]).forEach(p=>{if(p.placement!=="PAGE_BACKGROUND_WORKER")return;if(p.userId||p.handler&&p.handler.includes("USER_ID=")){const R=p.userId||(p.handler?this.extractUserIdFromHandler(p.handler):null);if(R){const w=+R;r.set(w,p),i.has(w)||i.set(w,[]),i.get(w).push(p)}}else a=p});const c=await this.resolveAdmins(),l=await this.getEligibleUsersForBackgroundWorker(c);l.sort((p,I)=>{const R=p.LAST_LOGIN?new Date(p.LAST_LOGIN):new Date(0);return(I.LAST_LOGIN?new Date(I.LAST_LOGIN):new Date(0))-R});const u=10,n=l.slice(0,u),f=n.filter(p=>{const I=r.get(+p.ID);if(!I)return!0;const R=`${s}?USER_ID=${p.ID}/`;return I.handler!==R}),d=[];for(const[p]of r){const I=+p||0;l.find(w=>+w.ID===I)||d.push(I)}for(const p of n){const I=r.get(+p.ID);if(!I)continue;const R=`${s}?USER_ID=${p.ID}/`;I.handler!==R&&d.push(+p.ID)}const A=[],h=[...new Set(d)];for(const p of h){const I=i.get(+p)||[];for(const R of I)R!=null&&R.handler&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:R.handler}})}const N=a&&(f.length>0||a.handler!==`${s}`);N&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:a.handler||`${s}`}});for(const p of f)A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${s}?USER_ID=${p.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${s}?USER_ID=${p.ID}/`},USER_ID:p.ID}});(!a||N)&&A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${s}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${s}`}}});const _=A.filter(p=>p.method==="placement.unbind"),b=A.filter(p=>p.method==="placement.bind");_.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(_.map((p,I)=>[`unbind_${I}`,p])))),b.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(b.map((p,I)=>[`bind_${I}`,p])))),A.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var s,e;try{const r=+(((s=this.bx.userInfo)==null?void 0:s.ID)??0),i=!!((e=this.bx)!=null&&e.isAdmin),a=await this.getAdminsList()||[];if(!i){if(r&&a.includes(+r)){const u=a.filter(n=>+n!=+r);return await this.saveAdminsList(u),u}return a}const c=new Set([...a||[]]);r&&c.add(+r);const l=[...c].filter(Boolean);return await this.saveAdminsList(l),l}catch(r){return console.error("BackgroundWorker: resolveAdmins error",r),[]}}async getEligibleUsersForBackgroundWorker(s=[]){const e=(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0),r=s.map(i=>+i||0).filter(Boolean);return e.filter(i=>r.includes(+i.ID||0))}async saveAdminsList(s=[]){try{BX24.appOption.set("adminsList",JSON.stringify(s))}catch(e){console.error("BackgroundWorker: saveAdminsList error",e)}}async getAdminsList(){try{const s=BX24.appOption.get("adminsList"),e=s?JSON.parse(s):[];return Array.isArray(e)?e.map(r=>+r||0).filter(Boolean):[]}catch(s){return console.error("BackgroundWorker: getAdminsList error",s),[]}}async getEntityData(){const s={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:e}=await this.safeCall(()=>this.bx.batch(s).then(r=>r?(Array.isArray(r.users)||(r.users=[]),r):{users:[]}));this.users=e}async ensureAdminPlacements(){var s,e;(s=this.bx)!=null&&s.isAdmin&&((e=this.users)!=null&&e.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(s=500,e){return new Promise(r=>{setTimeout(()=>{e&&e(),r(!0)},s)})}async safeCall(s){try{return await s()}catch(e){console.error("BackgroundWorker: safeCall error",e);return}}}_t=new WeakSet,ee=function(s){if(!s||typeof s!="string")return"";const e=Kt(s).replace(/\/+$/,"");return e?re(e)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):e:""},B.BackgroundWorker=Se,B.Batch=z,B.BxBoot=Te,B.BxHelper=jt,B.BxLogger=se,B.tempus=mt,Object.defineProperty(B,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "szdl-utils-kit",
3
3
  "description": "utils-kit library",
4
4
  "private": false,
5
- "version": "0.3.20",
5
+ "version": "0.3.21",
6
6
  "type": "module",
7
7
  "author": "Stanislav Ovv",
8
8
  "license": "BSD",