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