szdl-utils-kit 0.3.10 → 0.3.13
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 +3 -3
- package/dist/index.js +1262 -1040
- package/dist/index.umd.cjs +2 -2
- package/package.json +41 -41
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var It=Object.defineProperty;var
|
|
2
|
-
https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):n(JSON.parse(m.responseText))):f&&f(m))},m.open("GET",t,!1),m.send()},I={"%d":{format:function(t){return o(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 o(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 o(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 X[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 F[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 H[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 o(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 o(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 o(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 o(t.year()||s.MIN_YEAR,4)+"-"+o(t.month()||s.MIN_MONTH,2)+"-"+o(t.day()||s.MIN_DAY,2)},parse:function(t){var n=Number(t.slice(0,4)),f=Number(t.slice(5,7)),m=Number(t.slice(8,10));return{year:n,month:f,day:m}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return o(t.month()||s.MIN_MONTH,2)+"/"+o(t.day()||s.MIN_DAY,2)+"/"+o(t.year()||s.MIN_YEAR,4)},parse:function(t){var n=Number(t.slice(0,2)),f=Number(t.slice(3,5)),m=Number(t.slice(6,10));return{year:m,month:n,day:f}},minLength:10,maxLength:10,type:"string"}},ut={useMilliseconds:!1,monthFromZero:!1},R;R=function(t,n,f){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,f),this},R.fn=R.prototype,R.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},R.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},R.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},R.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},R.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},R.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},R.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},R.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},R.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)},R.fn.set=function(t,n,f){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 m,M=[],_,L,z=[],G=0,W=0,B,J,U={},Y;if(t===r)return _=a(this,f),_===r&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),_;for(n===r&&(n=s.detectFormat(t));G<n.length;){if(n.charAt(G)==="%"){if(L=n.charAt(G)+n.charAt(G+1),I[L]!==r){switch(B=0,J="",I[L].type){case"number":for(;B<I[L].maxLength&&W+B<t.length&&!isNaN(Number(t.charAt(W+B)));)J+=t.charAt(W+B),B+=1;break;case"word":for(;B<I[L].maxLength&&W+B<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(W+B));)J+=t.charAt(W+B),B+=1;break;case"string":for(;B<I[L].maxLength&&W+B<t.length;)J+=t.charAt(W+B),B+=1;break}if(B<I[L].minLength)return _=a(this,f),_===r&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),_;M.push(L),z.push(J),B-=1,W+=B,G+=1}}else if(t.charAt(W)!==n.charAt(G))return _=a(this,f),_===r&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),_;G+=1,W+=1}for(m in M)M.hasOwnProperty(m)&&I.hasOwnProperty(M[m])&&(Y=I[M[m]].parse(z[m]),U={year:Y.year!==r?Y.year:U.year,month:Y.month!==r?Y.month:U.month,day:Y.day!==r?Y.day:U.day,hours:Y.hours!==r?Y.hours:U.hours,minutes:Y.minutes!==r?Y.minutes:U.minutes,seconds:Y.seconds!==r?Y.seconds:U.seconds});this.day(s.MIN_DAY),this.year(U.year),this.month(U.month),this.day(U.day),this.hours(U.hours),this.minutes(U.minutes),this.seconds(U.seconds),this.milliseconds(U.milliseconds)}return this},R.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},R.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},R.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)},R.fn.dayOfWeek=function(t){if(t==="long")return X[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()})},R.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}},R.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()}}},R.fn.format=function(t){for(var n=0,f="",m;n<t.length;)t.charAt(n)==="%"?(m=t.charAt(n)+t.charAt(n+1),I[m]!==r?(f+=I[m].format(this),n+=1):f+="%"):f+=t.charAt(n),n+=1;return f},R.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},R.fn.errors=function(){return this._i},R.fn.between=function(t,n){var f=this.timestamp(),m=t.timestamp();switch(n){case"year":return Math.floor((m-f)/31556952);case"month":return Math.floor((m-f)/2629746);case"day":return Math.floor((m-f)/86400);case"hours":return Math.floor((m-f)/3600);case"minutes":return Math.floor((m-f)/60);case"seconds":return m-f;default:return r}},R.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,f){return new R(t,n,f)},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 ut;if(ut.hasOwnProperty(t)){if(n===r)return ut[t];ut[t]=n,t==="monthFromZero"&&(s.MIN_MONTH=n?0:1,s.MAX_MONTH=n?11:12)}return r},s.noConflict=function(){return i.tempus=c,s},s.generate=function(t){var n,f,m,M,_,L,z,G;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof R?n=t.dateFrom.utc():n=s(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof R?f=t.dateTo.utc():f=s(t.dateTo,t.formatTo!==r?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?_={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?_={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"&&(_={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?L=t.asObject===!0?{}:[]:(L=[],L.push([]),z=s(n).get()[t.groupBy]),G=function(J,U,Y){return t.asObject===!0?t.format!==r?J[s(U).format(t.format)]={}:J[s(U).format("%F %H:%M:%S")]={}:t.format!==r?J.push(Y?null:s(U).format(t.format)):J.push(Y?null:s(U)),J},t.groupBy!==r&&t.fillNulls){var W={year:_.year?-_.year:r,month:_.month?-_.month:r,day:_.day?-_.day:r,hours:_.hours?-_.hours:r,minutes:_.minutes?-_.minutes:r,seconds:_.seconds?-_.seconds:r,milliseconds:_.milliseconds?-_.milliseconds:r};for(m=s(n).calc(W).utc();s(m).get()[t.groupBy]===z;)G(L[L.length-1],m,!0),m=s(m).calc(W).utc();if(t.groupBy==="week"){var B=s(n).dayOfWeek();for(m=s(n).dayOfWeek(0).utc();L[0].length<B&&m<n;)G(L[L.length-1],m,!0),m=s(m).calc(_).utc()}}for(;n<=f;)t.groupBy===r?G(L,n):s(n).get()[t.groupBy]===z?G(L[L.length-1],n):(L.push([]),G(L[L.length-1],n),z=s(n).get()[t.groupBy]),n=s(n).calc(_).utc();if(t.groupBy!==r&&t.fillNulls)for(M=s(f).calc(_).utc();s(M).get()[t.groupBy]===z;)G(L[L.length-1],M,!0),M=s(M).calc(_).utc();return L},s.monthNames=function(t){switch(t){case"long":return H;default:return F}},s.dayNames=function(t){switch(t){case"long":return X;default:return b}},s.lang=function(t){if(t!==r)A=t,l[A]===r&&(A="en"),H=N(),F=O(),X=p(),b=S();else return A;return r},s.availableLangs=function(){return Object.keys(l)},s.registerFormat=function(t,n,f,m,M,_){I[t]={format:n,parse:f,minLength:m,maxLength:M,type:_}},s.unregisterFormat=function(t){delete I[t]},s.detectFormat=function(t){var n,f,m;return n=u(t,0),n!==""&&(m=10),f=t.charAt(m),(f==="T"||f===" ")&&(n+=f,m+=1),n+=h(t,m),n},d={TempusDate:R},s.classes=function(t,n){if(n===r)return d[t];d[t]=n},s.loadTranslations=function(t){typeof t=="object"?l=t:typeof t=="string"&&w(t,function(n){l=n},function(n){})},A=(g.language||g.systemLanguage||g.userLanguage||"en").substr(0,2).toLowerCase(),l[A]===r&&(A="en"),H=N(),F=O(),X=p(),b=S(),x.exports&&(e=x.exports=s),e.tempus=s}).call(T)})(tt,tt.exports);var Lt=tt.exports;const st=D(Lt);class K{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(o=>{const{total:a,count:h}=o;r+=a??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 o=this.getData(r.data()),a=Array.isArray(o)?o.length:0;let h=r.total()||a;i==="count"&&(h=a);let u=1;o&&(u=a),this.progressCall&&(this.progressData||(this.progressData={}),this.progressData[e]&&this.progressData[e].count&&(u+=this.progressData[e].count),this.progressData[e]?this.progressData[e].count=u:this.progressData[e]={total:h,count:u},this.progressTimer||(this.progressTimer=setInterval(()=>{const{percent:c,allCount:s,allTotal:d}=this.progressPercent;(this.oldPercent==="no"||this.oldPercent<this.progressPercent.percent)&&(this.progressCall({data:this.progressData,percent:c,allCount:s,allTotal:d}),this.oldPercent=this.progressPercent.percent),c>=100&&this.clearProgressData()},this.progressDelay)))}delay(){return new Promise(e=>setTimeout(e,500))}callBatchWithTimeout(e,r){return new Promise((i,o)=>{let a=!1;const h=6e4;let u=!1,c=!1,s=!1,d=null,g=null;const A=async(O,p)=>{if(!a){a=!0,d&&clearTimeout(d),g&&clearTimeout(g);try{await Promise.resolve(r(O)),i()}catch(S){console.error(`Error in callBatch callback (attempt ${p}):`,S),o(S)}}},l=async()=>{if(!a){a=!0,d&&clearTimeout(d),g&&clearTimeout(g),console.warn(`Batch request timeout after ${h}ms on both attempts. This may indicate a CORS or network error.`);const O={};Object.keys(e).forEach(p=>{O[p]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 30 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(r(O)),i()}catch(p){console.error("Error in timeout callback:",p),i()}}},N=O=>{try{this.callBatch(e,async p=>{O===1&&!u&&!a?(u=!0,await A(p,1)):O===2&&!s&&!a&&(s=!0,await A(p,2))})}catch(p){a||console.error(`Error calling callBatch (attempt ${O}):`,p)}};N(1),d=setTimeout(async()=>{!u&&!a&&!c&&(console.warn(`First batch request attempt timeout after ${h}ms. Starting second attempt...`),c=!0,N(2),g=setTimeout(async()=>{!u&&!s&&!a&&await l()},h))},h)})}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 o={};this.chunkRate=(1/Math.ceil(Object.keys(e).length/this.limit)).toFixed(5);let a={},h=0;for(const[u,c]of Object.entries(e)){if(!this.canContinue)break;const s=this.arrayChunk(c);if(!s){h++;continue}a[u]=s,(Object.keys(a).length>=50||h+1===Object.keys(e).length)&&(await this.batchChunk(a),Object.entries(this.result).forEach(([d,g])=>{o[d]=g}),this.totalProgress=Math.round(h/Object.keys(e).length*100),a={}),h++}return Object.entries(this.errors).length&&(o.errorsList=this.errors),r&&r({percent:100}),Promise.resolve(o)}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 o={};this.chunkRate=(1/Math.ceil(Object.keys(e).length/this.limit)).toFixed(5);let a={},h=0;for(const[u,c]of Object.entries(e)){if(!this.canContinue)break;const s=this.arrayChunk(c);if(!s){h++;continue}a[u]=s,(Object.keys(a).length>=50||h+1===Object.keys(e).length)&&(await this.batchChunk(a,"count"),Object.entries(this.result).forEach(([d,g])=>{o[d]=g}),this.totalProgress=Math.round(h/Object.keys(e).length*100),a={}),h++}return Object.entries(this.errors).length&&(o.errorsList=this.errors),r&&r({percent:100}),Promise.resolve(o)}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 o=r==="user.get"?i.FILTER:i.filter;typeof o=="object"&&o!==null&&!Array.isArray(o)&&Object.entries(o).forEach(([a,h])=>{(i.start===void 0||i.start!==-1)&&["id","ID"].includes(a)&&(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[o,a,h,u]=i;o.ID="ASC",u[0]!==""&&u.includes("ID")||u.push("ID")}return{method:r,params:i}}async batchChunk(e,r){return new Promise(i=>{const o=[];let a;this.callBatchWithTimeout(e,async h=>{var u,c,s,d,g,A,l;for(const[N,O]of Object.entries(h)){if(!this.canContinue)return;if(O.error())switch(this.errors[N]=((c=(u=O.error())==null?void 0:u.ex)==null?void 0:c.error)??((d=(s=O.error())==null?void 0:s.ex)==null?void 0:d.error_description)??((g=O.error())==null?void 0:g.toString())??"Неизвестная ошибка",a=!0,((l=(A=O.error())==null?void 0:A.ex)==null?void 0:l.error)??""){case"OPERATION_TIME_LIMIT":this.skipList.add(e[N].method),this.limitCall&&this.limitCall(N);break;case"ACCESS_DENIED":this.skipList.add(e[N].method);break;case"TIMEOUT":let w=e[N],I="";Array.isArray(w)?[I]=w:w!=null&&w.method&&(I=w.method),I&&this.skipList.add(I),this.limitCall&&this.limitCall(N);break}const p=this.getData(O.data()),S=Array.isArray(p)?p.length:0,H=typeof O.total=="function"&&O.total()!==void 0,F=H?O.total():S;r==="count"?this.result[N]?this.result[N]+=S:this.result[N]=F:this.result[N]=p,this.setProgressData({key:N,value:O,type:r});const X=r==="count"?!H&&S===this.limit:F>this.limit&&F>S;if(!this.canContinue||X){let b=e[N];if(Array.isArray(b)){const[w,I={}]=b;b=[w,I]}else{const{method:w,params:I={}}=b;b=[w,I]}o.push([N,b,F])}}a>0&&this.errorLogger(),o.length?await this.batchPayload(o,r).then(()=>i(this.result)):i(this.result)})})}async batchPayload(e,r){const i=new Map,o=(c,s,d,g)=>{let A="ID";this.result[c][this.result[c].length-1].ID||(A="id");let l=`${A}`;if(JSON.stringify(g[1]).toLocaleLowerCase().includes('"id":"desc"')?l="<"+l:l=">"+l,s===1||d.length===0)return{field:l,id:this.result[c][this.result[c].length-1][A]};let O="";const[p,S]=g;return(p==="tasks.task.list"||p==="task.item.list")&&(O="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(p)&&(O="[items]"),p==="crm.type.list"&&(O="[types]"),p==="socialnetwork.api.workgroup.list"&&(O="[workgroups]"),{field:l,id:`$result[${[c,s-1].join("__")}]${O}[49][${A}]`}},a=(c,s)=>{const[d,g]=c;let A=JSON.parse(JSON.stringify(g)),l;if(d==="task.item.list"){A=[...A];const[N,O,p,S]=A;return O[s.field]=s.id,[d,A]}return["user.get"].includes(d)||A.FILTER?(A.FILTER||(A.FILTER={}),l=A.FILTER):(A.filter||(A.filter={}),l=A.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(d)?l[">ID"]=s.id:l[s.field]=s.id,[d,{...A,start:-1}]},h=c=>{Object.entries(c).forEach(([s,d])=>{var l,N,O,p,S,H,F;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]=((N=(l=d.error())==null?void 0:l.ex)==null?void 0:N.error)??((p=(O=d.error())==null?void 0:O.ex)==null?void 0:p.error_description)??((S=d.error())==null?void 0:S.toString())??"Неизвестная ошибка";const X=((F=(H=d.error())==null?void 0:H.ex)==null?void 0:F.error)??"",b=i.get(g);switch(X){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":b&&this.skipList.add(b);break;case"TIMEOUT":b&&(this.skipList.add(b),this.limitCall&&this.limitCall(g));break}}this.setProgressData({key:g,value:d,type:r})})};let u=[];for await(const[c,s,d]of e){if(!this.canContinue)return;const[g]=s;if(i.set(c,g),this.skipList.has(g))continue;let A=1;for(;d>A*50&&!this.skipList.has(g);){const l=[c,A].join("__"),N=o(c,A,u,s);u.push([l,a(s,N)]),u.length%50===0&&(await this.callBatchWithTimeout(Object.fromEntries(u),O=>{h(O)}),u=[],await this.delay()),A++}}u.length&&(await this.callBatchWithTimeout(Object.fromEntries(u),c=>{h(c)}),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 ft{constructor(){C(this,V,{})}get hash(){return this.createHash(8)}createHash(e){let r="abcdefghijklmnopqrstuvwxyz0123456789",i="";e=e||6;for(let o=0;o<e;o++)i+=r.charAt(Math.floor(Math.random()*r.length));return i}actionFilter({keyTimer:e,duration:r=10,action:i}){E(this,V)[e]&&(clearTimeout(E(this,V)[e]),E(this,V)[e]=null),i&&(E(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,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(e,r){let i=new Blob([JSON.stringify(e)],{type:"application/json"}),o=URL.createObjectURL(i),a=document.createElement("a");a.style.display="none",a.href=o,a.download=`${r}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(o)},200)}}V=new WeakMap;const mt=new ft;class Ot{constructor(){C(this,ot);C(this,it);C(this,at);C(this,At);C(this,lt);C(this,Q,"logger");C(this,Z,!1);C(this,q,new Map);C(this,et,{});C(this,P,null);C(this,$,!1);C(this,rt,!1);k(this,"periodClear",3);v(this,ot,pt).call(this)}async init(){try{let e=new K(BX24.callBatch),{entityList:r}=await e.batch({entityList:{method:"entity.get"}});if(r&&Array.isArray(r))if(r.find(o=>o.ENTITY==E(this,Q)))j(this,Z,!0);else{let{entityAdd:o}=await e.batch({entityAdd:{method:"entity.add",params:{ENTITY:E(this,Q),NAME:E(this,Q),ACCESS:{AU:"X"}}}});o&&j(this,Z,!0)}return v(this,At,_t).call(this).catch(i=>{console.error("Ошибка при проверке периода очистки:",i)}),E(this,Z)}catch(e){return console.error("Ошибка при инициализации логера:",e),!1}}start({type:e,data:r}){if(!E(this,Z))return v(this,it,gt).call(this,"entity"),null;if(!e||!r)return console.error("Невалидные данные для логирования:",{type:e,data:r}),null;const i=mt.hash,o={type:e,data:r,userInfo:E(this,et),errorList:{},status:"",answer:null,date:new Date().getTime()};return E(this,q).set(i,o),j(this,rt,!0),i}async stop({key:e,errorList:r,status:i,answer:o}){var h;if(!E(this,rt))return;if(!E(this,Z)){v(this,it,gt).call(this,"entity");return}let a=E(this,q).get(e);if(!a){console.error(`Не найдены данные логирования для ключа: ${e}`);return}r&&(a.errorList=r),i&&(a.status=i),o&&(a.answer=o),await v(this,at,yt).call(this),(h=a==null?void 0:a.data)!=null&&h.updateList&&j(this,$,!0),j(this,rt,!1)}async getEntityList(e){var r;try{if((r=E(this,P))!=null&&r.length&&!E(this,$))return E(this,P);let i=new K(BX24.callBatch),{entityList:o}=await i.batch({entityList:{method:"entity.item.get",params:{ENTITY:E(this,Q),SORT:{ID:"DESC"}}}},e);return!o||!Array.isArray(o)?(console.warn("Получен невалидный список записей"),[]):(o=o.map(a=>{try{const{ID:h,DATE_CREATE:u,DETAIL_TEXT:c}=a;return{...JSON.parse(c),id:h,dateCreate:u}}catch(h){return console.error(`Ошибка парсинга записи ${a.ID}:`,h),null}}).filter(a=>a!==null),j(this,$,!1),j(this,P,o),o)}catch(i){return console.error("Ошибка при получении списка записей:",i),[]}}async downAllEntityJson(){try{if(E(this,P)||await this.getEntityList(),!E(this,P)||E(this,P).length===0)return console.warn("Нет данных для выгрузки"),!1;let e=st().format("%Y-%m-%d");return mt.downloadFileJson(E(this,P),`sdklogger-entity-data__${e}`),!0}catch(e){return console.error("Ошибка при выгрузке данных в JSON:",e),!1}}}Q=new WeakMap,Z=new WeakMap,q=new WeakMap,et=new WeakMap,P=new WeakMap,$=new WeakMap,rt=new WeakMap,ot=new WeakSet,pt=async function(){try{const e=new K(BX24.callBatch),r=BX24.isAdmin(),{curUser:i}=await e.batch({curUser:{method:"user.current"}});j(this,et,{isAdmin:r,curUser:i})}catch(e){console.error("Ошибка при получении информации о пользователе:",e),j(this,et,{isAdmin:!1,curUser:null})}},it=new WeakSet,gt=function(e){e=="entity"&&mt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},at=new WeakSet,yt=async function(){try{let e={},r=new K(BX24.callBatch);for(let[i,o]of E(this,q).entries())if(o.status){const a=JSON.stringify(o);e[i]={method:"entity.item.add",params:{ENTITY:E(this,Q),NAME:E(this,Q),DETAIL_TEXT:a}}}if(Object.keys(e).length){let i=await r.batch(e),{errors:o}=r;for(let[a,h]of Object.entries({...i,...o}))E(this,q).delete(a);return!0}return!1}catch(e){return console.error("Ошибка при добавлении записей в хранилище:",e),!1}},At=new WeakSet,_t=async function(){try{let e=new K(BX24.callBatch),{serverTime:r}=await e.batch({serverTime:{method:"server.time"}});if(!r){console.error("Не удалось получить время сервера");return}if(E(this,P)||await this.getEntityList(),!E(this,P)||E(this,P).length===0)return;let i=E(this,P).filter(o=>{try{let{dateCreate:a}=o;return a?st(new Date(a)).between(st(new Date(r)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});i.length>0&&(console.log(`Найдено ${i.length} записей для очистки (старше ${this.periodClear} месяцев)`),await v(this,lt,Et).call(this,i))}catch(e){console.error("Ошибка при проверке периода очистки:",e)}},lt=new WeakSet,Et=async function(e){try{if(!e||e.length===0)return!1;let r=new K(BX24.callBatch),i=e.filter(a=>a&&a.id).map(a=>{let{id:h}=a;return{method:"entity.item.delete",params:{ENTITY:E(this,Q),ID:h}}});if(i.length===0)return!1;const o=await r.batch(i);return console.log(`Успешно удалено ${i.length} записей`),j(this,$,!0),o}catch(r){return console.error("Ошибка при очистке устаревших записей:",r),!1}};class bt{constructor(e){C(this,ct);C(this,ht);C(this,nt);k(this,"domain","");k(this,"isAdmin",!1);k(this,"appInfo",null);k(this,"appConst",null);k(this,"userInfo",null);k(this,"placeData",null);k(this,"placeInfo",null);k(this,"logger",!1);this.appConst=e}init(){return new Promise((e,r)=>{let o=setInterval(()=>{window.BX24&&BX24.init(async()=>{console.info("init BX24"),clearInterval(o),clearTimeout(a),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info(),this.logger?(this.logger=new Ot,await this.logger.init()):this.logger={start:()=>{},stop:()=>{},getEntityList:()=>{}};const[h,u]=await Promise.all([v(this,ct,Tt).call(this),v(this,ht,Rt).call(this)]);this.appInfo=h,this.userInfo=u;let c=new ft;try{c.noSleep()}catch(s){console.warn("Failed to initialize noSleep:",s)}e(!0)})},100);const a=setTimeout(()=>{clearInterval(o);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 o;if(i&&(o=this.logger.start({type:"call",data:{method:e,params:r,updateList:i}})),r||(r={}),typeof BX24>"u"||!BX24.callMethod){const a=new Error("BX24 is not initialized");throw console.error(a),a}return new Promise((a,h)=>{BX24.callMethod(e,r,async u=>{let c={};if(u!=null&&u.answer)for(let[s,d]of Object.entries(u.answer))s!=="result"&&d&&(c[s]=d);if(u.error()){let s=u.error();if(console.error(s),o)try{await this.logger.stop({answer:c,key:o,status:"fail",errorList:{0:s.toString()}})}catch(d){console.error("Logger error:",d)}a(!1)}else{let s=u.data();if(s!=null&&s.items&&(s=s.items),o)try{await this.logger.stop({answer:c,key:o,status:"success"})}catch(d){console.error("Logger error:",d)}a(s)}})})}async batch(e,r,{errorCall:i,limitCommandSerial:o,updateList:a,limitCall:h}={}){if(typeof BX24>"u"||!BX24.callBatch){const s=new Error("BX24 is not initialized");return console.error(s),!1}let u=new K(BX24.callBatch),c;a&&(c=this.logger.start({type:"batch",data:{commandList:e,updateList:a}})),o&&console.warn("limitCommandSerial is deprecated and not used in current Batch implementation");try{let s=await u.batch(e,r,h);const d=v(this,nt,Nt).call(this,u,s,e,a);if(Object.keys(d).length){if(i&&i(d),c)try{await this.logger.stop({key:c,status:"fail",errorList:d})}catch(g){console.error("Logger error:",g)}}else if(c)try{await this.logger.stop({key:c,status:"success"})}catch(g){console.error("Logger error:",g)}return s}catch(s){if(c)try{await this.logger.stop({key:c,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:o,limitCall:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const c=new Error("BX24 is not initialized");return console.error(c),!1}let h=new K(BX24.callBatch),u;o&&(u=this.logger.start({type:"batch-total-count",data:{commandList:e}}));try{let c=await h.batchTotalCount(e,r,a);const s=v(this,nt,Nt).call(this,h,c,e,o);if(Object.keys(s).length){if(i&&i(s),u)try{await this.logger.stop({key:u,status:"fail",errorList:s})}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 c}catch(c){if(u)try{await this.logger.stop({key:u,status:"fail-runtime",errorList:{0:c==null?void 0:c.toString()}})}catch(s){console.error("Logger error:",s)}return console.error(c),!1}}async getPlacement(){return await this.call({method:"placement.get"}).then(e=>(this.placeData||(this.placeData=e),e))}async placementBind(e,r=!0){var g,A;if(!this.isAdmin)return;r&&await this.placementCheck();let i=[];if(Array.isArray(e)?i=e.map(l=>typeof l=="string"?{placement:l}:l):typeof e=="string"?i=[{placement:e}]:i=[e],this.placeData=await this.getPlacement(),!this.placeData)return;const{appName:o,pathApp:a}=this.appConst;let h=o;this.domain==="szdl.bitrix24.ru"&&((g=this.appInfo)!=null&&g.ID)&&(h=`${o}: #${this.appInfo.ID}`);const u=h.replace(" CRM",""),c={},s=[];let d=!1;for(let l=0;l<i.length;l++)i[l].placement==="PAGE_BACKGROUND_WORKER_ALL"&&(d=!0);if(d&&((A=this.userInfo)!=null&&A.ID)){const l=this.userInfo.ID,N=`${a}?USER_ID=${l}/`;if(!this.placeData.find(p=>p.placement==="PAGE_BACKGROUND_WORKER"&&p.handler===N)){const p={PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:N,LANG_ALL:{ru:{TITLE:h}},OPTIONS:{errorHandlerUrl:N},USER_ID:l};c[`bind_user_${l}`]={method:"placement.bind",params:p},console.log(`placementBind: Добавлено индивидуальное размещение для пользователя ${l} перед общим`)}}for(let l=0;l<i.length;l++){const N=i[l],O=N.placement,p=N.userId;let S=a,H=O;if(O==="PAGE_BACKGROUND_WORKER"){if(!p){console.warn(`placementBind: userId is required for PAGE_BACKGROUND_WORKER, skipping ${O}`);continue}S=`${a}?USER_ID=${p}/`}if(O==="PAGE_BACKGROUND_WORKER_ALL"&&(H="PAGE_BACKGROUND_WORKER"),this.placeData.find(w=>w.placement===H&&w.handler===S))continue;let X=this.placeData.find(w=>w.placement===H&&w.handler!==S);X&&s.push({placement:H,handler:X.handler});const b={PLACEMENT:H,HANDLER:S,LANG_ALL:{ru:{TITLE:H==="USER_PROFILE_TOOLBAR"?u:h}},OPTIONS:{errorHandlerUrl:S}};O==="PAGE_BACKGROUND_WORKER"&&p&&(b.USER_ID=p),c[`bind_${l}`]={method:"placement.bind",params:b}}s.length>0&&await this.placementUnBind(s),Object.keys(c).length>0&&await this.batch(c),Object.keys(c).length>0&&(this.placeData=await this.getPlacement(),Object.values(c).forEach(l=>{console.log("Приложение успешно встроено в",l.params.PLACEMENT)}))}async placementUnBind(e){let r=[];Array.isArray(e)?r=e.map(o=>typeof o=="string"?{placement:o}:o):typeof e=="string"?r=[{placement:e}]:r=[e];const i={};for(let o=0;o<r.length;o++){const a=r[o],h=a.placement,u=a.handler,c={PLACEMENT:h};u&&(c.HANDLER=u),i[`unbind_${o}`]={method:"placement.unbind",params:c}}Object.keys(i).length>0&&(await this.batch(i),r.forEach(o=>{console.log("Встройка отвязана",o.placement)}))}async placementCheck(){if(this.placeData=await this.getPlacement(),!this.placeData)return;const{pathApp:e}=this.appConst,r=[],i=[];for(const o of this.placeData){if(!o.handler||o.handler.includes(e))continue;const{placement:a,handler:h,userId:u}=o;r.push({placement:a,handler:h}),i.push({placement:a,userId:u})}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:o,pathApp:a,chatBotLogo:h}=this.appConst,u=this.appInfo.ID;return this.call({method:"imbot.register",params:{CODE:e??this.appInfo.CODE,TYPE:r??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${i??o} - бот #${u}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:st().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:h??""}}}).then(c=>(console.log("Чат-бот добавлен",c),c))}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)}}ct=new WeakSet,Tt=function(){return this.call({method:"app.info"})},ht=new WeakSet,Rt=function(){return this.call({method:"user.current"})},nt=new WeakSet,Nt=function(e,r,i,o){let a={...e.errors};if(Object.values(e.errors).some(u=>{if(typeof u!="string")return!1;const c=u.toUpperCase();return c==="TIMEOUT"||c==="OPERATION_TIME_LIMIT"||c.includes("TIMEOUT")||c.includes("OPERATION_TIME_LIMIT")})&&o){const u=r?Object.keys(r).filter(g=>g!=="errorsList"):[],c=new Set(Object.keys(e.errors||{})),s=new Set;if(r){for(const g of u)if(!c.has(g)){const A=r[g];A!=null&&s.add(g)}}const d=Object.values(e.errors).find(g=>{if(typeof g!="string")return!1;const A=g.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const g of Object.keys(i))!s.has(g)&&!e.errors[g]&&(a[g]=d||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a};class St{constructor(e){k(this,"entityName","tabs");k(this,"maxTabs",5);k(this,"interval");k(this,"id",0);k(this,"tabList",[]);k(this,"random",this.getRandomNum());k(this,"continueCondition");k(this,"defaultContinueBackground",()=>!0);k(this,"activeMaxPause",60*1e3*5+this.random);k(this,"activeMinPause",60*1e3*3+this.random);if(!e){console.error("В бек-воркер не переданы настройки, отмена вызова"),console.log("BackgroundWorker: Отмена конструктора - отсутствуют опции");return}const{appFunc:r,bx:i,users:o,continueBackground:a}=e;this.bx=i,this.appPath=i.appConst.pathApp??"",this.appName=i.appConst.appName??"",this.appInit=r,this.users=o,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.checkPlacementType()){console.log("BackgroundWorker: Отмена init - общая встройка обнаружена при наличии индивидуальной");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,o=>o.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(o){return console.log(o),{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 checkPlacementType(){var e;try{const r=await this.bx.getPlacement();if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не удалось получить список размещений, продолжаем выполнение"),!0;const i=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0);if(!i)return console.log("BackgroundWorker: Не удалось определить ID текущего пользователя, продолжаем выполнение"),!0;const a=!!(typeof window<"u"?window.location.href:"").includes("USER_ID=");let h=!1;for(const u of r)if(u.placement==="PAGE_BACKGROUND_WORKER"&&(u.userId||u.handler&&u.handler.includes("USER_ID="))){const s=u.userId||(u.handler?this.extractUserIdFromHandler(u.handler):null);if(s&&+s===i){h=!0;break}}return a?(console.log("BackgroundWorker: Обнаружена индивидуальная встройка, продолжаем выполнение"),!0):!currentPlacementIsGeneral&&h?(console.log(`BackgroundWorker: Обнаружена общая встройка при наличии индивидуальной для текущего пользователя (ID: ${i}), прекращаем выполнение`),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем выполнение"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}extractUserIdFromHandler(e){if(!e||typeof e!="string")return null;const r=e.match(/USER_ID=(\d+)/);return r?r[1]:null}async continueBackground(){try{const r=!!await Promise.resolve(this.continueCondition(this));return console.log(r?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: Отмена continueBackground - внешнее условие вернуло false"),r}catch(e){return console.error("BackgroundWorker: Ошибка при выполнении условия продолжения",e),console.log("BackgroundWorker: Отмена continueBackground - исключение в условии запуска"),!1}}async getFilteredTabList(){const e=[],r=[],i=await this.getTabs();for(const o of i){if(!(o!=null&&o.data)){e.push(o);continue}new Date().getTime()-new Date(o.data.lastActive).getTime()>this.activeMaxPause?e.push(o):r.push(o)}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 o,a;let e=!1,r=new Date().getTime()-new Date(this.start).getTime();for(const h of this.tabList)if(+h.id!==this.id&&((o=h.data)!=null&&o.start&&(e=!0),((a=h.data)==null?void 0:a.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 A,l;if(!((A=this.bx)!=null&&A.isAdmin)){console.log("BackgroundWorker: Отмена setBackgroundWorkerAll - пользователь не админ");return}(l=this.users)!=null&&l.length||await this.getEntityData();const e=await this.bx.getPlacement(),r=new Map;let i=null;e.forEach(N=>{N.placement==="PAGE_BACKGROUND_WORKER"&&(N.userId?r.set(+N.userId,N):i=N)}),console.log(`setBackgroundWorkerAll: Найдено ${r.size} индивидуальных и ${i?1:0} общих привязок PAGE_BACKGROUND_WORKER`);const o=await this.updateAdminsList(),a=await this.getEligibleUsersForBackgroundWorker(o);a.sort((N,O)=>{const p=N.LAST_LOGIN?new Date(N.LAST_LOGIN):new Date(0);return(O.LAST_LOGIN?new Date(O.LAST_LOGIN):new Date(0))-p}),console.log(`setBackgroundWorkerAll: Найдено ${a.length} подходящих пользователей (админы и руководители)`);const h=[],u=10,s=a.slice(0,u).filter(N=>!r.has(+N.ID)),d=i&&s.length>0,g=[];for(const[N]of r)a.find(p=>+p.ID===N)||g.push(N);for(const N of g)this.appPath&&(h.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${N}/`}}),console.log(`setBackgroundWorkerAll: Добавлена в очередь отвязка бэк-воркера от пользователя ${N}`));d&&this.appPath&&(h.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:i.handler||`${this.appPath}/`}}),console.log("setBackgroundWorkerAll: Добавлена в очередь отвязка общего бэк-воркера (для создания индивидуальных)"));for(const N of s)this.appPath&&h.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${N.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}?USER_ID=${N.ID}/`},USER_ID:N.ID}});(!i||d)&&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: Добавлен в очередь создание общего бэк-воркера (после индивидуальных)")),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 o=+i.ID;return e.includes(o)})}async updateAdminsList(){var e,r,i;try{let o=await this.getAdminsList();const a=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0);(r=this.bx)!=null&&r.isAdmin&&a&&!o.includes(a)&&(o.push(a),console.log(`updateAdminsList: Добавлен новый админ ${a}`)),!((i=this.bx)!=null&&i.isAdmin)&&a&&o.includes(a)&&(o=o.filter(c=>c!==a),console.log(`updateAdminsList: Удален из списка админов пользователь ${a} (больше не админ)`));const h=new Set((this.users??[]).filter(c=>c.ACTIVE==="Y"||c.ACTIVE===!0).map(c=>+c.ID)),u=o.filter(c=>h.has(c));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(o){return console.error("BackgroundWorker: Ошибка при обновлении списка админов:",o),[]}}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)})}}y.BackgroundWorker=St,y.Batch=K,y.BxBoot=bt,y.BxHelper=ft,y.BxLogger=Ot,y.tempus=st,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
var It=Object.defineProperty;var Mt=(_,L,C)=>L in _?It(_,L,{enumerable:!0,configurable:!0,writable:!0,value:C}):_[L]=C;var M=(_,L,C)=>(Mt(_,typeof L!="symbol"?L+"":L,C),C),dt=(_,L,C)=>{if(!L.has(_))throw TypeError("Cannot "+C)};var T=(_,L,C)=>(dt(_,L,"read from private field"),C?C.call(_):L.get(_)),Y=(_,L,C)=>{if(L.has(_))throw TypeError("Cannot add the same private member more than once");L instanceof WeakSet?L.add(_):L.set(_,C)},v=(_,L,C,et)=>(dt(_,L,"write to private field"),et?et.call(_,C):L.set(_,C),C);var K=(_,L,C)=>(dt(_,L,"access private method"),C);(function(_,L){typeof exports=="object"&&typeof module<"u"?L(exports):typeof define=="function"&&define.amd?define(["exports"],L):(_=typeof globalThis<"u"?globalThis:_||self,L(_["szdl-utils-kit"]={}))})(this,function(_){var q,Q,Z,$,rt,W,tt,st,at,Nt,nt,gt,At,Ot,ct,_t,ht,Et,lt,Tt,ut,Rt,ot,pt;"use strict";var L=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function C(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x.default:x}var et={exports:{}};(function(x,r){(function(e){Array.prototype.indexOf||(Array.prototype.indexOf=function(t,o){var d,g;for(d=o||0,g=this.length;d<g;d+=1)if(this[d]===t)return d;return-1});var i=this,n=function(t,o){for(var d=t.toString();d.length<o;)d="0"+d;return d},a=function(t,o){return o!==e?(t.year(o.year()||o.year),t.month(o.month()||o.month),t.day(o.day()||o.day),t.hours(o.hours()||o.hours),t.minutes(o.minutes()||o.minutes),t.seconds(o.seconds()||o.seconds),t.milliseconds(o.milliseconds()||o.milliseconds),t):e},l=function(t,o){var d,g="";return d=t.slice(o,o+1),d!==""&&!isNaN(Number(d))&&(g+="%H"),d=t.charAt(o+2),d!==""&&d===":"&&(g+=d),d=t.slice(o+3,o+4),d!==""&&!isNaN(Number(d))&&(g+="%M"),d=t.charAt(o+5),d!==""&&d===":"&&(g+=d),d=t.slice(o+6,o+7),d!==""&&!isNaN(Number(d))&&(g+="%S"),g},c=function(t,o){var d,g=[t.slice(o,o+1),t.charAt(o+2),t.slice(o+3,o+4),t.charAt(o+5),t.slice(o+6,o+9)],w;return!isNaN(Number(g[0]))&&!isNaN(Number(g[2]))&&!isNaN(Number(g[4]))?(g[1]==="."&&g[3]==="."?d="%d.%m.%Y":g[1]==="-"&&g[3]==="-"?d="%m-%d-%Y":g[1]==="/"&&g[3]==="/"&&(d="%m/%d/%Y"),d):(w=[t.slice(o,o+3),t.charAt(o+4),t.slice(o+5,o+6),t.charAt(o+7),t.slice(o+8,o+9)],!isNaN(Number(w[0]))&&!isNaN(Number(w[2]))&&!isNaN(Number(w[4]))?(w[1]==="-"&&w[3]==="-"&&(d="%Y-%m-%d"),d):"")},h=i.tempus,s,f,m=i.navigator||{},A="en",u={en:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"Mar",APRIL_SHORT:"Apr",MAY_SHORT:"May",JUNE_SHORT:"Jun",JULY_SHORT:"Jul",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sep",OCTOBER_SHORT:"Oct",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dec",JANUARY_LONG:"January",FEBRUARY_LONG:"February",MARCH_LONG:"March",APRIL_LONG:"April",MAY_LONG:"May",JUNE_LONG:"June",JULY_LONG:"July",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"October",NOVEMBER_LONG:"November",DECEMBER_LONG:"December",SUNDAY_SHORT:"Sun",MONDAY_SHORT:"Mon",TUESDAY_SHORT:"Tue",WEDNESDAY_SHORT:"Wed",THURSDAY_SHORT:"Thu",FRIDAY_SHORT:"Fri",SATURDAY_SHORT:"Sat",SUNDAY_LONG:"Sunday",MONDAY_LONG:"Monday",TUESDAY_LONG:"Tuesday",WEDNESDAY_LONG:"Wednesday",THURSDAY_LONG:"Thursday",FRIDAY_LONG:"Friday",SATURDAY_LONG:"Saturday"},ru:{JANUARY_SHORT:"Янв",FEBRUARY_SHORT:"Фев",MARCH_SHORT:"Мар",APRIL_SHORT:"Апр",MAY_SHORT:"Май",JUNE_SHORT:"Июн",JULY_SHORT:"Июл",AUGUST_SHORT:"Авг",SEPTEMBER_SHORT:"Сен",OCTOBER_SHORT:"Окт",NOVEMBER_SHORT:"Ноя",DECEMBER_SHORT:"Дек",JANUARY_LONG:"Январь",FEBRUARY_LONG:"Февраль",MARCH_LONG:"Март",APRIL_LONG:"Апрель",MAY_LONG:"Май",JUNE_LONG:"Июнь",JULY_LONG:"Июль",AUGUST_LONG:"Август",SEPTEMBER_LONG:"Сентябрь",OCTOBER_LONG:"Октябрь",NOVEMBER_LONG:"Ноябрь",DECEMBER_LONG:"Декабрь",SUNDAY_SHORT:"Вс",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Воскресенье",MONDAY_LONG:"Понедельник",TUESDAY_LONG:"Вторник",WEDNESDAY_LONG:"Среда",THURSDAY_LONG:"Четверг",FRIDAY_LONG:"Пятница",SATURDAY_LONG:"Суббота"},ua:{JANUARY_SHORT:"Січ",FEBRUARY_SHORT:"Лют",MARCH_SHORT:"Берез",APRIL_SHORT:"Квіт",MAY_SHORT:"Трав",JUNE_SHORT:"Черв",JULY_SHORT:"Лип",AUGUST_SHORT:"Серп",SEPTEMBER_SHORT:"Верес",OCTOBER_SHORT:"Жовт",NOVEMBER_SHORT:"Листоп",DECEMBER_SHORT:"Груд",JANUARY_LONG:"Січень",FEBRUARY_LONG:"Лютий",MARCH_LONG:"Березень",APRIL_LONG:"Квітень",MAY_LONG:"Травень",JUNE_LONG:"Червень",JULY_LONG:"Липень",AUGUST_LONG:"Серпень",SEPTEMBER_LONG:"Вересень",OCTOBER_LONG:"Жовтень",NOVEMBER_LONG:"Листопад",DECEMBER_LONG:"Грудень",SUNDAY_SHORT:"Нд",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Неділя",MONDAY_LONG:"Понеділок",TUESDAY_LONG:"Вівторок",WEDNESDAY_LONG:"Середа",THURSDAY_LONG:"Четвер",FRIDAY_LONG:"П’ятниця",SATURDAY_LONG:"Субота"},de:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"März",APRIL_SHORT:"Apr",MAY_SHORT:"Mai",JUNE_SHORT:"Juni",JULY_SHORT:"Juli",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sept",OCTOBER_SHORT:"Okt",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dez",JANUARY_LONG:"Januar",FEBRUARY_LONG:"Februar",MARCH_LONG:"März",APRIL_LONG:"April",MAY_LONG:"Mai",JUNE_LONG:"Juni",JULY_LONG:"Juli",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"Oktober",NOVEMBER_LONG:"November",DECEMBER_LONG:"Dezember",SUNDAY_SHORT:"So",MONDAY_SHORT:"Mo",TUESDAY_SHORT:"Di",WEDNESDAY_SHORT:"Mi",THURSDAY_SHORT:"Do",FRIDAY_SHORT:"Fr",SATURDAY_SHORT:"Sa",SUNDAY_LONG:"Sonntag",MONDAY_LONG:"Montag",TUESDAY_LONG:"Dienstag",WEDNESDAY_LONG:"Mittwoch",THURSDAY_LONG:"Donnerstag",FRIDAY_LONG:"Freitag",SATURDAY_LONG:"Samstag"}},N=function(){return[u[A].JANUARY_LONG,u[A].FEBRUARY_LONG,u[A].MARCH_LONG,u[A].APRIL_LONG,u[A].MAY_LONG,u[A].JUNE_LONG,u[A].JULY_LONG,u[A].AUGUST_LONG,u[A].SEPTEMBER_LONG,u[A].OCTOBER_LONG,u[A].NOVEMBER_LONG,u[A].DECEMBER_LONG]},y=function(){return[u[A].JANUARY_SHORT,u[A].FEBRUARY_SHORT,u[A].MARCH_SHORT,u[A].APRIL_SHORT,u[A].MAY_SHORT,u[A].JUNE_SHORT,u[A].JULY_SHORT,u[A].AUGUST_SHORT,u[A].SEPTEMBER_SHORT,u[A].OCTOBER_SHORT,u[A].NOVEMBER_SHORT,u[A].DECEMBER_SHORT]},p=function(){return[u[A].SUNDAY_LONG,u[A].MONDAY_LONG,u[A].TUESDAY_LONG,u[A].WEDNESDAY_LONG,u[A].THURSDAY_LONG,u[A].FRIDAY_LONG,u[A].SATURDAY_LONG]},R=function(){return[u[A].SUNDAY_SHORT,u[A].MONDAY_SHORT,u[A].TUESDAY_SHORT,u[A].WEDNESDAY_SHORT,u[A].THURSDAY_SHORT,u[A].FRIDAY_SHORT,u[A].SATURDAY_SHORT]},b,D,B,k,J=function(t,o,d){var g;i.XMLHttpRequest?g=new XMLHttpRequest:g=new ActiveXObject("Microsoft.XMLHTTP"),g.onreadystatechange=function(){g.readyState===4&&(g.status===200?o&&(i.JSON===e?alert(`Please, include json2 into your project if you want use old browsers!
|
|
2
|
+
https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(g.responseText))):d&&d(g))},g.open("GET",t,!1),g.send()},I={"%d":{format:function(t){return n(t.day()||s.MIN_DAY,2)},parse:function(t){var o=Number(t);return{day:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(t){return n(t.month()||s.MIN_MONTH,2)},parse:function(t){var o=Number(t);return{month:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(t){return n(t.year()||s.MIN_YEAR,4)},parse:function(t){var o=Number(t);return{year:isNaN(o)?e:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(t){return t.dayOfWeek()||s.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(t){var o=t.dayOfWeek();return k[o!==e?o:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var o=t.dayOfWeek();return B[o!==e?o:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(t){var o=s.options("monthFromZero")?t.month():t.month()-1;return D[o!==e?o:s.MIN_MONTH]},parse:function(t){var o=s.monthNames().indexOf(t)+(s.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var o=s.options("monthFromZero")?t.month():t.month()-1;return b[o!==e?o:s.MIN_MONTH]},parse:function(t){var o=s.monthNames(!0).indexOf(t)+(s.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(t){return n(t.hours()||s.MIN_HOURS,2)},parse:function(t){var o=Number(t);return{hours:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(t){return n(t.minutes()||s.MIN_MINUTES,2)},parse:function(t){var o=Number(t);return{minutes:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(t){return n(t.seconds()||s.MIN_SECONDS,2)},parse:function(t){var o=Number(t);return{seconds:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(t){return t.timestamp()},parse:function(t){return isNaN(Number(t))?{}:s(Number(t)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(t){return n(t.year()||s.MIN_YEAR,4)+"-"+n(t.month()||s.MIN_MONTH,2)+"-"+n(t.day()||s.MIN_DAY,2)},parse:function(t){var o=Number(t.slice(0,4)),d=Number(t.slice(5,7)),g=Number(t.slice(8,10));return{year:o,month:d,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return n(t.month()||s.MIN_MONTH,2)+"/"+n(t.day()||s.MIN_DAY,2)+"/"+n(t.year()||s.MIN_YEAR,4)},parse:function(t){var o=Number(t.slice(0,2)),d=Number(t.slice(3,5)),g=Number(t.slice(6,10));return{year:g,month:o,day:d}},minLength:10,maxLength:10,type:"string"}},X={useMilliseconds:!1,monthFromZero:!1},O;O=function(t,o,d){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t!==e&&this.set(t,o,d),this},O.fn=O.prototype,O.fn.dayCount=function(){var t=this.month(),o=s.MAX_DAY_IN_MONTHS[t-(s.options("monthFromZero")?0:1)];return this.leapYear()&&t===(s.options("monthFromZero")?1:2)&&(o+=1),o},O.fn.year=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_YEAR&&Number(t)<=s.MAX_YEAR?(this._d.setFullYear(Number(t)),this._i.year=!1):this._i.year=Number(t):(this._d.setFullYear(s.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},O.fn.month=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MONTH&&Number(t)<=s.MAX_MONTH?(this._d.setMonth(s.options("monthFromZero")?Number(t):Number(t)-1),this._i.month=!1):this._i.month=Number(t):(this._d.setMonth(s.options("monthFromZero")?s.MIN_MONTH:s.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?s.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},O.fn.day=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_DAY&&Number(t)<=this.dayCount()?(this._d.setDate(Number(t)),this._i.day=!1):this._i.day=Number(t):(this._d.setDate(s.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},O.fn.hours=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_HOURS&&Number(t)<=s.MAX_HOURS?(this._d.setHours(Number(t)),this._i.hours=!1):this._i.hours=Number(t):(this._d.setHours(s.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},O.fn.minutes=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MINUTES&&Number(t)<=s.MAX_MINUTES?(this._d.setMinutes(Number(t)),this._i.minutes=!1):this._i.minutes=Number(t):(this._d.setMinutes(s.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},O.fn.seconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_SECONDS&&Number(t)<=s.MAX_SECONDS?(this._d.setSeconds(Number(t)),this._i.seconds=!1):this._i.seconds=Number(t):(this._d.setSeconds(s.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},O.fn.milliseconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MILLISECONDS&&Number(t)<=s.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(t)),this._i.milliseconds=!1):this._i.milliseconds=Number(t):(this._d.setMilliseconds(s.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},O.fn.week=function(){var t=new Date(this.year(),0,1),o=s(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-t.getTime())/864e5+t.getDay()+1)/7)},O.fn.set=function(t,o,d){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t===e)return this._d=new Date,this;if(t instanceof Date)return this._d=t,this;if(typeof t=="number")return this._d=new Date(t*(s.options("useMilliseconds")?1:1e3)),this;if(typeof t=="object"&&(t instanceof Array?(this.day(s.MIN_DAY),this.year(t[0]),this.month(t[1]),this.day(t[2]),this.hours(t[3]),this.minutes(t[4]),this.seconds(t[5]),this.milliseconds(t[6])):(this.day(s.MIN_DAY),this.year(t.year),this.month(t.month),this.day(t.day),this.hours(t.hours),this.minutes(t.minutes),this.seconds(t.seconds),this.milliseconds(t.milliseconds))),typeof t=="string"){var g,w=[],E,S,V=[],P=0,F=0,U,j,H={},G;if(t===e)return E=a(this,d),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;for(o===e&&(o=s.detectFormat(t));P<o.length;){if(o.charAt(P)==="%"){if(S=o.charAt(P)+o.charAt(P+1),I[S]!==e){switch(U=0,j="",I[S].type){case"number":for(;U<I[S].maxLength&&F+U<t.length&&!isNaN(Number(t.charAt(F+U)));)j+=t.charAt(F+U),U+=1;break;case"word":for(;U<I[S].maxLength&&F+U<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(F+U));)j+=t.charAt(F+U),U+=1;break;case"string":for(;U<I[S].maxLength&&F+U<t.length;)j+=t.charAt(F+U),U+=1;break}if(U<I[S].minLength)return E=a(this,d),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;w.push(S),V.push(j),U-=1,F+=U,P+=1}}else if(t.charAt(F)!==o.charAt(P))return E=a(this,d),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;P+=1,F+=1}for(g in w)w.hasOwnProperty(g)&&I.hasOwnProperty(w[g])&&(G=I[w[g]].parse(V[g]),H={year:G.year!==e?G.year:H.year,month:G.month!==e?G.month:H.month,day:G.day!==e?G.day:H.day,hours:G.hours!==e?G.hours:H.hours,minutes:G.minutes!==e?G.minutes:H.minutes,seconds:G.seconds!==e?G.seconds:H.seconds});this.day(s.MIN_DAY),this.year(H.year),this.month(H.month),this.day(H.day),this.hours(H.hours),this.minutes(H.minutes),this.seconds(H.seconds),this.milliseconds(H.milliseconds)}return this},O.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},O.fn.timestamp=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(s.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):s.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},O.fn.utc=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(s.options("useMilliseconds")?1:1e3)),this):s.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},O.fn.dayOfWeek=function(t){if(t==="long")return B[this._d.getDay()];if(t==="short")return k[this._d.getDay()];if(t===e)return this._d.getDay();if(t===0||t==="Sunday")return this.calc({day:-this.dayOfWeek()});if(t===1||t==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(t===2||t==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(t===3||t==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(t===4||t==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(t===5||t==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(t===6||t==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},O.fn.timezone=function(t){switch(t){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},O.fn.get=function(t){switch(t){case"Date":return new Date(this.year(),this.month()-(s.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds());case"DateUTC":return new Date(Date.UTC(this.year(),this.month()-(s.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()));case"Array":return[this.year(),this.month(),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()];default:return{year:this.year(),month:this.month(),week:this.week(),day:this.day(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds(),utc:this.utc(),dayOfWeek:this.dayOfWeek(),dayOfWeekShort:this.dayOfWeek("short"),dayOfWeekLong:this.dayOfWeek("long"),timestamp:this.timestamp()}}},O.fn.format=function(t){for(var o=0,d="",g;o<t.length;)t.charAt(o)==="%"?(g=t.charAt(o)+t.charAt(o+1),I[g]!==e?(d+=I[g].format(this),o+=1):d+="%"):d+=t.charAt(o),o+=1;return d},O.fn.valid=function(){return this._i.year===!1&&this._i.month===!1&&this._i.day===!1&&this._i.hours===!1&&this._i.minutes===!1&&this._i.seconds===!1&&this._i.milliseconds===!1},O.fn.errors=function(){return this._i},O.fn.between=function(t,o){var d=this.timestamp(),g=t.timestamp();switch(o){case"year":return Math.floor((g-d)/31556952);case"month":return Math.floor((g-d)/2629746);case"day":return Math.floor((g-d)/86400);case"hours":return Math.floor((g-d)/3600);case"minutes":return Math.floor((g-d)/60);case"seconds":return g-d;default:return e}},O.fn.calc=function(t){return t.year!==e&&this._d.setFullYear(this._d.getFullYear()+t.year),t.month!==e&&this._d.setMonth(this._d.getMonth()+t.month),t.day!==e&&this._d.setDate(this._d.getDate()+t.day),t.hours!==e&&this._d.setHours(this._d.getHours()+t.hours),t.minutes!==e&&this._d.setMinutes(this._d.getMinutes()+t.minutes),t.seconds!==e&&this._d.setSeconds(this._d.getSeconds()+t.seconds),t.milliseconds!==e&&this._d.setMilliseconds(this._d.getMilliseconds()+t.milliseconds),this},s=function(t,o,d){return new O(t,o,d)},s.MIN_YEAR=1e3,s.MAX_YEAR=3e3,s.MIN_MONTH=1,s.MAX_MONTH=12,s.MIN_DAY=1,s.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],s.MIN_DAY_OF_WEEK=0,s.MAX_DAY_OF_WEEK=6,s.MIN_HOURS=0,s.MAX_HOURS=23,s.MIN_MINUTES=0,s.MAX_MINUTES=59,s.MIN_SECONDS=0,s.MAX_SECONDS=59,s.MIN_MILLISECONDS=0,s.MAX_MILLISECONDS=999,s.VERSION="0.2.18",s.options=function(t,o){if(t===e)return X;if(X.hasOwnProperty(t)){if(o===e)return X[t];X[t]=o,t==="monthFromZero"&&(s.MIN_MONTH=o?0:1,s.MAX_MONTH=o?11:12)}return e},s.noConflict=function(){return i.tempus=h,s},s.generate=function(t){var o,d,g,w,E,S,V,P;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof O?o=t.dateFrom.utc():o=s(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof O?d=t.dateTo.utc():d=s(t.dateTo,t.formatTo!==e?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?E={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?E={year:t.period==="year"?1:0,month:t.period==="month"?1:0,day:t.period==="day"?1:0,hours:t.period==="hours"?1:0,minutes:t.period==="minutes"?1:0,seconds:t.period==="seconds"?1:0}:typeof t.period=="object"&&(E={year:t.period.year!==e?t.period.year:0,month:t.period.month!==e?t.period.month:0,day:t.period.day!==e?t.period.day:0,hours:t.period.hours!==e?t.period.hours:0,minutes:t.period.minutes!==e?t.period.minutes:0,seconds:t.period.seconds!==e?t.period.seconds:0}),t.groupBy===e?S=t.asObject===!0?{}:[]:(S=[],S.push([]),V=s(o).get()[t.groupBy]),P=function(j,H,G){return t.asObject===!0?t.format!==e?j[s(H).format(t.format)]={}:j[s(H).format("%F %H:%M:%S")]={}:t.format!==e?j.push(G?null:s(H).format(t.format)):j.push(G?null:s(H)),j},t.groupBy!==e&&t.fillNulls){var F={year:E.year?-E.year:e,month:E.month?-E.month:e,day:E.day?-E.day:e,hours:E.hours?-E.hours:e,minutes:E.minutes?-E.minutes:e,seconds:E.seconds?-E.seconds:e,milliseconds:E.milliseconds?-E.milliseconds:e};for(g=s(o).calc(F).utc();s(g).get()[t.groupBy]===V;)P(S[S.length-1],g,!0),g=s(g).calc(F).utc();if(t.groupBy==="week"){var U=s(o).dayOfWeek();for(g=s(o).dayOfWeek(0).utc();S[0].length<U&&g<o;)P(S[S.length-1],g,!0),g=s(g).calc(E).utc()}}for(;o<=d;)t.groupBy===e?P(S,o):s(o).get()[t.groupBy]===V?P(S[S.length-1],o):(S.push([]),P(S[S.length-1],o),V=s(o).get()[t.groupBy]),o=s(o).calc(E).utc();if(t.groupBy!==e&&t.fillNulls)for(w=s(d).calc(E).utc();s(w).get()[t.groupBy]===V;)P(S[S.length-1],w,!0),w=s(w).calc(E).utc();return S},s.monthNames=function(t){switch(t){case"long":return b;default:return D}},s.dayNames=function(t){switch(t){case"long":return B;default:return k}},s.lang=function(t){if(t!==e)A=t,u[A]===e&&(A="en"),b=N(),D=y(),B=p(),k=R();else return A;return e},s.availableLangs=function(){return Object.keys(u)},s.registerFormat=function(t,o,d,g,w,E){I[t]={format:o,parse:d,minLength:g,maxLength:w,type:E}},s.unregisterFormat=function(t){delete I[t]},s.detectFormat=function(t){var o,d,g;return o=c(t,0),o!==""&&(g=10),d=t.charAt(g),(d==="T"||d===" ")&&(o+=d,g+=1),o+=l(t,g),o},f={TempusDate:O},s.classes=function(t,o){if(o===e)return f[t];f[t]=o},s.loadTranslations=function(t){typeof t=="object"?u=t:typeof t=="string"&&J(t,function(o){u=o},function(o){})},A=(m.language||m.systemLanguage||m.userLanguage||"en").substr(0,2).toLowerCase(),u[A]===e&&(A="en"),b=N(),D=y(),B=p(),k=R(),x.exports&&(r=x.exports=s),r.tempus=s}).call(L)})(et,et.exports);var Lt=et.exports;const it=C(Lt);class z{constructor(r){this.callBatch=r,this.result={},this.errors={},this.limit=50,this.canContinue=!0,this.progressCall="",this.limitCall="",this.progressData="",this.progressTimer="",this.progressDelay=100,this.oldPercent="no",this.chunkRate=1,this.totalProgress=0,this.skipList=new Set,this.filterChunkSize=50}getData(r){return(r==null?void 0:r.items)??(r==null?void 0:r.tasks)??(r==null?void 0:r.types)??(r==null?void 0:r.type)??(r==null?void 0:r.fields)??(r==null?void 0:r.workgroups)??r}splitLargeFilters(r,e){const{method:i,params:n}=e;if(!n)return[{key:r,request:e}];const a=n.filter||n.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:r,request:e}];for(const[l,c]of Object.entries(a))if(Array.isArray(c)&&c.length>this.filterChunkSize){const h=[];for(let s=0;s<c.length;s+=this.filterChunkSize){const f=c.slice(s,s+this.filterChunkSize),m=s===0?r:`${r}__chunk_${Math.floor(s/this.filterChunkSize)}`,A={...n};n.filter?(A.filter={...a},A.filter[l]=f):n.FILTER&&(A.FILTER={...a},A.FILTER[l]=f),h.push({key:m,request:{method:i,params:A},originalKey:r,filterKey:l,chunkIndex:Math.floor(s/this.filterChunkSize)})}return h}return[{key:r,request:e}]}mergeSplitResults(r,e){const i=[],n=Object.keys(r).filter(a=>a.startsWith(e)).sort((a,l)=>{const c=a.match(/__chunk_(\d+)$/),h=l.match(/__chunk_(\d+)$/);return c?h?parseInt(c[1])-parseInt(h[1]):1:-1});for(const a of n){const l=r[a];Array.isArray(l)?i.push(...l):l&&i.push(l)}return i}get progressPercent(){let r=0;if(!this.progressData)return{percent:Math.round(r),allCount:0,allTotal:0};let e=0,i=0;return Object.values(this.progressData).forEach(n=>{const{total:a,count:l}=n;e+=a??0,i+=l??0}),e?r=i/e*100*this.chunkRate+this.totalProgress:i===0&&e===0?r=100*this.chunkRate+this.totalProgress:r=100,{percent:Math.round(r),allCount:i,allTotal:e}}setProgressData({key:r,value:e,type:i}){const n=this.getData(e.data()),a=Array.isArray(n)?n.length:0;let l=e.total()||a;i==="count"&&(l=a);let c=1;n&&(c=a),this.progressCall&&(this.progressData||(this.progressData={}),this.progressData[r]&&this.progressData[r].count&&(c+=this.progressData[r].count),this.progressData[r]?this.progressData[r].count=c:this.progressData[r]={total:l,count:c},this.progressTimer||(this.progressTimer=setInterval(()=>{const{percent:h,allCount:s,allTotal:f}=this.progressPercent;(this.oldPercent==="no"||this.oldPercent<this.progressPercent.percent)&&(this.progressCall({data:this.progressData,percent:h,allCount:s,allTotal:f}),this.oldPercent=this.progressPercent.percent),h>=100&&this.clearProgressData()},this.progressDelay)))}delay(){return new Promise(r=>setTimeout(r,500))}callBatchWithTimeout(r,e){return new Promise((i,n)=>{let a=!1;const l=6e4;let c=!1,h=!1,s=!1,f=null,m=null;const A=async(y,p)=>{if(!a){a=!0,f&&clearTimeout(f),m&&clearTimeout(m);try{await Promise.resolve(e(y)),i()}catch(R){console.error(`Error in callBatch callback (attempt ${p}):`,R),n(R)}}},u=async()=>{if(!a){a=!0,f&&clearTimeout(f),m&&clearTimeout(m),console.warn(`Batch request timeout after ${l}ms on both attempts. This may indicate a CORS or network error.`);const y={};Object.keys(r).forEach(p=>{y[p]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 30 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(e(y)),i()}catch(p){console.error("Error in timeout callback:",p),i()}}},N=y=>{try{this.callBatch(r,async p=>{y===1&&!c&&!a?(c=!0,await A(p,1)):y===2&&!s&&!a&&(s=!0,await A(p,2))})}catch(p){a||console.error(`Error calling callBatch (attempt ${y}):`,p)}};N(1),f=setTimeout(async()=>{!c&&!a&&!h&&(console.warn(`First batch request attempt timeout after ${l}ms. Starting second attempt...`),h=!0,N(2),m=setTimeout(async()=>{!c&&!s&&!a&&await u()},l))},l)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.limitCall="",this.oldPercent="no"}async batch(r,e,i){this.progressTimer&&this.clearProgressData(),e&&(this.progressCall=e),i&&(this.limitCall=i),this.canContinue=!0,this.result={},this.errors={};const n={},a={},l={};for(const[f,m]of Object.entries(r)){const A=this.arrayChunk(m);if(!A)continue;const u=this.splitLargeFilters(f,A);if(u.length===1)a[f]=A;else{l[f]=[];for(const N of u)a[N.key]=N.request,l[f].push(N.key)}}this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let c={},h=0;const s=Object.keys(a).length;for(const[f,m]of Object.entries(a)){if(!this.canContinue)break;c[f]=m,(Object.keys(c).length>=50||h+1===s)&&(await this.batchChunk(c),Object.entries(this.result).forEach(([A,u])=>{n[A]=u}),this.totalProgress=Math.round(h/s*100),c={}),h++}for(const[f,m]of Object.entries(l))if(m&&m.length>0){const A=this.mergeSplitResults(n,f);for(const u of m)delete n[u];n[f]=A}return Object.entries(this.errors).length&&(n.errorsList=this.errors),e&&e({percent:100}),Promise.resolve(n)}async batchTotalCount(r,e,i){this.progressTimer&&this.clearProgressData(),e&&(this.progressCall=e),i&&(this.limitCall=i),this.canContinue=!0,this.result={},this.errors={};const n={},a={},l={};for(const[s,f]of Object.entries(r)){const m=this.arrayChunk(f);if(!m)continue;const A=this.splitLargeFilters(s,m);if(A.length===1)a[s]=m;else{l[s]=[];for(const u of A)a[u.key]=u.request,l[s].push(u.key)}}const c=[],h=Object.entries(a);for(let s=0;s<h.length;s+=this.limit){const f=h.slice(s,s+this.limit),m={};for(const[A,u]of f){if(!this.canContinue)break;m[A]=u}Object.keys(m).length>0&&c.push(m)}this.chunkRate=(1/c.length).toFixed(5);for(const[s,f]of Object.entries(c)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(s)/c.length*100),await this.callBatchWithTimeout(f,async m=>{var A,u,N,y,p,R,b;for(const[D,B]of Object.entries(m)){if(!this.canContinue)return;if(B.error()){const O=(u=(A=B.error())==null?void 0:A.ex)==null?void 0:u.error,t=(y=(N=B.error())==null?void 0:N.ex)==null?void 0:y.error_description;this.errors[D]=O&&O.trim()||t&&t.trim()||((p=B.error())==null?void 0:p.toString())||"Неизвестная ошибка",n[D]=0;const o=((b=(R=B.error())==null?void 0:R.ex)==null?void 0:b.error)??"";let d="";const g=f[D];switch(Array.isArray(g)?[d]=g:g!=null&&g.method&&(d=g.method),o){case"OPERATION_TIME_LIMIT":d&&this.skipList.add(d),this.limitCall&&this.limitCall(D);break;case"ACCESS_DENIED":d&&this.skipList.add(d);break;case"TIMEOUT":d&&this.skipList.add(d),this.limitCall&&this.limitCall(D);break}continue}const k=this.getData(B.data()),J=Array.isArray(k)?k.length:0,X=typeof B.total=="function"&&B.total()!==void 0?B.total():J;n[D]=X,this.setProgressData({key:D,value:B,type:"count"})}})}for(const[s,f]of Object.entries(l))if(f&&f.length>0){let m=0;for(const A of f)n[A]!==void 0&&(m+=n[A]||0),delete n[A];n[s]=m}return Object.entries(this.errors).length&&(n.errorsList=this.errors,this.errorLogger()),e&&e({percent:100}),Promise.resolve(n)}arrayChunk(r){let e="",i={};if(Array.isArray(r)?[e]=r:(e=r.method,i=r.params),this.skipList.has(e))return!1;if((e.includes("list")||e==="user.get")&&e!=="task.item.list"){if(!i)i={order:{ID:"ASC",id:"ASC"}};else{e==="tasks.task.list"?(i.order||(i.order={}),i.order.ID="asc"):e==="user.get"?(i.sort||(i.sort="ID"),i.order||(i.order="ASC")):i.order={ID:"ASC",id:"ASC"},Array.isArray(i.select)&&!i.select.includes("ID")&&i.select.push("ID");const n=e==="user.get"?i.FILTER:i.filter;typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.entries(n).forEach(([a,l])=>{(i.start===void 0||i.start!==-1)&&["id","ID"].includes(a)&&(typeof l=="string"||Array.isArray(l)&&l.length<=50)&&(i.start=-1)})}e==="crm.type.list"&&i.order&&delete i.order.ID}if(e==="task.item.list")if(!i)i=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(i[0])&&(i[0]={});const[n,a,l,c]=i;n.ID="ASC",c[0]!==""&&c.includes("ID")||c.push("ID")}return{method:e,params:i}}async batchChunk(r,e){return new Promise(i=>{const n=[];let a;this.callBatchWithTimeout(r,async l=>{var c,h,s,f,m,A,u;for(const[N,y]of Object.entries(l)){if(!this.canContinue)return;if(y.error()){const k=(h=(c=y.error())==null?void 0:c.ex)==null?void 0:h.error,J=(f=(s=y.error())==null?void 0:s.ex)==null?void 0:f.error_description;switch(this.errors[N]=k&&k.trim()||J&&J.trim()||((m=y.error())==null?void 0:m.toString())||"Неизвестная ошибка",a=!0,((u=(A=y.error())==null?void 0:A.ex)==null?void 0:u.error)??""){case"OPERATION_TIME_LIMIT":this.skipList.add(r[N].method),this.limitCall&&this.limitCall(N);break;case"ACCESS_DENIED":this.skipList.add(r[N].method);break;case"TIMEOUT":let X=r[N],O="";Array.isArray(X)?[O]=X:X!=null&&X.method&&(O=X.method),O&&this.skipList.add(O),this.limitCall&&this.limitCall(N);break}}const p=this.getData(y.data()),R=Array.isArray(p)?p.length:0,b=typeof y.total=="function"&&y.total()!==void 0,D=b?y.total():R;e==="count"?this.result[N]?this.result[N]+=R:this.result[N]=D:this.result[N]=p,this.setProgressData({key:N,value:y,type:e});const B=e==="count"?!b&&R===this.limit:D>this.limit&&D>R;if(!this.canContinue||B){let k=r[N];if(Array.isArray(k)){const[J,I={}]=k;k=[J,I]}else{const{method:J,params:I={}}=k;k=[J,I]}n.push([N,k,D])}}a>0&&this.errorLogger(),n.length?await this.batchPayload(n,e).then(()=>i(this.result)):i(this.result)})})}async batchPayload(r,e){const i=new Map,n=(h,s,f,m)=>{let A="ID";this.result[h][this.result[h].length-1].ID||(A="id");let u=`${A}`;if(JSON.stringify(m[1]).toLocaleLowerCase().includes('"id":"desc"')?u="<"+u:u=">"+u,s===1||f.length===0)return{field:u,id:this.result[h][this.result[h].length-1][A]};let y="";const[p,R]=m;return(p==="tasks.task.list"||p==="task.item.list")&&(y="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(p)&&(y="[items]"),p==="crm.type.list"&&(y="[types]"),p==="socialnetwork.api.workgroup.list"&&(y="[workgroups]"),{field:u,id:`$result[${[h,s-1].join("__")}]${y}[49][${A}]`}},a=(h,s)=>{const[f,m]=h;let A=JSON.parse(JSON.stringify(m)),u;if(f==="task.item.list"){A=[...A];const[N,y,p,R]=A;return y[s.field]=s.id,[f,A]}return["user.get"].includes(f)||A.FILTER?(A.FILTER||(A.FILTER={}),u=A.FILTER):(A.filter||(A.filter={}),u=A.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(f)?u[">ID"]=s.id:u[s.field]=s.id,[f,{...A,start:-1}]},l=h=>{Object.entries(h).forEach(([s,f])=>{var u,N,y,p,R,b,D;const[m]=s.split("__"),A=this.getData(f.data());if(Array.isArray(A)&&(e==="count"?this.result[m]+=A.length:this.result[m].push(...A)),f.error()){const B=(N=(u=f.error())==null?void 0:u.ex)==null?void 0:N.error,k=(p=(y=f.error())==null?void 0:y.ex)==null?void 0:p.error_description;this.errors[m]=B&&B.trim()||k&&k.trim()||((R=f.error())==null?void 0:R.toString())||"Неизвестная ошибка";const J=((D=(b=f.error())==null?void 0:b.ex)==null?void 0:D.error)??"",I=i.get(m);switch(J){case"OPERATION_TIME_LIMIT":I&&(this.skipList.add(I),this.limitCall&&this.limitCall(m));break;case"QUERY_LIMIT_EXCEEDED":this.canContinue=!1;break;case"ACCESS_DENIED":I&&this.skipList.add(I);break;case"TIMEOUT":I&&(this.skipList.add(I),this.limitCall&&this.limitCall(m));break}}this.setProgressData({key:m,value:f,type:e})})};let c=[];for await(const[h,s,f]of r){if(!this.canContinue)return;const[m]=s;if(i.set(h,m),this.skipList.has(m))continue;let A=1;for(;f>A*50&&!this.skipList.has(m);){const u=[h,A].join("__"),N=n(h,A,c,s);c.push([u,a(s,N)]),c.length%50===0&&(await this.callBatchWithTimeout(Object.fromEntries(c),y=>{l(y)}),c=[],await this.delay()),A++}}c.length&&(await this.callBatchWithTimeout(Object.fromEntries(c),h=>{l(h)}),await this.delay())}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([r,e])=>{e&&console.log(`[${r}]`,e.toString())}),console.groupEnd()}}class ft{constructor(){Y(this,q,{})}get hash(){return this.createHash(8)}createHash(r){let e="abcdefghijklmnopqrstuvwxyz0123456789",i="";r=r||6;for(let n=0;n<r;n++)i+=e.charAt(Math.floor(Math.random()*e.length));return i}actionFilter({keyTimer:r,duration:e=10,action:i}){T(this,q)[r]&&(clearTimeout(T(this,q)[r]),T(this,q)[r]=null),i&&(T(this,q)[r]=setTimeout(()=>{i()},e))}async noSleep(){let r=document.createElement("video");r.classList.add("no-sleep"),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.addEventListener("loadeddata",()=>{r.style.position="fixed",r.style.left="-9999px",document.querySelector("body").append(r),r.play().catch(e=>{console.warn("noSleep: autoplay prevented",e)})}),r.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{r.play().catch(e=>{console.warn("noSleep: replay prevented",e)})}})}),r.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(r,e){let i=new Blob([JSON.stringify(r)],{type:"application/json"}),n=URL.createObjectURL(i),a=document.createElement("a");a.style.display="none",a.href=n,a.download=`${e}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(n)},200)}}q=new WeakMap;const mt=new ft;class yt{constructor(){Y(this,at);Y(this,nt);Y(this,At);Y(this,ct);Y(this,ht);Y(this,Q,"logger");Y(this,Z,!1);Y(this,$,new Map);Y(this,rt,{});Y(this,W,null);Y(this,tt,!1);Y(this,st,!1);M(this,"periodClear",3);K(this,at,Nt).call(this)}async init(){try{let r=new z(BX24.callBatch),{entityList:e}=await r.batch({entityList:{method:"entity.get"}});if(e&&Array.isArray(e))if(e.find(n=>n.ENTITY==T(this,Q)))v(this,Z,!0);else{let{entityAdd:n}=await r.batch({entityAdd:{method:"entity.add",params:{ENTITY:T(this,Q),NAME:T(this,Q),ACCESS:{AU:"X"}}}});n&&v(this,Z,!0)}return K(this,ct,_t).call(this).catch(i=>{console.error("Ошибка при проверке периода очистки:",i)}),T(this,Z)}catch(r){return console.error("Ошибка при инициализации логера:",r),!1}}start({type:r,data:e}){if(!T(this,Z))return K(this,nt,gt).call(this,"entity"),null;if(!r||!e)return console.error("Невалидные данные для логирования:",{type:r,data:e}),null;const i=mt.hash,n={type:r,data:e,userInfo:T(this,rt),errorList:{},status:"",answer:null,date:new Date().getTime()};return T(this,$).set(i,n),v(this,st,!0),i}async stop({key:r,errorList:e,status:i,answer:n}){var l;if(!T(this,st))return;if(!T(this,Z)){K(this,nt,gt).call(this,"entity");return}let a=T(this,$).get(r);if(!a){console.error(`Не найдены данные логирования для ключа: ${r}`);return}e&&(a.errorList=e),i&&(a.status=i),n&&(a.answer=n),await K(this,At,Ot).call(this),(l=a==null?void 0:a.data)!=null&&l.updateList&&v(this,tt,!0),v(this,st,!1)}async getEntityList(r){var e;try{if((e=T(this,W))!=null&&e.length&&!T(this,tt))return T(this,W);let i=new z(BX24.callBatch),{entityList:n}=await i.batch({entityList:{method:"entity.item.get",params:{ENTITY:T(this,Q),SORT:{ID:"DESC"}}}},r);return!n||!Array.isArray(n)?(console.warn("Получен невалидный список записей"),[]):(n=n.map(a=>{try{const{ID:l,DATE_CREATE:c,DETAIL_TEXT:h}=a;return{...JSON.parse(h),id:l,dateCreate:c}}catch(l){return console.error(`Ошибка парсинга записи ${a.ID}:`,l),null}}).filter(a=>a!==null),v(this,tt,!1),v(this,W,n),n)}catch(i){return console.error("Ошибка при получении списка записей:",i),[]}}async downAllEntityJson(){try{if(T(this,W)||await this.getEntityList(),!T(this,W)||T(this,W).length===0)return console.warn("Нет данных для выгрузки"),!1;let r=it().format("%Y-%m-%d");return mt.downloadFileJson(T(this,W),`sdklogger-entity-data__${r}`),!0}catch(r){return console.error("Ошибка при выгрузке данных в JSON:",r),!1}}}Q=new WeakMap,Z=new WeakMap,$=new WeakMap,rt=new WeakMap,W=new WeakMap,tt=new WeakMap,st=new WeakMap,at=new WeakSet,Nt=async function(){try{const r=new z(BX24.callBatch),e=BX24.isAdmin(),{curUser:i}=await r.batch({curUser:{method:"user.current"}});v(this,rt,{isAdmin:e,curUser:i})}catch(r){console.error("Ошибка при получении информации о пользователе:",r),v(this,rt,{isAdmin:!1,curUser:null})}},nt=new WeakSet,gt=function(r){r=="entity"&&mt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},At=new WeakSet,Ot=async function(){try{let r={},e=new z(BX24.callBatch);for(let[i,n]of T(this,$).entries())if(n.status){const a=JSON.stringify(n);r[i]={method:"entity.item.add",params:{ENTITY:T(this,Q),NAME:T(this,Q),DETAIL_TEXT:a}}}if(Object.keys(r).length){let i=await e.batch(r),{errors:n}=e;for(let[a,l]of Object.entries({...i,...n}))T(this,$).delete(a);return!0}return!1}catch(r){return console.error("Ошибка при добавлении записей в хранилище:",r),!1}},ct=new WeakSet,_t=async function(){try{let r=new z(BX24.callBatch),{serverTime:e}=await r.batch({serverTime:{method:"server.time"}});if(!e){console.error("Не удалось получить время сервера");return}if(T(this,W)||await this.getEntityList(),!T(this,W)||T(this,W).length===0)return;let i=T(this,W).filter(n=>{try{let{dateCreate:a}=n;return a?it(new Date(a)).between(it(new Date(e)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});i.length>0&&(console.log(`Найдено ${i.length} записей для очистки (старше ${this.periodClear} месяцев)`),await K(this,ht,Et).call(this,i))}catch(r){console.error("Ошибка при проверке периода очистки:",r)}},ht=new WeakSet,Et=async function(r){try{if(!r||r.length===0)return!1;let e=new z(BX24.callBatch),i=r.filter(a=>a&&a.id).map(a=>{let{id:l}=a;return{method:"entity.item.delete",params:{ENTITY:T(this,Q),ID:l}}});if(i.length===0)return!1;const n=await e.batch(i);return console.log(`Успешно удалено ${i.length} записей`),v(this,tt,!0),n}catch(e){return console.error("Ошибка при очистке устаревших записей:",e),!1}};class bt{constructor(r){Y(this,lt);Y(this,ut);Y(this,ot);M(this,"domain","");M(this,"isAdmin",!1);M(this,"appInfo",null);M(this,"appConst",null);M(this,"userInfo",null);M(this,"placeData",null);M(this,"placeInfo",null);M(this,"logger",!1);this.appConst=r}init(){return new Promise((r,e)=>{let n=setInterval(()=>{window.BX24&&BX24.init(async()=>{console.info("init BX24"),clearInterval(n),clearTimeout(a),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info(),this.logger?(this.logger=new yt,await this.logger.init()):this.logger={start:()=>{},stop:()=>{},getEntityList:()=>{}};const[l,c]=await Promise.all([K(this,lt,Tt).call(this),K(this,ut,Rt).call(this)]);this.appInfo=l,this.userInfo=c;let h=new ft;try{h.noSleep()}catch(s){console.warn("Failed to initialize noSleep:",s)}r(!0)})},100);const a=setTimeout(()=>{clearInterval(n);const l=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(l),e(l)},3e4)})}userOption(r,e){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.userOption.set(r,e):BX24.userOption.get(r)}appOption(r,e){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.appOption.set(r,e):BX24.appOption.get(r)}async call({method:r,params:e,updateList:i}){let n;if(i&&(n=this.logger.start({type:"call",data:{method:r,params:e,updateList:i}})),e||(e={}),typeof BX24>"u"||!BX24.callMethod){const a=new Error("BX24 is not initialized");throw console.error(a),a}return new Promise((a,l)=>{BX24.callMethod(r,e,async c=>{let h={};if(c!=null&&c.answer)for(let[s,f]of Object.entries(c.answer))s!=="result"&&f&&(h[s]=f);if(c.error()){let s=c.error();if(console.error(s),n)try{await this.logger.stop({answer:h,key:n,status:"fail",errorList:{0:s.toString()}})}catch(f){console.error("Logger error:",f)}a(!1)}else{let s=c.data();if(s!=null&&s.items&&(s=s.items),n)try{await this.logger.stop({answer:h,key:n,status:"success"})}catch(f){console.error("Logger error:",f)}a(s)}})})}async batch(r,e,{errorCall:i,limitCommandSerial:n,updateList:a,limitCall:l}={}){if(typeof BX24>"u"||!BX24.callBatch){const s=new Error("BX24 is not initialized");return console.error(s),!1}let c=new z(BX24.callBatch),h;a&&(h=this.logger.start({type:"batch",data:{commandList:r,updateList:a}})),n&&console.warn("limitCommandSerial is deprecated and not used in current Batch implementation");try{let s=await c.batch(r,e,l);const f=K(this,ot,pt).call(this,c,s,r,a);if(Object.keys(f).length){if(i&&i(f),h)try{await this.logger.stop({key:h,status:"fail",errorList:f})}catch(m){console.error("Logger error:",m)}}else if(h)try{await this.logger.stop({key:h,status:"success"})}catch(m){console.error("Logger error:",m)}return s}catch(s){if(h)try{await this.logger.stop({key:h,status:"fail-runtime",errorList:{0:s==null?void 0:s.toString()}})}catch(f){console.error("Logger error:",f)}return console.error(s),!1}}async batchTotalCount(r,e,{errorCall:i,updateList:n,limitCall:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const h=new Error("BX24 is not initialized");return console.error(h),!1}let l=new z(BX24.callBatch),c;n&&(c=this.logger.start({type:"batch-total-count",data:{commandList:r}}));try{let h=await l.batchTotalCount(r,e,a);const s=K(this,ot,pt).call(this,l,h,r,n);if(Object.keys(s).length){if(i&&i(s),c)try{await this.logger.stop({key:c,status:"fail",errorList:s})}catch(f){console.error("Logger error:",f)}}else if(c)try{await this.logger.stop({key:c,status:"success"})}catch(f){console.error("Logger error:",f)}return h}catch(h){if(c)try{await this.logger.stop({key:c,status:"fail-runtime",errorList:{0:h==null?void 0:h.toString()}})}catch(s){console.error("Logger error:",s)}return console.error(h),!1}}async getPlacement(){return await this.call({method:"placement.get"}).then(r=>(this.placeData||(this.placeData=r),r))}async placementBind(r,e=!0){var f;if(!this.isAdmin)return;e&&await this.placementCheck();let i=[];if(Array.isArray(r)?i=r.map(m=>typeof m=="string"?{placement:m}:m):typeof r=="string"?i=[{placement:r}]:i=[r],i=i.filter(m=>m.placement!=="PAGE_BACKGROUND_WORKER"&&m.placement!=="PAGE_BACKGROUND_WORKER_ALL"),this.placeData=await this.getPlacement(),!this.placeData)return;const{appName:n,pathApp:a}=this.appConst;let l=n;this.domain==="szdl.bitrix24.ru"&&((f=this.appInfo)!=null&&f.ID)&&(l=`${n}: #${this.appInfo.ID}`);const c=l.replace(" CRM",""),h={},s=[];for(let m=0;m<i.length;m++){const u=i[m].placement,N=a;if(this.placeData.find(b=>b.placement===u&&b.handler===N))continue;const p=this.placeData.find(b=>b.placement===u&&b.handler!==N);p&&s.push({placement:u,handler:p.handler});const R={PLACEMENT:u,HANDLER:N,LANG_ALL:{ru:{TITLE:u==="USER_PROFILE_TOOLBAR"?c:l}},OPTIONS:{errorHandlerUrl:N}};h[`bind_${m}`]={method:"placement.bind",params:R}}s.length>0&&await this.placementUnBind(s),Object.keys(h).length>0&&await this.batch(h),Object.keys(h).length>0&&(this.placeData=await this.getPlacement(),Object.values(h).forEach(m=>{console.log("Приложение успешно встроено в",m.params.PLACEMENT)}))}async placementUnBind(r){let e=[];Array.isArray(r)?e=r.map(n=>typeof n=="string"?{placement:n}:n):typeof r=="string"?e=[{placement:r}]:e=[r],e=e.filter(n=>n.placement!=="PAGE_BACKGROUND_WORKER"&&n.placement!=="PAGE_BACKGROUND_WORKER_ALL");const i={};for(let n=0;n<e.length;n++){const a=e[n],l=a.placement,c=a.handler,h={PLACEMENT:l};c&&(h.HANDLER=c),i[`unbind_${n}`]={method:"placement.unbind",params:h}}Object.keys(i).length>0&&(await this.batch(i),e.forEach(n=>{console.log("Встройка отвязана",n.placement)}))}async placementCheck(){if(this.placeData=await this.getPlacement(),!this.placeData)return;const{pathApp:r}=this.appConst,e=[],i=[];for(const n of this.placeData){if(n.placement==="PAGE_BACKGROUND_WORKER"||!n.handler||n.handler.includes(r))continue;const{placement:a,handler:l,userId:c}=n;e.push({placement:a,handler:l}),i.push({placement:a,userId:c})}e.length>0&&await this.placementUnBind(e),i.length>0&&await this.placementBind(i,!1)}getBotList(){return this.call({method:"imbot.bot.list",params:{}}).then(r=>{let e=Object.values(r);return console.log("chat-bot list:",e),e})}regBot({code:r,type:e,name:i}){const{appName:n,pathApp:a,chatBotLogo:l}=this.appConst,c=this.appInfo.ID;return this.call({method:"imbot.register",params:{CODE:r??this.appInfo.CODE,TYPE:e??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${i??n} - бот #${c}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:it().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:l??""}}}).then(h=>(console.log("Чат-бот добавлен",h),h))}unRegBot(r){return this.call({method:"imbot.unregister",params:{BOT_ID:r}}).then(e=>(console.log("чат-бот удален",e),e))}getLoggerList(r){return this.logger.getEntityList(r)}}lt=new WeakSet,Tt=function(){return this.call({method:"app.info"})},ut=new WeakSet,Rt=function(){return this.call({method:"user.current"})},ot=new WeakSet,pt=function(r,e,i,n){let a={...r.errors};if(Object.values(r.errors).some(c=>{if(typeof c!="string")return!1;const h=c.toUpperCase();return h==="TIMEOUT"||h==="OPERATION_TIME_LIMIT"||h.includes("TIMEOUT")||h.includes("OPERATION_TIME_LIMIT")})&&n){const c=e?Object.keys(e).filter(m=>m!=="errorsList"):[],h=new Set(Object.keys(r.errors||{})),s=new Set;if(e){for(const m of c)if(!h.has(m)){const A=e[m];A!=null&&s.add(m)}}const f=Object.values(r.errors).find(m=>{if(typeof m!="string")return!1;const A=m.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const m of Object.keys(i))!s.has(m)&&!r.errors[m]&&(a[m]=f||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a};class St{constructor(r){M(this,"entityName","tabs");M(this,"maxTabs",20);M(this,"tabList",[]);M(this,"id",0);M(this,"hasStarted",!1);M(this,"heartbeat");M(this,"runHeartbeat");M(this,"random",this.getRandomNum());M(this,"activeMaxPause",5*60*1e3+this.random);M(this,"quickCleanupThreshold",2*60*1e3);M(this,"pollInterval",(60+this.random)*1e3);M(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);M(this,"continueCondition");M(this,"defaultContinueBackground",()=>!0);var l,c,h;if(!r){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:e,bx:i,users:n,continueBackground:a}=r;this.bx=i,this.appInit=e,this.users=n,this.appPath=((l=i==null?void 0:i.appConst)==null?void 0:l.pathApp)??"",this.appName=((c=i==null?void 0:i.appConst)==null?void 0:c.appName)??"",this.appCodeName=((h=i==null?void 0:i.appConst)==null?void 0:h.appCodeName)??"",this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("BackgroundWorker: appInit не передан");return}if(!this.bx){console.error("BackgroundWorker: bx не передан");return}if(this.isAppPage()){console.log("BackgroundWorker: Страница приложения, фоновый воркер не запускается");return}await this.checkPlacementType()&&await this.continueBackground()&&(await this.checkEntity(),await this.refreshTabs(!0),await this.ensureTabRegistered(),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(e=>{console.error("BackgroundWorker: backgroundTick failed",e)})},this.pollInterval),await this.backgroundTick())}async backgroundTick(){if(!await this.continueBackground()){this.stopTimers(),console.log("BackgroundWorker: Остановка backgroundTick - условие не выполнено");return}await this.refreshTabs(!0),await this.ensureTabRegistered();const e=this.selectLeaderId(),i=e&&this.id===e;await this.updateTabState(i),i&&!this.hasStarted&&(this.hasStarted=!0,await this.runAsLeader())}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var r;if(typeof BX24>"u"||!((r=BX24.placement)!=null&&r.info))return!1;try{const e=BX24.placement.info(),i=e==null?void 0:e.placement,n=(e==null?void 0:e.options)||{},a=(n==null?void 0:n.URI)||"",l=i==="PAGE_BACKGROUND_WORKER"||(n==null?void 0:n.ID)==="PAGE_BACKGROUND_WORKER",c=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!l||c}catch{return!1}}async checkEntity(){var i;const r=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((i=r==null?void 0:r.find)==null?void 0:i.call(r,n=>n.ENTITY===this.entityName))||await this.safeCall(()=>this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}}))}async getTabs(){const r=await this.safeCall(()=>{var e;return this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:(e=this.bx.userInfo)==null?void 0:e.ID},SORT:{DATE_CREATE:"DESC"}}})});return!Array.isArray(r)||!r.length?[]:r.map(e=>{if(!e)return{id:void 0,data:void 0};try{const i=JSON.parse(e.DETAIL_TEXT);return{id:e.ID,data:i}}catch(i){return console.log("BackgroundWorker: parse tab error",i),{id:e.ID,data:void 0}}})}async ensureTabRegistered(){if(this.id)return this.id;if(this.tabList.length>=this.maxTabs&&await this.refreshTabs(!0,this.quickCleanupThreshold),this.tabList.length>=this.maxTabs)return console.log("BackgroundWorker: Достигнут лимит вкладок даже после быстрой очистки, не регистрируемся"),0;const r={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId},e=await this.safeCall(()=>{var i;return this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(i=this.bx.userInfo)==null?void 0:i.ID,DETAIL_TEXT:JSON.stringify(r)}})})||0;return this.id=e,e}async updateTabState(r){if(!this.id)return;const e={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:r,sessionId:this.sessionId};await this.safeCall(()=>{var i;return this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(i=this.bx.userInfo)==null?void 0:i.ID,DETAIL_TEXT:JSON.stringify(e)}})})}async deleteTabs(r=[]){if(!r.length)return;const e=r.map(i=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:i.id}}));await this.safeCall(()=>this.bx.batch(e))}getRandomNum(){const r=Math.round(Number(Math.random().toFixed(2))*30);return Math.round(Math.random())?r:-r}async checkPlacementType(){var r;try{const e=await this.safeCall(()=>this.bx.getPlacement());if(!e||!Array.isArray(e))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((r=this.bx.userInfo)==null?void 0:r.ID)??0),n=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),a=!n;if(!i)return!0;let l=!1;for(const c of e){if(c.placement!=="PAGE_BACKGROUND_WORKER"||!(c.userId||c.handler&&c.handler.includes("USER_ID=")))continue;const s=c.userId||(c.handler?this.extractUserIdFromHandler(c.handler):null);if(s&&+s===i){l=!0;break}}return n?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):a&&l?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(e){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",e),!0}}isIndividualPlacement(r){return!r||typeof r!="string"?!1:r.includes("USER_ID=")}extractUserIdFromHandler(r){if(!r||typeof r!="string")return null;const e=r.match(/USER_ID=(\d+)/);return e?e[1]:null}async continueBackground(){try{const e=!!await Promise.resolve(this.continueCondition(this));return console.log(e?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),e}catch(r){return console.error("BackgroundWorker: Ошибка в continueCondition",r),!1}}async refreshTabs(r=!1,e=this.activeMaxPause){const i=[],n=[],a=Date.now(),l=await this.getTabs();for(const c of l){if(!(c!=null&&c.data)){i.push(c);continue}if(a-new Date(c.data.lastActive||0).getTime()>e){i.push(c);continue}n.push(c)}return r&&i.length&&await this.deleteTabs(i),this.tabList=n,n}selectLeaderId(){var e;return this.tabList.length&&((e=[...this.tabList].sort((i,n)=>{var c,h,s,f;const a=new Date(((c=i.data)==null?void 0:c.createdAt)||((h=i.data)==null?void 0:h.lastActive)||0).getTime(),l=new Date(((s=n.data)==null?void 0:s.createdAt)||((f=n.data)==null?void 0:f.lastActive)||0).getTime();return a===l?i.id-n.id:a-l})[0])==null?void 0:e.id)||0}async runAsLeader(){this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(r=>console.error("BackgroundWorker: heartbeat update failed",r))},Math.max(20*1e3,Math.floor(this.pollInterval/2)));try{await this.appInit()}catch(r){console.error("BackgroundWorker: appInit failed",r)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)}async setBackgroundWorkerAll(){var N,y;if(!((N=this.bx)!=null&&N.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(y=this.users)!=null&&y.length||await this.getEntityData();const r=await this.safeCall(()=>this.bx.getPlacement()),e=new Map;let i=null;(r||[]).forEach(p=>{if(p.placement!=="PAGE_BACKGROUND_WORKER")return;if(p.userId||p.handler&&p.handler.includes("USER_ID=")){const b=p.userId||(p.handler?this.extractUserIdFromHandler(p.handler):null);b&&e.set(+b,p)}else i=p});const n=await this.resolveAdmins(),a=await this.getEligibleUsersForBackgroundWorker(n);a.sort((p,R)=>{const b=p.LAST_LOGIN?new Date(p.LAST_LOGIN):new Date(0);return(R.LAST_LOGIN?new Date(R.LAST_LOGIN):new Date(0))-b});const l=10,h=a.slice(0,l).filter(p=>!e.has(+p.ID)),s=[];for(const[p]of e)a.find(b=>+b.ID===p)||s.push(p);const f=[];for(const p of s)this.appPath&&f.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${p}/`}});const m=i&&h.length>0;m&&this.appPath&&f.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:i.handler||`${this.appPath}`}});for(const p of h)this.appPath&&f.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${p.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}?USER_ID=${p.ID}/`},USER_ID:p.ID}});(!i||m)&&this.appPath&&f.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}`}}});const A=f.filter(p=>p.method==="placement.unbind"),u=f.filter(p=>p.method==="placement.bind");A.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(A.map((p,R)=>[`unbind_${R}`,p])))),u.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(u.map((p,R)=>[`bind_${R}`,p])))),f.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var r,e;try{const i=+(((r=this.bx.userInfo)==null?void 0:r.ID)??0),n=!!((e=this.bx)!=null&&e.isAdmin),a=await this.getAdminsList()||[];if(!n){if(i&&a.includes(i)){const h=a.filter(s=>s!==i);return await this.saveAdminsList(h),h}return a}const l=new Set([...a||[]]);i&&l.add(i);const c=[...l].filter(Boolean);return await this.saveAdminsList(c),c}catch(i){return console.error("BackgroundWorker: resolveAdmins error",i),[]}}async getEligibleUsersForBackgroundWorker(r=[]){return(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0).filter(i=>r.includes(+i.ID))}async saveAdminsList(r=[]){try{BX24.appOption.set("adminsList",JSON.stringify(r))}catch(e){console.error("BackgroundWorker: saveAdminsList error",e)}}async getAdminsList(){try{const r=BX24.appOption.get("adminsList");return r?JSON.parse(r):[]}catch(r){return console.error("BackgroundWorker: getAdminsList error",r),[]}}async getEntityData(){const r={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:e}=await this.safeCall(()=>this.bx.batch(r).then(i=>i?(Array.isArray(i.users)||(i.users=[]),i):{users:[]}));this.users=e}async ensureAdminPlacements(){var r,e;(r=this.bx)!=null&&r.isAdmin&&((e=this.users)!=null&&e.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(r=500,e){return new Promise(i=>{setTimeout(()=>{e&&e(),i(!0)},r)})}async safeCall(r){try{return await r()}catch(e){console.error("BackgroundWorker: safeCall error",e);return}}}_.BackgroundWorker=St,_.Batch=z,_.BxBoot=bt,_.BxHelper=ft,_.BxLogger=yt,_.tempus=it,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "szdl-utils-kit",
|
|
3
|
-
"description": "utils-kit library",
|
|
4
|
-
"private": false,
|
|
5
|
-
"version": "0.3.
|
|
6
|
-
"type": "module",
|
|
7
|
-
"author": "Stanislav Ovv",
|
|
8
|
-
"license": "BSD",
|
|
9
|
-
"module": "./dist/index.js",
|
|
10
|
-
"main": "./dist/index.umd.cjs",
|
|
11
|
-
"types": "./dist/types/index.d.ts",
|
|
12
|
-
"exports": {
|
|
13
|
-
".": {
|
|
14
|
-
"import": "./dist/index.js",
|
|
15
|
-
"require": "./dist/index.umd.cjs"
|
|
16
|
-
}
|
|
17
|
-
},
|
|
18
|
-
"files": [
|
|
19
|
-
"dist"
|
|
20
|
-
],
|
|
21
|
-
"keywords": [
|
|
22
|
-
"szdl",
|
|
23
|
-
"utils",
|
|
24
|
-
"szdl-utils-kit"
|
|
25
|
-
],
|
|
26
|
-
"scripts": {
|
|
27
|
-
"dev": "vite --host",
|
|
28
|
-
"watch": "vite build --watch",
|
|
29
|
-
"build": "vite build",
|
|
30
|
-
"preview": "vite preview",
|
|
31
|
-
"pub": "npm version patch --no-git-tag-version && npm publish"
|
|
32
|
-
},
|
|
33
|
-
"devDependencies": {
|
|
34
|
-
"vite": "^4.4.5",
|
|
35
|
-
"vite-plugin-dts": "^3.6.0",
|
|
36
|
-
"vite-plugin-static-copy": "^0.17.0"
|
|
37
|
-
},
|
|
38
|
-
"dependencies": {
|
|
39
|
-
"tempusjs": "^0.2.18"
|
|
40
|
-
}
|
|
41
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "szdl-utils-kit",
|
|
3
|
+
"description": "utils-kit library",
|
|
4
|
+
"private": false,
|
|
5
|
+
"version": "0.3.13",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"author": "Stanislav Ovv",
|
|
8
|
+
"license": "BSD",
|
|
9
|
+
"module": "./dist/index.js",
|
|
10
|
+
"main": "./dist/index.umd.cjs",
|
|
11
|
+
"types": "./dist/types/index.d.ts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"import": "./dist/index.js",
|
|
15
|
+
"require": "./dist/index.umd.cjs"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"keywords": [
|
|
22
|
+
"szdl",
|
|
23
|
+
"utils",
|
|
24
|
+
"szdl-utils-kit"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"dev": "vite --host",
|
|
28
|
+
"watch": "vite build --watch",
|
|
29
|
+
"build": "vite build",
|
|
30
|
+
"preview": "vite preview",
|
|
31
|
+
"pub": "npm version patch --no-git-tag-version && npm publish"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"vite": "^4.4.5",
|
|
35
|
+
"vite-plugin-dts": "^3.6.0",
|
|
36
|
+
"vite-plugin-static-copy": "^0.17.0"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"tempusjs": "^0.2.18"
|
|
40
|
+
}
|
|
41
|
+
}
|