@bitrix24/b24jssdk
Version:
Bitrix24 REST API JavaScript SDK
71 lines • 476 kB
JavaScript
var Ow=Object.defineProperty;var o=(I,K)=>Ow(I,"name",{value:K,configurable:!0});/**
* @package @bitrix24/b24jssdk
* @version 3.0.0
* @copyright (c) 2026 Bitrix24
* @license MIT
* @see https://github.com/bitrix24/b24jssdk
* @see https://bitrix24.github.io/b24jssdk/
*/(function(I,K){typeof exports=="object"&&typeof module<"u"?K(exports):typeof define=="function"&&define.amd?define(["exports"],K):(I=typeof globalThis<"u"?globalThis:I||self,K(I.B24Js={}))})(this,(function(I){"use strict";var K=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.NOTICE=2]="NOTICE",r[r.WARNING=3]="WARNING",r[r.ERROR=4]="ERROR",r[r.CRITICAL=5]="CRITICAL",r[r.ALERT=6]="ALERT",r[r.EMERGENCY=7]="EMERGENCY",r))(K||{});class jt extends Error{static{o(this,"LuxonError")}}class Qu extends jt{static{o(this,"InvalidDateTimeError")}constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class eh extends jt{static{o(this,"InvalidIntervalError")}constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class th extends jt{static{o(this,"InvalidDurationError")}constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class Qt extends jt{static{o(this,"ConflictingSpecificationError")}}class go extends jt{static{o(this,"InvalidUnitError")}constructor(e){super(`Invalid unit ${e}`)}}class Fe extends jt{static{o(this,"InvalidArgumentError")}}class It extends jt{static{o(this,"ZoneIsAbstractError")}constructor(){super("Zone is an abstract class")}}const M="numeric",ot="short",Ye="long",ns={year:M,month:M,day:M},mo={year:M,month:ot,day:M},rh={year:M,month:ot,day:M,weekday:ot},yo={year:M,month:Ye,day:M},bo={year:M,month:Ye,day:M,weekday:Ye},_o={hour:M,minute:M},wo={hour:M,minute:M,second:M},So={hour:M,minute:M,second:M,timeZoneName:ot},vo={hour:M,minute:M,second:M,timeZoneName:Ye},Eo={hour:M,minute:M,hourCycle:"h23"},Oo={hour:M,minute:M,second:M,hourCycle:"h23"},To={hour:M,minute:M,second:M,hourCycle:"h23",timeZoneName:ot},Ao={hour:M,minute:M,second:M,hourCycle:"h23",timeZoneName:Ye},ko={year:M,month:M,day:M,hour:M,minute:M},Io={year:M,month:M,day:M,hour:M,minute:M,second:M},Ro={year:M,month:ot,day:M,hour:M,minute:M},Co={year:M,month:ot,day:M,hour:M,minute:M,second:M},sh={year:M,month:ot,day:M,weekday:ot,hour:M,minute:M},No={year:M,month:Ye,day:M,hour:M,minute:M,timeZoneName:ot},Do={year:M,month:Ye,day:M,hour:M,minute:M,second:M,timeZoneName:ot},Lo={year:M,month:Ye,day:M,weekday:Ye,hour:M,minute:M,timeZoneName:Ye},Po={year:M,month:Ye,day:M,weekday:Ye,hour:M,minute:M,second:M,timeZoneName:Ye};class Tr{static{o(this,"Zone")}get type(){throw new It}get name(){throw new It}get ianaName(){return this.name}get isUniversal(){throw new It}offsetName(e,t){throw new It}formatOffset(e,t){throw new It}offset(e){throw new It}equals(e){throw new It}get isValid(){throw new It}}let ln=null;class is extends Tr{static{o(this,"SystemZone")}static get instance(){return ln===null&&(ln=new is),ln}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return oa(e,t,s)}formatOffset(e,t){return Rr(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const un=new Map;function nh(r){let e=un.get(r);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:r,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),un.set(r,e)),e}o(nh,"makeDTF");const ih={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function oh(r,e){const t=r.format(e).replace(/\u200E/g,""),s=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(t),[,n,i,c,a,l,h,u]=s;return[c,n,i,a,l,h,u]}o(oh,"hackyOffset");function ah(r,e){const t=r.formatToParts(e),s=[];for(let n=0;n<t.length;n++){const{type:i,value:c}=t[n],a=ih[i];i==="era"?s[a]=c:Z(a)||(s[a]=parseInt(c,10))}return s}o(ah,"partsOffset");const hn=new Map;class wt extends Tr{static{o(this,"IANAZone")}static create(e){let t=hn.get(e);return t===void 0&&hn.set(e,t=new wt(e)),t}static resetCache(){hn.clear(),un.clear()}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=wt.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return oa(e,t,s,this.name)}formatOffset(e,t){return Rr(this.offset(e),t)}offset(e){if(!this.valid)return NaN;const t=new Date(e);if(isNaN(t))return NaN;const s=nh(this.name);let[n,i,c,a,l,h,u]=s.formatToParts?ah(s,t):oh(s,t);a==="BC"&&(n=-Math.abs(n)+1);const g=us({year:n,month:i,day:c,hour:l===24?0:l,minute:h,second:u,millisecond:0});let f=+t;const d=f%1e3;return f-=d>=0?d:1e3+d,(g-f)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let Mo={};function ch(r,e={}){const t=JSON.stringify([r,e]);let s=Mo[t];return s||(s=new Intl.ListFormat(r,e),Mo[t]=s),s}o(ch,"getCachedLF");const dn=new Map;function fn(r,e={}){const t=JSON.stringify([r,e]);let s=dn.get(t);return s===void 0&&(s=new Intl.DateTimeFormat(r,e),dn.set(t,s)),s}o(fn,"getCachedDTF");const pn=new Map;function lh(r,e={}){const t=JSON.stringify([r,e]);let s=pn.get(t);return s===void 0&&(s=new Intl.NumberFormat(r,e),pn.set(t,s)),s}o(lh,"getCachedINF");const gn=new Map;function uh(r,e={}){const{base:t,...s}=e,n=JSON.stringify([r,s]);let i=gn.get(n);return i===void 0&&(i=new Intl.RelativeTimeFormat(r,e),gn.set(n,i)),i}o(uh,"getCachedRTF");let Ar=null;function hh(){return Ar||(Ar=new Intl.DateTimeFormat().resolvedOptions().locale,Ar)}o(hh,"systemLocale");const mn=new Map;function Fo(r){let e=mn.get(r);return e===void 0&&(e=new Intl.DateTimeFormat(r).resolvedOptions(),mn.set(r,e)),e}o(Fo,"getCachedIntResolvedOptions");const yn=new Map;function dh(r){let e=yn.get(r);if(!e){const t=new Intl.Locale(r);e="getWeekInfo"in t?t.getWeekInfo():t.weekInfo,"minimalDays"in e||(e={...xo,...e}),yn.set(r,e)}return e}o(dh,"getCachedWeekInfo");function fh(r){const e=r.indexOf("-x-");e!==-1&&(r=r.substring(0,e));const t=r.indexOf("-u-");if(t===-1)return[r];{let s,n;try{s=fn(r).resolvedOptions(),n=r}catch{const l=r.substring(0,t);s=fn(l).resolvedOptions(),n=l}const{numberingSystem:i,calendar:c}=s;return[n,i,c]}}o(fh,"parseLocaleString");function ph(r,e,t){return(t||e)&&(r.includes("-u-")||(r+="-u"),t&&(r+=`-ca-${t}`),e&&(r+=`-nu-${e}`)),r}o(ph,"intlConfigString");function gh(r){const e=[];for(let t=1;t<=12;t++){const s=z.utc(2009,t,1);e.push(r(s))}return e}o(gh,"mapMonths");function mh(r){const e=[];for(let t=1;t<=7;t++){const s=z.utc(2016,11,13+t);e.push(r(s))}return e}o(mh,"mapWeekdays");function os(r,e,t,s){const n=r.listingMode();return n==="error"?null:n==="en"?t(e):s(e)}o(os,"listStuff");function yh(r){return r.numberingSystem&&r.numberingSystem!=="latn"?!1:r.numberingSystem==="latn"||!r.locale||r.locale.startsWith("en")||Fo(r.locale).numberingSystem==="latn"}o(yh,"supportsFastNumbers");class bh{static{o(this,"PolyNumberFormatter")}constructor(e,t,s){this.padTo=s.padTo||0,this.floor=s.floor||!1;const{padTo:n,floor:i,...c}=s;if(!t||Object.keys(c).length>0){const a={useGrouping:!1,...s};s.padTo>0&&(a.minimumIntegerDigits=s.padTo),this.inf=lh(e,a)}}format(e){if(this.inf){const t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{const t=this.floor?Math.floor(e):An(e,3);return Oe(t,this.padTo)}}}class _h{static{o(this,"PolyDateFormatter")}constructor(e,t,s){this.opts=s,this.originalZone=void 0;let n;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){const c=-1*(e.offset/60),a=c>=0?`Etc/GMT+${c}`:`Etc/GMT${c}`;e.offset!==0&&wt.create(a).valid?(n=a,this.dt=e):(n="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,n=e.zone.name):(n="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);const i={...this.opts};i.timeZone=i.timeZone||n,this.dtf=fn(t,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(t=>{if(t.type==="timeZoneName"){const s=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...t,value:s}}else return t}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class wh{static{o(this,"PolyRelFormatter")}constructor(e,t,s){this.opts={style:"long",...s},!t&&ra()&&(this.rtf=uh(e,s))}format(e,t){return this.rtf?this.rtf.format(e,t):Vh(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}}const xo={firstDay:1,minimalDays:4,weekend:[6,7]};class ne{static{o(this,"Locale")}static fromOpts(e){return ne.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,t,s,n,i=!1){const c=e||ye.defaultLocale,a=c||(i?"en-US":hh()),l=t||ye.defaultNumberingSystem,h=s||ye.defaultOutputCalendar,u=On(n)||ye.defaultWeekSettings;return new ne(a,l,h,u,c)}static resetCache(){Ar=null,dn.clear(),pn.clear(),gn.clear(),mn.clear(),yn.clear()}static fromObject({locale:e,numberingSystem:t,outputCalendar:s,weekSettings:n}={}){return ne.create(e,t,s,n)}constructor(e,t,s,n,i){const[c,a,l]=fh(e);this.locale=c,this.numberingSystem=t||a||null,this.outputCalendar=s||l||null,this.weekSettings=n,this.intl=ph(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=yh(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&t?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:ne.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,On(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,t=!1){return os(this,e,la,()=>{const s=this.intl==="ja"||this.intl.startsWith("ja-");t&=!s;const n=t?{month:e,day:"numeric"}:{month:e},i=t?"format":"standalone";if(!this.monthsCache[i][e]){const c=s?a=>this.dtFormatter(a,n).format():a=>this.extract(a,n,"month");this.monthsCache[i][e]=gh(c)}return this.monthsCache[i][e]})}weekdays(e,t=!1){return os(this,e,da,()=>{const s=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},n=t?"format":"standalone";return this.weekdaysCache[n][e]||(this.weekdaysCache[n][e]=mh(i=>this.extract(i,s,"weekday"))),this.weekdaysCache[n][e]})}meridiems(){return os(this,void 0,()=>fa,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[z.utc(2016,11,13,9),z.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return os(this,e,pa,()=>{const t={era:e};return this.eraCache[e]||(this.eraCache[e]=[z.utc(-40,1,1),z.utc(2017,1,1)].map(s=>this.extract(s,t,"era"))),this.eraCache[e]})}extract(e,t,s){const n=this.dtFormatter(e,t),i=n.formatToParts(),c=i.find(a=>a.type.toLowerCase()===s);return c?c.value:null}numberFormatter(e={}){return new bh(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new _h(e,this.intl,t)}relFormatter(e={}){return new wh(this.intl,this.isEnglish(),e)}listFormatter(e={}){return ch(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||Fo(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:sa()?dh(this.locale):xo}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let bn=null;class Ve extends Tr{static{o(this,"FixedOffsetZone")}static get utcInstance(){return bn===null&&(bn=new Ve(0)),bn}static instance(e){return e===0?Ve.utcInstance:new Ve(e)}static parseSpecifier(e){if(e){const t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new Ve(hs(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Rr(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Rr(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return Rr(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class Sh extends Tr{static{o(this,"InvalidZone")}constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function Rt(r,e){if(Z(r)||r===null)return e;if(r instanceof Tr)return r;if(kh(r)){const t=r.toLowerCase();return t==="default"?e:t==="local"||t==="system"?is.instance:t==="utc"||t==="gmt"?Ve.utcInstance:Ve.parseSpecifier(t)||wt.create(r)}else return Ct(r)?Ve.instance(r):typeof r=="object"&&"offset"in r&&typeof r.offset=="function"?r:new Sh(r)}o(Rt,"normalizeZone");const _n={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},$o={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},vh=_n.hanidec.replace(/[\[|\]]/g,"").split("");function Eh(r){let e=parseInt(r,10);if(isNaN(e)){e="";for(let t=0;t<r.length;t++){const s=r.charCodeAt(t);if(r[t].search(_n.hanidec)!==-1)e+=vh.indexOf(r[t]);else for(const n in $o){const[i,c]=$o[n];s>=i&&s<=c&&(e+=s-i)}}return parseInt(e,10)}else return e}o(Eh,"parseDigits");const wn=new Map;function Oh(){wn.clear()}o(Oh,"resetDigitRegexCache");function at({numberingSystem:r},e=""){const t=r||"latn";let s=wn.get(t);s===void 0&&(s=new Map,wn.set(t,s));let n=s.get(e);return n===void 0&&(n=new RegExp(`${_n[t]}${e}`),s.set(e,n)),n}o(at,"digitRegex");let jo=o(()=>Date.now(),"now"),Bo="system",Uo=null,Vo=null,qo=null,Ho=60,Wo,zo=null;class ye{static{o(this,"Settings")}static get now(){return jo}static set now(e){jo=e}static set defaultZone(e){Bo=e}static get defaultZone(){return Rt(Bo,is.instance)}static get defaultLocale(){return Uo}static set defaultLocale(e){Uo=e}static get defaultNumberingSystem(){return Vo}static set defaultNumberingSystem(e){Vo=e}static get defaultOutputCalendar(){return qo}static set defaultOutputCalendar(e){qo=e}static get defaultWeekSettings(){return zo}static set defaultWeekSettings(e){zo=On(e)}static get twoDigitCutoffYear(){return Ho}static set twoDigitCutoffYear(e){Ho=e%100}static get throwOnInvalid(){return Wo}static set throwOnInvalid(e){Wo=e}static resetCaches(){ne.resetCache(),wt.resetCache(),z.resetCache(),Oh()}}class ct{static{o(this,"Invalid")}constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const Jo=[0,31,59,90,120,151,181,212,243,273,304,334],Ko=[0,31,60,91,121,152,182,213,244,274,305,335];function Qe(r,e){return new ct("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${r}, which is invalid`)}o(Qe,"unitOutOfRange");function Sn(r,e,t){const s=new Date(Date.UTC(r,e-1,t));r<100&&r>=0&&s.setUTCFullYear(s.getUTCFullYear()-1900);const n=s.getUTCDay();return n===0?7:n}o(Sn,"dayOfWeek");function Go(r,e,t){return t+(kr(r)?Ko:Jo)[e-1]}o(Go,"computeOrdinal");function Yo(r,e){const t=kr(r)?Ko:Jo,s=t.findIndex(i=>i<e),n=e-t[s];return{month:s+1,day:n}}o(Yo,"uncomputeOrdinal");function vn(r,e){return(r-e+7)%7+1}o(vn,"isoWeekdayToLocal");function as(r,e=4,t=1){const{year:s,month:n,day:i}=r,c=Go(s,n,i),a=vn(Sn(s,n,i),t);let l=Math.floor((c-a+14-e)/7),h;return l<1?(h=s-1,l=Ir(h,e,t)):l>Ir(s,e,t)?(h=s+1,l=1):h=s,{weekYear:h,weekNumber:l,weekday:a,...fs(r)}}o(as,"gregorianToWeek");function Zo(r,e=4,t=1){const{weekYear:s,weekNumber:n,weekday:i}=r,c=vn(Sn(s,1,e),t),a=tr(s);let l=n*7+i-c-7+e,h;l<1?(h=s-1,l+=tr(h)):l>a?(h=s+1,l-=tr(s)):h=s;const{month:u,day:p}=Yo(h,l);return{year:h,month:u,day:p,...fs(r)}}o(Zo,"weekToGregorian");function En(r){const{year:e,month:t,day:s}=r,n=Go(e,t,s);return{year:e,ordinal:n,...fs(r)}}o(En,"gregorianToOrdinal");function Xo(r){const{year:e,ordinal:t}=r,{month:s,day:n}=Yo(e,t);return{year:e,month:s,day:n,...fs(r)}}o(Xo,"ordinalToGregorian");function Qo(r,e){if(!Z(r.localWeekday)||!Z(r.localWeekNumber)||!Z(r.localWeekYear)){if(!Z(r.weekday)||!Z(r.weekNumber)||!Z(r.weekYear))throw new Qt("Cannot mix locale-based week fields with ISO-based week fields");return Z(r.localWeekday)||(r.weekday=r.localWeekday),Z(r.localWeekNumber)||(r.weekNumber=r.localWeekNumber),Z(r.localWeekYear)||(r.weekYear=r.localWeekYear),delete r.localWeekday,delete r.localWeekNumber,delete r.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}o(Qo,"usesLocalWeekValues");function Th(r,e=4,t=1){const s=cs(r.weekYear),n=et(r.weekNumber,1,Ir(r.weekYear,e,t)),i=et(r.weekday,1,7);return s?n?i?!1:Qe("weekday",r.weekday):Qe("week",r.weekNumber):Qe("weekYear",r.weekYear)}o(Th,"hasInvalidWeekData");function Ah(r){const e=cs(r.year),t=et(r.ordinal,1,tr(r.year));return e?t?!1:Qe("ordinal",r.ordinal):Qe("year",r.year)}o(Ah,"hasInvalidOrdinalData");function ea(r){const e=cs(r.year),t=et(r.month,1,12),s=et(r.day,1,ls(r.year,r.month));return e?t?s?!1:Qe("day",r.day):Qe("month",r.month):Qe("year",r.year)}o(ea,"hasInvalidGregorianData");function ta(r){const{hour:e,minute:t,second:s,millisecond:n}=r,i=et(e,0,23)||e===24&&t===0&&s===0&&n===0,c=et(t,0,59),a=et(s,0,59),l=et(n,0,999);return i?c?a?l?!1:Qe("millisecond",n):Qe("second",s):Qe("minute",t):Qe("hour",e)}o(ta,"hasInvalidTimeData");function Z(r){return typeof r>"u"}o(Z,"isUndefined$1");function Ct(r){return typeof r=="number"}o(Ct,"isNumber$1");function cs(r){return typeof r=="number"&&r%1===0}o(cs,"isInteger");function kh(r){return typeof r=="string"}o(kh,"isString$1");function Ih(r){return Object.prototype.toString.call(r)==="[object Date]"}o(Ih,"isDate$1");function ra(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}o(ra,"hasRelative");function sa(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}o(sa,"hasLocaleWeekInfo");function Rh(r){return Array.isArray(r)?r:[r]}o(Rh,"maybeArray");function na(r,e,t){if(r.length!==0)return r.reduce((s,n)=>{const i=[e(n),n];return s&&t(s[0],i[0])===s[0]?s:i},null)[1]}o(na,"bestBy");function Ch(r,e){return e.reduce((t,s)=>(t[s]=r[s],t),{})}o(Ch,"pick$1");function er(r,e){return Object.prototype.hasOwnProperty.call(r,e)}o(er,"hasOwnProperty$1");function On(r){if(r==null)return null;if(typeof r!="object")throw new Fe("Week settings must be an object");if(!et(r.firstDay,1,7)||!et(r.minimalDays,1,7)||!Array.isArray(r.weekend)||r.weekend.some(e=>!et(e,1,7)))throw new Fe("Invalid week settings");return{firstDay:r.firstDay,minimalDays:r.minimalDays,weekend:Array.from(r.weekend)}}o(On,"validateWeekSettings");function et(r,e,t){return cs(r)&&r>=e&&r<=t}o(et,"integerBetween");function Nh(r,e){return r-e*Math.floor(r/e)}o(Nh,"floorMod");function Oe(r,e=2){const t=r<0;let s;return t?s="-"+(""+-r).padStart(e,"0"):s=(""+r).padStart(e,"0"),s}o(Oe,"padStart");function Nt(r){if(!(Z(r)||r===null||r===""))return parseInt(r,10)}o(Nt,"parseInteger");function Bt(r){if(!(Z(r)||r===null||r===""))return parseFloat(r)}o(Bt,"parseFloating");function Tn(r){if(!(Z(r)||r===null||r==="")){const e=parseFloat("0."+r)*1e3;return Math.floor(e)}}o(Tn,"parseMillis");function An(r,e,t="round"){const s=10**e;switch(t){case"expand":return r>0?Math.ceil(r*s)/s:Math.floor(r*s)/s;case"trunc":return Math.trunc(r*s)/s;case"round":return Math.round(r*s)/s;case"floor":return Math.floor(r*s)/s;case"ceil":return Math.ceil(r*s)/s;default:throw new RangeError(`Value rounding ${t} is out of range`)}}o(An,"roundTo");function kr(r){return r%4===0&&(r%100!==0||r%400===0)}o(kr,"isLeapYear");function tr(r){return kr(r)?366:365}o(tr,"daysInYear");function ls(r,e){const t=Nh(e-1,12)+1,s=r+(e-t)/12;return t===2?kr(s)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}o(ls,"daysInMonth");function us(r){let e=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second,r.millisecond);return r.year<100&&r.year>=0&&(e=new Date(e),e.setUTCFullYear(r.year,r.month-1,r.day)),+e}o(us,"objToLocalTS");function ia(r,e,t){return-vn(Sn(r,1,e),t)+e-1}o(ia,"firstWeekOffset");function Ir(r,e=4,t=1){const s=ia(r,e,t),n=ia(r+1,e,t);return(tr(r)-s+n)/7}o(Ir,"weeksInWeekYear");function kn(r){return r>99?r:r>ye.twoDigitCutoffYear?1900+r:2e3+r}o(kn,"untruncateYear");function oa(r,e,t,s=null){const n=new Date(r),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};s&&(i.timeZone=s);const c={timeZoneName:e,...i},a=new Intl.DateTimeFormat(t,c).formatToParts(n).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}o(oa,"parseZoneInfo");function hs(r,e){let t=parseInt(r,10);Number.isNaN(t)&&(t=0);const s=parseInt(e,10)||0,n=t<0||Object.is(t,-0)?-s:s;return t*60+n}o(hs,"signedOffset");function aa(r){const e=Number(r);if(typeof r=="boolean"||r===""||!Number.isFinite(e))throw new Fe(`Invalid unit value ${r}`);return e}o(aa,"asNumber");function ds(r,e){const t={};for(const s in r)if(er(r,s)){const n=r[s];if(n==null)continue;t[e(s)]=aa(n)}return t}o(ds,"normalizeObject");function Rr(r,e){const t=Math.trunc(Math.abs(r/60)),s=Math.trunc(Math.abs(r%60)),n=r>=0?"+":"-";switch(e){case"short":return`${n}${Oe(t,2)}:${Oe(s,2)}`;case"narrow":return`${n}${t}${s>0?`:${s}`:""}`;case"techie":return`${n}${Oe(t,2)}${Oe(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}o(Rr,"formatOffset");function fs(r){return Ch(r,["hour","minute","second","millisecond"])}o(fs,"timeObject");const Dh=["January","February","March","April","May","June","July","August","September","October","November","December"],ca=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Lh=["J","F","M","A","M","J","J","A","S","O","N","D"];function la(r){switch(r){case"narrow":return[...Lh];case"short":return[...ca];case"long":return[...Dh];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}o(la,"months");const ua=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],ha=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Ph=["M","T","W","T","F","S","S"];function da(r){switch(r){case"narrow":return[...Ph];case"short":return[...ha];case"long":return[...ua];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}o(da,"weekdays");const fa=["AM","PM"],Mh=["Before Christ","Anno Domini"],Fh=["BC","AD"],xh=["B","A"];function pa(r){switch(r){case"narrow":return[...xh];case"short":return[...Fh];case"long":return[...Mh];default:return null}}o(pa,"eras");function $h(r){return fa[r.hour<12?0:1]}o($h,"meridiemForDateTime");function jh(r,e){return da(e)[r.weekday-1]}o(jh,"weekdayForDateTime");function Bh(r,e){return la(e)[r.month-1]}o(Bh,"monthForDateTime");function Uh(r,e){return pa(e)[r.year<0?0:1]}o(Uh,"eraForDateTime");function Vh(r,e,t="always",s=!1){const n={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},i=["hours","minutes","seconds"].indexOf(r)===-1;if(t==="auto"&&i){const p=r==="days";switch(e){case 1:return p?"tomorrow":`next ${n[r][0]}`;case-1:return p?"yesterday":`last ${n[r][0]}`;case 0:return p?"today":`this ${n[r][0]}`}}const c=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,h=n[r],u=s?l?h[1]:h[2]||h[1]:l?n[r][0]:r;return c?`${a} ${u} ago`:`in ${a} ${u}`}o(Vh,"formatRelativeTime");function ga(r,e){let t="";for(const s of r)s.literal?t+=s.val:t+=e(s.val);return t}o(ga,"stringifyTokens");const qh={D:ns,DD:mo,DDD:yo,DDDD:bo,t:_o,tt:wo,ttt:So,tttt:vo,T:Eo,TT:Oo,TTT:To,TTTT:Ao,f:ko,ff:Ro,fff:No,ffff:Lo,F:Io,FF:Co,FFF:Do,FFFF:Po};class xe{static{o(this,"Formatter")}static create(e,t={}){return new xe(e,t)}static parseFormat(e){let t=null,s="",n=!1;const i=[];for(let c=0;c<e.length;c++){const a=e.charAt(c);a==="'"?((s.length>0||n)&&i.push({literal:n||/^\s+$/.test(s),val:s===""?"'":s}),t=null,s="",n=!n):n||a===t?s+=a:(s.length>0&&i.push({literal:/^\s+$/.test(s),val:s}),s=a,t=a)}return s.length>0&&i.push({literal:n||/^\s+$/.test(s),val:s}),i}static macroTokenToFormatOpts(e){return qh[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0,s=void 0){if(this.opts.forceSimple)return Oe(e,t);const n={...this.opts};return t>0&&(n.padTo=t),s&&(n.signDisplay=s),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,t){const s=this.loc.listingMode()==="en",n=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=o((f,d)=>this.loc.extract(e,f,d),"string"),c=o(f=>e.isOffsetFixed&&e.offset===0&&f.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,f.format):"","formatOffset"),a=o(()=>s?$h(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),"meridiem"),l=o((f,d)=>s?Bh(e,f):i(d?{month:f}:{month:f,day:"numeric"},"month"),"month"),h=o((f,d)=>s?jh(e,f):i(d?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),"weekday"),u=o(f=>{const d=xe.macroTokenToFormatOpts(f);return d?this.formatWithSystemDefault(e,d):f},"maybeMacro"),p=o(f=>s?Uh(e,f):i({era:f},"era"),"era"),g=o(f=>{switch(f){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return c({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return c({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return c({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return n?i({day:"numeric"},"day"):this.num(e.day);case"dd":return n?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return h("short",!0);case"cccc":return h("long",!0);case"ccccc":return h("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return h("short",!1);case"EEEE":return h("long",!1);case"EEEEE":return h("narrow",!1);case"L":return n?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return n?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return n?i({month:"numeric"},"month"):this.num(e.month);case"MM":return n?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return n?i({year:"numeric"},"year"):this.num(e.year);case"yy":return n?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return n?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return n?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return p("short");case"GG":return p("long");case"GGGGG":return p("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return u(f)}},"tokenToString");return ga(xe.parseFormat(t),g)}formatDurationFromString(e,t){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,n=o(u=>{switch(u[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},"tokenToField"),i=o((u,p)=>g=>{const f=n(g);if(f){const d=p.isNegativeDuration&&f!==p.largestUnit?s:1;let y;return this.opts.signMode==="negativeLargestOnly"&&f!==p.largestUnit?y="never":this.opts.signMode==="all"?y="always":y="auto",this.num(u.get(f)*d,g.length,y)}else return g},"tokenToString"),c=xe.parseFormat(t),a=c.reduce((u,{literal:p,val:g})=>p?u:u.concat(g),[]),l=e.shiftTo(...a.map(n).filter(u=>u)),h={isNegativeDuration:l<0,largestUnit:Object.keys(l.values)[0]};return ga(c,i(l,h))}}const ma=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function rr(...r){const e=r.reduce((t,s)=>t+s.source,"");return RegExp(`^${e}$`)}o(rr,"combineRegexes");function sr(...r){return e=>r.reduce(([t,s,n],i)=>{const[c,a,l]=i(e,n);return[{...t,...c},a||s,l]},[{},null,1]).slice(0,2)}o(sr,"combineExtractors");function nr(r,...e){if(r==null)return[null,null];for(const[t,s]of e){const n=t.exec(r);if(n)return s(n)}return[null,null]}o(nr,"parse");function ya(...r){return(e,t)=>{const s={};let n;for(n=0;n<r.length;n++)s[r[n]]=Nt(e[t+n]);return[s,null,t+n]}}o(ya,"simpleParse");const ba=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Hh=`(?:${ba.source}?(?:\\[(${ma.source})\\])?)?`,In=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,_a=RegExp(`${In.source}${Hh}`),Rn=RegExp(`(?:[Tt]${_a.source})?`),Wh=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,zh=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Jh=/(\d{4})-?(\d{3})/,Kh=ya("weekYear","weekNumber","weekDay"),Gh=ya("year","ordinal"),Yh=/(\d{4})-(\d\d)-(\d\d)/,wa=RegExp(`${In.source} ?(?:${ba.source}|(${ma.source}))?`),Zh=RegExp(`(?: ${wa.source})?`);function ir(r,e,t){const s=r[e];return Z(s)?t:Nt(s)}o(ir,"int");function Xh(r,e){return[{year:ir(r,e),month:ir(r,e+1,1),day:ir(r,e+2,1)},null,e+3]}o(Xh,"extractISOYmd");function or(r,e){return[{hours:ir(r,e,0),minutes:ir(r,e+1,0),seconds:ir(r,e+2,0),milliseconds:Tn(r[e+3])},null,e+4]}o(or,"extractISOTime");function Cr(r,e){const t=!r[e]&&!r[e+1],s=hs(r[e+1],r[e+2]),n=t?null:Ve.instance(s);return[{},n,e+3]}o(Cr,"extractISOOffset");function Nr(r,e){const t=r[e]?wt.create(r[e]):null;return[{},t,e+1]}o(Nr,"extractIANAZone");const Qh=RegExp(`^T?${In.source}$`),ed=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function td(r){const[e,t,s,n,i,c,a,l,h]=r,u=e[0]==="-",p=l&&l[0]==="-",g=o((f,d=!1)=>f!==void 0&&(d||f&&u)?-f:f,"maybeNegate");return[{years:g(Bt(t)),months:g(Bt(s)),weeks:g(Bt(n)),days:g(Bt(i)),hours:g(Bt(c)),minutes:g(Bt(a)),seconds:g(Bt(l),l==="-0"),milliseconds:g(Tn(h),p)}]}o(td,"extractISODuration");const rd={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Cn(r,e,t,s,n,i,c){const a={year:e.length===2?kn(Nt(e)):Nt(e),month:ca.indexOf(t)+1,day:Nt(s),hour:Nt(n),minute:Nt(i)};return c&&(a.second=Nt(c)),r&&(a.weekday=r.length>3?ua.indexOf(r)+1:ha.indexOf(r)+1),a}o(Cn,"fromStrings");const sd=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function nd(r){const[,e,t,s,n,i,c,a,l,h,u,p]=r,g=Cn(e,n,s,t,i,c,a);let f;return l?f=rd[l]:h?f=0:f=hs(u,p),[g,new Ve(f)]}o(nd,"extractRFC2822");function id(r){return r.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}o(id,"preprocessRFC2822");const od=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,ad=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,cd=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function Sa(r){const[,e,t,s,n,i,c,a]=r;return[Cn(e,n,s,t,i,c,a),Ve.utcInstance]}o(Sa,"extractRFC1123Or850");function ld(r){const[,e,t,s,n,i,c,a]=r;return[Cn(e,a,t,s,n,i,c),Ve.utcInstance]}o(ld,"extractASCII");const ud=rr(Wh,Rn),hd=rr(zh,Rn),dd=rr(Jh,Rn),fd=rr(_a),va=sr(Xh,or,Cr,Nr),pd=sr(Kh,or,Cr,Nr),gd=sr(Gh,or,Cr,Nr),md=sr(or,Cr,Nr);function yd(r){return nr(r,[ud,va],[hd,pd],[dd,gd],[fd,md])}o(yd,"parseISODate");function bd(r){return nr(id(r),[sd,nd])}o(bd,"parseRFC2822Date");function _d(r){return nr(r,[od,Sa],[ad,Sa],[cd,ld])}o(_d,"parseHTTPDate");function wd(r){return nr(r,[ed,td])}o(wd,"parseISODuration");const Sd=sr(or);function vd(r){return nr(r,[Qh,Sd])}o(vd,"parseISOTimeOnly");const Ed=rr(Yh,Zh),Od=rr(wa),Td=sr(or,Cr,Nr);function Ad(r){return nr(r,[Ed,va],[Od,Td])}o(Ad,"parseSQL");const Ea="Invalid Duration",Oa={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},kd={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...Oa},tt=146097/400,ar=146097/4800,Id={years:{quarters:4,months:12,weeks:tt/7,days:tt,hours:tt*24,minutes:tt*24*60,seconds:tt*24*60*60,milliseconds:tt*24*60*60*1e3},quarters:{months:3,weeks:tt/28,days:tt/4,hours:tt*24/4,minutes:tt*24*60/4,seconds:tt*24*60*60/4,milliseconds:tt*24*60*60*1e3/4},months:{weeks:ar/7,days:ar,hours:ar*24,minutes:ar*24*60,seconds:ar*24*60*60,milliseconds:ar*24*60*60*1e3},...Oa},Ut=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Rd=Ut.slice(0).reverse();function St(r,e,t=!1){const s={values:t?e.values:{...r.values,...e.values||{}},loc:r.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||r.conversionAccuracy,matrix:e.matrix||r.matrix};return new te(s)}o(St,"clone$1");function Ta(r,e){let t=e.milliseconds??0;for(const s of Rd.slice(1))e[s]&&(t+=e[s]*r[s].milliseconds);return t}o(Ta,"durationToMillis");function Aa(r,e){const t=Ta(r,e)<0?-1:1;Ut.reduceRight((s,n)=>{if(Z(e[n]))return s;if(s){const i=e[s]*t,c=r[n][s],a=Math.floor(i/c);e[n]+=a*t,e[s]-=a*c*t}return n},null),Ut.reduce((s,n)=>{if(Z(e[n]))return s;if(s){const i=e[s]%1;e[s]-=i,e[n]+=i*r[s][n]}return n},null)}o(Aa,"normalizeValues");function ka(r){const e={};for(const[t,s]of Object.entries(r))s!==0&&(e[t]=s);return e}o(ka,"removeZeroes");class te{static{o(this,"Duration")}constructor(e){const t=e.conversionAccuracy==="longterm"||!1;let s=t?Id:kd;e.matrix&&(s=e.matrix),this.values=e.values,this.loc=e.loc||ne.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,t){return te.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new Fe(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new te({values:ds(e,te.normalizeUnit),loc:ne.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(Ct(e))return te.fromMillis(e);if(te.isDuration(e))return e;if(typeof e=="object")return te.fromObject(e);throw new Fe(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){const[s]=wd(e);return s?te.fromObject(s,t):te.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){const[s]=vd(e);return s?te.fromObject(s,t):te.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new Fe("need to specify a reason the Duration is invalid");const s=e instanceof ct?e:new ct(e,t);if(ye.throwOnInvalid)throw new th(s);return new te({invalid:s})}static normalizeUnit(e){const t={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!t)throw new go(e);return t}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,t={}){const s={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?xe.create(this.loc,s).formatDurationFromString(this,e):Ea}toHuman(e={}){if(!this.isValid)return Ea;const t=e.showZeros!==!1,s=Ut.map(n=>{const i=this.values[n];return Z(i)||i===0&&!t?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(i)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(s)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=An(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},z.fromMillis(t,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?Ta(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e),s={};for(const n of Ut)(er(t.values,n)||er(this.values,n))&&(s[n]=t.get(n)+this.get(n));return St(this,{values:s},!0)}minus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;const t={};for(const s of Object.keys(this.values))t[s]=aa(e(this.values[s],s));return St(this,{values:t},!0)}get(e){return this[te.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const t={...this.values,...ds(e,te.normalizeUnit)};return St(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:s,matrix:n}={}){const c={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:n,conversionAccuracy:s};return St(this,c)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return Aa(this.matrix,e),St(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=ka(this.normalize().shiftToAll().toObject());return St(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(c=>te.normalizeUnit(c));const t={},s={},n=this.toObject();let i;for(const c of Ut)if(e.indexOf(c)>=0){i=c;let a=0;for(const h in s)a+=this.matrix[h][c]*s[h],s[h]=0;Ct(n[c])&&(a+=n[c]);const l=Math.trunc(a);t[c]=l,s[c]=(a*1e3-l*1e3)/1e3}else Ct(n[c])&&(s[c]=n[c]);for(const c in s)s[c]!==0&&(t[i]+=c===i?s[c]:s[c]/this.matrix[i][c]);return Aa(this.matrix,t),St(this,{values:t},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const e={};for(const t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return St(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=ka(this.values);return St(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(s,n){return s===void 0||s===0?n===void 0||n===0:s===n}o(t,"eq");for(const s of Ut)if(!t(this.values[s],e.values[s]))return!1;return!0}}const cr="Invalid Interval";function Cd(r,e){return!r||!r.isValid?be.invalid("missing or invalid start"):!e||!e.isValid?be.invalid("missing or invalid end"):e<r?be.invalid("end before start",`The end of an interval must be after its start, but you had start=${r.toISO()} and end=${e.toISO()}`):null}o(Cd,"validateStartEnd");class be{static{o(this,"Interval")}constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,t=null){if(!e)throw new Fe("need to specify a reason the Interval is invalid");const s=e instanceof ct?e:new ct(e,t);if(ye.throwOnInvalid)throw new eh(s);return new be({invalid:s})}static fromDateTimes(e,t){const s=Pr(e),n=Pr(t),i=Cd(s,n);return i??new be({start:s,end:n})}static after(e,t){const s=te.fromDurationLike(t),n=Pr(e);return be.fromDateTimes(n,n.plus(s))}static before(e,t){const s=te.fromDurationLike(t),n=Pr(e);return be.fromDateTimes(n.minus(s),n)}static fromISO(e,t){const[s,n]=(e||"").split("/",2);if(s&&n){let i,c;try{i=z.fromISO(s,t),c=i.isValid}catch{c=!1}let a,l;try{a=z.fromISO(n,t),l=a.isValid}catch{l=!1}if(c&&l)return be.fromDateTimes(i,a);if(c){const h=te.fromISO(n,t);if(h.isValid)return be.after(i,h)}else if(l){const h=te.fromISO(s,t);if(h.isValid)return be.before(a,h)}}return be.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",t){if(!this.isValid)return NaN;const s=this.start.startOf(e,t);let n;return t?.useLocaleWeeks?n=this.end.reconfigure({locale:s.locale}):n=this.end,n=n.startOf(e,t),Math.floor(n.diff(s,e).get(e))+(n.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:t}={}){return this.isValid?be.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];const t=e.map(Pr).filter(c=>this.contains(c)).sort((c,a)=>c.toMillis()-a.toMillis()),s=[];let{s:n}=this,i=0;for(;n<this.e;){const c=t[i]||this.e,a=+c>+this.e?this.e:c;s.push(be.fromDateTimes(n,a)),n=a,i+=1}return s}splitBy(e){const t=te.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s}=this,n=1,i;const c=[];for(;s<this.e;){const a=this.start.plus(t.mapUnits(l=>l*n));i=+a>+this.e?this.e:a,c.push(be.fromDateTimes(s,i)),s=i,n+=1}return c}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const t=this.s>e.s?this.s:e.s,s=this.e<e.e?this.e:e.e;return t>=s?null:be.fromDateTimes(t,s)}union(e){if(!this.isValid)return this;const t=this.s<e.s?this.s:e.s,s=this.e>e.e?this.e:e.e;return be.fromDateTimes(t,s)}static merge(e){const[t,s]=e.sort((n,i)=>n.s-i.s).reduce(([n,i],c)=>i?i.overlaps(c)||i.abutsStart(c)?[n,i.union(c)]:[n.concat([i]),c]:[n,c],[[],null]);return s&&t.push(s),t}static xor(e){let t=null,s=0;const n=[],i=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),c=Array.prototype.concat(...i),a=c.sort((l,h)=>l.time-h.time);for(const l of a)s+=l.type==="s"?1:-1,s===1?t=l.time:(t&&+t!=+l.time&&n.push(be.fromDateTimes(t,l.time)),t=null);return be.merge(n)}difference(...e){return be.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:cr}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=ns,t={}){return this.isValid?xe.create(this.s.loc.clone(t),e).formatInterval(this):cr}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:cr}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:cr}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:cr}toFormat(e,{separator:t=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:cr}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):te.invalid(this.invalidReason)}mapEndpoints(e){return be.fromDateTimes(e(this.s),e(this.e))}}class ps{static{o(this,"Info")}static hasDST(e=ye.defaultZone){const t=z.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return wt.isValidZone(e)}static normalizeZone(e){return Rt(e,ye.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||ne.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||ne.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||ne.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:s=null,locObj:n=null,outputCalendar:i="gregory"}={}){return(n||ne.create(t,s,i)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:n=null,outputCalendar:i="gregory"}={}){return(n||ne.create(t,s,i)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:s=null,locObj:n=null}={}){return(n||ne.create(t,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:n=null}={}){return(n||ne.create(t,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ne.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return ne.create(t,null,"gregory").eras(e)}static features(){return{relative:ra(),localeWeek:sa()}}}function Ia(r,e){const t=o(n=>n.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),"utcDayStart"),s=t(e)-t(r);return Math.floor(te.fromMillis(s).as("days"))}o(Ia,"dayDiff");function Nd(r,e,t){const s=[["years",(l,h)=>h.year-l.year],["quarters",(l,h)=>h.quarter-l.quarter+(h.year-l.year)*4],["months",(l,h)=>h.month-l.month+(h.year-l.year)*12],["weeks",(l,h)=>{const u=Ia(l,h);return(u-u%7)/7}],["days",Ia]],n={},i=r;let c,a;for(const[l,h]of s)t.indexOf(l)>=0&&(c=l,n[l]=h(r,e),a=i.plus(n),a>e?(n[l]--,r=i.plus(n),r>e&&(a=r,n[l]--,r=i.plus(n))):r=a);return[r,n,a,c]}o(Nd,"highOrderDiffs");function Dd(r,e,t,s){let[n,i,c,a]=Nd(r,e,t);const l=e-n,h=t.filter(p=>["hours","minutes","seconds","milliseconds"].indexOf(p)>=0);h.length===0&&(c<e&&(c=n.plus({[a]:1})),c!==n&&(i[a]=(i[a]||0)+l/(c-n)));const u=te.fromObject(i,s);return h.length>0?te.fromMillis(l,s).shiftTo(...h).plus(u):u}o(Dd,"diff");const Ld="missing Intl.DateTimeFormat.formatToParts support";function se(r,e=t=>t){return{regex:r,deser:o(([t])=>e(Eh(t)),"deser")}}o(se,"intUnit");const Ra="[ \xA0]",Ca=new RegExp(Ra,"g");function Pd(r){return r.replace(/\./g,"\\.?").replace(Ca,Ra)}o(Pd,"fixListRegex");function Na(r){return r.replace(/\./g,"").replace(Ca," ").toLowerCase()}o(Na,"stripInsensitivities");function lt(r,e){return r===null?null:{regex:RegExp(r.map(Pd).join("|")),deser:o(([t])=>r.findIndex(s=>Na(t)===Na(s))+e,"deser")}}o(lt,"oneOf");function Da(r,e){return{regex:r,deser:o(([,t,s])=>hs(t,s),"deser"),groups:e}}o(Da,"offset");function gs(r){return{regex:r,deser:o(([e])=>e,"deser")}}o(gs,"simple");function Md(r){return r.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}o(Md,"escapeToken");function Fd(r,e){const t=at(e),s=at(e,"{2}"),n=at(e,"{3}"),i=at(e,"{4}"),c=at(e,"{6}"),a=at(e,"{1,2}"),l=at(e,"{1,3}"),h=at(e,"{1,6}"),u=at(e,"{1,9}"),p=at(e,"{2,4}"),g=at(e,"{4,6}"),f=o(b=>({regex:RegExp(Md(b.val)),deser:o(([m])=>m,"deser"),literal:!0}),"literal"),y=o(b=>{if(r.literal)return f(b);switch(b.val){case"G":return lt(e.eras("short"),0);case"GG":return lt(e.eras("long"),0);case"y":return se(h);case"yy":return se(p,kn);case"yyyy":return se(i);case"yyyyy":return se(g);case"yyyyyy":return se(c);case"M":return se(a);case"MM":return se(s);case"MMM":return lt(e.months("short",!0),1);case"MMMM":return lt(e.months("long",!0),1);case"L":return se(a);case"LL":return se(s);case"LLL":return lt(e.months("short",!1),1);case"LLLL":return lt(e.months("long",!1),1);case"d":return se(a);case"dd":return se(s);case"o":return se(l);case"ooo":return se(n);case"HH":return se(s);case"H":return se(a);case"hh":return se(s);case"h":return se(a);case"mm":return se(s);case"m":return se(a);case"q":return se(a);case"qq":return se(s);case"s":return se(a);case"ss":return se(s);case"S":return se(l);case"SSS":return se(n);case"u":return gs(u);case"uu":return gs(a);case"uuu":return se(t);case"a":return lt(e.meridiems(),0);case"kkkk":return se(i);case"kk":return se(p,kn);case"W":return se(a);case"WW":return se(s);case"E":case"c":return se(t);case"EEE":return lt(e.weekdays("short",!1),1);case"EEEE":return lt(e.weekdays("long",!1),1);case"ccc":return lt(e.weekdays("short",!0),1);case"cccc":return lt(e.weekdays("long",!0),1);case"Z":case"ZZ":return Da(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return Da(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return gs(/[a-z_+-/]{1,256}?/i);case" ":return gs(/[^\S\n\r]/);default:return f(b)}},"unitate")(r)||{invalidReason:Ld};return y.token=r,y}o(Fd,"unitForToken");const xd={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function $d(r,e,t){const{type:s,value:n}=r;if(s==="literal"){const l=/^\s+$/.test(n);return{literal:!l,val:l?" ":n}}const i=e[s];let c=s;s==="hour"&&(e.hour12!=null?c=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?c="hour12":c="hour24":c=t.hour12?"hour12":"hour24");let a=xd[c];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}o($d,"tokenForPart");function jd(r){return[`^${r.map(t=>t.regex).reduce((t,s)=>`${t}(${s.source})`,"")}$`,r]}o(jd,"buildRegex");function Bd(r,e,t){const s=r.match(e);if(s){const n={};let i=1;for(const c in t)if(er(t,c)){const a=t[c],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(n[a.token.val[0]]=a.deser(s.slice(i,i+l))),i+=l}return[s,n]}else return[s,{}]}o(Bd,"match");function Ud(r){const e=o(i=>{switch(i){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},"toField");let t=null,s;return Z(r.z)||(t=wt.create(r.z)),Z(r.Z)||(t||(t=new Ve(r.Z)),s=r.Z),Z(r.q)||(r.M=(r.q-1)*3+1),Z(r.h)||(r.h<12&&r.a===1?r.h+=12:r.h===12&&r.a===0&&(r.h=0)),r.G===0&&r.y&&(r.y=-r.y),Z(r.u)||(r.S=Tn(r.u)),[Object.keys(r).reduce((i,c)=>{const a=e(c);return a&&(i[a]=r[c]),i},{}),t,s]}o(Ud,"dateTimeFromMatches");let Nn=null;function Vd(){return Nn||(Nn=z.fromMillis(1555555555555)),Nn}o(Vd,"getDummyDateTime");function qd(r,e){if(r.literal)return r;const t=xe.macroTokenToFormatOpts(r.val),s=Fa(t,e);return s==null||s.includes(void 0)?r:s}o(qd,"maybeExpandMacroToken");function La(r,e){return Array.prototype.concat(...r.map(t=>qd(t,e)))}o(La,"expandMacroTokens");class Pa{static{o(this,"TokenParser")}constructor(e,t){if(this.locale=e,this.format=t,this.tokens=La(xe.parseFormat(t),e),this.units=this.tokens.map(s=>Fd(s,e)),this.disqualifyingUnit=this.units.find(s=>s.invalidReason),!this.disqualifyingUnit){const[s,n]=jd(this.units);this.regex=RegExp(s,"i"),this.handlers=n}}explainFromTokens(e){if(this.isValid){const[t,s]=Bd(e,this.regex,this.handlers),[n,i,c]=s?Ud(s):[null,null,void 0];if(er(s,"a")&&er(s,"H"))throw new Qt("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:t,matches:s,result:n,zone:i,specificOffset:c}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function Ma(r,e,t){return new Pa(r,t).explainFromTokens(e)}o(Ma,"explainFromTokens");function Hd(r,e,t){const{result:s,zone:n,specificOffset:i,invalidReason:c}=Ma(r,e,t);return[s,n,i,c]}o(Hd,"parseFromTokens");function Fa(r,e){if(!r)return null;const s=xe.create(e,r).dtFormatter(Vd()),n=s.formatToParts(),i=s.resolvedOptions();return n.map(c=>$d(c,r,i))}o(Fa,"formatOptsToTokens");const Dn="Invalid DateTime",xa=864e13;function Dr(r){return new ct("unsupported zone",`the zone "${r.name}" is not supported`)}o(Dr,"unsupportedZone");function Ln(r){return r.weekData===null&&(r.weekData=as(r.c)),r.weekData}o(Ln,"possiblyCachedWeekData");function Pn(r){return r.localWeekData===null&&(r.localWeekData=as(r.c,r.loc.getMinDaysInFirstWeek(),r.loc.getStartOfWeek())),r.localWeekData}o(Pn,"possiblyCachedLocalWeekData");function Vt(r,e){const t={ts:r.ts,zone:r.zone,c:r.c,o:r.o,loc:r.loc,invalid:r.invalid};return new z({...t,...e,old:t})}o(Vt,"clone");function $a(r,e,t){let s=r-e*60*1e3;const n=t.offset(s);if(e===n)return[s,e];s-=(n-e)*60*1e3;const i=t.offset(s);return n===i?[s,n]:[r-Math.min(n,i)*60*1e3,Math.max(n,i)]}o($a,"fixOffset");function ms(r,e){r+=e*60*1e3;const t=new Date(r);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}o(ms,"tsToObj");function ys(r,e,t){return $a(us(r),e,t)}o(ys,"objToTS");function ja(r,e){const t=r.o,s=r.c.year+Math.trunc(e.years),n=r.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...r.c,year:s,month:n,day:Math.min(r.c.day,ls(s,n))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},c=te.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=us(i);let[l,h]=$a(a,t,r.zone);return c!==0&&(l+=c,h=r.zone.offset(l)),{ts:l,o:h}}o(ja,"adjustTime");function lr(r,e,t,s,n,i){const{setZone:c,zone:a}=t;if(r&&Object.keys(r).length!==0||e){const l=e||a,h=z.fromObject(r,{...t,zone:l,specificOffset:i});return c?h:h.setZone(a)}else return z.invalid(new ct("unparsable",`the input "${n}" can't be parsed as ${s}`))}o(lr,"parseDataToDateTime");function bs(r,e,t=!0){return r.isValid?xe.create(ne.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(r,e):null}o(bs,"toTechFormat");function Mn(r,e,t){const s=r.c.year>9999||r.c.year<0;let n="";if(s&&r.c.year>=0&&(n+="+"),n+=Oe(r.c.year,s?6:4),t==="year")return n;if(e){if(n+="-",n+=Oe(r.c.month),t==="month")return n;n+="-"}else if(n+=Oe(r.c.month),t==="month")return n;return n+=Oe(r.c.day),n}o(Mn,"toISODate");function Ba(r,e,t,s,n,i,c){let a=!t||r.c.millisecond!==0||r.c.second!==0,l="";switch(c){case"day":case"month":case"year":break;default:if(l+=Oe(r.c.hour),c==="hour")break;if(e){if(l+=":",l+=Oe(r.c.minute),c==="minute")break;a&&(l+=":",l+=Oe(r.c.second))}else{if(l+=Oe(r.c.minute),c==="minute")break;a&&(l+=Oe(r.c.second))}if(c==="second")break;a&&(!s||r.c.millisecond!==0)&&(l+=".",l+=Oe(r.c.millisecond,3))}return n&&(r.isOffsetFixed&&r.offset===0&&!i?l+="Z":r.o<0?(l+="-",l+=Oe(Math.trunc(-r.o/60)),l+=":",l+=Oe(Math.trunc(-r.o%60))):(l+="+",l+=Oe(Math.trunc(r.o/60)),l+=":",l+=Oe(Math.trunc(r.o%60)))),i&&(l+="["+r.zone.ianaName+"]"),l}o(Ba,"toISOTime");const Ua={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Wd={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},zd={ordinal:1,hour:0,minute:0,second:0,millisecond:0},_s=["year","month","day","hour","minute","second","millisecond"],Jd=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Kd=["year","ordinal","hour","minute","second","millisecond"];function ws(r){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[r.toLowerCase()];if(!e)throw new go(r);return e}o(ws,"normalizeUnit");function Va(r){switch(r.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return ws(r)}}o(Va,"normalizeUnitWithLocalWeeks");function Gd(r){if(Lr===void 0&&(Lr=ye.now()),r.type!=="iana")return r.offset(Lr);const e=r.name;let t=Fn.get(e);return t===void 0&&(t=r.offset(Lr),Fn.set(e,t)),t}o(Gd,"guessOffsetForZone");function qa(r,e){const t=Rt(e.zone,ye.defaultZone);if(!t.isValid)return z.invalid(Dr(t));const s=ne.fromObject(e);let n,i;if(Z(r.year))n=ye.now();else{for(const l of _s)Z(r[l])&&(r[l]=Ua[l]);const c=ea(r)||ta(r);if(c)return z.invalid(c);const a=Gd(t);[n,i]=ys(r,a,t)}return new z({ts:n,zone:t,loc:s,o:i})}o(qa,"quickDT");function Ha(r,e,t){const s=Z(t.round)?!0:t.round,n=Z(t.rounding)?"trunc":t.rounding,i=o((a,l)=>(a=An(a,s||t.calendary?0:2,t.calendary?"round":n),e.loc.clone(t).relFormatter(t).format(a,l)),"format"),c=o(a=>t.calendary?e.hasSame(r,a)?0:e.startOf(a).diff(r.startOf(a),a).get(a):e.diff(r,a).get(a),"differ");if(t.unit)return i(c(t.unit),t.unit);for(const a of t.units){const l=c(a);if(Math.abs(l)>=1)return i(l,a)}return i(r>e?-0:0,t.units[t.units.length-1])}o(Ha,"diffRelative");function Wa(r){let e={},t;return r.length>0&&typeof r[r.length-1]=="object"?(e=r[r.length-1],t=Array.from(r).slice(0,r.length-1)):t=Array.from(r),[e,t]}o(Wa,"lastOpts");let Lr;const Fn=new Map;class z{static{o(this,"DateTime")}constructor(e){const t=e.zone||ye.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new ct("invalid input"):null)||(t.isValid?null:Dr(t));this.ts=Z(e.ts)?ye.now():e.ts;let n=null,i=null;if(!s)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[n,i]=[e.old.c,e.old.o];else{const a=Ct(e.o)&&!e.old?e.o:t.offset(this.ts);n=ms(this.ts,a),s=Number.isNaN(n.year)?new ct("invalid input"):null,n=s?null:n,i=s?null:a}this._zone=t,this.loc=e.loc||ne.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=n,this.o=i,this.isLuxonDateTime=!0}static now(){return new z({})}static local(){const[e,t]=Wa(arguments),[s,n,i,c,a,l,h]=t;return qa({year:s,month:n,day:i,hour:c,minute:a,second:l,millisecond:h},e)}static utc(){const[e,t]=Wa(arguments),[s,n,i,c,a,l,h]=t;return e.zone=Ve.utcInstance,qa({year:s,month:n,day:i,hour:c,minute:a,second:l,millisecond:h},e)}static fromJSDate(e,t={}){const s=Ih(e)?e.valueOf():NaN;if(Number.isNaN(s))return z.invalid("invalid input");const n=Rt(t.zone,ye.defaultZone);return n.isValid?new z({ts:s,zone:n,loc:ne.fromObject(t)}):z.invalid(Dr(n))}static fromMillis(e,t={}){if(Ct(e))return e<-xa||e>xa?z.invalid("Timestamp out of range"):new z({ts:e,zone:Rt(t.zone,ye.defaultZone),loc:ne.fromObject(t)});throw new Fe(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(Ct(e))return new z({ts:e*1e3,zone:Rt(t.zone,ye.defaultZone),loc:ne.fromObject(t)});throw new Fe("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};const s=Rt(t.zone,ye.defaultZone);if(!s.isValid)return z.invalid(Dr(s));const n=ne.fromObject(t),i=ds(e,Va),{minDaysInFirstWeek:c,startOfWeek:a}=Qo(i,n),l=ye.now(),h=Z(t.specificOffset)?s.offset(l):t.specificOffset,u=!Z(i.ordinal),p=!Z(i.year),g=!Z(i.month)||!Z(i.day),f=p||g,d=i.weekYear||i.weekNumber;if((f||u)&&d)throw new Qt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(g&&u)throw new Qt("Can't mix ordinal dates with month/day");const y=d||i.weekday&&!f;let b,m,_=ms(l,h);y?(b=Jd,m=Wd,_=as(_,c,a)):u?(b=Kd,m=zd,_=En(_)):(b=_s,m=Ua);let w=!1;for(const C of b){const B=i[C];Z(B)?w?i[C]=m[C]:i[C]=_[C]:w=!0}const S=y?Th(i,c,a):u?Ah(i):ea(i),T=S||ta(i);if(T)return z.invalid(T);const v=y?Zo(i,c,a):u?Xo(i):i,[A,O]=ys(v,h,s),k=new z({ts:A,zone:s,o:O,loc:n});return i.weekday&&f&&e.weekday!==k.weekday?z.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${k.toISO()}`):k.isValid?k:z.invalid(k.invalid)}static fromISO(e,t={}){const[s,n]=yd(e);return lr(s,n,t,"ISO 8601",e)}static fromRFC2822(e,t={}){const[s,n]=bd(e);return lr(s,n,t,"RFC 2822",e)}static fromHTTP(e,t={}){const[s,n]=_d(e);return lr(s,n,t,"HTTP",t)}static fromFormat(e,t,s={}){if(Z(e)||Z(t))throw new Fe("fromFormat requires an input string and a format");const{locale:n=null,numberingSystem:i=null}=s,c=ne.fromOpts({locale:n,numberingSystem:i,defaultToEN:!0}),[a,l,h,u]=Hd(c,e,t);return u?z.invalid(u):lr(a,l,s,`format ${t}`,e,h)}static fromString(e,t,s={}){return z.fromFormat(e,t,s)}static fromSQL(e,t={}){const[s,n]=Ad(e);return lr(s,n,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new Fe("need to specify a reason the DateTime is invalid");const s=e instanceof ct?e:new ct(e,t);if(ye.throwOnInvalid)throw new Qu(s);return new z({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){const s=Fa(e,ne.fromObject(t));return s?s.map(n=>n?n.val:null).join(""):null}static expandFormat(e,t={}){return La(xe.parseFormat(e),ne.fromObject(t)).map(n=>n.val).join("")}static resetCache(){Lr=void 0,Fn.clear()}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?Ln(this).weekYear:NaN}get weekNumber(){return this.isValid?Ln(this).weekNumber:NaN}get weekday(){return this.isValid?Ln(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?Pn(this).weekday:NaN}get localWeekNumber(){return this.isValid?Pn(this).weekNumber:NaN}get localWeekYear(){return this.isValid?Pn(this).weekYear:NaN}get ordinal(){return this.isValid?En(this.c).ordinal:NaN}get monthShort(){return this.isValid?ps.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?ps.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?ps.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?ps.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const e=864e5,t=6e4,s=us(this.c),n=this.zone.offset(s-e),i=this.zone.offset(s+e),c=this.zone.offset(s-n*t),a=this.zone.offset(s-i*t);if(c===a)return[this];const l=s-c*t,h=s-a*t,u=ms(l,c),p=ms(h,a);return u.hour===p.hour&&u.minute===p.minute&&u.second===p.second&&u.millisecond===p.millisecond?[Vt(this,{ts:l}),Vt(this,{ts:h})]:[this]}get isInLeapYear(){return kr(this.year)}get daysInMonth(){return ls(this.year,this.month)}get daysInYear(){return this.isValid?tr(this.year):NaN}get weeksInWeekYear(){return this.isValid?Ir(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Ir(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:t,numberingSystem:s,calendar:n}=xe.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:s,outputCalendar:n}}toUTC(e=0,t={}){return this.setZone(Ve.instance(e),t)}toLocal(){return this.setZone(ye.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:s=!1}={}){if(e=Rt(e,ye.defaultZone),e.equals(this.zone))return this;if(e.isValid){let n=this.ts;if(t||s){const i=e.offset(this.ts),c=this.toObject();[n]=ys(c,i,e)}return Vt(this,{ts:n,zone:e})}else return z.invalid(Dr(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:s}={}){const n=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:s});return Vt(this,{loc:n})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const t=ds(e,Va),{minDaysInFirstWeek:s,startOfWeek:n}=Qo(t,this.loc),i=!Z(t.weekYear)||!Z(t.weekNumber)||!Z(t.weekday),c=!Z(t.ordinal),a=!Z(t.year),l=!Z(t.month)||!Z(t.day),h=a||l,u=t.weekYear||t.weekNumber;if((h||c)&&u)throw new Qt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&c)throw new Qt("Can't mix ordinal dates with month/day");let p;i?p=Zo({...as(this.c,s,n),...t},s,n):Z(t.ordinal)?(p={...this.toObject(),...t},Z(t.day)&&(p.day=Math.min(ls(p.year,p.month),p.day))):p=Xo({...En(this.c),...t});const[g,f]=ys(p,this.o,this.zone);return Vt(this,{ts:g,o:f})}plus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e);return Vt(this,ja(this,t))}minus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e).negate();return Vt(this,ja(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;const s={},n=te.normalizeUnit(e);switch(n){case"years":s.month=1;case"quarters":case"months":s.day=1;case"weeks":case"days":s.hour=0;case"hours":s.minute=0;case"minutes":s.second=0;case"seconds":s.millisecond=0;break}if(n==="weeks")if(t){const i=this.loc.getStartOfWeek(),{weekday:c}=this;c<i&&(s.weekNumber=this.weekNumber-1),s.weekday=i}else s.weekday=1;if(n==="quarters"){const i=Math.ceil(this.month/3);s.month=(i-1)*3+1}return this.set(s)}endOf(e,t){return this.isValid?this.plus({[e]:1}).startOf(e,t).minus(1):this}toFormat(e,t={}){return this.isValid?xe.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):Dn}toLocaleString(e=ns,t={}){return this.isValid?xe.create(this.loc.clone(t),e).formatDateTime(this):Dn}toLocaleParts(e={}){return this.isValid?xe.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:s=!1,includeOffset:n=!0,extendedZone:i=!1,precision:c="milliseconds"}={}){if(!this.isValid)return null;c=ws(c);const a=e==="extended";let l=Mn(this,a,c);return _s.indexOf(c)>=3&&(l+="T"),l+=Ba(this,a,t,s,n,i,c),l}toISODate({format:e="extended",precision:t="day"}={}){return this.isValid?Mn(this,e==="extended",ws(t)):null}toISOWeekDate(){return bs(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:s=!0,includePrefix:n=!1,extendedZone:i=!1,format:c="extended",precision:a="milliseconds"}={}){return this.isValid?(a=ws(a),(n&&_s.indexOf(a)>=3?"T":"")+Ba(this,c==="extended",t,e,s,i,a)):null}toRFC2822(){return bs(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return bs(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Mn(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:s=!0}={}){let n="HH:mm:ss.SSS";return(t||e)&&(s&&(n+=" "),t?n+="z":e&&(n+="ZZ")),bs(this,n,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():Dn}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};const t={...this.c};return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t="milliseconds",s={}){if(!this.isValid||!e.isValid)return te.invalid("created by diffing an invalid DateTime");const n={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=Rh(t).map(te.normalizeUnit),c=e.valueOf()>this.valueOf(),a=c?this:e,l=c?e:this,h=Dd(a,l,i,n);return c?h.negate():h}diffNow(e="milliseconds",t={}){return this.diff(z.now(),e,t)}until(e){return this.isValid?be.fromDateTimes(this,e):this}hasSame(e,t,s){if(!this.isValid)return!1;const n=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(t,s)<=n&&n<=i.endOf(t,s)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const t=e.base||z.fromObject({},{zone:this.zone}),s=e.padding?this<t?-e.padding:e.padding:0;let n=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(n=e.unit,i=void 0),Ha(t,this.plus(s),{...e,numeric:"always",units:n,unit:i})}toRelativeCalendar(e={}){return this.isValid?Ha(e.base||z.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(z.isDateTime))throw new Fe("min requires all arguments be DateTimes");return na(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(z.isDateTime))throw new Fe("max requires all arguments be DateTimes");return na(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,s={}){const{locale:n=null,numberingSystem:i=null}=s,c=ne.fromOpts({locale:n,numberingSystem:i,defaultToEN:!0});return Ma(c,e,t)}static fromStringExplain(e,t,s={}){return z.fromFormatExplain(e,t,s)}static buildFormatParser(e,t={}){const{locale:s=null,numberingSystem:n=null}=t,i=ne.fromOpts({locale:s,numberingSystem:n,defaultToEN:!0});return new Pa(i,e)}static fromFormatParser(e,t,s={}){if(Z(e)||Z(t))throw new Fe("fromFormatParser requires an input string and a format parser");const{locale:n=null,numberingSystem:i=null}=s,c=ne.fromOpts({locale:n,numberingSystem:i,defaultToEN:!0});if(!c.equals(t.locale))throw new Fe(`fromFormatParser called with a locale of ${c}, but the format parser was created for ${t.locale}`);const{result:a,zone:l,specificOffset:h,invalidReason:u}=t.explainFromTokens(e);return u?z.invalid(u):lr(a,l,s,`format ${t.format}`,e,h)}static get DATE_SHORT(){return ns}static get DATE_MED(){return mo}static get DATE_MED_WITH_WEEKDAY(){return rh}static get DATE_FULL(){return yo}static get DATE_HUGE(){return bo}static get TIME_SIMPLE(){return _o}static get TIME_WITH_SECONDS(){return wo}static get TIME_WITH_SHORT_OFFSET(){return So}static get TIME_WITH_LONG_OFFSET(){return vo}static get TIME_24_SIMPLE(){return Eo}static get TIME_24_WITH_SECONDS(){return Oo}static get TIME_24_WITH_SHORT_OFFSET(){return To}static get TIME_24_WITH_LONG_OFFSET(){return Ao}static get DATETIME_SHORT(){return ko}static get DATETIME_SHORT_WITH_SECONDS(){return Io}static get DATETIME_MED(){return Ro}static get DATETIME_MED_WITH_SECONDS(){return Co}static get DATETIME_MED_WITH_WEEKDAY(){return sh}static get DATETIME_FULL(){return No}static get DATETIME_FULL_WITH_SECONDS(){return Do}static get DATETIME_HUGE(){return Lo}static get DATETIME_HUGE_WITH_SECONDS(){return Po}}function Pr(r){if(z.isDateTime(r))return r;if(r&&r.valueOf&&Ct(r.valueOf()))return z.fromJSDate(r);if(r&&typeof r=="object")return z.fromObject(r);throw new Fe(`Unknown datetime argument: ${r}, of type ${typeof r}`)}o(Pr,"friendlyDateTime");var Yd=Object.defineProperty,Zd=o((r,e)=>Yd(r,"name",{value:e,configurable:!0}),"o$v");class xn{static{o(this,"AbstractFormatter")}static{Zd(this,"AbstractFormatter")}dateFormat;constructor(e="YYYY-MM-DD HH:mm:ss"){this.dateFormat=e}_formatTimestamp(e){const t=z.fromJSDate(e);return Math.floor(t.toSeconds()).toFixed(0)}_formatDate(e){return z.fromJSDate(e).toFormat(this.dateFormat.replace(/YYYY/g,"yyyy").replace(/YY/g,"yy").replace(/DD/g,"dd").replace(/D/g,"d"))}}var Xd=Object.defineProperty,Qd=o((r,e)=>Xd(r,"name",{value:e,configurable:!0}),"m$d");class ef extends xn{static{o(this,"JsonFormatter")}static{Qd(this,"JsonFormatter")}constructor(e="YYYY-MM-DD HH:mm:ss"){super(e)}format(e){return JSON.stringify({channel:e.channel,levelName:e.levelName,message:e.message,context:e.context,extra:e.extra,timestamp:this._formatTimestamp(e.timestamp),date:this._formatDate(e.timestamp)})}}var tf=Object.defineProperty,rf=o((r,e)=>tf(r,"name",{value:e,configurable:!0}),"s$D");class Ss extends xn{static{o(this,"LineFormatter")}static{rf(this,"LineFormatter")}formatString;constructor(e="[{channel}] {levelName}: {message} {context} {extra} {date}",t="YYYY-MM-DD HH:mm:ss"){super(t),this.formatString=e}format(e){let t=this.formatString;const s={"{channel}":e.channel,"{levelName}":e.levelName,"{message}":e.message,"{context}":JSON.stringify(e.context),"{extra}":JSON.stringify(e.extra),"{timestamp}":this._formatTimestamp(e.timestamp),"{date}":this._formatDate(e.timestamp)};for(const[n,i]of Object.entries(s))t=t.replace(n,i);return t}}var sf=Object.defineProperty,nf=o((r,e)=>sf(r,"name",{value:e,configurable:!0}),"n$i");class za extends xn{static{o(this,"TelegramFormatter")}static{nf(this,"TelegramFormatter")}useHtml;maxMessageLength;constructor(e=!0,t="YYYY-MM-DD HH:mm:ss",s=4096){super(t),this.useHtml=e,this.maxMessageLength=s}format(e){let t=this._formatBaseMessage(e);const s=this._formatAdditionalInfo(e);return s&&(t+=`
${s}`),t.length>this.maxMessageLength&&(t=t.substring(0,this.maxMessageLength-3)+"..."),t}_formatBaseMessage(e){const t=this._formatDate(e.timestamp),s=e.levelName;return this.useHtml?`<b>${s}</b> | <code>${e.channel}</code>
<i>Time:</i> ${t}
<i>Message:</i>
${e.message}`:`*${s}* \`${e.channel}\`
_Time:_ \`${t}\`
_Message:_
${e.message}`}_formatAdditionalInfo(e){const t=[];if(e.context&&Object.keys(e.context).length>0){const s=JSON.stringify(e.context,null,2);this.useHtml?t.push(`<i>Context:</i>
<pre><code class="language-json">${this._escapeHtml(s)}</code></pre>`):t.push(`_Context:_
\`\`\`json
${s}
\`\`\``)}if(e.extra&&Object.keys(e.extra).length>0){const s=JSON.stringify(e.extra,null,2);this.useHtml?t.push(`<i>Extra:</i>
<pre><code class="language-json">${this._escapeHtml(s)}</code></pre>`):t.push(`_Extra:_
\`\`\`json
${s}
\`\`\``)}return t.join(`
`)}_escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}_escapeMarkdownV2(e){return e.replace(/_/g,"\\_").replace(/\*/g,"\\*").replace(/\[/g,"\\[").replace(/\]/g,"\\]").replace(/\(/g,"\\(").replace(/\)/g,"\\)").replace(/~/g,"\\~").replace(/`/g,"\\`").replace(/>/g,"\\>").replace(/#/g,"\\#").replace(/\+/g,"\\+").replace(/-/g,"\\-").replace(/=/g,"\\=").replace(/\|/g,"\\|").replace(/\{/g,"\\{").replace(/\}/g,"\\}").replace(/\./g,"\\.").replace(/!/g,"\\!")}setUseHtml(e){return this.useHtml=e,this}setMaxMessageLength(e){return this.maxMessageLength=e,this}}var of=Object.defineProperty,af=o((r,e)=>of(r,"name",{value:e,configurable:!0}),"e$e");const cf=af(r=>(r.extra.pid="?",typeof process<"u"&&process.pid&&(r.extra.pid=process.pid),r),"pidProcessor");var lf=Object.defineProperty,uf=o((r,e)=>lf(r,"name",{value:e,configurable:!0}),"o$u");const hf=uf(r=>(r.extra.memoryUsage="?",typeof process<"u"&&process.memoryUsage&&(r.extra.memoryUsage=Math.round(process.memoryUsage().heapUsed/1024/1024)+"MB"),r),"memoryUsageProcessor");var df=Object.defineProperty,ff=o((r,e)=>df(r,"name",{value:e,configurable:!0}),"o$t");class ur{static{o(this,"AbstractHandler")}static{ff(this,"AbstractHandler")}level;formatter=null;bubble=!0;constructor(e=K.DEBUG,t){this.level=e,t!==void 0&&(this.bubble=t)}isHandling(e){return e>=this.level}shouldBubble(){return this.bubble}setFormatter(e){this.formatter=e}getFormatter(){return this.formatter}}var pf=Object.defineProperty,gf=o((r,e)=>pf(r,"name",{value:e,configurable:!0}),"c$g");class Ja extends ur{static{o(this,"ConsoleHandler")}static{gf(this,"ConsoleHandler")}_styles=new Map;_useStyles;constructor(e=K.DEBUG,t){const s={useStyles:!0,...t};super(e,s.bubble),this._useStyles=s.useStyles,this._initStyles(),this.setFormatter(new Ss)}_initStyles(){const e="color: _color_; background: _bg_; padding: 2px 6px; border-radius: 3px; font-size: 11px;";this._styles.set(K.DEBUG,["%cDEBUG",e.replace("_color_","#666666").replace("_bg_","#F0F0F0")]),this._styles.set(K.INFO,["%cINFO",e.replace("_color_","white").replace("_bg_","#2196F3")]),this._styles.set(K.NOTICE,["%cNOTICE",e.replace("_color_","white").replace("_bg_","#213BF3")]),this._styles.set(K.WARNING,["%cWARN",e.replace("_color_","white").replace("_bg_","#FF9800")]),this._styles.set(K.ERROR,["%cERROR",e.replace("_color_","white").replace("_bg_","#F44336")]),this._styles.set(K.CRITICAL,["%cCRITICAL",e.replace("_color_","white").replace("_bg_","#9C27B0")])}async handle(e){const t=this.getFormatter().format(e);let s=this._getConsoleMethod(e.level);e.context.needTrace===!0&&(s="trace");const n=[];if(this._useStyles&&this._styles.has(e.level)){const i=this._styles.get(e.level);n.push(i[0],i[1])}return n.push(t),console[s](...n.filter(Boolean)),!0}_getConsoleMethod(e){switch(e){case K.INFO:case K.NOTICE:return"info";case K.WARNING:return"warn";case K.ERROR:case K.CRITICAL:case K.ALERT:case K.EMERGENCY:return"error";default:return"log"}}}var mf=Object.defineProperty,yf=o((r,e)=>mf(r,"name",{value:e,configurable:!0}),"a$r");class $n extends Ja{static{o(this,"ConsoleV2Handler")}static{yf(this,"ConsoleV2Handler")}constructor(e=K.DEBUG,t){super(e,t),this.setFormatter(new Ss("[{channel}]: {message}"))}async handle(e){const t=this.getFormatter().format(e);let s=this._getConsoleMethod(e.level);e.context.needTrace===!0&&(s="trace");const n=e.context&&Object.keys(e.context).length>0?e.context:void 0,i=e.extra&&Object.keys(e.extra).length>0?e.extra:void 0,c=[];if(this._useStyles&&this._styles.has(e.level)){const a=this._styles.get(e.level);c.push(a[0],a[1])}return c.push(t),c.push(n),c.push(i),console[s](...c.filter(Boolean)),!0}}var bf=Object.defineProperty,_f=o((r,e)=>bf(r,"name",{value:e,configurable:!0}),"t$c");class wf extends ur{static{o(this,"MemoryHandler")}static{_f(this,"MemoryHandler")}records=[];limit;constructor(e=K.DEBUG,t){const s={bubble:!0,limit:1e3,...t};super(e,s.bubble),this.limit=s.limit}async handle(e){return this.records.push(e),this.records.length>this.limit&&this.records.shift(),!0}getRecords(){return[...this.records]}clear(){this.records=[]}}var Sf=Object.defineProperty,vf=o((r,e)=>Sf(r,"name",{value:e,configurable:!0}),"s$z");class Ef extends ur{static{o(this,"StreamHandler")}static{vf(this,"StreamHandler")}stream;constructor(e=K.DEBUG,t){const s={bubble:!0,...t};super(e,s.bubble),this.stream=s.stream,this.setFormatter(new Ss)}async handle(e){try{const t=this.getFormatter().format(e)+`
`;this.stream.write(t)}catch(t){return console.error(`StreamHandler write error: ${t}`),!1}return!0}async close(){if(typeof this.stream.end=="function")return new Promise((e,t)=>{this.stream.end(s=>{s?t(s):e()})})}}var Of=Object.defineProperty,Tf=o((r,e)=>Of(r,"name",{value:e,configurable:!0}),"o$s");class Af extends ur{static{o(this,"ConsolaAdapter")}static{Tf(this,"ConsolaAdapter")}consolaInstance;constructor(e=K.DEBUG,t){const s={bubble:!0,...t};super(e,s.bubble),this.consolaInstance=s.consolaInstance}setFormatter(e){}getFormatter(){return null}async handle(e){const t=`[${e.channel}] ${e.levelName}: ${e.message}`,s={...e.context,...e.extra,timestamp:e.timestamp};switch(e.level){case K.DEBUG:this.consolaInstance.log(t,s);break;case K.INFO:this.consolaInstance.info(t,s);break;case K.NOTICE:this.consolaInstance.success(t,s);break;case K.WARNING:this.consolaInstance.warn(t,s);break;case K.ERROR:case K.CRITICAL:case K.ALERT:case K.EMERGENCY:this.consolaInstance.error(t,s);break;default:this.consolaInstance.log(t,s)}return!0}}var kf=Object.defineProperty,If=o((r,e)=>kf(r,"name",{value:e,configurable:!0}),"n$h");class Rf extends ur{static{o(this,"WinstonAdapter")}static{If(this,"WinstonAdapter")}winstonLogger;constructor(e=K.DEBUG,t){const s={bubble:!0,...t};super(e,s.bubble),this.winstonLogger=s.winstonLogger}setFormatter(e){}getFormatter(){return null}async handle(e){const t={DEBUG:"debug",INFO:"info",NOTICE:"notice",WARNING:"warn",ERROR:"error",CRITICAL:"error",ALERT:"error",EMERGENCY:"error"},s=t[e.levelName]||t.INFO;return this.winstonLogger.log({level:s,channel:e.channel,message:e.message,context:e.context,extra:e.extra,timestamp:e.timestamp}),!0}}var Cf=Object.defineProperty,jn=o((r,e)=>Cf(r,"name",{value:e,configurable:!0}),"o$r"),Bn=(r=>(r.UNKNOWN="unknown",r.BROWSE="browser",r.WORKER="worker",r.NODE="node",r))(Bn||{});function Ka(){try{const r=globalThis.WorkerGlobalScope;return typeof r>"u"?!1:globalThis instanceof r}catch{return!1}}o(Ka,"i$n"),jn(Ka,"isWorkerGlobalScope");function vs(){return typeof window<"u"&&typeof window.document<"u"?"browser":typeof process<"u"&&process.versions&&process.versions.node?"node":Ka()?"worker":"unknown"}o(vs,"getEnvironment"),jn(vs,"getEnvironment");function hr(){const r=vs();return r==="browser"||r==="worker"}o(hr,"isBrowserLikeRuntime"),jn(hr,"isBrowserLikeRuntime");var Nf=Object.defineProperty,Df=o((r,e)=>Nf(r,"name",{value:e,configurable:!0}),"s$x");class Lf extends ur{static{o(this,"TelegramHandler")}static{Df(this,"TelegramHandler")}botToken;chatId;parseMode;disableNotification;disableWebPagePreview;environment;isBrowserLike;warnInBrowser;constructor(e=K.ERROR,t){if(super(e,t.bubble),!t.botToken)throw new Error("botToken is required for TelegramHandler");if(!t.chatId)throw new Error("chatId is required for TelegramHandler");this.botToken=t.botToken,this.chatId=t.chatId,this.parseMode=t.parseMode||"HTML",this.disableNotification=t.disableNotification||!1,this.disableWebPagePreview=t.disableWebPagePreview||!0,this.environment=vs(),this.isBrowserLike=hr(),this.warnInBrowser=t.warnInBrowser!==!1,this.setFormatter(new za(this.parseMode==="HTML"))}async handle(e){const t=this.getFormatter();if(!t)return console.error("TelegramHandler: No formatter set"),!1;const s=t.format(e);return this.isBrowserLike?this._handleInBrowser(s,e):this.environment===Bn.NODE?this._handleInNode(s,e):(console.warn("TelegramHandler: Unknown environment, using fallback"),this._handleFallback(s))}async _handleInBrowser(e,t){if(this.warnInBrowser){const s=`\u26A0\uFE0F TelegramHandler: Cannot send logs to Telegram from a browser-like environment.
This would expose your bot token. Consider disabling this handler in browser.
Log message: ${t.message}
If you need to send logs from browser, use a proxy server.`;console.warn(s),console.log("%cTelegram Handler Warning","color: #FF9800; background: #FFF3E0; padding: 8px; border: 1px solid #FFB74D; border-radius: 4px;",s)}return!1}async _handleInNode(e,t){try{const s=`https://api.telegram.org/bot${this.botToken}/sendMessage`,n=JSON.stringify({chat_id:this.chatId,text:e,parse_mode:this.parseMode,disable_notification:this.disableNotification,disable_web_page_preview:this.disableWebPagePreview}),i=await(await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:n})).json();return i.ok?!0:(console.error("TelegramHandler: Failed to send message",i),!1)}catch(s){return console.error("TelegramHandler: Error sending message",s),!1}}async _handleFallback(e){return console.log("TelegramHandler (fallback):",e),!1}updateSettings(e){return e.botToken&&(this.botToken=e.botToken),e.chatId&&(this.chatId=e.chatId),e.parseMode&&(this.parseMode=e.parseMode),e.disableNotification!==void 0&&(this.disableNotification=e.disableNotification),e.disableWebPagePreview!==void 0&&(this.disableWebPagePreview=e.disableWebPagePreview),e.warnInBrowser!==void 0&&(this.warnInBrowser=e.warnInBrowser),this}getEnvironment(){return this.environment}async testConnection(){if(this.isBrowserLike)return console.warn("TelegramHandler: Cannot test connection in a browser-like environment"),!1;try{const e=`https://api.telegram.org/bot${this.botToken}/getMe`;return(await(await fetch(e)).json()).ok===!0}catch(e){return console.error("TelegramHandler: Test connection failed",e),!1}}}var Pf=Object.defineProperty,Mf=o((r,e)=>Pf(r,"name",{value:e,configurable:!0}),"n$g");class Un{static{o(this,"AbstractLogger")}static{Mf(this,"AbstractLogger")}async debug(e,t){return this.log(K.DEBUG,e,t)}async info(e,t){return this.log(K.INFO,e,t)}async notice(e,t){return this.log(K.NOTICE,e,t)}async warning(e,t){return this.log(K.WARNING,e,t)}async error(e,t){return this.log(K.ERROR,e,t)}async critical(e,t){return this.log(K.CRITICAL,e,t)}async alert(e,t){return this.log(K.ALERT,e,t)}async emergency(e,t){return this.log(K.EMERGENCY,e,t)}}var Ff=Object.defineProperty,xf=o((r,e)=>Ff(r,"name",{value:e,configurable:!0}),"r$g");class Mr extends Un{static{o(this,"NullLogger")}static{xf(this,"NullLogger")}static create(){return new Mr}async log(e,t,s){}}var $f=Object.defineProperty,jf=o((r,e)=>$f(r,"name",{value:e,configurable:!0}),"a$p");class Fr extends Un{static{o(this,"Logger")}static{jf(this,"Logger")}channel;handlers=[];processors=[];constructor(e){super(),this.channel=e}static create(e){return new Fr(e)}pushHandler(e){return this.handlers.push(e),this}popHandler(){return this.handlers.pop()||null}setHandlers(e){return this.handlers=e,this}pushProcessor(e){return this.processors.push(e),this}async log(e,t,s){let n={channel:this.channel,level:e,levelName:K[e],message:t,context:s??{},extra:{},timestamp:new Date};for(const i of this.processors)try{n=i(n)}catch(c){this.reportLoggingFailure(i,c)}for(const i of this.handlers)try{if(!i.isHandling(e))continue;if(await i.handle(n)&&!i.shouldBubble())break}catch(c){this.reportLoggingFailure(i,c)}}reportLoggingFailure(e,t){const s=e?.constructor?.name??"processor";console.warn(`[b24jssdk] logger channel "${this.channel}": ${s} failed; the record was skipped. Logging continues through the remaining handlers, and the operation being logged is unaffected.`,t)}}var Bf=Object.defineProperty,Uf=o((r,e)=>Bf(r,"name",{value:e,configurable:!0}),"t$a");class ae{static{o(this,"LoggerFactory")}static{Uf(this,"LoggerFactory")}static createNullLogger(){return Mr.create()}static createForBrowser(e,t=!1){return t?ae.createForBrowserDevelopment(e):ae.createForBrowserProduction(e)}static createForBrowserDevelopment(e,t=K.DEBUG){const s=new Fr(e),n=new $n(t);return s.pushHandler(n),s}static createForBrowserProduction(e,t=K.ERROR){const s=new Fr(e),n=new $n(t);return s.pushHandler(n),s}static async forcedLog(e,t,s,n){if(!(typeof globalThis<"u"&&"vitest"in globalThis)){if(e instanceof Mr)switch(t){case"debug":console.log(s,n);return;case"info":case"notice":console.info(s,n);return;case"warning":console.warn(s,n);return;default:console.error(s,n);return}return e[t](s,n)}}}var Ga=(r=>(r.undefined="undefined",r.any="any",r.integer="integer",r.boolean="boolean",r.double="double",r.date="date",r.datetime="datetime",r.string="string",r.text="text",r.file="file",r.array="array",r.object="object",r.user="user",r.location="location",r.crmCategory="crm_category",r.crmStatus="crm_status",r.crmCurrency="crm_currency",r))(Ga||{}),Vf=Object.defineProperty,qf=o((r,e)=>Vf(r,"name",{value:e,configurable:!0}),"o$p");const Hf=Function.prototype.toString.call(Object);let Wf=class{static{o(this,"y")}static{qf(this,"TypeManager")}getTag(e){return Object.prototype.toString.call(e)}isString(e){return typeof e=="string"||e instanceof String}isStringFilled(e){return this.isString(e)&&e!==""}isFunction(e){return e===null?!1:typeof e=="function"||e instanceof Function}isObject(e){return!!e&&(typeof e=="object"||typeof e=="function")}isObjectLike(e){return!!e&&typeof e=="object"}isPlainObject(e){if(!this.isObjectLike(e)||this.getTag(e)!=="[object Object]")return!1;const t=Object.getPrototypeOf(e);if(t===null)return!0;const s=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof s=="function"&&Function.prototype.toString.call(s)===Hf}isJsonRpcRequest(e){return typeof e=="object"&&e&&"jsonrpc"in e&&this.isStringFilled(e.jsonrpc)&&"method"in e&&this.isStringFilled(e.method)}isJsonRpcResponse(e){return typeof e=="object"&&e&&"jsonrpc"in e&&this.isStringFilled(e.jsonrpc)&&"id"in e&&("result"in e||"error"in e)}isBoolean(e){return e===!0||e===!1}isNumber(e){return typeof e=="number"&&!Number.isNaN(e)}isInteger(e){return Number.isInteger(e)}isFloat(e){return this.isNumber(e)&&!this.isInteger(e)}isNil(e){return e==null}isArray(e){return!this.isNil(e)&&Array.isArray(e)}isArrayFilled(e){return this.isArray(e)&&e.length>0}isArrayLike(e){return!this.isNil(e)&&!this.isFunction(e)&&e.length>-1&&e.length<=Number.MAX_SAFE_INTEGER}isDate(e){return e instanceof Date}isDomNode(e){return this.isObjectLike(e)&&!this.isPlainObject(e)&&"nodeType"in e}isElementNode(e){return this.isDomNode(e)&&e.nodeType===Node.ELEMENT_NODE}isTextNode(e){return this.isDomNode(e)&&e.nodeType===Node.TEXT_NODE}isMap(e){return this.isObjectLike(e)&&this.getTag(e)==="[object Map]"}isSet(e){return this.isObjectLike(e)&&this.getTag(e)==="[object Set]"}isWeakMap(e){return this.isObjectLike(e)&&this.getTag(e)==="[object WeakMap]"}isWeakSet(e){return this.isObjectLike(e)&&this.getTag(e)==="[object WeakSet]"}isPrototype(e){return(typeof(e&&e.constructor)=="function"&&e.constructor.prototype||Object.prototype)===e}isRegExp(e){return this.isObjectLike(e)&&this.getTag(e)==="[object RegExp]"}isNull(e){return e===null}isUndefined(e){return typeof e>"u"}isArrayBuffer(e){return this.isObjectLike(e)&&this.getTag(e)==="[object ArrayBuffer]"}isTypedArray(e){const t=/^\[object (?:Float(?:32|64)|(?:Int|Uint)(?:8|16|32)|Uint8Clamped)Array\]$/;return this.isObjectLike(e)&&t.test(this.getTag(e))}isBlob(e){return this.isObjectLike(e)&&this.isNumber(e.size)&&this.isString(e.type)&&this.isFunction(e.slice)}isFile(e){return this.isBlob(e)&&this.isString(e.name)&&(this.isNumber(e.lastModified)||this.isObjectLike(e.lastModifiedDate))}isFormData(e){return typeof FormData<"u"&&e instanceof FormData?!0:this.isObjectLike(e)&&this.getTag(e)==="[object FormData]"}clone(e,t=!0){let s,n,i;if(this.isNil(e)||typeof e!="object")return e;if(this.isDomNode(e))s=e.cloneNode(t);else if(typeof e=="object")if(this.isArray(e))for(s=[],n=0,i=e.length;n<i;n++)typeof e[n]=="object"&&t?s[n]=this.clone(e[n],t):s[n]=e[n];else{s={},e.constructor&&(this.isDate(e)?s=new Date(e):s=new e.constructor);for(n in e)Object.prototype.hasOwnProperty.call(e,n)&&(typeof e[n]=="object"&&t?s[n]=this.clone(e[n],t):s[n]=e[n])}else s=e;return s}};const F=new Wf;var zf=Object.defineProperty,Es=o((r,e)=>zf(r,"name",{value:e,configurable:!0}),"r$f");function Ya(r,e){const t={};for(const s of e)t[s]=r[s];return t}o(Ya,"pick"),Es(Ya,"pick");function Vn(r,e){const t={...r};for(const s of e)delete t[s];return t}o(Vn,"omit"),Es(Vn,"omit");function Za(r){return Array.isArray(r[0])}o(Za,"isArrayOfArray"),Es(Za,"isArrayOfArray");function Xa(r,e){return Object.values(r).includes(e)?e:void 0}o(Xa,"getEnumValue"),Es(Xa,"getEnumValue");var Jf=Object.defineProperty,Qa=o((r,e)=>Jf(r,"name",{value:e,configurable:!0}),"i$l");const Pe=[];for(let r=0;r<256;++r)Pe.push((r+256).toString(16).slice(1));function ec(r,e,t,s){return()=>{r|=0,e|=0,t|=0,s|=0;const n=(r+e|0)+s|0;return s=s+1|0,r=e^e>>>9,e=t+(t<<3)|0,t=(t<<21|t>>>11)+n|0,n>>>0}}o(ec,"m$c"),Qa(ec,"sfc32");function tc(){const r=new Uint8Array(16),e=BigInt(Date.now()),t=BigInt(Math.floor(performance.now()*1e3)%65535),s=e<<16n|t;r[0]=Number(s>>40n&0xFFn),r[1]=Number(s>>32n&0xFFn),r[2]=Number(s>>24n&0xFFn),r[3]=Number(s>>16n&0xFFn),r[4]=Number(s>>8n&0xFFn),r[5]=Number(s&0xFFn);const n=(Math.random()*4294967295^Date.now()^performance.now())>>>0,i=ec(2654435769,608135816,3084996962,n),c=new DataView(r.buffer);return c.setUint32(6,i()),c.setUint32(10,i()),c.setUint16(14,i()),r[6]=112|r[6]&15,r[8]=128|r[8]&63,(Pe[r[0]]+Pe[r[1]]+Pe[r[2]]+Pe[r[3]]+"-"+Pe[r[4]]+Pe[r[5]]+"-"+Pe[r[6]]+Pe[r[7]]+"-"+Pe[r[8]]+Pe[r[9]]+"-"+Pe[r[10]]+Pe[r[11]]+Pe[r[12]]+Pe[r[13]]+Pe[r[14]]+Pe[r[15]]).toLowerCase()}o(tc,"a$m"),Qa(tc,"uuidv7");var Kf=Object.defineProperty,rc=o((r,e)=>Kf(r,"name",{value:e,configurable:!0}),"g$h");const Gf=/[&<>'"]/g,Yf=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34)/g,Zf={"&":"&","<":"<",">":">","'":"'",'"':"""},Xf={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","&apos":"'","'":"'",""":'"',""":'"'};class Qf{static{o(this,"C")}static{rc(this,"TextManager")}getRandom(e=8){return Array.from({length:e}).map(()=>Math.trunc(Math.random()*36).toString(36)).join("")}getUniqId(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.trunc(Math.random()*16);return(e==="x"?t:t&3|8).toString(16)})}getUuidRfc4122(){return tc()}encode(e){return F.isString(e)?e.replace(Gf,t=>Zf[t]):e}decode(e){return F.isString(e)?e.replace(Yf,t=>Xf[t]):e}toNumber(e){const t=Number.parseFloat(e);return F.isNumber(t)?t:0}toInteger(e){return this.toNumber(Number.parseInt(e,10))}toBoolean(e,t=[]){const s=F.isString(e)?e.toLowerCase():e;return["true","y","1",1,!0,...t].includes(s)}toCamelCase(e){if(!F.isStringFilled(e))return e;const t=/[-_\s]+(.)?/g;if(!t.test(e))return/^[A-Z]+$/.test(e)?e.toLowerCase():e[0].toLowerCase()+e.slice(1);const s=e.toLowerCase().replace(t,(n,i)=>i?i.toUpperCase():"");return s[0].toLowerCase()+s.slice(1)}toPascalCase(e){return F.isStringFilled(e)?this.capitalize(this.toCamelCase(e)):e}toKebabCase(e){if(!F.isStringFilled(e))return e;const t=e.match(/[A-Z]{2,}(?=[A-Z][a-z]+\d*|\b)|[A-Z]?[a-z]+\d*|[A-Z]|\d+/g);return t?t.map(s=>s.toLowerCase()).join("-"):e}capitalize(e){return F.isStringFilled(e)?e[0].toUpperCase()+e.slice(1):e}numberFormat(e,t=0,s=".",n=","){const i=Number.isFinite(e)?e:0,c=Number.isFinite(t)?Math.abs(t):0,a=(c?rc((l,h)=>{const u=10**h;return Math.round(l*u)/u},"roundTo")(i,c):Math.round(i)).toString().split(".");return a[0]&&a[0].length>3&&(a[0]=a[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,n)),(a[1]||"").length<c&&(a[1]=(a[1]||"").padEnd(c,"0")),a.join(s)}toDateTime(e,t,s){return F.isStringFilled(t)?z.fromFormat(e,t,s):z.fromISO(e,s)}toB24Format(e){return typeof e=="string"?e:e instanceof Date?this.toB24Format(z.fromJSDate(e)):e.toFormat("yyyy-MM-dd'T'HH:mm:ssZZ")}getDateForLog(){return z.now().toFormat("yyyy-MM-dd HH:mm:ss")}buildQueryString(e){if(F.isNil(e))return"";const t=[];for(const[s,n]of Object.entries(e))F.isArray(n)?n.forEach((i,c)=>{t.push(`${encodeURIComponent(`${s}[${c}]`)}=${encodeURIComponent(i)}`)}):t.push(`${encodeURIComponent(s)}=${encodeURIComponent(n)}`);return t.join("&")}}const W=new Qf;var ep=Object.defineProperty,tp=o((r,e)=>ep(r,"name",{value:e,configurable:!0}),"s$v");let Ce="";try{Ce=navigator?.userAgent.toLowerCase()}catch{Ce="?"}let rp=class{static{o(this,"u")}static{tp(this,"BrowserManager")}isOpera(){return Ce.includes("opera")}isIE(){return"attachEvent"in document&&!this.isOpera()}isIE6(){return Ce.includes("msie 6")}isIE7(){return Ce.includes("msie 7")}isIE8(){return Ce.includes("msie 8")}isIE9(){return"documentMode"in document&&document?.documentMode>=9}isIE10(){return"documentMode"in document&&document?.documentMode>=10}isSafari(){return Ce.includes("safari")&&!Ce.includes("chrome")}isFirefox(){return Ce.includes("firefox")}isChrome(){return Ce.includes("chrome")}detectIEVersion(){if(this.isOpera()||this.isSafari()||this.isFirefox()||this.isChrome())return-1;let e=-1;if(window.MSStream&&!window.ActiveXObject&&"ActiveXObject"in window?e=11:this.isIE10()?e=10:this.isIE9()?e=9:this.isIE()&&(e=8),e===-1||e===8){if(navigator.appName==="Microsoft Internet Explorer"){const t=/MSIE (\d[.0-9]*)/,s=navigator.userAgent.match(t);F.isArrayLike(s)&&s.length>0&&(e=Number.parseFloat(s[1]))}if(navigator.appName==="Netscape"){e=11;const t=/Trident\/.*rv:(\d[.0-9]*)/;if(t.exec(navigator.userAgent)!=null){const s=navigator.userAgent.match(t);F.isArrayLike(s)&&s.length>0&&(e=Number.parseFloat(s[1]))}}}return e}isIE11(){return this.detectIEVersion()>=11}isMac(){return Ce.includes("macintosh")}isWin(){return Ce.includes("windows")}isLinux(){return Ce.includes("linux")&&!this.isAndroid()}isAndroid(){return Ce.includes("android")}isIPad(){return Ce.includes("ipad;")||this.isMac()&&this.isTouchDevice()}isIPhone(){return Ce.includes("iphone;")}isIOS(){return this.isIPad()||this.isIPhone()}isMobile(){return this.isIPhone()||this.isIPad()||this.isAndroid()||Ce.includes("mobile")||Ce.includes("touch")}isRetina(){return(window.devicePixelRatio&&window.devicePixelRatio>=2)===!0}isTouchDevice(){return"ontouchstart"in window||navigator.maxTouchPoints>0}isDoctype(e){const t=e||document;return t.compatMode?t.compatMode==="CSS1Compat":t.documentElement&&t.documentElement.clientHeight}isLocalStorageSupported(){try{return localStorage.setItem("test","test"),localStorage.removeItem("test"),!0}catch{return!1}}detectAndroidVersion(){const e=/Android (\d[.0-9]*)/;if(e.exec(navigator.userAgent)!=null){const t=navigator.userAgent.match(e);if(F.isArrayLike(t)&&t.length>0)return Number.parseFloat(t[1])}return 0}};const sc=new rp;var ee=(r=>(r.v3="v3",r.v2="v2",r))(ee||{}),sp=Object.defineProperty,np=o((r,e)=>sp(r,"name",{value:e,configurable:!0}),"R$5"),nc=(r=>(r.undefined="UNDEFINED",r.lead="CRM_LEAD",r.deal="CRM_DEAL",r.contact="CRM_CONTACT",r.company="CRM_COMPANY",r.oldInvoice="CRM_INVOICE",r.invoice="CRM_SMART_INVOICE",r.quote="CRM_QUOTE",r.requisite="CRM_REQUISITE",r.order="ORDER",r))(nc||{}),ut=(r=>(r[r.undefined=0]="undefined",r[r.lead=1]="lead",r[r.deal=2]="deal",r[r.contact=3]="contact",r[r.company=4]="company",r[r.oldInvoice=5]="oldInvoice",r[r.invoice=31]="invoice",r[r.quote=7]="quote",r[r.requisite=8]="requisite",r[r.order=14]="order",r))(ut||{}),qn=(r=>(r.undefined="?",r.lead="L",r.deal="D",r.contact="C",r.company="CO",r.oldInvoice="I",r.invoice="SI",r.quote="Q",r.requisite="RQ",r.order="O",r))(qn||{});function ic(r){const e=ut[r];return qn[e]||"?"}o(ic,"getEnumCrmEntityTypeShort"),np(ic,"getEnumCrmEntityTypeShort");var oc=(r=>(r[r.undefined=0]="undefined",r[r.absolute=1]="absolute",r[r.percentage=2]="percentage",r))(oc||{}),ac=(r=>(r[r.undefined=0]="undefined",r[r.product=1]="product",r[r.service=7]="service",r[r.sku=3]="sku",r[r.skuEmpty=6]="skuEmpty",r[r.offer=4]="offer",r[r.offerEmpty=5]="offerEmpty",r))(ac||{}),cc=(r=>(r.undefined="UNDEFINED",r.detail="DETAIL_PICTURE",r.preview="PREVIEW_PICTURE",r.morePhoto="MORE_PHOTO",r))(cc||{}),lc=(r=>(r[r.undefined=0]="undefined",r[r.mathematical=1]="mathematical",r[r.roundingUp=2]="roundingUp",r[r.roundingDown=4]="roundingDown",r))(lc||{}),ip=Object.defineProperty,Os=o((r,e)=>ip(r,"name",{value:e,configurable:!0}),"u$d"),uc=(r=>(r.undefined="undefined",r.b24="b24",r.box="box",r))(uc||{}),hc=(r=>(r.undefined="undefined",r.crm="crm",r.disk="disk",r.lists="lists",r))(hc||{}),dc=(r=>(r.undefined="undefined",r.lead="CCrmDocumentLead",r.company="CCrmDocumentCompany",r.contact="CCrmDocumentContact",r.deal="CCrmDocumentDeal",r.invoice="Bitrix\\Crm\\Integration\\BizProc\\Document\\SmartInvoice",r.quote="Bitrix\\Crm\\Integration\\BizProc\\Document\\Quote",r.order="Bitrix\\Crm\\Integration\\BizProc\\Document\\Order",r.dynamic="Bitrix\\Crm\\Integration\\BizProc\\Document\\Dynamic",r.disk="Bitrix\\Disk\\BizProcDocument",r.lists="BizprocDocument",r.listsList="Bitrix\\Lists\\BizprocDocumentLists",r))(dc||{});function fc(r){switch(r){case"CCrmDocumentLead":return ut.lead;case"CCrmDocumentCompany":return ut.company;case"CCrmDocumentContact":return ut.contact;case"CCrmDocumentDeal":return ut.deal;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\SmartInvoice":return ut.invoice;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Quote":return ut.quote;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Order":return ut.order}return ut.undefined}o(fc,"convertBizprocDocumentTypeToCrmEntityTypeId"),Os(fc,"convertBizprocDocumentTypeToCrmEntityTypeId");function Ts(r,e){let t="",s="undefined";switch(r){case"CCrmDocumentLead":s="crm",t="LEAD";break;case"CCrmDocumentCompany":s="crm",t="COMPANY";break;case"CCrmDocumentContact":s="crm",t="CONTACT";break;case"CCrmDocumentDeal":s="crm",t="DEAL";break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\SmartInvoice":s="crm",t="SMART_INVOICE";break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Quote":s="crm",t="QUOTE";break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Order":s="crm",t="ORDER";break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Dynamic":if(s="crm",t=`DYNAMIC_${e||0}`,(e||0)<1)throw new Error("Need set entityId");break;case"Bitrix\\Disk\\BizProcDocument":if(s="disk",t=`STORAGE_${e||0}`,(e||0)<1)throw new Error("Need set entityId");break;case"BizprocDocument":if(s="lists",t=`iblock_${e||0}`,(e||0)<1)throw new Error("Need set entityId");break;case"Bitrix\\Lists\\BizprocDocumentLists":if(s="lists",t=`iblock_${e||0}`,(e||0)<1)throw new Error("Need set entityId");break}return[s,r,t]}o(Ts,"getDocumentType"),Os(Ts,"getDocumentType");function pc(r,e,t){let s="";const n=Ts(r,1);switch(r){case"CCrmDocumentLead":s=`LEAD_${e}`;break;case"CCrmDocumentCompany":s=`COMPANY_${e}`;break;case"CCrmDocumentContact":s=`CONTACT_${e}`;break;case"CCrmDocumentDeal":s=`DEAL_${e}`;break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\SmartInvoice":s=`SMART_INVOICE_${e}`;break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Quote":s=`QUOTE_${e}`;break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Order":s=`ORDER_${e}`;break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Dynamic":if(s=`DYNAMIC_${t||0}_${e}`,(t||0)<1)throw new Error("Need set dynamicId");break;case"Bitrix\\Disk\\BizProcDocument":s=`${e}`;break;case"BizprocDocument":s=`${e}`;break;case"Bitrix\\Lists\\BizprocDocumentLists":s=`${e}`;break}return[n[0],n[1],s]}o(pc,"getDocumentId"),Os(pc,"getDocumentId");function gc(r){const e=Ts(r,1);return[e[0],e[1]]}o(gc,"getDocumentTypeForFilter"),Os(gc,"getDocumentTypeForFilter");var he=(r=>(r.App="app",r.Profile="profile",r.Currency="currency",r.AppOptions="appOptions",r.UserOptions="userOptions",r))(he||{});const vt={Free:"F",Demo:"D",Trial:"T",Paid:"P",Local:"L",Subscription:"S"},mc={[vt.Free]:"Free",[vt.Demo]:"Demo",[vt.Trial]:"Trial",[vt.Paid]:"Paid",[vt.Local]:"Local",[vt.Subscription]:"Subscription"},qt={MainSettings:"MainSettings",UfList:"UfList",UfPage:"UfPage"};var Et=(r=>(r.NotSet="notSet",r.JsonArray="jsonArray",r.JsonObject="jsonObject",r.FloatVal="float",r.IntegerVal="integer",r.BoolYN="boolYN",r.StringVal="string",r))(Et||{}),op=Object.defineProperty,ap=o((r,e)=>op(r,"name",{value:e,configurable:!0}),"s$u"),pe=(r=>(r.Undefined="undefined",r.WebSocket="webSocket",r.LongPolling="longPolling",r))(pe||{}),We=(r=>(r.PullConfig="bx-pull-config",r.WebsocketBlocked="bx-pull-websocket-blocked",r.LongPollingBlocked="bx-pull-longpolling-blocked",r.LoggingEnabled="bx-pull-logging-enabled",r))(We||{}),Ze=(r=>(r.Online="online",r.Offline="offline",r.Connecting="connect",r))(Ze||{}),As=(r=>(r[r.Unknown=0]="Unknown",r[r.Client=1]="Client",r[r.Backend=2]="Backend",r))(As||{}),Xe=(r=>(r.Server="server",r.Client="client",r.Online="online",r.Status="status",r.Revision="revision",r))(Xe||{}),$e=(r=>(r[r.NORMAL_CLOSURE=1e3]="NORMAL_CLOSURE",r[r.SERVER_DIE=1001]="SERVER_DIE",r[r.CONFIG_REPLACED=3e3]="CONFIG_REPLACED",r[r.CHANNEL_EXPIRED=3001]="CHANNEL_EXPIRED",r[r.SERVER_RESTARTED=3002]="SERVER_RESTARTED",r[r.CONFIG_EXPIRED=3003]="CONFIG_EXPIRED",r[r.MANUAL=3004]="MANUAL",r[r.STUCK=3005]="STUCK",r[r.WRONG_CHANNEL_ID=4010]="WRONG_CHANNEL_ID",r[r.NO_PUBLIC_CHANNEL_ID=4012]="NO_PUBLIC_CHANNEL_ID",r[r.WRONG_REQUEST_DATA=4013]="WRONG_REQUEST_DATA",r[r.REQUEST_COMMAND_NOT_ALLOWED=4014]="REQUEST_COMMAND_NOT_ALLOWED",r[r.WRONG_REQUEST_COMMAND=4015]="WRONG_REQUEST_COMMAND",r[r.TOO_MANY_MESSAGES=4016]="TOO_MANY_MESSAGES",r[r.NO_CHANNELS_FOUND=4017]="NO_CHANNELS_FOUND",r[r.TOO_MANY_CHANNELS=4018]="TOO_MANY_CHANNELS",r[r.INVALID_CHANNEL_ID=4019]="INVALID_CHANNEL_ID",r[r.PRIVATE_CHANNEL_NOT_ALLOWED=4020]="PRIVATE_CHANNEL_NOT_ALLOWED",r[r.INVALID_CHANNEL_SIGNATURE=4021]="INVALID_CHANNEL_SIGNATURE",r[r.TOO_MANY_CONNECTIONS=4029]="TOO_MANY_CONNECTIONS",r))($e||{});function yc(r){return cp.has(r)}o(yc,"isFrameRefusalCloseCode"),ap(yc,"isFrameRefusalCloseCode");const cp=new Set([4013,4014,4015,4016,4017,4018,4019,4020,4021]);var xr=(r=>(r.CHANNEL_EXPIRE="CHANNEL_EXPIRE",r.CONFIG_EXPIRE="CONFIG_EXPIRE",r.SERVER_RESTART="SERVER_RESTART",r))(xr||{}),Hn=(r=>(r.Shared="shared",r.Personal="personal",r))(Hn||{});const Wn={Parse:{code:-32700,message:"Parse error"},InvalidRequest:{code:-32600,message:"Invalid Request"},MethodNotFound:{code:-32601,message:"Method not found"},InvalidParams:{code:-32602,message:"Invalid params"},Internal:{code:-32603,message:"Internal error"}};var pt=(r=>(r.Publish="publish",r.GetUsersLastSeen="getUsersLastSeen",r.Ping="ping",r.ListChannels="listChannels",r.SubscribeStatusChange="subscribeStatusChange",r.UnsubscribeStatusChange="unsubscribeStatusChange",r))(pt||{}),zn=(r=>(r.ru="ru",r.id="id",r.ms="ms",r.de="de",r.en="en",r.la="la",r.fr="fr",r.in="in",r.it="it",r.pl="pl",r.br="br",r.vn="vn",r.tr="tr",r.kz="kz",r.ua="ua",r.ar="ar",r.th="th",r.sc="sc",r.tc="tc",r.ja="ja",r))(zn||{});const lp={ru:"ru-RU",id:"id-ID",ms:"ms-MY",de:"de-DE",en:"en-EN",la:"es-ES",fr:"fr-FR",in:"hi-IN",it:"it-IT",pl:"pl-PL",br:"pt-BR",vn:"vi-VN",tr:"tr-TR",kz:"kk",ua:"uk-UA",ar:"ar-SA",th:"th-TH",sc:"zh-CN",tc:"zh-TW",ja:"ja-JP"};var up=Object.defineProperty,hp=o((r,e)=>up(r,"name",{value:e,configurable:!0}),"s$t");class ke{static{o(this,"Result")}static{hp(this,"Result")}_errors;_data;constructor(e){this._errors=new Map,this._data=e??null}get isSuccess(){return this._errors.size===0}get errors(){return this._errors}setData(e){return this._data=e,this}getData(){return this._data}addError(e,t){const s=t??W.getUuidRfc4122(),n=typeof e=="string"?new Error(e):e;return this._errors.set(s,n),this}addErrors(e){for(const t of e)this.addError(t);return this}getErrors(){return this._errors.values()}hasError(e){return this._errors.has(e)}getErrorMessages(){return Array.from(this._errors.values(),e=>e.message)}getErrorsByKey(){return Object.fromEntries(this._errors)}getErrorMessagesByKey(){return Object.fromEntries(Array.from(this._errors,([e,t])=>[e,t.message]))}toString(){const e=this.isSuccess?"success":"failure",t=this.safeStringify(this._data);return this.isSuccess?`Result(${e}): ${t}`:`Result(${e}): ${t}
Errors: ${this.getErrorMessages().join(", ")}`}safeStringify(e){try{return JSON.stringify(e,this.replacer,2)}catch{return"[Unable to serialize data]"}}replacer(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t}static ok(e){return new ke(e)}static fail(e,t){return new ke().addError(e,t)}}var dp=Object.defineProperty,fp=o((r,e)=>dp(r,"name",{value:e,configurable:!0}),"e$b");class D extends Error{static{o(this,"SdkError")}static{fp(this,"SdkError")}code;_status;timestamp;constructor(e){const t=D.formatErrorMessage(e);super(t),this.name="SdkError",this.code=e.code,this._status=e.status,Object.defineProperty(this,"originalError",{value:e.originalError,enumerable:!1,writable:!1,configurable:!0}),this.timestamp=new Date,this.cleanErrorStack()}get status(){return this._status}static fromException(e,t){return e instanceof D?e:new D({code:t?.code||"JSSDK_INTERNAL_ERROR",status:t?.status||500,description:e instanceof Error?e.message:`${e}`,originalError:e})}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this._status,timestamp:this.timestamp.toISOString(),stack:this.stack}}toString(){let e=`[${this.name}] ${this.code} (${this._status}): ${this.message}`;return this.stack&&(e+=`
Stack trace:
${this.stack}`),e}static formatErrorMessage(e){return e?.description?`${e.description}`:"Internal error"}cleanErrorStack(){typeof this.stack=="string"&&(this.stack=this.stack.split(`
`).filter(e=>!e.includes("SdkError.constructor")).join(`
`))}}var pp=Object.defineProperty,Dt=o((r,e)=>pp(r,"name",{value:e,configurable:!0}),"e$a");const Jn=["auth","password","token","secret","access_token","refresh_token","client_secret","application_token","sessid","key","signature"],$r="***REDACTED***",gp=new RegExp(`([?&]|^)(${Jn.join("|")})=[^&#;]*`,"gi"),mp=/(\/rest\/(?:api\/)?\d+\/)[\w-]{8,}(?=[/?#]|$)/gi;function Kn(r){return r.replace(mp,`$1${$r}`)}o(Kn,"c$c"),Dt(Kn,"redactWebhookPath");function Gn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}o(Gn,"u$c"),Dt(Gn,"isPlainObject");function Yn(r){return r.includes("=")?r.replace(gp,(e,t,s)=>`${t}${s}=${$r}`):r}o(Yn,"a$k"),Dt(Yn,"redactQueryString");function bc(r){return Kn(Yn(r))}o(bc,"_$2"),Dt(bc,"redactString");function ks(r,e){return typeof r=="string"?bc(r):e<=0?r:Gn(r)?Zn(r,e-1):Array.isArray(r)?r.map(t=>ks(t,e)):r}o(ks,"o$o"),Dt(ks,"redactValue");function Zn(r,e){const t={...r};for(const s of Object.keys(t)){if(Jn.includes(s.toLowerCase())){t[s]=$r;continue}t[s]=ks(t[s],e)}return t}o(Zn,"g$f"),Dt(Zn,"redactObject");const _c=2;function qe(r){return Gn(r)?Zn(r,_c):ks(r,_c)}o(qe,"redactSensitiveParams"),Dt(qe,"redactSensitiveParams");function wc(r,e=[]){if(typeof r!="string")return r;const t=Kn(r);if(!t.includes("="))return t;if(e.length===0)return Yn(t);const s=e.map(i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),n=new RegExp(`([?&]|^)(${[...Jn,...s].join("|")})=[^&#;]*`,"gi");return t.replace(n,(i,c,a)=>`${c}${a}=${$r}`)}o(wc,"redactSensitiveUrl"),Dt(wc,"redactSensitiveUrl");var yp=Object.defineProperty,bp=o((r,e)=>yp(r,"name",{value:e,configurable:!0}),"r$e");class _e extends D{static{o(this,"AjaxError")}static{bp(this,"AjaxError")}requestInfo;validation;isV3Envelope;constructor(e){(e.code==="AUTHORIZE_ERROR"||e.code==="WRONG_AUTH_TYPE")&&(e.status=403),e.description=_e.formatErrorMessage(e),super(e),this.name="AjaxError",this.isV3Envelope=e.isV3Envelope,this.validation=e.validation?.length?Object.freeze(e.validation.map(t=>qe(t))):void 0,this.requestInfo=e.requestInfo?{...e.requestInfo,...e.requestInfo.params!==void 0?{params:qe(e.requestInfo.params)}:{}}:void 0,this.cleanErrorStack()}static fromResponse(e){return new _e({code:e.data?.error||"JSSDK_INTERNAL_AJAX_ERROR",description:e.data?.error_description,status:e.status,requestInfo:e.config})}static fromException(e,t){return e instanceof _e?e:new _e({code:t?.code||"JSSDK_INTERNAL_AJAX_ERROR",status:t?.status||500,description:e instanceof Error?e.message:String(e),requestInfo:t?.requestInfo,originalError:e})}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this._status,timestamp:this.timestamp.toISOString(),requestInfo:this.requestInfo,...this.validation?{validation:this.validation}:{},stack:this.stack}}toString(){let e=`[${this.name}] ${this.code} (${this._status}): ${this.message}`;return this.requestInfo&&(e+=`
Request: ${this.requestInfo?.requestId?`[${this.requestInfo.requestId}] `:""}${this.requestInfo.method}`),this.stack&&(e+=`
Stack trace:
${this.stack}`),e}static formatErrorMessage(e){return e?.description?`${e.description}`:e.requestInfo?.method?`${e.code} (on ${e.requestInfo.method})`:"Internal ajax error"}cleanErrorStack(){typeof this.stack=="string"&&(this.stack=this.stack.split(`
`).filter(e=>!e.includes("AjaxError.constructor")).join(`
`))}}var _p=Object.defineProperty,wp=o((r,e)=>_p(r,"name",{value:e,configurable:!0}),"s$r");function Xn(r,e,t){if(!r||typeof r!="object"||!("error"in r))return;const s=r;if(s.error&&typeof s.error=="object"&&"code"in s.error){const n=s.error;let i=String(n.message??"").trimEnd();if(n.validation&&n.validation.length>0){const c=n.validation.map(a=>a?.message||JSON.stringify(a)).filter(a=>a!==void 0&&a!=="");c.length>0&&(i.length>0&&(i.endsWith(".")||(i+="."),i+=" "),i+=c.join(" "))}return{code:n.code,description:i,isV3Envelope:!0,...n.validation?{validation:Object.freeze([...n.validation])}:{}}}if(s.error&&typeof s.error=="string")return{code:s.error!=="0"?s.error:e,description:s?.error_description??t,isV3Envelope:!1}}o(Xn,"parseErrorPayload"),wp(Xn,"parseErrorPayload");var Sp=Object.defineProperty,vp=o((r,e)=>Sp(r,"name",{value:e,configurable:!0}),"s$q");class jr extends ke{static{o(this,"AjaxResult")}static{vp(this,"AjaxResult")}_status;_query;_idempotency;_data;constructor(e){super(),this._data=e.answer?Object.freeze(e.answer):void 0,this._query=Object.freeze(structuredClone(e.query)),this._status=e.status,this._idempotency=e.idempotency?Object.freeze({...e.idempotency}):void 0,e.error?this.addError(e.error,"base-error"):this.#t()}get isSuccess(){return this.#e()}#e(){return this._errors.size===0}getData(){if(!this.isSuccess)return;const e=this._data;return e!==null&&typeof e=="object"&&"result"in e?Object.freeze({result:e.result,time:e.time}):Object.freeze({result:e,time:e?.time})}#t(){const e=Xn(this._data,"JSSDK_RESPONSE_ERROR","Some error in response");e!==void 0&&this.addError(this.#s({code:e.code,description:e.description,status:this._status,validation:e.validation,isV3Envelope:e.isV3Envelope}),"base-error")}#s(e){return new _e({code:e.code,description:e.description,status:e.status,validation:e.validation,isV3Envelope:e.isV3Envelope,requestInfo:{method:this._query.method,params:this._query.params,requestId:this._query.requestId}})}hasMore(){return this.isMore()}isMore(){if(!this.isSuccess)return!1;const e=this._data,t="next"in e?e.next:void 0;return F.isNumber(t)}getTotal(){if(!this.isSuccess)return 0;const e=this._data,t="total"in e?e.total:void 0;return W.toInteger(t)}getStatus(){return this._status}isIdempotentReplay(){return this._idempotency?.replayed??!1}getIdempotencyKey(){return this._idempotency?.key}getQuery(){return this._query}async fetchNext(e){const t=await this.getNext(e);return t===!1?null:t}async getNext(e){if(e.apiVersion===ee.v3)throw new D({code:"JSSDK_CORE_METHOD_NOT_SUPPORT_IN_API_V3",description:"restApi:v3 not support method getNext",status:500});if(!this.isSuccess||!this.isMore())return!1;const t=this.#r();return e.call(t.method,t.params)}#r(){const e=this._data,t="next"in e?e.next:void 0;return{...this._query,params:{...this._query.params,start:W.toInteger(t)}}}setData(){throw new ReferenceError("AjaxResult does not allow data modification")}}var Ep=Object.defineProperty,Op=o((r,e)=>Ep(r,"name",{value:e,configurable:!0}),"a$j");class Br{static{o(this,"ParamsFactory")}static{Op(this,"ParamsFactory")}static getDefault(){return{rateLimit:{burstLimit:50,drainRate:2,adaptiveEnabled:!0},operatingLimit:{windowMs:6e5,limitMs:48e4,heavyPercent:80},adaptiveConfig:{enabled:!0,thresholdPercent:80,coefficient:.01,maxDelay:7e3},maxRetries:3,retryDelay:1e3,retryOnNetworkError:!0}}static getEnterprise(){return{...this.getDefault(),rateLimit:{burstLimit:250,drainRate:5,adaptiveEnabled:!0}}}static getBatchProcessing(){return{...this.getDefault(),rateLimit:{burstLimit:30,drainRate:1,adaptiveEnabled:!0},operatingLimit:{windowMs:6e5,limitMs:48e4,heavyPercent:50},adaptiveConfig:{enabled:!0,thresholdPercent:50,coefficient:.015,maxDelay:1e4},maxRetries:5}}static getRealtime(){return{...this.getDefault(),adaptiveConfig:{enabled:!1,thresholdPercent:100,coefficient:.001,maxDelay:48e4},maxRetries:1}}static fromTariffPlan(e){return e.toLowerCase()==="enterprise"?this.getEnterprise():this.getDefault()}}var Tp=Object.defineProperty,Ap=o((r,e)=>Tp(r,"name",{value:e,configurable:!0}),"g$e");class Sc{static{o(this,"RateLimiter")}static{Ap(this,"RateLimiter")}#e;#t;#s;#r;#i=[];#n;#o=5;#a=20;#h=.5;#d=5;#c=[];#l=[];_logger;constructor(e){this._logger=ae.createNullLogger(),this.#r=e,this.#n={...e},this.#e=e.burstLimit,this.#t=Date.now(),this.#s=1e3/e.drainRate}getTitle(){return"rateLimiter"}setLogger(e){this._logger=e}getLogger(){return this._logger}async canProceed(e,t,s){await this.#u(e);try{const n=Date.now(),i=(n-this.#t)*this.#r.drainRate/1e3;return this.#e=Math.min(this.#r.burstLimit,this.#e+i),this.#t=n,this.#e>=1}finally{this.#f()}}async waitIfNeeded(e,t,s){await this.#u(e);try{const n=Date.now(),i=(n-this.#t)*this.#r.drainRate/1e3;if(this.#e=Math.min(this.#r.burstLimit,this.#e+i),this.#t=n,this.#e>=1)return this.#e-=1,0;const c=1-this.#e;return Math.ceil(c*this.#s)}finally{this.#f()}}async handleExceeded(e){await this.#u(e);try{return this.#_(),this.#r.adaptiveEnabled&&this.#p()&&this.#b(e),this.#e=0,this.#s+1e3}finally{this.#f()}}async updateStats(e,t,s){await this.#u(e);try{this.#w(),this.#r.adaptiveEnabled&&this.#T(e),this.#r.adaptiveEnabled&&this.#g()&&this.#m(e)}finally{this.#f()}}async reset(){await this.#u("reset");try{this.#e=this.#r.burstLimit,this.#t=Date.now(),this.#c=[],this.#l=[],this.#r.drainRate=this.#n.drainRate,this.#r.burstLimit=this.#n.burstLimit,this.#s=1e3/this.#r.drainRate}finally{this.#f()}}getStats(){return{tokens:this.#e,burstLimit:this.#r.burstLimit,originalBurstLimit:this.#n.burstLimit,drainRate:this.#r.drainRate,originalDrainRate:this.#n.drainRate,refillIntervalMs:this.#s,lastRefill:this.#t,pendingRequests:this.#i.length,recentErrors:this.#c.length,recentSuccesses:this.#l.length}}async setConfig(e){await this.#u("setConfig");try{this.#r=e,this.#n={...e},this.#s=1e3/this.#r.drainRate,e.burstLimit>this.#e&&(this.#e=Math.min(e.burstLimit,this.#e)),this.#c=[],this.#l=[]}finally{this.#f()}}async#u(e){return new Promise(t=>{const s=this.#i.push(t);s>1&&this.#O(e,s),this.#i.length===1&&t()})}#f(){if(this.#i.shift(),this.#i.length>0){const e=this.#i[0];e()}}#p(){return this.#c.length>=this.#o}#g(){return this.#l.length>=this.#a&&this.#c.length<this.#o/2&&(this.#r.drainRate<this.#n.drainRate||this.#r.burstLimit<this.#n.burstLimit)}#b(e){const t=Math.max(this.#h,Number.parseFloat((this.#r.drainRate*.8).toFixed(2))),s=Math.max(this.#d,Number.parseFloat((this.#r.burstLimit*.8).toFixed(2)));this.#r.drainRate=t,this.#r.burstLimit=s,this.#s=1e3/t,this.#v(e,t,s),this.#c=[],this.#l=[]}#m(e){if(this.#r.drainRate===this.#n.drainRate&&this.#r.burstLimit===this.#n.burstLimit)return;const t=Math.min(this.#n.drainRate,Number.parseFloat((this.#r.drainRate*1.1).toFixed(2))),s=Math.min(this.#n.burstLimit,Number.parseFloat((this.#r.burstLimit*1.1).toFixed(2)));this.#r.drainRate=t,this.#r.burstLimit=s,this.#s=1e3/t,this.#E(e,t,s),this.#c=[],this.#l=[]}#_(){const e=Date.now();this.#c.push(e),this.#l=[],this.#y(e)}#y(e){const t=e-6e4;this.#c=this.#c.filter(s=>s>t)}#w(){const e=Date.now();this.#l.push(e),this.#S(),this.#y(e)}#S(){this.#l=this.#l.slice(-1*this.#a)}#v(e,t,s){const n=this.#n.drainRate,i=t<n,c=this.#n.burstLimit,a=s<c;this.getLogger().warning(`${this.getTitle()} is lowering limits due to frequent errors`,{requestId:e,drainRate:{current:t,original:n,condition:i,formatted:`(${t} < ${n}) ${i}`},burstLimit:{current:s,original:c,condition:a,formatted:`(${s} < ${c}) ${a}`}}).catch(()=>{})}#E(e,t,s){const n=this.#n.drainRate,i=t<n,c=this.#n.burstLimit,a=s<c;this.getLogger().warning(`${this.getTitle()} increases limits during stable operation`,{requestId:e,drainRate:{current:t,original:n,condition:i,formatted:`(${t} < ${n}) ${i}`},burstLimit:{current:s,original:c,condition:a,formatted:`(${s} < ${c}) ${a}`}}).catch(()=>{})}#O(e,t){this.getLogger().debug(`${this.getTitle()} request in queue`,{requestId:e,queueLength:t}).catch(()=>{})}#T(e){const t=this.#l.length,s=this.#a,n=t>=s,i=this.#c.length,c=this.#o,a=i<c/2,l=this.#r.drainRate,h=this.#n.drainRate,u=l<h,p=this.#r.burstLimit,g=this.#n.burstLimit,f=p<g;this.getLogger().debug(`${this.getTitle()} state`,{requestId:e,success:{count:t,threshold:s,condition:n,formatted:`(${t} >= ${s}) ${n}`},fail:{count:i,threshold:c/2,condition:a,formatted:`(${i} < ${c/2}) ${a}`},drainRate:{current:l,original:h,condition:u,formatted:`(${l} < ${h}) ${u}`},burstLimit:{current:p,original:g,condition:f,formatted:`(${p} < ${g}) ${f}`}}).catch(()=>{})}}var kp=Object.defineProperty,Ip=o((r,e)=>kp(r,"name",{value:e,configurable:!0}),"g$d");class vc{static{o(this,"OperatingLimiter")}static{Ip(this,"OperatingLimiter")}#e;#t=new Map;#s={heavyRequestCount:0};_logger;getTitle(){return"operatingLimiter"}constructor(e){this._logger=ae.createNullLogger(),this.#e=e}setLogger(e){this._logger=e}getLogger(){return this._logger}get limitMs(){return this.#e.limitMs}getMethodStat(e){const t=this.#t.get(e);if(t)return t}async canProceed(e,t,s){return await this.getTimeToFree(e,t,s)===0}async waitIfNeeded(e,t,s){return this.getTimeToFree(e,t,s)}async getTimeToFree(e,t,s,n){this.#r();const i=this.#t.get(t);if(!i)return 0;const c=Math.max(1e3,this.#e.limitMs-5e3);if(i.operating>=c){const a=Date.now();return i.operating_reset_at>a?i.operating_reset_at-a+1e3:5e3}return 0}async updateStats(e,t,s){if(!s)return;this.#r();const{operating:n,operating_reset_at:i}=s;if(n==null)return;this.#t.has(t)||this.#t.set(t,{operating:0,operating_reset_at:0,lastUpdated:Date.now()});const c=this.#t.get(t);c.operating=n*1e3,i!==void 0&&(c.operating_reset_at=i*1e3),c.lastUpdated=Date.now();const a=c.operating/this.#e.limitMs*100;a>this.#e.heavyPercent&&(this.#s.heavyRequestCount++,this.#i(e,t,a,c.operating))}#r(){const e=Date.now(),t=this.#e.windowMs+1e4;for(const[s,n]of this.#t.entries())e-n.lastUpdated>t&&this.#t.delete(s)}async reset(){this.#t.clear(),this.#s={heavyRequestCount:0}}getStats(){const e={};for(const[t,s]of this.#t.entries())e[t]=Number.parseFloat((s.operating/1e3).toFixed(2));return{...this.#s,operatingStats:e}}async setConfig(e){this.#e=e}#i(e,t,s,n){this.getLogger().debug(`${this.getTitle()} detected limit for method ${t}`,{requestId:e,method:t,operating:{percent:Number.parseFloat(s.toFixed(2)),current:Number.parseFloat((n/1e3).toFixed(0)),max:Number.parseFloat((this.#e.limitMs/1e3).toFixed(0))}}).catch(()=>{})}}var Rp=Object.defineProperty,Cp=o((r,e)=>Rp(r,"name",{value:e,configurable:!0}),"g$c");class Ec{static{o(this,"AdaptiveDelayer")}static{Cp(this,"AdaptiveDelayer")}#e;#t;#s={adaptiveDelays:0,totalAdaptiveDelay:0};_logger;getTitle(){return"adaptiveDelayer"}constructor(e,t){this._logger=ae.createNullLogger(),this.#e=e,this.#t=t}setLogger(e){this._logger=e}getLogger(){return this._logger}async canProceed(e,t,s){return!0}async waitIfNeeded(e,t,s){if(!this.#e.enabled)return 0;const n=this.#r(e,t);return n>0&&(this.incrementAdaptiveDelays(),this.#s.totalAdaptiveDelay+=n),n}#r(e,t){const s=this.#t.getMethodStat(t);if(typeof s>"u")return 0;const n=s.operating/this.#t.limitMs*100;if(n>this.#e.thresholdPercent){let i=0;const c=Date.now();s.operating_reset_at>c?i+=(s.operating_reset_at-c)*this.#e.coefficient:i+=7e3;const a=Number.parseInt(Math.min(i,this.#e.maxDelay).toFixed(0));return this.#i(e,t,n,i,a),a}return 0}async updateStats(e,t,s){}async reset(){this.#s={adaptiveDelays:0,totalAdaptiveDelay:0}}getStats(){return{...this.#s,adaptiveDelayAvg:this.#s.adaptiveDelays>0?this.#s.totalAdaptiveDelay/this.#s.adaptiveDelays:0}}async setConfig(e){this.#e=e}incrementAdaptiveDelays(){this.#s.adaptiveDelays++}#i(e,t,s,n,i){this.getLogger().debug(`${this.getTitle()} state for method ${t}`,{requestId:e,method:t,percent:Number.parseFloat(s.toFixed(2)),delays:{calculated:n,actual:i}}).catch(()=>{})}}var Np=Object.defineProperty,Is=o((r,e)=>Np(r,"name",{value:e,configurable:!0}),"E$2");const Oc=["burstLimit","drainRate","adaptiveEnabled"],Tc=["windowMs","limitMs","heavyPercent"],Ac=["thresholdPercent","coefficient","maxDelay","enabled"];function Qn(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0))}o(Qn,"m$a"),Is(Qn,"definedOnly");function Rs(r){return{...r,...r.rateLimit?{rateLimit:{...r.rateLimit}}:{},...r.operatingLimit?{operatingLimit:{...r.operatingLimit}}:{},...r.adaptiveConfig?{adaptiveConfig:{...r.adaptiveConfig}}:{},...r.hardErrorCodes?{hardErrorCodes:[...r.hardErrorCodes]}:{},...r.softErrorCodes?{softErrorCodes:[...r.softErrorCodes]}:{}}}o(Rs,"g$b"),Is(Rs,"cloneParams");function Ht(r,e,t){if(r===void 0)return;const s=r,n=s===null?[...t]:t.filter(i=>s[i]===void 0);if(n.length!==0)throw new D({code:"JSSDK_LIMITER_INVALID_CONFIG_BLOCK",description:`setRestrictionManagerParams: \`${e}\` is replaced whole, not merged, so it must carry every field. Missing: ${n.join(", ")}. Spread the current block if you mean to change one value.`,status:500})}o(Ht,"a$i"),Is(Ht,"assertBlock");class dr{static{o(this,"RestrictionManager")}static{Is(this,"RestrictionManager")}#e;#t;#s;#r;#i={retries:0,consecutiveErrors:0,limitHits:0};#n=new Map;_logger;constructor(e){this._logger=ae.createNullLogger();const t=Qn(e);Ht(t.rateLimit,"rateLimit",Oc),Ht(t.operatingLimit,"operatingLimit",Tc),Ht(t.adaptiveConfig,"adaptiveConfig",Ac),this.#r=Rs({...Br.getDefault(),...t}),this.#e=new Sc(this.#r.rateLimit),this.#t=new vc(this.#r.operatingLimit),this.#s=new Ec(this.#r.adaptiveConfig,this.#t)}setLogger(e){this._logger=e,this.#e.setLogger(this._logger),this.#t.setLogger(this._logger),this.#s.setLogger(this._logger)}getLogger(){return this._logger}async applyOperatingLimits(e,t,s){const n=await this.#t.waitIfNeeded(e,t,s);if(n>0)this.incrementStats("limitHits"),this.#g(this.#t.getTitle(),e,t,n),await this.#p(n);else{const i=await this.#s.waitIfNeeded(e,t,s);i>0&&(this.incrementStats("limitHits"),this.#g(this.#s.getTitle(),e,t,i),await this.#p(i))}}async checkRateLimit(e,t){let s,n=1;do s=await this.#e.waitIfNeeded(e,t),s>0&&(this.incrementStats("limitHits"),this.#b(this.#e.getTitle(),e,t,s,n),await this.#p(s),n++);while(s>0)}async updateStats(e,t,s){await this.#t.updateStats(e,t,s),await this.#s.updateStats(e,t,s),await this.#e.updateStats(e,t,s)}async handleError(e,t,s,n,i){if(this.#o(n)){const c=await this.#a(e)*Math.pow(1.5,i);return this.#m(this.#e.getTitle(),e,"QUERY_LIMIT_EXCEEDED",n.message,t,c),c}if(this.#h(n)){const c=Math.max(1e4,await this.#d(e,t,s,n));return this.#m(this.#t.getTitle(),e,"OPERATION_TIME_LIMIT",n.message,t,c),c}if(this.#c(n))return this.#y(e,n?.code?`${n.code}`:"?",n?.message??"",t,Number(n?.status??0)),0;if(!this.#l(n)){const c=await this.#f(e),a=Math.max(3e4,c),l=Math.min(a,c*Math.pow(2,i)),h=l*.1*(Math.random()*2-1),u=Math.max(100,l+h);return this.#_(e,n?.code?`${n.code}`:"?",n.message,t,u),u}return 0}#o(e){return e.status===503||e.code==="QUERY_LIMIT_EXCEEDED"}async#a(e){return this.#e.handleExceeded(e)}#h(e){return e.status===429||e.code==="OPERATION_TIME_LIMIT"}async#d(e,t,s,n){return this.#t.getTimeToFree(e,t,s,n)}#c(e){const t=Number(e?.status??0);return Number.isNaN(t)?!1:t>=400&&t<500&&t!==408&&t!==429}#l(e){const t={code:e?.code??"-1",description:e?.message??""};return[...this.exceptionCodeForHard,...this.exceptionCodeForSoft].includes(t.code)||(t.description??"").includes("Could not find value for parameter")}static BUILT_IN_HARD_ERROR_CODES=["ERR_BAD_REQUEST","JSSDK_UNKNOWN_ERROR","100","INTERNAL_SERVER_ERROR","ERROR_UNEXPECTED_ANSWER","PORTAL_DELETED","ERROR_BATCH_METHOD_NOT_ALLOWED","ERROR_BATCH_LENGTH_EXCEEDED","NO_AUTH_FOUND","INVALID_REQUEST","OVERLOAD_LIMIT","expired_token","invalid_token","ACCESS_DENIED","INVALID_CREDENTIALS","user_access_error","insufficient_scope","BITRIX_REST_V3_EXCEPTION_INSUFFICIENTSCOPEEXCEPTION","JSSDK_HTTP_REDIRECT_BLOCKED","ERROR_MANIFEST_IS_NOT_AVAILABLE","allowed_only_intranet_user","NOT_FOUND","INVALID_ARG_VALUE"];static BUILT_IN_SOFT_ERROR_CODES=["ERROR_ENTITY_NOT_FOUND","BITRIX_REST_V3_EXCEPTION_ACCESSDENIEDEXCEPTION","BITRIX_REST_V3_EXCEPTION_INVALIDJSONEXCEPTION","BITRIX_REST_V3_EXCEPTION_INVALIDFILTEREXCEPTION","BITRIX_REST_V3_EXCEPTION_INVALIDSELECTEXCEPTION","BITRIX_REST_V3_EXCEPTION_ENTITYNOTFOUNDEXCEPTION","BITRIX_REST_V3_EXCEPTION_METHODNOTFOUNDEXCEPTION","BITRIX_REST_V3_EXCEPTION_UNKNOWNDTOPROPERTYEXCEPTION","BITRIX_REST_V3_EXCEPTION_VALIDATION_REQUESTVALIDATIONEXCEPTION","BITRIX_REST_V3_EXCEPTION_VALIDATION_DTOVALIDATIONEXCEPTION"];get exceptionCodeForHard(){const e=[...dr.BUILT_IN_HARD_ERROR_CODES];return this.#r.retryOnNetworkError===!1&&e.push("NETWORK_ERROR","REQUEST_TIMEOUT"),this.#r.hardErrorCodes&&this.#r.hardErrorCodes.length>0&&e.push(...this.#r.hardErrorCodes),e}get exceptionCodeForSoft(){const e=[...dr.BUILT_IN_SOFT_ERROR_CODES];return this.#r.softErrorCodes&&this.#r.softErrorCodes.length>0&&e.push(...this.#r.softErrorCodes),e}static#u=[401,408,429];isSoftError(e){const t=e?.code,s=typeof t=="string"?t:"";if(this.exceptionCodeForHard.includes(s))return!1;if(this.exceptionCodeForSoft.includes(s))return!0;if(e?.isV3Envelope!==!0)return!1;const n=Number(e?.status??0);return Number.isInteger(n)&&n>=400&&n<500&&!dr.#u.includes(n)}async#f(e){return this.#r.retryDelay??Br.getDefault().retryDelay}incrementError(e){const t=this.#n.get(e)||0;this.#n.set(e,t+1),this.incrementStats("consecutiveErrors")}resetErrors(e){this.#n.delete(e),this.#i.consecutiveErrors=0}incrementStats(e){this.#i[e]++}getStats(){return{...this.#i,...this.#e.getStats(),...this.#s.getStats(),...this.#t.getStats(),errorCounts:Object.fromEntries(this.#n)}}async reset(){await this.#e.reset(),await this.#t.reset(),await this.#s.reset(),this.#n.clear(),this.#i={retries:0,consecutiveErrors:0,limitHits:0}}async setConfig(e){const t=Qn(e);Ht(t.rateLimit,"rateLimit",Oc),Ht(t.operatingLimit,"operatingLimit",Tc),Ht(t.adaptiveConfig,"adaptiveConfig",Ac),this.#r=Rs({...this.#r,...t}),t.rateLimit!==void 0&&await this.#e.setConfig({...t.rateLimit}),t.operatingLimit!==void 0&&await this.#t.setConfig({...t.operatingLimit}),t.adaptiveConfig!==void 0&&await this.#s.setConfig({...t.adaptiveConfig})}getParams(){return Rs(this.#r)}async#p(e){return new Promise(t=>setTimeout(t,e))}async waiteDelay(e){return this.#p(e)}#g(e,t,s,n){this.getLogger().notice(`${e} blocked method ${s}`,{requestId:t,method:s,wait:n,limiter:e}).catch(()=>{})}#b(e,t,s,n,i){this.getLogger().notice(`${e} blocked method ${s} | ${i} times`,{requestId:t,method:s,times:i,wait:n,limiter:e}).catch(()=>{})}#m(e,t,s,n,i,c){this.getLogger().error(`${e} recognized the ${s} error for the ${i} method`,{requestId:t,method:i,wait:c,limiter:e,error:{code:s,message:n}}).catch(()=>{})}#_(e,t,s,n,i){this.getLogger().error(`recognized the ${t} error for the ${n} method`,{requestId:e,method:n,wait:i,error:{code:t,message:s}}).catch(()=>{})}#y(e,t,s,n,i){this.getLogger().error(`client error ${i} (${t}) for the ${n} method is not retryable`,{requestId:e,method:n,status:i,error:{code:t,message:s}}).catch(()=>{})}}var Dp=Object.defineProperty,Lp=o((r,e)=>Dp(r,"name",{value:e,configurable:!0}),"i$g");const fr=class Yu{static{o(this,"e")}static{Lp(this,"VersionManager")}static create(){return new Yu}getAllApiVersions(){return[ee.v3,ee.v2]}isSupport(e,t){return!0}automaticallyObtainApiVersion(e){return ee.v2}automaticallyObtainApiVersionForBatch(e){return ee.v2}}.create();var Pp=Object.defineProperty,Mp=o((r,e)=>Pp(r,"name",{value:e,configurable:!0}),"r$d");const Fp=["log","debug","info","notice","warning","error","critical","alert","emergency"];function kc(r,e){if(r===null||typeof r!="object"){console.warn(`[b24jssdk] ${e}: the value passed to setLogger() is not an object. Expected an implementation of LoggerInterface.`);return}const t=Fp.filter(s=>typeof r[s]!="function");t.length>0&&console.warn(`[b24jssdk] ${e}: the logger passed to setLogger() is missing ${t.join(", ")}. LoggerInterface declares every level as Promise<void>; the SDK calls them fire-and-forget, so a missing or non-promise method raises a TypeError at the callsite.`)}o(kc,"warnOnNonPromiseLogger"),Mp(kc,"warnOnNonPromiseLogger");var xp=Object.defineProperty,$p=o((r,e)=>xp(r,"name",{value:e,configurable:!0}),"i$e");class ht{static{o(this,"AbstractAction")}static{$p(this,"AbstractAction")}_b24;_logger;constructor(e,t){this._b24=e,this._logger=t}_warnMisplacedOptions(e,t,s){if(!e)return;const n=t.filter(i=>Object.hasOwn(e,i));n.length!==0&&this._logger.warning(`[b24jssdk] ${n.join(", ")} passed at the top level ${n.length===1?"is":"are"} ignored \u2014 ${n.length===1?"it belongs":"they belong"} in \`${s}\`. Write \`${s}: { ${n.join(", ")} }\`.`).catch(()=>{})}}var jp=Object.defineProperty,Bp=o((r,e)=>jp(r,"name",{value:e,configurable:!0}),"r$c");class Up extends ht{static{o(this,"CallV2")}static{Bp(this,"CallV2")}async make(e){const t=e.params||{};return this._b24.getHttpClient(ee.v2).call(e.method,t,e.requestId)}}var Vp=Object.defineProperty,Ur=o((r,e)=>Vp(r,"name",{value:e,configurable:!0}),"t$9");const Ic=1e4;function Cs(r,e){if(e===void 0)return Ic;if(!Number.isInteger(e)||e<1)throw new D({code:"JSSDK_ACTION_INVALID_MAX_PAGES",description:`${r}: \`maxPages\` must be a positive integer \u2014 it is the number of pages the walk may read before it gives up. Omit it to use the default of ${Ic}.`,status:400});return e}o(Cs,"resolveMaxPages"),Ur(Cs,"resolveMaxPages");function Ns(r,e,t){return new D({code:"JSSDK_ACTION_MAX_PAGES_EXCEEDED",description:`${r}: stopped after ${t} pages of \`${e}\` without reaching the end of the data. Either the read is genuinely larger than the ceiling \u2014 raise \`maxPages\` \u2014 or the walk is not making progress, which happens when the page condition is not applied and the cursor repeats values whose order the SDK cannot judge (a cursor that demonstrably moves backwards is reported earlier, as JSSDK_ACTION_CURSOR_WENT_BACKWARDS). The eager helpers (callList / callTail) return the pages they did read, with this error attached \u2014 so check \`isSuccess\` rather than assuming a returned list is whole. A streaming helper (fetchList / fetchTail) has already yielded every page it read, and throws this instead.`,status:500})}o(Ns,"maxPagesExceededError"),Ur(Ns,"maxPagesExceededError");function Rc(r,e){return new D({code:"JSSDK_ACTION_ABORTED",description:`${r}: the walk over \`${e}\` was aborted through its \`signal\`. The eager helpers (callList / callTail) return the pages they did read, with this error attached; a streaming helper (fetchList / fetchTail) has already yielded every page it read, and throws this instead.`,status:400})}o(Rc,"walkAbortedError"),Ur(Rc,"walkAbortedError");function pr(r,e,t){if(r?.aborted===!0)throw Rc(e,t)}o(pr,"assertNotAborted"),Ur(pr,"assertNotAborted");const qp=new Set(["JSSDK_ACTION_MAX_PAGES_EXCEEDED","JSSDK_ACTION_ABORTED"]);function Ds(r){return r instanceof D&&qp.has(r.code)}o(Ds,"isWalkBoundsError"),Ur(Ds,"isWalkBoundsError");var Hp=Object.defineProperty,Cc=o((r,e)=>Hp(r,"name",{value:e,configurable:!0}),"r$b");function Ls(r,e){return new D({code:"JSSDK_ACTION_CURSOR_STALLED",description:`${r}: the cursor did not move \u2014 the server answered with the same page again, so this walk can never finish. ${e} Stopping instead of looping for ever. Note that a streaming helper (fetchList / fetchTail) has already yielded every page it read, including the repeated one, so a consumer that persisted them has to undo that.`,status:500})}o(Ls,"cursorStalledError"),Cc(Ls,"cursorStalledError");const gr="Check `idKey` \u2014 the id field as the response spells it \u2014 against `cursorIdKey`, the field name the request sorts and filters by. When the two differ, the page condition is written with a name the server does not match, and it is dropped: on `restApi:v2` `tasks.task.list` the response carries a lowercase `id` while the filter accepts an uppercase `ID`, so that walk needs `idKey: 'id', cursorIdKey: 'ID'`. The v3 method spells it lowercase both ways and needs no override.",Nc="Check `cursorField`: it must name the field the server actually pages by, it must be readable in the response (include it in `select`), and its values must advance from page to page \u2014 a block of rows sharing one value is enough to stall the walk, so prefer a unique field. With `order: 'DESC'`, check `initialValue` too.";function Ps(r,e){return new D({code:"JSSDK_ACTION_CURSOR_WENT_BACKWARDS",description:`${r}: the cursor moved backwards \u2014 the server answered with a page it had already passed, so this walk can never finish. ${e} A server that alternates between two pages produces exactly this, and the "did not move" check cannot see it: the value differs from the one just sent, it is simply one the walk had already used. Stopping instead of looping for ever. Note that a streaming helper (fetchList / fetchTail) has already yielded every page it read, so a consumer that persisted them has to undo that.`,status:500})}o(Ps,"cursorWentBackwardsError"),Cc(Ps,"cursorWentBackwardsError");var Wp=Object.defineProperty,ei=o((r,e)=>Wp(r,"name",{value:e,configurable:!0}),"n$d");const Dc=/^\d{4}-\d{2}-\d{2}([T ])\d{2}:\d{2}:\d{2}(?:\.\d+)?(Z|[+-]\d{2}:?\d{2})$/,Lc=/^\d+$/;function ti(r){return ri.test(r)?"DESC":"ASC"}o(ti,"resolveCursorDirection"),ei(ti,"resolveCursorDirection");const ri=/desc/i;function Pc(r,e){if(typeof r=="number"&&typeof e=="number")return Number.isFinite(r)&&Number.isFinite(e);if(typeof r=="string"&&typeof e=="string"){if(r.length!==e.length)return!1;if(Lc.test(r)&&Lc.test(e))return!0;const t=Dc.exec(r),s=Dc.exec(e);return t!==null&&s!==null&&t[1]===s[1]&&t[2]===s[2]}return!1}o(Pc,"c$a"),ei(Pc,"isComparableCursorPair");function Ms(r,e,t){return r===e?!1:Pc(r,e)?t==="DESC"?r<e:r>e:!0}o(Ms,"cursorProgressed"),ei(Ms,"cursorProgressed");var zp=Object.defineProperty,si=o((r,e)=>zp(r,"name",{value:e,configurable:!0}),"a$g");const Jp=["filter","order","start"],Kp={filter:"the `>id` cursor condition that advances the walk",order:"the ordering by the cursor field, which cursor paging depends on",start:"the `start: -1` that turns off the portal's own row counting"},Gp={filter:"its conditions are dropped and the request returns rows they should have excluded",order:"it is ignored \u2014 cursor paging must order by the cursor field",start:"it is ignored \u2014 the walker pages by cursor, not by offset"},Yp={filter:"The walk will not advance and will fail as stalled.",order:"Ordering is then unstable across pages, which cursor paging cannot survive.",start:"The walk still advances, but the portal resumes counting rows on every page and an offset skips rows."},Mc={filter:"Move the conditions into `filter`, which is merged with the page condition rather than replaced by it",order:"Remove it: cursor paging must order by `cursorIdKey`, and a lowercase `order` is stripped just the same",start:"Remove it: the walker pages by cursor and forces `start: -1`"};function Fs(r,e){return Object.prototype.hasOwnProperty.call(r,e)&&r[e]!==void 0}o(Fs,"c$9"),si(Fs,"isSentKey");function ni(r,e,t){ae.forcedLog(r,"warning",`${e}: ${t}`,{code:"JSSDK_ACTION_V2_SHADOWED_PARAM"}).catch(()=>{})}o(ni,"g$a"),si(ni,"warn");function ii(r,e,t){const s=[],n=Object.keys(e);for(const c of n){if(!Fs(e,c))continue;const a=c.toLowerCase();if(c===a||!Jp.includes(a)||!Fs(e,a))continue;const l=n.indexOf(c)>n.indexOf(a)?`\`${c}\` is sent after the \`${a}\` this walker pages with, and the portal keeps only the later of two top-level keys that differ by case \u2014 so \`${c}\` overwrites ${Kp[a]}. ${Yp[a]} ${Mc[a]}, and remove \`${c}\`; writing \`${a}\` while leaving \`${c}\` in place is what produces this.`:`\`${c}\` is not the key this walker pages with. It writes the lowercase \`${a}\`, the portal keeps only the later of two top-level keys that differ by case, and here the injected one is later \u2014 so \`${c}\` never takes effect and ${Gp[a]}. ${Mc[a]}.`;s.push({key:c,message:l}),ni(t,r,l)}const i=n.find(c=>c.toLowerCase()==="sort"&&Fs(e,c));if(i!==void 0){const c=`\`${i}\` makes this request fail. The walker replaces \`order\` with an object to page by the cursor, the portal folds that onto \`ORDER\`, and a method that takes \`SORT\` validates \`ORDER\` as a string \u2014 so the call throws ERROR_ARGUMENT ("Order must be a string"). Measured on \`user.get\`. Cursor paging fixes the ordering; drop \`SORT\` and narrow with lowercase \`filter\` instead.`;s.push({key:i,message:c}),ni(t,r,c)}return s}o(ii,"warnOnShadowedUppercaseParams"),si(ii,"warnOnShadowedUppercaseParams");var Zp=Object.defineProperty,Xp=o((r,e)=>Zp(r,"name",{value:e,configurable:!0}),"k$1");class Qp extends ht{static{o(this,"CallListV2")}static{Xp(this,"CallListV2")}async make(e){const t=new ke,s=e?.idKey??"ID",n=e?.cursorIdKey??s,i=e?.customKeyForResult??null,c=e?.params??{};"order"in c&&c.order&&this._logger.warning("callList.make: user-provided `order` parameter is ignored because cursor-based pagination requires ordering by cursorIdKey. Use `filter` to narrow results instead.").catch(()=>{});const a=`>${n}`,{order:l,...h}=c,u={...h,order:{[n]:"ASC"},filter:{...c.filter||{},[a]:0},start:-1};ii("callList.make",u,this._logger);let p=[],g=0;const f=Cs("callList.make",e?.maxPages);try{for(;;){pr(e?.signal,"callList.make",e.method);const d=await this._b24.actions.v2.call.make({method:e.method,params:u,requestId:e.requestId});if(!d.isSuccess){this._logger.error("callFastListMethod",{method:e.method,requestId:e.requestId,messages:d.getErrorMessages()}).catch(()=>{});for(const[S,T]of d.errors)t.addError(T,S);break}const y=d.getData();if(!y)break;const b=i===null?y.result:y.result[i];if(b.length===0)break;p=[...p,...b],g+=1,e.progress?.({pages:g,rows:p.length});const m=b.length<50,_=b[b.length-1],w=_?Number.parseInt(_[s],10):Number.NaN;if(Number.isFinite(w)){if(w===u.filter[a])throw Ls("callList.make",gr);if(!Ms(w,u.filter[a],"ASC"))throw Ps("callList.make",gr);if(m)break;if(u.filter[a]=w,g>=f)throw Ns("callList.make",e.method,f)}else{m||this._logger.warning(`callList.make: pagination stops here \u2014 no numeric id could be read from the returned items via idKey "${s}". Make sure idKey matches the id field in the response; if the sortable field name differs from it, also set cursorIdKey (e.g. idKey: 'id', cursorIdKey: 'ID').`).catch(()=>{});break}}}catch(d){if(Ds(d))t.addError(d);else throw d}return t.setData(p)}}var eg=Object.defineProperty,tg=o((r,e)=>eg(r,"name",{value:e,configurable:!0}),"y$6");class rg extends ht{static{o(this,"FetchListV2")}static{tg(this,"FetchListV2")}async*make(e){const t=e?.idKey??"ID",s=e?.cursorIdKey??t,n=e?.customKeyForResult??null,i=e?.params??{};"order"in i&&i.order&&this._logger.warning("fetchList.make: user-provided `order` parameter is ignored because cursor-based pagination requires ordering by cursorIdKey. Use `filter` to narrow results instead.").catch(()=>{});const c=`>${s}`,{order:a,...l}=i,h={...l,order:{[s]:"ASC"},filter:{...i.filter||{},[c]:0},start:-1};ii("fetchList.make",h,this._logger);let u=0;const p=Cs("fetchList.make",e?.maxPages);for(;;){pr(e?.signal,"fetchList.make",e.method);const g=await this._b24.actions.v2.call.make({method:e.method,params:h,requestId:e.requestId});if(!g.isSuccess)throw this._logger.error("fetchList.make",{method:e.method,requestId:e.requestId,messages:g.getErrorMessages()}).catch(()=>{}),new D({code:"JSSDK_CORE_B24_FETCH_LIST_METHOD_API_V2",description:`API Error: ${g.getErrorMessages().join("; ")}`,status:500});const f=g.getData();if(!f)break;const d=n===null?f.result:f.result[n];if(d.length===0)break;u+=1,yield d,pr(e?.signal,"fetchList.make",e.method);const y=d.length<50,b=d[d.length-1],m=b?Number.parseInt(b[t],10):Number.NaN;if(Number.isFinite(m)){if(m===h.filter[c])throw Ls("fetchList.make",gr);if(!Ms(m,h.filter[c],"ASC"))throw Ps("fetchList.make",gr);if(y)break;if(h.filter[c]=m,u>=p)throw Ns("fetchList.make",e.method,p)}else{y||this._logger.warning(`fetchList.make: pagination stops here \u2014 no numeric id could be read from the returned items via idKey "${t}". Make sure idKey matches the id field in the response; if the sortable field name differs from it, also set cursorIdKey (e.g. idKey: 'id', cursorIdKey: 'ID').`).catch(()=>{});break}}}}var sg=Object.defineProperty,ng=o((r,e)=>sg(r,"name",{value:e,configurable:!0}),"u$8");class xs extends ht{static{o(this,"AbstractBatch")}static{ng(this,"AbstractBatch")}_addBatchErrorsIfAny(e,t){if(!e.isSuccess)for(const[s,n]of e.errors)t.addError(n,s)}_processBatchResponse(e,t,s){const n=Array.isArray(t);return s.returnAjaxResult?this._createBatchResultWithAjax(e,n):this._createBatchResultSimple(e,n)}_createBatchResultWithAjax(e,t){return t?this._createBatchArrayResult(e):this._createBatchObjectResult(e)}_createBatchArrayResult(e){const t=new ke;this._addBatchErrorsIfAny(e,t);const s=[];for(const[n,i]of e.getData().result)s.push(i);return t.setData(s)}_createBatchObjectResult(e){const t=new ke;this._addBatchErrorsIfAny(e,t);const s={};for(const[n,i]of e.getData().result)s[n]=i;return t.setData(s)}_createBatchResultSimple(e,t){const s=new ke;return this._addBatchErrorsIfAny(e,s),s.setData(this._extractBatchSimpleData(e,t))}_extractBatchSimpleData(e,t){if(t){const s=[];for(const[n,i]of e.getData().result)i.isSuccess&&s.push(i.getData().result);return s}else{const s={};for(const[n,i]of e.getData().result)i.isSuccess&&(s[n]=i.getData().result);return s}}chunkArray(e,t=50){const s=[];for(let n=0;n<e.length;n+=t){const i=e.slice(n,n+t);s.push(i)}return s}}var ig=Object.defineProperty,og=o((r,e)=>ig(r,"name",{value:e,configurable:!0}),"e$8");class ag extends xs{static{o(this,"BatchV2")}static{og(this,"BatchV2")}async make(e){this._warnMisplacedOptions(e,["isHaltOnError","returnAjaxResult","requestId"],"options");const t={...e.options,apiVersion:ee.v2},s=await this._b24.getHttpClient(ee.v2).batch(e.calls,t);return this._processBatchResponse(s,e.calls,t)}}var cg=Object.defineProperty,lg=o((r,e)=>cg(r,"name",{value:e,configurable:!0}),"o$m");class ug extends xs{static{o(this,"BatchByChunkV2")}static{lg(this,"BatchByChunkV2")}async make(e){this._warnMisplacedOptions(e,["isHaltOnError","requestId"],"options");const t=50,s={...e.options,returnAjaxResult:!1,apiVersion:ee.v2},n=new ke,i=[],c=this.chunkArray(e.calls,t);for(const a of c){const l=await this._b24.getHttpClient(ee.v2).batch(a,s);l.isSuccess||this._addBatchErrorsIfAny(l,n);for(const[h,u]of l.getData().result)u.isSuccess&&i.push(u.getData().result)}return n.setData(i)}}var hg=Object.defineProperty,dg=o((r,e)=>hg(r,"name",{value:e,configurable:!0}),"r$a");const oi=Symbol("call_V2"),ai=Symbol("callList_V2"),ci=Symbol("fetchList_V2"),li=Symbol("batch_V2"),ui=Symbol("batchByChunk_V2");class fg{static{o(this,"ActionsManagerV2")}static{dg(this,"ActionsManagerV2")}_b24;_logger;_mapActions;constructor(e){this._b24=e,this._logger=ae.createNullLogger(),this._mapActions=new Map}setLogger(e){this._logger=e}getLogger(){return this._logger}get call(){return this._mapActions.has(oi)||this._mapActions.set(oi,new Up(this._b24,this._logger)),this._mapActions.get(oi)}get callList(){return this._mapActions.has(ai)||this._mapActions.set(ai,new Qp(this._b24,this._logger)),this._mapActions.get(ai)}get fetchList(){return this._mapActions.has(ci)||this._mapActions.set(ci,new rg(this._b24,this._logger)),this._mapActions.get(ci)}get batch(){return this._mapActions.has(li)||this._mapActions.set(li,new ag(this._b24,this._logger)),this._mapActions.get(li)}get batchByChunk(){return this._mapActions.has(ui)||this._mapActions.set(ui,new ug(this._b24,this._logger)),this._mapActions.get(ui)}}var pg=Object.defineProperty,gg=o((r,e)=>pg(r,"name",{value:e,configurable:!0}),"r$9");class mg extends ht{static{o(this,"CallV3")}static{gg(this,"CallV3")}async make(e){const t=e.params||{};return this._b24.getHttpClient(ee.v3).call(e.method,t,e.requestId,e.idempotencyKey===void 0?void 0:{idempotencyKey:e.idempotencyKey})}}var yg=Object.defineProperty,Wt=o((r,e)=>yg(r,"name",{value:e,configurable:!0}),"i$a");function hi(r,e){if(!(r===void 0||Array.isArray(r)))throw new D({code:"JSSDK_ACTION_V3_LIST_FILTER_NOT_ARRAY",description:di(r)?`${e}: \`filter\` must be an array here. A logic group is a valid v3 filter \u2014 the portal accepts one on its own \u2014 but this action appends its page condition to \`filter\` on every request, and only an array can be extended. Wrap it: filter: [FilterV3.or(...)].`:`${e}: \`filter\` must be the restApi:v3 array form, e.g. [['id', '>', 100]] or FilterV3.build(...). The restApi:v2 object dialect ({ '>id': 100 }) is not accepted by the portal: a filter element carrying none of type/logic/conditions/negative is read positionally, so a map keyed by an operator prefix matches no condition it knows.`,status:500})}o(hi,"assertArrayFilter"),Wt(hi,"assertArrayFilter");const bg=["type","logic","conditions","negative"];function di(r){return typeof r!="object"||r===null||Array.isArray(r)?!1:bg.some(e=>e in r)}o(di,"y$5"),Wt(di,"isPortalFilterGroup");const _g=32;function fi(r,e,t=_g){return $s(r,e,t,new WeakMap)}o(fi,"filterMentionsField"),Wt(fi,"filterMentionsField");function $s(r,e,t,s){if(t<=0)return!1;if(typeof r=="object"&&r!==null){const n=s.get(r);if(n!==void 0&&n>=t)return!1;s.set(r,t)}return Array.isArray(r)?typeof r[0]=="string"?r[0]===e:r.some(n=>$s(n,e,t-1,s)):typeof r=="object"&&r!==null&&"conditions"in r?$s(r.conditions,e,t-1,s):!1}o($s,"c$7"),Wt($s,"walkFilterForField");function pi(r,e){if(!(r===void 0||Array.isArray(r)||di(r)))throw new D({code:"JSSDK_ACTION_V3_TAIL_FILTER_INVALID",description:`${e}: \`filter\` must be the restApi:v3 array form, e.g. [['id', '>', 100]] or FilterV3.build(...), or a logic group from FilterV3.or() / and() / not(). The restApi:v2 object dialect ({ '>id': 100 }) is not accepted by the portal: a filter element carrying none of type/logic/conditions/negative is read positionally, so a map keyed by an operator prefix matches no condition it knows. Rejected here rather than one round trip later, where the server reports it in wording that never mentions the dialect.`,status:500})}o(pi,"assertTailFilter"),Wt(pi,"assertTailFilter");class Vr extends Error{static{o(this,"KeysetPaginationError")}static{Wt(this,"KeysetPaginationError")}errors;messages;constructor(e,t){super(t.join("; ")),this.name="KeysetPaginationError",this.errors=e,this.messages=t}}async function*qr(r,e,t){let s=t.initialCursor,n=0,i=0;const c=Cs(t.actionLabel,t.maxPages);for(;;){pr(t.signal,t.actionLabel,t.method);const a=await r.actions.v3.call.make({method:t.method,params:t.buildParams(s),requestId:t.requestId});if(!a.isSuccess)throw e.error(t.errorLabel,{method:t.method,requestId:t.requestId,messages:a.getErrorMessages()}).catch(()=>{}),new Vr(a.errors,a.getErrorMessages());const l=a.getData();if(!l)break;const h=l.result[t.customKeyForResult];if(!Array.isArray(h)||h.length===0)break;i+=1,yield h,pr(t.signal,t.actionLabel,t.method),n=Math.max(n,h.length);const u=h.length<n,p=h[h.length-1],g=p?t.readNextCursor(p):null;if(typeof g!="number"&&typeof g!="string"){u||e.warning(t.noCursorWarning).catch(()=>{});break}if(g===s)throw Ls(t.actionLabel,t.stalledCursorHint);if(!Ms(g,s,t.cursorDirection))throw Ps(t.actionLabel,t.stalledCursorHint);if(u)break;if(i>=c)throw Ns(t.actionLabel,t.method,c);s=g}}o(qr,"keysetPaginate"),Wt(qr,"keysetPaginate");var wg=Object.defineProperty,gi=o((r,e)=>wg(r,"name",{value:e,configurable:!0}),"i$9");class Sg extends ht{static{o(this,"CallListV3")}static{gi(this,"CallListV3")}async make(e){const t=e?.limit??50,s=new ke,n=e?.idKey??"id",i=e?.cursorIdKey??n,c=e?.customKeyForResult??null,a=e?.params??{};"order"in a&&a.order&&this._logger.warning("callList.make: user-provided `order` parameter is ignored because cursor-based pagination requires ordering by cursorIdKey. Use `filter` to narrow results instead.").catch(()=>{}),hi(a.filter,"callList.make");const{order:l,...h}=a,u={...h,order:{[i]:"ASC"},filter:[...a.filter??[]],pagination:{page:0,limit:t}},p=[];let g=0;try{for await(const f of qr(this._b24,this._logger,{method:e.method,requestId:e.requestId,customKeyForResult:c,initialCursor:0,buildParams:gi(d=>({...u,filter:[...u.filter,[i,">",d]]}),"buildParams"),readNextCursor:gi(d=>{const y=Number.parseInt(d[n],10);return Number.isFinite(y)?y:null},"readNextCursor"),noCursorWarning:`callList.make: pagination stops here \u2014 no numeric id could be read from the returned items via idKey "${n}". Make sure idKey matches the id field in the response; if the sortable field name differs from it, also set cursorIdKey (e.g. idKey: 'id', cursorIdKey: 'ID').`,errorLabel:"callFastListMethod",actionLabel:"callList.make",stalledCursorHint:gr,cursorDirection:"ASC",maxPages:e?.maxPages,signal:e?.signal})){for(const d of f)p.push(d);g+=1,e.progress?.({pages:g,rows:p.length})}}catch(f){if(f instanceof Vr)for(const[d,y]of f.errors)s.addError(y,d);else if(Ds(f))s.addError(f);else throw f}return s.setData(p)}}var vg=Object.defineProperty,mi=o((r,e)=>vg(r,"name",{value:e,configurable:!0}),"i$8");class Eg extends ht{static{o(this,"FetchListV3")}static{mi(this,"FetchListV3")}async*make(e){const t=e?.limit??50,s=e?.idKey??"id",n=e?.cursorIdKey??s,i=e?.customKeyForResult??null,c=e?.params??{};"order"in c&&c.order&&this._logger.warning("fetchList.make: user-provided `order` parameter is ignored because cursor-based pagination requires ordering by cursorIdKey. Use `filter` to narrow results instead.").catch(()=>{}),hi(c.filter,"fetchList.make");const{order:a,...l}=c,h={...l,order:{[n]:"ASC"},filter:[...c.filter??[]],pagination:{page:0,limit:t}};try{yield*qr(this._b24,this._logger,{method:e.method,requestId:e.requestId,customKeyForResult:i,initialCursor:0,buildParams:mi(u=>({...h,filter:[...h.filter,[n,">",u]]}),"buildParams"),readNextCursor:mi(u=>{const p=Number.parseInt(u[s],10);return Number.isFinite(p)?p:null},"readNextCursor"),noCursorWarning:`fetchList.make: pagination stops here \u2014 no numeric id could be read from the returned items via idKey "${s}". Make sure idKey matches the id field in the response; if the sortable field name differs from it, also set cursorIdKey (e.g. idKey: 'id', cursorIdKey: 'ID').`,errorLabel:"fetchList.make",actionLabel:"fetchList.make",stalledCursorHint:gr,cursorDirection:"ASC",maxPages:e?.maxPages,signal:e?.signal})}catch(u){throw u instanceof Vr?new D({code:"JSSDK_CORE_B24_FETCH_LIST_METHOD_API_V3",description:`API Error: ${u.messages.join("; ")}`,status:500}):u}}}var Og=Object.defineProperty,yi=o((r,e)=>Og(r,"name",{value:e,configurable:!0}),"l$g");class Tg extends ht{static{o(this,"CallTailV3")}static{yi(this,"CallTailV3")}async make(e){const t=e?.limit??50,s=new ke,n=e?.cursorField??"id",i=e?.order??"ASC",c=e?.customKeyForResult??"items",a=e?.params??{};if(pi(a.filter,"callTail.make"),ri.test(i)&&e?.initialValue===void 0)throw new D({code:"JSSDK_CORE_B24_CALL_TAIL_DESC_REQUIRES_INITIAL_VALUE",description:'callTail.make: order "DESC" requires an explicit `initialValue` (the server pages by `field < value`, so the default 0 returns nothing). Pass `initialValue` set to the type maximum / newest value.',status:500});fi(a.filter,n)&&this._logger.warning(`callTail.make: the cursor field "${n}" must not appear in \`filter\` \u2014 the server orders and pages by it and will reject a filter on the same field (INVALIDFILTEREXCEPTION). Remove it from \`filter\`.`).catch(()=>{});let l=a.select;Array.isArray(l)?l.includes(n)||(l=[...l,n]):n!=="id"&&this._logger.warning(`callTail.make: no \`select\` provided with a non-default cursorField "${n}" \u2014 make sure it is in the server's default field set, otherwise pass \`select\` including "${n}" so the cursor can advance.`).catch(()=>{});const{select:h,...u}=a,p=[];let g=0;try{for await(const f of qr(this._b24,this._logger,{method:e.method,requestId:e.requestId,customKeyForResult:c,initialCursor:e?.initialValue??0,buildParams:yi(d=>({...u,...l?{select:l}:{},cursor:{field:n,value:d,order:i,limit:t}}),"buildParams"),readNextCursor:yi(d=>d[n]??null,"readNextCursor"),noCursorWarning:`callTail.make: pagination stops here \u2014 no value could be read from the returned items via cursorField "${n}". Make sure cursorField matches a field present in the response (and in \`select\`).`,errorLabel:"callTailMethod",actionLabel:"callTail.make",stalledCursorHint:Nc,cursorDirection:ti(i),maxPages:e?.maxPages,signal:e?.signal})){for(const d of f)p.push(d);g+=1,e.progress?.({pages:g,rows:p.length})}}catch(f){if(f instanceof Vr)for(const[d,y]of f.errors)s.addError(y,d);else if(Ds(f))s.addError(f);else throw f}return s.setData(p)}}var Ag=Object.defineProperty,bi=o((r,e)=>Ag(r,"name",{value:e,configurable:!0}),"s$l");class kg extends ht{static{o(this,"FetchTailV3")}static{bi(this,"FetchTailV3")}async*make(e){const t=e?.limit??50,s=e?.cursorField??"id",n=e?.order??"ASC",i=e?.customKeyForResult??"items",c=e?.params??{};if(pi(c.filter,"fetchTail.make"),ri.test(n)&&e?.initialValue===void 0)throw new D({code:"JSSDK_CORE_B24_FETCH_TAIL_DESC_REQUIRES_INITIAL_VALUE",description:'fetchTail.make: order "DESC" requires an explicit `initialValue` (the server pages by `field < value`, so the default 0 returns nothing). Pass `initialValue` set to the type maximum / newest value.',status:500});fi(c.filter,s)&&this._logger.warning(`fetchTail.make: the cursor field "${s}" must not appear in \`filter\` \u2014 the server orders and pages by it and will reject a filter on the same field (INVALIDFILTEREXCEPTION). Remove it from \`filter\`.`).catch(()=>{});let a=c.select;Array.isArray(a)?a.includes(s)||(a=[...a,s]):s!=="id"&&this._logger.warning(`fetchTail.make: no \`select\` provided with a non-default cursorField "${s}" \u2014 make sure it is in the server's default field set, otherwise pass \`select\` including "${s}" so the cursor can advance.`).catch(()=>{});const{select:l,...h}=c;try{yield*qr(this._b24,this._logger,{method:e.method,requestId:e.requestId,customKeyForResult:i,initialCursor:e?.initialValue??0,buildParams:bi(u=>({...h,...a?{select:a}:{},cursor:{field:s,value:u,order:n,limit:t}}),"buildParams"),readNextCursor:bi(u=>u[s]??null,"readNextCursor"),noCursorWarning:`fetchTail.make: pagination stops here \u2014 no value could be read from the returned items via cursorField "${s}". Make sure cursorField matches a field present in the response (and in \`select\`).`,errorLabel:"fetchTailMethod",actionLabel:"fetchTail.make",stalledCursorHint:Nc,cursorDirection:ti(n),maxPages:e?.maxPages,signal:e?.signal})}catch(u){throw u instanceof Vr?new D({code:"JSSDK_CORE_B24_FETCH_TAIL_METHOD_API_V3",description:`API Error: ${u.messages.join("; ")}`,status:500}):u}}}var Ig=Object.defineProperty,Rg=o((r,e)=>Ig(r,"name",{value:e,configurable:!0}),"m$7");const Fc=["sum","avg","min","max","count","countDistinct"];class Cg extends ht{static{o(this,"AggregateV3")}static{Rg(this,"AggregateV3")}async make(e){const t=new ke,s=e?.select??{},n=Object.keys(s);let i=0;for(const u of n){if(!Fc.includes(u))throw new D({code:"JSSDK_AGGREGATE_V3_INVALID_FUNCTION",description:`AggregateV3: "${u}" is not an aggregate function \u2014 use one of ${Fc.join(" ")}.`,status:400});const p=s[u];if(!Array.isArray(p)&&(typeof p!="object"||p===null))throw new D({code:"JSSDK_AGGREGATE_V3_INVALID_SELECT",description:`AggregateV3: select.${u} must be a string[] (default alias) or a { field: alias } map.`,status:400});i+=Array.isArray(p)?p.length:Object.keys(p).length}if(i===0)throw new D({code:"JSSDK_AGGREGATE_V3_EMPTY_SELECT",description:"AggregateV3: `select` names no field to aggregate, e.g. { count: ['id'] }. The portal answers such a request with a 500 that says nothing, so it is refused here.",status:400});const c={select:s};e?.params?.filter&&(c.filter=e.params.filter);const a=await this._b24.actions.v3.call.make({method:e.method,params:c,requestId:e.requestId});if(!a.isSuccess){this._logger.error("aggregateMethod",{method:e.method,requestId:e.requestId,messages:a.getErrorMessages()}).catch(()=>{});for(const[u,p]of a.errors)t.addError(p,u);return t}const l=a.getData()?.result;let h;return l&&typeof l=="object"&&"result"in l?h=l.result??{}:l&&typeof l=="object"?(this._logger.warning(`aggregate.make: response has no nested 'result.result' envelope, which is what a portal was measured to send and what the v3 reference \xA77 specifies; falling back to the top-level 'result'. method=${e.method}`).catch(()=>{}),h=l):(this._logger.warning(`aggregate.make: response carried no usable 'result' object \u2014 returning empty buckets, which is not the same as an aggregate over no rows (that answers null per function). method=${e.method}`).catch(()=>{}),h={}),t.setData(h)}}var Ng=Object.defineProperty,Dg=o((r,e)=>Ng(r,"name",{value:e,configurable:!0}),"e$6");class Lg extends xs{static{o(this,"BatchV3")}static{Dg(this,"BatchV3")}async make(e){this._warnMisplacedOptions(e,["isHaltOnError","returnAjaxResult","requestId"],"options");const t={...e.options,apiVersion:ee.v3},s=await this._b24.getHttpClient(ee.v3).batch(e.calls,t);return this._processBatchResponse(s,e.calls,t)}}var Pg=Object.defineProperty,Mg=o((r,e)=>Pg(r,"name",{value:e,configurable:!0}),"o$k");class Fg extends xs{static{o(this,"BatchByChunkV3")}static{Mg(this,"BatchByChunkV3")}async make(e){this._warnMisplacedOptions(e,["isHaltOnError","requestId"],"options");const t=50,s={...e.options,returnAjaxResult:!1,apiVersion:ee.v3},n=new ke,i=[],c=this.chunkArray(e.calls,t);for(const a of c){const l=await this._b24.getHttpClient(ee.v3).batch(a,s);l.isSuccess||this._addBatchErrorsIfAny(l,n);for(const[h,u]of l.getData().result)u.isSuccess&&i.push(u.getData().result)}return n.setData(i)}}var xg=Object.defineProperty,$g=o((r,e)=>xg(r,"name",{value:e,configurable:!0}),"n$b");class Lt{static{o(this,"ParseRow")}static{$g(this,"ParseRow")}static getBatchCommand(e,t){if(e){if(typeof e=="object"&&"method"in e&&typeof e.method=="string")return{method:e.method,query:e.params??{},as:e.as??t.asDefaultValue,parallel:e.parallel??t.parallelDefaultValue};if(Array.isArray(e)&&e.length>0&&typeof e[0]=="string")return{method:e[0],query:e[1]??{},as:t.asDefaultValue,parallel:t.parallelDefaultValue}}const{parallelDefaultValue:s,asDefaultValue:n}=t,i=e&&typeof e=="object"?{keys:Object.keys(e).join(", "),...Array.isArray(e)?{length:e.length}:{method:typeof e.method=="string"?e.method:void 0}}:{type:typeof e};throw new D({code:"JSSDK_INTERACTION_BATCH_ROW_FAIL",description:`There were difficulties parsing the command for batch.
${JSON.stringify({row:i,options:{parallelDefaultValue:s,asDefaultValue:n}})}`,status:500})}static getMethodsFromCommands(e){const t=[],s={parallelDefaultValue:!1};return Array.isArray(e)?e.forEach(n=>{const i=Lt.getBatchCommand(n,s);t.push(i.method)}):Object.entries(e).forEach(([n,i])=>{const c=Lt.getBatchCommand(i,{...s,asDefaultValue:n});t.push(c.method)}),t}}var jg=Object.defineProperty,mr=o((r,e)=>jg(r,"name",{value:e,configurable:!0}),"l$f");const Bg=2e3,Ug=250,Vg=6e5,qg=2147483647;class Hg extends ht{static{o(this,"DeferredBatchV3")}static{mr(this,"DeferredBatchV3")}async make(e){const t=new ke;if(this.#s(e.calls),e.signal?.aborted)return t.addError(_i(),"base-error");const s=await this.add(e);if(!s.isSuccess)return this.#n(s,t);const n=s.getData(),i=n.id;this.#i(e.onStatus,n,i);const c=await this.#t(i,e,n.status);if(!c.isSuccess)return c.getData()?.status==="error"&&(this._logger.warning('deferredBatch: the job ended with status "error"',{id:i,errorMessage:c.getData()?.errorMessage}).catch(()=>{}),e.deleteAfter!==!1&&await this.#e(i)),this.#n(c,t);const a=await this.download(i);return a.isSuccess?(e.deleteAfter!==!1&&await this.#e(i),t.setData(a.getData())):this.#n(a,t)}async#e(e){const t=await this.delete(e);t.isSuccess||this._logger.warning("deferredBatch: the job could not be deleted",{id:e,errors:t.getErrorMessages()}).catch(()=>{})}async add(e){const t=this.#s(e.calls);return this.#r("rest.deferredbatch.add",{fields:{commands:t}},s=>s.item,e.requestId,e.idempotencyKey)}async get(e){return this.#r("rest.deferredbatch.get",{id:e},t=>t.item)}async list(){return this.#r("rest.deferredbatch.list",{},e=>Array.isArray(e)?e:Array.isArray(e.items)?e.items:void 0)}async waitFor(e,t={}){return this.#t(e,t,void 0)}async#t(e,t,s){const n=Math.min(qg,Math.max(Ug,xc(t.pollInterval,Bg))),i=Math.max(0,typeof t.timeout=="number"&&!Number.isNaN(t.timeout)?t.timeout:Vg),c=Date.now()+i,a=new ke;let l=s;for(;;){if(t.signal?.aborted)return a.addError(_i(e),"base-error");const h=await this.get(e);if(!h.isSuccess)return this.#n(h,a);const u=h.getData();if(u.status!==l&&(l=u.status,this.#i(t.onStatus,u,e)),u.status==="done")return a.setData(u);if(u.status==="error")return a.setData(u),a.addError(new D({code:"JSSDK_DEFERRED_BATCH_FAILED",description:`deferredBatch: job #${e} ended with status "error"; see the job's errorMessage (waitFor / get).`,status:500}),"base-error");if(Date.now()+n>c)return a.addError(new D({code:"JSSDK_DEFERRED_BATCH_TIMEOUT",description:`deferredBatch: job #${e} reached no final status within ${i} ms; it keeps running on the portal.`,status:408}),"base-error");await this.#o(n,t.signal)}}async getDownloadUrl(e){return this.#r("rest.deferredbatch.downloadresult",{id:e},t=>t.downloadUrl)}async download(e){const t=new ke,s=await this.getDownloadUrl(e);if(!s.isSuccess)return this.#n(s,t);let n;try{const i=await this._b24.getHttpClient(ee.v3).ajaxClient.get(s.getData(),{responseType:"arraybuffer",maxRedirects:0});if(!i.status)return t.addError(new D({code:"JSSDK_DEFERRED_BATCH_DOWNLOAD_FAILED",description:"deferredBatch: the result file could not be downloaded (no status: a refused redirect or a dropped connection).",status:0}),"base-error");n=i.data}catch(i){const c=Number(i?.response?.status??0);return t.addError(new D({code:"JSSDK_DEFERRED_BATCH_DOWNLOAD_FAILED",description:`deferredBatch: the result file could not be downloaded (HTTP ${c||"no response"}).`,status:c||500}),"base-error")}try{return t.setData(await this.decode(n))}catch(i){return t.addError(i instanceof Error?i:new Error(String(i)),"base-error")}}async decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),s=t.length>=2&&t[0]===31&&t[1]===139,n=new TextDecoder().decode(s?await $c(t):t);let i;try{i=JSON.parse(n)}catch{i=void 0}if(!Array.isArray(i))throw new D({code:"JSSDK_DEFERRED_BATCH_DECODE_FAILED",description:"deferredBatch: the result file is not a JSON array.",status:500});return i}async delete(e){return this.#r("rest.deferredbatch.delete",{id:e},()=>!0,void 0,void 0,!1)}#s(e){if(!Array.isArray(e)||e.length===0)throw new D({code:"JSSDK_DEFERRED_BATCH_EMPTY",description:"deferredBatch: `calls` must be a non-empty array of commands.",status:400});return e.map(t=>{const s=Lt.getBatchCommand(t,{parallelDefaultValue:!1});return{method:s.method,query:s.query??{}}})}async#r(e,t,s,n,i,c=!0){const a=new ke;let l;try{l=await this._b24.getHttpClient(ee.v3).call(e,t,n,i===void 0?void 0:{idempotencyKey:i})}catch(p){return a.addError(p instanceof Error?p:new Error(String(p)),"base-error")}if(!l.isSuccess)return this.#n(l,a);const h=l.getData()?.result,u=h==null&&c?void 0:s(h);return u==null?a.addError(new D({code:"JSSDK_DEFERRED_BATCH_UNEXPECTED_RESPONSE",description:`deferredBatch: ${e} answered without the expected data.`,status:500}),"base-error"):a.setData(u)}#i(e,t,s){const n=mr(i=>{this._logger.warning("deferredBatch: onStatus threw",{id:s,error:String(i)}).catch(()=>{})},"report");try{const i=e?.(t);i&&typeof i.then=="function"&&Promise.resolve(i).catch(n)}catch(i){n(i)}}#n(e,t){for(const[s,n]of e.errors)t.addError(n,s);return t}#o(e,t){return new Promise(s=>{if(t?.aborted){s();return}const n=setTimeout(i,e);function i(){clearTimeout(n),t?.removeEventListener("abort",i),s()}o(i,"t"),mr(i,"done"),t?.addEventListener("abort",i,{once:!0})})}}function _i(r){return new D({code:"JSSDK_DEFERRED_BATCH_ABORTED",description:r===void 0?"deferredBatch: aborted before anything was added.":`deferredBatch: waiting for job #${r} was aborted; it keeps running on the portal.`,status:499})}o(_i,"b"),mr(_i,"abortedError");function xc(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}o(xc,"_$1"),mr(xc,"finiteOr");async function $c(r){if(typeof DecompressionStream!="function")throw new D({code:"JSSDK_DEFERRED_BATCH_GZIP_UNSUPPORTED",description:"deferredBatch: this runtime has no DecompressionStream, so the gzip result file cannot be decoded. Use Node.js 18+ or a current browser.",status:500});try{const e=new Blob([r]).stream().pipeThrough(new DecompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}catch{throw new D({code:"JSSDK_DEFERRED_BATCH_DECODE_FAILED",description:"deferredBatch: the result file is not valid gzip.",status:500})}}o($c,"S$1"),mr($c,"gunzip");var Wg=Object.defineProperty,zg=o((r,e)=>Wg(r,"name",{value:e,configurable:!0}),"m$6");const wi=Symbol("call_V3"),Si=Symbol("callList_V3"),vi=Symbol("fetchList_V3"),Ei=Symbol("callTail_V3"),Oi=Symbol("fetchTail_V3"),Ti=Symbol("aggregate_V3"),Ai=Symbol("batch_V3"),ki=Symbol("batchByChunk_V3"),Ii=Symbol("deferredBatch_V3");class Jg{static{o(this,"ActionsManagerV3")}static{zg(this,"ActionsManagerV3")}_b24;_logger;_mapActions;constructor(e){this._b24=e,this._logger=ae.createNullLogger(),this._mapActions=new Map}setLogger(e){this._logger=e}getLogger(){return this._logger}get call(){return this._mapActions.has(wi)||this._mapActions.set(wi,new mg(this._b24,this._logger)),this._mapActions.get(wi)}get callList(){return this._mapActions.has(Si)||this._mapActions.set(Si,new Sg(this._b24,this._logger)),this._mapActions.get(Si)}get fetchList(){return this._mapActions.has(vi)||this._mapActions.set(vi,new Eg(this._b24,this._logger)),this._mapActions.get(vi)}get callTail(){return this._mapActions.has(Ei)||this._mapActions.set(Ei,new Tg(this._b24,this._logger)),this._mapActions.get(Ei)}get fetchTail(){return this._mapActions.has(Oi)||this._mapActions.set(Oi,new kg(this._b24,this._logger)),this._mapActions.get(Oi)}get aggregate(){return this._mapActions.has(Ti)||this._mapActions.set(Ti,new Cg(this._b24,this._logger)),this._mapActions.get(Ti)}get batch(){return this._mapActions.has(Ai)||this._mapActions.set(Ai,new Lg(this._b24,this._logger)),this._mapActions.get(Ai)}get batchByChunk(){return this._mapActions.has(ki)||this._mapActions.set(ki,new Fg(this._b24,this._logger)),this._mapActions.get(ki)}get deferredBatch(){return this._mapActions.has(Ii)||this._mapActions.set(Ii,new Hg(this._b24,this._logger)),this._mapActions.get(Ii)}}var Kg=Object.defineProperty,Gg=o((r,e)=>Kg(r,"name",{value:e,configurable:!0}),"s$j");const Ri=Symbol(ee.v2),Ci=Symbol(ee.v3);class Yg{static{o(this,"ActionsManager")}static{Gg(this,"ActionsManager")}_b24;_logger;_mapActions;constructor(e){this._b24=e,this._logger=ae.createNullLogger(),this._mapActions=new Map}setLogger(e){this._logger=e,this.v2.setLogger(this._logger),this.v3.setLogger(this._logger)}getLogger(){return this._logger}get v2(){return this._mapActions.has(Ri)||this._mapActions.set(Ri,new fg(this._b24)),this._mapActions.get(Ri)}get v3(){return this._mapActions.has(Ci)||this._mapActions.set(Ci,new Jg(this._b24)),this._mapActions.get(Ci)}}var Zg=Object.defineProperty,Xg=o((r,e)=>Zg(r,"name",{value:e,configurable:!0}),"o$h");class jc{static{o(this,"AbstractTool")}static{Xg(this,"AbstractTool")}_b24;_logger;constructor(e,t){this._b24=e,this._logger=t}}var Qg=Object.defineProperty,em=o((r,e)=>Qg(r,"name",{value:e,configurable:!0}),"r$7");class tm extends jc{static{o(this,"Ping")}static{em(this,"Ping")}async make(e){const t=Date.now();try{return await this._b24.actions.v2.call.make({method:"server.time",params:{},requestId:e?.requestId}),Date.now()-t}catch{return-1}}}var rm=Object.defineProperty,sm=o((r,e)=>rm(r,"name",{value:e,configurable:!0}),"s$h");class nm extends jc{static{o(this,"HealthCheck")}static{sm(this,"HealthCheck")}async make(e){try{return(await this._b24.actions.v2.call.make({method:"server.time",params:{},requestId:e?.requestId})).isSuccess}catch{return!1}}}var im=Object.defineProperty,om=o((r,e)=>im(r,"name",{value:e,configurable:!0}),"g$6");const Ni=Symbol("ping"),Di=Symbol("healthCheck");class am{static{o(this,"ToolsManager")}static{om(this,"ToolsManager")}_b24;_logger;_mapTools;constructor(e){this._b24=e,this._logger=ae.createNullLogger(),this._mapTools=new Map}setLogger(e){this._logger=e}getLogger(){return this._logger}get ping(){return this._mapTools.has(Ni)||this._mapTools.set(Ni,new tm(this._b24,this._logger)),this._mapTools.get(Ni)}get healthCheck(){return this._mapTools.has(Di)||this._mapTools.set(Di,new nm(this._b24,this._logger)),this._mapTools.get(Di)}}var cm=Object.defineProperty,lm=o((r,e)=>cm(r,"name",{value:e,configurable:!0}),"s$f");class js{static{o(this,"AbstractB24")}static{lm(this,"AbstractB24")}_isInit=!1;_httpV2=null;_httpV3=null;_logger;_actionsManager;_toolsManager;constructor(){this._isInit=!1,this._logger=ae.createNullLogger(),this._actionsManager=new Yg(this),this._toolsManager=new am(this)}get isInit(){return this._isInit}async init(){this._isInit=!0}destroy(){}get actions(){return this._ensureInitialized(),this._actionsManager}get tools(){return this._ensureInitialized(),this._toolsManager}getHttpClient(e){switch(this._ensureInitialized(),e){case ee.v3:if(this._httpV3===null)throw new D({code:"JSSDK_CORE_B24_HTTP_V3_NOT_INIT",description:"HttpV3 not init",status:500});return this._httpV3;case ee.v2:if(this._httpV2===null)throw new D({code:"JSSDK_CORE_B24_HTTP_V2_NOT_INIT",description:"HttpV2 not init",status:500});return this._httpV2}throw new D({code:"JSSDK_CORE_B24_API_WRONG",description:`Wrong Api Version ${e}`,status:500})}setHttpClient(e,t){switch(e){case ee.v3:this._httpV3=t;return;case ee.v2:this._httpV2=t;return}throw new D({code:"JSSDK_CORE_B24_API_WRONG",description:`Wrong Api Version ${e}`,status:500})}setLogger(e){kc(e,"B24 client"),this._logger=e,this._actionsManager.setLogger(this._logger),this._toolsManager.setLogger(this._logger),fr.getAllApiVersions().forEach(t=>{this.getHttpClient(t).setLogger(this._logger)})}getLogger(){return this._logger}async setRestrictionManagerParams(e){const t=fr.getAllApiVersions().map(s=>this.getHttpClient(s).setRestrictionManagerParams(e));await Promise.all(t)}_httpOptions=null;_getHttpOptions(){return this._httpOptions}_ensureInitialized(){if(!this._isInit)throw new D({code:"JSSDK_CORE_B24_NOT_INIT",description:"B24 not initialized",status:500})}}function Bc(r,e){return o(function(){return r.apply(e,arguments)},"wrap")}o(Bc,"bind");const{toString:um}=Object.prototype,{getPrototypeOf:Pt}=Object,{iterator:Hr,toStringTag:Uc}=Symbol,Wr=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),Vc=o(r=>typeof r=="string"&&(r==="__proto__"||r==="constructor"||r==="prototype"),"isUnsafeObjectKey"),qc=o((r,e,t)=>r===Object.prototype||!t&&e===null,"isPrototypeBoundary"),hm=o(r=>{if(!Object.isExtensible(r))return!1;const e=Object.getOwnPropertyNames(r);return Object.getOwnPropertySymbols&&e.push(...Object.getOwnPropertySymbols(r)),e.every(t=>{if(Vc(t))return!1;const s=Object.getOwnPropertyDescriptor(r,t);return!!s&&s.configurable&&s.writable===!0})},"isSafeAndFullyMutable"),zr=o((r,e)=>{let t=r;const s=[];for(;t!=null;){if(s.indexOf(t)!==-1)return!1;s.push(t);const n=Pt(t);if(qc(t,n,t===r))return!1;if(Wr(t,e))return!0;t=n}return!1},"hasOwnInPrototypeChain"),dm=o((r,e)=>r!=null&&zr(r,e)?r[e]:void 0,"getSafeProp"),fm=o(r=>{if(r==null||typeof r!="object"&&typeof r!="function")return r;const e=Pt(r);if(e===null&&hm(r))return r;const t=Object.create(null),s=Object.create(null),n=[];let i=r;for(;i!=null&&n.indexOf(i)===-1;){n.push(i);const c=i===r?e:Pt(i);if(qc(i,c,i===r))break;const a=Object.getOwnPropertyNames(i);Object.getOwnPropertySymbols&&a.push(...Object.getOwnPropertySymbols(i));for(const l of a)Vc(l)||Wr(s,l)||(t[l]=r[l],s[l]=!0);i=c}return t},"toSafeFlatObject"),Li=(r=>e=>{const t=um.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),rt=o(r=>(r=r.toLowerCase(),e=>Li(e)===r),"kindOfTest"),Bs=o(r=>e=>typeof e===r,"typeOfTest"),{isArray:zt}=Array,Jt=Bs("undefined");function yr(r){return r!==null&&!Jt(r)&&r.constructor!==null&&!Jt(r.constructor)&&ze(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}o(yr,"isBuffer$1");const Hc=rt("ArrayBuffer");function pm(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&Hc(r.buffer),e}o(pm,"isArrayBufferView");const gm=Bs("string"),ze=Bs("function"),Wc=Bs("number"),br=o(r=>r!==null&&typeof r=="object","isObject"),mm=o(r=>r===!0||r===!1,"isBoolean"),Us=o(r=>{if(!br(r))return!1;const e=Pt(r);return(e===null||e===Object.prototype||Pt(e)===null)&&!zr(r,Uc)&&!zr(r,Hr)},"isPlainObject"),ym=o(r=>{if(!br(r)||yr(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},"isEmptyObject"),bm=rt("Date"),_m=rt("File"),wm=o(r=>!!(r&&typeof r.uri<"u"),"isReactNativeBlob"),Sm=o(r=>r&&typeof r.getParts<"u","isReactNative"),vm=rt("Blob"),Em=rt("FileList"),Om=rt("Set"),Tm=o(r=>br(r)&&ze(r.pipe),"isStream");function Am(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}o(Am,"getGlobal");const zc=Am(),Jc=typeof zc.FormData<"u"?zc.FormData:void 0,km=o(r=>{if(!r)return!1;if(Jc&&r instanceof Jc)return!0;const e=Pt(r);if(!e||e===Object.prototype||!ze(r.append))return!1;const t=Li(r);return t==="formdata"||t==="object"&&ze(r.toString)&&r.toString()==="[object FormData]"},"isFormData"),Im=rt("URLSearchParams"),[Rm,Cm,Nm,Dm]=["ReadableStream","Request","Response","Headers"].map(rt),Lm=o(r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),"trim");function Jr(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let s,n;if(typeof r!="object"&&(r=[r]),zt(r))for(s=0,n=r.length;s<n;s++)e.call(null,r[s],s,r);else{if(yr(r))return;const i=t?Object.getOwnPropertyNames(r):Object.keys(r),c=i.length;let a;for(s=0;s<c;s++)a=i[s],e.call(null,r[a],a,r)}}o(Jr,"forEach");function Kc(r,e){if(yr(r))return null;e=e.toLowerCase();const t=Object.keys(r);let s=t.length,n;for(;s-- >0;)if(n=t[s],e===n.toLowerCase())return n;return null}o(Kc,"findKey");const Kt=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Gc=o(r=>!Jt(r)&&r!==Kt,"isContextDefined");function Pi(...r){const{caseless:e,skipUndefined:t}=Gc(this)&&this||{},s={},n=o((i,c)=>{if(c==="__proto__"||c==="constructor"||c==="prototype")return;const a=e&&typeof c=="string"&&Kc(s,c)||c,l=Wr(s,a)?s[a]:void 0;Us(l)&&Us(i)?s[a]=Pi(l,i):Us(i)?s[a]=Pi({},i):zt(i)?s[a]=i.slice():(!t||!Jt(i))&&(s[a]=i)},"assignValue");for(let i=0,c=r.length;i<c;i++){const a=r[i];if(!a||yr(a)||(Jr(a,n),typeof a!="object"||zt(a)))continue;const l=Object.getOwnPropertySymbols(a);for(let h=0;h<l.length;h++){const u=l[h];Wm.call(a,u)&&n(a[u],u)}}return s}o(Pi,"merge");const Pm=o((r,e,t,{allOwnKeys:s}={})=>(Jr(e,(n,i)=>{t&&ze(n)?Object.defineProperty(r,i,{__proto__:null,value:Bc(n,t),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(r,i,{__proto__:null,value:n,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:s}),r),"extend"),Mm=o(r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),"stripBOM"),Fm=o((r,e,t,s)=>{r.prototype=Object.create(e.prototype,s),Object.defineProperty(r.prototype,"constructor",{__proto__:null,value:r,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(r,"super",{__proto__:null,value:e.prototype}),t&&Object.assign(r.prototype,t)},"inherits"),xm=o((r,e,t,s)=>{let n,i,c;const a={};if(e=e||{},r==null)return e;do{for(n=Object.getOwnPropertyNames(r),i=n.length;i-- >0;)c=n[i],(!s||s(c,r,e))&&!a[c]&&(e[c]=r[c],a[c]=!0);r=t!==!1&&Pt(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},"toFlatObject"),$m=o((r,e,t)=>{r=String(r),(t===void 0||t>r.length)&&(t=r.length),t-=e.length;const s=r.indexOf(e,t);return s!==-1&&s===t},"endsWith"),jm=o(r=>{if(!r)return null;if(zt(r))return r;let e=r.length;if(!Wc(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},"toArray"),Bm=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&Pt(Uint8Array)),Um=o((r,e)=>{const s=(r&&r[Hr]).call(r);let n;for(;(n=s.next())&&!n.done;){const i=n.value;e.call(r,i[0],i[1])}},"forEachEntry"),Vm=o((r,e)=>{let t;const s=[];for(;(t=r.exec(e))!==null;)s.push(t);return s},"matchAll"),qm=rt("HTMLFormElement"),Hm=o(r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,o(function(t,s,n){return s.toUpperCase()+n},"replacer")),"toCamelCase"),{propertyIsEnumerable:Wm}=Object.prototype,zm=rt("RegExp"),Yc=o((r,e)=>{const t=Object.getOwnPropertyDescriptors(r),s={};Jr(t,(n,i)=>{let c;(c=e(n,i,r))!==!1&&(s[i]=c||n)}),Object.defineProperties(r,s)},"reduceDescriptors"),Jm=o(r=>{Yc(r,(e,t)=>{if(ze(r)&&["arguments","caller","callee"].includes(t))return!1;const s=r[t];if(ze(s)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},"freezeMethods"),Km=o((r,e)=>{const t={},s=o(n=>{n.forEach(i=>{t[i]=!0})},"define");return zt(r)?s(r):s(String(r).split(e)),t},"toObjectSet"),Gm=o(()=>{},"noop"),Ym=o((r,e)=>r!=null&&Number.isFinite(r=+r)?r:e,"toFiniteNumber");function Zm(r){return!!(r&&ze(r.append)&&r[Uc]==="FormData"&&r[Hr])}o(Zm,"isSpecCompliantForm");const Xm=o(r=>{const e=new WeakSet,t=o(s=>{if(br(s)){if(e.has(s))return;if(yr(s))return s;if(!("toJSON"in s)){e.add(s);let n;if(Om(s)){n=[];for(const i of s){const c=t(i);!Jt(c)&&n.push(c)}}else n=zt(s)?[]:{},Jr(s,(i,c)=>{const a=t(i);!Jt(a)&&(n[c]=a)});return e.delete(s),n}}return s},"visit");return t(r)},"toJSONObject"),Qm=rt("AsyncFunction"),ey=o(r=>r&&(br(r)||ze(r))&&ze(r.then)&&ze(r.catch),"isThenable"),Zc=((r,e)=>r?setImmediate:e?((t,s)=>(Kt.addEventListener("message",({source:n,data:i})=>{n===Kt&&i===t&&s.length&&s.shift()()},!1),n=>{s.push(n),Kt.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",ze(Kt.postMessage)),ty=typeof queueMicrotask<"u"?queueMicrotask.bind(Kt):typeof process<"u"&&process.nextTick||Zc,Xc=o(r=>r!=null&&ze(r[Hr]),"isIterable"),E={isArray:zt,isArrayBuffer:Hc,isBuffer:yr,isFormData:km,isArrayBufferView:pm,isString:gm,isNumber:Wc,isBoolean:mm,isObject:br,isPlainObject:Us,isEmptyObject:ym,isReadableStream:Rm,isRequest:Cm,isResponse:Nm,isHeaders:Dm,isUndefined:Jt,isDate:bm,isFile:_m,isReactNativeBlob:wm,isReactNative:Sm,isBlob:vm,isRegExp:zm,isFunction:ze,isStream:Tm,isURLSearchParams:Im,isTypedArray:Bm,isFileList:Em,forEach:Jr,merge:Pi,extend:Pm,trim:Lm,stripBOM:Mm,inherits:Fm,toFlatObject:xm,kindOf:Li,kindOfTest:rt,endsWith:$m,toArray:jm,forEachEntry:Um,matchAll:Vm,isHTMLForm:qm,hasOwnProperty:Wr,hasOwnProp:Wr,hasOwnInPrototypeChain:zr,getSafeProp:dm,toSafeFlatObject:fm,reduceDescriptors:Yc,freezeMethods:Jm,toObjectSet:Km,toCamelCase:Hm,noop:Gm,toFiniteNumber:Ym,findKey:Kc,global:Kt,isContextDefined:Gc,isSpecCompliantForm:Zm,toJSONObject:Xm,isAsyncFn:Qm,isThenable:ey,setImmediate:Zc,asap:ty,isIterable:Xc,isSafeIterable:o(r=>r!=null&&zr(r,Hr)&&Xc(r),"isSafeIterable")},ry=E.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),sy=o(r=>{const e={};let t,s,n;return r&&r.split(`
`).forEach(o(function(c){n=c.indexOf(":"),t=c.substring(0,n).trim().toLowerCase(),s=c.substring(n+1).trim();const a=E.hasOwnProp(e,t);!t||a&&E.hasOwnProp(ry,t)||(t==="set-cookie"?a?e[t].push(s):e[t]=[s]:e[t]=a?e[t]+", "+s:s)},"parser")),e},"parseHeaders");function ny(r){let e=0,t=r.length;for(;e<t;){const s=r.charCodeAt(e);if(s!==9&&s!==32)break;e+=1}for(;t>e;){const s=r.charCodeAt(t-1);if(s!==9&&s!==32)break;t-=1}return e===0&&t===r.length?r:r.slice(e,t)}o(ny,"trimSPorHTAB");const iy=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),oy=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function Mi(r,e){return E.isArray(r)?r.map(t=>Mi(t,e)):ny(String(r).replace(e,""))}o(Mi,"sanitizeValue");const ay=o(r=>Mi(r,iy),"sanitizeHeaderValue"),cy=o(r=>Mi(r,oy),"sanitizeByteStringHeaderValue");function Qc(r){const e=Object.create(null);return E.forEach(r.toJSON(),(t,s)=>{e[s]=cy(t)}),e}o(Qc,"toByteStringHeaderObject");const el=Symbol("internals");function Kr(r){return r&&String(r).trim().toLowerCase()}o(Kr,"normalizeHeader");function Vs(r){return r===!1||r==null?r:E.isArray(r)?r.map(Vs):ay(String(r))}o(Vs,"normalizeValue");function ly(r){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=t.exec(r);)e[s[1]]=s[2];return e}o(ly,"parseTokens");const uy=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function Fi(r){let e=0,t=r.length;for(;e<t;){const s=r.charCodeAt(e);if(s!==9&&s!==32)break;e+=1}for(;t>e;){const s=r.charCodeAt(t-1);if(s!==9&&s!==32)break;t-=1}return e===0&&t===r.length?r:r.slice(e,t)}o(Fi,"trimOWS");function hy(r){const e=r.length-1;if(e<1||r.charCodeAt(0)!==34||r.charCodeAt(e)!==34)return r;let t="";for(let s=1;s<e;s++){const n=r.charCodeAt(s);if(n===34||n===92&&(s+=1,s>=e))return r;t+=r[s]}return t}o(hy,"decodeQuotedString");function dy(r){const e=Object.create(null),t=String(r);let s=0,n=!1,i=!1;function c(a){const l=Fi(t.slice(s,a)),h=l.indexOf("=");if(h<1)return;const u=Fi(l.slice(0,h));if(!uy.test(u))return;const p=u.toLowerCase();if(p==="__proto__"||p==="constructor"||p==="prototype")return;const g=Fi(l.slice(h+1));e[p]=hy(g)}o(c,"parseParameter");for(let a=0;a<t.length;a++){const l=t.charCodeAt(a);n?i?i=!1:l===92?i=!0:l===34&&(n=!1):l===34?n=!0:(l===44||l===59)&&(c(a),s=a+1)}return c(t.length),e}o(dy,"parseParameters");const fy=o(r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim()),"isValidHeaderName");function xi(r,e,t,s,n){if(E.isFunction(s))return s.call(this,e,t);if(n&&(e=t),!!E.isString(e)){if(E.isString(s))return e.indexOf(s)!==-1;if(E.isRegExp(s))return s.test(e)}}o(xi,"matchHeaderValue");function py(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,s)=>t.toUpperCase()+s)}o(py,"formatHeader");function gy(r,e){const t=E.toCamelCase(" "+e);["get","set","has"].forEach(s=>{Object.defineProperty(r,s+t,{__proto__:null,value:o(function(n,i,c){return this[s].call(this,e,n,i,c)},"value"),configurable:!0})})}o(gy,"buildAccessors");let je=class{static{o(this,"AxiosHeaders")}constructor(e){e&&this.set(e)}set(e,t,s){const n=this;function i(a,l,h){const u=Kr(l);if(!u)return;const p=E.findKey(n,u);(!p||n[p]===void 0||h===!0||h===void 0&&n[p]!==!1)&&(n[p||l]=Vs(a))}o(i,"setHeader");const c=o((a,l)=>E.forEach(a,(h,u)=>i(h,u,l)),"setHeaders");if(E.isPlainObject(e)||e instanceof this.constructor)c(e,t);else if(E.isString(e)&&(e=e.trim())&&!fy(e))c(sy(e),t);else if(E.isObject(e)&&E.isSafeIterable(e)){let a=Object.create(null),l,h;for(const u of e){if(!E.isArray(u))throw new TypeError("Object iterator must return a key-value pair");h=u[0],E.hasOwnProp(a,h)?(l=a[h],a[h]=E.isArray(l)?[...l,u[1]]:[l,u[1]]):a[h]=u[1]}c(a,t)}else e!=null&&i(t,e,s);return this}get(e,t){if(e=Kr(e),e){const s=E.findKey(this,e);if(s){const n=this[s];if(!t)return n;if(t===!0)return ly(n);if(E.isFunction(t))return t.call(this,n,s);if(E.isRegExp(t))return t.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Kr(e),e){const s=E.findKey(this,e);return!!(s&&this[s]!==void 0&&(!t||xi(this,this[s],s,t)))}return!1}delete(e,t){const s=this;let n=!1;function i(c){if(c=Kr(c),c){const a=E.findKey(s,c);a&&(!t||xi(s,s[a],a,t))&&(delete s[a],n=!0)}}return o(i,"deleteHeader"),E.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let s=t.length,n=!1;for(;s--;){const i=t[s];(!e||xi(this,this[i],i,e,!0))&&(delete this[i],n=!0)}return n}normalize(e){const t=this,s={};return E.forEach(this,(n,i)=>{const c=E.findKey(s,i);if(c){t[c]=Vs(n),delete t[i];return}const a=e?py(i):String(i).trim();a!==i&&delete t[i],t[a]=Vs(n),s[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return E.forEach(this,(s,n)=>{s!=null&&s!==!1&&(t[n]=e&&E.isArray(s)?s.join(", "):s)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(`
`)}getSetCookie(){const e=this.get("set-cookie");return E.isArray(e)?e:e==null||e===!1?[]:[e]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static parseParameters(e){return dy(e)}static concat(e,...t){const s=new this(e);return t.forEach(n=>s.set(n)),s}static accessor(e){const s=(this[el]=this[el]={accessors:{}}).accessors,n=this.prototype;function i(c){const a=Kr(c);s[a]||(gy(n,c),s[a]=!0)}return o(i,"defineAccessor"),E.isArray(e)?e.forEach(i):i(e),this}};je.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),E.reduceDescriptors(je.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:o(()=>r,"get"),set(s){this[t]=s}}}),E.freezeMethods(je);const qs="[REDACTED ****]";function my(r){if(E.hasOwnProp(r,"toJSON"))return!0;let e=Object.getPrototypeOf(r);for(;e&&e!==Object.prototype;){if(E.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}o(my,"hasOwnOrPrototypeToJSON");function yy(r,e){const t=new Set(e.map(i=>String(i).toLowerCase())),s=[],n=o(i=>{if(i===null||typeof i!="object"||E.isBuffer(i))return i;if(s.indexOf(i)!==-1)return;i instanceof je&&(i=i.toJSON()),s.push(i);let c;if(E.isArray(i))c=[],i.forEach((a,l)=>{const h=n(a);E.isUndefined(h)||(c[l]=h)});else{if(!E.isPlainObject(i)&&my(i))return s.pop(),i;c=Object.create(null);for(const[a,l]of Object.entries(i)){const h=t.has(a.toLowerCase())?qs:n(l);E.isUndefined(h)||(c[a]=h)}}return s.pop(),c},"visit");return n(r)}o(yy,"redactConfig");function tl(r){try{return String(r)}catch{return""}}o(tl,"stringifySafely$1");function by(r){return r.errors.map(t=>{try{return t&&t.message?tl(t.message):tl(t)}catch{return""}}).filter(Boolean).join("; ")||r.name||"AggregateError"}o(by,"aggregateErrorMessage");let P=class Zu extends Error{static{o(this,"AxiosError")}static from(e,t,s,n,i,c){let a=e.message;!a&&E.isArray(e.errors)&&e.errors.length&&(a=by(e));const l=new Zu(a,t||e.code,s,n,i);return Object.defineProperty(l,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),l.name=e.name,e.status!=null&&l.status==null&&(l.status=e.status),c&&Object.assign(l,c),l}constructor(e,t,s,n,i){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),s&&(this.config=s),n&&(this.request=n),i&&(this.response=i,this.status=i.status)}toJSON(){const e=this.config,t=e&&E.hasOwnProp(e,"redact")?e.redact:void 0,s=E.isArray(t)&&t.length>0?yy(e,t):E.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:s,code:this.code,status:this.status}}};P.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",P.ERR_BAD_OPTION="ERR_BAD_OPTION",P.ECONNABORTED="ECONNABORTED",P.ETIMEDOUT="ETIMEDOUT",P.ECONNREFUSED="ECONNREFUSED",P.ERR_NETWORK="ERR_NETWORK",P.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",P.ERR_DEPRECATED="ERR_DEPRECATED",P.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",P.ERR_BAD_REQUEST="ERR_BAD_REQUEST",P.ERR_CANCELED="ERR_CANCELED",P.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",P.ERR_INVALID_URL="ERR_INVALID_URL",P.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const _y=null,rl=100;function $i(r){return E.isPlainObject(r)||E.isArray(r)}o($i,"isVisitable");function sl(r){return E.endsWith(r,"[]")?r.slice(0,-2):r}o(sl,"removeBrackets");function ji(r,e,t){return r?r.concat(e).map(o(function(n,i){return n=sl(n),!t&&i?"["+n+"]":n},"each")).join(t?".":""):e}o(ji,"renderKey");function wy(r){return E.isArray(r)&&!r.some($i)}o(wy,"isFlatArray");const Sy=E.toFlatObject(E,{},null,o(function(e){return/^is[A-Z]/.test(e)},"filter"));function Hs(r,e,t){if(!E.isObject(r))throw new TypeError("target must be an object");e=e||new FormData;const s=o((_,w)=>{const S=E.getSafeProp(t,_);return E.isUndefined(S)?w:S},"option"),n=s("metaTokens",!0),i=s("visitor")||y,c=s("dots",!1),a=s("indexes",!1),l=s("Blob")||typeof Blob<"u"&&Blob,h=s("maxDepth",rl),u=l&&E.isSpecCompliantForm(e),p=[];if(!E.isFunction(i))throw new TypeError("visitor must be a function");function g(_){if(_===null)return"";if(E.isDate(_))return _.toISOString();if(E.isBoolean(_))return _.toString();if(!u&&E.isBlob(_))throw new P("Blob is not supported. Use a Buffer instead.");if(E.isArrayBuffer(_)||E.isTypedArray(_)){if(u&&typeof l=="function")return new l([_]);throw new P("Blob is not supported. Use a Buffer instead.",P.ERR_NOT_SUPPORT)}return _}o(g,"convertValue");function f(_){if(_>h)throw new P("Object is too deeply nested ("+_+" levels). Max depth: "+h,P.ERR_FORM_DATA_DEPTH_EXCEEDED)}o(f,"throwIfMaxDepthExceeded");function d(_,w){if(h===1/0)return JSON.stringify(_);const S=[];return JSON.stringify(_,o(function(v,A){if(!E.isObject(A))return A;for(;S.length&&S[S.length-1]!==this;)S.pop();return S.push(A),f(w+S.length-1),A},"limitDepth"))}o(d,"stringifyWithDepthLimit");function y(_,w,S){let T=_;if(E.isReactNative(e)&&E.isReactNativeBlob(_))return e.append(ji(S,w,c),g(_)),!1;if(_&&!S&&typeof _=="object"){if(E.endsWith(w,"{}"))w=n?w:w.slice(0,-2),_=d(_,1);else if(E.isArray(_)&&wy(_)||(E.isFileList(_)||E.endsWith(w,"[]"))&&(T=E.toArray(_)))return w=sl(w),T.forEach(o(function(A,O){!(E.isUndefined(A)||A===null)&&e.append(a===!0?ji([w],O,c):a===null?w:w+"[]",g(A))},"each")),!1}return $i(_)?!0:(e.append(ji(S,w,c),g(_)),!1)}o(y,"defaultVisitor");const b=Object.assign(Sy,{defaultVisitor:y,convertValue:g,isVisitable:$i});function m(_,w,S=0){if(!E.isUndefined(_)){if(f(S),p.indexOf(_)!==-1)throw new Error("Circular reference detected in "+w.join("."));p.push(_),E.forEach(_,o(function(v,A){(!(E.isUndefined(v)||v===null)&&i.call(e,v,E.isString(A)?A.trim():A,w,b))===!0&&m(v,w?w.concat(A):[A],S+1)},"each")),p.pop()}}if(o(m,"build"),!E.isObject(r))throw new TypeError("data must be an object");return m(r),e}o(Hs,"toFormData$1");function nl(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(r).replace(/[!'()~]|%20/g,o(function(s){return e[s]},"replacer"))}o(nl,"encode$2");function Bi(r,e){this._pairs=[],r&&Hs(r,this,e)}o(Bi,"AxiosURLSearchParams");const il=Bi.prototype;il.append=o(function(e,t){this._pairs.push([e,t])},"append"),il.toString=o(function(e){const t=e?s=>e.call(this,s,nl):nl;return this._pairs.map(o(function(n){return t(n[0])+"="+t(n[1])},"each"),"").join("&")},"toString");function vy(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}o(vy,"encode$1");function ol(r,e,t){if(!e)return r;r=r||"";const s=E.isFunction(t)?{serialize:t}:t,n=E.getSafeProp(s,"encode")||vy,i=E.getSafeProp(s,"serialize");let c;if(i?c=i(e,s):c=E.isURLSearchParams(e)?e.toString():new Bi(e,s).toString(n),c){const a=r.indexOf("#");a!==-1&&(r=r.slice(0,a)),r+=(r.indexOf("?")===-1?"?":"&")+c}return r}o(ol,"buildURL");const Gr=Symbol("internals");function al(r){return r?r.length:0}o(al,"countHandlers");function cl(r){if(r)for(;r.length&&r[r.length-1]===null;)r.pop()}o(cl,"trimHandlers");function Yr(r,e){const t=r.handlers,s=al(t);t!==e.handlersRef?(e.handlersRef=t,e.handlerEntries.clear()):s!==e.handlersLength&&(s?e.handlerEntries.forEach(o(function(i,c){t[i.index]!==i.handler&&e.handlerEntries.delete(c)},"removeStaleEntry")):e.handlerEntries.clear()),e.handlersLength=s}o(Yr,"syncHandlerEntries");class ll{static{o(this,"InterceptorManager")}constructor(){this.handlers=[],this[Gr]={handlersRef:this.handlers,handlersLength:this.handlers.length,handlerEntries:new Map,iterationDepth:0,nextId:0}}use(e,t,s){const n={fulfilled:e,rejected:t,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null},i=this[Gr];this.handlers==null&&(this.handlers=[]),Yr(this,i);const c=i.nextId++;return this.handlers.push(n),i.handlerEntries.set(c,{handler:n,index:this.handlers.length-1}),i.handlersLength=this.handlers.length,c}eject(e){const t=this[Gr];Yr(this,t);const s=t.handlerEntries.get(e);if(s){if(t.handlerEntries.delete(e),this.handlers[s.index]!==s.handler)return;this.handlers[s.index]=null,t.iterationDepth||(cl(this.handlers),t.handlersLength=this.handlers.length)}}clear(){this.handlers&&(this.handlers=[],Yr(this,this[Gr]))}forEach(e){const t=this[Gr];Yr(this,t),t.iterationDepth++;try{E.forEach(this.handlers,o(function(n){n!==null&&e(n)},"forEachHandler"))}finally{--t.iterationDepth||(Yr(this,t),cl(this.handlers),t.handlersLength=al(this.handlers))}}}const Ui={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},Ey={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:Bi,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Vi=typeof window<"u"&&typeof document<"u",qi=typeof navigator=="object"&&navigator||void 0,Oy=Vi&&(!qi||["ReactNative","NativeScript","NS"].indexOf(qi.product)<0),Ty=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Ay=Vi&&window.location.href||"http://localhost",Ne={...{__proto__:null,hasBrowserEnv:Vi,hasStandardBrowserEnv:Oy,hasStandardBrowserWebWorkerEnv:Ty,navigator:qi,origin:Ay},...Ey};function ky(r,e){return Hs(r,new Ne.classes.URLSearchParams,{visitor:o(function(t,s,n,i){return Ne.isNode&&E.isBuffer(t)?(this.append(s,t.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},"visitor"),...e})}o(ky,"toURLEncodedForm");const ul=rl;function hl(r){if(r>ul)throw new P("FormData field is too deeply nested ("+r+" levels). Max depth: "+ul,P.ERR_FORM_DATA_DEPTH_EXCEEDED)}o(hl,"throwIfDepthExceeded");function Iy(r){const e=[],t=/[^.[\]]+|\[([^.[\]]*)]/g;let s;for(;(s=t.exec(r))!==null;)hl(e.length),e.push(s[0]==="[]"?"":s[1]||s[0]);return e}o(Iy,"parsePropPath");function Ry(r){const e={},t=Object.keys(r);let s;const n=t.length;let i;for(s=0;s<n;s++)i=t[s],e[i]=r[i];return e}o(Ry,"arrayToObject");function dl(r){function e(t,s,n,i){hl(i);let c=t[i++];if(c==="__proto__")return!0;const a=Number.isFinite(+c),l=i>=t.length;return c=!c&&E.isArray(n)?n.length:c,l?(E.hasOwnProp(n,c)?n[c]=E.isArray(n[c])?n[c].concat(s):[n[c],s]:n[c]=s,!a):((!E.hasOwnProp(n,c)||!E.isObject(n[c]))&&(n[c]=[]),e(t,s,n[c],i)&&E.isArray(n[c])&&(n[c]=Ry(n[c])),!a)}if(o(e,"buildPath"),E.isFormData(r)&&E.isFunction(r.entries)){const t={};return E.forEachEntry(r,(s,n)=>{e(Iy(s),n,t,0)}),t}return null}o(dl,"formDataToJSON");const fl=Object.freeze(["get","delete","head","options","post","put","patch","purge","link","unlink","query"]),_r=o((r,e)=>r!=null&&E.hasOwnProp(r,e)?r[e]:void 0,"own");function Cy(r,e,t){if(E.isString(r))try{return(e||JSON.parse)(r),E.trim(r)}catch(s){if(s.name!=="SyntaxError")throw s}return(t||JSON.stringify)(r)}o(Cy,"stringifySafely");const Zr={transitional:Ui,adapter:["xhr","http","fetch"],transformRequest:[o(function(e,t){const s=t.getContentType()||"",n=s.indexOf("application/json")>-1,i=E.isObject(e);if(i&&E.isHTMLForm(e)&&(e=new FormData(e)),E.isFormData(e))return n?JSON.stringify(dl(e)):e;if(E.isArrayBuffer(e)||E.isBuffer(e)||E.isStream(e)||E.isFile(e)||E.isBlob(e)||E.isReadableStream(e))return e;if(E.isArrayBufferView(e))return e.buffer;if(E.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(i){const l=_r(this,"formSerializer");if(s.indexOf("application/x-www-form-urlencoded")>-1)return ky(e,l).toString();if((a=E.isFileList(e))||s.indexOf("multipart/form-data")>-1){const h=_r(this,"env"),u=h&&h.FormData;return Hs(a?{"files[]":e}:e,u&&new u,l)}}return i||n?(t.setContentType("application/json",!1),Cy(e)):e},"transformRequest")],transformResponse:[o(function(e){const t=_r(this,"transitional")||Zr.transitional,s=t&&t.forcedJSONParsing,n=_r(this,"responseType"),i=n==="json";if(E.isResponse(e)||E.isReadableStream(e))return e;if(e&&E.isString(e)&&(s&&!n||i)){const a=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e,_r(this,"parseReviver"))}catch(l){if(a)throw l.name==="SyntaxError"?P.from(l,P.ERR_BAD_RESPONSE,this,null,_r(this,"response")):l}}return e},"transformResponse")],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ne.classes.FormData,Blob:Ne.classes.Blob},validateStatus:o(function(e){return e>=200&&e<300},"validateStatus"),headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};E.forEach(fl,r=>{Zr.headers[r]={}});function Hi(r,e){const t=this||Zr,s=e||t,n=je.from(s.headers);let i=s.data;return E.forEach(r,o(function(a){i=a.call(t,i,n.normalize(),e?e.status:void 0)},"transform")),n.normalize(),i}o(Hi,"transformData");function pl(r){return!!(r&&r.__CANCEL__)}o(pl,"isCancel$1");let Xr=class extends P{static{o(this,"CanceledError")}constructor(e,t,s){super(e??"canceled",P.ERR_CANCELED,t,s),this.name="CanceledError",this.__CANCEL__=!0}};function gl(r,e,t){const s=t.config.validateStatus;!t.status||!s||s(t.status)?r(t):e(new P("Request failed with status code "+t.status,t.status>=400&&t.status<500?P.ERR_BAD_REQUEST:P.ERR_BAD_RESPONSE,t.config,t.request,t))}o(gl,"settle");const Ny=/[\t\n\r]/g;function ml(r){if(typeof r!="string")return r;let e=0;for(;e<r.length&&r.charCodeAt(e)<=32;)e++;return r.slice(e).replace(Ny,"")}o(ml,"normalizeURLForProtocolCheck");function Wi(r){const e=/^([-+\w]{1,25}):(?:\/\/)?/.exec(r);return e&&e[1]||""}o(Wi,"parseProtocol");function Dy(r,e){r=r||10;const t=new Array(r),s=new Array(r);let n=0,i=0,c;return e=e!==void 0?e:1e3,o(function(l){const h=Date.now(),u=s[i];c||(c=h),t[n]=l,s[n]=h;let p=i,g=0;for(;p!==n;)g+=t[p++],p=p%r;if(n=(n+1)%r,n===i&&(i=(i+1)%r),h-c<e)return;const f=u&&h-u;return f?Math.round(g*1e3/f):void 0},"push")}o(Dy,"speedometer");function Ly(r,e){let t=0,s=1e3/e,n,i;const c=o((u,p=Date.now())=>{t=p,n=null,i&&(clearTimeout(i),i=null),r(...u)},"invoke");return[o((...u)=>{const p=Date.now(),g=p-t;g>=s?c(u,p):(n=u,i||(i=setTimeout(()=>{i=null,c(n)},s-g)))},"throttled"),o(()=>n&&c(n),"flush"),o((...u)=>c(u),"flushWith")]}o(Ly,"throttle");const Ws=o((r,e,t=3)=>{let s=0;const n=Dy(50,250);return Ly(i=>{if(!i||!E.isNumber(i.loaded))return;const c=i.loaded,a=i.lengthComputable?i.total:void 0,l=Math.max(0,a!=null?Math.min(c,a):c),h=Math.max(0,l-s),u=n(h);s=Math.max(s,l);const p={loaded:l,total:a,progress:a?l/a:void 0,bytes:h,rate:u||void 0,estimated:u&&a?(a-l)/u:void 0,event:i,lengthComputable:a!=null,[e?"download":"upload"]:!0};r(p)},t)},"progressEventReducer"),yl=o((r,e)=>{const t=r!=null;return[s=>e[0]({lengthComputable:t,total:r,loaded:s}),e[1]]},"progressEventDecorator"),bl=o((r,e=E.asap)=>(...t)=>e(()=>r(...t)),"asyncDecorator"),Py=Ne.hasStandardBrowserEnv?((r,e)=>t=>(t=new URL(t,Ne.origin),r.protocol===t.protocol&&r.host===t.host&&(e||r.port===t.port)))(new URL(Ne.origin),Ne.navigator&&/(msie|trident)/i.test(Ne.navigator.userAgent)):()=>!0,My=Ne.hasStandardBrowserEnv?{write(r,e,t,s,n,i,c){if(typeof document>"u")return;const a=[`${r}=${encodeURIComponent(e)}`];E.isNumber(t)&&a.push(`expires=${new Date(t).toUTCString()}`),E.isString(s)&&a.push(`path=${s}`),E.isString(n)&&a.push(`domain=${n}`),i===!0&&a.push("secure"),E.isString(c)&&a.push(`SameSite=${c}`),document.cookie=a.join("; ")},read(r){if(typeof document>"u")return null;const e=document.cookie.split(";");for(let t=0;t<e.length;t++){const s=e[t].replace(/^\s+/,""),n=s.indexOf("=");if(n!==-1&&s.slice(0,n)===r)try{return decodeURIComponent(s.slice(n+1))}catch{return s.slice(n+1)}}return null},remove(r){this.write(r,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function Fy(r){return typeof r!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}o(Fy,"isAbsoluteURL");function xy(r,e){if(!e)return r;let t=r.length;for(;t>0&&r.charCodeAt(t-1)===47;)t--;return r.slice(0,t)+"/"+e.replace(/^\/+/,"")}o(xy,"combineURLs");const $y=/^https?:(?!\/\/)/i;function jy(r){return r&&r.replace(/(^|&)([^=&]*=)?[^&]+/g,(e,t,s="")=>`${t}${s}${qs}`)}o(jy,"redactFragment");function By(r){const e=r.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${qs}@`),t=e.indexOf("#"),n=(t===-1?e:e.slice(0,t)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${qs}`);return t===-1?n:`${n}#${jy(e.slice(t+1))}`}o(By,"redactSensitiveURLParts");function _l(r,e){if(typeof r=="string"){const t=ml(r);if($y.test(t))throw new P(`Invalid URL ${JSON.stringify(By(t))}: missing "//" after protocol`,P.ERR_INVALID_URL,e)}}o(_l,"assertValidHttpProtocolURL");function wl(r,e,t,s){_l(e,s);let n=!Fy(e);return r&&(n||t===!1)?(_l(r,s),xy(r,e)):e}o(wl,"buildFullPath");const Sl=o(r=>r instanceof je?{...r}:r,"headersToObject"),Uy=o(r=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(r).concat(Object.getOwnPropertySymbols(r).filter(e=>Object.getOwnPropertyDescriptor(r,e).enumerable)):Object.keys(r),"ownEnumerableKeys");function Gt(r,e){r=r||{},e=e||{};const t=Object.create(null);Object.defineProperty(t,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function s(u,p,g,f){return E.isPlainObject(u)&&E.isPlainObject(p)?E.merge.call({caseless:f},u,p):E.isPlainObject(p)?E.merge({},p):E.isArray(p)?p.slice():p}o(s,"getMergedValue");function n(u,p,g,f){if(E.isUndefined(p)){if(!E.isUndefined(u))return s(void 0,u,g,f)}else return s(u,p,g,f)}o(n,"mergeDeepProperties");function i(u,p){if(!E.isUndefined(p))return s(void 0,p)}o(i,"valueFromConfig2");function c(u,p){if(E.isUndefined(p)){if(!E.isUndefined(u))return s(void 0,u)}else return s(void 0,p)}o(c,"defaultToConfig2");function a(u){const p=E.hasOwnProp(e,"transitional")?e.transitional:void 0;if(!E.isUndefined(p))if(E.isPlainObject(p)){if(E.hasOwnProp(p,u))return p[u]}else return;const g=E.hasOwnProp(r,"transitional")?r.transitional:void 0;if(E.isPlainObject(g)&&E.hasOwnProp(g,u))return g[u]}o(a,"getMergedTransitionalOption");function l(u,p,g){if(E.hasOwnProp(e,g))return s(u,p);if(E.hasOwnProp(r,g))return s(void 0,u)}o(l,"mergeDirectKeys");const h={url:i,method:i,data:i,baseURL:c,transformRequest:c,transformResponse:c,paramsSerializer:c,timeout:c,timeoutErrorMessage:c,withCredentials:c,withXSRFToken:c,adapter:c,responseType:c,xsrfCookieName:c,xsrfHeaderName:c,onUploadProgress:c,onDownloadProgress:c,decompress:c,maxContentLength:c,maxBodyLength:c,beforeRedirect:c,transport:c,httpAgent:c,httpsAgent:c,cancelToken:c,socketPath:c,allowedSocketPaths:c,responseEncoding:c,validateStatus:l,headers:o((u,p,g)=>n(Sl(u),Sl(p),g,!0),"headers")};return E.forEach(Uy({...r,...e}),o(function(p){if(p==="__proto__"||p==="constructor"||p==="prototype")return;const g=E.hasOwnProp(h,p)?h[p]:n,f=E.hasOwnProp(r,p)?r[p]:void 0,d=E.hasOwnProp(e,p)?e[p]:void 0,y=g(f,d,p);E.isUndefined(y)&&g!==l||(t[p]=y)},"computeConfigValue")),E.hasOwnProp(e,"validateStatus")&&E.isUndefined(e.validateStatus)&&a("validateStatusUndefinedResolves")===!1&&(E.hasOwnProp(r,"validateStatus")?t.validateStatus=s(void 0,r.validateStatus):delete t.validateStatus),t}o(Gt,"mergeConfig$1");const Vy=["content-type","content-length"];function qy(r,e,t){if(t!=="content-only"){r.set(e);return}Object.entries(e||{}).forEach(([s,n])=>{Vy.includes(s.toLowerCase())&&r.set(s,n)})}o(qy,"setFormDataHeaders");const Hy=o(r=>encodeURIComponent(r).replace(/%([0-9A-F]{2})/gi,(e,t)=>String.fromCharCode(parseInt(t,16))),"encodeUTF8$1");function vl(r){const e=Gt({},r),t=o(g=>E.hasOwnProp(e,g)?e[g]:void 0,"own"),s=t("data");let n=t("withXSRFToken");const i=t("xsrfHeaderName"),c=t("xsrfCookieName");let a=t("headers");const l=t("auth"),h=t("baseURL"),u=t("allowAbsoluteUrls"),p=t("url");if(e.headers=a=je.from(a),e.url=ol(wl(h,p,u,e),t("params"),t("paramsSerializer")),l){const g=E.getSafeProp(l,"username")||"",f=E.getSafeProp(l,"password")||"";try{a.set("Authorization","Basic "+btoa(g+":"+(f?Hy(f):"")))}catch(d){throw P.from(d,P.ERR_BAD_OPTION_VALUE,r)}}if(E.isFormData(s)){const g=E.getSafeProp(s,"getHeaders");Ne.hasStandardBrowserEnv||Ne.hasStandardBrowserWebWorkerEnv||E.isReactNative(s)?a.setContentType(void 0):E.isFunction(g)&&qy(a,g.call(s),t("formDataHeaderPolicy"))}if(Ne.hasStandardBrowserEnv&&(E.isFunction(n)&&(n=n(e)),n===!0||n==null&&Py(e.url))){const f=i&&c&&My.read(c);f&&a.set(i,f)}return e}o(vl,"resolveConfig");const Wy=typeof XMLHttpRequest<"u"&&function(r){return new Promise(o(function(t,s){const n=vl(r);let i=n.data;const c=je.from(n.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:h}=n,u,p,g,f,d,y;function b(){f&&f(),d&&d(),n.cancelToken&&n.cancelToken.unsubscribe(u),n.signal&&n.signal.removeEventListener("abort",u)}o(b,"done");let m=new XMLHttpRequest;m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout;function _(S){if(!m)return;if(m.status===0&&(Wi(ml(n.url))||Wi(Ne.origin))!=="file"&&!(m.responseURL&&m.responseURL.startsWith("file:"))){s(new P("Request aborted",P.ECONNABORTED,r,m)),b(),m=null;return}try{S?y&&y(S):d&&d()}catch(O){setTimeout(()=>{throw O})}if(!m)return;const T=je.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),A={data:!a||a==="text"||a==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:T,config:r,request:m};gl(o(function(k){t(k),b()},"_resolve"),o(function(k){s(k),b()},"_reject"),A),m=null}o(_,"onloadend"),"onloadend"in m?m.onloadend=_:m.onreadystatechange=o(function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.startsWith("file:"))||setTimeout(_)},"handleLoad"),m.onabort=o(function(){m&&(s(new P("Request aborted",P.ECONNABORTED,r,m)),b(),m=null)},"handleAbort"),m.onerror=o(function(T){const v=T&&T.message?T.message:"Network Error",A=new P(v,P.ERR_NETWORK,r,m);A.event=T||null,s(A),b(),m=null},"handleError"),m.ontimeout=o(function(){let T=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const v=n.transitional||Ui;n.timeoutErrorMessage&&(T=n.timeoutErrorMessage),s(new P(T,v.clarifyTimeoutError?P.ETIMEDOUT:P.ECONNABORTED,r,m)),b(),m=null},"handleTimeout"),i===void 0&&c.setContentType(null),"setRequestHeader"in m&&E.forEach(Qc(c),o(function(T,v){m.setRequestHeader(v,T)},"setRequestHeader")),E.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),a&&a!=="json"&&(m.responseType=n.responseType),h&&([g,d,y]=Ws(h,!0),m.addEventListener("progress",g)),l&&m.upload&&([p,f]=Ws(l),m.upload.addEventListener("progress",p),m.upload.addEventListener("loadend",f)),(n.cancelToken||n.signal)&&(u=o(S=>{m&&(s(!S||S.type?new Xr(null,r,m):S),m.abort(),b(),m=null)},"onCanceled"),n.cancelToken&&n.cancelToken.subscribe(u),n.signal&&(n.signal.aborted?u():n.signal.addEventListener("abort",u)));const w=Wi(n.url);if(w&&!Ne.protocols.includes(w)){s(new P("Unsupported protocol "+w+":",P.ERR_BAD_REQUEST,r)),b();return}m.send(i||null)},"dispatchXhrRequest"))},zy=o((r,e)=>{if(r=r?r.filter(Boolean):[],!e&&!r.length)return;const t=new AbortController;let s=!1;const n=o(function(l){if(!s){s=!0,c();const h=l instanceof Error?l:this.reason;t.abort(h instanceof P?h:new Xr(h instanceof Error?h.message:h))}},"onabort");let i=e&&setTimeout(()=>{i=null,n(new P(`timeout of ${e}ms exceeded`,P.ETIMEDOUT))},e);const c=o(()=>{r&&(i&&clearTimeout(i),i=null,r.forEach(l=>{l.unsubscribe?l.unsubscribe(n):l.removeEventListener("abort",n)}),r=null)},"unsubscribe");r.forEach(l=>{if(!s){if(l.aborted){n.call(l);return}l.addEventListener("abort",n,{once:!0})}});const{signal:a}=t;return a.unsubscribe=()=>E.asap(c),a},"composeSignals"),Jy=o(function*(r,e){let t=r.byteLength;if(t<e){yield r;return}let s=0,n;for(;s<t;)n=s+e,yield r.slice(s,n),s=n},"streamChunk"),Ky=o(async function*(r,e){for await(const t of Gy(r))yield*Jy(t,e)},"readBytes"),Gy=o(async function*(r){if(r[Symbol.asyncIterator]){yield*r;return}const e=r.getReader();try{for(;;){const{done:t,value:s}=await e.read();if(t)break;yield s}}finally{await e.cancel()}},"readStream"),El=o((r,e,t,s)=>{const n=Ky(r,e);let i=0,c,a=o(l=>{c||(c=!0,s&&s(l))},"_onFinish");return new ReadableStream({async pull(l){try{const{done:h,value:u}=await n.next();if(h){a(),l.close();return}let p=u.byteLength;if(t){let g=i+=p;t(g)}l.enqueue(new Uint8Array(u))}catch(h){throw a(h),h}},cancel(l){return a(l),n.return()}},{highWaterMark:2})},"trackStream"),Ol=o(r=>r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102,"isHexDigit"),Tl=o((r,e,t)=>e+2<t&&Ol(r.charCodeAt(e+1))&&Ol(r.charCodeAt(e+2)),"isPercentEncodedByte"),Al=o(r=>r<=57?r-48:(r&223)-55,"hexValue"),Yy=o(r=>r>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||r===43||r===47||r===45||r===95,"isBase64Char"),Zy=o(r=>r===9||r===10||r===12||r===13||r===32,"isBase64Whitespace"),Xy=o(r=>{const e=Math.floor(r/4),t=r%4;return e*3+(t===2?1:t===3?2:0)},"base64Bytes"),Qy=o(r=>{const e=r.length;let t=0;return e>0&&r.charCodeAt(e-1)===61&&(t++,e>1&&r.charCodeAt(e-2)===61&&t++),Math.floor((e-t)*3/4)},"estimateBase64BufferAllocation"),e0=o(r=>{const e=r.length;let t=0,s=0,n=!1;for(let i=0;i<e;i++){let c=r.charCodeAt(i);if(c===37&&Tl(r,i,e)&&(c=Al(r.charCodeAt(i+1))*16+Al(r.charCodeAt(i+2)),i+=2),!Zy(c)){if(c===61){s++;continue}if(!Yy(c)||s>0){n=!0;continue}t++}}return n||s>2||s>0&&(t+s)%4!==0||t%4===1?Qy(r):Xy(t)},"estimatePercentDecodedBase64Bytes"),t0=o((r,e)=>{if(!r||typeof r!="string"||!r.startsWith("data:"))return 0;const t=r.indexOf(",");if(t<0)return 0;const s=r.slice(5,t),n=r.slice(t+1);if(/;base64/i.test(s))return e(n);let c=0;for(let a=0,l=n.length;a<l;a++){const h=n.charCodeAt(a);if(h===37&&Tl(n,a,l))c+=1,a+=2;else if(h<128)c+=1;else if(h<2048)c+=2;else if(h>=55296&&h<=56319&&a+1<l){const u=n.charCodeAt(a+1);u>=56320&&u<=57343?(c+=4,a++):c+=3}else c+=3}return c},"estimateDataURLBytes");function r0(r){const e=typeof r=="string"?r.indexOf("#"):-1;return t0(e===-1?r:r.slice(0,e),e0)}o(r0,"estimateDataURLDecodedBytes");const zi="1.20.0",kl=64*1024,s0={cache:"default",redirect:"follow",referrer:"about:client",referrerPolicy:"",mode:"cors",integrity:"",keepalive:!1,priority:"auto",window:null},{isFunction:zs}=E,n0=o(r=>encodeURIComponent(r).replace(/%([0-9A-F]{2})/gi,(e,t)=>String.fromCharCode(parseInt(t,16))),"encodeUTF8"),Il=o(r=>{if(!E.isString(r))return r;try{return decodeURIComponent(r)}catch{return r}},"decodeURIComponentSafe"),Rl=o((r,...e)=>{try{return!!r(...e)}catch{return!1}},"test"),i0=o(r=>{const e=r.indexOf("://");let t=r;return e!==-1&&(t=t.slice(e+3)),t.includes("@")||t.includes(":")},"maybeWithAuthCredentials"),o0=o(r=>{const e=E.global!==void 0&&E.global!==null?E.global:globalThis,{ReadableStream:t,TextEncoder:s}=e;r=E.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response},r);const{fetch:n,Request:i,Response:c}=r,a=n?zs(n):typeof fetch=="function",l=zs(i),h=zs(c);if(!a)return!1;const u=a&&zs(t),p=a&&(typeof s=="function"?(m=>_=>m.encode(_))(new s):async m=>new Uint8Array(await new i(m).arrayBuffer())),g=l&&u&&Rl(()=>{let m=!1;const _=new i(Ne.origin,{body:new t,method:"POST",get duplex(){return m=!0,"half"}}),w=_.headers.has("Content-Type");return _.body!=null&&_.body.cancel(),m&&!w}),f=h&&u&&Rl(()=>E.isReadableStream(new c("").body)),d={stream:f&&(m=>m.body)};a&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!d[m]&&(d[m]=(_,w)=>{let S=_&&_[m];if(S)return S.call(_);throw new P(`Response type '${m}' is not supported`,P.ERR_NOT_SUPPORT,w)})});const y=o(async m=>{if(m==null)return 0;if(E.isBlob(m))return m.size;if(E.isSpecCompliantForm(m))return(await new i(Ne.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(E.isArrayBufferView(m)||E.isArrayBuffer(m))return m.byteLength;if(E.isURLSearchParams(m)&&(m=m+""),E.isString(m))return(await p(m)).byteLength},"getBodyLength"),b=o(async(m,_)=>{const w=E.toFiniteNumber(m.getContentLength());return w??y(_)},"resolveBodyLength");return async m=>{let{url:_,method:w,data:S,signal:T,cancelToken:v,timeout:A,onDownloadProgress:O,onUploadProgress:k,responseType:C,headers:B,withCredentials:q="same-origin",fetchOptions:de,maxContentLength:ge,maxBodyLength:G,maxRedirects:ce}=vl(m);const H=E.isNumber(ge)&&ge>-1,ve=E.isNumber(G)&&G>-1,me=o(J=>E.hasOwnProp(m,J)?m[J]:void 0,"own");let V=n||fetch;C=C?(C+"").toLowerCase():"text";let Le=zy([T,v&&v.toAbortSignal()],A),ue=null;const Me=Le&&Le.unsubscribe&&(()=>{Le.unsubscribe()});let Q,ie=null;const fe=o(()=>new P("Request body larger than maxBodyLength limit",P.ERR_BAD_REQUEST,m,ue),"maxBodyLengthError");try{let J;const oe=me("auth");if(oe){const X=E.getSafeProp(oe,"username")||"",Ee=E.getSafeProp(oe,"password")||"";J={username:X,password:Ee}}if(i0(_)){const X=new URL(_,Ne.origin);if(!J&&(X.username||X.password)){const Ee=Il(X.username),Ae=Il(X.password);J={username:Ee,password:Ae}}(X.username||X.password)&&(X.username="",X.password="",_=X.href)}if(J&&(B.delete("authorization"),B.set("Authorization","Basic "+btoa(n0((J.username||"")+":"+(J.password||""))))),H&&typeof _=="string"&&_.startsWith("data:")&&r0(_)>ge)throw new P("maxContentLength size of "+ge+" exceeded",P.ERR_BAD_RESPONSE,m,ue);if(ve&&w!=="get"&&w!=="head"){const X=await y(S);if(typeof X=="number"&&isFinite(X)&&(Q=X,X>G))throw fe()}const Ie=ve&&(E.isReadableStream(S)||E.isStream(S)),Y=o((X,Ee,Ae)=>El(X,kl,bt=>{if(ve&&bt>G)throw ie=fe();Ee&&Ee(bt)},Ae),"trackRequestStream");if(g&&w!=="get"&&w!=="head"&&(k||Ie)){if(Q=Q??await b(B,S),Q!==0||Ie){let X=new i(_,{method:"POST",body:S,duplex:"half"}),Ee;if(E.isFormData(S)&&(Ee=X.headers.get("content-type"))&&B.setContentType(Ee),X.body){const[Ae,bt]=k&&yl(Q,Ws(bl(k)))||[];S=Y(X.body,Ae,bt)}}}else if(Ie&&!l&&u&&w!=="get"&&w!=="head")S=Y(S);else if(Ie&&l&&!g&&w!=="get"&&w!=="head")throw new P("Stream request bodies are not supported by the current fetch implementation",P.ERR_NOT_SUPPORT,m,ue);E.isString(q)||(q=q?"include":"omit");const st=l&&"credentials"in i.prototype;if(E.isFormData(S)){const X=B.getContentType();X&&/^multipart\/form-data/i.test(X)&&!/boundary=/i.test(X)&&B.delete("content-type")}B.set("User-Agent","axios/"+zi,!1);const He=de==null?de:Object.assign(Object.create(null),de);He&&(delete He.body,delete He.headers,delete He.method,delete He.signal,delete He.duplex,delete He.credentials);const Ke=Object.assign(Object.create(null),He,{signal:Le,method:w.toUpperCase(),headers:Qc(B.normalize()),body:S,duplex:"half",credentials:st?q:void 0});l&&(E.forEach(s0,(X,Ee)=>{Ke[Ee]===void 0&&(Ke[Ee]=X)}),Ke.signal===void 0&&(Ke.signal=null),Ke.body===void 0&&(Ke.body=null)),ce===0&&(Ke.redirect="manual",He&&(He.redirect="manual")),ue=l&&new i(_,Ke);let nt=await(l?V(ue,He):V(_,Ke));const yt=je.from(nt.headers);if(H){const X=E.toFiniteNumber(yt.getContentLength());if(X!=null&&X>ge)throw new P("maxContentLength size of "+ge+" exceeded",P.ERR_BAD_RESPONSE,m,ue)}const Or=f&&(C==="stream"||C==="response");if(f&&nt.body&&(O||H||Or&&Me)){const X={};["status","statusText","headers"].forEach(xt=>{X[xt]=nt[xt]});const Ee=E.toFiniteNumber(yt.getContentLength()),[Ae,bt]=O&&yl(Ee,Ws(bl(O),!0))||[];let _t=0;const on=o(xt=>{if(H&&(_t=xt,_t>ge))throw new P("maxContentLength size of "+ge+" exceeded",P.ERR_BAD_RESPONSE,m,ue);Ae&&Ae(xt)},"onChunkProgress");nt=new c(El(nt.body,kl,on,()=>{bt&&bt(),Me&&Me()}),X)}C=C||"text";let it=await d[E.findKey(d,C)||"text"](nt,m);if(H&&!f&&!Or){let X;if(it!=null&&(typeof it.byteLength=="number"?X=it.byteLength:typeof it.size=="number"?X=it.size:typeof it=="string"&&(X=typeof s=="function"?new s().encode(it).byteLength:it.length)),typeof X=="number"&&X>ge)throw new P("maxContentLength size of "+ge+" exceeded",P.ERR_BAD_RESPONSE,m,ue)}return!Or&&Me&&Me(),await new Promise((X,Ee)=>{gl(X,Ee,{data:it,headers:je.from(nt.headers),status:nt.status,statusText:nt.statusText,config:m,request:ue})})}catch(J){if(Me&&Me(),Le&&Le.aborted&&Le.reason instanceof P){const oe=Le.reason;throw oe.config=m,ue&&(oe.request=ue),J!==oe&&Object.defineProperty(oe,"cause",{__proto__:null,value:J,writable:!0,enumerable:!1,configurable:!0}),oe}if(ie)throw ue&&!ie.request&&(ie.request=ue),ie;if(J instanceof P)throw ue&&!J.request&&(J.request=ue),J;if(J&&J.name==="TypeError"&&/Load failed|fetch/i.test(J.message)){const oe=new P("Network Error",P.ERR_NETWORK,m,ue,J&&J.response);throw Object.defineProperty(oe,"cause",{__proto__:null,value:J.cause||J,writable:!0,enumerable:!1,configurable:!0}),oe}throw P.from(J,J&&J.code,m,ue,J&&J.response)}}},"factory"),a0=new Map,Cl=o(r=>{let e=r&&r.env||{};const{fetch:t,Request:s,Response:n}=e,i=[s,n,t];let c=i.length,a=c,l,h,u=a0;for(;a--;)l=i[a],h=u.get(l),h===void 0&&u.set(l,h=a?new Map:o0(e)),u=h;return h},"getFetch");Cl();const Ji={http:_y,xhr:Wy,fetch:{get:Cl}};E.forEach(Ji,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(r,"adapterName",{__proto__:null,value:e})}});const Nl=o(r=>`- ${r}`,"renderReason"),c0=o(r=>E.isFunction(r)||r===null||r===!1,"isResolvedHandle");function l0(r,e){r=E.isArray(r)?r:[r];const{length:t}=r;let s,n;const i={};for(let c=0;c<t;c++){s=r[c];let a;if(n=s,!c0(s)&&(n=Ji[(a=String(s)).toLowerCase()],n===void 0))throw new P(`Unknown adapter '${a}'`);if(n&&(E.isFunction(n)||(n=n.get(e))))break;i[a||"#"+c]=n}if(!n){const c=Object.entries(i).map(([l,h])=>`adapter ${l} `+(h===!1?"is not supported by the environment":"is not available in the build"));let a=t?c.length>1?`since :
`+c.map(Nl).join(`
`):" "+Nl(c[0]):"as no adapter specified";throw new P("There is no suitable adapter to dispatch the request "+a,P.ERR_NOT_SUPPORT)}return n}o(l0,"getAdapter$1");const Dl={getAdapter:l0,adapters:Ji};function Ki(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new Xr(null,r)}o(Ki,"throwIfCancellationRequested");function Gi(r){const e=E.toSafeFlatObject(r);return Ki(e),e.headers=je.from(E.getSafeProp(e,"headers")),e.data=Hi.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Dl.getAdapter(e.adapter||Zr.adapter,e)(e).then(o(function(n){Ki(e),e.response=n;try{n.data=Hi.call(e,e.transformResponse,n)}finally{delete e.response}return n.headers=je.from(n.headers),n},"onAdapterResolution"),o(function(n){if(!pl(n)&&(Ki(e),n&&n.response)){e.response=n.response;try{n.response.data=Hi.call(e,e.transformResponse,n.response)}finally{delete e.response}n.response.headers=je.from(n.response.headers)}return Promise.reject(n)},"onAdapterRejection"))}o(Gi,"dispatchRequest");const Js={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{Js[r]=o(function(s){return typeof s===r||"a"+(e<1?"n ":" ")+r},"validator")});const Ll={};Js.transitional=o(function(e,t,s){function n(i,c){return"[Axios v"+zi+"] Transitional option '"+i+"'"+c+(s?". "+s:"")}return o(n,"formatMessage"),(i,c,a)=>{if(e===!1)throw new P(n(c," has been removed"+(t?" in "+t:"")),P.ERR_DEPRECATED);return t&&!Ll[c]&&(Ll[c]=!0,console.warn(n(c," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(i,c,a):!0}},"transitional"),Js.spelling=o(function(e){return(t,s)=>(console.warn(`${s} is likely a misspelling of ${e}`),!0)},"spelling");function u0(r,e,t){if(typeof r!="object"||r===null)throw new P("options must be an object",P.ERR_BAD_OPTION_VALUE);const s=Object.keys(r);let n=s.length;for(;n-- >0;){const i=s[n],c=Object.prototype.hasOwnProperty.call(e,i)?e[i]:void 0;if(c){const a=r[i],l=a===void 0||c(a,i,r);if(l!==!0)throw new P("option "+i+" must be "+l,P.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new P("Unknown option "+i,P.ERR_BAD_OPTION)}}o(u0,"assertOptions");const Ks={assertOptions:u0,validators:Js},Be=Ks.validators;let Yt=class{static{o(this,"Axios")}constructor(e){this.defaults=e||{},this.interceptors={request:new ll,response:new ll}}async request(e,t){try{return await this._request(e,t)}catch(s){if(s instanceof Error)try{let n={};Error.captureStackTrace?Error.captureStackTrace(n):n=new Error;const i=n.stack;let c="";if(typeof i=="string"){const a=i.indexOf(`
`);c=a===-1?"":i.slice(a+1)}if(!s.stack)s.stack=c;else if(c){const a=c.indexOf(`
`),l=a===-1?-1:c.indexOf(`
`,a+1),h=l===-1?"":c.slice(l+1);String(s.stack).endsWith(h)||(s.stack+=`
`+c)}}catch{}throw s}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=Gt(this.defaults,t);const{transitional:s,paramsSerializer:n,headers:i}=t;s!==void 0&&Ks.assertOptions(s,{silentJSONParsing:Be.transitional(Be.boolean),forcedJSONParsing:Be.transitional(Be.boolean),clarifyTimeoutError:Be.transitional(Be.boolean),legacyInterceptorReqResOrdering:Be.transitional(Be.boolean),advertiseZstdAcceptEncoding:Be.transitional(Be.boolean),validateStatusUndefinedResolves:Be.transitional(Be.boolean)},!1),n!=null&&(E.isFunction(n)?t.paramsSerializer={serialize:n}:Ks.assertOptions(n,{encode:Be.function,serialize:Be.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Ks.assertOptions(t,{baseUrl:Be.spelling("baseURL"),withXsrfToken:Be.spelling("withXSRFToken")},!0),t.method=(E.getSafeProp(t,"method")||E.getSafeProp(this.defaults,"method")||"get").toLowerCase();let c=i&&E.merge(i.common,i[t.method]);i&&E.forEach(fl.concat("common"),d=>{delete i[d]}),t.headers=je.concat(c,i);const a=[];let l=!0;this.interceptors.request.forEach(o(function(y){if(typeof y.runWhen=="function"&&y.runWhen(t)===!1)return;l=l&&y.synchronous;const b=t.transitional||Ui;b&&b.legacyInterceptorReqResOrdering?a.unshift(y.fulfilled,y.rejected):a.push(y.fulfilled,y.rejected)},"unshiftRequestInterceptors"));const h=[];this.interceptors.response.forEach(o(function(y){h.push(y.fulfilled,y.rejected)},"pushResponseInterceptors"));let u,p=0,g;if(!l){const d=[Gi.bind(this),void 0];for(d.unshift(...a),d.push(...h),g=d.length,u=Promise.resolve(t);p<g;)u=u.then(d[p++],d[p++]);return u}g=a.length;let f=t;for(;p<g;){const d=a[p++],y=a[p++];try{f=d?d(f):f}catch(b){if(!y){u=Promise.reject(b);break}try{const m=y.call(this,b);E.isThenable(m)&&(u=Promise.resolve(m).then(()=>Gi.call(this,f)))}catch(m){u=Promise.reject(m)}break}}if(!u)try{u=Gi.call(this,f)}catch(d){u=Promise.reject(d)}for(p=0,g=h.length;p<g;)u=u.then(h[p++],h[p++]);return u}getUri(e){e=Gt(this.defaults,e);const t=wl(e.baseURL,e.url,e.allowAbsoluteUrls,e);return ol(t,e.params,e.paramsSerializer)}};E.forEach(["delete","get","head","options"],o(function(e){Yt.prototype[e]=function(t,s){return this.request(Gt(s||{},{method:e,url:t,data:s&&E.hasOwnProp(s,"data")?s.data:void 0}))}},"forEachMethodNoData")),E.forEach(["post","put","patch","query"],o(function(e){function t(s){return o(function(i,c,a){return this.request(Gt(a||{},{method:e,headers:s?{"Content-Type":"multipart/form-data"}:{},url:i,data:c}))},"httpMethod")}o(t,"generateHTTPMethod"),Yt.prototype[e]=t(),e!=="query"&&(Yt.prototype[e+"Form"]=t(!0))},"forEachMethodWithData"));let h0=class Xu{static{o(this,"CancelToken")}constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(o(function(i){t=i},"promiseExecutor"));const s=this;this.promise.then(n=>{if(!s._listeners)return;let i=s._listeners.length;for(;i-- >0;)s._listeners[i](n);s._listeners=null}),this.promise.then=n=>{let i;const c=new Promise(a=>{s.subscribe(a),i=a}).then(n);return c.cancel=o(function(){s.unsubscribe(i)},"reject"),c},e(o(function(i,c,a){s.reason||(s.reason=new Xr(i,c,a),t(s.reason))},"cancel"))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=o(s=>{e.abort(s)},"abort");return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new Xu(o(function(n){e=n},"executor")),cancel:e}}};function d0(r){return o(function(t){return r.apply(null,t)},"wrap")}o(d0,"spread$1");function f0(r){return E.isObject(r)&&r.isAxiosError===!0}o(f0,"isAxiosError$1");const Gs={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Gs).forEach(([r,e])=>{Gs[e]===void 0&&(Gs[e]=r)});function Pl(r){const e=new Yt(r),t=Bc(Yt.prototype.request,e);return E.extend(t,Yt.prototype,e,{allOwnKeys:!0}),E.extend(t,e,null,{allOwnKeys:!0}),t.create=o(function(n){return Pl(Gt(r,n))},"create"),t}o(Pl,"createInstance");const we=Pl(Zr);we.Axios=Yt,we.CanceledError=Xr,we.CancelToken=h0,we.isCancel=pl,we.VERSION=zi,we.toFormData=Hs,we.AxiosError=P,we.Cancel=we.CanceledError,we.all=o(function(e){return Promise.all(e)},"all"),we.spread=d0,we.isAxiosError=f0,we.mergeConfig=Gt,we.AxiosHeaders=je,we.formToJSON=r=>dl(E.isHTMLForm(r)?new FormData(r):r),we.getAdapter=Dl.getAdapter,we.HttpStatusCode=Gs,we.default=we;const{Axios:Lw,AxiosError:Yi,CanceledError:Pw,isCancel:Mw,CancelToken:Fw,VERSION:xw,all:$w,Cancel:jw,isAxiosError:Bw,spread:Uw,toFormData:Vw,AxiosHeaders:qw,HttpStatusCode:Hw,formToJSON:Ww,getAdapter:zw,mergeConfig:Jw,create:Kw}=we;var p0=Object.defineProperty,g0=o((r,e)=>p0(r,"name",{value:e,configurable:!0}),"t$7");const m0="X-Request-ID",y0="bx24_request_id",b0="bx24_sdk_ver",_0="bx24_sdk_type";class w0{static{o(this,"RequestIdGenerator")}static{g0(this,"RequestIdGenerator")}getQueryStringParameterName(){return y0}getQueryStringSdkParameterName(){return b0}getQueryStringSdkTypeParameterName(){return _0}generate(){return W.getUuidRfc4122()}getRequestId(){return this.generate()}getHeaderFieldName(){return m0}}var S0=Object.defineProperty,v0=o((r,e)=>S0(r,"name",{value:e,configurable:!0}),"o$e");const Ml=["adapter","timeout","timeoutErrorMessage","proxy","httpAgent","httpsAgent","maxRedirects","maxContentLength","maxBodyLength","decompress","withCredentials"];function Fl(r){const e={},t=[];if(!r)return{picked:e,dropped:t};for(const[s,n]of Object.entries(r)){if(Ml.includes(s)){e[s]=n;continue}s!=="headers"&&t.push(s)}return{picked:e,dropped:t}}o(Fl,"pickHttpOptions"),v0(Fl,"pickHttpOptions");var E0=Object.defineProperty,Qr=o((r,e)=>E0(r,"name",{value:e,configurable:!0}),"d$4");const O0=300,T0=100;function Ys(r){const e=typeof r=="string"?r:String(r);return e.length>O0?e.slice(0,T0)+"...":e}o(Ys,"truncateForLog"),Qr(Ys,"truncateForLog");const xl="Idempotency-Key",A0="idempotency-key",k0="idempotent-replayed",I0=/^[\u0021-\u007E]{1,255}$/;function $l(r){if(r===null||typeof r!="object")return;let e,t;for(const[s,n]of Object.entries(r)){const i=s.toLowerCase(),c=Array.isArray(n)?n[0]:n;A0===i&&typeof c=="string"?e=c:k0===i&&(t=c===!0||String(c).trim().toLowerCase()==="true")}if(!(e===void 0&&t===void 0))return{key:e,replayed:t??!1}}o($l,"readIdempotencyHeaders"),Qr($l,"readIdempotencyHeaders");function Zs(){return hr()}o(Zs,"w$1"),Qr(Zs,"isCorsEnforcedRuntime");const jl=new WeakSet;function Bl(){return hr()?typeof globalThis.fetch=="function"?{adapter:"fetch"}:{}:{}}o(Bl,"$"),Qr(Bl,"preferredAdapter");class Ul{static{o(this,"AbstractHttp")}static{Qr(this,"AbstractHttp")}_clientAxios;_authActions;_requestIdGenerator;_restrictionManager;_pendingRefresh=null;_logger;_isClientSideWarning=!1;_clientSideWarningMessage="";_version;_metrics={totalRequests:0,successfulRequests:0,failedRequests:0,totalDuration:0,byMethod:new Map,lastErrors:[]};constructor(e,t,s){this._version=ee.v2,this._logger=ae.createNullLogger();const n={};this.isServerSide()&&(n["User-Agent"]="b24-js-sdk/3.0.0"),this._authActions=e,this._requestIdGenerator=new w0;const{picked:i,dropped:c}=Fl(t);this._clientAxios=we.create({timeout:3e4,timeoutErrorMessage:"Request timeout exceeded",...Bl(),...i,headers:{...n,...t?.headers??{}}}),c.length>0&&!jl.has(t)&&(jl.add(t),ae.forcedLog(this._logger,"warning","httpOptions: keys not accepted at construction were dropped",{dropped:c.join(", "),accepted:Ml.join(", "),hint:"set them on getHttpClient(version).ajaxClient.defaults instead"}).catch(()=>{}));const a={...Br.getDefault(),...s};this._restrictionManager=new dr(a)}get apiVersion(){return this._version}get ajaxClient(){return this._clientAxios}setLogger(e){this._logger=e,this._restrictionManager.setLogger(this._logger)}getLogger(){return this._logger}async setRestrictionManagerParams(e){await this._restrictionManager.setConfig(e)}getRestrictionManagerParams(){return this._restrictionManager.getParams()}getStats(){return{...this._restrictionManager.getStats(),totalRequests:this._metrics.totalRequests,successfulRequests:this._metrics.successfulRequests,failedRequests:this._metrics.failedRequests,totalDuration:this._metrics.totalDuration,byMethod:this._metrics.byMethod,lastErrors:this._metrics.lastErrors}}async reset(){return this._metrics.totalRequests=0,this._metrics.successfulRequests=0,this._metrics.failedRequests=0,this._metrics.totalDuration=0,this._metrics.byMethod.clear(),this._metrics.lastErrors=[],this._restrictionManager.reset()}_updateMetrics(e,t,s,n){this._metrics.totalRequests++,t?this._metrics.successfulRequests++:(this._metrics.failedRequests++,n instanceof _e&&(this._metrics.lastErrors.push({method:e,error:n.message,timestamp:Date.now()}),this._metrics.lastErrors.length>100&&(this._metrics.lastErrors=this._metrics.lastErrors.slice(-100)))),this._metrics.byMethod.has(e)||this._metrics.byMethod.set(e,{count:0,totalDuration:0});const i=this._metrics.byMethod.get(e);i.count++,i.totalDuration+=s}_validateParams(e,t,s){try{JSON.stringify(s)}catch(n){throw new _e({code:"JSSDK_INVALID_PARAMS",description:"Parameters contain circular references",status:400,requestInfo:{method:t,params:s,requestId:e},originalError:n})}}async call(e,t,s,n){s=s??this._requestIdGenerator.getRequestId();const i=this._restrictionManager.getParams().maxRetries;this._validateParams(s,e,t),this._logRequest(s,e,t);const c=this._prepareRequestConfig(s,e,n);let a=null;const l=Date.now();for(let h=0;h<i;h++)try{this._logAttempt(s,e,h+1,i),await this._restrictionManager.applyOperatingLimits(s,e,t);const u=await this._executeSingleCall(s,e,t,c),p=Date.now()-l;return this._restrictionManager.resetErrors(e),this._updateMetrics(e,!0,p),this._logSuccessfulRequest(s,e,p),u}catch(u){a=this._convertToAjaxError(s,u,e,t);const p=Date.now()-l;if(this._restrictionManager.incrementError(e),this._updateMetrics(e,!1,p,a),this._logFailedRequest(s,e,h+1,i,a),h+1<i){const g=await this._restrictionManager.handleError(s,e,t,a,h);if(g>0){this._restrictionManager.incrementStats("limitHits"),this._logAttemptRetryWaiteDelay(s,e,g,h+1,i),await this._restrictionManager.waiteDelay(g),this._restrictionManager.incrementStats("retries");continue}}if(h+1===i&&this._logAllAttemptsExhausted(s,e,h+1,i),this._restrictionManager.isSoftError(a))return this._createAjaxResultWithErrorFromResponse(a,s,e,t);throw a}throw new _e({code:"JSSDK_CALL_ALL_ATTEMPTS_EXHAUSTED",description:"All attempts exhausted",status:a?.status||500,requestInfo:{method:e,params:t,requestId:s},originalError:a?.originalError||null})}_convertToAjaxError(e,t,s,n){return t instanceof _e?t:t instanceof Yi?this._convertAxiosErrorToAjaxError(e,t,s,n):this._convertUnknownErrorToAjaxError(e,t,s,n)}_convertAxiosErrorToAjaxError(e,t,s,n){const i=`${t.code||"JSSDK_AXIOS_ERROR"}`,c=t.message,a=t.response?.status||0;if(i==="ERR_NETWORK")return new _e({code:"NETWORK_ERROR",description:"Network connection failed",status:0,requestInfo:{method:s,params:n,requestId:e},originalError:t});if(i==="ECONNABORTED"||t.message.includes("timeout"))return new _e({code:"REQUEST_TIMEOUT",description:"Request timeout exceeded",status:408,requestInfo:{method:s,params:n,requestId:e},originalError:t});const l=Xn(t.response?.data,i,c);return new _e({code:l?.code??i,description:l?.description??c,status:a,validation:l?.validation,isV3Envelope:l?.isV3Envelope,requestInfo:{method:s,params:n,requestId:e},originalError:t})}_convertUnknownErrorToAjaxError(e,t,s,n){return new _e({code:"JSSDK_UNKNOWN_ERROR",description:t instanceof Error?t.message:String(t),status:0,requestInfo:{method:s,params:n,requestId:e},originalError:t})}async _executeSingleCall(e,t,s,n){this._checkClientSideWarning(e);const i=await this._ensureAuth(e),c=await this._makeRequestWithAuthRetry(e,t,s,i,n);return this._createAjaxResultFromResponse(c,e,t,s)}async _ensureAuth(e){let t=this._authActions.getAuthData();return t===!1&&(this._logRefreshingAuthToken(e),t=await this._refreshAuth()),t}_refreshAuth(){if(this._pendingRefresh)return this._pendingRefresh;const e=this._authActions.refreshAuth();return this._pendingRefresh=e,e.finally(()=>{this._pendingRefresh=null}).catch(()=>{}),e}async _makeRequestWithAuthRetry(e,t,s,n,i){try{return await this._restrictionManager.checkRateLimit(e,t),await this._makeAxiosRequest(e,t,s,n,i)}catch(c){c instanceof Yi&&this.getLogger().info("post/catchError",{requestId:e,status:c.status,responseData:Ys(JSON.stringify(qe(c?.response?.data),null,0))}).catch(()=>{});const a=this._convertToAjaxError(e,c,t,s);if(this._isAuthError(a)){this._logAuthErrorDetected(e),this._logRefreshingAuthToken(e);const l=await this._refreshAuth();return await this._restrictionManager.checkRateLimit(e,t),await this._makeAxiosRequest(e,t,s,l,i)}throw a}}async _makeAxiosRequest(e,t,s,n,i){let c=this._prepareMethod(e,t,this.getBaseUrl());const a=ee.v3===this._version&&t==="batch"&&Array.isArray(s),l=n.refresh_token==="hook",h=typeof n.access_token=="string"&&n.access_token.trim().length>0,u=ee.v3===this._version&&typeof i?.headers?.[xl]=="string",p=(a||u)&&!l&&h,g=p&&!Zs(),f=p&&Zs(),d=a&&(l||g||f),y=d?s:this._prepareParams(n,s);p&&!d&&delete y.auth;const b={"Content-Type":"application/json"},m=g?{maxRedirects:0,...i,headers:{...b,...i?.headers,Authorization:`Bearer ${n.access_token}`}}:f?{maxRedirects:0,...i,headers:{...b,...i?.headers}}:{...i,headers:{...b,...i?.headers}},_=JSON.stringify(qe(y),null,0);if(this.getLogger().info("post/send",{requestId:e,method:t,params:Ys(_)}).catch(()=>{}),f){const v=c.includes("?")?"&":"?";c+=`${v}auth=${encodeURIComponent(n.access_token)}`}const w=await this._clientAxios.post(c,y,m);if((m?.maxRedirects??this._clientAxios.defaults.maxRedirects)===0&&w.status===0)throw new _e({code:"JSSDK_HTTP_REDIRECT_BLOCKED",description:"This request does not follow redirects (`maxRedirects: 0`) and the answer carried no status of its own \u2014 which is what a refused redirect looks like on the fetch adapter, and what a dropped connection can look like too. The SDK sets `maxRedirects: 0` on a `restApi:v3` batch and on a `restApi:v3` call with `idempotencyKey`, both on a non-hook transport, because they carry an access token a redirect would take along. Point the SDK at the final URL instead.",status:0,requestInfo:{method:t,params:s,requestId:e}});const S=JSON.stringify(qe(w.data?.result),null,0);this.getLogger().info("post/response",{requestId:e,result:Ys(S),time:JSON.stringify(w.data?.time,null,0)}).catch(()=>{});const T=$l(w.headers);return{status:w.status,payload:w.data,...T?{idempotency:T}:{}}}_prepareRequestConfig(e,t,s){const n=s?.idempotencyKey;if(n!==void 0){if(!I0.test(n))throw new D({code:"JSSDK_HTTP_INVALID_IDEMPOTENCY_KEY",description:"`idempotencyKey` must be 1-255 printable ASCII characters with no whitespace or control characters. A `crypto.randomUUID()` value satisfies this. See https://apidocs.bitrix24.ru/api-reference/rest-v3.html",status:500});if(ee.v3===this._version&&Zs())throw new D({code:"JSSDK_HTTP_IDEMPOTENCY_KEY_BROWSER",description:"`idempotencyKey` cannot be used from a browser: the portal's CORS preflight does not allow the `Idempotency-Key` header, so a cross-origin request carrying it is refused. Make idempotent writes from a server. See https://github.com/bitrix24/b24jssdk/issues/573",status:500});return{headers:{[xl]:n}}}}_isAuthError(e){return e instanceof _e?e.status===401&&["expired_token","invalid_token"].includes(e.code):!1}async _createAjaxResultFromResponse(e,t,s,n){const i=new jr({answer:e.payload,query:{method:s,params:n,requestId:t},status:e.status,idempotency:e.idempotency});if(i.isSuccess){const c=i.getData()?.time;c&&await this._restrictionManager.updateStats(t,s,c)}return i}_createAjaxResultWithErrorFromResponse(e,t,s,n){return new jr({answer:{error:{code:e.code,message:e.message}},query:{method:s,params:n,requestId:t},status:e.status,error:e})}_prepareMethod(e,t,s){const n=`/${encodeURIComponent(t)}`;if(/^task\./.test(t))return`${s}${n}`;const i=new URLSearchParams({[this._requestIdGenerator.getQueryStringParameterName()]:e,[this._requestIdGenerator.getQueryStringSdkParameterName()]:"3.0.0",[this._requestIdGenerator.getQueryStringSdkTypeParameterName()]:"b24-js-sdk"});return`${s}${n}?${i.toString()}`}_prepareParams(e,t){const s={...t};if(e.refresh_token!=="hook"&&(s.auth=e.access_token),s?.data&&"start"in s.data){const{start:n,...i}=s.data;s.data=i}return s}setClientSideWarning(e,t){this._isClientSideWarning=e,this._clientSideWarningMessage=t}isServerSide(){return!hr()}getBaseUrl(){return this._authActions.getTargetOriginWithPath().get(this._version)}_sanitizeParams(e){return qe(e)}_logRequest(e,t,s){this.getLogger().debug("http request starting",{requestId:e,method:t,params:this._sanitizeParams(s),api:this.apiVersion,timestamp:Date.now()}).catch(()=>{})}_logAttempt(e,t,s,n){this.getLogger().info("http request attempt",{requestId:e,method:t,api:this.apiVersion,attempt:{current:s,max:n}}).catch(()=>{})}_logRefreshingAuthToken(e){this.getLogger().info("http refreshing auth token",{requestId:e,api:this.apiVersion}).catch(()=>{})}_logAuthErrorDetected(e){this.getLogger().info("http auth error detected",{requestId:e,api:this.apiVersion}).catch(()=>{})}_logSuccessfulRequest(e,t,s){this.getLogger().debug("http request successful",{requestId:e,method:t,api:this.apiVersion,duration:{ms:s,sec:Number.parseFloat((s/1e3).toFixed(2))}}).catch(()=>{})}_logFailedRequest(e,t,s,n,i){this.getLogger().debug("http request failed",{requestId:e,method:t,api:this.apiVersion,attempt:{current:s,max:n},error:{code:i.code,message:i.message,status:i.status}}).catch(()=>{})}_logAttemptRetryWaiteDelay(e,t,s,n,i){this.getLogger().debug(`http wait ${(s/1e3).toFixed(2)} sec.`,{requestId:e,method:t,api:this.apiVersion,wait:s,attempt:{current:n,max:i}}).catch(()=>{})}_logAllAttemptsExhausted(e,t,s,n){this.getLogger().warning("http all retry attempts exhausted",{requestId:e,method:t,api:this.apiVersion,attempt:{current:s,max:n}}).catch(()=>{})}_logBatchStart(e,t,s){const n=Array.isArray(t)?t.length:Object.keys(t).length;this.getLogger().debug("http batch request starting ",{requestId:e,callCount:n,api:this.apiVersion,isHaltOnError:s.isHaltOnError,timestamp:Date.now()}).catch(()=>{})}_logBatchCompletion(e,t,s){this.getLogger().debug("http batch request completed",{requestId:e,api:this.apiVersion,totalCalls:t,successful:t-s,failed:s,successRate:t>0?((t-s)/t*100).toFixed(1)+"%":"??"}).catch(()=>{})}_checkClientSideWarning(e){this._isClientSideWarning&&!this.isServerSide()&&F.isStringFilled(this._clientSideWarningMessage)&&ae.forcedLog(this.getLogger(),"warning",this._clientSideWarningMessage,{requestId:e,code:"JSSDK_CLIENT_SIDE_WARNING"})}}var R0=Object.defineProperty,C0=o((r,e)=>R0(r,"name",{value:e,configurable:!0}),"m$5");const Vl=["method","params","as","parallel"];class ql{static{o(this,"AbstractInteractionBatch")}static{C0(this,"AbstractInteractionBatch")}parallelDefaultValue;requestId;restrictionManager;logger;processingStrategy;_commands=[];constructor(e){this.parallelDefaultValue=e.parallelDefaultValue,this.requestId=e.requestId,this.restrictionManager=e.restrictionManager,this.processingStrategy=e.processingStrategy,this.logger=e.logger}setProcessingStrategy(e){this.processingStrategy=e}get size(){return this._commands.length}get maxSize(){return 0}addCommands(e){if(!this.processingStrategy)throw new D({code:"JSSDK_INTERACTION_BATCH_EMPTY_PROCESSING_STRATEGY",description:"ProcessingStrategy not set",status:500});try{this._warnUnreadCommandKeys(e)}catch{}this._commands=this.processingStrategy.prepareCommands(e,{parallelDefaultValue:this.parallelDefaultValue})}_warnUnreadCommandKeys(e){const t=new Set,s=[];for(const[i,c]of Object.entries(e)){if(!c||typeof c!="object"||Array.isArray(c))continue;const a=Object.keys(c).filter(p=>!Vl.includes(p)&&c[p]!==void 0);if(a.length===0)continue;const l=c.params,h=l!==null&&typeof l=="object"&&Object.keys(l).length>0,u=a.some(p=>p.toLowerCase()==="query");h&&!u||(a.forEach(p=>t.add(p)),s.push(i))}if(t.size===0)return;const n=[...t];ae.forcedLog(this.logger??ae.createNullLogger(),"warning",`[b24jssdk] batch command: ${n.join(", ")} ${n.length===1?"is":"are"} ignored \u2014 a command's arguments go in \`params\`. Write \`params: { \u2026 }\`. (\`query\` is the portal's own wire spelling on \`restApi:v3\`, which the SDK writes for you; on \`restApi:v2\` the arguments are serialised into the \`cmd\` querystring instead.)`,{code:"JSSDK_BATCH_UNREAD_COMMAND_KEY",unread:n.join(", "),read:Vl.join(", "),commands:s.join(", ")}).catch(()=>{})}getCommandsForCall(){if(!this.processingStrategy)throw new D({code:"JSSDK_INTERACTION_BATCH_EMPTY_PROCESSING_STRATEGY",description:"ProcessingStrategy not set",status:500});return this.processingStrategy.buildCommands(this._commands)}}var N0=Object.defineProperty,D0=o((r,e)=>N0(r,"name",{value:e,configurable:!0}),"s$d");const L0=50;class P0 extends ql{static{o(this,"InteractionBatchV2")}static{D0(this,"InteractionBatchV2")}get maxSize(){return L0}async prepareResponse(e){if(!this.processingStrategy)throw new D({code:"JSSDK_INTERACTION_BATCH_EMPTY_PROCESSING_STRATEGY",description:"ProcessingStrategy not set",status:500});const t={requestId:e.getQuery().requestId,parallelDefaultValue:this.parallelDefaultValue,restrictionManager:this.restrictionManager,response:e},s=await this.processingStrategy.prepareItems(this._commands,t);return this.processingStrategy.handleResults(this._commands,s,t)}}const M0=String.prototype.replace,F0=/%20/g,Hl={RFC1738:"RFC1738",RFC3986:"RFC3986"},x0={RFC1738:o(function(r){return M0.call(r,F0,"+")},"RFC1738"),RFC3986:o(function(r){return String(r)},"RFC3986")},$0=Hl.RFC1738,j0=Hl.RFC3986,B0=Array.isArray,gt=(function(){const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),Xs=1024,U0=o(function(e,t,s,n){if(e.length===0)return e;let i=e;typeof e=="symbol"?i=Symbol.prototype.toString.call(e):typeof e!="string"&&(i=String(e));let c="";for(let a=0;a<i.length;a+=Xs){let l=i.length>=Xs?i.slice(a,a+Xs):i;if(a+Xs<i.length){const u=l.charCodeAt(l.length-1);u>=55296&&u<=56319&&(l=l.slice(0,-1),a-=1)}const h=[];for(let u=0;u<l.length;++u){let p=l.charCodeAt(u);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||n===$0&&(p===40||p===41)){h[h.length]=l.charAt(u);continue}if(p<128){h[h.length]=gt[p];continue}if(p<2048){h[h.length]=gt[192|p>>6]+gt[128|p&63];continue}if(p<55296||p>=57344){h[h.length]=gt[224|p>>12]+gt[128|p>>6&63]+gt[128|p&63];continue}u+=1,p=65536+((p&1023)<<10|l.charCodeAt(u)&1023),h[h.length]=gt[240|p>>18]+gt[128|p>>12&63]+gt[128|p>>6&63]+gt[128|p&63]}c+=h.join("")}return c},"encode"),V0=o(function(e){return!e||typeof e!="object"?!1:!!(e.constructor&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e))},"isBuffer"),Wl=o(function(e,t){if(B0(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)},"maybeMap"),q0={brackets:o(function(e){return e+"[]"},"brackets"),comma:"comma",indices:o(function(e,t){return e+"["+t+"]"},"indices"),repeat:o(function(e){return e},"repeat")},Ot=Array.isArray,H0=Array.prototype.push,zl=o(function(r,e){H0.apply(r,Ot(e)?e:[e])},"pushToArray"),W0=Date.prototype.toISOString,Jl=j0,Qs={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:U0,encodeValuesOnly:!1,format:Jl,formatter:x0[Jl],indices:!1,serializeDate:o(function(e){return W0.call(e)},"serializeDate"),skipNulls:!1,strictNullHandling:!1},z0=o(function(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"},"isNonNullishPrimitive"),Zi={},Kl=o(function(e,t,s,n,i,c,a,l,h,u,p,g,f,d,y,b,m){let _=e,w=m,S=0,T=!1;for(;(w=w.get(Zi))!==void 0&&!T;){const C=w.get(e);if(S+=1,typeof C<"u"){if(C===S)throw new RangeError("Cyclic object value");T=!0}typeof w.get(Zi)>"u"&&(S=0)}if(typeof u=="function"?_=u(t,_):_ instanceof Date?_=f(_):s==="comma"&&Ot(_)&&(_=Wl(_,function(C){return C instanceof Date?f(C):C})),_===null){if(c)return h&&!b?h(t,Qs.encoder,"key",d):t;_=""}if(z0(_)||V0(_)){if(h){const C=b?t:h(t,Qs.encoder,"key",d);return[y(C)+"="+y(h(_,Qs.encoder,"value",d))]}return[y(t)+"="+y(String(_))]}const v=[];if(typeof _>"u")return v;let A;if(s==="comma"&&Ot(_))b&&h&&(_=Wl(_,function(C){return C===null||typeof C>"u"?C:h(C)})),A=[{value:_.length>0?_.join(",")||null:void 0}];else if(Ot(u))A=u;else{const C=Object.keys(_);A=p?C.sort(p):C}const O=l?t.replace(/\./g,"%2E"):t,k=n&&Ot(_)&&_.length===1?O+"[]":O;if(i&&Ot(_)&&_.length===0)return k+"[]";for(let C=0;C<A.length;++C){const B=A[C],q=typeof B=="object"&&typeof B.value<"u"?B.value:_[B];if(a&&q===null)continue;const de=g&&l?B.replace(/\./g,"%2E"):B,ge=Ot(_)?typeof s=="function"?s(k,de):k:k+(g?"."+de:"["+de+"]");m.set(e,S);const G=new WeakMap;G.set(Zi,m),zl(v,Kl(q,ge,s,n,i,c,a,l,s==="comma"&&b&&Ot(_)?null:h,u,p,g,f,d,y,b,G))}return v},"stringify"),J0=o(function(e){return Qs},"normalizeStringifyOptions");function K0(r,e){let t=r;const s=J0();let n,i;typeof s.filter=="function"?(i=s.filter,t=i("",t)):Ot(s.filter)&&(i=s.filter,n=i);const c=[];if(typeof t!="object"||t===null)return"";const a=q0[s.arrayFormat],l=a==="comma"&&s.commaRoundTrip;n||(n=Object.keys(t)),s.sort&&n.sort(s.sort);const h=new WeakMap;for(let g=0;g<n.length;++g){const f=n[g];s.skipNulls&&t[f]===null||zl(c,Kl(t[f],f,a,l,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,h))}const u=c.join(s.delimiter),p=s.addQueryPrefix===!0?"?":"";return u.length>0?p+u:""}o(K0,"stringify");var G0=Object.defineProperty,Y0=o((r,e)=>G0(r,"name",{value:e,configurable:!0}),"o$c");class Gl{static{o(this,"AbstractProcessing")}static{Y0(this,"AbstractProcessing")}async prepareItems(e,t){const s=new Map;return t.response.isSuccess?this._prepareItemsSuccess(e,t,s):s}async handleResults(e,t,s){const n=new ke;if(!s.response.isSuccess){for(const[i,c]of s.response.errors)n.addError(c,i);return n.setData({result:new Map,time:void 0}),n}return this._handleResultsSuccess(e,t,s,n)}_getBatchResultByIndex(e,t){if(e)return e[t]}_createErrorFromAjaxResult(e){return e.hasError("base-error")?e.errors.get("base-error"):new _e({code:"JSSDK_BATCH_SUB_ERROR",description:e.getErrorMessages().join("; "),status:e.getStatus(),requestInfo:{...e.getQuery()},originalError:e.getErrors().next().value})}}var Z0=Object.defineProperty,X0=o((r,e)=>Z0(r,"name",{value:e,configurable:!0}),"u$5");class Yl extends Gl{static{o(this,"AbstractProcessingV2")}static{X0(this,"AbstractProcessingV2")}_buildRow(e){return`${e.method}?${K0(e.query||{})}`}buildCommands(e){if(e.length<1)throw new D({code:"JSSDK_INTERACTION_BATCH_STRATEGY_V2_EMPTY_COMMANDS",description:"commands not set",status:500});const t=e[0];if(typeof t.as=="string"&&t.as.length>0){const n={};for(const i of e)n[i.as]=this._buildRow(i);return n}const s=[];for(const n of e)s.push(this._buildRow(n));return s}async _prepareItemsSuccess(e,t,s){for(const[n,i]of e.entries())await this._processResponseItem(i,i.as??n,t,s);return s}async _processResponseItem(e,t,s,n){const i=s.response.getData().result,c=this._getBatchResultByIndex(i.result,t),a=this._getBatchResultByIndex(i.result_error,t);if(typeof c<"u"||typeof a<"u"){const l=e.method,h=this._getBatchResultByIndex(i.result_time,t),u=new jr({answer:{error:a?typeof a=="string"?a:a.error:void 0,error_description:a?typeof a=="string"?void 0:a.error_description:void 0,result:c,total:Number.parseInt(this._getBatchResultByIndex(i.result_total,t)||"0"),next:Number.parseInt(this._getBatchResultByIndex(i.result_next,t)||"0"),time:h},query:{method:l,params:e.query||{},requestId:s.requestId},status:s.response.getStatus()});n.set(t,u);return}if(s.parallelDefaultValue)throw new D({code:"JSSDK_INTERACTION_BATCH_STRATEGY_V2_EMPTY_COMMAND_RESPONSE",description:`There were difficulties parsing the response for batch { index: ${t}, method: ${e.method} }`,status:500})}async _handleResultsSuccess(e,t,s,n){const i=new Map;for(const[c,a]of t){if(a.getStatus()!==200||!a.isSuccess){const l=this._createErrorFromAjaxResult(a);this._processResponseError(n,l,`${c}`),i.set(c,a)}i.set(c,a)}return n.setData({result:i,time:s.response.getData().time}),n}}var Q0=Object.defineProperty,eb=o((r,e)=>Q0(r,"name",{value:e,configurable:!0}),"o$b");class tb extends Yl{static{o(this,"ProcessingAsArrayV2")}static{eb(this,"ProcessingAsArrayV2")}prepareCommands(e,t){const s=[];return e.forEach(n=>{const i=Lt.getBatchCommand(n,t);s.push(i)}),s}_processResponseError(e,t,s){e.addError(t,s)}}var rb=Object.defineProperty,sb=o((r,e)=>rb(r,"name",{value:e,configurable:!0}),"s$c");class nb extends Yl{static{o(this,"ProcessingAsObjectV2")}static{sb(this,"ProcessingAsObjectV2")}prepareCommands(e,t){const s=[];return Object.entries(e).forEach(([n,i])=>{const c=Lt.getBatchCommand(i,{...t,asDefaultValue:n});s.push(c)}),s}_processResponseError(e,t,s){e.addError(t,s)}}var ib=Object.defineProperty,ob=o((r,e)=>ib(r,"name",{value:e,configurable:!0}),"i$4");class en extends Ul{static{o(this,"HttpV2")}static{ob(this,"HttpV2")}constructor(e,t,s){super(e,t,s),this._version=ee.v2}_prepareRequestConfig(e,t,s){if(s?.idempotencyKey===void 0)return super._prepareRequestConfig(e,t,s);this.getLogger().warning("http.call: `idempotencyKey` is ignored on `restApi:v2` \u2014 the portal honours `Idempotency-Key` only on the v3 endpoint (`/rest/api/`). Use `b24.actions.v3.call.make()` for an idempotent write, or an application-layer dedup guard if the method exists only on v2.",{requestId:e,method:t}).catch(()=>{});const{idempotencyKey:n,...i}=s;return super._prepareRequestConfig(e,t,i)}async batch(e,t){const s={isHaltOnError:!0,...t},n=s.requestId??this._requestIdGenerator.getRequestId();this._logBatchStart(n,e,s);const i=new P0({requestId:n,parallelDefaultValue:!s.isHaltOnError,restrictionManager:this._restrictionManager,logger:this.getLogger()});if(Array.isArray(e)?i.setProcessingStrategy(new tb):i.setProcessingStrategy(new nb),i.addCommands(e),i.size>i.maxSize)throw new _e({code:"JSSDK_BATCH_TOO_LARGE",description:`Batch too large: ${i.size} commands (max: ${i.maxSize})`,status:400,requestInfo:{method:"batch",params:{cmd:e},requestId:n},originalError:null});if(i.size===0)throw new _e({code:"JSSDK_BATCH_EMPTY",description:"Batch must contain at least one command",status:400,requestInfo:{method:"batch",params:{cmd:e},requestId:n},originalError:null});const c={halt:s.isHaltOnError?1:0,cmd:i.getCommandsForCall()},a=await this.call("batch",c,n),l=await i.prepareResponse(a);return this._logBatchCompletion(n,l.getData()?.result?.size??0,l.getErrorMessages().length),l}}var ab=Object.defineProperty,cb=o((r,e)=>ab(r,"name",{value:e,configurable:!0}),"s$b");const lb=50;class ub extends ql{static{o(this,"InteractionBatchV3")}static{cb(this,"InteractionBatchV3")}get maxSize(){return lb}async prepareResponse(e){if(!this.processingStrategy)throw new D({code:"JSSDK_INTERACTION_BATCH_EMPTY_PROCESSING_STRATEGY",description:"ProcessingStrategy not set",status:500});const t={requestId:e.getQuery().requestId,parallelDefaultValue:this.parallelDefaultValue,restrictionManager:this.restrictionManager,response:e},s=await this.processingStrategy.prepareItems(this._commands,t);return this.processingStrategy.handleResults(this._commands,s,t)}}var hb=Object.defineProperty,db=o((r,e)=>hb(r,"name",{value:e,configurable:!0}),"p$3");class Zl extends Gl{static{o(this,"AbstractProcessingV3")}static{db(this,"AbstractProcessingV3")}buildCommands(e){if(e.length<1)throw new D({code:"JSSDK_INTERACTION_BATCH_BUILD_STRATEGY_V3_EMPTY_COMMANDS",description:"commands not set",status:500});return e}async _prepareItemsSuccess(e,t,s){for(const[n,i]of e.entries())await this._processResponseItem(i,n,t,s);return s}async _processResponseItem(e,t,s,n){const i=s.response.getData().result,c=this._getBatchResultByIndex(i,t);if(typeof c>"u")throw new D({code:"JSSDK_INTERACTION_BATCH_STRATEGY_V3_EMPTY_COMMAND_RESPONSE",description:`There were difficulties parsing the response for batch { index: ${t}, method: ${e.method} }`,status:500});const a=s.response.getData().time,l=new jr({answer:{result:c,error:void 0,time:a},query:{method:e.method,params:e.query||{},requestId:s.requestId},status:s.response.getStatus()});n.set(t,l)}async _handleResultsSuccess(e,t,s,n){const i=new Map;for(const[c,a]of t){const l=Number.parseInt(`${c}`),h=e[l];if(typeof h>"u")throw new D({code:"JSSDK_INTERACTION_BATCH_BUILD_STRATEGY_V3_EMPTY_COMMAND",description:`command for index ${c} not set`,status:500});const u=h.as??c;if(a.getStatus()!==200||!a.isSuccess){const p=this._createErrorFromAjaxResult(a);this._processResponseError(n,p,`${u}`),i.set(u,a)}i.set(u,a)}return n.setData({result:i,time:s.response.getData().time}),n}}var fb=Object.defineProperty,pb=o((r,e)=>fb(r,"name",{value:e,configurable:!0}),"o$9");class gb extends Zl{static{o(this,"ProcessingAsArrayV3")}static{pb(this,"ProcessingAsArrayV3")}prepareCommands(e,t){const s=[];return e.forEach(n=>{const i=Lt.getBatchCommand(n,t);s.push(i)}),s}_processResponseError(e,t,s){e.addError(t,s)}}var mb=Object.defineProperty,yb=o((r,e)=>mb(r,"name",{value:e,configurable:!0}),"s$a");class bb extends Zl{static{o(this,"ProcessingAsObjectV3")}static{yb(this,"ProcessingAsObjectV3")}prepareCommands(e,t){const s=[];return Object.entries(e).forEach(([n,i])=>{const c=Lt.getBatchCommand(i,{...t,asDefaultValue:n});s.push(c)}),s}_processResponseError(e,t,s){e.addError(t,s)}}var _b=Object.defineProperty,wb=o((r,e)=>_b(r,"name",{value:e,configurable:!0}),"n$7");class tn extends Ul{static{o(this,"HttpV3")}static{wb(this,"HttpV3")}constructor(e,t,s){super(e,t,s),this._version=ee.v3}async batch(e,t){const s={isHaltOnError:!0,...t},n=s.requestId??this._requestIdGenerator.getRequestId();this._logBatchStart(n,e,s);const i=new ub({requestId:n,parallelDefaultValue:!s.isHaltOnError,restrictionManager:this._restrictionManager,logger:this.getLogger()});if(Array.isArray(e)?i.setProcessingStrategy(new gb):i.setProcessingStrategy(new bb),i.addCommands(e),i.size>i.maxSize)throw new _e({code:"JSSDK_BATCH_TOO_LARGE",description:`Batch too large: ${i.size} commands (max: ${i.maxSize})`,status:400,requestInfo:{method:"batch",params:{cmd:e},requestId:n},originalError:null});if(i.size===0)throw new _e({code:"JSSDK_BATCH_EMPTY",description:"Batch must contain at least one command",status:400,requestInfo:{method:"batch",params:{cmd:e},requestId:n},originalError:null});const c=await this.call("batch",i.getCommandsForCall(),n),a=await i.prepareResponse(c);return this._logBatchCompletion(n,a.getData()?.result?.size??0,a.getErrorMessages().length),a}}var Sb=Object.defineProperty,vb=o((r,e)=>Sb(r,"name",{value:e,configurable:!0}),"e$3");const Eb=vb(()=>({scrollWidth:Math.max(document.documentElement.scrollWidth,document.documentElement.offsetWidth),scrollHeight:Math.max(document.documentElement.scrollHeight,document.documentElement.offsetHeight)}),"useScrollSize");var Ob=Object.defineProperty,Tb=o((r,e)=>Ob(r,"name",{value:e,configurable:!0}),"s$9");let Ab=class $t{static{o(this,"t")}static{Tb(this,"FormatterNumbers")}static isInternalConstructing=!1;static instance=null;_defLocale=null;constructor(){if(!$t.isInternalConstructing)throw new TypeError("FormatterNumber is not constructable");$t.isInternalConstructing=!1}static getInstance(){return $t.instance||($t.isInternalConstructing=!0,$t.instance=new $t),$t.instance}setDefLocale(e){this._defLocale=e}format(e,t){let s;(typeof t>"u"||!F.isStringFilled(t))&&(t=F.isStringFilled(this._defLocale)?this._defLocale||"en":typeof navigator>"u"?"en":navigator?.language||"en"),Number.isInteger(e)?s=new Intl.NumberFormat(t,{minimumFractionDigits:0,maximumFractionDigits:0}):s=new Intl.NumberFormat(t,{minimumFractionDigits:2,maximumFractionDigits:2});let n=s.format(e);return t.includes("ru")&&(n=n.replace(",",".")),n}};var kb=Object.defineProperty,Xl=o((r,e)=>kb(r,"name",{value:e,configurable:!0}),"n$6");class R{static{o(this,"IbanSpecification")}static{Xl(this,"IbanSpecification")}countryCode;length;structure;example;_cachedRegex=null;constructor(e,t,s,n){this.countryCode=e,this.length=t,this.structure=s,this.example=n}isValid(e){return this.length===e.length&&this.countryCode===e.slice(0,2)&&this._regex().test(e.slice(4))&&this._iso7064Mod9710(this._iso13616Prepare(e))==1}toBBAN(e,t){return(this._regex().exec(e.slice(4)||"")||[]).slice(1).join(t)}fromBBAN(e){if(!this.isValidBBAN(e))throw new Error("Invalid BBAN");const t=("0"+(98-this._iso7064Mod9710(this._iso13616Prepare(this.countryCode+"00"+e)))).slice(-2);return this.countryCode+t+e}isValidBBAN(e){return this.length-4===e.length&&this._regex().test(e)}_regex(){return this._cachedRegex===null&&(this._cachedRegex=this._parseStructure(this.structure)),this._cachedRegex}_parseStructure(e){const t=(e.match(/(.{3})/g)||[]).map(s=>{let n;const i=s.slice(0,1),c=Number.parseInt(s.slice(1),10);switch(i){case"A":n="0-9A-Za-z";break;case"B":n="0-9A-Z";break;case"C":n="A-Za-z";break;case"F":n="0-9";break;case"L":n="a-z";break;case"U":n="A-Z";break;case"W":n="0-9a-z";break}return"(["+n+"]{"+c+"})"});return new RegExp("^"+t.join("")+"$")}_iso13616Prepare(e){return e=e.toUpperCase(),e=e.substring(4)+e.substring(0,4),e.split("").map(t=>{const s=t.charCodeAt(0);return s>=65&&s<=90?(s-65+10).toString():t}).join("")}_iso7064Mod9710(e){let t=e,s;for(;t.length>2;)s=t.slice(0,9),t=Number.parseInt(s,10)%97+t.slice(s.length);return Number.parseInt(t,10)%97}}class Tt{static{o(this,"FormatterIban")}static{Xl(this,"FormatterIban")}static isInternalConstructing=!1;static instance=null;_countries;constructor(){if(!Tt.isInternalConstructing)throw new TypeError("FormatterIban is not constructable");Tt.isInternalConstructing=!1,this._countries=new Map}static getInstance(){return Tt.instance||(Tt.isInternalConstructing=!0,Tt.instance=new Tt),Tt.instance}addSpecification(e){this._countries.set(e.countryCode,e)}isValid(e){if(!F.isString(e))return!1;e=this.electronicFormat(e);const t=e.slice(0,2);if(!this._countries.has(t))throw new Error(`No country with code ${t}`);const s=this._countries.get(t);return!!s&&s.isValid(e)}printFormat(e,t){typeof t>"u"&&(t=" ");const s=/(.{4})(?!$)/g;return this.electronicFormat(e).replace(s,"$1"+t)}electronicFormat(e){const t=/[^a-z0-9]/gi;return e.replace(t,"").toUpperCase()}toBBAN(e,t){typeof t>"u"&&(t=" "),e=this.electronicFormat(e);const s=e.slice(0,2);if(!this._countries.has(s))throw new Error(`No country with code ${s}`);const n=this._countries.get(s);if(!n)throw new Error(`No country with code ${s}`);return n.toBBAN(e,t)}fromBBAN(e,t){if(!this._countries.has(e))throw new Error(`No country with code ${e}`);const s=this._countries.get(e);if(!s)throw new Error(`No country with code ${e}`);return s.fromBBAN(this.electronicFormat(t))}isValidBBAN(e,t){if(!F.isString(t))return!1;if(!this._countries.has(e))throw new Error(`No country with code ${e}`);const s=this._countries.get(e);return!!s&&s.isValidBBAN(this.electronicFormat(t))}}var Ib=Object.defineProperty,Rb=o((r,e)=>Ib(r,"name",{value:e,configurable:!0}),"n$5");const Cb=Rb(()=>{const r=Ab.getInstance(),e=Tt.getInstance();return e.addSpecification(new R("AD",24,"F04F04A12","AD1200012030200359100100")),e.addSpecification(new R("AE",23,"F03F16","AE070331234567890123456")),e.addSpecification(new R("AL",28,"F08A16","AL47212110090000000235698741")),e.addSpecification(new R("AT",20,"F05F11","AT611904300234573201")),e.addSpecification(new R("AZ",28,"U04A20","AZ21NABZ00000000137010001944")),e.addSpecification(new R("BA",20,"F03F03F08F02","BA391290079401028494")),e.addSpecification(new R("BE",16,"F03F07F02","BE68539007547034")),e.addSpecification(new R("BG",22,"U04F04F02A08","BG80BNBG96611020345678")),e.addSpecification(new R("BH",22,"U04A14","BH67BMAG00001299123456")),e.addSpecification(new R("BR",29,"F08F05F10U01A01","BR9700360305000010009795493P1")),e.addSpecification(new R("BY",28,"A04F04A16","BY13NBRB3600900000002Z00AB00")),e.addSpecification(new R("CH",21,"F05A12","CH9300762011623852957")),e.addSpecification(new R("CR",22,"F04F14","CR72012300000171549015")),e.addSpecification(new R("CY",28,"F03F05A16","CY17002001280000001200527600")),e.addSpecification(new R("CZ",24,"F04F06F10","CZ6508000000192000145399")),e.addSpecification(new R("DE",22,"F08F10","DE89370400440532013000")),e.addSpecification(new R("DK",18,"F04F09F01","DK5000400440116243")),e.addSpecification(new R("DO",28,"U04F20","DO28BAGR00000001212453611324")),e.addSpecification(new R("EE",20,"F02F02F11F01","EE382200221020145685")),e.addSpecification(new R("EG",29,"F04F04F17","EG800002000156789012345180002")),e.addSpecification(new R("ES",24,"F04F04F01F01F10","ES9121000418450200051332")),e.addSpecification(new R("FI",18,"F06F07F01","FI2112345600000785")),e.addSpecification(new R("FO",18,"F04F09F01","FO6264600001631634")),e.addSpecification(new R("FR",27,"F05F05A11F02","FR1420041010050500013M02606")),e.addSpecification(new R("GB",22,"U04F06F08","GB29NWBK60161331926819")),e.addSpecification(new R("GE",22,"U02F16","GE29NB0000000101904917")),e.addSpecification(new R("GI",23,"U04A15","GI75NWBK000000007099453")),e.addSpecification(new R("GL",18,"F04F09F01","GL8964710001000206")),e.addSpecification(new R("GR",27,"F03F04A16","GR1601101250000000012300695")),e.addSpecification(new R("GT",28,"A04A20","GT82TRAJ01020000001210029690")),e.addSpecification(new R("HR",21,"F07F10","HR1210010051863000160")),e.addSpecification(new R("HU",28,"F03F04F01F15F01","HU42117730161111101800000000")),e.addSpecification(new R("IE",22,"U04F06F08","IE29AIBK93115212345678")),e.addSpecification(new R("IL",23,"F03F03F13","IL620108000000099999999")),e.addSpecification(new R("IS",26,"F04F02F06F10","IS140159260076545510730339")),e.addSpecification(new R("IT",27,"U01F05F05A12","IT60X0542811101000000123456")),e.addSpecification(new R("IQ",23,"U04F03A12","IQ98NBIQ850123456789012")),e.addSpecification(new R("JO",30,"A04F22","JO15AAAA1234567890123456789012")),e.addSpecification(new R("KW",30,"U04A22","KW81CBKU0000000000001234560101")),e.addSpecification(new R("KZ",20,"F03A13","KZ86125KZT5004100100")),e.addSpecification(new R("LB",28,"F04A20","LB62099900000001001901229114")),e.addSpecification(new R("LC",32,"U04F24","LC07HEMM000100010012001200013015")),e.addSpecification(new R("LI",21,"F05A12","LI21088100002324013AA")),e.addSpecification(new R("LT",20,"F05F11","LT121000011101001000")),e.addSpecification(new R("LU",20,"F03A13","LU280019400644750000")),e.addSpecification(new R("LV",21,"U04A13","LV80BANK0000435195001")),e.addSpecification(new R("MC",27,"F05F05A11F02","MC5811222000010123456789030")),e.addSpecification(new R("MD",24,"U02A18","MD24AG000225100013104168")),e.addSpecification(new R("ME",22,"F03F13F02","ME25505000012345678951")),e.addSpecification(new R("MK",19,"F03A10F02","MK07250120000058984")),e.addSpecification(new R("MR",27,"F05F05F11F02","MR1300020001010000123456753")),e.addSpecification(new R("MT",31,"U04F05A18","MT84MALT011000012345MTLCAST001S")),e.addSpecification(new R("MU",30,"U04F02F02F12F03U03","MU17BOMM0101101030300200000MUR")),e.addSpecification(new R("NL",18,"U04F10","NL91ABNA0417164300")),e.addSpecification(new R("NO",15,"F04F06F01","NO9386011117947")),e.addSpecification(new R("PK",24,"U04A16","PK36SCBL0000001123456702")),e.addSpecification(new R("PL",28,"F08F16","PL61109010140000071219812874")),e.addSpecification(new R("PS",29,"U04A21","PS92PALS000000000400123456702")),e.addSpecification(new R("PT",25,"F04F04F11F02","PT50000201231234567890154")),e.addSpecification(new R("QA",29,"U04A21","QA30AAAA123456789012345678901")),e.addSpecification(new R("RO",24,"U04A16","RO49AAAA1B31007593840000")),e.addSpecification(new R("RS",22,"F03F13F02","RS35260005601001611379")),e.addSpecification(new R("SA",24,"F02A18","SA0380000000608010167519")),e.addSpecification(new R("SC",31,"U04F04F16U03","SC18SSCB11010000000000001497USD")),e.addSpecification(new R("SE",24,"F03F16F01","SE4550000000058398257466")),e.addSpecification(new R("SI",19,"F05F08F02","SI56263300012039086")),e.addSpecification(new R("SK",24,"F04F06F10","SK3112000000198742637541")),e.addSpecification(new R("SM",27,"U01F05F05A12","SM86U0322509800000000270100")),e.addSpecification(new R("ST",25,"F08F11F02","ST68000100010051845310112")),e.addSpecification(new R("SV",28,"U04F20","SV62CENR00000000000000700025")),e.addSpecification(new R("TL",23,"F03F14F02","TL380080012345678910157")),e.addSpecification(new R("TN",24,"F02F03F13F02","TN5910006035183598478831")),e.addSpecification(new R("TR",26,"F05F01A16","TR330006100519786457841326")),e.addSpecification(new R("UA",29,"F25","UA511234567890123456789012345")),e.addSpecification(new R("VA",22,"F18","VA59001123000012345678")),e.addSpecification(new R("VG",24,"U04F16","VG96VPVG0000012345678901")),e.addSpecification(new R("XK",20,"F04F10F02","XK051212012345678906")),e.addSpecification(new R("AO",25,"F21","AO69123456789012345678901")),e.addSpecification(new R("BF",27,"F23","BF2312345678901234567890123")),e.addSpecification(new R("BI",16,"F12","BI41123456789012")),e.addSpecification(new R("BJ",28,"F24","BJ39123456789012345678901234")),e.addSpecification(new R("CI",28,"U02F22","CI70CI1234567890123456789012")),e.addSpecification(new R("CM",27,"F23","CM9012345678901234567890123")),e.addSpecification(new R("CV",25,"F21","CV30123456789012345678901")),e.addSpecification(new R("DZ",24,"F20","DZ8612345678901234567890")),e.addSpecification(new R("IR",26,"F22","IR861234568790123456789012")),e.addSpecification(new R("MG",27,"F23","MG1812345678901234567890123")),e.addSpecification(new R("ML",28,"U01F23","ML15A12345678901234567890123")),e.addSpecification(new R("MZ",25,"F21","MZ25123456789012345678901")),e.addSpecification(new R("SN",28,"U01F23","SN52A12345678901234567890123")),e.addSpecification(new R("GF",27,"F05F05A11F02","GF121234512345123456789AB13")),e.addSpecification(new R("GP",27,"F05F05A11F02","GP791234512345123456789AB13")),e.addSpecification(new R("MQ",27,"F05F05A11F02","MQ221234512345123456789AB13")),e.addSpecification(new R("RE",27,"F05F05A11F02","RE131234512345123456789AB13")),e.addSpecification(new R("PF",27,"F05F05A11F02","PF281234512345123456789AB13")),e.addSpecification(new R("TF",27,"F05F05A11F02","TF891234512345123456789AB13")),e.addSpecification(new R("YT",27,"F05F05A11F02","YT021234512345123456789AB13")),e.addSpecification(new R("NC",27,"F05F05A11F02","NC551234512345123456789AB13")),e.addSpecification(new R("BL",27,"F05F05A11F02","BL391234512345123456789AB13")),e.addSpecification(new R("MF",27,"F05F05A11F02","MF551234512345123456789AB13")),e.addSpecification(new R("PM",27,"F05F05A11F02","PM071234512345123456789AB13")),e.addSpecification(new R("WF",27,"F05F05A11F02","WF621234512345123456789AB13")),{formatterNumber:r,formatterIban:e}},"useFormatter");var Nb=Object.defineProperty,Xi=o((r,e)=>Nb(r,"name",{value:e,configurable:!0}),"o$6");const Qi=["=","!=",">",">=","<","<=","in","between"];function At(r,e,t){if(typeof r!="string"||r.length===0)throw new D({code:"JSSDK_FILTER_V3_INVALID_FIELD",description:`FilterV3: field name must be a non-empty string, got ${JSON.stringify(r)}.`,status:400});if(!Qi.includes(e))throw new D({code:"JSSDK_FILTER_V3_INVALID_OPERATOR",description:`FilterV3: operator "${e}" is not one of ${Qi.join(" ")}.`,status:400});return[r,e,t]}o(At,"e$2"),Xi(At,"condition");const Db=Object.freeze({eq(r,e){return At(r,"=",e)},ne(r,e){return At(r,"!=",e)},gt(r,e){return At(r,">",e)},ge(r,e){return At(r,">=",e)},lt(r,e){return At(r,"<",e)},le(r,e){return At(r,"<=",e)},in(r,e){if(!Array.isArray(e)||e.length===0)throw new D({code:"JSSDK_FILTER_V3_INVALID_IN",description:`FilterV3.in("${r}"): value must be a non-empty array.`,status:400});return At(r,"in",e)},between(r,e,t){if(e==null||t===void 0||t===null)throw new D({code:"JSSDK_FILTER_V3_INVALID_BETWEEN",description:`FilterV3.between("${r}"): both range operands must be defined (got [${String(e)}, ${String(t)}]).`,status:400});return At(r,"between",[e,t])},and(...r){return{logic:"and",conditions:r}},or(...r){return{logic:"or",conditions:r}},not(r){return eo(r)?{...r,conditions:[...r.conditions],negative:!0}:{logic:"and",negative:!0,conditions:[r]}},build(...r){const e=r.filter(Boolean);for(const t of e)Ql(t);return e}});function eo(r){return!Array.isArray(r)&&typeof r=="object"&&r!==null&&"conditions"in r}o(eo,"u$4"),Xi(eo,"isGroup");function Ql(r){if(!eo(r)&&!(Array.isArray(r)&&typeof r[0]=="string"&&r[0].length>0&&(r.length===2||r.length===3&&Qi.includes(r[1]))))throw new D({code:"JSSDK_FILTER_V3_INVALID_NODE",description:`FilterV3.build: each node must be a [field, operator, value] condition, a [field, value] equality or a group \u2014 got ${JSON.stringify(r)}. Did you forget to spread (build(...nodes)) or build a condition with FilterV3 helpers?`,status:400})}o(Ql,"d$2"),Xi(Ql,"assertNode");var Lb=Object.defineProperty,Pb=o((r,e)=>Lb(r,"name",{value:e,configurable:!0}),"t$5");function to(r,e){if(typeof r!="string"||r.length===0)throw new D({code:"JSSDK_BATCH_REF_V3_INVALID_PATH",description:`${e}: path must be a non-empty dotted string (e.g. "tasks.id").`,status:400})}o(to,"a$a"),Pb(to,"assertPath");const Mb=Object.freeze({ref(r){return to(r,"BatchRefV3.ref"),{$ref:r}},refArray(r){if(to(r,"BatchRefV3.refArray"),!r.includes("."))throw new D({code:"JSSDK_BATCH_REF_V3_INVALID_REF_ARRAY",description:`BatchRefV3.refArray: path "${r}" must contain a dot ("alias.field") \u2014 the server collects <field> across the alias's items[].`,status:400});return{$refArray:r}}});var Fb=Object.defineProperty,xb=o((r,e)=>Fb(r,"name",{value:e,configurable:!0}),"r$6");class eu{static{o(this,"AuthHookManager")}static{xb(this,"AuthHookManager")}#e;#t;#s;#r;#i;constructor(e){this.#e=Object.freeze(Object.assign({},e)),this.#t=this.#e.b24Url.replaceAll("https://","").replaceAll("http://","").replace(/:(80|443)$/,""),this.#s=`https://${this.#t}/rest`,this.#r=`https://${this.#t}`,this.#i=new Map,this.#i.set(ee.v2,`${this.#s}/${this.#e.userId}/${this.#e.secret}`),this.#i.set(ee.v3,`${this.#s}/api/${this.#e.userId}/${this.#e.secret}`)}getAuthData(){return{access_token:this.#e.secret,refresh_token:"hook",expires:0,expires_in:0,domain:this.#t,member_id:this.#t}}refreshAuth(){return Promise.resolve(this.getAuthData())}getUniq(e){const t=this.getAuthData();if(t===!1)throw new Error("AuthData not init");return[e,t.member_id].join("_")}getTargetOrigin(){return`${this.#r}`}getTargetOriginWithPath(){return this.#i}get isAdmin(){return!0}}var $b=Object.defineProperty,jb=o((r,e)=>$b(r,"name",{value:e,configurable:!0}),"n$4");class ro extends js{static{o(this,"B24Hook")}static{jb(this,"B24Hook")}#e;constructor(e,t){super(),this.#e=new eu(e);const s=`The B24Hook object is intended exclusively for use on the server.
A webhook contains a secret access key, which MUST NOT be used in client-side code (browser, worker, mobile app).`;this._httpOptions=t?.httpOptions??null,this._httpV2=new en(this.#e,this._getHttpOptions(),t?.restrictionParams),this._httpV2.setClientSideWarning(!0,s),this._httpV3=new tn(this.#e,this._getHttpOptions(),t?.restrictionParams),this._httpV3.setClientSideWarning(!0,s),this._isInit=!0}get auth(){return this.#e}offClientSideWarning(){fr.getAllApiVersions().forEach(e=>{this.getHttpClient(e).setClientSideWarning(!1,"")})}getTargetOrigin(){return this._ensureInitialized(),this.#e.getTargetOrigin()}getTargetOriginWithPath(){return this._ensureInitialized(),this.#e.getTargetOriginWithPath()}static fromWebhookUrl(e,t){if(!e.trim())throw new D({code:"JSSDK_HOOK_URL_EMPTY",description:"Webhook URL cannot be empty",status:0});let s;try{s=new URL(e.replace("/rest/api","/rest"))}catch{throw new D({code:"JSSDK_HOOK_URL_INVALID",description:"Invalid webhook URL format",status:0})}if(s.protocol!=="https:")throw new D({code:"JSSDK_HOOK_URL_NOT_HTTPS",description:"Webhook requires HTTPS protocol",status:0});const n=s.pathname.split("/").filter(Boolean);if(!(n.length===3&&n[0]==="rest"||n.length===4&&n[0]==="rest"&&n[1]==="api"))throw new D({code:"JSSDK_HOOK_URL_MALFORMED",description:"Webhook URL must follow format: /rest/<userId>/<secret> or /rest/api/<userId>/<secret>",status:0});const i=n[1]==="api"?2:1,c=n[1]==="api"?3:2,a=n[i],l=n[c];if(!/^\d+$/.test(a))throw new D({code:"JSSDK_HOOK_URL_USER_ID_NOT_NUMERIC",description:"User ID must be numeric in webhook URL",status:0});const h=Number.parseInt(a,10);return new ro({b24Url:s.origin,userId:h,secret:l},t)}}var le=(r=>(r.getInitData="getInitData",r.setInstallFinish="setInstallFinish",r.setInstall="setInstall",r.refreshAuth="refreshAuth",r.setAppOption="setAppOption",r.setUserOption="setUserOption",r.resizeWindow="resizeWindow",r.reloadWindow="reloadWindow",r.setTitle="setTitle",r.setScroll="setScroll",r.openApplication="openApplication",r.closeApplication="closeApplication",r.openPath="openPath",r.imCallTo="imCallTo",r.imPhoneTo="imPhoneTo",r.imOpenMessenger="imOpenMessenger",r.imOpenHistory="imOpenHistory",r.selectUser="selectUser",r.selectAccess="selectAccess",r.selectCRM="selectCRM",r.showAppForm="showAppForm",r.getInterface="getInterface",r.placementBindEvent="placementBindEvent",r))(le||{}),Bb=Object.defineProperty,Ub=o((r,e)=>Bb(r,"name",{value:e,configurable:!0}),"m$4");const Vb=50,qb=64;class tu{static{o(this,"MessageManager")}static{Ub(this,"MessageManager")}#e;#t;#s;#r=new Set;_logger;runCallbackHandler;constructor(e){this._logger=ae.createNullLogger(),this.#e=e,this.#t=new Map,this.#s=new Map,this.runCallbackHandler=this._runCallback.bind(this)}setLogger(e){this._logger=e}getLogger(){return this._logger}subscribe(){window.addEventListener("message",this.runCallbackHandler)}unsubscribe(){window.removeEventListener("message",this.runCallbackHandler);for(const[e,t]of this.#t)t.timeoutId&&clearTimeout(t.timeoutId),this.#t.delete(e),t.reject(new D({code:"JSSDK_FRAME_DISPOSED",description:"The B24Frame was destroyed before the parent window answered this command.",status:0}));this.#s.clear(),this.#r.clear()}async send(e,t=null){return new Promise((s,n)=>{let i;const c={resolve:s,reject:n,timeoutId:null},a=this.#n(c);let l=null;const h=Vn(t||{},["singleOption","callBack","isSafely","safelyTime","requestId"]),{callBack:u,singleOption:p,requestId:g}=t||{};if(u&&this.#s.set(a,u),p?l=p:Object.keys(h).length>0&&(l={...h}),e.toString().includes(":"))i={method:e.toString(),params:l||"",callback:a,appSid:this.#e.getAppSid(),requestId:g};else{i=e.toString(),t?.isRawValue!==!0&&l?l=JSON.stringify(l):t?.isRawValue===!0&&l&&F.isPlainObject(l)&&l.value&&(l=l.value);const f=[l||"",a,this.#e.getAppSid()];i+=":"+f.filter(Boolean).join(":")}if(this.getLogger().debug(`send to ${this.#e.getTargetOrigin()}`,{command:e.toString(),callbackKey:a,origin:this.#e.getTargetOrigin()}).catch(()=>{}),parent.postMessage(i,this.#e.getTargetOrigin()),t?.isSafely){const f=Number.parseInt(String(t?.safelyTime||900));this.#t.get(a).timeoutId=window.setTimeout(()=>{this.#t.has(a)&&(this.getLogger().warning(`action ${e.toString()} stop by timeout`,{command:e.toString(),safelyTime:f}).catch(()=>{}),this.#t.delete(a),s({isSafely:!0}))},f)}})}_runCallback(e){if(e.origin!==this.#e.getTargetOrigin()){!this.#r.has(e.origin)&&this.#r.size<Vb&&(this.#r.add(e.origin),this.getLogger().warning("message rejected: unexpected origin",{origin:e.origin,expected:this.#e.getTargetOrigin()}).catch(()=>{}));return}if(typeof e.data=="string"&&e.data.length>0){const[t="",...s]=e.data.split(":"),n={id:t,args:s.join(":")};if(this.getLogger().debug(`get from ${e.origin}`,{id:n.id,origin:e.origin}).catch(()=>{}),n.args)try{n.args=JSON.parse(n.args)}catch{this.getLogger().warning("message dropped: payload is not valid JSON",{id:n.id,origin:e.origin}).catch(()=>{}),this.#i(n.id,new D({code:"JSSDK_FRAME_BAD_PAYLOAD",description:`The parent window answered command "${n.id.slice(0,qb)}" with a payload that is not valid JSON.`,status:0}));return}if(this.#t.has(n.id)){const i=this.#t.get(n.id);i.timeoutId&&clearTimeout(i.timeoutId),this.#t.delete(n.id),i.resolve(n.args)}else if(this.#s.has(n.id)){const i=this.#s.get(n.id);i&&i.apply(globalThis,[n.args])}}}#i(e,t){const s=this.#t.get(e);s&&(s.timeoutId&&clearTimeout(s.timeoutId),this.#t.delete(e),s.reject(t))}#n(e){const t=W.getUniqId();return this.#t.set(t,e),t}}var Hb=Object.defineProperty,Wb=o((r,e)=>Hb(r,"name",{value:e,configurable:!0}),"r$5");class ru{static{o(this,"AppFrame")}static{Wb(this,"AppFrame")}#e="";#t=!0;#s=null;#r=null;#i=null;#n;#o;#a;constructor(e){e.DOMAIN&&(this.#e=e.DOMAIN,this.#e=this.#e.replace(/:(80|443)$/,"")),this.#t=e.PROTOCOL===!0,e.LANG&&(this.#i=e.LANG),e.APP_SID&&(this.#s=e.APP_SID),this.#a=new Map,this.#o=`${this.#t?"https":"http"}://${this.#e}`,this.#n=`${this.#o}/rest`,this.#a.set(ee.v2,`${this.#n}`),this.#a.set(ee.v3,`${this.#n}/api`)}initData(e){return this.#e||(this.#e=e.DOMAIN),this.#r||(this.#r=e.PATH),this.#i||(this.#i=e.LANG),this.#t=Number.parseInt(e.PROTOCOL)===1,this.#e=this.#e.replace(/:(80|443)$/,""),this.#o=`${this.#t?"https":"http"}://${this.#e}`,this.#n=`${this.#o}/rest`,this.#a.set(ee.v2,`${this.#n}`),this.#a.set(ee.v3,`${this.#n}/api`),this}getAppSid(){if(this.#s===null)throw new D({code:"JSSDK_FRAME_APP_SID_NOT_INIT",description:"Not init appSid",status:0});return this.#s}getTargetOrigin(){return this.#o}getTargetOriginWithPath(){return this.#a}getLang(){return this.#i||zn.en}}var zb=Object.defineProperty,Jb=o((r,e)=>zb(r,"name",{value:e,configurable:!0}),"n$3");const su=1e4;class nu{static{o(this,"AuthManager")}static{Jb(this,"AuthManager")}#e=null;#t=null;#s=0;#r=0;#i=null;#n=!1;#o=null;#a;#h;constructor(e,t){this.#a=e,this.#h=t}initData(e){return e.AUTH_ID&&(this.#e=e.AUTH_ID,this.#t=e.REFRESH_ID,this.#r=Number.parseInt(e.AUTH_EXPIRES),this.#s=Date.now()+this.#r*1e3,this.#n=e.IS_ADMIN,this.#i=e.MEMBER_ID||""),this}getAuthData(){return this.#s>Date.now()?{access_token:this.#e,refresh_token:this.#t,expires:this.#s/1e3,expires_in:this.#r,domain:this.#a.getTargetOrigin(),member_id:this.#i}:!1}refreshAuth(){if(this.#o!==null)return this.#o;const e=(async()=>{try{return await this.#d()}finally{this.#o=null}})();return this.#o=e,e}async#d(){let e;const t=new Promise((s,n)=>{e=setTimeout(()=>n(new D({code:"JSSDK_FRAME_REFRESH_AUTH_TIMEOUT",status:408,description:`refreshAuth: the parent window did not answer within ${su}ms`})),su)});try{const s=await Promise.race([this.#h.send(le.refreshAuth,{}),t]),n=Number.parseInt(s?.AUTH_EXPIRES);if(!Number.isFinite(n)||n<=0)throw new D({code:"JSSDK_FRAME_REFRESH_AUTH_BAD_RESPONSE",status:500,description:"refreshAuth: the parent window answered without a usable AUTH_EXPIRES"});return this.#e=s.AUTH_ID,this.#t=s.REFRESH_ID,this.#r=n,this.#s=Date.now()+n*1e3,this.getAuthData()}finally{e&&clearTimeout(e)}}getUniq(e){return[e,this.#i||""].join("_")}get isAdmin(){return this.#n}getTargetOrigin(){return this.#a.getTargetOrigin()}getTargetOriginWithPath(){return this.#a.getTargetOriginWithPath()}}var Kb=Object.defineProperty,Gb=o((r,e)=>Kb(r,"name",{value:e,configurable:!0}),"m$3");class iu{static{o(this,"ParentManager")}static{Gb(this,"ParentManager")}#e;constructor(e){this.#e=e}get message(){return this.#e}async closeApplication(){return this.#e.send(le.closeApplication,{isSafely:!1})}async fitWindow(){const e="100%",t=this.getScrollSize().scrollHeight;return this.#e.send(le.resizeWindow,{width:e,height:t,isSafely:!0})}async resizeWindow(e,t){return e>0&&t>0?this.#e.send(le.resizeWindow,{width:e,height:t,isSafely:!0}):Promise.reject(new Error(`Wrong width:number = ${e} or height:number = ${t}`))}async resizeWindowAuto(e=null,t=0,s=0){const n=document.body;let i=Math.max(n.scrollWidth,n.offsetWidth);s>0&&(i=Math.max(s,i));let c=Math.max(n.scrollHeight,n.offsetHeight);return e&&(c=Math.max(e.scrollHeight,e.offsetHeight)),t>0&&(c=Math.max(t,c)),this.resizeWindow(i,c)}getScrollSize(){return Eb()}async scrollParentWindow(e){return Number.isInteger(e)?(e<0&&(e=0),this.#e.send(le.setScroll,{scroll:e,isSafely:!0})):Promise.reject(new Error("Wrong scroll number"))}async reloadWindow(){return this.#e.send(le.reloadWindow,{isSafely:!0})}async setTitle(e){return this.#e.send(le.setTitle,{title:e.toString(),isSafely:!0})}async imCallTo(e,t=!0){return this.#e.send(le.imCallTo,{userId:e,video:t,isSafely:!0})}async imPhoneTo(e,t){return this.#e.send(le.imPhoneTo,{phone:e,...t===void 0?{}:{params:t},isSafely:!0})}async imOpenMessenger(e,t){return this.#e.send(le.imOpenMessenger,{dialogId:e,...t===void 0?{}:{messageId:t},isSafely:!0})}async imOpenHistory(e){return this.#e.send(le.imOpenHistory,{dialogId:e,isSafely:!0})}}var Yb=Object.defineProperty,Zb=o((r,e)=>Yb(r,"name",{value:e,configurable:!0}),"r$4");let ou=class{static{o(this,"OptionsManager")}static{Zb(this,"OptionsManager")}#e;#t=null;#s=null;constructor(e){this.#e=e}initData(e){return e.APP_OPTIONS&&(this.#t=e.APP_OPTIONS),e.USER_OPTIONS&&(this.#s=e.USER_OPTIONS),this}appGet(e){if(this.#t&&this.#t[e])return this.#t[e];throw new Error(`app.option.${e} not set`)}async appSet(e,t){return this.#t||(this.#t=[]),this.#t[e]=t,this.#r(le.setAppOption,e,this.#t[e])}userGet(e){if(this.#s&&this.#s[e])return this.#s[e];throw new Error(`user.option.${e} not set`)}async userSet(e,t){return this.#t||(this.#t=[]),this.#t[e]||(this.#t[e]=null),this.#s[e]=t,this.#r(le.setUserOption,e,this.#s[e])}async#r(e,t,s){return this.#e.send(e,{name:t,value:s,isSafely:!0}).then(()=>Promise.resolve())}};var Xb=Object.defineProperty,au=o((r,e)=>Xb(r,"name",{value:e,configurable:!0}),"i$3");class cu{static{o(this,"DialogManager")}static{au(this,"DialogManager")}#e;constructor(e){this.#e=e}async selectUser(){return this.#e.send(le.selectUser,{mult:!1})}async selectUsers(){return this.#e.send(le.selectUser,{mult:!0})}async selectAccess(e=[]){return this.#e.send(le.selectAccess,{value:e})}async selectCRM(e){const t=await this.#e.send(le.selectCRM,{entityType:e?.entityType,multiple:e?.multiple,value:e?.value}),s={};if(!t)return s;const n=au(u=>{if(u!=null)return Array.isArray(u)?u:Object.values(u)},"toArray"),i=n(t.lead);i&&(s.lead=i);const c=n(t.contact);c&&(s.contact=c);const a=n(t.company);a&&(s.company=a);const l=n(t.deal);l&&(s.deal=l);const h=n(t.quote);return h&&(s.quote=h),s}}var Qb=Object.defineProperty,e_=o((r,e)=>Qb(r,"name",{value:e,configurable:!0}),"m$2");class lu{static{o(this,"SliderManager")}static{e_(this,"SliderManager")}#e;#t;constructor(e,t){this.#e=e,this.#t=t}getUrl(e="/"){return new URL(e,this.#e.getTargetOrigin())}getTargetOrigin(){return this.#e.getTargetOrigin()}async openSliderAppPage(e={}){return this.#t.send(le.openApplication,e)}async closeSliderAppPage(){return this.#t.send(le.closeApplication,{isSafely:!1})}#s(e=1640){return e>0?e>1200&&e<=1640?"/crm/type/0/details/0/../../../../..":e>950&&e<=1200?"/company/personal/user/0/groups/create/../../../../../..":e>900&&e<=950?"/crm/company/requisite/0/../../../..":e<=900?"/workgroups/group/0/card/../../../..":"/crm/deal/../..":"/crm/deal/../.."}async openPath(e,t=1640){const s=new URL(e);return s.searchParams.set("IFRAME","Y"),s.searchParams.set("IFRAME_TYPE","SIDE_SLIDER"),this.#t.send(le.openPath,{path:[this.#s(t),s.pathname,s.search].join("")}).then(n=>n?.result==="error"?n?.errorCode==="METHOD_NOT_SUPPORTED_ON_DEVICE"?new Promise((i,c)=>{const a=window.open(e,"_blank");if(!a){c(new Error("Error open window"));return}let l=0;const h=1e3*60*5,u=window.setInterval(()=>{l=l+1,a.closed?(clearInterval(u),i({isOpenAtNewWindow:!0,isClose:!0})):l>h&&(clearInterval(u),i({isOpenAtNewWindow:!0,isClose:!1}))},1e3)}):Promise.reject(new Error(n?.errorCode)):n?.result==="close"?Promise.resolve({isOpenAtNewWindow:!1,isClose:!0}):Promise.resolve({isOpenAtNewWindow:!1,isClose:!1}))}}var t_=Object.defineProperty,uu=o((r,e)=>t_(r,"name",{value:e,configurable:!0}),"t$4");const so=Object.freeze({});function no(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}o(no,"o$5"),uu(no,"isPlainObject");function hu(r){try{if(no(r))return Object.freeze({...r});if(typeof r=="string"&&r.length>0){const e=JSON.parse(r);return no(e)?Object.freeze({...e}):so}}catch{return so}return so}o(hu,"normalisePlacementOptions"),uu(hu,"normalisePlacementOptions");var r_=Object.defineProperty,s_=o((r,e)=>r_(r,"name",{value:e,configurable:!0}),"i$2");class du{static{o(this,"PlacementManager")}static{s_(this,"PlacementManager")}#e;#t="";#s=Object.freeze({});constructor(e){this.#e=e}initData(e){return this.#t=e.PLACEMENT||"DEFAULT",this.#s=hu(e.PLACEMENT_OPTIONS),this}get title(){return this.#t}get placement(){return this.#t}get isDefault(){return this.placement==="DEFAULT"}get options(){return this.#s}get isSliderMode(){return this.#s.IFRAME==="Y"}async getInterface(){return this.#e.send(le.getInterface,{isSafely:!0})}async bindEvent(e,t){return this.#e.send(le.placementBindEvent,{event:e,callBack:t,isSafely:!0})}async call(e,t={}){if(e==="setValue"&&!F.isString(t?.value))throw new TypeError("placement.call('setValue', { value }) expects `value` to be a JSON-serialized string. Use placement.setValue(value) to serialize automatically, or call JSON.stringify yourself.");return this.#e.send(e,{...t,isSafely:!0,isRawValue:["setValue"].includes(e)})}async setValue(e){return this.#e.send("setValue",{value:JSON.stringify(e),isSafely:!0,isRawValue:!0})}async callCustomBind(e,t=null,s){let n={};return F.isString(t)?n.singleOption=t:F.isObjectLike(t)&&(n={...t}),this.#e.send(e,{...n,callBack:s,isSafely:!0})}}var n_=Object.defineProperty,es=o((r,e)=>n_(r,"name",{value:e,configurable:!0}),"u$2");function rn(r){const e=es((i,c)=>Number.isFinite(i)&&i>0?i:c,"pick"),t=e(r?.marginMs,3e5),s=Math.max(3e4,e(r?.minDelayMs,3e4)),n=e(r?.maxDelayMs,6e5);return{marginMs:t,minDelayMs:s,maxDelayMs:Math.max(s,n)}}o(rn,"resolveKeepAuthFreshParams"),es(rn,"resolveKeepAuthFreshParams");function io(r,e,t){if(!Number.isFinite(r)||r<=0)return!0;const{marginMs:s}=rn(t);return r*1e3-e<=s}o(io,"frameTokenDue"),es(io,"frameTokenDue");function oo(r,e,t){const{marginMs:s,minDelayMs:n,maxDelayMs:i}=rn(t);if(!Number.isFinite(r)||r<=0)return n;const c=r*1e3-e-s;return Math.min(i,Math.max(n,c))}o(oo,"frameTokenDelayMs"),es(oo,"frameTokenDelayMs");class i_{static{o(this,"AuthKeepAlive")}static{es(this,"AuthKeepAlive")}#e;#t;#s;#r=null;#i=!1;#n=null;#o=null;#a=0;#h=0;#d=0;constructor(e,t,s){this.#e=e,this.#s=t,this.#t=rn(s)}start(){if(this.#i||typeof window>"u")return;this.#i=!0,this.#h=0;const e=this.#a;if(typeof document<"u"&&(this.#o=()=>{if(document.visibilityState!=="visible")return;const t=this.#a,s=this.#d-Date.now();if(s>0){this.#u(s,t);return}this.#c(t)},document.addEventListener("visibilitychange",this.#o)),this.#n!==null){this.#u(this.#t.minDelayMs,e);return}this.#c(e)}stop(){this.#i=!1,this.#a+=1,this.#f(),this.#o!==null&&typeof document<"u"&&document.removeEventListener("visibilitychange",this.#o),this.#o=null}get isRunning(){return this.#i}async#c(e){if(!this.#i||this.#n===e)return;this.#n=e;let t=this.#t.minDelayMs;try{const s=this.#e.getAuthData(),n=s===!1?void 0:s.expires;if(!io(n,Date.now(),this.#t))this.#h=0,t=oo(n,Date.now(),this.#t);else{const i=await this.#e.refreshAuth(),c=i?i.expires:void 0;io(c,Date.now(),this.#t)?(this.#h+=1,t=this.#l()):(this.#h=0,t=oo(c,Date.now(),this.#t))}}catch(s){this.#h+=1,t=this.#l();try{this.#s().warning("keepAuthFresh: refresh failed, will retry",{error:s instanceof Error?s.message:String(s),failures:this.#h,retryInMs:t}).catch(()=>{})}catch{}}finally{this.#n===e&&(this.#n=null),this.#u(t,e)}}#l(){const e=Math.min(Math.max(this.#h-1,0),10);return Math.min(this.#t.maxDelayMs,this.#t.minDelayMs*2**e)}#u(e,t){if(!this.#i||this.#a!==t)return;this.#f(),this.#d=Date.now()+e,this.#r=setTimeout(()=>{this.#r=null,this.#c(t)},e);const s=this.#r;typeof s?.unref=="function"&&s.unref()}#f(){this.#r!==null&&(clearTimeout(this.#r),this.#r=null)}}var o_=Object.defineProperty,a_=o((r,e)=>o_(r,"name",{value:e,configurable:!0}),"s$7");class fu extends js{static{o(this,"B24Frame")}static{a_(this,"B24Frame")}#e=!1;#t=!1;#s;#r;#i;#n;#o;#a;#h;#d;#c;#l;#u=null;constructor(e,t){super(),this.#c=t?.restrictionParams,this.#l=t?.keepAuthFresh,this._httpOptions=t?.httpOptions??null,this.#s=new ru(e),this.#r=new tu(this.#s),this.#r.subscribe(),this.#i=new nu(this.#s,this.#r),this.#n=new iu(this.#r),this.#o=new ou(this.#r),this.#a=new cu(this.#r),this.#h=new lu(this.#s,this.#r),this.#d=new du(this.#r),this._isInit=!1}setLogger(e){super.setLogger(e),this.#r.setLogger(this.getLogger())}get isFirstRun(){return this._ensureInitialized(),this.#t}get isInstallMode(){return this._ensureInitialized(),this.#e}get parent(){return this._ensureInitialized(),this.#n}get auth(){return this._ensureInitialized(),this.#i}get slider(){return this._ensureInitialized(),this.#h}get placement(){return this._ensureInitialized(),this.#d}get options(){return this._ensureInitialized(),this.#o}get dialog(){return this._ensureInitialized(),this.#a}async init(){const e=await this.#r.send(le.getInitData,{});return this.getLogger().debug("init data",{PLACEMENT:e.PLACEMENT,LANG:e.LANG,INSTALL:e.INSTALL,IS_ADMIN:e.IS_ADMIN,FIRST_RUN:e.FIRST_RUN}).catch(()=>{}),this.#s.initData(e),this.#i.initData(e),this.#d.initData(e),this.#o.initData(e),this.#e=e.INSTALL,this.#t=e.FIRST_RUN,this._httpV2=new en(this.#i,this._getHttpOptions(),this.#c),this._httpV3=new tn(this.#i,this._getHttpOptions(),this.#c),this._isInit=!0,this.#f(),this.#t?this.#r.send(le.setInstall,{install:!0}):Promise.resolve()}destroy(){this.#u?.stop(),this.#u=null,this.#r.unsubscribe(),super.destroy()}#f(){!this.#l||this.#u!==null||(this.#u=new i_(this.#i,()=>this.getLogger(),this.#l===!0?void 0:this.#l),this.#u.start())}async installFinish(){return this.isInstallMode?this.#r.send(le.setInstallFinish,{}):Promise.reject(new D({code:"JSSDK_FRAME_INSTALL_ALREADY_FINISHED",description:"Application was previously installed. You cannot call installFinish",status:0}))}getTargetOrigin(){return this._ensureInitialized(),this.#i.getTargetOrigin()}getTargetOriginWithPath(){return this._ensureInitialized(),this.#i.getTargetOriginWithPath()}getAppSid(){return this._ensureInitialized(),this.#s.getAppSid()}getLang(){return this._ensureInitialized(),this.#s.getLang()}}var c_=Object.defineProperty,l_=o((r,e)=>c_(r,"name",{value:e,configurable:!0}),"e$1");class pu extends D{static{o(this,"RefreshTokenError")}static{l_(this,"RefreshTokenError")}}var u_=Object.defineProperty,h_=o((r,e)=>u_(r,"name",{value:e,configurable:!0}),"h$5");class gu{static{o(this,"AuthOAuthManager")}static{h_(this,"AuthOAuthManager")}#e;#t=null;#s=null;#r;#i;#n=0;#o=0;#a;#h;#d;#c;#l;#u=null;constructor(e,t){this.#r=Object.assign({},e),this.#i=Object.freeze(Object.assign({},t)),this.#a=this.#r.domain.replaceAll("https://","").replaceAll("http://","").replace(/:(80|443)$/,""),this.#h=this.#r.clientEndpoint.replace(/\/+$/,""),this.#d=this.#h.replace(/\/rest$/,""),this.#l=this.#r.serverEndpoint.replace(/\/+$/,"").replace(/\/rest$/,""),this.#n=this.#r.expires*1e3,this.#o=this.#r.expiresIn,this.#e=we.create({baseURL:this.#l}),this.#c=new Map,this.#c.set(ee.v2,`${this.#h}`),this.#c.set(ee.v3,`${this.#h}/api`)}getAuthData(){return this.#n>Date.now()?{access_token:this.#r.accessToken,refresh_token:this.#r.refreshToken,expires:this.#n/1e3,expires_in:this.#o,domain:this.#a,member_id:this.#r.memberId}:!1}async refreshAuth(){try{let e;if(this.#s)e=await this.#s();else{const s=new URLSearchParams({grant_type:"refresh_token",client_id:this.#i.clientId,client_secret:this.#i.clientSecret,refresh_token:this.#r.refreshToken}),n=await this.#e.post("/oauth/token/",s,{headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(n.data.error)throw new D({code:"JSSDK_OAUTH_TOKEN_REFRESH_FAILED",description:`Token update error: ${n.data.error}`,status:0});if(n.status!==200)throw new D({code:"JSSDK_OAUTH_TOKEN_REFRESH_BAD_STATUS",description:`Token update error status code: ${n.status}`,status:n.status});e=n.data}if(!e)throw new D({code:"JSSDK_OAUTH_TOKEN_REFRESH_NO_DATA",description:"Unable to obtain authorization update data",status:0});this.#r.accessToken=e.access_token,this.#r.refreshToken=e.refresh_token,this.#r.expires=Number.parseInt(e.expires||"0"),this.#r.expiresIn=Number.parseInt(e.expires_in||"3600"),this.#r.clientEndpoint=e.client_endpoint,this.#r.serverEndpoint=e.server_endpoint,this.#r.scope=e.scope,this.#r.status=Object.values(vt).find(s=>s===e.status)||vt.Free,this.#n=this.#r.expires*1e3;const t=this.getAuthData();return this.#t&&await this.#t({authData:t,b24OAuthParams:this.#r}),t}catch(e){if(e instanceof Yi){const t={code:e?.code||0,description:e?.message||""};if(e.response&&e.response.data&&!F.isUndefined(e.response.data.error)){const s=e.response.data;s.error&&typeof s.error=="object"&&"code"in s.error?(t.code=s.error.code,t.description=s.error.message,s.error.validation&&s.error.validation.forEach(n=>{t.description+=`${n?.message||JSON.stringify(n)}`})):s.error&&typeof s.error=="string"&&(t.code=s.error,t.description=s?.error_description??t.description)}throw new pu({code:String(t.code),description:t.description,status:e.response?.status||0})}else if(e instanceof Error)throw e;throw new Error(`Strange error: ${String(e)}`,{cause:e})}}setCallbackRefreshAuth(e){this.#t=e}removeCallbackRefreshAuth(){this.#t=null}setCustomRefreshAuth(e){this.#s=e}removeCustomRefreshAuth(){this.#s=null}getUniq(e){return[e,this.#r.memberId||""].join("_")}getTargetOrigin(){return`${this.#d}`}getTargetOriginWithPath(){return this.#c}get isAdmin(){if(this.#u===null)throw new D({code:"JSSDK_OAUTH_IS_ADMIN_NOT_INIT",description:"isAdmin not init. You need call B24OAuth::initIsAdmin().",status:0});return this.#u}async initIsAdmin(e,t){if(this.#u=!1,e.apiVersion===ee.v3){const n=await e.call("profile",{},t);if(!n.isSuccess)throw new D({code:"JSSDK_OAUTH_PROFILE_FAILED",description:n.getErrorMessages().join(";"),status:0});n.getData().result.profile?.admin&&(this.#u=!0);return}const s=await e.call("profile",{},t);if(!s.isSuccess)throw new D({code:"JSSDK_OAUTH_PROFILE_FAILED",description:s.getErrorMessages().join(";"),status:0});s.getData().result?.ADMIN&&(this.#u=!0)}}var d_=Object.defineProperty,f_=o((r,e)=>d_(r,"name",{value:e,configurable:!0}),"n$2");class p_ extends js{static{o(this,"B24OAuth")}static{f_(this,"B24OAuth")}#e;constructor(e,t,s){super(),this.#e=new gu(e,t);const n=`The B24OAuth object is intended exclusively for use on the server.
A webhook contains a secret access key, which MUST NOT be used in client-side code (browser, worker, mobile app).`;this._httpOptions=s?.httpOptions??null,this._httpV2=new en(this.#e,this._getHttpOptions(),s?.restrictionParams),this._httpV2.setClientSideWarning(!0,n),this._httpV3=new tn(this.#e,this._getHttpOptions(),s?.restrictionParams),this._httpV3.setClientSideWarning(!0,n),this._isInit=!0}async initIsAdmin(e){const t="profile";this._ensureInitialized();try{const s=fr.automaticallyObtainApiVersion(t),n=this.getHttpClient(s);return this.#e.initIsAdmin(n,e)}catch(s){this.getLogger().error("initIsAdmin: setup failed before the profile call; treating the user as non-admin",{code:s instanceof D?s.code:"JSSDK_OAUTH_IS_ADMIN_LOOKUP_FAILED"}).catch(()=>{});return}}setCallbackRefreshAuth(e){this._ensureInitialized(),this.#e.setCallbackRefreshAuth(e)}removeCallbackRefreshAuth(){this._ensureInitialized(),this.#e.removeCallbackRefreshAuth()}setCustomRefreshAuth(e){this._ensureInitialized(),this.#e.setCustomRefreshAuth(e)}removeCustomRefreshAuth(){this._ensureInitialized(),this.#e.removeCustomRefreshAuth()}offClientSideWarning(){fr.getAllApiVersions().forEach(e=>{this.getHttpClient(e).setClientSideWarning(!1,"")})}get auth(){return this.#e}getTargetOrigin(){return this._ensureInitialized(),this.#e.getTargetOrigin()}getTargetOriginWithPath(){return this._ensureInitialized(),this.#e.getTargetOriginWithPath()}}var g_=Object.defineProperty,mu=o((r,e)=>g_(r,"name",{value:e,configurable:!0}),"t$3");class ao extends Error{static{o(this,"UnhandledMatchError")}static{mu(this,"UnhandledMatchError")}constructor(e,...t){super(...t),this.name="UnhandledMatchError",this.message=`Unhandled match value of type ${e}`,this.stack=`${new Error("for stack").stack}`}}class wr{static{o(this,"AbstractHelper")}static{mu(this,"AbstractHelper")}_b24;_data=null;_logger;constructor(e){this._b24=e,this._logger=ae.createNullLogger()}setLogger(e){this._logger=e}getLogger(){return this._logger}async initData(e){return Promise.reject(new Error("Rewrite this function"))}}var m_=Object.defineProperty,y_=o((r,e)=>m_(r,"name",{value:e,configurable:!0}),"t$2");class b_ extends wr{static{o(this,"ProfileManager")}static{y_(this,"ProfileManager")}_data=null;async initData(e){this._data=e}get data(){if(this._data===null)throw new Error("ProfileManager.data not initialized");return this._data}}var __=Object.defineProperty,w_=o((r,e)=>__(r,"name",{value:e,configurable:!0}),"a$4");class S_ extends wr{static{o(this,"AppManager")}static{w_(this,"AppManager")}_data=null;async initData(e){this._data=e}get data(){if(this._data===null)throw new Error("AppManager.data not initialized");return this._data}get statusCode(){return mc[this.data.status]||"Unknown status"}}var v_=Object.defineProperty,E_=o((r,e)=>v_(r,"name",{value:e,configurable:!0}),"a$3");class O_ extends wr{static{o(this,"PaymentManager")}static{E_(this,"PaymentManager")}_data=null;async initData(e){this._data=e}get data(){if(this._data===null)throw new Error("PaymentManager.data not initialized");return this._data}}var T_=Object.defineProperty,A_=o((r,e)=>T_(r,"name",{value:e,configurable:!0}),"t$1");class k_ extends wr{static{o(this,"LicenseManager")}static{A_(this,"LicenseManager")}_data=null;async initData(e){this._data=e,await this.makeRestrictionManagerParams()}get data(){if(this._data===null)throw new Error("LicenseManager.data not initialized");return this._data}async makeRestrictionManagerParams(){if(!this.data?.license)return;const e=Br.fromTariffPlan(this.data.license);this.getLogger().debug("set restriction manager params",{license:this.data.license,restrictionParams:e}).catch(()=>{}),await this._b24.setRestrictionManagerParams(e)}}var I_=Object.defineProperty,R_=o((r,e)=>I_(r,"name",{value:e,configurable:!0}),"l$7");class C_ extends wr{static{o(this,"CurrencyManager")}static{R_(this,"CurrencyManager")}async initData(e){this._data={currencyBase:"?",currencyList:new Map},this.setBaseCurrency(e.currencyBase),this.setCurrencyList(e.currencyList);try{await this.loadData()}catch(t){throw t instanceof Error?t:(this.getLogger().error("Failed to load data",{error:t}).catch(()=>{}),new Error("Failed to load data",{cause:t}))}}async loadData(){const e=this.currencyList.map(t=>({method:"crm.currency.get",params:{id:t}}));if(e.length===0)return Promise.resolve();try{const t=(await this._b24.actions.v2.batchByChunk.make({calls:e,options:{isHaltOnError:!0}})).getData();if(!Array.isArray(t))return Promise.resolve();t.forEach(s=>{if(typeof s.LANG>"u")return;const n=s.CURRENCY,i=this.data.currencyList.get(n);if(!(typeof i>"u"))for(const[c,a]of Object.entries(s.LANG))switch(i.lang[c]={decimals:Number.parseInt(a.DECIMALS),decPoint:a.DEC_POINT,formatString:a.FORMAT_STRING,fullName:a.FULL_NAME,isHideZero:a.HIDE_ZERO==="Y",thousandsSep:a.THOUSANDS_SEP,thousandsVariant:a.THOUSANDS_VARIANT},i.lang[c].thousandsVariant){case"N":i.lang[c].thousandsSep="";break;case"D":i.lang[c].thousandsSep=".";break;case"C":i.lang[c].thousandsSep=",";break;case"S":i.lang[c].thousandsSep=" ";break;case"B":i.lang[c].thousandsSep=" ";break;default:F.isStringFilled(i.lang[c].thousandsSep)||(i.lang[c].thousandsSep=" ");break}})}catch(t){this.getLogger().error("Failed to load data",{error:t}).catch(()=>{})}}get data(){if(this._data===null)throw new Error("CurrencyManager.data not initialized");return this._data}setBaseCurrency(e){this._data.currencyBase=e}get baseCurrency(){return this.data.currencyBase}setCurrencyList(e=[]){this.data.currencyList.clear();for(const t of e)this.data.currencyList.set(t.CURRENCY,{amount:Number.parseFloat(t.CURRENCY),amountCnt:Number.parseInt(t.AMOUNT_CNT),isBase:t.BASE==="Y",currencyCode:t.CURRENCY,dateUpdate:W.toDateTime(t.DATE_UPDATE),decimals:Number.parseInt(t.DECIMALS),decPoint:t.DEC_POINT,formatString:t.FORMAT_STRING,fullName:t.FULL_NAME,lid:t.LID,sort:Number.parseInt(t.SORT),thousandsSep:t?.THOUSANDS_SEP||null,lang:{}})}getCurrencyFullName(e,t){const s=this.data.currencyList.get(e);if(typeof s>"u")throw new ao(e);let n=s.fullName;if(!(typeof t>"u")){const i=s.lang[t];F.isUndefined(i)||(n=i.fullName)}return n}getCurrencyLiteral(e,t){const s=this.data.currencyList.get(e);if(typeof s>"u")throw new ao(e);let n=s.formatString;if(!(typeof t>"u")){const i=s.lang[t];F.isUndefined(i)||(n=i.formatString)}return n.replaceAll("&#","&%").replaceAll("#","").replaceAll("&%","&#").trim()||""}get currencyList(){return[...this.data.currencyList.keys()]}format(e,t,s){const n=this.data.currencyList.get(t);if(typeof n>"u")throw new ao(t);const i={formatString:n.formatString,decimals:n.decimals,decPoint:n.decPoint,thousandsSep:n.thousandsSep};F.isStringFilled(i.thousandsSep)||(i.thousandsSep="");const c=n.lang[s];return F.isUndefined(c)||(i.formatString=c.formatString,i.decimals=c.decimals,i.decPoint=c.decPoint,i.thousandsSep=c.thousandsSep),i.formatString.replaceAll("&#","&%").replace("#",W.numberFormat(e,i.decimals,i.decPoint,i.thousandsSep)).replaceAll("&%","&#")||""}}var N_=Object.defineProperty,D_=o((r,e)=>N_(r,"name",{value:e,configurable:!0}),"o$2");class co extends wr{static{o(this,"OptionsManager")}static{D_(this,"OptionsManager")}_data;_type;static getSupportTypes(){return[Et.NotSet,Et.JsonArray,Et.JsonObject,Et.FloatVal,Et.IntegerVal,Et.BoolYN,Et.StringVal]}static prepareArrayList(e){return F.isArray(e)?e:F.isObject(e)?Object.values(e):[]}constructor(e,t){super(e),this._type=t,this._data=new Map}get data(){return this._data}reset(){this.data.clear()}async initData(e){if(this.reset(),F.isObject(e))for(const[t,s]of Object.entries(e))this.data.set(t,s)}getJsonArray(e,t=[]){if(!this.data.has(e))return t;let s=this.data.get(e);try{s=JSON.parse(s),!F.isArray(s)&&!F.isObject(s)&&(s=t)}catch(n){this.getLogger().error("Failed JSON parse",{error:n}).catch(()=>{}),s=t}return co.prepareArrayList(s)}getJsonObject(e,t={}){if(!this.data.has(e))return t;let s=this.data.get(e);try{s=JSON.parse(s)}catch(n){this.getLogger().error("Failed JSON parse",{error:n}).catch(()=>{}),s=t}return F.isObject(s)||(s=t),s}getFloat(e,t=0){return this.data.has(e)?W.toNumber(this.data.get(e)):t}getInteger(e,t=0){return this.data.has(e)?W.toInteger(this.data.get(e)):t}getBoolYN(e,t=!0){return this.data.has(e)?W.toBoolean(this.data.get(e)):t}getBoolNY(e,t=!1){return this.data.has(e)?W.toBoolean(this.data.get(e)):t}getString(e,t=""){return this.data.has(e)?this.data.get(e).toString():t}getDate(e,t=null){if(!this.data.has(e))return t;try{const s=W.toDateTime(this.data.get(e).toString());return s.isValid?s:t}catch{return t}}encode(e){return JSON.stringify(e)}decode(e,t){try{return e.length>0?JSON.parse(e):t}catch(s){this.getLogger().error("Failed JSON parse",{error:s}).catch(()=>{})}return t}getMethodSave(){switch(this._type){case"app":return"app.option.set";case"user":return"user.option.set"}}async save(e,t,s){const n=[];return n.push({method:this.getMethodSave(),params:{options:e}}),F.isObject(t)&&n.push({method:"pull.application.event.add",params:{COMMAND:t?.command,PARAMS:t?.params,MODULE_ID:t?.moduleId}}),this._b24.actions.v2.batch.make({calls:n,options:{isHaltOnError:!0,returnAjaxResult:!1,requestId:s}})}}var L_=Object.defineProperty,P_=o((r,e)=>L_(r,"name",{value:e,configurable:!0}),"n$1");class yu{static{o(this,"StorageManager")}static{P_(this,"StorageManager")}_logger;userId;siteId;constructor(e={}){this._logger=ae.createNullLogger(),this.userId=e.userId?W.toInteger(e.userId):0,this.siteId=e.siteId??"none"}setLogger(e){this._logger=e}getLogger(){return this._logger}set(e,t){if(typeof window>"u"||typeof window.localStorage>"u"){this.getLogger().error("localStorage undefined",{error:new Error("undefined window.localStorage")}).catch(()=>{});return}typeof t!="string"&&t&&(t=JSON.stringify(t)),window.localStorage.setItem(this._getKey(e),t)}get(e,t){if(typeof window>"u"||typeof window.localStorage>"u")return t||null;const s=window.localStorage.getItem(this._getKey(e));return s===null?t||null:JSON.parse(s)}remove(e){if(typeof window>"u"||typeof window.localStorage>"u"){this.getLogger().error("localStorage undefined",{error:new Error("undefined window.localStorage")}).catch(()=>{});return}return window.localStorage.removeItem(this._getKey(e))}_getKey(e){return`@bitrix24/b24jssdk-pull-${this.userId}-${this.siteId}-${e}`}compareKey(e,t){return e===this._getKey(t)}}var M_=Object.defineProperty,bu=o((r,e)=>M_(r,"name",{value:e,configurable:!0}),"t");class F_ extends Error{static{o(this,"ErrorNotConnected")}static{bu(this,"ErrorNotConnected")}constructor(e){super(e),this.name="ErrorNotConnected"}}class x_ extends Error{static{o(this,"ErrorTimeout")}static{bu(this,"ErrorTimeout")}constructor(e){super(e),this.name="ErrorTimeout"}}var $_=Object.defineProperty,j_=o((r,e)=>$_(r,"name",{value:e,configurable:!0}),"R$2");const sn="2.0";class B_{static{o(this,"JsonRpc")}static{j_(this,"JsonRpc")}_logger;_connector;_idCounter=0;_handlers={};_rpcResponseAwaiters=new Map;constructor(e){if(this._logger=ae.createNullLogger(),this._connector=e.connector,F.isPlainObject(e.handlers))for(const t in e.handlers)this.handle(t,e.handlers[t])}setLogger(e){this._logger=e}getLogger(){return this._logger}handle(e,t){this._handlers[e]=t}async executeOutgoingRpcCommand(e,t,s=5){return new Promise((n,i)=>{const c=this.createRequest(e,t);this._connector.send(JSON.stringify(c))||i(new F_("websocket is not connected"));const a=setTimeout(()=>{this._rpcResponseAwaiters.delete(c.id),i(new x_("no response"))},s*1e3);this._rpcResponseAwaiters.set(c.id,{resolve:n,reject:i,timeout:a})})}executeOutgoingRpcBatch(e){const t=[],s=[];return e.forEach(({method:n,params:i,id:c})=>{const a=this.createRequest(n,i,c);t.push(a),s.push(new Promise((l,h)=>this._rpcResponseAwaiters.set(a.id,{resolve:l,reject:h})))}),this._connector.send(JSON.stringify(t)),s}processRpcResponse(e){if("id"in e&&this._rpcResponseAwaiters.has(Number(e.id))){const t=this._rpcResponseAwaiters.get(Number(e.id));t&&("result"in e?t.resolve(e.result):"error"in e?t.reject(e?.error||"error"):t.reject("wrong response structure"),clearTimeout(t.timeout),this._rpcResponseAwaiters.delete(Number(e.id)));return}this.getLogger().error(`${W.getDateForLog()}: Pull: Received rpc response with unknown id`,qe({response:e})).catch(()=>{})}parseJsonRpcMessage(e){let t;try{t=JSON.parse(e)}catch(s){return this.getLogger().error(`${W.getDateForLog()}: Pull: Could not decode json rpc message`,{error:s}).catch(()=>{}),[]}return F.isArray(t)?this.executeIncomingRpcBatch(t):F.isJsonRpcRequest(t)?this.executeIncomingRpcCommand(t):F.isJsonRpcResponse(t)?(this.processRpcResponse(t),[]):(this.getLogger().error(`${W.getDateForLog()}: Pull: unknown rpc packet`,qe({decoded:t})).catch(()=>{}),[])}executeIncomingRpcCommand({method:e,params:t}){return e in this._handlers?this._handlers[e].call(this,t||{}):{jsonrpc:sn,error:Wn.MethodNotFound}}executeIncomingRpcBatch(e){const t=[];for(const s of e)if("jsonrpc"in s)if("method"in s){const n=this.executeIncomingRpcCommand(s);n&&(n.jsonrpc=sn,n.id=s.id,t.push(n))}else this.processRpcResponse(s);else this.getLogger().error(`${W.getDateForLog()}: Pull: unknown rpc command in batch`,qe({command:s})).catch(()=>{}),t.push({jsonrpc:sn,error:Wn.InvalidRequest});return t}nextId(){return++this._idCounter}createPublishRequest(e){return e.map(t=>this.createRequest("publish",t))}createRequest(e,t,s){return s||(s=this.nextId()),{jsonrpc:sn,method:e,params:t,id:s}}}var U_=Object.defineProperty,V_=o((r,e)=>U_(r,"name",{value:e,configurable:!0}),"g$2");class q_{static{o(this,"SharedConfig")}static{V_(this,"SharedConfig")}_logger;_storage;_ttl=1440*60;_callbacks;constructor(e={}){this._logger=ae.createNullLogger(),e=e||{},this._storage=e.storage||new yu,this._callbacks={onWebSocketBlockChanged:F.isFunction(e.onWebSocketBlockChanged)?e.onWebSocketBlockChanged:()=>{}},this._storage&&typeof window<"u"&&window.addEventListener("storage",this.onLocalStorageSet.bind(this))}setLogger(e){this._logger=e}getLogger(){return this._logger}onLocalStorageSet(e){this._storage.compareKey(e.key||"",We.WebsocketBlocked)&&e.newValue!==e.oldValue&&this._callbacks.onWebSocketBlockChanged({isWebSocketBlocked:this.isWebSocketBlocked()})}isWebSocketBlocked(){return this._storage?this._storage.get(We.WebsocketBlocked,0)>Date.now():!1}setWebSocketBlocked(e){if(!this._storage)return!1;try{this._storage.set(We.WebsocketBlocked,e?Date.now()+this._ttl:0)}catch(t){return this.getLogger().error(`${W.getDateForLog()}: Pull: Could not save WS_blocked flag in local storage`,{error:t}).catch(()=>{}),!1}return!0}isLongPollingBlocked(){return this._storage?this._storage.get(We.LongPollingBlocked,0)>Date.now():!1}setLongPollingBlocked(e){if(!this._storage)return!1;try{this._storage.set(We.LongPollingBlocked,e?Date.now()+this._ttl:0)}catch(t){return this.getLogger().error(`${W.getDateForLog()}: Pull: Could not save LP_blocked flag in local storage.`,{error:t}).catch(()=>{}),!1}return!0}isLoggingEnabled(){return this._storage?this._storage.get(We.LoggingEnabled,0)>this.getTimestamp():!1}setLoggingEnabled(e){if(!this._storage)return!1;try{this._storage.set(We.LoggingEnabled,e?this.getTimestamp()+this._ttl:0)}catch(t){return this.getLogger().error(`${W.getDateForLog()}: LocalStorage error.`,{error:t}).catch(()=>{}),!1}return!0}getTimestamp(){return Date.now()}}var H_=Object.defineProperty,W_=o((r,e)=>H_(r,"name",{value:e,configurable:!0}),"c");const _u="JSSDK_PULL_PUBLIC_IDS_UNAVAILABLE";class z_{static{o(this,"ChannelManager")}static{W_(this,"ChannelManager")}_logger;_publicIds;_restClient;_getPublicListMethod;constructor(e){this._logger=ae.createNullLogger(),this._publicIds=new Map,this._restClient=e.b24,this._getPublicListMethod=e.getPublicListMethod||"pull.channel.public.list"}setLogger(e){this._logger=e}getLogger(){return this._logger}async getPublicIds(e){const t=new Date,s={},n=[];for(const i of e){const c=this._publicIds.get(i);c&&c.end>t?s[c.userId]=c:n.push(i)}return n.length===0?Promise.resolve(s):new Promise((i,c)=>{this._restClient.actions.v2.call.make({method:this._getPublicListMethod,params:{users:n}}).then(a=>{if(!a.isSuccess)return c(this.publicIdsUnavailable(new Error(a.getErrorMessages().join("; "))));const l=a.getData();l?.result&&this.setPublicIds(Object.values(l.result));for(const h of n){const u=this._publicIds.get(h);u&&(s[u.userId]=u)}if(Object.keys(s).length===0)return c(this.publicIdsUnavailable(new Error(`\`${this._getPublicListMethod}\` answered without a channel for any requested user`)));i(s)}).catch(a=>a instanceof D&&a.code===_u?c(a):c(this.publicIdsUnavailable(a)))})}publicIdsUnavailable(e){return this.getLogger().error("some error in getPublicIds",{error:e}).catch(()=>{}),new D({code:_u,description:`Pull: could not resolve channel ids through \`${this._getPublicListMethod}\`, so there is nobody to send to. Publishing from the client needs that method; that method is not part of the application REST surface \u2014 put messages into the channel with \`pull.application.event.add\` from your back end instead.`,status:0,...e instanceof Error?{originalError:e}:{}})}setPublicIds(e){e.forEach(t=>{const s=Number(t.user_id);this._publicIds.set(s,{userId:s,publicId:t.public_id,signature:t.signature,start:new Date(t.start),end:new Date(t.end)})})}}var ts=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function J_(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}o(J_,"getDefaultExportFromCjs");var lo={exports:{}},wu;function K_(){return wu||(wu=1,(function(r){var e=Object.defineProperty,t=o((s,n)=>e(s,"name",{value:n,configurable:!0}),"i");/*!
* protobuf.js v6.8.6 (c) 2016, daniel wirtz
* compiled mon, 26 feb 2018 11:35:34 utc
* licensed under the bsd-3-clause license
* see: https://github.com/dcodeio/protobuf.js for details
*
* Modify a list for integration with Bitrix Framework:
* - removed integration with RequireJS and AMD package builders;
*/(function(s){t((function(n,i,c){function a(h){var u=i[h];return u||n[h][0].call(u=i[h]={exports:{}},a,u,u.exports),u.exports}o(a,"d"),t(a,"$require");var l=a(c[0]);r&&r.exports&&(r.exports=l)}),"prelude")({1:[function(n,i,c){i.exports=a;function a(l,h){for(var u=new Array(arguments.length-1),p=0,g=2,f=!0;g<arguments.length;)u[p++]=arguments[g++];return new Promise(t(function(d,y){u[p]=t(function(b){if(f)if(f=!1,b)y(b);else{for(var m=new Array(arguments.length-1),_=0;_<m.length;)m[_++]=arguments[_];d.apply(null,m)}},"callback");try{l.apply(h||null,u)}catch(b){f&&(f=!1,y(b))}},"executor"))}o(a,"l"),t(a,"asPromise")},{}],2:[function(n,i,c){var a=c;a.length=t(function(g){var f=g.length;if(!f)return 0;for(var d=0;--f%4>1&&g.charAt(f)==="=";)++d;return Math.ceil(g.length*3)/4-d},"length");for(var l=new Array(64),h=new Array(123),u=0;u<64;)h[l[u]=u<26?u+65:u<52?u+71:u<62?u-4:u-59|43]=u++;a.encode=t(function(g,f,d){for(var y=null,b=[],m=0,_=0,w;f<d;){var S=g[f++];switch(_){case 0:b[m++]=l[S>>2],w=(S&3)<<4,_=1;break;case 1:b[m++]=l[w|S>>4],w=(S&15)<<2,_=2;break;case 2:b[m++]=l[w|S>>6],b[m++]=l[S&63],_=0;break}m>8191&&((y||(y=[])).push(String.fromCharCode.apply(String,b)),m=0)}return _&&(b[m++]=l[w],b[m++]=61,_===1&&(b[m++]=61)),y?(m&&y.push(String.fromCharCode.apply(String,b.slice(0,m))),y.join("")):String.fromCharCode.apply(String,b.slice(0,m))},"encode");var p="invalid encoding";a.decode=t(function(g,f,d){for(var y=d,b=0,m,_=0;_<g.length;){var w=g.charCodeAt(_++);if(w===61&&b>1)break;if((w=h[w])===s)throw Error(p);switch(b){case 0:m=w,b=1;break;case 1:f[d++]=m<<2|(w&48)>>4,m=w,b=2;break;case 2:f[d++]=(m&15)<<4|(w&60)>>2,m=w,b=3;break;case 3:f[d++]=(m&3)<<6|w,b=0;break}}if(b===1)throw Error(p);return d-y},"decode"),a.test=t(function(g){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(g)},"test")},{}],3:[function(n,i,c){i.exports=a;function a(l,h){typeof l=="string"&&(h=l,l=s);var u=[];function p(f){if(typeof f!="string"){var d=g();if(a.verbose&&console.log("codegen: "+d),d="return "+d,f){for(var y=Object.keys(f),b=new Array(y.length+1),m=new Array(y.length),_=0;_<y.length;)b[_]=y[_],m[_]=f[y[_++]];return b[_]=d,Function.apply(null,b).apply(null,m)}return Function(d)()}for(var w=new Array(arguments.length-1),S=0;S<w.length;)w[S]=arguments[++S];if(S=0,f=f.replace(/%([%dfijs])/g,t(function(T,v){var A=w[S++];switch(v){case"d":case"f":return String(Number(A));case"i":return String(Math.floor(A));case"j":return JSON.stringify(A);case"s":return String(A)}return"%"},"replace")),S!==w.length)throw Error("parameter count mismatch");return u.push(f),p}o(p,"a"),t(p,"Codegen");function g(f){return"function "+(f||h||"")+"("+(l&&l.join(",")||"")+`){
`+u.join(`
`)+`
}`}return o(g,"s"),t(g,"toString"),p.toString=g,p}o(a,"l"),t(a,"codegen"),a.verbose=!1},{}],4:[function(n,i,c){i.exports=a;function a(){this._listeners={}}o(a,"l"),t(a,"EventEmitter"),a.prototype.on=t(function(l,h,u){return(this._listeners[l]||(this._listeners[l]=[])).push({fn:h,ctx:u||this}),this},"on"),a.prototype.off=t(function(l,h){if(l===s)this._listeners={};else if(h===s)this._listeners[l]=[];else for(var u=this._listeners[l],p=0;p<u.length;)u[p].fn===h?u.splice(p,1):++p;return this},"off"),a.prototype.emit=t(function(l){var h=this._listeners[l];if(h){for(var u=[],p=1;p<arguments.length;)u.push(arguments[p++]);for(p=0;p<h.length;)h[p].fn.apply(h[p++].ctx,u)}return this},"emit")},{}],5:[function(n,i,c){i.exports=u;var a=n(1),l=n(7),h=l("fs");function u(p,g,f){return typeof g=="function"?(f=g,g={}):g||(g={}),f?!g.xhr&&h&&h.readFile?h.readFile(p,t(function(d,y){return d&&typeof XMLHttpRequest<"u"?u.xhr(p,g,f):d?f(d):f(null,g.binary?y:y.toString("utf8"))},"fetchReadFileCallback")):u.xhr(p,g,f):a(u,this,p,g)}o(u,"u"),t(u,"fetch"),u.xhr=t(function(p,g,f){var d=new XMLHttpRequest;d.onreadystatechange=t(function(){if(d.readyState!==4)return s;if(d.status!==0&&d.status!==200)return f(Error("status "+d.status));if(g.binary){var y=d.response;if(!y){y=[];for(var b=0;b<d.responseText.length;++b)y.push(d.responseText.charCodeAt(b)&255)}return f(null,typeof Uint8Array<"u"?new Uint8Array(y):y)}return f(null,d.responseText)},"fetchOnReadyStateChange"),g.binary&&("overrideMimeType"in d&&d.overrideMimeType("text/plain; charset=x-user-defined"),d.responseType="arraybuffer"),d.open("GET",p),d.send()},"fetch_xhr")},{1:1,7:7}],6:[function(n,i,c){i.exports=a(a);function a(g){return typeof Float32Array<"u"?(function(){var f=new Float32Array([-0]),d=new Uint8Array(f.buffer),y=d[3]===128;function b(S,T,v){f[0]=S,T[v]=d[0],T[v+1]=d[1],T[v+2]=d[2],T[v+3]=d[3]}o(b,"f"),t(b,"writeFloat_f32_cpy");function m(S,T,v){f[0]=S,T[v]=d[3],T[v+1]=d[2],T[v+2]=d[1],T[v+3]=d[0]}o(m,"n"),t(m,"writeFloat_f32_rev"),g.writeFloatLE=y?b:m,g.writeFloatBE=y?m:b;function _(S,T){return d[0]=S[T],d[1]=S[T+1],d[2]=S[T+2],d[3]=S[T+3],f[0]}o(_,"o"),t(_,"readFloat_f32_cpy");function w(S,T){return d[3]=S[T],d[2]=S[T+1],d[1]=S[T+2],d[0]=S[T+3],f[0]}o(w,"p"),t(w,"readFloat_f32_rev"),g.readFloatLE=y?_:w,g.readFloatBE=y?w:_})():(function(){function f(y,b,m,_){var w=b<0?1:0;if(w&&(b=-b),b===0)y(1/b>0?0:2147483648,m,_);else if(isNaN(b))y(2143289344,m,_);else if(b>34028234663852886e22)y((w<<31|2139095040)>>>0,m,_);else if(b<11754943508222875e-54)y((w<<31|Math.round(b/1401298464324817e-60))>>>0,m,_);else{var S=Math.floor(Math.log(b)/Math.LN2),T=Math.round(b*Math.pow(2,-S)*8388608)&8388607;y((w<<31|S+127<<23|T)>>>0,m,_)}}o(f,"t"),t(f,"writeFloat_ieee754"),g.writeFloatLE=f.bind(null,l),g.writeFloatBE=f.bind(null,h);function d(y,b,m){var _=y(b,m),w=(_>>31)*2+1,S=_>>>23&255,T=_&8388607;return S===255?T?NaN:w*(1/0):S===0?w*1401298464324817e-60*T:w*Math.pow(2,S-150)*(T+8388608)}o(d,"r"),t(d,"readFloat_ieee754"),g.readFloatLE=d.bind(null,u),g.readFloatBE=d.bind(null,p)})(),typeof Float64Array<"u"?(function(){var f=new Float64Array([-0]),d=new Uint8Array(f.buffer),y=d[7]===128;function b(S,T,v){f[0]=S,T[v]=d[0],T[v+1]=d[1],T[v+2]=d[2],T[v+3]=d[3],T[v+4]=d[4],T[v+5]=d[5],T[v+6]=d[6],T[v+7]=d[7]}o(b,"f"),t(b,"writeDouble_f64_cpy");function m(S,T,v){f[0]=S,T[v]=d[7],T[v+1]=d[6],T[v+2]=d[5],T[v+3]=d[4],T[v+4]=d[3],T[v+5]=d[2],T[v+6]=d[1],T[v+7]=d[0]}o(m,"n"),t(m,"writeDouble_f64_rev"),g.writeDoubleLE=y?b:m,g.writeDoubleBE=y?m:b;function _(S,T){return d[0]=S[T],d[1]=S[T+1],d[2]=S[T+2],d[3]=S[T+3],d[4]=S[T+4],d[5]=S[T+5],d[6]=S[T+6],d[7]=S[T+7],f[0]}o(_,"o"),t(_,"readDouble_f64_cpy");function w(S,T){return d[7]=S[T],d[6]=S[T+1],d[5]=S[T+2],d[4]=S[T+3],d[3]=S[T+4],d[2]=S[T+5],d[1]=S[T+6],d[0]=S[T+7],f[0]}o(w,"p"),t(w,"readDouble_f64_rev"),g.readDoubleLE=y?_:w,g.readDoubleBE=y?w:_})():(function(){function f(y,b,m,_,w,S){var T=_<0?1:0;if(T&&(_=-_),_===0)y(0,w,S+b),y(1/_>0?0:2147483648,w,S+m);else if(isNaN(_))y(0,w,S+b),y(2146959360,w,S+m);else if(_>17976931348623157e292)y(0,w,S+b),y((T<<31|2146435072)>>>0,w,S+m);else{var v;if(_<22250738585072014e-324)v=_/5e-324,y(v>>>0,w,S+b),y((T<<31|v/4294967296)>>>0,w,S+m);else{var A=Math.floor(Math.log(_)/Math.LN2);A===1024&&(A=1023),v=_*Math.pow(2,-A),y(v*4503599627370496>>>0,w,S+b),y((T<<31|A+1023<<20|v*1048576&1048575)>>>0,w,S+m)}}}o(f,"t"),t(f,"writeDouble_ieee754"),g.writeDoubleLE=f.bind(null,l,0,4),g.writeDoubleBE=f.bind(null,h,4,0);function d(y,b,m,_,w){var S=y(_,w+b),T=y(_,w+m),v=(T>>31)*2+1,A=T>>>20&2047,O=4294967296*(T&1048575)+S;return A===2047?O?NaN:v*(1/0):A===0?v*5e-324*O:v*Math.pow(2,A-1075)*(O+4503599627370496)}o(d,"r"),t(d,"readDouble_ieee754"),g.readDoubleLE=d.bind(null,u,0,4),g.readDoubleBE=d.bind(null,p,4,0)})(),g}o(a,"l"),t(a,"factory");function l(g,f,d){f[d]=g&255,f[d+1]=g>>>8&255,f[d+2]=g>>>16&255,f[d+3]=g>>>24}o(l,"d"),t(l,"writeUintLE");function h(g,f,d){f[d]=g>>>24,f[d+1]=g>>>16&255,f[d+2]=g>>>8&255,f[d+3]=g&255}o(h,"c"),t(h,"writeUintBE");function u(g,f){return(g[f]|g[f+1]<<8|g[f+2]<<16|g[f+3]<<24)>>>0}o(u,"u"),t(u,"readUintLE");function p(g,f){return(g[f]<<24|g[f+1]<<16|g[f+2]<<8|g[f+3])>>>0}o(p,"a"),t(p,"readUintBE")},{}],7:[function(n,i,c){i.exports=a;function a(l){try{var h=n(l);if(h&&(h.length||Object.keys(h).length))return h}catch{}return null}o(a,"l"),t(a,"inquire")},{}],8:[function(n,i,c){var a=c,l=a.isAbsolute=t(function(u){return/^(?:\/|\w+:)/.test(u)},"isAbsolute"),h=a.normalize=t(function(u){u=u.replace(/\\/g,"/").replace(/\/{2,}/g,"/");var p=u.split("/"),g=l(u),f="";g&&(f=p.shift()+"/");for(var d=0;d<p.length;)p[d]===".."?d>0&&p[d-1]!==".."?p.splice(--d,2):g?p.splice(d,1):++d:p[d]==="."?p.splice(d,1):++d;return f+p.join("/")},"normalize");a.resolve=t(function(u,p,g){return g||(p=h(p)),l(p)?p:(g||(u=h(u)),(u=u.replace(/(?:\/|^)[^/]+$/,"")).length?h(u+"/"+p):p)},"resolve")},{}],9:[function(n,i,c){i.exports=a;function a(l,h,u){var p=u||8192,g=p>>>1,f=null,d=p;return t(function(y){if(y<1||y>g)return l(y);d+y>p&&(f=l(p),d=0);var b=h.call(f,d,d+=y);return d&7&&(d=(d|7)+1),b},"pool_alloc")}o(a,"l"),t(a,"pool")},{}],10:[function(n,i,c){var a=c;a.length=t(function(l){for(var h=0,u=0,p=0;p<l.length;++p)u=l.charCodeAt(p),u<128?h+=1:u<2048?h+=2:(u&64512)===55296&&(l.charCodeAt(p+1)&64512)===56320?(++p,h+=4):h+=3;return h},"utf8_length"),a.read=t(function(l,h,u){var p=u-h;if(p<1)return"";for(var g=null,f=[],d=0,y;h<u;)y=l[h++],y<128?f[d++]=y:y>191&&y<224?f[d++]=(y&31)<<6|l[h++]&63:y>239&&y<365?(y=((y&7)<<18|(l[h++]&63)<<12|(l[h++]&63)<<6|l[h++]&63)-65536,f[d++]=55296+(y>>10),f[d++]=56320+(y&1023)):f[d++]=(y&15)<<12|(l[h++]&63)<<6|l[h++]&63,d>8191&&((g||(g=[])).push(String.fromCharCode.apply(String,f)),d=0);return g?(d&&g.push(String.fromCharCode.apply(String,f.slice(0,d))),g.join("")):String.fromCharCode.apply(String,f.slice(0,d))},"utf8_read"),a.write=t(function(l,h,u){for(var p=u,g,f,d=0;d<l.length;++d)g=l.charCodeAt(d),g<128?h[u++]=g:g<2048?(h[u++]=g>>6|192,h[u++]=g&63|128):(g&64512)===55296&&((f=l.charCodeAt(d+1))&64512)===56320?(g=65536+((g&1023)<<10)+(f&1023),++d,h[u++]=g>>18|240,h[u++]=g>>12&63|128,h[u++]=g>>6&63|128,h[u++]=g&63|128):(h[u++]=g>>12|224,h[u++]=g>>6&63|128,h[u++]=g&63|128);return u-p},"utf8_write")},{}],11:[function(n,i,c){i.exports=l;var a=/\/|\./;function l(u,p){a.test(u)||(u="google/protobuf/"+u+".proto",p={nested:{google:{nested:{protobuf:{nested:p}}}}}),l[u]=p}o(l,"d"),t(l,"common"),l("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var h;l("duration",{Duration:h={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),l("timestamp",{Timestamp:h}),l("empty",{Empty:{fields:{}}}),l("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),l("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),l("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),l.get=t(function(u){return l[u]||null},"get")},{}],12:[function(n,i,c){var a=c,l=n(15),h=n(37);function u(g,f,d,y){if(f.resolvedType)if(f.resolvedType instanceof l){g("switch(d%s){",y);for(var b=f.resolvedType.values,m=Object.keys(b),_=0;_<m.length;++_)f.repeated&&b[m[_]]===f.typeDefault&&g("default:"),g("case%j:",m[_])("case %i:",b[m[_]])("m%s=%j",y,b[m[_]])("break");g("}")}else g('if(typeof d%s!=="object")',y)("throw TypeError(%j)",f.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",y,d,y);else{var w=!1;switch(f.type){case"double":case"float":g("m%s=Number(d%s)",y,y);break;case"uint32":case"fixed32":g("m%s=d%s>>>0",y,y);break;case"int32":case"sint32":case"sfixed32":g("m%s=d%s|0",y,y);break;case"uint64":w=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":g("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",y,y,w)('else if(typeof d%s==="string")',y)("m%s=parseInt(d%s,10)",y,y)('else if(typeof d%s==="number")',y)("m%s=d%s",y,y)('else if(typeof d%s==="object")',y)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",y,y,y,w?"true":"");break;case"bytes":g('if(typeof d%s==="string")',y)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",y,y,y)("else if(d%s.length)",y)("m%s=d%s",y,y);break;case"string":g("m%s=String(d%s)",y,y);break;case"bool":g("m%s=Boolean(d%s)",y,y);break}}return g}o(u,"u"),t(u,"genValuePartial_fromObject"),a.fromObject=t(function(g){var f=g.fieldsArray,d=h.codegen(["d"],g.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!f.length)return d("return new this.ctor");d("var m=new this.ctor");for(var y=0;y<f.length;++y){var b=f[y].resolve(),m=h.safeProp(b.name);b.map?(d("if(d%s){",m)('if(typeof d%s!=="object")',m)("throw TypeError(%j)",b.fullName+": object expected")("m%s={}",m)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",m),u(d,b,y,m+"[ks[i]]")("}")("}")):b.repeated?(d("if(d%s){",m)("if(!Array.isArray(d%s))",m)("throw TypeError(%j)",b.fullName+": array expected")("m%s=[]",m)("for(var i=0;i<d%s.length;++i){",m),u(d,b,y,m+"[i]")("}")("}")):(b.resolvedType instanceof l||d("if(d%s!=null){",m),u(d,b,y,m),b.resolvedType instanceof l||d("}"))}return d("return m")},"fromObject");function p(g,f,d,y){if(f.resolvedType)f.resolvedType instanceof l?g("d%s=o.enums===String?types[%i].values[m%s]:m%s",y,d,y,y):g("d%s=types[%i].toObject(m%s,o)",y,d,y);else{var b=!1;switch(f.type){case"double":case"float":g("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",y,y,y,y);break;case"uint64":b=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":g('if(typeof m%s==="number")',y)("d%s=o.longs===String?String(m%s):m%s",y,y,y)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",y,y,y,y,b?"true":"",y);break;case"bytes":g("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",y,y,y,y,y);break;default:g("d%s=m%s",y,y);break}}return g}o(p,"a"),t(p,"genValuePartial_toObject"),a.toObject=t(function(g){var f=g.fieldsArray.slice().sort(h.compareFieldsById);if(!f.length)return h.codegen()("return {}");for(var d=h.codegen(["m","o"],g.name+"$toObject")("if(!o)")("o={}")("var d={}"),y=[],b=[],m=[],_=0;_<f.length;++_)f[_].partOf||(f[_].resolve().repeated?y:f[_].map?b:m).push(f[_]);if(y.length){for(d("if(o.arrays||o.defaults){"),_=0;_<y.length;++_)d("d%s=[]",h.safeProp(y[_].name));d("}")}if(b.length){for(d("if(o.objects||o.defaults){"),_=0;_<b.length;++_)d("d%s={}",h.safeProp(b[_].name));d("}")}if(m.length){for(d("if(o.defaults){"),_=0;_<m.length;++_){var w=m[_],S=h.safeProp(w.name);w.resolvedType instanceof l?d("d%s=o.enums===String?%j:%j",S,w.resolvedType.valuesById[w.typeDefault],w.typeDefault):w.long?d("if(util.Long){")("var n=new util.Long(%i,%i,%j)",w.typeDefault.low,w.typeDefault.high,w.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",S)("}else")("d%s=o.longs===String?%j:%i",S,w.typeDefault.toString(),w.typeDefault.toNumber()):w.bytes?d("d%s=o.bytes===String?%j:%s",S,String.fromCharCode.apply(String,w.typeDefault),"["+Array.prototype.slice.call(w.typeDefault).join(",")+"]"):d("d%s=%j",S,w.typeDefault)}d("}")}var T=!1;for(_=0;_<f.length;++_){var w=f[_],v=g._fieldsArray.indexOf(w),S=h.safeProp(w.name);w.map?(T||(T=!0,d("var ks2")),d("if(m%s&&(ks2=Object.keys(m%s)).length){",S,S)("d%s={}",S)("for(var j=0;j<ks2.length;++j){"),p(d,w,v,S+"[ks2[j]]")("}")):w.repeated?(d("if(m%s&&m%s.length){",S,S)("d%s=[]",S)("for(var j=0;j<m%s.length;++j){",S),p(d,w,v,S+"[j]")("}")):(d("if(m%s!=null&&m.hasOwnProperty(%j)){",S,w.name),p(d,w,v,S),w.partOf&&d("if(o.oneofs)")("d%s=%j",h.safeProp(w.partOf.name),w.name)),d("}")}return d("return d")},"toObject")},{15:15,37:37}],13:[function(n,i,c){i.exports=p;var a=n(15),l=n(36),h=n(37);function u(g){return"missing required '"+g.name+"'"}o(u,"u"),t(u,"missing");function p(g){var f=h.codegen(["r","l"],g.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(g.fieldsArray.filter(function(w){return w.map}).length?",k":""))("while(r.pos<c){")("var t=r.uint32()");g.group&&f("if((t&7)===4)")("break"),f("switch(t>>>3){");for(var d=0;d<g.fieldsArray.length;++d){var y=g._fieldsArray[d].resolve(),b=y.resolvedType instanceof a?"int32":y.type,m="m"+h.safeProp(y.name);f("case %i:",y.id),y.map?(f("r.skip().pos++")("if(%s===util.emptyObject)",m)("%s={}",m)("k=r.%s()",y.keyType)("r.pos++"),l.long[y.keyType]!==s?l.basic[b]===s?f('%s[typeof k==="object"?util.longToHash(k):k]=types[%i].decode(r,r.uint32())',m,d):f('%s[typeof k==="object"?util.longToHash(k):k]=r.%s()',m,b):l.basic[b]===s?f("%s[k]=types[%i].decode(r,r.uint32())",m,d):f("%s[k]=r.%s()",m,b)):y.repeated?(f("if(!(%s&&%s.length))",m,m)("%s=[]",m),l.packed[b]!==s&&f("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",m,b)("}else"),l.basic[b]===s?f(y.resolvedType.group?"%s.push(types[%i].decode(r))":"%s.push(types[%i].decode(r,r.uint32()))",m,d):f("%s.push(r.%s())",m,b)):l.basic[b]===s?f(y.resolvedType.group?"%s=types[%i].decode(r)":"%s=types[%i].decode(r,r.uint32())",m,d):f("%s=r.%s()",m,b),f("break")}for(f("default:")("r.skipType(t&7)")("break")("}")("}"),d=0;d<g._fieldsArray.length;++d){var _=g._fieldsArray[d];_.required&&f("if(!m.hasOwnProperty(%j))",_.name)("throw util.ProtocolError(%j,{instance:m})",u(_))}return f("return m")}o(p,"a"),t(p,"decoder")},{15:15,36:36,37:37}],14:[function(n,i,c){i.exports=p;var a=n(15),l=n(36),h=n(37);function u(g,f,d,y){return f.resolvedType.group?g("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",d,y,(f.id<<3|3)>>>0,(f.id<<3|4)>>>0):g("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",d,y,(f.id<<3|2)>>>0)}o(u,"u"),t(u,"genTypePartial");function p(g){for(var f=h.codegen(["m","w"],g.name+"$encode")("if(!w)")("w=Writer.create()"),b,d,y=g.fieldsArray.slice().sort(h.compareFieldsById),b=0;b<y.length;++b){var m=y[b].resolve(),_=g._fieldsArray.indexOf(m),w=m.resolvedType instanceof a?"int32":m.type,S=l.basic[w];d="m"+h.safeProp(m.name),m.map?(f("if(%s!=null&&m.hasOwnProperty(%j)){",d,m.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",d)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(m.id<<3|2)>>>0,8|l.mapKey[m.keyType],m.keyType),S===s?f("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",_,d):f(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|S,w,d),f("}")("}")):m.repeated?(f("if(%s!=null&&%s.length){",d,d),m.packed&&l.packed[w]!==s?f("w.uint32(%i).fork()",(m.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",d)("w.%s(%s[i])",w,d)("w.ldelim()"):(f("for(var i=0;i<%s.length;++i)",d),S===s?u(f,m,_,d+"[i]"):f("w.uint32(%i).%s(%s[i])",(m.id<<3|S)>>>0,w,d)),f("}")):(m.optional&&f("if(%s!=null&&m.hasOwnProperty(%j))",d,m.name),S===s?u(f,m,_,d):f("w.uint32(%i).%s(%s)",(m.id<<3|S)>>>0,w,d))}return f("return w")}o(p,"a"),t(p,"encoder")},{15:15,36:36,37:37}],15:[function(n,i,c){i.exports=u;var a=n(24);((u.prototype=Object.create(a.prototype)).constructor=u).className="Enum";var l=n(23),h=n(37);function u(p,g,f,d,y){if(a.call(this,p,f),g&&typeof g!="object")throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=d,this.comments=y||{},this.reserved=s,g)for(var b=Object.keys(g),m=0;m<b.length;++m)typeof g[b[m]]=="number"&&(this.valuesById[this.values[b[m]]=g[b[m]]]=b[m])}o(u,"u"),t(u,"Enum"),u.fromJSON=t(function(p,g){var f=new u(p,g.values,g.options,g.comment,g.comments);return f.reserved=g.reserved,f},"fromJSON"),u.prototype.toJSON=t(function(p){var g=p?!!p.keepComments:!1;return h.toObject(["options",this.options,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:s,"comment",g?this.comment:s,"comments",g?this.comments:s])},"toJSON"),u.prototype.add=t(function(p,g,f){if(!h.isString(p))throw TypeError("name must be a string");if(!h.isInteger(g))throw TypeError("id must be an integer");if(this.values[p]!==s)throw Error("duplicate name '"+p+"' in "+this);if(this.isReservedId(g))throw Error("id "+g+" is reserved in "+this);if(this.isReservedName(p))throw Error("name '"+p+"' is reserved in "+this);if(this.valuesById[g]!==s){if(!(this.options&&this.options.allow_alias))throw Error("duplicate id "+g+" in "+this);this.values[p]=g}else this.valuesById[this.values[p]=g]=p;return this.comments[p]=f||null,this},"add"),u.prototype.remove=t(function(p){if(!h.isString(p))throw TypeError("name must be a string");var g=this.values[p];if(g==null)throw Error("name '"+p+"' does not exist in "+this);return delete this.valuesById[g],delete this.values[p],delete this.comments[p],this},"remove"),u.prototype.isReservedId=t(function(p){return l.isReservedId(this.reserved,p)},"isReservedId"),u.prototype.isReservedName=t(function(p){return l.isReservedName(this.reserved,p)},"isReservedName")},{23:23,24:24,37:37}],16:[function(n,i,c){i.exports=f;var a=n(24);((f.prototype=Object.create(a.prototype)).constructor=f).className="Field";var l=n(15),h=n(36),u=n(37),p,g=/^required|optional|repeated$/;f.fromJSON=t(function(d,y){return new f(d,y.id,y.type,y.rule,y.extend,y.options,y.comment)},"fromJSON");function f(d,y,b,m,_,w,S){if(u.isObject(m)?(S=_,w=m,m=_=s):u.isObject(_)&&(S=w,w=_,_=s),a.call(this,d,w),!u.isInteger(y)||y<0)throw TypeError("id must be a non-negative integer");if(!u.isString(b))throw TypeError("type must be a string");if(m!==s&&!g.test(m=m.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(_!==s&&!u.isString(_))throw TypeError("extend must be a string");this.rule=m&&m!=="optional"?m:s,this.type=b,this.id=y,this.extend=_||s,this.required=m==="required",this.optional=!this.required,this.repeated=m==="repeated",this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=u.Long?h.long[b]!==s:!1,this.bytes=b==="bytes",this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=S}o(f,"t"),t(f,"Field"),Object.defineProperty(f.prototype,"packed",{get:t(function(){return this._packed===null&&(this._packed=this.getOption("packed")!==!1),this._packed},"get")}),f.prototype.setOption=t(function(d,y,b){return d==="packed"&&(this._packed=null),a.prototype.setOption.call(this,d,y,b)},"setOption"),f.prototype.toJSON=t(function(d){var y=d?!!d.keepComments:!1;return u.toObject(["rule",this.rule!=="optional"&&this.rule||s,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",y?this.comment:s])},"toJSON"),f.prototype.resolve=t(function(){if(this.resolved)return this;if((this.typeDefault=h.defaults[this.type])===s&&(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof p?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]),this.options&&this.options.default!=null&&(this.typeDefault=this.options.default,this.resolvedType instanceof l&&typeof this.typeDefault=="string"&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&((this.options.packed===!0||this.options.packed!==s&&this.resolvedType&&!(this.resolvedType instanceof l))&&delete this.options.packed,Object.keys(this.options).length||(this.options=s)),this.long)this.typeDefault=u.Long.fromNumber(this.typeDefault,this.type.charAt(0)==="u"),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&typeof this.typeDefault=="string"){var d;u.base64.test(this.typeDefault)?u.base64.decode(this.typeDefault,d=u.newBuffer(u.base64.length(this.typeDefault)),0):u.utf8.write(this.typeDefault,d=u.newBuffer(u.utf8.length(this.typeDefault)),0),this.typeDefault=d}return this.map?this.defaultValue=u.emptyObject:this.repeated?this.defaultValue=u.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof p&&(this.parent.ctor.prototype[this.name]=this.defaultValue),a.prototype.resolve.call(this)},"resolve"),f.d=t(function(d,y,b,m){return typeof y=="function"?y=u.decorateType(y).name:y&&typeof y=="object"&&(y=u.decorateEnum(y).name),t(function(_,w){u.decorateType(_.constructor).add(new f(w,d,y,b,{default:m}))},"fieldDecorator")},"decorateField"),f._configure=t(function(d){p=d},"configure")},{15:15,24:24,36:36,37:37}],17:[function(n,i,c){var a=i.exports=n(18);a.build="light";function l(u,p,g){return typeof p=="function"?(g=p,p=new a.Root):p||(p=new a.Root),p.load(u,g)}o(l,"d"),t(l,"load"),a.load=l;function h(u,p){return p||(p=new a.Root),p.loadSync(u)}o(h,"c"),t(h,"loadSync"),a.loadSync=h,a.encoder=n(14),a.decoder=n(13),a.verifier=n(40),a.converter=n(12),a.ReflectionObject=n(24),a.Namespace=n(23),a.Root=n(29),a.Enum=n(15),a.Type=n(35),a.Field=n(16),a.OneOf=n(25),a.MapField=n(20),a.Service=n(33),a.Method=n(22),a.Message=n(21),a.wrappers=n(41),a.types=n(36),a.util=n(37),a.ReflectionObject._configure(a.Root),a.Namespace._configure(a.Type,a.Service),a.Root._configure(a.Type),a.Field._configure(a.Type)},{12:12,13:13,14:14,15:15,16:16,18:18,20:20,21:21,22:22,23:23,24:24,25:25,29:29,33:33,35:35,36:36,37:37,40:40,41:41}],18:[function(n,i,c){var a=c;a.build="minimal",a.Writer=n(42),a.BufferWriter=n(43),a.Reader=n(27),a.BufferReader=n(28),a.util=n(39),a.rpc=n(31),a.roots=n(30),a.configure=l;function l(){a.Reader._configure(a.BufferReader),a.util._configure()}o(l,"d"),t(l,"configure"),a.Writer._configure(a.BufferWriter),l()},{27:27,28:28,30:30,31:31,39:39,42:42,43:43}],19:[function(n,i,c){var a=i.exports=n(17);a.build="full",a.tokenize=n(34),a.parse=n(26),a.common=n(11),a.Root._configure(a.Type,a.parse,a.common)},{11:11,17:17,26:26,34:34}],20:[function(n,i,c){i.exports=u;var a=n(16);((u.prototype=Object.create(a.prototype)).constructor=u).className="MapField";var l=n(36),h=n(37);function u(p,g,f,d,y,b){if(a.call(this,p,g,d,s,s,y,b),!h.isString(f))throw TypeError("keyType must be a string");this.keyType=f,this.resolvedKeyType=null,this.map=!0}o(u,"u"),t(u,"MapField"),u.fromJSON=t(function(p,g){return new u(p,g.id,g.keyType,g.type,g.options,g.comment)},"fromJSON"),u.prototype.toJSON=t(function(p){var g=p?!!p.keepComments:!1;return h.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",g?this.comment:s])},"toJSON"),u.prototype.resolve=t(function(){if(this.resolved)return this;if(l.mapKey[this.keyType]===s)throw Error("invalid key type: "+this.keyType);return a.prototype.resolve.call(this)},"resolve"),u.d=t(function(p,g,f){return typeof f=="function"?f=h.decorateType(f).name:f&&typeof f=="object"&&(f=h.decorateEnum(f).name),t(function(d,y){h.decorateType(d.constructor).add(new u(y,p,g,f))},"mapFieldDecorator")},"decorateMapField")},{16:16,36:36,37:37}],21:[function(n,i,c){i.exports=l;var a=n(39);function l(h){if(h)for(var u=Object.keys(h),p=0;p<u.length;++p)this[u[p]]=h[u[p]]}o(l,"d"),t(l,"Message"),l.create=t(function(h){return this.$type.create(h)},"create"),l.encode=t(function(h,u){return this.$type.encode(h,u)},"encode"),l.encodeDelimited=t(function(h,u){return this.$type.encodeDelimited(h,u)},"encodeDelimited"),l.decode=t(function(h){return this.$type.decode(h)},"decode"),l.decodeDelimited=t(function(h){return this.$type.decodeDelimited(h)},"decodeDelimited"),l.verify=t(function(h){return this.$type.verify(h)},"verify"),l.fromObject=t(function(h){return this.$type.fromObject(h)},"fromObject"),l.toObject=t(function(h,u){return this.$type.toObject(h,u)},"toObject"),l.prototype.toJSON=t(function(){return this.$type.toObject(this,a.toJSONOptions)},"toJSON")},{39:39}],22:[function(n,i,c){i.exports=h;var a=n(24);((h.prototype=Object.create(a.prototype)).constructor=h).className="Method";var l=n(37);function h(u,p,g,f,d,y,b,m){if(l.isObject(d)?(b=d,d=y=s):l.isObject(y)&&(b=y,y=s),!(p===s||l.isString(p)))throw TypeError("type must be a string");if(!l.isString(g))throw TypeError("requestType must be a string");if(!l.isString(f))throw TypeError("responseType must be a string");a.call(this,u,b),this.type=p||"rpc",this.requestType=g,this.requestStream=d?!0:s,this.responseType=f,this.responseStream=y?!0:s,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=m}o(h,"c"),t(h,"Method"),h.fromJSON=t(function(u,p){return new h(u,p.type,p.requestType,p.responseType,p.requestStream,p.responseStream,p.options,p.comment)},"fromJSON"),h.prototype.toJSON=t(function(u){var p=u?!!u.keepComments:!1;return l.toObject(["type",this.type!=="rpc"&&this.type||s,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",p?this.comment:s])},"toJSON"),h.prototype.resolve=t(function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),a.prototype.resolve.call(this))},"resolve")},{24:24,37:37}],23:[function(n,i,c){i.exports=d;var a=n(24);((d.prototype=Object.create(a.prototype)).constructor=d).className="Namespace";var l=n(15),h=n(16),u=n(37),p,g;d.fromJSON=t(function(b,m){return new d(b,m.options).addJSON(m.nested)},"fromJSON");function f(b,m){if(!(b&&b.length))return s;for(var _={},w=0;w<b.length;++w)_[b[w].name]=b[w].toJSON(m);return _}o(f,"t"),t(f,"arrayToJSON"),d.arrayToJSON=f,d.isReservedId=t(function(b,m){if(b){for(var _=0;_<b.length;++_)if(typeof b[_]!="string"&&b[_][0]<=m&&b[_][1]>=m)return!0}return!1},"isReservedId"),d.isReservedName=t(function(b,m){if(b){for(var _=0;_<b.length;++_)if(b[_]===m)return!0}return!1},"isReservedName");function d(b,m){a.call(this,b,m),this.nested=s,this._nestedArray=null}o(d,"r"),t(d,"Namespace");function y(b){return b._nestedArray=null,b}o(y,"e"),t(y,"clearCache"),Object.defineProperty(d.prototype,"nestedArray",{get:t(function(){return this._nestedArray||(this._nestedArray=u.toArray(this.nested))},"get")}),d.prototype.toJSON=t(function(b){return u.toObject(["options",this.options,"nested",f(this.nestedArray,b)])},"toJSON"),d.prototype.addJSON=t(function(b){var m=this;if(b)for(var _=Object.keys(b),w=0,S;w<_.length;++w)S=b[_[w]],m.add((S.fields!==s?p.fromJSON:S.values!==s?l.fromJSON:S.methods!==s?g.fromJSON:S.id!==s?h.fromJSON:d.fromJSON)(_[w],S));return this},"addJSON"),d.prototype.get=t(function(b){return this.nested&&this.nested[b]||null},"get"),d.prototype.getEnum=t(function(b){if(this.nested&&this.nested[b]instanceof l)return this.nested[b].values;throw Error("no such enum: "+b)},"getEnum"),d.prototype.add=t(function(b){if(!(b instanceof h&&b.extend!==s||b instanceof p||b instanceof l||b instanceof g||b instanceof d))throw TypeError("object must be a valid nested object");if(!this.nested)this.nested={};else{var m=this.get(b.name);if(m)if(m instanceof d&&b instanceof d&&!(m instanceof p||m instanceof g)){for(var _=m.nestedArray,w=0;w<_.length;++w)b.add(_[w]);this.remove(m),this.nested||(this.nested={}),b.setOptions(m.options,!0)}else throw Error("duplicate name '"+b.name+"' in "+this)}return this.nested[b.name]=b,b.onAdd(this),y(this)},"add"),d.prototype.remove=t(function(b){if(!(b instanceof a))throw TypeError("object must be a ReflectionObject");if(b.parent!==this)throw Error(b+" is not a member of "+this);return delete this.nested[b.name],Object.keys(this.nested).length||(this.nested=s),b.onRemove(this),y(this)},"remove"),d.prototype.define=t(function(b,m){if(u.isString(b))b=b.split(".");else if(!Array.isArray(b))throw TypeError("illegal path");if(b&&b.length&&b[0]==="")throw Error("path must be relative");for(var _=this;b.length>0;){var w=b.shift();if(_.nested&&_.nested[w]){if(_=_.nested[w],!(_ instanceof d))throw Error("path conflicts with non-namespace objects")}else _.add(_=new d(w))}return m&&_.addJSON(m),_},"define"),d.prototype.resolveAll=t(function(){for(var b=this.nestedArray,m=0;m<b.length;)b[m]instanceof d?b[m++].resolveAll():b[m++].resolve();return this.resolve()},"resolveAll"),d.prototype.lookup=t(function(b,m,_){if(typeof m=="boolean"?(_=m,m=s):m&&!Array.isArray(m)&&(m=[m]),u.isString(b)&&b.length){if(b===".")return this.root;b=b.split(".")}else if(!b.length)return this;if(b[0]==="")return this.root.lookup(b.slice(1),m);var w=this.get(b[0]);if(w){if(b.length===1){if(!m||m.indexOf(w.constructor)>-1)return w}else if(w instanceof d&&(w=w.lookup(b.slice(1),m,!0)))return w}else for(var S=0;S<this.nestedArray.length;++S)if(this._nestedArray[S]instanceof d&&(w=this._nestedArray[S].lookup(b,m,!0)))return w;return this.parent===null||_?null:this.parent.lookup(b,m)},"lookup"),d.prototype.lookupType=t(function(b){var m=this.lookup(b,[p]);if(!m)throw Error("no such type: "+b);return m},"lookupType"),d.prototype.lookupEnum=t(function(b){var m=this.lookup(b,[l]);if(!m)throw Error("no such Enum '"+b+"' in "+this);return m},"lookupEnum"),d.prototype.lookupTypeOrEnum=t(function(b){var m=this.lookup(b,[p,l]);if(!m)throw Error("no such Type or Enum '"+b+"' in "+this);return m},"lookupTypeOrEnum"),d.prototype.lookupService=t(function(b){var m=this.lookup(b,[g]);if(!m)throw Error("no such Service '"+b+"' in "+this);return m},"lookupService"),d._configure=function(b,m){p=b,g=m}},{15:15,16:16,24:24,37:37}],24:[function(n,i,c){i.exports=h,h.className="ReflectionObject";var a=n(37),l;function h(u,p){if(!a.isString(u))throw TypeError("name must be a string");if(p&&!a.isObject(p))throw TypeError("options must be an object");this.options=p,this.name=u,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}o(h,"c"),t(h,"ReflectionObject"),Object.defineProperties(h.prototype,{root:{get:t(function(){for(var u=this;u.parent!==null;)u=u.parent;return u},"get")},fullName:{get:t(function(){for(var u=[this.name],p=this.parent;p;)u.unshift(p.name),p=p.parent;return u.join(".")},"get")}}),h.prototype.toJSON=t(function(){throw Error()},"toJSON"),h.prototype.onAdd=t(function(u){this.parent&&this.parent!==u&&this.parent.remove(this),this.parent=u,this.resolved=!1;var p=u.root;p instanceof l&&p._handleAdd(this)},"onAdd"),h.prototype.onRemove=t(function(u){var p=u.root;p instanceof l&&p._handleRemove(this),this.parent=null,this.resolved=!1},"onRemove"),h.prototype.resolve=t(function(){return this.resolved?this:(this.root instanceof l&&(this.resolved=!0),this)},"resolve"),h.prototype.getOption=t(function(u){return this.options?this.options[u]:s},"getOption"),h.prototype.setOption=t(function(u,p,g){return(!g||!this.options||this.options[u]===s)&&((this.options||(this.options={}))[u]=p),this},"setOption"),h.prototype.setOptions=t(function(u,p){if(u)for(var g=Object.keys(u),f=0;f<g.length;++f)this.setOption(g[f],u[g[f]],p);return this},"setOptions"),h.prototype.toString=t(function(){var u=this.constructor.className,p=this.fullName;return p.length?u+" "+p:u},"toString"),h._configure=function(u){l=u}},{37:37}],25:[function(n,i,c){i.exports=u;var a=n(24);((u.prototype=Object.create(a.prototype)).constructor=u).className="OneOf";var l=n(16),h=n(37);function u(g,f,d,y){if(Array.isArray(f)||(d=f,f=s),a.call(this,g,d),!(f===s||Array.isArray(f)))throw TypeError("fieldNames must be an Array");this.oneof=f||[],this.fieldsArray=[],this.comment=y}o(u,"u"),t(u,"OneOf"),u.fromJSON=t(function(g,f){return new u(g,f.oneof,f.options,f.comment)},"fromJSON"),u.prototype.toJSON=t(function(g){var f=g?!!g.keepComments:!1;return h.toObject(["options",this.options,"oneof",this.oneof,"comment",f?this.comment:s])},"toJSON");function p(g){if(g.parent)for(var f=0;f<g.fieldsArray.length;++f)g.fieldsArray[f].parent||g.parent.add(g.fieldsArray[f])}o(p,"a"),t(p,"addFieldsToParent"),u.prototype.add=t(function(g){if(!(g instanceof l))throw TypeError("field must be a Field");return g.parent&&g.parent!==this.parent&&g.parent.remove(g),this.oneof.push(g.name),this.fieldsArray.push(g),g.partOf=this,p(this),this},"add"),u.prototype.remove=t(function(g){if(!(g instanceof l))throw TypeError("field must be a Field");var f=this.fieldsArray.indexOf(g);if(f<0)throw Error(g+" is not a member of "+this);return this.fieldsArray.splice(f,1),f=this.oneof.indexOf(g.name),f>-1&&this.oneof.splice(f,1),g.partOf=null,this},"remove"),u.prototype.onAdd=t(function(g){a.prototype.onAdd.call(this,g);for(var f=this,d=0;d<this.oneof.length;++d){var y=g.get(this.oneof[d]);y&&!y.partOf&&(y.partOf=f,f.fieldsArray.push(y))}p(this)},"onAdd"),u.prototype.onRemove=t(function(g){for(var f=0,d;f<this.fieldsArray.length;++f)(d=this.fieldsArray[f]).parent&&d.parent.remove(d);a.prototype.onRemove.call(this,g)},"onRemove"),u.d=t(function(){for(var g=new Array(arguments.length),f=0;f<arguments.length;)g[f]=arguments[f++];return t(function(d,y){h.decorateType(d.constructor).add(new u(y,g)),Object.defineProperty(d,y,{get:h.oneOfGetter(g),set:h.oneOfSetter(g)})},"oneOfDecorator")},"decorateOneOf")},{16:16,24:24,37:37}],26:[function(n,i,c){i.exports=q,q.filename=null,q.defaults={keepCase:!1};var a=n(34),l=n(29),h=n(35),u=n(16),p=n(20),g=n(25),f=n(15),d=n(33),y=n(22),b=n(36),m=n(37),_=/^[1-9][0-9]*$/,w=/^-?[1-9][0-9]*$/,S=/^0[x][0-9a-fA-F]+$/,T=/^-?0[x][0-9a-fA-F]+$/,v=/^0[0-7]+$/,A=/^-?0[0-7]+$/,O=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,k=/^[a-zA-Z_][a-zA-Z_0-9]*$/,C=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,B=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function q(de,ge,G){ge instanceof l||(G=ge,ge=new l),G||(G=q.defaults);var ce=a(de,G.alternateCommentMode||!1),H=ce.next,ve=ce.push,me=ce.peek,V=ce.skip,Le=ce.cmnt,ue=!0,Me,Q,ie,fe,J=!1,oe=ge,Ie=G.keepCase?function(L){return L}:m.camelCase;function Y(L,N,x){var U=q.filename;return x||(q.filename=null),Error("illegal "+(N||"token")+" '"+L+"' ("+(U?U+", ":"")+"line "+ce.line+")")}o(Y,"F"),t(Y,"illegal");function st(){var L=[],N;do{if((N=H())!=='"'&&N!=="'")throw Y(N);L.push(H()),V(N),N=me()}while(N==='"'||N==="'");return L.join("")}o(st,"Y"),t(st,"readString");function He(L){var N=H();switch(N){case"'":case'"':return ve(N),st();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return nt(N,!0)}catch{if(L&&C.test(N))return N;throw Y(N,"value")}}o(He,"ht"),t(He,"readValue");function Ke(L,N){var x,U;do N&&((x=me())==='"'||x==="'")?L.push(st()):L.push([U=yt(H()),V("to",!0)?yt(H()):U]);while(V(",",!0));V(";")}o(Ke,"ot"),t(Ke,"readRanges");function nt(L,N){var x=1;switch(L.charAt(0)==="-"&&(x=-1,L=L.substring(1)),L){case"inf":case"INF":case"Inf":return x*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(_.test(L))return x*parseInt(L,10);if(S.test(L))return x*parseInt(L,16);if(v.test(L))return x*parseInt(L,8);if(O.test(L))return x*parseFloat(L);throw Y(L,"number",N)}o(nt,"pt"),t(nt,"parseNumber");function yt(L,N){switch(L){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!N&&L.charAt(0)==="-")throw Y(L,"id");if(w.test(L))return parseInt(L,10);if(T.test(L))return parseInt(L,16);if(A.test(L))return parseInt(L,8);throw Y(L,"id")}o(yt,"nt"),t(yt,"parseId");function Or(){if(Me!==s)throw Y("package");if(Me=H(),!C.test(Me))throw Y(Me,"name");oe=oe.define(Me),V(";")}o(Or,"dt"),t(Or,"parsePackage");function it(){var L=me(),N;switch(L){case"weak":N=ie||(ie=[]),H();break;case"public":H();default:N=Q||(Q=[]);break}L=st(),V(";"),N.push(L)}o(it,"yt"),t(it,"parseImport");function X(){if(V("="),fe=st(),J=fe==="proto3",!J&&fe!=="proto2")throw Y(fe,"syntax");V(";")}o(X,"mt"),t(X,"parseSyntax");function Ee(L,N){switch(N){case"option":return ft(L,N),V(";"),!0;case"message":return bt(L,N),!0;case"enum":return Wu(L,N),!0;case"service":return Ju(L,N),!0;case"extend":return Gu(L,N),!0}return!1}o(Ee,"at"),t(Ee,"parseCommon");function Ae(L,N,x){var U=ce.line;if(L&&(L.comment=Le(),L.filename=q.filename),V("{",!0)){for(var Se;(Se=H())!=="}";)N(Se);V(";",!0)}else x&&x(),V(";"),L&&typeof L.comment!="string"&&(L.comment=Le(U))}o(Ae,"K"),t(Ae,"ifBlock");function bt(L,N){if(!k.test(N=H()))throw Y(N,"type name");var x=new h(N);Ae(x,t(function(U){if(!Ee(x,U))switch(U){case"map":xt(x);break;case"required":case"optional":case"repeated":_t(x,U);break;case"oneof":Hu(x,U);break;case"extensions":Ke(x.extensions||(x.extensions=[]));break;case"reserved":Ke(x.reserved||(x.reserved=[]),!0);break;default:if(!J||!C.test(U))throw Y(U);ve(U),_t(x,"optional");break}},"parseType_block")),L.add(x)}o(bt,"vt"),t(bt,"parseType");function _t(L,N,x){var U=H();if(U==="group"){on(L,N);return}if(!C.test(U))throw Y(U,"type");var Se=H();if(!k.test(Se))throw Y(Se,"name");Se=Ie(Se),V("=");var Re=new u(Se,yt(H()),U,N,x);Ae(Re,t(function(kt){if(kt==="option")ft(Re,kt),V(";");else throw Y(kt)},"parseField_block"),t(function(){cn(Re)},"parseField_line")),L.add(Re),!J&&Re.repeated&&(b.packed[U]!==s||b.basic[U]===s)&&Re.setOption("packed",!1,!0)}o(_t,"st"),t(_t,"parseField");function on(L,N){var x=H();if(!k.test(x))throw Y(x,"name");var U=m.lcFirst(x);x===U&&(x=m.ucFirst(x)),V("=");var Se=yt(H()),Re=new h(x);Re.group=!0;var kt=new u(U,Se,x,N);kt.filename=q.filename,Ae(Re,t(function(Xt){switch(Xt){case"option":ft(Re,Xt),V(";");break;case"required":case"optional":case"repeated":_t(Re,Xt);break;default:throw Y(Xt)}},"parseGroup_block")),L.add(Re).add(kt)}o(on,"gt"),t(on,"parseGroup");function xt(L){V("<");var N=H();if(b.mapKey[N]===s)throw Y(N,"type");V(",");var x=H();if(!C.test(x))throw Y(x,"type");V(">");var U=H();if(!k.test(U))throw Y(U,"name");V("=");var Se=new p(Ie(U),yt(H()),N,x);Ae(Se,t(function(Re){if(Re==="option")ft(Se,Re),V(";");else throw Y(Re)},"parseMapField_block"),t(function(){cn(Se)},"parseMapField_line")),L.add(Se)}o(xt,"wt"),t(xt,"parseMapField");function Hu(L,N){if(!k.test(N=H()))throw Y(N,"name");var x=new g(Ie(N));Ae(x,t(function(U){U==="option"?(ft(x,U),V(";")):(ve(U),_t(x,"optional"))},"parseOneOf_block")),L.add(x)}o(Hu,"Ot"),t(Hu,"parseOneOf");function Wu(L,N){if(!k.test(N=H()))throw Y(N,"name");var x=new f(N);Ae(x,t(function(U){switch(U){case"option":ft(x,U),V(";");break;case"reserved":Ke(x.reserved||(x.reserved=[]),!0);break;default:zu(x,U)}},"parseEnum_block")),L.add(x)}o(Wu,"bt"),t(Wu,"parseEnum");function zu(L,N){if(!k.test(N))throw Y(N,"name");V("=");var x=yt(H(),!0),U={};Ae(U,t(function(Se){if(Se==="option")ft(U,Se),V(";");else throw Y(Se)},"parseEnumValue_block"),t(function(){cn(U)},"parseEnumValue_line")),L.add(N,x,U.comment)}o(zu,"_t"),t(zu,"parseEnumValue");function ft(L,N){var x=V("(",!0);if(!C.test(N=H()))throw Y(N,"name");var U=N;x&&(V(")"),U="("+U+")",N=me(),B.test(N)&&(U+=N,H())),V("="),an(L,U)}o(ft,"Q"),t(ft,"parseOption");function an(L,N){if(V("{",!0))do{if(!k.test(Ge=H()))throw Y(Ge,"name");me()==="{"?an(L,N+"."+Ge):(V(":"),me()==="{"?an(L,N+"."+Ge):ho(L,N+"."+Ge,He(!0)))}while(!V("}",!0));else ho(L,N,He(!0))}o(an,"ut"),t(an,"parseOptionValue");function ho(L,N,x){L.setOption&&L.setOption(N,x)}o(ho,"ct"),t(ho,"setOption");function cn(L){if(V("[",!0)){do ft(L,"option");while(V(",",!0));V("]")}return L}o(cn,"ft"),t(cn,"parseInlineOptions");function Ju(L,N){if(!k.test(N=H()))throw Y(N,"service name");var x=new d(N);Ae(x,t(function(U){if(!Ee(x,U))if(U==="rpc")Ku(x,U);else throw Y(U)},"parseService_block")),L.add(x)}o(Ju,"xt"),t(Ju,"parseService");function Ku(L,N){var x=N;if(!k.test(N=H()))throw Y(N,"name");var U=N,Se,Re,kt,Xt;if(V("("),V("stream",!0)&&(Re=!0),!C.test(N=H())||(Se=N,V(")"),V("returns"),V("("),V("stream",!0)&&(Xt=!0),!C.test(N=H())))throw Y(N);kt=N,V(")");var fo=new y(U,x,Se,kt,Re,Xt);Ae(fo,t(function(po){if(po==="option")ft(fo,po),V(";");else throw Y(po)},"parseMethod_block")),L.add(fo)}o(Ku,"At"),t(Ku,"parseMethod");function Gu(L,N){if(!C.test(N=H()))throw Y(N,"reference");var x=N;Ae(null,t(function(U){switch(U){case"required":case"repeated":case"optional":_t(L,U,x);break;default:if(!J||!C.test(U))throw Y(U);ve(U),_t(L,"optional",x);break}},"parseExtension_block"))}o(Gu,"St"),t(Gu,"parseExtension");for(var Ge;(Ge=H())!==null;)switch(Ge){case"package":if(!ue)throw Y(Ge);Or();break;case"import":if(!ue)throw Y(Ge);it();break;case"syntax":if(!ue)throw Y(Ge);X();break;case"option":if(!ue)throw Y(Ge);ft(oe,Ge),V(";");break;default:if(Ee(oe,Ge)){ue=!1;continue}throw Y(Ge)}return q.filename=null,{package:Me,imports:Q,weakImports:ie,syntax:fe,root:ge}}o(q,"T"),t(q,"parse")},{15:15,16:16,20:20,22:22,25:25,29:29,33:33,34:34,35:35,36:36,37:37}],27:[function(n,i,c){i.exports=g;var a=n(39),l,h=a.LongBits,u=a.utf8;function p(m,_){return RangeError("index out of range: "+m.pos+" + "+(_||1)+" > "+m.len)}o(p,"a"),t(p,"indexOutOfRange");function g(m){this.buf=m,this.pos=0,this.len=m.length}o(g,"s"),t(g,"Reader");var f=typeof Uint8Array<"u"?t(function(m){if(m instanceof Uint8Array||Array.isArray(m))return new g(m);throw Error("illegal buffer")},"create_typed_array"):t(function(m){if(Array.isArray(m))return new g(m);throw Error("illegal buffer")},"create_array");g.create=a.Buffer?t(function(m){return(g.create=t(function(_){return a.Buffer.isBuffer(_)?new l(_):f(_)},"create_buffer"))(m)},"create_buffer_setup"):f,g.prototype._slice=a.Array.prototype.subarray||a.Array.prototype.slice,g.prototype.uint32=t((function(){var m=4294967295;return t(function(){if(m=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(m=(m|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(m=(m|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(m=(m|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(m=(m|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return m;if((this.pos+=5)>this.len)throw this.pos=this.len,p(this,10);return m},"read_uint32")}),"read_uint32_setup")(),g.prototype.int32=t(function(){return this.uint32()|0},"read_int32"),g.prototype.sint32=t(function(){var m=this.uint32();return m>>>1^-(m&1)|0},"read_sint32");function d(){var m=new h(0,0),_=0;if(this.len-this.pos>4){for(;_<4;++_)if(m.lo=(m.lo|(this.buf[this.pos]&127)<<_*7)>>>0,this.buf[this.pos++]<128)return m;if(m.lo=(m.lo|(this.buf[this.pos]&127)<<28)>>>0,m.hi=(m.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return m;_=0}else{for(;_<3;++_){if(this.pos>=this.len)throw p(this);if(m.lo=(m.lo|(this.buf[this.pos]&127)<<_*7)>>>0,this.buf[this.pos++]<128)return m}return m.lo=(m.lo|(this.buf[this.pos++]&127)<<_*7)>>>0,m}if(this.len-this.pos>4){for(;_<5;++_)if(m.hi=(m.hi|(this.buf[this.pos]&127)<<_*7+3)>>>0,this.buf[this.pos++]<128)return m}else for(;_<5;++_){if(this.pos>=this.len)throw p(this);if(m.hi=(m.hi|(this.buf[this.pos]&127)<<_*7+3)>>>0,this.buf[this.pos++]<128)return m}throw Error("invalid varint encoding")}o(d,"r"),t(d,"readLongVarint"),g.prototype.bool=t(function(){return this.uint32()!==0},"read_bool");function y(m,_){return(m[_-4]|m[_-3]<<8|m[_-2]<<16|m[_-1]<<24)>>>0}o(y,"e"),t(y,"readFixed32_end"),g.prototype.fixed32=t(function(){if(this.pos+4>this.len)throw p(this,4);return y(this.buf,this.pos+=4)},"read_fixed32"),g.prototype.sfixed32=t(function(){if(this.pos+4>this.len)throw p(this,4);return y(this.buf,this.pos+=4)|0},"read_sfixed32");function b(){if(this.pos+8>this.len)throw p(this,8);return new h(y(this.buf,this.pos+=4),y(this.buf,this.pos+=4))}o(b,"f"),t(b,"readFixed64"),g.prototype.float=t(function(){if(this.pos+4>this.len)throw p(this,4);var m=a.float.readFloatLE(this.buf,this.pos);return this.pos+=4,m},"read_float"),g.prototype.double=t(function(){if(this.pos+8>this.len)throw p(this,4);var m=a.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,m},"read_double"),g.prototype.bytes=t(function(){var m=this.uint32(),_=this.pos,w=this.pos+m;if(w>this.len)throw p(this,m);return this.pos+=m,Array.isArray(this.buf)?this.buf.slice(_,w):_===w?new this.buf.constructor(0):this._slice.call(this.buf,_,w)},"read_bytes"),g.prototype.string=t(function(){var m=this.bytes();return u.read(m,0,m.length)},"read_string"),g.prototype.skip=t(function(m){if(typeof m=="number"){if(this.pos+m>this.len)throw p(this,m);this.pos+=m}else do if(this.pos>=this.len)throw p(this);while(this.buf[this.pos++]&128);return this},"skip"),g.prototype.skipType=function(m){switch(m){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:do{if((m=this.uint32()&7)===4)break;this.skipType(m)}while(!0);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+m+" at offset "+this.pos)}return this},g._configure=function(m){l=m;var _=a.Long?"toLong":"toNumber";a.merge(g.prototype,{int64:t(function(){return d.call(this)[_](!1)},"read_int64"),uint64:t(function(){return d.call(this)[_](!0)},"read_uint64"),sint64:t(function(){return d.call(this).zzDecode()[_](!1)},"read_sint64"),fixed64:t(function(){return b.call(this)[_](!0)},"read_fixed64"),sfixed64:t(function(){return b.call(this)[_](!1)},"read_sfixed64")})}},{39:39}],28:[function(n,i,c){i.exports=h;var a=n(27);(h.prototype=Object.create(a.prototype)).constructor=h;var l=n(39);function h(u){a.call(this,u)}o(h,"c"),t(h,"BufferReader"),l.Buffer&&(h.prototype._slice=l.Buffer.prototype.slice),h.prototype.string=t(function(){var u=this.uint32();return this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+u,this.len))},"read_string_buffer")},{27:27,39:39}],29:[function(n,i,c){i.exports=y;var a=n(23);((y.prototype=Object.create(a.prototype)).constructor=y).className="Root";var l=n(16),h=n(15),u=n(25),p=n(37),g,f,d;function y(w){a.call(this,"",w),this.deferred=[],this.files=[]}o(y,"e"),t(y,"Root"),y.fromJSON=t(function(w,S){return S||(S=new y),w.options&&S.setOptions(w.options),S.addJSON(w.nested)},"fromJSON"),y.prototype.resolvePath=p.path.resolve;function b(){}o(b,"f"),t(b,"SYNC"),y.prototype.load=t(o(function w(S,T,v){typeof T=="function"&&(v=T,T=s);var A=this;if(!v)return p.asPromise(w,A,S,T);var O=v===b;function k(G,ce){if(v){var H=v;if(v=null,O)throw G;H(G,ce)}}o(k,"g"),t(k,"finish");function C(G,ce){try{if(p.isString(ce)&&ce.charAt(0)==="{"&&(ce=JSON.parse(ce)),!p.isString(ce))A.setOptions(ce.options).addJSON(ce.nested);else{f.filename=G;var H=f(ce,A,T),ve,me=0;if(H.imports)for(;me<H.imports.length;++me)(ve=A.resolvePath(G,H.imports[me]))&&B(ve);if(H.weakImports)for(me=0;me<H.weakImports.length;++me)(ve=A.resolvePath(G,H.weakImports[me]))&&B(ve,!0)}}catch(V){k(V)}!O&&!q&&k(null,A)}o(C,"_"),t(C,"process");function B(G,ce){var H=G.lastIndexOf("google/protobuf/");if(H>-1){var ve=G.substring(H);ve in d&&(G=ve)}if(!(A.files.indexOf(G)>-1)){if(A.files.push(G),G in d){O?C(G,d[G]):(++q,setTimeout(function(){--q,C(G,d[G])}));return}if(O){var me;try{me=p.fs.readFileSync(G).toString("utf8")}catch(V){ce||k(V);return}C(G,me)}else++q,p.fetch(G,function(V,Le){if(--q,!!v){if(V){ce?q||k(null,A):k(V);return}C(G,Le)}})}}o(B,"D"),t(B,"fetch");var q=0;p.isString(S)&&(S=[S]);for(var de=0,ge;de<S.length;++de)(ge=A.resolvePath("",S[de]))&&B(ge);return O?A:(q||k(null,A),s)},"p"),"load"),y.prototype.loadSync=t(function(w,S){if(!p.isNode)throw Error("not supported");return this.load(w,S,b)},"loadSync"),y.prototype.resolveAll=t(function(){if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(w){return"'extend "+w.extend+"' in "+w.parent.fullName}).join(", "));return a.prototype.resolveAll.call(this)},"resolveAll");var m=/^[A-Z]/;function _(w,S){var T=S.parent.lookup(S.extend);if(T){var v=new l(S.fullName,S.id,S.type,S.rule,s,S.options);return v.declaringField=S,S.extensionField=v,T.add(v),!0}return!1}o(_,"o"),t(_,"tryHandleExtension"),y.prototype._handleAdd=t(function(w){if(w instanceof l)w.extend!==s&&!w.extensionField&&(_(this,w)||this.deferred.push(w));else if(w instanceof h)m.test(w.name)&&(w.parent[w.name]=w.values);else if(!(w instanceof u)){if(w instanceof g)for(var S=0;S<this.deferred.length;)_(this,this.deferred[S])?this.deferred.splice(S,1):++S;for(var T=0;T<w.nestedArray.length;++T)this._handleAdd(w._nestedArray[T]);m.test(w.name)&&(w.parent[w.name]=w)}},"_handleAdd"),y.prototype._handleRemove=t(function(w){if(w instanceof l){if(w.extend!==s)if(w.extensionField)w.extensionField.parent.remove(w.extensionField),w.extensionField=null;else{var S=this.deferred.indexOf(w);S>-1&&this.deferred.splice(S,1)}}else if(w instanceof h)m.test(w.name)&&delete w.parent[w.name];else if(w instanceof a){for(var T=0;T<w.nestedArray.length;++T)this._handleRemove(w._nestedArray[T]);m.test(w.name)&&delete w.parent[w.name]}},"_handleRemove"),y._configure=function(w,S,T){g=w,f=S,d=T}},{15:15,16:16,23:23,25:25,37:37}],30:[function(n,i,c){i.exports={}},{}],31:[function(n,i,c){var a=c;a.Service=n(32)},{32:32}],32:[function(n,i,c){i.exports=l;var a=n(39);(l.prototype=Object.create(a.EventEmitter.prototype)).constructor=l;function l(h,u,p){if(typeof h!="function")throw TypeError("rpcImpl must be a function");a.EventEmitter.call(this),this.rpcImpl=h,this.requestDelimited=!!u,this.responseDelimited=!!p}o(l,"d"),t(l,"Service"),l.prototype.rpcCall=t(o(function h(u,p,g,f,d){if(!f)throw TypeError("request must be specified");var y=this;if(!d)return a.asPromise(h,y,u,p,g,f);if(!y.rpcImpl)return setTimeout(function(){d(Error("already ended"))},0),s;try{return y.rpcImpl(u,p[y.requestDelimited?"encodeDelimited":"encode"](f).finish(),t(function(b,m){if(b)return y.emit("error",b,u),d(b);if(m===null)return y.end(!0),s;if(!(m instanceof g))try{m=g[y.responseDelimited?"decodeDelimited":"decode"](m)}catch(_){return y.emit("error",_,u),d(_)}return y.emit("data",m,u),d(null,m)},"rpcCallback"))}catch(b){return y.emit("error",b,u),setTimeout(function(){d(b)},0),s}},"c"),"rpcCall"),l.prototype.end=t(function(h){return this.rpcImpl&&(h||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},"end")},{39:39}],33:[function(n,i,c){i.exports=p;var a=n(23);((p.prototype=Object.create(a.prototype)).constructor=p).className="Service";var l=n(22),h=n(37),u=n(31);function p(f,d){a.call(this,f,d),this.methods={},this._methodsArray=null}o(p,"a"),t(p,"Service"),p.fromJSON=t(function(f,d){var y=new p(f,d.options);if(d.methods)for(var b=Object.keys(d.methods),m=0;m<b.length;++m)y.add(l.fromJSON(b[m],d.methods[b[m]]));return d.nested&&y.addJSON(d.nested),y.comment=d.comment,y},"fromJSON"),p.prototype.toJSON=t(function(f){var d=a.prototype.toJSON.call(this,f),y=f?!!f.keepComments:!1;return h.toObject(["options",d&&d.options||s,"methods",a.arrayToJSON(this.methodsArray,f)||{},"nested",d&&d.nested||s,"comment",y?this.comment:s])},"toJSON"),Object.defineProperty(p.prototype,"methodsArray",{get:t(function(){return this._methodsArray||(this._methodsArray=h.toArray(this.methods))},"get")});function g(f){return f._methodsArray=null,f}o(g,"s"),t(g,"clearCache"),p.prototype.get=t(function(f){return this.methods[f]||a.prototype.get.call(this,f)},"get"),p.prototype.resolveAll=t(function(){for(var f=this.methodsArray,d=0;d<f.length;++d)f[d].resolve();return a.prototype.resolve.call(this)},"resolveAll"),p.prototype.add=t(function(f){if(this.get(f.name))throw Error("duplicate name '"+f.name+"' in "+this);return f instanceof l?(this.methods[f.name]=f,f.parent=this,g(this)):a.prototype.add.call(this,f)},"add"),p.prototype.remove=t(function(f){if(f instanceof l){if(this.methods[f.name]!==f)throw Error(f+" is not a member of "+this);return delete this.methods[f.name],f.parent=null,g(this)}return a.prototype.remove.call(this,f)},"remove"),p.prototype.create=t(function(f,d,y){for(var b=new u.Service(f,d,y),m=0,_;m<this.methodsArray.length;++m){var w=h.lcFirst((_=this._methodsArray[m]).resolve().name).replace(/[^$\w_]/g,"");b[w]=h.codegen(["r","c"],h.isReserved(w)?w+"_":w)("return this.rpcCall(m,q,s,r,c)")({m:_,q:_.resolvedRequestType.ctor,s:_.resolvedResponseType.ctor})}return b},"create")},{22:22,23:23,31:31,37:37}],34:[function(n,i,c){i.exports=m;var a=/[\s{}=;:[\],'"()<>]/g,l=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,h=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,u=/^ *[*/]+ */,p=/^\s*\*?\/*/,g=/\n/g,f=/\s/,d=/\\(.?)/g,y={0:"\0",r:"\r",n:`
`,t:" "};function b(_){return _.replace(d,function(w,S){switch(S){case"\\":case"":return S;default:return y[S]||""}})}o(b,"f"),t(b,"unescape"),m.unescape=b;function m(_,w){_=_.toString();var S=0,T=_.length,v=1,A=null,O=null,k=0,C=!1,B=[],q=null;function de(Q){return Error("illegal "+Q+" (line "+v+")")}o(de,"J"),t(de,"illegal");function ge(){var Q=q==="'"?h:l;Q.lastIndex=S-1;var ie=Q.exec(_);if(!ie)throw de("string");return S=Q.lastIndex,V(q),q=null,b(ie[1])}o(ge,"H"),t(ge,"readString");function G(Q){return _.charAt(Q)}o(G,"I"),t(G,"charAt");function ce(Q,ie){A=_.charAt(Q++),k=v,C=!1;var fe;w?fe=2:fe=3;var J=Q-fe,oe;do if(--J<0||(oe=_.charAt(J))===`
`){C=!0;break}while(oe===" "||oe===" ");for(var Ie=_.substring(Q,ie).split(g),Y=0;Y<Ie.length;++Y)Ie[Y]=Ie[Y].replace(w?p:u,"").trim();O=Ie.join(`
`).trim()}o(ce,"$"),t(ce,"setComment");function H(Q){var ie=ve(Q),fe=_.substring(Q,ie),J=/^\s*\/{1,2}/.test(fe);return J}o(H,"B"),t(H,"isDoubleSlashCommentLine");function ve(Q){for(var ie=Q;ie<T&&G(ie)!==`
`;)ie++;return ie}o(ve,"U"),t(ve,"findEndOfLine");function me(){if(B.length>0)return B.shift();if(q)return ge();var Q,ie,fe,J,oe;do{if(S===T)return null;for(Q=!1;f.test(fe=G(S));)if(fe===`
`&&++v,++S===T)return null;if(G(S)==="/"){if(++S===T)throw de("comment");if(G(S)==="/")if(w){if(J=S,oe=!1,H(S)){oe=!0;do{if(S=ve(S),S===T)break;S++}while(H(S))}else S=Math.min(T,ve(S)+1);oe&&ce(J,S),v++,Q=!0}else{for(oe=G(J=S+1)==="/";G(++S)!==`
`;)if(S===T)return null;++S,oe&&ce(J,S-1),++v,Q=!0}else if((fe=G(S))==="*"){J=S+1,oe=w||G(J)==="*";do{if(fe===`
`&&++v,++S===T)throw de("comment");ie=fe,fe=G(S)}while(ie!=="*"||fe!=="/");++S,oe&&ce(J,S-2),Q=!0}else return"/"}}while(Q);var Ie=S;a.lastIndex=0;var Y=a.test(G(Ie++));if(!Y)for(;Ie<T&&!a.test(G(Ie));)++Ie;var st=_.substring(S,S=Ie);return(st==='"'||st==="'")&&(q=st),st}o(me,"P"),t(me,"next");function V(Q){B.push(Q)}o(V,"N"),t(V,"push");function Le(){if(!B.length){var Q=me();if(Q===null)return null;V(Q)}return B[0]}o(Le,"q"),t(Le,"peek");function ue(Q,ie){var fe=Le(),J=fe===Q;if(J)return me(),!0;if(!ie)throw de("token '"+fe+"', '"+Q+"' expected");return!1}o(ue,"rt"),t(ue,"skip");function Me(Q){var ie=null;return Q===s?k===v-1&&(w||A==="*"||C)&&(ie=O):(k<Q&&Le(),k===Q&&!C&&(w||A==="/")&&(ie=O)),ie}return o(Me,"tt"),t(Me,"cmnt"),Object.defineProperty({next:me,peek:Le,push:V,skip:ue,cmnt:Me},"line",{get:t(function(){return v},"get")})}o(m,"n"),t(m,"tokenize")},{}],35:[function(n,i,c){i.exports=v;var a=n(23);((v.prototype=Object.create(a.prototype)).constructor=v).className="Type";var l=n(15),h=n(25),u=n(16),p=n(20),g=n(33),f=n(21),d=n(27),y=n(42),b=n(37),m=n(14),_=n(13),w=n(40),S=n(12),T=n(41);function v(O,k){a.call(this,O,k),this.fields={},this.oneofs=s,this.extensions=s,this.reserved=s,this.group=s,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}o(v,"m"),t(v,"Type"),Object.defineProperties(v.prototype,{fieldsById:{get:t(function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var O=Object.keys(this.fields),k=0;k<O.length;++k){var C=this.fields[O[k]],B=C.id;if(this._fieldsById[B])throw Error("duplicate id "+B+" in "+this);this._fieldsById[B]=C}return this._fieldsById},"get")},fieldsArray:{get:t(function(){return this._fieldsArray||(this._fieldsArray=b.toArray(this.fields))},"get")},oneofsArray:{get:t(function(){return this._oneofsArray||(this._oneofsArray=b.toArray(this.oneofs))},"get")},ctor:{get:t(function(){return this._ctor||(this.ctor=v.generateConstructor(this)())},"get"),set:t(function(O){var k=O.prototype;k instanceof f||((O.prototype=new f).constructor=O,b.merge(O.prototype,k)),O.$type=O.prototype.$type=this,b.merge(O,f,!0),this._ctor=O;for(var C=0;C<this.fieldsArray.length;++C)this._fieldsArray[C].resolve();var B={};for(C=0;C<this.oneofsArray.length;++C)B[this._oneofsArray[C].resolve().name]={get:b.oneOfGetter(this._oneofsArray[C].oneof),set:b.oneOfSetter(this._oneofsArray[C].oneof)};C&&Object.defineProperties(O.prototype,B)},"set")}}),v.generateConstructor=t(function(O){for(var k=b.codegen(["p"],O.name),C=0,B;C<O.fieldsArray.length;++C)(B=O._fieldsArray[C]).map?k("this%s={}",b.safeProp(B.name)):B.repeated&&k("this%s=[]",b.safeProp(B.name));return k("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")},"generateConstructor");function A(O){return O._fieldsById=O._fieldsArray=O._oneofsArray=null,delete O.encode,delete O.decode,delete O.verify,O}o(A,"w"),t(A,"clearCache"),v.fromJSON=t(function(O,k){var C=new v(O,k.options);C.extensions=k.extensions,C.reserved=k.reserved;for(var B=Object.keys(k.fields),q=0;q<B.length;++q)C.add((typeof k.fields[B[q]].keyType<"u"?p.fromJSON:u.fromJSON)(B[q],k.fields[B[q]]));if(k.oneofs)for(B=Object.keys(k.oneofs),q=0;q<B.length;++q)C.add(h.fromJSON(B[q],k.oneofs[B[q]]));if(k.nested)for(B=Object.keys(k.nested),q=0;q<B.length;++q){var de=k.nested[B[q]];C.add((de.id!==s?u.fromJSON:de.fields!==s?v.fromJSON:de.values!==s?l.fromJSON:de.methods!==s?g.fromJSON:a.fromJSON)(B[q],de))}return k.extensions&&k.extensions.length&&(C.extensions=k.extensions),k.reserved&&k.reserved.length&&(C.reserved=k.reserved),k.group&&(C.group=!0),k.comment&&(C.comment=k.comment),C},"fromJSON"),v.prototype.toJSON=t(function(O){var k=a.prototype.toJSON.call(this,O),C=O?!!O.keepComments:!1;return b.toObject(["options",k&&k.options||s,"oneofs",a.arrayToJSON(this.oneofsArray,O),"fields",a.arrayToJSON(this.fieldsArray.filter(function(B){return!B.declaringField}),O)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:s,"reserved",this.reserved&&this.reserved.length?this.reserved:s,"group",this.group||s,"nested",k&&k.nested||s,"comment",C?this.comment:s])},"toJSON"),v.prototype.resolveAll=t(function(){for(var O=this.fieldsArray,k=0;k<O.length;)O[k++].resolve();var C=this.oneofsArray;for(k=0;k<C.length;)C[k++].resolve();return a.prototype.resolveAll.call(this)},"resolveAll"),v.prototype.get=t(function(O){return this.fields[O]||this.oneofs&&this.oneofs[O]||this.nested&&this.nested[O]||null},"get"),v.prototype.add=t(function(O){if(this.get(O.name))throw Error("duplicate name '"+O.name+"' in "+this);if(O instanceof u&&O.extend===s){if(this._fieldsById?this._fieldsById[O.id]:this.fieldsById[O.id])throw Error("duplicate id "+O.id+" in "+this);if(this.isReservedId(O.id))throw Error("id "+O.id+" is reserved in "+this);if(this.isReservedName(O.name))throw Error("name '"+O.name+"' is reserved in "+this);return O.parent&&O.parent.remove(O),this.fields[O.name]=O,O.message=this,O.onAdd(this),A(this)}return O instanceof h?(this.oneofs||(this.oneofs={}),this.oneofs[O.name]=O,O.onAdd(this),A(this)):a.prototype.add.call(this,O)},"add"),v.prototype.remove=t(function(O){if(O instanceof u&&O.extend===s){if(!this.fields||this.fields[O.name]!==O)throw Error(O+" is not a member of "+this);return delete this.fields[O.name],O.parent=null,O.onRemove(this),A(this)}if(O instanceof h){if(!this.oneofs||this.oneofs[O.name]!==O)throw Error(O+" is not a member of "+this);return delete this.oneofs[O.name],O.parent=null,O.onRemove(this),A(this)}return a.prototype.remove.call(this,O)},"remove"),v.prototype.isReservedId=t(function(O){return a.isReservedId(this.reserved,O)},"isReservedId"),v.prototype.isReservedName=t(function(O){return a.isReservedName(this.reserved,O)},"isReservedName"),v.prototype.create=t(function(O){return new this.ctor(O)},"create"),v.prototype.setup=t(function(){for(var O=this.fullName,k=[],C=0;C<this.fieldsArray.length;++C)k.push(this._fieldsArray[C].resolve().resolvedType);this.encode=m(this)({Writer:y,types:k,util:b}),this.decode=_(this)({Reader:d,types:k,util:b}),this.verify=w(this)({types:k,util:b}),this.fromObject=S.fromObject(this)({types:k,util:b}),this.toObject=S.toObject(this)({types:k,util:b});var B=T[O];if(B){var q=Object.create(this);q.fromObject=this.fromObject,this.fromObject=B.fromObject.bind(q),q.toObject=this.toObject,this.toObject=B.toObject.bind(q)}return this},"setup"),v.prototype.encode=t(function(O,k){return this.setup().encode(O,k)},"encode_setup"),v.prototype.encodeDelimited=t(function(O,k){return this.encode(O,k&&k.len?k.fork():k).ldelim()},"encodeDelimited"),v.prototype.decode=t(function(O,k){return this.setup().decode(O,k)},"decode_setup"),v.prototype.decodeDelimited=t(function(O){return O instanceof d||(O=d.create(O)),this.decode(O,O.uint32())},"decodeDelimited"),v.prototype.verify=t(function(O){return this.setup().verify(O)},"verify_setup"),v.prototype.fromObject=t(function(O){return this.setup().fromObject(O)},"fromObject"),v.prototype.toObject=t(function(O,k){return this.setup().toObject(O,k)},"toObject"),v.d=t(function(O){return t(function(k){b.decorateType(k,O)},"typeDecorator")},"decorateType")},{12:12,13:13,14:14,15:15,16:16,20:20,21:21,23:23,25:25,27:27,33:33,37:37,40:40,41:41,42:42}],36:[function(n,i,c){var a=c,l=n(37),h=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function u(p,g){var f=0,d={};for(g|=0;f<p.length;)d[h[f+g]]=p[f++];return d}o(u,"u"),t(u,"bake"),a.basic=u([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),a.defaults=u([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",l.emptyArray,null]),a.long=u([0,0,0,1,1],7),a.mapKey=u([0,0,0,5,5,0,0,0,1,1,0,2],2),a.packed=u([1,5,0,0,0,5,5,0,0,0,1,1,0])},{37:37}],37:[function(n,i,c){var a=i.exports=n(39),l=n(30),h,u;a.codegen=n(3),a.fetch=n(5),a.path=n(8),a.fs=a.inquire("fs"),a.toArray=t(function(y){if(y){for(var b=Object.keys(y),m=new Array(b.length),_=0;_<b.length;)m[_]=y[b[_++]];return m}return[]},"toArray"),a.toObject=t(function(y){for(var b={},m=0;m<y.length;){var _=y[m++],w=y[m++];w!==s&&(b[_]=w)}return b},"toObject");var p=/\\/g,g=/"/g;a.isReserved=t(function(y){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(y)},"isReserved"),a.safeProp=t(function(y){return!/^[$\w_]+$/.test(y)||a.isReserved(y)?'["'+y.replace(p,"\\\\").replace(g,'\\"')+'"]':"."+y},"safeProp"),a.ucFirst=t(function(y){return y.charAt(0).toUpperCase()+y.substring(1)},"ucFirst");var f=/_([a-z])/g;a.camelCase=t(function(y){return y.substring(0,1)+y.substring(1).replace(f,function(b,m){return m.toUpperCase()})},"camelCase"),a.compareFieldsById=t(function(y,b){return y.id-b.id},"compareFieldsById"),a.decorateType=t(function(y,b){if(y.$type)return b&&y.$type.name!==b&&(a.decorateRoot.remove(y.$type),y.$type.name=b,a.decorateRoot.add(y.$type)),y.$type;h||(h=n(35));var m=new h(b||y.name);return a.decorateRoot.add(m),m.ctor=y,Object.defineProperty(y,"$type",{value:m,enumerable:!1}),Object.defineProperty(y.prototype,"$type",{value:m,enumerable:!1}),m},"decorateType");var d=0;a.decorateEnum=t(function(y){if(y.$type)return y.$type;u||(u=n(15));var b=new u("Enum"+d++,y);return a.decorateRoot.add(b),Object.defineProperty(y,"$type",{value:b,enumerable:!1}),b},"decorateEnum"),Object.defineProperty(a,"decorateRoot",{get:t(function(){return l.decorated||(l.decorated=new(n(29)))},"get")})},{15:15,29:29,3:3,30:30,35:35,39:39,5:5,8:8}],38:[function(n,i,c){i.exports=l;var a=n(39);function l(g,f){this.lo=g>>>0,this.hi=f>>>0}o(l,"d"),t(l,"LongBits");var h=l.zero=new l(0,0);h.toNumber=function(){return 0},h.zzEncode=h.zzDecode=function(){return this},h.length=function(){return 1};var u=l.zeroHash="\0\0\0\0\0\0\0\0";l.fromNumber=t(function(g){if(g===0)return h;var f=g<0;f&&(g=-g);var d=g>>>0,y=(g-d)/4294967296>>>0;return f&&(y=~y>>>0,d=~d>>>0,++d>4294967295&&(d=0,++y>4294967295&&(y=0))),new l(d,y)},"fromNumber"),l.from=t(function(g){if(typeof g=="number")return l.fromNumber(g);if(a.isString(g))if(a.Long)g=a.Long.fromString(g);else return l.fromNumber(parseInt(g,10));return g.low||g.high?new l(g.low>>>0,g.high>>>0):h},"from"),l.prototype.toNumber=t(function(g){if(!g&&this.hi>>>31){var f=~this.lo+1>>>0,d=~this.hi>>>0;return f||(d=d+1>>>0),-(f+d*4294967296)}return this.lo+this.hi*4294967296},"toNumber"),l.prototype.toLong=t(function(g){return a.Long?new a.Long(this.lo|0,this.hi|0,!!g):{low:this.lo|0,high:this.hi|0,unsigned:!!g}},"toLong");var p=String.prototype.charCodeAt;l.fromHash=t(function(g){return g===u?h:new l((p.call(g,0)|p.call(g,1)<<8|p.call(g,2)<<16|p.call(g,3)<<24)>>>0,(p.call(g,4)|p.call(g,5)<<8|p.call(g,6)<<16|p.call(g,7)<<24)>>>0)},"fromHash"),l.prototype.toHash=t(function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},"toHash"),l.prototype.zzEncode=t(function(){var g=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^g)>>>0,this.lo=(this.lo<<1^g)>>>0,this},"zzEncode"),l.prototype.zzDecode=t(function(){var g=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^g)>>>0,this.hi=(this.hi>>>1^g)>>>0,this},"zzDecode"),l.prototype.length=t(function(){var g=this.lo,f=(this.lo>>>28|this.hi<<4)>>>0,d=this.hi>>>24;return d===0?f===0?g<16384?g<128?1:2:g<2097152?3:4:f<16384?f<128?5:6:f<2097152?7:8:d<128?9:10},"length")},{39:39}],39:[function(n,i,c){var a=c;a.asPromise=n(1),a.base64=n(2),a.EventEmitter=n(4),a.float=n(6),a.inquire=n(7),a.utf8=n(10),a.pool=n(9),a.LongBits=n(38),a.emptyArray=Object.freeze?Object.freeze([]):[],a.emptyObject=Object.freeze?Object.freeze({}):{},a.isNode=!!(ts.process&&ts.process.versions&&ts.process.versions.node),a.isInteger=Number.isInteger||t(function(u){return typeof u=="number"&&isFinite(u)&&Math.floor(u)===u},"isInteger"),a.isString=t(function(u){return typeof u=="string"||u instanceof String},"isString"),a.isObject=t(function(u){return u&&typeof u=="object"},"isObject"),a.isset=a.isSet=t(function(u,p){var g=u[p];return g!=null&&u.hasOwnProperty(p)?typeof g!="object"||(Array.isArray(g)?g.length:Object.keys(g).length)>0:!1},"isSet"),a.Buffer=(function(){try{var u=a.inquire("buffer").Buffer;return u.prototype.utf8Write?u:null}catch{return null}})(),a._Buffer_from=null,a._Buffer_allocUnsafe=null,a.newBuffer=t(function(u){return typeof u=="number"?a.Buffer?a._Buffer_allocUnsafe(u):new a.Array(u):a.Buffer?a._Buffer_from(u):typeof Uint8Array>"u"?u:new Uint8Array(u)},"newBuffer"),a.Array=typeof Uint8Array<"u"?Uint8Array:Array,a.Long=ts.dcodeIO&&ts.dcodeIO.Long||a.inquire("long"),a.key2Re=/^true|false|0|1$/,a.key32Re=/^-?(?:0|[1-9][0-9]*)$/,a.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,a.longToHash=t(function(u){return u?a.LongBits.from(u).toHash():a.LongBits.zeroHash},"longToHash"),a.longFromHash=t(function(u,p){var g=a.LongBits.fromHash(u);return a.Long?a.Long.fromBits(g.lo,g.hi,p):g.toNumber(!!p)},"longFromHash");function l(u,p,g){for(var f=Object.keys(p),d=0;d<f.length;++d)(u[f[d]]===s||!g)&&(u[f[d]]=p[f[d]]);return u}o(l,"d"),t(l,"merge"),a.merge=l,a.lcFirst=t(function(u){return u.charAt(0).toLowerCase()+u.substring(1)},"lcFirst");function h(u){function p(g,f){if(!(this instanceof p))return new p(g,f);Object.defineProperty(this,"message",{get:t(function(){return g},"get")}),Error.captureStackTrace?Error.captureStackTrace(this,p):Object.defineProperty(this,"stack",{value:new Error().stack||""}),f&&l(this,f)}return o(p,"a"),t(p,"CustomError"),(p.prototype=Object.create(Error.prototype)).constructor=p,Object.defineProperty(p.prototype,"name",{get:t(function(){return u},"get")}),p.prototype.toString=t(function(){return this.name+": "+this.message},"toString"),p}o(h,"c"),t(h,"newError"),a.newError=h,a.ProtocolError=h("ProtocolError"),a.oneOfGetter=t(function(u){for(var p={},g=0;g<u.length;++g)p[u[g]]=1;return function(){for(var f=Object.keys(this),d=f.length-1;d>-1;--d)if(p[f[d]]===1&&this[f[d]]!==s&&this[f[d]]!==null)return f[d]}},"getOneOf"),a.oneOfSetter=t(function(u){return function(p){for(var g=0;g<u.length;++g)u[g]!==p&&delete this[u[g]]}},"setOneOf"),a.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},a._configure=function(){var u=a.Buffer;if(!u){a._Buffer_from=a._Buffer_allocUnsafe=null;return}a._Buffer_from=u.from!==Uint8Array.from&&u.from||t(function(p,g){return new u(p,g)},"Buffer_from"),a._Buffer_allocUnsafe=u.allocUnsafe||t(function(p){return new u(p)},"Buffer_allocUnsafe")}},{1:1,10:10,2:2,38:38,4:4,6:6,7:7,9:9}],40:[function(n,i,c){i.exports=g;var a=n(15),l=n(37);function h(f,d){return f.name+": "+d+(f.repeated&&d!=="array"?"[]":f.map&&d!=="object"?"{k:"+f.keyType+"}":"")+" expected"}o(h,"c"),t(h,"invalid");function u(f,d,y,b){if(d.resolvedType)if(d.resolvedType instanceof a){f("switch(%s){",b)("default:")("return%j",h(d,"enum value"));for(var m=Object.keys(d.resolvedType.values),_=0;_<m.length;++_)f("case %i:",d.resolvedType.values[m[_]]);f("break")("}")}else f("{")("var e=types[%i].verify(%s);",y,b)("if(e)")("return%j+e",d.name+".")("}");else switch(d.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":f("if(!util.isInteger(%s))",b)("return%j",h(d,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":f("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",b,b,b,b)("return%j",h(d,"integer|Long"));break;case"float":case"double":f('if(typeof %s!=="number")',b)("return%j",h(d,"number"));break;case"bool":f('if(typeof %s!=="boolean")',b)("return%j",h(d,"boolean"));break;case"string":f("if(!util.isString(%s))",b)("return%j",h(d,"string"));break;case"bytes":f('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',b,b,b)("return%j",h(d,"buffer"));break}return f}o(u,"u"),t(u,"genVerifyValue");function p(f,d,y){switch(d.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":f("if(!util.key32Re.test(%s))",y)("return%j",h(d,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":f("if(!util.key64Re.test(%s))",y)("return%j",h(d,"integer|Long key"));break;case"bool":f("if(!util.key2Re.test(%s))",y)("return%j",h(d,"boolean key"));break}return f}o(p,"a"),t(p,"genVerifyKey");function g(f){var d=l.codegen(["m"],f.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),y=f.oneofsArray,b={};y.length&&d("var p={}");for(var m=0;m<f.fieldsArray.length;++m){var _=f._fieldsArray[m].resolve(),w="m"+l.safeProp(_.name);if(_.optional&&d("if(%s!=null&&m.hasOwnProperty(%j)){",w,_.name),_.map)d("if(!util.isObject(%s))",w)("return%j",h(_,"object"))("var k=Object.keys(%s)",w)("for(var i=0;i<k.length;++i){"),p(d,_,"k[i]"),u(d,_,m,w+"[k[i]]")("}");else if(_.repeated)d("if(!Array.isArray(%s))",w)("return%j",h(_,"array"))("for(var i=0;i<%s.length;++i){",w),u(d,_,m,w+"[i]")("}");else{if(_.partOf){var S=l.safeProp(_.partOf.name);b[_.partOf.name]===1&&d("if(p%s===1)",S)("return%j",_.partOf.name+": multiple values"),b[_.partOf.name]=1,d("p%s=1",S)}u(d,_,m,w)}_.optional&&d("}")}return d("return null")}o(g,"s"),t(g,"verifier")},{15:15,37:37}],41:[function(n,i,c){var a=c,l=n(21);a[".google.protobuf.Any"]={fromObject:t(function(h){if(h&&h["@type"]){var u=this.lookup(h["@type"]);if(u){var p=h["@type"].charAt(0)==="."?h["@type"].substr(1):h["@type"];return this.create({type_url:"/"+p,value:u.encode(u.fromObject(h)).finish()})}}return this.fromObject(h)},"fromObject"),toObject:t(function(h,u){if(u&&u.json&&h.type_url&&h.value){var p=h.type_url.substring(h.type_url.lastIndexOf("/")+1),g=this.lookup(p);g&&(h=g.decode(h.value))}if(!(h instanceof this.ctor)&&h instanceof l){var f=h.$type.toObject(h,u);return f["@type"]=h.$type.fullName,f}return this.toObject(h,u)},"toObject")}},{21:21}],42:[function(n,i,c){i.exports=y;var a=n(39),l,h=a.LongBits,u=a.base64,p=a.utf8;function g(v,A,O){this.fn=v,this.len=A,this.next=s,this.val=O}o(g,"s"),t(g,"Op");function f(){}o(f,"t"),t(f,"noop");function d(v){this.head=v.head,this.tail=v.tail,this.len=v.len,this.next=v.states}o(d,"r"),t(d,"State");function y(){this.len=0,this.head=new g(f,0,0),this.tail=this.head,this.states=null}o(y,"e"),t(y,"Writer"),y.create=a.Buffer?t(function(){return(y.create=t(function(){return new l},"create_buffer"))()},"create_buffer_setup"):t(function(){return new y},"create_array"),y.alloc=t(function(v){return new a.Array(v)},"alloc"),a.Array!==Array&&(y.alloc=a.pool(y.alloc,a.Array.prototype.subarray)),y.prototype._push=t(function(v,A,O){return this.tail=this.tail.next=new g(v,A,O),this.len+=A,this},"push");function b(v,A,O){A[O]=v&255}o(b,"f"),t(b,"writeByte");function m(v,A,O){for(;v>127;)A[O++]=v&127|128,v>>>=7;A[O]=v}o(m,"n"),t(m,"writeVarint32");function _(v,A){this.len=v,this.next=s,this.val=A}o(_,"o"),t(_,"VarintOp"),_.prototype=Object.create(g.prototype),_.prototype.fn=m,y.prototype.uint32=t(function(v){return this.len+=(this.tail=this.tail.next=new _((v=v>>>0)<128?1:v<16384?2:v<2097152?3:v<268435456?4:5,v)).len,this},"write_uint32"),y.prototype.int32=t(function(v){return v<0?this._push(w,10,h.fromNumber(v)):this.uint32(v)},"write_int32"),y.prototype.sint32=t(function(v){return this.uint32((v<<1^v>>31)>>>0)},"write_sint32");function w(v,A,O){for(;v.hi;)A[O++]=v.lo&127|128,v.lo=(v.lo>>>7|v.hi<<25)>>>0,v.hi>>>=7;for(;v.lo>127;)A[O++]=v.lo&127|128,v.lo=v.lo>>>7;A[O++]=v.lo}o(w,"p"),t(w,"writeVarint64"),y.prototype.uint64=t(function(v){var A=h.from(v);return this._push(w,A.length(),A)},"write_uint64"),y.prototype.int64=y.prototype.uint64,y.prototype.sint64=t(function(v){var A=h.from(v).zzEncode();return this._push(w,A.length(),A)},"write_sint64"),y.prototype.bool=t(function(v){return this._push(b,1,v?1:0)},"write_bool");function S(v,A,O){A[O]=v&255,A[O+1]=v>>>8&255,A[O+2]=v>>>16&255,A[O+3]=v>>>24}o(S,"h"),t(S,"writeFixed32"),y.prototype.fixed32=t(function(v){return this._push(S,4,v>>>0)},"write_fixed32"),y.prototype.sfixed32=y.prototype.fixed32,y.prototype.fixed64=t(function(v){var A=h.from(v);return this._push(S,4,A.lo)._push(S,4,A.hi)},"write_fixed64"),y.prototype.sfixed64=y.prototype.fixed64,y.prototype.float=t(function(v){return this._push(a.float.writeFloatLE,4,v)},"write_float"),y.prototype.double=t(function(v){return this._push(a.float.writeDoubleLE,8,v)},"write_double");var T=a.Array.prototype.set?t(function(v,A,O){A.set(v,O)},"writeBytes_set"):t(function(v,A,O){for(var k=0;k<v.length;++k)A[O+k]=v[k]},"writeBytes_for");y.prototype.bytes=t(function(v){var A=v.length>>>0;if(!A)return this._push(b,1,0);if(a.isString(v)){var O=y.alloc(A=u.length(v));u.decode(v,O,0),v=O}return this.uint32(A)._push(T,A,v)},"write_bytes"),y.prototype.string=t(function(v){var A=p.length(v);return A?this.uint32(A)._push(p.write,A,v):this._push(b,1,0)},"write_string"),y.prototype.fork=t(function(){return this.states=new d(this),this.head=this.tail=new g(f,0,0),this.len=0,this},"fork"),y.prototype.reset=t(function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new g(f,0,0),this.len=0),this},"reset"),y.prototype.ldelim=t(function(){var v=this.head,A=this.tail,O=this.len;return this.reset().uint32(O),O&&(this.tail.next=v.next,this.tail=A,this.len+=O),this},"ldelim"),y.prototype.finish=t(function(){for(var v=this.head.next,A=this.constructor.alloc(this.len),O=0;v;)v.fn(v.val,A,O),O+=v.len,v=v.next;return A},"finish"),y._configure=function(v){l=v}},{39:39}],43:[function(n,i,c){i.exports=u;var a=n(42);(u.prototype=Object.create(a.prototype)).constructor=u;var l=n(39),h=l.Buffer;function u(){a.call(this)}o(u,"u"),t(u,"BufferWriter"),u.alloc=t(function(f){return(u.alloc=l._Buffer_allocUnsafe)(f)},"alloc_buffer");var p=h&&h.prototype instanceof Uint8Array&&h.prototype.set.name==="set"?t(function(f,d,y){d.set(f,y)},"writeBytesBuffer_set"):t(function(f,d,y){if(f.copy)f.copy(d,y,0,f.length);else for(var b=0;b<f.length;)d[y++]=f[b++]},"writeBytesBuffer_copy");u.prototype.bytes=t(function(f){l.isString(f)&&(f=l._Buffer_from(f,"base64"));var d=f.length>>>0;return this.uint32(d),d&&this._push(p,d,f),this},"write_bytes_buffer");function g(f,d,y){f.length<40?l.utf8.write(f,d,y):d.utf8Write(f,y)}o(g,"s"),t(g,"writeStringBuffer"),u.prototype.string=t(function(f){var d=h.byteLength(f);return this.uint32(d),d&&this._push(g,d,f),this},"write_string_buffer")},{39:39,42:42}]},{},[19])})()})(lo)),lo.exports}o(K_,"requireProtobuf");var G_=K_();const rs=J_(G_);var Y_=Object.defineProperty,j=o((r,e)=>Y_(r,"name",{value:e,configurable:!0}),"s$4");let re=rs.Reader,Ue=rs.Writer,De=rs.util;const $=rs.roots["push-server"]||(rs.roots["push-server"]={});$.RequestBatch=(function(){function r(e){if(this.requests=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"RequestBatch"),r.prototype.requests=De.emptyArray,r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){if(t||(t=Ue.create()),e.requests!=null&&e.requests.length)for(var s=0;s<e.requests.length;++s)$.Request.encode(e.requests[s],t.uint32(10).fork()).ldelim();return t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.RequestBatch;e.pos<s;){var i=e.uint32();i>>>3===1?(n.requests&&n.requests.length||(n.requests=[]),n.requests.push($.Request.decode(e,e.uint32()))):e.skipType(i&7)}return n},"decode"),r})(),$.Request=(function(){function r(t){if(t)for(var s=Object.keys(t),n=0;n<s.length;++n)t[s[n]]!=null&&(this[s[n]]=t[s[n]])}o(r,"t"),j(r,"Request"),r.prototype.incomingMessages=null,r.prototype.channelStats=null,r.prototype.serverStats=null;var e;return Object.defineProperty(r.prototype,"command",{get:De.oneOfGetter(e=["incomingMessages","channelStats","serverStats"]),set:De.oneOfSetter(e)}),r.create=j(function(t){return new r(t)},"create"),r.encode=j(function(t,s){return s||(s=Ue.create()),t.incomingMessages!=null&&t.hasOwnProperty("incomingMessages")&&$.IncomingMessagesRequest.encode(t.incomingMessages,s.uint32(10).fork()).ldelim(),t.channelStats!=null&&t.hasOwnProperty("channelStats")&&$.ChannelStatsRequest.encode(t.channelStats,s.uint32(18).fork()).ldelim(),t.serverStats!=null&&t.hasOwnProperty("serverStats")&&$.ServerStatsRequest.encode(t.serverStats,s.uint32(26).fork()).ldelim(),s},"encode"),r.decode=j(function(t,s){t instanceof re||(t=re.create(t));for(var n=s===void 0?t.len:t.pos+s,i=new $.Request;t.pos<n;){var c=t.uint32();switch(c>>>3){case 1:i.incomingMessages=$.IncomingMessagesRequest.decode(t,t.uint32());break;case 2:i.channelStats=$.ChannelStatsRequest.decode(t,t.uint32());break;case 3:i.serverStats=$.ServerStatsRequest.decode(t,t.uint32());break;default:t.skipType(c&7);break}}return i},"decode"),r})(),$.IncomingMessagesRequest=(function(){function r(e){if(this.messages=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"IncomingMessagesRequest"),r.prototype.messages=De.emptyArray,r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){if(t||(t=Ue.create()),e.messages!=null&&e.messages.length)for(var s=0;s<e.messages.length;++s)$.IncomingMessage.encode(e.messages[s],t.uint32(10).fork()).ldelim();return t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.IncomingMessagesRequest;e.pos<s;){var i=e.uint32();i>>>3===1?(n.messages&&n.messages.length||(n.messages=[]),n.messages.push($.IncomingMessage.decode(e,e.uint32()))):e.skipType(i&7)}return n},"decode"),r})(),$.IncomingMessage=(function(){function r(e){if(this.receivers=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"IncomingMessage"),r.prototype.receivers=De.emptyArray,r.prototype.sender=null,r.prototype.body="",r.prototype.expiry=0,r.prototype.type="",r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){if(t||(t=Ue.create()),e.receivers!=null&&e.receivers.length)for(var s=0;s<e.receivers.length;++s)$.Receiver.encode(e.receivers[s],t.uint32(10).fork()).ldelim();return e.sender!=null&&e.hasOwnProperty("sender")&&$.Sender.encode(e.sender,t.uint32(18).fork()).ldelim(),e.body!=null&&e.hasOwnProperty("body")&&t.uint32(26).string(e.body),e.expiry!=null&&e.hasOwnProperty("expiry")&&t.uint32(32).uint32(e.expiry),e.type!=null&&e.hasOwnProperty("type")&&t.uint32(42).string(e.type),t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.IncomingMessage;e.pos<s;){var i=e.uint32();switch(i>>>3){case 1:n.receivers&&n.receivers.length||(n.receivers=[]),n.receivers.push($.Receiver.decode(e,e.uint32()));break;case 2:n.sender=$.Sender.decode(e,e.uint32());break;case 3:n.body=e.string();break;case 4:n.expiry=e.uint32();break;case 5:n.type=e.string();break;default:e.skipType(i&7);break}}return n},"decode"),r})(),$.ChannelStatsRequest=(function(){function r(e){if(this.channels=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"ChannelStatsRequest"),r.prototype.channels=De.emptyArray,r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){if(t||(t=Ue.create()),e.channels!=null&&e.channels.length)for(var s=0;s<e.channels.length;++s)$.ChannelId.encode(e.channels[s],t.uint32(10).fork()).ldelim();return t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.ChannelStatsRequest;e.pos<s;){var i=e.uint32();i>>>3===1?(n.channels&&n.channels.length||(n.channels=[]),n.channels.push($.ChannelId.decode(e,e.uint32()))):e.skipType(i&7)}return n},"decode"),r})(),$.ChannelId=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"ChannelId"),r.prototype.id=De.newBuffer([]),r.prototype.isPrivate=!1,r.prototype.signature=De.newBuffer([]),r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){return t||(t=Ue.create()),e.id!=null&&e.hasOwnProperty("id")&&t.uint32(10).bytes(e.id),e.isPrivate!=null&&e.hasOwnProperty("isPrivate")&&t.uint32(16).bool(e.isPrivate),e.signature!=null&&e.hasOwnProperty("signature")&&t.uint32(26).bytes(e.signature),t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.ChannelId;e.pos<s;){var i=e.uint32();switch(i>>>3){case 1:n.id=e.bytes();break;case 2:n.isPrivate=e.bool();break;case 3:n.signature=e.bytes();break;default:e.skipType(i&7);break}}return n},"decode"),r})(),$.ServerStatsRequest=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"ServerStatsRequest"),r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){return t||(t=Ue.create()),t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.ServerStatsRequest;e.pos<s;){var i=e.uint32();switch(i>>>3){default:e.skipType(i&7);break}}return n},"decode"),r})(),$.Sender=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"Sender"),r.prototype.type=0,r.prototype.id=De.newBuffer([]),r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){return t||(t=Ue.create()),e.type!=null&&e.hasOwnProperty("type")&&t.uint32(8).int32(e.type),e.id!=null&&e.hasOwnProperty("id")&&t.uint32(18).bytes(e.id),t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.Sender;e.pos<s;){var i=e.uint32();switch(i>>>3){case 1:n.type=e.int32();break;case 2:n.id=e.bytes();break;default:e.skipType(i&7);break}}return n},"decode"),r})(),$.SenderType=(function(){var r={},e=Object.create(r);return e[r[0]="UNKNOWN"]=0,e[r[1]="CLIENT"]=1,e[r[2]="BACKEND"]=2,e})(),$.Receiver=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"Receiver"),r.prototype.id=De.newBuffer([]),r.prototype.isPrivate=!1,r.prototype.signature=De.newBuffer([]),r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){return t||(t=Ue.create()),e.id!=null&&e.hasOwnProperty("id")&&t.uint32(10).bytes(e.id),e.isPrivate!=null&&e.hasOwnProperty("isPrivate")&&t.uint32(16).bool(e.isPrivate),e.signature!=null&&e.hasOwnProperty("signature")&&t.uint32(26).bytes(e.signature),t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.Receiver;e.pos<s;){var i=e.uint32();switch(i>>>3){case 1:n.id=e.bytes();break;case 2:n.isPrivate=e.bool();break;case 3:n.signature=e.bytes();break;default:e.skipType(i&7);break}}return n},"decode"),r})(),$.ResponseBatch=(function(){function r(e){if(this.responses=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"ResponseBatch"),r.prototype.responses=De.emptyArray,r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){if(t||(t=Ue.create()),e.responses!=null&&e.responses.length)for(var s=0;s<e.responses.length;++s)$.Response.encode(e.responses[s],t.uint32(10).fork()).ldelim();return t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.ResponseBatch;e.pos<s;){var i=e.uint32();i>>>3===1?(n.responses&&n.responses.length||(n.responses=[]),n.responses.push($.Response.decode(e,e.uint32()))):e.skipType(i&7)}return n},"decode"),r})(),$.Response=(function(){function r(t){if(t)for(var s=Object.keys(t),n=0;n<s.length;++n)t[s[n]]!=null&&(this[s[n]]=t[s[n]])}o(r,"t"),j(r,"Response"),r.prototype.outgoingMessages=null,r.prototype.channelStats=null,r.prototype.serverStats=null;var e;return Object.defineProperty(r.prototype,"command",{get:De.oneOfGetter(e=["outgoingMessages","channelStats","serverStats"]),set:De.oneOfSetter(e)}),r.create=j(function(t){return new r(t)},"create"),r.encode=j(function(t,s){return s||(s=Ue.create()),t.outgoingMessages!=null&&t.hasOwnProperty("outgoingMessages")&&$.OutgoingMessagesResponse.encode(t.outgoingMessages,s.uint32(10).fork()).ldelim(),t.channelStats!=null&&t.hasOwnProperty("channelStats")&&$.ChannelStatsResponse.encode(t.channelStats,s.uint32(18).fork()).ldelim(),t.serverStats!=null&&t.hasOwnProperty("serverStats")&&$.JsonResponse.encode(t.serverStats,s.uint32(26).fork()).ldelim(),s},"encode"),r.decode=j(function(t,s){t instanceof re||(t=re.create(t));for(var n=s===void 0?t.len:t.pos+s,i=new $.Response;t.pos<n;){var c=t.uint32();switch(c>>>3){case 1:i.outgoingMessages=$.OutgoingMessagesResponse.decode(t,t.uint32());break;case 2:i.channelStats=$.ChannelStatsResponse.decode(t,t.uint32());break;case 3:i.serverStats=$.JsonResponse.decode(t,t.uint32());break;default:t.skipType(c&7);break}}return i},"decode"),r})(),$.OutgoingMessagesResponse=(function(){function r(e){if(this.messages=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"OutgoingMessagesResponse"),r.prototype.messages=De.emptyArray,r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){if(t||(t=Ue.create()),e.messages!=null&&e.messages.length)for(var s=0;s<e.messages.length;++s)$.OutgoingMessage.encode(e.messages[s],t.uint32(10).fork()).ldelim();return t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.OutgoingMessagesResponse;e.pos<s;){var i=e.uint32();i>>>3===1?(n.messages&&n.messages.length||(n.messages=[]),n.messages.push($.OutgoingMessage.decode(e,e.uint32()))):e.skipType(i&7)}return n},"decode"),r})(),$.OutgoingMessage=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"OutgoingMessage"),r.prototype.id=De.newBuffer([]),r.prototype.body="",r.prototype.expiry=0,r.prototype.created=0,r.prototype.sender=null,r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){return t||(t=Ue.create()),e.id!=null&&e.hasOwnProperty("id")&&t.uint32(10).bytes(e.id),e.body!=null&&e.hasOwnProperty("body")&&t.uint32(18).string(e.body),e.expiry!=null&&e.hasOwnProperty("expiry")&&t.uint32(24).uint32(e.expiry),e.created!=null&&e.hasOwnProperty("created")&&t.uint32(37).fixed32(e.created),e.sender!=null&&e.hasOwnProperty("sender")&&$.Sender.encode(e.sender,t.uint32(42).fork()).ldelim(),t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.OutgoingMessage;e.pos<s;){var i=e.uint32();switch(i>>>3){case 1:n.id=e.bytes();break;case 2:n.body=e.string();break;case 3:n.expiry=e.uint32();break;case 4:n.created=e.fixed32();break;case 5:n.sender=$.Sender.decode(e,e.uint32());break;default:e.skipType(i&7);break}}return n},"decode"),r})(),$.ChannelStatsResponse=(function(){function r(e){if(this.channels=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"ChannelStatsResponse"),r.prototype.channels=De.emptyArray,r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){if(t||(t=Ue.create()),e.channels!=null&&e.channels.length)for(var s=0;s<e.channels.length;++s)$.ChannelStats.encode(e.channels[s],t.uint32(10).fork()).ldelim();return t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.ChannelStatsResponse;e.pos<s;){var i=e.uint32();i>>>3===1?(n.channels&&n.channels.length||(n.channels=[]),n.channels.push($.ChannelStats.decode(e,e.uint32()))):e.skipType(i&7)}return n},"decode"),r})(),$.ChannelStats=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"ChannelStats"),r.prototype.id=De.newBuffer([]),r.prototype.isPrivate=!1,r.prototype.isOnline=!1,r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){return t||(t=Ue.create()),e.id!=null&&e.hasOwnProperty("id")&&t.uint32(10).bytes(e.id),e.isPrivate!=null&&e.hasOwnProperty("isPrivate")&&t.uint32(16).bool(e.isPrivate),e.isOnline!=null&&e.hasOwnProperty("isOnline")&&t.uint32(24).bool(e.isOnline),t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.ChannelStats;e.pos<s;){var i=e.uint32();switch(i>>>3){case 1:n.id=e.bytes();break;case 2:n.isPrivate=e.bool();break;case 3:n.isOnline=e.bool();break;default:e.skipType(i&7);break}}return n},"decode"),r})(),$.JsonResponse=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return o(r,"t"),j(r,"JsonResponse"),r.prototype.json="",r.create=j(function(e){return new r(e)},"create"),r.encode=j(function(e,t){return t||(t=Ue.create()),e.json!=null&&e.hasOwnProperty("json")&&t.uint32(10).string(e.json),t},"encode"),r.decode=j(function(e,t){e instanceof re||(e=re.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new $.JsonResponse;e.pos<s;){var i=e.uint32();i>>>3===1?n.json=e.string():e.skipType(i&7)}return n},"decode"),r})();const Z_=$.ResponseBatch,Su=$.RequestBatch;$.IncomingMessage,$.Receiver;var X_=Object.defineProperty,nn=o((r,e)=>X_(r,"name",{value:e,configurable:!0}),"s$3");class Mt extends Error{static{o(this,"WireError")}static{nn(this,"WireError")}name="WireError"}const Sr=0,Te=2,vu=5,Q_=3,ew=4,tw=64;function Je(r,e){return r<<3|e}o(Je,"tag"),nn(Je,"tag");class vr{static{o(this,"Writer")}static{nn(this,"Writer")}#e=new Uint8Array(64);#t=0;get length(){return this.#t}#s(e){const t=this.#t+e;if(t<=this.#e.length)return;let s=this.#e.length*2;for(;s<t;)s*=2;const n=new Uint8Array(s);n.set(this.#e.subarray(0,this.#t)),this.#e=n}#r(e){this.#s(1),this.#e[this.#t++]=e}varint(e){let t=e>>>0;for(;t>127;)this.#r(t&127|128),t>>>=7;return this.#r(t),this}fixed32(e){const t=e>>>0;return this.#s(4),this.#e[this.#t++]=t&255,this.#e[this.#t++]=t>>>8&255,this.#e[this.#t++]=t>>>16&255,this.#e[this.#t++]=t>>>24&255,this}bytes(e){return this.varint(e.length),this.#s(e.length),this.#e.set(e,this.#t),this.#t+=e.length,this}string(e){return this.bytes(new TextEncoder().encode(e))}finish(){return this.#e.slice(0,this.#t)}}class rw{static{o(this,"Reader")}static{nn(this,"Reader")}#e;#t=0;constructor(e){this.#e=e}get done(){return this.#t>=this.#e.length}varint(){let e=0,t=0;for(;;){if(this.done)throw new Mt("pull protobuf: truncated varint");const s=this.#e[this.#t++];if(e+=(s&127)*2**t,(s&128)===0)return e;if(t+=7,t>=70)throw new Mt("pull protobuf: varint longer than ten bytes")}}uint32(){return this.varint()>>>0}fixed32(){if(this.#t+4>this.#e.length)throw new Mt("pull protobuf: truncated fixed32");const e=this.#e[this.#t]|this.#e[this.#t+1]<<8|this.#e[this.#t+2]<<16|this.#e[this.#t+3]<<24;return this.#t+=4,e>>>0}bytes(){const e=this.varint();if(this.#t+e>this.#e.length)throw new Mt("pull protobuf: length-delimited field runs past the end");const t=this.#e.subarray(this.#t,this.#t+e);return this.#t+=e,t}string(){return new TextDecoder().decode(this.bytes())}skip(e,t=0){switch(e){case Sr:{this.varint();break}case Te:{this.bytes();break}case vu:{this.fixed32();break}case 1:{if(this.#t+8>this.#e.length)throw new Mt("pull protobuf: truncated 64-bit field");this.#t+=8;break}case Q_:{this.#s(t);break}default:throw new Mt(`pull protobuf: unsupported wire type ${e}`)}}#s(e){if(e>=tw)throw new Mt("pull protobuf: groups nested too deeply");for(;;){const t=this.varint()&7;if(t===ew)return;this.skip(t,e+1)}}}var sw=Object.defineProperty,dt=o((r,e)=>sw(r,"name",{value:e,configurable:!0}),"g");function mt(r,e){return Object.hasOwn(r,e)&&r[e]!==null&&r[e]!==void 0}o(mt,"d"),dt(mt,"has");function Eu(r){const e=new vr;return mt(r,"id")&&e.varint(Je(1,Te)).bytes(r.id),mt(r,"isPrivate")&&e.varint(Je(2,Sr)).varint(r.isPrivate?1:0),mt(r,"signature")&&e.varint(Je(3,Te)).bytes(r.signature),e.finish()}o(Eu,"v"),dt(Eu,"writeReceiver");function Ou(r){const e=new vr;return mt(r,"type")&&e.varint(Je(1,Sr)).varint(r.type),mt(r,"id")&&e.varint(Je(2,Te)).bytes(r.id),e.finish()}o(Ou,"L$1"),dt(Ou,"writeSender");function Tu(r){const e=new vr;for(const t of r.receivers??[])e.varint(Je(1,Te)).bytes(Eu(t));return mt(r,"sender")&&e.varint(Je(2,Te)).bytes(Ou(r.sender)),mt(r,"body")&&e.varint(Je(3,Te)).string(r.body),mt(r,"expiry")&&e.varint(Je(4,Sr)).varint(r.expiry),mt(r,"type")&&e.varint(Je(5,Te)).string(r.type),e.finish()}o(Tu,"l$4"),dt(Tu,"writeIncomingMessage");function Au(r){const e=new vr;for(const n of r)e.varint(Je(1,Te)).bytes(Tu(n));const t=new vr;t.varint(Je(1,Te)).bytes(e.finish());const s=new vr;return s.varint(Je(1,Te)).bytes(t.finish()),s.finish()}o(Au,"encodeRequestBatch"),dt(Au,"encodeRequestBatch");function Er(r,e,t){const s=new rw(r);for(;!s.done;)try{const n=s.varint();t(n>>>3,n&7,s)}catch(n){if(!(n instanceof Mt))throw n;e.damaged=!0;return}}o(Er,"f"),dt(Er,"readFields");function ku(r,e){const t={type:0,id:new Uint8Array(0)};return Er(r,e,(s,n,i)=>{s===1&&n===Sr?t.type=i.uint32():s===2&&n===Te?t.id=i.bytes():i.skip(n)}),t}o(ku,"R$1"),dt(ku,"readSender");function Iu(r,e){const t={id:new Uint8Array(0),body:"",expiry:0,created:0};return Er(r,e,(s,n,i)=>{s===1&&n===Te?t.id=i.bytes():s===2&&n===Te?t.body=i.string():s===3&&n===Sr?t.expiry=i.uint32():s===4&&n===vu?t.created=i.fixed32():s===5&&n===Te?t.sender=ku(i.bytes(),e):i.skip(n)}),t}o(Iu,"h$1"),dt(Iu,"readOutgoingMessage");function Ru(r,e){const t=[];return Er(r,e,(s,n,i)=>{s===1&&n===Te?t.push(Iu(i.bytes(),e)):i.skip(n)}),{messages:t}}o(Ru,"x"),dt(Ru,"readOutgoingMessagesResponse");function Cu(r,e){const t={};return Er(r,e,(s,n,i)=>{s===1&&n===Te?(t.outgoingMessages=Ru(i.bytes(),e),t.command="outgoingMessages"):s===2&&n===Te?(i.bytes(),t.command="channelStats"):s===3&&n===Te?(i.bytes(),t.command="serverStats"):i.skip(n)}),t}o(Cu,"A"),dt(Cu,"readResponse");function Nu(r){const e={damaged:!1},t=[];return Er(r,e,(s,n,i)=>{s===1&&n===Te?t.push(Cu(i.bytes(),e)):i.skip(n)}),{responses:t,damaged:e.damaged}}o(Nu,"decodeResponseBatch"),dt(Nu,"decodeResponseBatch");var nw=Object.defineProperty,iw=o((r,e)=>nw(r,"name",{value:e,configurable:!0}),"o");class Du{static{o(this,"AbstractConnector")}static{iw(this,"AbstractConnector")}_logger;_connected=!1;_connectionType;_disconnectCode=0;_disconnectReason="";_parent;_callbacks;constructor(e){this._logger=ae.createNullLogger(),this._parent=e.parent,this._connectionType=pe.Undefined,this._callbacks={onOpen:F.isFunction(e.onOpen)?e.onOpen:()=>{},onDisconnect:F.isFunction(e.onDisconnect)?e.onDisconnect:()=>{},onError:F.isFunction(e.onError)?e.onError:()=>{},onMessage:F.isFunction(e.onMessage)?e.onMessage:()=>{}}}setLogger(e){this._logger=e}getLogger(){return this._logger}destroy(){}get connected(){return this._connected}set connected(e){e!=this._connected&&(this._connected=e,this._connected?this._callbacks.onOpen():this._callbacks.onDisconnect({code:this.disconnectCode,reason:this.disconnectReason}))}get disconnectCode(){return this._disconnectCode}get disconnectReason(){return this._disconnectReason}get connectionPath(){return this._parent.getConnectionPath(this._connectionType)}}var ow=Object.defineProperty,aw=o((r,e)=>ow(r,"name",{value:e,configurable:!0}),"s$2");class cw extends Du{static{o(this,"WebSocketConnector")}static{aw(this,"WebSocketConnector")}_socket;_onSocketOpenHandler;_onSocketCloseHandler;_onSocketErrorHandler;_onSocketMessageHandler;constructor(e){super(e),this._connectionType=pe.WebSocket,this._socket=null,this._onSocketOpenHandler=this._onSocketOpen.bind(this),this._onSocketCloseHandler=this._onSocketClose.bind(this),this._onSocketErrorHandler=this._onSocketError.bind(this),this._onSocketMessageHandler=this._onSocketMessage.bind(this)}destroy(){super.destroy(),this._socket&&(this._socket.close(),this._socket=null)}connect(){if(this._socket){if(this._socket.readyState===1)return;this.clearEventListener(),this._socket.close(),this._socket=null}this._createSocket()}get socket(){return this._socket}disconnect(e,t){this._socket!==null&&(this.clearEventListener(),this._socket.close(e,t)),this._socket=null,this._disconnectCode=e,this._disconnectReason=t,this.connected=!1}send(e){return!this._socket||this._socket.readyState!==1?(this.getLogger().error(`${W.getDateForLog()}: Pull: WebSocket is not connected`).catch(()=>{}),!1):(this._socket.send(e),!0)}_onSocketOpen(){this.connected=!0}_onSocketClose(e){this._socket=null,this._disconnectCode=Number(e.code),this._disconnectReason=e.reason,this.connected=!1}_onSocketError(e){this._callbacks.onError(new Error(`Socket error: ${e}`))}_onSocketMessage(e){this._callbacks.onMessage(e.data)}clearEventListener(){this._socket&&(this._socket.removeEventListener("open",this._onSocketOpenHandler),this._socket.removeEventListener("close",this._onSocketCloseHandler),this._socket.removeEventListener("error",this._onSocketErrorHandler),this._socket.removeEventListener("message",this._onSocketMessageHandler))}_createSocket(){if(this._socket)throw new Error("Socket already exists");if(!this.connectionPath)throw new Error("Websocket connection path is not defined");this._socket=new WebSocket(this.connectionPath),this._socket.binaryType="arraybuffer",this._socket.addEventListener("open",this._onSocketOpenHandler),this._socket.addEventListener("close",this._onSocketCloseHandler),this._socket.addEventListener("error",this._onSocketErrorHandler),this._socket.addEventListener("message",this._onSocketMessageHandler)}}var lw=Object.defineProperty,uw=o((r,e)=>lw(r,"name",{value:e,configurable:!0}),"s$1");const hw=60;class dw extends Du{static{o(this,"LongPollingConnector")}static{uw(this,"LongPollingConnector")}_active;_requestTimeout;_failureTimeout;_xhr;_requestAborted;constructor(e){super(e),this._active=!1,this._connectionType=pe.LongPolling,this._requestTimeout=null,this._failureTimeout=null,this._xhr=null,this._requestAborted=!1}connect(){if(!this._xhr){if(typeof XMLHttpRequest>"u"){this._callbacks.onError(new Error("LongPollingConnector: XMLHttpRequest is not available in this environment (SSR/Node); a long-polling connection requires a browser"));return}this._xhr=this.createXhr()}this._active=!0,this.performRequest()}disconnect(e,t){this._active=!1,this.clearTimeOut(),this._xhr&&(this._requestAborted=!0,this._xhr.abort()),this._disconnectCode=e,this._disconnectReason=t,this.connected=!1}performRequest(){if(!this._active)return;if(!this.connectionPath)throw new Error("Long polling connection path is not defined");const e=this._xhr;e&&(e.readyState!==0&&e.readyState!==4||(this.clearTimeOut(),this._failureTimeout=setTimeout(()=>{this.connected=!0},5e3),this._requestTimeout=setTimeout(this.onRequestTimeout.bind(this),hw*1e3),e.open("GET",this.connectionPath),e.send()))}onRequestTimeout(){this._requestAborted=!0,this._xhr?.abort(),this.performRequest()}onXhrReadyStateChange(){const e=this._xhr;e&&e.readyState===4&&((!this._requestAborted||e.status==200)&&this.onResponse(e.response),this._requestAborted=!1)}send(e){const t=this._parent.getPublicationPath();if(!t)return this.getLogger().error(`${W.getDateForLog()}: Pull: publication path is empty`).catch(()=>{}),!1;if(typeof XMLHttpRequest>"u")return this.getLogger().error(`${W.getDateForLog()}: Pull: XMLHttpRequest is not available; cannot publish`).catch(()=>{}),!1;const s=new XMLHttpRequest;return s.open("POST",t),s.send(e),!0}onResponse(e){this.clearTimeOut();const t=this._xhr;if(t)if(t.status===200)this.connected=!0,F.isStringFilled(e)||e instanceof ArrayBuffer?this._callbacks.onMessage(e):this._parent.session.mid=null,this.performRequest();else if(t.status===304){if(this.connected=!0,t.getResponseHeader("Expires")==="Thu, 01 Jan 1973 11:11:01 GMT"){const s=t.getResponseHeader("Last-Message-Id");F.isStringFilled(s)&&this._parent.setLastMessageId(s||"")}this.performRequest()}else this._callbacks.onError(new Error("Could not connect to the server")),this.connected=!1}clearTimeOut(){this._failureTimeout&&(clearTimeout(this._failureTimeout),this._failureTimeout=null),this._requestTimeout&&(clearTimeout(this._requestTimeout),this._requestTimeout=null)}createXhr(){const e=new XMLHttpRequest;return this._parent.isProtobufSupported()&&!this._parent.isJsonRpc()&&(e.responseType="arraybuffer"),e.addEventListener("readystatechange",this.onXhrReadyStateChange.bind(this)),e}}var fw=Object.defineProperty,Lu=o((r,e)=>fw(r,"name",{value:e,configurable:!0}),"S");const ss=19,Pu=1800,pw=5e3,gw=60*1e3,Mu=10,Fu=10,mw="ping",yw="pong",xu="bx-pull-session",bw=20,$u={api:{},channels:{},publicChannels:{},server:{timeShift:0},clientId:null,jwt:null,exp:0};class ju{static{o(this,"PullClient")}static{Lu(this,"PullClient")}_logger;_restClient;_status;_context;_guestMode;_guestUserId;_userId;_configGetMethod;_getPublicListMethod;_siteId;_enabled;_unloading=!1;_starting=!1;_debug=!1;_connectionAttempt=0;_connectionType=pe.WebSocket;_skipStorageInit;_skipCheckRevision;_subscribers={};_watchTagsQueue=new Map;_watchUpdateInterval=174e4;_watchForceUpdateInterval=5e3;_configTimestamp=0;_session={mid:null,tag:null,time:null,history:{},lastMessageIds:[],messageCount:0};_connectors={[pe.Undefined]:null,[pe.WebSocket]:null,[pe.LongPolling]:null};_isSecure;_config=null;_storage=null;_sharedConfig;_channelManager;_jsonRpcAdapter=null;_useLiteProtobuf=!1;_reconnectTimeout=null;_restartTimeout=null;_restoreWebSocketTimeout=null;_checkInterval=null;_offlineTimeout=null;_watchUpdateTimeout=null;_pingWaitTimeout=null;_timerFields=["_reconnectTimeout","_restartTimeout","_restoreWebSocketTimeout","_checkInterval","_offlineTimeout","_watchUpdateTimeout","_pingWaitTimeout"];_windowListeners=[];_isManualDisconnect=!1;_disposed=!1;_loggingEnabled=!1;_onPingTimeoutHandler;_onBeforeUnloadHandler;_onOfflineHandler;_onOnlineHandler;_userStatusCallbacks={};_connectPromise=null;_startingPromise=null;_startGeneration=0;constructor(e){this._logger=ae.createNullLogger(),this._restClient=e.b24,this._status=Ze.Offline,this._context="master",this._useLiteProtobuf=e.protobufCodec==="lite",e.restApplication&&(typeof e.configGetMethod>"u"&&(e.configGetMethod="pull.application.config.get"),typeof e.skipCheckRevision>"u"&&(e.skipCheckRevision=!0),F.isStringFilled(e.restApplication)&&(e.siteId=e.restApplication),e.serverEnabled=!0),this._guestMode=e.guestMode?W.toBoolean(e.guestMode):!1,this._guestUserId=e.guestUserId?W.toInteger(e.guestUserId):0,this._guestMode&&this._guestUserId>0?this._userId=this._guestUserId:(this._guestMode=!1,this._userId=e.userId?W.toInteger(e.userId):0),this._siteId=e.siteId??"none",this._enabled=F.isUndefined(e.serverEnabled)?!0:e.serverEnabled===!0,this._configGetMethod=F.isStringFilled(e.configGetMethod)?e.configGetMethod||"":"pull.config.get",this._getPublicListMethod=F.isStringFilled(e.getPublicListMethod)?e.getPublicListMethod||"":"pull.channel.public.list",this._skipStorageInit=e.skipStorageInit===!0,this._skipCheckRevision=e.skipCheckRevision===!0,F.isUndefined(e.configTimestamp)||(this._configTimestamp=W.toInteger(e.configTimestamp)),this._isSecure=typeof document<"u"&&document?.location.href.indexOf("https")===0,this._userId&&!this._skipStorageInit&&(this._storage=new yu({userId:this._userId,siteId:this._siteId})),this._sharedConfig=new q_({onWebSocketBlockChanged:this.onWebSocketBlockChanged.bind(this),storage:this._storage}),this._channelManager=new z_({b24:this._restClient,getPublicListMethod:this._getPublicListMethod}),this._loggingEnabled=this._sharedConfig.isLoggingEnabled(),this._onPingTimeoutHandler=this.onPingTimeout.bind(this),this._onBeforeUnloadHandler=this.onBeforeUnload.bind(this),this._onOfflineHandler=this.onOffline.bind(this),this._onOnlineHandler=this.onOnline.bind(this)}setLogger(e){this._logger=e,this._jsonRpcAdapter?.setLogger(this.getLogger()),this._storage?.setLogger(this.getLogger()),this._sharedConfig.setLogger(this.getLogger()),this._channelManager.setLogger(this.getLogger()),this._connectors.webSocket?.setLogger(this.getLogger()),this._connectors.longPolling?.setLogger(this.getLogger())}getLogger(){return this._logger}destroy(){this._disposed=!0,this._startGeneration++,this.stop($e.NORMAL_CLOSURE,"manual stop"),this.removeAllWindowListeners(),this._storage&&this._storage.remove(We.PullConfig),this.persistSession()}init(){this._disposed||(this._connectors.webSocket=new cw({parent:this,onOpen:this.onWebSocketOpen.bind(this),onMessage:this.onIncomingMessage.bind(this),onDisconnect:this.onWebSocketDisconnect.bind(this),onError:this.onWebSocketError.bind(this)}),this._connectors.longPolling=new dw({parent:this,onOpen:this.onLongPollingOpen.bind(this),onMessage:this.onIncomingMessage.bind(this),onDisconnect:this.onLongPollingDisconnect.bind(this),onError:this.onLongPollingError.bind(this)}),this._connectionType=this.isWebSocketAllowed()?pe.WebSocket:pe.LongPolling,this.addWindowListener("beforeunload",this._onBeforeUnloadHandler),this.addWindowListener("offline",this._onOfflineHandler),this.addWindowListener("online",this._onOnlineHandler),this._jsonRpcAdapter=new B_({connector:this._connectors.webSocket,handlers:{"incoming.message":this.handleRpcIncomingMessage.bind(this)}}))}get connector(){return this._connectors[this._connectionType]}get status(){return this._status}set status(e){this._status!==e&&(this._status=e,this._offlineTimeout&&(clearTimeout(this._offlineTimeout),this._offlineTimeout=null),e===Ze.Offline?this.sendPullStatusDelayed(e,pw):this.sendPullStatus(e))}get session(){return this._session}subscribe(e){if(!F.isPlainObject(e))return this.attachCommandHandler(e);if(e=e,e.type=e.type||Xe.Server,e.command=e.command||null,e.type==Xe.Server||e.type==Xe.Client){if(typeof e.moduleId>"u")throw new TypeError(`${W.getDateForLog()}: Pull.subscribe: parameter moduleId is not specified`);return typeof this._subscribers[e.type]>"u"&&(this._subscribers[e.type]={}),typeof this._subscribers[e.type][e.moduleId]>"u"&&(this._subscribers[e.type][e.moduleId]={callbacks:[],commands:{}}),e.command?(typeof this._subscribers[e.type][e.moduleId].commands[e.command]>"u"&&(this._subscribers[e.type][e.moduleId].commands[e.command]=[]),this._subscribers[e.type][e.moduleId].commands[e.command].push(e.callback),()=>{typeof e.type>"u"||typeof e.moduleId>"u"||typeof e.command>"u"||e.command===null||(this._subscribers[e.type][e.moduleId].commands[e.command]=this._subscribers[e.type][e.moduleId].commands[e.command].filter(t=>t!==e.callback))}):(this._subscribers[e.type][e.moduleId].callbacks.push(e.callback),()=>{typeof e.type>"u"||typeof e.moduleId>"u"||(this._subscribers[e.type][e.moduleId].callbacks=this._subscribers[e.type][e.moduleId].callbacks.filter(t=>t!==e.callback))})}else return typeof this._subscribers[e.type]>"u"&&(this._subscribers[e.type]=[]),this._subscribers[e.type].push(e.callback),()=>{typeof e.type>"u"||(this._subscribers[e.type]=this._subscribers[e.type].filter(t=>t!==e.callback))}}attachCommandHandler(e){if(typeof e.getModuleId!="function"||typeof e.getModuleId()!="string")return this.getLogger().error(`${W.getDateForLog()}: Pull.attachCommandHandler: result of handler.getModuleId() is not a string.`).catch(()=>{}),()=>{};let t=Xe.Server;return typeof e.getSubscriptionType=="function"&&(t=e.getSubscriptionType()),this.subscribe({type:t,moduleId:e.getModuleId(),callback:Lu(s=>{let n=null;if(typeof e.getMap=="function"){const i=e.getMap();if(i&&typeof i=="object"){const c=i[s.command];typeof c=="function"?n=c.bind(e):typeof c=="string"&&typeof e[c]=="function"&&(n=e[c].bind(e))}}if(!n){const i=`handle${W.capitalize(s.command)}`;typeof e[i]=="function"&&(n=e[i].bind(e))}n&&(this._debug&&this._context!=="master"&&this.getLogger().warning(`${W.getDateForLog()}: Pull.attachCommandHandler: result of handler.getModuleId() is not a string`,qe({data:s})).catch(()=>{}),n(s.params,s.extra,s.command))},"callback")})}async start(e=null){if(this._disposed)return Promise.reject({ex:{error:"PULL_DISPOSED",error_description:"PullClient has been destroyed; create a new instance"}});let t=!0;if(this.isConnected())return Promise.resolve(!0);if(this._starting&&this._startingPromise)return this._startingPromise;if(!this._userId)throw new Error("Not set userId");if(this._siteId==="none")throw new Error("Not set siteId");let s=!1;if(e&&F.isPlainObject(e)&&(typeof e?.skipReconnectToLastSession<"u"&&(s=e.skipReconnectToLastSession,delete e.skipReconnectToLastSession),this._config=e,t=!1),!this._enabled)return Promise.reject({ex:{error:"PULL_DISABLED",error_description:"Push & Pull server is disabled"}});const n=Date.now();let i;!s&&this._storage&&(i=this._storage.get(xu,null)),F.isPlainObject(i)&&Object.prototype.hasOwnProperty.call(i,"ttl")&&i.ttl>=n&&(this._session.mid=i.mid),this._starting=!0;const c=++this._startGeneration;return this._startingPromise=new Promise((a,l)=>{this.loadConfig("client_start").then(h=>{if(this._disposed||this._startGeneration!==c){this._starting=!1,l({ex:{error:"PULL_DISPOSED",error_description:"PullClient has been destroyed; create a new instance"}});return}this.setConfig(h,t),this.init(),this.updateWatch(!0),this.startCheckConfig(),this.connect().then(()=>a(!0),u=>l(u))}).catch(h=>{this._starting=!1,this.status=Ze.Offline,this.stopCheckConfig(),this.getLogger().error(`${W.getDateForLog()}: Pull: could not read push-server config`,{error:h}).catch(()=>{}),l(h)})})}restart(e=$e.NORMAL_CLOSURE,t="manual restart"){if(this._disposed)return;this._restartTimeout&&(clearTimeout(this._restartTimeout),this._restartTimeout=null),this.getLogger().debug(`${W.getDateForLog()}: Pull: restarting with code ${e}`).catch(()=>{}),this.disconnect(e,t),this._storage&&this._storage.remove(We.PullConfig),this._config=null;const s=`${e}_${t.replaceAll(" ","_")}`;this.loadConfig(s).then(n=>{this.setConfig(n,!0),this.updateWatch(),this.startCheckConfig(),this.connect().catch(i=>{this.getLogger().error("restart error",{error:i}).catch(()=>{})})},n=>{this.getLogger().error(`${W.getDateForLog()}: Pull: could not read push-server config `,{error:n}).catch(()=>{}),this.status=Ze.Offline,this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null),(n?.status==401||n?.status==403)&&(this.stopCheckConfig(),this.onCustomEvent("onPullError",["AUTHORIZE_ERROR"]))})}stop(e=$e.NORMAL_CLOSURE,t="manual stop"){this.disconnect(e,t),this.stopCheckConfig(),this.clearAllTimers()}clearAllTimers(){for(const e of this._timerFields){const t=this[e];t&&(e==="_checkInterval"?clearInterval(t):clearTimeout(t)),this[e]=null}}armTimeout(e,t,s){const n=this[e];n&&clearTimeout(n),this[e]=setTimeout(t,s)}addWindowListener(e,t){typeof window>"u"||(window.addEventListener(e,t),this._windowListeners.push({type:e,handler:t}))}removeAllWindowListeners(){if(typeof window<"u")for(const{type:e,handler:t}of this._windowListeners)window.removeEventListener(e,t);this._windowListeners=[]}reconnect(e,t,s=1){this.disconnect(e,t),this.scheduleReconnect(s)}setLastMessageId(e){this._session.mid=e}async sendMessage(e,t,s,n,i){const c={userList:e,body:{module_id:t,command:s,params:n},expiry:i};return this.isJsonRpc()?this.requireJsonRpcAdapter().executeOutgoingRpcCommand(pt.Publish,c):this.sendMessageBatch([c])}async sendMessageToChannels(e,t,s,n,i){const c={channelList:e,body:{module_id:t,command:s,params:n},expiry:i};return this.isJsonRpc()?this.requireJsonRpcAdapter().executeOutgoingRpcCommand(pt.Publish,c):this.sendMessageBatch([c])}capturePullEvent(e=!0){this._debug=e}enableLogging(e=!0){this._sharedConfig.setLoggingEnabled(e),this._loggingEnabled=e}async listChannels(){return this._jsonRpcAdapter?.executeOutgoingRpcCommand(pt.ListChannels,{})||Promise.reject(new Error("jsonRpcAdapter not init"))}async getUsersLastSeen(e){if(!F.isArray(e)||!e.every(s=>typeof s=="number"))throw new Error("userList must be an array of numbers");const t={};return new Promise((s,n)=>{this._jsonRpcAdapter?.executeOutgoingRpcCommand(pt.GetUsersLastSeen,{userList:e}).then(i=>{const c=[];for(let l=0;l<e.length;l++)Object.prototype.hasOwnProperty.call(i,e[l])||c.push(e[l]);if(c.length===0)return s(t);const a={userIds:c,sendToQueueSever:!0};this._restClient.actions.v2.call.make({method:"pull.api.user.getLastSeen",params:a}).then(l=>{const h=l.getData().result;for(const u in h)t[Number(u)]=Number(h[u]);return s(t)}).catch(l=>{this.getLogger().error("getUsersLastSeen",{error:l}).catch(()=>{}),n(l)})}).catch(i=>{this.getLogger().error("getUsersLastSeen",{error:i}).catch(()=>{}),n(i)})})}async ping(e=5){return this._jsonRpcAdapter?.executeOutgoingRpcCommand(pt.Ping,{},e)}async subscribeUserStatusChange(e,t){return new Promise((s,n)=>{this._jsonRpcAdapter?.executeOutgoingRpcCommand(pt.SubscribeStatusChange,{userId:e}).then(()=>(this._userStatusCallbacks[e]||(this._userStatusCallbacks[e]=[]),F.isFunction(t)&&this._userStatusCallbacks[e].push(t),s())).catch(i=>n(i))})}async unsubscribeUserStatusChange(e,t){return this._userStatusCallbacks[e]&&(this._userStatusCallbacks[e]=this._userStatusCallbacks[e].filter(s=>s!==t),this._userStatusCallbacks[e].length===0)?this._jsonRpcAdapter?.executeOutgoingRpcCommand(pt.UnsubscribeStatusChange,{userId:e}):Promise.resolve()}getRevision(){return this._config&&this._config.api?this._config.api.revision_web:null}getServerVersion(){return this._config&&this._config.server?this._config.server.version:0}getServerMode(){return this._config&&this._config.server?this._config.server.mode:null}getConfig(){return this._config}getDebugInfo(){if(!JSON||!JSON.stringify)return{};let e;this._config&&this._config.channels?e={ChannelID:this._config.channels.private?.id?$r:"n/a",ChannelDie:this._config.channels.private?.end||"n/a",ChannelDieShared:this._config.channels.shared?.end||"n/a"}:e={ConfigError:"config is not loaded"};let t="-";this._connectors.webSocket&&this._connectors.webSocket?.socket&&(this.isJsonRpc()?t="json-rpc":t=this._connectors.webSocket?.socket?.url.search("binaryMode=true")!=-1?"protobuf":"text");const s=this.connector?.connectionPath;return{UserId:this._userId+(this._userId>0?"":"(guest)"),"Guest userId":this._guestMode&&this._guestUserId!==0?this._guestUserId:"-","Browser online":typeof navigator<"u"&&navigator.onLine?"Y":"N",Connect:this.isConnected()?"Y":"N","Server type":this.isSharedMode()?"cloud":"local","WebSocket supported":this.isWebSocketSupported()?"Y":"N","WebSocket connected":this._connectors.webSocket&&this._connectors.webSocket.connected?"Y":"N","WebSocket mode":t,"Try connect":this._reconnectTimeout?"Y":"N","Try number":this._connectionAttempt,Path:s?wc(s,["CHANNEL_ID"]):"-",...e,"Last message":this._session.mid||"-","Session history":this._session.history,"Watch tags":this._watchTagsQueue.entries()}}getConnectionPath(e){let t;const s={};switch(e){case pe.WebSocket:t=this._isSecure?this._config?.server.websocket_secure:this._config?.server.websocket;break;case pe.LongPolling:t=this._isSecure?this._config?.server.long_pooling_secure:this._config?.server.long_polling;break;default:throw new Error(`Unknown connection type ${e}`)}if(!F.isStringFilled(t))throw new Error("Empty path");if(typeof this._config?.jwt=="string"&&this._config?.jwt!=="")s.token=this._config?.jwt;else{const n=[];if(this._config?.channels?.private?.id&&n.push(this._config.channels.private.id),this._config?.channels?.shared?.id&&n.push(this._config.channels.shared.id),n.length===0)throw new Error("Empty channels");s.CHANNEL_ID=n.join("/")}if(this.isJsonRpc()?s.jsonRpc="true":this.isProtobufSupported()&&(s.binaryMode="true"),this.isSharedMode()){if(!this._config?.clientId)throw new Error("Push-server is in shared mode, but clientId is not set");s.clientId=this._config.clientId}return this._session.mid&&(s.mid=this._session.mid),this._session.tag&&(s.tag=this._session.tag),this._session.time&&(s.time=this._session.time),s.revision=ss,`${t}?${W.buildQueryString(s)}`}getPublicationPath(){const e=this._isSecure?this._config?.server.publish_secure:this._config?.server.publish;if(!e)return"";const t=[];this._config?.channels.private?.id&&t.push(this._config.channels.private.id),this._config?.channels.shared?.id&&t.push(this._config.channels.shared.id);const s={CHANNEL_ID:t.join("/")};return e+"?"+W.buildQueryString(s)}isConnected(){return this.connector?this.connector.connected:!1}isWebSocketSupported(){return typeof window<"u"&&typeof window.WebSocket<"u"}isWebSocketAllowed(){return this._sharedConfig.isWebSocketBlocked()?!1:this.isWebSocketEnabled()}isWebSocketEnabled(){return!this.isWebSocketSupported()||!this._config||!this._config.server?!1:this._config.server.websocket_enabled}isPublishingSupported(){return this.getServerVersion()>3}isPublishingEnabled(){return this.isPublishingSupported()?this._config?.server.publish_enabled===!0:!1}isProtobufSupported(){return this.getServerVersion()==4&&!sc.isIE()}isJsonRpc(){return this.getServerVersion()>=5}isSharedMode(){return this.getServerMode()===Hn.Shared}emit(e){if(e.type==Xe.Server||e.type==Xe.Client){if(typeof this._subscribers[e.type]>"u"&&(this._subscribers[e.type]={}),typeof e.moduleId>"u")throw new TypeError(`${W.getDateForLog()}: Pull.emit: parameter moduleId is not specified`);return typeof this._subscribers[e.type][e.moduleId]>"u"&&(this._subscribers[e.type][e.moduleId]={callbacks:[],commands:{}}),this._subscribers[e.type][e.moduleId].callbacks.length>0&&this._subscribers[e.type][e.moduleId].callbacks.forEach(t=>{t(e.data,{type:e.type,moduleId:e.moduleId??"?"})}),!(typeof e.data>"u")&&!(typeof e.data.command>"u")&&this._subscribers[e.type][e.moduleId].commands[e.data.command]&&this._subscribers[e.type][e.moduleId].commands[e.data.command].length>0&&this._subscribers[e.type][e.moduleId].commands[e.data.command].forEach(t=>{typeof e.data>"u"||t(e.data.params,e.data.extra,e.data.command,{type:e.type,moduleId:e.moduleId})}),!0}else return typeof this._subscribers[e.type]>"u"&&(this._subscribers[e.type]=[]),this._subscribers[e.type].length<=0||this._subscribers[e.type].forEach(t=>{t(e.data,{type:e.type})}),!0}broadcastMessage(e){const t=e.module_id=e.module_id.toLowerCase(),s=e.command;e.extra||(e.extra={}),e.extra.server_time_unix&&(e.extra.server_time_ago=(Date.now()-e.extra.server_time_unix*1e3)/1e3-(this._config?.server.timeShift||0),e.extra.server_time_ago=Math.max(e.extra.server_time_ago,0)),this.logMessage(e);try{e.extra.sender&&e.extra.sender.type===As.Client?(this.onCustomEvent("onPullClientEvent-"+t,[s,e.params,e.extra],!0),this.onCustomEvent("onPullClientEvent",[t,s,e.params,e.extra],!0),this.emit({type:Xe.Client,moduleId:t,data:{command:s,params:F.clone(e.params),extra:F.clone(e.extra)}})):t==="pull"?this.handleInternalPullEvent(s,e):t=="online"?((e?.extra?.server_time_ago||0)<240&&(this.onCustomEvent("onPullOnlineEvent",[s,e.params,e.extra],!0),this.emit({type:Xe.Online,data:{command:s,params:F.clone(e.params),extra:F.clone(e.extra)}})),s==="userStatusChange"&&this.emitUserStatusChange(e.params.user_id,e.params.online)):(this.onCustomEvent("onPullEvent-"+t,[s,e.params,e.extra],!0),this.onCustomEvent("onPullEvent",[t,s,e.params,e.extra],!0),this.emit({type:Xe.Server,moduleId:t,data:{command:s,params:F.clone(e.params),extra:F.clone(e.extra)}}))}catch(n){this.getLogger().warning("PULL ERROR",{errorType:"broadcastMessages execute error",errorEvent:n,message:qe(e)}).catch(()=>{})}e.extra&&e.extra.revision_web&&this.checkRevision(W.toInteger(e.extra.revision_web))}broadcastMessages(e){for(const t of e)this.broadcastMessage(t)}async sendMessageBatch(e){if(!this.isPublishingEnabled())return this.getLogger().error("Client publishing is not supported or is disabled").catch(()=>{}),Promise.reject(new D({code:"JSSDK_PULL_PUBLISHING_DISABLED",description:"Pull: this portal has not enabled client publishing, so the message cannot be sent. Publish from your back end with `pull.application.event.add` instead.",status:0}));if(this.isJsonRpc()){const t=this.requireJsonRpcAdapter().createPublishRequest(e);return Promise.resolve(this.handOverToConnector(JSON.stringify(t)))}else{const t={};for(const s of e)if(typeof s.userList<"u")for(const n of s.userList){const i=Number(n);t[i]=i}return this._channelManager.getPublicIds(Object.values(t)).then(s=>this.handOverToConnector(this.encodeMessageBatch(e,s)))}}requireJsonRpcAdapter(){if(!this._jsonRpcAdapter)throw new D({code:"JSSDK_PULL_SEND_REFUSED",description:"Pull: the JSON-RPC adapter is not ready, so the message was not sent. The client has not finished starting.",status:0});return this._jsonRpcAdapter}handOverToConnector(e){const t=this.connector;if(!t)throw new D({code:"JSSDK_PULL_SEND_REFUSED",description:"Pull: there is no connector to send through \u2014 the client is not connected.",status:0});if(!t.send(e))throw new D({code:"JSSDK_PULL_SEND_REFUSED",description:"Pull: the connector refused the frame, so it never left \u2014 the socket is not open, or long-polling has no publication path. The connector log carries the specific reason.",status:0});return!0}encodeMessageBatch(e,t){const s=[];return e.forEach(n=>{const i=n.body;let c=[];if(n.userList&&(c=this.createMessageReceivers(n.userList,t)),n.channelList){if(!F.isArray(n.channelList))throw new TypeError("messageFields.publicChannels must be an array");n.channelList.forEach(a=>{let l,h;if(typeof a=="string"&&a.includes(".")){const u=a.toString().split(".");l=u[0],h=u[1]}else if(typeof a=="object"&&"publicId"in a&&"signature"in a)l=a?.publicId,h=a?.signature;else throw new Error(`Public channel MUST be either a string, formatted like "{publicId}.{signature}" or an object with fields 'publicId' and 'signature'`);c.push({id:this.encodeId(l),signature:this.encodeId(h)})})}s.push({receivers:c,body:JSON.stringify(i),expiry:n.expiry||0})}),this._useLiteProtobuf?Au(s):Su.encode(Su.create({requests:[{incomingMessages:{messages:s}}]})).finish()}createMessageReceivers(e,t){const s=[];for(const n of e){if(!t[n]||!t[n].publicId)throw new Error(`Could not determine public id for user ${n}`);s.push({id:this.encodeId(t[n].publicId),signature:this.encodeId(t[n].signature)})}return s}emitUserStatusChange(e,t){if(this._userStatusCallbacks[e])for(const s of this._userStatusCallbacks[e])s({userId:e,isOnline:t})}restoreUserStatusSubscription(){for(const e in this._userStatusCallbacks)Object.prototype.hasOwnProperty.call(this._userStatusCallbacks,e)&&this._userStatusCallbacks[e].length>0&&this._jsonRpcAdapter?.executeOutgoingRpcCommand(pt.SubscribeStatusChange,{userId:e})}async loadConfig(e){if(this._config){if(this.isConfigActual(this._config)&&this.checkRevision(this._config.api.revision_web))return Promise.resolve(this._config);this._config=Object.assign({},$u)}else{this._config=Object.assign({},$u);let t;if(this._storage&&(t=this._storage.get(We.PullConfig,null)),this.isConfigActual(t)&&this.checkRevision(t.api.revision_web))return Promise.resolve(t);this._storage&&this._storage.remove(We.PullConfig)}return new Promise((t,s)=>{this._restClient.actions.v2.call.make({method:this._configGetMethod,params:{CACHE:"N"}}).then(n=>{const i=n.getData().result,c=Math.floor((Date.now()-new Date(i.serverTime).getTime())/1e3);delete i.serverTime;const a=Object.assign({},i);a.server.timeShift=c,t(a)}).catch(n=>{s(n)})})}isConfigActual(e){if(!F.isPlainObject(e)||Number(e.server.config_timestamp)!==this._configTimestamp)return!1;const t=new Date;if(F.isNumber(e.exp)&&e.exp>0&&e.exp<t.getTime()/1e3||Object.keys(e.channels).length===0)return!1;for(const s in e.channels){if(!Object.prototype.hasOwnProperty.call(e.channels,s))continue;const n=e.channels[s];if(new Date(n.end)<t)return!1}return!0}startCheckConfig(){this._disposed||(this._checkInterval&&(clearInterval(this._checkInterval),this._checkInterval=null),this._checkInterval=setInterval(this.checkConfig.bind(this),gw))}stopCheckConfig(){this._checkInterval&&clearInterval(this._checkInterval),this._checkInterval=null}checkConfig(){if(this.isConfigActual(this._config)){if(!this.checkRevision(W.toInteger(this._config?.api.revision_web)))return!1}else this.logToConsole("Stale config detected. Restarting"),this.restart($e.CONFIG_EXPIRED,"config expired");return!0}setConfig(e,t){for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&Object.prototype.hasOwnProperty.call(this._config,s)&&(this._config[s]=e[s]);if(e.publicChannels&&this.setPublicIds(Object.values(e.publicChannels)),this._configTimestamp=Number(e.server.config_timestamp),this._storage&&t&&!this._disposed)try{this._storage.set(We.PullConfig,e)}catch(s){typeof localStorage<"u"&&localStorage.removeItem&&localStorage.removeItem("history"),this.getLogger().error(`${W.getDateForLog()}: Pull: Could not cache config in local storage.`,{error:s}).catch(()=>{})}}setPublicIds(e){this._channelManager.setPublicIds(e)}checkRevision(e){return this._skipCheckRevision?!0:e>0&&e!==ss?(this._enabled=!1,this.showNotification("PULL_OLD_REVISION"),this.disconnect($e.NORMAL_CLOSURE,"check_revision"),this.onCustomEvent("onPullRevisionUp",[e,ss]),this.emit({type:Xe.Revision,data:{server:e,client:ss}}),this.logToConsole(`Pull revision changed from ${ss} to ${e}. Reload required`),!1):!0}disconnect(e,t){this.connector&&(this._isManualDisconnect=!0,this.connector.disconnect(e,t))}restoreWebSocketConnection(){this._connectionType!==pe.WebSocket&&this._connectors.webSocket?.connect()}scheduleReconnect(e=0){this._disposed||!this._enabled||(e||(e=this.getConnectionAttemptDelay(this._connectionAttempt)),this.logToConsole(`Pull: scheduling reconnection in ${e} seconds; attempt # ${this._connectionAttempt}`),this.armTimeout("_reconnectTimeout",()=>{this.connect().catch(t=>{this.getLogger().error("scheduleReconnect",{error:t}).catch(()=>{})})},e*1e3))}scheduleRestoreWebSocketConnection(){this._disposed||(this.logToConsole(`Pull: scheduling restoration of websocket connection in ${Pu} seconds`),!this._restoreWebSocketTimeout&&this.armTimeout("_restoreWebSocketTimeout",()=>{this._restoreWebSocketTimeout=null,this.restoreWebSocketConnection()},Pu*1e3))}async connect(){return this._disposed||!this._enabled?Promise.reject():this.connector?.connected?Promise.resolve():(this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null),this.status=Ze.Connecting,this._connectionAttempt++,new Promise((e,t)=>{this._connectPromise={resolve:e,reject:t},this.connector?.connect()}))}scheduleRestart(e,t,s=0){this._disposed||(s<1&&(s=Math.ceil(Math.random()*30)+5),this.armTimeout("_restartTimeout",()=>this.restart(e,t),s*1e3))}handleRpcIncomingMessage(e){this._session.mid=e.mid;const t=e.body;return t===null||typeof t!="object"?(this.getLogger().warning(`${W.getDateForLog()}: Pull: an rpc message body was not an object and was skipped`,{bodyType:t===null?"null":typeof t}).catch(()=>{}),{}):((t.extra===null||typeof t.extra!="object")&&(t.extra={}),t.extra.sender=e.sender,(F.isPlainObject(e.user_params)||F.isPlainObject(e.dictionary))&&(t.params===null||typeof t.params!="object")&&(t.params={}),"user_params"in e&&F.isPlainObject(e.user_params)&&Object.assign(t.params,e.user_params),"dictionary"in e&&F.isPlainObject(e.dictionary)&&Object.assign(t.params,e.dictionary),this.checkDuplicate(e.mid)&&(this.addMessageToStat(t),this.trimDuplicates(),this.broadcastMessage(t)),this.connector?.send(`mack:${e.mid}`),{})}handleIncomingEvents(e){const t=[];if(e.length===0){this._session.mid=null;return}for(const s of e)this.updateSessionFromEvent(s),!(s.mid&&!this.checkDuplicate(s.mid))&&(this.addMessageToStat(s.text),t.push(s.text));this.trimDuplicates(),this.broadcastMessages(t)}updateSessionFromEvent(e){this._session.mid=e.mid||null,this._session.tag=e.tag||null,this._session.time=e.time||null}handleInternalPullEvent(e,t){switch(e.toUpperCase()){case xr.CHANNEL_EXPIRE:{if(t.params.action==="reconnect"){const s=t.params?.channel.type;s==="private"&&this._config?.channels?.private&&(this._config.channels.private=t.params.new_channel,this.logToConsole(`Pull: new config for ${t.params.channel.type} channel set: [updated]`)),s==="shared"&&this._config?.channels?.shared&&(this._config.channels.shared=t.params.new_channel,this.logToConsole(`Pull: new config for ${t.params.channel.type} channel set: [updated]`)),this.reconnect($e.CONFIG_REPLACED,"config was replaced")}else this.restart($e.CHANNEL_EXPIRED,"channel expired received");break}case xr.CONFIG_EXPIRE:{this.restart($e.CONFIG_EXPIRED,"config expired received");break}case xr.SERVER_RESTART:{this.reconnect($e.SERVER_RESTARTED,"server was restarted",15);break}}}onIncomingMessage(e){if(this.isJsonRpc())e===mw?this.onJsonRpcPing():this._jsonRpcAdapter?.parseJsonRpcMessage(e);else{const t=this.extractMessages(e);this.handleIncomingEvents(t)}}onLongPollingOpen(){this._unloading=!1,this._starting=!1,this._connectionAttempt=0,this._isManualDisconnect=!1,this.status=Ze.Online,this.logToConsole("Pull: Long polling connection with push-server opened"),this.isWebSocketEnabled()&&this.scheduleRestoreWebSocketConnection(),this._connectPromise&&this._connectPromise.resolve({})}onLongPollingDisconnect(e){this._connectionType===pe.LongPolling&&(this.status=Ze.Offline),this.logToConsole(`Pull: Long polling connection with push-server closed. Code: ${e.code}, reason: ${e.reason}`),this._isManualDisconnect||this.scheduleReconnect(),this._isManualDisconnect=!1,this.clearPingWaitTimeout()}onLongPollingError(e){this._starting=!1,this._connectionType===pe.LongPolling&&(this.status=Ze.Offline),this.getLogger().error(`${W.getDateForLog()}: Pull: Long polling connection error`,{error:e}).catch(()=>{}),this.scheduleReconnect(),this._connectPromise&&this._connectPromise.reject(e),this.clearPingWaitTimeout()}onWebSocketBlockChanged(e){const t=e.isWebSocketBlocked;t&&this._connectionType===pe.WebSocket&&!this.isConnected()?(this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null),this._connectionAttempt=0,this._connectionType=pe.LongPolling,this.scheduleReconnect(1)):!t&&this._connectionType===pe.LongPolling&&(this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null),this._restoreWebSocketTimeout&&(clearTimeout(this._restoreWebSocketTimeout),this._restoreWebSocketTimeout=null),this._connectionAttempt=0,this._connectionType=pe.WebSocket,this.scheduleReconnect(1))}onWebSocketOpen(){this._unloading=!1,this._starting=!1,this._connectionAttempt=0,this._isManualDisconnect=!1,this.status=Ze.Online,this._sharedConfig.setWebSocketBlocked(!1),this._sharedConfig.setLongPollingBlocked(!0),this._connectionType==pe.LongPolling&&(this._connectionType=pe.WebSocket,this._connectors.longPolling?.disconnect($e.CONFIG_REPLACED,"Fire at onWebSocketOpen")),this._restoreWebSocketTimeout&&(clearTimeout(this._restoreWebSocketTimeout),this._restoreWebSocketTimeout=null),this.logToConsole("Pull: Websocket connection with push-server opened"),this._connectPromise&&this._connectPromise.resolve({}),this.restoreUserStatusSubscription()}onWebSocketDisconnect(e){this._connectionType===pe.WebSocket&&(this.status=Ze.Offline),this.logToConsole(`Pull: Websocket connection with push-server closed. Code: ${e.code}, reason: ${e.reason}`,!0),this._isManualDisconnect||(e.code==$e.WRONG_CHANNEL_ID?this.scheduleRestart($e.WRONG_CHANNEL_ID,"wrong channel signature"):this.scheduleReconnect()),this._sharedConfig.setLongPollingBlocked(!0),this._isManualDisconnect=!1,this.clearPingWaitTimeout()}onWebSocketError(e){this._starting=!1,this._connectionType===pe.WebSocket&&(this.status=Ze.Offline),this.getLogger().error(`${W.getDateForLog()}: Pull: WebSocket connection error`,{error:e}).catch(()=>{}),this.scheduleReconnect(),this._connectPromise&&this._connectPromise.reject(e),this.clearPingWaitTimeout()}extractMessages(e){if(e instanceof ArrayBuffer)return this.extractProtobufMessages(e);if(F.isStringFilled(e))return this.extractPlainTextMessages(e);throw new Error("Error pullEvent type")}extractProtobufMessages(e){const t=[];try{const s=this._useLiteProtobuf?Nu(new Uint8Array(e)):Z_.decode(new Uint8Array(e));"damaged"in s&&s.damaged&&this.getLogger().warning(`${W.getDateForLog()}: Pull: a protobuf frame was damaged; whatever could not be read was dropped`,{byteLength:e.byteLength}).catch(()=>{});for(let n=0;n<s.responses.length;n++){const i=s.responses[n];if(i.command!=="outgoingMessages")continue;const c=i.outgoingMessages.messages;for(const a of c){let l;try{l=JSON.parse(a.body)}catch(u){this.getLogger().error(`${W.getDateForLog()}: Pull: Could not parse message body`,{error:u}).catch(()=>{});continue}if(l===null||typeof l!="object"){this.getLogger().warning(`${W.getDateForLog()}: Pull: a message body was not a JSON object and was skipped`,{responseIndex:n,bodyType:l===null?"null":typeof l}).catch(()=>{});continue}if((l.extra===null||typeof l.extra!="object")&&(l.extra={}),!a.sender){this.getLogger().warning(`${W.getDateForLog()}: Pull: a protobuf message arrived with no sender and was skipped`,{responseIndex:n,moduleId:typeof l.module_id=="string"?l.module_id:null}).catch(()=>{});continue}l.extra.sender={type:a.sender.type},a.sender.id instanceof Uint8Array&&(l.extra.sender.id=this.decodeId(a.sender.id));const h={mid:this.decodeId(a.id),text:l};t.push(h)}}}catch(s){this.getLogger().error(`${W.getDateForLog()}: Pull: Could not parse message`,{error:s}).catch(()=>{})}return t}extractPlainTextMessages(e){const t=[],s=e.match(/#!NGINXNMS!#(.*?)#!NGINXNME!#/g);if(s===null)return this.getLogger().warning("PULL ERROR",{errorType:"parseResponse error parsing message",byteLength:e.length}).catch(()=>{}),[];for(let n=0;n<s.length;n++){if(s[n]=s[n].substring(12,s[n].length-12),s[n].length<=0)continue;let i;try{i=JSON.parse(s[n])}catch{continue}t.push(i)}return t}decodeId(e){let t="";for(const s of e){const n=s.toString(16);n.length===1&&(t+="0"),t+=n}return t}encodeId(e){if(!e)return new Uint8Array;const t=[];for(let s=0;s<e.length;s+=2)t.push(Number.parseInt(e.slice(s,s+2),16));return new Uint8Array(t)}onOffline(){this._disposed||this.disconnect($e.NORMAL_CLOSURE,"offline")}onOnline(){this._disposed||this.connect().catch(e=>{this.getLogger().error("onOnline",{error:e}).catch(()=>{})})}onBeforeUnload(){this._unloading=!0,this.persistSession(),this.scheduleReconnect(15)}persistSession(){const e=F.clone(this.session);if(e.ttl=Date.now()+bw*1e3,this._storage)try{this._storage.set(xu,JSON.stringify(e))}catch(t){this.getLogger().error(`${W.getDateForLog()}: Pull: Could not save session info in local storage. Error: `,{error:t}).catch(()=>{})}}sendPullStatusDelayed(e,t){this._disposed||this.armTimeout("_offlineTimeout",()=>{this._offlineTimeout=null,this.sendPullStatus(e)},t)}sendPullStatus(e){this._unloading||(this.onCustomEvent("onPullStatus",[e]),this.emit({type:Xe.Status,data:{status:e}}))}extendWatch(e,t=!1){this._watchTagsQueue.get(e)||(this._watchTagsQueue.set(e,!0),t&&this.updateWatch(t))}updateWatch(e=!1){this._disposed||this.armTimeout("_watchUpdateTimeout",()=>{const t=[...this._watchTagsQueue.keys()];t.length>0?this._restClient.actions.v2.call.make({method:"pull.watch.extend",params:{tags:t}}).then(s=>{const n=s.getData().result;for(const i of n)this.clearWatch(i);this.updateWatch()}).catch(()=>{this.updateWatch()}):this.updateWatch()},e?this._watchForceUpdateInterval:this._watchUpdateInterval)}clearWatch(e){this._watchTagsQueue.delete(e)}onJsonRpcPing(){this.updatePingWaitTimeout(),this.connector?.send(yw)}updatePingWaitTimeout(){this._disposed||this.armTimeout("_pingWaitTimeout",this._onPingTimeoutHandler,Fu*2*1e3)}clearPingWaitTimeout(){this._pingWaitTimeout&&clearTimeout(this._pingWaitTimeout),this._pingWaitTimeout=null}onPingTimeout(){this._pingWaitTimeout=null,!(this._disposed||!this._enabled||!this.isConnected())&&(this.getLogger().warning(`No pings are received in ${Fu*2} seconds. Reconnecting`).catch(()=>{}),this.disconnect($e.STUCK,"connection stuck"),this.scheduleReconnect())}getConnectionAttemptDelay(e){let t;return e<1?t=.5:e<3?t=15:e<5?t=45:e<10?t=600:t=3600,t+t*Math.random()*.2}checkDuplicate(e){return this._session.lastMessageIds.includes(e)?(this.getLogger().warning(`Duplicate message ${e} skipped`).catch(()=>{}),!1):(this._session.lastMessageIds.push(e),!0)}trimDuplicates(){this._session.lastMessageIds.length>Mu&&(this._session.lastMessageIds=this._session.lastMessageIds.slice(-Mu))}logMessage(e){this._debug&&(e.extra?.sender&&e.extra.sender.type===As.Client?this.getLogger().info(`onPullClientEvent-${e.module_id}`,qe({command:e.command,params:e.params,extra:e.extra})).catch(()=>{}):e.module_id=="online"?this.getLogger().info("onPullOnlineEvent",qe({command:e.command,params:e.params,extra:e.extra})).catch(()=>{}):this.getLogger().info("onPullEvent",qe({moduleId:e.module_id,command:e.command,params:e.params,extra:e.extra})).catch(()=>{}))}logToConsole(e,t=!1){(this._loggingEnabled||t)&&this.getLogger().debug(`${W.getDateForLog()}: ${e}`).catch(()=>{})}addMessageToStat(e){this._session.history[e.module_id]||(this._session.history[e.module_id]={}),this._session.history[e.module_id][e.command]||(this.session.history[e.module_id][e.command]=0),this._session.history[e.module_id][e.command]++,this._session.messageCount++}showNotification(e){this.getLogger().notice(e).catch(()=>{})}onCustomEvent(e,t,s=!1){}}var _w=Object.defineProperty,ww=o((r,e)=>_w(r,"name",{value:e,configurable:!0}),"l$2");class Bu{static{o(this,"B24HelperManager")}static{ww(this,"B24HelperManager")}_b24;_isInit=!1;_profile=null;_app=null;_payment=null;_license=null;_currency=null;_appOptions=null;_userOptions=null;_b24PullClient=null;_pullClientUnSubscribe=[];_pullClientModuleId="";_logger;constructor(e){this._logger=ae.createNullLogger(),this._b24=e}setLogger(e){this._logger=e,this._profile!==null&&this._profile.setLogger(this.getLogger()),this._app!==null&&this._app.setLogger(this.getLogger()),this._payment!==null&&this._payment.setLogger(this.getLogger()),this._license!==null&&this._license.setLogger(this.getLogger()),this._currency!==null&&this._currency.setLogger(this.getLogger()),this._appOptions!==null&&this._appOptions.setLogger(this.getLogger()),this._userOptions!==null&&this._userOptions.setLogger(this.getLogger())}getLogger(){return this._logger}destroy(){this._destroyPullClient()}async loadData(e=[he.App,he.Profile],t="helper-load-data"){const s={[he.App]:{method:"app.info"},[he.Profile]:{method:"profile"},[he.Currency]:[{method:"crm.currency.base.get"},{method:"crm.currency.list"}],[he.AppOptions]:{method:"app.option.get"},[he.UserOptions]:{method:"user.option.get"}},n=e.reduce((i,c)=>{if(s[c])if(Array.isArray(s[c]))for(const[a,l]of s[c].entries())i[`get_${c}_${a}`]=l;else i[`get_${c}`]=s[c];return i},{});try{const i=(await this._b24.actions.v2.batch.make({calls:n,options:{isHaltOnError:!0,returnAjaxResult:!1,requestId:t}})).getData();i[`get_${he.App}`]&&(this._app=await this.parseAppData(i[`get_${he.App}`]),this._payment=await this.parsePaymentData(i[`get_${he.App}`]),this._license=await this.parseLicenseData(i[`get_${he.App}`])),i[`get_${he.Profile}`]&&(this._profile=await this.parseUserData(i[`get_${he.Profile}`])),i[`get_${he.Currency}_0`]&&i[`get_${he.Currency}_1`]&&(this._currency=await this.parseCurrencyData({currencyBase:i[`get_${he.Currency}_0`],currencyList:i[`get_${he.Currency}_1`]})),i[`get_${he.AppOptions}`]&&(this._appOptions=await this.parseOptionsData("app",i[`get_${he.AppOptions}`])),i[`get_${he.UserOptions}`]&&(this._userOptions=await this.parseOptionsData("user",i[`get_${he.UserOptions}`])),this._isInit=!0}catch(i){throw i instanceof Error?i:(this.getLogger().error("Failed to load data",{error:i}).catch(()=>{}),new Error("Failed to load data",{cause:i}))}}async parseUserData(e){const t=new b_(this._b24);return t.setLogger(this.getLogger()),t.initData({id:Number(e.ID),isAdmin:e.ADMIN===!0,lastName:e?.LAST_NAME||"",name:e?.NAME||"",gender:e?.PERSONAL_GENDER||"",photo:e?.PERSONAL_PHOTO||"",TimeZone:e?.TIME_ZONE||"",TimeZoneOffset:e?.TIME_ZONE_OFFSET}).then(()=>t)}async parseAppData(e){const t=new S_(this._b24);return t.setLogger(this.getLogger()),t.initData({id:Number.parseInt(e.ID),code:e.CODE,version:Number.parseInt(e.VERSION),status:e.STATUS,isInstalled:e.INSTALLED}).then(()=>t)}async parsePaymentData(e){const t=new O_(this._b24);return t.setLogger(this.getLogger()),t.initData({isExpired:e.PAYMENT_EXPIRED==="Y",days:Number.parseInt(e.DAYS||"0")}).then(()=>t)}async parseLicenseData(e){const t=new k_(this._b24);return t.setLogger(this.getLogger()),t.initData({languageId:e.LANGUAGE_ID,license:e.LICENSE,licensePrevious:e.LICENSE_PREVIOUS,licenseType:e.LICENSE_TYPE,licenseFamily:e.LICENSE_FAMILY,isSelfHosted:e.LICENSE.includes("selfhosted")}).then(()=>t)}async parseCurrencyData(e){const t=new C_(this._b24);return t.setLogger(this.getLogger()),t.initData(e).then(()=>t)}async parseOptionsData(e,t){const s=new co(this._b24,e);return s.setLogger(this.getLogger()),s.initData(t).then(()=>s)}get isInit(){return this._isInit}get forB24Form(){if(this.ensureInitialized(),this._profile===null)throw new Error("B24HelperManager.profileInfo not initialized");if(this._app===null)throw new Error("B24HelperManager.appInfo not initialized");return{app_code:this.appInfo.data.code,app_status:this.appInfo.data.status,payment_expired:this.paymentInfo.data.isExpired?"Y":"N",days:this.paymentInfo.data.days,b24_plan:this.licenseInfo.data.license,c_name:this.profileInfo.data.name,c_last_name:this.profileInfo.data.lastName,hostname:this.hostName}}get hostName(){return this._b24.getTargetOrigin()}get profileInfo(){if(this.ensureInitialized(),this._profile===null)throw new Error("B24HelperManager.profileInfo not initialized");return this._profile}get appInfo(){if(this.ensureInitialized(),this._app===null)throw new Error("B24HelperManager.appInfo not initialized");return this._app}get paymentInfo(){if(this.ensureInitialized(),this._payment===null)throw new Error("B24HelperManager.paymentInfo not initialized");return this._payment}get licenseInfo(){if(this.ensureInitialized(),this._license===null)throw new Error("B24HelperManager.licenseInfo not initialized");return this._license}get currency(){if(this.ensureInitialized(),this._currency===null)throw new Error("B24HelperManager.currency not initialized");return this._currency}get appOptions(){if(this.ensureInitialized(),this._appOptions===null)throw new Error("B24HelperManager.appOptions not initialized");return this._appOptions}get userOptions(){if(this.ensureInitialized(),this._userOptions===null)throw new Error("B24HelperManager.userOptions not initialized");return this._userOptions}get isSelfHosted(){return this.licenseInfo.data.isSelfHosted}get primaryKeyIncrementValue(){return this.isSelfHosted?1:2}get b24SpecificUrl(){return this.isSelfHosted?{[qt.MainSettings]:"/configs/",[qt.UfList]:"/configs/userfield_list.php",[qt.UfPage]:"/configs/userfield.php"}:{[qt.MainSettings]:"/settings/configs/",[qt.UfList]:"/settings/configs/userfield_list.php",[qt.UfPage]:"/settings/configs/userfield.php"}}usePullClient(e="prefix",t,s){return this._b24PullClient?this:(this.initializePullClient(typeof t>"u"?this.profileInfo.data.id||0:t,e,s),this)}initializePullClient(e,t="prefix",s){this._b24PullClient=new ju({b24:this._b24,restApplication:this._b24.auth.getUniq(t),userId:e,...s===void 0?{}:{protobufCodec:s}})}subscribePullClient(e,t="application"){if(!this._b24PullClient)throw new Error("PullClient not init");return this._pullClientModuleId=t,this._pullClientUnSubscribe.push(this._b24PullClient.subscribe({moduleId:this._pullClientModuleId,callback:e})),this}startPullClient(){if(!this._b24PullClient)throw new Error("PullClient not init");this._b24PullClient.start().catch(e=>{this.getLogger().error(`${W.getDateForLog()}: Pull not running`,{error:e}).catch(()=>{})})}getModuleIdPullClient(){if(!this._b24PullClient)throw new Error("PullClient not init");return this._pullClientModuleId}_destroyPullClient(){for(const e of this._pullClientUnSubscribe)e();this._b24PullClient?.destroy(),this._b24PullClient=null}ensureInitialized(){if(!this._isInit)throw new Error("B24HelperManager not initialized")}}var Sw=Object.defineProperty,Ft=o((r,e)=>Sw(r,"name",{value:e,configurable:!0}),"l$1");const vw=Ft(()=>{let r=!1,e=!1,t=null;return{initB24Helper:Ft(async(s,n=[he.App,he.Profile],i="helper-load-data")=>(t===null&&(t=new Bu(s)),r||(await t.loadData(n,i),r=!0),t),"initB24Helper"),isInitB24Helper:Ft(()=>r,"isInitB24Helper"),destroyB24Helper:Ft(()=>{t?.destroy(),t=null,r=!1,e=!1},"destroyB24Helper"),getB24Helper:Ft(()=>{if(t===null)throw new D({code:"JSSDK_HELPER_NOT_INIT",description:"B24HelperManager is not initialized. You need to call initB24Helper first.",status:0});return t},"getB24Helper"),usePullClient:Ft((s,n,i)=>{if(t===null)throw new D({code:"JSSDK_HELPER_NOT_INIT",description:"B24HelperManager is not initialized. You need to call initB24Helper first.",status:0});t.usePullClient(s,n,i),e=!0},"usePullClient"),useSubscribePullClient:Ft((s,n="application")=>{if(!e)throw new D({code:"JSSDK_HELPER_PULL_CLIENT_NOT_INIT",description:"PullClient is not initialized. You need to call usePullClient first.",status:0});t?.subscribePullClient(s,n)},"useSubscribePullClient"),startPullClient:Ft(()=>{if(!e)throw new D({code:"JSSDK_HELPER_PULL_CLIENT_NOT_INIT",description:"PullClient is not initialized. You need to call usePullClient first.",status:0});t?.startPullClient()},"startPullClient")}},"useB24Helper");var Ew=Object.defineProperty,uo=o((r,e)=>Ew(r,"name",{value:e,configurable:!0}),"s");let Zt=null;function Uu(){const r={DOMAIN:null,PROTOCOL:!1,APP_SID:null,LANG:null};if(window.name){const[e,t,s]=window.name.split("|");r.DOMAIN=e,r.PROTOCOL=Number.parseInt(t??"0")===1,r.APP_SID=s,r.LANG=null}return r}o(Uu,"m"),uo(Uu,"parseFrameQueryParams");async function Vu(r){const e=Uu();if(!e.DOMAIN||!e.APP_SID)throw new D({code:"JSSDK_CLIENT_SIDE_WARNING",description:"Well done! Now paste this URL into the Bitrix24 app settings",status:500});const t=new fu(e,r);try{await t.init()}catch(s){try{t.destroy()}catch{}throw s}return t}o(Vu,"l"),uo(Vu,"makeFrame");async function qu(r){if(Zt!==null)return Zt;const e=Vu(r);return Zt=e,e.then(t=>{const s=t.destroy.bind(t);t.destroy=()=>{Zt===e&&(Zt=null),s()}},()=>{Zt===e&&(Zt=null)}),e}o(qu,"initializeB24Frame"),uo(qu,"initializeB24Frame"),I.AbstractB24=js,I.AbstractLogger=Un,I.AdaptiveDelayer=Ec,I.AjaxError=_e,I.AjaxResult=jr,I.ApiVersion=ee,I.AppFrame=ru,I.AuthHookManager=eu,I.AuthManager=nu,I.AuthOAuthManager=gu,I.B24Frame=fu,I.B24HelperManager=Bu,I.B24Hook=ro,I.B24LangList=zn,I.B24LocaleMap=lp,I.B24OAuth=p_,I.B24PullClientManager=ju,I.BatchRefV3=Mb,I.Browser=sc,I.CatalogProductImageType=cc,I.CatalogProductType=ac,I.CatalogRoundingRuleType=lc,I.CloseReasons=$e,I.ConnectionType=pe,I.ConsolaAdapter=Af,I.ConsoleHandler=Ja,I.ConsoleV2Handler=$n,I.DataType=Ga,I.DialogManager=cu,I.EnumAppStatus=vt,I.EnumBitrix24Edition=uc,I.EnumBizprocBaseType=hc,I.EnumBizprocDocumentType=dc,I.EnumCrmEntityType=nc,I.EnumCrmEntityTypeId=ut,I.EnumCrmEntityTypeShort=qn,I.Environment=Bn,I.FilterV3=Db,I.HttpV2=en,I.HttpV3=tn,I.JsonFormatter=ef,I.LineFormatter=Ss,I.ListRpcError=Wn,I.LoadDataType=he,I.LogLevel=K,I.Logger=Fr,I.LoggerFactory=ae,I.LsKeys=We,I.MemoryHandler=wf,I.MessageCommands=le,I.MessageManager=tu,I.NullLogger=Mr,I.OperatingLimiter=vc,I.OptionsManager=ou,I.ParamsFactory=Br,I.ParentManager=iu,I.PlacementManager=du,I.ProductRowDiscountTypeId=oc,I.PullStatus=Ze,I.RateLimiter=Sc,I.RefreshTokenError=pu,I.RestrictionManager=dr,I.Result=ke,I.RpcMethod=pt,I.SdkError=D,I.SenderType=As,I.ServerMode=Hn,I.SliderManager=lu,I.StatusDescriptions=mc,I.StreamHandler=Ef,I.SubscriptionType=Xe,I.SystemCommands=xr,I.TelegramFormatter=za,I.TelegramHandler=Lf,I.Text=W,I.Type=F,I.TypeOption=Et,I.TypeSpecificUrl=qt,I.WinstonAdapter=Rf,I.convertBizprocDocumentTypeToCrmEntityTypeId=fc,I.getDocumentId=pc,I.getDocumentType=Ts,I.getDocumentTypeForFilter=gc,I.getEnumCrmEntityTypeShort=ic,I.getEnumValue=Xa,I.getEnvironment=vs,I.initializeB24Frame=qu,I.isArrayOfArray=Za,I.isBrowserLikeRuntime=hr,I.isFrameRefusalCloseCode=yc,I.memoryUsageProcessor=hf,I.omit=Vn,I.pick=Ya,I.pidProcessor=cf,I.useB24Helper=vw,I.useFormatter=Cb,I.versionManager=fr}));
//# sourceMappingURL=index.min.js.map