szdl-utils-kit 0.3.4 → 0.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Readme.md +6 -3
- package/dist/index.js +750 -671
- package/dist/index.umd.cjs +2 -2
- package/package.json +1 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):i(JSON.parse(c.responseText))):l&&l(c))},c.open("GET",t,!1),c.send()},k={"%d":{format:function(t){return A(t.day()||r.MIN_DAY,2)},parse:function(t){var i=Number(t);return{day:isNaN(i)?s:i}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(t){return A(t.month()||r.MIN_MONTH,2)},parse:function(t){var i=Number(t);return{month:isNaN(i)?s:i}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(t){return A(t.year()||r.MIN_YEAR,4)},parse:function(t){var i=Number(t);return{year:isNaN(i)?s:i}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(t){return t.dayOfWeek()||r.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(t){var i=t.dayOfWeek();return B[i!==s?i:r.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var i=t.dayOfWeek();return j[i!==s?i:r.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(t){var i=r.options("monthFromZero")?t.month():t.month()-1;return W[i!==s?i:r.MIN_MONTH]},parse:function(t){var i=r.monthNames().indexOf(t)+(r.options("monthFromZero")?0:1);return{month:i!==-1?i:s}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var i=r.options("monthFromZero")?t.month():t.month()-1;return J[i!==s?i:r.MIN_MONTH]},parse:function(t){var i=r.monthNames(!0).indexOf(t)+(r.options("monthFromZero")?0:1);return{month:i!==-1?i:s}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(t){return A(t.hours()||r.MIN_HOURS,2)},parse:function(t){var i=Number(t);return{hours:isNaN(i)?s:i}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(t){return A(t.minutes()||r.MIN_MINUTES,2)},parse:function(t){var i=Number(t);return{minutes:isNaN(i)?s:i}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(t){return A(t.seconds()||r.MIN_SECONDS,2)},parse:function(t){var i=Number(t);return{seconds:isNaN(i)?s:i}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(t){return t.timestamp()},parse:function(t){return isNaN(Number(t))?{}:r(Number(t)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(t){return A(t.year()||r.MIN_YEAR,4)+"-"+A(t.month()||r.MIN_MONTH,2)+"-"+A(t.day()||r.MIN_DAY,2)},parse:function(t){var i=Number(t.slice(0,4)),l=Number(t.slice(5,7)),c=Number(t.slice(8,10));return{year:i,month:l,day:c}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return A(t.month()||r.MIN_MONTH,2)+"/"+A(t.day()||r.MIN_DAY,2)+"/"+A(t.year()||r.MIN_YEAR,4)},parse:function(t){var i=Number(t.slice(0,2)),l=Number(t.slice(3,5)),c=Number(t.slice(6,10));return{year:c,month:i,day:l}},minLength:10,maxLength:10,type:"string"}},ct={useMilliseconds:!1,monthFromZero:!1},p;p=function(t,i,l){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t!==s&&this.set(t,i,l),this},p.fn=p.prototype,p.fn.dayCount=function(){var t=this.month(),i=r.MAX_DAY_IN_MONTHS[t-(r.options("monthFromZero")?0:1)];return this.leapYear()&&t===(r.options("monthFromZero")?1:2)&&(i+=1),i},p.fn.year=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=r.MIN_YEAR&&Number(t)<=r.MAX_YEAR?(this._d.setFullYear(Number(t)),this._i.year=!1):this._i.year=Number(t):(this._d.setFullYear(r.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},p.fn.month=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=r.MIN_MONTH&&Number(t)<=r.MAX_MONTH?(this._d.setMonth(r.options("monthFromZero")?Number(t):Number(t)-1),this._i.month=!1):this._i.month=Number(t):(this._d.setMonth(r.options("monthFromZero")?r.MIN_MONTH:r.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?r.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},p.fn.day=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=r.MIN_DAY&&Number(t)<=this.dayCount()?(this._d.setDate(Number(t)),this._i.day=!1):this._i.day=Number(t):(this._d.setDate(r.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},p.fn.hours=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=r.MIN_HOURS&&Number(t)<=r.MAX_HOURS?(this._d.setHours(Number(t)),this._i.hours=!1):this._i.hours=Number(t):(this._d.setHours(r.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},p.fn.minutes=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=r.MIN_MINUTES&&Number(t)<=r.MAX_MINUTES?(this._d.setMinutes(Number(t)),this._i.minutes=!1):this._i.minutes=Number(t):(this._d.setMinutes(r.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},p.fn.seconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=r.MIN_SECONDS&&Number(t)<=r.MAX_SECONDS?(this._d.setSeconds(Number(t)),this._i.seconds=!1):this._i.seconds=Number(t):(this._d.setSeconds(r.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},p.fn.milliseconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=r.MIN_MILLISECONDS&&Number(t)<=r.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(t)),this._i.milliseconds=!1):this._i.milliseconds=Number(t):(this._d.setMilliseconds(r.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},p.fn.week=function(){var t=new Date(this.year(),0,1),i=r(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((i-t.getTime())/864e5+t.getDay()+1)/7)},p.fn.set=function(t,i,l){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t===s)return this._d=new Date,this;if(t instanceof Date)return this._d=t,this;if(typeof t=="number")return this._d=new Date(t*(r.options("useMilliseconds")?1:1e3)),this;if(typeof t=="object"&&(t instanceof Array?(this.day(r.MIN_DAY),this.year(t[0]),this.month(t[1]),this.day(t[2]),this.hours(t[3]),this.minutes(t[4]),this.seconds(t[5]),this.milliseconds(t[6])):(this.day(r.MIN_DAY),this.year(t.year),this.month(t.month),this.day(t.day),this.hours(t.hours),this.minutes(t.minutes),this.seconds(t.seconds),this.milliseconds(t.milliseconds))),typeof t=="string"){var c,L=[],N,T,V=[],w=0,U=0,b,F,M={},H;if(t===s)return N=a(this,l),N===s&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),N;for(i===s&&(i=r.detectFormat(t));w<i.length;){if(i.charAt(w)==="%"){if(T=i.charAt(w)+i.charAt(w+1),k[T]!==s){switch(b=0,F="",k[T].type){case"number":for(;b<k[T].maxLength&&U+b<t.length&&!isNaN(Number(t.charAt(U+b)));)F+=t.charAt(U+b),b+=1;break;case"word":for(;b<k[T].maxLength&&U+b<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(U+b));)F+=t.charAt(U+b),b+=1;break;case"string":for(;b<k[T].maxLength&&U+b<t.length;)F+=t.charAt(U+b),b+=1;break}if(b<k[T].minLength)return N=a(this,l),N===s&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),N;L.push(T),V.push(F),b-=1,U+=b,w+=1}}else if(t.charAt(U)!==i.charAt(w))return N=a(this,l),N===s&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),N;w+=1,U+=1}for(c in L)L.hasOwnProperty(c)&&k.hasOwnProperty(L[c])&&(H=k[L[c]].parse(V[c]),M={year:H.year!==s?H.year:M.year,month:H.month!==s?H.month:M.month,day:H.day!==s?H.day:M.day,hours:H.hours!==s?H.hours:M.hours,minutes:H.minutes!==s?H.minutes:M.minutes,seconds:H.seconds!==s?H.seconds:M.seconds});this.day(r.MIN_DAY),this.year(M.year),this.month(M.month),this.day(M.day),this.hours(M.hours),this.minutes(M.minutes),this.seconds(M.seconds),this.milliseconds(M.milliseconds)}return this},p.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},p.fn.timestamp=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(r.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):r.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},p.fn.utc=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(r.options("useMilliseconds")?1:1e3)),this):r.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},p.fn.dayOfWeek=function(t){if(t==="long")return j[this._d.getDay()];if(t==="short")return B[this._d.getDay()];if(t===s)return this._d.getDay();if(t===0||t==="Sunday")return this.calc({day:-this.dayOfWeek()});if(t===1||t==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(t===2||t==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(t===3||t==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(t===4||t==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(t===5||t==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(t===6||t==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},p.fn.timezone=function(t){switch(t){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},p.fn.get=function(t){switch(t){case"Date":return new Date(this.year(),this.month()-(r.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()-(r.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()}}},p.fn.format=function(t){for(var i=0,l="",c;i<t.length;)t.charAt(i)==="%"?(c=t.charAt(i)+t.charAt(i+1),k[c]!==s?(l+=k[c].format(this),i+=1):l+="%"):l+=t.charAt(i),i+=1;return l},p.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},p.fn.errors=function(){return this._i},p.fn.between=function(t,i){var l=this.timestamp(),c=t.timestamp();switch(i){case"year":return Math.floor((c-l)/31556952);case"month":return Math.floor((c-l)/2629746);case"day":return Math.floor((c-l)/86400);case"hours":return Math.floor((c-l)/3600);case"minutes":return Math.floor((c-l)/60);case"seconds":return c-l;default:return s}},p.fn.calc=function(t){return t.year!==s&&this._d.setFullYear(this._d.getFullYear()+t.year),t.month!==s&&this._d.setMonth(this._d.getMonth()+t.month),t.day!==s&&this._d.setDate(this._d.getDate()+t.day),t.hours!==s&&this._d.setHours(this._d.getHours()+t.hours),t.minutes!==s&&this._d.setMinutes(this._d.getMinutes()+t.minutes),t.seconds!==s&&this._d.setSeconds(this._d.getSeconds()+t.seconds),t.milliseconds!==s&&this._d.setMilliseconds(this._d.getMilliseconds()+t.milliseconds),this},r=function(t,i,l){return new p(t,i,l)},r.MIN_YEAR=1e3,r.MAX_YEAR=3e3,r.MIN_MONTH=1,r.MAX_MONTH=12,r.MIN_DAY=1,r.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],r.MIN_DAY_OF_WEEK=0,r.MAX_DAY_OF_WEEK=6,r.MIN_HOURS=0,r.MAX_HOURS=23,r.MIN_MINUTES=0,r.MAX_MINUTES=59,r.MIN_SECONDS=0,r.MAX_SECONDS=59,r.MIN_MILLISECONDS=0,r.MAX_MILLISECONDS=999,r.VERSION="0.2.18",r.options=function(t,i){if(t===s)return ct;if(ct.hasOwnProperty(t)){if(i===s)return ct[t];ct[t]=i,t==="monthFromZero"&&(r.MIN_MONTH=i?0:1,r.MAX_MONTH=i?11:12)}return s},r.noConflict=function(){return n.tempus=f,r},r.generate=function(t){var i,l,c,L,N,T,V,w;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof p?i=t.dateFrom.utc():i=r(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof p?l=t.dateTo.utc():l=r(t.dateTo,t.formatTo!==s?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?N={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?N={year:t.period==="year"?1:0,month:t.period==="month"?1:0,day:t.period==="day"?1:0,hours:t.period==="hours"?1:0,minutes:t.period==="minutes"?1:0,seconds:t.period==="seconds"?1:0}:typeof t.period=="object"&&(N={year:t.period.year!==s?t.period.year:0,month:t.period.month!==s?t.period.month:0,day:t.period.day!==s?t.period.day:0,hours:t.period.hours!==s?t.period.hours:0,minutes:t.period.minutes!==s?t.period.minutes:0,seconds:t.period.seconds!==s?t.period.seconds:0}),t.groupBy===s?T=t.asObject===!0?{}:[]:(T=[],T.push([]),V=r(i).get()[t.groupBy]),w=function(F,M,H){return t.asObject===!0?t.format!==s?F[r(M).format(t.format)]={}:F[r(M).format("%F %H:%M:%S")]={}:t.format!==s?F.push(H?null:r(M).format(t.format)):F.push(H?null:r(M)),F},t.groupBy!==s&&t.fillNulls){var U={year:N.year?-N.year:s,month:N.month?-N.month:s,day:N.day?-N.day:s,hours:N.hours?-N.hours:s,minutes:N.minutes?-N.minutes:s,seconds:N.seconds?-N.seconds:s,milliseconds:N.milliseconds?-N.milliseconds:s};for(c=r(i).calc(U).utc();r(c).get()[t.groupBy]===V;)w(T[T.length-1],c,!0),c=r(c).calc(U).utc();if(t.groupBy==="week"){var b=r(i).dayOfWeek();for(c=r(i).dayOfWeek(0).utc();T[0].length<b&&c<i;)w(T[T.length-1],c,!0),c=r(c).calc(N).utc()}}for(;i<=l;)t.groupBy===s?w(T,i):r(i).get()[t.groupBy]===V?w(T[T.length-1],i):(T.push([]),w(T[T.length-1],i),V=r(i).get()[t.groupBy]),i=r(i).calc(N).utc();if(t.groupBy!==s&&t.fillNulls)for(L=r(l).calc(N).utc();r(L).get()[t.groupBy]===V;)w(T[T.length-1],L,!0),L=r(L).calc(N).utc();return T},r.monthNames=function(t){switch(t){case"long":return J;default:return W}},r.dayNames=function(t){switch(t){case"long":return j;default:return B}},r.lang=function(t){if(t!==s)o=t,u[o]===s&&(o="en"),J=R(),W=E(),j=I(),B=P();else return o;return s},r.availableLangs=function(){return Object.keys(u)},r.registerFormat=function(t,i,l,c,L,N){k[t]={format:i,parse:l,minLength:c,maxLength:L,type:N}},r.unregisterFormat=function(t){delete k[t]},r.detectFormat=function(t){var i,l,c;return i=m(t,0),i!==""&&(c=10),l=t.charAt(c),(l==="T"||l===" ")&&(i+=l,c+=1),i+=h(t,c),i},d={TempusDate:p},r.classes=function(t,i){if(i===s)return d[t];d[t]=i},r.loadTranslations=function(t){typeof t=="object"?u=t:typeof t=="string"&&it(t,function(i){u=i},function(i){})},o=(_.language||_.systemLanguage||_.userLanguage||"en").substr(0,2).toLowerCase(),u[o]===s&&(o="en"),J=R(),W=E(),j=I(),B=P(),G.exports&&(e=G.exports=r),e.tempus=r}).call(y)})($,$.exports);var Tt=$.exports;const st=S(Tt);class Q{constructor(e){this.callBatch=e,this.result={},this.errors={},this.limit=50,this.canContinue=!0,this.progressCall="",this.limitCall="",this.progressData="",this.progressTimer="",this.progressDelay=100,this.oldPercent="no",this.chunkRate=1,this.totalProgress=0,this.skipList=new Set}getData(e){return(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}get progressPercent(){let e=0;if(!this.progressData)return{percent:Math.round(e),allCount:0,allTotal:0};let s=0,n=0;return Object.values(this.progressData).forEach(A=>{const{total:a,count:h}=A;s+=a??0,n+=h??0}),s?e=n/s*100*this.chunkRate+this.totalProgress:n===0&&s===0?e=100*this.chunkRate+this.totalProgress:e=100,{percent:Math.round(e),allCount:n,allTotal:s}}setProgressData({key:e,value:s,type:n}){const A=this.getData(s.data()),a=Array.isArray(A)?A.length:0;let h=s.total()||a;n==="count"&&(h=a);let m=1;A&&(m=a),this.progressCall&&(this.progressData||(this.progressData={}),this.progressData[e]&&this.progressData[e].count&&(m+=this.progressData[e].count),this.progressData[e]?this.progressData[e].count=m:this.progressData[e]={total:h,count:m},this.progressTimer||(this.progressTimer=setInterval(()=>{const{percent:f,allCount:r,allTotal:d}=this.progressPercent;(this.oldPercent==="no"||this.oldPercent<this.progressPercent.percent)&&(this.progressCall({data:this.progressData,percent:f,allCount:r,allTotal:d}),this.oldPercent=this.progressPercent.percent),f>=100&&this.clearProgressData()},this.progressDelay)))}delay(){return new Promise(e=>setTimeout(e,500))}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.limitCall="",this.oldPercent="no"}async batch(e,s,n){this.progressTimer&&this.clearProgressData(),s&&(this.progressCall=s),n&&(this.limitCall=n),this.canContinue=!0,this.result={},this.errors={};const A={};this.chunkRate=(1/Math.ceil(Object.keys(e).length/this.limit)).toFixed(5);let a={},h=0;for(const[m,f]of Object.entries(e)){if(!this.canContinue)break;const r=this.arrayChunk(f);if(!r){h++;continue}a[m]=r,(Object.keys(a).length>=50||h+1===Object.keys(e).length)&&(await this.batchChunk(a),Object.entries(this.result).forEach(([d,_])=>{A[d]=_}),this.totalProgress=Math.round(h/Object.keys(e).length*100),a={}),h++}return Object.entries(this.errors).length&&(A.errorsList=this.errors),s&&s({percent:100}),Promise.resolve(A)}async batchTotalCount(e,s,n){this.progressTimer&&this.clearProgressData(),s&&(this.progressCall=s),n&&(this.limitCall=n),this.canContinue=!0,this.result={},this.errors={};const A={};this.chunkRate=(1/Math.ceil(Object.keys(e).length/this.limit)).toFixed(5);let a={},h=0;for(const[m,f]of Object.entries(e)){if(!this.canContinue)break;const r=this.arrayChunk(f);if(!r){h++;continue}a[m]=r,(Object.keys(a).length>=50||h+1===Object.keys(e).length)&&(await this.batchChunk(a,"count"),Object.entries(this.result).forEach(([d,_])=>{A[d]=_}),this.totalProgress=Math.round(h/Object.keys(e).length*100),a={}),h++}return Object.entries(this.errors).length&&(A.errorsList=this.errors),s&&s({percent:100}),Promise.resolve(A)}arrayChunk(e){let s="",n={};if(Array.isArray(e)?[s]=e:(s=e.method,n=e.params),this.skipList.has(s))return!1;if((s.includes("list")||s==="user.get")&&s!=="task.item.list"){if(!n)n={order:{ID:"ASC",id:"ASC"}};else{s==="tasks.task.list"?(n.order||(n.order={}),n.order.ID="asc"):s==="user.get"?(n.sort||(n.sort="ID"),n.order||(n.order="ASC")):n.order={ID:"ASC",id:"ASC"},Array.isArray(n.select)&&!n.select.includes("ID")&&n.select.push("ID");const A=s==="user.get"?n.FILTER:n.filter;typeof A=="object"&&A!==null&&!Array.isArray(A)&&Object.entries(A).forEach(([a,h])=>{(n.start===void 0||n.start!==-1)&&["id","ID"].includes(a)&&(typeof h=="string"||Array.isArray(h)&&h.length<=50)&&(n.start=-1)})}s==="crm.type.list"&&n.order&&delete n.order.ID}if(s==="task.item.list")if(!n)n=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(n[0])&&(n[0]={});const[A,a,h,m]=n;A.ID="ASC",m[0]!==""&&m.includes("ID")||m.push("ID")}return{method:s,params:n}}async batchChunk(e,s){return new Promise(n=>{const A=[];let a;this.callBatch(e,async h=>{var m,f,r,d,_,o,u;for(const[R,E]of Object.entries(h)){if(!this.canContinue)return;if(E.error())switch(this.errors[R]=((f=(m=E.error())==null?void 0:m.ex)==null?void 0:f.error)??((d=(r=E.error())==null?void 0:r.ex)==null?void 0:d.error_description)??((_=E.error())==null?void 0:_.toString())??"Неизвестная ошибка",a=!0,((u=(o=E.error())==null?void 0:o.ex)==null?void 0:u.error)??""){case"OPERATION_TIME_LIMIT":this.skipList.add(e[R].method),this.limitCall&&this.limitCall(R);break;case"QUERY_LIMIT_EXCEEDED":this.canContinue=!1;break;case"ACCESS_DENIED":this.skipList.add(e[R].method);break}const I=this.getData(E.data()),P=Array.isArray(I)?I.length:0,J=typeof E.total=="function"&&E.total()!==void 0,W=J?E.total():P;s==="count"?this.result[R]?this.result[R]+=P:this.result[R]=W:this.result[R]=I,this.setProgressData({key:R,value:E,type:s});const j=s==="count"?!J&&P===this.limit:W>this.limit&&W>P;if(!this.canContinue||j){let B=e[R];if(Array.isArray(B)){const[it,k={}]=B;B=[it,k]}else{const{method:it,params:k={}}=B;B=[it,k]}A.push([R,B,W])}}a>0&&this.errorLogger(),A.length?await this.batchPayload(A,s).then(()=>n(this.result)):n(this.result)})})}async batchPayload(e,s){const n=new Map,A=(f,r,d,_)=>{let o="ID";this.result[f][this.result[f].length-1].ID||(o="id");let u=`${o}`;if(JSON.stringify(_[1]).toLocaleLowerCase().includes('"id":"desc"')?u="<"+u:u=">"+u,r===1||d.length===0)return{field:u,id:this.result[f][this.result[f].length-1][o]};let E="";const[I,P]=_;return(I==="tasks.task.list"||I==="task.item.list")&&(E="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(I)&&(E="[items]"),I==="crm.type.list"&&(E="[types]"),I==="socialnetwork.api.workgroup.list"&&(E="[workgroups]"),{field:u,id:`$result[${[f,r-1].join("__")}]${E}[49][${o}]`}},a=(f,r)=>{const[d,_]=f;let o=JSON.parse(JSON.stringify(_)),u;if(d==="task.item.list"){o=[...o];const[R,E,I,P]=o;return E[r.field]=r.id,[d,o]}return["user.get"].includes(d)||o.FILTER?(o.FILTER||(o.FILTER={}),u=o.FILTER):(o.filter||(o.filter={}),u=o.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(d)?u[">ID"]=r.id:u[r.field]=r.id,[d,{...o,start:-1}]},h=f=>{Object.entries(f).forEach(([r,d])=>{var u,R,E,I,P,J,W;const[_]=r.split("__"),o=this.getData(d.data());if(Array.isArray(o)&&(s==="count"?this.result[_]+=o.length:this.result[_].push(...o)),d.error()){this.errors[_]=((R=(u=d.error())==null?void 0:u.ex)==null?void 0:R.error)??((I=(E=d.error())==null?void 0:E.ex)==null?void 0:I.error_description)??((P=d.error())==null?void 0:P.toString())??"Неизвестная ошибка";const j=((W=(J=d.error())==null?void 0:J.ex)==null?void 0:W.error)??"";if(j==="OPERATION_TIME_LIMIT"){this.limitCall&&this.limitCall(_);const B=n.get(_);switch(j){case"OPERATION_TIME_LIMIT":B&&(this.skipList.add(B),this.limitCall&&this.limitCall(_));break;case"QUERY_LIMIT_EXCEEDED":this.canContinue=!1;break;case"ACCESS_DENIED":this.skipList.add(B);break}}}this.setProgressData({key:_,value:d,type:s})})};let m=[];for await(const[f,r,d]of e){if(!this.canContinue)return;const[_]=r;if(n.set(f,_),this.skipList.has(_))continue;let o=1;for(;d>o*50&&!this.skipList.has(_);){const u=[f,o].join("__"),R=A(f,o,m,r);m.push([u,a(r,R)]),m.length%50===0&&(await new Promise(E=>this.callBatch(Object.fromEntries(m),I=>{h(I),E()})),m=[],await this.delay()),o++}}m.length&&(await new Promise(f=>this.callBatch(Object.fromEntries(m),r=>{h(r),f()})),await this.delay())}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([e,s])=>{s&&console.log(`[${e}]`,s.toString())}),console.groupEnd()}}class ut{constructor(){Y(this,z,{})}get hash(){return this.createHash(8)}createHash(e){let s="abcdefghijklmnopqrstuvwxyz0123456789",n="";e=e||6;for(let A=0;A<e;A++)n+=s.charAt(Math.floor(Math.random()*s.length));return n}actionFilter({keyTimer:e,duration:s=10,action:n}){O(this,z)[e]&&(clearTimeout(O(this,z)[e]),O(this,z)[e]=null),n&&(O(this,z)[e]=setTimeout(()=>{n()},s))}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(s=>{console.warn("noSleep: autoplay prevented",s)})}),e.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{e.play().catch(s=>{console.warn("noSleep: replay prevented",s)})}})}),e.src="data:video/mp4;base64,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"}downloadFileJson(e,s){let n=new Blob([JSON.stringify(e)],{type:"application/json"}),A=URL.createObjectURL(n),a=document.createElement("a");a.style.display="none",a.href=A,a.download=`${s}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(A)},200)}}z=new WeakMap;const ft=new ut;class gt{constructor(){Y(this,nt);Y(this,rt);Y(this,At);Y(this,at);Y(this,ot);Y(this,X,"logger");Y(this,Z,!1);Y(this,K,new Map);Y(this,tt,{});Y(this,C,null);Y(this,q,!1);Y(this,et,!1);D(this,"periodClear",3);v(this,nt,Nt).call(this)}async init(){try{let e=new Q(BX24.callBatch),{entityList:s}=await e.batch({entityList:{method:"entity.get"}});if(s&&Array.isArray(s))if(s.find(A=>A.ENTITY==O(this,X)))x(this,Z,!0);else{let{entityAdd:A}=await e.batch({entityAdd:{method:"entity.add",params:{ENTITY:O(this,X),NAME:O(this,X),ACCESS:{AU:"X"}}}});A&&x(this,Z,!0)}return v(this,at,_t).call(this).catch(n=>{console.error("Ошибка при проверке периода очистки:",n)}),O(this,Z)}catch(e){return console.error("Ошибка при инициализации логера:",e),!1}}start({type:e,data:s}){if(!O(this,Z))return v(this,rt,dt).call(this,"entity"),null;if(!e||!s)return console.error("Невалидные данные для логирования:",{type:e,data:s}),null;const n=ft.hash,A={type:e,data:s,userInfo:O(this,tt),errorList:{},status:"",answer:null,date:new Date().getTime()};return O(this,K).set(n,A),x(this,et,!0),n}async stop({key:e,errorList:s,status:n,answer:A}){var h;if(!O(this,et))return;if(!O(this,Z)){v(this,rt,dt).call(this,"entity");return}let a=O(this,K).get(e);if(!a){console.error(`Не найдены данные логирования для ключа: ${e}`);return}s&&(a.errorList=s),n&&(a.status=n),A&&(a.answer=A),await v(this,At,Ot).call(this),(h=a==null?void 0:a.data)!=null&&h.updateList&&x(this,q,!0),x(this,et,!1)}async getEntityList(e){var s;try{if((s=O(this,C))!=null&&s.length&&!O(this,q))return O(this,C);let n=new Q(BX24.callBatch),{entityList:A}=await n.batch({entityList:{method:"entity.item.get",params:{ENTITY:O(this,X),SORT:{ID:"DESC"}}}},e);return!A||!Array.isArray(A)?(console.warn("Получен невалидный список записей"),[]):(A=A.map(a=>{try{const{ID:h,DATE_CREATE:m,DETAIL_TEXT:f}=a;return{...JSON.parse(f),id:h,dateCreate:m}}catch(h){return console.error(`Ошибка парсинга записи ${a.ID}:`,h),null}}).filter(a=>a!==null),x(this,q,!1),x(this,C,A),A)}catch(n){return console.error("Ошибка при получении списка записей:",n),[]}}async downAllEntityJson(){try{if(O(this,C)||await this.getEntityList(),!O(this,C)||O(this,C).length===0)return console.warn("Нет данных для выгрузки"),!1;let e=st().format("%Y-%m-%d");return ft.downloadFileJson(O(this,C),`sdklogger-entity-data__${e}`),!0}catch(e){return console.error("Ошибка при выгрузке данных в JSON:",e),!1}}}X=new WeakMap,Z=new WeakMap,K=new WeakMap,tt=new WeakMap,C=new WeakMap,q=new WeakMap,et=new WeakMap,nt=new WeakSet,Nt=async function(){try{const e=new Q(BX24.callBatch),s=BX24.isAdmin(),{curUser:n}=await e.batch({curUser:{method:"user.current"}});x(this,tt,{isAdmin:s,curUser:n})}catch(e){console.error("Ошибка при получении информации о пользователе:",e),x(this,tt,{isAdmin:!1,curUser:null})}},rt=new WeakSet,dt=function(e){e=="entity"&&ft.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},At=new WeakSet,Ot=async function(){try{let e={},s=new Q(BX24.callBatch);for(let[n,A]of O(this,K).entries())if(A.status){const a=JSON.stringify(A);e[n]={method:"entity.item.add",params:{ENTITY:O(this,X),NAME:O(this,X),DETAIL_TEXT:a}}}if(Object.keys(e).length){let n=await s.batch(e),{errors:A}=s;for(let[a,h]of Object.entries({...n,...A}))O(this,K).delete(a);return!0}return!1}catch(e){return console.error("Ошибка при добавлении записей в хранилище:",e),!1}},at=new WeakSet,_t=async function(){try{let e=new Q(BX24.callBatch),{serverTime:s}=await e.batch({serverTime:{method:"server.time"}});if(!s){console.error("Не удалось получить время сервера");return}if(O(this,C)||await this.getEntityList(),!O(this,C)||O(this,C).length===0)return;let n=O(this,C).filter(A=>{try{let{dateCreate:a}=A;return a?st(new Date(a)).between(st(new Date(s)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});n.length>0&&(console.log(`Найдено ${n.length} записей для очистки (старше ${this.periodClear} месяцев)`),await v(this,ot,yt).call(this,n))}catch(e){console.error("Ошибка при проверке периода очистки:",e)}},ot=new WeakSet,yt=async function(e){try{if(!e||e.length===0)return!1;let s=new Q(BX24.callBatch),n=e.filter(a=>a&&a.id).map(a=>{let{id:h}=a;return{method:"entity.item.delete",params:{ENTITY:O(this,X),ID:h}}});if(n.length===0)return!1;const A=await s.batch(n);return console.log(`Успешно удалено ${n.length} записей`),x(this,q,!0),A}catch(s){return console.error("Ошибка при очистке устаревших записей:",s),!1}};class Rt{constructor(e){Y(this,ht);Y(this,lt);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);this.appConst=e}init(){return new Promise((e,s)=>{let A=setInterval(()=>{window.BX24&&BX24.init(async()=>{console.info("init BX24"),clearInterval(A),clearTimeout(a),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info(),this.logger?(this.logger=new gt,await this.logger.init()):this.logger={start:()=>{},stop:()=>{},getEntityList:()=>{}};const[h,m]=await Promise.all([v(this,ht,pt).call(this),v(this,lt,Et).call(this)]);this.appInfo=h,this.userInfo=m;let f=new ut;try{f.noSleep()}catch(r){console.warn("Failed to initialize noSleep:",r)}e(!0)})},100);const a=setTimeout(()=>{clearInterval(A);const h=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(h),s(h)},3e4)})}userOption(e,s){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return s!==void 0?BX24.userOption.set(e,s):BX24.userOption.get(e)}appOption(e,s){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return s!==void 0?BX24.appOption.set(e,s):BX24.appOption.get(e)}async call({method:e,params:s,updateList:n}){let A;return n&&(A=this.logger.start({type:"call",data:{method:e,params:s,updateList:n}}),console.log("keyLogger call:",A)),new Promise(async(a,h)=>{if(s||(s={}),typeof BX24>"u"||!BX24.callMethod){const m=new Error("BX24 is not initialized");console.error(m),h(m);return}BX24.callMethod(e,s,async m=>{let f={};if(m!=null&&m.answer)for(let[r,d]of Object.entries(m.answer))r!="result"&&d&&(f[r]=d);if(m.error()){let r=m.error();console.error(r),A&&await this.logger.stop({answer:f,key:A,status:"fail",errorList:{0:r.toString()}}),a(!1)}else{let r=m.data();r!=null&&r.items&&(r=r.items),A&&await this.logger.stop({answer:f,key:A,status:"success"}),a(r)}})})}async batch(e,s,{errorCall:n,limitCommandSerial:A,updateList:a,limitCall:h}={}){if(typeof BX24>"u"||!BX24.callBatch){const r=new Error("BX24 is not initialized");return console.error(r),!1}let m=new Q(BX24.callBatch),f;a&&(f=this.logger.start({type:"batch",data:{commandList:e,updateList:a}})),A&&console.warn("limitCommandSerial is deprecated and not used in current Batch implementation");try{let r=await m.batch(e,s,h);return Object.keys(m.errors).length?(n&&n(m.errors),f&&await this.logger.stop({key:f,status:"fail",errorList:m.errors})):f&&await this.logger.stop({key:f,status:"success"}),r}catch(r){return f&&await this.logger.stop({key:f,status:"fail-runtime",errorList:{0:r==null?void 0:r.toString()}}),console.error(r),!1}}async batchTotalCount(e,s){if(typeof BX24>"u"||!BX24.callBatch){const a=new Error("BX24 is not initialized");return console.error(a),!1}let n=new Q(BX24.callBatch),A=this.logger.start({type:"batch-total-count",data:{commandList:e}});try{let a=await n.batchTotalCount(e,s);if(Object.keys(n.errors).length){let h=Object.entries(n.errors).map(([m,f])=>({key:m,error:f.toString()}));A&&await this.logger.stop({key:A,status:"fail",errorList:h})}else A&&await this.logger.stop({key:A,status:"success"});return a}catch(a){return A&&await this.logger.stop({key:A,status:"fail-runtime",errorList:[a.toString()]}),console.error(a),!1}}async getPlacement(){return await this.call({method:"placement.get"}).then(e=>(this.placeData||(this.placeData=e),e))}async placementBind(e,s=void 0){if(Array.isArray(e)){await Promise.all(e.map(f=>this.placementBind(f,s)));return}if(this.placeData=await this.getPlacement(),!this.placeData)return;const{appName:n,pathApp:A}=this.appConst;let a=A;e==="PAGE_BACKGROUND_WORKER"&&(a=`${A}?USER_ID=${s??this.userInfo.ID}/`);let h={method:"placement.bind",params:{PLACEMENT:e,HANDLER:a,LANG_ALL:{ru:{TITLE:n}},OPTIONS:{errorHandlerUrl:a}}};e==="PAGE_BACKGROUND_WORKER"&&(h.params.USER_ID=s??this.userInfo.ID),e==="PAGE_BACKGROUND_WORKER_ALL"&&(e="PAGE_BACKGROUND_WORKER",h.params.PLACEMENT=e),this.placeData.find(f=>f.placement===e&&f.handler===a)||this.call(h)}async placementUnBind(e,s=void 0){if(Array.isArray(e)){await Promise.all(e.map(a=>this.placementUnBind(a,s)));return}if(this.placeData=await this.getPlacement(),!this.placeData)return;const{appName:n,pathApp:A}=this.appConst;s||(e==="PAGE_BACKGROUND_WORKER"?s=`${A}?USER_ID=${this.userInfo.ID}/`:s=A),await this.call({method:"placement.unbind",params:{PLACEMENT:e,HANDLER:s,LANG_ALL:{ru:{TITLE:n}},OPTIONS:{errorHandlerUrl:s}}})}async placementCheck(){if(this.placeData=await this.getPlacement(),!this.placeData)return;const{pathApp:e}=this.appConst;for(const s of this.placeData)s.handler.includes(e)||(await this.placementUnBind(s.placement,s.handler),s.userId!==0&&await this.placementBind(s.placement,s.userId))}getBotList(){return this.call({method:"imbot.bot.list",params:{}}).then(e=>{let s=Object.values(e);return console.log("chat-bot list:",s),s})}regBot({code:e,type:s,name:n}){const{appName:A,pathApp:a,chatBotLogo:h}=this.appConst,m=this.appInfo.ID;return this.call({method:"imbot.register",params:{CODE:e??this.appInfo.CODE,TYPE:s??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${n??A} - бот #${m}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:st().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:h??""}}}).then(f=>(console.log("Чат-бот добавлен",f),f))}unRegBot(e){return this.call({method:"imbot.unregister",params:{BOT_ID:e}}).then(s=>(console.log("чат-бот удален",s),s))}getLoggerList(e){return this.logger.getEntityList(e)}}ht=new WeakSet,pt=function(){return this.call({method:"app.info"})},lt=new WeakSet,Et=function(){return this.call({method:"user.current"})};class St{constructor(e){D(this,"entityName","tabs");D(this,"maxTabs",5);D(this,"interval");D(this,"id",0);D(this,"tabList",[]);D(this,"random",this.getRandomNum());D(this,"continueCondition");D(this,"defaultContinueBackground",()=>!0);D(this,"activeMaxPause",60*1e3*5+this.random);D(this,"activeMinPause",60*1e3*3+this.random);if(!e){console.error("В бек-воркер не переданы настройки, отмена вызова"),console.log("BackgroundWorker: Отмена конструктора - отсутствуют опции");return}const{appFunc:s,bx:n,users:A,continueBackground:a}=e;this.bx=n,this.appPath=n.appConst.pathApp??"",this.appName=n.appConst.appName??"",this.appInit=s,this.users=A,this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("Функция-запуск не передана в appInit, отмена инициализации бекворкера"),console.log("BackgroundWorker: Отмена init - не передана appInit");return}if(!this.bx){console.error("Не передан экземпляр bxBoot"),console.log("BackgroundWorker: Отмена init - отсутствует bx");return}if(await this.bx.placementBind(["PAGE_BACKGROUND_WORKER"]),!await this.continueBackground()){console.log("BackgroundWorker: Отмена init - условие запуска не выполнено");return}await this.checkEntity(),this.tabList=await this.getFilteredTabList(),this.id=await this.addTab(),console.log("tabId",this.id),this.interval=setInterval(()=>{this.backgroundPolling().catch(e=>{console.error("BackgroundWorker: backgroundPolling failed",e)})},this.activeMinPause)}async checkEntity(){var n;const e=await this.bx.call({method:"entity.get"});((n=e==null?void 0:e.find)==null?void 0:n.call(e,A=>A.ENTITY===this.entityName))||await this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}})}async getTabs(){var s;const e=await this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:(s=this.bx.userInfo)==null?void 0:s.ID},SORT:{DATE_CREATE:"DESC"}}});return e!=null&&e.length?e.map(n=>{if(!n)return{id:void 0,data:void 0};try{return{id:n.ID,data:{...JSON.parse(n.DETAIL_TEXT)}}}catch(A){return console.log(A),{id:n.ID,data:void 0}}}):[]}async addTab(){var s;const e={lastActive:new Date().toISOString(),duration:new Date().getTime()-this.start.getTime(),start:!1};return this.tabList.length<this.maxTabs&&await this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(s=this.bx.userInfo)==null?void 0:s.ID,DETAIL_TEXT:JSON.stringify(e)}})||0}async updateTab(e){var n;const s={lastActive:new Date().toISOString(),duration:new Date().getTime()-this.start.getTime(),start:e};await this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(n=this.bx.userInfo)==null?void 0:n.ID,DETAIL_TEXT:JSON.stringify(s)}})}async deleteTabs(e=[]){if(!e.length)return;const s=e.map(n=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:n.id}}));s.length&&await this.bx.batch(s)}getRandomNum(){const e=Math.round(Number(Math.random().toFixed(2))*30);return Math.round(Math.random())?e:-e}async continueBackground(){try{const s=!!await Promise.resolve(this.continueCondition(this));return console.log(s?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: Отмена continueBackground - внешнее условие вернуло false"),s}catch(e){return console.error("BackgroundWorker: Ошибка при выполнении условия продолжения",e),console.log("BackgroundWorker: Отмена continueBackground - исключение в условии запуска"),!1}}async getFilteredTabList(){const e=[],s=[],n=await this.getTabs();for(const A of n){if(!(A!=null&&A.data)){e.push(A);continue}new Date().getTime()-new Date(A.data.lastActive).getTime()>this.activeMaxPause?e.push(A):s.push(A)}return await this.deleteTabs(e),s}async backgroundPolling(){if(!await this.continueBackground()){this.interval&&(clearInterval(this.interval),this.interval=void 0),console.log("BackgroundWorker: Остановка backgroundPolling - условие continueBackground не выполнено");return}if(this.tabList=await this.getFilteredTabList(),!this.id){this.id=await this.addTab();return}let e=this.checkOtherTabs();e&&(await this.pause(Math.round(Number(Math.random().toFixed(2))*1e4)),this.tabList=await this.getFilteredTabList(),e=this.checkOtherTabs(),e&&await this.startBackground())}checkOtherTabs(){var A,a;let e=!1,s=new Date().getTime()-new Date(this.start).getTime();for(const h of this.tabList)if(+h.id!==this.id&&((A=h.data)!=null&&A.start&&(e=!0),((a=h.data)==null?void 0:a.duration)>s)){s=!1;break}const n=!e&&!!s;return this.updateTab(n).catch(h=>{console.error("BackgroundWorker: updateTab failed",h)}),console.log(`BackgroundWorker: Проверка вкладок - можно запускать приложение? ${n}`),n}async startBackground(){this.interval&&(clearInterval(this.interval),this.interval=void 0),this.interval=setInterval(()=>{this.updateTab(!0).catch(e=>{console.error("BackgroundWorker: periodic updateTab failed",e)})},this.activeMinPause),await this.appInit(),this.interval&&(clearInterval(this.interval),this.interval=void 0),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)}async setBackgroundWorkerAll(){var d,_;if(!((d=this.bx)!=null&&d.isAdmin)){console.log("BackgroundWorker: Отмена setBackgroundWorkerAll - пользователь не админ");return}(_=this.users)!=null&&_.length||await this.getEntityData();const e=await this.bx.getPlacement(),s=new Map;let n=null;e.forEach(o=>{o.placement==="PAGE_BACKGROUND_WORKER"&&(o.userId?s.set(+o.userId,o):n=o)}),console.log(`setBackgroundWorkerAll: Найдено ${s.size} индивидуальных и ${n?1:0} общих привязок PAGE_BACKGROUND_WORKER`);const A=await this.getAdminsList(),a=await this.getEligibleUsersForBackgroundWorker(A);a.sort((o,u)=>{const R=o.LAST_LOGIN?new Date(o.LAST_LOGIN):new Date(0);return(u.LAST_LOGIN?new Date(u.LAST_LOGIN):new Date(0))-R}),console.log(`setBackgroundWorkerAll: Найдено ${a.length} подходящих пользователей (админы и руководители)`);const h=[];!n&&this.appPath&&(h.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}/`}}}),console.log("setBackgroundWorkerAll: Добавлен в очередь создание общего бэк-воркера"));const m=10,f=a.slice(0,m),r=[];for(const[o]of s)a.find(R=>+R.ID===o)||r.push(o);for(const o of r)this.appPath&&(h.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${o}/`}}),console.log(`setBackgroundWorkerAll: Добавлена в очередь отвязка бэк-воркера от пользователя ${o}`));for(const o of f)s.has(+o.ID)||!this.appPath||h.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${o.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}?USER_ID=${o.ID}/`},USER_ID:o.ID}});h.length?(console.log(`setBackgroundWorkerAll: Выполняем ${h.length} операций через batch`),await this.bx.batch(h),console.log("setBackgroundWorkerAll: Все операции batch выполнены успешно")):console.log("setBackgroundWorkerAll: Нет операций для выполнения")}async getEligibleUsersForBackgroundWorker(e=[]){return(this.users??[]).filter(n=>n.ACTIVE==="Y"||n.ACTIVE===!0).filter(n=>{const A=+n.ID;return e.includes(A)})}async updateAdminsList(){var e,s,n;try{const A=BX24.appOption.get("adminsList");let a=[];if(A)try{a=JSON.parse(A)}catch{console.log("updateAdminsList: Ошибка парсинга существующего списка админов, создаем новый"),a=[]}const h=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0);(s=this.bx)!=null&&s.isAdmin&&h&&!a.includes(h)&&(a.push(h),console.log(`updateAdminsList: Добавлен новый админ ${h}`)),!((n=this.bx)!=null&&n.isAdmin)&&h&&a.includes(h)&&(a=a.filter(r=>r!==h),console.log(`updateAdminsList: Удален из списка админов пользователь ${h} (больше не админ)`));const m=new Set((this.users??[]).filter(r=>r.ACTIVE==="Y"||r.ACTIVE===!0).map(r=>+r.ID)),f=a.filter(r=>m.has(r));return f.length!==a.length&&(console.log(`updateAdminsList: Удалено ${a.length-f.length} неактивных админов`),a=f),BX24.appOption.set("adminsList",JSON.stringify(a)),console.log(`BackgroundWorker: Список админов обновлен: ${a.length} админов`),a}catch(A){return console.error("BackgroundWorker: Ошибка при обновлении списка админов:",A),[]}}async getAdminsList(){try{const e=BX24.appOption.get("adminsList");return e?JSON.parse(e):[]}catch(e){return console.error("getAdminsList: Ошибка при получении списка админов:",e),[]}}async getEntityData(){const e={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:s}=await this.bx.batch(e).then(n=>n?(Array.isArray(n.users)||(n.users=[]),n):{users:[]});this.users=s}pause(e=500,s){return new Promise(n=>{setTimeout(()=>{s&&s(),n(!0)},e)})}}g.BackgroundWorker=St,g.Batch=Q,g.BxBoot=Rt,g.BxHelper=ut,g.BxLogger=gt,g.tempus=st,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
var bt=Object.defineProperty;var St=(N,E,b)=>E in N?bt(N,E,{enumerable:!0,configurable:!0,writable:!0,value:b}):N[E]=b;var M=(N,E,b)=>(St(N,typeof E!="symbol"?E+"":E,b),b),mt=(N,E,b)=>{if(!E.has(N))throw TypeError("Cannot "+b)};var _=(N,E,b)=>(mt(N,E,"read from private field"),b?b.call(N):E.get(N)),Y=(N,E,b)=>{if(E.has(N))throw TypeError("Cannot add the same private member more than once");E instanceof WeakSet?E.add(N):E.set(N,b)},J=(N,E,b,$)=>(mt(N,E,"write to private field"),$?$.call(N,b):E.set(N,b),b);var Q=(N,E,b)=>(mt(N,E,"access private method"),b);(function(N,E){typeof exports=="object"&&typeof module<"u"?E(exports):typeof define=="function"&&define.amd?define(["exports"],E):(N=typeof globalThis<"u"?globalThis:N||self,E(N["szdl-utils-kit"]={}))})(this,function(N){var V,j,Z,K,tt,G,q,et,nt,Nt,st,dt,At,Ot,ot,pt,at,_t,ht,yt,lt,Et;"use strict";var E=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function b(W){return W&&W.__esModule&&Object.prototype.hasOwnProperty.call(W,"default")?W.default:W}var $={exports:{}};(function(W,e){(function(r){Array.prototype.indexOf||(Array.prototype.indexOf=function(t,n){var l,f;for(l=n||0,f=this.length;l<f;l+=1)if(this[l]===t)return l;return-1});var i=this,A=function(t,n){for(var l=t.toString();l.length<n;)l="0"+l;return l},o=function(t,n){return n!==r?(t.year(n.year()||n.year),t.month(n.month()||n.month),t.day(n.day()||n.day),t.hours(n.hours()||n.hours),t.minutes(n.minutes()||n.minutes),t.seconds(n.seconds()||n.seconds),t.milliseconds(n.milliseconds()||n.milliseconds),t):r},h=function(t,n){var l,f="";return l=t.slice(n,n+1),l!==""&&!isNaN(Number(l))&&(f+="%H"),l=t.charAt(n+2),l!==""&&l===":"&&(f+=l),l=t.slice(n+3,n+4),l!==""&&!isNaN(Number(l))&&(f+="%M"),l=t.charAt(n+5),l!==""&&l===":"&&(f+=l),l=t.slice(n+6,n+7),l!==""&&!isNaN(Number(l))&&(f+="%S"),f},m=function(t,n){var l,f=[t.slice(n,n+1),t.charAt(n+2),t.slice(n+3,n+4),t.charAt(n+5),t.slice(n+6,n+9)],S;return!isNaN(Number(f[0]))&&!isNaN(Number(f[2]))&&!isNaN(Number(f[4]))?(f[1]==="."&&f[3]==="."?l="%d.%m.%Y":f[1]==="-"&&f[3]==="-"?l="%m-%d-%Y":f[1]==="/"&&f[3]==="/"&&(l="%m/%d/%Y"),l):(S=[t.slice(n,n+3),t.charAt(n+4),t.slice(n+5,n+6),t.charAt(n+7),t.slice(n+8,n+9)],!isNaN(Number(S[0]))&&!isNaN(Number(S[2]))&&!isNaN(Number(S[4]))?(S[1]==="-"&&S[3]==="-"&&(l="%Y-%m-%d"),l):"")},u=i.tempus,s,d,g=i.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"}},y=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]},F=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]},x,U,k,B,it=function(t,n,l){var f;i.XMLHttpRequest?f=new XMLHttpRequest:f=new ActiveXObject("Microsoft.XMLHTTP"),f.onreadystatechange=function(){f.readyState===4&&(f.status===200?n&&(i.JSON===r?alert(`Please, include json2 into your project if you want use old browsers!
|
|
2
|
+
https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):n(JSON.parse(f.responseText))):l&&l(f))},f.open("GET",t,!1),f.send()},H={"%d":{format:function(t){return A(t.day()||s.MIN_DAY,2)},parse:function(t){var n=Number(t);return{day:isNaN(n)?r:n}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(t){return A(t.month()||s.MIN_MONTH,2)},parse:function(t){var n=Number(t);return{month:isNaN(n)?r:n}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(t){return A(t.year()||s.MIN_YEAR,4)},parse:function(t){var n=Number(t);return{year:isNaN(n)?r:n}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(t){return t.dayOfWeek()||s.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(t){var n=t.dayOfWeek();return B[n!==r?n:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var n=t.dayOfWeek();return k[n!==r?n:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(t){var n=s.options("monthFromZero")?t.month():t.month()-1;return U[n!==r?n:s.MIN_MONTH]},parse:function(t){var n=s.monthNames().indexOf(t)+(s.options("monthFromZero")?0:1);return{month:n!==-1?n:r}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var n=s.options("monthFromZero")?t.month():t.month()-1;return x[n!==r?n:s.MIN_MONTH]},parse:function(t){var n=s.monthNames(!0).indexOf(t)+(s.options("monthFromZero")?0:1);return{month:n!==-1?n:r}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(t){return A(t.hours()||s.MIN_HOURS,2)},parse:function(t){var n=Number(t);return{hours:isNaN(n)?r:n}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(t){return A(t.minutes()||s.MIN_MINUTES,2)},parse:function(t){var n=Number(t);return{minutes:isNaN(n)?r:n}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(t){return A(t.seconds()||s.MIN_SECONDS,2)},parse:function(t){var n=Number(t);return{seconds:isNaN(n)?r:n}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(t){return t.timestamp()},parse:function(t){return isNaN(Number(t))?{}:s(Number(t)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(t){return A(t.year()||s.MIN_YEAR,4)+"-"+A(t.month()||s.MIN_MONTH,2)+"-"+A(t.day()||s.MIN_DAY,2)},parse:function(t){var n=Number(t.slice(0,4)),l=Number(t.slice(5,7)),f=Number(t.slice(8,10));return{year:n,month:l,day:f}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return A(t.month()||s.MIN_MONTH,2)+"/"+A(t.day()||s.MIN_DAY,2)+"/"+A(t.year()||s.MIN_YEAR,4)},parse:function(t){var n=Number(t.slice(0,2)),l=Number(t.slice(3,5)),f=Number(t.slice(6,10));return{year:f,month:n,day:l}},minLength:10,maxLength:10,type:"string"}},ct={useMilliseconds:!1,monthFromZero:!1},T;T=function(t,n,l){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t!==r&&this.set(t,n,l),this},T.fn=T.prototype,T.fn.dayCount=function(){var t=this.month(),n=s.MAX_DAY_IN_MONTHS[t-(s.options("monthFromZero")?0:1)];return this.leapYear()&&t===(s.options("monthFromZero")?1:2)&&(n+=1),n},T.fn.year=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_YEAR&&Number(t)<=s.MAX_YEAR?(this._d.setFullYear(Number(t)),this._i.year=!1):this._i.year=Number(t):(this._d.setFullYear(s.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},T.fn.month=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MONTH&&Number(t)<=s.MAX_MONTH?(this._d.setMonth(s.options("monthFromZero")?Number(t):Number(t)-1),this._i.month=!1):this._i.month=Number(t):(this._d.setMonth(s.options("monthFromZero")?s.MIN_MONTH:s.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?s.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},T.fn.day=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_DAY&&Number(t)<=this.dayCount()?(this._d.setDate(Number(t)),this._i.day=!1):this._i.day=Number(t):(this._d.setDate(s.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},T.fn.hours=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_HOURS&&Number(t)<=s.MAX_HOURS?(this._d.setHours(Number(t)),this._i.hours=!1):this._i.hours=Number(t):(this._d.setHours(s.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},T.fn.minutes=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MINUTES&&Number(t)<=s.MAX_MINUTES?(this._d.setMinutes(Number(t)),this._i.minutes=!1):this._i.minutes=Number(t):(this._d.setMinutes(s.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},T.fn.seconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_SECONDS&&Number(t)<=s.MAX_SECONDS?(this._d.setSeconds(Number(t)),this._i.seconds=!1):this._i.seconds=Number(t):(this._d.setSeconds(s.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},T.fn.milliseconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MILLISECONDS&&Number(t)<=s.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(t)),this._i.milliseconds=!1):this._i.milliseconds=Number(t):(this._d.setMilliseconds(s.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},T.fn.week=function(){var t=new Date(this.year(),0,1),n=s(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((n-t.getTime())/864e5+t.getDay()+1)/7)},T.fn.set=function(t,n,l){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t===r)return this._d=new Date,this;if(t instanceof Date)return this._d=t,this;if(typeof t=="number")return this._d=new Date(t*(s.options("useMilliseconds")?1:1e3)),this;if(typeof t=="object"&&(t instanceof Array?(this.day(s.MIN_DAY),this.year(t[0]),this.month(t[1]),this.day(t[2]),this.hours(t[3]),this.minutes(t[4]),this.seconds(t[5]),this.milliseconds(t[6])):(this.day(s.MIN_DAY),this.year(t.year),this.month(t.month),this.day(t.day),this.hours(t.hours),this.minutes(t.minutes),this.seconds(t.seconds),this.milliseconds(t.milliseconds))),typeof t=="string"){var f,S=[],p,R,z=[],C=0,P=0,D,X,I={},w;if(t===r)return p=o(this,l),p===r&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),p;for(n===r&&(n=s.detectFormat(t));C<n.length;){if(n.charAt(C)==="%"){if(R=n.charAt(C)+n.charAt(C+1),H[R]!==r){switch(D=0,X="",H[R].type){case"number":for(;D<H[R].maxLength&&P+D<t.length&&!isNaN(Number(t.charAt(P+D)));)X+=t.charAt(P+D),D+=1;break;case"word":for(;D<H[R].maxLength&&P+D<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(P+D));)X+=t.charAt(P+D),D+=1;break;case"string":for(;D<H[R].maxLength&&P+D<t.length;)X+=t.charAt(P+D),D+=1;break}if(D<H[R].minLength)return p=o(this,l),p===r&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),p;S.push(R),z.push(X),D-=1,P+=D,C+=1}}else if(t.charAt(P)!==n.charAt(C))return p=o(this,l),p===r&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),p;C+=1,P+=1}for(f in S)S.hasOwnProperty(f)&&H.hasOwnProperty(S[f])&&(w=H[S[f]].parse(z[f]),I={year:w.year!==r?w.year:I.year,month:w.month!==r?w.month:I.month,day:w.day!==r?w.day:I.day,hours:w.hours!==r?w.hours:I.hours,minutes:w.minutes!==r?w.minutes:I.minutes,seconds:w.seconds!==r?w.seconds:I.seconds});this.day(s.MIN_DAY),this.year(I.year),this.month(I.month),this.day(I.day),this.hours(I.hours),this.minutes(I.minutes),this.seconds(I.seconds),this.milliseconds(I.milliseconds)}return this},T.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},T.fn.timestamp=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(s.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):s.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},T.fn.utc=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(s.options("useMilliseconds")?1:1e3)),this):s.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},T.fn.dayOfWeek=function(t){if(t==="long")return k[this._d.getDay()];if(t==="short")return B[this._d.getDay()];if(t===r)return this._d.getDay();if(t===0||t==="Sunday")return this.calc({day:-this.dayOfWeek()});if(t===1||t==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(t===2||t==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(t===3||t==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(t===4||t==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(t===5||t==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(t===6||t==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},T.fn.timezone=function(t){switch(t){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},T.fn.get=function(t){switch(t){case"Date":return new Date(this.year(),this.month()-(s.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds());case"DateUTC":return new Date(Date.UTC(this.year(),this.month()-(s.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()));case"Array":return[this.year(),this.month(),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()];default:return{year:this.year(),month:this.month(),week:this.week(),day:this.day(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds(),utc:this.utc(),dayOfWeek:this.dayOfWeek(),dayOfWeekShort:this.dayOfWeek("short"),dayOfWeekLong:this.dayOfWeek("long"),timestamp:this.timestamp()}}},T.fn.format=function(t){for(var n=0,l="",f;n<t.length;)t.charAt(n)==="%"?(f=t.charAt(n)+t.charAt(n+1),H[f]!==r?(l+=H[f].format(this),n+=1):l+="%"):l+=t.charAt(n),n+=1;return l},T.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},T.fn.errors=function(){return this._i},T.fn.between=function(t,n){var l=this.timestamp(),f=t.timestamp();switch(n){case"year":return Math.floor((f-l)/31556952);case"month":return Math.floor((f-l)/2629746);case"day":return Math.floor((f-l)/86400);case"hours":return Math.floor((f-l)/3600);case"minutes":return Math.floor((f-l)/60);case"seconds":return f-l;default:return r}},T.fn.calc=function(t){return t.year!==r&&this._d.setFullYear(this._d.getFullYear()+t.year),t.month!==r&&this._d.setMonth(this._d.getMonth()+t.month),t.day!==r&&this._d.setDate(this._d.getDate()+t.day),t.hours!==r&&this._d.setHours(this._d.getHours()+t.hours),t.minutes!==r&&this._d.setMinutes(this._d.getMinutes()+t.minutes),t.seconds!==r&&this._d.setSeconds(this._d.getSeconds()+t.seconds),t.milliseconds!==r&&this._d.setMilliseconds(this._d.getMilliseconds()+t.milliseconds),this},s=function(t,n,l){return new T(t,n,l)},s.MIN_YEAR=1e3,s.MAX_YEAR=3e3,s.MIN_MONTH=1,s.MAX_MONTH=12,s.MIN_DAY=1,s.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],s.MIN_DAY_OF_WEEK=0,s.MAX_DAY_OF_WEEK=6,s.MIN_HOURS=0,s.MAX_HOURS=23,s.MIN_MINUTES=0,s.MAX_MINUTES=59,s.MIN_SECONDS=0,s.MAX_SECONDS=59,s.MIN_MILLISECONDS=0,s.MAX_MILLISECONDS=999,s.VERSION="0.2.18",s.options=function(t,n){if(t===r)return ct;if(ct.hasOwnProperty(t)){if(n===r)return ct[t];ct[t]=n,t==="monthFromZero"&&(s.MIN_MONTH=n?0:1,s.MAX_MONTH=n?11:12)}return r},s.noConflict=function(){return i.tempus=u,s},s.generate=function(t){var n,l,f,S,p,R,z,C;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof T?n=t.dateFrom.utc():n=s(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof T?l=t.dateTo.utc():l=s(t.dateTo,t.formatTo!==r?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?p={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?p={year:t.period==="year"?1:0,month:t.period==="month"?1:0,day:t.period==="day"?1:0,hours:t.period==="hours"?1:0,minutes:t.period==="minutes"?1:0,seconds:t.period==="seconds"?1:0}:typeof t.period=="object"&&(p={year:t.period.year!==r?t.period.year:0,month:t.period.month!==r?t.period.month:0,day:t.period.day!==r?t.period.day:0,hours:t.period.hours!==r?t.period.hours:0,minutes:t.period.minutes!==r?t.period.minutes:0,seconds:t.period.seconds!==r?t.period.seconds:0}),t.groupBy===r?R=t.asObject===!0?{}:[]:(R=[],R.push([]),z=s(n).get()[t.groupBy]),C=function(X,I,w){return t.asObject===!0?t.format!==r?X[s(I).format(t.format)]={}:X[s(I).format("%F %H:%M:%S")]={}:t.format!==r?X.push(w?null:s(I).format(t.format)):X.push(w?null:s(I)),X},t.groupBy!==r&&t.fillNulls){var P={year:p.year?-p.year:r,month:p.month?-p.month:r,day:p.day?-p.day:r,hours:p.hours?-p.hours:r,minutes:p.minutes?-p.minutes:r,seconds:p.seconds?-p.seconds:r,milliseconds:p.milliseconds?-p.milliseconds:r};for(f=s(n).calc(P).utc();s(f).get()[t.groupBy]===z;)C(R[R.length-1],f,!0),f=s(f).calc(P).utc();if(t.groupBy==="week"){var D=s(n).dayOfWeek();for(f=s(n).dayOfWeek(0).utc();R[0].length<D&&f<n;)C(R[R.length-1],f,!0),f=s(f).calc(p).utc()}}for(;n<=l;)t.groupBy===r?C(R,n):s(n).get()[t.groupBy]===z?C(R[R.length-1],n):(R.push([]),C(R[R.length-1],n),z=s(n).get()[t.groupBy]),n=s(n).calc(p).utc();if(t.groupBy!==r&&t.fillNulls)for(S=s(l).calc(p).utc();s(S).get()[t.groupBy]===z;)C(R[R.length-1],S,!0),S=s(S).calc(p).utc();return R},s.monthNames=function(t){switch(t){case"long":return x;default:return U}},s.dayNames=function(t){switch(t){case"long":return k;default:return B}},s.lang=function(t){if(t!==r)a=t,c[a]===r&&(a="en"),x=y(),U=O(),k=L(),B=F();else return a;return r},s.availableLangs=function(){return Object.keys(c)},s.registerFormat=function(t,n,l,f,S,p){H[t]={format:n,parse:l,minLength:f,maxLength:S,type:p}},s.unregisterFormat=function(t){delete H[t]},s.detectFormat=function(t){var n,l,f;return n=m(t,0),n!==""&&(f=10),l=t.charAt(f),(l==="T"||l===" ")&&(n+=l,f+=1),n+=h(t,f),n},d={TempusDate:T},s.classes=function(t,n){if(n===r)return d[t];d[t]=n},s.loadTranslations=function(t){typeof t=="object"?c=t:typeof t=="string"&&it(t,function(n){c=n},function(n){})},a=(g.language||g.systemLanguage||g.userLanguage||"en").substr(0,2).toLowerCase(),c[a]===r&&(a="en"),x=y(),U=O(),k=L(),B=F(),W.exports&&(e=W.exports=s),e.tempus=s}).call(E)})($,$.exports);var Tt=$.exports;const rt=b(Tt);class v{constructor(e){this.callBatch=e,this.result={},this.errors={},this.limit=50,this.canContinue=!0,this.progressCall="",this.limitCall="",this.progressData="",this.progressTimer="",this.progressDelay=100,this.oldPercent="no",this.chunkRate=1,this.totalProgress=0,this.skipList=new Set}getData(e){return(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}get progressPercent(){let e=0;if(!this.progressData)return{percent:Math.round(e),allCount:0,allTotal:0};let r=0,i=0;return Object.values(this.progressData).forEach(A=>{const{total:o,count:h}=A;r+=o??0,i+=h??0}),r?e=i/r*100*this.chunkRate+this.totalProgress:i===0&&r===0?e=100*this.chunkRate+this.totalProgress:e=100,{percent:Math.round(e),allCount:i,allTotal:r}}setProgressData({key:e,value:r,type:i}){const A=this.getData(r.data()),o=Array.isArray(A)?A.length:0;let h=r.total()||o;i==="count"&&(h=o);let m=1;A&&(m=o),this.progressCall&&(this.progressData||(this.progressData={}),this.progressData[e]&&this.progressData[e].count&&(m+=this.progressData[e].count),this.progressData[e]?this.progressData[e].count=m:this.progressData[e]={total:h,count:m},this.progressTimer||(this.progressTimer=setInterval(()=>{const{percent:u,allCount:s,allTotal:d}=this.progressPercent;(this.oldPercent==="no"||this.oldPercent<this.progressPercent.percent)&&(this.progressCall({data:this.progressData,percent:u,allCount:s,allTotal:d}),this.oldPercent=this.progressPercent.percent),u>=100&&this.clearProgressData()},this.progressDelay)))}delay(){return new Promise(e=>setTimeout(e,500))}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.limitCall="",this.oldPercent="no"}async batch(e,r,i){this.progressTimer&&this.clearProgressData(),r&&(this.progressCall=r),i&&(this.limitCall=i),this.canContinue=!0,this.result={},this.errors={};const A={};this.chunkRate=(1/Math.ceil(Object.keys(e).length/this.limit)).toFixed(5);let o={},h=0;for(const[m,u]of Object.entries(e)){if(!this.canContinue)break;const s=this.arrayChunk(u);if(!s){h++;continue}o[m]=s,(Object.keys(o).length>=50||h+1===Object.keys(e).length)&&(await this.batchChunk(o),Object.entries(this.result).forEach(([d,g])=>{A[d]=g}),this.totalProgress=Math.round(h/Object.keys(e).length*100),o={}),h++}return Object.entries(this.errors).length&&(A.errorsList=this.errors),r&&r({percent:100}),Promise.resolve(A)}async batchTotalCount(e,r,i){this.progressTimer&&this.clearProgressData(),r&&(this.progressCall=r),i&&(this.limitCall=i),this.canContinue=!0,this.result={},this.errors={};const A={};this.chunkRate=(1/Math.ceil(Object.keys(e).length/this.limit)).toFixed(5);let o={},h=0;for(const[m,u]of Object.entries(e)){if(!this.canContinue)break;const s=this.arrayChunk(u);if(!s){h++;continue}o[m]=s,(Object.keys(o).length>=50||h+1===Object.keys(e).length)&&(await this.batchChunk(o,"count"),Object.entries(this.result).forEach(([d,g])=>{A[d]=g}),this.totalProgress=Math.round(h/Object.keys(e).length*100),o={}),h++}return Object.entries(this.errors).length&&(A.errorsList=this.errors),r&&r({percent:100}),Promise.resolve(A)}arrayChunk(e){let r="",i={};if(Array.isArray(e)?[r]=e:(r=e.method,i=e.params),this.skipList.has(r))return!1;if((r.includes("list")||r==="user.get")&&r!=="task.item.list"){if(!i)i={order:{ID:"ASC",id:"ASC"}};else{r==="tasks.task.list"?(i.order||(i.order={}),i.order.ID="asc"):r==="user.get"?(i.sort||(i.sort="ID"),i.order||(i.order="ASC")):i.order={ID:"ASC",id:"ASC"},Array.isArray(i.select)&&!i.select.includes("ID")&&i.select.push("ID");const A=r==="user.get"?i.FILTER:i.filter;typeof A=="object"&&A!==null&&!Array.isArray(A)&&Object.entries(A).forEach(([o,h])=>{(i.start===void 0||i.start!==-1)&&["id","ID"].includes(o)&&(typeof h=="string"||Array.isArray(h)&&h.length<=50)&&(i.start=-1)})}r==="crm.type.list"&&i.order&&delete i.order.ID}if(r==="task.item.list")if(!i)i=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(i[0])&&(i[0]={});const[A,o,h,m]=i;A.ID="ASC",m[0]!==""&&m.includes("ID")||m.push("ID")}return{method:r,params:i}}async batchChunk(e,r){return new Promise(i=>{const A=[];let o;this.callBatch(e,async h=>{var m,u,s,d,g,a,c;for(const[y,O]of Object.entries(h)){if(!this.canContinue)return;if(O.error())switch(this.errors[y]=((u=(m=O.error())==null?void 0:m.ex)==null?void 0:u.error)??((d=(s=O.error())==null?void 0:s.ex)==null?void 0:d.error_description)??((g=O.error())==null?void 0:g.toString())??"Неизвестная ошибка",o=!0,((c=(a=O.error())==null?void 0:a.ex)==null?void 0:c.error)??""){case"OPERATION_TIME_LIMIT":this.skipList.add(e[y].method),this.limitCall&&this.limitCall(y);break;case"QUERY_LIMIT_EXCEEDED":this.canContinue=!1;break;case"ACCESS_DENIED":this.skipList.add(e[y].method);break}const L=this.getData(O.data()),F=Array.isArray(L)?L.length:0,x=typeof O.total=="function"&&O.total()!==void 0,U=x?O.total():F;r==="count"?this.result[y]?this.result[y]+=F:this.result[y]=U:this.result[y]=L,this.setProgressData({key:y,value:O,type:r});const k=r==="count"?!x&&F===this.limit:U>this.limit&&U>F;if(!this.canContinue||k){let B=e[y];if(Array.isArray(B)){const[it,H={}]=B;B=[it,H]}else{const{method:it,params:H={}}=B;B=[it,H]}A.push([y,B,U])}}o>0&&this.errorLogger(),A.length?await this.batchPayload(A,r).then(()=>i(this.result)):i(this.result)})})}async batchPayload(e,r){const i=new Map,A=(u,s,d,g)=>{let a="ID";this.result[u][this.result[u].length-1].ID||(a="id");let c=`${a}`;if(JSON.stringify(g[1]).toLocaleLowerCase().includes('"id":"desc"')?c="<"+c:c=">"+c,s===1||d.length===0)return{field:c,id:this.result[u][this.result[u].length-1][a]};let O="";const[L,F]=g;return(L==="tasks.task.list"||L==="task.item.list")&&(O="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(L)&&(O="[items]"),L==="crm.type.list"&&(O="[types]"),L==="socialnetwork.api.workgroup.list"&&(O="[workgroups]"),{field:c,id:`$result[${[u,s-1].join("__")}]${O}[49][${a}]`}},o=(u,s)=>{const[d,g]=u;let a=JSON.parse(JSON.stringify(g)),c;if(d==="task.item.list"){a=[...a];const[y,O,L,F]=a;return O[s.field]=s.id,[d,a]}return["user.get"].includes(d)||a.FILTER?(a.FILTER||(a.FILTER={}),c=a.FILTER):(a.filter||(a.filter={}),c=a.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(d)?c[">ID"]=s.id:c[s.field]=s.id,[d,{...a,start:-1}]},h=u=>{Object.entries(u).forEach(([s,d])=>{var c,y,O,L,F,x,U;const[g]=s.split("__"),a=this.getData(d.data());if(Array.isArray(a)&&(r==="count"?this.result[g]+=a.length:this.result[g].push(...a)),d.error()){this.errors[g]=((y=(c=d.error())==null?void 0:c.ex)==null?void 0:y.error)??((L=(O=d.error())==null?void 0:O.ex)==null?void 0:L.error_description)??((F=d.error())==null?void 0:F.toString())??"Неизвестная ошибка";const k=((U=(x=d.error())==null?void 0:x.ex)==null?void 0:U.error)??"";if(k==="OPERATION_TIME_LIMIT"){this.limitCall&&this.limitCall(g);const B=i.get(g);switch(k){case"OPERATION_TIME_LIMIT":B&&(this.skipList.add(B),this.limitCall&&this.limitCall(g));break;case"QUERY_LIMIT_EXCEEDED":this.canContinue=!1;break;case"ACCESS_DENIED":this.skipList.add(B);break}}}this.setProgressData({key:g,value:d,type:r})})};let m=[];for await(const[u,s,d]of e){if(!this.canContinue)return;const[g]=s;if(i.set(u,g),this.skipList.has(g))continue;let a=1;for(;d>a*50&&!this.skipList.has(g);){const c=[u,a].join("__"),y=A(u,a,m,s);m.push([c,o(s,y)]),m.length%50===0&&(await new Promise(O=>this.callBatch(Object.fromEntries(m),L=>{h(L),O()})),m=[],await this.delay()),a++}}m.length&&(await new Promise(u=>this.callBatch(Object.fromEntries(m),s=>{h(s),u()})),await this.delay())}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([e,r])=>{r&&console.log(`[${e}]`,r.toString())}),console.groupEnd()}}class ut{constructor(){Y(this,V,{})}get hash(){return this.createHash(8)}createHash(e){let r="abcdefghijklmnopqrstuvwxyz0123456789",i="";e=e||6;for(let A=0;A<e;A++)i+=r.charAt(Math.floor(Math.random()*r.length));return i}actionFilter({keyTimer:e,duration:r=10,action:i}){_(this,V)[e]&&(clearTimeout(_(this,V)[e]),_(this,V)[e]=null),i&&(_(this,V)[e]=setTimeout(()=>{i()},r))}async noSleep(){let e=document.createElement("video");e.classList.add("no-sleep"),e.muted=!0,e.autoplay=!0,e.setAttribute("playsinline",""),e.addEventListener("loadeddata",()=>{e.style.position="fixed",e.style.left="-9999px",document.querySelector("body").append(e),e.play().catch(r=>{console.warn("noSleep: autoplay prevented",r)})}),e.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{e.play().catch(r=>{console.warn("noSleep: replay prevented",r)})}})}),e.src="data:video/mp4;base64,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"}downloadFileJson(e,r){let i=new Blob([JSON.stringify(e)],{type:"application/json"}),A=URL.createObjectURL(i),o=document.createElement("a");o.style.display="none",o.href=A,o.download=`${r}.json`,document.body.appendChild(o),o.click(),setTimeout(()=>{document.body.removeChild(o),URL.revokeObjectURL(A)},200)}}V=new WeakMap;const ft=new ut;class gt{constructor(){Y(this,nt);Y(this,st);Y(this,At);Y(this,ot);Y(this,at);Y(this,j,"logger");Y(this,Z,!1);Y(this,K,new Map);Y(this,tt,{});Y(this,G,null);Y(this,q,!1);Y(this,et,!1);M(this,"periodClear",3);Q(this,nt,Nt).call(this)}async init(){try{let e=new v(BX24.callBatch),{entityList:r}=await e.batch({entityList:{method:"entity.get"}});if(r&&Array.isArray(r))if(r.find(A=>A.ENTITY==_(this,j)))J(this,Z,!0);else{let{entityAdd:A}=await e.batch({entityAdd:{method:"entity.add",params:{ENTITY:_(this,j),NAME:_(this,j),ACCESS:{AU:"X"}}}});A&&J(this,Z,!0)}return Q(this,ot,pt).call(this).catch(i=>{console.error("Ошибка при проверке периода очистки:",i)}),_(this,Z)}catch(e){return console.error("Ошибка при инициализации логера:",e),!1}}start({type:e,data:r}){if(!_(this,Z))return Q(this,st,dt).call(this,"entity"),null;if(!e||!r)return console.error("Невалидные данные для логирования:",{type:e,data:r}),null;const i=ft.hash,A={type:e,data:r,userInfo:_(this,tt),errorList:{},status:"",answer:null,date:new Date().getTime()};return _(this,K).set(i,A),J(this,et,!0),i}async stop({key:e,errorList:r,status:i,answer:A}){var h;if(!_(this,et))return;if(!_(this,Z)){Q(this,st,dt).call(this,"entity");return}let o=_(this,K).get(e);if(!o){console.error(`Не найдены данные логирования для ключа: ${e}`);return}r&&(o.errorList=r),i&&(o.status=i),A&&(o.answer=A),await Q(this,At,Ot).call(this),(h=o==null?void 0:o.data)!=null&&h.updateList&&J(this,q,!0),J(this,et,!1)}async getEntityList(e){var r;try{if((r=_(this,G))!=null&&r.length&&!_(this,q))return _(this,G);let i=new v(BX24.callBatch),{entityList:A}=await i.batch({entityList:{method:"entity.item.get",params:{ENTITY:_(this,j),SORT:{ID:"DESC"}}}},e);return!A||!Array.isArray(A)?(console.warn("Получен невалидный список записей"),[]):(A=A.map(o=>{try{const{ID:h,DATE_CREATE:m,DETAIL_TEXT:u}=o;return{...JSON.parse(u),id:h,dateCreate:m}}catch(h){return console.error(`Ошибка парсинга записи ${o.ID}:`,h),null}}).filter(o=>o!==null),J(this,q,!1),J(this,G,A),A)}catch(i){return console.error("Ошибка при получении списка записей:",i),[]}}async downAllEntityJson(){try{if(_(this,G)||await this.getEntityList(),!_(this,G)||_(this,G).length===0)return console.warn("Нет данных для выгрузки"),!1;let e=rt().format("%Y-%m-%d");return ft.downloadFileJson(_(this,G),`sdklogger-entity-data__${e}`),!0}catch(e){return console.error("Ошибка при выгрузке данных в JSON:",e),!1}}}j=new WeakMap,Z=new WeakMap,K=new WeakMap,tt=new WeakMap,G=new WeakMap,q=new WeakMap,et=new WeakMap,nt=new WeakSet,Nt=async function(){try{const e=new v(BX24.callBatch),r=BX24.isAdmin(),{curUser:i}=await e.batch({curUser:{method:"user.current"}});J(this,tt,{isAdmin:r,curUser:i})}catch(e){console.error("Ошибка при получении информации о пользователе:",e),J(this,tt,{isAdmin:!1,curUser:null})}},st=new WeakSet,dt=function(e){e=="entity"&&ft.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},At=new WeakSet,Ot=async function(){try{let e={},r=new v(BX24.callBatch);for(let[i,A]of _(this,K).entries())if(A.status){const o=JSON.stringify(A);e[i]={method:"entity.item.add",params:{ENTITY:_(this,j),NAME:_(this,j),DETAIL_TEXT:o}}}if(Object.keys(e).length){let i=await r.batch(e),{errors:A}=r;for(let[o,h]of Object.entries({...i,...A}))_(this,K).delete(o);return!0}return!1}catch(e){return console.error("Ошибка при добавлении записей в хранилище:",e),!1}},ot=new WeakSet,pt=async function(){try{let e=new v(BX24.callBatch),{serverTime:r}=await e.batch({serverTime:{method:"server.time"}});if(!r){console.error("Не удалось получить время сервера");return}if(_(this,G)||await this.getEntityList(),!_(this,G)||_(this,G).length===0)return;let i=_(this,G).filter(A=>{try{let{dateCreate:o}=A;return o?rt(new Date(o)).between(rt(new Date(r)),"month")>=this.periodClear:!1}catch(o){return console.error("Ошибка при проверке даты записи:",o),!1}});i.length>0&&(console.log(`Найдено ${i.length} записей для очистки (старше ${this.periodClear} месяцев)`),await Q(this,at,_t).call(this,i))}catch(e){console.error("Ошибка при проверке периода очистки:",e)}},at=new WeakSet,_t=async function(e){try{if(!e||e.length===0)return!1;let r=new v(BX24.callBatch),i=e.filter(o=>o&&o.id).map(o=>{let{id:h}=o;return{method:"entity.item.delete",params:{ENTITY:_(this,j),ID:h}}});if(i.length===0)return!1;const A=await r.batch(i);return console.log(`Успешно удалено ${i.length} записей`),J(this,q,!0),A}catch(r){return console.error("Ошибка при очистке устаревших записей:",r),!1}};class Rt{constructor(e){Y(this,ht);Y(this,lt);M(this,"domain","");M(this,"isAdmin",!1);M(this,"appInfo",null);M(this,"appConst",null);M(this,"userInfo",null);M(this,"placeData",null);M(this,"placeInfo",null);M(this,"logger",!1);this.appConst=e}init(){return new Promise((e,r)=>{let A=setInterval(()=>{window.BX24&&BX24.init(async()=>{console.info("init BX24"),clearInterval(A),clearTimeout(o),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info(),this.logger?(this.logger=new gt,await this.logger.init()):this.logger={start:()=>{},stop:()=>{},getEntityList:()=>{}};const[h,m]=await Promise.all([Q(this,ht,yt).call(this),Q(this,lt,Et).call(this)]);this.appInfo=h,this.userInfo=m;let u=new ut;try{u.noSleep()}catch(s){console.warn("Failed to initialize noSleep:",s)}e(!0)})},100);const o=setTimeout(()=>{clearInterval(A);const h=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(h),r(h)},3e4)})}userOption(e,r){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return r!==void 0?BX24.userOption.set(e,r):BX24.userOption.get(e)}appOption(e,r){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return r!==void 0?BX24.appOption.set(e,r):BX24.appOption.get(e)}async call({method:e,params:r,updateList:i}){let A;if(i&&(A=this.logger.start({type:"call",data:{method:e,params:r,updateList:i}})),r||(r={}),typeof BX24>"u"||!BX24.callMethod){const o=new Error("BX24 is not initialized");throw console.error(o),o}return new Promise((o,h)=>{BX24.callMethod(e,r,async m=>{let u={};if(m!=null&&m.answer)for(let[s,d]of Object.entries(m.answer))s!=="result"&&d&&(u[s]=d);if(m.error()){let s=m.error();if(console.error(s),A)try{await this.logger.stop({answer:u,key:A,status:"fail",errorList:{0:s.toString()}})}catch(d){console.error("Logger error:",d)}o(!1)}else{let s=m.data();if(s!=null&&s.items&&(s=s.items),A)try{await this.logger.stop({answer:u,key:A,status:"success"})}catch(d){console.error("Logger error:",d)}o(s)}})})}async batch(e,r,{errorCall:i,limitCommandSerial:A,updateList:o,limitCall:h}={}){if(typeof BX24>"u"||!BX24.callBatch){const s=new Error("BX24 is not initialized");return console.error(s),!1}let m=new v(BX24.callBatch),u;o&&(u=this.logger.start({type:"batch",data:{commandList:e,updateList:o}})),A&&console.warn("limitCommandSerial is deprecated and not used in current Batch implementation");try{let s=await m.batch(e,r,h);if(Object.keys(m.errors).length){if(i&&i(m.errors),u)try{await this.logger.stop({key:u,status:"fail",errorList:m.errors})}catch(d){console.error("Logger error:",d)}}else if(u)try{await this.logger.stop({key:u,status:"success"})}catch(d){console.error("Logger error:",d)}return s}catch(s){if(u)try{await this.logger.stop({key:u,status:"fail-runtime",errorList:{0:s==null?void 0:s.toString()}})}catch(d){console.error("Logger error:",d)}return console.error(s),!1}}async batchTotalCount(e,r,{errorCall:i,updateList:A,limitCall:o}={}){if(typeof BX24>"u"||!BX24.callBatch){const u=new Error("BX24 is not initialized");return console.error(u),!1}let h=new v(BX24.callBatch),m;A&&(m=this.logger.start({type:"batch-total-count",data:{commandList:e}}));try{let u=await h.batchTotalCount(e,r,o);if(Object.keys(h.errors).length){if(i&&i(h.errors),m)try{await this.logger.stop({key:m,status:"fail",errorList:h.errors})}catch(s){console.error("Logger error:",s)}}else if(m)try{await this.logger.stop({key:m,status:"success"})}catch(s){console.error("Logger error:",s)}return u}catch(u){if(m)try{await this.logger.stop({key:m,status:"fail-runtime",errorList:{0:u==null?void 0:u.toString()}})}catch(s){console.error("Logger error:",s)}return console.error(u),!1}}async getPlacement(){return await this.call({method:"placement.get"}).then(e=>(this.placeData||(this.placeData=e),e))}async placementBind(e,r=!0){var d;if(!this.isAdmin)return;r&&await this.placementCheck();let i=[];if(Array.isArray(e)?i=e.map(g=>typeof g=="string"?{placement:g}:g):typeof e=="string"?i=[{placement:e}]:i=[e],this.placeData=await this.getPlacement(),!this.placeData)return;const{appName:A,pathApp:o}=this.appConst;let h=A;this.domain==="szdl.bitrix24.ru"&&((d=this.appInfo)!=null&&d.ID)&&(h=`${A}: #${this.appInfo.ID}`);const m=h.replace(" CRM",""),u={},s=[];for(let g=0;g<i.length;g++){const a=i[g],c=a.placement,y=a.userId;let O=o,L=c;if(c==="PAGE_BACKGROUND_WORKER"){if(!y){console.warn(`placementBind: userId is required for PAGE_BACKGROUND_WORKER, skipping ${c}`);continue}O=`${o}?USER_ID=${y}/`}if(c==="PAGE_BACKGROUND_WORKER_ALL"&&(L="PAGE_BACKGROUND_WORKER"),this.placeData.find(k=>k.placement===L&&k.handler===O))continue;let x=this.placeData.find(k=>k.placement===L&&k.handler!==O);x&&s.push({placement:L,handler:x.handler});const U={PLACEMENT:L,HANDLER:O,LANG_ALL:{ru:{TITLE:L==="USER_PROFILE_TOOLBAR"?m:h}},OPTIONS:{errorHandlerUrl:O}};c==="PAGE_BACKGROUND_WORKER"&&y&&(U.USER_ID=y),u[`bind_${g}`]={method:"placement.bind",params:U}}s.length>0&&await this.placementUnBind(s),Object.keys(u).length>0&&await this.batch(u),Object.keys(u).length>0&&(this.placeData=await this.getPlacement(),Object.values(u).forEach(g=>{console.log("Приложение успешно встроено в",g.params.PLACEMENT)}))}async placementUnBind(e){let r=[];Array.isArray(e)?r=e.map(A=>typeof A=="string"?{placement:A}:A):typeof e=="string"?r=[{placement:e}]:r=[e];const i={};for(let A=0;A<r.length;A++){const o=r[A],h=o.placement,m=o.handler,u={PLACEMENT:h};m&&(u.HANDLER=m),i[`unbind_${A}`]={method:"placement.unbind",params:u}}Object.keys(i).length>0&&(await this.batch(i),r.forEach(A=>{console.log("Встройка отвязана",A.placement)}))}async placementCheck(){if(this.placeData=await this.getPlacement(),!this.placeData)return;const{pathApp:e}=this.appConst,r=[],i=[];for(const A of this.placeData){if(!A.handler||A.handler.includes(e))continue;const{placement:o,handler:h,userId:m}=A;r.push({placement:o,handler:h}),i.push({placement:o,userId:m})}r.length>0&&await this.placementUnBind(r),i.length>0&&await this.placementBind(i,!1)}getBotList(){return this.call({method:"imbot.bot.list",params:{}}).then(e=>{let r=Object.values(e);return console.log("chat-bot list:",r),r})}regBot({code:e,type:r,name:i}){const{appName:A,pathApp:o,chatBotLogo:h}=this.appConst,m=this.appInfo.ID;return this.call({method:"imbot.register",params:{CODE:e??this.appInfo.CODE,TYPE:r??"O",EVENT_HANDLER:o,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${i??A} - бот #${m}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:rt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:h??""}}}).then(u=>(console.log("Чат-бот добавлен",u),u))}unRegBot(e){return this.call({method:"imbot.unregister",params:{BOT_ID:e}}).then(r=>(console.log("чат-бот удален",r),r))}getLoggerList(e){return this.logger.getEntityList(e)}}ht=new WeakSet,yt=function(){return this.call({method:"app.info"})},lt=new WeakSet,Et=function(){return this.call({method:"user.current"})};class Lt{constructor(e){M(this,"entityName","tabs");M(this,"maxTabs",5);M(this,"interval");M(this,"id",0);M(this,"tabList",[]);M(this,"random",this.getRandomNum());M(this,"continueCondition");M(this,"defaultContinueBackground",()=>!0);M(this,"activeMaxPause",60*1e3*5+this.random);M(this,"activeMinPause",60*1e3*3+this.random);if(!e){console.error("В бек-воркер не переданы настройки, отмена вызова"),console.log("BackgroundWorker: Отмена конструктора - отсутствуют опции");return}const{appFunc:r,bx:i,users:A,continueBackground:o}=e;this.bx=i,this.appPath=i.appConst.pathApp??"",this.appName=i.appConst.appName??"",this.appInit=r,this.users=A,this.start=new Date,this.continueCondition=typeof o=="function"?o:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("Функция-запуск не передана в appInit, отмена инициализации бекворкера"),console.log("BackgroundWorker: Отмена init - не передана appInit");return}if(!this.bx){console.error("Не передан экземпляр bxBoot"),console.log("BackgroundWorker: Отмена init - отсутствует bx");return}if(await this.bx.placementBind(["PAGE_BACKGROUND_WORKER"]),!await this.continueBackground()){console.log("BackgroundWorker: Отмена init - условие запуска не выполнено");return}await this.checkEntity(),this.tabList=await this.getFilteredTabList(),this.id=await this.addTab(),console.log("tabId",this.id),this.interval=setInterval(()=>{this.backgroundPolling().catch(e=>{console.error("BackgroundWorker: backgroundPolling failed",e)})},this.activeMinPause)}async checkEntity(){var i;const e=await this.bx.call({method:"entity.get"});((i=e==null?void 0:e.find)==null?void 0:i.call(e,A=>A.ENTITY===this.entityName))||await this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}})}async getTabs(){var r;const e=await this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:(r=this.bx.userInfo)==null?void 0:r.ID},SORT:{DATE_CREATE:"DESC"}}});return e!=null&&e.length?e.map(i=>{if(!i)return{id:void 0,data:void 0};try{return{id:i.ID,data:{...JSON.parse(i.DETAIL_TEXT)}}}catch(A){return console.log(A),{id:i.ID,data:void 0}}}):[]}async addTab(){var r;const e={lastActive:new Date().toISOString(),duration:new Date().getTime()-this.start.getTime(),start:!1};return this.tabList.length<this.maxTabs&&await this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(e)}})||0}async updateTab(e){var i;const r={lastActive:new Date().toISOString(),duration:new Date().getTime()-this.start.getTime(),start:e};await this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(i=this.bx.userInfo)==null?void 0:i.ID,DETAIL_TEXT:JSON.stringify(r)}})}async deleteTabs(e=[]){if(!e.length)return;const r=e.map(i=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:i.id}}));r.length&&await this.bx.batch(r)}getRandomNum(){const e=Math.round(Number(Math.random().toFixed(2))*30);return Math.round(Math.random())?e:-e}async continueBackground(){try{const r=!!await Promise.resolve(this.continueCondition(this));return console.log(r?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: Отмена continueBackground - внешнее условие вернуло false"),r}catch(e){return console.error("BackgroundWorker: Ошибка при выполнении условия продолжения",e),console.log("BackgroundWorker: Отмена continueBackground - исключение в условии запуска"),!1}}async getFilteredTabList(){const e=[],r=[],i=await this.getTabs();for(const A of i){if(!(A!=null&&A.data)){e.push(A);continue}new Date().getTime()-new Date(A.data.lastActive).getTime()>this.activeMaxPause?e.push(A):r.push(A)}return await this.deleteTabs(e),r}async backgroundPolling(){if(!await this.continueBackground()){this.interval&&(clearInterval(this.interval),this.interval=void 0),console.log("BackgroundWorker: Остановка backgroundPolling - условие continueBackground не выполнено");return}if(this.tabList=await this.getFilteredTabList(),!this.id){this.id=await this.addTab();return}let e=this.checkOtherTabs();e&&(await this.pause(Math.round(Number(Math.random().toFixed(2))*1e4)),this.tabList=await this.getFilteredTabList(),e=this.checkOtherTabs(),e&&await this.startBackground())}checkOtherTabs(){var A,o;let e=!1,r=new Date().getTime()-new Date(this.start).getTime();for(const h of this.tabList)if(+h.id!==this.id&&((A=h.data)!=null&&A.start&&(e=!0),((o=h.data)==null?void 0:o.duration)>r)){r=!1;break}const i=!e&&!!r;return this.updateTab(i).catch(h=>{console.error("BackgroundWorker: updateTab failed",h)}),console.log(`BackgroundWorker: Проверка вкладок - можно запускать приложение? ${i}`),i}async startBackground(){this.interval&&(clearInterval(this.interval),this.interval=void 0),this.interval=setInterval(()=>{this.updateTab(!0).catch(e=>{console.error("BackgroundWorker: periodic updateTab failed",e)})},this.activeMinPause),await this.appInit(),this.interval&&(clearInterval(this.interval),this.interval=void 0),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)}async setBackgroundWorkerAll(){var d,g;if(!((d=this.bx)!=null&&d.isAdmin)){console.log("BackgroundWorker: Отмена setBackgroundWorkerAll - пользователь не админ");return}(g=this.users)!=null&&g.length||await this.getEntityData();const e=await this.bx.getPlacement(),r=new Map;let i=null;e.forEach(a=>{a.placement==="PAGE_BACKGROUND_WORKER"&&(a.userId?r.set(+a.userId,a):i=a)}),console.log(`setBackgroundWorkerAll: Найдено ${r.size} индивидуальных и ${i?1:0} общих привязок PAGE_BACKGROUND_WORKER`);const A=await this.getAdminsList(),o=await this.getEligibleUsersForBackgroundWorker(A);o.sort((a,c)=>{const y=a.LAST_LOGIN?new Date(a.LAST_LOGIN):new Date(0);return(c.LAST_LOGIN?new Date(c.LAST_LOGIN):new Date(0))-y}),console.log(`setBackgroundWorkerAll: Найдено ${o.length} подходящих пользователей (админы и руководители)`);const h=[];!i&&this.appPath&&(h.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}/`}}}),console.log("setBackgroundWorkerAll: Добавлен в очередь создание общего бэк-воркера"));const m=10,u=o.slice(0,m),s=[];for(const[a]of r)o.find(y=>+y.ID===a)||s.push(a);for(const a of s)this.appPath&&(h.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${a}/`}}),console.log(`setBackgroundWorkerAll: Добавлена в очередь отвязка бэк-воркера от пользователя ${a}`));for(const a of u)r.has(+a.ID)||!this.appPath||h.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${a.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}?USER_ID=${a.ID}/`},USER_ID:a.ID}});h.length?(console.log(`setBackgroundWorkerAll: Выполняем ${h.length} операций через batch`),await this.bx.batch(h),console.log("setBackgroundWorkerAll: Все операции batch выполнены успешно")):console.log("setBackgroundWorkerAll: Нет операций для выполнения")}async getEligibleUsersForBackgroundWorker(e=[]){return(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0).filter(i=>{const A=+i.ID;return e.includes(A)})}async updateAdminsList(){var e,r,i;try{const A=BX24.appOption.get("adminsList");let o=[];if(A)try{o=JSON.parse(A)}catch{console.log("updateAdminsList: Ошибка парсинга существующего списка админов, создаем новый"),o=[]}const h=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0);(r=this.bx)!=null&&r.isAdmin&&h&&!o.includes(h)&&(o.push(h),console.log(`updateAdminsList: Добавлен новый админ ${h}`)),!((i=this.bx)!=null&&i.isAdmin)&&h&&o.includes(h)&&(o=o.filter(s=>s!==h),console.log(`updateAdminsList: Удален из списка админов пользователь ${h} (больше не админ)`));const m=new Set((this.users??[]).filter(s=>s.ACTIVE==="Y"||s.ACTIVE===!0).map(s=>+s.ID)),u=o.filter(s=>m.has(s));return u.length!==o.length&&(console.log(`updateAdminsList: Удалено ${o.length-u.length} неактивных админов`),o=u),BX24.appOption.set("adminsList",JSON.stringify(o)),console.log(`BackgroundWorker: Список админов обновлен: ${o.length} админов`),o}catch(A){return console.error("BackgroundWorker: Ошибка при обновлении списка админов:",A),[]}}async getAdminsList(){try{const e=BX24.appOption.get("adminsList");return e?JSON.parse(e):[]}catch(e){return console.error("getAdminsList: Ошибка при получении списка админов:",e),[]}}async getEntityData(){const e={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:r}=await this.bx.batch(e).then(i=>i?(Array.isArray(i.users)||(i.users=[]),i):{users:[]});this.users=r}pause(e=500,r){return new Promise(i=>{setTimeout(()=>{r&&r(),i(!0)},e)})}}N.BackgroundWorker=Lt,N.Batch=v,N.BxBoot=Rt,N.BxHelper=ut,N.BxLogger=gt,N.tempus=rt,Object.defineProperty(N,Symbol.toStringTag,{value:"Module"})});
|