szdl-utils-kit 0.3.21 → 0.3.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1028 -968
- package/dist/index.umd.cjs +2 -2
- package/dist/types/background-worker.d.ts +31 -0
- package/dist/types/index.d.ts +14 -2
- package/package.json +1 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(g.responseText))):m&&m(g))},g.open("GET",t,!1),g.send()},R={"%d":{format:function(t){return i(t.day()||n.MIN_DAY,2)},parse:function(t){var o=Number(t);return{day:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(t){return i(t.month()||n.MIN_MONTH,2)},parse:function(t){var o=Number(t);return{month:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(t){return i(t.year()||n.MIN_YEAR,4)},parse:function(t){var o=Number(t);return{year:isNaN(o)?e:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(t){return t.dayOfWeek()||n.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(t){var o=t.dayOfWeek();return p[o!==e?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var o=t.dayOfWeek();return U[o!==e?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(t){var o=n.options("monthFromZero")?t.month():t.month()-1;return T[o!==e?o:n.MIN_MONTH]},parse:function(t){var o=n.monthNames().indexOf(t)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var o=n.options("monthFromZero")?t.month():t.month()-1;return y[o!==e?o:n.MIN_MONTH]},parse:function(t){var o=n.monthNames(!0).indexOf(t)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(t){return i(t.hours()||n.MIN_HOURS,2)},parse:function(t){var o=Number(t);return{hours:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(t){return i(t.minutes()||n.MIN_MINUTES,2)},parse:function(t){var o=Number(t);return{minutes:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(t){return i(t.seconds()||n.MIN_SECONDS,2)},parse:function(t){var o=Number(t);return{seconds:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(t){return t.timestamp()},parse:function(t){return isNaN(Number(t))?{}:n(Number(t)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(t){return i(t.year()||n.MIN_YEAR,4)+"-"+i(t.month()||n.MIN_MONTH,2)+"-"+i(t.day()||n.MIN_DAY,2)},parse:function(t){var o=Number(t.slice(0,4)),m=Number(t.slice(5,7)),g=Number(t.slice(8,10));return{year:o,month:m,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return i(t.month()||n.MIN_MONTH,2)+"/"+i(t.day()||n.MIN_DAY,2)+"/"+i(t.year()||n.MIN_YEAR,4)},parse:function(t){var o=Number(t.slice(0,2)),m=Number(t.slice(3,5)),g=Number(t.slice(6,10));return{year:g,month:o,day:m}},minLength:10,maxLength:10,type:"string"}},w={useMilliseconds:!1,monthFromZero:!1},k;k=function(t,o,m){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t!==e&&this.set(t,o,m),this},k.fn=k.prototype,k.fn.dayCount=function(){var t=this.month(),o=n.MAX_DAY_IN_MONTHS[t-(n.options("monthFromZero")?0:1)];return this.leapYear()&&t===(n.options("monthFromZero")?1:2)&&(o+=1),o},k.fn.year=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_YEAR&&Number(t)<=n.MAX_YEAR?(this._d.setFullYear(Number(t)),this._i.year=!1):this._i.year=Number(t):(this._d.setFullYear(n.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},k.fn.month=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MONTH&&Number(t)<=n.MAX_MONTH?(this._d.setMonth(n.options("monthFromZero")?Number(t):Number(t)-1),this._i.month=!1):this._i.month=Number(t):(this._d.setMonth(n.options("monthFromZero")?n.MIN_MONTH:n.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?n.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},k.fn.day=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_DAY&&Number(t)<=this.dayCount()?(this._d.setDate(Number(t)),this._i.day=!1):this._i.day=Number(t):(this._d.setDate(n.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},k.fn.hours=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_HOURS&&Number(t)<=n.MAX_HOURS?(this._d.setHours(Number(t)),this._i.hours=!1):this._i.hours=Number(t):(this._d.setHours(n.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},k.fn.minutes=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MINUTES&&Number(t)<=n.MAX_MINUTES?(this._d.setMinutes(Number(t)),this._i.minutes=!1):this._i.minutes=Number(t):(this._d.setMinutes(n.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},k.fn.seconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_SECONDS&&Number(t)<=n.MAX_SECONDS?(this._d.setSeconds(Number(t)),this._i.seconds=!1):this._i.seconds=Number(t):(this._d.setSeconds(n.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},k.fn.milliseconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=n.MIN_MILLISECONDS&&Number(t)<=n.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(t)),this._i.milliseconds=!1):this._i.milliseconds=Number(t):(this._d.setMilliseconds(n.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},k.fn.week=function(){var t=new Date(this.year(),0,1),o=n(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-t.getTime())/864e5+t.getDay()+1)/7)},k.fn.set=function(t,o,m){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t===e)return this._d=new Date,this;if(t instanceof Date)return this._d=t,this;if(typeof t=="number")return this._d=new Date(t*(n.options("useMilliseconds")?1:1e3)),this;if(typeof t=="object"&&(t instanceof Array?(this.day(n.MIN_DAY),this.year(t[0]),this.month(t[1]),this.day(t[2]),this.hours(t[3]),this.minutes(t[4]),this.seconds(t[5]),this.milliseconds(t[6])):(this.day(n.MIN_DAY),this.year(t.year),this.month(t.month),this.day(t.day),this.hours(t.hours),this.minutes(t.minutes),this.seconds(t.seconds),this.milliseconds(t.milliseconds))),typeof t=="string"){var g,H=[],D,G,et=[],X=0,K=0,W,v,x={},F;if(t===e)return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;for(o===e&&(o=n.detectFormat(t));X<o.length;){if(o.charAt(X)==="%"){if(G=o.charAt(X)+o.charAt(X+1),R[G]!==e){switch(W=0,v="",R[G].type){case"number":for(;W<R[G].maxLength&&K+W<t.length&&!isNaN(Number(t.charAt(K+W)));)v+=t.charAt(K+W),W+=1;break;case"word":for(;W<R[G].maxLength&&K+W<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(K+W));)v+=t.charAt(K+W),W+=1;break;case"string":for(;W<R[G].maxLength&&K+W<t.length;)v+=t.charAt(K+W),W+=1;break}if(W<R[G].minLength)return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;H.push(G),et.push(v),W-=1,K+=W,X+=1}}else if(t.charAt(K)!==o.charAt(X))return D=a(this,m),D===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;X+=1,K+=1}for(g in H)H.hasOwnProperty(g)&&R.hasOwnProperty(H[g])&&(F=R[H[g]].parse(et[g]),x={year:F.year!==e?F.year:x.year,month:F.month!==e?F.month:x.month,day:F.day!==e?F.day:x.day,hours:F.hours!==e?F.hours:x.hours,minutes:F.minutes!==e?F.minutes:x.minutes,seconds:F.seconds!==e?F.seconds:x.seconds});this.day(n.MIN_DAY),this.year(x.year),this.month(x.month),this.day(x.day),this.hours(x.hours),this.minutes(x.minutes),this.seconds(x.seconds),this.milliseconds(x.milliseconds)}return this},k.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},k.fn.timestamp=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(n.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):n.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},k.fn.utc=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(n.options("useMilliseconds")?1:1e3)),this):n.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},k.fn.dayOfWeek=function(t){if(t==="long")return U[this._d.getDay()];if(t==="short")return p[this._d.getDay()];if(t===e)return this._d.getDay();if(t===0||t==="Sunday")return this.calc({day:-this.dayOfWeek()});if(t===1||t==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(t===2||t==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(t===3||t==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(t===4||t==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(t===5||t==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(t===6||t==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},k.fn.timezone=function(t){switch(t){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},k.fn.get=function(t){switch(t){case"Date":return new Date(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds());case"DateUTC":return new Date(Date.UTC(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()));case"Array":return[this.year(),this.month(),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()];default:return{year:this.year(),month:this.month(),week:this.week(),day:this.day(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds(),utc:this.utc(),dayOfWeek:this.dayOfWeek(),dayOfWeekShort:this.dayOfWeek("short"),dayOfWeekLong:this.dayOfWeek("long"),timestamp:this.timestamp()}}},k.fn.format=function(t){for(var o=0,m="",g;o<t.length;)t.charAt(o)==="%"?(g=t.charAt(o)+t.charAt(o+1),R[g]!==e?(m+=R[g].format(this),o+=1):m+="%"):m+=t.charAt(o),o+=1;return m},k.fn.valid=function(){return this._i.year===!1&&this._i.month===!1&&this._i.day===!1&&this._i.hours===!1&&this._i.minutes===!1&&this._i.seconds===!1&&this._i.milliseconds===!1},k.fn.errors=function(){return this._i},k.fn.between=function(t,o){var m=this.timestamp(),g=t.timestamp();switch(o){case"year":return Math.floor((g-m)/31556952);case"month":return Math.floor((g-m)/2629746);case"day":return Math.floor((g-m)/86400);case"hours":return Math.floor((g-m)/3600);case"minutes":return Math.floor((g-m)/60);case"seconds":return g-m;default:return e}},k.fn.calc=function(t){return t.year!==e&&this._d.setFullYear(this._d.getFullYear()+t.year),t.month!==e&&this._d.setMonth(this._d.getMonth()+t.month),t.day!==e&&this._d.setDate(this._d.getDate()+t.day),t.hours!==e&&this._d.setHours(this._d.getHours()+t.hours),t.minutes!==e&&this._d.setMinutes(this._d.getMinutes()+t.minutes),t.seconds!==e&&this._d.setSeconds(this._d.getSeconds()+t.seconds),t.milliseconds!==e&&this._d.setMilliseconds(this._d.getMilliseconds()+t.milliseconds),this},n=function(t,o,m){return new k(t,o,m)},n.MIN_YEAR=1e3,n.MAX_YEAR=3e3,n.MIN_MONTH=1,n.MAX_MONTH=12,n.MIN_DAY=1,n.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],n.MIN_DAY_OF_WEEK=0,n.MAX_DAY_OF_WEEK=6,n.MIN_HOURS=0,n.MAX_HOURS=23,n.MIN_MINUTES=0,n.MAX_MINUTES=59,n.MIN_SECONDS=0,n.MAX_SECONDS=59,n.MIN_MILLISECONDS=0,n.MAX_MILLISECONDS=999,n.VERSION="0.2.18",n.options=function(t,o){if(t===e)return w;if(w.hasOwnProperty(t)){if(o===e)return w[t];w[t]=o,t==="monthFromZero"&&(n.MIN_MONTH=o?0:1,n.MAX_MONTH=o?11:12)}return e},n.noConflict=function(){return r.tempus=u,n},n.generate=function(t){var o,m,g,H,D,G,et,X;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof k?o=t.dateFrom.utc():o=n(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof k?m=t.dateTo.utc():m=n(t.dateTo,t.formatTo!==e?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?D={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?D={year:t.period==="year"?1:0,month:t.period==="month"?1:0,day:t.period==="day"?1:0,hours:t.period==="hours"?1:0,minutes:t.period==="minutes"?1:0,seconds:t.period==="seconds"?1:0}:typeof t.period=="object"&&(D={year:t.period.year!==e?t.period.year:0,month:t.period.month!==e?t.period.month:0,day:t.period.day!==e?t.period.day:0,hours:t.period.hours!==e?t.period.hours:0,minutes:t.period.minutes!==e?t.period.minutes:0,seconds:t.period.seconds!==e?t.period.seconds:0}),t.groupBy===e?G=t.asObject===!0?{}:[]:(G=[],G.push([]),et=n(o).get()[t.groupBy]),X=function(v,x,F){return t.asObject===!0?t.format!==e?v[n(x).format(t.format)]={}:v[n(x).format("%F %H:%M:%S")]={}:t.format!==e?v.push(F?null:n(x).format(t.format)):v.push(F?null:n(x)),v},t.groupBy!==e&&t.fillNulls){var K={year:D.year?-D.year:e,month:D.month?-D.month:e,day:D.day?-D.day:e,hours:D.hours?-D.hours:e,minutes:D.minutes?-D.minutes:e,seconds:D.seconds?-D.seconds:e,milliseconds:D.milliseconds?-D.milliseconds:e};for(g=n(o).calc(K).utc();n(g).get()[t.groupBy]===et;)X(G[G.length-1],g,!0),g=n(g).calc(K).utc();if(t.groupBy==="week"){var W=n(o).dayOfWeek();for(g=n(o).dayOfWeek(0).utc();G[0].length<W&&g<o;)X(G[G.length-1],g,!0),g=n(g).calc(D).utc()}}for(;o<=m;)t.groupBy===e?X(G,o):n(o).get()[t.groupBy]===et?X(G[G.length-1],o):(G.push([]),X(G[G.length-1],o),et=n(o).get()[t.groupBy]),o=n(o).calc(D).utc();if(t.groupBy!==e&&t.fillNulls)for(H=n(m).calc(D).utc();n(H).get()[t.groupBy]===et;)X(G[G.length-1],H,!0),H=n(H).calc(D).utc();return G},n.monthNames=function(t){switch(t){case"long":return y;default:return T}},n.dayNames=function(t){switch(t){case"long":return U;default:return p}},n.lang=function(t){if(t!==e)A=t,h[A]===e&&(A="en"),y=N(),T=_(),U=b(),p=S();else return A;return e},n.availableLangs=function(){return Object.keys(h)},n.registerFormat=function(t,o,m,g,H,D){R[t]={format:o,parse:m,minLength:g,maxLength:H,type:D}},n.unregisterFormat=function(t){delete R[t]},n.detectFormat=function(t){var o,m,g;return o=l(t,0),o!==""&&(g=10),m=t.charAt(g),(m==="T"||m===" ")&&(o+=m,g+=1),o+=c(t,g),o},f={TempusDate:k},n.classes=function(t,o){if(o===e)return f[t];f[t]=o},n.loadTranslations=function(t){typeof t=="object"?h=t:typeof t=="string"&&I(t,function(o){h=o},function(o){})},A=(d.language||d.systemLanguage||d.userLanguage||"en").substr(0,2).toLowerCase(),h[A]===e&&(A="en"),y=N(),T=_(),U=b(),p=S(),E.exports&&(s=E.exports=n),s.tempus=n}).call(C)})(ot,ot.exports);var Oe=ot.exports;const mt=Y(Oe),q=class q{constructor(s){L(this,bt);L(this,At);L(this,Mt);L(this,Dt);L(this,V);L(this,st);L(this,rt);L(this,kt);L(this,dt);typeof s=="function"?(this.callBatch=s,this.callMethod=null):(this.callBatch=(s==null?void 0:s.callBatch)||null,this.callMethod=(s==null?void 0:s.callMethod)||null),this.result={},this.errors={},this.timeLimit={limit:!1,date:void 0,pauseMs:void 0},this.timeLimitListeners=new Set,this.canContinue=!0,this.progressCall="",this.progressData="",this.progressTimer="",this.lastProgressSnapshot=null,this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.filterChunkSize=50,this.limit=50,this.progressDelay=100,this.operatingThreshold=475,this.defaultPauseMs=12e4,this.callLimitPauseMs=3e4,this.requestTimeoutMs=6e4}get progressPercent(){if(!this.progressData)return{percent:0,allCount:0,allTotal:0};const s=this.totalBatchCommands||0;if(s>0&&Array.isArray(this.batchCommandKeyOrder)&&this.batchCommandKeyOrder.length&&O(this,bt,ae).call(this)){let l=0;for(const A of this.batchCommandKeyOrder){const h=this.progressData[A];if(!h)continue;const N=Number(h.total)||0,_=Number(h.count)||0;N===0&&_===0?l+=1:N>0&&(l+=Math.min(1,_/N))}const u=l/s*100;let n=Math.max(0,Math.min(100,Math.floor(u)));const f=s,d=Math.min(s,Math.floor(l));return{percent:n,allCount:d,allTotal:f}}let e=0,r=0;for(const l of Object.values(this.progressData)){const{total:u,count:n}=l;e+=u??0,r+=n??0}const i=Number(this.chunkRate)||0;let a=0;e?a=r/e*100*i+this.totalProgress:r===0&&e===0?a=100*i+this.totalProgress:a=100,a=Math.max(0,Math.min(a,100));let c=Math.floor(a);return e>0&&r>=e&&(c=100),{percent:c,allCount:r,allTotal:e}}setProgressData({key:s,value:e,type:r}){var h,N;if(!this.progressCall)return;const i=this.getData(e.data()),a=Array.isArray(i)?i.length:0;let c=a;if(typeof e.total=="function"){const _=e.total();if(_!=null&&_!==""){const b=Number(_);Number.isFinite(b)&&(c=b)}}r==="count"&&(c=a);let l=1;i&&(l=a),this.progressData||(this.progressData={});const u=((h=this.progressData[s])==null?void 0:h.total)??0,n=((N=this.progressData[s])==null?void 0:N.count)??0,f=l+n,d=Math.max(u,c??0,f);if(this.progressData[s]={total:d,count:Math.min(f,d)},typeof document<"u"&&(document==null?void 0:document.hidden)===!0){O(this,At,Ft).call(this);return}O(this,At,Ft).call(this),this.progressTimer||(this.progressTimer=setInterval(()=>{if(!this.progressCall){this.clearProgressData();return}O(this,At,Ft).call(this);const{percent:_}=this.progressPercent;_>=100&&(clearInterval(this.progressTimer),this.progressTimer="")},this.progressDelay))}getData(s){if(s==null)return s;let e=(s==null?void 0:s.items)??(s==null?void 0:s.tasks)??(s==null?void 0:s.types)??(s==null?void 0:s.type)??(s==null?void 0:s.fields)??(s==null?void 0:s.workgroups)??s;return e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.result)&&(e=e.result),e}setTimeLimitState(s,e,r){this.timeLimit.limit=!!s,this.timeLimit.date=s?e:void 0,s&&typeof r=="number"&&r>0?this.timeLimit.pauseMs=r:this.timeLimit.pauseMs=void 0,O(this,Dt,Ae).call(this)}subscribeTimeLimit(s){return typeof s!="function"?()=>{}:(this.timeLimitListeners.add(s),s({limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs}),()=>{this.timeLimitListeners.delete(s)})}splitLargeFilters(s,e){const{method:r,params:i}=e;if(!i)return[{key:s,request:e}];const a=i.filter||i.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:s,request:e}];for(const[c,l]of Object.entries(a))if(!String(c).trim().startsWith("!")&&Array.isArray(l)&&l.length>this.filterChunkSize){const u=[];for(let n=0;n<l.length;n+=this.filterChunkSize){const f=l.slice(n,n+this.filterChunkSize),d=n===0?s:`${s}__chunk_${Math.floor(n/this.filterChunkSize)}`,A={...i};i.filter?(A.filter={...a},A.filter[c]=f):i.FILTER&&(A.FILTER={...a},A.FILTER[c]=f),u.push({key:d,request:{method:r,params:A},originalKey:s,filterKey:c,chunkIndex:Math.floor(n/this.filterChunkSize)})}return u}return[{key:s,request:e}]}mergeSplitResults(s,e){const r=[],i=String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${i}(?:__chunk_\\d+)?$`),c=Object.keys(s).filter(l=>a.test(l)).sort((l,u)=>{const n=l.match(/__chunk_(\d+)$/),f=u.match(/__chunk_(\d+)$/);return n?f?parseInt(n[1])-parseInt(f[1]):1:-1});for(const l of c){const u=s[l];Array.isArray(u)?r.push(...u):u&&r.push(u)}return r}delay(){return typeof document<"u"&&(document==null?void 0:document.hidden)===!0?Promise.resolve():new Promise(e=>setTimeout(e,500))}callBatchWithTimeout(s,e){return new Promise((r,i)=>{let a=!1,c=null;const l=async n=>{if(!a){a=!0,c&&clearTimeout(c);try{await Promise.resolve(e(n)),r()}catch(f){console.error("Error in callBatch callback:",f),i(f)}}},u=async()=>{if(!a){a=!0,c&&clearTimeout(c),console.warn(`Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`);const n={};Object.keys(s).forEach(f=>{n[f]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 60 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(e(n)),r()}catch(f){console.error("Error in timeout callback:",f),r()}}};try{this.callBatch(s,async n=>{await l(n)})}catch(n){a||console.error("Error calling callBatch:",n)}c=setTimeout(async()=>{a||(console.warn(`Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`),await u())},this.requestTimeoutMs)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.lastProgressSnapshot=null}async batch(s,e,r={}){O(this,dt,Qt).call(this,e);const i={},a={},c={};for(const[f,d]of Object.entries(s)){const A=this.arrayChunk(d);if(!A)continue;const h=this.splitLargeFilters(f,A);if(h.length===1)a[f]=A;else{c[f]=[];for(const N of h)a[N.key]=N.request,c[f].push(N.key)}}this.batchCommandKeyOrder=Object.keys(a),this.totalBatchCommands=this.batchCommandKeyOrder.length,this.batchCommandMethods=this.batchCommandKeyOrder.map(f=>{var d;return String(((d=a[f])==null?void 0:d.method)||"")}),this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let l={},u=0;const n=Object.keys(a).length;for(const[f,d]of Object.entries(a)){if(!this.canContinue)break;if(l[f]=d,Object.keys(l).length>=this.limit||u+1===n){const A=u+1===n;await this.batchChunk(l,void 0,!A,{disablePagination:!1,oneBatch:!!(r!=null&&r.oneBatch)}),Object.entries(this.result).forEach(([h,N])=>{i[h]=N}),this.totalProgress=Math.round(u/n*100),l={}}u++}for(const[f,d]of Object.entries(c))if(d&&d.length>0){const A=this.mergeSplitResults(i,f);for(const h of d)delete i[h];i[f]=A}return Object.entries(this.errors).length&&(i.errorsList=this.errors),e&&e({percent:100}),Promise.resolve(i)}async batchTotalCount(s,e){O(this,dt,Qt).call(this,e);const r={},i={},a={};for(const[u,n]of Object.entries(s)){const f=this.arrayChunk(n);if(!f)continue;const d=this.splitLargeFilters(u,f);if(d.length===1)i[u]=f;else{a[u]=[];for(const A of d)i[A.key]=A.request,a[u].push(A.key)}}const c=[],l=Object.entries(i);for(let u=0;u<l.length;u+=this.limit){const n=l.slice(u,u+this.limit),f={};for(const[d,A]of n){if(!this.canContinue)break;f[d]=A}Object.keys(f).length>0&&c.push(f)}this.chunkRate=(1/c.length).toFixed(5);for(const[u,n]of Object.entries(c)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(u)/c.length*100);const f=Number(u)===c.length-1;await O(this,rt,Et).call(this,n,async d=>{var A,h,N,_,b;for(const[S,y]of Object.entries(d)){if(!this.canContinue)return;if(y.error()){const R=(h=(A=y.error())==null?void 0:A.ex)==null?void 0:h.error,w=(_=(N=y.error())==null?void 0:N.ex)==null?void 0:_.error_description;this.errors[S]=R&&R.trim()||w&&w.trim()||((b=y.error())==null?void 0:b.toString())||"Неизвестная ошибка",r[S]=0;continue}const T=this.getData(y.data()),U=Array.isArray(T)?T.length:0,I=typeof y.total=="function"&&y.total()!==void 0?y.total():U;r[S]=I,this.setProgressData({key:S,value:y,type:"count"})}await O(this,st,Tt).call(this,d,!f)})}for(const[u,n]of Object.entries(a))if(n&&n.length>0){let f=0;for(const d of n)r[d]!==void 0&&(f+=r[d]||0),delete r[d];r[u]=f}return Object.entries(this.errors).length&&(r.errorsList=this.errors,this.errorLogger()),e&&e({percent:100}),Promise.resolve(r)}async call({method:s,params:e={}}){var r,i,a,c,l,u,n;for(;;){const f=await O(this,kt,ce).call(this,s,e);if(!f){await O(this,V,ut).call(this,this.callLimitPauseMs);continue}const d={};if(f!=null&&f.answer)for(const[h,N]of Object.entries(f.answer))h!=="result"&&N&&(d[h]=N);if(f.error()){const h=((i=(r=f.error())==null?void 0:r.ex)==null?void 0:i.error)??"";if(["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT","TIMEOUT"].includes(h)){await O(this,V,ut).call(this,this.callLimitPauseMs);continue}const N=((a=f.error())==null?void 0:a.toString())||((l=(c=f.error())==null?void 0:c.ex)==null?void 0:l.error_description)||((n=(u=f.error())==null?void 0:u.ex)==null?void 0:n.error)||"Неизвестная ошибка";return{success:!1,data:!1,answer:d,error:N}}let A=f.data();return A!=null&&A.items&&(A=A.items),{success:!0,data:A,answer:d,error:null}}}arrayChunk(s){let e="",r={};if(Array.isArray(s)?[e]=s:(e=s.method,r=s.params),(e.includes("list")||e==="user.get"||e==="entity.item.get")&&e!=="task.item.list"){if(!r)r=e==="entity.item.get"?{SORT:{ID:"ASC"}}:{order:{ID:"ASC",id:"ASC"}};else{e==="entity.item.get"?(r.SORT||(r.SORT={ID:"ASC"}),Array.isArray(r.select)?r.select.includes("ID")||r.select.push("ID"):r.select=["ID"]):e==="tasks.task.list"?(r.order||(r.order={}),r.order.ID="asc"):e==="user.get"?(r.sort||(r.sort="ID"),r.order||(r.order="ASC")):r.order={ID:"ASC",id:"ASC"},Array.isArray(r.select)&&!r.select.includes("ID")&&r.select.push("ID");const i=e==="user.get"||e==="entity.item.get"?r.FILTER:r.filter;typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.entries(i).forEach(([a,c])=>{(r.start===void 0||r.start!==-1)&&["id","ID"].includes(a)&&(typeof c=="string"||Array.isArray(c)&&c.length<=50)&&(r.start=-1)})}e==="crm.type.list"&&r.order&&delete r.order.ID}if(e==="task.item.list")if(!r)r=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(r[0])&&(r[0]={});const[i,a,c,l]=r;i.ID="ASC",l[0]!==""&&l.includes("ID")||l.push("ID")}return{method:e,params:r}}async batchChunk(s,e,r=!0,i={}){return new Promise(a=>{const c=[];let l;const u=!!(i!=null&&i.disablePagination);(async()=>{await O(this,rt,Et).call(this,s,async f=>{var A,h,N,_,b;for(const[S,y]of Object.entries(f)){if(!this.canContinue)return;if(y.error()){const g=(h=(A=y.error())==null?void 0:A.ex)==null?void 0:h.error,H=(_=(N=y.error())==null?void 0:N.ex)==null?void 0:_.error_description;this.errors[S]=g&&g.trim()||H&&H.trim()||((b=y.error())==null?void 0:b.toString())||"Неизвестная ошибка",l=!0}const T=this.getData(y.data()),U=Array.isArray(T)?T.length:0,p=typeof y.total=="function"&&y.total()!==void 0,I=p?y.total():U;e==="count"?this.result[S]?this.result[S]+=U:this.result[S]=I:this.result[S]=T,this.setProgressData({key:S,value:y,type:e});const R=s[S],w=Array.isArray(R)?R[0]:R==null?void 0:R.method,k=typeof w=="string"&&(w.includes(".list")||w==="user.get"||w==="entity.item.get"),t=e==="count"?!p&&U===this.limit:k?U===this.limit:I>this.limit&&I>U,o=e!=="count"&&w==="entity.item.get"&&U===this.limit&&!t,m=t||o;if(!u&&(!this.canContinue||m)){let g=s[S];if(Array.isArray(g)){const[H,D={}]=g;g=[H,D]}else{const{method:H,params:D={}}=g;g=[H,D]}c.push([S,g,I,{entityItemGetScan:o}])}}l>0&&this.errorLogger();const d=c.length>0||r;await O(this,st,Tt).call(this,f,d),c.length?await this.batchPayload(c,e,i).then(()=>a(this.result)):a(this.result)})})()})}async batchPayload(s,e,r={}){const i=!!(r!=null&&r.oneBatch),a=(N,_,b,S)=>{let y="ID";this.result[N][this.result[N].length-1].ID||(y="id");let T=`${y}`;if(JSON.stringify(S[1]).toLocaleLowerCase().includes('"id":"desc"')?T="<"+T:T=">"+T,_===1||b.length===0)return{field:T,id:this.result[N][this.result[N].length-1][y]};let p="";const[I,R]=S;return(I==="tasks.task.list"||I==="task.item.list")&&(p="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(I)&&(p="[items]"),I==="crm.type.list"&&(p="[types]"),I==="socialnetwork.api.workgroup.list"&&(p="[workgroups]"),{field:T,id:`$result[${[N,_-1].join("__")}]${p}[49][${y}]`}},c=(N,_)=>{const[b,S]=N;let y=JSON.parse(JSON.stringify(S)),T;if(b==="task.item.list"){y=[...y];const[U,p,I,R]=y;return p[_.field]=_.id,[b,y]}return["user.get"].includes(b)||y.FILTER?(y.FILTER||(y.FILTER={}),T=y.FILTER):(y.filter||(y.filter={}),T=y.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(b)?T[">ID"]=_.id:T[_.field]=_.id,[b,{...y,start:-1}]},l=N=>{Object.entries(N).forEach(([_,b])=>{var T,U,p,I,R;const[S]=_.split("__"),y=this.getData(b.data());if(Array.isArray(y)&&(e==="count"?this.result[S]+=y.length:this.result[S].push(...y)),b.error()){const w=(U=(T=b.error())==null?void 0:T.ex)==null?void 0:U.error,k=(I=(p=b.error())==null?void 0:p.ex)==null?void 0:I.error_description;this.errors[S]=w&&w.trim()||k&&k.trim()||((R=b.error())==null?void 0:R.toString())||"Неизвестная ошибка"}this.setProgressData({key:S,value:b,type:e})})},u=(N,_)=>{if(!Array.isArray(N)||N.length===0)return null;const b=N[N.length-1];let S="ID";b.ID||(S="id");let y=S;return JSON.stringify(_[1]).toLocaleLowerCase().includes('"id":"desc"')?y="<"+y:y=">"+y,{field:y,id:b[S]}},n=1e4,f=async(N,_)=>{var S,y;let b=this.limit;for(let T=1;this.canContinue&&b===this.limit&&T<=n;T++){const U=this.result[N],p=u(U,_);if(!p)break;const I=`${N}__eiscan_${T}`,R=c(_,p);let w=null;await O(this,rt,Et).call(this,{[I]:R},async m=>{w=m,l(m)});const k=T<n;await O(this,st,Tt).call(this,w,k),await this.delay();const t=w==null?void 0:w[I];if((S=t==null?void 0:t.error)!=null&&S.call(t)){b=0;break}const o=this.getData((y=t==null?void 0:t.data)==null?void 0:y.call(t));b=Array.isArray(o)?o.length:0}};let d=[],A=0;const h=async(N=!0)=>d.length?(await O(this,rt,Et).call(this,Object.fromEntries(d),async _=>{l(_),await O(this,st,Tt).call(this,_,N)}),A++,d=[],i&&A>=1?!0:(await this.delay(),!1)):!1;for await(const N of s){if(!this.canContinue)return;const[_,b,S,y={}]=N;if(y.entityItemGetScan){if(await h(!0))return;if(i)continue;await f(_,b);continue}let T=1;for(;S>T*this.limit;){const U=[_,T].join("__"),p=a(_,T,d,b);if(d.push([U,c(b,p)]),i&&d.length===49&&await h(!0)||d.length%50===0&&await h(!0))return;T++}}await h(!1)}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([s,e])=>{e&&console.log(`[${s}]`,e.toString())}),console.groupEnd()}};bt=new WeakSet,ae=function(){const s=this.totalBatchCommands||0,e=this.batchCommandMethods;if(s<M(q,Rt)||!Array.isArray(e)||e.length!==s)return!1;if(e.filter(a=>a==="crm.deal.list").length>=M(q,Lt))return!0;const i=e.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=M(q,St)&&i/s>=M(q,It)},Rt=new WeakMap,Lt=new WeakMap,St=new WeakMap,It=new WeakMap,At=new WeakSet,Ft=function(){if(!this.progressCall||!this.progressData)return;const{percent:s,allCount:e,allTotal:r}=this.progressPercent,i={percent:s,allCount:e,allTotal:r};O(this,Mt,oe).call(this,i)&&(this.progressCall({data:this.progressData,percent:s,allCount:e,allTotal:r}),this.lastProgressSnapshot=i)},Mt=new WeakSet,oe=function(s){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==s.percent||this.lastProgressSnapshot.allCount!==s.allCount||this.lastProgressSnapshot.allTotal!==s.allTotal:!0},Dt=new WeakSet,Ae=function(){const s={limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs};for(const e of this.timeLimitListeners)try{e(s)}catch(r){console.warn("Batch timeLimit listener error:",r)}},V=new WeakSet,ut=async function(s=this.defaultPauseMs){this.setTimeLimitState(!0,new Date().toISOString(),s),await new Promise(e=>setTimeout(e,s)),this.setTimeLimitState(!1,void 0)},st=new WeakSet,Tt=async function(s,e=!0){if(!e)return 0;let r=0;if(!s||typeof s!="object")return 0;for(const i of Object.values(s))if(!(!i||typeof i!="object"))try{if(typeof i.time=="function"){const a=i.time();a&&typeof a.operating=="number"&&(r=Math.max(r,a.operating))}}catch{}r>=this.operatingThreshold&&await O(this,V,ut).call(this)},rt=new WeakSet,Et=async function(s,e){let r=!1,i=s;do r=!1,await this.callBatchWithTimeout(i,async a=>{var u,n;let c=!1;const l=new Set;for(const[f,d]of Object.entries(a||{})){if(!(d!=null&&d.error)||!d.error())continue;const A=((n=(u=d.error())==null?void 0:u.ex)==null?void 0:n.error)??"";if(A==="TIMEOUT"){c=!0;break}["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT"].includes(A)&&l.add(f)}if(c){r=!0,await O(this,V,ut).call(this);return}if(l.size>0){const f={};for(const[A,h]of Object.entries(a||{}))l.has(A)||(f[A]=h);Object.keys(f).length&&await e(f);const d={};for(const A of l)i[A]&&(d[A]=i[A]);i=d,Object.keys(i).length&&(r=!0,await O(this,V,ut).call(this));return}await e(a)});while(r)},kt=new WeakSet,ce=function(s,e){return new Promise(r=>{if(typeof this.callMethod!="function"){r(null);return}let i=!1;const a=setTimeout(()=>{i||(i=!0,r(null))},this.requestTimeoutMs);try{this.callMethod(s,e,c=>{i||(i=!0,clearTimeout(a),r(c))})}catch{i||(i=!0,clearTimeout(a),r(null))}})},dt=new WeakSet,Qt=function(s){this.clearProgressData(),this.progressCall=typeof s=="function"?s:"",this.canContinue=!0,this.result={},this.errors={},this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.setTimeLimitState(!1,void 0)},L(q,Rt,5),L(q,Lt,5),L(q,St,8),L(q,It,.65);let z=q;class jt{constructor(){L(this,it,{})}get hash(){return this.createHash(8)}createHash(s){let e="abcdefghijklmnopqrstuvwxyz0123456789",r="";s=s||6;for(let i=0;i<s;i++)r+=e.charAt(Math.floor(Math.random()*e.length));return r}actionFilter({keyTimer:s,duration:e=10,action:r}){M(this,it)[s]&&(clearTimeout(M(this,it)[s]),M(this,it)[s]=null),r&&(M(this,it)[s]=setTimeout(()=>{r()},e))}async noSleep(){let s=document.createElement("video");s.classList.add("no-sleep"),s.muted=!0,s.autoplay=!0,s.setAttribute("playsinline",""),s.addEventListener("loadeddata",()=>{s.style.position="fixed",s.style.left="-9999px",document.querySelector("body").append(s),s.play().catch(e=>{console.warn("noSleep: autoplay prevented",e)})}),s.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{s.play().catch(e=>{console.warn("noSleep: replay prevented",e)})}})}),s.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(s,e){let r=new Blob([JSON.stringify(s)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=i,a.download=`${e}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(i)},200)}}it=new WeakMap;const Jt=new jt;class se{constructor(){L(this,Bt);L(this,yt);L(this,wt);L(this,Ct);L(this,Ht);L(this,Q,"logger");L(this,Z,!1);L(this,nt,new Map);L(this,ct,{});L(this,gt,!1);L(this,$,null);L(this,J,null);L(this,at,!1);L(this,lt,!1);P(this,"periodClear",3)}async init(){try{let s=new z(BX24.callBatch),{entityList:e}=await s.batch({entityList:{method:"entity.get"}});if(e&&Array.isArray(e))if(e.find(i=>i.ENTITY==M(this,Q)))j(this,Z,!0);else{let{entityAdd:i}=await s.batch({entityAdd:{method:"entity.add",params:{ENTITY:M(this,Q),NAME:M(this,Q),ACCESS:{AU:"X"}}}});i&&j(this,Z,!0)}return M(this,Z)}catch(s){return console.error("Ошибка при инициализации логера:",s),!1}}enableBackworkerMode(){return j(this,Z,!0),!0}start({type:s,data:e}){if(!M(this,Z))return O(this,yt,Zt).call(this,"entity"),null;if(!s||!e)return console.error("Невалидные данные для логирования:",{type:s,data:e}),null;const r=Jt.hash,i={type:s,data:e,userInfo:null,errorList:{},status:"",answer:null,date:new Date().getTime()};return M(this,nt).set(r,i),j(this,lt,!0),r}async stop({key:s,errorList:e,status:r,answer:i}){var c;if(!M(this,lt))return;if(!M(this,Z)){O(this,yt,Zt).call(this,"entity");return}let a=M(this,nt).get(s);if(!a){console.error(`Не найдены данные логирования для ключа: ${s}`);return}e&&(a.errorList=e),r&&(a.status=r),i&&(a.answer=i),await O(this,Bt,le).call(this),a.userInfo=M(this,ct),await O(this,wt,he).call(this),(c=a==null?void 0:a.data)!=null&&c.updateList&&j(this,at,!0),j(this,lt,!1)}async getEntityList(s){var e;try{if((e=M(this,J))!=null&&e.length&&!M(this,at))return M(this,J);let r=new z(BX24.callBatch),{entityList:i}=await r.batch({entityList:{method:"entity.item.get",params:{ENTITY:M(this,Q),SORT:{ID:"DESC"}}}},s);return!i||!Array.isArray(i)?(console.warn("Получен невалидный список записей"),[]):(i=i.map(a=>{try{const{ID:c,DATE_CREATE:l,DETAIL_TEXT:u}=a;return{...JSON.parse(u),id:c,dateCreate:l}}catch(c){return console.error(`Ошибка парсинга записи ${a.ID}:`,c),null}}).filter(a=>a!==null),j(this,at,!1),j(this,J,i),i)}catch(r){return console.error("Ошибка при получении списка записей:",r),[]}}runStorageMaintenance(){return O(this,Ct,ue).call(this)}async downAllEntityJson(){try{if(M(this,J)||await this.getEntityList(),!M(this,J)||M(this,J).length===0)return console.warn("Нет данных для выгрузки"),!1;let s=mt().format("%Y-%m-%d");return Jt.downloadFileJson(M(this,J),`sdklogger-entity-data__${s}`),!0}catch(s){return console.error("Ошибка при выгрузке данных в JSON:",s),!1}}}Q=new WeakMap,Z=new WeakMap,nt=new WeakMap,ct=new WeakMap,gt=new WeakMap,$=new WeakMap,J=new WeakMap,at=new WeakMap,lt=new WeakMap,Bt=new WeakSet,le=async function(){if(!M(this,gt))return M(this,$)?M(this,$):(j(this,$,(async()=>{try{const s=new z(BX24.callBatch),e=BX24.isAdmin(),{curUser:r}=await s.batch({curUser:{method:"user.current"}});j(this,ct,{isAdmin:e,curUser:r})}catch(s){console.error("Ошибка при получении информации о пользователе:",s),j(this,ct,{isAdmin:!1,curUser:null})}finally{j(this,gt,!0),j(this,$,null)}})()),M(this,$))},yt=new WeakSet,Zt=function(s){s=="entity"&&Jt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},wt=new WeakSet,he=async function(){try{let s={},e=new z(BX24.callBatch);for(let[r,i]of M(this,nt).entries())if(i.status){const a=JSON.stringify(i);s[r]={method:"entity.item.add",params:{ENTITY:M(this,Q),NAME:M(this,Q),DETAIL_TEXT:a}}}if(Object.keys(s).length){let r=await e.batch(s),{errors:i}=e;for(let[a,c]of Object.entries({...r,...i}))M(this,nt).delete(a);return!0}return!1}catch(s){return console.error("Ошибка при добавлении записей в хранилище:",s),!1}},Ct=new WeakSet,ue=async function(){try{let s=new z(BX24.callBatch),{serverTime:e}=await s.batch({serverTime:{method:"server.time"}});if(!e){console.error("Не удалось получить время сервера");return}if(M(this,J)||await this.getEntityList(),!M(this,J)||M(this,J).length===0)return;let r=M(this,J).filter(i=>{try{let{dateCreate:a}=i;return a?mt(new Date(a)).between(mt(new Date(e)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});r.length>0&&(console.log(`Найдено ${r.length} записей для очистки (старше ${this.periodClear} месяцев)`),await O(this,Ht,fe).call(this,r))}catch(s){console.error("Ошибка при проверке периода очистки:",s)}},Ht=new WeakSet,fe=async function(s){try{if(!s||s.length===0)return!1;let e=new z(BX24.callBatch),r=s.filter(a=>a&&a.id).map(a=>{let{id:c}=a;return{method:"entity.item.delete",params:{ENTITY:M(this,Q),ID:c}}});if(r.length===0)return!1;const i=await e.batch(r);return console.log(`Успешно удалено ${r.length} записей`),j(this,at,!0),i}catch(e){return console.error("Ошибка при очистке устаревших записей:",e),!1}};function Kt(E){if(!E||typeof E!="string")return"";try{const s=new URL(E);s.search="",s.hash="";let e=s.toString();return e.endsWith("/")&&s.pathname!=="/"&&(e=e.slice(0,-1)),e}catch{return E.split("?")[0].split("#")[0].replace(/\/$/,"")}}function re(E){return!E||typeof E!="string"?!1:E.toLowerCase().includes("/marketplace/app")}function _e(){var s;if(typeof window>"u"||!((s=window.location)!=null&&s.href))return"";const E=Kt(window.location.href);return re(E)?"":E}function vt(E){if(!(E!=null&&E.appConst)||typeof E.appConst!="object")return"";const s=_e();return s?(E.appConst.pathApp=s,s):Kt(E.appConst.pathApp??"")}class Te{constructor(s){L(this,ht);L(this,Ut);L(this,pt);L(this,Gt);L(this,Pt);L(this,Yt);L(this,tt);L(this,Nt);L(this,Wt);L(this,Ot);L(this,xt);P(this,"domain","");P(this,"isAdmin",!1);P(this,"appInfo",null);P(this,"appConst",null);P(this,"userInfo",null);P(this,"placeData",null);P(this,"placeInfo",null);P(this,"logger",!1);P(this,"timeLimit",{limit:!1,date:void 0,pauseMs:void 0});P(this,"batchClient",null);this.appConst=s}subscribeTimeLimit(s){return O(this,ht,Xt).call(this).subscribeTimeLimit(s)}init(){return new Promise((s,e)=>{const i=setTimeout(()=>{clearInterval(a);const c=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(c),e(c)},3e4);let a=setInterval(()=>{window.BX24&&BX24.init(async()=>{clearInterval(a),clearTimeout(i),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info();const c=O(this,Gt,de).call(this);if(console.info(c?"init BX24 (background worker)":"init BX24"),this.appInfo=await O(this,Pt,ge).call(this),this.userInfo=await O(this,Yt,ye).call(this),vt(this),c)await O(this,pt,Vt).call(this,!1,{skipInit:!0});else{await O(this,pt,Vt).call(this,!0);const l=new jt;try{l.noSleep()}catch(u){console.warn("Failed to initialize noSleep:",u)}}s({isBackworker:c})})},100)})}userOption(s,e){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.userOption.set(s,e):BX24.userOption.get(s)}appOption(s,e){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.appOption.set(s,e):BX24.appOption.get(s)}async call({method:s,params:e,updateList:r}){let i;if(r&&(i=this.logger.start({type:"call",data:{method:s,params:e,updateList:r}})),e||(e={}),typeof BX24>"u"||!BX24.callMethod){const l=new Error("BX24 is not initialized");throw console.error(l),l}const c=await O(this,ht,Xt).call(this).call({method:s,params:e});return c.success?(await O(this,tt,ft).call(this,i,{answer:c.answer,status:"success"}),c.data):(console.error(c.error),await O(this,tt,ft).call(this,i,{answer:c.answer,status:"fail",errorList:{0:c.error||"Unknown call error"}}),!1)}async batch(s,e,{errorCall:r,updateList:i,batchOptions:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const c=new Error("BX24 is not initialized");return console.error(c),!1}return O(this,Nt,$t).call(this,{mode:"batch",commandList:s,progressCall:e,errorCall:r,updateList:i,batchOptions:a})}async batchTotalCount(s,e,{errorCall:r,updateList:i}={}){if(typeof BX24>"u"||!BX24.callBatch){const a=new Error("BX24 is not initialized");return console.error(a),!1}return O(this,Nt,$t).call(this,{mode:"batch-total-count",commandList:s,progressCall:e,errorCall:r,updateList:i})}async getPlacement(){const s=await this.call({method:"placement.get"});return this.placeData||(this.placeData=s),s}async placementBind(s){var A;if(!this.isAdmin||(this.placeData=await this.getPlacement(),!this.placeData))return;const{appName:e,pathApp:r}=this.appConst;let i=O(this,Ot,te).call(this,s);i=i.filter(h=>h.placement!=="PAGE_BACKGROUND_WORKER"&&h.placement!=="PAGE_BACKGROUND_WORKER_ALL");const a=O(this,xt,Ne).call(this,r),c=new Set(i.map(h=>h.placement));for(const h of a)c.has(h.placement)||i.push({placement:h.placement});if(i.length===0)return;let l=e;this.domain==="szdl.bitrix24.ru"&&((A=this.appInfo)!=null&&A.ID)&&(l=`${e}: #${this.appInfo.ID}`);const u=l.replace(" CRM",""),n={},f=[],d=new Map;for(const h of this.placeData)d.has(h.placement)||d.set(h.placement,[]),d.get(h.placement).push(h);for(let h=0;h<i.length;h++){const{placement:N,options:_}=i[h],b=d.get(N)||[];if(b.some(T=>T.handler===r))continue;const y=b.filter(T=>T.handler!==r);for(const T of y)f.push({placement:N,handler:T.handler});n[`bind_${h}`]={method:"placement.bind",params:{PLACEMENT:N,HANDLER:r,LANG_ALL:{ru:{TITLE:N==="USER_PROFILE_TOOLBAR"?u:l}},OPTIONS:{errorHandlerUrl:r,..._&&typeof _=="object"?_:{}}}}}f.length>0&&await this.placementUnBind(f),Object.keys(n).length>0&&(await this.batch(n),this.placeData=await this.getPlacement(),Object.values(n).forEach(h=>{console.log("Приложение успешно встроено в",h.params.PLACEMENT)}))}async placementUnBind(s){let e=O(this,Ot,te).call(this,s);if(e=e.filter(i=>i.placement!=="PAGE_BACKGROUND_WORKER"&&i.placement!=="PAGE_BACKGROUND_WORKER_ALL"),e.length===0)return;const r={};for(let i=0;i<e.length;i++){const a={PLACEMENT:e[i].placement};e[i].handler&&(a.HANDLER=e[i].handler),r[`unbind_${i}`]={method:"placement.unbind",params:a}}await this.batch(r),e.forEach(i=>{console.log("Встройка отвязана",i.placement)})}async getBotList(){const s=await this.call({method:"imbot.bot.list",params:{}}),e=Object.values(s);return console.log("chat-bot list:",e),e}async regBot({code:s,type:e,name:r}){const{appName:i,pathApp:a,chatBotLogo:c}=this.appConst,l=this.appInfo.ID,u=await this.call({method:"imbot.register",params:{CODE:s??this.appInfo.CODE,TYPE:e??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${r??i} - бот #${l}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:mt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:c??""}}});return console.log("Чат-бот добавлен",u),u}async unRegBot(s){const e=await this.call({method:"imbot.unregister",params:{BOT_ID:s}});return console.log("чат-бот удален",e),e}getLoggerList(s){return this.logger.getEntityList(s)}}ht=new WeakSet,Xt=function(){return this.batchClient||(this.batchClient=new z({callBatch:BX24.callBatch,callMethod:BX24.callMethod}),this.timeLimit=this.batchClient.timeLimit),this.batchClient},Ut=new WeakSet,me=function(){return{start:()=>{},stop:()=>{},getEntityList:()=>{}}},pt=new WeakSet,Vt=async function(s,{skipInit:e=!1}={}){this.logger?(this.logger=new se,e?this.logger.enableBackworkerMode():await this.logger.init(),s&&typeof this.logger.runStorageMaintenance=="function"&&this.logger.runStorageMaintenance()):this.logger=O(this,Ut,me).call(this)},Gt=new WeakSet,de=function(){var r,i,a;const s=(r=this.placeInfo)==null?void 0:r.placement,e=(a=(i=this.placeInfo)==null?void 0:i.options)==null?void 0:a.ID;return s==="PAGE_BACKGROUND_WORKER"||e==="PAGE_BACKGROUND_WORKER"},Pt=new WeakSet,ge=function(){return this.call({method:"app.info"})},Yt=new WeakSet,ye=function(){return this.call({method:"user.current"})},tt=new WeakSet,ft=async function(s,e){if(s)try{await this.logger.stop({key:s,...e})}catch(r){console.error("Logger error:",r)}},Nt=new WeakSet,$t=async function({mode:s,commandList:e,progressCall:r,errorCall:i,updateList:a,batchOptions:c}){const l=O(this,ht,Xt).call(this),u=a?this.logger.start({type:s,data:s==="batch"?{commandList:e,updateList:a}:{commandList:e}}):void 0;try{const n=s==="batch"?await l.batch(e,r,c):await l.batchTotalCount(e,r),f=O(this,Wt,pe).call(this,l,n,e,a);return Object.keys(f).length?(i&&i(f),await O(this,tt,ft).call(this,u,{status:"fail",errorList:f})):await O(this,tt,ft).call(this,u,{status:"success"}),n}catch(n){return await O(this,tt,ft).call(this,u,{status:"fail-runtime",errorList:{0:n==null?void 0:n.toString()}}),console.error(n),!1}},Wt=new WeakSet,pe=function(s,e,r,i){let a={...s.errors};if(Object.values(s.errors).some(l=>{if(typeof l!="string")return!1;const u=l.toUpperCase();return u==="TIMEOUT"||u==="OPERATION_TIME_LIMIT"||u.includes("TIMEOUT")||u.includes("OPERATION_TIME_LIMIT")})&&i){const l=e?Object.keys(e).filter(d=>d!=="errorsList"):[],u=new Set(Object.keys(s.errors||{})),n=new Set;if(e){for(const d of l)if(!u.has(d)){const A=e[d];A!=null&&n.add(d)}}const f=Object.values(s.errors).find(d=>{if(typeof d!="string")return!1;const A=d.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const d of Object.keys(r))!n.has(d)&&!s.errors[d]&&(a[d]=f||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a},Ot=new WeakSet,te=function(s){if(!s)return[];let e=[];return Array.isArray(s)?e=s.map(r=>typeof r=="string"?{placement:r}:r):typeof s=="string"?e=[{placement:s}]:e=[s],e},xt=new WeakSet,Ne=function(s){return this.placeData?this.placeData.filter(e=>!(e.placement==="PAGE_BACKGROUND_WORKER"||!e.handler||e.handler.includes(s))):[]};const ie="szdl-utils-kit|";function Ee(){if(typeof sessionStorage>"u")return`ephemeral-${Date.now()}-${Math.random().toString(16).slice(2)}`;let E=sessionStorage.getItem("szdl-cross-tab-instance-id");return E||(E=`${Date.now()}-${Math.random().toString(16).slice(2)}`,sessionStorage.setItem("szdl-cross-tab-instance-id",E)),E}function be(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}const zt=new Map;function Re(E="default"){if(typeof BroadcastChannel>"u")return null;const s=`${ie}bc:${E}`;return zt.has(s)||zt.set(s,new BroadcastChannel(s)),zt.get(s)}function ne(E,s){const e=Re(E);if(e)try{const r=s&&typeof s=="object"&&!Array.isArray(s)?s:{data:s};e.postMessage({...r,tabId:Ee(),ts:Date.now()})}catch{}}async function Le(E,s,e={}){const{ifAvailable:r=!1}=e,i=typeof E=="string"&&E.length>0?E:"default",a=`${ie}${i}`;return be()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!r},async c=>{if(r&&c==null)return{skipped:!0,coordination:"locks"};ne(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await s(),coordination:"locks"}}finally{ne(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await s(),coordination:"none"}}class Se{constructor(s){L(this,_t);P(this,"entityName","tabs");P(this,"maxTabs",20);P(this,"tabList",[]);P(this,"id",0);P(this,"hasStarted",!1);P(this,"heartbeat");P(this,"runHeartbeat");P(this,"activeMaxPause",10*1e3);P(this,"quickCleanupThreshold",2*60*1e3);P(this,"pollInterval",6*1e3+Math.floor(Math.random()*2e3));P(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);P(this,"continueCondition");P(this,"defaultContinueBackground",()=>!0);var c,l,u;if(!s){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:e,bx:r,users:i,continueBackground:a}=s;this.bx=r,this.appInit=e,this.users=i,vt(r),this.appPath=O(this,_t,ee).call(this,((c=r==null?void 0:r.appConst)==null?void 0:c.pathApp)??""),this.appName=((l=r==null?void 0:r.appConst)==null?void 0:l.appName)??"",this.appCodeName=((u=r==null?void 0:r.appConst)==null?void 0:u.appCodeName)??"",this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("BackgroundWorker: appInit не передан");return}if(!this.bx){console.error("BackgroundWorker: bx не передан");return}if(this.isAppPage()){console.log("BackgroundWorker: Страница приложения, фоновый воркер не запускается");return}await this.checkPlacementType()&&await this.continueBackground()&&(await this.checkEntity(),await this.refreshTabs(!0),await this.ensureTabRegistered(),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(e=>{console.error("BackgroundWorker: backgroundTick failed",e)})},this.pollInterval),await this.backgroundTick())}async backgroundTick(){if(!await this.continueBackground()){this.stopTimers(),console.log("BackgroundWorker: Остановка backgroundTick - условие не выполнено");return}await this.refreshTabs(!0),await this.ensureTabRegistered();const e=this.selectLeaderId(),r=e&&+this.id==+e;await this.updateTabState(r),r&&!this.hasStarted&&await this.runAsLeader()}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var s;if(typeof BX24>"u"||!((s=BX24.placement)!=null&&s.info))return!1;try{const e=BX24.placement.info(),r=e==null?void 0:e.placement,i=(e==null?void 0:e.options)||{},a=(i==null?void 0:i.URI)||"",c=r==="PAGE_BACKGROUND_WORKER"||(i==null?void 0:i.ID)==="PAGE_BACKGROUND_WORKER",l=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!c||l}catch{return!1}}async checkEntity(){var r;const s=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((r=s==null?void 0:s.find)==null?void 0:r.call(s,i=>i.ENTITY===this.entityName))||await this.safeCall(()=>this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}}))}async getTabs(){const s=await this.safeCall(()=>{var e;return this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:(e=this.bx.userInfo)==null?void 0:e.ID},SORT:{DATE_CREATE:"DESC"}}})});return!Array.isArray(s)||!s.length?[]:s.map(e=>{if(!e)return{id:void 0,data:void 0};try{const r=JSON.parse(e.DETAIL_TEXT);return{id:+e.ID||0,data:r}}catch(r){return console.log("BackgroundWorker: parse tab error",r),{id:+e.ID||0,data:void 0}}})}async ensureTabRegistered(){if(this.id)return+this.id||0;if(this.tabList.length>=this.maxTabs&&await this.refreshTabs(!0,this.quickCleanupThreshold),this.tabList.length>=this.maxTabs)return console.log("BackgroundWorker: Достигнут лимит вкладок даже после быстрой очистки, не регистрируемся"),0;const s={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId},e=await this.safeCall(()=>{var r;return this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(s)}})})||0;return this.id=+e||0,this.id}async updateTabState(s){if(!this.id)return;const e={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:s,sessionId:this.sessionId};await this.safeCall(()=>{var r;return this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(e)}})})}async deleteTabs(s=[]){if(!s.length)return;const e=s.map(r=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:r.id}}));await this.safeCall(()=>this.bx.batch(e))}async checkPlacementType(){var s,e;try{if(!((s=this.bx)!=null&&s.isAdmin))return!0;const r=await this.safeCall(()=>this.bx.getPlacement());if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),a=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),c=!a;if(!i)return!0;let l=!1;for(const u of r){if(u.placement!=="PAGE_BACKGROUND_WORKER"||!(u.userId||u.handler&&u.handler.includes("USER_ID=")))continue;const f=u.userId||(u.handler?this.extractUserIdFromHandler(u.handler):null);if(f&&+f===i){l=!0;break}}return a?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):c&&l?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}isIndividualPlacement(s){return!s||typeof s!="string"?!1:s.includes("USER_ID=")}extractUserIdFromHandler(s){if(!s||typeof s!="string")return null;const e=s.match(/USER_ID=(\d+)/);return e?+e[1]:null}async continueBackground(){try{const e=!!await Promise.resolve(this.continueCondition(this));return console.log(e?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),e}catch(s){return console.error("BackgroundWorker: Ошибка в continueCondition",s),!1}}async refreshTabs(s=!1,e=this.activeMaxPause){const r=[],i=[],a=Date.now(),c=await this.getTabs();for(const l of c){if(!(l!=null&&l.data)){r.push(l);continue}if(a-new Date(l.data.lastActive||0).getTime()>e){r.push(l);continue}i.push(l)}return s&&r.length&&await this.deleteTabs(r),this.tabList=i,i}selectLeaderId(){var e;return this.tabList.length&&+((e=[...this.tabList].sort((r,i)=>{var l,u,n,f;const a=new Date(((l=r.data)==null?void 0:l.createdAt)||((u=r.data)==null?void 0:u.lastActive)||0).getTime(),c=new Date(((n=i.data)==null?void 0:n.createdAt)||((f=i.data)==null?void 0:f.lastActive)||0).getTime();return a===c?(+r.id||0)-(+i.id||0):a-c})[0])==null?void 0:e.id)||0}async runAsLeader(){var i,a;const s=String(((a=(i=this.bx)==null?void 0:i.userInfo)==null?void 0:a.ID)??"0"),e=`background-worker:${this.entityName}:${s}`;(await Le(e,async()=>{this.hasStarted=!0;const c=Math.min(this.activeMaxPause-1500,Math.max(2500,Math.floor(this.pollInterval/2)));this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(l=>console.error("BackgroundWorker: heartbeat update failed",l))},c);try{await this.appInit()}catch(l){console.error("BackgroundWorker: appInit failed",l)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)},{ifAvailable:!0})).skipped&&console.log("BackgroundWorker: runAsLeader пропущен — Web Lock у другой вкладки (тот же фоновый воркер)")}async setBackgroundWorkerAll(){var S,y,T,U;if(!((S=this.bx)!=null&&S.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(y=this.users)!=null&&y.length||await this.getEntityData(),vt(this.bx);const s=O(this,_t,ee).call(this,((U=(T=this.bx)==null?void 0:T.appConst)==null?void 0:U.pathApp)??"");if(!s){console.error("BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена");return}const e=await this.safeCall(()=>this.bx.getPlacement()),r=new Map,i=new Map;let a=null;(e||[]).forEach(p=>{if(p.placement!=="PAGE_BACKGROUND_WORKER")return;if(p.userId||p.handler&&p.handler.includes("USER_ID=")){const R=p.userId||(p.handler?this.extractUserIdFromHandler(p.handler):null);if(R){const w=+R;r.set(w,p),i.has(w)||i.set(w,[]),i.get(w).push(p)}}else a=p});const c=await this.resolveAdmins(),l=await this.getEligibleUsersForBackgroundWorker(c);l.sort((p,I)=>{const R=p.LAST_LOGIN?new Date(p.LAST_LOGIN):new Date(0);return(I.LAST_LOGIN?new Date(I.LAST_LOGIN):new Date(0))-R});const u=10,n=l.slice(0,u),f=n.filter(p=>{const I=r.get(+p.ID);if(!I)return!0;const R=`${s}?USER_ID=${p.ID}/`;return I.handler!==R}),d=[];for(const[p]of r){const I=+p||0;l.find(w=>+w.ID===I)||d.push(I)}for(const p of n){const I=r.get(+p.ID);if(!I)continue;const R=`${s}?USER_ID=${p.ID}/`;I.handler!==R&&d.push(+p.ID)}const A=[],h=[...new Set(d)];for(const p of h){const I=i.get(+p)||[];for(const R of I)R!=null&&R.handler&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:R.handler}})}const N=a&&(f.length>0||a.handler!==`${s}`);N&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:a.handler||`${s}`}});for(const p of f)A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${s}?USER_ID=${p.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${s}?USER_ID=${p.ID}/`},USER_ID:p.ID}});(!a||N)&&A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${s}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${s}`}}});const _=A.filter(p=>p.method==="placement.unbind"),b=A.filter(p=>p.method==="placement.bind");_.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(_.map((p,I)=>[`unbind_${I}`,p])))),b.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(b.map((p,I)=>[`bind_${I}`,p])))),A.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var s,e;try{const r=+(((s=this.bx.userInfo)==null?void 0:s.ID)??0),i=!!((e=this.bx)!=null&&e.isAdmin),a=await this.getAdminsList()||[];if(!i){if(r&&a.includes(+r)){const u=a.filter(n=>+n!=+r);return await this.saveAdminsList(u),u}return a}const c=new Set([...a||[]]);r&&c.add(+r);const l=[...c].filter(Boolean);return await this.saveAdminsList(l),l}catch(r){return console.error("BackgroundWorker: resolveAdmins error",r),[]}}async getEligibleUsersForBackgroundWorker(s=[]){const e=(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0),r=s.map(i=>+i||0).filter(Boolean);return e.filter(i=>r.includes(+i.ID||0))}async saveAdminsList(s=[]){try{BX24.appOption.set("adminsList",JSON.stringify(s))}catch(e){console.error("BackgroundWorker: saveAdminsList error",e)}}async getAdminsList(){try{const s=BX24.appOption.get("adminsList"),e=s?JSON.parse(s):[];return Array.isArray(e)?e.map(r=>+r||0).filter(Boolean):[]}catch(s){return console.error("BackgroundWorker: getAdminsList error",s),[]}}async getEntityData(){const s={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:e}=await this.safeCall(()=>this.bx.batch(s).then(r=>r?(Array.isArray(r.users)||(r.users=[]),r):{users:[]}));this.users=e}async ensureAdminPlacements(){var s,e;(s=this.bx)!=null&&s.isAdmin&&((e=this.users)!=null&&e.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(s=500,e){return new Promise(r=>{setTimeout(()=>{e&&e(),r(!0)},s)})}async safeCall(s){try{return await s()}catch(e){console.error("BackgroundWorker: safeCall error",e);return}}}_t=new WeakSet,ee=function(s){if(!s||typeof s!="string")return"";const e=Kt(s).replace(/\/+$/,"");return e?re(e)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):e:""},B.BackgroundWorker=Se,B.Batch=z,B.BxBoot=Te,B.BxHelper=jt,B.BxLogger=se,B.tempus=mt,Object.defineProperty(B,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
var Be=Object.defineProperty;var we=(k,H,Y)=>H in k?Be(k,H,{enumerable:!0,configurable:!0,writable:!0,value:Y}):k[H]=Y;var C=(k,H,Y)=>(we(k,typeof H!="symbol"?H+"":H,Y),Y),Zt=(k,H,Y)=>{if(!H.has(k))throw TypeError("Cannot "+Y)};var S=(k,H,Y)=>(Zt(k,H,"read from private field"),Y?Y.call(k):H.get(k)),L=(k,H,Y)=>{if(H.has(k))throw TypeError("Cannot add the same private member more than once");H instanceof WeakSet?H.add(k):H.set(k,Y)},X=(k,H,Y,At)=>(Zt(k,H,"write to private field"),At?At.call(k,Y):H.set(k,Y),Y);var O=(k,H,Y)=>(Zt(k,H,"access private method"),Y);(function(k,H){typeof exports=="object"&&typeof module<"u"?H(exports):typeof define=="function"&&define.amd?define(["exports"],H):(k=typeof globalThis<"u"?globalThis:k||self,H(k["szdl-utils-kit"]={}))})(this,function(k){var Rt,le,Lt,Mt,It,St,lt,Xt,Dt,ce,kt,he,$,ft,rt,Et,it,bt,Bt,ue,gt,Vt,nt,Z,V,at,ct,yt,tt,J,ot,ht,wt,fe,pt,$t,Ct,de,Ht,me,Ut,ge,ut,Jt,Pt,ye,Nt,te,Gt,pe,Yt,Ne,Wt,Oe,et,dt,Ot,ee,xt,_e,_t,se,Ft,Te,vt,Ee,Tt,re;"use strict";var H=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Y(_){return _&&_.__esModule&&Object.prototype.hasOwnProperty.call(_,"default")?_.default:_}var At={exports:{}};(function(_,e){(function(t){Array.prototype.indexOf||(Array.prototype.indexOf=function(s,o){var d,g;for(d=o||0,g=this.length;d<g;d+=1)if(this[d]===s)return d;return-1});var r=this,i=function(s,o){for(var d=s.toString();d.length<o;)d="0"+d;return d},a=function(s,o){return o!==t?(s.year(o.year()||o.year),s.month(o.month()||o.month),s.day(o.day()||o.day),s.hours(o.hours()||o.hours),s.minutes(o.minutes()||o.minutes),s.seconds(o.seconds()||o.seconds),s.milliseconds(o.milliseconds()||o.milliseconds),s):t},l=function(s,o){var d,g="";return d=s.slice(o,o+1),d!==""&&!isNaN(Number(d))&&(g+="%H"),d=s.charAt(o+2),d!==""&&d===":"&&(g+=d),d=s.slice(o+3,o+4),d!==""&&!isNaN(Number(d))&&(g+="%M"),d=s.charAt(o+5),d!==""&&d===":"&&(g+=d),d=s.slice(o+6,o+7),d!==""&&!isNaN(Number(d))&&(g+="%S"),g},c=function(s,o){var d,g=[s.slice(o,o+1),s.charAt(o+2),s.slice(o+3,o+4),s.charAt(o+5),s.slice(o+6,o+9)],U;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):(U=[s.slice(o,o+3),s.charAt(o+4),s.slice(o+5,o+6),s.charAt(o+7),s.slice(o+8,o+9)],!isNaN(Number(U[0]))&&!isNaN(Number(U[2]))&&!isNaN(Number(U[4]))?(U[1]==="-"&&U[3]==="-"&&(d="%Y-%m-%d"),d):"")},h=r.tempus,n,f,m=r.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]},T=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]},E=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]},M=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]},y,b,P,p,I=function(s,o,d){var g;r.XMLHttpRequest?g=new XMLHttpRequest:g=new ActiveXObject("Microsoft.XMLHTTP"),g.onreadystatechange=function(){g.readyState===4&&(g.status===200?o&&(r.JSON===t?alert(`Please, include json2 into your project if you want use old browsers!
|
|
2
|
+
https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(g.responseText))):d&&d(g))},g.open("GET",s,!1),g.send()},R={"%d":{format:function(s){return i(s.day()||n.MIN_DAY,2)},parse:function(s){var o=Number(s);return{day:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(s){return i(s.month()||n.MIN_MONTH,2)},parse:function(s){var o=Number(s);return{month:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(s){return i(s.year()||n.MIN_YEAR,4)},parse:function(s){var o=Number(s);return{year:isNaN(o)?t:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(s){return s.dayOfWeek()||n.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(s){var o=s.dayOfWeek();return p[o!==t?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(s){var o=s.dayOfWeek();return P[o!==t?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(s){var o=n.options("monthFromZero")?s.month():s.month()-1;return b[o!==t?o:n.MIN_MONTH]},parse:function(s){var o=n.monthNames().indexOf(s)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:t}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(s){var o=n.options("monthFromZero")?s.month():s.month()-1;return y[o!==t?o:n.MIN_MONTH]},parse:function(s){var o=n.monthNames(!0).indexOf(s)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:t}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(s){return i(s.hours()||n.MIN_HOURS,2)},parse:function(s){var o=Number(s);return{hours:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(s){return i(s.minutes()||n.MIN_MINUTES,2)},parse:function(s){var o=Number(s);return{minutes:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(s){return i(s.seconds()||n.MIN_SECONDS,2)},parse:function(s){var o=Number(s);return{seconds:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(s){return s.timestamp()},parse:function(s){return isNaN(Number(s))?{}:n(Number(s)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(s){return i(s.year()||n.MIN_YEAR,4)+"-"+i(s.month()||n.MIN_MONTH,2)+"-"+i(s.day()||n.MIN_DAY,2)},parse:function(s){var o=Number(s.slice(0,4)),d=Number(s.slice(5,7)),g=Number(s.slice(8,10));return{year:o,month:d,day:g}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(s){return i(s.month()||n.MIN_MONTH,2)+"/"+i(s.day()||n.MIN_DAY,2)+"/"+i(s.year()||n.MIN_YEAR,4)},parse:function(s){var o=Number(s.slice(0,2)),d=Number(s.slice(3,5)),g=Number(s.slice(6,10));return{year:g,month:o,day:d}},minLength:10,maxLength:10,type:"string"}},w={useMilliseconds:!1,monthFromZero:!1},B;B=function(s,o,d){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},s!==t&&this.set(s,o,d),this},B.fn=B.prototype,B.fn.dayCount=function(){var s=this.month(),o=n.MAX_DAY_IN_MONTHS[s-(n.options("monthFromZero")?0:1)];return this.leapYear()&&s===(n.options("monthFromZero")?1:2)&&(o+=1),o},B.fn.year=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_YEAR&&Number(s)<=n.MAX_YEAR?(this._d.setFullYear(Number(s)),this._i.year=!1):this._i.year=Number(s):(this._d.setFullYear(n.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},B.fn.month=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MONTH&&Number(s)<=n.MAX_MONTH?(this._d.setMonth(n.options("monthFromZero")?Number(s):Number(s)-1),this._i.month=!1):this._i.month=Number(s):(this._d.setMonth(n.options("monthFromZero")?n.MIN_MONTH:n.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?n.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},B.fn.day=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_DAY&&Number(s)<=this.dayCount()?(this._d.setDate(Number(s)),this._i.day=!1):this._i.day=Number(s):(this._d.setDate(n.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},B.fn.hours=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_HOURS&&Number(s)<=n.MAX_HOURS?(this._d.setHours(Number(s)),this._i.hours=!1):this._i.hours=Number(s):(this._d.setHours(n.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},B.fn.minutes=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MINUTES&&Number(s)<=n.MAX_MINUTES?(this._d.setMinutes(Number(s)),this._i.minutes=!1):this._i.minutes=Number(s):(this._d.setMinutes(n.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},B.fn.seconds=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_SECONDS&&Number(s)<=n.MAX_SECONDS?(this._d.setSeconds(Number(s)),this._i.seconds=!1):this._i.seconds=Number(s):(this._d.setSeconds(n.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},B.fn.milliseconds=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MILLISECONDS&&Number(s)<=n.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(s)),this._i.milliseconds=!1):this._i.milliseconds=Number(s):(this._d.setMilliseconds(n.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},B.fn.week=function(){var s=new Date(this.year(),0,1),o=n(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-s.getTime())/864e5+s.getDay()+1)/7)},B.fn.set=function(s,o,d){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},s===t)return this._d=new Date,this;if(s instanceof Date)return this._d=s,this;if(typeof s=="number")return this._d=new Date(s*(n.options("useMilliseconds")?1:1e3)),this;if(typeof s=="object"&&(s instanceof Array?(this.day(n.MIN_DAY),this.year(s[0]),this.month(s[1]),this.day(s[2]),this.hours(s[3]),this.minutes(s[4]),this.seconds(s[5]),this.milliseconds(s[6])):(this.day(n.MIN_DAY),this.year(s.year),this.month(s.month),this.day(s.day),this.hours(s.hours),this.minutes(s.minutes),this.seconds(s.seconds),this.milliseconds(s.milliseconds))),typeof s=="string"){var g,U=[],D,G,st=[],v=0,j=0,W,K,x={},F;if(s===t)return D=a(this,d),D===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;for(o===t&&(o=n.detectFormat(s));v<o.length;){if(o.charAt(v)==="%"){if(G=o.charAt(v)+o.charAt(v+1),R[G]!==t){switch(W=0,K="",R[G].type){case"number":for(;W<R[G].maxLength&&j+W<s.length&&!isNaN(Number(s.charAt(j+W)));)K+=s.charAt(j+W),W+=1;break;case"word":for(;W<R[G].maxLength&&j+W<s.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(s.charAt(j+W));)K+=s.charAt(j+W),W+=1;break;case"string":for(;W<R[G].maxLength&&j+W<s.length;)K+=s.charAt(j+W),W+=1;break}if(W<R[G].minLength)return D=a(this,d),D===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;U.push(G),st.push(K),W-=1,j+=W,v+=1}}else if(s.charAt(j)!==o.charAt(v))return D=a(this,d),D===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),D;v+=1,j+=1}for(g in U)U.hasOwnProperty(g)&&R.hasOwnProperty(U[g])&&(F=R[U[g]].parse(st[g]),x={year:F.year!==t?F.year:x.year,month:F.month!==t?F.month:x.month,day:F.day!==t?F.day:x.day,hours:F.hours!==t?F.hours:x.hours,minutes:F.minutes!==t?F.minutes:x.minutes,seconds:F.seconds!==t?F.seconds:x.seconds});this.day(n.MIN_DAY),this.year(x.year),this.month(x.month),this.day(x.day),this.hours(x.hours),this.minutes(x.minutes),this.seconds(x.seconds),this.milliseconds(x.milliseconds)}return this},B.fn.leapYear=function(){var s=this.year();return s%4===0?s%100===0?s%400===0:!0:!1},B.fn.timestamp=function(s){return arguments.length!==0?(this._d=new Date(Number(s)*(n.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):n.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},B.fn.utc=function(s){return arguments.length!==0?(this._d=new Date(Number(s)*(n.options("useMilliseconds")?1:1e3)),this):n.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},B.fn.dayOfWeek=function(s){if(s==="long")return P[this._d.getDay()];if(s==="short")return p[this._d.getDay()];if(s===t)return this._d.getDay();if(s===0||s==="Sunday")return this.calc({day:-this.dayOfWeek()});if(s===1||s==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(s===2||s==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(s===3||s==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(s===4||s==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(s===5||s==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(s===6||s==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},B.fn.timezone=function(s){switch(s){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},B.fn.get=function(s){switch(s){case"Date":return new Date(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds());case"DateUTC":return new Date(Date.UTC(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()));case"Array":return[this.year(),this.month(),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()];default:return{year:this.year(),month:this.month(),week:this.week(),day:this.day(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds(),utc:this.utc(),dayOfWeek:this.dayOfWeek(),dayOfWeekShort:this.dayOfWeek("short"),dayOfWeekLong:this.dayOfWeek("long"),timestamp:this.timestamp()}}},B.fn.format=function(s){for(var o=0,d="",g;o<s.length;)s.charAt(o)==="%"?(g=s.charAt(o)+s.charAt(o+1),R[g]!==t?(d+=R[g].format(this),o+=1):d+="%"):d+=s.charAt(o),o+=1;return d},B.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},B.fn.errors=function(){return this._i},B.fn.between=function(s,o){var d=this.timestamp(),g=s.timestamp();switch(o){case"year":return Math.floor((g-d)/31556952);case"month":return Math.floor((g-d)/2629746);case"day":return Math.floor((g-d)/86400);case"hours":return Math.floor((g-d)/3600);case"minutes":return Math.floor((g-d)/60);case"seconds":return g-d;default:return t}},B.fn.calc=function(s){return s.year!==t&&this._d.setFullYear(this._d.getFullYear()+s.year),s.month!==t&&this._d.setMonth(this._d.getMonth()+s.month),s.day!==t&&this._d.setDate(this._d.getDate()+s.day),s.hours!==t&&this._d.setHours(this._d.getHours()+s.hours),s.minutes!==t&&this._d.setMinutes(this._d.getMinutes()+s.minutes),s.seconds!==t&&this._d.setSeconds(this._d.getSeconds()+s.seconds),s.milliseconds!==t&&this._d.setMilliseconds(this._d.getMilliseconds()+s.milliseconds),this},n=function(s,o,d){return new B(s,o,d)},n.MIN_YEAR=1e3,n.MAX_YEAR=3e3,n.MIN_MONTH=1,n.MAX_MONTH=12,n.MIN_DAY=1,n.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],n.MIN_DAY_OF_WEEK=0,n.MAX_DAY_OF_WEEK=6,n.MIN_HOURS=0,n.MAX_HOURS=23,n.MIN_MINUTES=0,n.MAX_MINUTES=59,n.MIN_SECONDS=0,n.MAX_SECONDS=59,n.MIN_MILLISECONDS=0,n.MAX_MILLISECONDS=999,n.VERSION="0.2.18",n.options=function(s,o){if(s===t)return w;if(w.hasOwnProperty(s)){if(o===t)return w[s];w[s]=o,s==="monthFromZero"&&(n.MIN_MONTH=o?0:1,n.MAX_MONTH=o?11:12)}return t},n.noConflict=function(){return r.tempus=h,n},n.generate=function(s){var o,d,g,U,D,G,st,v;if(typeof s.dateFrom!="number"&&(s.dateFrom instanceof B?o=s.dateFrom.utc():o=n(s.dateFrom,s.formatFrom).utc()),typeof s.dateTo!="number"&&(s.dateTo instanceof B?d=s.dateTo.utc():d=n(s.dateTo,s.formatTo!==t?s.formatTo:s.formatFrom).utc()),typeof s.period=="number"?D={year:0,month:0,day:0,hours:0,minutes:0,seconds:s.period}:typeof s.period=="string"?D={year:s.period==="year"?1:0,month:s.period==="month"?1:0,day:s.period==="day"?1:0,hours:s.period==="hours"?1:0,minutes:s.period==="minutes"?1:0,seconds:s.period==="seconds"?1:0}:typeof s.period=="object"&&(D={year:s.period.year!==t?s.period.year:0,month:s.period.month!==t?s.period.month:0,day:s.period.day!==t?s.period.day:0,hours:s.period.hours!==t?s.period.hours:0,minutes:s.period.minutes!==t?s.period.minutes:0,seconds:s.period.seconds!==t?s.period.seconds:0}),s.groupBy===t?G=s.asObject===!0?{}:[]:(G=[],G.push([]),st=n(o).get()[s.groupBy]),v=function(K,x,F){return s.asObject===!0?s.format!==t?K[n(x).format(s.format)]={}:K[n(x).format("%F %H:%M:%S")]={}:s.format!==t?K.push(F?null:n(x).format(s.format)):K.push(F?null:n(x)),K},s.groupBy!==t&&s.fillNulls){var j={year:D.year?-D.year:t,month:D.month?-D.month:t,day:D.day?-D.day:t,hours:D.hours?-D.hours:t,minutes:D.minutes?-D.minutes:t,seconds:D.seconds?-D.seconds:t,milliseconds:D.milliseconds?-D.milliseconds:t};for(g=n(o).calc(j).utc();n(g).get()[s.groupBy]===st;)v(G[G.length-1],g,!0),g=n(g).calc(j).utc();if(s.groupBy==="week"){var W=n(o).dayOfWeek();for(g=n(o).dayOfWeek(0).utc();G[0].length<W&&g<o;)v(G[G.length-1],g,!0),g=n(g).calc(D).utc()}}for(;o<=d;)s.groupBy===t?v(G,o):n(o).get()[s.groupBy]===st?v(G[G.length-1],o):(G.push([]),v(G[G.length-1],o),st=n(o).get()[s.groupBy]),o=n(o).calc(D).utc();if(s.groupBy!==t&&s.fillNulls)for(U=n(d).calc(D).utc();n(U).get()[s.groupBy]===st;)v(G[G.length-1],U,!0),U=n(U).calc(D).utc();return G},n.monthNames=function(s){switch(s){case"long":return y;default:return b}},n.dayNames=function(s){switch(s){case"long":return P;default:return p}},n.lang=function(s){if(s!==t)A=s,u[A]===t&&(A="en"),y=N(),b=T(),P=E(),p=M();else return A;return t},n.availableLangs=function(){return Object.keys(u)},n.registerFormat=function(s,o,d,g,U,D){R[s]={format:o,parse:d,minLength:g,maxLength:U,type:D}},n.unregisterFormat=function(s){delete R[s]},n.detectFormat=function(s){var o,d,g;return o=c(s,0),o!==""&&(g=10),d=s.charAt(g),(d==="T"||d===" ")&&(o+=d,g+=1),o+=l(s,g),o},f={TempusDate:B},n.classes=function(s,o){if(o===t)return f[s];f[s]=o},n.loadTranslations=function(s){typeof s=="object"?u=s:typeof s=="string"&&I(s,function(o){u=o},function(o){})},A=(m.language||m.systemLanguage||m.userLanguage||"en").substr(0,2).toLowerCase(),u[A]===t&&(A="en"),y=N(),b=T(),P=E(),p=M(),_.exports&&(e=_.exports=n),e.tempus=n}).call(H)})(At,At.exports);var be=At.exports;const mt=Y(be),Q=class Q{constructor(e){L(this,Rt);L(this,lt);L(this,Dt);L(this,kt);L(this,$);L(this,rt);L(this,it);L(this,Bt);L(this,gt);typeof e=="function"?(this.callBatch=e,this.callMethod=null):(this.callBatch=(e==null?void 0:e.callBatch)||null,this.callMethod=(e==null?void 0:e.callMethod)||null),this.result={},this.errors={},this.timeLimit={limit:!1,date:void 0,pauseMs:void 0},this.timeLimitListeners=new Set,this.canContinue=!0,this.progressCall="",this.progressData="",this.progressTimer="",this.lastProgressSnapshot=null,this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.filterChunkSize=50,this.limit=50,this.progressDelay=100,this.operatingThreshold=475,this.defaultPauseMs=12e4,this.callLimitPauseMs=3e4,this.requestTimeoutMs=6e4}get progressPercent(){if(!this.progressData)return{percent:0,allCount:0,allTotal:0};const e=this.totalBatchCommands||0;if(e>0&&Array.isArray(this.batchCommandKeyOrder)&&this.batchCommandKeyOrder.length&&O(this,Rt,le).call(this)){let h=0;for(const u of this.batchCommandKeyOrder){const N=this.progressData[u];if(!N)continue;const T=Number(N.total)||0,E=Number(N.count)||0;T===0&&E===0?h+=1:T>0&&(h+=Math.min(1,E/T))}const n=h/e*100;let f=Math.max(0,Math.min(100,Math.floor(n)));const m=e,A=Math.min(e,Math.floor(h));return{percent:f,allCount:A,allTotal:m}}let t=0,r=0;for(const h of Object.values(this.progressData)){const{total:n,count:f}=h;t+=n??0,r+=f??0}const i=Number(this.chunkRate)||0;let a=0;t?a=r/t*100*i+this.totalProgress:r===0&&t===0?a=i<1?this.totalProgress:100*i+this.totalProgress:a=100,a=Math.max(0,Math.min(a,100));let l=Math.floor(a);const c=Number(this.chunkRate)||0;return t>0&&r>=t&&c>=1&&(l=100),{percent:l,allCount:r,allTotal:t}}setProgressData({key:e,value:t,type:r}){var u,N;if(!this.progressCall)return;const i=this.getData(t.data()),a=Array.isArray(i)?i.length:0;let l=a;if(typeof t.total=="function"){const T=t.total();if(T!=null&&T!==""){const E=Number(T);Number.isFinite(E)&&(l=E)}}let c=1;r==="count"?(l||(l=a),c=l>0?l:a>0?a:1):i&&(c=a),this.progressData||(this.progressData={});const h=((u=this.progressData[e])==null?void 0:u.total)??0,n=((N=this.progressData[e])==null?void 0:N.count)??0,f=c+n,m=Math.max(h,l??0,f);if(this.progressData[e]={total:m,count:Math.min(f,m)},typeof document<"u"&&(document==null?void 0:document.hidden)===!0){O(this,lt,Xt).call(this);return}O(this,lt,Xt).call(this),this.progressTimer||(this.progressTimer=setInterval(()=>{if(!this.progressCall){this.clearProgressData();return}O(this,lt,Xt).call(this);const{percent:T}=this.progressPercent;T>=100&&(clearInterval(this.progressTimer),this.progressTimer="")},this.progressDelay))}getData(e){if(e==null)return e;let t=(e==null?void 0:e.items)??(e==null?void 0:e.tasks)??(e==null?void 0:e.types)??(e==null?void 0:e.type)??(e==null?void 0:e.fields)??(e==null?void 0:e.workgroups)??e;return t&&typeof t=="object"&&!Array.isArray(t)&&Array.isArray(t.result)&&(t=t.result),t}setTimeLimitState(e,t,r){this.timeLimit.limit=!!e,this.timeLimit.date=e?t:void 0,e&&typeof r=="number"&&r>0?this.timeLimit.pauseMs=r:this.timeLimit.pauseMs=void 0,O(this,kt,he).call(this)}subscribeTimeLimit(e){return typeof e!="function"?()=>{}:(this.timeLimitListeners.add(e),e({limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs}),()=>{this.timeLimitListeners.delete(e)})}splitLargeFilters(e,t){const{method:r,params:i}=t;if(!i)return[{key:e,request:t}];const a=i.filter||i.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:e,request:t}];for(const[l,c]of Object.entries(a))if(!String(l).trim().startsWith("!")&&Array.isArray(c)&&c.length>this.filterChunkSize){const h=[];for(let n=0;n<c.length;n+=this.filterChunkSize){const f=c.slice(n,n+this.filterChunkSize),m=n===0?e:`${e}__chunk_${Math.floor(n/this.filterChunkSize)}`,A={...i};i.filter?(A.filter={...a},A.filter[l]=f):i.FILTER&&(A.FILTER={...a},A.FILTER[l]=f),h.push({key:m,request:{method:r,params:A},originalKey:e,filterKey:l,chunkIndex:Math.floor(n/this.filterChunkSize)})}return h}return[{key:e,request:t}]}mergeSplitResults(e,t){const r=[],i=String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${i}(?:__chunk_\\d+)?$`),l=Object.keys(e).filter(c=>a.test(c)).sort((c,h)=>{const n=c.match(/__chunk_(\d+)$/),f=h.match(/__chunk_(\d+)$/);return n?f?parseInt(n[1])-parseInt(f[1]):1:-1});for(const c of l){const h=e[c];Array.isArray(h)?r.push(...h):h&&r.push(h)}return r}delay(){return typeof document<"u"&&(document==null?void 0:document.hidden)===!0?Promise.resolve():new Promise(t=>setTimeout(t,500))}callBatchWithTimeout(e,t){return new Promise((r,i)=>{let a=!1,l=null;const c=async n=>{if(!a){a=!0,l&&clearTimeout(l);try{await Promise.resolve(t(n)),r()}catch(f){console.error("Error in callBatch callback:",f),i(f)}}},h=async()=>{if(!a){a=!0,l&&clearTimeout(l),console.warn(`Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`);const n={};Object.keys(e).forEach(f=>{n[f]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 60 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(t(n)),r()}catch(f){console.error("Error in timeout callback:",f),r()}}};try{this.callBatch(e,async n=>{await c(n)})}catch(n){a||console.error("Error calling callBatch:",n)}l=setTimeout(async()=>{a||(console.warn(`Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`),await h())},this.requestTimeoutMs)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.lastProgressSnapshot=null}async batch(e,t,r={}){O(this,gt,Vt).call(this,t);const i={},a={},l={};for(const[f,m]of Object.entries(e)){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.batchCommandKeyOrder=Object.keys(a),this.totalBatchCommands=this.batchCommandKeyOrder.length,this.batchCommandMethods=this.batchCommandKeyOrder.map(f=>{var m;return String(((m=a[f])==null?void 0:m.method)||"")}),this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let c={},h=0;const n=Object.keys(a).length;for(const[f,m]of Object.entries(a)){if(!this.canContinue)break;if(c[f]=m,Object.keys(c).length>=this.limit||h+1===n){const A=h+1===n;await this.batchChunk(c,void 0,!A,{disablePagination:!1,oneBatch:!!(r!=null&&r.oneBatch)}),Object.entries(this.result).forEach(([u,N])=>{i[u]=N}),this.totalProgress=Math.round(h/n*100),c={}}h++}for(const[f,m]of Object.entries(l))if(m&&m.length>0){const A=this.mergeSplitResults(i,f);for(const u of m)delete i[u];i[f]=A}return Object.entries(this.errors).length&&(i.errorsList=this.errors),t&&t({percent:100}),Promise.resolve(i)}async batchTotalCount(e,t){O(this,gt,Vt).call(this,t);const r={},i={},a={};for(const[h,n]of Object.entries(e)){const f=this.arrayChunk(n);if(!f)continue;const m=this.splitLargeFilters(h,f);if(m.length===1)i[h]=f;else{a[h]=[];for(const A of m)i[A.key]=A.request,a[h].push(A.key)}}const l=[],c=Object.entries(i);for(let h=0;h<c.length;h+=this.limit){const n=c.slice(h,h+this.limit),f={};for(const[m,A]of n){if(!this.canContinue)break;f[m]=A}Object.keys(f).length>0&&l.push(f)}this.chunkRate=(1/l.length).toFixed(5);for(const[h,n]of Object.entries(l)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(h)/l.length*100),this.progressData={},this.lastProgressSnapshot=null;const f=Number(h)===l.length-1;await O(this,it,bt).call(this,n,async m=>{var A,u,N,T,E;for(const[M,y]of Object.entries(m)){if(!this.canContinue)return;if(y.error()){const R=(u=(A=y.error())==null?void 0:A.ex)==null?void 0:u.error,w=(T=(N=y.error())==null?void 0:N.ex)==null?void 0:T.error_description;this.errors[M]=R&&R.trim()||w&&w.trim()||((E=y.error())==null?void 0:E.toString())||"Неизвестная ошибка",r[M]=0;continue}const b=this.getData(y.data()),P=Array.isArray(b)?b.length:0,I=typeof y.total=="function"&&y.total()!==void 0?y.total():P;r[M]=I,this.setProgressData({key:M,value:y,type:"count"})}await O(this,rt,Et).call(this,m,!f)})}for(const[h,n]of Object.entries(a))if(n&&n.length>0){let f=0;for(const m of n)r[m]!==void 0&&(f+=r[m]||0),delete r[m];r[h]=f}return Object.entries(this.errors).length&&(r.errorsList=this.errors,this.errorLogger()),t&&t({percent:100}),Promise.resolve(r)}async call({method:e,params:t={}}){var r,i,a,l,c,h,n;for(;;){const f=await O(this,Bt,ue).call(this,e,t);if(!f){await O(this,$,ft).call(this,this.callLimitPauseMs);continue}const m={};if(f!=null&&f.answer)for(const[u,N]of Object.entries(f.answer))u!=="result"&&N&&(m[u]=N);if(f.error()){const u=((i=(r=f.error())==null?void 0:r.ex)==null?void 0:i.error)??"";if(["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT","TIMEOUT"].includes(u)){await O(this,$,ft).call(this,this.callLimitPauseMs);continue}const N=((a=f.error())==null?void 0:a.toString())||((c=(l=f.error())==null?void 0:l.ex)==null?void 0:c.error_description)||((n=(h=f.error())==null?void 0:h.ex)==null?void 0:n.error)||"Неизвестная ошибка";return{success:!1,data:!1,answer:m,error:N}}let A=f.data();return A!=null&&A.items&&(A=A.items),{success:!0,data:A,answer:m,error:null}}}arrayChunk(e){let t="",r={};if(Array.isArray(e)?[t]=e:(t=e.method,r=e.params),(t.includes("list")||t==="user.get"||t==="entity.item.get")&&t!=="task.item.list"){if(!r)r=t==="entity.item.get"?{SORT:{ID:"ASC"}}:{order:{ID:"ASC",id:"ASC"}};else{t==="entity.item.get"?(r.SORT||(r.SORT={ID:"ASC"}),Array.isArray(r.select)?r.select.includes("ID")||r.select.push("ID"):r.select=["ID"]):t==="tasks.task.list"?(r.order||(r.order={}),r.order.ID="asc"):t==="user.get"?(r.sort||(r.sort="ID"),r.order||(r.order="ASC")):r.order={ID:"ASC",id:"ASC"},Array.isArray(r.select)&&!r.select.includes("ID")&&r.select.push("ID");const i=t==="user.get"||t==="entity.item.get"?r.FILTER:r.filter;typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.entries(i).forEach(([a,l])=>{(r.start===void 0||r.start!==-1)&&["id","ID"].includes(a)&&(typeof l=="string"||Array.isArray(l)&&l.length<=50)&&(r.start=-1)})}t==="crm.type.list"&&r.order&&delete r.order.ID}if(t==="task.item.list")if(!r)r=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(r[0])&&(r[0]={});const[i,a,l,c]=r;i.ID="ASC",c[0]!==""&&c.includes("ID")||c.push("ID")}return{method:t,params:r}}async batchChunk(e,t,r=!0,i={}){return new Promise(a=>{const l=[];let c;const h=!!(i!=null&&i.disablePagination);(async()=>{await O(this,it,bt).call(this,e,async f=>{var A,u,N,T,E;for(const[M,y]of Object.entries(f)){if(!this.canContinue)return;if(y.error()){const g=(u=(A=y.error())==null?void 0:A.ex)==null?void 0:u.error,U=(T=(N=y.error())==null?void 0:N.ex)==null?void 0:T.error_description;this.errors[M]=g&&g.trim()||U&&U.trim()||((E=y.error())==null?void 0:E.toString())||"Неизвестная ошибка",c=!0}const b=this.getData(y.data()),P=Array.isArray(b)?b.length:0,p=typeof y.total=="function"&&y.total()!==void 0,I=p?y.total():P;t==="count"?this.result[M]?this.result[M]+=P:this.result[M]=I:this.result[M]=b,this.setProgressData({key:M,value:y,type:t});const R=e[M],w=Array.isArray(R)?R[0]:R==null?void 0:R.method,B=typeof w=="string"&&(w.includes(".list")||w==="user.get"||w==="entity.item.get"),s=t==="count"?!p&&P===this.limit:B?P===this.limit:I>this.limit&&I>P,o=t!=="count"&&w==="entity.item.get"&&P===this.limit&&!s,d=s||o;if(!h&&(!this.canContinue||d)){let g=e[M];if(Array.isArray(g)){const[U,D={}]=g;g=[U,D]}else{const{method:U,params:D={}}=g;g=[U,D]}l.push([M,g,I,{entityItemGetScan:o}])}}c>0&&this.errorLogger();const m=l.length>0||r;await O(this,rt,Et).call(this,f,m),l.length?await this.batchPayload(l,t,i).then(()=>a(this.result)):a(this.result)})})()})}async batchPayload(e,t,r={}){const i=!!(r!=null&&r.oneBatch),a=(N,T,E,M)=>{let y="ID";this.result[N][this.result[N].length-1].ID||(y="id");let b=`${y}`;if(JSON.stringify(M[1]).toLocaleLowerCase().includes('"id":"desc"')?b="<"+b:b=">"+b,T===1||E.length===0)return{field:b,id:this.result[N][this.result[N].length-1][y]};let p="";const[I,R]=M;return(I==="tasks.task.list"||I==="task.item.list")&&(p="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(I)&&(p="[items]"),I==="crm.type.list"&&(p="[types]"),I==="socialnetwork.api.workgroup.list"&&(p="[workgroups]"),{field:b,id:`$result[${[N,T-1].join("__")}]${p}[49][${y}]`}},l=(N,T)=>{const[E,M]=N;let y=JSON.parse(JSON.stringify(M)),b;if(E==="task.item.list"){y=[...y];const[P,p,I,R]=y;return p[T.field]=T.id,[E,y]}return["user.get"].includes(E)||y.FILTER?(y.FILTER||(y.FILTER={}),b=y.FILTER):(y.filter||(y.filter={}),b=y.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(E)?b[">ID"]=T.id:b[T.field]=T.id,[E,{...y,start:-1}]},c=N=>{Object.entries(N).forEach(([T,E])=>{var b,P,p,I,R;const[M]=T.split("__"),y=this.getData(E.data());if(Array.isArray(y)&&(t==="count"?this.result[M]+=y.length:this.result[M].push(...y)),E.error()){const w=(P=(b=E.error())==null?void 0:b.ex)==null?void 0:P.error,B=(I=(p=E.error())==null?void 0:p.ex)==null?void 0:I.error_description;this.errors[M]=w&&w.trim()||B&&B.trim()||((R=E.error())==null?void 0:R.toString())||"Неизвестная ошибка"}this.setProgressData({key:M,value:E,type:t})})},h=(N,T)=>{if(!Array.isArray(N)||N.length===0)return null;const E=N[N.length-1];let M="ID";E.ID||(M="id");let y=M;return JSON.stringify(T[1]).toLocaleLowerCase().includes('"id":"desc"')?y="<"+y:y=">"+y,{field:y,id:E[M]}},n=1e4,f=async(N,T)=>{var M,y;let E=this.limit;for(let b=1;this.canContinue&&E===this.limit&&b<=n;b++){const P=this.result[N],p=h(P,T);if(!p)break;const I=`${N}__eiscan_${b}`,R=l(T,p);let w=null;await O(this,it,bt).call(this,{[I]:R},async d=>{w=d,c(d)});const B=b<n;await O(this,rt,Et).call(this,w,B),await this.delay();const s=w==null?void 0:w[I];if((M=s==null?void 0:s.error)!=null&&M.call(s)){E=0;break}const o=this.getData((y=s==null?void 0:s.data)==null?void 0:y.call(s));E=Array.isArray(o)?o.length:0}};let m=[],A=0;const u=async(N=!0)=>m.length?(await O(this,it,bt).call(this,Object.fromEntries(m),async T=>{c(T),await O(this,rt,Et).call(this,T,N)}),A++,m=[],i&&A>=1?!0:(await this.delay(),!1)):!1;for await(const N of e){if(!this.canContinue)return;const[T,E,M,y={}]=N;if(y.entityItemGetScan){if(await u(!0))return;if(i)continue;await f(T,E);continue}let b=1;for(;M>b*this.limit;){const P=[T,b].join("__"),p=a(T,b,m,E);if(m.push([P,l(E,p)]),i&&m.length===49&&await u(!0)||m.length%50===0&&await u(!0))return;b++}}await u(!1)}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([e,t])=>{t&&console.log(`[${e}]`,t.toString())}),console.groupEnd()}};Rt=new WeakSet,le=function(){const e=this.totalBatchCommands||0,t=this.batchCommandMethods;if(e<S(Q,Lt)||!Array.isArray(t)||t.length!==e)return!1;if(t.filter(a=>a==="crm.deal.list").length>=S(Q,Mt))return!0;const i=t.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=S(Q,It)&&i/e>=S(Q,St)},Lt=new WeakMap,Mt=new WeakMap,It=new WeakMap,St=new WeakMap,lt=new WeakSet,Xt=function(){if(!this.progressCall||!this.progressData)return;const{percent:e,allCount:t,allTotal:r}=this.progressPercent,i={percent:e,allCount:t,allTotal:r};O(this,Dt,ce).call(this,i)&&(this.progressCall({data:this.progressData,percent:e,allCount:t,allTotal:r}),this.lastProgressSnapshot=i)},Dt=new WeakSet,ce=function(e){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==e.percent||this.lastProgressSnapshot.allCount!==e.allCount||this.lastProgressSnapshot.allTotal!==e.allTotal:!0},kt=new WeakSet,he=function(){const e={limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs};for(const t of this.timeLimitListeners)try{t(e)}catch(r){console.warn("Batch timeLimit listener error:",r)}},$=new WeakSet,ft=async function(e=this.defaultPauseMs){this.setTimeLimitState(!0,new Date().toISOString(),e),await new Promise(t=>setTimeout(t,e)),this.setTimeLimitState(!1,void 0)},rt=new WeakSet,Et=async function(e,t=!0){if(!t)return 0;let r=0;if(!e||typeof e!="object")return 0;for(const i of Object.values(e))if(!(!i||typeof i!="object"))try{if(typeof i.time=="function"){const a=i.time();a&&typeof a.operating=="number"&&(r=Math.max(r,a.operating))}}catch{}r>=this.operatingThreshold&&await O(this,$,ft).call(this)},it=new WeakSet,bt=async function(e,t){let r=!1,i=e;do r=!1,await this.callBatchWithTimeout(i,async a=>{var h,n;let l=!1;const c=new Set;for(const[f,m]of Object.entries(a||{})){if(!(m!=null&&m.error)||!m.error())continue;const A=((n=(h=m.error())==null?void 0:h.ex)==null?void 0:n.error)??"";if(A==="TIMEOUT"){l=!0;break}["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT"].includes(A)&&c.add(f)}if(l){r=!0,await O(this,$,ft).call(this);return}if(c.size>0){const f={};for(const[A,u]of Object.entries(a||{}))c.has(A)||(f[A]=u);Object.keys(f).length&&await t(f);const m={};for(const A of c)i[A]&&(m[A]=i[A]);i=m,Object.keys(i).length&&(r=!0,await O(this,$,ft).call(this));return}await t(a)});while(r)},Bt=new WeakSet,ue=function(e,t){return new Promise(r=>{if(typeof this.callMethod!="function"){r(null);return}let i=!1;const a=setTimeout(()=>{i||(i=!0,r(null))},this.requestTimeoutMs);try{this.callMethod(e,t,l=>{i||(i=!0,clearTimeout(a),r(l))})}catch{i||(i=!0,clearTimeout(a),r(null))}})},gt=new WeakSet,Vt=function(e){this.clearProgressData(),this.progressCall=typeof e=="function"?e:"",this.canContinue=!0,this.result={},this.errors={},this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.setTimeLimitState(!1,void 0)},L(Q,Lt,5),L(Q,Mt,5),L(Q,It,8),L(Q,St,.65);let q=Q;class jt{constructor(){L(this,nt,{})}get hash(){return this.createHash(8)}createHash(e){let t="abcdefghijklmnopqrstuvwxyz0123456789",r="";e=e||6;for(let i=0;i<e;i++)r+=t.charAt(Math.floor(Math.random()*t.length));return r}actionFilter({keyTimer:e,duration:t=10,action:r}){S(this,nt)[e]&&(clearTimeout(S(this,nt)[e]),S(this,nt)[e]=null),r&&(S(this,nt)[e]=setTimeout(()=>{r()},t))}async noSleep(){let e=document.createElement("video");e.classList.add("no-sleep"),e.muted=!0,e.autoplay=!0,e.setAttribute("playsinline",""),e.addEventListener("loadeddata",()=>{e.style.position="fixed",e.style.left="-9999px",document.querySelector("body").append(e),e.play().catch(t=>{console.warn("noSleep: autoplay prevented",t)})}),e.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{e.play().catch(t=>{console.warn("noSleep: replay prevented",t)})}})}),e.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(e,t){let r=new Blob([JSON.stringify(e)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=i,a.download=`${t}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(i)},200)}}nt=new WeakMap;const Kt=new jt;class ie{constructor(){L(this,wt);L(this,pt);L(this,Ct);L(this,Ht);L(this,Ut);L(this,Z,"logger");L(this,V,!1);L(this,at,new Map);L(this,ct,{});L(this,yt,!1);L(this,tt,null);L(this,J,null);L(this,ot,!1);L(this,ht,!1);C(this,"periodClear",3)}async init(){try{let e=new q(BX24.callBatch),{entityList:t}=await e.batch({entityList:{method:"entity.get"}});if(t&&Array.isArray(t))if(t.find(i=>i.ENTITY==S(this,Z)))X(this,V,!0);else{let{entityAdd:i}=await e.batch({entityAdd:{method:"entity.add",params:{ENTITY:S(this,Z),NAME:S(this,Z),ACCESS:{AU:"X"}}}});i&&X(this,V,!0)}return S(this,V)}catch(e){return console.error("Ошибка при инициализации логера:",e),!1}}enableBackworkerMode(){return X(this,V,!0),!0}start({type:e,data:t}){if(!S(this,V))return O(this,pt,$t).call(this,"entity"),null;if(!e||!t)return console.error("Невалидные данные для логирования:",{type:e,data:t}),null;const r=Kt.hash,i={type:e,data:t,userInfo:null,errorList:{},status:"",answer:null,date:new Date().getTime()};return S(this,at).set(r,i),X(this,ht,!0),r}async stop({key:e,errorList:t,status:r,answer:i}){var l;if(!S(this,ht))return;if(!S(this,V)){O(this,pt,$t).call(this,"entity");return}let a=S(this,at).get(e);if(!a){console.error(`Не найдены данные логирования для ключа: ${e}`);return}t&&(a.errorList=t),r&&(a.status=r),i&&(a.answer=i),await O(this,wt,fe).call(this),a.userInfo=S(this,ct),await O(this,Ct,de).call(this),(l=a==null?void 0:a.data)!=null&&l.updateList&&X(this,ot,!0),X(this,ht,!1)}async getEntityList(e){var t;try{if((t=S(this,J))!=null&&t.length&&!S(this,ot))return S(this,J);let r=new q(BX24.callBatch),{entityList:i}=await r.batch({entityList:{method:"entity.item.get",params:{ENTITY:S(this,Z),SORT:{ID:"DESC"}}}},e);return!i||!Array.isArray(i)?(console.warn("Получен невалидный список записей"),[]):(i=i.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),X(this,ot,!1),X(this,J,i),i)}catch(r){return console.error("Ошибка при получении списка записей:",r),[]}}runStorageMaintenance(){return O(this,Ht,me).call(this)}async downAllEntityJson(){try{if(S(this,J)||await this.getEntityList(),!S(this,J)||S(this,J).length===0)return console.warn("Нет данных для выгрузки"),!1;let e=mt().format("%Y-%m-%d");return Kt.downloadFileJson(S(this,J),`sdklogger-entity-data__${e}`),!0}catch(e){return console.error("Ошибка при выгрузке данных в JSON:",e),!1}}}Z=new WeakMap,V=new WeakMap,at=new WeakMap,ct=new WeakMap,yt=new WeakMap,tt=new WeakMap,J=new WeakMap,ot=new WeakMap,ht=new WeakMap,wt=new WeakSet,fe=async function(){if(!S(this,yt))return S(this,tt)?S(this,tt):(X(this,tt,(async()=>{try{const e=new q(BX24.callBatch),t=BX24.isAdmin(),{curUser:r}=await e.batch({curUser:{method:"user.current"}});X(this,ct,{isAdmin:t,curUser:r})}catch(e){console.error("Ошибка при получении информации о пользователе:",e),X(this,ct,{isAdmin:!1,curUser:null})}finally{X(this,yt,!0),X(this,tt,null)}})()),S(this,tt))},pt=new WeakSet,$t=function(e){e=="entity"&&Kt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},Ct=new WeakSet,de=async function(){try{let e={},t=new q(BX24.callBatch);for(let[r,i]of S(this,at).entries())if(i.status){const a=JSON.stringify(i);e[r]={method:"entity.item.add",params:{ENTITY:S(this,Z),NAME:S(this,Z),DETAIL_TEXT:a}}}if(Object.keys(e).length){let r=await t.batch(e),{errors:i}=t;for(let[a,l]of Object.entries({...r,...i}))S(this,at).delete(a);return!0}return!1}catch(e){return console.error("Ошибка при добавлении записей в хранилище:",e),!1}},Ht=new WeakSet,me=async function(){try{let e=new q(BX24.callBatch),{serverTime:t}=await e.batch({serverTime:{method:"server.time"}});if(!t){console.error("Не удалось получить время сервера");return}if(S(this,J)||await this.getEntityList(),!S(this,J)||S(this,J).length===0)return;let r=S(this,J).filter(i=>{try{let{dateCreate:a}=i;return a?mt(new Date(a)).between(mt(new Date(t)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});r.length>0&&(console.log(`Найдено ${r.length} записей для очистки (старше ${this.periodClear} месяцев)`),await O(this,Ut,ge).call(this,r))}catch(e){console.error("Ошибка при проверке периода очистки:",e)}},Ut=new WeakSet,ge=async function(e){try{if(!e||e.length===0)return!1;let t=new q(BX24.callBatch),r=e.filter(a=>a&&a.id).map(a=>{let{id:l}=a;return{method:"entity.item.delete",params:{ENTITY:S(this,Z),ID:l}}});if(r.length===0)return!1;const i=await t.batch(r);return console.log(`Успешно удалено ${r.length} записей`),X(this,ot,!0),i}catch(t){return console.error("Ошибка при очистке устаревших записей:",t),!1}};function qt(_){if(!_||typeof _!="string")return"";try{const e=new URL(_);e.search="",e.hash="";let t=e.toString();return t.endsWith("/")&&e.pathname!=="/"&&(t=t.slice(0,-1)),t}catch{return _.split("?")[0].split("#")[0].replace(/\/$/,"")}}function ne(_){return!_||typeof _!="string"?!1:_.toLowerCase().includes("/marketplace/app")}function Re(){var e;if(typeof window>"u"||!((e=window.location)!=null&&e.href))return"";const _=qt(window.location.href);return ne(_)?"":_}function zt(_){if(!(_!=null&&_.appConst)||typeof _.appConst!="object")return"";const e=Re();return e?(_.appConst.pathApp=e,e):qt(_.appConst.pathApp??"")}class Le{constructor(e){L(this,ut);L(this,Pt);L(this,Nt);L(this,Gt);L(this,Yt);L(this,Wt);L(this,et);L(this,Ot);L(this,xt);L(this,_t);L(this,Ft);C(this,"domain","");C(this,"isAdmin",!1);C(this,"appInfo",null);C(this,"appConst",null);C(this,"userInfo",null);C(this,"placeData",null);C(this,"placeInfo",null);C(this,"logger",!1);C(this,"timeLimit",{limit:!1,date:void 0,pauseMs:void 0});C(this,"batchClient",null);this.appConst=e}subscribeTimeLimit(e){return O(this,ut,Jt).call(this).subscribeTimeLimit(e)}init(){return new Promise((e,t)=>{const i=setTimeout(()=>{clearInterval(a);const l=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(l),t(l)},3e4);let a=setInterval(()=>{window.BX24&&BX24.init(async()=>{clearInterval(a),clearTimeout(i),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info();const l=O(this,Gt,pe).call(this);if(console.info(l?"init BX24 (background worker)":"init BX24"),this.appInfo=await O(this,Yt,Ne).call(this),this.userInfo=await O(this,Wt,Oe).call(this),zt(this),l)await O(this,Nt,te).call(this,!1,{skipInit:!0});else{await O(this,Nt,te).call(this,!0);const c=new jt;try{c.noSleep()}catch(h){console.warn("Failed to initialize noSleep:",h)}}e({isBackworker:l})})},100)})}userOption(e,t){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return t!==void 0?BX24.userOption.set(e,t):BX24.userOption.get(e)}appOption(e,t){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return t!==void 0?BX24.appOption.set(e,t):BX24.appOption.get(e)}async call({method:e,params:t,updateList:r}){let i;if(r&&(i=this.logger.start({type:"call",data:{method:e,params:t,updateList:r}})),t||(t={}),typeof BX24>"u"||!BX24.callMethod){const c=new Error("BX24 is not initialized");throw console.error(c),c}const l=await O(this,ut,Jt).call(this).call({method:e,params:t});return l.success?(await O(this,et,dt).call(this,i,{answer:l.answer,status:"success"}),l.data):(console.error(l.error),await O(this,et,dt).call(this,i,{answer:l.answer,status:"fail",errorList:{0:l.error||"Unknown call error"}}),!1)}async batch(e,t,{errorCall:r,updateList:i,batchOptions:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const l=new Error("BX24 is not initialized");return console.error(l),!1}return O(this,Ot,ee).call(this,{mode:"batch",commandList:e,progressCall:t,errorCall:r,updateList:i,batchOptions:a})}async batchTotalCount(e,t,{errorCall:r,updateList:i}={}){if(typeof BX24>"u"||!BX24.callBatch){const a=new Error("BX24 is not initialized");return console.error(a),!1}return O(this,Ot,ee).call(this,{mode:"batch-total-count",commandList:e,progressCall:t,errorCall:r,updateList:i})}async getPlacement(){const e=await this.call({method:"placement.get"});return this.placeData||(this.placeData=e),e}async placementBind(e){var A;if(!this.isAdmin||(this.placeData=await this.getPlacement(),!this.placeData))return;const{appName:t,pathApp:r}=this.appConst;let i=O(this,_t,se).call(this,e);i=i.filter(u=>u.placement!=="PAGE_BACKGROUND_WORKER"&&u.placement!=="PAGE_BACKGROUND_WORKER_ALL");const a=O(this,Ft,Te).call(this,r),l=new Set(i.map(u=>u.placement));for(const u of a)l.has(u.placement)||i.push({placement:u.placement});if(i.length===0)return;let c=t;this.domain==="szdl.bitrix24.ru"&&((A=this.appInfo)!=null&&A.ID)&&(c=`${t}: #${this.appInfo.ID}`);const h=c.replace(" CRM",""),n={},f=[],m=new Map;for(const u of this.placeData)m.has(u.placement)||m.set(u.placement,[]),m.get(u.placement).push(u);for(let u=0;u<i.length;u++){const{placement:N,options:T}=i[u],E=m.get(N)||[];if(E.some(b=>b.handler===r))continue;const y=E.filter(b=>b.handler!==r);for(const b of y)f.push({placement:N,handler:b.handler});n[`bind_${u}`]={method:"placement.bind",params:{PLACEMENT:N,HANDLER:r,LANG_ALL:{ru:{TITLE:N==="USER_PROFILE_TOOLBAR"?h:c}},OPTIONS:{errorHandlerUrl:r,...T&&typeof T=="object"?T:{}}}}}f.length>0&&await this.placementUnBind(f),Object.keys(n).length>0&&(await this.batch(n),this.placeData=await this.getPlacement(),Object.values(n).forEach(u=>{console.log("Приложение успешно встроено в",u.params.PLACEMENT)}))}async placementUnBind(e){let t=O(this,_t,se).call(this,e);if(t=t.filter(i=>i.placement!=="PAGE_BACKGROUND_WORKER"&&i.placement!=="PAGE_BACKGROUND_WORKER_ALL"),t.length===0)return;const r={};for(let i=0;i<t.length;i++){const a={PLACEMENT:t[i].placement};t[i].handler&&(a.HANDLER=t[i].handler),r[`unbind_${i}`]={method:"placement.unbind",params:a}}await this.batch(r),t.forEach(i=>{console.log("Встройка отвязана",i.placement)})}async getBotList(){const e=await this.call({method:"imbot.bot.list",params:{}}),t=Object.values(e);return console.log("chat-bot list:",t),t}async regBot({code:e,type:t,name:r}){const{appName:i,pathApp:a,chatBotLogo:l}=this.appConst,c=this.appInfo.ID,h=await this.call({method:"imbot.register",params:{CODE:e??this.appInfo.CODE,TYPE:t??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${r??i} - бот #${c}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:mt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:l??""}}});return console.log("Чат-бот добавлен",h),h}async unRegBot(e){const t=await this.call({method:"imbot.unregister",params:{BOT_ID:e}});return console.log("чат-бот удален",t),t}getLoggerList(e){return this.logger.getEntityList(e)}}ut=new WeakSet,Jt=function(){return this.batchClient||(this.batchClient=new q({callBatch:BX24.callBatch,callMethod:BX24.callMethod}),this.timeLimit=this.batchClient.timeLimit),this.batchClient},Pt=new WeakSet,ye=function(){return{start:()=>{},stop:()=>{},getEntityList:()=>{}}},Nt=new WeakSet,te=async function(e,{skipInit:t=!1}={}){this.logger?(this.logger=new ie,t?this.logger.enableBackworkerMode():await this.logger.init(),e&&typeof this.logger.runStorageMaintenance=="function"&&this.logger.runStorageMaintenance()):this.logger=O(this,Pt,ye).call(this)},Gt=new WeakSet,pe=function(){var r,i,a;const e=(r=this.placeInfo)==null?void 0:r.placement,t=(a=(i=this.placeInfo)==null?void 0:i.options)==null?void 0:a.ID;return e==="PAGE_BACKGROUND_WORKER"||t==="PAGE_BACKGROUND_WORKER"},Yt=new WeakSet,Ne=function(){return this.call({method:"app.info"})},Wt=new WeakSet,Oe=function(){return this.call({method:"user.current"})},et=new WeakSet,dt=async function(e,t){if(e)try{await this.logger.stop({key:e,...t})}catch(r){console.error("Logger error:",r)}},Ot=new WeakSet,ee=async function({mode:e,commandList:t,progressCall:r,errorCall:i,updateList:a,batchOptions:l}){const c=O(this,ut,Jt).call(this),h=a?this.logger.start({type:e,data:e==="batch"?{commandList:t,updateList:a}:{commandList:t}}):void 0;try{const n=e==="batch"?await c.batch(t,r,l):await c.batchTotalCount(t,r),f=O(this,xt,_e).call(this,c,n,t,a);return Object.keys(f).length?(i&&i(f),await O(this,et,dt).call(this,h,{status:"fail",errorList:f})):await O(this,et,dt).call(this,h,{status:"success"}),n}catch(n){return await O(this,et,dt).call(this,h,{status:"fail-runtime",errorList:{0:n==null?void 0:n.toString()}}),console.error(n),!1}},xt=new WeakSet,_e=function(e,t,r,i){let a={...e.errors};if(Object.values(e.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")})&&i){const c=t?Object.keys(t).filter(m=>m!=="errorsList"):[],h=new Set(Object.keys(e.errors||{})),n=new Set;if(t){for(const m of c)if(!h.has(m)){const A=t[m];A!=null&&n.add(m)}}const f=Object.values(e.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(r))!n.has(m)&&!e.errors[m]&&(a[m]=f||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a},_t=new WeakSet,se=function(e){if(!e)return[];let t=[];return Array.isArray(e)?t=e.map(r=>typeof r=="string"?{placement:r}:r):typeof e=="string"?t=[{placement:e}]:t=[e],t},Ft=new WeakSet,Te=function(e){return this.placeData?this.placeData.filter(t=>!(t.placement==="PAGE_BACKGROUND_WORKER"||!t.handler||t.handler.includes(e))):[]};const ae="szdl-utils-kit|";function Me(){if(typeof sessionStorage>"u")return`ephemeral-${Date.now()}-${Math.random().toString(16).slice(2)}`;let _=sessionStorage.getItem("szdl-cross-tab-instance-id");return _||(_=`${Date.now()}-${Math.random().toString(16).slice(2)}`,sessionStorage.setItem("szdl-cross-tab-instance-id",_)),_}function Ie(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}const Qt=new Map;function Se(_="default"){if(typeof BroadcastChannel>"u")return null;const e=`${ae}bc:${_}`;return Qt.has(e)||Qt.set(e,new BroadcastChannel(e)),Qt.get(e)}function oe(_,e){const t=Se(_);if(t)try{const r=e&&typeof e=="object"&&!Array.isArray(e)?e:{data:e};t.postMessage({...r,tabId:Me(),ts:Date.now()})}catch{}}async function De(_,e,t={}){const{ifAvailable:r=!1}=t,i=typeof _=="string"&&_.length>0?_:"default",a=`${ae}${i}`;return Ie()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!r},async l=>{if(r&&l==null)return{skipped:!0,coordination:"locks"};oe(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await e(),coordination:"locks"}}finally{oe(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await e(),coordination:"none"}}const z={startDelayMs:0,pollIntervalMs:60*1e3,pollIntervalJitterMs:30*1e3,leaderConfirmDelayMs:60*1e3,activeMaxPauseMs:3*60*1e3,quickCleanupThresholdMs:5*60*1e3,leaderHeartbeatMs:null};function Ae(_={}){const e={...z,..._};for(const t of Object.keys(z)){if(t==="leaderHeartbeatMs"){const i=_==null?void 0:_.leaderHeartbeatMs;if(i==null){e.leaderHeartbeatMs=null;continue}const a=Number(i);e.leaderHeartbeatMs=Number.isFinite(a)&&a>=0?a:null;continue}const r=Number(e[t]);e[t]=Number.isFinite(r)&&r>=0?r:z[t]}return e}class ke{constructor(e){L(this,vt);L(this,Tt);C(this,"entityName","tabs");C(this,"maxTabs",20);C(this,"tabList",[]);C(this,"id",0);C(this,"hasStarted",!1);C(this,"heartbeat");C(this,"runHeartbeat");C(this,"startDelay",0);C(this,"activeMaxPause",z.activeMaxPauseMs);C(this,"quickCleanupThreshold",z.quickCleanupThresholdMs);C(this,"pollInterval",z.pollIntervalMs);C(this,"pollIntervalBase",z.pollIntervalMs);C(this,"pollIntervalJitter",z.pollIntervalJitterMs);C(this,"leaderConfirmDelay",z.leaderConfirmDelayMs);C(this,"leaderHeartbeatMs",null);C(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);C(this,"continueCondition");C(this,"defaultContinueBackground",()=>!0);var c,h,n;if(!e){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:t,bx:r,users:i,continueBackground:a,timing:l}=e;this.bx=r,this.appInit=t,this.users=i,O(this,vt,Ee).call(this,l),zt(r),this.appPath=O(this,Tt,re).call(this,((c=r==null?void 0:r.appConst)==null?void 0:c.pathApp)??""),this.appName=((h=r==null?void 0:r.appConst)==null?void 0:h.appName)??"",this.appCodeName=((n=r==null?void 0:r.appConst)==null?void 0:n.appCodeName)??"",this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("BackgroundWorker: appInit не передан");return}if(!this.bx){console.error("BackgroundWorker: bx не передан");return}if(this.isAppPage()){console.log("BackgroundWorker: Страница приложения, фоновый воркер не запускается");return}await this.checkPlacementType()&&await this.continueBackground()&&(await this.checkEntity(),await this.refreshTabs(!0),await this.ensureTabRegistered(),this.startDelay>0&&(console.log(`BackgroundWorker: старт отложен на ${this.startDelay} мс`),await this.pause(this.startDelay)),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(t=>{console.error("BackgroundWorker: backgroundTick failed",t)})},this.pollInterval),await this.backgroundTick())}async backgroundTick(){if(!await this.continueBackground()){this.stopTimers(),console.log("BackgroundWorker: Остановка backgroundTick - условие не выполнено");return}await this.refreshTabs(!0),await this.ensureTabRegistered();const t=this.selectLeaderId(),r=t&&+this.id==+t;await this.updateTabState(r),r&&!this.hasStarted&&await this.runAsLeader()}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var e;if(typeof BX24>"u"||!((e=BX24.placement)!=null&&e.info))return!1;try{const t=BX24.placement.info(),r=t==null?void 0:t.placement,i=(t==null?void 0:t.options)||{},a=(i==null?void 0:i.URI)||"",l=r==="PAGE_BACKGROUND_WORKER"||(i==null?void 0:i.ID)==="PAGE_BACKGROUND_WORKER",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 r;const e=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((r=e==null?void 0:e.find)==null?void 0:r.call(e,i=>i.ENTITY===this.entityName))||await this.safeCall(()=>this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}}))}async getTabs(){const e=await this.safeCall(()=>{var t;return this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:(t=this.bx.userInfo)==null?void 0:t.ID},SORT:{DATE_CREATE:"DESC"}}})});return!Array.isArray(e)||!e.length?[]:e.map(t=>{if(!t)return{id:void 0,data:void 0};try{const r=JSON.parse(t.DETAIL_TEXT);return{id:+t.ID||0,data:r}}catch(r){return console.log("BackgroundWorker: parse tab error",r),{id:+t.ID||0,data:void 0}}})}async ensureTabRegistered(){if(this.id)return+this.id||0;if(this.tabList.length>=this.maxTabs&&await this.refreshTabs(!0,this.quickCleanupThreshold),this.tabList.length>=this.maxTabs)return console.log("BackgroundWorker: Достигнут лимит вкладок даже после быстрой очистки, не регистрируемся"),0;const e={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId},t=await this.safeCall(()=>{var r;return this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(e)}})})||0;return this.id=+t||0,this.id}async updateTabState(e){if(!this.id)return;const t={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:e,sessionId:this.sessionId};await this.safeCall(()=>{var r;return this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(t)}})})}async deleteTabs(e=[]){if(!e.length)return;const t=e.map(r=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:r.id}}));await this.safeCall(()=>this.bx.batch(t))}async checkPlacementType(){var e,t;try{if(!((e=this.bx)!=null&&e.isAdmin))return!0;const r=await this.safeCall(()=>this.bx.getPlacement());if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((t=this.bx.userInfo)==null?void 0:t.ID)??0),a=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),l=!a;if(!i)return!0;let c=!1;for(const h of r){if(h.placement!=="PAGE_BACKGROUND_WORKER"||!(h.userId||h.handler&&h.handler.includes("USER_ID=")))continue;const f=h.userId||(h.handler?this.extractUserIdFromHandler(h.handler):null);if(f&&+f===i){c=!0;break}}return a?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):l&&c?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}isIndividualPlacement(e){return!e||typeof e!="string"?!1:e.includes("USER_ID=")}extractUserIdFromHandler(e){if(!e||typeof e!="string")return null;const t=e.match(/USER_ID=(\d+)/);return t?+t[1]:null}async continueBackground(){try{const t=!!await Promise.resolve(this.continueCondition(this));return console.log(t?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),t}catch(e){return console.error("BackgroundWorker: Ошибка в continueCondition",e),!1}}async refreshTabs(e=!1,t=this.activeMaxPause){const r=[],i=[],a=Date.now(),l=await this.getTabs();for(const c of l){if(!(c!=null&&c.data)){r.push(c);continue}if(a-new Date(c.data.lastActive||0).getTime()>t){r.push(c);continue}i.push(c)}return e&&r.length&&await this.deleteTabs(r),this.tabList=i,i}selectLeaderId(){var t;return this.tabList.length&&+((t=[...this.tabList].sort((r,i)=>{var c,h,n,f;const a=new Date(((c=r.data)==null?void 0:c.createdAt)||((h=r.data)==null?void 0:h.lastActive)||0).getTime(),l=new Date(((n=i.data)==null?void 0:n.createdAt)||((f=i.data)==null?void 0:f.lastActive)||0).getTime();return a===l?(+r.id||0)-(+i.id||0):a-l})[0])==null?void 0:t.id)||0}async confirmLeaderAfterLock(){await this.refreshTabs(!0);const e=this.selectLeaderId();return!!(e&&+this.id==+e)}async runAsLeader(){var i,a;const e=String(((a=(i=this.bx)==null?void 0:i.userInfo)==null?void 0:a.ID)??"0"),t=`background-worker:${this.entityName}:${e}`;(await De(t,async()=>{if(await this.updateTabState(!0),console.log(`BackgroundWorker: захват лидерства, пауза ${this.leaderConfirmDelay} мс перед запуском`),await this.pause(this.leaderConfirmDelay),!await this.confirmLeaderAfterLock()){console.log("BackgroundWorker: запуск отменён — после паузы лидером оказалась другая вкладка"),await this.updateTabState(!1);return}this.hasStarted=!0;const c=this.leaderHeartbeatMs??Math.min(this.activeMaxPause-1500,Math.max(2500,Math.floor(this.pollInterval/2)));this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(h=>console.error("BackgroundWorker: heartbeat update failed",h))},c);try{await this.appInit()}catch(h){console.error("BackgroundWorker: appInit failed",h)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)},{ifAvailable:!0})).skipped&&console.log("BackgroundWorker: runAsLeader пропущен — Web Lock у другой вкладки (подтверждение лидерства)")}async setBackgroundWorkerAll(){var M,y,b,P;if(!((M=this.bx)!=null&&M.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(y=this.users)!=null&&y.length||await this.getEntityData(),zt(this.bx);const e=O(this,Tt,re).call(this,((P=(b=this.bx)==null?void 0:b.appConst)==null?void 0:P.pathApp)??"");if(!e){console.error("BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена");return}const t=await this.safeCall(()=>this.bx.getPlacement()),r=new Map,i=new Map;let a=null;(t||[]).forEach(p=>{if(p.placement!=="PAGE_BACKGROUND_WORKER")return;if(p.userId||p.handler&&p.handler.includes("USER_ID=")){const R=p.userId||(p.handler?this.extractUserIdFromHandler(p.handler):null);if(R){const w=+R;r.set(w,p),i.has(w)||i.set(w,[]),i.get(w).push(p)}}else a=p});const l=await this.resolveAdmins(),c=await this.getEligibleUsersForBackgroundWorker(l);c.sort((p,I)=>{const R=p.LAST_LOGIN?new Date(p.LAST_LOGIN):new Date(0);return(I.LAST_LOGIN?new Date(I.LAST_LOGIN):new Date(0))-R});const h=10,n=c.slice(0,h),f=n.filter(p=>{const I=r.get(+p.ID);if(!I)return!0;const R=`${e}?USER_ID=${p.ID}/`;return I.handler!==R}),m=[];for(const[p]of r){const I=+p||0;c.find(w=>+w.ID===I)||m.push(I)}for(const p of n){const I=r.get(+p.ID);if(!I)continue;const R=`${e}?USER_ID=${p.ID}/`;I.handler!==R&&m.push(+p.ID)}const A=[],u=[...new Set(m)];for(const p of u){const I=i.get(+p)||[];for(const R of I)R!=null&&R.handler&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:R.handler}})}const N=a&&(f.length>0||a.handler!==`${e}`);N&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:a.handler||`${e}`}});for(const p of f)A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}?USER_ID=${p.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}?USER_ID=${p.ID}/`},USER_ID:p.ID}});(!a||N)&&A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}`}}});const T=A.filter(p=>p.method==="placement.unbind"),E=A.filter(p=>p.method==="placement.bind");T.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(T.map((p,I)=>[`unbind_${I}`,p])))),E.length&&await this.safeCall(()=>this.bx.batch(Object.fromEntries(E.map((p,I)=>[`bind_${I}`,p])))),A.length||console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var e,t;try{const r=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),i=!!((t=this.bx)!=null&&t.isAdmin),a=await this.getAdminsList()||[];if(!i){if(r&&a.includes(+r)){const h=a.filter(n=>+n!=+r);return await this.saveAdminsList(h),h}return a}const l=new Set([...a||[]]);r&&l.add(+r);const c=[...l].filter(Boolean);return await this.saveAdminsList(c),c}catch(r){return console.error("BackgroundWorker: resolveAdmins error",r),[]}}async getEligibleUsersForBackgroundWorker(e=[]){const t=(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0),r=e.map(i=>+i||0).filter(Boolean);return t.filter(i=>r.includes(+i.ID||0))}async saveAdminsList(e=[]){try{BX24.appOption.set("adminsList",JSON.stringify(e))}catch(t){console.error("BackgroundWorker: saveAdminsList error",t)}}async getAdminsList(){try{const e=BX24.appOption.get("adminsList"),t=e?JSON.parse(e):[];return Array.isArray(t)?t.map(r=>+r||0).filter(Boolean):[]}catch(e){return console.error("BackgroundWorker: getAdminsList error",e),[]}}async getEntityData(){const e={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:t}=await this.safeCall(()=>this.bx.batch(e).then(r=>r?(Array.isArray(r.users)||(r.users=[]),r):{users:[]}));this.users=t}async ensureAdminPlacements(){var e,t;(e=this.bx)!=null&&e.isAdmin&&((t=this.users)!=null&&t.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(e=500,t){return new Promise(r=>{setTimeout(()=>{t&&t(),r(!0)},e)})}async safeCall(e){try{return await e()}catch(t){console.error("BackgroundWorker: safeCall error",t);return}}}vt=new WeakSet,Ee=function(e){const t=Ae(e);this.startDelay=t.startDelayMs,this.leaderConfirmDelay=t.leaderConfirmDelayMs,this.activeMaxPause=t.activeMaxPauseMs,this.quickCleanupThreshold=t.quickCleanupThresholdMs,this.pollIntervalBase=t.pollIntervalMs,this.pollIntervalJitter=t.pollIntervalJitterMs,this.pollInterval=t.pollIntervalMs+(t.pollIntervalJitterMs>0?Math.floor(Math.random()*t.pollIntervalJitterMs):0),this.leaderHeartbeatMs=t.leaderHeartbeatMs;const r=t.pollIntervalMs+t.pollIntervalJitterMs+t.leaderConfirmDelayMs;t.activeMaxPauseMs<r&&console.warn(`BackgroundWorker: activeMaxPauseMs (${t.activeMaxPauseMs}) меньше poll+jitter+leaderConfirm (${r}) — «живые» вкладки могут удаляться раньше следующего тика`)},Tt=new WeakSet,re=function(e){if(!e||typeof e!="string")return"";const t=qt(e).replace(/\/+$/,"");return t?ne(t)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):t:""},k.BackgroundWorker=ke,k.Batch=q,k.BxBoot=Le,k.BxHelper=jt,k.BxLogger=ie,k.DEFAULT_BACKGROUND_WORKER_TIMING=z,k.resolveBackgroundWorkerTiming=Ae,k.tempus=mt,Object.defineProperty(k,Symbol.toStringTag,{value:"Module"})});
|
|
@@ -17,11 +17,31 @@ type BackgroundWorkerTab = {
|
|
|
17
17
|
data?: Record<string, unknown>;
|
|
18
18
|
};
|
|
19
19
|
|
|
20
|
+
/** Тайминги poll-цикла, подтверждения лидерства и разнесённого старта приложений. */
|
|
21
|
+
type BackgroundWorkerTiming = {
|
|
22
|
+
/** Пауза перед первым тиком (мс). Разносит старт разных приложений. */
|
|
23
|
+
startDelayMs?: number;
|
|
24
|
+
/** Базовый интервал poll-тиков (мс). */
|
|
25
|
+
pollIntervalMs?: number;
|
|
26
|
+
/** Случайная добавка к pollIntervalMs (мс). */
|
|
27
|
+
pollIntervalJitterMs?: number;
|
|
28
|
+
/** Пауза после захвата Web Lock перед повторной проверкой лидерства (мс). */
|
|
29
|
+
leaderConfirmDelayMs?: number;
|
|
30
|
+
/** Вкладка «мёртва» без lastActive дольше этого (мс). */
|
|
31
|
+
activeMaxPauseMs?: number;
|
|
32
|
+
/** Агрессивная очистка tabList при переполнении (мс). */
|
|
33
|
+
quickCleanupThresholdMs?: number;
|
|
34
|
+
/** Heartbeat лидера во время appInit (мс); не задан — вычисляется автоматически. */
|
|
35
|
+
leaderHeartbeatMs?: number | null;
|
|
36
|
+
};
|
|
37
|
+
|
|
20
38
|
type BackgroundWorkerOptions = {
|
|
21
39
|
bx: BxBoot;
|
|
22
40
|
appFunc?: () => void | Promise<void>;
|
|
23
41
|
users?: BackgroundWorkerUser[];
|
|
24
42
|
continueBackground?: (worker: BackgroundWorker) => boolean | Promise<boolean>;
|
|
43
|
+
/** Частичное переопределение таймингов; см. DEFAULT_BACKGROUND_WORKER_TIMING. */
|
|
44
|
+
timing?: BackgroundWorkerTiming;
|
|
25
45
|
};
|
|
26
46
|
|
|
27
47
|
declare class BackgroundWorker {
|
|
@@ -72,10 +92,21 @@ declare class BackgroundWorker {
|
|
|
72
92
|
pause(duration?: number, call?: () => void): Promise<boolean>;
|
|
73
93
|
}
|
|
74
94
|
|
|
95
|
+
/** Стандартные тайминги: poll ~1–1,5 мин, подтверждение лидерства 1 мин. */
|
|
96
|
+
declare const DEFAULT_BACKGROUND_WORKER_TIMING: Required<
|
|
97
|
+
Omit<BackgroundWorkerTiming, 'leaderHeartbeatMs'>
|
|
98
|
+
> & { leaderHeartbeatMs: number | null };
|
|
99
|
+
|
|
100
|
+
declare function resolveBackgroundWorkerTiming(
|
|
101
|
+
partial?: BackgroundWorkerTiming,
|
|
102
|
+
): typeof DEFAULT_BACKGROUND_WORKER_TIMING;
|
|
103
|
+
|
|
75
104
|
export type {
|
|
76
105
|
BackgroundWorkerOptions,
|
|
106
|
+
BackgroundWorkerTiming,
|
|
77
107
|
BackgroundWorkerUser,
|
|
78
108
|
BackgroundWorkerTab,
|
|
79
109
|
};
|
|
80
110
|
|
|
81
111
|
export default BackgroundWorker;
|
|
112
|
+
export { DEFAULT_BACKGROUND_WORKER_TIMING, resolveBackgroundWorkerTiming };
|
package/dist/types/index.d.ts
CHANGED
|
@@ -2,7 +2,10 @@ import Batch from "./batch";
|
|
|
2
2
|
import BxBoot from "./bx-boot";
|
|
3
3
|
import BxHelper from "./bx-helper";
|
|
4
4
|
import BxLogger from "./bx-logger";
|
|
5
|
-
import BackgroundWorker
|
|
5
|
+
import BackgroundWorker, {
|
|
6
|
+
DEFAULT_BACKGROUND_WORKER_TIMING,
|
|
7
|
+
resolveBackgroundWorkerTiming,
|
|
8
|
+
} from "./background-worker";
|
|
6
9
|
|
|
7
10
|
declare function tempus():{
|
|
8
11
|
format();
|
|
@@ -13,4 +16,13 @@ declare function tempus():{
|
|
|
13
16
|
generate();
|
|
14
17
|
};
|
|
15
18
|
|
|
16
|
-
export {
|
|
19
|
+
export {
|
|
20
|
+
Batch,
|
|
21
|
+
BxBoot,
|
|
22
|
+
BxHelper,
|
|
23
|
+
BxLogger,
|
|
24
|
+
BackgroundWorker,
|
|
25
|
+
DEFAULT_BACKGROUND_WORKER_TIMING,
|
|
26
|
+
resolveBackgroundWorkerTiming,
|
|
27
|
+
tempus,
|
|
28
|
+
};
|