szdl-utils-kit 0.3.29 → 0.3.31

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 Je=Object.defineProperty;var je=(M,w,P)=>w in M?Je(M,w,{enumerable:!0,configurable:!0,writable:!0,value:P}):M[w]=P;var C=(M,w,P)=>(je(M,typeof w!="symbol"?w+"":w,P),P),ne=(M,w,P)=>{if(!w.has(M))throw TypeError("Cannot "+P)};var b=(M,w,P)=>(ne(M,w,"read from private field"),P?P.call(M):w.get(M)),E=(M,w,P)=>{if(w.has(M))throw TypeError("Cannot add the same private member more than once");w instanceof WeakSet?w.add(M):w.set(M,P)},X=(M,w,P,lt)=>(ne(M,w,"write to private field"),lt?lt.call(M,P):w.set(M,P),P);var y=(M,w,P)=>(ne(M,w,"access private method"),P);(function(M,w){typeof exports=="object"&&typeof module<"u"?w(exports):typeof define=="function"&&define.amd?define(["exports"],w):(M=typeof globalThis<"u"?globalThis:M||self,w(M["szdl-utils-kit"]={}))})(this,function(M){var Dt,Ne,kt,Bt,Ct,wt,ct,Zt,Ht,Oe,Ut,_e,st,bt,rt,Mt,yt,ae,it,St,Pt,Te,Gt,Ee,ht,Vt,pt,oe,Nt,Ae,nt,Z,V,at,ut,Ot,$,J,ot,ft,Yt,Re,_t,le,Wt,Le,xt,be,Ft,Me,dt,$t,vt,Se,Tt,ce,Xt,Ie,Jt,De,jt,ke,tt,mt,Et,he,Kt,Be,Rt,ue,qt,Ce,zt,we,Lt,fe,At,It,Qt,He;"use strict";var w=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function P(_){return _&&_.__esModule&&Object.prototype.hasOwnProperty.call(_,"default")?_.default:_}var lt={exports:{}};(function(_,e){(function(t){Array.prototype.indexOf||(Array.prototype.indexOf=function(s,o){var d,g;for(d=o||0,g=this.length;d<g;d+=1)if(this[d]===s)return d;return-1});var r=this,i=function(s,o){for(var d=s.toString();d.length<o;)d="0"+d;return d},a=function(s,o){return o!==t?(s.year(o.year()||o.year),s.month(o.month()||o.month),s.day(o.day()||o.day),s.hours(o.hours()||o.hours),s.minutes(o.minutes()||o.minutes),s.seconds(o.seconds()||o.seconds),s.milliseconds(o.milliseconds()||o.milliseconds),s):t},l=function(s,o){var d,g="";return d=s.slice(o,o+1),d!==""&&!isNaN(Number(d))&&(g+="%H"),d=s.charAt(o+2),d!==""&&d===":"&&(g+=d),d=s.slice(o+3,o+4),d!==""&&!isNaN(Number(d))&&(g+="%M"),d=s.charAt(o+5),d!==""&&d===":"&&(g+=d),d=s.slice(o+6,o+7),d!==""&&!isNaN(Number(d))&&(g+="%S"),g},h=function(s,o){var d,g=[s.slice(o,o+1),s.charAt(o+2),s.slice(o+3,o+4),s.charAt(o+5),s.slice(o+6,o+9)],G;return!isNaN(Number(g[0]))&&!isNaN(Number(g[2]))&&!isNaN(Number(g[4]))?(g[1]==="."&&g[3]==="."?d="%d.%m.%Y":g[1]==="-"&&g[3]==="-"?d="%m-%d-%Y":g[1]==="/"&&g[3]==="/"&&(d="%m/%d/%Y"),d):(G=[s.slice(o,o+3),s.charAt(o+4),s.slice(o+5,o+6),s.charAt(o+7),s.slice(o+8,o+9)],!isNaN(Number(G[0]))&&!isNaN(Number(G[2]))&&!isNaN(Number(G[4]))?(G[1]==="-"&&G[3]==="-"&&(d="%Y-%m-%d"),d):"")},u=r.tempus,n,m,f=r.navigator||{},A="en",c={en:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"Mar",APRIL_SHORT:"Apr",MAY_SHORT:"May",JUNE_SHORT:"Jun",JULY_SHORT:"Jul",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sep",OCTOBER_SHORT:"Oct",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dec",JANUARY_LONG:"January",FEBRUARY_LONG:"February",MARCH_LONG:"March",APRIL_LONG:"April",MAY_LONG:"May",JUNE_LONG:"June",JULY_LONG:"July",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"October",NOVEMBER_LONG:"November",DECEMBER_LONG:"December",SUNDAY_SHORT:"Sun",MONDAY_SHORT:"Mon",TUESDAY_SHORT:"Tue",WEDNESDAY_SHORT:"Wed",THURSDAY_SHORT:"Thu",FRIDAY_SHORT:"Fri",SATURDAY_SHORT:"Sat",SUNDAY_LONG:"Sunday",MONDAY_LONG:"Monday",TUESDAY_LONG:"Tuesday",WEDNESDAY_LONG:"Wednesday",THURSDAY_LONG:"Thursday",FRIDAY_LONG:"Friday",SATURDAY_LONG:"Saturday"},ru:{JANUARY_SHORT:"Янв",FEBRUARY_SHORT:"Фев",MARCH_SHORT:"Мар",APRIL_SHORT:"Апр",MAY_SHORT:"Май",JUNE_SHORT:"Июн",JULY_SHORT:"Июл",AUGUST_SHORT:"Авг",SEPTEMBER_SHORT:"Сен",OCTOBER_SHORT:"Окт",NOVEMBER_SHORT:"Ноя",DECEMBER_SHORT:"Дек",JANUARY_LONG:"Январь",FEBRUARY_LONG:"Февраль",MARCH_LONG:"Март",APRIL_LONG:"Апрель",MAY_LONG:"Май",JUNE_LONG:"Июнь",JULY_LONG:"Июль",AUGUST_LONG:"Август",SEPTEMBER_LONG:"Сентябрь",OCTOBER_LONG:"Октябрь",NOVEMBER_LONG:"Ноябрь",DECEMBER_LONG:"Декабрь",SUNDAY_SHORT:"Вс",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Воскресенье",MONDAY_LONG:"Понедельник",TUESDAY_LONG:"Вторник",WEDNESDAY_LONG:"Среда",THURSDAY_LONG:"Четверг",FRIDAY_LONG:"Пятница",SATURDAY_LONG:"Суббота"},ua:{JANUARY_SHORT:"Січ",FEBRUARY_SHORT:"Лют",MARCH_SHORT:"Берез",APRIL_SHORT:"Квіт",MAY_SHORT:"Трав",JUNE_SHORT:"Черв",JULY_SHORT:"Лип",AUGUST_SHORT:"Серп",SEPTEMBER_SHORT:"Верес",OCTOBER_SHORT:"Жовт",NOVEMBER_SHORT:"Листоп",DECEMBER_SHORT:"Груд",JANUARY_LONG:"Січень",FEBRUARY_LONG:"Лютий",MARCH_LONG:"Березень",APRIL_LONG:"Квітень",MAY_LONG:"Травень",JUNE_LONG:"Червень",JULY_LONG:"Липень",AUGUST_LONG:"Серпень",SEPTEMBER_LONG:"Вересень",OCTOBER_LONG:"Жовтень",NOVEMBER_LONG:"Листопад",DECEMBER_LONG:"Грудень",SUNDAY_SHORT:"Нд",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Неділя",MONDAY_LONG:"Понеділок",TUESDAY_LONG:"Вівторок",WEDNESDAY_LONG:"Середа",THURSDAY_LONG:"Четвер",FRIDAY_LONG:"П’ятниця",SATURDAY_LONG:"Субота"},de:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"März",APRIL_SHORT:"Apr",MAY_SHORT:"Mai",JUNE_SHORT:"Juni",JULY_SHORT:"Juli",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sept",OCTOBER_SHORT:"Okt",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dez",JANUARY_LONG:"Januar",FEBRUARY_LONG:"Februar",MARCH_LONG:"März",APRIL_LONG:"April",MAY_LONG:"Mai",JUNE_LONG:"Juni",JULY_LONG:"Juli",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"Oktober",NOVEMBER_LONG:"November",DECEMBER_LONG:"Dezember",SUNDAY_SHORT:"So",MONDAY_SHORT:"Mo",TUESDAY_SHORT:"Di",WEDNESDAY_SHORT:"Mi",THURSDAY_SHORT:"Do",FRIDAY_SHORT:"Fr",SATURDAY_SHORT:"Sa",SUNDAY_LONG:"Sonntag",MONDAY_LONG:"Montag",TUESDAY_LONG:"Dienstag",WEDNESDAY_LONG:"Mittwoch",THURSDAY_LONG:"Donnerstag",FRIDAY_LONG:"Freitag",SATURDAY_LONG:"Samstag"}},p=function(){return[c[A].JANUARY_LONG,c[A].FEBRUARY_LONG,c[A].MARCH_LONG,c[A].APRIL_LONG,c[A].MAY_LONG,c[A].JUNE_LONG,c[A].JULY_LONG,c[A].AUGUST_LONG,c[A].SEPTEMBER_LONG,c[A].OCTOBER_LONG,c[A].NOVEMBER_LONG,c[A].DECEMBER_LONG]},O=function(){return[c[A].JANUARY_SHORT,c[A].FEBRUARY_SHORT,c[A].MARCH_SHORT,c[A].APRIL_SHORT,c[A].MAY_SHORT,c[A].JUNE_SHORT,c[A].JULY_SHORT,c[A].AUGUST_SHORT,c[A].SEPTEMBER_SHORT,c[A].OCTOBER_SHORT,c[A].NOVEMBER_SHORT,c[A].DECEMBER_SHORT]},L=function(){return[c[A].SUNDAY_LONG,c[A].MONDAY_LONG,c[A].TUESDAY_LONG,c[A].WEDNESDAY_LONG,c[A].THURSDAY_LONG,c[A].FRIDAY_LONG,c[A].SATURDAY_LONG]},B=function(){return[c[A].SUNDAY_SHORT,c[A].MONDAY_SHORT,c[A].TUESDAY_SHORT,c[A].WEDNESDAY_SHORT,c[A].THURSDAY_SHORT,c[A].FRIDAY_SHORT,c[A].SATURDAY_SHORT]},T,R,x,N,I=function(s,o,d){var g;r.XMLHttpRequest?g=new XMLHttpRequest:g=new ActiveXObject("Microsoft.XMLHTTP"),g.onreadystatechange=function(){g.readyState===4&&(g.status===200?o&&(r.JSON===t?alert(`Please, include json2 into your project if you want use old browsers!
2
- https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(g.responseText))):d&&d(g))},g.open("GET",s,!1),g.send()},D={"%d":{format:function(s){return i(s.day()||n.MIN_DAY,2)},parse:function(s){var o=Number(s);return{day:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(s){return i(s.month()||n.MIN_MONTH,2)},parse:function(s){var o=Number(s);return{month:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(s){return i(s.year()||n.MIN_YEAR,4)},parse:function(s){var o=Number(s);return{year:isNaN(o)?t:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(s){return s.dayOfWeek()||n.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(s){var o=s.dayOfWeek();return N[o!==t?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(s){var o=s.dayOfWeek();return x[o!==t?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(s){var o=n.options("monthFromZero")?s.month():s.month()-1;return R[o!==t?o:n.MIN_MONTH]},parse:function(s){var o=n.monthNames().indexOf(s)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:t}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(s){var o=n.options("monthFromZero")?s.month():s.month()-1;return T[o!==t?o:n.MIN_MONTH]},parse:function(s){var o=n.monthNames(!0).indexOf(s)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:t}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(s){return i(s.hours()||n.MIN_HOURS,2)},parse:function(s){var o=Number(s);return{hours:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(s){return i(s.minutes()||n.MIN_MINUTES,2)},parse:function(s){var o=Number(s);return{minutes:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(s){return i(s.seconds()||n.MIN_SECONDS,2)},parse:function(s){var o=Number(s);return{seconds:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(s){return s.timestamp()},parse:function(s){return isNaN(Number(s))?{}:n(Number(s)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(s){return i(s.year()||n.MIN_YEAR,4)+"-"+i(s.month()||n.MIN_MONTH,2)+"-"+i(s.day()||n.MIN_DAY,2)},parse:function(s){var o=Number(s.slice(0,4)),d=Number(s.slice(5,7)),g=Number(s.slice(8,10));return{year:o,month:d,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(s){return i(s.month()||n.MIN_MONTH,2)+"/"+i(s.day()||n.MIN_DAY,2)+"/"+i(s.year()||n.MIN_YEAR,4)},parse:function(s){var o=Number(s.slice(0,2)),d=Number(s.slice(3,5)),g=Number(s.slice(6,10));return{year:g,month:o,day:d}},minLength:10,maxLength:10,type:"string"}},U={useMilliseconds:!1,monthFromZero:!1},S;S=function(s,o,d){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},s!==t&&this.set(s,o,d),this},S.fn=S.prototype,S.fn.dayCount=function(){var s=this.month(),o=n.MAX_DAY_IN_MONTHS[s-(n.options("monthFromZero")?0:1)];return this.leapYear()&&s===(n.options("monthFromZero")?1:2)&&(o+=1),o},S.fn.year=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_YEAR&&Number(s)<=n.MAX_YEAR?(this._d.setFullYear(Number(s)),this._i.year=!1):this._i.year=Number(s):(this._d.setFullYear(n.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},S.fn.month=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MONTH&&Number(s)<=n.MAX_MONTH?(this._d.setMonth(n.options("monthFromZero")?Number(s):Number(s)-1),this._i.month=!1):this._i.month=Number(s):(this._d.setMonth(n.options("monthFromZero")?n.MIN_MONTH:n.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?n.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},S.fn.day=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_DAY&&Number(s)<=this.dayCount()?(this._d.setDate(Number(s)),this._i.day=!1):this._i.day=Number(s):(this._d.setDate(n.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},S.fn.hours=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_HOURS&&Number(s)<=n.MAX_HOURS?(this._d.setHours(Number(s)),this._i.hours=!1):this._i.hours=Number(s):(this._d.setHours(n.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},S.fn.minutes=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MINUTES&&Number(s)<=n.MAX_MINUTES?(this._d.setMinutes(Number(s)),this._i.minutes=!1):this._i.minutes=Number(s):(this._d.setMinutes(n.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},S.fn.seconds=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_SECONDS&&Number(s)<=n.MAX_SECONDS?(this._d.setSeconds(Number(s)),this._i.seconds=!1):this._i.seconds=Number(s):(this._d.setSeconds(n.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},S.fn.milliseconds=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MILLISECONDS&&Number(s)<=n.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(s)),this._i.milliseconds=!1):this._i.milliseconds=Number(s):(this._d.setMilliseconds(n.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},S.fn.week=function(){var s=new Date(this.year(),0,1),o=n(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-s.getTime())/864e5+s.getDay()+1)/7)},S.fn.set=function(s,o,d){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},s===t)return this._d=new Date,this;if(s instanceof Date)return this._d=s,this;if(typeof s=="number")return this._d=new Date(s*(n.options("useMilliseconds")?1:1e3)),this;if(typeof s=="object"&&(s instanceof Array?(this.day(n.MIN_DAY),this.year(s[0]),this.month(s[1]),this.day(s[2]),this.hours(s[3]),this.minutes(s[4]),this.seconds(s[5]),this.milliseconds(s[6])):(this.day(n.MIN_DAY),this.year(s.year),this.month(s.month),this.day(s.day),this.hours(s.hours),this.minutes(s.minutes),this.seconds(s.seconds),this.milliseconds(s.milliseconds))),typeof s=="string"){var g,G=[],k,H,et=[],v=0,j=0,Y,K,W={},F;if(s===t)return k=a(this,d),k===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),k;for(o===t&&(o=n.detectFormat(s));v<o.length;){if(o.charAt(v)==="%"){if(H=o.charAt(v)+o.charAt(v+1),D[H]!==t){switch(Y=0,K="",D[H].type){case"number":for(;Y<D[H].maxLength&&j+Y<s.length&&!isNaN(Number(s.charAt(j+Y)));)K+=s.charAt(j+Y),Y+=1;break;case"word":for(;Y<D[H].maxLength&&j+Y<s.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(s.charAt(j+Y));)K+=s.charAt(j+Y),Y+=1;break;case"string":for(;Y<D[H].maxLength&&j+Y<s.length;)K+=s.charAt(j+Y),Y+=1;break}if(Y<D[H].minLength)return k=a(this,d),k===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),k;G.push(H),et.push(K),Y-=1,j+=Y,v+=1}}else if(s.charAt(j)!==o.charAt(v))return k=a(this,d),k===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),k;v+=1,j+=1}for(g in G)G.hasOwnProperty(g)&&D.hasOwnProperty(G[g])&&(F=D[G[g]].parse(et[g]),W={year:F.year!==t?F.year:W.year,month:F.month!==t?F.month:W.month,day:F.day!==t?F.day:W.day,hours:F.hours!==t?F.hours:W.hours,minutes:F.minutes!==t?F.minutes:W.minutes,seconds:F.seconds!==t?F.seconds:W.seconds});this.day(n.MIN_DAY),this.year(W.year),this.month(W.month),this.day(W.day),this.hours(W.hours),this.minutes(W.minutes),this.seconds(W.seconds),this.milliseconds(W.milliseconds)}return this},S.fn.leapYear=function(){var s=this.year();return s%4===0?s%100===0?s%400===0:!0:!1},S.fn.timestamp=function(s){return arguments.length!==0?(this._d=new Date(Number(s)*(n.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):n.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},S.fn.utc=function(s){return arguments.length!==0?(this._d=new Date(Number(s)*(n.options("useMilliseconds")?1:1e3)),this):n.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},S.fn.dayOfWeek=function(s){if(s==="long")return x[this._d.getDay()];if(s==="short")return N[this._d.getDay()];if(s===t)return this._d.getDay();if(s===0||s==="Sunday")return this.calc({day:-this.dayOfWeek()});if(s===1||s==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(s===2||s==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(s===3||s==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(s===4||s==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(s===5||s==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(s===6||s==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},S.fn.timezone=function(s){switch(s){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},S.fn.get=function(s){switch(s){case"Date":return new Date(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds());case"DateUTC":return new Date(Date.UTC(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()));case"Array":return[this.year(),this.month(),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()];default:return{year:this.year(),month:this.month(),week:this.week(),day:this.day(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds(),utc:this.utc(),dayOfWeek:this.dayOfWeek(),dayOfWeekShort:this.dayOfWeek("short"),dayOfWeekLong:this.dayOfWeek("long"),timestamp:this.timestamp()}}},S.fn.format=function(s){for(var o=0,d="",g;o<s.length;)s.charAt(o)==="%"?(g=s.charAt(o)+s.charAt(o+1),D[g]!==t?(d+=D[g].format(this),o+=1):d+="%"):d+=s.charAt(o),o+=1;return d},S.fn.valid=function(){return this._i.year===!1&&this._i.month===!1&&this._i.day===!1&&this._i.hours===!1&&this._i.minutes===!1&&this._i.seconds===!1&&this._i.milliseconds===!1},S.fn.errors=function(){return this._i},S.fn.between=function(s,o){var d=this.timestamp(),g=s.timestamp();switch(o){case"year":return Math.floor((g-d)/31556952);case"month":return Math.floor((g-d)/2629746);case"day":return Math.floor((g-d)/86400);case"hours":return Math.floor((g-d)/3600);case"minutes":return Math.floor((g-d)/60);case"seconds":return g-d;default:return t}},S.fn.calc=function(s){return s.year!==t&&this._d.setFullYear(this._d.getFullYear()+s.year),s.month!==t&&this._d.setMonth(this._d.getMonth()+s.month),s.day!==t&&this._d.setDate(this._d.getDate()+s.day),s.hours!==t&&this._d.setHours(this._d.getHours()+s.hours),s.minutes!==t&&this._d.setMinutes(this._d.getMinutes()+s.minutes),s.seconds!==t&&this._d.setSeconds(this._d.getSeconds()+s.seconds),s.milliseconds!==t&&this._d.setMilliseconds(this._d.getMilliseconds()+s.milliseconds),this},n=function(s,o,d){return new S(s,o,d)},n.MIN_YEAR=1e3,n.MAX_YEAR=3e3,n.MIN_MONTH=1,n.MAX_MONTH=12,n.MIN_DAY=1,n.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],n.MIN_DAY_OF_WEEK=0,n.MAX_DAY_OF_WEEK=6,n.MIN_HOURS=0,n.MAX_HOURS=23,n.MIN_MINUTES=0,n.MAX_MINUTES=59,n.MIN_SECONDS=0,n.MAX_SECONDS=59,n.MIN_MILLISECONDS=0,n.MAX_MILLISECONDS=999,n.VERSION="0.2.18",n.options=function(s,o){if(s===t)return U;if(U.hasOwnProperty(s)){if(o===t)return U[s];U[s]=o,s==="monthFromZero"&&(n.MIN_MONTH=o?0:1,n.MAX_MONTH=o?11:12)}return t},n.noConflict=function(){return r.tempus=u,n},n.generate=function(s){var o,d,g,G,k,H,et,v;if(typeof s.dateFrom!="number"&&(s.dateFrom instanceof S?o=s.dateFrom.utc():o=n(s.dateFrom,s.formatFrom).utc()),typeof s.dateTo!="number"&&(s.dateTo instanceof S?d=s.dateTo.utc():d=n(s.dateTo,s.formatTo!==t?s.formatTo:s.formatFrom).utc()),typeof s.period=="number"?k={year:0,month:0,day:0,hours:0,minutes:0,seconds:s.period}:typeof s.period=="string"?k={year:s.period==="year"?1:0,month:s.period==="month"?1:0,day:s.period==="day"?1:0,hours:s.period==="hours"?1:0,minutes:s.period==="minutes"?1:0,seconds:s.period==="seconds"?1:0}:typeof s.period=="object"&&(k={year:s.period.year!==t?s.period.year:0,month:s.period.month!==t?s.period.month:0,day:s.period.day!==t?s.period.day:0,hours:s.period.hours!==t?s.period.hours:0,minutes:s.period.minutes!==t?s.period.minutes:0,seconds:s.period.seconds!==t?s.period.seconds:0}),s.groupBy===t?H=s.asObject===!0?{}:[]:(H=[],H.push([]),et=n(o).get()[s.groupBy]),v=function(K,W,F){return s.asObject===!0?s.format!==t?K[n(W).format(s.format)]={}:K[n(W).format("%F %H:%M:%S")]={}:s.format!==t?K.push(F?null:n(W).format(s.format)):K.push(F?null:n(W)),K},s.groupBy!==t&&s.fillNulls){var j={year:k.year?-k.year:t,month:k.month?-k.month:t,day:k.day?-k.day:t,hours:k.hours?-k.hours:t,minutes:k.minutes?-k.minutes:t,seconds:k.seconds?-k.seconds:t,milliseconds:k.milliseconds?-k.milliseconds:t};for(g=n(o).calc(j).utc();n(g).get()[s.groupBy]===et;)v(H[H.length-1],g,!0),g=n(g).calc(j).utc();if(s.groupBy==="week"){var Y=n(o).dayOfWeek();for(g=n(o).dayOfWeek(0).utc();H[0].length<Y&&g<o;)v(H[H.length-1],g,!0),g=n(g).calc(k).utc()}}for(;o<=d;)s.groupBy===t?v(H,o):n(o).get()[s.groupBy]===et?v(H[H.length-1],o):(H.push([]),v(H[H.length-1],o),et=n(o).get()[s.groupBy]),o=n(o).calc(k).utc();if(s.groupBy!==t&&s.fillNulls)for(G=n(d).calc(k).utc();n(G).get()[s.groupBy]===et;)v(H[H.length-1],G,!0),G=n(G).calc(k).utc();return H},n.monthNames=function(s){switch(s){case"long":return T;default:return R}},n.dayNames=function(s){switch(s){case"long":return x;default:return N}},n.lang=function(s){if(s!==t)A=s,c[A]===t&&(A="en"),T=p(),R=O(),x=L(),N=B();else return A;return t},n.availableLangs=function(){return Object.keys(c)},n.registerFormat=function(s,o,d,g,G,k){D[s]={format:o,parse:d,minLength:g,maxLength:G,type:k}},n.unregisterFormat=function(s){delete D[s]},n.detectFormat=function(s){var o,d,g;return o=h(s,0),o!==""&&(g=10),d=s.charAt(g),(d==="T"||d===" ")&&(o+=d,g+=1),o+=l(s,g),o},m={TempusDate:S},n.classes=function(s,o){if(o===t)return m[s];m[s]=o},n.loadTranslations=function(s){typeof s=="object"?c=s:typeof s=="string"&&I(s,function(o){c=o},function(o){})},A=(f.language||f.systemLanguage||f.userLanguage||"en").substr(0,2).toLowerCase(),c[A]===t&&(A="en"),T=p(),R=O(),x=L(),N=B(),_.exports&&(e=_.exports=n),e.tempus=n}).call(w)})(lt,lt.exports);var Ue=lt.exports;const gt=P(Ue),Q=class Q{constructor(e){E(this,Dt);E(this,ct);E(this,Ht);E(this,Ut);E(this,st);E(this,rt);E(this,yt);E(this,it);E(this,Pt);E(this,Gt);E(this,ht);E(this,pt);E(this,Nt);typeof e=="function"?(this.callBatch=e,this.callMethod=null):(this.callBatch=(e==null?void 0:e.callBatch)||null,this.callMethod=(e==null?void 0:e.callMethod)||null),this.result={},this.errors={},this.errorMessages={},this.timeLimit={limit:!1,date:void 0,pauseMs:void 0},this.timeLimitListeners=new Set,this.canContinue=!0,this.progressCall="",this.progressData="",this.progressTimer="",this.lastProgressSnapshot=null,this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.filterChunkSize=50,this.limit=50,this.progressDelay=100,this.operatingThreshold=475,this.defaultPauseMs=12e4,this.callLimitPauseMs=3e4,this.requestTimeoutMs=6e4}get progressPercent(){if(!this.progressData)return{percent:0,allCount:0,allTotal:0};const e=this.totalBatchCommands||0;if(e>0&&Array.isArray(this.batchCommandKeyOrder)&&this.batchCommandKeyOrder.length&&y(this,Dt,Ne).call(this)){let u=0;for(const c of this.batchCommandKeyOrder){const p=this.progressData[c];if(!p)continue;const O=Number(p.total)||0,L=Number(p.count)||0;O===0&&L===0?u+=1:O>0&&(u+=Math.min(1,L/O))}const n=u/e*100;let m=Math.max(0,Math.min(100,Math.floor(n)));const f=e,A=Math.min(e,Math.floor(u));return{percent:m,allCount:A,allTotal:f}}let t=0,r=0;for(const u of Object.values(this.progressData)){const{total:n,count:m}=u;t+=n??0,r+=m??0}const i=Number(this.chunkRate)||0;let a=0;t?a=r/t*100*i+this.totalProgress:r===0&&t===0?a=i<1?this.totalProgress:100*i+this.totalProgress:a=100,a=Math.max(0,Math.min(a,100));let l=Math.floor(a);const h=Number(this.chunkRate)||0;return t>0&&r>=t&&h>=1&&(l=100),{percent:l,allCount:r,allTotal:t}}setProgressData({key:e,value:t,type:r}){var c,p;if(!this.progressCall)return;const i=this.getData(t.data()),a=Array.isArray(i)?i.length:0;let l=a;if(typeof t.total=="function"){const O=t.total();if(O!=null&&O!==""){const L=Number(O);Number.isFinite(L)&&(l=L)}}let h=1;r==="count"?(l||(l=a),h=l>0?l:a>0?a:1):i&&(h=a),this.progressData||(this.progressData={});const u=((c=this.progressData[e])==null?void 0:c.total)??0,n=((p=this.progressData[e])==null?void 0:p.count)??0,m=h+n,f=Math.max(u,l??0,m);if(this.progressData[e]={total:f,count:Math.min(m,f)},typeof document<"u"&&(document==null?void 0:document.hidden)===!0){y(this,ct,Zt).call(this);return}y(this,ct,Zt).call(this),this.progressTimer||(this.progressTimer=setInterval(()=>{if(!this.progressCall){this.clearProgressData();return}y(this,ct,Zt).call(this);const{percent:O}=this.progressPercent;O>=100&&(clearInterval(this.progressTimer),this.progressTimer="")},this.progressDelay))}getData(e){if(e==null)return e;let t=(e==null?void 0:e.items)??(e==null?void 0:e.tasks)??(e==null?void 0:e.types)??(e==null?void 0:e.type)??(e==null?void 0:e.fields)??(e==null?void 0:e.workgroups)??e;return t&&typeof t=="object"&&!Array.isArray(t)&&Array.isArray(t.result)&&(t=t.result),t}setTimeLimitState(e,t,r){this.timeLimit.limit=!!e,this.timeLimit.date=e?t:void 0,e&&typeof r=="number"&&r>0?this.timeLimit.pauseMs=r:this.timeLimit.pauseMs=void 0,y(this,Ut,_e).call(this)}subscribeTimeLimit(e){return typeof e!="function"?()=>{}:(this.timeLimitListeners.add(e),e({limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs}),()=>{this.timeLimitListeners.delete(e)})}splitLargeFilters(e,t){const{method:r,params:i}=t;if(!i)return[{key:e,request:t}];const a=i.filter||i.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:e,request:t}];for(const[l,h]of Object.entries(a))if(!String(l).trim().startsWith("!")&&Array.isArray(h)&&h.length>this.filterChunkSize){const u=[];for(let n=0;n<h.length;n+=this.filterChunkSize){const m=h.slice(n,n+this.filterChunkSize),f=n===0?e:`${e}__chunk_${Math.floor(n/this.filterChunkSize)}`,A={...i};i.filter?(A.filter={...a},A.filter[l]=m):i.FILTER&&(A.FILTER={...a},A.FILTER[l]=m),u.push({key:f,request:{method:r,params:A},originalKey:e,filterKey:l,chunkIndex:Math.floor(n/this.filterChunkSize)})}return u}return[{key:e,request:t}]}mergeSplitResults(e,t){const r=[],i=String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${i}(?:__chunk_\\d+)?$`),l=Object.keys(e).filter(h=>a.test(h)).sort((h,u)=>{const n=h.match(/__chunk_(\d+)$/),m=u.match(/__chunk_(\d+)$/);return n?m?parseInt(n[1])-parseInt(m[1]):1:-1});for(const h of l){const u=e[h];Array.isArray(u)?r.push(...u):u&&r.push(u)}return r}delay(){return typeof document<"u"&&(document==null?void 0:document.hidden)===!0?Promise.resolve():new Promise(t=>setTimeout(t,500))}callBatchWithTimeout(e,t,r={}){const{onLateResponse:i}=r;return new Promise((a,l)=>{let h=!1,u=null;const n=async f=>{if(h)typeof i=="function"&&i(f);else{h=!0,u&&clearTimeout(u);try{await Promise.resolve(t(f)),a()}catch(A){console.error("Error in callBatch callback:",A),l(A)}}},m=async()=>{if(!h){h=!0,u&&clearTimeout(u),console.warn(`Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`);const f={};Object.keys(e).forEach(A=>{f[A]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 60 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(t(f)),a()}catch(A){console.error("Error in timeout callback:",A),a()}}};try{this.callBatch(e,async f=>{await n(f)})}catch(f){h||console.error("Error calling callBatch:",f)}u=setTimeout(async()=>{h||(console.warn(`Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`),await m())},this.requestTimeoutMs)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.lastProgressSnapshot=null}async batch(e,t,r={}){y(this,Nt,Ae).call(this,t);const i={},a={},l={};for(const[m,f]of Object.entries(e)){const A=this.arrayChunk(f);if(!A)continue;const c=this.splitLargeFilters(m,A);if(c.length===1)a[m]=A;else{l[m]=[];for(const p of c)a[p.key]=p.request,l[m].push(p.key)}}this.batchCommandKeyOrder=Object.keys(a),this.totalBatchCommands=this.batchCommandKeyOrder.length,this.batchCommandMethods=this.batchCommandKeyOrder.map(m=>{var f;return String(((f=a[m])==null?void 0:f.method)||"")}),this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let h={},u=0;const n=Object.keys(a).length;for(const[m,f]of Object.entries(a)){if(!this.canContinue)break;if(h[m]=f,Object.keys(h).length>=this.limit||u+1===n){const A=u+1===n;await this.batchChunk(h,void 0,!A,{disablePagination:!1,oneBatch:!!(r!=null&&r.oneBatch)}),Object.entries(this.result).forEach(([c,p])=>{i[c]=p}),this.totalProgress=Math.round(u/n*100),h={}}u++}for(const[m,f]of Object.entries(l))if(f&&f.length>0){const A=this.mergeSplitResults(i,m);for(const c of f)delete i[c];i[m]=A}return y(this,pt,oe).call(this,i),t&&t({percent:100}),Promise.resolve(i)}async batchTotalCount(e,t){y(this,Nt,Ae).call(this,t);const r={},i={},a={};for(const[u,n]of Object.entries(e)){const m=this.arrayChunk(n);if(!m)continue;const f=this.splitLargeFilters(u,m);if(f.length===1)i[u]=m;else{a[u]=[];for(const A of f)i[A.key]=A.request,a[u].push(A.key)}}const l=[],h=Object.entries(i);for(let u=0;u<h.length;u+=this.limit){const n=h.slice(u,u+this.limit),m={};for(const[f,A]of n){if(!this.canContinue)break;m[f]=A}Object.keys(m).length>0&&l.push(m)}this.chunkRate=(1/l.length).toFixed(5);for(const[u,n]of Object.entries(l)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(u)/l.length*100),this.progressData={},this.lastProgressSnapshot=null;const m=Number(u)===l.length-1;await y(this,it,St).call(this,n,async f=>{for(const[A,c]of Object.entries(f)){if(!this.canContinue)return;if(c.error()){y(this,ht,Vt).call(this,A,c),r[A]=0;continue}const p=this.getData(c.data()),O=Array.isArray(p)?p.length:0,B=typeof c.total=="function"&&c.total()!==void 0?c.total():O;r[A]=B,this.setProgressData({key:A,value:c,type:"count"})}await y(this,rt,Mt).call(this,f,!m)})}for(const[u,n]of Object.entries(a))if(n&&n.length>0){let m=0;for(const f of n)r[f]!==void 0&&(m+=r[f]||0),delete r[f];r[u]=m}return Object.entries(this.errors).length&&(y(this,pt,oe).call(this,r),this.errorLogger()),t&&t({percent:100}),Promise.resolve(r)}async call({method:e,params:t={}}){var i,a,l,h,u,n,m;const r=y(this,yt,ae).call(this,this.callLimitPauseMs);for(;;){let f=await y(this,Pt,Te).call(this,e,t,{onLateResponse:p=>r.notifyLateResponse(p)});if(!f)if(r.inRetryCycle=!0,await r.waitForLateOrLimit(),r.lateResult)f=r.lateResult,r.resetLateResult(),r.inRetryCycle=!1;else continue;const A={};if(f!=null&&f.answer)for(const[p,O]of Object.entries(f.answer))p!=="result"&&O&&(A[p]=O);if(f.error()){const p=((a=(i=f.error())==null?void 0:i.ex)==null?void 0:a.error)??"";if(["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT","TIMEOUT"].includes(p)){await y(this,st,bt).call(this,this.callLimitPauseMs);continue}const O=((l=f.error())==null?void 0:l.toString())||((u=(h=f.error())==null?void 0:h.ex)==null?void 0:u.error_description)||((m=(n=f.error())==null?void 0:n.ex)==null?void 0:m.error)||"Неизвестная ошибка";return{success:!1,data:!1,answer:A,error:O}}let c=f.data();return c!=null&&c.items&&(c=c.items),r.inRetryCycle=!1,{success:!0,data:c,answer:A,error:null}}}arrayChunk(e){let t="",r={};if(Array.isArray(e)?[t]=e:(t=e.method,r=e.params),(t.includes("list")||t==="user.get"||t==="entity.item.get"||t==="sonet_group.get")&&t!=="task.item.list"){if(!r)r=t==="entity.item.get"?{SORT:{ID:"ASC"}}:t==="sonet_group.get"?{ORDER:{ID:"ASC"}}:{order:{ID:"ASC",id:"ASC"}};else{t==="entity.item.get"?(r.SORT||(r.SORT={ID:"ASC"}),Array.isArray(r.select)?r.select.includes("ID")||r.select.push("ID"):r.select=["ID"]):t==="sonet_group.get"?r.ORDER?!r.ORDER.ID&&!r.ORDER.id&&(r.ORDER.ID="ASC"):r.ORDER={ID:"ASC"}:t==="tasks.task.list"?(r.order||(r.order={}),r.order.ID="asc"):t==="user.get"?(r.sort||(r.sort="ID"),r.order||(r.order="ASC")):r.order={ID:"ASC",id:"ASC"},Array.isArray(r.select)&&!r.select.includes("ID")&&r.select.push("ID");const i=t==="user.get"||t==="entity.item.get"||t==="sonet_group.get"?r.FILTER:r.filter;typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.entries(i).forEach(([a,l])=>{(r.start===void 0||r.start!==-1)&&["id","ID"].includes(a)&&(typeof l=="string"||Array.isArray(l)&&l.length<=50)&&(r.start=-1)})}t==="crm.type.list"&&r.order&&delete r.order.ID}if(t==="task.item.list")if(!r)r=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(r[0])&&(r[0]={});const[i,a,l,h]=r;i.ID="ASC",h[0]!==""&&h.includes("ID")||h.push("ID")}return{method:t,params:r}}async batchChunk(e,t,r=!0,i={}){return new Promise(a=>{const l=[];let h;const u=!!(i!=null&&i.disablePagination);(async()=>{await y(this,it,St).call(this,e,async m=>{for(const[A,c]of Object.entries(m)){if(!this.canContinue)return;c.error()&&(y(this,ht,Vt).call(this,A,c),h=!0);const p=this.getData(c.data()),O=Array.isArray(p)?p.length:0,L=typeof c.total=="function"&&c.total()!==void 0,B=L?c.total():O;t==="count"?this.result[A]?this.result[A]+=O:this.result[A]=B:this.result[A]=p,this.setProgressData({key:A,value:c,type:t});const T=e[A],R=Array.isArray(T)?T[0]:T==null?void 0:T.method,x=typeof R=="string"&&(R.includes(".list")||R==="user.get"||R==="entity.item.get"||R==="sonet_group.get"),N=t==="count"?!L&&O===this.limit:x?O===this.limit:B>this.limit&&B>O,I=t!=="count"&&R==="entity.item.get"&&O===this.limit&&!N,D=N||I;if(!u&&(!this.canContinue||D)){let U=e[A];if(Array.isArray(U)){const[S,s={}]=U;U=[S,s]}else{const{method:S,params:s={}}=U;U=[S,s]}l.push([A,U,B,{entityItemGetScan:I}])}}h>0&&this.errorLogger();const f=l.length>0||r;await y(this,rt,Mt).call(this,m,f),l.length?await this.batchPayload(l,t,i).then(()=>a(this.result)):a(this.result)})})()})}async batchPayload(e,t,r={}){const i=!!(r!=null&&r.oneBatch),a=(p,O,L,B)=>{let T="ID";this.result[p][this.result[p].length-1].ID||(T="id");let R=`${T}`;if(JSON.stringify(B[1]).toLocaleLowerCase().includes('"id":"desc"')?R="<"+R:R=">"+R,O===1||L.length===0)return{field:R,id:this.result[p][this.result[p].length-1][T]};let N="";const[I,D]=B;return(I==="tasks.task.list"||I==="task.item.list")&&(N="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(I)&&(N="[items]"),I==="crm.type.list"&&(N="[types]"),I==="socialnetwork.api.workgroup.list"&&(N="[workgroups]"),{field:R,id:`$result[${[p,O-1].join("__")}]${N}[49][${T}]`}},l=(p,O)=>{const[L,B]=p;let T=JSON.parse(JSON.stringify(B)),R;if(L==="task.item.list"){T=[...T];const[x,N,I,D]=T;return N[O.field]=O.id,[L,T]}return["user.get","sonet_group.get"].includes(L)||T.FILTER?(T.FILTER||(T.FILTER={}),R=T.FILTER):(T.filter||(T.filter={}),R=T.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(L)?R[">ID"]=O.id:R[O.field]=O.id,[L,{...T,start:-1}]},h=p=>{Object.entries(p).forEach(([O,L])=>{const[B]=O.split("__"),T=this.getData(L.data());Array.isArray(T)&&(t==="count"?this.result[B]+=T.length:this.result[B].push(...T)),L.error()&&y(this,ht,Vt).call(this,B,L),this.setProgressData({key:B,value:L,type:t})})},u=(p,O)=>{if(!Array.isArray(p)||p.length===0)return null;const L=p[p.length-1];let B="ID";L.ID||(B="id");let T=B;return JSON.stringify(O[1]).toLocaleLowerCase().includes('"id":"desc"')?T="<"+T:T=">"+T,{field:T,id:L[B]}},n=1e4,m=async(p,O)=>{var B,T;let L=this.limit;for(let R=1;this.canContinue&&L===this.limit&&R<=n;R++){const x=this.result[p],N=u(x,O);if(!N)break;const I=`${p}__eiscan_${R}`,D=l(O,N);let U=null;await y(this,it,St).call(this,{[I]:D},async d=>{U=d,h(d)});const S=R<n;await y(this,rt,Mt).call(this,U,S),await this.delay();const s=U==null?void 0:U[I];if((B=s==null?void 0:s.error)!=null&&B.call(s)){L=0;break}const o=this.getData((T=s==null?void 0:s.data)==null?void 0:T.call(s));L=Array.isArray(o)?o.length:0}};let f=[],A=0;const c=async(p=!0)=>f.length?(await y(this,it,St).call(this,Object.fromEntries(f),async O=>{h(O),await y(this,rt,Mt).call(this,O,p)}),A++,f=[],i&&A>=1?!0:(await this.delay(),!1)):!1;for await(const p of e){if(!this.canContinue)return;const[O,L,B,T={}]=p;if(T.entityItemGetScan){if(await c(!0))return;if(i)continue;await m(O,L);continue}let R=1;for(;B>R*this.limit;){const x=[O,R].join("__"),N=a(O,R,f,L);if(f.push([x,l(L,N)]),i&&f.length===49&&await c(!0)||f.length%50===0&&await c(!0))return;R++}}await c(!1)}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([e,t])=>{t&&console.log(`[${e}]`,t.toString())}),console.groupEnd()}};Dt=new WeakSet,Ne=function(){const e=this.totalBatchCommands||0,t=this.batchCommandMethods;if(e<b(Q,kt)||!Array.isArray(t)||t.length!==e)return!1;if(t.filter(a=>a==="crm.deal.list").length>=b(Q,Bt))return!0;const i=t.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=b(Q,Ct)&&i/e>=b(Q,wt)},kt=new WeakMap,Bt=new WeakMap,Ct=new WeakMap,wt=new WeakMap,ct=new WeakSet,Zt=function(){if(!this.progressCall||!this.progressData)return;const{percent:e,allCount:t,allTotal:r}=this.progressPercent,i={percent:e,allCount:t,allTotal:r};y(this,Ht,Oe).call(this,i)&&(this.progressCall({data:this.progressData,percent:e,allCount:t,allTotal:r}),this.lastProgressSnapshot=i)},Ht=new WeakSet,Oe=function(e){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==e.percent||this.lastProgressSnapshot.allCount!==e.allCount||this.lastProgressSnapshot.allTotal!==e.allTotal:!0},Ut=new WeakSet,_e=function(){const e={limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs};for(const t of this.timeLimitListeners)try{t(e)}catch(r){console.warn("Batch timeLimit listener error:",r)}},st=new WeakSet,bt=async function(e=this.defaultPauseMs){this.setTimeLimitState(!0,new Date().toISOString(),e),await new Promise(t=>setTimeout(t,e)),this.setTimeLimitState(!1,void 0)},rt=new WeakSet,Mt=async function(e,t=!0){if(!t)return 0;let r=0;if(!e||typeof e!="object")return 0;for(const i of Object.values(e))if(!(!i||typeof i!="object"))try{if(typeof i.time=="function"){const a=i.time();a&&typeof a.operating=="number"&&(r=Math.max(r,a.operating))}}catch{}r>=this.operatingThreshold&&await y(this,st,bt).call(this)},yt=new WeakSet,ae=function(e=this.defaultPauseMs){const t=this;return{inRetryCycle:!1,inTimeoutWait:!1,lateResult:null,lateWaiters:[],notifyLateResponse(i){if(!(!this.inRetryCycle&&!this.inTimeoutWait)){this.lateResult=i;for(const a of this.lateWaiters)a(i);this.lateWaiters=[]}},waitForLateOrLimit(){var a;this.inTimeoutWait=!0;const i=new Promise(l=>{if(this.lateResult){l(this.lateResult);return}this.lateWaiters.push(l)});return Promise.race([y(a=t,st,bt).call(a,e),i]).finally(()=>{this.inTimeoutWait=!1})},resetLateResult(){this.lateResult=null}}},it=new WeakSet,St=async function(e,t){let r=!1,i=e;const a=y(this,yt,ae).call(this);do r=!1,await this.callBatchWithTimeout(i,async l=>{var n,m;let h=!1;const u=new Set;for(const[f,A]of Object.entries(l||{})){if(!(A!=null&&A.error)||!A.error())continue;const c=((m=(n=A.error())==null?void 0:n.ex)==null?void 0:m.error)??"";if(c==="TIMEOUT"){h=!0;break}["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT"].includes(c)&&u.add(f)}if(h){if(a.inRetryCycle=!0,r=!0,await a.waitForLateOrLimit(),a.lateResult){r=!1,a.inRetryCycle=!1;const f=a.lateResult;a.resetLateResult(),await t(f)}return}if(u.size>0){const f={};for(const[c,p]of Object.entries(l||{}))u.has(c)||(f[c]=p);Object.keys(f).length&&await t(f);const A={};for(const c of u)i[c]&&(A[c]=i[c]);i=A,Object.keys(i).length&&(r=!0,await y(this,st,bt).call(this));return}a.inRetryCycle=!1,await t(l)},{onLateResponse:l=>a.notifyLateResponse(l)});while(r)},Pt=new WeakSet,Te=function(e,t,r={}){const{onLateResponse:i}=r;return new Promise(a=>{if(typeof this.callMethod!="function"){a(null);return}let l=!1;const h=setTimeout(()=>{l||(l=!0,a(null))},this.requestTimeoutMs);try{this.callMethod(e,t,u=>{l?typeof i=="function"&&i(u):(l=!0,clearTimeout(h),a(u))})}catch{l||(l=!0,clearTimeout(h),a(null))}})},Gt=new WeakSet,Ee=function(e){const t=typeof(e==null?void 0:e.error)=="function"?e.error():null,r=(t==null?void 0:t.ex)||{},i=String(r.error||"").trim(),a=String(r.error_description||"").trim(),l=typeof(t==null?void 0:t.toString)=="function"?String(t.toString()).trim():"";let h=a;return!h&&l&&l!==i&&(h=l),h||(h=i||"Неизвестная ошибка"),{code:i||h,message:h}},ht=new WeakSet,Vt=function(e,t){const{code:r,message:i}=y(this,Gt,Ee).call(this,t);this.errors[e]=r,this.errorMessages[e]=i},pt=new WeakSet,oe=function(e){Object.entries(this.errors).length&&(e.errorsList={...this.errors},Object.entries(this.errorMessages).length&&(e.errorsListMessages={...this.errorMessages}))},Nt=new WeakSet,Ae=function(e){this.clearProgressData(),this.progressCall=typeof e=="function"?e:"",this.canContinue=!0,this.result={},this.errors={},this.errorMessages={},this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.setTimeLimitState(!1,void 0)},E(Q,kt,5),E(Q,Bt,5),E(Q,Ct,8),E(Q,wt,.65);let q=Q;class te{constructor(){E(this,nt,{})}get hash(){return this.createHash(8)}createHash(e){let t="abcdefghijklmnopqrstuvwxyz0123456789",r="";e=e||6;for(let i=0;i<e;i++)r+=t.charAt(Math.floor(Math.random()*t.length));return r}actionFilter({keyTimer:e,duration:t=10,action:r}){b(this,nt)[e]&&(clearTimeout(b(this,nt)[e]),b(this,nt)[e]=null),r&&(b(this,nt)[e]=setTimeout(()=>{r()},t))}async noSleep(){let e=document.createElement("video");e.classList.add("no-sleep"),e.muted=!0,e.autoplay=!0,e.setAttribute("playsinline",""),e.addEventListener("loadeddata",()=>{e.style.position="fixed",e.style.left="-9999px",document.querySelector("body").append(e),e.play().catch(t=>{console.warn("noSleep: autoplay prevented",t)})}),e.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{e.play().catch(t=>{console.warn("noSleep: replay prevented",t)})}})}),e.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(e,t){let r=new Blob([JSON.stringify(e)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=i,a.download=`${t}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(i)},200)}}nt=new WeakMap;const ee=new te;class de{constructor(){E(this,Yt);E(this,_t);E(this,Wt);E(this,xt);E(this,Ft);E(this,Z,"logger");E(this,V,!1);E(this,at,new Map);E(this,ut,{});E(this,Ot,!1);E(this,$,null);E(this,J,null);E(this,ot,!1);E(this,ft,!1);C(this,"periodClear",3)}async init(){try{let e=new q(BX24.callBatch),{entityList:t}=await e.batch({entityList:{method:"entity.get"}});if(t&&Array.isArray(t))if(t.find(i=>i.ENTITY==b(this,Z)))X(this,V,!0);else{let{entityAdd:i}=await e.batch({entityAdd:{method:"entity.add",params:{ENTITY:b(this,Z),NAME:b(this,Z),ACCESS:{AU:"X"}}}});i&&X(this,V,!0)}return b(this,V)}catch(e){return console.error("Ошибка при инициализации логера:",e),!1}}enableBackworkerMode(){return X(this,V,!0),!0}start({type:e,data:t}){if(!b(this,V))return y(this,_t,le).call(this,"entity"),null;if(!e||!t)return console.error("Невалидные данные для логирования:",{type:e,data:t}),null;const r=ee.hash,i={type:e,data:t,userInfo:null,errorList:{},status:"",answer:null,date:new Date().getTime()};return b(this,at).set(r,i),X(this,ft,!0),r}async stop({key:e,errorList:t,status:r,answer:i}){var l;if(!b(this,ft))return;if(!b(this,V)){y(this,_t,le).call(this,"entity");return}let a=b(this,at).get(e);if(!a){console.error(`Не найдены данные логирования для ключа: ${e}`);return}t&&(a.errorList=t),r&&(a.status=r),i&&(a.answer=i),await y(this,Yt,Re).call(this),a.userInfo=b(this,ut),await y(this,Wt,Le).call(this),(l=a==null?void 0:a.data)!=null&&l.updateList&&X(this,ot,!0),X(this,ft,!1)}async getEntityList(e){var t;try{if((t=b(this,J))!=null&&t.length&&!b(this,ot))return b(this,J);let r=new q(BX24.callBatch),{entityList:i}=await r.batch({entityList:{method:"entity.item.get",params:{ENTITY:b(this,Z),SORT:{ID:"DESC"}}}},e);return!i||!Array.isArray(i)?(console.warn("Получен невалидный список записей"),[]):(i=i.map(a=>{try{const{ID:l,DATE_CREATE:h,DETAIL_TEXT:u}=a;return{...JSON.parse(u),id:l,dateCreate:h}}catch(l){return console.error(`Ошибка парсинга записи ${a.ID}:`,l),null}}).filter(a=>a!==null),X(this,ot,!1),X(this,J,i),i)}catch(r){return console.error("Ошибка при получении списка записей:",r),[]}}runStorageMaintenance(){return y(this,xt,be).call(this)}async downAllEntityJson(){try{if(b(this,J)||await this.getEntityList(),!b(this,J)||b(this,J).length===0)return console.warn("Нет данных для выгрузки"),!1;let e=gt().format("%Y-%m-%d");return ee.downloadFileJson(b(this,J),`sdklogger-entity-data__${e}`),!0}catch(e){return console.error("Ошибка при выгрузке данных в JSON:",e),!1}}}Z=new WeakMap,V=new WeakMap,at=new WeakMap,ut=new WeakMap,Ot=new WeakMap,$=new WeakMap,J=new WeakMap,ot=new WeakMap,ft=new WeakMap,Yt=new WeakSet,Re=async function(){if(!b(this,Ot))return b(this,$)?b(this,$):(X(this,$,(async()=>{try{const e=new q(BX24.callBatch),t=BX24.isAdmin(),{curUser:r}=await e.batch({curUser:{method:"user.current"}});X(this,ut,{isAdmin:t,curUser:r})}catch(e){console.error("Ошибка при получении информации о пользователе:",e),X(this,ut,{isAdmin:!1,curUser:null})}finally{X(this,Ot,!0),X(this,$,null)}})()),b(this,$))},_t=new WeakSet,le=function(e){e=="entity"&&ee.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},Wt=new WeakSet,Le=async function(){try{let e={},t=new q(BX24.callBatch);for(let[r,i]of b(this,at).entries())if(i.status){const a=JSON.stringify(i);e[r]={method:"entity.item.add",params:{ENTITY:b(this,Z),NAME:b(this,Z),DETAIL_TEXT:a}}}if(Object.keys(e).length){let r=await t.batch(e),{errors:i}=t;for(let[a,l]of Object.entries({...r,...i}))b(this,at).delete(a);return!0}return!1}catch(e){return console.error("Ошибка при добавлении записей в хранилище:",e),!1}},xt=new WeakSet,be=async function(){try{let e=new q(BX24.callBatch),{serverTime:t}=await e.batch({serverTime:{method:"server.time"}});if(!t){console.error("Не удалось получить время сервера");return}if(b(this,J)||await this.getEntityList(),!b(this,J)||b(this,J).length===0)return;let r=b(this,J).filter(i=>{try{let{dateCreate:a}=i;return a?gt(new Date(a)).between(gt(new Date(t)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});r.length>0&&(console.log(`Найдено ${r.length} записей для очистки (старше ${this.periodClear} месяцев)`),await y(this,Ft,Me).call(this,r))}catch(e){console.error("Ошибка при проверке периода очистки:",e)}},Ft=new WeakSet,Me=async function(e){try{if(!e||e.length===0)return!1;let t=new q(BX24.callBatch),r=e.filter(a=>a&&a.id).map(a=>{let{id:l}=a;return{method:"entity.item.delete",params:{ENTITY:b(this,Z),ID:l}}});if(r.length===0)return!1;const i=await t.batch(r);return console.log(`Успешно удалено ${r.length} записей`),X(this,ot,!0),i}catch(t){return console.error("Ошибка при очистке устаревших записей:",t),!1}};function se(_){if(!_||typeof _!="string")return"";try{const e=new URL(_);e.search="",e.hash="";let t=e.toString();return t.endsWith("/")&&e.pathname!=="/"&&(t=t.slice(0,-1)),t}catch{return _.split("?")[0].split("#")[0].replace(/\/$/,"")}}function me(_){return!_||typeof _!="string"?!1:_.toLowerCase().includes("/marketplace/app")}function Pe(){var e;if(typeof window>"u"||!((e=window.location)!=null&&e.href))return"";const _=se(window.location.href);return me(_)?"":_}function re(_){if(!(_!=null&&_.appConst)||typeof _.appConst!="object")return"";const e=Pe();return e?(_.appConst.pathApp=e,e):se(_.appConst.pathApp??"")}class Ge{constructor(e){E(this,dt);E(this,vt);E(this,Tt);E(this,Xt);E(this,Jt);E(this,jt);E(this,tt);E(this,Et);E(this,Kt);E(this,Rt);E(this,qt);C(this,"domain","");C(this,"isAdmin",!1);C(this,"appInfo",null);C(this,"appConst",null);C(this,"userInfo",null);C(this,"placeData",null);C(this,"placeInfo",null);C(this,"logger",!1);C(this,"timeLimit",{limit:!1,date:void 0,pauseMs:void 0});C(this,"batchClient",null);this.appConst=e}subscribeTimeLimit(e){return y(this,dt,$t).call(this).subscribeTimeLimit(e)}init(){return new Promise((e,t)=>{const i=setTimeout(()=>{clearInterval(a);const l=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(l),t(l)},3e4);let a=setInterval(()=>{window.BX24&&BX24.init(async()=>{clearInterval(a),clearTimeout(i),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info();const l=y(this,Xt,Ie).call(this);if(console.info(l?"init BX24 (background worker)":"init BX24"),this.appInfo=await y(this,Jt,De).call(this),this.userInfo=await y(this,jt,ke).call(this),re(this),l)await y(this,Tt,ce).call(this,!1,{skipInit:!0});else{await y(this,Tt,ce).call(this,!0);const h=new te;try{h.noSleep()}catch(u){console.warn("Failed to initialize noSleep:",u)}}e({isBackworker:l})})},100)})}userOption(e,t){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return t!==void 0?BX24.userOption.set(e,t):BX24.userOption.get(e)}appOption(e,t){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return t!==void 0?BX24.appOption.set(e,t):BX24.appOption.get(e)}async call({method:e,params:t,updateList:r}){let i;if(r&&(i=this.logger.start({type:"call",data:{method:e,params:t,updateList:r}})),t||(t={}),typeof BX24>"u"||!BX24.callMethod){const h=new Error("BX24 is not initialized");throw console.error(h),h}const l=await y(this,dt,$t).call(this).call({method:e,params:t});return l.success?(await y(this,tt,mt).call(this,i,{answer:l.answer,status:"success"}),l.data):(console.error(l.error),await y(this,tt,mt).call(this,i,{answer:l.answer,status:"fail",errorList:{0:l.error||"Unknown call error"}}),!1)}async batch(e,t,{errorCall:r,updateList:i,batchOptions:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const l=new Error("BX24 is not initialized");return console.error(l),!1}return y(this,Et,he).call(this,{mode:"batch",commandList:e,progressCall:t,errorCall:r,updateList:i,batchOptions:a})}async batchTotalCount(e,t,{errorCall:r,updateList:i}={}){if(typeof BX24>"u"||!BX24.callBatch){const a=new Error("BX24 is not initialized");return console.error(a),!1}return y(this,Et,he).call(this,{mode:"batch-total-count",commandList:e,progressCall:t,errorCall:r,updateList:i})}async getPlacement(){const e=await this.call({method:"placement.get"});return this.placeData||(this.placeData=e),e}async placementBind(e){var A;if(!this.isAdmin||(this.placeData=await this.getPlacement(),!this.placeData))return;const{appName:t,pathApp:r}=this.appConst;let i=y(this,Rt,ue).call(this,e);i=i.filter(c=>c.placement!=="PAGE_BACKGROUND_WORKER"&&c.placement!=="PAGE_BACKGROUND_WORKER_ALL");const a=y(this,qt,Ce).call(this,r),l=new Set(i.map(c=>c.placement));for(const c of a)l.has(c.placement)||i.push({placement:c.placement});if(i.length===0)return;let h=t;this.domain==="szdl.bitrix24.ru"&&((A=this.appInfo)!=null&&A.ID)&&(h=`${t}: #${this.appInfo.ID}`);const u=h.replace(" CRM",""),n={},m=[],f=new Map;for(const c of this.placeData)f.has(c.placement)||f.set(c.placement,[]),f.get(c.placement).push(c);for(let c=0;c<i.length;c++){const{placement:p,options:O}=i[c],L=f.get(p)||[];if(L.some(R=>R.handler===r))continue;const T=L.filter(R=>R.handler!==r);for(const R of T)m.push({placement:p,handler:R.handler});n[`bind_${c}`]={method:"placement.bind",params:{PLACEMENT:p,HANDLER:r,LANG_ALL:{ru:{TITLE:p==="USER_PROFILE_TOOLBAR"?u:h}},OPTIONS:{errorHandlerUrl:r,...O&&typeof O=="object"?O:{}}}}}m.length>0&&await this.placementUnBind(m),Object.keys(n).length>0&&(await this.batch(n),this.placeData=await this.getPlacement(),Object.values(n).forEach(c=>{console.log("Приложение успешно встроено в",c.params.PLACEMENT)}))}async placementUnBind(e){let t=y(this,Rt,ue).call(this,e);if(t=t.filter(i=>i.placement!=="PAGE_BACKGROUND_WORKER"&&i.placement!=="PAGE_BACKGROUND_WORKER_ALL"),t.length===0)return;const r={};for(let i=0;i<t.length;i++){const a={PLACEMENT:t[i].placement};t[i].handler&&(a.HANDLER=t[i].handler),r[`unbind_${i}`]={method:"placement.unbind",params:a}}await this.batch(r),t.forEach(i=>{console.log("Встройка отвязана",i.placement)})}async getBotList(){const e=await this.call({method:"imbot.bot.list",params:{}}),t=Object.values(e);return console.log("chat-bot list:",t),t}async regBot({code:e,type:t,name:r}){const{appName:i,pathApp:a,chatBotLogo:l}=this.appConst,h=this.appInfo.ID,u=await this.call({method:"imbot.register",params:{CODE:e??this.appInfo.CODE,TYPE:t??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${r??i} - бот #${h}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:gt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:l??""}}});return console.log("Чат-бот добавлен",u),u}async unRegBot(e){const t=await this.call({method:"imbot.unregister",params:{BOT_ID:e}});return console.log("чат-бот удален",t),t}getLoggerList(e){return this.logger.getEntityList(e)}}dt=new WeakSet,$t=function(){return this.batchClient||(this.batchClient=new q({callBatch:BX24.callBatch,callMethod:BX24.callMethod}),this.timeLimit=this.batchClient.timeLimit),this.batchClient},vt=new WeakSet,Se=function(){return{start:()=>{},stop:()=>{},getEntityList:()=>{}}},Tt=new WeakSet,ce=async function(e,{skipInit:t=!1}={}){this.logger?(this.logger=new de,t?this.logger.enableBackworkerMode():await this.logger.init(),e&&typeof this.logger.runStorageMaintenance=="function"&&this.logger.runStorageMaintenance()):this.logger=y(this,vt,Se).call(this)},Xt=new WeakSet,Ie=function(){var r,i,a;const e=(r=this.placeInfo)==null?void 0:r.placement,t=(a=(i=this.placeInfo)==null?void 0:i.options)==null?void 0:a.ID;return e==="PAGE_BACKGROUND_WORKER"||t==="PAGE_BACKGROUND_WORKER"},Jt=new WeakSet,De=function(){return this.call({method:"app.info"})},jt=new WeakSet,ke=function(){return this.call({method:"user.current"})},tt=new WeakSet,mt=async function(e,t){if(e)try{await this.logger.stop({key:e,...t})}catch(r){console.error("Logger error:",r)}},Et=new WeakSet,he=async function({mode:e,commandList:t,progressCall:r,errorCall:i,updateList:a,batchOptions:l}){const h=y(this,dt,$t).call(this),u=a?this.logger.start({type:e,data:e==="batch"?{commandList:t,updateList:a}:{commandList:t}}):void 0;try{const n=e==="batch"?await h.batch(t,r,l):await h.batchTotalCount(t,r),m=y(this,Kt,Be).call(this,h,n,t,a);return Object.keys(m).length?(i&&i(m),await y(this,tt,mt).call(this,u,{status:"fail",errorList:m})):await y(this,tt,mt).call(this,u,{status:"success"}),n}catch(n){return await y(this,tt,mt).call(this,u,{status:"fail-runtime",errorList:{0:n==null?void 0:n.toString()}}),console.error(n),!1}},Kt=new WeakSet,Be=function(e,t,r,i){let a={...e.errors};if(Object.values(e.errors).some(h=>{if(typeof h!="string")return!1;const u=h.toUpperCase();return u==="TIMEOUT"||u==="OPERATION_TIME_LIMIT"||u.includes("TIMEOUT")||u.includes("OPERATION_TIME_LIMIT")})&&i){const h=t?Object.keys(t).filter(f=>f!=="errorsList"&&f!=="errorsListMessages"):[],u=new Set(Object.keys(e.errors||{})),n=new Set;if(t){for(const f of h)if(!u.has(f)){const A=t[f];A!=null&&n.add(f)}}const m=Object.values(e.errors).find(f=>{if(typeof f!="string")return!1;const A=f.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const f of Object.keys(r))!n.has(f)&&!e.errors[f]&&(a[f]=m||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a},Rt=new WeakSet,ue=function(e){if(!e)return[];let t=[];return Array.isArray(e)?t=e.map(r=>typeof r=="string"?{placement:r}:r):typeof e=="string"?t=[{placement:e}]:t=[e],t},qt=new WeakSet,Ce=function(e){return this.placeData?this.placeData.filter(t=>!(t.placement==="PAGE_BACKGROUND_WORKER"||!t.handler||t.handler.includes(e))):[]};const ge="szdl-utils-kit|";function Ye(){if(typeof sessionStorage>"u")return`ephemeral-${Date.now()}-${Math.random().toString(16).slice(2)}`;let _=sessionStorage.getItem("szdl-cross-tab-instance-id");return _||(_=`${Date.now()}-${Math.random().toString(16).slice(2)}`,sessionStorage.setItem("szdl-cross-tab-instance-id",_)),_}function We(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}const ie=new Map;function xe(_="default"){if(typeof BroadcastChannel>"u")return null;const e=`${ge}bc:${_}`;return ie.has(e)||ie.set(e,new BroadcastChannel(e)),ie.get(e)}function ye(_,e){const t=xe(_);if(t)try{const r=e&&typeof e=="object"&&!Array.isArray(e)?e:{data:e};t.postMessage({...r,tabId:Ye(),ts:Date.now()})}catch{}}async function Fe(_,e,t={}){const{ifAvailable:r=!1}=t,i=typeof _=="string"&&_.length>0?_:"default",a=`${ge}${i}`;return We()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!r},async l=>{if(r&&l==null)return{skipped:!0,coordination:"locks"};ye(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await e(),coordination:"locks"}}finally{ye(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await e(),coordination:"none"}}const z={startDelayMs:0,pollIntervalMs:60*1e3,pollIntervalJitterMs:30*1e3,leaderConfirmDelayMs:60*1e3,activeMaxPauseMs:3*60*1e3,quickCleanupThresholdMs:5*60*1e3,leaderHeartbeatMs:null};function ve(_){return _==null?"user":_==="user"||_==="portal"?_:(console.warn(`BackgroundWorker: coordinationScope должен быть 'user' или 'portal', получено ${JSON.stringify(_)} — используется 'user'`),"user")}function pe(_={}){const e={...z,..._};for(const t of Object.keys(z)){if(t==="leaderHeartbeatMs"){const i=_==null?void 0:_.leaderHeartbeatMs;if(i==null){e.leaderHeartbeatMs=null;continue}const a=Number(i);e.leaderHeartbeatMs=Number.isFinite(a)&&a>=0?a:null;continue}const r=Number(e[t]);e[t]=Number.isFinite(r)&&r>=0?r:z[t]}return e}class Xe{constructor(e){E(this,zt);E(this,Lt);E(this,At);E(this,Qt);C(this,"entityName","tabs");C(this,"maxTabs",20);C(this,"tabList",[]);C(this,"id",0);C(this,"hasStarted",!1);C(this,"heartbeat");C(this,"runHeartbeat");C(this,"startDelay",0);C(this,"activeMaxPause",z.activeMaxPauseMs);C(this,"quickCleanupThreshold",z.quickCleanupThresholdMs);C(this,"pollInterval",z.pollIntervalMs);C(this,"pollIntervalBase",z.pollIntervalMs);C(this,"pollIntervalJitter",z.pollIntervalJitterMs);C(this,"leaderConfirmDelay",z.leaderConfirmDelayMs);C(this,"leaderHeartbeatMs",null);C(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);C(this,"continueCondition");C(this,"defaultContinueBackground",()=>!0);C(this,"coordinationScope","user");C(this,"bindGeneralPlacement",!0);var n,m,f;if(!e){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:t,bx:r,users:i,continueBackground:a,timing:l,coordinationScope:h,bindGeneralPlacement:u}=e;this.bx=r,this.appInit=t,this.users=i,this.coordinationScope=ve(h),this.bindGeneralPlacement=u!==!1,y(this,zt,we).call(this,l),re(r),this.appPath=y(this,Lt,fe).call(this,((n=r==null?void 0:r.appConst)==null?void 0:n.pathApp)??""),this.appName=((m=r==null?void 0:r.appConst)==null?void 0:m.appName)??"",this.appCodeName=((f=r==null?void 0:r.appConst)==null?void 0:f.appCodeName)??"",this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("BackgroundWorker: appInit не передан");return}if(!this.bx){console.error("BackgroundWorker: bx не передан");return}if(this.isAppPage()){console.log("BackgroundWorker: Страница приложения, фоновый воркер не запускается");return}await this.checkPlacementType()&&await this.continueBackground()&&(await this.checkEntity(),await this.refreshTabs(!0),await this.ensureTabRegistered(),this.startDelay>0&&(console.log(`BackgroundWorker: старт отложен на ${this.startDelay} мс`),await this.pause(this.startDelay)),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(t=>{console.error("BackgroundWorker: backgroundTick failed",t)})},this.pollInterval),await this.backgroundTick())}async backgroundTick(){if(!await this.continueBackground()){this.stopTimers(),console.log("BackgroundWorker: Остановка backgroundTick - условие не выполнено");return}await this.refreshTabs(!0),await this.ensureTabRegistered();const t=this.selectLeaderId(),r=t&&+this.id==+t;await this.updateTabState(r),r&&!this.hasStarted&&await this.runAsLeader()}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var e;if(typeof BX24>"u"||!((e=BX24.placement)!=null&&e.info))return!1;try{const t=BX24.placement.info(),r=t==null?void 0:t.placement,i=(t==null?void 0:t.options)||{},a=(i==null?void 0:i.URI)||"",l=r==="PAGE_BACKGROUND_WORKER"||(i==null?void 0:i.ID)==="PAGE_BACKGROUND_WORKER",h=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!l||h}catch{return!1}}async checkEntity(){var r;const e=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((r=e==null?void 0:e.find)==null?void 0:r.call(e,i=>i.ENTITY===this.entityName))||await this.safeCall(()=>this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}}))}async getTabs(){const e=y(this,At,It).call(this),t=await this.safeCall(()=>this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:e},SORT:{DATE_CREATE:"DESC"}}}));return!Array.isArray(t)||!t.length?[]:t.map(r=>{if(!r)return{id:void 0,data:void 0};try{const i=JSON.parse(r.DETAIL_TEXT);return{id:+r.ID||0,data:i}}catch(i){return console.log("BackgroundWorker: parse tab error",i),{id:+r.ID||0,data:void 0}}})}async ensureTabRegistered(){var r,i;if(this.id)return+this.id||0;if(this.tabList.length>=this.maxTabs&&await this.refreshTabs(!0,this.quickCleanupThreshold),this.tabList.length>=this.maxTabs)return console.log("BackgroundWorker: Достигнут лимит вкладок даже после быстрой очистки, не регистрируемся"),0;const e={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId,userId:(i=(r=this.bx)==null?void 0:r.userInfo)==null?void 0:i.ID},t=await this.safeCall(()=>this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:y(this,At,It).call(this),DETAIL_TEXT:JSON.stringify(e)}}))||0;return this.id=+t||0,this.id}async updateTabState(e){var r,i;if(!this.id)return;const t={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:e,sessionId:this.sessionId,userId:(i=(r=this.bx)==null?void 0:r.userInfo)==null?void 0:i.ID};await this.safeCall(()=>this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:y(this,At,It).call(this),DETAIL_TEXT:JSON.stringify(t)}}))}async deleteTabs(e=[]){if(!e.length)return;const t=e.map(r=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:r.id}}));await this.safeCall(()=>this.bx.batch(t))}async checkPlacementType(){var e,t;try{if(!((e=this.bx)!=null&&e.isAdmin))return!0;const r=await this.safeCall(()=>this.bx.getPlacement());if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((t=this.bx.userInfo)==null?void 0:t.ID)??0),a=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),l=!a;if(!i)return!0;let h=!1;for(const u of r){if(u.placement!=="PAGE_BACKGROUND_WORKER"||!(u.userId||u.handler&&u.handler.includes("USER_ID=")))continue;const m=u.userId||(u.handler?this.extractUserIdFromHandler(u.handler):null);if(m&&+m===i){h=!0;break}}return a?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):l&&h?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}isIndividualPlacement(e){return!e||typeof e!="string"?!1:e.includes("USER_ID=")}extractUserIdFromHandler(e){if(!e||typeof e!="string")return null;const t=e.match(/USER_ID=(\d+)/);return t?+t[1]:null}async continueBackground(){try{const t=!!await Promise.resolve(this.continueCondition(this));return console.log(t?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),t}catch(e){return console.error("BackgroundWorker: Ошибка в continueCondition",e),!1}}async refreshTabs(e=!1,t=this.activeMaxPause){const r=[],i=[],a=Date.now(),l=await this.getTabs();for(const h of l){if(!(h!=null&&h.data)){r.push(h);continue}if(a-new Date(h.data.lastActive||0).getTime()>t){r.push(h);continue}i.push(h)}return e&&r.length&&await this.deleteTabs(r),this.tabList=i,i}selectLeaderId(){var t;return this.tabList.length&&+((t=[...this.tabList].sort((r,i)=>{var h,u,n,m;const a=new Date(((h=r.data)==null?void 0:h.createdAt)||((u=r.data)==null?void 0:u.lastActive)||0).getTime(),l=new Date(((n=i.data)==null?void 0:n.createdAt)||((m=i.data)==null?void 0:m.lastActive)||0).getTime();return a===l?(+r.id||0)-(+i.id||0):a-l})[0])==null?void 0:t.id)||0}async confirmLeaderAfterLock(){await this.refreshTabs(!0);const e=this.selectLeaderId();return!!(e&&+this.id==+e)}async runAsLeader(){const e=y(this,Qt,He).call(this);(await Fe(e,async()=>{if(await this.updateTabState(!0),console.log(`BackgroundWorker: захват лидерства, пауза ${this.leaderConfirmDelay} мс перед запуском`),await this.pause(this.leaderConfirmDelay),!await this.confirmLeaderAfterLock()){console.log("BackgroundWorker: запуск отменён — после паузы лидером оказалась другая вкладка"),await this.updateTabState(!1);return}this.hasStarted=!0;const i=this.leaderHeartbeatMs??Math.min(this.activeMaxPause-1500,Math.max(2500,Math.floor(this.pollInterval/2)));this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(a=>console.error("BackgroundWorker: heartbeat update failed",a))},i);try{await this.appInit()}catch(a){console.error("BackgroundWorker: appInit failed",a)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)},{ifAvailable:!0})).skipped&&console.log("BackgroundWorker: runAsLeader пропущен — Web Lock у другой вкладки (подтверждение лидерства)")}async setBackgroundWorkerAll(){var B,T,R,x;if(!((B=this.bx)!=null&&B.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(T=this.users)!=null&&T.length||await this.getEntityData(),re(this.bx);const e=y(this,Lt,fe).call(this,((x=(R=this.bx)==null?void 0:R.appConst)==null?void 0:x.pathApp)??"");if(!e){console.error("BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена");return}const t=await this.safeCall(()=>this.bx.getPlacement()),r=new Map,i=new Map;let a=null;(t||[]).forEach(N=>{if(N.placement!=="PAGE_BACKGROUND_WORKER")return;if(N.userId||N.handler&&N.handler.includes("USER_ID=")){const D=N.userId||(N.handler?this.extractUserIdFromHandler(N.handler):null);if(D){const U=+D;r.set(U,N),i.has(U)||i.set(U,[]),i.get(U).push(N)}}else a=N});const l=await this.resolveAdmins(),h=await this.getEligibleUsersForBackgroundWorker(l);h.sort((N,I)=>{const D=N.LAST_LOGIN?new Date(N.LAST_LOGIN):new Date(0);return(I.LAST_LOGIN?new Date(I.LAST_LOGIN):new Date(0))-D});const u=10,n=h.slice(0,u),m=n.filter(N=>{const I=r.get(+N.ID);if(!I)return!0;const D=`${e}?USER_ID=${N.ID}/`;return I.handler!==D}),f=[];for(const[N]of r){const I=+N||0;h.find(U=>+U.ID===I)||f.push(I)}for(const N of n){const I=r.get(+N.ID);if(!I)continue;const D=`${e}?USER_ID=${N.ID}/`;I.handler!==D&&f.push(+N.ID)}const A=[],c=[...new Set(f)];for(const N of c){const I=i.get(+N)||[];for(const D of I)D!=null&&D.handler&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:D.handler}})}const p=a&&(!this.bindGeneralPlacement||m.length>0||a.handler!==`${e}`);p&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:a.handler||`${e}`}});for(const N of m)A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}?USER_ID=${N.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}?USER_ID=${N.ID}/`},USER_ID:N.ID}});this.bindGeneralPlacement&&(!a||p)&&A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}`}}});const O=A.filter(N=>N.method==="placement.unbind"),L=A.filter(N=>N.method==="placement.bind");O.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(O.map((N,I)=>[`unbind_${I}`,N])))),L.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(L.map((N,I)=>[`bind_${I}`,N])))),A.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var e,t;try{const r=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),i=!!((t=this.bx)!=null&&t.isAdmin),a=await this.getAdminsList()||[];if(!i){if(r&&a.includes(+r)){const u=a.filter(n=>+n!=+r);return await this.saveAdminsList(u),u}return a}const l=new Set([...a||[]]);r&&l.add(+r);const h=[...l].filter(Boolean);return await this.saveAdminsList(h),h}catch(r){return console.error("BackgroundWorker: resolveAdmins error",r),[]}}async getEligibleUsersForBackgroundWorker(e=[]){const t=(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0),r=e.map(i=>+i||0).filter(Boolean);return t.filter(i=>r.includes(+i.ID||0))}async saveAdminsList(e=[]){try{BX24.appOption.set("adminsList",JSON.stringify(e))}catch(t){console.error("BackgroundWorker: saveAdminsList error",t)}}async getAdminsList(){try{const e=BX24.appOption.get("adminsList"),t=e?JSON.parse(e):[];return Array.isArray(t)?t.map(r=>+r||0).filter(Boolean):[]}catch(e){return console.error("BackgroundWorker: getAdminsList error",e),[]}}async getEntityData(){const e={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:t}=await this.safeCall(()=>this.bx.batch(e).then(r=>r?(Array.isArray(r.users)||(r.users=[]),r):{users:[]}));this.users=t}async ensureAdminPlacements(){var e,t;(e=this.bx)!=null&&e.isAdmin&&((t=this.users)!=null&&t.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(e=500,t){return new Promise(r=>{setTimeout(()=>{t&&t(),r(!0)},e)})}async safeCall(e){try{return await e()}catch(t){console.error("BackgroundWorker: safeCall error",t);return}}}zt=new WeakSet,we=function(e){const t=pe(e);this.startDelay=t.startDelayMs,this.leaderConfirmDelay=t.leaderConfirmDelayMs,this.activeMaxPause=t.activeMaxPauseMs,this.quickCleanupThreshold=t.quickCleanupThresholdMs,this.pollIntervalBase=t.pollIntervalMs,this.pollIntervalJitter=t.pollIntervalJitterMs,this.pollInterval=t.pollIntervalMs+(t.pollIntervalJitterMs>0?Math.floor(Math.random()*t.pollIntervalJitterMs):0),this.leaderHeartbeatMs=t.leaderHeartbeatMs;const r=t.pollIntervalMs+t.pollIntervalJitterMs+t.leaderConfirmDelayMs;t.activeMaxPauseMs<r&&console.warn(`BackgroundWorker: activeMaxPauseMs (${t.activeMaxPauseMs}) меньше poll+jitter+leaderConfirm (${r}) — «живые» вкладки могут удаляться раньше следующего тика`)},Lt=new WeakSet,fe=function(e){if(!e||typeof e!="string")return"";const t=se(e).replace(/\/+$/,"");return t?me(t)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):t:""},At=new WeakSet,It=function(){var e,t;return this.coordinationScope==="portal"?`${this.appCodeName||"app"}:portal`:String(((t=(e=this.bx)==null?void 0:e.userInfo)==null?void 0:t.ID)??"")},Qt=new WeakSet,He=function(){return`background-worker:${this.entityName}:${y(this,At,It).call(this)}`},M.BackgroundWorker=Xe,M.Batch=q,M.BxBoot=Ge,M.BxHelper=te,M.BxLogger=de,M.DEFAULT_BACKGROUND_WORKER_TIMING=z,M.resolveBackgroundWorkerTiming=pe,M.tempus=gt,Object.defineProperty(M,Symbol.toStringTag,{value:"Module"})});
1
+ var Je=Object.defineProperty;var je=(I,C,G)=>C in I?Je(I,C,{enumerable:!0,configurable:!0,writable:!0,value:G}):I[C]=G;var D=(I,C,G)=>(je(I,typeof C!="symbol"?C+"":C,G),G),ne=(I,C,G)=>{if(!C.has(I))throw TypeError("Cannot "+G)};var L=(I,C,G)=>(ne(I,C,"read from private field"),G?G.call(I):C.get(I)),E=(I,C,G)=>{if(C.has(I))throw TypeError("Cannot add the same private member more than once");C instanceof WeakSet?C.add(I):C.set(I,G)},X=(I,C,G,ct)=>(ne(I,C,"write to private field"),ct?ct.call(I,G):C.set(I,G),G);var y=(I,C,G)=>(ne(I,C,"access private method"),G);(function(I,C){typeof exports=="object"&&typeof module<"u"?C(exports):typeof define=="function"&&define.amd?define(["exports"],C):(I=typeof globalThis<"u"?globalThis:I||self,C(I["szdl-utils-kit"]={}))})(this,function(I){var Dt,Ne,kt,Bt,Ct,wt,ht,Zt,Ht,Oe,Ut,_e,rt,It,V,lt,yt,ae,it,Mt,Pt,Te,Gt,Ee,ut,Vt,Nt,oe,Ot,Ae,nt,Z,$,at,ft,_t,tt,J,ot,dt,Yt,Re,Tt,le,Wt,Le,xt,be,Ft,Ie,mt,$t,vt,Me,Et,ce,Xt,Se,Jt,De,jt,ke,et,gt,Rt,he,Kt,Be,Lt,ue,qt,Ce,zt,we,bt,fe,At,St,Qt,He;"use strict";var C=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function G(_){return _&&_.__esModule&&Object.prototype.hasOwnProperty.call(_,"default")?_.default:_}var ct={exports:{}};(function(_,e){(function(t){Array.prototype.indexOf||(Array.prototype.indexOf=function(s,o){var m,p;for(m=o||0,p=this.length;m<p;m+=1)if(this[m]===s)return m;return-1});var r=this,i=function(s,o){for(var m=s.toString();m.length<o;)m="0"+m;return m},a=function(s,o){return o!==t?(s.year(o.year()||o.year),s.month(o.month()||o.month),s.day(o.day()||o.day),s.hours(o.hours()||o.hours),s.minutes(o.minutes()||o.minutes),s.seconds(o.seconds()||o.seconds),s.milliseconds(o.milliseconds()||o.milliseconds),s):t},l=function(s,o){var m,p="";return m=s.slice(o,o+1),m!==""&&!isNaN(Number(m))&&(p+="%H"),m=s.charAt(o+2),m!==""&&m===":"&&(p+=m),m=s.slice(o+3,o+4),m!==""&&!isNaN(Number(m))&&(p+="%M"),m=s.charAt(o+5),m!==""&&m===":"&&(p+=m),m=s.slice(o+6,o+7),m!==""&&!isNaN(Number(m))&&(p+="%S"),p},h=function(s,o){var m,p=[s.slice(o,o+1),s.charAt(o+2),s.slice(o+3,o+4),s.charAt(o+5),s.slice(o+6,o+9)],Y;return!isNaN(Number(p[0]))&&!isNaN(Number(p[2]))&&!isNaN(Number(p[4]))?(p[1]==="."&&p[3]==="."?m="%d.%m.%Y":p[1]==="-"&&p[3]==="-"?m="%m-%d-%Y":p[1]==="/"&&p[3]==="/"&&(m="%m/%d/%Y"),m):(Y=[s.slice(o,o+3),s.charAt(o+4),s.slice(o+5,o+6),s.charAt(o+7),s.slice(o+8,o+9)],!isNaN(Number(Y[0]))&&!isNaN(Number(Y[2]))&&!isNaN(Number(Y[4]))?(Y[1]==="-"&&Y[3]==="-"&&(m="%Y-%m-%d"),m):"")},u=r.tempus,n,d,f=r.navigator||{},A="en",c={en:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"Mar",APRIL_SHORT:"Apr",MAY_SHORT:"May",JUNE_SHORT:"Jun",JULY_SHORT:"Jul",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sep",OCTOBER_SHORT:"Oct",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dec",JANUARY_LONG:"January",FEBRUARY_LONG:"February",MARCH_LONG:"March",APRIL_LONG:"April",MAY_LONG:"May",JUNE_LONG:"June",JULY_LONG:"July",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"October",NOVEMBER_LONG:"November",DECEMBER_LONG:"December",SUNDAY_SHORT:"Sun",MONDAY_SHORT:"Mon",TUESDAY_SHORT:"Tue",WEDNESDAY_SHORT:"Wed",THURSDAY_SHORT:"Thu",FRIDAY_SHORT:"Fri",SATURDAY_SHORT:"Sat",SUNDAY_LONG:"Sunday",MONDAY_LONG:"Monday",TUESDAY_LONG:"Tuesday",WEDNESDAY_LONG:"Wednesday",THURSDAY_LONG:"Thursday",FRIDAY_LONG:"Friday",SATURDAY_LONG:"Saturday"},ru:{JANUARY_SHORT:"Янв",FEBRUARY_SHORT:"Фев",MARCH_SHORT:"Мар",APRIL_SHORT:"Апр",MAY_SHORT:"Май",JUNE_SHORT:"Июн",JULY_SHORT:"Июл",AUGUST_SHORT:"Авг",SEPTEMBER_SHORT:"Сен",OCTOBER_SHORT:"Окт",NOVEMBER_SHORT:"Ноя",DECEMBER_SHORT:"Дек",JANUARY_LONG:"Январь",FEBRUARY_LONG:"Февраль",MARCH_LONG:"Март",APRIL_LONG:"Апрель",MAY_LONG:"Май",JUNE_LONG:"Июнь",JULY_LONG:"Июль",AUGUST_LONG:"Август",SEPTEMBER_LONG:"Сентябрь",OCTOBER_LONG:"Октябрь",NOVEMBER_LONG:"Ноябрь",DECEMBER_LONG:"Декабрь",SUNDAY_SHORT:"Вс",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Воскресенье",MONDAY_LONG:"Понедельник",TUESDAY_LONG:"Вторник",WEDNESDAY_LONG:"Среда",THURSDAY_LONG:"Четверг",FRIDAY_LONG:"Пятница",SATURDAY_LONG:"Суббота"},ua:{JANUARY_SHORT:"Січ",FEBRUARY_SHORT:"Лют",MARCH_SHORT:"Берез",APRIL_SHORT:"Квіт",MAY_SHORT:"Трав",JUNE_SHORT:"Черв",JULY_SHORT:"Лип",AUGUST_SHORT:"Серп",SEPTEMBER_SHORT:"Верес",OCTOBER_SHORT:"Жовт",NOVEMBER_SHORT:"Листоп",DECEMBER_SHORT:"Груд",JANUARY_LONG:"Січень",FEBRUARY_LONG:"Лютий",MARCH_LONG:"Березень",APRIL_LONG:"Квітень",MAY_LONG:"Травень",JUNE_LONG:"Червень",JULY_LONG:"Липень",AUGUST_LONG:"Серпень",SEPTEMBER_LONG:"Вересень",OCTOBER_LONG:"Жовтень",NOVEMBER_LONG:"Листопад",DECEMBER_LONG:"Грудень",SUNDAY_SHORT:"Нд",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Неділя",MONDAY_LONG:"Понеділок",TUESDAY_LONG:"Вівторок",WEDNESDAY_LONG:"Середа",THURSDAY_LONG:"Четвер",FRIDAY_LONG:"П’ятниця",SATURDAY_LONG:"Субота"},de:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"März",APRIL_SHORT:"Apr",MAY_SHORT:"Mai",JUNE_SHORT:"Juni",JULY_SHORT:"Juli",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sept",OCTOBER_SHORT:"Okt",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dez",JANUARY_LONG:"Januar",FEBRUARY_LONG:"Februar",MARCH_LONG:"März",APRIL_LONG:"April",MAY_LONG:"Mai",JUNE_LONG:"Juni",JULY_LONG:"Juli",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"Oktober",NOVEMBER_LONG:"November",DECEMBER_LONG:"Dezember",SUNDAY_SHORT:"So",MONDAY_SHORT:"Mo",TUESDAY_SHORT:"Di",WEDNESDAY_SHORT:"Mi",THURSDAY_SHORT:"Do",FRIDAY_SHORT:"Fr",SATURDAY_SHORT:"Sa",SUNDAY_LONG:"Sonntag",MONDAY_LONG:"Montag",TUESDAY_LONG:"Dienstag",WEDNESDAY_LONG:"Mittwoch",THURSDAY_LONG:"Donnerstag",FRIDAY_LONG:"Freitag",SATURDAY_LONG:"Samstag"}},N=function(){return[c[A].JANUARY_LONG,c[A].FEBRUARY_LONG,c[A].MARCH_LONG,c[A].APRIL_LONG,c[A].MAY_LONG,c[A].JUNE_LONG,c[A].JULY_LONG,c[A].AUGUST_LONG,c[A].SEPTEMBER_LONG,c[A].OCTOBER_LONG,c[A].NOVEMBER_LONG,c[A].DECEMBER_LONG]},O=function(){return[c[A].JANUARY_SHORT,c[A].FEBRUARY_SHORT,c[A].MARCH_SHORT,c[A].APRIL_SHORT,c[A].MAY_SHORT,c[A].JUNE_SHORT,c[A].JULY_SHORT,c[A].AUGUST_SHORT,c[A].SEPTEMBER_SHORT,c[A].OCTOBER_SHORT,c[A].NOVEMBER_SHORT,c[A].DECEMBER_SHORT]},R=function(){return[c[A].SUNDAY_LONG,c[A].MONDAY_LONG,c[A].TUESDAY_LONG,c[A].WEDNESDAY_LONG,c[A].THURSDAY_LONG,c[A].FRIDAY_LONG,c[A].SATURDAY_LONG]},k=function(){return[c[A].SUNDAY_SHORT,c[A].MONDAY_SHORT,c[A].TUESDAY_SHORT,c[A].WEDNESDAY_SHORT,c[A].THURSDAY_SHORT,c[A].FRIDAY_SHORT,c[A].SATURDAY_SHORT]},T,g,B,b,P=function(s,o,m){var p;r.XMLHttpRequest?p=new XMLHttpRequest:p=new ActiveXObject("Microsoft.XMLHTTP"),p.onreadystatechange=function(){p.readyState===4&&(p.status===200?o&&(r.JSON===t?alert(`Please, include json2 into your project if you want use old browsers!
2
+ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(p.responseText))):m&&m(p))},p.open("GET",s,!1),p.send()},H={"%d":{format:function(s){return i(s.day()||n.MIN_DAY,2)},parse:function(s){var o=Number(s);return{day:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(s){return i(s.month()||n.MIN_MONTH,2)},parse:function(s){var o=Number(s);return{month:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(s){return i(s.year()||n.MIN_YEAR,4)},parse:function(s){var o=Number(s);return{year:isNaN(o)?t:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(s){return s.dayOfWeek()||n.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(s){var o=s.dayOfWeek();return b[o!==t?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(s){var o=s.dayOfWeek();return B[o!==t?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(s){var o=n.options("monthFromZero")?s.month():s.month()-1;return g[o!==t?o:n.MIN_MONTH]},parse:function(s){var o=n.monthNames().indexOf(s)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:t}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(s){var o=n.options("monthFromZero")?s.month():s.month()-1;return T[o!==t?o:n.MIN_MONTH]},parse:function(s){var o=n.monthNames(!0).indexOf(s)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:t}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(s){return i(s.hours()||n.MIN_HOURS,2)},parse:function(s){var o=Number(s);return{hours:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(s){return i(s.minutes()||n.MIN_MINUTES,2)},parse:function(s){var o=Number(s);return{minutes:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(s){return i(s.seconds()||n.MIN_SECONDS,2)},parse:function(s){var o=Number(s);return{seconds:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(s){return s.timestamp()},parse:function(s){return isNaN(Number(s))?{}:n(Number(s)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(s){return i(s.year()||n.MIN_YEAR,4)+"-"+i(s.month()||n.MIN_MONTH,2)+"-"+i(s.day()||n.MIN_DAY,2)},parse:function(s){var o=Number(s.slice(0,4)),m=Number(s.slice(5,7)),p=Number(s.slice(8,10));return{year:o,month:m,day:p}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(s){return i(s.month()||n.MIN_MONTH,2)+"/"+i(s.day()||n.MIN_DAY,2)+"/"+i(s.year()||n.MIN_YEAR,4)},parse:function(s){var o=Number(s.slice(0,2)),m=Number(s.slice(3,5)),p=Number(s.slice(6,10));return{year:p,month:o,day:m}},minLength:10,maxLength:10,type:"string"}},U={useMilliseconds:!1,monthFromZero:!1},M;M=function(s,o,m){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},s!==t&&this.set(s,o,m),this},M.fn=M.prototype,M.fn.dayCount=function(){var s=this.month(),o=n.MAX_DAY_IN_MONTHS[s-(n.options("monthFromZero")?0:1)];return this.leapYear()&&s===(n.options("monthFromZero")?1:2)&&(o+=1),o},M.fn.year=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_YEAR&&Number(s)<=n.MAX_YEAR?(this._d.setFullYear(Number(s)),this._i.year=!1):this._i.year=Number(s):(this._d.setFullYear(n.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},M.fn.month=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MONTH&&Number(s)<=n.MAX_MONTH?(this._d.setMonth(n.options("monthFromZero")?Number(s):Number(s)-1),this._i.month=!1):this._i.month=Number(s):(this._d.setMonth(n.options("monthFromZero")?n.MIN_MONTH:n.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?n.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},M.fn.day=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_DAY&&Number(s)<=this.dayCount()?(this._d.setDate(Number(s)),this._i.day=!1):this._i.day=Number(s):(this._d.setDate(n.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},M.fn.hours=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_HOURS&&Number(s)<=n.MAX_HOURS?(this._d.setHours(Number(s)),this._i.hours=!1):this._i.hours=Number(s):(this._d.setHours(n.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},M.fn.minutes=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MINUTES&&Number(s)<=n.MAX_MINUTES?(this._d.setMinutes(Number(s)),this._i.minutes=!1):this._i.minutes=Number(s):(this._d.setMinutes(n.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},M.fn.seconds=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_SECONDS&&Number(s)<=n.MAX_SECONDS?(this._d.setSeconds(Number(s)),this._i.seconds=!1):this._i.seconds=Number(s):(this._d.setSeconds(n.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},M.fn.milliseconds=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MILLISECONDS&&Number(s)<=n.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(s)),this._i.milliseconds=!1):this._i.milliseconds=Number(s):(this._d.setMilliseconds(n.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},M.fn.week=function(){var s=new Date(this.year(),0,1),o=n(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-s.getTime())/864e5+s.getDay()+1)/7)},M.fn.set=function(s,o,m){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},s===t)return this._d=new Date,this;if(s instanceof Date)return this._d=s,this;if(typeof s=="number")return this._d=new Date(s*(n.options("useMilliseconds")?1:1e3)),this;if(typeof s=="object"&&(s instanceof Array?(this.day(n.MIN_DAY),this.year(s[0]),this.month(s[1]),this.day(s[2]),this.hours(s[3]),this.minutes(s[4]),this.seconds(s[5]),this.milliseconds(s[6])):(this.day(n.MIN_DAY),this.year(s.year),this.month(s.month),this.day(s.day),this.hours(s.hours),this.minutes(s.minutes),this.seconds(s.seconds),this.milliseconds(s.milliseconds))),typeof s=="string"){var p,Y=[],S,w,st=[],v=0,j=0,W,K,x={},F;if(s===t)return S=a(this,m),S===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),S;for(o===t&&(o=n.detectFormat(s));v<o.length;){if(o.charAt(v)==="%"){if(w=o.charAt(v)+o.charAt(v+1),H[w]!==t){switch(W=0,K="",H[w].type){case"number":for(;W<H[w].maxLength&&j+W<s.length&&!isNaN(Number(s.charAt(j+W)));)K+=s.charAt(j+W),W+=1;break;case"word":for(;W<H[w].maxLength&&j+W<s.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(s.charAt(j+W));)K+=s.charAt(j+W),W+=1;break;case"string":for(;W<H[w].maxLength&&j+W<s.length;)K+=s.charAt(j+W),W+=1;break}if(W<H[w].minLength)return S=a(this,m),S===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),S;Y.push(w),st.push(K),W-=1,j+=W,v+=1}}else if(s.charAt(j)!==o.charAt(v))return S=a(this,m),S===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),S;v+=1,j+=1}for(p in Y)Y.hasOwnProperty(p)&&H.hasOwnProperty(Y[p])&&(F=H[Y[p]].parse(st[p]),x={year:F.year!==t?F.year:x.year,month:F.month!==t?F.month:x.month,day:F.day!==t?F.day:x.day,hours:F.hours!==t?F.hours:x.hours,minutes:F.minutes!==t?F.minutes:x.minutes,seconds:F.seconds!==t?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 s=this.year();return s%4===0?s%100===0?s%400===0:!0:!1},M.fn.timestamp=function(s){return arguments.length!==0?(this._d=new Date(Number(s)*(n.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):n.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},M.fn.utc=function(s){return arguments.length!==0?(this._d=new Date(Number(s)*(n.options("useMilliseconds")?1:1e3)),this):n.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},M.fn.dayOfWeek=function(s){if(s==="long")return B[this._d.getDay()];if(s==="short")return b[this._d.getDay()];if(s===t)return this._d.getDay();if(s===0||s==="Sunday")return this.calc({day:-this.dayOfWeek()});if(s===1||s==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(s===2||s==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(s===3||s==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(s===4||s==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(s===5||s==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(s===6||s==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},M.fn.timezone=function(s){switch(s){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},M.fn.get=function(s){switch(s){case"Date":return new Date(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds());case"DateUTC":return new Date(Date.UTC(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()));case"Array":return[this.year(),this.month(),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()];default:return{year:this.year(),month:this.month(),week:this.week(),day:this.day(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds(),utc:this.utc(),dayOfWeek:this.dayOfWeek(),dayOfWeekShort:this.dayOfWeek("short"),dayOfWeekLong:this.dayOfWeek("long"),timestamp:this.timestamp()}}},M.fn.format=function(s){for(var o=0,m="",p;o<s.length;)s.charAt(o)==="%"?(p=s.charAt(o)+s.charAt(o+1),H[p]!==t?(m+=H[p].format(this),o+=1):m+="%"):m+=s.charAt(o),o+=1;return m},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(s,o){var m=this.timestamp(),p=s.timestamp();switch(o){case"year":return Math.floor((p-m)/31556952);case"month":return Math.floor((p-m)/2629746);case"day":return Math.floor((p-m)/86400);case"hours":return Math.floor((p-m)/3600);case"minutes":return Math.floor((p-m)/60);case"seconds":return p-m;default:return t}},M.fn.calc=function(s){return s.year!==t&&this._d.setFullYear(this._d.getFullYear()+s.year),s.month!==t&&this._d.setMonth(this._d.getMonth()+s.month),s.day!==t&&this._d.setDate(this._d.getDate()+s.day),s.hours!==t&&this._d.setHours(this._d.getHours()+s.hours),s.minutes!==t&&this._d.setMinutes(this._d.getMinutes()+s.minutes),s.seconds!==t&&this._d.setSeconds(this._d.getSeconds()+s.seconds),s.milliseconds!==t&&this._d.setMilliseconds(this._d.getMilliseconds()+s.milliseconds),this},n=function(s,o,m){return new M(s,o,m)},n.MIN_YEAR=1e3,n.MAX_YEAR=3e3,n.MIN_MONTH=1,n.MAX_MONTH=12,n.MIN_DAY=1,n.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],n.MIN_DAY_OF_WEEK=0,n.MAX_DAY_OF_WEEK=6,n.MIN_HOURS=0,n.MAX_HOURS=23,n.MIN_MINUTES=0,n.MAX_MINUTES=59,n.MIN_SECONDS=0,n.MAX_SECONDS=59,n.MIN_MILLISECONDS=0,n.MAX_MILLISECONDS=999,n.VERSION="0.2.18",n.options=function(s,o){if(s===t)return U;if(U.hasOwnProperty(s)){if(o===t)return U[s];U[s]=o,s==="monthFromZero"&&(n.MIN_MONTH=o?0:1,n.MAX_MONTH=o?11:12)}return t},n.noConflict=function(){return r.tempus=u,n},n.generate=function(s){var o,m,p,Y,S,w,st,v;if(typeof s.dateFrom!="number"&&(s.dateFrom instanceof M?o=s.dateFrom.utc():o=n(s.dateFrom,s.formatFrom).utc()),typeof s.dateTo!="number"&&(s.dateTo instanceof M?m=s.dateTo.utc():m=n(s.dateTo,s.formatTo!==t?s.formatTo:s.formatFrom).utc()),typeof s.period=="number"?S={year:0,month:0,day:0,hours:0,minutes:0,seconds:s.period}:typeof s.period=="string"?S={year:s.period==="year"?1:0,month:s.period==="month"?1:0,day:s.period==="day"?1:0,hours:s.period==="hours"?1:0,minutes:s.period==="minutes"?1:0,seconds:s.period==="seconds"?1:0}:typeof s.period=="object"&&(S={year:s.period.year!==t?s.period.year:0,month:s.period.month!==t?s.period.month:0,day:s.period.day!==t?s.period.day:0,hours:s.period.hours!==t?s.period.hours:0,minutes:s.period.minutes!==t?s.period.minutes:0,seconds:s.period.seconds!==t?s.period.seconds:0}),s.groupBy===t?w=s.asObject===!0?{}:[]:(w=[],w.push([]),st=n(o).get()[s.groupBy]),v=function(K,x,F){return s.asObject===!0?s.format!==t?K[n(x).format(s.format)]={}:K[n(x).format("%F %H:%M:%S")]={}:s.format!==t?K.push(F?null:n(x).format(s.format)):K.push(F?null:n(x)),K},s.groupBy!==t&&s.fillNulls){var j={year:S.year?-S.year:t,month:S.month?-S.month:t,day:S.day?-S.day:t,hours:S.hours?-S.hours:t,minutes:S.minutes?-S.minutes:t,seconds:S.seconds?-S.seconds:t,milliseconds:S.milliseconds?-S.milliseconds:t};for(p=n(o).calc(j).utc();n(p).get()[s.groupBy]===st;)v(w[w.length-1],p,!0),p=n(p).calc(j).utc();if(s.groupBy==="week"){var W=n(o).dayOfWeek();for(p=n(o).dayOfWeek(0).utc();w[0].length<W&&p<o;)v(w[w.length-1],p,!0),p=n(p).calc(S).utc()}}for(;o<=m;)s.groupBy===t?v(w,o):n(o).get()[s.groupBy]===st?v(w[w.length-1],o):(w.push([]),v(w[w.length-1],o),st=n(o).get()[s.groupBy]),o=n(o).calc(S).utc();if(s.groupBy!==t&&s.fillNulls)for(Y=n(m).calc(S).utc();n(Y).get()[s.groupBy]===st;)v(w[w.length-1],Y,!0),Y=n(Y).calc(S).utc();return w},n.monthNames=function(s){switch(s){case"long":return T;default:return g}},n.dayNames=function(s){switch(s){case"long":return B;default:return b}},n.lang=function(s){if(s!==t)A=s,c[A]===t&&(A="en"),T=N(),g=O(),B=R(),b=k();else return A;return t},n.availableLangs=function(){return Object.keys(c)},n.registerFormat=function(s,o,m,p,Y,S){H[s]={format:o,parse:m,minLength:p,maxLength:Y,type:S}},n.unregisterFormat=function(s){delete H[s]},n.detectFormat=function(s){var o,m,p;return o=h(s,0),o!==""&&(p=10),m=s.charAt(p),(m==="T"||m===" ")&&(o+=m,p+=1),o+=l(s,p),o},d={TempusDate:M},n.classes=function(s,o){if(o===t)return d[s];d[s]=o},n.loadTranslations=function(s){typeof s=="object"?c=s:typeof s=="string"&&P(s,function(o){c=o},function(o){})},A=(f.language||f.systemLanguage||f.userLanguage||"en").substr(0,2).toLowerCase(),c[A]===t&&(A="en"),T=N(),g=O(),B=R(),b=k(),_.exports&&(e=_.exports=n),e.tempus=n}).call(C)})(ct,ct.exports);var Ue=ct.exports;const pt=G(Ue),Q=class Q{constructor(e){E(this,Dt);E(this,ht);E(this,Ht);E(this,Ut);E(this,rt);E(this,V);E(this,yt);E(this,it);E(this,Pt);E(this,Gt);E(this,ut);E(this,Nt);E(this,Ot);typeof e=="function"?(this.callBatch=e,this.callMethod=null):(this.callBatch=(e==null?void 0:e.callBatch)||null,this.callMethod=(e==null?void 0:e.callMethod)||null),this.result={},this.errors={},this.errorMessages={},this.timeLimit={limit:!1,date:void 0,pauseMs:void 0},this.timeLimitListeners=new Set,this.canContinue=!0,this.progressCall="",this.progressData="",this.progressTimer="",this.lastProgressSnapshot=null,this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.filterChunkSize=50,this.limit=50,this.progressDelay=100,this.operatingThreshold=475,this.defaultPauseMs=12e4,this.callLimitPauseMs=3e4,this.requestTimeoutMs=6e4}get progressPercent(){if(!this.progressData)return{percent:0,allCount:0,allTotal:0};const e=this.totalBatchCommands||0;if(e>0&&Array.isArray(this.batchCommandKeyOrder)&&this.batchCommandKeyOrder.length&&y(this,Dt,Ne).call(this)){let u=0;for(const c of this.batchCommandKeyOrder){const N=this.progressData[c];if(!N)continue;const O=Number(N.total)||0,R=Number(N.count)||0;O===0&&R===0?u+=1:O>0&&(u+=Math.min(1,R/O))}const n=u/e*100;let d=Math.max(0,Math.min(100,Math.floor(n)));const f=e,A=Math.min(e,Math.floor(u));return{percent:d,allCount:A,allTotal:f}}let t=0,r=0;for(const u of Object.values(this.progressData)){const{total:n,count:d}=u;t+=n??0,r+=d??0}const i=Number(this.chunkRate)||0;let a=0;t?a=r/t*100*i+this.totalProgress:r===0&&t===0?a=i<1?this.totalProgress:100*i+this.totalProgress:a=100,a=Math.max(0,Math.min(a,100));let l=Math.floor(a);const h=Number(this.chunkRate)||0;return t>0&&r>=t&&h>=1&&(l=100),{percent:l,allCount:r,allTotal:t}}setProgressData({key:e,value:t,type:r}){var c,N;if(!this.progressCall)return;const i=this.getData(t.data()),a=Array.isArray(i)?i.length:0;let l=a;if(typeof t.total=="function"){const O=t.total();if(O!=null&&O!==""){const R=Number(O);Number.isFinite(R)&&(l=R)}}let h=1;r==="count"?(l||(l=a),h=l>0?l:a>0?a:1):i&&(h=a),this.progressData||(this.progressData={});const u=((c=this.progressData[e])==null?void 0:c.total)??0,n=((N=this.progressData[e])==null?void 0:N.count)??0,d=h+n,f=Math.max(u,l??0,d);if(this.progressData[e]={total:f,count:Math.min(d,f)},typeof document<"u"&&(document==null?void 0:document.hidden)===!0){y(this,ht,Zt).call(this);return}y(this,ht,Zt).call(this),this.progressTimer||(this.progressTimer=setInterval(()=>{if(!this.progressCall){this.clearProgressData();return}y(this,ht,Zt).call(this);const{percent:O}=this.progressPercent;O>=100&&(clearInterval(this.progressTimer),this.progressTimer="")},this.progressDelay))}getData(e){if(e==null)return e;let t=(e==null?void 0:e.items)??(e==null?void 0:e.tasks)??(e==null?void 0:e.types)??(e==null?void 0:e.type)??(e==null?void 0:e.fields)??(e==null?void 0:e.workgroups)??e;return t&&typeof t=="object"&&!Array.isArray(t)&&Array.isArray(t.result)&&(t=t.result),t}setTimeLimitState(e,t,r){this.timeLimit.limit=!!e,this.timeLimit.date=e?t:void 0,e&&typeof r=="number"&&r>0?this.timeLimit.pauseMs=r:this.timeLimit.pauseMs=void 0,y(this,Ut,_e).call(this)}subscribeTimeLimit(e){return typeof e!="function"?()=>{}:(this.timeLimitListeners.add(e),e({limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs}),()=>{this.timeLimitListeners.delete(e)})}splitLargeFilters(e,t){const{method:r,params:i}=t;if(!i)return[{key:e,request:t}];const a=i.filter||i.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:e,request:t}];for(const[l,h]of Object.entries(a))if(!String(l).trim().startsWith("!")&&Array.isArray(h)&&h.length>this.filterChunkSize){const u=[];for(let n=0;n<h.length;n+=this.filterChunkSize){const d=h.slice(n,n+this.filterChunkSize),f=n===0?e:`${e}__chunk_${Math.floor(n/this.filterChunkSize)}`,A={...i};i.filter?(A.filter={...a},A.filter[l]=d):i.FILTER&&(A.FILTER={...a},A.FILTER[l]=d),u.push({key:f,request:{method:r,params:A},originalKey:e,filterKey:l,chunkIndex:Math.floor(n/this.filterChunkSize)})}return u}return[{key:e,request:t}]}mergeSplitResults(e,t){const r=[],i=String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${i}(?:__chunk_\\d+)?$`),l=Object.keys(e).filter(h=>a.test(h)).sort((h,u)=>{const n=h.match(/__chunk_(\d+)$/),d=u.match(/__chunk_(\d+)$/);return n?d?parseInt(n[1])-parseInt(d[1]):1:-1});for(const h of l){const u=e[h];Array.isArray(u)?r.push(...u):u&&r.push(u)}return r}delay(){return typeof document<"u"&&(document==null?void 0:document.hidden)===!0?Promise.resolve():new Promise(t=>setTimeout(t,500))}callBatchWithTimeout(e,t,r={}){const{onLateResponse:i}=r;return new Promise((a,l)=>{let h=!1,u=null;const n=async f=>{if(h)typeof i=="function"&&i(f);else{h=!0,u&&clearTimeout(u);try{await Promise.resolve(t(f)),a()}catch(A){console.error("Error in callBatch callback:",A),l(A)}}},d=async()=>{if(!h){h=!0,u&&clearTimeout(u),console.warn(`Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`);const f={};Object.keys(e).forEach(A=>{f[A]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 60 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(t(f)),a()}catch(A){console.error("Error in timeout callback:",A),a()}}};try{this.callBatch(e,async f=>{await n(f)})}catch(f){h||console.error("Error calling callBatch:",f)}u=setTimeout(async()=>{h||(console.warn(`Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`),await d())},this.requestTimeoutMs)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.lastProgressSnapshot=null}async batch(e,t,r={}){y(this,Ot,Ae).call(this,t);const i={},a={},l={};for(const[d,f]of Object.entries(e)){const A=this.arrayChunk(f);if(!A)continue;const c=this.splitLargeFilters(d,A);if(c.length===1)a[d]=A;else{l[d]=[];for(const N of c)a[N.key]=N.request,l[d].push(N.key)}}this.batchCommandKeyOrder=Object.keys(a),this.totalBatchCommands=this.batchCommandKeyOrder.length,this.batchCommandMethods=this.batchCommandKeyOrder.map(d=>{var f;return String(((f=a[d])==null?void 0:f.method)||"")}),this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let h={},u=0;const n=Object.keys(a).length;for(const[d,f]of Object.entries(a)){if(!this.canContinue)break;if(h[d]=f,Object.keys(h).length>=this.limit||u+1===n){const A=u+1===n;await this.batchChunk(h,void 0,!A,{disablePagination:!1,oneBatch:!!(r!=null&&r.oneBatch)}),Object.entries(this.result).forEach(([c,N])=>{i[c]=N}),this.totalProgress=Math.round(u/n*100),h={}}u++}for(const[d,f]of Object.entries(l))if(f&&f.length>0){const A=this.mergeSplitResults(i,d);for(const c of f)delete i[c];i[d]=A}return y(this,Nt,oe).call(this,i),t&&t({percent:100}),Promise.resolve(i)}async batchTotalCount(e,t){y(this,Ot,Ae).call(this,t);const r={},i={},a={};for(const[u,n]of Object.entries(e)){const d=this.arrayChunk(n);if(!d)continue;const f=this.splitLargeFilters(u,d);if(f.length===1)i[u]=d;else{a[u]=[];for(const A of f)i[A.key]=A.request,a[u].push(A.key)}}const l=[],h=Object.entries(i);for(let u=0;u<h.length;u+=this.limit){const n=h.slice(u,u+this.limit),d={};for(const[f,A]of n){if(!this.canContinue)break;d[f]=A}Object.keys(d).length>0&&l.push(d)}this.chunkRate=(1/l.length).toFixed(5);for(const[u,n]of Object.entries(l)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(u)/l.length*100),this.progressData={},this.lastProgressSnapshot=null;const d=Number(u)===l.length-1;await y(this,it,Mt).call(this,n,async f=>{for(const[A,c]of Object.entries(f)){if(!this.canContinue)return;if(c.error()){y(this,ut,Vt).call(this,A,c),r[A]=0;continue}const N=this.getData(c.data()),O=Array.isArray(N)?N.length:0,k=typeof c.total=="function"&&c.total()!==void 0?c.total():O;r[A]=k,this.setProgressData({key:A,value:c,type:"count"})}await y(this,V,lt).call(this,f,!d)})}for(const[u,n]of Object.entries(a))if(n&&n.length>0){let d=0;for(const f of n)r[f]!==void 0&&(d+=r[f]||0),delete r[f];r[u]=d}return Object.entries(this.errors).length&&(y(this,Nt,oe).call(this,r),this.errorLogger()),t&&t({percent:100}),Promise.resolve(r)}async call({method:e,params:t={}}){var i,a,l,h,u,n,d;const r=y(this,yt,ae).call(this,this.callLimitPauseMs);for(;;){let f=await y(this,Pt,Te).call(this,e,t,{onLateResponse:N=>r.notifyLateResponse(N)});if(!f)if(r.inRetryCycle=!0,await r.waitForLateOrLimit(),r.lateResult)f=r.lateResult,r.resetLateResult(),r.inRetryCycle=!1;else continue;const A={};if(f!=null&&f.answer)for(const[N,O]of Object.entries(f.answer))N!=="result"&&O&&(A[N]=O);if(f.error()){const N=((a=(i=f.error())==null?void 0:i.ex)==null?void 0:a.error)??"";if(["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT","TIMEOUT"].includes(N)){await y(this,rt,It).call(this,this.callLimitPauseMs);continue}const O=((l=f.error())==null?void 0:l.toString())||((u=(h=f.error())==null?void 0:h.ex)==null?void 0:u.error_description)||((d=(n=f.error())==null?void 0:n.ex)==null?void 0:d.error)||"Неизвестная ошибка";return{success:!1,data:!1,answer:A,error:O}}let c=f.data();return c!=null&&c.items&&(c=c.items),r.inRetryCycle=!1,{success:!0,data:c,answer:A,error:null}}}arrayChunk(e){let t="",r={};if(Array.isArray(e)?[t]=e:(t=e.method,r=e.params),(t.includes("list")||t==="user.get"||t==="entity.item.get"||t==="sonet_group.get")&&t!=="task.item.list"){if(!r)r=t==="entity.item.get"?{SORT:{ID:"ASC"}}:t==="sonet_group.get"?{ORDER:{ID:"ASC"}}:t.startsWith("crm.")?{order:{ID:"ASC",id:"ASC"}}:{order:{ID:"ASC"}};else{t==="entity.item.get"?(r.SORT||(r.SORT={ID:"ASC"}),Array.isArray(r.select)?r.select.includes("ID")||r.select.push("ID"):r.select=["ID"]):t==="sonet_group.get"?r.ORDER?!r.ORDER.ID&&!r.ORDER.id&&(r.ORDER.ID="ASC"):r.ORDER={ID:"ASC"}:t==="tasks.task.list"?(r.order||(r.order={}),r.order.ID="asc"):t==="user.get"?(r.sort||(r.sort="ID"),r.order||(r.order="ASC")):t.startsWith("crm.")?r.order={ID:"ASC",id:"ASC"}:r.order?!r.order.ID&&!r.order.id&&(r.order.ID="ASC"):r.order={ID:"ASC"},Array.isArray(r.select)&&!r.select.includes("ID")&&r.select.push("ID");const i=t==="user.get"||t==="entity.item.get"||t==="sonet_group.get"?r.FILTER:r.filter;typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.entries(i).forEach(([a,l])=>{(r.start===void 0||r.start!==-1)&&["id","ID"].includes(a)&&(typeof l=="string"||Array.isArray(l)&&l.length<=50)&&(r.start=-1)})}t==="crm.type.list"&&r.order&&delete r.order.ID}if(t==="task.item.list")if(!r)r=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(r[0])&&(r[0]={});const[i,a,l,h]=r;i.ID="ASC",h[0]!==""&&h.includes("ID")||h.push("ID")}return{method:t,params:r}}async batchChunk(e,t,r=!0,i={}){return new Promise(a=>{const l=[];let h;const u=!!(i!=null&&i.disablePagination);(async()=>{await y(this,it,Mt).call(this,e,async d=>{for(const[A,c]of Object.entries(d)){if(!this.canContinue)return;c.error()&&(y(this,ut,Vt).call(this,A,c),h=!0);const N=this.getData(c.data()),O=Array.isArray(N)?N.length:0,R=typeof c.total=="function"&&c.total()!==void 0,k=R?c.total():O;t==="count"?this.result[A]?this.result[A]+=O:this.result[A]=k:this.result[A]=N,this.setProgressData({key:A,value:c,type:t});const T=e[A],g=Array.isArray(T)?T[0]:T==null?void 0:T.method,B=typeof g=="string"&&(g.includes(".list")||g.endsWith("getlist")||g==="user.get"||g==="entity.item.get"||g==="sonet_group.get"),b=t==="count"?!R&&O===this.limit:B?O===this.limit:k>this.limit&&k>O,P=t!=="count"&&g==="entity.item.get"&&O===this.limit&&!b,H=b||P;if(!u&&(!this.canContinue||H)){let U=e[A];if(Array.isArray(U)){const[M,s={}]=U;U=[M,s]}else{const{method:M,params:s={}}=U;U=[M,s]}l.push([A,U,k,{entityItemGetScan:P}])}}h>0&&this.errorLogger();const f=l.length>0||r;await y(this,V,lt).call(this,d,f),l.length?await this.batchPayload(l,t,i).then(()=>a(this.result)):a(this.result)})})()})}async batchPayload(e,t,r={}){const i=!!(r!=null&&r.oneBatch),a=(N,O,R,k)=>{let T="ID";this.result[N][this.result[N].length-1].ID||(T="id");let g=`${T}`;if(JSON.stringify(k[1]).toLocaleLowerCase().includes('"id":"desc"')?g="<"+g:g=">"+g,O===1||R.length===0)return{field:g,id:this.result[N][this.result[N].length-1][T]};let b="";const[P,H]=k;return(P==="tasks.task.list"||P==="task.item.list")&&(b="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(P)&&(b="[items]"),P==="crm.type.list"&&(b="[types]"),P==="socialnetwork.api.workgroup.list"&&(b="[workgroups]"),{field:g,id:`$result[${[N,O-1].join("__")}]${b}[49][${T}]`}},l=(N,O)=>{const[R,k]=N;let T=JSON.parse(JSON.stringify(k)),g;if(R==="task.item.list"){T=[...T];const[B,b,P,H]=T;return b[O.field]=O.id,[R,T]}return["user.get","sonet_group.get"].includes(R)||T.FILTER?(T.FILTER||(T.FILTER={}),g=T.FILTER):(T.filter||(T.filter={}),g=T.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(R)?g[">ID"]=O.id:g[O.field]=O.id,[R,{...T,start:-1}]},h=N=>{Object.entries(N).forEach(([O,R])=>{const[k]=O.split("__"),T=this.getData(R.data());Array.isArray(T)&&(t==="count"?this.result[k]+=T.length:this.result[k].push(...T)),R.error()&&y(this,ut,Vt).call(this,k,R),this.setProgressData({key:k,value:R,type:t})})},u=(N,O)=>{if(!Array.isArray(N)||N.length===0)return null;const R=N[N.length-1];let k="ID";R.ID||(k="id");let T=k;return JSON.stringify(O[1]).toLocaleLowerCase().includes('"id":"desc"')?T="<"+T:T=">"+T,{field:T,id:R[k]}},n=1e4,d=async(N,O)=>{var R,k;for(let T=1;this.canContinue&&T<=n;T++){const g=this.result[N],B=u(g,O);if(!B)break;const b=`${N}__page_${T}`,P=l(O,B);let H=null;await y(this,it,Mt).call(this,{[b]:P},async o=>{H=o,h(o)});const U=H==null?void 0:H[b];if((R=U==null?void 0:U.error)!=null&&R.call(U)){await y(this,V,lt).call(this,H,!1);break}const M=this.getData((k=U==null?void 0:U.data)==null?void 0:k.call(U));if((Array.isArray(M)?M.length:0)===0){await y(this,V,lt).call(this,H,!1);break}await y(this,V,lt).call(this,H,T<n)}};let f=[],A=0;const c=async(N=!0)=>f.length?(await y(this,it,Mt).call(this,Object.fromEntries(f),async O=>{h(O),await y(this,V,lt).call(this,O,N)}),A++,f=[],i&&A>=1?!0:(await this.delay(),!1)):!1;for await(const N of e){if(!this.canContinue)return;const[O,R,k,T={}]=N;if(T.entityItemGetScan||!i){if(await c(!0))return;if(i)continue;await d(O,R);continue}let g=1;for(;k>g*this.limit;){const B=[O,g].join("__"),b=a(O,g,f,R);if(f.push([B,l(R,b)]),i&&f.length===49&&await c(!0)||f.length%50===0&&await c(!0))return;g++}}await c(!1)}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([e,t])=>{t&&console.log(`[${e}]`,t.toString())}),console.groupEnd()}};Dt=new WeakSet,Ne=function(){const e=this.totalBatchCommands||0,t=this.batchCommandMethods;if(e<L(Q,kt)||!Array.isArray(t)||t.length!==e)return!1;if(t.filter(a=>a==="crm.deal.list").length>=L(Q,Bt))return!0;const i=t.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=L(Q,Ct)&&i/e>=L(Q,wt)},kt=new WeakMap,Bt=new WeakMap,Ct=new WeakMap,wt=new WeakMap,ht=new WeakSet,Zt=function(){if(!this.progressCall||!this.progressData)return;const{percent:e,allCount:t,allTotal:r}=this.progressPercent,i={percent:e,allCount:t,allTotal:r};y(this,Ht,Oe).call(this,i)&&(this.progressCall({data:this.progressData,percent:e,allCount:t,allTotal:r}),this.lastProgressSnapshot=i)},Ht=new WeakSet,Oe=function(e){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==e.percent||this.lastProgressSnapshot.allCount!==e.allCount||this.lastProgressSnapshot.allTotal!==e.allTotal:!0},Ut=new WeakSet,_e=function(){const e={limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs};for(const t of this.timeLimitListeners)try{t(e)}catch(r){console.warn("Batch timeLimit listener error:",r)}},rt=new WeakSet,It=async function(e=this.defaultPauseMs){this.setTimeLimitState(!0,new Date().toISOString(),e),await new Promise(t=>setTimeout(t,e)),this.setTimeLimitState(!1,void 0)},V=new WeakSet,lt=async function(e,t=!0){if(!t)return 0;let r=0;if(!e||typeof e!="object")return 0;for(const i of Object.values(e))if(!(!i||typeof i!="object"))try{if(typeof i.time=="function"){const a=i.time();a&&typeof a.operating=="number"&&(r=Math.max(r,a.operating))}}catch{}r>=this.operatingThreshold&&await y(this,rt,It).call(this)},yt=new WeakSet,ae=function(e=this.defaultPauseMs){const t=this;return{inRetryCycle:!1,inTimeoutWait:!1,lateResult:null,lateWaiters:[],notifyLateResponse(i){if(!(!this.inRetryCycle&&!this.inTimeoutWait)){this.lateResult=i;for(const a of this.lateWaiters)a(i);this.lateWaiters=[]}},waitForLateOrLimit(){var a;this.inTimeoutWait=!0;const i=new Promise(l=>{if(this.lateResult){l(this.lateResult);return}this.lateWaiters.push(l)});return Promise.race([y(a=t,rt,It).call(a,e),i]).finally(()=>{this.inTimeoutWait=!1})},resetLateResult(){this.lateResult=null}}},it=new WeakSet,Mt=async function(e,t){let r=!1,i=e;const a=y(this,yt,ae).call(this);do r=!1,await this.callBatchWithTimeout(i,async l=>{var n,d;let h=!1;const u=new Set;for(const[f,A]of Object.entries(l||{})){if(!(A!=null&&A.error)||!A.error())continue;const c=((d=(n=A.error())==null?void 0:n.ex)==null?void 0:d.error)??"";if(c==="TIMEOUT"){h=!0;break}["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT"].includes(c)&&u.add(f)}if(h){if(a.inRetryCycle=!0,r=!0,await a.waitForLateOrLimit(),a.lateResult){r=!1,a.inRetryCycle=!1;const f=a.lateResult;a.resetLateResult(),await t(f)}return}if(u.size>0){const f={};for(const[c,N]of Object.entries(l||{}))u.has(c)||(f[c]=N);Object.keys(f).length&&await t(f);const A={};for(const c of u)i[c]&&(A[c]=i[c]);i=A,Object.keys(i).length&&(r=!0,await y(this,rt,It).call(this));return}a.inRetryCycle=!1,await t(l)},{onLateResponse:l=>a.notifyLateResponse(l)});while(r)},Pt=new WeakSet,Te=function(e,t,r={}){const{onLateResponse:i}=r;return new Promise(a=>{if(typeof this.callMethod!="function"){a(null);return}let l=!1;const h=setTimeout(()=>{l||(l=!0,a(null))},this.requestTimeoutMs);try{this.callMethod(e,t,u=>{l?typeof i=="function"&&i(u):(l=!0,clearTimeout(h),a(u))})}catch{l||(l=!0,clearTimeout(h),a(null))}})},Gt=new WeakSet,Ee=function(e){const t=typeof(e==null?void 0:e.error)=="function"?e.error():null,r=(t==null?void 0:t.ex)||{},i=String(r.error||"").trim(),a=String(r.error_description||"").trim(),l=typeof(t==null?void 0:t.toString)=="function"?String(t.toString()).trim():"";let h=a;return!h&&l&&l!==i&&(h=l),h||(h=i||"Неизвестная ошибка"),{code:i||h,message:h}},ut=new WeakSet,Vt=function(e,t){const{code:r,message:i}=y(this,Gt,Ee).call(this,t);this.errors[e]=r,this.errorMessages[e]=i},Nt=new WeakSet,oe=function(e){Object.entries(this.errors).length&&(e.errorsList={...this.errors},Object.entries(this.errorMessages).length&&(e.errorsListMessages={...this.errorMessages}))},Ot=new WeakSet,Ae=function(e){this.clearProgressData(),this.progressCall=typeof e=="function"?e:"",this.canContinue=!0,this.result={},this.errors={},this.errorMessages={},this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.setTimeLimitState(!1,void 0)},E(Q,kt,5),E(Q,Bt,5),E(Q,Ct,8),E(Q,wt,.65);let q=Q;class te{constructor(){E(this,nt,{})}get hash(){return this.createHash(8)}createHash(e){let t="abcdefghijklmnopqrstuvwxyz0123456789",r="";e=e||6;for(let i=0;i<e;i++)r+=t.charAt(Math.floor(Math.random()*t.length));return r}actionFilter({keyTimer:e,duration:t=10,action:r}){L(this,nt)[e]&&(clearTimeout(L(this,nt)[e]),L(this,nt)[e]=null),r&&(L(this,nt)[e]=setTimeout(()=>{r()},t))}async noSleep(){let e=document.createElement("video");e.classList.add("no-sleep"),e.muted=!0,e.autoplay=!0,e.setAttribute("playsinline",""),e.addEventListener("loadeddata",()=>{e.style.position="fixed",e.style.left="-9999px",document.querySelector("body").append(e),e.play().catch(t=>{console.warn("noSleep: autoplay prevented",t)})}),e.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{e.play().catch(t=>{console.warn("noSleep: replay prevented",t)})}})}),e.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(e,t){let r=new Blob([JSON.stringify(e)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=i,a.download=`${t}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(i)},200)}}nt=new WeakMap;const ee=new te;class de{constructor(){E(this,Yt);E(this,Tt);E(this,Wt);E(this,xt);E(this,Ft);E(this,Z,"logger");E(this,$,!1);E(this,at,new Map);E(this,ft,{});E(this,_t,!1);E(this,tt,null);E(this,J,null);E(this,ot,!1);E(this,dt,!1);D(this,"periodClear",3)}async init(){try{let e=new q(BX24.callBatch),{entityList:t}=await e.batch({entityList:{method:"entity.get"}});if(t&&Array.isArray(t))if(t.find(i=>i.ENTITY==L(this,Z)))X(this,$,!0);else{let{entityAdd:i}=await e.batch({entityAdd:{method:"entity.add",params:{ENTITY:L(this,Z),NAME:L(this,Z),ACCESS:{AU:"X"}}}});i&&X(this,$,!0)}return L(this,$)}catch(e){return console.error("Ошибка при инициализации логера:",e),!1}}enableBackworkerMode(){return X(this,$,!0),!0}start({type:e,data:t}){if(!L(this,$))return y(this,Tt,le).call(this,"entity"),null;if(!e||!t)return console.error("Невалидные данные для логирования:",{type:e,data:t}),null;const r=ee.hash,i={type:e,data:t,userInfo:null,errorList:{},status:"",answer:null,date:new Date().getTime()};return L(this,at).set(r,i),X(this,dt,!0),r}async stop({key:e,errorList:t,status:r,answer:i}){var l;if(!L(this,dt))return;if(!L(this,$)){y(this,Tt,le).call(this,"entity");return}let a=L(this,at).get(e);if(!a){console.error(`Не найдены данные логирования для ключа: ${e}`);return}t&&(a.errorList=t),r&&(a.status=r),i&&(a.answer=i),await y(this,Yt,Re).call(this),a.userInfo=L(this,ft),await y(this,Wt,Le).call(this),(l=a==null?void 0:a.data)!=null&&l.updateList&&X(this,ot,!0),X(this,dt,!1)}async getEntityList(e){var t;try{if((t=L(this,J))!=null&&t.length&&!L(this,ot))return L(this,J);let r=new q(BX24.callBatch),{entityList:i}=await r.batch({entityList:{method:"entity.item.get",params:{ENTITY:L(this,Z),SORT:{ID:"DESC"}}}},e);return!i||!Array.isArray(i)?(console.warn("Получен невалидный список записей"),[]):(i=i.map(a=>{try{const{ID:l,DATE_CREATE:h,DETAIL_TEXT:u}=a;return{...JSON.parse(u),id:l,dateCreate:h}}catch(l){return console.error(`Ошибка парсинга записи ${a.ID}:`,l),null}}).filter(a=>a!==null),X(this,ot,!1),X(this,J,i),i)}catch(r){return console.error("Ошибка при получении списка записей:",r),[]}}runStorageMaintenance(){return y(this,xt,be).call(this)}async downAllEntityJson(){try{if(L(this,J)||await this.getEntityList(),!L(this,J)||L(this,J).length===0)return console.warn("Нет данных для выгрузки"),!1;let e=pt().format("%Y-%m-%d");return ee.downloadFileJson(L(this,J),`sdklogger-entity-data__${e}`),!0}catch(e){return console.error("Ошибка при выгрузке данных в JSON:",e),!1}}}Z=new WeakMap,$=new WeakMap,at=new WeakMap,ft=new WeakMap,_t=new WeakMap,tt=new WeakMap,J=new WeakMap,ot=new WeakMap,dt=new WeakMap,Yt=new WeakSet,Re=async function(){if(!L(this,_t))return L(this,tt)?L(this,tt):(X(this,tt,(async()=>{try{const e=new q(BX24.callBatch),t=BX24.isAdmin(),{curUser:r}=await e.batch({curUser:{method:"user.current"}});X(this,ft,{isAdmin:t,curUser:r})}catch(e){console.error("Ошибка при получении информации о пользователе:",e),X(this,ft,{isAdmin:!1,curUser:null})}finally{X(this,_t,!0),X(this,tt,null)}})()),L(this,tt))},Tt=new WeakSet,le=function(e){e=="entity"&&ee.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},Wt=new WeakSet,Le=async function(){try{let e={},t=new q(BX24.callBatch);for(let[r,i]of L(this,at).entries())if(i.status){const a=JSON.stringify(i);e[r]={method:"entity.item.add",params:{ENTITY:L(this,Z),NAME:L(this,Z),DETAIL_TEXT:a}}}if(Object.keys(e).length){let r=await t.batch(e),{errors:i}=t;for(let[a,l]of Object.entries({...r,...i}))L(this,at).delete(a);return!0}return!1}catch(e){return console.error("Ошибка при добавлении записей в хранилище:",e),!1}},xt=new WeakSet,be=async function(){try{let e=new q(BX24.callBatch),{serverTime:t}=await e.batch({serverTime:{method:"server.time"}});if(!t){console.error("Не удалось получить время сервера");return}if(L(this,J)||await this.getEntityList(),!L(this,J)||L(this,J).length===0)return;let r=L(this,J).filter(i=>{try{let{dateCreate:a}=i;return a?pt(new Date(a)).between(pt(new Date(t)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});r.length>0&&(console.log(`Найдено ${r.length} записей для очистки (старше ${this.periodClear} месяцев)`),await y(this,Ft,Ie).call(this,r))}catch(e){console.error("Ошибка при проверке периода очистки:",e)}},Ft=new WeakSet,Ie=async function(e){try{if(!e||e.length===0)return!1;let t=new q(BX24.callBatch),r=e.filter(a=>a&&a.id).map(a=>{let{id:l}=a;return{method:"entity.item.delete",params:{ENTITY:L(this,Z),ID:l}}});if(r.length===0)return!1;const i=await t.batch(r);return console.log(`Успешно удалено ${r.length} записей`),X(this,ot,!0),i}catch(t){return console.error("Ошибка при очистке устаревших записей:",t),!1}};function se(_){if(!_||typeof _!="string")return"";try{const e=new URL(_);e.search="",e.hash="";let t=e.toString();return t.endsWith("/")&&e.pathname!=="/"&&(t=t.slice(0,-1)),t}catch{return _.split("?")[0].split("#")[0].replace(/\/$/,"")}}function me(_){return!_||typeof _!="string"?!1:_.toLowerCase().includes("/marketplace/app")}function Pe(){var e;if(typeof window>"u"||!((e=window.location)!=null&&e.href))return"";const _=se(window.location.href);return me(_)?"":_}function re(_){if(!(_!=null&&_.appConst)||typeof _.appConst!="object")return"";const e=Pe();return e?(_.appConst.pathApp=e,e):se(_.appConst.pathApp??"")}class Ge{constructor(e){E(this,mt);E(this,vt);E(this,Et);E(this,Xt);E(this,Jt);E(this,jt);E(this,et);E(this,Rt);E(this,Kt);E(this,Lt);E(this,qt);D(this,"domain","");D(this,"isAdmin",!1);D(this,"appInfo",null);D(this,"appConst",null);D(this,"userInfo",null);D(this,"placeData",null);D(this,"placeInfo",null);D(this,"logger",!1);D(this,"timeLimit",{limit:!1,date:void 0,pauseMs:void 0});D(this,"batchClient",null);this.appConst=e}subscribeTimeLimit(e){return y(this,mt,$t).call(this).subscribeTimeLimit(e)}init(){return new Promise((e,t)=>{const i=setTimeout(()=>{clearInterval(a);const l=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(l),t(l)},3e4);let a=setInterval(()=>{window.BX24&&BX24.init(async()=>{clearInterval(a),clearTimeout(i),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info();const l=y(this,Xt,Se).call(this);if(console.info(l?"init BX24 (background worker)":"init BX24"),this.appInfo=await y(this,Jt,De).call(this),this.userInfo=await y(this,jt,ke).call(this),re(this),l)await y(this,Et,ce).call(this,!1,{skipInit:!0});else{await y(this,Et,ce).call(this,!0);const h=new te;try{h.noSleep()}catch(u){console.warn("Failed to initialize noSleep:",u)}}e({isBackworker:l})})},100)})}userOption(e,t){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return t!==void 0?BX24.userOption.set(e,t):BX24.userOption.get(e)}appOption(e,t){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return t!==void 0?BX24.appOption.set(e,t):BX24.appOption.get(e)}async call({method:e,params:t,updateList:r}){let i;if(r&&(i=this.logger.start({type:"call",data:{method:e,params:t,updateList:r}})),t||(t={}),typeof BX24>"u"||!BX24.callMethod){const h=new Error("BX24 is not initialized");throw console.error(h),h}const l=await y(this,mt,$t).call(this).call({method:e,params:t});return l.success?(await y(this,et,gt).call(this,i,{answer:l.answer,status:"success"}),l.data):(console.error(l.error),await y(this,et,gt).call(this,i,{answer:l.answer,status:"fail",errorList:{0:l.error||"Unknown call error"}}),!1)}async batch(e,t,{errorCall:r,updateList:i,batchOptions:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const l=new Error("BX24 is not initialized");return console.error(l),!1}return y(this,Rt,he).call(this,{mode:"batch",commandList:e,progressCall:t,errorCall:r,updateList:i,batchOptions:a})}async batchTotalCount(e,t,{errorCall:r,updateList:i}={}){if(typeof BX24>"u"||!BX24.callBatch){const a=new Error("BX24 is not initialized");return console.error(a),!1}return y(this,Rt,he).call(this,{mode:"batch-total-count",commandList:e,progressCall:t,errorCall:r,updateList:i})}async getPlacement(){const e=await this.call({method:"placement.get"});return this.placeData||(this.placeData=e),e}async placementBind(e){var A;if(!this.isAdmin||(this.placeData=await this.getPlacement(),!this.placeData))return;const{appName:t,pathApp:r}=this.appConst;let i=y(this,Lt,ue).call(this,e);i=i.filter(c=>c.placement!=="PAGE_BACKGROUND_WORKER"&&c.placement!=="PAGE_BACKGROUND_WORKER_ALL");const a=y(this,qt,Ce).call(this,r),l=new Set(i.map(c=>c.placement));for(const c of a)l.has(c.placement)||i.push({placement:c.placement});if(i.length===0)return;let h=t;this.domain==="szdl.bitrix24.ru"&&((A=this.appInfo)!=null&&A.ID)&&(h=`${t}: #${this.appInfo.ID}`);const u=h.replace(" CRM",""),n={},d=[],f=new Map;for(const c of this.placeData)f.has(c.placement)||f.set(c.placement,[]),f.get(c.placement).push(c);for(let c=0;c<i.length;c++){const{placement:N,options:O}=i[c],R=f.get(N)||[];if(R.some(g=>g.handler===r))continue;const T=R.filter(g=>g.handler!==r);for(const g of T)d.push({placement:N,handler:g.handler});n[`bind_${c}`]={method:"placement.bind",params:{PLACEMENT:N,HANDLER:r,LANG_ALL:{ru:{TITLE:N==="USER_PROFILE_TOOLBAR"?u:h}},OPTIONS:{errorHandlerUrl:r,...O&&typeof O=="object"?O:{}}}}}d.length>0&&await this.placementUnBind(d),Object.keys(n).length>0&&(await this.batch(n),this.placeData=await this.getPlacement(),Object.values(n).forEach(c=>{console.log("Приложение успешно встроено в",c.params.PLACEMENT)}))}async placementUnBind(e){let t=y(this,Lt,ue).call(this,e);if(t=t.filter(i=>i.placement!=="PAGE_BACKGROUND_WORKER"&&i.placement!=="PAGE_BACKGROUND_WORKER_ALL"),t.length===0)return;const r={};for(let i=0;i<t.length;i++){const a={PLACEMENT:t[i].placement};t[i].handler&&(a.HANDLER=t[i].handler),r[`unbind_${i}`]={method:"placement.unbind",params:a}}await this.batch(r),t.forEach(i=>{console.log("Встройка отвязана",i.placement)})}async getBotList(){const e=await this.call({method:"imbot.bot.list",params:{}}),t=Object.values(e);return console.log("chat-bot list:",t),t}async regBot({code:e,type:t,name:r}){const{appName:i,pathApp:a,chatBotLogo:l}=this.appConst,h=this.appInfo.ID,u=await this.call({method:"imbot.register",params:{CODE:e??this.appInfo.CODE,TYPE:t??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${r??i} - бот #${h}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:pt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:l??""}}});return console.log("Чат-бот добавлен",u),u}async unRegBot(e){const t=await this.call({method:"imbot.unregister",params:{BOT_ID:e}});return console.log("чат-бот удален",t),t}getLoggerList(e){return this.logger.getEntityList(e)}}mt=new WeakSet,$t=function(){return this.batchClient||(this.batchClient=new q({callBatch:BX24.callBatch,callMethod:BX24.callMethod}),this.timeLimit=this.batchClient.timeLimit),this.batchClient},vt=new WeakSet,Me=function(){return{start:()=>{},stop:()=>{},getEntityList:()=>{}}},Et=new WeakSet,ce=async function(e,{skipInit:t=!1}={}){this.logger?(this.logger=new de,t?this.logger.enableBackworkerMode():await this.logger.init(),e&&typeof this.logger.runStorageMaintenance=="function"&&this.logger.runStorageMaintenance()):this.logger=y(this,vt,Me).call(this)},Xt=new WeakSet,Se=function(){var r,i,a;const e=(r=this.placeInfo)==null?void 0:r.placement,t=(a=(i=this.placeInfo)==null?void 0:i.options)==null?void 0:a.ID;return e==="PAGE_BACKGROUND_WORKER"||t==="PAGE_BACKGROUND_WORKER"},Jt=new WeakSet,De=function(){return this.call({method:"app.info"})},jt=new WeakSet,ke=function(){return this.call({method:"user.current"})},et=new WeakSet,gt=async function(e,t){if(e)try{await this.logger.stop({key:e,...t})}catch(r){console.error("Logger error:",r)}},Rt=new WeakSet,he=async function({mode:e,commandList:t,progressCall:r,errorCall:i,updateList:a,batchOptions:l}){const h=y(this,mt,$t).call(this),u=a?this.logger.start({type:e,data:e==="batch"?{commandList:t,updateList:a}:{commandList:t}}):void 0;try{const n=e==="batch"?await h.batch(t,r,l):await h.batchTotalCount(t,r),d=y(this,Kt,Be).call(this,h,n,t,a);return Object.keys(d).length?(i&&i(d),await y(this,et,gt).call(this,u,{status:"fail",errorList:d})):await y(this,et,gt).call(this,u,{status:"success"}),n}catch(n){return await y(this,et,gt).call(this,u,{status:"fail-runtime",errorList:{0:n==null?void 0:n.toString()}}),console.error(n),!1}},Kt=new WeakSet,Be=function(e,t,r,i){let a={...e.errors};if(Object.values(e.errors).some(h=>{if(typeof h!="string")return!1;const u=h.toUpperCase();return u==="TIMEOUT"||u==="OPERATION_TIME_LIMIT"||u.includes("TIMEOUT")||u.includes("OPERATION_TIME_LIMIT")})&&i){const h=t?Object.keys(t).filter(f=>f!=="errorsList"&&f!=="errorsListMessages"):[],u=new Set(Object.keys(e.errors||{})),n=new Set;if(t){for(const f of h)if(!u.has(f)){const A=t[f];A!=null&&n.add(f)}}const d=Object.values(e.errors).find(f=>{if(typeof f!="string")return!1;const A=f.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const f of Object.keys(r))!n.has(f)&&!e.errors[f]&&(a[f]=d||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a},Lt=new WeakSet,ue=function(e){if(!e)return[];let t=[];return Array.isArray(e)?t=e.map(r=>typeof r=="string"?{placement:r}:r):typeof e=="string"?t=[{placement:e}]:t=[e],t},qt=new WeakSet,Ce=function(e){return this.placeData?this.placeData.filter(t=>!(t.placement==="PAGE_BACKGROUND_WORKER"||!t.handler||t.handler.includes(e))):[]};const ge="szdl-utils-kit|";function Ye(){if(typeof sessionStorage>"u")return`ephemeral-${Date.now()}-${Math.random().toString(16).slice(2)}`;let _=sessionStorage.getItem("szdl-cross-tab-instance-id");return _||(_=`${Date.now()}-${Math.random().toString(16).slice(2)}`,sessionStorage.setItem("szdl-cross-tab-instance-id",_)),_}function We(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}const ie=new Map;function xe(_="default"){if(typeof BroadcastChannel>"u")return null;const e=`${ge}bc:${_}`;return ie.has(e)||ie.set(e,new BroadcastChannel(e)),ie.get(e)}function pe(_,e){const t=xe(_);if(t)try{const r=e&&typeof e=="object"&&!Array.isArray(e)?e:{data:e};t.postMessage({...r,tabId:Ye(),ts:Date.now()})}catch{}}async function Fe(_,e,t={}){const{ifAvailable:r=!1}=t,i=typeof _=="string"&&_.length>0?_:"default",a=`${ge}${i}`;return We()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!r},async l=>{if(r&&l==null)return{skipped:!0,coordination:"locks"};pe(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await e(),coordination:"locks"}}finally{pe(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await e(),coordination:"none"}}const z={startDelayMs:0,pollIntervalMs:60*1e3,pollIntervalJitterMs:30*1e3,leaderConfirmDelayMs:60*1e3,activeMaxPauseMs:3*60*1e3,quickCleanupThresholdMs:5*60*1e3,leaderHeartbeatMs:null};function ve(_){return _==null?"user":_==="user"||_==="portal"?_:(console.warn(`BackgroundWorker: coordinationScope должен быть 'user' или 'portal', получено ${JSON.stringify(_)} — используется 'user'`),"user")}function ye(_={}){const e={...z,..._};for(const t of Object.keys(z)){if(t==="leaderHeartbeatMs"){const i=_==null?void 0:_.leaderHeartbeatMs;if(i==null){e.leaderHeartbeatMs=null;continue}const a=Number(i);e.leaderHeartbeatMs=Number.isFinite(a)&&a>=0?a:null;continue}const r=Number(e[t]);e[t]=Number.isFinite(r)&&r>=0?r:z[t]}return e}class Xe{constructor(e){E(this,zt);E(this,bt);E(this,At);E(this,Qt);D(this,"entityName","tabs");D(this,"maxTabs",20);D(this,"tabList",[]);D(this,"id",0);D(this,"hasStarted",!1);D(this,"heartbeat");D(this,"runHeartbeat");D(this,"startDelay",0);D(this,"activeMaxPause",z.activeMaxPauseMs);D(this,"quickCleanupThreshold",z.quickCleanupThresholdMs);D(this,"pollInterval",z.pollIntervalMs);D(this,"pollIntervalBase",z.pollIntervalMs);D(this,"pollIntervalJitter",z.pollIntervalJitterMs);D(this,"leaderConfirmDelay",z.leaderConfirmDelayMs);D(this,"leaderHeartbeatMs",null);D(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);D(this,"continueCondition");D(this,"defaultContinueBackground",()=>!0);D(this,"coordinationScope","user");D(this,"bindGeneralPlacement",!0);D(this,"ensureAdminPlacementsBeforeAppInit");var d,f,A;if(!e){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:t,bx:r,users:i,continueBackground:a,timing:l,coordinationScope:h,bindGeneralPlacement:u,ensureAdminPlacementsBeforeAppInit:n}=e;this.bx=r,this.appInit=t,this.users=i,this.coordinationScope=ve(h),this.bindGeneralPlacement=u!==!1,this.ensureAdminPlacementsBeforeAppInit=n,y(this,zt,we).call(this,l),re(r),this.appPath=y(this,bt,fe).call(this,((d=r==null?void 0:r.appConst)==null?void 0:d.pathApp)??""),this.appName=((f=r==null?void 0:r.appConst)==null?void 0:f.appName)??"",this.appCodeName=((A=r==null?void 0:r.appConst)==null?void 0:A.appCodeName)??"",this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("BackgroundWorker: appInit не передан");return}if(!this.bx){console.error("BackgroundWorker: bx не передан");return}if(this.isAppPage()){console.log("BackgroundWorker: Страница приложения, фоновый воркер не запускается");return}await this.checkPlacementType()&&await this.continueBackground()&&(await this.checkEntity(),await this.refreshTabs(!0),await this.ensureTabRegistered(),this.startDelay>0&&(console.log(`BackgroundWorker: старт отложен на ${this.startDelay} мс`),await this.pause(this.startDelay)),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(t=>{console.error("BackgroundWorker: backgroundTick failed",t)})},this.pollInterval),await this.backgroundTick())}async backgroundTick(){if(!await this.continueBackground()){this.stopTimers(),console.log("BackgroundWorker: Остановка backgroundTick - условие не выполнено");return}await this.refreshTabs(!0),await this.ensureTabRegistered();const t=this.selectLeaderId(),r=t&&+this.id==+t;await this.updateTabState(r),r&&!this.hasStarted&&await this.runAsLeader()}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var e;if(typeof BX24>"u"||!((e=BX24.placement)!=null&&e.info))return!1;try{const t=BX24.placement.info(),r=t==null?void 0:t.placement,i=(t==null?void 0:t.options)||{},a=(i==null?void 0:i.URI)||"",l=r==="PAGE_BACKGROUND_WORKER"||(i==null?void 0:i.ID)==="PAGE_BACKGROUND_WORKER",h=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!l||h}catch{return!1}}async checkEntity(){var r;const e=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((r=e==null?void 0:e.find)==null?void 0:r.call(e,i=>i.ENTITY===this.entityName))||await this.safeCall(()=>this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}}))}async getTabs(){const e=y(this,At,St).call(this),t=await this.safeCall(()=>this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:e},SORT:{DATE_CREATE:"DESC"}}}));return!Array.isArray(t)||!t.length?[]:t.map(r=>{if(!r)return{id:void 0,data:void 0};try{const i=JSON.parse(r.DETAIL_TEXT);return{id:+r.ID||0,data:i}}catch(i){return console.log("BackgroundWorker: parse tab error",i),{id:+r.ID||0,data:void 0}}})}async ensureTabRegistered(){var r,i;if(this.id)return+this.id||0;if(this.tabList.length>=this.maxTabs&&await this.refreshTabs(!0,this.quickCleanupThreshold),this.tabList.length>=this.maxTabs)return console.log("BackgroundWorker: Достигнут лимит вкладок даже после быстрой очистки, не регистрируемся"),0;const e={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId,userId:(i=(r=this.bx)==null?void 0:r.userInfo)==null?void 0:i.ID},t=await this.safeCall(()=>this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:y(this,At,St).call(this),DETAIL_TEXT:JSON.stringify(e)}}))||0;return this.id=+t||0,this.id}async updateTabState(e){var r,i;if(!this.id)return;const t={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:e,sessionId:this.sessionId,userId:(i=(r=this.bx)==null?void 0:r.userInfo)==null?void 0:i.ID};await this.safeCall(()=>this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:y(this,At,St).call(this),DETAIL_TEXT:JSON.stringify(t)}}))}async deleteTabs(e=[]){if(!e.length)return;const t=e.map(r=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:r.id}}));await this.safeCall(()=>this.bx.batch(t))}async checkPlacementType(){var e,t;try{if(!((e=this.bx)!=null&&e.isAdmin))return!0;const r=await this.safeCall(()=>this.bx.getPlacement());if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((t=this.bx.userInfo)==null?void 0:t.ID)??0),a=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),l=!a;if(!i)return!0;let h=!1;for(const u of r){if(u.placement!=="PAGE_BACKGROUND_WORKER"||!(u.userId||u.handler&&u.handler.includes("USER_ID=")))continue;const d=u.userId||(u.handler?this.extractUserIdFromHandler(u.handler):null);if(d&&+d===i){h=!0;break}}return a?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):l&&h?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}isIndividualPlacement(e){return!e||typeof e!="string"?!1:e.includes("USER_ID=")}extractUserIdFromHandler(e){if(!e||typeof e!="string")return null;const t=e.match(/USER_ID=(\d+)/);return t?+t[1]:null}async continueBackground(){try{const t=!!await Promise.resolve(this.continueCondition(this));return console.log(t?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),t}catch(e){return console.error("BackgroundWorker: Ошибка в continueCondition",e),!1}}async refreshTabs(e=!1,t=this.activeMaxPause){const r=[],i=[],a=Date.now(),l=await this.getTabs();for(const h of l){if(!(h!=null&&h.data)){r.push(h);continue}if(a-new Date(h.data.lastActive||0).getTime()>t){r.push(h);continue}i.push(h)}return e&&r.length&&await this.deleteTabs(r),this.tabList=i,i}selectLeaderId(){var t;return this.tabList.length&&+((t=[...this.tabList].sort((r,i)=>{var h,u,n,d;const a=new Date(((h=r.data)==null?void 0:h.createdAt)||((u=r.data)==null?void 0:u.lastActive)||0).getTime(),l=new Date(((n=i.data)==null?void 0:n.createdAt)||((d=i.data)==null?void 0:d.lastActive)||0).getTime();return a===l?(+r.id||0)-(+i.id||0):a-l})[0])==null?void 0:t.id)||0}async confirmLeaderAfterLock(){await this.refreshTabs(!0);const e=this.selectLeaderId();return!!(e&&+this.id==+e)}async runAsLeader(){const e=y(this,Qt,He).call(this);(await Fe(e,async()=>{if(await this.updateTabState(!0),console.log(`BackgroundWorker: захват лидерства, пауза ${this.leaderConfirmDelay} мс перед запуском`),await this.pause(this.leaderConfirmDelay),!await this.confirmLeaderAfterLock()){console.log("BackgroundWorker: запуск отменён — после паузы лидером оказалась другая вкладка"),await this.updateTabState(!1);return}this.hasStarted=!0;const i=this.leaderHeartbeatMs??Math.min(this.activeMaxPause-1500,Math.max(2500,Math.floor(this.pollInterval/2)));this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(a=>console.error("BackgroundWorker: heartbeat update failed",a))},i);try{await this._ensurePlacementsBeforeAppInitIfNeeded(),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 _ensurePlacementsBeforeAppInitIfNeeded(){var r;const e=this.ensureAdminPlacementsBeforeAppInit;if(!(!e||!((r=this.bx)!=null&&r.isAdmin)||!(typeof e=="function"?await Promise.resolve(e(this)):e)))try{await this.ensureAdminPlacements()}catch(i){console.error("BackgroundWorker: ensureAdminPlacements before appInit failed",i)}}async setBackgroundWorkerAll(){var O,R,k,T;if(!((O=this.bx)!=null&&O.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(R=this.users)!=null&&R.length||await this.getEntityData(),re(this.bx);const e=y(this,bt,fe).call(this,((T=(k=this.bx)==null?void 0:k.appConst)==null?void 0:T.pathApp)??"");if(!e){console.error("BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена");return}const t=await this.safeCall(()=>this.bx.getPlacement()),r=new Map,i=new Map;let a=null;(t||[]).forEach(g=>{if(g.placement!=="PAGE_BACKGROUND_WORKER")return;if(g.userId||g.handler&&g.handler.includes("USER_ID=")){const b=g.userId||(g.handler?this.extractUserIdFromHandler(g.handler):null);if(b){const P=+b;r.set(P,g),i.has(P)||i.set(P,[]),i.get(P).push(g)}}else a=g});const l=await this.resolveAdmins(),h=await this.getEligibleUsersForBackgroundWorker(l);h.sort((g,B)=>{const b=g.LAST_LOGIN?new Date(g.LAST_LOGIN):new Date(0);return(B.LAST_LOGIN?new Date(B.LAST_LOGIN):new Date(0))-b});const u=10,n=h.slice(0,u),d=n.filter(g=>{const B=r.get(+g.ID);if(!B)return!0;const b=`${e}?USER_ID=${g.ID}/`;return B.handler!==b}),f=[];for(const[g]of r){const B=+g||0;h.find(P=>+P.ID===B)||f.push(B)}for(const g of n){const B=r.get(+g.ID);if(!B)continue;const b=`${e}?USER_ID=${g.ID}/`;B.handler!==b&&f.push(+g.ID)}const A=[],c=[...new Set(f)];for(const g of c){const B=i.get(+g)||[];for(const b of B)b!=null&&b.handler&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:b.handler}})}const N=a&&(!this.bindGeneralPlacement||d.length>0||a.handler!==`${e}`);N&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:a.handler||`${e}`}});for(const g of d)A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}?USER_ID=${g.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}?USER_ID=${g.ID}/`},USER_ID:g.ID}});this.bindGeneralPlacement&&(!a||N)&&A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}`}}}),A.length?await this.safeCall(()=>this.bx.batch(Object.fromEntries(A.map((g,B)=>[`placement_${B}`,g])))):console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var e,t;try{const r=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),i=!!((t=this.bx)!=null&&t.isAdmin),a=await this.getAdminsList()||[];if(!i){if(r&&a.includes(+r)){const u=a.filter(n=>+n!=+r);return await this.saveAdminsList(u),u}return a}const l=new Set([...a||[]]);r&&l.add(+r);const h=[...l].filter(Boolean);return await this.saveAdminsList(h),h}catch(r){return console.error("BackgroundWorker: resolveAdmins error",r),[]}}async getEligibleUsersForBackgroundWorker(e=[]){const t=(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0),r=e.map(i=>+i||0).filter(Boolean);return t.filter(i=>r.includes(+i.ID||0))}async saveAdminsList(e=[]){try{BX24.appOption.set("adminsList",JSON.stringify(e))}catch(t){console.error("BackgroundWorker: saveAdminsList error",t)}}async getAdminsList(){try{const e=BX24.appOption.get("adminsList"),t=e?JSON.parse(e):[];return Array.isArray(t)?t.map(r=>+r||0).filter(Boolean):[]}catch(e){return console.error("BackgroundWorker: getAdminsList error",e),[]}}async getEntityData(){const e={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:t}=await this.safeCall(()=>this.bx.batch(e).then(r=>r?(Array.isArray(r.users)||(r.users=[]),r):{users:[]}));this.users=t}async ensureAdminPlacements(){var e,t;(e=this.bx)!=null&&e.isAdmin&&((t=this.users)!=null&&t.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(e=500,t){return new Promise(r=>{setTimeout(()=>{t&&t(),r(!0)},e)})}async safeCall(e){try{return await e()}catch(t){console.error("BackgroundWorker: safeCall error",t);return}}}zt=new WeakSet,we=function(e){const t=ye(e);this.startDelay=t.startDelayMs,this.leaderConfirmDelay=t.leaderConfirmDelayMs,this.activeMaxPause=t.activeMaxPauseMs,this.quickCleanupThreshold=t.quickCleanupThresholdMs,this.pollIntervalBase=t.pollIntervalMs,this.pollIntervalJitter=t.pollIntervalJitterMs,this.pollInterval=t.pollIntervalMs+(t.pollIntervalJitterMs>0?Math.floor(Math.random()*t.pollIntervalJitterMs):0),this.leaderHeartbeatMs=t.leaderHeartbeatMs;const r=t.pollIntervalMs+t.pollIntervalJitterMs+t.leaderConfirmDelayMs;t.activeMaxPauseMs<r&&console.warn(`BackgroundWorker: activeMaxPauseMs (${t.activeMaxPauseMs}) меньше poll+jitter+leaderConfirm (${r}) — «живые» вкладки могут удаляться раньше следующего тика`)},bt=new WeakSet,fe=function(e){if(!e||typeof e!="string")return"";const t=se(e).replace(/\/+$/,"");return t?me(t)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):t:""},At=new WeakSet,St=function(){var e,t;return this.coordinationScope==="portal"?`${this.appCodeName||"app"}:portal`:String(((t=(e=this.bx)==null?void 0:e.userInfo)==null?void 0:t.ID)??"")},Qt=new WeakSet,He=function(){return`background-worker:${this.entityName}:${y(this,At,St).call(this)}`},I.BackgroundWorker=Xe,I.Batch=q,I.BxBoot=Ge,I.BxHelper=te,I.BxLogger=de,I.DEFAULT_BACKGROUND_WORKER_TIMING=z,I.resolveBackgroundWorkerTiming=ye,I.tempus=pt,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"})});
@@ -56,6 +56,13 @@ type BackgroundWorkerOptions = {
56
56
  * @default true
57
57
  */
58
58
  bindGeneralPlacement?: boolean;
59
+ /**
60
+ * Перед `appFunc` вызвать `ensureAdminPlacements` у админа.
61
+ * `true` — всегда; функция — по её результату (например, только перед регулярной задачей).
62
+ */
63
+ ensureAdminPlacementsBeforeAppInit?:
64
+ | boolean
65
+ | ((worker: BackgroundWorker) => boolean | Promise<boolean>);
59
66
  };
60
67
 
61
68
  declare class BackgroundWorker {
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "szdl-utils-kit",
3
3
  "description": "utils-kit library",
4
4
  "private": false,
5
- "version": "0.3.29",
5
+ "version": "0.3.31",
6
6
  "type": "module",
7
7
  "author": "Stanislav Ovv",
8
8
  "license": "BSD",