szdl-utils-kit 0.3.14 → 0.3.16

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.
@@ -1,2 +1,2 @@
1
- var It=Object.defineProperty;var Mt=(_,L,C)=>L in _?It(_,L,{enumerable:!0,configurable:!0,writable:!0,value:C}):_[L]=C;var M=(_,L,C)=>(Mt(_,typeof L!="symbol"?L+"":L,C),C),dt=(_,L,C)=>{if(!L.has(_))throw TypeError("Cannot "+C)};var T=(_,L,C)=>(dt(_,L,"read from private field"),C?C.call(_):L.get(_)),Y=(_,L,C)=>{if(L.has(_))throw TypeError("Cannot add the same private member more than once");L instanceof WeakSet?L.add(_):L.set(_,C)},v=(_,L,C,et)=>(dt(_,L,"write to private field"),et?et.call(_,C):L.set(_,C),C);var K=(_,L,C)=>(dt(_,L,"access private method"),C);(function(_,L){typeof exports=="object"&&typeof module<"u"?L(exports):typeof define=="function"&&define.amd?define(["exports"],L):(_=typeof globalThis<"u"?globalThis:_||self,L(_["szdl-utils-kit"]={}))})(this,function(_){var q,Q,Z,$,rt,W,tt,st,at,Nt,nt,gt,At,Ot,ct,_t,ht,Et,lt,Tt,ut,Rt,ot,pt;"use strict";var L=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function C(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x.default:x}var et={exports:{}};(function(x,r){(function(e){Array.prototype.indexOf||(Array.prototype.indexOf=function(t,o){var d,g;for(d=o||0,g=this.length;d<g;d+=1)if(this[d]===t)return d;return-1});var i=this,n=function(t,o){for(var d=t.toString();d.length<o;)d="0"+d;return d},a=function(t,o){return o!==e?(t.year(o.year()||o.year),t.month(o.month()||o.month),t.day(o.day()||o.day),t.hours(o.hours()||o.hours),t.minutes(o.minutes()||o.minutes),t.seconds(o.seconds()||o.seconds),t.milliseconds(o.milliseconds()||o.milliseconds),t):e},l=function(t,o){var d,g="";return d=t.slice(o,o+1),d!==""&&!isNaN(Number(d))&&(g+="%H"),d=t.charAt(o+2),d!==""&&d===":"&&(g+=d),d=t.slice(o+3,o+4),d!==""&&!isNaN(Number(d))&&(g+="%M"),d=t.charAt(o+5),d!==""&&d===":"&&(g+=d),d=t.slice(o+6,o+7),d!==""&&!isNaN(Number(d))&&(g+="%S"),g},c=function(t,o){var d,g=[t.slice(o,o+1),t.charAt(o+2),t.slice(o+3,o+4),t.charAt(o+5),t.slice(o+6,o+9)],w;return!isNaN(Number(g[0]))&&!isNaN(Number(g[2]))&&!isNaN(Number(g[4]))?(g[1]==="."&&g[3]==="."?d="%d.%m.%Y":g[1]==="-"&&g[3]==="-"?d="%m-%d-%Y":g[1]==="/"&&g[3]==="/"&&(d="%m/%d/%Y"),d):(w=[t.slice(o,o+3),t.charAt(o+4),t.slice(o+5,o+6),t.charAt(o+7),t.slice(o+8,o+9)],!isNaN(Number(w[0]))&&!isNaN(Number(w[2]))&&!isNaN(Number(w[4]))?(w[1]==="-"&&w[3]==="-"&&(d="%Y-%m-%d"),d):"")},h=i.tempus,s,f,m=i.navigator||{},A="en",u={en:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"Mar",APRIL_SHORT:"Apr",MAY_SHORT:"May",JUNE_SHORT:"Jun",JULY_SHORT:"Jul",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sep",OCTOBER_SHORT:"Oct",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dec",JANUARY_LONG:"January",FEBRUARY_LONG:"February",MARCH_LONG:"March",APRIL_LONG:"April",MAY_LONG:"May",JUNE_LONG:"June",JULY_LONG:"July",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"October",NOVEMBER_LONG:"November",DECEMBER_LONG:"December",SUNDAY_SHORT:"Sun",MONDAY_SHORT:"Mon",TUESDAY_SHORT:"Tue",WEDNESDAY_SHORT:"Wed",THURSDAY_SHORT:"Thu",FRIDAY_SHORT:"Fri",SATURDAY_SHORT:"Sat",SUNDAY_LONG:"Sunday",MONDAY_LONG:"Monday",TUESDAY_LONG:"Tuesday",WEDNESDAY_LONG:"Wednesday",THURSDAY_LONG:"Thursday",FRIDAY_LONG:"Friday",SATURDAY_LONG:"Saturday"},ru:{JANUARY_SHORT:"Янв",FEBRUARY_SHORT:"Фев",MARCH_SHORT:"Мар",APRIL_SHORT:"Апр",MAY_SHORT:"Май",JUNE_SHORT:"Июн",JULY_SHORT:"Июл",AUGUST_SHORT:"Авг",SEPTEMBER_SHORT:"Сен",OCTOBER_SHORT:"Окт",NOVEMBER_SHORT:"Ноя",DECEMBER_SHORT:"Дек",JANUARY_LONG:"Январь",FEBRUARY_LONG:"Февраль",MARCH_LONG:"Март",APRIL_LONG:"Апрель",MAY_LONG:"Май",JUNE_LONG:"Июнь",JULY_LONG:"Июль",AUGUST_LONG:"Август",SEPTEMBER_LONG:"Сентябрь",OCTOBER_LONG:"Октябрь",NOVEMBER_LONG:"Ноябрь",DECEMBER_LONG:"Декабрь",SUNDAY_SHORT:"Вс",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Воскресенье",MONDAY_LONG:"Понедельник",TUESDAY_LONG:"Вторник",WEDNESDAY_LONG:"Среда",THURSDAY_LONG:"Четверг",FRIDAY_LONG:"Пятница",SATURDAY_LONG:"Суббота"},ua:{JANUARY_SHORT:"Січ",FEBRUARY_SHORT:"Лют",MARCH_SHORT:"Берез",APRIL_SHORT:"Квіт",MAY_SHORT:"Трав",JUNE_SHORT:"Черв",JULY_SHORT:"Лип",AUGUST_SHORT:"Серп",SEPTEMBER_SHORT:"Верес",OCTOBER_SHORT:"Жовт",NOVEMBER_SHORT:"Листоп",DECEMBER_SHORT:"Груд",JANUARY_LONG:"Січень",FEBRUARY_LONG:"Лютий",MARCH_LONG:"Березень",APRIL_LONG:"Квітень",MAY_LONG:"Травень",JUNE_LONG:"Червень",JULY_LONG:"Липень",AUGUST_LONG:"Серпень",SEPTEMBER_LONG:"Вересень",OCTOBER_LONG:"Жовтень",NOVEMBER_LONG:"Листопад",DECEMBER_LONG:"Грудень",SUNDAY_SHORT:"Нд",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Неділя",MONDAY_LONG:"Понеділок",TUESDAY_LONG:"Вівторок",WEDNESDAY_LONG:"Середа",THURSDAY_LONG:"Четвер",FRIDAY_LONG:"П’ятниця",SATURDAY_LONG:"Субота"},de:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"März",APRIL_SHORT:"Apr",MAY_SHORT:"Mai",JUNE_SHORT:"Juni",JULY_SHORT:"Juli",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sept",OCTOBER_SHORT:"Okt",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dez",JANUARY_LONG:"Januar",FEBRUARY_LONG:"Februar",MARCH_LONG:"März",APRIL_LONG:"April",MAY_LONG:"Mai",JUNE_LONG:"Juni",JULY_LONG:"Juli",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"Oktober",NOVEMBER_LONG:"November",DECEMBER_LONG:"Dezember",SUNDAY_SHORT:"So",MONDAY_SHORT:"Mo",TUESDAY_SHORT:"Di",WEDNESDAY_SHORT:"Mi",THURSDAY_SHORT:"Do",FRIDAY_SHORT:"Fr",SATURDAY_SHORT:"Sa",SUNDAY_LONG:"Sonntag",MONDAY_LONG:"Montag",TUESDAY_LONG:"Dienstag",WEDNESDAY_LONG:"Mittwoch",THURSDAY_LONG:"Donnerstag",FRIDAY_LONG:"Freitag",SATURDAY_LONG:"Samstag"}},N=function(){return[u[A].JANUARY_LONG,u[A].FEBRUARY_LONG,u[A].MARCH_LONG,u[A].APRIL_LONG,u[A].MAY_LONG,u[A].JUNE_LONG,u[A].JULY_LONG,u[A].AUGUST_LONG,u[A].SEPTEMBER_LONG,u[A].OCTOBER_LONG,u[A].NOVEMBER_LONG,u[A].DECEMBER_LONG]},y=function(){return[u[A].JANUARY_SHORT,u[A].FEBRUARY_SHORT,u[A].MARCH_SHORT,u[A].APRIL_SHORT,u[A].MAY_SHORT,u[A].JUNE_SHORT,u[A].JULY_SHORT,u[A].AUGUST_SHORT,u[A].SEPTEMBER_SHORT,u[A].OCTOBER_SHORT,u[A].NOVEMBER_SHORT,u[A].DECEMBER_SHORT]},p=function(){return[u[A].SUNDAY_LONG,u[A].MONDAY_LONG,u[A].TUESDAY_LONG,u[A].WEDNESDAY_LONG,u[A].THURSDAY_LONG,u[A].FRIDAY_LONG,u[A].SATURDAY_LONG]},R=function(){return[u[A].SUNDAY_SHORT,u[A].MONDAY_SHORT,u[A].TUESDAY_SHORT,u[A].WEDNESDAY_SHORT,u[A].THURSDAY_SHORT,u[A].FRIDAY_SHORT,u[A].SATURDAY_SHORT]},S,D,B,k,J=function(t,o,d){var g;i.XMLHttpRequest?g=new XMLHttpRequest:g=new ActiveXObject("Microsoft.XMLHTTP"),g.onreadystatechange=function(){g.readyState===4&&(g.status===200?o&&(i.JSON===e?alert(`Please, include json2 into your project if you want use old browsers!
2
- https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(g.responseText))):d&&d(g))},g.open("GET",t,!1),g.send()},I={"%d":{format:function(t){return n(t.day()||s.MIN_DAY,2)},parse:function(t){var o=Number(t);return{day:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(t){return n(t.month()||s.MIN_MONTH,2)},parse:function(t){var o=Number(t);return{month:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(t){return n(t.year()||s.MIN_YEAR,4)},parse:function(t){var o=Number(t);return{year:isNaN(o)?e:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(t){return t.dayOfWeek()||s.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(t){var o=t.dayOfWeek();return k[o!==e?o:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var o=t.dayOfWeek();return B[o!==e?o:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(t){var o=s.options("monthFromZero")?t.month():t.month()-1;return D[o!==e?o:s.MIN_MONTH]},parse:function(t){var o=s.monthNames().indexOf(t)+(s.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var o=s.options("monthFromZero")?t.month():t.month()-1;return S[o!==e?o:s.MIN_MONTH]},parse:function(t){var o=s.monthNames(!0).indexOf(t)+(s.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(t){return n(t.hours()||s.MIN_HOURS,2)},parse:function(t){var o=Number(t);return{hours:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(t){return n(t.minutes()||s.MIN_MINUTES,2)},parse:function(t){var o=Number(t);return{minutes:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(t){return n(t.seconds()||s.MIN_SECONDS,2)},parse:function(t){var o=Number(t);return{seconds:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(t){return t.timestamp()},parse:function(t){return isNaN(Number(t))?{}:s(Number(t)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(t){return n(t.year()||s.MIN_YEAR,4)+"-"+n(t.month()||s.MIN_MONTH,2)+"-"+n(t.day()||s.MIN_DAY,2)},parse:function(t){var o=Number(t.slice(0,4)),d=Number(t.slice(5,7)),g=Number(t.slice(8,10));return{year:o,month:d,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return n(t.month()||s.MIN_MONTH,2)+"/"+n(t.day()||s.MIN_DAY,2)+"/"+n(t.year()||s.MIN_YEAR,4)},parse:function(t){var o=Number(t.slice(0,2)),d=Number(t.slice(3,5)),g=Number(t.slice(6,10));return{year:g,month:o,day:d}},minLength:10,maxLength:10,type:"string"}},X={useMilliseconds:!1,monthFromZero:!1},O;O=function(t,o,d){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t!==e&&this.set(t,o,d),this},O.fn=O.prototype,O.fn.dayCount=function(){var t=this.month(),o=s.MAX_DAY_IN_MONTHS[t-(s.options("monthFromZero")?0:1)];return this.leapYear()&&t===(s.options("monthFromZero")?1:2)&&(o+=1),o},O.fn.year=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_YEAR&&Number(t)<=s.MAX_YEAR?(this._d.setFullYear(Number(t)),this._i.year=!1):this._i.year=Number(t):(this._d.setFullYear(s.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},O.fn.month=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MONTH&&Number(t)<=s.MAX_MONTH?(this._d.setMonth(s.options("monthFromZero")?Number(t):Number(t)-1),this._i.month=!1):this._i.month=Number(t):(this._d.setMonth(s.options("monthFromZero")?s.MIN_MONTH:s.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?s.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},O.fn.day=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_DAY&&Number(t)<=this.dayCount()?(this._d.setDate(Number(t)),this._i.day=!1):this._i.day=Number(t):(this._d.setDate(s.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},O.fn.hours=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_HOURS&&Number(t)<=s.MAX_HOURS?(this._d.setHours(Number(t)),this._i.hours=!1):this._i.hours=Number(t):(this._d.setHours(s.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},O.fn.minutes=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MINUTES&&Number(t)<=s.MAX_MINUTES?(this._d.setMinutes(Number(t)),this._i.minutes=!1):this._i.minutes=Number(t):(this._d.setMinutes(s.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},O.fn.seconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_SECONDS&&Number(t)<=s.MAX_SECONDS?(this._d.setSeconds(Number(t)),this._i.seconds=!1):this._i.seconds=Number(t):(this._d.setSeconds(s.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},O.fn.milliseconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MILLISECONDS&&Number(t)<=s.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(t)),this._i.milliseconds=!1):this._i.milliseconds=Number(t):(this._d.setMilliseconds(s.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},O.fn.week=function(){var t=new Date(this.year(),0,1),o=s(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-t.getTime())/864e5+t.getDay()+1)/7)},O.fn.set=function(t,o,d){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t===e)return this._d=new Date,this;if(t instanceof Date)return this._d=t,this;if(typeof t=="number")return this._d=new Date(t*(s.options("useMilliseconds")?1:1e3)),this;if(typeof t=="object"&&(t instanceof Array?(this.day(s.MIN_DAY),this.year(t[0]),this.month(t[1]),this.day(t[2]),this.hours(t[3]),this.minutes(t[4]),this.seconds(t[5]),this.milliseconds(t[6])):(this.day(s.MIN_DAY),this.year(t.year),this.month(t.month),this.day(t.day),this.hours(t.hours),this.minutes(t.minutes),this.seconds(t.seconds),this.milliseconds(t.milliseconds))),typeof t=="string"){var g,w=[],E,b,V=[],P=0,F=0,U,j,H={},G;if(t===e)return E=a(this,d),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;for(o===e&&(o=s.detectFormat(t));P<o.length;){if(o.charAt(P)==="%"){if(b=o.charAt(P)+o.charAt(P+1),I[b]!==e){switch(U=0,j="",I[b].type){case"number":for(;U<I[b].maxLength&&F+U<t.length&&!isNaN(Number(t.charAt(F+U)));)j+=t.charAt(F+U),U+=1;break;case"word":for(;U<I[b].maxLength&&F+U<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(F+U));)j+=t.charAt(F+U),U+=1;break;case"string":for(;U<I[b].maxLength&&F+U<t.length;)j+=t.charAt(F+U),U+=1;break}if(U<I[b].minLength)return E=a(this,d),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;w.push(b),V.push(j),U-=1,F+=U,P+=1}}else if(t.charAt(F)!==o.charAt(P))return E=a(this,d),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;P+=1,F+=1}for(g in w)w.hasOwnProperty(g)&&I.hasOwnProperty(w[g])&&(G=I[w[g]].parse(V[g]),H={year:G.year!==e?G.year:H.year,month:G.month!==e?G.month:H.month,day:G.day!==e?G.day:H.day,hours:G.hours!==e?G.hours:H.hours,minutes:G.minutes!==e?G.minutes:H.minutes,seconds:G.seconds!==e?G.seconds:H.seconds});this.day(s.MIN_DAY),this.year(H.year),this.month(H.month),this.day(H.day),this.hours(H.hours),this.minutes(H.minutes),this.seconds(H.seconds),this.milliseconds(H.milliseconds)}return this},O.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},O.fn.timestamp=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(s.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):s.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},O.fn.utc=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(s.options("useMilliseconds")?1:1e3)),this):s.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},O.fn.dayOfWeek=function(t){if(t==="long")return B[this._d.getDay()];if(t==="short")return k[this._d.getDay()];if(t===e)return this._d.getDay();if(t===0||t==="Sunday")return this.calc({day:-this.dayOfWeek()});if(t===1||t==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(t===2||t==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(t===3||t==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(t===4||t==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(t===5||t==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(t===6||t==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},O.fn.timezone=function(t){switch(t){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},O.fn.get=function(t){switch(t){case"Date":return new Date(this.year(),this.month()-(s.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds());case"DateUTC":return new Date(Date.UTC(this.year(),this.month()-(s.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()));case"Array":return[this.year(),this.month(),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()];default:return{year:this.year(),month:this.month(),week:this.week(),day:this.day(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds(),utc:this.utc(),dayOfWeek:this.dayOfWeek(),dayOfWeekShort:this.dayOfWeek("short"),dayOfWeekLong:this.dayOfWeek("long"),timestamp:this.timestamp()}}},O.fn.format=function(t){for(var o=0,d="",g;o<t.length;)t.charAt(o)==="%"?(g=t.charAt(o)+t.charAt(o+1),I[g]!==e?(d+=I[g].format(this),o+=1):d+="%"):d+=t.charAt(o),o+=1;return d},O.fn.valid=function(){return this._i.year===!1&&this._i.month===!1&&this._i.day===!1&&this._i.hours===!1&&this._i.minutes===!1&&this._i.seconds===!1&&this._i.milliseconds===!1},O.fn.errors=function(){return this._i},O.fn.between=function(t,o){var d=this.timestamp(),g=t.timestamp();switch(o){case"year":return Math.floor((g-d)/31556952);case"month":return Math.floor((g-d)/2629746);case"day":return Math.floor((g-d)/86400);case"hours":return Math.floor((g-d)/3600);case"minutes":return Math.floor((g-d)/60);case"seconds":return g-d;default:return e}},O.fn.calc=function(t){return t.year!==e&&this._d.setFullYear(this._d.getFullYear()+t.year),t.month!==e&&this._d.setMonth(this._d.getMonth()+t.month),t.day!==e&&this._d.setDate(this._d.getDate()+t.day),t.hours!==e&&this._d.setHours(this._d.getHours()+t.hours),t.minutes!==e&&this._d.setMinutes(this._d.getMinutes()+t.minutes),t.seconds!==e&&this._d.setSeconds(this._d.getSeconds()+t.seconds),t.milliseconds!==e&&this._d.setMilliseconds(this._d.getMilliseconds()+t.milliseconds),this},s=function(t,o,d){return new O(t,o,d)},s.MIN_YEAR=1e3,s.MAX_YEAR=3e3,s.MIN_MONTH=1,s.MAX_MONTH=12,s.MIN_DAY=1,s.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],s.MIN_DAY_OF_WEEK=0,s.MAX_DAY_OF_WEEK=6,s.MIN_HOURS=0,s.MAX_HOURS=23,s.MIN_MINUTES=0,s.MAX_MINUTES=59,s.MIN_SECONDS=0,s.MAX_SECONDS=59,s.MIN_MILLISECONDS=0,s.MAX_MILLISECONDS=999,s.VERSION="0.2.18",s.options=function(t,o){if(t===e)return X;if(X.hasOwnProperty(t)){if(o===e)return X[t];X[t]=o,t==="monthFromZero"&&(s.MIN_MONTH=o?0:1,s.MAX_MONTH=o?11:12)}return e},s.noConflict=function(){return i.tempus=h,s},s.generate=function(t){var o,d,g,w,E,b,V,P;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof O?o=t.dateFrom.utc():o=s(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof O?d=t.dateTo.utc():d=s(t.dateTo,t.formatTo!==e?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?E={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?E={year:t.period==="year"?1:0,month:t.period==="month"?1:0,day:t.period==="day"?1:0,hours:t.period==="hours"?1:0,minutes:t.period==="minutes"?1:0,seconds:t.period==="seconds"?1:0}:typeof t.period=="object"&&(E={year:t.period.year!==e?t.period.year:0,month:t.period.month!==e?t.period.month:0,day:t.period.day!==e?t.period.day:0,hours:t.period.hours!==e?t.period.hours:0,minutes:t.period.minutes!==e?t.period.minutes:0,seconds:t.period.seconds!==e?t.period.seconds:0}),t.groupBy===e?b=t.asObject===!0?{}:[]:(b=[],b.push([]),V=s(o).get()[t.groupBy]),P=function(j,H,G){return t.asObject===!0?t.format!==e?j[s(H).format(t.format)]={}:j[s(H).format("%F %H:%M:%S")]={}:t.format!==e?j.push(G?null:s(H).format(t.format)):j.push(G?null:s(H)),j},t.groupBy!==e&&t.fillNulls){var F={year:E.year?-E.year:e,month:E.month?-E.month:e,day:E.day?-E.day:e,hours:E.hours?-E.hours:e,minutes:E.minutes?-E.minutes:e,seconds:E.seconds?-E.seconds:e,milliseconds:E.milliseconds?-E.milliseconds:e};for(g=s(o).calc(F).utc();s(g).get()[t.groupBy]===V;)P(b[b.length-1],g,!0),g=s(g).calc(F).utc();if(t.groupBy==="week"){var U=s(o).dayOfWeek();for(g=s(o).dayOfWeek(0).utc();b[0].length<U&&g<o;)P(b[b.length-1],g,!0),g=s(g).calc(E).utc()}}for(;o<=d;)t.groupBy===e?P(b,o):s(o).get()[t.groupBy]===V?P(b[b.length-1],o):(b.push([]),P(b[b.length-1],o),V=s(o).get()[t.groupBy]),o=s(o).calc(E).utc();if(t.groupBy!==e&&t.fillNulls)for(w=s(d).calc(E).utc();s(w).get()[t.groupBy]===V;)P(b[b.length-1],w,!0),w=s(w).calc(E).utc();return b},s.monthNames=function(t){switch(t){case"long":return S;default:return D}},s.dayNames=function(t){switch(t){case"long":return B;default:return k}},s.lang=function(t){if(t!==e)A=t,u[A]===e&&(A="en"),S=N(),D=y(),B=p(),k=R();else return A;return e},s.availableLangs=function(){return Object.keys(u)},s.registerFormat=function(t,o,d,g,w,E){I[t]={format:o,parse:d,minLength:g,maxLength:w,type:E}},s.unregisterFormat=function(t){delete I[t]},s.detectFormat=function(t){var o,d,g;return o=c(t,0),o!==""&&(g=10),d=t.charAt(g),(d==="T"||d===" ")&&(o+=d,g+=1),o+=l(t,g),o},f={TempusDate:O},s.classes=function(t,o){if(o===e)return f[t];f[t]=o},s.loadTranslations=function(t){typeof t=="object"?u=t:typeof t=="string"&&J(t,function(o){u=o},function(o){})},A=(m.language||m.systemLanguage||m.userLanguage||"en").substr(0,2).toLowerCase(),u[A]===e&&(A="en"),S=N(),D=y(),B=p(),k=R(),x.exports&&(r=x.exports=s),r.tempus=s}).call(L)})(et,et.exports);var Lt=et.exports;const it=C(Lt);class z{constructor(r){this.callBatch=r,this.result={},this.errors={},this.limit=50,this.canContinue=!0,this.progressCall="",this.limitCall="",this.progressData="",this.progressTimer="",this.progressDelay=100,this.oldPercent="no",this.chunkRate=1,this.totalProgress=0,this.skipList=new Set,this.filterChunkSize=50}getData(r){return(r==null?void 0:r.items)??(r==null?void 0:r.tasks)??(r==null?void 0:r.types)??(r==null?void 0:r.type)??(r==null?void 0:r.fields)??(r==null?void 0:r.workgroups)??r}splitLargeFilters(r,e){const{method:i,params:n}=e;if(!n)return[{key:r,request:e}];const a=n.filter||n.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:r,request:e}];for(const[l,c]of Object.entries(a))if(Array.isArray(c)&&c.length>this.filterChunkSize){const h=[];for(let s=0;s<c.length;s+=this.filterChunkSize){const f=c.slice(s,s+this.filterChunkSize),m=s===0?r:`${r}__chunk_${Math.floor(s/this.filterChunkSize)}`,A={...n};n.filter?(A.filter={...a},A.filter[l]=f):n.FILTER&&(A.FILTER={...a},A.FILTER[l]=f),h.push({key:m,request:{method:i,params:A},originalKey:r,filterKey:l,chunkIndex:Math.floor(s/this.filterChunkSize)})}return h}return[{key:r,request:e}]}mergeSplitResults(r,e){const i=[],n=Object.keys(r).filter(a=>a.startsWith(e)).sort((a,l)=>{const c=a.match(/__chunk_(\d+)$/),h=l.match(/__chunk_(\d+)$/);return c?h?parseInt(c[1])-parseInt(h[1]):1:-1});for(const a of n){const l=r[a];Array.isArray(l)?i.push(...l):l&&i.push(l)}return i}get progressPercent(){let r=0;if(!this.progressData)return{percent:Math.round(r),allCount:0,allTotal:0};let e=0,i=0;return Object.values(this.progressData).forEach(n=>{const{total:a,count:l}=n;e+=a??0,i+=l??0}),e?r=i/e*100*this.chunkRate+this.totalProgress:i===0&&e===0?r=100*this.chunkRate+this.totalProgress:r=100,{percent:Math.round(r),allCount:i,allTotal:e}}setProgressData({key:r,value:e,type:i}){const n=this.getData(e.data()),a=Array.isArray(n)?n.length:0;let l=e.total()||a;i==="count"&&(l=a);let c=1;n&&(c=a),this.progressCall&&(this.progressData||(this.progressData={}),this.progressData[r]&&this.progressData[r].count&&(c+=this.progressData[r].count),this.progressData[r]?this.progressData[r].count=c:this.progressData[r]={total:l,count:c},this.progressTimer||(this.progressTimer=setInterval(()=>{const{percent:h,allCount:s,allTotal:f}=this.progressPercent;(this.oldPercent==="no"||this.oldPercent<this.progressPercent.percent)&&(this.progressCall({data:this.progressData,percent:h,allCount:s,allTotal:f}),this.oldPercent=this.progressPercent.percent),h>=100&&this.clearProgressData()},this.progressDelay)))}delay(){return new Promise(r=>setTimeout(r,500))}callBatchWithTimeout(r,e){return new Promise((i,n)=>{let a=!1;const l=6e4;let c=!1,h=!1,s=!1,f=null,m=null;const A=async(y,p)=>{if(!a){a=!0,f&&clearTimeout(f),m&&clearTimeout(m);try{await Promise.resolve(e(y)),i()}catch(R){console.error(`Error in callBatch callback (attempt ${p}):`,R),n(R)}}},u=async()=>{if(!a){a=!0,f&&clearTimeout(f),m&&clearTimeout(m),console.warn(`Batch request timeout after ${l}ms on both attempts. This may indicate a CORS or network error.`);const y={};Object.keys(r).forEach(p=>{y[p]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 30 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(e(y)),i()}catch(p){console.error("Error in timeout callback:",p),i()}}},N=y=>{try{this.callBatch(r,async p=>{y===1&&!c&&!a?(c=!0,await A(p,1)):y===2&&!s&&!a&&(s=!0,await A(p,2))})}catch(p){a||console.error(`Error calling callBatch (attempt ${y}):`,p)}};N(1),f=setTimeout(async()=>{!c&&!a&&!h&&(console.warn(`First batch request attempt timeout after ${l}ms. Starting second attempt...`),h=!0,N(2),m=setTimeout(async()=>{!c&&!s&&!a&&await u()},l))},l)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.limitCall="",this.oldPercent="no"}async batch(r,e,i){this.progressTimer&&this.clearProgressData(),e&&(this.progressCall=e),i&&(this.limitCall=i),this.canContinue=!0,this.result={},this.errors={};const n={},a={},l={};for(const[f,m]of Object.entries(r)){const A=this.arrayChunk(m);if(!A)continue;const u=this.splitLargeFilters(f,A);if(u.length===1)a[f]=A;else{l[f]=[];for(const N of u)a[N.key]=N.request,l[f].push(N.key)}}this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let c={},h=0;const s=Object.keys(a).length;for(const[f,m]of Object.entries(a)){if(!this.canContinue)break;c[f]=m,(Object.keys(c).length>=50||h+1===s)&&(await this.batchChunk(c),Object.entries(this.result).forEach(([A,u])=>{n[A]=u}),this.totalProgress=Math.round(h/s*100),c={}),h++}for(const[f,m]of Object.entries(l))if(m&&m.length>0){const A=this.mergeSplitResults(n,f);for(const u of m)delete n[u];n[f]=A}return Object.entries(this.errors).length&&(n.errorsList=this.errors),e&&e({percent:100}),Promise.resolve(n)}async batchTotalCount(r,e,i){this.progressTimer&&this.clearProgressData(),e&&(this.progressCall=e),i&&(this.limitCall=i),this.canContinue=!0,this.result={},this.errors={};const n={},a={},l={};for(const[s,f]of Object.entries(r)){const m=this.arrayChunk(f);if(!m)continue;const A=this.splitLargeFilters(s,m);if(A.length===1)a[s]=m;else{l[s]=[];for(const u of A)a[u.key]=u.request,l[s].push(u.key)}}const c=[],h=Object.entries(a);for(let s=0;s<h.length;s+=this.limit){const f=h.slice(s,s+this.limit),m={};for(const[A,u]of f){if(!this.canContinue)break;m[A]=u}Object.keys(m).length>0&&c.push(m)}this.chunkRate=(1/c.length).toFixed(5);for(const[s,f]of Object.entries(c)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(s)/c.length*100),await this.callBatchWithTimeout(f,async m=>{var A,u,N,y,p,R,S;for(const[D,B]of Object.entries(m)){if(!this.canContinue)return;if(B.error()){const O=(u=(A=B.error())==null?void 0:A.ex)==null?void 0:u.error,t=(y=(N=B.error())==null?void 0:N.ex)==null?void 0:y.error_description;this.errors[D]=O&&O.trim()||t&&t.trim()||((p=B.error())==null?void 0:p.toString())||"Неизвестная ошибка",n[D]=0;const o=((S=(R=B.error())==null?void 0:R.ex)==null?void 0:S.error)??"";let d="";const g=f[D];switch(Array.isArray(g)?[d]=g:g!=null&&g.method&&(d=g.method),o){case"OPERATION_TIME_LIMIT":d&&this.skipList.add(d),this.limitCall&&this.limitCall(D);break;case"ACCESS_DENIED":d&&this.skipList.add(d);break;case"TIMEOUT":d&&this.skipList.add(d),this.limitCall&&this.limitCall(D);break}continue}const k=this.getData(B.data()),J=Array.isArray(k)?k.length:0,X=typeof B.total=="function"&&B.total()!==void 0?B.total():J;n[D]=X,this.setProgressData({key:D,value:B,type:"count"})}})}for(const[s,f]of Object.entries(l))if(f&&f.length>0){let m=0;for(const A of f)n[A]!==void 0&&(m+=n[A]||0),delete n[A];n[s]=m}return Object.entries(this.errors).length&&(n.errorsList=this.errors,this.errorLogger()),e&&e({percent:100}),Promise.resolve(n)}arrayChunk(r){let e="",i={};if(Array.isArray(r)?[e]=r:(e=r.method,i=r.params),this.skipList.has(e))return!1;if((e.includes("list")||e==="user.get")&&e!=="task.item.list"){if(!i)i={order:{ID:"ASC",id:"ASC"}};else{e==="tasks.task.list"?(i.order||(i.order={}),i.order.ID="asc"):e==="user.get"?(i.sort||(i.sort="ID"),i.order||(i.order="ASC")):i.order={ID:"ASC",id:"ASC"},Array.isArray(i.select)&&!i.select.includes("ID")&&i.select.push("ID");const n=e==="user.get"?i.FILTER:i.filter;typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.entries(n).forEach(([a,l])=>{(i.start===void 0||i.start!==-1)&&["id","ID"].includes(a)&&(typeof l=="string"||Array.isArray(l)&&l.length<=50)&&(i.start=-1)})}e==="crm.type.list"&&i.order&&delete i.order.ID}if(e==="task.item.list")if(!i)i=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(i[0])&&(i[0]={});const[n,a,l,c]=i;n.ID="ASC",c[0]!==""&&c.includes("ID")||c.push("ID")}return{method:e,params:i}}async batchChunk(r,e){return new Promise(i=>{const n=[];let a;this.callBatchWithTimeout(r,async l=>{var c,h,s,f,m,A,u;for(const[N,y]of Object.entries(l)){if(!this.canContinue)return;if(y.error()){const k=(h=(c=y.error())==null?void 0:c.ex)==null?void 0:h.error,J=(f=(s=y.error())==null?void 0:s.ex)==null?void 0:f.error_description;switch(this.errors[N]=k&&k.trim()||J&&J.trim()||((m=y.error())==null?void 0:m.toString())||"Неизвестная ошибка",a=!0,((u=(A=y.error())==null?void 0:A.ex)==null?void 0:u.error)??""){case"OPERATION_TIME_LIMIT":this.skipList.add(r[N].method),this.limitCall&&this.limitCall(N);break;case"ACCESS_DENIED":this.skipList.add(r[N].method);break;case"TIMEOUT":let X=r[N],O="";Array.isArray(X)?[O]=X:X!=null&&X.method&&(O=X.method),O&&this.skipList.add(O),this.limitCall&&this.limitCall(N);break}}const p=this.getData(y.data()),R=Array.isArray(p)?p.length:0,S=typeof y.total=="function"&&y.total()!==void 0,D=S?y.total():R;e==="count"?this.result[N]?this.result[N]+=R:this.result[N]=D:this.result[N]=p,this.setProgressData({key:N,value:y,type:e});const B=e==="count"?!S&&R===this.limit:D>this.limit&&D>R;if(!this.canContinue||B){let k=r[N];if(Array.isArray(k)){const[J,I={}]=k;k=[J,I]}else{const{method:J,params:I={}}=k;k=[J,I]}n.push([N,k,D])}}a>0&&this.errorLogger(),n.length?await this.batchPayload(n,e).then(()=>i(this.result)):i(this.result)})})}async batchPayload(r,e){const i=new Map,n=(h,s,f,m)=>{let A="ID";this.result[h][this.result[h].length-1].ID||(A="id");let u=`${A}`;if(JSON.stringify(m[1]).toLocaleLowerCase().includes('"id":"desc"')?u="<"+u:u=">"+u,s===1||f.length===0)return{field:u,id:this.result[h][this.result[h].length-1][A]};let y="";const[p,R]=m;return(p==="tasks.task.list"||p==="task.item.list")&&(y="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(p)&&(y="[items]"),p==="crm.type.list"&&(y="[types]"),p==="socialnetwork.api.workgroup.list"&&(y="[workgroups]"),{field:u,id:`$result[${[h,s-1].join("__")}]${y}[49][${A}]`}},a=(h,s)=>{const[f,m]=h;let A=JSON.parse(JSON.stringify(m)),u;if(f==="task.item.list"){A=[...A];const[N,y,p,R]=A;return y[s.field]=s.id,[f,A]}return["user.get"].includes(f)||A.FILTER?(A.FILTER||(A.FILTER={}),u=A.FILTER):(A.filter||(A.filter={}),u=A.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(f)?u[">ID"]=s.id:u[s.field]=s.id,[f,{...A,start:-1}]},l=h=>{Object.entries(h).forEach(([s,f])=>{var u,N,y,p,R,S,D;const[m]=s.split("__"),A=this.getData(f.data());if(Array.isArray(A)&&(e==="count"?this.result[m]+=A.length:this.result[m].push(...A)),f.error()){const B=(N=(u=f.error())==null?void 0:u.ex)==null?void 0:N.error,k=(p=(y=f.error())==null?void 0:y.ex)==null?void 0:p.error_description;this.errors[m]=B&&B.trim()||k&&k.trim()||((R=f.error())==null?void 0:R.toString())||"Неизвестная ошибка";const J=((D=(S=f.error())==null?void 0:S.ex)==null?void 0:D.error)??"",I=i.get(m);switch(J){case"OPERATION_TIME_LIMIT":I&&(this.skipList.add(I),this.limitCall&&this.limitCall(m));break;case"QUERY_LIMIT_EXCEEDED":this.canContinue=!1;break;case"ACCESS_DENIED":I&&this.skipList.add(I);break;case"TIMEOUT":I&&(this.skipList.add(I),this.limitCall&&this.limitCall(m));break}}this.setProgressData({key:m,value:f,type:e})})};let c=[];for await(const[h,s,f]of r){if(!this.canContinue)return;const[m]=s;if(i.set(h,m),this.skipList.has(m))continue;let A=1;for(;f>A*50&&!this.skipList.has(m);){const u=[h,A].join("__"),N=n(h,A,c,s);c.push([u,a(s,N)]),c.length%50===0&&(await this.callBatchWithTimeout(Object.fromEntries(c),y=>{l(y)}),c=[],await this.delay()),A++}}c.length&&(await this.callBatchWithTimeout(Object.fromEntries(c),h=>{l(h)}),await this.delay())}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([r,e])=>{e&&console.log(`[${r}]`,e.toString())}),console.groupEnd()}}class ft{constructor(){Y(this,q,{})}get hash(){return this.createHash(8)}createHash(r){let e="abcdefghijklmnopqrstuvwxyz0123456789",i="";r=r||6;for(let n=0;n<r;n++)i+=e.charAt(Math.floor(Math.random()*e.length));return i}actionFilter({keyTimer:r,duration:e=10,action:i}){T(this,q)[r]&&(clearTimeout(T(this,q)[r]),T(this,q)[r]=null),i&&(T(this,q)[r]=setTimeout(()=>{i()},e))}async noSleep(){let r=document.createElement("video");r.classList.add("no-sleep"),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.addEventListener("loadeddata",()=>{r.style.position="fixed",r.style.left="-9999px",document.querySelector("body").append(r),r.play().catch(e=>{console.warn("noSleep: autoplay prevented",e)})}),r.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{r.play().catch(e=>{console.warn("noSleep: replay prevented",e)})}})}),r.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(r,e){let i=new Blob([JSON.stringify(r)],{type:"application/json"}),n=URL.createObjectURL(i),a=document.createElement("a");a.style.display="none",a.href=n,a.download=`${e}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(n)},200)}}q=new WeakMap;const mt=new ft;class yt{constructor(){Y(this,at);Y(this,nt);Y(this,At);Y(this,ct);Y(this,ht);Y(this,Q,"logger");Y(this,Z,!1);Y(this,$,new Map);Y(this,rt,{});Y(this,W,null);Y(this,tt,!1);Y(this,st,!1);M(this,"periodClear",3);K(this,at,Nt).call(this)}async init(){try{let r=new z(BX24.callBatch),{entityList:e}=await r.batch({entityList:{method:"entity.get"}});if(e&&Array.isArray(e))if(e.find(n=>n.ENTITY==T(this,Q)))v(this,Z,!0);else{let{entityAdd:n}=await r.batch({entityAdd:{method:"entity.add",params:{ENTITY:T(this,Q),NAME:T(this,Q),ACCESS:{AU:"X"}}}});n&&v(this,Z,!0)}return K(this,ct,_t).call(this).catch(i=>{console.error("Ошибка при проверке периода очистки:",i)}),T(this,Z)}catch(r){return console.error("Ошибка при инициализации логера:",r),!1}}start({type:r,data:e}){if(!T(this,Z))return K(this,nt,gt).call(this,"entity"),null;if(!r||!e)return console.error("Невалидные данные для логирования:",{type:r,data:e}),null;const i=mt.hash,n={type:r,data:e,userInfo:T(this,rt),errorList:{},status:"",answer:null,date:new Date().getTime()};return T(this,$).set(i,n),v(this,st,!0),i}async stop({key:r,errorList:e,status:i,answer:n}){var l;if(!T(this,st))return;if(!T(this,Z)){K(this,nt,gt).call(this,"entity");return}let a=T(this,$).get(r);if(!a){console.error(`Не найдены данные логирования для ключа: ${r}`);return}e&&(a.errorList=e),i&&(a.status=i),n&&(a.answer=n),await K(this,At,Ot).call(this),(l=a==null?void 0:a.data)!=null&&l.updateList&&v(this,tt,!0),v(this,st,!1)}async getEntityList(r){var e;try{if((e=T(this,W))!=null&&e.length&&!T(this,tt))return T(this,W);let i=new z(BX24.callBatch),{entityList:n}=await i.batch({entityList:{method:"entity.item.get",params:{ENTITY:T(this,Q),SORT:{ID:"DESC"}}}},r);return!n||!Array.isArray(n)?(console.warn("Получен невалидный список записей"),[]):(n=n.map(a=>{try{const{ID:l,DATE_CREATE:c,DETAIL_TEXT:h}=a;return{...JSON.parse(h),id:l,dateCreate:c}}catch(l){return console.error(`Ошибка парсинга записи ${a.ID}:`,l),null}}).filter(a=>a!==null),v(this,tt,!1),v(this,W,n),n)}catch(i){return console.error("Ошибка при получении списка записей:",i),[]}}async downAllEntityJson(){try{if(T(this,W)||await this.getEntityList(),!T(this,W)||T(this,W).length===0)return console.warn("Нет данных для выгрузки"),!1;let r=it().format("%Y-%m-%d");return mt.downloadFileJson(T(this,W),`sdklogger-entity-data__${r}`),!0}catch(r){return console.error("Ошибка при выгрузке данных в JSON:",r),!1}}}Q=new WeakMap,Z=new WeakMap,$=new WeakMap,rt=new WeakMap,W=new WeakMap,tt=new WeakMap,st=new WeakMap,at=new WeakSet,Nt=async function(){try{const r=new z(BX24.callBatch),e=BX24.isAdmin(),{curUser:i}=await r.batch({curUser:{method:"user.current"}});v(this,rt,{isAdmin:e,curUser:i})}catch(r){console.error("Ошибка при получении информации о пользователе:",r),v(this,rt,{isAdmin:!1,curUser:null})}},nt=new WeakSet,gt=function(r){r=="entity"&&mt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},At=new WeakSet,Ot=async function(){try{let r={},e=new z(BX24.callBatch);for(let[i,n]of T(this,$).entries())if(n.status){const a=JSON.stringify(n);r[i]={method:"entity.item.add",params:{ENTITY:T(this,Q),NAME:T(this,Q),DETAIL_TEXT:a}}}if(Object.keys(r).length){let i=await e.batch(r),{errors:n}=e;for(let[a,l]of Object.entries({...i,...n}))T(this,$).delete(a);return!0}return!1}catch(r){return console.error("Ошибка при добавлении записей в хранилище:",r),!1}},ct=new WeakSet,_t=async function(){try{let r=new z(BX24.callBatch),{serverTime:e}=await r.batch({serverTime:{method:"server.time"}});if(!e){console.error("Не удалось получить время сервера");return}if(T(this,W)||await this.getEntityList(),!T(this,W)||T(this,W).length===0)return;let i=T(this,W).filter(n=>{try{let{dateCreate:a}=n;return a?it(new Date(a)).between(it(new Date(e)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});i.length>0&&(console.log(`Найдено ${i.length} записей для очистки (старше ${this.periodClear} месяцев)`),await K(this,ht,Et).call(this,i))}catch(r){console.error("Ошибка при проверке периода очистки:",r)}},ht=new WeakSet,Et=async function(r){try{if(!r||r.length===0)return!1;let e=new z(BX24.callBatch),i=r.filter(a=>a&&a.id).map(a=>{let{id:l}=a;return{method:"entity.item.delete",params:{ENTITY:T(this,Q),ID:l}}});if(i.length===0)return!1;const n=await e.batch(i);return console.log(`Успешно удалено ${i.length} записей`),v(this,tt,!0),n}catch(e){return console.error("Ошибка при очистке устаревших записей:",e),!1}};class bt{constructor(r){Y(this,lt);Y(this,ut);Y(this,ot);M(this,"domain","");M(this,"isAdmin",!1);M(this,"appInfo",null);M(this,"appConst",null);M(this,"userInfo",null);M(this,"placeData",null);M(this,"placeInfo",null);M(this,"logger",!1);this.appConst=r}init(){return new Promise((r,e)=>{let n=setInterval(()=>{window.BX24&&BX24.init(async()=>{console.info("init BX24"),clearInterval(n),clearTimeout(a),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info(),this.logger?(this.logger=new yt,await this.logger.init()):this.logger={start:()=>{},stop:()=>{},getEntityList:()=>{}};const[l,c]=await Promise.all([K(this,lt,Tt).call(this),K(this,ut,Rt).call(this)]);this.appInfo=l,this.userInfo=c;let h=new ft;try{h.noSleep()}catch(s){console.warn("Failed to initialize noSleep:",s)}r(!0)})},100);const a=setTimeout(()=>{clearInterval(n);const l=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(l),e(l)},3e4)})}userOption(r,e){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.userOption.set(r,e):BX24.userOption.get(r)}appOption(r,e){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.appOption.set(r,e):BX24.appOption.get(r)}async call({method:r,params:e,updateList:i}){let n;if(i&&(n=this.logger.start({type:"call",data:{method:r,params:e,updateList:i}})),e||(e={}),typeof BX24>"u"||!BX24.callMethod){const a=new Error("BX24 is not initialized");throw console.error(a),a}return new Promise((a,l)=>{BX24.callMethod(r,e,async c=>{let h={};if(c!=null&&c.answer)for(let[s,f]of Object.entries(c.answer))s!=="result"&&f&&(h[s]=f);if(c.error()){let s=c.error();if(console.error(s),n)try{await this.logger.stop({answer:h,key:n,status:"fail",errorList:{0:s.toString()}})}catch(f){console.error("Logger error:",f)}a(!1)}else{let s=c.data();if(s!=null&&s.items&&(s=s.items),n)try{await this.logger.stop({answer:h,key:n,status:"success"})}catch(f){console.error("Logger error:",f)}a(s)}})})}async batch(r,e,{errorCall:i,limitCommandSerial:n,updateList:a,limitCall:l}={}){if(typeof BX24>"u"||!BX24.callBatch){const s=new Error("BX24 is not initialized");return console.error(s),!1}let c=new z(BX24.callBatch),h;a&&(h=this.logger.start({type:"batch",data:{commandList:r,updateList:a}})),n&&console.warn("limitCommandSerial is deprecated and not used in current Batch implementation");try{let s=await c.batch(r,e,l);const f=K(this,ot,pt).call(this,c,s,r,a);if(Object.keys(f).length){if(i&&i(f),h)try{await this.logger.stop({key:h,status:"fail",errorList:f})}catch(m){console.error("Logger error:",m)}}else if(h)try{await this.logger.stop({key:h,status:"success"})}catch(m){console.error("Logger error:",m)}return s}catch(s){if(h)try{await this.logger.stop({key:h,status:"fail-runtime",errorList:{0:s==null?void 0:s.toString()}})}catch(f){console.error("Logger error:",f)}return console.error(s),!1}}async batchTotalCount(r,e,{errorCall:i,updateList:n,limitCall:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const h=new Error("BX24 is not initialized");return console.error(h),!1}let l=new z(BX24.callBatch),c;n&&(c=this.logger.start({type:"batch-total-count",data:{commandList:r}}));try{let h=await l.batchTotalCount(r,e,a);const s=K(this,ot,pt).call(this,l,h,r,n);if(Object.keys(s).length){if(i&&i(s),c)try{await this.logger.stop({key:c,status:"fail",errorList:s})}catch(f){console.error("Logger error:",f)}}else if(c)try{await this.logger.stop({key:c,status:"success"})}catch(f){console.error("Logger error:",f)}return h}catch(h){if(c)try{await this.logger.stop({key:c,status:"fail-runtime",errorList:{0:h==null?void 0:h.toString()}})}catch(s){console.error("Logger error:",s)}return console.error(h),!1}}async getPlacement(){return await this.call({method:"placement.get"}).then(r=>(this.placeData||(this.placeData=r),r))}async placementBind(r,e=!0){var f;if(!this.isAdmin)return;e&&await this.placementCheck();let i=[];if(Array.isArray(r)?i=r.map(m=>typeof m=="string"?{placement:m}:m):typeof r=="string"?i=[{placement:r}]:i=[r],i=i.filter(m=>m.placement!=="PAGE_BACKGROUND_WORKER"&&m.placement!=="PAGE_BACKGROUND_WORKER_ALL"),this.placeData=await this.getPlacement(),!this.placeData)return;const{appName:n,pathApp:a}=this.appConst;let l=n;this.domain==="szdl.bitrix24.ru"&&((f=this.appInfo)!=null&&f.ID)&&(l=`${n}: #${this.appInfo.ID}`);const c=l.replace(" CRM",""),h={},s=[];for(let m=0;m<i.length;m++){const u=i[m].placement,N=a;if(this.placeData.find(S=>S.placement===u&&S.handler===N))continue;const p=this.placeData.find(S=>S.placement===u&&S.handler!==N);p&&s.push({placement:u,handler:p.handler});const R={PLACEMENT:u,HANDLER:N,LANG_ALL:{ru:{TITLE:u==="USER_PROFILE_TOOLBAR"?c:l}},OPTIONS:{errorHandlerUrl:N}};h[`bind_${m}`]={method:"placement.bind",params:R}}s.length>0&&await this.placementUnBind(s),Object.keys(h).length>0&&await this.batch(h),Object.keys(h).length>0&&(this.placeData=await this.getPlacement(),Object.values(h).forEach(m=>{console.log("Приложение успешно встроено в",m.params.PLACEMENT)}))}async placementUnBind(r){let e=[];Array.isArray(r)?e=r.map(n=>typeof n=="string"?{placement:n}:n):typeof r=="string"?e=[{placement:r}]:e=[r],e=e.filter(n=>n.placement!=="PAGE_BACKGROUND_WORKER"&&n.placement!=="PAGE_BACKGROUND_WORKER_ALL");const i={};for(let n=0;n<e.length;n++){const a=e[n],l=a.placement,c=a.handler,h={PLACEMENT:l};c&&(h.HANDLER=c),i[`unbind_${n}`]={method:"placement.unbind",params:h}}Object.keys(i).length>0&&(await this.batch(i),e.forEach(n=>{console.log("Встройка отвязана",n.placement)}))}async placementCheck(){if(this.placeData=await this.getPlacement(),!this.placeData)return;const{pathApp:r}=this.appConst,e=[],i=[];for(const n of this.placeData){if(n.placement==="PAGE_BACKGROUND_WORKER"||!n.handler||n.handler.includes(r))continue;const{placement:a,handler:l,userId:c}=n;e.push({placement:a,handler:l}),i.push({placement:a,userId:c})}e.length>0&&await this.placementUnBind(e),i.length>0&&await this.placementBind(i,!1)}getBotList(){return this.call({method:"imbot.bot.list",params:{}}).then(r=>{let e=Object.values(r);return console.log("chat-bot list:",e),e})}regBot({code:r,type:e,name:i}){const{appName:n,pathApp:a,chatBotLogo:l}=this.appConst,c=this.appInfo.ID;return this.call({method:"imbot.register",params:{CODE:r??this.appInfo.CODE,TYPE:e??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${i??n} - бот #${c}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:it().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:l??""}}}).then(h=>(console.log("Чат-бот добавлен",h),h))}unRegBot(r){return this.call({method:"imbot.unregister",params:{BOT_ID:r}}).then(e=>(console.log("чат-бот удален",e),e))}getLoggerList(r){return this.logger.getEntityList(r)}}lt=new WeakSet,Tt=function(){return this.call({method:"app.info"})},ut=new WeakSet,Rt=function(){return this.call({method:"user.current"})},ot=new WeakSet,pt=function(r,e,i,n){let a={...r.errors};if(Object.values(r.errors).some(c=>{if(typeof c!="string")return!1;const h=c.toUpperCase();return h==="TIMEOUT"||h==="OPERATION_TIME_LIMIT"||h.includes("TIMEOUT")||h.includes("OPERATION_TIME_LIMIT")})&&n){const c=e?Object.keys(e).filter(m=>m!=="errorsList"):[],h=new Set(Object.keys(r.errors||{})),s=new Set;if(e){for(const m of c)if(!h.has(m)){const A=e[m];A!=null&&s.add(m)}}const f=Object.values(r.errors).find(m=>{if(typeof m!="string")return!1;const A=m.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const m of Object.keys(i))!s.has(m)&&!r.errors[m]&&(a[m]=f||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a};class St{constructor(r){M(this,"entityName","tabs");M(this,"maxTabs",20);M(this,"tabList",[]);M(this,"id",0);M(this,"hasStarted",!1);M(this,"heartbeat");M(this,"runHeartbeat");M(this,"random",this.getRandomNum());M(this,"activeMaxPause",5*60*1e3+this.random);M(this,"quickCleanupThreshold",2*60*1e3);M(this,"pollInterval",(60+this.random)*1e3);M(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);M(this,"continueCondition");M(this,"defaultContinueBackground",()=>!0);var l,c,h;if(!r){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:e,bx:i,users:n,continueBackground:a}=r;this.bx=i,this.appInit=e,this.users=n,this.appPath=((l=i==null?void 0:i.appConst)==null?void 0:l.pathApp)??"",this.appName=((c=i==null?void 0:i.appConst)==null?void 0:c.appName)??"",this.appCodeName=((h=i==null?void 0:i.appConst)==null?void 0:h.appCodeName)??"",this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("BackgroundWorker: appInit не передан");return}if(!this.bx){console.error("BackgroundWorker: bx не передан");return}if(this.isAppPage()){console.log("BackgroundWorker: Страница приложения, фоновый воркер не запускается");return}await this.checkPlacementType()&&await this.continueBackground()&&(await this.checkEntity(),await this.refreshTabs(!0),await this.ensureTabRegistered(),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(e=>{console.error("BackgroundWorker: backgroundTick failed",e)})},this.pollInterval),await this.backgroundTick())}async backgroundTick(){if(!await this.continueBackground()){this.stopTimers(),console.log("BackgroundWorker: Остановка backgroundTick - условие не выполнено");return}await this.refreshTabs(!0),await this.ensureTabRegistered();const e=this.selectLeaderId(),i=e&&+this.id==+e;await this.updateTabState(i),i&&!this.hasStarted&&(this.hasStarted=!0,await this.runAsLeader())}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var r;if(typeof BX24>"u"||!((r=BX24.placement)!=null&&r.info))return!1;try{const e=BX24.placement.info(),i=e==null?void 0:e.placement,n=(e==null?void 0:e.options)||{},a=(n==null?void 0:n.URI)||"",l=i==="PAGE_BACKGROUND_WORKER"||(n==null?void 0:n.ID)==="PAGE_BACKGROUND_WORKER",c=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!l||c}catch{return!1}}async checkEntity(){var i;const r=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((i=r==null?void 0:r.find)==null?void 0:i.call(r,n=>n.ENTITY===this.entityName))||await this.safeCall(()=>this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}}))}async getTabs(){const r=await this.safeCall(()=>{var e;return this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:(e=this.bx.userInfo)==null?void 0:e.ID},SORT:{DATE_CREATE:"DESC"}}})});return!Array.isArray(r)||!r.length?[]:r.map(e=>{if(!e)return{id:void 0,data:void 0};try{const i=JSON.parse(e.DETAIL_TEXT);return{id:+e.ID||0,data:i}}catch(i){return console.log("BackgroundWorker: parse tab error",i),{id:+e.ID||0,data:void 0}}})}async ensureTabRegistered(){if(this.id)return+this.id||0;if(this.tabList.length>=this.maxTabs&&await this.refreshTabs(!0,this.quickCleanupThreshold),this.tabList.length>=this.maxTabs)return console.log("BackgroundWorker: Достигнут лимит вкладок даже после быстрой очистки, не регистрируемся"),0;const r={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId},e=await this.safeCall(()=>{var i;return this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(i=this.bx.userInfo)==null?void 0:i.ID,DETAIL_TEXT:JSON.stringify(r)}})})||0;return this.id=+e||0,this.id}async updateTabState(r){if(!this.id)return;const e={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:r,sessionId:this.sessionId};await this.safeCall(()=>{var i;return this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(i=this.bx.userInfo)==null?void 0:i.ID,DETAIL_TEXT:JSON.stringify(e)}})})}async deleteTabs(r=[]){if(!r.length)return;const e=r.map(i=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:i.id}}));await this.safeCall(()=>this.bx.batch(e))}getRandomNum(){const r=Math.round(Number(Math.random().toFixed(2))*30);return Math.round(Math.random())?r:-r}async checkPlacementType(){var r;try{const e=await this.safeCall(()=>this.bx.getPlacement());if(!e||!Array.isArray(e))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((r=this.bx.userInfo)==null?void 0:r.ID)??0),n=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),a=!n;if(!i)return!0;let l=!1;for(const c of e){if(c.placement!=="PAGE_BACKGROUND_WORKER"||!(c.userId||c.handler&&c.handler.includes("USER_ID=")))continue;const s=c.userId||(c.handler?this.extractUserIdFromHandler(c.handler):null);if(s&&+s===i){l=!0;break}}return n?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):a&&l?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(e){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",e),!0}}isIndividualPlacement(r){return!r||typeof r!="string"?!1:r.includes("USER_ID=")}extractUserIdFromHandler(r){if(!r||typeof r!="string")return null;const e=r.match(/USER_ID=(\d+)/);return e?+e[1]:null}async continueBackground(){try{const e=!!await Promise.resolve(this.continueCondition(this));return console.log(e?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),e}catch(r){return console.error("BackgroundWorker: Ошибка в continueCondition",r),!1}}async refreshTabs(r=!1,e=this.activeMaxPause){const i=[],n=[],a=Date.now(),l=await this.getTabs();for(const c of l){if(!(c!=null&&c.data)){i.push(c);continue}if(a-new Date(c.data.lastActive||0).getTime()>e){i.push(c);continue}n.push(c)}return r&&i.length&&await this.deleteTabs(i),this.tabList=n,n}selectLeaderId(){var e;return this.tabList.length&&+((e=[...this.tabList].sort((i,n)=>{var c,h,s,f;const a=new Date(((c=i.data)==null?void 0:c.createdAt)||((h=i.data)==null?void 0:h.lastActive)||0).getTime(),l=new Date(((s=n.data)==null?void 0:s.createdAt)||((f=n.data)==null?void 0:f.lastActive)||0).getTime();return a===l?(+i.id||0)-(+n.id||0):a-l})[0])==null?void 0:e.id)||0}async runAsLeader(){this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(r=>console.error("BackgroundWorker: heartbeat update failed",r))},Math.max(20*1e3,Math.floor(this.pollInterval/2)));try{await this.appInit()}catch(r){console.error("BackgroundWorker: appInit failed",r)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)}async setBackgroundWorkerAll(){var N,y;if(!((N=this.bx)!=null&&N.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(y=this.users)!=null&&y.length||await this.getEntityData();const r=await this.safeCall(()=>this.bx.getPlacement()),e=new Map;let i=null;(r||[]).forEach(p=>{if(p.placement!=="PAGE_BACKGROUND_WORKER")return;if(p.userId||p.handler&&p.handler.includes("USER_ID=")){const S=p.userId||(p.handler?this.extractUserIdFromHandler(p.handler):null);S&&e.set(+S,p)}else i=p});const n=await this.resolveAdmins(),a=await this.getEligibleUsersForBackgroundWorker(n);a.sort((p,R)=>{const S=p.LAST_LOGIN?new Date(p.LAST_LOGIN):new Date(0);return(R.LAST_LOGIN?new Date(R.LAST_LOGIN):new Date(0))-S});const l=10,h=a.slice(0,l).filter(p=>!e.has(+p.ID)),s=[];for(const[p]of e){const R=+p||0;a.find(D=>+D.ID===R)||s.push(R)}const f=[];for(const p of s)this.appPath&&f.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${p}/`}});const m=i&&h.length>0;m&&this.appPath&&f.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:i.handler||`${this.appPath}`}});for(const p of h)this.appPath&&f.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${p.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}?USER_ID=${p.ID}/`},USER_ID:p.ID}});(!i||m)&&this.appPath&&f.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}`}}});const A=f.filter(p=>p.method==="placement.unbind"),u=f.filter(p=>p.method==="placement.bind");A.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(A.map((p,R)=>[`unbind_${R}`,p])))),u.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(u.map((p,R)=>[`bind_${R}`,p])))),f.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var r,e;try{const i=+(((r=this.bx.userInfo)==null?void 0:r.ID)??0),n=!!((e=this.bx)!=null&&e.isAdmin),a=await this.getAdminsList()||[];if(!n){if(i&&a.includes(+i)){const h=a.filter(s=>+s!=+i);return await this.saveAdminsList(h),h}return a}const l=new Set([...a||[]]);i&&l.add(+i);const c=[...l].filter(Boolean);return await this.saveAdminsList(c),c}catch(i){return console.error("BackgroundWorker: resolveAdmins error",i),[]}}async getEligibleUsersForBackgroundWorker(r=[]){const e=(this.users??[]).filter(n=>n.ACTIVE==="Y"||n.ACTIVE===!0),i=r.map(n=>+n||0).filter(Boolean);return e.filter(n=>i.includes(+n.ID||0))}async saveAdminsList(r=[]){try{BX24.appOption.set("adminsList",JSON.stringify(r))}catch(e){console.error("BackgroundWorker: saveAdminsList error",e)}}async getAdminsList(){try{const r=BX24.appOption.get("adminsList"),e=r?JSON.parse(r):[];return Array.isArray(e)?e.map(i=>+i||0).filter(Boolean):[]}catch(r){return console.error("BackgroundWorker: getAdminsList error",r),[]}}async getEntityData(){const r={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:e}=await this.safeCall(()=>this.bx.batch(r).then(i=>i?(Array.isArray(i.users)||(i.users=[]),i):{users:[]}));this.users=e}async ensureAdminPlacements(){var r,e;(r=this.bx)!=null&&r.isAdmin&&((e=this.users)!=null&&e.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(r=500,e){return new Promise(i=>{setTimeout(()=>{e&&e(),i(!0)},r)})}async safeCall(r){try{return await r()}catch(e){console.error("BackgroundWorker: safeCall error",e);return}}}_.BackgroundWorker=St,_.Batch=z,_.BxBoot=bt,_.BxHelper=ft,_.BxLogger=yt,_.tempus=it,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"})});
1
+ var ge=Object.defineProperty;var ye=(k,B,P)=>B in k?ge(k,B,{enumerable:!0,configurable:!0,writable:!0,value:P}):k[B]=P;var U=(k,B,P)=>(ye(k,typeof B!="symbol"?B+"":B,P),P),xt=(k,B,P)=>{if(!B.has(k))throw TypeError("Cannot "+P)};var S=(k,B,P)=>(xt(k,B,"read from private field"),P?P.call(k):B.get(k)),D=(k,B,P)=>{if(B.has(k))throw TypeError("Cannot add the same private member more than once");B instanceof WeakSet?B.add(k):B.set(k,P)},v=(k,B,P,ot)=>(xt(k,B,"write to private field"),ot?ot.call(k,P):B.set(k,P),P);var E=(k,B,P)=>(xt(k,B,"access private method"),P);(function(k,B){typeof exports=="object"&&typeof module<"u"?B(exports):typeof define=="function"&&define.amd?define(["exports"],B):(k=typeof globalThis<"u"?globalThis:k||self,B(k["szdl-utils-kit"]={}))})(this,function(k){var Ot,Zt,_t,Tt,Et,Lt,at,Ht,bt,Vt,Rt,$t,Z,lt,tt,yt,et,pt,St,te,ut,Ft,rt,q,V,st,At,j,it,ct,It,ee,ft,Xt,Mt,re,Dt,se,kt,ie,nt,Nt,Bt,ne,wt,oe,mt,jt,dt,Jt,Ct,ae,gt,Kt;"use strict";var B=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function P(T){return T&&T.__esModule&&Object.prototype.hasOwnProperty.call(T,"default")?T.default:T}var ot={exports:{}};(function(T,e){(function(r){Array.prototype.indexOf||(Array.prototype.indexOf=function(t,o){var d,g;for(d=o||0,g=this.length;d<g;d+=1)if(this[d]===t)return d;return-1});var s=this,i=function(t,o){for(var d=t.toString();d.length<o;)d="0"+d;return d},a=function(t,o){return o!==r?(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):r},l=function(t,o){var d,g="";return d=t.slice(o,o+1),d!==""&&!isNaN(Number(d))&&(g+="%H"),d=t.charAt(o+2),d!==""&&d===":"&&(g+=d),d=t.slice(o+3,o+4),d!==""&&!isNaN(Number(d))&&(g+="%M"),d=t.charAt(o+5),d!==""&&d===":"&&(g+=d),d=t.slice(o+6,o+7),d!==""&&!isNaN(Number(d))&&(g+="%S"),g},A=function(t,o){var d,g=[t.slice(o,o+1),t.charAt(o+2),t.slice(o+3,o+4),t.charAt(o+5),t.slice(o+6,o+9)],C;return!isNaN(Number(g[0]))&&!isNaN(Number(g[2]))&&!isNaN(Number(g[4]))?(g[1]==="."&&g[3]==="."?d="%d.%m.%Y":g[1]==="-"&&g[3]==="-"?d="%m-%d-%Y":g[1]==="/"&&g[3]==="/"&&(d="%m/%d/%Y"),d):(C=[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(C[0]))&&!isNaN(Number(C[2]))&&!isNaN(Number(C[4]))?(C[1]==="-"&&C[3]==="-"&&(d="%Y-%m-%d"),d):"")},h=s.tempus,n,u,m=s.navigator||{},c="en",f={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[f[c].JANUARY_LONG,f[c].FEBRUARY_LONG,f[c].MARCH_LONG,f[c].APRIL_LONG,f[c].MAY_LONG,f[c].JUNE_LONG,f[c].JULY_LONG,f[c].AUGUST_LONG,f[c].SEPTEMBER_LONG,f[c].OCTOBER_LONG,f[c].NOVEMBER_LONG,f[c].DECEMBER_LONG]},_=function(){return[f[c].JANUARY_SHORT,f[c].FEBRUARY_SHORT,f[c].MARCH_SHORT,f[c].APRIL_SHORT,f[c].MAY_SHORT,f[c].JUNE_SHORT,f[c].JULY_SHORT,f[c].AUGUST_SHORT,f[c].SEPTEMBER_SHORT,f[c].OCTOBER_SHORT,f[c].NOVEMBER_SHORT,f[c].DECEMBER_SHORT]},O=function(){return[f[c].SUNDAY_LONG,f[c].MONDAY_LONG,f[c].TUESDAY_LONG,f[c].WEDNESDAY_LONG,f[c].THURSDAY_LONG,f[c].FRIDAY_LONG,f[c].SATURDAY_LONG]},b=function(){return[f[c].SUNDAY_SHORT,f[c].MONDAY_SHORT,f[c].TUESDAY_SHORT,f[c].WEDNESDAY_SHORT,f[c].THURSDAY_SHORT,f[c].FRIDAY_SHORT,f[c].SATURDAY_SHORT]},p,y,L,I,Y=function(t,o,d){var g;s.XMLHttpRequest?g=new XMLHttpRequest:g=new ActiveXObject("Microsoft.XMLHTTP"),g.onreadystatechange=function(){g.readyState===4&&(g.status===200?o&&(s.JSON===r?alert(`Please, include json2 into your project if you want use old browsers!
2
+ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(g.responseText))):d&&d(g))},g.open("GET",t,!1),g.send()},w={"%d":{format:function(t){return i(t.day()||n.MIN_DAY,2)},parse:function(t){var o=Number(t);return{day:isNaN(o)?r: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)?r: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)?r: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 I[o!==r?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var o=t.dayOfWeek();return L[o!==r?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 y[o!==r?o:n.MIN_MONTH]},parse:function(t){var o=n.monthNames().indexOf(t)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:r}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var o=n.options("monthFromZero")?t.month():t.month()-1;return p[o!==r?o:n.MIN_MONTH]},parse:function(t){var o=n.monthNames(!0).indexOf(t)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:r}},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)?r: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)?r: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)?r: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)),d=Number(t.slice(5,7)),g=Number(t.slice(8,10));return{year:o,month:d,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return 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)),d=Number(t.slice(3,5)),g=Number(t.slice(6,10));return{year:g,month:o,day:d}},minLength:10,maxLength:10,type:"string"}},G={useMilliseconds:!1,monthFromZero:!1},M;M=function(t,o,d){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t!==r&&this.set(t,o,d),this},M.fn=M.prototype,M.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},M.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},M.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},M.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},M.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},M.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},M.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},M.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},M.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)},M.fn.set=function(t,o,d){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t===r)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,C=[],R,H,$=[],X=0,J=0,W,K,x={},F;if(t===r)return R=a(this,d),R===r&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),R;for(o===r&&(o=n.detectFormat(t));X<o.length;){if(o.charAt(X)==="%"){if(H=o.charAt(X)+o.charAt(X+1),w[H]!==r){switch(W=0,K="",w[H].type){case"number":for(;W<w[H].maxLength&&J+W<t.length&&!isNaN(Number(t.charAt(J+W)));)K+=t.charAt(J+W),W+=1;break;case"word":for(;W<w[H].maxLength&&J+W<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(J+W));)K+=t.charAt(J+W),W+=1;break;case"string":for(;W<w[H].maxLength&&J+W<t.length;)K+=t.charAt(J+W),W+=1;break}if(W<w[H].minLength)return R=a(this,d),R===r&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),R;C.push(H),$.push(K),W-=1,J+=W,X+=1}}else if(t.charAt(J)!==o.charAt(X))return R=a(this,d),R===r&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),R;X+=1,J+=1}for(g in C)C.hasOwnProperty(g)&&w.hasOwnProperty(C[g])&&(F=w[C[g]].parse($[g]),x={year:F.year!==r?F.year:x.year,month:F.month!==r?F.month:x.month,day:F.day!==r?F.day:x.day,hours:F.hours!==r?F.hours:x.hours,minutes:F.minutes!==r?F.minutes:x.minutes,seconds:F.seconds!==r?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},M.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},M.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},M.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)},M.fn.dayOfWeek=function(t){if(t==="long")return L[this._d.getDay()];if(t==="short")return I[this._d.getDay()];if(t===r)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()})},M.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}},M.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()}}},M.fn.format=function(t){for(var o=0,d="",g;o<t.length;)t.charAt(o)==="%"?(g=t.charAt(o)+t.charAt(o+1),w[g]!==r?(d+=w[g].format(this),o+=1):d+="%"):d+=t.charAt(o),o+=1;return d},M.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},M.fn.errors=function(){return this._i},M.fn.between=function(t,o){var d=this.timestamp(),g=t.timestamp();switch(o){case"year":return Math.floor((g-d)/31556952);case"month":return Math.floor((g-d)/2629746);case"day":return Math.floor((g-d)/86400);case"hours":return Math.floor((g-d)/3600);case"minutes":return Math.floor((g-d)/60);case"seconds":return g-d;default:return r}},M.fn.calc=function(t){return t.year!==r&&this._d.setFullYear(this._d.getFullYear()+t.year),t.month!==r&&this._d.setMonth(this._d.getMonth()+t.month),t.day!==r&&this._d.setDate(this._d.getDate()+t.day),t.hours!==r&&this._d.setHours(this._d.getHours()+t.hours),t.minutes!==r&&this._d.setMinutes(this._d.getMinutes()+t.minutes),t.seconds!==r&&this._d.setSeconds(this._d.getSeconds()+t.seconds),t.milliseconds!==r&&this._d.setMilliseconds(this._d.getMilliseconds()+t.milliseconds),this},n=function(t,o,d){return new M(t,o,d)},n.MIN_YEAR=1e3,n.MAX_YEAR=3e3,n.MIN_MONTH=1,n.MAX_MONTH=12,n.MIN_DAY=1,n.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],n.MIN_DAY_OF_WEEK=0,n.MAX_DAY_OF_WEEK=6,n.MIN_HOURS=0,n.MAX_HOURS=23,n.MIN_MINUTES=0,n.MAX_MINUTES=59,n.MIN_SECONDS=0,n.MAX_SECONDS=59,n.MIN_MILLISECONDS=0,n.MAX_MILLISECONDS=999,n.VERSION="0.2.18",n.options=function(t,o){if(t===r)return G;if(G.hasOwnProperty(t)){if(o===r)return G[t];G[t]=o,t==="monthFromZero"&&(n.MIN_MONTH=o?0:1,n.MAX_MONTH=o?11:12)}return r},n.noConflict=function(){return s.tempus=h,n},n.generate=function(t){var o,d,g,C,R,H,$,X;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof M?o=t.dateFrom.utc():o=n(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof M?d=t.dateTo.utc():d=n(t.dateTo,t.formatTo!==r?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?R={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?R={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"&&(R={year:t.period.year!==r?t.period.year:0,month:t.period.month!==r?t.period.month:0,day:t.period.day!==r?t.period.day:0,hours:t.period.hours!==r?t.period.hours:0,minutes:t.period.minutes!==r?t.period.minutes:0,seconds:t.period.seconds!==r?t.period.seconds:0}),t.groupBy===r?H=t.asObject===!0?{}:[]:(H=[],H.push([]),$=n(o).get()[t.groupBy]),X=function(K,x,F){return t.asObject===!0?t.format!==r?K[n(x).format(t.format)]={}:K[n(x).format("%F %H:%M:%S")]={}:t.format!==r?K.push(F?null:n(x).format(t.format)):K.push(F?null:n(x)),K},t.groupBy!==r&&t.fillNulls){var J={year:R.year?-R.year:r,month:R.month?-R.month:r,day:R.day?-R.day:r,hours:R.hours?-R.hours:r,minutes:R.minutes?-R.minutes:r,seconds:R.seconds?-R.seconds:r,milliseconds:R.milliseconds?-R.milliseconds:r};for(g=n(o).calc(J).utc();n(g).get()[t.groupBy]===$;)X(H[H.length-1],g,!0),g=n(g).calc(J).utc();if(t.groupBy==="week"){var W=n(o).dayOfWeek();for(g=n(o).dayOfWeek(0).utc();H[0].length<W&&g<o;)X(H[H.length-1],g,!0),g=n(g).calc(R).utc()}}for(;o<=d;)t.groupBy===r?X(H,o):n(o).get()[t.groupBy]===$?X(H[H.length-1],o):(H.push([]),X(H[H.length-1],o),$=n(o).get()[t.groupBy]),o=n(o).calc(R).utc();if(t.groupBy!==r&&t.fillNulls)for(C=n(d).calc(R).utc();n(C).get()[t.groupBy]===$;)X(H[H.length-1],C,!0),C=n(C).calc(R).utc();return H},n.monthNames=function(t){switch(t){case"long":return p;default:return y}},n.dayNames=function(t){switch(t){case"long":return L;default:return I}},n.lang=function(t){if(t!==r)c=t,f[c]===r&&(c="en"),p=N(),y=_(),L=O(),I=b();else return c;return r},n.availableLangs=function(){return Object.keys(f)},n.registerFormat=function(t,o,d,g,C,R){w[t]={format:o,parse:d,minLength:g,maxLength:C,type:R}},n.unregisterFormat=function(t){delete w[t]},n.detectFormat=function(t){var o,d,g;return o=A(t,0),o!==""&&(g=10),d=t.charAt(g),(d==="T"||d===" ")&&(o+=d,g+=1),o+=l(t,g),o},u={TempusDate:M},n.classes=function(t,o){if(o===r)return u[t];u[t]=o},n.loadTranslations=function(t){typeof t=="object"?f=t:typeof t=="string"&&Y(t,function(o){f=o},function(o){})},c=(m.language||m.systemLanguage||m.userLanguage||"en").substr(0,2).toLowerCase(),f[c]===r&&(c="en"),p=N(),y=_(),L=O(),I=b(),T.exports&&(e=T.exports=n),e.tempus=n}).call(B)})(ot,ot.exports);var Ae=ot.exports;const ht=P(Ae),Q=class Q{constructor(e){D(this,Ot);D(this,at);D(this,bt);D(this,Rt);D(this,Z);D(this,tt);D(this,et);D(this,St);D(this,ut);typeof e=="function"?(this.callBatch=e,this.callMethod=null):(this.callBatch=(e==null?void 0:e.callBatch)||null,this.callMethod=(e==null?void 0:e.callMethod)||null),this.result={},this.errors={},this.timeLimit={limit:!1,date:void 0,pauseMs:void 0},this.timeLimitListeners=new Set,this.canContinue=!0,this.progressCall="",this.progressData="",this.progressTimer="",this.lastProgressSnapshot=null,this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.filterChunkSize=50,this.limit=50,this.progressDelay=100,this.operatingThreshold=475,this.defaultPauseMs=12e4,this.callLimitPauseMs=3e4,this.requestTimeoutMs=6e4}get progressPercent(){if(!this.progressData)return{percent:0,allCount:0,allTotal:0};const e=this.totalBatchCommands||0;if(e>0&&Array.isArray(this.batchCommandKeyOrder)&&this.batchCommandKeyOrder.length&&E(this,Ot,Zt).call(this)){let A=0;for(const c of this.batchCommandKeyOrder){const f=this.progressData[c];if(!f)continue;const N=Number(f.total)||0,_=Number(f.count)||0;N===0&&_===0?A+=1:N>0&&(A+=Math.min(1,_/N))}const h=A/e*100;let n=Math.max(0,Math.min(100,Math.floor(h)));const u=e,m=Math.min(e,Math.floor(A));return{percent:n,allCount:m,allTotal:u}}let r=0,s=0;for(const A of Object.values(this.progressData)){const{total:h,count:n}=A;r+=h??0,s+=n??0}const i=Number(this.chunkRate)||0;let a=0;r?a=s/r*100*i+this.totalProgress:s===0&&r===0?a=100*i+this.totalProgress:a=100,a=Math.max(0,Math.min(a,100));let l=Math.floor(a);return r>0&&s>=r&&(l=100),{percent:l,allCount:s,allTotal:r}}setProgressData({key:e,value:r,type:s}){var f,N;if(!this.progressCall)return;const i=this.getData(r.data()),a=Array.isArray(i)?i.length:0;let l=a;if(typeof r.total=="function"){const _=r.total();if(_!=null&&_!==""){const O=Number(_);Number.isFinite(O)&&(l=O)}}s==="count"&&(l=a);let A=1;i&&(A=a),this.progressData||(this.progressData={});const h=((f=this.progressData[e])==null?void 0:f.total)??0,n=((N=this.progressData[e])==null?void 0:N.count)??0,u=A+n,m=Math.max(h,l??0,u);if(this.progressData[e]={total:m,count:Math.min(u,m)},typeof document<"u"&&(document==null?void 0:document.hidden)===!0){E(this,at,Ht).call(this);return}E(this,at,Ht).call(this),this.progressTimer||(this.progressTimer=setInterval(()=>{if(!this.progressCall){this.clearProgressData();return}E(this,at,Ht).call(this);const{percent:_}=this.progressPercent;_>=100&&(clearInterval(this.progressTimer),this.progressTimer="")},this.progressDelay))}getData(e){if(e==null)return e;let r=(e==null?void 0:e.items)??(e==null?void 0:e.tasks)??(e==null?void 0:e.types)??(e==null?void 0:e.type)??(e==null?void 0:e.fields)??(e==null?void 0:e.workgroups)??e;return r&&typeof r=="object"&&!Array.isArray(r)&&Array.isArray(r.result)&&(r=r.result),r}setTimeLimitState(e,r,s){this.timeLimit.limit=!!e,this.timeLimit.date=e?r:void 0,e&&typeof s=="number"&&s>0?this.timeLimit.pauseMs=s:this.timeLimit.pauseMs=void 0,E(this,Rt,$t).call(this)}subscribeTimeLimit(e){return typeof e!="function"?()=>{}:(this.timeLimitListeners.add(e),e({limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs}),()=>{this.timeLimitListeners.delete(e)})}splitLargeFilters(e,r){const{method:s,params:i}=r;if(!i)return[{key:e,request:r}];const a=i.filter||i.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:e,request:r}];for(const[l,A]of Object.entries(a))if(!String(l).trim().startsWith("!")&&Array.isArray(A)&&A.length>this.filterChunkSize){const h=[];for(let n=0;n<A.length;n+=this.filterChunkSize){const u=A.slice(n,n+this.filterChunkSize),m=n===0?e:`${e}__chunk_${Math.floor(n/this.filterChunkSize)}`,c={...i};i.filter?(c.filter={...a},c.filter[l]=u):i.FILTER&&(c.FILTER={...a},c.FILTER[l]=u),h.push({key:m,request:{method:s,params:c},originalKey:e,filterKey:l,chunkIndex:Math.floor(n/this.filterChunkSize)})}return h}return[{key:e,request:r}]}mergeSplitResults(e,r){const s=[],i=String(r).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${i}(?:__chunk_\\d+)?$`),l=Object.keys(e).filter(A=>a.test(A)).sort((A,h)=>{const n=A.match(/__chunk_(\d+)$/),u=h.match(/__chunk_(\d+)$/);return n?u?parseInt(n[1])-parseInt(u[1]):1:-1});for(const A of l){const h=e[A];Array.isArray(h)?s.push(...h):h&&s.push(h)}return s}delay(){return typeof document<"u"&&(document==null?void 0:document.hidden)===!0?Promise.resolve():new Promise(r=>setTimeout(r,500))}callBatchWithTimeout(e,r){return new Promise((s,i)=>{let a=!1,l=null;const A=async n=>{if(!a){a=!0,l&&clearTimeout(l);try{await Promise.resolve(r(n)),s()}catch(u){console.error("Error in callBatch callback:",u),i(u)}}},h=async()=>{if(!a){a=!0,l&&clearTimeout(l),console.warn(`Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`);const n={};Object.keys(e).forEach(u=>{n[u]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 60 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(r(n)),s()}catch(u){console.error("Error in timeout callback:",u),s()}}};try{this.callBatch(e,async n=>{await A(n)})}catch(n){a||console.error("Error calling callBatch:",n)}l=setTimeout(async()=>{a||(console.warn(`Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`),await h())},this.requestTimeoutMs)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.lastProgressSnapshot=null}async batch(e,r,s={}){E(this,ut,Ft).call(this,r);const i={},a={},l={};for(const[u,m]of Object.entries(e)){const c=this.arrayChunk(m);if(!c)continue;const f=this.splitLargeFilters(u,c);if(f.length===1)a[u]=c;else{l[u]=[];for(const N of f)a[N.key]=N.request,l[u].push(N.key)}}this.batchCommandKeyOrder=Object.keys(a),this.totalBatchCommands=this.batchCommandKeyOrder.length,this.batchCommandMethods=this.batchCommandKeyOrder.map(u=>{var m;return String(((m=a[u])==null?void 0:m.method)||"")}),this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let A={},h=0;const n=Object.keys(a).length;for(const[u,m]of Object.entries(a)){if(!this.canContinue)break;if(A[u]=m,Object.keys(A).length>=this.limit||h+1===n){const c=h+1===n;await this.batchChunk(A,void 0,!c,{disablePagination:!1,oneBatch:!!(s!=null&&s.oneBatch)}),Object.entries(this.result).forEach(([f,N])=>{i[f]=N}),this.totalProgress=Math.round(h/n*100),A={}}h++}for(const[u,m]of Object.entries(l))if(m&&m.length>0){const c=this.mergeSplitResults(i,u);for(const f of m)delete i[f];i[u]=c}return Object.entries(this.errors).length&&(i.errorsList=this.errors),r&&r({percent:100}),Promise.resolve(i)}async batchTotalCount(e,r){E(this,ut,Ft).call(this,r);const s={},i={},a={};for(const[h,n]of Object.entries(e)){const u=this.arrayChunk(n);if(!u)continue;const m=this.splitLargeFilters(h,u);if(m.length===1)i[h]=u;else{a[h]=[];for(const c of m)i[c.key]=c.request,a[h].push(c.key)}}const l=[],A=Object.entries(i);for(let h=0;h<A.length;h+=this.limit){const n=A.slice(h,h+this.limit),u={};for(const[m,c]of n){if(!this.canContinue)break;u[m]=c}Object.keys(u).length>0&&l.push(u)}this.chunkRate=(1/l.length).toFixed(5);for(const[h,n]of Object.entries(l)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(h)/l.length*100);const u=Number(h)===l.length-1;await E(this,et,pt).call(this,n,async m=>{var c,f,N,_,O;for(const[b,p]of Object.entries(m)){if(!this.canContinue)return;if(p.error()){const w=(f=(c=p.error())==null?void 0:c.ex)==null?void 0:f.error,G=(_=(N=p.error())==null?void 0:N.ex)==null?void 0:_.error_description;this.errors[b]=w&&w.trim()||G&&G.trim()||((O=p.error())==null?void 0:O.toString())||"Неизвестная ошибка",s[b]=0;continue}const y=this.getData(p.data()),L=Array.isArray(y)?y.length:0,Y=typeof p.total=="function"&&p.total()!==void 0?p.total():L;s[b]=Y,this.setProgressData({key:b,value:p,type:"count"})}await E(this,tt,yt).call(this,m,!u)})}for(const[h,n]of Object.entries(a))if(n&&n.length>0){let u=0;for(const m of n)s[m]!==void 0&&(u+=s[m]||0),delete s[m];s[h]=u}return Object.entries(this.errors).length&&(s.errorsList=this.errors,this.errorLogger()),r&&r({percent:100}),Promise.resolve(s)}async call({method:e,params:r={}}){var s,i,a,l,A,h,n;for(;;){const u=await E(this,St,te).call(this,e,r);if(!u){await E(this,Z,lt).call(this,this.callLimitPauseMs);continue}const m={};if(u!=null&&u.answer)for(const[f,N]of Object.entries(u.answer))f!=="result"&&N&&(m[f]=N);if(u.error()){const f=((i=(s=u.error())==null?void 0:s.ex)==null?void 0:i.error)??"";if(["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT","TIMEOUT"].includes(f)){await E(this,Z,lt).call(this,this.callLimitPauseMs);continue}const N=((a=u.error())==null?void 0:a.toString())||((A=(l=u.error())==null?void 0:l.ex)==null?void 0:A.error_description)||((n=(h=u.error())==null?void 0:h.ex)==null?void 0:n.error)||"Неизвестная ошибка";return{success:!1,data:!1,answer:m,error:N}}let c=u.data();return c!=null&&c.items&&(c=c.items),{success:!0,data:c,answer:m,error:null}}}arrayChunk(e){let r="",s={};if(Array.isArray(e)?[r]=e:(r=e.method,s=e.params),(r.includes("list")||r==="user.get"||r==="entity.item.get")&&r!=="task.item.list"){if(!s)s=r==="entity.item.get"?{SORT:{ID:"ASC"}}:{order:{ID:"ASC",id:"ASC"}};else{r==="entity.item.get"?(s.SORT||(s.SORT={ID:"ASC"}),Array.isArray(s.select)?s.select.includes("ID")||s.select.push("ID"):s.select=["ID"]):r==="tasks.task.list"?(s.order||(s.order={}),s.order.ID="asc"):r==="user.get"?(s.sort||(s.sort="ID"),s.order||(s.order="ASC")):s.order={ID:"ASC",id:"ASC"},Array.isArray(s.select)&&!s.select.includes("ID")&&s.select.push("ID");const i=r==="user.get"||r==="entity.item.get"?s.FILTER:s.filter;typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.entries(i).forEach(([a,l])=>{(s.start===void 0||s.start!==-1)&&["id","ID"].includes(a)&&(typeof l=="string"||Array.isArray(l)&&l.length<=50)&&(s.start=-1)})}r==="crm.type.list"&&s.order&&delete s.order.ID}if(r==="task.item.list")if(!s)s=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(s[0])&&(s[0]={});const[i,a,l,A]=s;i.ID="ASC",A[0]!==""&&A.includes("ID")||A.push("ID")}return{method:r,params:s}}async batchChunk(e,r,s=!0,i={}){return new Promise(a=>{const l=[];let A;const h=!!(i!=null&&i.disablePagination);(async()=>{await E(this,et,pt).call(this,e,async u=>{var c,f,N,_,O;for(const[b,p]of Object.entries(u)){if(!this.canContinue)return;if(p.error()){const g=(f=(c=p.error())==null?void 0:c.ex)==null?void 0:f.error,C=(_=(N=p.error())==null?void 0:N.ex)==null?void 0:_.error_description;this.errors[b]=g&&g.trim()||C&&C.trim()||((O=p.error())==null?void 0:O.toString())||"Неизвестная ошибка",A=!0}const y=this.getData(p.data()),L=Array.isArray(y)?y.length:0,I=typeof p.total=="function"&&p.total()!==void 0,Y=I?p.total():L;r==="count"?this.result[b]?this.result[b]+=L:this.result[b]=Y:this.result[b]=y,this.setProgressData({key:b,value:p,type:r});const w=e[b],G=Array.isArray(w)?w[0]:w==null?void 0:w.method,M=typeof G=="string"&&(G.includes(".list")||G==="user.get"||G==="entity.item.get"),t=r==="count"?!I&&L===this.limit:M?L===this.limit:Y>this.limit&&Y>L,o=r!=="count"&&G==="entity.item.get"&&L===this.limit&&!t,d=t||o;if(!h&&(!this.canContinue||d)){let g=e[b];if(Array.isArray(g)){const[C,R={}]=g;g=[C,R]}else{const{method:C,params:R={}}=g;g=[C,R]}l.push([b,g,Y,{entityItemGetScan:o}])}}A>0&&this.errorLogger();const m=l.length>0||s;await E(this,tt,yt).call(this,u,m),l.length?await this.batchPayload(l,r,i).then(()=>a(this.result)):a(this.result)})})()})}async batchPayload(e,r,s={}){const i=!!(s!=null&&s.oneBatch),a=(N,_,O,b)=>{let p="ID";this.result[N][this.result[N].length-1].ID||(p="id");let y=`${p}`;if(JSON.stringify(b[1]).toLocaleLowerCase().includes('"id":"desc"')?y="<"+y:y=">"+y,_===1||O.length===0)return{field:y,id:this.result[N][this.result[N].length-1][p]};let I="";const[Y,w]=b;return(Y==="tasks.task.list"||Y==="task.item.list")&&(I="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(Y)&&(I="[items]"),Y==="crm.type.list"&&(I="[types]"),Y==="socialnetwork.api.workgroup.list"&&(I="[workgroups]"),{field:y,id:`$result[${[N,_-1].join("__")}]${I}[49][${p}]`}},l=(N,_)=>{const[O,b]=N;let p=JSON.parse(JSON.stringify(b)),y;if(O==="task.item.list"){p=[...p];const[L,I,Y,w]=p;return I[_.field]=_.id,[O,p]}return["user.get"].includes(O)||p.FILTER?(p.FILTER||(p.FILTER={}),y=p.FILTER):(p.filter||(p.filter={}),y=p.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(O)?y[">ID"]=_.id:y[_.field]=_.id,[O,{...p,start:-1}]},A=N=>{Object.entries(N).forEach(([_,O])=>{var y,L,I,Y,w;const[b]=_.split("__"),p=this.getData(O.data());if(Array.isArray(p)&&(r==="count"?this.result[b]+=p.length:this.result[b].push(...p)),O.error()){const G=(L=(y=O.error())==null?void 0:y.ex)==null?void 0:L.error,M=(Y=(I=O.error())==null?void 0:I.ex)==null?void 0:Y.error_description;this.errors[b]=G&&G.trim()||M&&M.trim()||((w=O.error())==null?void 0:w.toString())||"Неизвестная ошибка"}this.setProgressData({key:b,value:O,type:r})})},h=(N,_)=>{if(!Array.isArray(N)||N.length===0)return null;const O=N[N.length-1];let b="ID";O.ID||(b="id");let p=b;return JSON.stringify(_[1]).toLocaleLowerCase().includes('"id":"desc"')?p="<"+p:p=">"+p,{field:p,id:O[b]}},n=1e4,u=async(N,_)=>{var b,p;let O=this.limit;for(let y=1;this.canContinue&&O===this.limit&&y<=n;y++){const L=this.result[N],I=h(L,_);if(!I)break;const Y=`${N}__eiscan_${y}`,w=l(_,I);let G=null;await E(this,et,pt).call(this,{[Y]:w},async d=>{G=d,A(d)});const M=y<n;await E(this,tt,yt).call(this,G,M),await this.delay();const t=G==null?void 0:G[Y];if((b=t==null?void 0:t.error)!=null&&b.call(t)){O=0;break}const o=this.getData((p=t==null?void 0:t.data)==null?void 0:p.call(t));O=Array.isArray(o)?o.length:0}};let m=[],c=0;const f=async(N=!0)=>m.length?(await E(this,et,pt).call(this,Object.fromEntries(m),async _=>{A(_),await E(this,tt,yt).call(this,_,N)}),c++,m=[],i&&c>=1?!0:(await this.delay(),!1)):!1;for await(const N of e){if(!this.canContinue)return;const[_,O,b,p={}]=N;if(p.entityItemGetScan){if(await f(!0))return;if(i)continue;await u(_,O);continue}let y=1;for(;b>y*this.limit;){const L=[_,y].join("__"),I=a(_,y,m,O);if(m.push([L,l(O,I)]),i&&m.length===49&&await f(!0)||m.length%50===0&&await f(!0))return;y++}}await f(!1)}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([e,r])=>{r&&console.log(`[${e}]`,r.toString())}),console.groupEnd()}};Ot=new WeakSet,Zt=function(){const e=this.totalBatchCommands||0,r=this.batchCommandMethods;if(e<S(Q,_t)||!Array.isArray(r)||r.length!==e)return!1;if(r.filter(a=>a==="crm.deal.list").length>=S(Q,Tt))return!0;const i=r.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=S(Q,Et)&&i/e>=S(Q,Lt)},_t=new WeakMap,Tt=new WeakMap,Et=new WeakMap,Lt=new WeakMap,at=new WeakSet,Ht=function(){if(!this.progressCall||!this.progressData)return;const{percent:e,allCount:r,allTotal:s}=this.progressPercent,i={percent:e,allCount:r,allTotal:s};E(this,bt,Vt).call(this,i)&&(this.progressCall({data:this.progressData,percent:e,allCount:r,allTotal:s}),this.lastProgressSnapshot=i)},bt=new WeakSet,Vt=function(e){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==e.percent||this.lastProgressSnapshot.allCount!==e.allCount||this.lastProgressSnapshot.allTotal!==e.allTotal:!0},Rt=new WeakSet,$t=function(){const e={limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs};for(const r of this.timeLimitListeners)try{r(e)}catch(s){console.warn("Batch timeLimit listener error:",s)}},Z=new WeakSet,lt=async function(e=this.defaultPauseMs){this.setTimeLimitState(!0,new Date().toISOString(),e),await new Promise(r=>setTimeout(r,e)),this.setTimeLimitState(!1,void 0)},tt=new WeakSet,yt=async function(e,r=!0){if(!r)return 0;let s=0;if(!e||typeof e!="object")return 0;for(const i of Object.values(e))if(!(!i||typeof i!="object"))try{if(typeof i.time=="function"){const a=i.time();a&&typeof a.operating=="number"&&(s=Math.max(s,a.operating))}}catch{}s>=this.operatingThreshold&&await E(this,Z,lt).call(this)},et=new WeakSet,pt=async function(e,r){let s=!1,i=e;do s=!1,await this.callBatchWithTimeout(i,async a=>{var h,n;let l=!1;const A=new Set;for(const[u,m]of Object.entries(a||{})){if(!(m!=null&&m.error)||!m.error())continue;const c=((n=(h=m.error())==null?void 0:h.ex)==null?void 0:n.error)??"";if(c==="TIMEOUT"){l=!0;break}["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT"].includes(c)&&A.add(u)}if(l){s=!0,await E(this,Z,lt).call(this);return}if(A.size>0){const u={};for(const[c,f]of Object.entries(a||{}))A.has(c)||(u[c]=f);Object.keys(u).length&&await r(u);const m={};for(const c of A)i[c]&&(m[c]=i[c]);i=m,Object.keys(i).length&&(s=!0,await E(this,Z,lt).call(this));return}await r(a)});while(s)},St=new WeakSet,te=function(e,r){return new Promise(s=>{if(typeof this.callMethod!="function"){s(null);return}let i=!1;const a=setTimeout(()=>{i||(i=!0,s(null))},this.requestTimeoutMs);try{this.callMethod(e,r,l=>{i||(i=!0,clearTimeout(a),s(l))})}catch{i||(i=!0,clearTimeout(a),s(null))}})},ut=new WeakSet,Ft=function(e){this.clearProgressData(),this.progressCall=typeof e=="function"?e:"",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)},D(Q,_t,5),D(Q,Tt,5),D(Q,Et,8),D(Q,Lt,.65);let z=Q;class Ut{constructor(){D(this,rt,{})}get hash(){return this.createHash(8)}createHash(e){let r="abcdefghijklmnopqrstuvwxyz0123456789",s="";e=e||6;for(let i=0;i<e;i++)s+=r.charAt(Math.floor(Math.random()*r.length));return s}actionFilter({keyTimer:e,duration:r=10,action:s}){S(this,rt)[e]&&(clearTimeout(S(this,rt)[e]),S(this,rt)[e]=null),s&&(S(this,rt)[e]=setTimeout(()=>{s()},r))}async noSleep(){let e=document.createElement("video");e.classList.add("no-sleep"),e.muted=!0,e.autoplay=!0,e.setAttribute("playsinline",""),e.addEventListener("loadeddata",()=>{e.style.position="fixed",e.style.left="-9999px",document.querySelector("body").append(e),e.play().catch(r=>{console.warn("noSleep: autoplay prevented",r)})}),e.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{e.play().catch(r=>{console.warn("noSleep: replay prevented",r)})}})}),e.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(e,r){let s=new Blob([JSON.stringify(e)],{type:"application/json"}),i=URL.createObjectURL(s),a=document.createElement("a");a.style.display="none",a.href=i,a.download=`${r}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(i)},200)}}rt=new WeakMap;const Yt=new Ut;class vt{constructor(){D(this,It);D(this,ft);D(this,Mt);D(this,Dt);D(this,kt);D(this,q,"logger");D(this,V,!1);D(this,st,new Map);D(this,At,{});D(this,j,null);D(this,it,!1);D(this,ct,!1);U(this,"periodClear",3);E(this,It,ee).call(this)}async init(){try{let e=new z(BX24.callBatch),{entityList:r}=await e.batch({entityList:{method:"entity.get"}});if(r&&Array.isArray(r))if(r.find(i=>i.ENTITY==S(this,q)))v(this,V,!0);else{let{entityAdd:i}=await e.batch({entityAdd:{method:"entity.add",params:{ENTITY:S(this,q),NAME:S(this,q),ACCESS:{AU:"X"}}}});i&&v(this,V,!0)}return E(this,Dt,se).call(this).catch(s=>{console.error("Ошибка при проверке периода очистки:",s)}),S(this,V)}catch(e){return console.error("Ошибка при инициализации логера:",e),!1}}start({type:e,data:r}){if(!S(this,V))return E(this,ft,Xt).call(this,"entity"),null;if(!e||!r)return console.error("Невалидные данные для логирования:",{type:e,data:r}),null;const s=Yt.hash,i={type:e,data:r,userInfo:S(this,At),errorList:{},status:"",answer:null,date:new Date().getTime()};return S(this,st).set(s,i),v(this,ct,!0),s}async stop({key:e,errorList:r,status:s,answer:i}){var l;if(!S(this,ct))return;if(!S(this,V)){E(this,ft,Xt).call(this,"entity");return}let a=S(this,st).get(e);if(!a){console.error(`Не найдены данные логирования для ключа: ${e}`);return}r&&(a.errorList=r),s&&(a.status=s),i&&(a.answer=i),await E(this,Mt,re).call(this),(l=a==null?void 0:a.data)!=null&&l.updateList&&v(this,it,!0),v(this,ct,!1)}async getEntityList(e){var r;try{if((r=S(this,j))!=null&&r.length&&!S(this,it))return S(this,j);let s=new z(BX24.callBatch),{entityList:i}=await s.batch({entityList:{method:"entity.item.get",params:{ENTITY:S(this,q),SORT:{ID:"DESC"}}}},e);return!i||!Array.isArray(i)?(console.warn("Получен невалидный список записей"),[]):(i=i.map(a=>{try{const{ID:l,DATE_CREATE:A,DETAIL_TEXT:h}=a;return{...JSON.parse(h),id:l,dateCreate:A}}catch(l){return console.error(`Ошибка парсинга записи ${a.ID}:`,l),null}}).filter(a=>a!==null),v(this,it,!1),v(this,j,i),i)}catch(s){return console.error("Ошибка при получении списка записей:",s),[]}}async downAllEntityJson(){try{if(S(this,j)||await this.getEntityList(),!S(this,j)||S(this,j).length===0)return console.warn("Нет данных для выгрузки"),!1;let e=ht().format("%Y-%m-%d");return Yt.downloadFileJson(S(this,j),`sdklogger-entity-data__${e}`),!0}catch(e){return console.error("Ошибка при выгрузке данных в JSON:",e),!1}}}q=new WeakMap,V=new WeakMap,st=new WeakMap,At=new WeakMap,j=new WeakMap,it=new WeakMap,ct=new WeakMap,It=new WeakSet,ee=async function(){try{const e=new z(BX24.callBatch),r=BX24.isAdmin(),{curUser:s}=await e.batch({curUser:{method:"user.current"}});v(this,At,{isAdmin:r,curUser:s})}catch(e){console.error("Ошибка при получении информации о пользователе:",e),v(this,At,{isAdmin:!1,curUser:null})}},ft=new WeakSet,Xt=function(e){e=="entity"&&Yt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},Mt=new WeakSet,re=async function(){try{let e={},r=new z(BX24.callBatch);for(let[s,i]of S(this,st).entries())if(i.status){const a=JSON.stringify(i);e[s]={method:"entity.item.add",params:{ENTITY:S(this,q),NAME:S(this,q),DETAIL_TEXT:a}}}if(Object.keys(e).length){let s=await r.batch(e),{errors:i}=r;for(let[a,l]of Object.entries({...s,...i}))S(this,st).delete(a);return!0}return!1}catch(e){return console.error("Ошибка при добавлении записей в хранилище:",e),!1}},Dt=new WeakSet,se=async function(){try{let e=new z(BX24.callBatch),{serverTime:r}=await e.batch({serverTime:{method:"server.time"}});if(!r){console.error("Не удалось получить время сервера");return}if(S(this,j)||await this.getEntityList(),!S(this,j)||S(this,j).length===0)return;let s=S(this,j).filter(i=>{try{let{dateCreate:a}=i;return a?ht(new Date(a)).between(ht(new Date(r)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});s.length>0&&(console.log(`Найдено ${s.length} записей для очистки (старше ${this.periodClear} месяцев)`),await E(this,kt,ie).call(this,s))}catch(e){console.error("Ошибка при проверке периода очистки:",e)}},kt=new WeakSet,ie=async function(e){try{if(!e||e.length===0)return!1;let r=new z(BX24.callBatch),s=e.filter(a=>a&&a.id).map(a=>{let{id:l}=a;return{method:"entity.item.delete",params:{ENTITY:S(this,q),ID:l}}});if(s.length===0)return!1;const i=await r.batch(s);return console.log(`Успешно удалено ${s.length} записей`),v(this,it,!0),i}catch(r){return console.error("Ошибка при очистке устаревших записей:",r),!1}};function Gt(T){if(!T||typeof T!="string")return"";try{const e=new URL(T);e.search="",e.hash="";let r=e.toString();return r.endsWith("/")&&e.pathname!=="/"&&(r=r.slice(0,-1)),r}catch{return T.split("?")[0].split("#")[0].replace(/\/$/,"")}}function zt(T){return!T||typeof T!="string"?!1:T.toLowerCase().includes("/marketplace/app")}function ce(){var e;if(typeof window>"u"||!((e=window.location)!=null&&e.href))return"";const T=Gt(window.location.href);return zt(T)?"":T}function Pt(T){if(!(T!=null&&T.appConst)||typeof T.appConst!="object")return"";const e=ce();return e?(T.appConst.pathApp=e,e):Gt(T.appConst.pathApp??"")}class le{constructor(e){D(this,nt);D(this,Bt);D(this,wt);D(this,mt);D(this,dt);D(this,Ct);U(this,"domain","");U(this,"isAdmin",!1);U(this,"appInfo",null);U(this,"appConst",null);U(this,"userInfo",null);U(this,"placeData",null);U(this,"placeInfo",null);U(this,"logger",!1);U(this,"timeLimit",{limit:!1,date:void 0,pauseMs:void 0});U(this,"batchClient",null);this.appConst=e}subscribeTimeLimit(e){return E(this,nt,Nt).call(this).subscribeTimeLimit(e)}init(){return new Promise((e,r)=>{let i=setInterval(()=>{window.BX24&&BX24.init(async()=>{console.info("init BX24"),clearInterval(i),clearTimeout(a),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info(),this.logger?(this.logger=new vt,await this.logger.init()):this.logger={start:()=>{},stop:()=>{},getEntityList:()=>{}};const[l,A]=await Promise.all([E(this,Bt,ne).call(this),E(this,wt,oe).call(this)]);this.appInfo=l,this.userInfo=A,Pt(this);let h=new Ut;try{h.noSleep()}catch(n){console.warn("Failed to initialize noSleep:",n)}e(!0)})},100);const a=setTimeout(()=>{clearInterval(i);const l=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(l),r(l)},3e4)})}userOption(e,r){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return r!==void 0?BX24.userOption.set(e,r):BX24.userOption.get(e)}appOption(e,r){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return r!==void 0?BX24.appOption.set(e,r):BX24.appOption.get(e)}async call({method:e,params:r,updateList:s}){let i;if(s&&(i=this.logger.start({type:"call",data:{method:e,params:r,updateList:s}})),r||(r={}),typeof BX24>"u"||!BX24.callMethod){const A=new Error("BX24 is not initialized");throw console.error(A),A}const l=await E(this,nt,Nt).call(this).call({method:e,params:r});if(!l.success){if(console.error(l.error),i)try{await this.logger.stop({answer:l.answer,key:i,status:"fail",errorList:{0:l.error||"Unknown call error"}})}catch(A){console.error("Logger error:",A)}return!1}if(i)try{await this.logger.stop({answer:l.answer,key:i,status:"success"})}catch(A){console.error("Logger error:",A)}return l.data}async batch(e,r,{errorCall:s,updateList:i,batchOptions:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const h=new Error("BX24 is not initialized");return console.error(h),!1}const l=E(this,nt,Nt).call(this);let A;i&&(A=this.logger.start({type:"batch",data:{commandList:e,updateList:i}}));try{let h=await l.batch(e,r,a);const n=E(this,mt,jt).call(this,l,h,e,i);if(Object.keys(n).length){if(s&&s(n),A)try{await this.logger.stop({key:A,status:"fail",errorList:n})}catch(u){console.error("Logger error:",u)}}else if(A)try{await this.logger.stop({key:A,status:"success"})}catch(u){console.error("Logger error:",u)}return h}catch(h){if(A)try{await this.logger.stop({key:A,status:"fail-runtime",errorList:{0:h==null?void 0:h.toString()}})}catch(n){console.error("Logger error:",n)}return console.error(h),!1}}async batchTotalCount(e,r,{errorCall:s,updateList:i}={}){if(typeof BX24>"u"||!BX24.callBatch){const A=new Error("BX24 is not initialized");return console.error(A),!1}const a=E(this,nt,Nt).call(this);let l;i&&(l=this.logger.start({type:"batch-total-count",data:{commandList:e}}));try{let A=await a.batchTotalCount(e,r);const h=E(this,mt,jt).call(this,a,A,e,i);if(Object.keys(h).length){if(s&&s(h),l)try{await this.logger.stop({key:l,status:"fail",errorList:h})}catch(n){console.error("Logger error:",n)}}else if(l)try{await this.logger.stop({key:l,status:"success"})}catch(n){console.error("Logger error:",n)}return A}catch(A){if(l)try{await this.logger.stop({key:l,status:"fail-runtime",errorList:{0:A==null?void 0:A.toString()}})}catch(h){console.error("Logger error:",h)}return console.error(A),!1}}async getPlacement(){return await this.call({method:"placement.get"}).then(e=>(this.placeData||(this.placeData=e),e))}async placementBind(e){var m;if(!this.isAdmin||(this.placeData=await this.getPlacement(),!this.placeData))return;const{appName:r,pathApp:s}=this.appConst;let i=E(this,dt,Jt).call(this,e);i=i.filter(c=>c.placement!=="PAGE_BACKGROUND_WORKER"&&c.placement!=="PAGE_BACKGROUND_WORKER_ALL");const a=E(this,Ct,ae).call(this,s),l=new Set(i.map(c=>c.placement));for(const c of a)l.has(c.placement)||i.push({placement:c.placement});if(i.length===0)return;let A=r;this.domain==="szdl.bitrix24.ru"&&((m=this.appInfo)!=null&&m.ID)&&(A=`${r}: #${this.appInfo.ID}`);const h=A.replace(" CRM",""),n={},u=[];for(let c=0;c<i.length;c++){const f=i[c].placement;if(this.placeData.find(O=>O.placement===f&&O.handler===s))continue;const _=this.placeData.filter(O=>O.placement===f&&O.handler!==s);for(const O of _)u.push({placement:f,handler:O.handler});n[`bind_${c}`]={method:"placement.bind",params:{PLACEMENT:f,HANDLER:s,LANG_ALL:{ru:{TITLE:f==="USER_PROFILE_TOOLBAR"?h:A}},OPTIONS:{errorHandlerUrl:s}}}}u.length>0&&await this.placementUnBind(u),Object.keys(n).length>0&&(await this.batch(n),this.placeData=await this.getPlacement(),Object.values(n).forEach(c=>{console.log("Приложение успешно встроено в",c.params.PLACEMENT)}))}async placementUnBind(e){let r=E(this,dt,Jt).call(this,e);if(r=r.filter(i=>i.placement!=="PAGE_BACKGROUND_WORKER"&&i.placement!=="PAGE_BACKGROUND_WORKER_ALL"),r.length===0)return;const s={};for(let i=0;i<r.length;i++){const a={PLACEMENT:r[i].placement};r[i].handler&&(a.HANDLER=r[i].handler),s[`unbind_${i}`]={method:"placement.unbind",params:a}}await this.batch(s),r.forEach(i=>{console.log("Встройка отвязана",i.placement)})}getBotList(){return this.call({method:"imbot.bot.list",params:{}}).then(e=>{let r=Object.values(e);return console.log("chat-bot list:",r),r})}regBot({code:e,type:r,name:s}){const{appName:i,pathApp:a,chatBotLogo:l}=this.appConst,A=this.appInfo.ID;return this.call({method:"imbot.register",params:{CODE:e??this.appInfo.CODE,TYPE:r??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${s??i} - бот #${A}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:ht().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:l??""}}}).then(h=>(console.log("Чат-бот добавлен",h),h))}unRegBot(e){return this.call({method:"imbot.unregister",params:{BOT_ID:e}}).then(r=>(console.log("чат-бот удален",r),r))}getLoggerList(e){return this.logger.getEntityList(e)}}nt=new WeakSet,Nt=function(){return this.batchClient||(this.batchClient=new z({callBatch:BX24.callBatch,callMethod:BX24.callMethod}),this.timeLimit=this.batchClient.timeLimit),this.batchClient},Bt=new WeakSet,ne=function(){return this.call({method:"app.info"})},wt=new WeakSet,oe=function(){return this.call({method:"user.current"})},mt=new WeakSet,jt=function(e,r,s,i){let a={...e.errors};if(Object.values(e.errors).some(A=>{if(typeof A!="string")return!1;const h=A.toUpperCase();return h==="TIMEOUT"||h==="OPERATION_TIME_LIMIT"||h.includes("TIMEOUT")||h.includes("OPERATION_TIME_LIMIT")})&&i){const A=r?Object.keys(r).filter(m=>m!=="errorsList"):[],h=new Set(Object.keys(e.errors||{})),n=new Set;if(r){for(const m of A)if(!h.has(m)){const c=r[m];c!=null&&n.add(m)}}const u=Object.values(e.errors).find(m=>{if(typeof m!="string")return!1;const c=m.toUpperCase();return c==="TIMEOUT"||c==="OPERATION_TIME_LIMIT"||c.includes("TIMEOUT")||c.includes("OPERATION_TIME_LIMIT")});for(const m of Object.keys(s))!n.has(m)&&!e.errors[m]&&(a[m]=u||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a},dt=new WeakSet,Jt=function(e){if(!e)return[];let r=[];return Array.isArray(e)?r=e.map(s=>typeof s=="string"?{placement:s}:s):typeof e=="string"?r=[{placement:e}]:r=[e],r},Ct=new WeakSet,ae=function(e){return this.placeData?this.placeData.filter(r=>!(r.placement==="PAGE_BACKGROUND_WORKER"||!r.handler||r.handler.includes(e))):[]};const Qt="szdl-utils-kit|";function he(){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 ue(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}const Wt=new Map;function fe(T="default"){if(typeof BroadcastChannel>"u")return null;const e=`${Qt}bc:${T}`;return Wt.has(e)||Wt.set(e,new BroadcastChannel(e)),Wt.get(e)}function qt(T,e){const r=fe(T);if(r)try{const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{data:e};r.postMessage({...s,tabId:he(),ts:Date.now()})}catch{}}async function me(T,e,r={}){const{ifAvailable:s=!1}=r,i=typeof T=="string"&&T.length>0?T:"default",a=`${Qt}${i}`;return ue()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!s},async l=>{if(s&&l==null)return{skipped:!0,coordination:"locks"};qt(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await e(),coordination:"locks"}}finally{qt(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await e(),coordination:"none"}}class de{constructor(e){D(this,gt);U(this,"entityName","tabs");U(this,"maxTabs",20);U(this,"tabList",[]);U(this,"id",0);U(this,"hasStarted",!1);U(this,"heartbeat");U(this,"runHeartbeat");U(this,"activeMaxPause",10*1e3);U(this,"quickCleanupThreshold",2*60*1e3);U(this,"pollInterval",6*1e3+Math.floor(Math.random()*2e3));U(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);U(this,"continueCondition");U(this,"defaultContinueBackground",()=>!0);var l,A,h;if(!e){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:r,bx:s,users:i,continueBackground:a}=e;this.bx=s,this.appInit=r,this.users=i,Pt(s),this.appPath=E(this,gt,Kt).call(this,((l=s==null?void 0:s.appConst)==null?void 0:l.pathApp)??""),this.appName=((A=s==null?void 0:s.appConst)==null?void 0:A.appName)??"",this.appCodeName=((h=s==null?void 0:s.appConst)==null?void 0:h.appCodeName)??"",this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("BackgroundWorker: appInit не передан");return}if(!this.bx){console.error("BackgroundWorker: bx не передан");return}if(this.isAppPage()){console.log("BackgroundWorker: Страница приложения, фоновый воркер не запускается");return}await this.checkPlacementType()&&await this.continueBackground()&&(await this.checkEntity(),await this.refreshTabs(!0),await this.ensureTabRegistered(),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(r=>{console.error("BackgroundWorker: backgroundTick failed",r)})},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 r=this.selectLeaderId(),s=r&&+this.id==+r;await this.updateTabState(s),s&&!this.hasStarted&&await this.runAsLeader()}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var e;if(typeof BX24>"u"||!((e=BX24.placement)!=null&&e.info))return!1;try{const r=BX24.placement.info(),s=r==null?void 0:r.placement,i=(r==null?void 0:r.options)||{},a=(i==null?void 0:i.URI)||"",l=s==="PAGE_BACKGROUND_WORKER"||(i==null?void 0:i.ID)==="PAGE_BACKGROUND_WORKER",A=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!l||A}catch{return!1}}async checkEntity(){var s;const e=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((s=e==null?void 0:e.find)==null?void 0:s.call(e,i=>i.ENTITY===this.entityName))||await this.safeCall(()=>this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}}))}async getTabs(){const e=await this.safeCall(()=>{var r;return this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:(r=this.bx.userInfo)==null?void 0:r.ID},SORT:{DATE_CREATE:"DESC"}}})});return!Array.isArray(e)||!e.length?[]:e.map(r=>{if(!r)return{id:void 0,data:void 0};try{const s=JSON.parse(r.DETAIL_TEXT);return{id:+r.ID||0,data:s}}catch(s){return console.log("BackgroundWorker: parse tab error",s),{id:+r.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 e={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId},r=await this.safeCall(()=>{var s;return this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(s=this.bx.userInfo)==null?void 0:s.ID,DETAIL_TEXT:JSON.stringify(e)}})})||0;return this.id=+r||0,this.id}async updateTabState(e){if(!this.id)return;const r={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:e,sessionId:this.sessionId};await this.safeCall(()=>{var s;return this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(s=this.bx.userInfo)==null?void 0:s.ID,DETAIL_TEXT:JSON.stringify(r)}})})}async deleteTabs(e=[]){if(!e.length)return;const r=e.map(s=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:s.id}}));await this.safeCall(()=>this.bx.batch(r))}async checkPlacementType(){var e;try{const r=await this.safeCall(()=>this.bx.getPlacement());if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const s=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),i=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),a=!i;if(!s)return!0;let l=!1;for(const A of r){if(A.placement!=="PAGE_BACKGROUND_WORKER"||!(A.userId||A.handler&&A.handler.includes("USER_ID=")))continue;const n=A.userId||(A.handler?this.extractUserIdFromHandler(A.handler):null);if(n&&+n===s){l=!0;break}}return i?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):a&&l?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}isIndividualPlacement(e){return!e||typeof e!="string"?!1:e.includes("USER_ID=")}extractUserIdFromHandler(e){if(!e||typeof e!="string")return null;const r=e.match(/USER_ID=(\d+)/);return r?+r[1]:null}async continueBackground(){try{const r=!!await Promise.resolve(this.continueCondition(this));return console.log(r?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),r}catch(e){return console.error("BackgroundWorker: Ошибка в continueCondition",e),!1}}async refreshTabs(e=!1,r=this.activeMaxPause){const s=[],i=[],a=Date.now(),l=await this.getTabs();for(const A of l){if(!(A!=null&&A.data)){s.push(A);continue}if(a-new Date(A.data.lastActive||0).getTime()>r){s.push(A);continue}i.push(A)}return e&&s.length&&await this.deleteTabs(s),this.tabList=i,i}selectLeaderId(){var r;return this.tabList.length&&+((r=[...this.tabList].sort((s,i)=>{var A,h,n,u;const a=new Date(((A=s.data)==null?void 0:A.createdAt)||((h=s.data)==null?void 0:h.lastActive)||0).getTime(),l=new Date(((n=i.data)==null?void 0:n.createdAt)||((u=i.data)==null?void 0:u.lastActive)||0).getTime();return a===l?(+s.id||0)-(+i.id||0):a-l})[0])==null?void 0:r.id)||0}async runAsLeader(){var i,a;const e=String(((a=(i=this.bx)==null?void 0:i.userInfo)==null?void 0:a.ID)??"0"),r=`background-worker:${this.entityName}:${e}`;(await me(r,async()=>{this.hasStarted=!0;const l=Math.min(this.activeMaxPause-1500,Math.max(2500,Math.floor(this.pollInterval/2)));this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(A=>console.error("BackgroundWorker: heartbeat update failed",A))},l);try{await this.appInit()}catch(A){console.error("BackgroundWorker: appInit failed",A)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)},{ifAvailable:!0})).skipped&&console.log("BackgroundWorker: runAsLeader пропущен — Web Lock у другой вкладки (тот же фоновый воркер)")}async setBackgroundWorkerAll(){var _,O,b,p;if(!((_=this.bx)!=null&&_.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(O=this.users)!=null&&O.length||await this.getEntityData(),Pt(this.bx);const e=E(this,gt,Kt).call(this,((p=(b=this.bx)==null?void 0:b.appConst)==null?void 0:p.pathApp)??"");if(!e){console.error("BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена");return}const r=await this.safeCall(()=>this.bx.getPlacement()),s=new Map;let i=null;(r||[]).forEach(y=>{if(y.placement!=="PAGE_BACKGROUND_WORKER")return;if(y.userId||y.handler&&y.handler.includes("USER_ID=")){const I=y.userId||(y.handler?this.extractUserIdFromHandler(y.handler):null);I&&s.set(+I,y)}else i=y});const a=await this.resolveAdmins(),l=await this.getEligibleUsersForBackgroundWorker(a);l.sort((y,L)=>{const I=y.LAST_LOGIN?new Date(y.LAST_LOGIN):new Date(0);return(L.LAST_LOGIN?new Date(L.LAST_LOGIN):new Date(0))-I});const A=10,h=l.slice(0,A),n=h.filter(y=>{const L=s.get(+y.ID);if(!L)return!0;const I=`${e}?USER_ID=${y.ID}/`;return L.handler!==I}),u=[];for(const[y]of s){const L=+y||0;l.find(Y=>+Y.ID===L)||u.push(L)}for(const y of h){const L=s.get(+y.ID);if(!L)continue;const I=`${e}?USER_ID=${y.ID}/`;L.handler!==I&&u.push(+y.ID)}const m=[];for(const y of u)m.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}?USER_ID=${y}/`}});const c=i&&(n.length>0||i.handler!==`${e}`);c&&m.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:i.handler||`${e}`}});for(const y of n)m.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}?USER_ID=${y.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}?USER_ID=${y.ID}/`},USER_ID:y.ID}});(!i||c)&&m.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}`}}});const f=m.filter(y=>y.method==="placement.unbind"),N=m.filter(y=>y.method==="placement.bind");f.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(f.map((y,L)=>[`unbind_${L}`,y])))),N.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(N.map((y,L)=>[`bind_${L}`,y])))),m.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var e,r;try{const s=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),i=!!((r=this.bx)!=null&&r.isAdmin),a=await this.getAdminsList()||[];if(!i){if(s&&a.includes(+s)){const h=a.filter(n=>+n!=+s);return await this.saveAdminsList(h),h}return a}const l=new Set([...a||[]]);s&&l.add(+s);const A=[...l].filter(Boolean);return await this.saveAdminsList(A),A}catch(s){return console.error("BackgroundWorker: resolveAdmins error",s),[]}}async getEligibleUsersForBackgroundWorker(e=[]){const r=(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0),s=e.map(i=>+i||0).filter(Boolean);return r.filter(i=>s.includes(+i.ID||0))}async saveAdminsList(e=[]){try{BX24.appOption.set("adminsList",JSON.stringify(e))}catch(r){console.error("BackgroundWorker: saveAdminsList error",r)}}async getAdminsList(){try{const e=BX24.appOption.get("adminsList"),r=e?JSON.parse(e):[];return Array.isArray(r)?r.map(s=>+s||0).filter(Boolean):[]}catch(e){return console.error("BackgroundWorker: getAdminsList error",e),[]}}async getEntityData(){const e={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:r}=await this.safeCall(()=>this.bx.batch(e).then(s=>s?(Array.isArray(s.users)||(s.users=[]),s):{users:[]}));this.users=r}async ensureAdminPlacements(){var e,r;(e=this.bx)!=null&&e.isAdmin&&((r=this.users)!=null&&r.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(e=500,r){return new Promise(s=>{setTimeout(()=>{r&&r(),s(!0)},e)})}async safeCall(e){try{return await e()}catch(r){console.error("BackgroundWorker: safeCall error",r);return}}}gt=new WeakSet,Kt=function(e){if(!e||typeof e!="string")return"";const r=Gt(e).replace(/\/+$/,"");return r?zt(r)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):r:""},k.BackgroundWorker=de,k.Batch=z,k.BxBoot=le,k.BxHelper=Ut,k.BxLogger=vt,k.tempus=ht,Object.defineProperty(k,Symbol.toStringTag,{value:"Module"})});
@@ -31,38 +31,61 @@ type TBatchProgress = {
31
31
 
32
32
  type TBatchProgressCallback = (payload: TBatchProgress) => void;
33
33
 
34
- type TBatchLimitCallback = (key: string) => void;
35
-
36
34
  type TCallBatch = (
37
35
  commandList: Record<string, TCommand>,
38
36
  callback: (result: Record<string, any>) => void
39
37
  ) => void;
40
38
 
39
+ type TCallMethodResult = {
40
+ error: () => { ex?: { error?: string; error_description?: string } } | null;
41
+ data: () => unknown;
42
+ answer?: Record<string, unknown>;
43
+ };
44
+
45
+ type TCallMethod = (
46
+ method: string,
47
+ params: Record<string, unknown>,
48
+ callback: (result: TCallMethodResult) => void
49
+ ) => void;
50
+
51
+ type TBatchClientConfig = {
52
+ callBatch?: TCallBatch;
53
+ callMethod?: TCallMethod;
54
+ };
55
+
56
+ type TTimeLimitState = {
57
+ limit: boolean;
58
+ date?: string;
59
+ pauseMs?: number;
60
+ };
61
+
41
62
  /**
42
63
  * Класс-обертка над BX24.callBatch с дополнительной логикой пагинации,
43
64
  * логированием и трекингом прогресса выполнения.
44
65
  */
45
66
  declare class Batch {
46
67
  /**
47
- * @param callBatch - проксированный метод BX24.callBatch
68
+ * @param callBatchOrConfig - функция callBatch или объект с callBatch/callMethod
48
69
  */
49
- constructor(callBatch: TCallBatch);
70
+ constructor(callBatchOrConfig: TCallBatch | TBatchClientConfig);
50
71
 
51
72
  /** Сохраненная ссылка на callBatch */
52
- private callBatch: TCallBatch;
73
+ private callBatch: TCallBatch | null;
74
+ /** Сохраненная ссылка на callMethod */
75
+ private callMethod: TCallMethod | null;
53
76
 
54
77
  /** Объект с результатами, где ключ совпадает с ключом исходного запроса */
55
78
  result: Record<string, unknown>;
56
79
  /** Объект ошибок, где ключ совпадает с ключом чанка, а значение описывает ошибку */
57
80
  errors: Record<string, string>;
81
+ /** Глобальное состояние лимита выполнения */
82
+ timeLimit: TTimeLimitState;
58
83
  /** Лимит команд в одном запросе (по умолчанию 50) */
59
84
  limit: number;
60
85
  /** Флаг продолжения выполнения запросов */
61
86
  canContinue: boolean;
62
87
  /** Callback прогресса выполнения batch */
63
88
  progressCall?: TBatchProgressCallback;
64
- /** Callback при достижении лимитов/ошибок времени выполнения */
65
- limitCall?: TBatchLimitCallback;
66
89
  /** Хранилище промежуточных данных прогресса */
67
90
  progressData: Record<string, { total: number; count: number }> | '';
68
91
  /** Таймер для обновления прогресса */
@@ -70,13 +93,19 @@ declare class Batch {
70
93
  /** Задержка между отправкой прогресса (мс) */
71
94
  progressDelay: number;
72
95
  /** Предыдущее значение процента прогресса */
73
- oldPercent: number | 'no';
96
+ oldPercent: number | null;
74
97
  /** Коэффициент чанков (используется при вычислении прогресса) */
75
98
  chunkRate: number | string;
76
99
  /** Общий прогресс выполнения в процентах */
77
100
  totalProgress: number;
78
- /** Список методов, которые нужно пропустить (например, при ошибках) */
79
- skipList: Set<string>;
101
+ /** Порог operating для включения лимит-паузы */
102
+ operatingThreshold: number;
103
+ /** Длительность лимит-паузы для batch (мс) */
104
+ defaultPauseMs: number;
105
+ /** Длительность лимит-паузы для одиночного `call` (callMethod), мс */
106
+ callLimitPauseMs: number;
107
+ /** Таймаут ожидания ответа от API (мс) */
108
+ requestTimeoutMs: number;
80
109
 
81
110
  /** Вычисление текущего прогресса выполнения batch-запросов */
82
111
  get progressPercent(): TBatchProgress;
@@ -98,20 +127,32 @@ declare class Batch {
98
127
 
99
128
  batch(
100
129
  commandList: TCommandList,
101
- progressCall?: TBatchProgressCallback,
102
- limitCall?: TBatchLimitCallback
130
+ progressCall?: TBatchProgressCallback
103
131
  ): Promise<TBatchResult>;
104
132
 
105
133
  batchTotalCount(
106
134
  commandList: TCommandList,
107
- progressCall?: TBatchProgressCallback,
108
- limitCall?: TBatchLimitCallback
135
+ progressCall?: TBatchProgressCallback
109
136
  ): Promise<TBatchResult>;
110
137
 
138
+ /**
139
+ * Одиночный REST-вызов через callMethod с таймаутом и лимит-ретраями.
140
+ */
141
+ call(params: {
142
+ method: string;
143
+ params?: Record<string, unknown>;
144
+ }): Promise<{
145
+ success: boolean;
146
+ data: unknown | false;
147
+ answer: Record<string, unknown>;
148
+ error: string | null;
149
+ }>;
150
+
111
151
  /** Выполнение одного чанка запросов */
112
152
  batchChunk(
113
153
  commandList: Record<string, TCommand>,
114
- type?: 'count'
154
+ type?: 'count',
155
+ shouldPauseAfterResult?: boolean
115
156
  ): Promise<Record<string, unknown>>;
116
157
 
117
158
  /** Рекурсивная пагинация для списочных методов */
@@ -133,6 +174,8 @@ export type {
133
174
  TBatchResult,
134
175
  TBatchProgress,
135
176
  TBatchProgressCallback,
136
- TBatchLimitCallback,
137
177
  TCallBatch,
178
+ TCallMethod,
179
+ TBatchClientConfig,
180
+ TTimeLimitState,
138
181
  };
@@ -3,7 +3,7 @@ import type {
3
3
  TCommandList,
4
4
  TBatchResult,
5
5
  TBatchProgressCallback,
6
- TBatchLimitCallback,
6
+ TTimeLimitState,
7
7
  } from './batch';
8
8
  import type BxLogger from './bx-logger';
9
9
 
@@ -16,7 +16,6 @@ type BxAppConst = {
16
16
  appName: string;
17
17
  pathApp: string;
18
18
  appNameEng?: string;
19
- zip?: string;
20
19
  chatBotLogo?: string;
21
20
  entity?: BxAppEntity[];
22
21
  };
@@ -45,8 +44,6 @@ type UpdateList = UpdateListItem[];
45
44
  type BatchOptions = {
46
45
  updateList?: UpdateList;
47
46
  errorCall?: (errors: Record<string, string>) => void;
48
- limitCommandSerial?: number;
49
- limitCall?: TBatchLimitCallback;
50
47
  };
51
48
 
52
49
  type LoggerStub = {
@@ -74,6 +71,8 @@ declare class BxBoot {
74
71
  placeInfo: { placement: string; options: Record<string, string> } | null;
75
72
  /** Экземпляр логгера или заглушка, если логирование отключено */
76
73
  logger: false | BxLogger | LoggerStub;
74
+ /** Глобальное состояние лимита запросов для UI */
75
+ timeLimit: TTimeLimitState;
77
76
 
78
77
  /** Инициализация SDK BX24 */
79
78
  init(): Promise<boolean>;
package/package.json CHANGED
@@ -1,41 +1,44 @@
1
- {
2
- "name": "szdl-utils-kit",
3
- "description": "utils-kit library",
4
- "private": false,
5
- "version": "0.3.14",
6
- "type": "module",
7
- "author": "Stanislav Ovv",
8
- "license": "BSD",
9
- "module": "./dist/index.js",
10
- "main": "./dist/index.umd.cjs",
11
- "types": "./dist/types/index.d.ts",
12
- "exports": {
13
- ".": {
14
- "import": "./dist/index.js",
15
- "require": "./dist/index.umd.cjs"
16
- }
17
- },
18
- "files": [
19
- "dist"
20
- ],
21
- "keywords": [
22
- "szdl",
23
- "utils",
24
- "szdl-utils-kit"
25
- ],
26
- "scripts": {
27
- "dev": "vite --host",
28
- "watch": "vite build --watch",
29
- "build": "vite build",
30
- "preview": "vite preview",
31
- "pub": "npm version patch --no-git-tag-version && npm publish"
32
- },
33
- "devDependencies": {
34
- "vite": "^4.4.5",
35
- "vite-plugin-dts": "^3.6.0",
36
- "vite-plugin-static-copy": "^0.17.0"
37
- },
38
- "dependencies": {
39
- "tempusjs": "^0.2.18"
40
- }
41
- }
1
+ {
2
+ "name": "szdl-utils-kit",
3
+ "description": "utils-kit library",
4
+ "private": false,
5
+ "version": "0.3.16",
6
+ "type": "module",
7
+ "author": "Stanislav Ovv",
8
+ "license": "BSD",
9
+ "module": "./dist/index.js",
10
+ "main": "./dist/index.umd.cjs",
11
+ "types": "./dist/types/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "import": "./dist/index.js",
15
+ "require": "./dist/index.umd.cjs"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "keywords": [
22
+ "szdl",
23
+ "utils",
24
+ "szdl-utils-kit"
25
+ ],
26
+ "scripts": {
27
+ "dev": "vite --host",
28
+ "watch": "vite build --watch",
29
+ "build": "vite build",
30
+ "preview": "vite preview",
31
+ "test": "vitest",
32
+ "test:run": "vitest run",
33
+ "pub": "npm version patch --no-git-tag-version && npm publish"
34
+ },
35
+ "devDependencies": {
36
+ "vitest": "^2.1.9",
37
+ "vite": "^4.4.5",
38
+ "vite-plugin-dts": "^3.6.0",
39
+ "vite-plugin-static-copy": "^0.17.0"
40
+ },
41
+ "dependencies": {
42
+ "tempusjs": "^0.2.18"
43
+ }
44
+ }