@msafe/sui3-sdk 0.0.48 → 0.0.49-pre-de73866.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Oi=Object.create;var wn=Object.defineProperty;var Ei=Object.getOwnPropertyDescriptor;var Ci=Object.getOwnPropertyNames;var vi=Object.getPrototypeOf,Mi=Object.prototype.hasOwnProperty;var gt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Ai=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ci(e))!Mi.call(r,s)&&s!==t&&wn(r,s,{get:()=>e[s],enumerable:!(n=Ei(e,s))||n.enumerable});return r};var ar=(r,e,t)=>(t=r!=null?Oi(vi(r)):{},Ai(e||!r||!r.__esModule?wn(t,"default",{value:r,enumerable:!0}):t,r));var Ds=gt((Bm,As)=>{"use strict";As.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Ps=gt((qm,Ns)=>{"use strict";var Vr=Ds();Ns.exports=(r,e={})=>{if(!Vr(r)&&!Array.isArray(r))throw new TypeError("Expected a plain object or array");let{deep:t}=e,n=[],s=[],a=o=>{let c=n.indexOf(o);if(c!==-1)return s[c];let u=[];return n.push(o),s.push(u),u.push(...o.map(d=>Array.isArray(d)?a(d):Vr(d)?i(d):d)),u},i=o=>{let c=n.indexOf(o);if(c!==-1)return s[c];let u={},d=Object.keys(o).sort(e.compare);n.push(o),s.push(u);for(let f of d){let g=o[f],m;t&&Array.isArray(g)?m=a(g):m=t&&Vr(g)?i(g):g,Object.defineProperty(u,f,{...Object.getOwnPropertyDescriptor(o,f),value:m})}return u};return Array.isArray(r)?t?a(r):r.slice():i(r)}});var _s=gt((Um,Rs)=>{"use strict";var ic=Object.prototype.toString;Rs.exports=function(e){if(e===void 0)return"undefined";if(e===null)return"null";var t=typeof e;if(t==="boolean")return"boolean";if(t==="string")return"string";if(t==="number")return"number";if(t==="symbol")return"symbol";if(t==="function")return dc(e)?"generatorfunction":"function";if(oc(e))return"array";if(fc(e))return"buffer";if(hc(e))return"arguments";if(uc(e))return"date";if(cc(e))return"error";if(lc(e))return"regexp";switch(Fs(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(mc(e))return"generator";switch(t=ic.call(e),t){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return t.slice(8,-1).toLowerCase().replace(/\s/g,"")};function Fs(r){return typeof r.constructor=="function"?r.constructor.name:null}function oc(r){return Array.isArray?Array.isArray(r):r instanceof Array}function cc(r){return r instanceof Error||typeof r.message=="string"&&r.constructor&&typeof r.constructor.stackTraceLimit=="number"}function uc(r){return r instanceof Date?!0:typeof r.toDateString=="function"&&typeof r.getDate=="function"&&typeof r.setDate=="function"}function lc(r){return r instanceof RegExp?!0:typeof r.flags=="string"&&typeof r.ignoreCase=="boolean"&&typeof r.multiline=="boolean"&&typeof r.global=="boolean"}function dc(r,e){return Fs(r)==="GeneratorFunction"}function mc(r){return typeof r.throw=="function"&&typeof r.return=="function"&&typeof r.next=="function"}function hc(r){try{if(typeof r.length=="number"&&typeof r.callee=="function")return!0}catch(e){if(e.message.indexOf("callee")!==-1)return!0}return!1}function fc(r){return r.constructor&&typeof r.constructor.isBuffer=="function"?r.constructor.isBuffer(r):!1}});var _t=gt((Hm,Bs)=>{"use strict";var pc=Ps(),Gr=_s(),Ws=(r,e)=>!e||Gr(e)!=="array"?!1:e.indexOf(r)>-1,gc=(r,e)=>pc(r,{compare:e}),js=(r,e)=>{let t=e&&e.compareFunction;return r.slice().sort(t)};function Ls(r,e){let t=e&&e.compareFunction,n=gc(r,t);return Object.keys(r).forEach(function(s){let a=n[s],i=Gr(a);if(i==="object"){(!e||!Ws(s,e.ignoreObjectAtKeys))&&(n[s]=Ls(a,e));return}i==="array"&&(!e||!Ws(s,e.ignoreArrayAtKeys))&&(n[s]=js(a,e))}),n}var ht=(r,e)=>{let t=Gr(r);return ht[t]?ht[t](r,e):r};ht.array=js;ht.object=Ls;Bs.exports=ht});import{isSameAddress as Di,MultiSigAccount as Ni,PublicKeySerde as Sn,SigningMessageHelper as Pi}from"@msafe/sui3-utils";var _e=class{constructor(e,t){this.globals=e;this.pkHelper=t}async getPublicKeyBatch(e){return this.pkHelper.getPublicKeyBatch(e)}async calculateMSafeAddress(e){let t=await this.reduceCreationInfoToRawConfig(e);return new Ni(t).address}async validateCreateInfo(e){return this.calculateMSafeAddress(e)}addPublicKey(e,t){let n=Sn.de(t);if(!Di(e,n.toSuiAddress()))throw new Error("Public key not match");this.pkHelper.addPublicKey(e,n)}async submitMSafeCreation(e){let t=await this.validateCreateInfo(e),n=Pi.createMSafeMessage(t),s=await this.globals.wallet.signPersonalMessage({messageStr:n});return await this.submitToBackend(e,s.signature),t}async reduceCreationInfoToRawConfig(e){let t=await this.getPublicKeyBatch(e.owners.map(n=>n.address));return t.forEach((n,s)=>{if(n===void 0)throw new Error(`Unknown public key for address: ${e.owners[s].address}`)}),{threshold:e.threshold,ownersWithWeight:e.owners.map((n,s)=>({publicKey:t[s],weight:n.weight})),creationNonce:e.creationNonce}}async submitToBackend(e,t){let n=await this.pkHelper.getPublicKeyBatch(e.owners.map(s=>s.address));await this.globals.backend.createMSafeAccount({owners:e.owners.map((s,a)=>({address:s.address,weight:s.weight,...Sn.ser(n[a])})),threshold:e.threshold,name:e.name,description:e.description,creationNonce:e.creationNonce,signature:t})}};import{SigningMessageHelper as Tl,UserMSafeStatus as Il}from"@msafe/sui3-utils";import{SigningMessageHelper as Fi}from"@msafe/sui3-utils";var We=class{constructor(e){this.globals=e}async getEntries(e){return this.globals.backend.getAddressBookEntries(e)}async update(e){let t=Fi.updateAddressBookMessage(e),n=await this.globals.wallet.signPersonalMessage({messageStr:t});return this.globals.backend.updateAddressBook({updates:e,signature:n.signature})}async getMode(){return(await this.globals.backend.getAddressBookMode()).mode}async setMode(e){return this.globals.backend.setAddressBookMode({mode:e})}};var yt=class{constructor(e){this.globals=e}async getMSafeByStatus(e,t){return this.globals.backend.getOwnedMSafeByStatus({status:e,pagination:t})}async updateMSafeStatus(e,t){return this.globals.backend.updateMSafeStatus({msafeAddress:e,status:t})}};import{TransactionType as wc}from"@msafe/sui3-utils";import{SuiClient as Dc}from"@mysten/sui.js/client";import ve,{AxiosError as Fc}from"axios";import{SUI_TYPE_ARG as _c,normalizeStructTag as Wc,normalizeSuiAddress as Hs}from"@mysten/sui.js/utils";import{normalizeStructTag as Yr,SUI_TYPE_ARG as jc}from"@mysten/sui.js/utils";var G=class extends Error{},wt=class extends G{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},St=class extends G{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},bt=class extends G{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},W=class extends G{},fe=class extends G{constructor(e){super(`Invalid unit ${e}`)}},I=class extends G{},j=class extends G{constructor(){super("Zone is an abstract class")}};var l="numeric",L="short",A="long",K={year:l,month:l,day:l},je={year:l,month:L,day:l},ir={year:l,month:L,day:l,weekday:L},Le={year:l,month:A,day:l},Be={year:l,month:A,day:l,weekday:A},qe={hour:l,minute:l},Ue={hour:l,minute:l,second:l},He={hour:l,minute:l,second:l,timeZoneName:L},Ve={hour:l,minute:l,second:l,timeZoneName:A},Ge={hour:l,minute:l,hourCycle:"h23"},ze={hour:l,minute:l,second:l,hourCycle:"h23"},$e={hour:l,minute:l,second:l,hourCycle:"h23",timeZoneName:L},Ze={hour:l,minute:l,second:l,hourCycle:"h23",timeZoneName:A},Ke={year:l,month:l,day:l,hour:l,minute:l},Ye={year:l,month:l,day:l,hour:l,minute:l,second:l},Je={year:l,month:L,day:l,hour:l,minute:l},Qe={year:l,month:L,day:l,hour:l,minute:l,second:l},or={year:l,month:L,day:l,weekday:L,hour:l,minute:l},Xe={year:l,month:A,day:l,hour:l,minute:l,timeZoneName:L},et={year:l,month:A,day:l,hour:l,minute:l,second:l,timeZoneName:L},tt={year:l,month:A,day:l,weekday:A,hour:l,minute:l,timeZoneName:A},rt={year:l,month:A,day:l,weekday:A,hour:l,minute:l,second:l,timeZoneName:A};var M=class{get type(){throw new j}get name(){throw new j}get ianaName(){return this.name}get isUniversal(){throw new j}offsetName(e,t){throw new j}formatOffset(e,t){throw new j}offset(e){throw new j}equals(e){throw new j}get isValid(){throw new j}};var cr=null,Y=class r extends M{static get instance(){return cr===null&&(cr=new r),cr}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return It(e,t,n)}formatOffset(e,t){return J(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var kt={};function Ri(r){return kt[r]||(kt[r]=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"})),kt[r]}var _i={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Wi(r,e){let t=r.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(t),[,s,a,i,o,c,u,d]=n;return[i,s,a,o,c,u,d]}function ji(r,e){let t=r.formatToParts(e),n=[];for(let s=0;s<t.length;s++){let{type:a,value:i}=t[s],o=_i[a];a==="era"?n[o]=i:h(o)||(n[o]=parseInt(i,10))}return n}var xt={},v=class r extends M{static create(e){return xt[e]||(xt[e]=new r(e)),xt[e]}static resetCache(){xt={},kt={}}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=r.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return It(e,t,n,this.name)}formatOffset(e,t){return J(this.offset(e),t)}offset(e){let t=new Date(e);if(isNaN(t))return NaN;let n=Ri(this.name),[s,a,i,o,c,u,d]=n.formatToParts?ji(n,t):Wi(n,t);o==="BC"&&(s=-Math.abs(s)+1);let g=pe({year:s,month:a,day:i,hour:c===24?0:c,minute:u,second:d,millisecond:0}),m=+t,x=m%1e3;return m-=x>=0?x:1e3+x,(g-m)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var bn={};function Li(r,e={}){let t=JSON.stringify([r,e]),n=bn[t];return n||(n=new Intl.ListFormat(r,e),bn[t]=n),n}var ur={};function lr(r,e={}){let t=JSON.stringify([r,e]),n=ur[t];return n||(n=new Intl.DateTimeFormat(r,e),ur[t]=n),n}var dr={};function Bi(r,e={}){let t=JSON.stringify([r,e]),n=dr[t];return n||(n=new Intl.NumberFormat(r,e),dr[t]=n),n}var mr={};function qi(r,e={}){let{base:t,...n}=e,s=JSON.stringify([r,n]),a=mr[s];return a||(a=new Intl.RelativeTimeFormat(r,e),mr[s]=a),a}var nt=null;function Ui(){return nt||(nt=new Intl.DateTimeFormat().resolvedOptions().locale,nt)}var Tn={};function Hi(r){let e=Tn[r];if(!e){let t=new Intl.Locale(r);e="getWeekInfo"in t?t.getWeekInfo():t.weekInfo,Tn[r]=e}return e}function Vi(r){let e=r.indexOf("-x-");e!==-1&&(r=r.substring(0,e));let t=r.indexOf("-u-");if(t===-1)return[r];{let n,s;try{n=lr(r).resolvedOptions(),s=r}catch{let c=r.substring(0,t);n=lr(c).resolvedOptions(),s=c}let{numberingSystem:a,calendar:i}=n;return[s,a,i]}}function Gi(r,e,t){return(t||e)&&(r.includes("-u-")||(r+="-u"),t&&(r+=`-ca-${t}`),e&&(r+=`-nu-${e}`)),r}function zi(r){let e=[];for(let t=1;t<=12;t++){let n=p.utc(2009,t,1);e.push(r(n))}return e}function $i(r){let e=[];for(let t=1;t<=7;t++){let n=p.utc(2016,11,13+t);e.push(r(n))}return e}function Ot(r,e,t,n){let s=r.listingMode();return s==="error"?null:s==="en"?t(e):n(e)}function Zi(r){return r.numberingSystem&&r.numberingSystem!=="latn"?!1:r.numberingSystem==="latn"||!r.locale||r.locale.startsWith("en")||new Intl.DateTimeFormat(r.intl).resolvedOptions().numberingSystem==="latn"}var hr=class{constructor(e,t,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:s,floor:a,...i}=n;if(!t||Object.keys(i).length>0){let o={useGrouping:!1,...n};n.padTo>0&&(o.minimumIntegerDigits=n.padTo),this.inf=Bi(e,o)}}format(e){if(this.inf){let t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{let t=this.floor?Math.floor(e):ge(e,3);return T(t,this.padTo)}}},fr=class{constructor(e,t,n){this.opts=n,this.originalZone=void 0;let s;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let i=-1*(e.offset/60),o=i>=0?`Etc/GMT+${i}`:`Etc/GMT${i}`;e.offset!==0&&v.create(o).valid?(s=o,this.dt=e):(s="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,s=e.zone.name):(s="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let a={...this.opts};a.timeZone=a.timeZone||s,this.dtf=lr(t,a)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(t=>{if(t.type==="timeZoneName"){let n=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...t,value:n}}else return t}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},pr=class{constructor(e,t,n){this.opts={style:"long",...n},!t&&Et()&&(this.rtf=qi(e,n))}format(e,t){return this.rtf?this.rtf.format(e,t):In(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}},Ki={firstDay:1,minimalDays:4,weekend:[6,7]},S=class r{static fromOpts(e){return r.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,t,n,s,a=!1){let i=e||y.defaultLocale,o=i||(a?"en-US":Ui()),c=t||y.defaultNumberingSystem,u=n||y.defaultOutputCalendar,d=st(s)||y.defaultWeekSettings;return new r(o,c,u,d,i)}static resetCache(){nt=null,ur={},dr={},mr={}}static fromObject({locale:e,numberingSystem:t,outputCalendar:n,weekSettings:s}={}){return r.create(e,t,n,s)}constructor(e,t,n,s,a){let[i,o,c]=Vi(e);this.locale=i,this.numberingSystem=t||o||null,this.outputCalendar=n||c||null,this.weekSettings=s,this.intl=Gi(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=a,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=Zi(this)),this.fastNumbersCached}listingMode(){let 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:r.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,st(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 Ot(this,e,gr,()=>{let n=t?{month:e,day:"numeric"}:{month:e},s=t?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=zi(a=>this.extract(a,n,"month"))),this.monthsCache[s][e]})}weekdays(e,t=!1){return Ot(this,e,yr,()=>{let n=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},s=t?"format":"standalone";return this.weekdaysCache[s][e]||(this.weekdaysCache[s][e]=$i(a=>this.extract(a,n,"weekday"))),this.weekdaysCache[s][e]})}meridiems(){return Ot(this,void 0,()=>wr,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[p.utc(2016,11,13,9),p.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return Ot(this,e,Sr,()=>{let t={era:e};return this.eraCache[e]||(this.eraCache[e]=[p.utc(-40,1,1),p.utc(2017,1,1)].map(n=>this.extract(n,t,"era"))),this.eraCache[e]})}extract(e,t,n){let s=this.dtFormatter(e,t),a=s.formatToParts(),i=a.find(o=>o.type.toLowerCase()===n);return i?i.value:null}numberFormatter(e={}){return new hr(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new fr(e,this.intl,t)}relFormatter(e={}){return new pr(this.intl,this.isEnglish(),e)}listFormatter(e={}){return Li(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Ct()?Hi(this.locale):Ki}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}};var Tr=null,k=class r extends M{static get utcInstance(){return Tr===null&&(Tr=new r(0)),Tr}static instance(e){return e===0?r.utcInstance:new r(e)}static parseSpecifier(e){if(e){let t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new r(ae(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${J(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${J(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return J(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}};var ye=class extends M{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 B(r,e){let t;if(h(r)||r===null)return e;if(r instanceof M)return r;if(xn(r)){let n=r.toLowerCase();return n==="default"?e:n==="local"||n==="system"?Y.instance:n==="utc"||n==="gmt"?k.utcInstance:k.parseSpecifier(n)||v.create(r)}else return V(r)?k.instance(r):typeof r=="object"&&"offset"in r&&typeof r.offset=="function"?r:new ye(r)}var kn=()=>Date.now(),On="system",En=null,Cn=null,vn=null,Mn=60,An,Dn=null,y=class{static get now(){return kn}static set now(e){kn=e}static set defaultZone(e){On=e}static get defaultZone(){return B(On,Y.instance)}static get defaultLocale(){return En}static set defaultLocale(e){En=e}static get defaultNumberingSystem(){return Cn}static set defaultNumberingSystem(e){Cn=e}static get defaultOutputCalendar(){return vn}static set defaultOutputCalendar(e){vn=e}static get defaultWeekSettings(){return Dn}static set defaultWeekSettings(e){Dn=st(e)}static get twoDigitCutoffYear(){return Mn}static set twoDigitCutoffYear(e){Mn=e%100}static get throwOnInvalid(){return An}static set throwOnInvalid(e){An=e}static resetCaches(){S.resetCache(),v.resetCache()}};var O=class{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var Nn=[0,31,59,90,120,151,181,212,243,273,304,334],Pn=[0,31,60,91,121,152,182,213,244,274,305,335];function F(r,e){return new O("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${r}, which is invalid`)}function vt(r,e,t){let n=new Date(Date.UTC(r,e-1,t));r<100&&r>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let s=n.getUTCDay();return s===0?7:s}function Fn(r,e,t){return t+(oe(r)?Pn:Nn)[e-1]}function Rn(r,e){let t=oe(r)?Pn:Nn,n=t.findIndex(a=>a<e),s=e-t[n];return{month:n+1,day:s}}function Mt(r,e){return(r-e+7)%7+1}function at(r,e=4,t=1){let{year:n,month:s,day:a}=r,i=Fn(n,s,a),o=Mt(vt(n,s,a),t),c=Math.floor((i-o+14-e)/7),u;return c<1?(u=n-1,c=ie(u,e,t)):c>ie(n,e,t)?(u=n+1,c=1):u=n,{weekYear:u,weekNumber:c,weekday:o,...ot(r)}}function Ir(r,e=4,t=1){let{weekYear:n,weekNumber:s,weekday:a}=r,i=Mt(vt(n,1,e),t),o=Q(n),c=s*7+a-i-7+e,u;c<1?(u=n-1,c+=Q(u)):c>o?(u=n+1,c-=Q(n)):u=n;let{month:d,day:f}=Rn(u,c);return{year:u,month:d,day:f,...ot(r)}}function At(r){let{year:e,month:t,day:n}=r,s=Fn(e,t,n);return{year:e,ordinal:s,...ot(r)}}function xr(r){let{year:e,ordinal:t}=r,{month:n,day:s}=Rn(e,t);return{year:e,month:n,day:s,...ot(r)}}function kr(r,e){if(!h(r.localWeekday)||!h(r.localWeekNumber)||!h(r.localWeekYear)){if(!h(r.weekday)||!h(r.weekNumber)||!h(r.weekYear))throw new W("Cannot mix locale-based week fields with ISO-based week fields");return h(r.localWeekday)||(r.weekday=r.localWeekday),h(r.localWeekNumber)||(r.weekNumber=r.localWeekNumber),h(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}}function _n(r,e=4,t=1){let n=it(r.weekYear),s=D(r.weekNumber,1,ie(r.weekYear,e,t)),a=D(r.weekday,1,7);return n?s?a?!1:F("weekday",r.weekday):F("week",r.weekNumber):F("weekYear",r.weekYear)}function Wn(r){let e=it(r.year),t=D(r.ordinal,1,Q(r.year));return e?t?!1:F("ordinal",r.ordinal):F("year",r.year)}function Or(r){let e=it(r.year),t=D(r.month,1,12),n=D(r.day,1,we(r.year,r.month));return e?t?n?!1:F("day",r.day):F("month",r.month):F("year",r.year)}function Er(r){let{hour:e,minute:t,second:n,millisecond:s}=r,a=D(e,0,23)||e===24&&t===0&&n===0&&s===0,i=D(t,0,59),o=D(n,0,59),c=D(s,0,999);return a?i?o?c?!1:F("millisecond",s):F("second",n):F("minute",t):F("hour",e)}function h(r){return typeof r>"u"}function V(r){return typeof r=="number"}function it(r){return typeof r=="number"&&r%1===0}function xn(r){return typeof r=="string"}function Ln(r){return Object.prototype.toString.call(r)==="[object Date]"}function Et(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Ct(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function Bn(r){return Array.isArray(r)?r:[r]}function Cr(r,e,t){if(r.length!==0)return r.reduce((n,s)=>{let a=[e(s),s];return n&&t(n[0],a[0])===n[0]?n:a},null)[1]}function qn(r,e){return e.reduce((t,n)=>(t[n]=r[n],t),{})}function X(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function st(r){if(r==null)return null;if(typeof r!="object")throw new I("Week settings must be an object");if(!D(r.firstDay,1,7)||!D(r.minimalDays,1,7)||!Array.isArray(r.weekend)||r.weekend.some(e=>!D(e,1,7)))throw new I("Invalid week settings");return{firstDay:r.firstDay,minimalDays:r.minimalDays,weekend:Array.from(r.weekend)}}function D(r,e,t){return it(r)&&r>=e&&r<=t}function Yi(r,e){return r-e*Math.floor(r/e)}function T(r,e=2){let t=r<0,n;return t?n="-"+(""+-r).padStart(e,"0"):n=(""+r).padStart(e,"0"),n}function z(r){if(!(h(r)||r===null||r===""))return parseInt(r,10)}function ee(r){if(!(h(r)||r===null||r===""))return parseFloat(r)}function ct(r){if(!(h(r)||r===null||r==="")){let e=parseFloat("0."+r)*1e3;return Math.floor(e)}}function ge(r,e,t=!1){let n=10**e;return(t?Math.trunc:Math.round)(r*n)/n}function oe(r){return r%4===0&&(r%100!==0||r%400===0)}function Q(r){return oe(r)?366:365}function we(r,e){let t=Yi(e-1,12)+1,n=r+(e-t)/12;return t===2?oe(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function pe(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}function jn(r,e,t){return-Mt(vt(r,1,e),t)+e-1}function ie(r,e=4,t=1){let n=jn(r,e,t),s=jn(r+1,e,t);return(Q(r)-n+s)/7}function ut(r){return r>99?r:r>y.twoDigitCutoffYear?1900+r:2e3+r}function It(r,e,t,n=null){let s=new Date(r),a={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(a.timeZone=n);let i={timeZoneName:e,...a},o=new Intl.DateTimeFormat(t,i).formatToParts(s).find(c=>c.type.toLowerCase()==="timezonename");return o?o.value:null}function ae(r,e){let t=parseInt(r,10);Number.isNaN(t)&&(t=0);let n=parseInt(e,10)||0,s=t<0||Object.is(t,-0)?-n:n;return t*60+s}function vr(r){let e=Number(r);if(typeof r=="boolean"||r===""||Number.isNaN(e))throw new I(`Invalid unit value ${r}`);return e}function Se(r,e){let t={};for(let n in r)if(X(r,n)){let s=r[n];if(s==null)continue;t[e(n)]=vr(s)}return t}function J(r,e){let t=Math.trunc(Math.abs(r/60)),n=Math.trunc(Math.abs(r%60)),s=r>=0?"+":"-";switch(e){case"short":return`${s}${T(t,2)}:${T(n,2)}`;case"narrow":return`${s}${t}${n>0?`:${n}`:""}`;case"techie":return`${s}${T(t,2)}${T(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function ot(r){return qn(r,["hour","minute","second","millisecond"])}var Ji=["January","February","March","April","May","June","July","August","September","October","November","December"],Mr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Qi=["J","F","M","A","M","J","J","A","S","O","N","D"];function gr(r){switch(r){case"narrow":return[...Qi];case"short":return[...Mr];case"long":return[...Ji];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}}var Ar=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Dr=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Xi=["M","T","W","T","F","S","S"];function yr(r){switch(r){case"narrow":return[...Xi];case"short":return[...Dr];case"long":return[...Ar];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var wr=["AM","PM"],eo=["Before Christ","Anno Domini"],to=["BC","AD"],ro=["B","A"];function Sr(r){switch(r){case"narrow":return[...ro];case"short":return[...to];case"long":return[...eo];default:return null}}function Un(r){return wr[r.hour<12?0:1]}function Hn(r,e){return yr(e)[r.weekday-1]}function Vn(r,e){return gr(e)[r.month-1]}function Gn(r,e){return Sr(e)[r.year<0?0:1]}function In(r,e,t="always",n=!1){let s={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."]},a=["hours","minutes","seconds"].indexOf(r)===-1;if(t==="auto"&&a){let f=r==="days";switch(e){case 1:return f?"tomorrow":`next ${s[r][0]}`;case-1:return f?"yesterday":`last ${s[r][0]}`;case 0:return f?"today":`this ${s[r][0]}`;default:}}let i=Object.is(e,-0)||e<0,o=Math.abs(e),c=o===1,u=s[r],d=n?c?u[1]:u[2]||u[1]:c?s[r][0]:r;return i?`${o} ${d} ago`:`in ${o} ${d}`}function zn(r,e){let t="";for(let n of r)n.literal?t+=n.val:t+=e(n.val);return t}var no={D:K,DD:je,DDD:Le,DDDD:Be,t:qe,tt:Ue,ttt:He,tttt:Ve,T:Ge,TT:ze,TTT:$e,TTTT:Ze,f:Ke,ff:Je,fff:Xe,ffff:tt,F:Ye,FF:Qe,FFF:et,FFFF:rt},E=class r{static create(e,t={}){return new r(e,t)}static parseFormat(e){let t=null,n="",s=!1,a=[];for(let i=0;i<e.length;i++){let o=e.charAt(i);o==="'"?(n.length>0&&a.push({literal:s||/^\s+$/.test(n),val:n}),t=null,n="",s=!s):s||o===t?n+=o:(n.length>0&&a.push({literal:/^\s+$/.test(n),val:n}),n=o,t=o)}return n.length>0&&a.push({literal:s||/^\s+$/.test(n),val:n}),a}static macroTokenToFormatOpts(e){return no[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){if(this.opts.forceSimple)return T(e,t);let n={...this.opts};return t>0&&(n.padTo=t),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,t){let n=this.loc.listingMode()==="en",s=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",a=(m,x)=>this.loc.extract(e,m,x),i=m=>e.isOffsetFixed&&e.offset===0&&m.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,m.format):"",o=()=>n?Un(e):a({hour:"numeric",hourCycle:"h12"},"dayperiod"),c=(m,x)=>n?Vn(e,m):a(x?{month:m}:{month:m,day:"numeric"},"month"),u=(m,x)=>n?Hn(e,m):a(x?{weekday:m}:{weekday:m,month:"long",day:"numeric"},"weekday"),d=m=>{let x=r.macroTokenToFormatOpts(m);return x?this.formatWithSystemDefault(e,x):m},f=m=>n?Gn(e,m):a({era:m},"era"),g=m=>{switch(m){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 i({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return i({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return i({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 o();case"d":return s?a({day:"numeric"},"day"):this.num(e.day);case"dd":return s?a({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return u("short",!0);case"cccc":return u("long",!0);case"ccccc":return u("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return u("short",!1);case"EEEE":return u("long",!1);case"EEEEE":return u("narrow",!1);case"L":return s?a({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return s?a({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return c("short",!0);case"LLLL":return c("long",!0);case"LLLLL":return c("narrow",!0);case"M":return s?a({month:"numeric"},"month"):this.num(e.month);case"MM":return s?a({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return c("short",!1);case"MMMM":return c("long",!1);case"MMMMM":return c("narrow",!1);case"y":return s?a({year:"numeric"},"year"):this.num(e.year);case"yy":return s?a({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return s?a({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return s?a({year:"numeric"},"year"):this.num(e.year,6);case"G":return f("short");case"GG":return f("long");case"GGGGG":return f("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 d(m)}};return zn(r.parseFormat(t),g)}formatDurationFromString(e,t){let n=c=>{switch(c[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},s=c=>u=>{let d=n(u);return d?this.num(c.get(d),u.length):u},a=r.parseFormat(t),i=a.reduce((c,{literal:u,val:d})=>u?c:c.concat(d),[]),o=e.shiftTo(...i.map(n).filter(c=>c));return zn(a,s(o))}};var Zn=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Te(...r){let e=r.reduce((t,n)=>t+n.source,"");return RegExp(`^${e}$`)}function Ie(...r){return e=>r.reduce(([t,n,s],a)=>{let[i,o,c]=a(e,s);return[{...t,...i},o||n,c]},[{},null,1]).slice(0,2)}function xe(r,...e){if(r==null)return[null,null];for(let[t,n]of e){let s=t.exec(r);if(s)return n(s)}return[null,null]}function Kn(...r){return(e,t)=>{let n={},s;for(s=0;s<r.length;s++)n[r[s]]=z(e[t+s]);return[n,null,t+s]}}var Yn=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,so=`(?:${Yn.source}?(?:\\[(${Zn.source})\\])?)?`,Nr=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Jn=RegExp(`${Nr.source}${so}`),Pr=RegExp(`(?:T${Jn.source})?`),ao=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,io=/(\d{4})-?W(\d\d)(?:-?(\d))?/,oo=/(\d{4})-?(\d{3})/,co=Kn("weekYear","weekNumber","weekDay"),uo=Kn("year","ordinal"),lo=/(\d{4})-(\d\d)-(\d\d)/,Qn=RegExp(`${Nr.source} ?(?:${Yn.source}|(${Zn.source}))?`),mo=RegExp(`(?: ${Qn.source})?`);function be(r,e,t){let n=r[e];return h(n)?t:z(n)}function ho(r,e){return[{year:be(r,e),month:be(r,e+1,1),day:be(r,e+2,1)},null,e+3]}function ke(r,e){return[{hours:be(r,e,0),minutes:be(r,e+1,0),seconds:be(r,e+2,0),milliseconds:ct(r[e+3])},null,e+4]}function lt(r,e){let t=!r[e]&&!r[e+1],n=ae(r[e+1],r[e+2]),s=t?null:k.instance(n);return[{},s,e+3]}function dt(r,e){let t=r[e]?v.create(r[e]):null;return[{},t,e+1]}var fo=RegExp(`^T?${Nr.source}$`),po=/^-?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 go(r){let[e,t,n,s,a,i,o,c,u]=r,d=e[0]==="-",f=c&&c[0]==="-",g=(m,x=!1)=>m!==void 0&&(x||m&&d)?-m:m;return[{years:g(ee(t)),months:g(ee(n)),weeks:g(ee(s)),days:g(ee(a)),hours:g(ee(i)),minutes:g(ee(o)),seconds:g(ee(c),c==="-0"),milliseconds:g(ct(u),f)}]}var yo={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function Fr(r,e,t,n,s,a,i){let o={year:e.length===2?ut(z(e)):z(e),month:Mr.indexOf(t)+1,day:z(n),hour:z(s),minute:z(a)};return i&&(o.second=z(i)),r&&(o.weekday=r.length>3?Ar.indexOf(r)+1:Dr.indexOf(r)+1),o}var wo=/^(?:(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 So(r){let[,e,t,n,s,a,i,o,c,u,d,f]=r,g=Fr(e,s,n,t,a,i,o),m;return c?m=yo[c]:u?m=0:m=ae(d,f),[g,new k(m)]}function bo(r){return r.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var To=/^(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$/,Io=/^(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$/,xo=/^(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 $n(r){let[,e,t,n,s,a,i,o]=r;return[Fr(e,s,n,t,a,i,o),k.utcInstance]}function ko(r){let[,e,t,n,s,a,i,o]=r;return[Fr(e,o,t,n,s,a,i),k.utcInstance]}var Oo=Te(ao,Pr),Eo=Te(io,Pr),Co=Te(oo,Pr),vo=Te(Jn),Xn=Ie(ho,ke,lt,dt),Mo=Ie(co,ke,lt,dt),Ao=Ie(uo,ke,lt,dt),Do=Ie(ke,lt,dt);function es(r){return xe(r,[Oo,Xn],[Eo,Mo],[Co,Ao],[vo,Do])}function ts(r){return xe(bo(r),[wo,So])}function rs(r){return xe(r,[To,$n],[Io,$n],[xo,ko])}function ns(r){return xe(r,[po,go])}var No=Ie(ke);function ss(r){return xe(r,[fo,No])}var Po=Te(lo,mo),Fo=Te(Qn),Ro=Ie(ke,lt,dt);function as(r){return xe(r,[Po,Xn],[Fo,Ro])}var is="Invalid Duration",cs={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},_o={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:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...cs},R=146097/400,Oe=146097/4800,Wo={years:{quarters:4,months:12,weeks:R/7,days:R,hours:R*24,minutes:R*24*60,seconds:R*24*60*60,milliseconds:R*24*60*60*1e3},quarters:{months:3,weeks:R/28,days:R/4,hours:R*24/4,minutes:R*24*60/4,seconds:R*24*60*60/4,milliseconds:R*24*60*60*1e3/4},months:{weeks:Oe/7,days:Oe,hours:Oe*24,minutes:Oe*24*60,seconds:Oe*24*60*60,milliseconds:Oe*24*60*60*1e3},...cs},ce=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],jo=ce.slice(0).reverse();function te(r,e,t=!1){let n={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 b(n)}function us(r,e){let t=e.milliseconds??0;for(let n of jo.slice(1))e[n]&&(t+=e[n]*r[n].milliseconds);return t}function os(r,e){let t=us(r,e)<0?-1:1;ce.reduceRight((n,s)=>{if(h(e[s]))return n;if(n){let a=e[n]*t,i=r[s][n],o=Math.floor(a/i);e[s]+=o*t,e[n]-=o*i*t}return s},null),ce.reduce((n,s)=>{if(h(e[s]))return n;if(n){let a=e[n]%1;e[n]-=a,e[s]+=a*r[n][s]}return s},null)}function Lo(r){let e={};for(let[t,n]of Object.entries(r))n!==0&&(e[t]=n);return e}var b=class r{constructor(e){let t=e.conversionAccuracy==="longterm"||!1,n=t?Wo:_o;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||S.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(e,t){return r.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new I(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new r({values:Se(e,r.normalizeUnit),loc:S.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(V(e))return r.fromMillis(e);if(r.isDuration(e))return e;if(typeof e=="object")return r.fromObject(e);throw new I(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){let[n]=ns(e);return n?r.fromObject(n,t):r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){let[n]=ss(e);return n?r.fromObject(n,t):r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new I("need to specify a reason the Duration is invalid");let n=e instanceof O?e:new O(e,t);if(y.throwOnInvalid)throw new bt(n);return new r({invalid:n})}static normalizeUnit(e){let 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 fe(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={}){let n={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?E.create(this.loc,n).formatDurationFromString(this,e):is}toHuman(e={}){if(!this.isValid)return is;let t=ce.map(n=>{let s=this.values[n];return h(s)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(s)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(t)}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+=ge(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},p.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?us(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let t=r.fromDurationLike(e),n={};for(let s of ce)(X(t.values,s)||X(this.values,s))&&(n[s]=t.get(s)+this.get(s));return te(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let t=r.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;let t={};for(let n of Object.keys(this.values))t[n]=vr(e(this.values[n],n));return te(this,{values:t},!0)}get(e){return this[r.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let t={...this.values,...Se(e,r.normalizeUnit)};return te(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:n,matrix:s}={}){let i={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:s,conversionAccuracy:n};return te(this,i)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return os(this.matrix,e),te(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Lo(this.normalize().shiftToAll().toObject());return te(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(i=>r.normalizeUnit(i));let t={},n={},s=this.toObject(),a;for(let i of ce)if(e.indexOf(i)>=0){a=i;let o=0;for(let u in n)o+=this.matrix[u][i]*n[u],n[u]=0;V(s[i])&&(o+=s[i]);let c=Math.trunc(o);t[i]=c,n[i]=(o*1e3-c*1e3)/1e3}else V(s[i])&&(n[i]=s[i]);for(let i in n)n[i]!==0&&(t[a]+=i===a?n[i]:n[i]/this.matrix[a][i]);return os(this.matrix,t),te(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;let e={};for(let t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return te(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(n,s){return n===void 0||n===0?s===void 0||s===0:n===s}for(let n of ce)if(!t(this.values[n],e.values[n]))return!1;return!0}};var Ee="Invalid Interval";function Bo(r,e){return!r||!r.isValid?$.invalid("missing or invalid start"):!e||!e.isValid?$.invalid("missing or invalid end"):e<r?$.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}var $=class r{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 I("need to specify a reason the Interval is invalid");let n=e instanceof O?e:new O(e,t);if(y.throwOnInvalid)throw new St(n);return new r({invalid:n})}static fromDateTimes(e,t){let n=Ce(e),s=Ce(t),a=Bo(n,s);return a??new r({start:n,end:s})}static after(e,t){let n=b.fromDurationLike(t),s=Ce(e);return r.fromDateTimes(s,s.plus(n))}static before(e,t){let n=b.fromDurationLike(t),s=Ce(e);return r.fromDateTimes(s.minus(n),s)}static fromISO(e,t){let[n,s]=(e||"").split("/",2);if(n&&s){let a,i;try{a=p.fromISO(n,t),i=a.isValid}catch{i=!1}let o,c;try{o=p.fromISO(s,t),c=o.isValid}catch{c=!1}if(i&&c)return r.fromDateTimes(a,o);if(i){let u=b.fromISO(s,t);if(u.isValid)return r.after(a,u)}else if(c){let u=b.fromISO(n,t);if(u.isValid)return r.before(o,u)}}return r.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 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;let n=this.start.startOf(e,t),s;return t?.useLocaleWeeks?s=this.end.reconfigure({locale:n.locale}):s=this.end,s=s.startOf(e,t),Math.floor(s.diff(n,e).get(e))+(s.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?r.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];let t=e.map(Ce).filter(i=>this.contains(i)).sort((i,o)=>i.toMillis()-o.toMillis()),n=[],{s}=this,a=0;for(;s<this.e;){let i=t[a]||this.e,o=+i>+this.e?this.e:i;n.push(r.fromDateTimes(s,o)),s=o,a+=1}return n}splitBy(e){let t=b.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s:n}=this,s=1,a,i=[];for(;n<this.e;){let o=this.start.plus(t.mapUnits(c=>c*s));a=+o>+this.e?this.e:o,i.push(r.fromDateTimes(n,a)),n=a,s+=1}return i}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;let t=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return t>=n?null:r.fromDateTimes(t,n)}union(e){if(!this.isValid)return this;let t=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return r.fromDateTimes(t,n)}static merge(e){let[t,n]=e.sort((s,a)=>s.s-a.s).reduce(([s,a],i)=>a?a.overlaps(i)||a.abutsStart(i)?[s,a.union(i)]:[s.concat([a]),i]:[s,i],[[],null]);return n&&t.push(n),t}static xor(e){let t=null,n=0,s=[],a=e.map(c=>[{time:c.s,type:"s"},{time:c.e,type:"e"}]),i=Array.prototype.concat(...a),o=i.sort((c,u)=>c.time-u.time);for(let c of o)n+=c.type==="s"?1:-1,n===1?t=c.time:(t&&+t!=+c.time&&s.push(r.fromDateTimes(t,c.time)),t=null);return r.merge(s)}difference(...e){return r.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()})`:Ee}[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=K,t={}){return this.isValid?E.create(this.s.loc.clone(t),e).formatInterval(this):Ee}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Ee}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Ee}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Ee}toFormat(e,{separator:t=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:Ee}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):b.invalid(this.invalidReason)}mapEndpoints(e){return r.fromDateTimes(e(this.s),e(this.e))}};var Z=class{static hasDST(e=y.defaultZone){let t=p.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return v.isValidZone(e)}static normalizeZone(e){return B(e,y.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||S.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||S.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||S.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null,outputCalendar:a="gregory"}={}){return(s||S.create(t,n,a)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null,outputCalendar:a="gregory"}={}){return(s||S.create(t,n,a)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null}={}){return(s||S.create(t,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null}={}){return(s||S.create(t,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return S.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return S.create(t,null,"gregory").eras(e)}static features(){return{relative:Et(),localeWeek:Ct()}}};function ls(r,e){let t=s=>s.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=t(e)-t(r);return Math.floor(b.fromMillis(n).as("days"))}function qo(r,e,t){let n=[["years",(c,u)=>u.year-c.year],["quarters",(c,u)=>u.quarter-c.quarter+(u.year-c.year)*4],["months",(c,u)=>u.month-c.month+(u.year-c.year)*12],["weeks",(c,u)=>{let d=ls(c,u);return(d-d%7)/7}],["days",ls]],s={},a=r,i,o;for(let[c,u]of n)t.indexOf(c)>=0&&(i=c,s[c]=u(r,e),o=a.plus(s),o>e?(s[c]--,r=a.plus(s),r>e&&(o=r,s[c]--,r=a.plus(s))):r=o);return[r,s,o,i]}function ds(r,e,t,n){let[s,a,i,o]=qo(r,e,t),c=e-s,u=t.filter(f=>["hours","minutes","seconds","milliseconds"].indexOf(f)>=0);u.length===0&&(i<e&&(i=s.plus({[o]:1})),i!==s&&(a[o]=(a[o]||0)+c/(i-s)));let d=b.fromObject(a,n);return u.length>0?b.fromMillis(c,n).shiftTo(...u).plus(d):d}var Rr={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"},ms={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]},Uo=Rr.hanidec.replace(/[\[|\]]/g,"").split("");function hs(r){let e=parseInt(r,10);if(isNaN(e)){e="";for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);if(r[t].search(Rr.hanidec)!==-1)e+=Uo.indexOf(r[t]);else for(let s in ms){let[a,i]=ms[s];n>=a&&n<=i&&(e+=n-a)}}return parseInt(e,10)}else return e}function _({numberingSystem:r},e=""){return new RegExp(`${Rr[r||"latn"]}${e}`)}var Ho="missing Intl.DateTimeFormat.formatToParts support";function w(r,e=t=>t){return{regex:r,deser:([t])=>e(hs(t))}}var Vo="\xA0",gs=`[ ${Vo}]`,ys=new RegExp(gs,"g");function Go(r){return r.replace(/\./g,"\\.?").replace(ys,gs)}function fs(r){return r.replace(/\./g,"").replace(ys," ").toLowerCase()}function q(r,e){return r===null?null:{regex:RegExp(r.map(Go).join("|")),deser:([t])=>r.findIndex(n=>fs(t)===fs(n))+e}}function ps(r,e){return{regex:r,deser:([,t,n])=>ae(t,n),groups:e}}function Dt(r){return{regex:r,deser:([e])=>e}}function zo(r){return r.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function $o(r,e){let t=_(e),n=_(e,"{2}"),s=_(e,"{3}"),a=_(e,"{4}"),i=_(e,"{6}"),o=_(e,"{1,2}"),c=_(e,"{1,3}"),u=_(e,"{1,6}"),d=_(e,"{1,9}"),f=_(e,"{2,4}"),g=_(e,"{4,6}"),m=H=>({regex:RegExp(zo(H.val)),deser:([he])=>he,literal:!0}),me=(H=>{if(r.literal)return m(H);switch(H.val){case"G":return q(e.eras("short"),0);case"GG":return q(e.eras("long"),0);case"y":return w(u);case"yy":return w(f,ut);case"yyyy":return w(a);case"yyyyy":return w(g);case"yyyyyy":return w(i);case"M":return w(o);case"MM":return w(n);case"MMM":return q(e.months("short",!0),1);case"MMMM":return q(e.months("long",!0),1);case"L":return w(o);case"LL":return w(n);case"LLL":return q(e.months("short",!1),1);case"LLLL":return q(e.months("long",!1),1);case"d":return w(o);case"dd":return w(n);case"o":return w(c);case"ooo":return w(s);case"HH":return w(n);case"H":return w(o);case"hh":return w(n);case"h":return w(o);case"mm":return w(n);case"m":return w(o);case"q":return w(o);case"qq":return w(n);case"s":return w(o);case"ss":return w(n);case"S":return w(c);case"SSS":return w(s);case"u":return Dt(d);case"uu":return Dt(o);case"uuu":return w(t);case"a":return q(e.meridiems(),0);case"kkkk":return w(a);case"kk":return w(f,ut);case"W":return w(o);case"WW":return w(n);case"E":case"c":return w(t);case"EEE":return q(e.weekdays("short",!1),1);case"EEEE":return q(e.weekdays("long",!1),1);case"ccc":return q(e.weekdays("short",!0),1);case"cccc":return q(e.weekdays("long",!0),1);case"Z":case"ZZ":return ps(new RegExp(`([+-]${o.source})(?::(${n.source}))?`),2);case"ZZZ":return ps(new RegExp(`([+-]${o.source})(${n.source})?`),2);case"z":return Dt(/[a-z_+-/]{1,256}?/i);case" ":return Dt(/[^\S\n\r]/);default:return m(H)}})(r)||{invalidReason:Ho};return me.token=r,me}var Zo={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 Ko(r,e,t){let{type:n,value:s}=r;if(n==="literal"){let c=/^\s+$/.test(s);return{literal:!c,val:c?" ":s}}let a=e[n],i=n;n==="hour"&&(e.hour12!=null?i=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?i="hour12":i="hour24":i=t.hour12?"hour12":"hour24");let o=Zo[i];if(typeof o=="object"&&(o=o[a]),o)return{literal:!1,val:o}}function Yo(r){return[`^${r.map(t=>t.regex).reduce((t,n)=>`${t}(${n.source})`,"")}$`,r]}function Jo(r,e,t){let n=r.match(e);if(n){let s={},a=1;for(let i in t)if(X(t,i)){let o=t[i],c=o.groups?o.groups+1:1;!o.literal&&o.token&&(s[o.token.val[0]]=o.deser(n.slice(a,a+c))),a+=c}return[n,s]}else return[n,{}]}function Qo(r){let e=a=>{switch(a){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}},t=null,n;return h(r.z)||(t=v.create(r.z)),h(r.Z)||(t||(t=new k(r.Z)),n=r.Z),h(r.q)||(r.M=(r.q-1)*3+1),h(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),h(r.u)||(r.S=ct(r.u)),[Object.keys(r).reduce((a,i)=>{let o=e(i);return o&&(a[o]=r[i]),a},{}),t,n]}var _r=null;function Xo(){return _r||(_r=p.fromMillis(1555555555555)),_r}function ec(r,e){if(r.literal)return r;let t=E.macroTokenToFormatOpts(r.val),n=Lr(t,e);return n==null||n.includes(void 0)?r:n}function Wr(r,e){return Array.prototype.concat(...r.map(t=>ec(t,e)))}function jr(r,e,t){let n=Wr(E.parseFormat(t),r),s=n.map(i=>$o(i,r)),a=s.find(i=>i.invalidReason);if(a)return{input:e,tokens:n,invalidReason:a.invalidReason};{let[i,o]=Yo(s),c=RegExp(i,"i"),[u,d]=Jo(e,c,o),[f,g,m]=d?Qo(d):[null,null,void 0];if(X(d,"a")&&X(d,"H"))throw new W("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:c,rawMatches:u,matches:d,result:f,zone:g,specificOffset:m}}}function ws(r,e,t){let{result:n,zone:s,specificOffset:a,invalidReason:i}=jr(r,e,t);return[n,s,a,i]}function Lr(r,e){if(!r)return null;let n=E.create(e,r).dtFormatter(Xo()),s=n.formatToParts(),a=n.resolvedOptions();return s.map(i=>Ko(i,r,a))}var Br="Invalid DateTime",Ss=864e13;function Nt(r){return new O("unsupported zone",`the zone "${r.name}" is not supported`)}function qr(r){return r.weekData===null&&(r.weekData=at(r.c)),r.weekData}function Ur(r){return r.localWeekData===null&&(r.localWeekData=at(r.c,r.loc.getMinDaysInFirstWeek(),r.loc.getStartOfWeek())),r.localWeekData}function ue(r,e){let t={ts:r.ts,zone:r.zone,c:r.c,o:r.o,loc:r.loc,invalid:r.invalid};return new p({...t,...e,old:t})}function Es(r,e,t){let n=r-e*60*1e3,s=t.offset(n);if(e===s)return[n,e];n-=(s-e)*60*1e3;let a=t.offset(n);return s===a?[n,s]:[r-Math.min(s,a)*60*1e3,Math.max(s,a)]}function Pt(r,e){r+=e*60*1e3;let 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()}}function Rt(r,e,t){return Es(pe(r),e,t)}function bs(r,e){let t=r.o,n=r.c.year+Math.trunc(e.years),s=r.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,a={...r.c,year:n,month:s,day:Math.min(r.c.day,we(n,s))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},i=b.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"),o=pe(a),[c,u]=Es(o,t,r.zone);return i!==0&&(c+=i,u=r.zone.offset(c)),{ts:c,o:u}}function mt(r,e,t,n,s,a){let{setZone:i,zone:o}=t;if(r&&Object.keys(r).length!==0||e){let c=e||o,u=p.fromObject(r,{...t,zone:c,specificOffset:a});return i?u:u.setZone(o)}else return p.invalid(new O("unparsable",`the input "${s}" can't be parsed as ${n}`))}function Ft(r,e,t=!0){return r.isValid?E.create(S.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(r,e):null}function Hr(r,e){let t=r.c.year>9999||r.c.year<0,n="";return t&&r.c.year>=0&&(n+="+"),n+=T(r.c.year,t?6:4),e?(n+="-",n+=T(r.c.month),n+="-",n+=T(r.c.day)):(n+=T(r.c.month),n+=T(r.c.day)),n}function Ts(r,e,t,n,s,a){let i=T(r.c.hour);return e?(i+=":",i+=T(r.c.minute),(r.c.millisecond!==0||r.c.second!==0||!t)&&(i+=":")):i+=T(r.c.minute),(r.c.millisecond!==0||r.c.second!==0||!t)&&(i+=T(r.c.second),(r.c.millisecond!==0||!n)&&(i+=".",i+=T(r.c.millisecond,3))),s&&(r.isOffsetFixed&&r.offset===0&&!a?i+="Z":r.o<0?(i+="-",i+=T(Math.trunc(-r.o/60)),i+=":",i+=T(Math.trunc(-r.o%60))):(i+="+",i+=T(Math.trunc(r.o/60)),i+=":",i+=T(Math.trunc(r.o%60)))),a&&(i+="["+r.zone.ianaName+"]"),i}var Cs={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},tc={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},rc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},vs=["year","month","day","hour","minute","second","millisecond"],nc=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],sc=["year","ordinal","hour","minute","second","millisecond"];function ac(r){let 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 fe(r);return e}function Is(r){switch(r.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return ac(r)}}function xs(r,e){let t=B(e.zone,y.defaultZone),n=S.fromObject(e),s=y.now(),a,i;if(h(r.year))a=s;else{for(let u of vs)h(r[u])&&(r[u]=Cs[u]);let o=Or(r)||Er(r);if(o)return p.invalid(o);let c=t.offset(s);[a,i]=Rt(r,c,t)}return new p({ts:a,zone:t,loc:n,o:i})}function ks(r,e,t){let n=h(t.round)?!0:t.round,s=(i,o)=>(i=ge(i,n||t.calendary?0:2,!0),e.loc.clone(t).relFormatter(t).format(i,o)),a=i=>t.calendary?e.hasSame(r,i)?0:e.startOf(i).diff(r.startOf(i),i).get(i):e.diff(r,i).get(i);if(t.unit)return s(a(t.unit),t.unit);for(let i of t.units){let o=a(i);if(Math.abs(o)>=1)return s(o,i)}return s(r>e?-0:0,t.units[t.units.length-1])}function Os(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]}var p=class r{constructor(e){let t=e.zone||y.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new O("invalid input"):null)||(t.isValid?null:Nt(t));this.ts=h(e.ts)?y.now():e.ts;let s=null,a=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[s,a]=[e.old.c,e.old.o];else{let o=t.offset(this.ts);s=Pt(this.ts,o),n=Number.isNaN(s.year)?new O("invalid input"):null,s=n?null:s,a=n?null:o}this._zone=t,this.loc=e.loc||S.create(),this.invalid=n,this.weekData=null,this.localWeekData=null,this.c=s,this.o=a,this.isLuxonDateTime=!0}static now(){return new r({})}static local(){let[e,t]=Os(arguments),[n,s,a,i,o,c,u]=t;return xs({year:n,month:s,day:a,hour:i,minute:o,second:c,millisecond:u},e)}static utc(){let[e,t]=Os(arguments),[n,s,a,i,o,c,u]=t;return e.zone=k.utcInstance,xs({year:n,month:s,day:a,hour:i,minute:o,second:c,millisecond:u},e)}static fromJSDate(e,t={}){let n=Ln(e)?e.valueOf():NaN;if(Number.isNaN(n))return r.invalid("invalid input");let s=B(t.zone,y.defaultZone);return s.isValid?new r({ts:n,zone:s,loc:S.fromObject(t)}):r.invalid(Nt(s))}static fromMillis(e,t={}){if(V(e))return e<-Ss||e>Ss?r.invalid("Timestamp out of range"):new r({ts:e,zone:B(t.zone,y.defaultZone),loc:S.fromObject(t)});throw new I(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(V(e))return new r({ts:e*1e3,zone:B(t.zone,y.defaultZone),loc:S.fromObject(t)});throw new I("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};let n=B(t.zone,y.defaultZone);if(!n.isValid)return r.invalid(Nt(n));let s=S.fromObject(t),a=Se(e,Is),{minDaysInFirstWeek:i,startOfWeek:o}=kr(a,s),c=y.now(),u=h(t.specificOffset)?n.offset(c):t.specificOffset,d=!h(a.ordinal),f=!h(a.year),g=!h(a.month)||!h(a.day),m=f||g,x=a.weekYear||a.weekNumber;if((m||d)&&x)throw new W("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(g&&d)throw new W("Can't mix ordinal dates with month/day");let me=x||a.weekday&&!m,H,he,Fe=Pt(c,u);me?(H=nc,he=tc,Fe=at(Fe,i,o)):d?(H=sc,he=rc,Fe=At(Fe)):(H=vs,he=Cs);let gn=!1;for(let Re of H){let ki=a[Re];h(ki)?gn?a[Re]=he[Re]:a[Re]=Fe[Re]:gn=!0}let bi=me?_n(a,i,o):d?Wn(a):Or(a),yn=bi||Er(a);if(yn)return r.invalid(yn);let Ti=me?Ir(a,i,o):d?xr(a):a,[Ii,xi]=Rt(Ti,u,n),sr=new r({ts:Ii,zone:n,o:xi,loc:s});return a.weekday&&m&&e.weekday!==sr.weekday?r.invalid("mismatched weekday",`you can't specify both a weekday of ${a.weekday} and a date of ${sr.toISO()}`):sr}static fromISO(e,t={}){let[n,s]=es(e);return mt(n,s,t,"ISO 8601",e)}static fromRFC2822(e,t={}){let[n,s]=ts(e);return mt(n,s,t,"RFC 2822",e)}static fromHTTP(e,t={}){let[n,s]=rs(e);return mt(n,s,t,"HTTP",t)}static fromFormat(e,t,n={}){if(h(e)||h(t))throw new I("fromFormat requires an input string and a format");let{locale:s=null,numberingSystem:a=null}=n,i=S.fromOpts({locale:s,numberingSystem:a,defaultToEN:!0}),[o,c,u,d]=ws(i,e,t);return d?r.invalid(d):mt(o,c,n,`format ${t}`,e,u)}static fromString(e,t,n={}){return r.fromFormat(e,t,n)}static fromSQL(e,t={}){let[n,s]=as(e);return mt(n,s,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new I("need to specify a reason the DateTime is invalid");let n=e instanceof O?e:new O(e,t);if(y.throwOnInvalid)throw new wt(n);return new r({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){let n=Lr(e,S.fromObject(t));return n?n.map(s=>s?s.val:null).join(""):null}static expandFormat(e,t={}){return Wr(E.parseFormat(e),S.fromObject(t)).map(s=>s.val).join("")}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?qr(this).weekYear:NaN}get weekNumber(){return this.isValid?qr(this).weekNumber:NaN}get weekday(){return this.isValid?qr(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?Ur(this).weekday:NaN}get localWeekNumber(){return this.isValid?Ur(this).weekNumber:NaN}get localWeekYear(){return this.isValid?Ur(this).weekYear:NaN}get ordinal(){return this.isValid?At(this.c).ordinal:NaN}get monthShort(){return this.isValid?Z.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Z.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Z.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Z.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];let e=864e5,t=6e4,n=pe(this.c),s=this.zone.offset(n-e),a=this.zone.offset(n+e),i=this.zone.offset(n-s*t),o=this.zone.offset(n-a*t);if(i===o)return[this];let c=n-i*t,u=n-o*t,d=Pt(c,i),f=Pt(u,o);return d.hour===f.hour&&d.minute===f.minute&&d.second===f.second&&d.millisecond===f.millisecond?[ue(this,{ts:c}),ue(this,{ts:u})]:[this]}get isInLeapYear(){return oe(this.year)}get daysInMonth(){return we(this.year,this.month)}get daysInYear(){return this.isValid?Q(this.year):NaN}get weeksInWeekYear(){return this.isValid?ie(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?ie(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:t,numberingSystem:n,calendar:s}=E.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:n,outputCalendar:s}}toUTC(e=0,t={}){return this.setZone(k.instance(e),t)}toLocal(){return this.setZone(y.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:n=!1}={}){if(e=B(e,y.defaultZone),e.equals(this.zone))return this;if(e.isValid){let s=this.ts;if(t||n){let a=e.offset(this.ts),i=this.toObject();[s]=Rt(i,a,e)}return ue(this,{ts:s,zone:e})}else return r.invalid(Nt(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:n}={}){let s=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:n});return ue(this,{loc:s})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let t=Se(e,Is),{minDaysInFirstWeek:n,startOfWeek:s}=kr(t,this.loc),a=!h(t.weekYear)||!h(t.weekNumber)||!h(t.weekday),i=!h(t.ordinal),o=!h(t.year),c=!h(t.month)||!h(t.day),u=o||c,d=t.weekYear||t.weekNumber;if((u||i)&&d)throw new W("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(c&&i)throw new W("Can't mix ordinal dates with month/day");let f;a?f=Ir({...at(this.c,n,s),...t},n,s):h(t.ordinal)?(f={...this.toObject(),...t},h(t.day)&&(f.day=Math.min(we(f.year,f.month),f.day))):f=xr({...At(this.c),...t});let[g,m]=Rt(f,this.o,this.zone);return ue(this,{ts:g,o:m})}plus(e){if(!this.isValid)return this;let t=b.fromDurationLike(e);return ue(this,bs(this,t))}minus(e){if(!this.isValid)return this;let t=b.fromDurationLike(e).negate();return ue(this,bs(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;let n={},s=b.normalizeUnit(e);switch(s){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break;case"milliseconds":break}if(s==="weeks")if(t){let a=this.loc.getStartOfWeek(),{weekday:i}=this;i<a&&(n.weekNumber=this.weekNumber-1),n.weekday=a}else n.weekday=1;if(s==="quarters"){let a=Math.ceil(this.month/3);n.month=(a-1)*3+1}return this.set(n)}endOf(e,t){return this.isValid?this.plus({[e]:1}).startOf(e,t).minus(1):this}toFormat(e,t={}){return this.isValid?E.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):Br}toLocaleString(e=K,t={}){return this.isValid?E.create(this.loc.clone(t),e).formatDateTime(this):Br}toLocaleParts(e={}){return this.isValid?E.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:n=!1,includeOffset:s=!0,extendedZone:a=!1}={}){if(!this.isValid)return null;let i=e==="extended",o=Hr(this,i);return o+="T",o+=Ts(this,i,t,n,s,a),o}toISODate({format:e="extended"}={}){return this.isValid?Hr(this,e==="extended"):null}toISOWeekDate(){return Ft(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:n=!0,includePrefix:s=!1,extendedZone:a=!1,format:i="extended"}={}){return this.isValid?(s?"T":"")+Ts(this,i==="extended",t,e,n,a):null}toRFC2822(){return Ft(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Ft(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Hr(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:n=!0}={}){let s="HH:mm:ss.SSS";return(t||e)&&(n&&(s+=" "),t?s+="z":e&&(s+="ZZ")),Ft(this,s,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():Br}[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{};let 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",n={}){if(!this.isValid||!e.isValid)return b.invalid("created by diffing an invalid DateTime");let s={locale:this.locale,numberingSystem:this.numberingSystem,...n},a=Bn(t).map(b.normalizeUnit),i=e.valueOf()>this.valueOf(),o=i?this:e,c=i?e:this,u=ds(o,c,a,s);return i?u.negate():u}diffNow(e="milliseconds",t={}){return this.diff(r.now(),e,t)}until(e){return this.isValid?$.fromDateTimes(this,e):this}hasSame(e,t,n){if(!this.isValid)return!1;let s=e.valueOf(),a=this.setZone(e.zone,{keepLocalTime:!0});return a.startOf(t,n)<=s&&s<=a.endOf(t,n)}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;let t=e.base||r.fromObject({},{zone:this.zone}),n=e.padding?this<t?-e.padding:e.padding:0,s=["years","months","days","hours","minutes","seconds"],a=e.unit;return Array.isArray(e.unit)&&(s=e.unit,a=void 0),ks(t,this.plus(n),{...e,numeric:"always",units:s,unit:a})}toRelativeCalendar(e={}){return this.isValid?ks(e.base||r.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(r.isDateTime))throw new I("min requires all arguments be DateTimes");return Cr(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(r.isDateTime))throw new I("max requires all arguments be DateTimes");return Cr(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,n={}){let{locale:s=null,numberingSystem:a=null}=n,i=S.fromOpts({locale:s,numberingSystem:a,defaultToEN:!0});return jr(i,e,t)}static fromStringExplain(e,t,n={}){return r.fromFormatExplain(e,t,n)}static get DATE_SHORT(){return K}static get DATE_MED(){return je}static get DATE_MED_WITH_WEEKDAY(){return ir}static get DATE_FULL(){return Le}static get DATE_HUGE(){return Be}static get TIME_SIMPLE(){return qe}static get TIME_WITH_SECONDS(){return Ue}static get TIME_WITH_SHORT_OFFSET(){return He}static get TIME_WITH_LONG_OFFSET(){return Ve}static get TIME_24_SIMPLE(){return Ge}static get TIME_24_WITH_SECONDS(){return ze}static get TIME_24_WITH_SHORT_OFFSET(){return $e}static get TIME_24_WITH_LONG_OFFSET(){return Ze}static get DATETIME_SHORT(){return Ke}static get DATETIME_SHORT_WITH_SECONDS(){return Ye}static get DATETIME_MED(){return Je}static get DATETIME_MED_WITH_SECONDS(){return Qe}static get DATETIME_MED_WITH_WEEKDAY(){return or}static get DATETIME_FULL(){return Xe}static get DATETIME_FULL_WITH_SECONDS(){return et}static get DATETIME_HUGE(){return tt}static get DATETIME_HUGE_WITH_SECONDS(){return rt}};function Ce(r){if(p.isDateTime(r))return r;if(r&&r.valueOf&&V(r.valueOf()))return p.fromJSDate(r);if(r&&typeof r=="object")return p.fromObject(r);throw new I(`Unknown datetime argument: ${r}, of type ${typeof r}`)}import{TransactionBlock as Wt}from"@mysten/sui.js/transactions";import{TransactionBlock as Vs}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as Gs,normalizeStructTag as Lc}from"@mysten/sui.js/utils";import{Buffer as Ks}from"buffer";import{normalizeSuiAddress as qc}from"@mysten/sui.js/utils";import{bcs as _a}from"@mysten/sui.js/bcs";import{normalizeStructTag as Ut}from"@mysten/sui.js/utils";var Ms=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");import{Transactions as Qs}from"@mysten/sui.js/transactions";import{normalizeStructTag as Xs,normalizeSuiAddress as Ht}from"@mysten/sui.js/utils";import{TransactionBlock as jt}from"@mysten/sui.js/transactions";import{normalizeStructTag as ea,parseStructTag as Jc}from"@mysten/sui.js/utils";var Qa=ar(_t(),1),ei=ar(_t(),1),Oh=ar(_t(),1);import{TransactionType as ku}from"@msafe/sui3-utils";import{TransactionType as Ou}from"@msafe/sui3-utils";import{TransactionType as Eu}from"@msafe/sui3-utils";import{bcs as fa}from"@mysten/sui.js/bcs";import{normalizeStructTag as Cu,normalizeSuiAddress as ft}from"@mysten/sui.js/utils";import{TransactionType as Au}from"@msafe/sui3-utils";import{TransactionDefaultApplication as Nu,TransactionSubTypes as Kr}from"@msafe/sui3-utils";import{buildCoinTransferTxb as Pu}from"@msafe/sui3-utils";import{buildObjectTransferTxb as Ru}from"@msafe/sui3-utils";import{isSameAddress as Wu}from"@msafe/sui3-utils";import{TransactionBlock as ju}from"@mysten/sui.js/transactions";import{TransactionSubTypes as Uu,TransactionType as Hu}from"@msafe/sui3-utils";import{TransactionBlock as Vu}from"@mysten/sui.js/transactions";import{fromHEX as Gu,toHEX as zu}from"@mysten/sui.js/utils";var yc=Object.defineProperty,ga=(r,e)=>{for(var t in e)yc(r,t,{get:e[t],enumerable:!0})},ya={};ga(ya,{contractId:()=>ba,default:()=>Sc,feeObjId:()=>xa,roleObjId:()=>Ta,status:()=>Sa,transaction:()=>wa,upgradeCapObjId:()=>ka,vaultObjId:()=>Ia});var wa="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Sa="success",ba="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Ta="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Ia="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",xa="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",ka="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Sc={transaction:wa,status:Sa,contractId:ba,roleObjId:Ta,vaultObjId:Ia,feeObjId:xa,upgradeCapObjId:ka},Oa={};ga(Oa,{contractId:()=>va,default:()=>bc,feeObjId:()=>Da,roleObjId:()=>Ma,status:()=>Ca,transaction:()=>Ea,upgradeCapObjId:()=>Na,vaultObjId:()=>Aa});var Ea="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Ca="success",va="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",Ma="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Aa="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",Da="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Na="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",bc={transaction:Ea,status:Ca,contractId:va,roleObjId:Ma,vaultObjId:Aa,feeObjId:Da,upgradeCapObjId:Na},Tc="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Ic="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",xc="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",kc="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Oc="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Ec="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Cc="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",vc="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",qs=ya,Us=Oa,Mc=new Map([["dev",{env:"dev",rpc:{url:Tc},backend:{url:Oc},contract:qs}],["stg",{env:"stg",rpc:{url:Ic},backend:{url:Ec},contract:qs}],["prev",{env:"prev",rpc:{url:xc},backend:{url:Cc},contract:Us}],["prod",{env:"prod",rpc:{url:kc},backend:{url:vc},contract:Us}]]);function Ac(r,e){let t=Mc.get(r);if(!t)throw new Error(`Env not supported: ${r}`);return e&&e.rpc&&(t.rpc=e.rpc),e&&e.backend&&(t.backend=e.backend),e&&e.contract&&(t.contract=e.contract),t}var P=class extends Error{mpayErrorCode;context;constructor(r,e,t={}){let{cause:n,context:s}=t;n?super(`[MPay] ${e}: ${n}`):super(`[MPay] ${e}`),this.mpayErrorCode=r,this.context=s}},Nc=class extends P{constructor(){super(11,"Backend is not specified")}},Pc=class extends P{constructor(){super(1,"Wallet not connected")}},zr=class extends P{constructor(r,e){super(10,r,{context:e})}},Rc=class de{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof Fc)throw new zr(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new zr(e.data.code)}throw new zr(e.status.toString())}async getIncomingStreams(e,t){let n=await ve.post(`${this.apiURL}/stream`,{recipient:e,...t});return de.parseResponseData(n)}async getOutgoingStreams(e,t){let n=await ve.post(`${this.apiURL}/stream`,{sender:e,...t});return de.parseResponseData(n)}async getStreamHistory(e){let t=await ve.post(`${this.apiURL}/stream-events`,e),n=de.parseResponseData(t);return n.data.forEach(s=>{let a=s;return a.data.type==="create_stream"?a.data.balance=BigInt(a.data.balance):a.data.type==="cancel_stream"?a.data.withdrawAmount=BigInt(a.data.withdrawAmount):a.data.type==="claim"||a.data.type==="auto_claim"?a.data.claimAmount=BigInt(a.data.claimAmount):a.data.type==="set_auto_claim"&&(a.data.enabled=!!a.data.enabled),a.createdAt=new Date(a.createdAt),a}),n}async getAllCoinTypes(e){let t=await ve.post(`${this.apiURL}/stream-info`,{address:e});return de.parseResponseData(t)}async getAllRecipients(e,t){let n=await ve.post(`${this.apiURL}/stream-info`,{sender:e,status:t});return de.parseResponseData(n)}async getAllSenders(e,t){let n=await ve.post(`${this.apiURL}/stream-info`,{recipient:e,status:t});return de.parseResponseData(n)}},Pa=class Fa{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Dc({url:e.rpc.url}),e.backend&&(this._backend=new Rc(e.backend.url))}static new(e,t){let n=Ac(e,t);return new Fa(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new Nc;return this._backend}set backend(e){this._backend=e}connectWallet(e){this.signer=e}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new Pc;return this.signer}async walletAddress(){return this.wallet.address()}},zs=50n,$r=10000n,Bc=25n,$s=100000000n,le=class{constructor(r){this.object=r}moveArg(r){return r.object(this.object)}},Zs=class{constructor(r){this.objects=r}moveArgs(r){return r.makeMoveVec({objects:this.objects.map(e=>r.object(e))})}},qt=class Ra{constructor(e){return this.result=e,new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(t,n){if(n in t)return Reflect.get(t,n);let s=i=>new Ra(t.result[i]);if(n===Symbol.iterator)return function*(){let i=0;for(;;)yield s(i),i++};if(typeof n=="symbol")return;let a=parseInt(n,10);if(!(Number.isNaN(a)||a<0))return s(a)}})}moveArg(){return this.result}},Ys=class extends P{constructor(r,e){super(3,r,{context:e})}},Uc=class{constructor(r){this.results=r}callResult(r){return this.results.results[r]}returnValue(r,e){return r.returnValues[e]}getValue(r=0,e=0){let t=this.callResult(r);return this.returnValue(t,e)}getAddress(r=0,e=0){let[t,n]=this.getValue(r,e);if(n!=="address")throw new Ys("Invalid contract return type.",{ctx:{expectType:"address",gotType:n}});return qc(Ks.from(t).toString("hex"))}getU64(r=0,e=0){let[t,n]=this.getValue(r,e);if(n!=="u64")throw new Ys("Invalid contract return type.",{ctx:{expectType:"u64",gotType:n}});return Ks.from(t).readBigInt64LE()}},N=class extends P{constructor(r,e,t){super(2,`Invalid input: ${r}`,{context:{fieldKey:e,fieldValue:t}})}},Wa={groupId:"string",name:"string"},Hc=64;function Vc(r){return ja(r),_a.ser(Wa,r).toString("base64")}function Jr(r){let e=_a.de(Wa,r,"base64");return ja(e),e}function ja(r){if(!Js(r.name))throw new N("Invalid metadata: Name contains unknown character");if(!Js(r.groupId))throw new N("Invalid metadata: Group ID contains unknown character");if(r.name.length>Hc)throw new N("Invalid metadata: Name exceed max length 64")}function Js(r){return/^[\x00-\x7F]+$/.test(r)}function La(r,e){return Ut(r)===Ut(e)}function Me(r,e){return Ut(r)===Ut(e)}var Ba="txn.gas";function Gc(){return Ms()}var Qr=class qa{constructor(e,t,n){this.globals=e,this.feeContract=t,this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:Vc({name:e.name,groupId:Gc()}),coinType:Lc(e.coinType),recipients:e.recipients.map(t=>({address:t.address,cliffAmount:t.cliffAmount,amountPerEpoch:t.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let t=new Vs,n=this.calculateFeesInternal(e),s=this.getCreateStreamCoinRequests(e,n),a=await this.wallet.requestCoins(s),i=await this.addMergeCoins(t,a[0]),o;s.length>1?o=await this.addMergeCoins(t,a[1]):o=i;for(let c=0;c<e.recipients.length;c++){let u=e.recipients[c],d=this.amountForRecipient(u,e.numberEpoch),f=this.getStreamFeeLocal(d),[g]=t.splitCoins(i,[t.pure(d+f,"u64")]),[m]=t.splitCoins(o,[t.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(t,{paymentCoin:new qt(g),flatFeeCoin:new qt(m),metadata:e.metadata,recipient:u.address,timeStart:e.startTime,cliff:u.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:u.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return t}calculateCreateStreamFees(e){let t=qa.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(t)}feeParams(){return{createFeePercent:{numerator:zs,denominator:$r},claimFeePercent:{numerator:Bc,denominator:$r},flatFeePerStream:$s}}async addMergeCoins(e,t){let n;return t.mergedCoins&&t.mergedCoins.length?(e.mergeCoins(e.object(t.primaryCoin),t.mergedCoins.map(s=>e.object(s))),n=e.object(t.primaryCoin)):t.primaryCoin===Ba?n=e.gas:n=e.object(t.primaryCoin),n}getCreateStreamCoinRequests(e,t){let n=e.coinType;return La(n,Gs)?[{coinType:n,amount:t.totalAmount+t.streamFeeAmount+t.flatFeeAmount}]:[{coinType:n,amount:t.totalAmount+t.streamFeeAmount},{coinType:Gs,amount:t.flatFeeAmount}]}calculateFeesInternal(e){let t=e.recipients.reduce((n,s)=>{let a=this.amountForRecipient(s,e.numberEpoch),i=this.getStreamFeeLocal(a);return{totalAmount:n.totalAmount+a,streamFeeAmount:n.streamFeeAmount+i}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...t}}amountForRecipient(e,t){return BigInt(e.amountPerEpoch)*BigInt(t)+BigInt(e.cliffAmount)}get flatSuiFee(){return $s}getStreamFeeLocal(e){return e*zs/$r}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new Vs,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:t});return new Uc(n).getU64()}get wallet(){return this.globals.wallet}},zc="0x0000000000000000000000000000000000000000000000000000000000000006",Ua=class{constructor(r,e,t){this.moduleName=r,this.config=e,this.globals=t}addContractCall(r,e){let t=`${this.config.contractId}::${this.moduleName}::${e.method}`;return r.add(Qs.MoveCall({target:t,arguments:e.arguments.map(n=>n instanceof Zs?n.moveArgs(r):n instanceof le?n.moveArg(r):n instanceof qt?n.moveArg():r.pure(n)),typeArguments:e.typeArgs})),r}addTransactionBlock(r,e,t=[],n=[]){r.add(Qs.MoveCall({target:e,arguments:t.map(s=>s instanceof Zs?s.moveArgs(r):s instanceof le?s.moveArg(r):s instanceof qt?s.moveArg():r.pure(s)),typeArguments:n}))}makeObject(r){return typeof r=="string"?new le(r):r}vaultObject(){return new le(this.config.vaultObjId)}roleObject(){return new le(this.config.roleObjId)}feeObject(){return new le(this.config.feeObjId)}clockObject(){return new le(zc)}},Ha=class re extends Ua{constructor(e,t){super(re.ModuleName,e,t),this.config=e,this.globals=t}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,t){let n=this.roleObject(),s=this.feeObject();return this.addContractCall(e,{method:re.MethodName.set_streaming_fee,arguments:[n,s,t],typeArgs:[]})}setStreamingFlatFee(e,t){let n=this.roleObject(),s=this.feeObject();return this.addContractCall(e,{method:re.MethodName.set_streaming_flat_fee,arguments:[n,s,t],typeArgs:[]})}setClaimFee(e,t){let n=this.roleObject(),s=this.feeObject();return this.addContractCall(e,{method:re.MethodName.set_claim_fee,arguments:[n,s,t],typeArgs:[]})}streamingFee(e,t){let n=this.feeObject();return this.addContractCall(e,{method:re.MethodName.streaming_fee,arguments:[n,t],typeArgs:[]})}claimFee(e,t){return this.addContractCall(e,{method:re.MethodName.claim_fee,arguments:[this.feeObject(),t],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:re.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},Gt=class C extends Ua{constructor(e,t){super(C.ModuleName,e,t),this.config=e,this.globals=t}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,t){let n=this.feeObject(),s=this.vaultObject(),a=this.makeObject(t.paymentCoin),i=this.makeObject(t.flatFeeCoin),o=this.clockObject();return this.addContractCall(e,{method:C.MethodName.create_stream,arguments:[n,s,a,i,t.metadata,t.recipient,t.timeStart,t.cliff,t.epochInterval,t.numEpoch,t.amountPerEpoch,t.cancelable,o],typeArgs:[t.coinType]})}setAutoClaim(e,t){let n=this.makeObject(t.streamId);return this.addContractCall(e,{method:C.MethodName.set_auto_claim,arguments:[n,t.enabled],typeArgs:[t.coinType]})}cancelStream(e,t){let n=this.makeObject(t.streamId),s=this.clockObject();return this.addContractCall(e,{method:C.MethodName.cancel_stream,arguments:[n,s],typeArgs:[t.coinType]})}claimStream(e,t){let n=this.makeObject(t.streamId),s=this.clockObject();return this.addContractCall(e,{method:C.MethodName.claim_stream,arguments:[n,s],typeArgs:[t.coinType]})}claimStreamByProxy(e,t){let n=this.makeObject(t.streamId),s=this.vaultObject(),a=this.feeObject(),i=this.clockObject();return this.addContractCall(e,{method:C.MethodName.claim_stream_by_proxy,arguments:[n,s,a,i],typeArgs:[t.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${C.ModuleName}::${C.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${C.ModuleName}::${C.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${C.ModuleName}::${C.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${C.ModuleName}::${C.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${C.ModuleName}::${C.MethodName.claim_stream_by_proxy}`}},Va=class{constructor(r){this.globals=r;let e=r.envConfig.contract;this.feeContract=new Ha(e,r),this.streamContract=new Gt(e,r)}feeContract;streamContract;async createStreams(r){let e=Qr.convertCreateStreamInfoToInternal(r);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new Qr(this.globals,this.feeContract,this.streamContract)}setAutoClaim(r,e,t){let n=new Wt;return this.streamContract.setAutoClaim(n,{streamId:r,enabled:e,coinType:t})}claimStream(r,e){let t=new Wt;return this.streamContract.claimStream(t,{streamId:r,coinType:e})}claimStreamByProxy(r,e){let t=new Wt;return this.streamContract.claimStreamByProxy(t,{streamId:r,coinType:e})}cancelStream(r,e){let t=new Wt;return this.streamContract.cancelStream(t,{streamId:r,coinType:e}),t}},$c=class extends P{constructor(r,e){super(12,`Transaction failed: ${e}`,{context:{status:r,msg:e}})}},Zc=1e3,Kc=class{constructor(r){this.globals=r,this.coinMetaHelper=new Yc(r.suiClient),this.createStreamHelper=new Va(r).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(r){if(r.effects?.status.status!=="success")throw new $c(r.effects?.status.status,r.effects?.status.error);return r.objectChanges.filter(e=>e.type==="created"&&e.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(e=>e.objectId)}calculateCreateStreamFees(r){return this.createStreamHelper.calculateCreateStreamFees(r)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(r){if(r.steps===0n)throw new N("Invalid stream steps: 0");let e=r.cliff?r.cliff:{numerator:0n,denominator:100n},t=r.totalAmount*e.numerator/e.denominator,n=(r.totalAmount-t)/r.steps,s={realTotalAmount:n*r.steps+t,cliffAmount:t,amountPerStep:n};return this.validateStreamAmount(s,r.totalAmount),s}calculateTimelineByInterval(r){if(r.steps===0n)throw new N("Invalid stream steps: 0");let e=r.timeStart.plus(r.interval.toMillis()*Number(r.steps)),t={timeStart:r.timeStart,timeEnd:e,interval:r.interval,steps:r.steps};return this.validateTimeline(t),t}calculateTimelineByTotalDuration(r){if(r.steps===0n)throw new N("Invalid stream steps: 0");let e=BigInt(r.total.toMillis())/r.steps,t=r.timeStart.plus(b.fromMillis(Number(e*r.steps))),n={timeStart:r.timeStart,timeEnd:t,interval:b.fromMillis(Number(e)),steps:r.steps};return this.validateTimeline(n),n}async getBalance(r,e){let t=await this.globals.suiClient.getBalance({owner:r,coinType:e}),n=await this.getCoinMeta(e);return{...t,coinType:Yr(t.coinType),coinMeta:n}}async getAllBalance(r){let e=await this.globals.suiClient.getAllBalances({owner:r}),t=await Promise.all(e.map(n=>this.getCoinMeta(n.coinType)));return e.map((n,s)=>({...n,coinType:Yr(n.coinType),coinMeta:t[s]}))}async getCoinMeta(r){return this.coinMetaHelper.getCoinMeta(r)}async simulateTransactionBlock(r){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:r,sender:await this.globals.wallet.address()})}validateStreamAmount(r,e){if(r.amountPerStep===0n)throw new N("Stream amount too small","totalAmount",e);if(r.cliffAmount>r.realTotalAmount)throw new N("Invalid cliff settings")}validateTimeline(r){if(r.interval.toMillis()<Zc)throw new N("Interval shall be at least 1 second","interval",r.interval)}},Yc=class{constructor(r){this.suiClient=r,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(r){let e=Yr(r||jc);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let t=await this.queryCoinMeta(e);return t&&this.coinMetaReg.set(e,t),t}async queryCoinMeta(r){return await this.suiClient.getCoinMetadata({coinType:r})||void 0}},Qc=class extends P{constructor(){super(7,"Connected wallet is not creator")}},ta=class extends P{constructor(){super(8,"Connected wallet is not recipient")}},ra=class extends P{constructor(r,e){super(6,r,{context:e})}},U=class extends P{constructor(r,e={}){super(0,r,e)}},Xc=class extends P{constructor(r){super(5,"Stream not found",{context:{streamId:r}})}},eu=(1n<<64n)-1n,Vt=1e3;function na(r){let e;typeof r=="number"?e=r:typeof r=="bigint"?e=Number(r):e=r.toMillis();let t=Math.round(e/Vt);return p.fromMillis(t*Vt)}function sa(r){let e;typeof r=="number"?e=r:typeof r=="bigint"?e=Number(r):e=r.toMillis();let t=Math.round(e/Vt);return b.fromMillis(t*Vt)}var rn=class ne{constructor(e,t,n){this.globals=e,this.streamId=t,this.rawData=n,this.streamContract=new Gt(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,t){let n=await ne.fetchStreamData(e,t);return new ne(e,t,n)}static fromObjectData(e,t,n){let s=ne.parseRawStreamData(t,n);return new ne(e,t,s)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await ne.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new U("Object Id does not align");this.rawData=ne.parseRawStreamData(this.streamId,e)}async historyEvents(e){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:e})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new Qc;let e=new jt;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new ta;let e=new jt;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new ta;let t=new jt;return this.streamContract.setAutoClaim(t,{streamId:this.streamId,coinType:this.coinType,enabled:e}),t}async claimByProxy(){let e=new jt;return this.streamContract.claimStreamByProxy(e,{streamId:this.streamId,coinType:this.coinType}),e}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return ea(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return sa(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return Jr(e).groupId}get name(){let{metadata:e}=this.rawData.config;return Jr(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return na(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return sa(t)}get timeEnd(){return this.timeStart.plus(this.duration)}get totalSteps(){return this.rawData.config.totalEpoch}get claimable(){return this.streamedAmount-this.claimedAmount}get nextReleaseDate(){return this.currentEpoch===-1n?this.timeStart:this.currentEpoch>=this.totalSteps||this.isCanceled?null:na((this.currentEpoch+1n)*this.rawData.config.epochInterval+this.rawData.config.timeStart)}get nextReleaseAmount(){return this.currentEpoch===-1n?this.cliff:this.currentEpoch>=this.totalSteps||this.isCanceled?null:this.amountPerEpoch}get streamStatus(){let e=this.rawData.status.status;return e===16?"CANCELED":e===17?"SETTLED":e===1?"COMPLETED":this.currentEpoch>=this.totalSteps?"STREAMED":"STREAMING"}get streamedAmount(){return this.currentEpoch===-1n?0n:this.isCanceled?this.rawData.status.epochCanceled*this.amountPerEpoch+this.cliff:this.currentEpoch*this.amountPerEpoch+this.cliff}get claimedAmount(){return this.rawData.status.epochClaimed===eu?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=p.now().toMillis(),t=this.timeStart.toMillis();if(e<t)return-1n;let n=Math.floor((e-t)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,t){let n=await e.suiClient.getObject({id:t,options:{showContent:!0,showType:!0}});return ne.parseRawStreamData(t,n)}static parseRawStreamData(e,t){if(t.error)throw t.error.code==="notExists"?new Xc(e):new ra(`get stream data: ${t.error.code}`,{streamId:e,...t.error});let n=t.data.content;if(n.dataType!=="moveObject")throw new ra("Unexpected object type",{gotType:n.dataType});let{typeParams:s}=Jc(n.type),a=ea(s[0]),i=n.fields,o=i.config.fields,c=i.status.fields;return{coinType:a,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(o.amount_per_epoch),cancelable:o.cancelable,cliff:BigInt(o.cliff),creator:o.creator,epochInterval:BigInt(o.epoch_interval),metadata:o.metadata,recipient:o.recipient,timeStart:BigInt(o.time_start),totalEpoch:BigInt(o.total_epoch)},status:{status:c.status,epochCanceled:BigInt(c.epoch_canceled),epochClaimed:BigInt(c.epoch_claimed)}}}},Zr=class extends P{constructor(r,e){super(9,`Invalid stream group: ${r}`,{context:e})}};async function tu(r){let e=[];for(;await r.hasNext();){let t=await r.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var ru=class{constructor(r){this.requester=r,this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},Ga=class{constructor(r){this.requester=r,this.pager=new ru(r),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}},nu=25;async function aa(r,e,t){let n=new za(e),s=new $a(r,n,t);return await tu(s)}var za=class{constructor(r){this.ids=r,this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},$a=class extends Ga{constructor(r,e,t){super(new su(r,e,t)),this.suiClient=r,this.idIter=e,this.options=t}},su=class{constructor(r,e,t){this.suiClient=r,this.stringIter=e,this.options=t,this.filter=t?.filter,this.pageSize=t?.pageSize||nu,this.objectOptions=t?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let r=[];for(;r.length<this.pageSize&&await this.stringIter.hasNext();){let n=await this.stringIter.next();n&&r.push(n)}let e=await this.suiClient.multiGetObjects({ids:r,options:this.objectOptions}),t;if(this.filter){let{filter:n}=this;t=e.filter(s=>n?.(s))}else t=e;return{data:t,hasNext:await this.stringIter.hasNext()}}},au=class Lt{constructor(e,t){if(this.globals=e,this.streams=t,t.length===0)throw new Zr("stream size 0");let n=t.map(s=>s.groupId);if(new Set(n).size!==1)throw new N("Stream does not have same group ID")}type="StreamGroup";static async new(e,t){let n=await aa(e.suiClient,t);return n.forEach(s=>{if(!s)throw new U("stream group object data undefined")}),Lt.newFromObjectResponse(e,t,n)}static async newFromObjectResponse(e,t,n){let s=await Lt.parseGroupStreams(e,t,n);return new Lt(e,s)}static checkStreamGroup(e){let t=e.map(a=>a.groupCommonInfo),n=t[0],s=!0;return t.forEach(a=>{iu(n,a)||(s=!1)}),s}async refresh(){let e=await aa(this.globals.suiClient,this.streams.map(t=>t.streamId));this.streams.forEach((t,n)=>{t.refreshWithData(e[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(e=>e.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((e,t)=>e+t.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,t)=>e+t.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,t)=>t.nextReleaseAmount===null?e:e+t.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,t)=>e+t.totalAmount,0n),streamed:this.streams.reduce((e,t)=>e+t.streamedAmount,0n),claimed:this.streams.reduce((e,t)=>e+t.claimedAmount,0n),claimable:this.streams.reduce((e,t)=>e+t.claimable,0n),canceled:this.streams.reduce((e,t)=>e+t.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,t,n){let s=n.map((a,i)=>rn.fromObjectData(e,t[i],a)).filter(a=>!!a);if(new Set(s.map(a=>a.groupId)).size!==1)throw new Zr("Not same group ID");if(!this.checkStreamGroup(s))throw new Zr("Not same stream settings");return s}};function iu(r,e){return r.name===e.name&&r.groupId===e.groupId&&r.creator===e.creator&&r.start.toMillis()===e.start.toMillis()&&r.interval.toMillis()===e.interval.toMillis()&&r.steps===e.steps&&r.cancelable===e.cancelable}var ia=class Xr{constructor(e,t){this.it=e,this.pageSize=t}static async newIncoming(e){let t=await oa.newIncoming(e);return new Xr(t,e.pageSize)}static async newOutgoing(e){let t=await oa.newOutgoing(e);return new Xr(t,e.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let e=[];for(;e.length<this.pageSize&&await this.it.hasNext();)e.push(await this.it.next());return e}},oa=class en{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let t=await ca.newIncomingQuery(e);return new en(t)}static async newOutgoing(e){let t=await ca.newOutgoingQuery(e);return new en(t)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let t=await this.requester.doNextRequest();if(t===null)throw new U("No more results");return t}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new U("No more results");return e}},ca=class tn{constructor(e,t,n,s){this.globals=e,this.recipient=t,this.groupRefs=n,this.query=s,this.current=0;let a=new za(n.flat().map(i=>i.streamId));this.objectIter=new $a(e.suiClient,a)}current=0;objectIter;static async newIncomingQuery(e){let t=du(e.query),n=await e.globals.walletAddress(),s=(await e.globals.backend.getIncomingStreams(n,t)).filter(i=>Ht(i.recipient)===Ht(n)),a=ua(s);return new tn(e.globals,n,a,e.query)}static async newOutgoingQuery(e){let t=mu(e.query),n=await e.globals.walletAddress(),s=await e.globals.backend.getOutgoingStreams(n,t),a=ua(s);return new tn(e.globals,n,a,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let t=await uu(this.globals,e[0].streamId,this.objectIter);return this.current++,Za(t,this.query)?t:this.doNextRequest()}if(e.length>1){let t=await lu(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,cu(t,this.query)?t:this.doNextRequest()}throw new U("Stream group with no stream")}};function ua(r){let e=new Map;return r.forEach(t=>{let n=e.get(t.groupId);n?(n.push(t),e.set(t.groupId,n)):e.set(t.groupId,[t])}),Array.from(e.values()).sort((t,n)=>p.fromISO(n[0].createDate).toMillis()-p.fromISO(t[0].createDate).toMillis())}function Za(r,e){if(e===void 0)return!0;let t=ou(r,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?r.progress.claimable!==0n:r.progress.claimable===0n;return t&&n}return t}function ou(r,e){return e===void 0?!0:Array.isArray(e)?e.includes(r.progress.status):r.progress.status===e}function cu(r,e){if(!e)return!0;let t=!1;return r.streams.forEach(n=>{Za(n,e)&&(t=!0)}),t}async function uu(r,e,t){let n=await Ka(t,e);return rn.fromObjectData(r,e,n)}async function lu(r,e,t){let n=[];for(;n.length<e.length;){let s=await Ka(t,e[n.length]);n.push(s)}return au.newFromObjectResponse(r,e,n)}async function Ka(r,e){if(!await r.hasNext())throw new U("object iterator has been consumed");let t=await r.next();if(!t||t.error||t.data===void 0||t.data===null)throw new U("object iterator undefined response",{cause:t?.error});if(t?.data?.objectId!==e)throw new U("stream id not aligned");return t}function du(r){return{status:nn(r?.status),coinType:Ya(r?.coinType),sender:Ja(r?.sender)}}function mu(r){return{status:nn(r?.status),coinType:Ya(r?.coinType),recipient:Ja(r?.recipient)}}function nn(r){return r===void 0||r.length===0?"all":Array.isArray(r)?r.reduce((e,t)=>{let n=nn(t);return!e||e===n?n:"all"},void 0):hu(r)}function hu(r){switch(r){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new N("Unknown stream filtered status")}}function Ya(r){if(r)return Array.isArray(r)?r.length!==0?r.map(e=>Xs(e)):void 0:Xs(r)}function Ja(r){if(r)return Array.isArray(r)?r.length!==0?r.map(e=>Ht(e)):void 0:Ht(r)}var fu=class extends P{constructor(r,e,t){super(4,`Not enough balance: ${r}`,{context:{coinType:r,requestAmount:e,gotAmount:t}}),this.coinType=r,this.requestAmount=e,this.gotAmount=t}},pu=25;async function gu(r,e,t,n="0x2::sui::SUI",s=pu){let a=new yu(r,e,n,s),i=BigInt(0),o=[];for(;await a.hasNext()&&i<t;){let c=await a.next();c&&(o.push(c),i+=BigInt(c.balance))}if(i<t)throw new fu(n,t,i);return o}var yu=class extends Ga{constructor(r,e,t,n){super(new wu(r,e,t,n)),this.suiClient=r,this.owner=e,this.coinType=t,this.reqPageSize=n}},wu=class{constructor(r,e,t,n){if(this.suiClient=r,this.owner=e,this.coinType=t,this.reqPageSize=n,n<=0)throw new U("Invalid reqPageSize")}nextCursor;async doNextRequest(){let r=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=r.nextCursor,{data:r.data,hasNext:r.hasNextPage}}},Su=class{constructor(r){this.msafe=r}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(r){return this.msafe.requestCoins(r)}},bu=class{constructor(r){this.account=r}async address(){return this.account.address}},Tu=class{constructor(r,e){this.singleWallet=r,this.suiClient=e}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(r){return Promise.all(r.map(e=>this.requestCoin(e)))}async requestCoin(r){if(La(r.coinType,_c))return{primaryCoin:Ba};if(r.amount<=0)throw new N("Invalid coin request","coinAmount",r.amount);let e=await gu(this.suiClient,await this.address(),r.amount,r.coinType);if(e.length===0)throw new U("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(t=>t.coinObjectId)}}},Iu=class{globals;helper;constructor(r,e){this.globals=Pa.new(r,e),this.helper=new Kc(this.globals)}connectSingleWallet(r){let e=new Tu(r,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(r){let e=new Su(r);this.globals.connectWallet(e)}async createStream(r){return this.builder().createStreams(r)}async getStream(r){return rn.new(this.globals,r)}async getIncomingStreams(r,e=10){return ia.newIncoming({globals:this.globals,query:r,pageSize:e})}async getOutgoingStreams(r,e=10){return ia.newOutgoing({globals:this.globals,query:r,pageSize:e})}async getCoinTypesForStreamFilter(){let r=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(r)).map(e=>Wc(e))}async getRecipientsForStreamFilter(r){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,r)).map(t=>Hs(t))}async getCreatorsForStreamFilter(r){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,r)).map(t=>Hs(t))}get wallet(){return this.globals.wallet}builder(){return new Va(this.globals)}},xu=class{constructor(r){this.data=r}serialize(){return JSON.stringify((0,Qa.default)(this.data))}},pt=class extends xu{application="mpay";getClient(r,e){let t=new Iu(r==="sui:mainnet"?"prod":"dev");return t.connectSingleWallet(new bu(e)),t}},la=class extends pt{constructor(r){super(r),this.data=r}txType=wc.Stream;txSubType="Cancel";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).cancel()}},da=class extends pt{constructor(r){super(r),this.data=r}txType=ku.Stream;txSubType="ClaimByProxy";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).claimByProxy()}},ma=class extends pt{constructor(r){super(r),this.data=r}txType=Ou.Stream;txSubType="Claim";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).claim()}},ha=class extends pt{constructor(r){super(r),this.data=r}txType=Eu.Stream;txSubType="CreateStream";async build(r){let{network:e,account:t}=r;return this.getClient(e,t).createStream(this.data)}},Xa=class Bt{constructor(e,t){this.moveCall=e,this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return Bt.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return Bt.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return BigInt(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return ft(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return Bt.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return fa.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return ft(e.value.Object.ImmOrOwned.objectId)}return ft(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return ft(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return ft(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return fa.de(t,new Uint8Array(n))}typeArg(e){return Cu(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},vu=class{constructor(r,e){this.globals=r,this.txb=e}decode(){let r=this.decodeCreateStreamInfo(),e=this.createStreamHelper().calculateCreateStreamFees(r);return{type:"CreateStream",info:r,fees:e}}decodeCreateStreamInfo(){let r=this.createStreamTransactions().map(e=>this.getCreationInfoFromMoveCall(e));return this.aggregateGroupStreamInfo(r)}createStreamTransactions(){let r=this.transactions.filter(e=>e.kind==="MoveCall"&&Me(e.target,this.contract.createStreamTarget));if(r.length===0)throw new U("No create stream transactions");return r.map(e=>new Xa(e,this.txb))}getCreationInfoFromMoveCall(r){let e=r.decodeInputString(4),{name:t,groupId:n}=Jr(e),s=r.decodeInputAddress(5),a=r.decodeInputU64(6),i=r.decodeInputU64(7),o=r.decodeInputU64(8),c=r.decodeInputU64(9),u=r.decodeInputU64(10),d=r.decodeInputBool(11),f=r.typeArg(0);return{name:t,groupId:n,recipient:s,timeStart:a,cliff:i,epochInterval:o,totalEpoch:c,amountPerEpoch:u,cancelable:d,coinType:f}}aggregateGroupStreamInfo(r){if(new Set(r.map(t=>JSON.stringify({name:t.name,groupId:t.groupId,timeStart:String(t.timeStart),epochInterval:String(t.epochInterval),totalEpoch:String(t.totalEpoch),cancelable:t.cancelable,coinType:t.coinType}))).size!==1)throw new N("Stream group not have common info");let e=r.map(t=>({address:t.recipient,amountPerStep:t.amountPerEpoch,cliffAmount:t.cliff}));return{name:r[0].name,coinType:r[0].coinType,recipients:e,interval:r[0].epochInterval,steps:r[0].totalEpoch,startTimeMs:r[0].timeStart,cancelable:r[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(r=>r.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new Gt(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Ha(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new Qr(this.globals,this.feeContract,this.contract)}getInputArg(r){if(r.kind!=="Input")throw new Error("not input type");return"value"in r?r:this.txb.blockData.inputs[r.index]}},Mu=class{constructor(r,e){this.globals=r,this.txb=e,this.contract=new Gt(r.envConfig.contract,r)}contract;decode(){if(this.isCreateStreamTransaction())return this.decodeCreateStreamTransaction();if(this.isClaimByProxyTransaction())return this.decodeClaimByProxyTransaction();if(this.isSetAutoClaimTransaction())return this.decodeSetAutoClaimTransaction();if(this.isCancelStreamTransaction())return this.decodeCancelStreamTransaction();if(this.isClaimStreamTransaction())return this.decodeClaimTransaction()}get transactions(){return this.txb.blockData.transactions}isCreateStreamTransaction(){return this.transactions.findIndex(r=>r.kind==="MoveCall"&&Me(r.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Me(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Me(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Me(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Me(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new vu(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let r=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:r,enabled:e}}decodeClaimTransaction(){return{type:"Claim",streamId:this.helper.decodeSharedObjectId(0)}}decodeClaimByProxyTransaction(){return{type:"ClaimByProxy",streamId:this.helper.decodeSharedObjectId(0)}}decodeCancelStreamTransaction(){return{type:"Cancel",streamId:this.helper.decodeSharedObjectId(0)}}get helper(){let r=this.transactions[0];return new Xa(r,this.txb)}},pa=class extends pt{constructor(r){super(r),this.data=r}txType=Au.Stream;txSubType="SetAutoClaim";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}},Du=class{application="mpay";async deserialize(r){let{chain:e,transactionBlock:t}=r,n=Pa.new(e==="sui:mainnet"?"prod":"dev"),s=new Mu(n,t).decode(),a;switch(s.type){case"CreateStream":a=new ha(s.info);break;case"SetAutoClaim":a=new pa({streamId:s.streamId,enabled:s.enabled});break;case"Claim":a=new ma({streamId:s.streamId});break;case"ClaimByProxy":a=new da({streamId:s.streamId});break;case"Cancel":a=new la({streamId:s.streamId});break;default:throw new Error(`Unknown transaction type: ${s}`)}return{txType:a.txType,txSubType:a.txSubType,intentionData:a.data}}async build(r){let{intentionData:e}=r,t;switch(r.txSubType){case"CreateStream":t=new ha(e);break;case"Claim":t=new ma(e);break;case"ClaimByProxy":t=new da(e);break;case"SetAutoClaim":t=new pa(e);break;case"Cancel":t=new la(e);break;default:throw new Error("not implemented")}return t.build({...r})}},sn=class{constructor(r){this.data=r}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,ei.default)(this.data))}},Fu=class ti extends sn{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:t,account:n}=e;return Pu(t,this.data,n.address)}static fromData(e){return new ti(e)}},_u=class ri extends sn{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:t,account:n}=e;return Ru(t,this.data,n.address)}static fromData(e){return new ri(e)}},Lu=class ni extends sn{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:t}=e,n=ju.from(this.data.content);if(!Wu(n.blockData.sender,t.address))throw new Error("Invalid sender address");return n}static fromData(e){return new ni(e)}},Bu=class{application;constructor(){this.application=Nu}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(r){let{suiClient:e,account:t}=r,n;switch(r.txSubType){case Kr.assets.coin.send:n=Fu.fromData(r.intentionData);break;case Kr.assets.object.send:n=_u.fromData(r.intentionData);break;case Kr.others.plain:n=Lu.fromData(r.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:t})}},qu=class{apps;constructor(r){this.apps=new Map(r.map(e=>[e.application,e]))}getAppHelper(r){let e=this.apps.get(r);if(!e)throw new Error(`${r} not registered`);return e}},$u="msafe-plain-tx",Zu=Uu.others.plain,Ku=class{application;constructor(){this.application=$u}async deserialize(r){let{transactionBlock:e,suiClient:t}=r,n=await e.build({client:t});return{txType:Hu.Other,txSubType:Zu,intentionData:{content:zu(n)}}}async build(r){let{suiClient:e,account:t}=r,n=Vu.from(Gu(r.intentionData.content)),s=await e.devInspectTransactionBlock({transactionBlock:n,sender:t.address});if(s.effects.status.status!=="success")throw new Error(s.effects.status.error);return n}},zt=new qu([new Bu,new Du,new Ku]);import{MultiSigAccount as ol,SigningMessageHelper as cl,TransactionDefaultApplication as Ae,TransactionSubTypes as De,TransactionType as Ne,buildRejectTxb as mi,isSameAddress as hi}from"@msafe/sui3-utils";import{TransactionBlock as fi}from"@mysten/sui.js/transactions";import{normalizeStructTag as ul,toHEX as ll}from"@mysten/sui.js/utils";import{TransactionBlock as Yu}from"@mysten/sui.js/transactions";var Ju=1000n,Qu=120n,Xu=100n,el={multiplier:{numerator:Qu,denominator:Xu}};var $t=class{constructor(e){this.globals=e}async simulate(e,t=el){let n=this.copyTransactionBlock(e.txb),{suiClient:s}=this.globals,a=await this.getGasPrice(t);n.setGasPrice(a);let i=await s.devInspectTransactionBlock({transactionBlock:n,sender:e.sender}),{gasUsed:o}=i.effects,c=this.toGasBudget(o,a),u=i.effects.status.status==="success",d;return u||(d=i.effects.status.error),{success:u,gasPrice:a,gasObject:i.effects.gasObject.reference,gasUsed:o,gasBudget:c,simulationError:d}}async getGasPrice(e){if(this.isFixedValue(e))return e.fixedVal;let t=await this.globals.suiClient.getReferenceGasPrice();return this.applyGasOption(t,e)}toGasBudget(e,t){let{computationCost:n,storageCost:s}=e,a=Ju*t,i=BigInt(n)+a,o=i+BigInt(s);return o>i?o:i}isFixedValue(e){return"fixedVal"in e}isMultiplier(e){return"multiplier"in e}applyGasOption(e,t){if(this.isFixedValue(t))return t.fixedVal;if(this.isMultiplier(t)){let{multiplier:n}=t;return e*n.numerator/n.denominator}throw new Error("Sanity: Unknown gas price option")}copyTransactionBlock(e){return Yu.from(e.serialize())}};import{Buffer as si}from"buffer";function an(r){return si.from(r,"utf-8")}function kf(r){return`0x${Array.prototype.map.call(r,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function on(r){return Uint8Array.from(si.from(r.startsWith("0x")?r.slice(2):r,"hex"))}import{verifyPersonalMessage as tl,verifyTransactionBlock as rl}from"@mysten/sui.js/verify";import{normalizeSuiAddress as un,normalizeStructTag as ln}from"@mysten/sui.js/utils";import{normalizeStructTag as cn}from"@mysten/sui.js/utils";var Zt=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let t=cn(e);if(this._coinMetaReg.has(t))return this._coinMetaReg.get(t);let n=await this.queryCoinMeta(t);return n&&this._coinMetaReg.set(t,n),n}async queryCoinMeta(e){return await this._client.getCoinMetadata({coinType:e})||void 0}},ai=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,Kt=class r{static isCoin(e){return e?cn(e).match(ai)!=null:!1}static getCoinType(e){let[,t]=cn(e).match(ai)??[];return t||null}static getBalance(e){if(!r.isCoin(e.type)||e.content?.dataType!=="moveObject")return;let{balance:t}=e.content?.fields;if(t!==void 0)return BigInt(t)}};var se=class{static normalizeSuiAddress(e){return un(e)}static normalizeStructTag(e){return ln(e)}static isSuiAddressEqual(e,t){return un(e)===un(t)}static isSuiStructEqual(e,t){return ln(e)===ln(t)}static isCoinObjectType(e){return Kt.isCoin(e)}};function ii(r,e){return r.startsWith(e)?r:e+r}var oi=class r{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?rl(e.message,e.signature):tl(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let t=an(e.messageStr);return this.getPublicKeyFromSignature({message:t,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let t=await r.getPublicKeyFromSignature(e);return se.isSuiAddressEqual(t.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let t=an(e.messageStr);return this.verifySignature({message:t,messageType:"Personal",signature:e.signature,targetAddress:e.targetAddress})}static async verifyTransactionSignature(e){return this.verifySignature({messageType:"TransactionBlock",message:e.payload,signature:e.signature,targetAddress:e.targetAddress})}};import{PublicKeySerde as nl}from"@msafe/sui3-utils";import{parseSerializedSignature as sl}from"@mysten/sui.js/cryptography";import{MultiSigPublicKey as al}from"@mysten/sui.js/multisig";var qf="0x2::sui::SUI";async function ci(r,e){let t;try{t=await r.queryTransactionBlocks({filter:{FromAddress:e},options:{showInput:!0},limit:2})}catch{return}if(t.data.length===0||!t.data[0].transaction?.txSignatures)return;let s=t.data[0].transaction?.txSignatures;for(let a=0;a!==s.length;a++){let i=s[a],o=il(i,e);if(o)return o}}function il(r,e){let t=sl(r);switch(t.signatureScheme){case"MultiSig":{let n=new al(t.multisig.multisig_pk).toSuiAddress();if(se.isSuiAddressEqual(n,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(se.isSuiAddressEqual(t.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let n=nl.de({publicKeyEncoded:t.publicKey,schema:t.signatureScheme});return se.isSuiAddressEqual(n.toSuiAddress(),e)?n:void 0}default:throw new Error("Unknown schema")}}async function Uf(r){let e=!0,t,n=[];for(;e;){let s=await r.suiClient.getCoins({owner:r.owner,coinType:r.coinType,cursor:t});n.push(...s.data),e=s.hasNextPage,t=s.nextCursor}return n}var ui=25;async function li(r){let e=[];for(;await r.hasNext();){let t=await r.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var dn=class{constructor(e){this.requester=e;this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},Yt=class{constructor(e){this.requester=e;this.pager=new dn(e),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}};async function di(r,e,t){let n=new mn(r,e,t);return await li(n)}var mn=class extends Yt{constructor(t,n,s){super(new hn(t,n,s));this.provider=t;this.owner=n;this.options=s}},hn=class{constructor(e,t,n){this.provider=e;this.owner=t;this.options=n;this.nextCursor=null,this.filter=n?.filter,this.pageSize=n?.pageSize||ui,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}nextCursor;filter;pageSize;objectOptions;async doNextRequest(){let e=await this.provider.getOwnedObjects({owner:this.owner,options:this.objectOptions,cursor:this.nextCursor,limit:this.pageSize});this.nextCursor=e.nextCursor;let t;if(this.filter){let{filter:n}=this;t=e.data.filter(s=>n?.(s))}else t=e.data;return{data:t.map(n=>n.data).filter(n=>n),hasNext:e.hasNextPage}}};var Pe=class r{constructor(e,t){this.globals=e;this.info=t;this.multiSig=new ol({threshold:t.threshold,ownersWithWeight:t.owners,creationNonce:t.creationNonce}),this.coinHelper=new Zt(this.suiClient),this.simulator=new $t(e)}multiSig;coinHelper;simulator;static async New(e,t){let n=await e.backend.getMSafeAccountInfo(t);if(new r(e,n).address!==t)throw new Error("Invalid msafe config with address")}async ownedCoins(){let e=await this.suiClient.getAllBalances({owner:this.address});return Promise.all(e.map(async t=>{let n=await this.coinHelper.getCoinMeta(t.coinType),s=t.lockedBalance.number?BigInt(t.totalBalance)-BigInt(t.lockedBalance.number):BigInt(t.totalBalance);return{type:ul(t.coinType),balance:BigInt(s),metadata:n}}))}async ownedObjects(e){let t={filter:n=>!n?.data?.type?.startsWith("0x2::coin::Coin"),...e};return di(this.suiClient,this.address,t)}async pendingTransaction(){let e=await this.backend.getPendingTransactions({msafeAddress:this.address});if(!e.pending)return;let t=e.pending,n=e.reject;return{application:t.application,txType:t.txType,txSubType:t.txSubType,createdAt:t.createdAt,creator:t.creator,digest:t.digest,intention:t.intention,sequenceNumber:t.sequenceNumber,payload:t.payload,votes:t.votes,approvalWeight:this.calculateWeightFromVotes(t.votes),msafeAddress:t.msafeAddress,rejectDigest:n?.digest??"",rejectPayload:n?.payload??"",rejectVotes:n?.votes??[],rejectWeight:this.calculateWeightFromVotes(n?.votes??[])}}async historyTransaction(e){return this.backend.getHistoryTransactions({msafeAddress:this.address,...e})}async futureIntentions(e){return this.backend.getFutureIntentions({msafeAddress:this.address,...e})}async currentSequenceNumber(){return this.backend.getCurrentSequenceNumber(this.address)}async nextSequenceNumber(){return this.backend.getNextSequenceNumber(this.address)}async simulateIntention(e){let t=zt.getAppHelper(e.application);if(!t)throw new Error(`Can't find app helper for application ${e.application}`);let n=await t.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async proposeIntention(e){let t=cl.proposeIntentionMessage({msafeAddress:this.address,intention:e.intention,sn:e.sequenceNumber}),n=await this.wallet.signPersonalMessage({messageStr:t});return this.backend.proposeIntention({...e,msafeAddress:this.address,signature:n.signature})}async proposeIntentionAndBuildVote(e){let t=zt.getAppHelper(e.application);if(!t)throw new Error(`Can't find app helper for application ${e.application}`);let n=await t.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});n.setGasPrice(e.gasPrice),n.setGasBudget(e.gasBudget),n.setSender(this.address);let s=await n.build({client:this.globals.suiClient}),a=await n.getDigest({client:this.globals.suiClient}),i=await this.wallet.signTransactionBlock({transactionBlock:s});return this.backend.proposeIntentionAndBuildVote({...e,payload:ll(s),digest:a,msafeAddress:this.address,signature:i.signature})}async simulateCoinTransferIntention(e){let t=await this.nextSequenceNumber();return this.simulateIntention({application:Ae,txType:Ne.Assets,txSubType:De.assets.coin.send,sequenceNumber:t,intention:e})}async proposeCoinTransferIntention(e){let t=await this.nextSequenceNumber();return this.proposeIntention({application:Ae,txType:Ne.Assets,txSubType:De.assets.coin.send,sequenceNumber:t,intention:e})}async simulateObjectTransferIntention(e){let t=await this.nextSequenceNumber();return this.simulateIntention({application:Ae,txType:Ne.Assets,txSubType:De.assets.object.send,sequenceNumber:t,intention:e})}async proposeObjectTransferIntention(e){let t=await this.nextSequenceNumber();return this.proposeIntention({application:Ae,txType:Ne.Assets,txSubType:De.assets.object.send,sequenceNumber:t,intention:e})}async simulatePlainPayloadIntention(e){let t=await this.nextSequenceNumber();return this.simulateIntention({application:Ae,txType:Ne.Other,txSubType:De.others.plain,sequenceNumber:t,intention:e})}async proposePlainPayloadIntention(e){let t=await this.nextSequenceNumber(),n=fi.from(e.payload);if(!n.blockData.sender||!hi(n.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:Ae,txType:Ne.Other,txSubType:De.others.plain,sequenceNumber:t,intention:e})}async voteForTransaction(e,t){let n=on(t),s=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.voteForTransaction({msafeAddress:this.address,digest:e,signature:s.signature})}async proposePendingTransaction(e){let t=new fi,n=await t.build({client:this.suiClient}),s=await t.getDigest({client:this.suiClient}),a=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.proposePendingTransaction({msafeAddress:this.address,userAddress:await this.userAddress(),intention:e,digest:s,signature:a.signature})}async simulateRejectTx(){let e=await this.pendingTransaction();if(!e||e.rejectDigest!=="")throw new Error("Already rejected");let t=e.payload,n=mi(this.address,t);return this.simulator.simulate({txb:n,sender:this.address})}async rejectCurrentTx(e){let t=await this.pendingTransaction();if(!t||t.rejectDigest!=="")throw new Error("Already rejected");let n=t.payload,s=mi(this.address,n),a=await s.getDigest({client:this.suiClient}),i=await s.build({client:this.suiClient}),o=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.rejectCurrentTx({msafeAddress:this.address,digest:a,signature:o.signature,...e})}async simulateBuildTransaction(){let e=await this.backend.getNextIntention({msafeAddress:this.address}),t=zt.getAppHelper(e.application);if(!t)throw new Error(`Can't find app helper for application ${e.application}`);let n=await t.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async buildNextIntentionAndAddToPending(e){return this.backend.buildNextIntentionAndAddToPending({msafeAddress:this.address,forceBuild:e.forceBuild,gasPrice:e.gasPrice,gasBudget:e.gasBudget})}async skipNextFailedIntention(){return this.backend.skipNextFailedIntention({msafeAddress:this.address})}async executePendingTx(e,t=!1){let n=t?e.rejectVotes:e.votes,s=t?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(n)<this.info.threshold)throw new Error("Not enough signature");let a=[],i=new Map(n.map(c=>[c.userAddress,c.signature]));for(let c=0;c<this.info.owners.length;c++){let u=this.info.owners[c],d=i.get(u.address);d&&a.push(d)}let o=this.multiSig.combinePartialSignatures(a);return this.suiClient.executeTransactionBlock({transactionBlock:on(s),signature:o,options:{showEffects:!0,showEvents:!0}})}async dashboard(){return this.backend.getDashboard({msafeAddress:this.address})}calculateWeightFromVotes(e){return this.calculateWeight(e.map(t=>t.userAddress))}calculateWeight(e){let t=0;for(let n=0;n<e.length;n++){let s=this.info.owners.find(a=>hi(a.address,e[n]));s&&(t+=s.weight)}return t}get address(){return this.multiSig.address}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}async userAddress(){return this.globals.wallet.address()}get suiClient(){return this.globals.suiClient}};import{isSameAddress as dl}from"@msafe/sui3-utils";import{normalizeSuiAddress as ml}from"@mysten/sui.js/utils";var Jt=class{constructor(e){this.globals=e;this.knownPublicKeys=new Map}knownPublicKeys;async getPublicKey(e){let t=this.knownPublicKeys.get(e);if(t)return t;let n=await this._getPublicKey(e);return n&&this.knownPublicKeys.set(e,n),n}async getPublicKeyBatch(e){let t=new Array(e.length).fill(void 0);for(let a=0;a<e.length;a++){let i=e[a];t[a]=this.knownPublicKeys.get(i)}let n=t.map((a,i)=>a===void 0?i:-1).filter(a=>a!==-1);if(n.length===0)return t;let s=await this.globals.backend.getPublicKeyBatch(n.map(a=>e[a]));for(let a=0;a<n.length;a++){let i=n[a];t[i]=s[a]}for(let a=0;a<t.length;a++)t[a]===void 0&&(t[a]=await this.getPublicKeyFromChain(e[a]));for(let a=0;a<e.length;a++)t[a]&&this.knownPublicKeys.set(e[a],t[a]);return t}addPublicKey(e,t){if(!dl(e,t.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set(ml(e),t)}async _getPublicKey(e){let t=await this.getPublicKeyFromBackend(e);if(t)return t;let n=await this.getPublicKeyFromChain(e);if(n)return n}async getPublicKeyFromBackend(e){try{return await this.globals.backend.getPublicKey(e)}catch{return}}async getPublicKeyFromChain(e){return ci(this.globals.suiClient,e)}};var Qt=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};import{SuiClient as bl}from"@mysten/sui.js/client";import{PublicKeySerde as pi,UserMSafeStatus as hl}from"@msafe/sui3-utils";import Xt from"axios";import*as rr from"json-bigint";var er=class r{constructor(e){this.apiURL=e}_token;async authSign(e){let t=await this.post("/auth/login",e);return this._token=t.data.accessToken,this._token}async verifyToken(e){try{return(await this.get("/auth",{headers:this.headers(e)})).status===200}catch{return!1}}setJWTToken(e){this._token=e}async getPublicKey(e){return(await this.getPublicKeyBatch([e]))[0]}async getPublicKeyBatch(e){let t={userAddressList:e};return(await this.get("/user/public-keys",{params:t,headers:this.headers()})).data?.map(s=>s?pi.de(s):void 0)}async getMSafeAccountInfo(e){let t={msafeAddress:e},n=await this.get("/msafe",{params:t,headers:this.headers()});return r.toMSafeConfig(n.data)}async getUserInfo(){return(await this.get("/user",{headers:this.headers()})).data}async getOwnedMSafeByStatus(e){let t={status:e.status??hl.active,...e.pagination?{page:e.pagination.page.toString(),limit:e.pagination.limit.toString()}:{}},n=await this.get("/msafe/owned",{params:t,headers:this.headers()});return{data:n.data.data.map(r.toMSafeConfig),meta:n.data.meta}}async updateMSafeStatus(e){let t=e;await this.post("/msafe/status",t,{headers:this.headers()})}async getPendingTransactions(e){return(await this.get("/transaction/pending",{params:e,headers:this.headers()})).data}async getHistoryTransactions(e){return(await this.get("/transaction/history",{params:e,headers:this.headers()})).data}async getFutureIntentions(e){return(await this.get("/transaction/intention",{params:e,headers:this.headers()})).data}async getNextIntention(e){return(await this.get("/transaction/intention/next",{params:e,headers:this.headers()})).data}async getCurrentSequenceNumber(e){return(await this.get("/transaction/sn/current",{params:{msafeAddress:e},headers:this.headers()})).data}async getNextSequenceNumber(e){return(await this.get("/transaction/sn/next",{params:{msafeAddress:e},headers:this.headers()})).data}async createMSafeAccount(e){await this.post("/msafe/create",e,{headers:this.headers()})}async proposeIntention(e){await this.post("/transaction/intention",e,{headers:this.headers()})}async proposePendingTransaction(e){}async rejectCurrentTx(e){await this.post("/transaction/pending/reject",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async voteForTransaction(e){await this.post("/transaction/pending/vote",e,{headers:this.headers()})}async buildNextIntentionAndAddToPending(e){await this.post("/transaction/pending/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async proposeIntentionAndBuildVote(e){await this.post("/transaction/intention/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async skipNextFailedIntention(e){await this.post("/transaction/pending/skip",e,{headers:this.headers()})}async getAddressBookEntries(e){return(await this.get("/address-book",{headers:this.headers(),params:e})).data}async updateAddressBook(e){await this.post("/address-book",e,{headers:this.headers()})}async getAddressBookMode(){return(await this.get("/address-book/mode",{headers:this.headers()})).data}async setAddressBookMode(e){await this.post("/address-book/mode",{mode:e.mode},{headers:this.headers()})}async submitReport(e){await this.post("/report",e)}async getDashboard(e){return(await this.get("/dashboard",{params:e,headers:this.headers()})).data}headers(e){return{Authorization:`Bearer ${e||this._token}`}}static toMSafeConfig(e){return{...e,owners:e.owners.map(t=>({address:t.address,weight:t.weight,publicKey:pi.de({publicKeyEncoded:t.publicKeyEncoded,schema:t.schema})}))}}async get(e,t){let n=this.getFullUrl(e);try{return await Xt.get(n,t)}catch(s){throw tr.fromError(s)??s}}async post(e,t,n){let s=this.getFullUrl(e);try{return await Xt.post(s,t,{...n,transformRequest:this.getTransformRequest()})}catch(a){throw tr.fromError(a)??a}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${ii(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:t}=Xt.defaults;return t?t instanceof Array?e=t:e=[t]:e=[],[n=>rr.parse(rr.stringify(n)),...e]}},tr=class r extends Error{constructor(t){super();this.e=t;Error.captureStackTrace(this,this.constructor)}name;static fromError(t){if(Xt.isAxiosError(t)&&t?.response?.data&&"message"in t.response.data)return new r(t)}get status(){return this.e.response?.status??void 0}get message(){return`${this.respMessage()??"Unknown resp"}`}respMessage(){if(this.e.response?.data)return(this.e.response?.data).message??void 0}get endpoint(){return this.e.config?.url??""}toString(){return this.message}};var fl=(a=>(a.local="local",a.unit="unit",a.dev="dev",a.prev="prev",a.prod="prod",a))(fl||{}),fn="https://fullnode.testnet.sui.io",gi="https://fullnode.mainnet.sui.io",yi="http://127.0.0.1:3000",wi="http://127.0.0.1:3001",pl="https://sui-dev.m-safe.link",gl="http://13.56.226.148:81",yl="https://sui-preview.m-safe.link",wl="https://sui.m-safe.link",Sl=new Map([["unit",{suiClient:{url:fn},backend:{url:yi},syncingURL:wi,network:"sui:testnet"}],["local",{suiClient:{url:fn},backend:{url:yi},syncingURL:wi,network:"sui:testnet"}],["dev",{suiClient:{url:fn},backend:{url:pl},syncingURL:gl,network:"sui:testnet"}],["prev",{suiClient:{url:gi},backend:{url:yl},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:gi},backend:{url:wl},syncingURL:"",network:"sui:mainnet"}]]);function Si(r,e){let t=Sl.get(r);if(!t)throw new Error("Unknown environment");return e?.suiClient?.url&&(t.suiClient.url=e.suiClient.url),e?.backend?.url&&(t.backend.url=e.backend.url),t}var nr=class r{backend;suiClient;config;_wallet;constructor(e){this.backend=e.backend,this.suiClient=e.suiClient,this.config=e.config}static async New(e,t){let n=Si(e,t),s=new bl(n.suiClient),a=new er(n.backend.url);return new r({backend:a,suiClient:s,config:n})}connectWallet(e){this._wallet=e}get wallet(){if(!this._wallet)throw new Error("wallet not connected");return this._wallet}set wallet(e){this._wallet=e}};var pn=class r{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,t){let n=await nr.New(e,t);return new r(n)}async connectWallet(e){if(e.jwtToken&&await this.backend.verifyToken(e.jwtToken))return this.globals.wallet=e.wallet,this.backend.setJWTToken(e.jwtToken),e.jwtToken;let t=await this.authSign(e.wallet);return this.globals.wallet=e.wallet,this.backend.setJWTToken(t),t}async authSign(e){let t=Tl.loginMessageWithTimestamp(new Date().toUTCString()),n=await e.signPersonalMessage({messageStr:t});return this.backend.authSign({address:await e.address(),message:t,signature:n.signature,walletType:e.walletType})}async userInfo(){return this.globals.backend.getUserInfo()}async ownedMSafe(e){return this.globals.backend.getOwnedMSafeByStatus({status:Il.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new Pe(this.globals,e)}async getMSafeAccountFromAddress(e){let t=await this.backend.getMSafeAccountInfo(e);return new Pe(this.globals,t)}get creationHelper(){return this._creationHelper||(this._creationHelper=new _e(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new Jt(this.globals)),this._publicKeyHelper}get config(){return this.globals.config}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}get AddressBook(){return new We(this.globals)}get Invitation(){return new yt(this.globals)}get Report(){return new Qt(this.globals)}async walletAddress(){return this.wallet.address()}};export{We as AddressBookSDK,ai as COIN_TYPE_ARG_REGEX,Kt as Coin,Zt as CoinHelper,_e as CreateHelper,pl as DEV_API_URL,gl as DEV_SYNCING_URL,Sl as ENV_CONFIGS,se as Formatter,on as HexToUint8Array,yi as LOCAL_API_URL,wi as LOCAL_SYNCING_URL,gi as MAINNET_RPC_URL,Pe as MSafeAccount,pn as MSafeClient,fl as MSafeEnv,nr as MSafeGlobals,yl as PREV_API_URL,wl as PROD_API_URL,qf as SUI_COIN,oi as SignatureVerifier,fn as TESTNET_RPC_URL,kf as Uint8ArrayToHex,ii as addPrefix,Uf as getAllCoins,Si as getMSafeConfig,ci as getPublicKeyFromChain,an as stringToBuffer};
|
|
1
|
+
var Li=Object.create;var kn=Object.defineProperty;var Ui=Object.getOwnPropertyDescriptor;var Vi=Object.getOwnPropertyNames;var qi=Object.getPrototypeOf,Hi=Object.prototype.hasOwnProperty;var Tt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var $i=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Vi(e))!Hi.call(r,s)&&s!==t&&kn(r,s,{get:()=>e[s],enumerable:!(n=Ui(e,s))||n.enumerable});return r};var dr=(r,e,t)=>(t=r!=null?Li(qi(r)):{},$i(e||!r||!r.__esModule?kn(t,"default",{value:r,enumerable:!0}):t,r));var _s=Tt((Sf,js)=>{"use strict";js.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Ws=Tt((Tf,Bs)=>{"use strict";var Yr=_s();Bs.exports=(r,e={})=>{if(!Yr(r)&&!Array.isArray(r))throw new TypeError("Expected a plain object or array");let{deep:t}=e,n=[],s=[],a=o=>{let c=n.indexOf(o);if(c!==-1)return s[c];let u=[];return n.push(o),s.push(u),u.push(...o.map(l=>Array.isArray(l)?a(l):Yr(l)?i(l):l)),u},i=o=>{let c=n.indexOf(o);if(c!==-1)return s[c];let u={},l=Object.keys(o).sort(e.compare);n.push(o),s.push(u);for(let h of l){let y=o[h],m;t&&Array.isArray(y)?m=a(y):m=t&&Yr(y)?i(y):y,Object.defineProperty(u,h,{...Object.getOwnPropertyDescriptor(o,h),value:m})}return u};return Array.isArray(r)?t?a(r):r.slice():i(r)}});var Vs=Tt((If,Us)=>{"use strict";var Tc=Object.prototype.toString;Us.exports=function(e){if(e===void 0)return"undefined";if(e===null)return"null";var t=typeof e;if(t==="boolean")return"boolean";if(t==="string")return"string";if(t==="number")return"number";if(t==="symbol")return"symbol";if(t==="function")return vc(e)?"generatorfunction":"function";if(Ic(e))return"array";if(Mc(e))return"buffer";if(Cc(e))return"arguments";if(kc(e))return"date";if(xc(e))return"error";if(Oc(e))return"regexp";switch(Ls(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(Ec(e))return"generator";switch(t=Tc.call(e),t){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return t.slice(8,-1).toLowerCase().replace(/\s/g,"")};function Ls(r){return typeof r.constructor=="function"?r.constructor.name:null}function Ic(r){return Array.isArray?Array.isArray(r):r instanceof Array}function xc(r){return r instanceof Error||typeof r.message=="string"&&r.constructor&&typeof r.constructor.stackTraceLimit=="number"}function kc(r){return r instanceof Date?!0:typeof r.toDateString=="function"&&typeof r.getDate=="function"&&typeof r.setDate=="function"}function Oc(r){return r instanceof RegExp?!0:typeof r.flags=="string"&&typeof r.ignoreCase=="boolean"&&typeof r.multiline=="boolean"&&typeof r.global=="boolean"}function vc(r,e){return Ls(r)==="GeneratorFunction"}function Ec(r){return typeof r.throw=="function"&&typeof r.return=="function"&&typeof r.next=="function"}function Cc(r){try{if(typeof r.length=="number"&&typeof r.callee=="function")return!0}catch(e){if(e.message.indexOf("callee")!==-1)return!0}return!1}function Mc(r){return r.constructor&&typeof r.constructor.isBuffer=="function"?r.constructor.isBuffer(r):!1}});var Ut=Tt((xf,Gs)=>{"use strict";var Dc=Ws(),Jr=Vs(),qs=(r,e)=>!e||Jr(e)!=="array"?!1:e.indexOf(r)>-1,Ac=(r,e)=>Dc(r,{compare:e}),Hs=(r,e)=>{let t=e&&e.compareFunction;return r.slice().sort(t)};function $s(r,e){let t=e&&e.compareFunction,n=Ac(r,t);return Object.keys(r).forEach(function(s){let a=n[s],i=Jr(a);if(i==="object"){(!e||!qs(s,e.ignoreObjectAtKeys))&&(n[s]=$s(a,e));return}i==="array"&&(!e||!qs(s,e.ignoreArrayAtKeys))&&(n[s]=Hs(a,e))}),n}var pt=(r,e)=>{let t=Jr(r);return pt[t]?pt[t](r,e):r};pt.array=Hs;pt.object=$s;Gs.exports=pt});import{isSameAddress as Gi,MultiSigAccount as zi,PublicKeySerde as On,SigningMessageHelper as Zi}from"@msafe/sui3-utils";var Be=class{constructor(e,t){this.globals=e;this.pkHelper=t}async getPublicKeyBatch(e){return this.pkHelper.getPublicKeyBatch(e)}async calculateMSafeAddress(e){let t=await this.reduceCreationInfoToRawConfig(e);return new zi(t).address}async validateCreateInfo(e){return this.calculateMSafeAddress(e)}addPublicKey(e,t){let n=On.de(t);if(!Gi(e,n.toSuiAddress()))throw new Error("Public key not match");this.pkHelper.addPublicKey(e,n)}async submitMSafeCreation(e){let t=await this.validateCreateInfo(e),n=Zi.createMSafeMessage(t),s=await this.globals.wallet.signPersonalMessage({messageStr:n});return await this.submitToBackend(e,s.signature),t}async reduceCreationInfoToRawConfig(e){let t=await this.getPublicKeyBatch(e.owners.map(n=>n.address));return t.forEach((n,s)=>{if(n===void 0)throw new Error(`Unknown public key for address: ${e.owners[s].address}`)}),{threshold:e.threshold,ownersWithWeight:e.owners.map((n,s)=>({publicKey:t[s],weight:n.weight})),creationNonce:e.creationNonce}}async submitToBackend(e,t){let n=await this.pkHelper.getPublicKeyBatch(e.owners.map(s=>s.address));await this.globals.backend.createMSafeAccount({owners:e.owners.map((s,a)=>({address:s.address,weight:s.weight,...On.ser(n[a])})),threshold:e.threshold,name:e.name,description:e.description,creationNonce:e.creationNonce,signature:t})}};import{SigningMessageHelper as ed,UserMSafeStatus as td}from"@msafe/sui3-utils";import{SigningMessageHelper as Ki}from"@msafe/sui3-utils";var We=class{constructor(e){this.globals=e}async getEntries(e){return this.globals.backend.getAddressBookEntries(e)}async update(e){let t=Ki.updateAddressBookMessage(e),n=await this.globals.wallet.signPersonalMessage({messageStr:t});return this.globals.backend.updateAddressBook({updates:e,signature:n.signature})}async getMode(){return(await this.globals.backend.getAddressBookMode()).mode}async setMode(e){return this.globals.backend.setAddressBookMode({mode:e})}};var It=class{constructor(e){this.globals=e}async getMSafeByStatus(e,t){return this.globals.backend.getOwnedMSafeByStatus({status:e,pagination:t})}async updateMSafeStatus(e,t){return this.globals.backend.updateMSafeStatus({msafeAddress:e,status:t})}};import{TransactionType as Nc}from"@msafe/sui3-utils";import{SuiClient as Gc}from"@mysten/sui.js/client";import De,{AxiosError as Kc}from"axios";import{SUI_TYPE_ARG as Jc,normalizeStructTag as Qc,normalizeSuiAddress as Ks}from"@mysten/sui.js/utils";import{normalizeStructTag as rn,SUI_TYPE_ARG as Xc}from"@mysten/sui.js/utils";var G=class extends Error{},xt=class extends G{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},kt=class extends G{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},Ot=class extends G{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},B=class extends G{},ge=class extends G{constructor(e){super(`Invalid unit ${e}`)}},x=class extends G{},W=class extends G{constructor(){super("Zone is an abstract class")}};var d="numeric",L="short",A="long",Y={year:d,month:d,day:d},Le={year:d,month:L,day:d},mr={year:d,month:L,day:d,weekday:L},Ue={year:d,month:A,day:d},Ve={year:d,month:A,day:d,weekday:A},qe={hour:d,minute:d},He={hour:d,minute:d,second:d},$e={hour:d,minute:d,second:d,timeZoneName:L},Ge={hour:d,minute:d,second:d,timeZoneName:A},ze={hour:d,minute:d,hourCycle:"h23"},Ze={hour:d,minute:d,second:d,hourCycle:"h23"},Ke={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:L},Ye={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:A},Je={year:d,month:d,day:d,hour:d,minute:d},Qe={year:d,month:d,day:d,hour:d,minute:d,second:d},Xe={year:d,month:L,day:d,hour:d,minute:d},et={year:d,month:L,day:d,hour:d,minute:d,second:d},fr={year:d,month:L,day:d,weekday:L,hour:d,minute:d},tt={year:d,month:A,day:d,hour:d,minute:d,timeZoneName:L},rt={year:d,month:A,day:d,hour:d,minute:d,second:d,timeZoneName:L},nt={year:d,month:A,day:d,weekday:A,hour:d,minute:d,timeZoneName:A},st={year:d,month:A,day:d,weekday:A,hour:d,minute:d,second:d,timeZoneName:A};var D=class{get type(){throw new W}get name(){throw new W}get ianaName(){return this.name}get isUniversal(){throw new W}offsetName(e,t){throw new W}formatOffset(e,t){throw new W}offset(e){throw new W}equals(e){throw new W}get isValid(){throw new W}};var hr=null,J=class r extends D{static get instance(){return hr===null&&(hr=new r),hr}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return Et(e,t,n)}formatOffset(e,t){return Q(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var Mt={};function Yi(r){return Mt[r]||(Mt[r]=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"})),Mt[r]}var Ji={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Qi(r,e){let t=r.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(t),[,s,a,i,o,c,u,l]=n;return[i,s,a,o,c,u,l]}function Xi(r,e){let t=r.formatToParts(e),n=[];for(let s=0;s<t.length;s++){let{type:a,value:i}=t[s],o=Ji[a];a==="era"?n[o]=i:f(o)||(n[o]=parseInt(i,10))}return n}var Ct={},M=class r extends D{static create(e){return Ct[e]||(Ct[e]=new r(e)),Ct[e]}static resetCache(){Ct={},Mt={}}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=r.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return Et(e,t,n,this.name)}formatOffset(e,t){return Q(this.offset(e),t)}offset(e){let t=new Date(e);if(isNaN(t))return NaN;let n=Yi(this.name),[s,a,i,o,c,u,l]=n.formatToParts?Xi(n,t):Qi(n,t);o==="BC"&&(s=-Math.abs(s)+1);let y=ye({year:s,month:a,day:i,hour:c===24?0:c,minute:u,second:l,millisecond:0}),m=+t,k=m%1e3;return m-=k>=0?k:1e3+k,(y-m)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var vn={};function eo(r,e={}){let t=JSON.stringify([r,e]),n=vn[t];return n||(n=new Intl.ListFormat(r,e),vn[t]=n),n}var pr={};function gr(r,e={}){let t=JSON.stringify([r,e]),n=pr[t];return n||(n=new Intl.DateTimeFormat(r,e),pr[t]=n),n}var yr={};function to(r,e={}){let t=JSON.stringify([r,e]),n=yr[t];return n||(n=new Intl.NumberFormat(r,e),yr[t]=n),n}var br={};function ro(r,e={}){let{base:t,...n}=e,s=JSON.stringify([r,n]),a=br[s];return a||(a=new Intl.RelativeTimeFormat(r,e),br[s]=a),a}var at=null;function no(){return at||(at=new Intl.DateTimeFormat().resolvedOptions().locale,at)}var En={};function so(r){let e=En[r];if(!e){let t=new Intl.Locale(r);e="getWeekInfo"in t?t.getWeekInfo():t.weekInfo,En[r]=e}return e}function ao(r){let e=r.indexOf("-x-");e!==-1&&(r=r.substring(0,e));let t=r.indexOf("-u-");if(t===-1)return[r];{let n,s;try{n=gr(r).resolvedOptions(),s=r}catch{let c=r.substring(0,t);n=gr(c).resolvedOptions(),s=c}let{numberingSystem:a,calendar:i}=n;return[s,a,i]}}function io(r,e,t){return(t||e)&&(r.includes("-u-")||(r+="-u"),t&&(r+=`-ca-${t}`),e&&(r+=`-nu-${e}`)),r}function oo(r){let e=[];for(let t=1;t<=12;t++){let n=g.utc(2009,t,1);e.push(r(n))}return e}function co(r){let e=[];for(let t=1;t<=7;t++){let n=g.utc(2016,11,13+t);e.push(r(n))}return e}function Dt(r,e,t,n){let s=r.listingMode();return s==="error"?null:s==="en"?t(e):n(e)}function uo(r){return r.numberingSystem&&r.numberingSystem!=="latn"?!1:r.numberingSystem==="latn"||!r.locale||r.locale.startsWith("en")||new Intl.DateTimeFormat(r.intl).resolvedOptions().numberingSystem==="latn"}var wr=class{constructor(e,t,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:s,floor:a,...i}=n;if(!t||Object.keys(i).length>0){let o={useGrouping:!1,...n};n.padTo>0&&(o.minimumIntegerDigits=n.padTo),this.inf=to(e,o)}}format(e){if(this.inf){let t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{let t=this.floor?Math.floor(e):be(e,3);return I(t,this.padTo)}}},Sr=class{constructor(e,t,n){this.opts=n,this.originalZone=void 0;let s;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let i=-1*(e.offset/60),o=i>=0?`Etc/GMT+${i}`:`Etc/GMT${i}`;e.offset!==0&&M.create(o).valid?(s=o,this.dt=e):(s="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,s=e.zone.name):(s="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let a={...this.opts};a.timeZone=a.timeZone||s,this.dtf=gr(t,a)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(t=>{if(t.type==="timeZoneName"){let n=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...t,value:n}}else return t}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},Tr=class{constructor(e,t,n){this.opts={style:"long",...n},!t&&At()&&(this.rtf=ro(e,n))}format(e,t){return this.rtf?this.rtf.format(e,t):Cn(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}},lo={firstDay:1,minimalDays:4,weekend:[6,7]},S=class r{static fromOpts(e){return r.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,t,n,s,a=!1){let i=e||b.defaultLocale,o=i||(a?"en-US":no()),c=t||b.defaultNumberingSystem,u=n||b.defaultOutputCalendar,l=it(s)||b.defaultWeekSettings;return new r(o,c,u,l,i)}static resetCache(){at=null,pr={},yr={},br={}}static fromObject({locale:e,numberingSystem:t,outputCalendar:n,weekSettings:s}={}){return r.create(e,t,n,s)}constructor(e,t,n,s,a){let[i,o,c]=ao(e);this.locale=i,this.numberingSystem=t||o||null,this.outputCalendar=n||c||null,this.weekSettings=s,this.intl=io(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=a,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=uo(this)),this.fastNumbersCached}listingMode(){let 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:r.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,it(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 Dt(this,e,Ir,()=>{let n=t?{month:e,day:"numeric"}:{month:e},s=t?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=oo(a=>this.extract(a,n,"month"))),this.monthsCache[s][e]})}weekdays(e,t=!1){return Dt(this,e,xr,()=>{let n=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},s=t?"format":"standalone";return this.weekdaysCache[s][e]||(this.weekdaysCache[s][e]=co(a=>this.extract(a,n,"weekday"))),this.weekdaysCache[s][e]})}meridiems(){return Dt(this,void 0,()=>kr,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[g.utc(2016,11,13,9),g.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return Dt(this,e,Or,()=>{let t={era:e};return this.eraCache[e]||(this.eraCache[e]=[g.utc(-40,1,1),g.utc(2017,1,1)].map(n=>this.extract(n,t,"era"))),this.eraCache[e]})}extract(e,t,n){let s=this.dtFormatter(e,t),a=s.formatToParts(),i=a.find(o=>o.type.toLowerCase()===n);return i?i.value:null}numberFormatter(e={}){return new wr(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new Sr(e,this.intl,t)}relFormatter(e={}){return new Tr(this.intl,this.isEnglish(),e)}listFormatter(e={}){return eo(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Pt()?so(this.locale):lo}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}};var Er=null,O=class r extends D{static get utcInstance(){return Er===null&&(Er=new r(0)),Er}static instance(e){return e===0?r.utcInstance:new r(e)}static parseSpecifier(e){if(e){let t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new r(oe(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Q(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Q(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return Q(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}};var we=class extends D{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 U(r,e){let t;if(f(r)||r===null)return e;if(r instanceof D)return r;if(Mn(r)){let n=r.toLowerCase();return n==="default"?e:n==="local"||n==="system"?J.instance:n==="utc"||n==="gmt"?O.utcInstance:O.parseSpecifier(n)||M.create(r)}else return $(r)?O.instance(r):typeof r=="object"&&"offset"in r&&typeof r.offset=="function"?r:new we(r)}var Dn=()=>Date.now(),An="system",Pn=null,Nn=null,Fn=null,Rn=60,jn,_n=null,b=class{static get now(){return Dn}static set now(e){Dn=e}static set defaultZone(e){An=e}static get defaultZone(){return U(An,J.instance)}static get defaultLocale(){return Pn}static set defaultLocale(e){Pn=e}static get defaultNumberingSystem(){return Nn}static set defaultNumberingSystem(e){Nn=e}static get defaultOutputCalendar(){return Fn}static set defaultOutputCalendar(e){Fn=e}static get defaultWeekSettings(){return _n}static set defaultWeekSettings(e){_n=it(e)}static get twoDigitCutoffYear(){return Rn}static set twoDigitCutoffYear(e){Rn=e%100}static get throwOnInvalid(){return jn}static set throwOnInvalid(e){jn=e}static resetCaches(){S.resetCache(),M.resetCache()}};var v=class{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var Bn=[0,31,59,90,120,151,181,212,243,273,304,334],Wn=[0,31,60,91,121,152,182,213,244,274,305,335];function R(r,e){return new v("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${r}, which is invalid`)}function Nt(r,e,t){let n=new Date(Date.UTC(r,e-1,t));r<100&&r>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let s=n.getUTCDay();return s===0?7:s}function Ln(r,e,t){return t+(ue(r)?Wn:Bn)[e-1]}function Un(r,e){let t=ue(r)?Wn:Bn,n=t.findIndex(a=>a<e),s=e-t[n];return{month:n+1,day:s}}function Ft(r,e){return(r-e+7)%7+1}function ot(r,e=4,t=1){let{year:n,month:s,day:a}=r,i=Ln(n,s,a),o=Ft(Nt(n,s,a),t),c=Math.floor((i-o+14-e)/7),u;return c<1?(u=n-1,c=ce(u,e,t)):c>ce(n,e,t)?(u=n+1,c=1):u=n,{weekYear:u,weekNumber:c,weekday:o,...ut(r)}}function Cr(r,e=4,t=1){let{weekYear:n,weekNumber:s,weekday:a}=r,i=Ft(Nt(n,1,e),t),o=X(n),c=s*7+a-i-7+e,u;c<1?(u=n-1,c+=X(u)):c>o?(u=n+1,c-=X(n)):u=n;let{month:l,day:h}=Un(u,c);return{year:u,month:l,day:h,...ut(r)}}function Rt(r){let{year:e,month:t,day:n}=r,s=Ln(e,t,n);return{year:e,ordinal:s,...ut(r)}}function Mr(r){let{year:e,ordinal:t}=r,{month:n,day:s}=Un(e,t);return{year:e,month:n,day:s,...ut(r)}}function Dr(r,e){if(!f(r.localWeekday)||!f(r.localWeekNumber)||!f(r.localWeekYear)){if(!f(r.weekday)||!f(r.weekNumber)||!f(r.weekYear))throw new B("Cannot mix locale-based week fields with ISO-based week fields");return f(r.localWeekday)||(r.weekday=r.localWeekday),f(r.localWeekNumber)||(r.weekNumber=r.localWeekNumber),f(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}}function Vn(r,e=4,t=1){let n=ct(r.weekYear),s=P(r.weekNumber,1,ce(r.weekYear,e,t)),a=P(r.weekday,1,7);return n?s?a?!1:R("weekday",r.weekday):R("week",r.weekNumber):R("weekYear",r.weekYear)}function qn(r){let e=ct(r.year),t=P(r.ordinal,1,X(r.year));return e?t?!1:R("ordinal",r.ordinal):R("year",r.year)}function Ar(r){let e=ct(r.year),t=P(r.month,1,12),n=P(r.day,1,Se(r.year,r.month));return e?t?n?!1:R("day",r.day):R("month",r.month):R("year",r.year)}function Pr(r){let{hour:e,minute:t,second:n,millisecond:s}=r,a=P(e,0,23)||e===24&&t===0&&n===0&&s===0,i=P(t,0,59),o=P(n,0,59),c=P(s,0,999);return a?i?o?c?!1:R("millisecond",s):R("second",n):R("minute",t):R("hour",e)}function f(r){return typeof r>"u"}function $(r){return typeof r=="number"}function ct(r){return typeof r=="number"&&r%1===0}function Mn(r){return typeof r=="string"}function $n(r){return Object.prototype.toString.call(r)==="[object Date]"}function At(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Pt(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function Gn(r){return Array.isArray(r)?r:[r]}function Nr(r,e,t){if(r.length!==0)return r.reduce((n,s)=>{let a=[e(s),s];return n&&t(n[0],a[0])===n[0]?n:a},null)[1]}function zn(r,e){return e.reduce((t,n)=>(t[n]=r[n],t),{})}function ee(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function it(r){if(r==null)return null;if(typeof r!="object")throw new x("Week settings must be an object");if(!P(r.firstDay,1,7)||!P(r.minimalDays,1,7)||!Array.isArray(r.weekend)||r.weekend.some(e=>!P(e,1,7)))throw new x("Invalid week settings");return{firstDay:r.firstDay,minimalDays:r.minimalDays,weekend:Array.from(r.weekend)}}function P(r,e,t){return ct(r)&&r>=e&&r<=t}function mo(r,e){return r-e*Math.floor(r/e)}function I(r,e=2){let t=r<0,n;return t?n="-"+(""+-r).padStart(e,"0"):n=(""+r).padStart(e,"0"),n}function z(r){if(!(f(r)||r===null||r===""))return parseInt(r,10)}function te(r){if(!(f(r)||r===null||r===""))return parseFloat(r)}function lt(r){if(!(f(r)||r===null||r==="")){let e=parseFloat("0."+r)*1e3;return Math.floor(e)}}function be(r,e,t=!1){let n=10**e;return(t?Math.trunc:Math.round)(r*n)/n}function ue(r){return r%4===0&&(r%100!==0||r%400===0)}function X(r){return ue(r)?366:365}function Se(r,e){let t=mo(e-1,12)+1,n=r+(e-t)/12;return t===2?ue(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function ye(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}function Hn(r,e,t){return-Ft(Nt(r,1,e),t)+e-1}function ce(r,e=4,t=1){let n=Hn(r,e,t),s=Hn(r+1,e,t);return(X(r)-n+s)/7}function dt(r){return r>99?r:r>b.twoDigitCutoffYear?1900+r:2e3+r}function Et(r,e,t,n=null){let s=new Date(r),a={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(a.timeZone=n);let i={timeZoneName:e,...a},o=new Intl.DateTimeFormat(t,i).formatToParts(s).find(c=>c.type.toLowerCase()==="timezonename");return o?o.value:null}function oe(r,e){let t=parseInt(r,10);Number.isNaN(t)&&(t=0);let n=parseInt(e,10)||0,s=t<0||Object.is(t,-0)?-n:n;return t*60+s}function Fr(r){let e=Number(r);if(typeof r=="boolean"||r===""||Number.isNaN(e))throw new x(`Invalid unit value ${r}`);return e}function Te(r,e){let t={};for(let n in r)if(ee(r,n)){let s=r[n];if(s==null)continue;t[e(n)]=Fr(s)}return t}function Q(r,e){let t=Math.trunc(Math.abs(r/60)),n=Math.trunc(Math.abs(r%60)),s=r>=0?"+":"-";switch(e){case"short":return`${s}${I(t,2)}:${I(n,2)}`;case"narrow":return`${s}${t}${n>0?`:${n}`:""}`;case"techie":return`${s}${I(t,2)}${I(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function ut(r){return zn(r,["hour","minute","second","millisecond"])}var fo=["January","February","March","April","May","June","July","August","September","October","November","December"],Rr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ho=["J","F","M","A","M","J","J","A","S","O","N","D"];function Ir(r){switch(r){case"narrow":return[...ho];case"short":return[...Rr];case"long":return[...fo];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}}var jr=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],_r=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],po=["M","T","W","T","F","S","S"];function xr(r){switch(r){case"narrow":return[...po];case"short":return[..._r];case"long":return[...jr];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var kr=["AM","PM"],go=["Before Christ","Anno Domini"],yo=["BC","AD"],bo=["B","A"];function Or(r){switch(r){case"narrow":return[...bo];case"short":return[...yo];case"long":return[...go];default:return null}}function Zn(r){return kr[r.hour<12?0:1]}function Kn(r,e){return xr(e)[r.weekday-1]}function Yn(r,e){return Ir(e)[r.month-1]}function Jn(r,e){return Or(e)[r.year<0?0:1]}function Cn(r,e,t="always",n=!1){let s={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."]},a=["hours","minutes","seconds"].indexOf(r)===-1;if(t==="auto"&&a){let h=r==="days";switch(e){case 1:return h?"tomorrow":`next ${s[r][0]}`;case-1:return h?"yesterday":`last ${s[r][0]}`;case 0:return h?"today":`this ${s[r][0]}`;default:}}let i=Object.is(e,-0)||e<0,o=Math.abs(e),c=o===1,u=s[r],l=n?c?u[1]:u[2]||u[1]:c?s[r][0]:r;return i?`${o} ${l} ago`:`in ${o} ${l}`}function Qn(r,e){let t="";for(let n of r)n.literal?t+=n.val:t+=e(n.val);return t}var wo={D:Y,DD:Le,DDD:Ue,DDDD:Ve,t:qe,tt:He,ttt:$e,tttt:Ge,T:ze,TT:Ze,TTT:Ke,TTTT:Ye,f:Je,ff:Xe,fff:tt,ffff:nt,F:Qe,FF:et,FFF:rt,FFFF:st},E=class r{static create(e,t={}){return new r(e,t)}static parseFormat(e){let t=null,n="",s=!1,a=[];for(let i=0;i<e.length;i++){let o=e.charAt(i);o==="'"?(n.length>0&&a.push({literal:s||/^\s+$/.test(n),val:n}),t=null,n="",s=!s):s||o===t?n+=o:(n.length>0&&a.push({literal:/^\s+$/.test(n),val:n}),n=o,t=o)}return n.length>0&&a.push({literal:s||/^\s+$/.test(n),val:n}),a}static macroTokenToFormatOpts(e){return wo[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){if(this.opts.forceSimple)return I(e,t);let n={...this.opts};return t>0&&(n.padTo=t),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,t){let n=this.loc.listingMode()==="en",s=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",a=(m,k)=>this.loc.extract(e,m,k),i=m=>e.isOffsetFixed&&e.offset===0&&m.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,m.format):"",o=()=>n?Zn(e):a({hour:"numeric",hourCycle:"h12"},"dayperiod"),c=(m,k)=>n?Yn(e,m):a(k?{month:m}:{month:m,day:"numeric"},"month"),u=(m,k)=>n?Kn(e,m):a(k?{weekday:m}:{weekday:m,month:"long",day:"numeric"},"weekday"),l=m=>{let k=r.macroTokenToFormatOpts(m);return k?this.formatWithSystemDefault(e,k):m},h=m=>n?Jn(e,m):a({era:m},"era"),y=m=>{switch(m){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 i({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return i({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return i({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 o();case"d":return s?a({day:"numeric"},"day"):this.num(e.day);case"dd":return s?a({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return u("short",!0);case"cccc":return u("long",!0);case"ccccc":return u("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return u("short",!1);case"EEEE":return u("long",!1);case"EEEEE":return u("narrow",!1);case"L":return s?a({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return s?a({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return c("short",!0);case"LLLL":return c("long",!0);case"LLLLL":return c("narrow",!0);case"M":return s?a({month:"numeric"},"month"):this.num(e.month);case"MM":return s?a({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return c("short",!1);case"MMMM":return c("long",!1);case"MMMMM":return c("narrow",!1);case"y":return s?a({year:"numeric"},"year"):this.num(e.year);case"yy":return s?a({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return s?a({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return s?a({year:"numeric"},"year"):this.num(e.year,6);case"G":return h("short");case"GG":return h("long");case"GGGGG":return h("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 l(m)}};return Qn(r.parseFormat(t),y)}formatDurationFromString(e,t){let n=c=>{switch(c[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},s=c=>u=>{let l=n(u);return l?this.num(c.get(l),u.length):u},a=r.parseFormat(t),i=a.reduce((c,{literal:u,val:l})=>u?c:c.concat(l),[]),o=e.shiftTo(...i.map(n).filter(c=>c));return Qn(a,s(o))}};var es=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function xe(...r){let e=r.reduce((t,n)=>t+n.source,"");return RegExp(`^${e}$`)}function ke(...r){return e=>r.reduce(([t,n,s],a)=>{let[i,o,c]=a(e,s);return[{...t,...i},o||n,c]},[{},null,1]).slice(0,2)}function Oe(r,...e){if(r==null)return[null,null];for(let[t,n]of e){let s=t.exec(r);if(s)return n(s)}return[null,null]}function ts(...r){return(e,t)=>{let n={},s;for(s=0;s<r.length;s++)n[r[s]]=z(e[t+s]);return[n,null,t+s]}}var rs=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,So=`(?:${rs.source}?(?:\\[(${es.source})\\])?)?`,Br=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,ns=RegExp(`${Br.source}${So}`),Wr=RegExp(`(?:T${ns.source})?`),To=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Io=/(\d{4})-?W(\d\d)(?:-?(\d))?/,xo=/(\d{4})-?(\d{3})/,ko=ts("weekYear","weekNumber","weekDay"),Oo=ts("year","ordinal"),vo=/(\d{4})-(\d\d)-(\d\d)/,ss=RegExp(`${Br.source} ?(?:${rs.source}|(${es.source}))?`),Eo=RegExp(`(?: ${ss.source})?`);function Ie(r,e,t){let n=r[e];return f(n)?t:z(n)}function Co(r,e){return[{year:Ie(r,e),month:Ie(r,e+1,1),day:Ie(r,e+2,1)},null,e+3]}function ve(r,e){return[{hours:Ie(r,e,0),minutes:Ie(r,e+1,0),seconds:Ie(r,e+2,0),milliseconds:lt(r[e+3])},null,e+4]}function mt(r,e){let t=!r[e]&&!r[e+1],n=oe(r[e+1],r[e+2]),s=t?null:O.instance(n);return[{},s,e+3]}function ft(r,e){let t=r[e]?M.create(r[e]):null;return[{},t,e+1]}var Mo=RegExp(`^T?${Br.source}$`),Do=/^-?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 Ao(r){let[e,t,n,s,a,i,o,c,u]=r,l=e[0]==="-",h=c&&c[0]==="-",y=(m,k=!1)=>m!==void 0&&(k||m&&l)?-m:m;return[{years:y(te(t)),months:y(te(n)),weeks:y(te(s)),days:y(te(a)),hours:y(te(i)),minutes:y(te(o)),seconds:y(te(c),c==="-0"),milliseconds:y(lt(u),h)}]}var Po={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function Lr(r,e,t,n,s,a,i){let o={year:e.length===2?dt(z(e)):z(e),month:Rr.indexOf(t)+1,day:z(n),hour:z(s),minute:z(a)};return i&&(o.second=z(i)),r&&(o.weekday=r.length>3?jr.indexOf(r)+1:_r.indexOf(r)+1),o}var No=/^(?:(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 Fo(r){let[,e,t,n,s,a,i,o,c,u,l,h]=r,y=Lr(e,s,n,t,a,i,o),m;return c?m=Po[c]:u?m=0:m=oe(l,h),[y,new O(m)]}function Ro(r){return r.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var jo=/^(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$/,_o=/^(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$/,Bo=/^(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 Xn(r){let[,e,t,n,s,a,i,o]=r;return[Lr(e,s,n,t,a,i,o),O.utcInstance]}function Wo(r){let[,e,t,n,s,a,i,o]=r;return[Lr(e,o,t,n,s,a,i),O.utcInstance]}var Lo=xe(To,Wr),Uo=xe(Io,Wr),Vo=xe(xo,Wr),qo=xe(ns),as=ke(Co,ve,mt,ft),Ho=ke(ko,ve,mt,ft),$o=ke(Oo,ve,mt,ft),Go=ke(ve,mt,ft);function is(r){return Oe(r,[Lo,as],[Uo,Ho],[Vo,$o],[qo,Go])}function os(r){return Oe(Ro(r),[No,Fo])}function cs(r){return Oe(r,[jo,Xn],[_o,Xn],[Bo,Wo])}function us(r){return Oe(r,[Do,Ao])}var zo=ke(ve);function ls(r){return Oe(r,[Mo,zo])}var Zo=xe(vo,Eo),Ko=xe(ss),Yo=ke(ve,mt,ft);function ds(r){return Oe(r,[Zo,as],[Ko,Yo])}var ms="Invalid Duration",hs={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},Jo={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:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...hs},j=146097/400,Ee=146097/4800,Qo={years:{quarters:4,months:12,weeks:j/7,days:j,hours:j*24,minutes:j*24*60,seconds:j*24*60*60,milliseconds:j*24*60*60*1e3},quarters:{months:3,weeks:j/28,days:j/4,hours:j*24/4,minutes:j*24*60/4,seconds:j*24*60*60/4,milliseconds:j*24*60*60*1e3/4},months:{weeks:Ee/7,days:Ee,hours:Ee*24,minutes:Ee*24*60,seconds:Ee*24*60*60,milliseconds:Ee*24*60*60*1e3},...hs},le=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Xo=le.slice(0).reverse();function re(r,e,t=!1){let n={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 T(n)}function ps(r,e){let t=e.milliseconds??0;for(let n of Xo.slice(1))e[n]&&(t+=e[n]*r[n].milliseconds);return t}function fs(r,e){let t=ps(r,e)<0?-1:1;le.reduceRight((n,s)=>{if(f(e[s]))return n;if(n){let a=e[n]*t,i=r[s][n],o=Math.floor(a/i);e[s]+=o*t,e[n]-=o*i*t}return s},null),le.reduce((n,s)=>{if(f(e[s]))return n;if(n){let a=e[n]%1;e[n]-=a,e[s]+=a*r[n][s]}return s},null)}function ec(r){let e={};for(let[t,n]of Object.entries(r))n!==0&&(e[t]=n);return e}var T=class r{constructor(e){let t=e.conversionAccuracy==="longterm"||!1,n=t?Qo:Jo;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||S.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(e,t){return r.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new x(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new r({values:Te(e,r.normalizeUnit),loc:S.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if($(e))return r.fromMillis(e);if(r.isDuration(e))return e;if(typeof e=="object")return r.fromObject(e);throw new x(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){let[n]=us(e);return n?r.fromObject(n,t):r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){let[n]=ls(e);return n?r.fromObject(n,t):r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new x("need to specify a reason the Duration is invalid");let n=e instanceof v?e:new v(e,t);if(b.throwOnInvalid)throw new Ot(n);return new r({invalid:n})}static normalizeUnit(e){let 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 ge(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={}){let n={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?E.create(this.loc,n).formatDurationFromString(this,e):ms}toHuman(e={}){if(!this.isValid)return ms;let t=le.map(n=>{let s=this.values[n];return f(s)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(s)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(t)}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+=be(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},g.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?ps(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let t=r.fromDurationLike(e),n={};for(let s of le)(ee(t.values,s)||ee(this.values,s))&&(n[s]=t.get(s)+this.get(s));return re(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let t=r.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;let t={};for(let n of Object.keys(this.values))t[n]=Fr(e(this.values[n],n));return re(this,{values:t},!0)}get(e){return this[r.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let t={...this.values,...Te(e,r.normalizeUnit)};return re(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:n,matrix:s}={}){let i={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:s,conversionAccuracy:n};return re(this,i)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return fs(this.matrix,e),re(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=ec(this.normalize().shiftToAll().toObject());return re(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(i=>r.normalizeUnit(i));let t={},n={},s=this.toObject(),a;for(let i of le)if(e.indexOf(i)>=0){a=i;let o=0;for(let u in n)o+=this.matrix[u][i]*n[u],n[u]=0;$(s[i])&&(o+=s[i]);let c=Math.trunc(o);t[i]=c,n[i]=(o*1e3-c*1e3)/1e3}else $(s[i])&&(n[i]=s[i]);for(let i in n)n[i]!==0&&(t[a]+=i===a?n[i]:n[i]/this.matrix[a][i]);return fs(this.matrix,t),re(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;let e={};for(let t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return re(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(n,s){return n===void 0||n===0?s===void 0||s===0:n===s}for(let n of le)if(!t(this.values[n],e.values[n]))return!1;return!0}};var Ce="Invalid Interval";function tc(r,e){return!r||!r.isValid?Z.invalid("missing or invalid start"):!e||!e.isValid?Z.invalid("missing or invalid end"):e<r?Z.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}var Z=class r{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 x("need to specify a reason the Interval is invalid");let n=e instanceof v?e:new v(e,t);if(b.throwOnInvalid)throw new kt(n);return new r({invalid:n})}static fromDateTimes(e,t){let n=Me(e),s=Me(t),a=tc(n,s);return a??new r({start:n,end:s})}static after(e,t){let n=T.fromDurationLike(t),s=Me(e);return r.fromDateTimes(s,s.plus(n))}static before(e,t){let n=T.fromDurationLike(t),s=Me(e);return r.fromDateTimes(s.minus(n),s)}static fromISO(e,t){let[n,s]=(e||"").split("/",2);if(n&&s){let a,i;try{a=g.fromISO(n,t),i=a.isValid}catch{i=!1}let o,c;try{o=g.fromISO(s,t),c=o.isValid}catch{c=!1}if(i&&c)return r.fromDateTimes(a,o);if(i){let u=T.fromISO(s,t);if(u.isValid)return r.after(a,u)}else if(c){let u=T.fromISO(n,t);if(u.isValid)return r.before(o,u)}}return r.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 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;let n=this.start.startOf(e,t),s;return t?.useLocaleWeeks?s=this.end.reconfigure({locale:n.locale}):s=this.end,s=s.startOf(e,t),Math.floor(s.diff(n,e).get(e))+(s.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?r.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];let t=e.map(Me).filter(i=>this.contains(i)).sort((i,o)=>i.toMillis()-o.toMillis()),n=[],{s}=this,a=0;for(;s<this.e;){let i=t[a]||this.e,o=+i>+this.e?this.e:i;n.push(r.fromDateTimes(s,o)),s=o,a+=1}return n}splitBy(e){let t=T.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s:n}=this,s=1,a,i=[];for(;n<this.e;){let o=this.start.plus(t.mapUnits(c=>c*s));a=+o>+this.e?this.e:o,i.push(r.fromDateTimes(n,a)),n=a,s+=1}return i}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;let t=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return t>=n?null:r.fromDateTimes(t,n)}union(e){if(!this.isValid)return this;let t=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return r.fromDateTimes(t,n)}static merge(e){let[t,n]=e.sort((s,a)=>s.s-a.s).reduce(([s,a],i)=>a?a.overlaps(i)||a.abutsStart(i)?[s,a.union(i)]:[s.concat([a]),i]:[s,i],[[],null]);return n&&t.push(n),t}static xor(e){let t=null,n=0,s=[],a=e.map(c=>[{time:c.s,type:"s"},{time:c.e,type:"e"}]),i=Array.prototype.concat(...a),o=i.sort((c,u)=>c.time-u.time);for(let c of o)n+=c.type==="s"?1:-1,n===1?t=c.time:(t&&+t!=+c.time&&s.push(r.fromDateTimes(t,c.time)),t=null);return r.merge(s)}difference(...e){return r.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()})`:Ce}[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=Y,t={}){return this.isValid?E.create(this.s.loc.clone(t),e).formatInterval(this):Ce}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Ce}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Ce}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Ce}toFormat(e,{separator:t=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:Ce}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):T.invalid(this.invalidReason)}mapEndpoints(e){return r.fromDateTimes(e(this.s),e(this.e))}};var K=class{static hasDST(e=b.defaultZone){let t=g.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return M.isValidZone(e)}static normalizeZone(e){return U(e,b.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||S.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||S.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||S.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null,outputCalendar:a="gregory"}={}){return(s||S.create(t,n,a)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null,outputCalendar:a="gregory"}={}){return(s||S.create(t,n,a)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null}={}){return(s||S.create(t,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null}={}){return(s||S.create(t,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return S.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return S.create(t,null,"gregory").eras(e)}static features(){return{relative:At(),localeWeek:Pt()}}};function gs(r,e){let t=s=>s.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=t(e)-t(r);return Math.floor(T.fromMillis(n).as("days"))}function rc(r,e,t){let n=[["years",(c,u)=>u.year-c.year],["quarters",(c,u)=>u.quarter-c.quarter+(u.year-c.year)*4],["months",(c,u)=>u.month-c.month+(u.year-c.year)*12],["weeks",(c,u)=>{let l=gs(c,u);return(l-l%7)/7}],["days",gs]],s={},a=r,i,o;for(let[c,u]of n)t.indexOf(c)>=0&&(i=c,s[c]=u(r,e),o=a.plus(s),o>e?(s[c]--,r=a.plus(s),r>e&&(o=r,s[c]--,r=a.plus(s))):r=o);return[r,s,o,i]}function ys(r,e,t,n){let[s,a,i,o]=rc(r,e,t),c=e-s,u=t.filter(h=>["hours","minutes","seconds","milliseconds"].indexOf(h)>=0);u.length===0&&(i<e&&(i=s.plus({[o]:1})),i!==s&&(a[o]=(a[o]||0)+c/(i-s)));let l=T.fromObject(a,n);return u.length>0?T.fromMillis(c,n).shiftTo(...u).plus(l):l}var Ur={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"},bs={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]},nc=Ur.hanidec.replace(/[\[|\]]/g,"").split("");function ws(r){let e=parseInt(r,10);if(isNaN(e)){e="";for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);if(r[t].search(Ur.hanidec)!==-1)e+=nc.indexOf(r[t]);else for(let s in bs){let[a,i]=bs[s];n>=a&&n<=i&&(e+=n-a)}}return parseInt(e,10)}else return e}function _({numberingSystem:r},e=""){return new RegExp(`${Ur[r||"latn"]}${e}`)}var sc="missing Intl.DateTimeFormat.formatToParts support";function w(r,e=t=>t){return{regex:r,deser:([t])=>e(ws(t))}}var ac="\xA0",Is=`[ ${ac}]`,xs=new RegExp(Is,"g");function ic(r){return r.replace(/\./g,"\\.?").replace(xs,Is)}function Ss(r){return r.replace(/\./g,"").replace(xs," ").toLowerCase()}function V(r,e){return r===null?null:{regex:RegExp(r.map(ic).join("|")),deser:([t])=>r.findIndex(n=>Ss(t)===Ss(n))+e}}function Ts(r,e){return{regex:r,deser:([,t,n])=>oe(t,n),groups:e}}function jt(r){return{regex:r,deser:([e])=>e}}function oc(r){return r.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function cc(r,e){let t=_(e),n=_(e,"{2}"),s=_(e,"{3}"),a=_(e,"{4}"),i=_(e,"{6}"),o=_(e,"{1,2}"),c=_(e,"{1,3}"),u=_(e,"{1,6}"),l=_(e,"{1,9}"),h=_(e,"{2,4}"),y=_(e,"{4,6}"),m=H=>({regex:RegExp(oc(H.val)),deser:([pe])=>pe,literal:!0}),he=(H=>{if(r.literal)return m(H);switch(H.val){case"G":return V(e.eras("short"),0);case"GG":return V(e.eras("long"),0);case"y":return w(u);case"yy":return w(h,dt);case"yyyy":return w(a);case"yyyyy":return w(y);case"yyyyyy":return w(i);case"M":return w(o);case"MM":return w(n);case"MMM":return V(e.months("short",!0),1);case"MMMM":return V(e.months("long",!0),1);case"L":return w(o);case"LL":return w(n);case"LLL":return V(e.months("short",!1),1);case"LLLL":return V(e.months("long",!1),1);case"d":return w(o);case"dd":return w(n);case"o":return w(c);case"ooo":return w(s);case"HH":return w(n);case"H":return w(o);case"hh":return w(n);case"h":return w(o);case"mm":return w(n);case"m":return w(o);case"q":return w(o);case"qq":return w(n);case"s":return w(o);case"ss":return w(n);case"S":return w(c);case"SSS":return w(s);case"u":return jt(l);case"uu":return jt(o);case"uuu":return w(t);case"a":return V(e.meridiems(),0);case"kkkk":return w(a);case"kk":return w(h,dt);case"W":return w(o);case"WW":return w(n);case"E":case"c":return w(t);case"EEE":return V(e.weekdays("short",!1),1);case"EEEE":return V(e.weekdays("long",!1),1);case"ccc":return V(e.weekdays("short",!0),1);case"cccc":return V(e.weekdays("long",!0),1);case"Z":case"ZZ":return Ts(new RegExp(`([+-]${o.source})(?::(${n.source}))?`),2);case"ZZZ":return Ts(new RegExp(`([+-]${o.source})(${n.source})?`),2);case"z":return jt(/[a-z_+-/]{1,256}?/i);case" ":return jt(/[^\S\n\r]/);default:return m(H)}})(r)||{invalidReason:sc};return he.token=r,he}var uc={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 lc(r,e,t){let{type:n,value:s}=r;if(n==="literal"){let c=/^\s+$/.test(s);return{literal:!c,val:c?" ":s}}let a=e[n],i=n;n==="hour"&&(e.hour12!=null?i=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?i="hour12":i="hour24":i=t.hour12?"hour12":"hour24");let o=uc[i];if(typeof o=="object"&&(o=o[a]),o)return{literal:!1,val:o}}function dc(r){return[`^${r.map(t=>t.regex).reduce((t,n)=>`${t}(${n.source})`,"")}$`,r]}function mc(r,e,t){let n=r.match(e);if(n){let s={},a=1;for(let i in t)if(ee(t,i)){let o=t[i],c=o.groups?o.groups+1:1;!o.literal&&o.token&&(s[o.token.val[0]]=o.deser(n.slice(a,a+c))),a+=c}return[n,s]}else return[n,{}]}function fc(r){let e=a=>{switch(a){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}},t=null,n;return f(r.z)||(t=M.create(r.z)),f(r.Z)||(t||(t=new O(r.Z)),n=r.Z),f(r.q)||(r.M=(r.q-1)*3+1),f(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),f(r.u)||(r.S=lt(r.u)),[Object.keys(r).reduce((a,i)=>{let o=e(i);return o&&(a[o]=r[i]),a},{}),t,n]}var Vr=null;function hc(){return Vr||(Vr=g.fromMillis(1555555555555)),Vr}function pc(r,e){if(r.literal)return r;let t=E.macroTokenToFormatOpts(r.val),n=$r(t,e);return n==null||n.includes(void 0)?r:n}function qr(r,e){return Array.prototype.concat(...r.map(t=>pc(t,e)))}function Hr(r,e,t){let n=qr(E.parseFormat(t),r),s=n.map(i=>cc(i,r)),a=s.find(i=>i.invalidReason);if(a)return{input:e,tokens:n,invalidReason:a.invalidReason};{let[i,o]=dc(s),c=RegExp(i,"i"),[u,l]=mc(e,c,o),[h,y,m]=l?fc(l):[null,null,void 0];if(ee(l,"a")&&ee(l,"H"))throw new B("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:c,rawMatches:u,matches:l,result:h,zone:y,specificOffset:m}}}function ks(r,e,t){let{result:n,zone:s,specificOffset:a,invalidReason:i}=Hr(r,e,t);return[n,s,a,i]}function $r(r,e){if(!r)return null;let n=E.create(e,r).dtFormatter(hc()),s=n.formatToParts(),a=n.resolvedOptions();return s.map(i=>lc(i,r,a))}var Gr="Invalid DateTime",Os=864e13;function _t(r){return new v("unsupported zone",`the zone "${r.name}" is not supported`)}function zr(r){return r.weekData===null&&(r.weekData=ot(r.c)),r.weekData}function Zr(r){return r.localWeekData===null&&(r.localWeekData=ot(r.c,r.loc.getMinDaysInFirstWeek(),r.loc.getStartOfWeek())),r.localWeekData}function de(r,e){let t={ts:r.ts,zone:r.zone,c:r.c,o:r.o,loc:r.loc,invalid:r.invalid};return new g({...t,...e,old:t})}function Ps(r,e,t){let n=r-e*60*1e3,s=t.offset(n);if(e===s)return[n,e];n-=(s-e)*60*1e3;let a=t.offset(n);return s===a?[n,s]:[r-Math.min(s,a)*60*1e3,Math.max(s,a)]}function Bt(r,e){r+=e*60*1e3;let 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()}}function Lt(r,e,t){return Ps(ye(r),e,t)}function vs(r,e){let t=r.o,n=r.c.year+Math.trunc(e.years),s=r.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,a={...r.c,year:n,month:s,day:Math.min(r.c.day,Se(n,s))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},i=T.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"),o=ye(a),[c,u]=Ps(o,t,r.zone);return i!==0&&(c+=i,u=r.zone.offset(c)),{ts:c,o:u}}function ht(r,e,t,n,s,a){let{setZone:i,zone:o}=t;if(r&&Object.keys(r).length!==0||e){let c=e||o,u=g.fromObject(r,{...t,zone:c,specificOffset:a});return i?u:u.setZone(o)}else return g.invalid(new v("unparsable",`the input "${s}" can't be parsed as ${n}`))}function Wt(r,e,t=!0){return r.isValid?E.create(S.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(r,e):null}function Kr(r,e){let t=r.c.year>9999||r.c.year<0,n="";return t&&r.c.year>=0&&(n+="+"),n+=I(r.c.year,t?6:4),e?(n+="-",n+=I(r.c.month),n+="-",n+=I(r.c.day)):(n+=I(r.c.month),n+=I(r.c.day)),n}function Es(r,e,t,n,s,a){let i=I(r.c.hour);return e?(i+=":",i+=I(r.c.minute),(r.c.millisecond!==0||r.c.second!==0||!t)&&(i+=":")):i+=I(r.c.minute),(r.c.millisecond!==0||r.c.second!==0||!t)&&(i+=I(r.c.second),(r.c.millisecond!==0||!n)&&(i+=".",i+=I(r.c.millisecond,3))),s&&(r.isOffsetFixed&&r.offset===0&&!a?i+="Z":r.o<0?(i+="-",i+=I(Math.trunc(-r.o/60)),i+=":",i+=I(Math.trunc(-r.o%60))):(i+="+",i+=I(Math.trunc(r.o/60)),i+=":",i+=I(Math.trunc(r.o%60)))),a&&(i+="["+r.zone.ianaName+"]"),i}var Ns={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},gc={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},yc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Fs=["year","month","day","hour","minute","second","millisecond"],bc=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],wc=["year","ordinal","hour","minute","second","millisecond"];function Sc(r){let 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 ge(r);return e}function Cs(r){switch(r.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return Sc(r)}}function Ms(r,e){let t=U(e.zone,b.defaultZone),n=S.fromObject(e),s=b.now(),a,i;if(f(r.year))a=s;else{for(let u of Fs)f(r[u])&&(r[u]=Ns[u]);let o=Ar(r)||Pr(r);if(o)return g.invalid(o);let c=t.offset(s);[a,i]=Lt(r,c,t)}return new g({ts:a,zone:t,loc:n,o:i})}function Ds(r,e,t){let n=f(t.round)?!0:t.round,s=(i,o)=>(i=be(i,n||t.calendary?0:2,!0),e.loc.clone(t).relFormatter(t).format(i,o)),a=i=>t.calendary?e.hasSame(r,i)?0:e.startOf(i).diff(r.startOf(i),i).get(i):e.diff(r,i).get(i);if(t.unit)return s(a(t.unit),t.unit);for(let i of t.units){let o=a(i);if(Math.abs(o)>=1)return s(o,i)}return s(r>e?-0:0,t.units[t.units.length-1])}function As(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]}var g=class r{constructor(e){let t=e.zone||b.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new v("invalid input"):null)||(t.isValid?null:_t(t));this.ts=f(e.ts)?b.now():e.ts;let s=null,a=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[s,a]=[e.old.c,e.old.o];else{let o=t.offset(this.ts);s=Bt(this.ts,o),n=Number.isNaN(s.year)?new v("invalid input"):null,s=n?null:s,a=n?null:o}this._zone=t,this.loc=e.loc||S.create(),this.invalid=n,this.weekData=null,this.localWeekData=null,this.c=s,this.o=a,this.isLuxonDateTime=!0}static now(){return new r({})}static local(){let[e,t]=As(arguments),[n,s,a,i,o,c,u]=t;return Ms({year:n,month:s,day:a,hour:i,minute:o,second:c,millisecond:u},e)}static utc(){let[e,t]=As(arguments),[n,s,a,i,o,c,u]=t;return e.zone=O.utcInstance,Ms({year:n,month:s,day:a,hour:i,minute:o,second:c,millisecond:u},e)}static fromJSDate(e,t={}){let n=$n(e)?e.valueOf():NaN;if(Number.isNaN(n))return r.invalid("invalid input");let s=U(t.zone,b.defaultZone);return s.isValid?new r({ts:n,zone:s,loc:S.fromObject(t)}):r.invalid(_t(s))}static fromMillis(e,t={}){if($(e))return e<-Os||e>Os?r.invalid("Timestamp out of range"):new r({ts:e,zone:U(t.zone,b.defaultZone),loc:S.fromObject(t)});throw new x(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if($(e))return new r({ts:e*1e3,zone:U(t.zone,b.defaultZone),loc:S.fromObject(t)});throw new x("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};let n=U(t.zone,b.defaultZone);if(!n.isValid)return r.invalid(_t(n));let s=S.fromObject(t),a=Te(e,Cs),{minDaysInFirstWeek:i,startOfWeek:o}=Dr(a,s),c=b.now(),u=f(t.specificOffset)?n.offset(c):t.specificOffset,l=!f(a.ordinal),h=!f(a.year),y=!f(a.month)||!f(a.day),m=h||y,k=a.weekYear||a.weekNumber;if((m||l)&&k)throw new B("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(y&&l)throw new B("Can't mix ordinal dates with month/day");let he=k||a.weekday&&!m,H,pe,je=Bt(c,u);he?(H=bc,pe=gc,je=ot(je,i,o)):l?(H=wc,pe=yc,je=Rt(je)):(H=Fs,pe=Ns);let In=!1;for(let _e of H){let Wi=a[_e];f(Wi)?In?a[_e]=pe[_e]:a[_e]=je[_e]:In=!0}let Ri=he?Vn(a,i,o):l?qn(a):Ar(a),xn=Ri||Pr(a);if(xn)return r.invalid(xn);let ji=he?Cr(a,i,o):l?Mr(a):a,[_i,Bi]=Lt(ji,u,n),lr=new r({ts:_i,zone:n,o:Bi,loc:s});return a.weekday&&m&&e.weekday!==lr.weekday?r.invalid("mismatched weekday",`you can't specify both a weekday of ${a.weekday} and a date of ${lr.toISO()}`):lr}static fromISO(e,t={}){let[n,s]=is(e);return ht(n,s,t,"ISO 8601",e)}static fromRFC2822(e,t={}){let[n,s]=os(e);return ht(n,s,t,"RFC 2822",e)}static fromHTTP(e,t={}){let[n,s]=cs(e);return ht(n,s,t,"HTTP",t)}static fromFormat(e,t,n={}){if(f(e)||f(t))throw new x("fromFormat requires an input string and a format");let{locale:s=null,numberingSystem:a=null}=n,i=S.fromOpts({locale:s,numberingSystem:a,defaultToEN:!0}),[o,c,u,l]=ks(i,e,t);return l?r.invalid(l):ht(o,c,n,`format ${t}`,e,u)}static fromString(e,t,n={}){return r.fromFormat(e,t,n)}static fromSQL(e,t={}){let[n,s]=ds(e);return ht(n,s,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new x("need to specify a reason the DateTime is invalid");let n=e instanceof v?e:new v(e,t);if(b.throwOnInvalid)throw new xt(n);return new r({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){let n=$r(e,S.fromObject(t));return n?n.map(s=>s?s.val:null).join(""):null}static expandFormat(e,t={}){return qr(E.parseFormat(e),S.fromObject(t)).map(s=>s.val).join("")}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?zr(this).weekYear:NaN}get weekNumber(){return this.isValid?zr(this).weekNumber:NaN}get weekday(){return this.isValid?zr(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?Zr(this).weekday:NaN}get localWeekNumber(){return this.isValid?Zr(this).weekNumber:NaN}get localWeekYear(){return this.isValid?Zr(this).weekYear:NaN}get ordinal(){return this.isValid?Rt(this.c).ordinal:NaN}get monthShort(){return this.isValid?K.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?K.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?K.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?K.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];let e=864e5,t=6e4,n=ye(this.c),s=this.zone.offset(n-e),a=this.zone.offset(n+e),i=this.zone.offset(n-s*t),o=this.zone.offset(n-a*t);if(i===o)return[this];let c=n-i*t,u=n-o*t,l=Bt(c,i),h=Bt(u,o);return l.hour===h.hour&&l.minute===h.minute&&l.second===h.second&&l.millisecond===h.millisecond?[de(this,{ts:c}),de(this,{ts:u})]:[this]}get isInLeapYear(){return ue(this.year)}get daysInMonth(){return Se(this.year,this.month)}get daysInYear(){return this.isValid?X(this.year):NaN}get weeksInWeekYear(){return this.isValid?ce(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?ce(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:t,numberingSystem:n,calendar:s}=E.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:n,outputCalendar:s}}toUTC(e=0,t={}){return this.setZone(O.instance(e),t)}toLocal(){return this.setZone(b.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:n=!1}={}){if(e=U(e,b.defaultZone),e.equals(this.zone))return this;if(e.isValid){let s=this.ts;if(t||n){let a=e.offset(this.ts),i=this.toObject();[s]=Lt(i,a,e)}return de(this,{ts:s,zone:e})}else return r.invalid(_t(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:n}={}){let s=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:n});return de(this,{loc:s})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let t=Te(e,Cs),{minDaysInFirstWeek:n,startOfWeek:s}=Dr(t,this.loc),a=!f(t.weekYear)||!f(t.weekNumber)||!f(t.weekday),i=!f(t.ordinal),o=!f(t.year),c=!f(t.month)||!f(t.day),u=o||c,l=t.weekYear||t.weekNumber;if((u||i)&&l)throw new B("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(c&&i)throw new B("Can't mix ordinal dates with month/day");let h;a?h=Cr({...ot(this.c,n,s),...t},n,s):f(t.ordinal)?(h={...this.toObject(),...t},f(t.day)&&(h.day=Math.min(Se(h.year,h.month),h.day))):h=Mr({...Rt(this.c),...t});let[y,m]=Lt(h,this.o,this.zone);return de(this,{ts:y,o:m})}plus(e){if(!this.isValid)return this;let t=T.fromDurationLike(e);return de(this,vs(this,t))}minus(e){if(!this.isValid)return this;let t=T.fromDurationLike(e).negate();return de(this,vs(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;let n={},s=T.normalizeUnit(e);switch(s){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break;case"milliseconds":break}if(s==="weeks")if(t){let a=this.loc.getStartOfWeek(),{weekday:i}=this;i<a&&(n.weekNumber=this.weekNumber-1),n.weekday=a}else n.weekday=1;if(s==="quarters"){let a=Math.ceil(this.month/3);n.month=(a-1)*3+1}return this.set(n)}endOf(e,t){return this.isValid?this.plus({[e]:1}).startOf(e,t).minus(1):this}toFormat(e,t={}){return this.isValid?E.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):Gr}toLocaleString(e=Y,t={}){return this.isValid?E.create(this.loc.clone(t),e).formatDateTime(this):Gr}toLocaleParts(e={}){return this.isValid?E.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:n=!1,includeOffset:s=!0,extendedZone:a=!1}={}){if(!this.isValid)return null;let i=e==="extended",o=Kr(this,i);return o+="T",o+=Es(this,i,t,n,s,a),o}toISODate({format:e="extended"}={}){return this.isValid?Kr(this,e==="extended"):null}toISOWeekDate(){return Wt(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:n=!0,includePrefix:s=!1,extendedZone:a=!1,format:i="extended"}={}){return this.isValid?(s?"T":"")+Es(this,i==="extended",t,e,n,a):null}toRFC2822(){return Wt(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Wt(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Kr(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:n=!0}={}){let s="HH:mm:ss.SSS";return(t||e)&&(n&&(s+=" "),t?s+="z":e&&(s+="ZZ")),Wt(this,s,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():Gr}[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{};let 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",n={}){if(!this.isValid||!e.isValid)return T.invalid("created by diffing an invalid DateTime");let s={locale:this.locale,numberingSystem:this.numberingSystem,...n},a=Gn(t).map(T.normalizeUnit),i=e.valueOf()>this.valueOf(),o=i?this:e,c=i?e:this,u=ys(o,c,a,s);return i?u.negate():u}diffNow(e="milliseconds",t={}){return this.diff(r.now(),e,t)}until(e){return this.isValid?Z.fromDateTimes(this,e):this}hasSame(e,t,n){if(!this.isValid)return!1;let s=e.valueOf(),a=this.setZone(e.zone,{keepLocalTime:!0});return a.startOf(t,n)<=s&&s<=a.endOf(t,n)}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;let t=e.base||r.fromObject({},{zone:this.zone}),n=e.padding?this<t?-e.padding:e.padding:0,s=["years","months","days","hours","minutes","seconds"],a=e.unit;return Array.isArray(e.unit)&&(s=e.unit,a=void 0),Ds(t,this.plus(n),{...e,numeric:"always",units:s,unit:a})}toRelativeCalendar(e={}){return this.isValid?Ds(e.base||r.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(r.isDateTime))throw new x("min requires all arguments be DateTimes");return Nr(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(r.isDateTime))throw new x("max requires all arguments be DateTimes");return Nr(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,n={}){let{locale:s=null,numberingSystem:a=null}=n,i=S.fromOpts({locale:s,numberingSystem:a,defaultToEN:!0});return Hr(i,e,t)}static fromStringExplain(e,t,n={}){return r.fromFormatExplain(e,t,n)}static get DATE_SHORT(){return Y}static get DATE_MED(){return Le}static get DATE_MED_WITH_WEEKDAY(){return mr}static get DATE_FULL(){return Ue}static get DATE_HUGE(){return Ve}static get TIME_SIMPLE(){return qe}static get TIME_WITH_SECONDS(){return He}static get TIME_WITH_SHORT_OFFSET(){return $e}static get TIME_WITH_LONG_OFFSET(){return Ge}static get TIME_24_SIMPLE(){return ze}static get TIME_24_WITH_SECONDS(){return Ze}static get TIME_24_WITH_SHORT_OFFSET(){return Ke}static get TIME_24_WITH_LONG_OFFSET(){return Ye}static get DATETIME_SHORT(){return Je}static get DATETIME_SHORT_WITH_SECONDS(){return Qe}static get DATETIME_MED(){return Xe}static get DATETIME_MED_WITH_SECONDS(){return et}static get DATETIME_MED_WITH_WEEKDAY(){return fr}static get DATETIME_FULL(){return tt}static get DATETIME_FULL_WITH_SECONDS(){return rt}static get DATETIME_HUGE(){return nt}static get DATETIME_HUGE_WITH_SECONDS(){return st}};function Me(r){if(g.isDateTime(r))return r;if(r&&r.valueOf&&$(r.valueOf()))return g.fromJSDate(r);if(r&&typeof r=="object")return g.fromObject(r);throw new x(`Unknown datetime argument: ${r}, of type ${typeof r}`)}import{TransactionBlock as Vt}from"@mysten/sui.js/transactions";import{TransactionBlock as Ys}from"@mysten/sui.js/transactions";import{SUI_TYPE_ARG as Js,normalizeStructTag as eu}from"@mysten/sui.js/utils";import{Buffer as ta}from"buffer";import{normalizeSuiAddress as ru}from"@mysten/sui.js/utils";import{bcs as $a}from"@mysten/sui.js/bcs";import{normalizeStructTag as Zt}from"@mysten/sui.js/utils";var Rs=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");import{Transactions as sa}from"@mysten/sui.js/transactions";import{normalizeStructTag as aa,normalizeSuiAddress as Kt}from"@mysten/sui.js/utils";import{TransactionBlock as qt}from"@mysten/sui.js/transactions";import{normalizeStructTag as ia,parseStructTag as mu}from"@mysten/sui.js/utils";var oi=dr(Ut(),1),ui=dr(Ut(),1),hh=dr(Ut(),1);import{TransactionType as Wu}from"@msafe/sui3-utils";import{TransactionType as Lu}from"@msafe/sui3-utils";import{TransactionType as Uu}from"@msafe/sui3-utils";import{bcs as Sa}from"@mysten/sui.js/bcs";import{normalizeStructTag as Vu,normalizeSuiAddress as gt}from"@mysten/sui.js/utils";import{TransactionType as $u}from"@msafe/sui3-utils";import{TransactionDefaultApplication as zu,TransactionSubTypes as tn}from"@msafe/sui3-utils";import{buildCoinTransferTxb as Zu}from"@msafe/sui3-utils";import{buildObjectTransferTxb as Yu}from"@msafe/sui3-utils";import{isSameAddress as Qu}from"@msafe/sui3-utils";import{TransactionBlock as Xu}from"@mysten/sui.js/transactions";import{TransactionType as rl}from"@msafe/sui3-utils";import{TransactionType as yt}from"@msafe/sui3-utils";import{bcs as Ia}from"@mysten/sui.js/bcs";import{normalizeStructTag as un,normalizeSuiAddress as bt}from"@mysten/sui.js/utils";import{TransactionBlock as il}from"@mysten/sui.js/transactions";import{TransactionBlock as dl}from"@mysten/sui.js/transactions";import{TransactionBlock as fl}from"@mysten/sui.js/transactions";import{TransactionBlock as pl}from"@mysten/sui.js/transactions";import{TransactionBlock as yl}from"@mysten/sui.js/transactions";import{TransactionSubTypes as Tl,TransactionType as Il}from"@msafe/sui3-utils";import{TransactionBlock as xl}from"@mysten/sui.js/transactions";import{fromHEX as kl,toHEX as Ol}from"@mysten/sui.js/utils";var Pc=Object.defineProperty,Oa=(r,e)=>{for(var t in e)Pc(r,t,{get:e[t],enumerable:!0})},va={};Oa(va,{contractId:()=>Ma,default:()=>Fc,feeObjId:()=>Pa,roleObjId:()=>Da,status:()=>Ca,transaction:()=>Ea,upgradeCapObjId:()=>Na,vaultObjId:()=>Aa});var Ea="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Ca="success",Ma="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Da="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Aa="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Pa="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Na="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Fc={transaction:Ea,status:Ca,contractId:Ma,roleObjId:Da,vaultObjId:Aa,feeObjId:Pa,upgradeCapObjId:Na},Fa={};Oa(Fa,{contractId:()=>_a,default:()=>Rc,feeObjId:()=>La,roleObjId:()=>Ba,status:()=>ja,transaction:()=>Ra,upgradeCapObjId:()=>Ua,vaultObjId:()=>Wa});var Ra="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",ja="success",_a="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",Ba="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",Wa="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",La="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Ua="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Rc={transaction:Ra,status:ja,contractId:_a,roleObjId:Ba,vaultObjId:Wa,feeObjId:La,upgradeCapObjId:Ua},jc="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",_c="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Bc="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Wc="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",Lc="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Uc="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Vc="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",qc="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",zs=va,Zs=Fa,Hc=new Map([["dev",{env:"dev",rpc:{url:jc},backend:{url:Lc},contract:zs}],["stg",{env:"stg",rpc:{url:_c},backend:{url:Uc},contract:zs}],["prev",{env:"prev",rpc:{url:Bc},backend:{url:Vc},contract:Zs}],["prod",{env:"prod",rpc:{url:Wc},backend:{url:qc},contract:Zs}]]);function $c(r,e){let t=Hc.get(r);if(!t)throw new Error(`Env not supported: ${r}`);return e&&e.rpc&&(t.rpc=e.rpc),e&&e.backend&&(t.backend=e.backend),e&&e.contract&&(t.contract=e.contract),t}var F=class extends Error{mpayErrorCode;context;constructor(r,e,t={}){let{cause:n,context:s}=t;n?super(`[MPay] ${e}: ${n}`):super(`[MPay] ${e}`),this.mpayErrorCode=r,this.context=s}},zc=class extends F{constructor(){super(11,"Backend is not specified")}},Zc=class extends F{constructor(){super(1,"Wallet not connected")}},Qr=class extends F{constructor(r,e){super(10,r,{context:e})}},Yc=class fe{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof Kc)throw new Qr(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new Qr(e.data.code)}throw new Qr(e.status.toString())}async getIncomingStreams(e,t){let n=await De.post(`${this.apiURL}/stream`,{recipient:e,...t});return fe.parseResponseData(n)}async getOutgoingStreams(e,t){let n=await De.post(`${this.apiURL}/stream`,{sender:e,...t});return fe.parseResponseData(n)}async getStreamHistory(e){let t=await De.post(`${this.apiURL}/stream-events`,e),n=fe.parseResponseData(t);return n.data.forEach(s=>{let a=s;return a.data.type==="create_stream"?a.data.balance=BigInt(a.data.balance):a.data.type==="cancel_stream"?a.data.withdrawAmount=BigInt(a.data.withdrawAmount):a.data.type==="claim"||a.data.type==="auto_claim"?a.data.claimAmount=BigInt(a.data.claimAmount):a.data.type==="set_auto_claim"&&(a.data.enabled=!!a.data.enabled),a.createdAt=new Date(a.createdAt),a}),n}async getAllCoinTypes(e){let t=await De.post(`${this.apiURL}/stream-info`,{address:e});return fe.parseResponseData(t)}async getAllRecipients(e,t){let n=await De.post(`${this.apiURL}/stream-info`,{sender:e,status:t});return fe.parseResponseData(n)}async getAllSenders(e,t){let n=await De.post(`${this.apiURL}/stream-info`,{recipient:e,status:t});return fe.parseResponseData(n)}},Va=class qa{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Gc({url:e.rpc.url}),e.backend&&(this._backend=new Yc(e.backend.url))}static new(e,t){let n=$c(e,t);return new qa(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new zc;return this._backend}set backend(e){this._backend=e}connectWallet(e){this.signer=e}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new Zc;return this.signer}async walletAddress(){return this.wallet.address()}},Qs=50n,Xr=10000n,tu=25n,Xs=100000000n,me=class{constructor(r){this.object=r}moveArg(r){return r.object(this.object)}},ea=class{constructor(r){this.objects=r}moveArgs(r){return r.makeMoveVec({objects:this.objects.map(e=>r.object(e))})}},zt=class Ha{constructor(e){return this.result=e,new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(t,n){if(n in t)return Reflect.get(t,n);let s=i=>new Ha(t.result[i]);if(n===Symbol.iterator)return function*(){let i=0;for(;;)yield s(i),i++};if(typeof n=="symbol")return;let a=parseInt(n,10);if(!(Number.isNaN(a)||a<0))return s(a)}})}moveArg(){return this.result}},ra=class extends F{constructor(r,e){super(3,r,{context:e})}},nu=class{constructor(r){this.results=r}callResult(r){return this.results.results[r]}returnValue(r,e){return r.returnValues[e]}getValue(r=0,e=0){let t=this.callResult(r);return this.returnValue(t,e)}getAddress(r=0,e=0){let[t,n]=this.getValue(r,e);if(n!=="address")throw new ra("Invalid contract return type.",{ctx:{expectType:"address",gotType:n}});return ru(ta.from(t).toString("hex"))}getU64(r=0,e=0){let[t,n]=this.getValue(r,e);if(n!=="u64")throw new ra("Invalid contract return type.",{ctx:{expectType:"u64",gotType:n}});return ta.from(t).readBigInt64LE()}},N=class extends F{constructor(r,e,t){super(2,`Invalid input: ${r}`,{context:{fieldKey:e,fieldValue:t}})}},Ga={groupId:"string",name:"string"},su=64;function au(r){return za(r),$a.ser(Ga,r).toString("base64")}function nn(r){let e=$a.de(Ga,r,"base64");return za(e),e}function za(r){if(!na(r.name))throw new N("Invalid metadata: Name contains unknown character");if(!na(r.groupId))throw new N("Invalid metadata: Group ID contains unknown character");if(r.name.length>su)throw new N("Invalid metadata: Name exceed max length 64")}function na(r){return/^[\x00-\x7F]+$/.test(r)}function Za(r,e){return Zt(r)===Zt(e)}function Ae(r,e){return Zt(r)===Zt(e)}var Ka="txn.gas";function iu(){return Rs()}var sn=class Ya{constructor(e,t,n){this.globals=e,this.feeContract=t,this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:au({name:e.name,groupId:iu()}),coinType:eu(e.coinType),recipients:e.recipients.map(t=>({address:t.address,cliffAmount:t.cliffAmount,amountPerEpoch:t.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let t=new Ys,n=this.calculateFeesInternal(e),s=this.getCreateStreamCoinRequests(e,n),a=await this.wallet.requestCoins(s),i=await this.addMergeCoins(t,a[0]),o;s.length>1?o=await this.addMergeCoins(t,a[1]):o=i;for(let c=0;c<e.recipients.length;c++){let u=e.recipients[c],l=this.amountForRecipient(u,e.numberEpoch),h=this.getStreamFeeLocal(l),[y]=t.splitCoins(i,[t.pure(l+h,"u64")]),[m]=t.splitCoins(o,[t.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(t,{paymentCoin:new zt(y),flatFeeCoin:new zt(m),metadata:e.metadata,recipient:u.address,timeStart:e.startTime,cliff:u.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:u.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return t}calculateCreateStreamFees(e){let t=Ya.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(t)}feeParams(){return{createFeePercent:{numerator:Qs,denominator:Xr},claimFeePercent:{numerator:tu,denominator:Xr},flatFeePerStream:Xs}}async addMergeCoins(e,t){let n;return t.mergedCoins&&t.mergedCoins.length?(e.mergeCoins(e.object(t.primaryCoin),t.mergedCoins.map(s=>e.object(s))),n=e.object(t.primaryCoin)):t.primaryCoin===Ka?n=e.gas:n=e.object(t.primaryCoin),n}getCreateStreamCoinRequests(e,t){let n=e.coinType;return Za(n,Js)?[{coinType:n,amount:t.totalAmount+t.streamFeeAmount+t.flatFeeAmount}]:[{coinType:n,amount:t.totalAmount+t.streamFeeAmount},{coinType:Js,amount:t.flatFeeAmount}]}calculateFeesInternal(e){let t=e.recipients.reduce((n,s)=>{let a=this.amountForRecipient(s,e.numberEpoch),i=this.getStreamFeeLocal(a);return{totalAmount:n.totalAmount+a,streamFeeAmount:n.streamFeeAmount+i}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...t}}amountForRecipient(e,t){return BigInt(e.amountPerEpoch)*BigInt(t)+BigInt(e.cliffAmount)}get flatSuiFee(){return Xs}getStreamFeeLocal(e){return e*Qs/Xr}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new Ys,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:t});return new nu(n).getU64()}get wallet(){return this.globals.wallet}},ou="0x0000000000000000000000000000000000000000000000000000000000000006",Ja=class{constructor(r,e,t){this.moduleName=r,this.config=e,this.globals=t}addContractCall(r,e){let t=`${this.config.contractId}::${this.moduleName}::${e.method}`;return r.add(sa.MoveCall({target:t,arguments:e.arguments.map(n=>n instanceof ea?n.moveArgs(r):n instanceof me?n.moveArg(r):n instanceof zt?n.moveArg():r.pure(n)),typeArguments:e.typeArgs})),r}addTransactionBlock(r,e,t=[],n=[]){r.add(sa.MoveCall({target:e,arguments:t.map(s=>s instanceof ea?s.moveArgs(r):s instanceof me?s.moveArg(r):s instanceof zt?s.moveArg():r.pure(s)),typeArguments:n}))}makeObject(r){return typeof r=="string"?new me(r):r}vaultObject(){return new me(this.config.vaultObjId)}roleObject(){return new me(this.config.roleObjId)}feeObject(){return new me(this.config.feeObjId)}clockObject(){return new me(ou)}},Qa=class ne extends Ja{constructor(e,t){super(ne.ModuleName,e,t),this.config=e,this.globals=t}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,t){let n=this.roleObject(),s=this.feeObject();return this.addContractCall(e,{method:ne.MethodName.set_streaming_fee,arguments:[n,s,t],typeArgs:[]})}setStreamingFlatFee(e,t){let n=this.roleObject(),s=this.feeObject();return this.addContractCall(e,{method:ne.MethodName.set_streaming_flat_fee,arguments:[n,s,t],typeArgs:[]})}setClaimFee(e,t){let n=this.roleObject(),s=this.feeObject();return this.addContractCall(e,{method:ne.MethodName.set_claim_fee,arguments:[n,s,t],typeArgs:[]})}streamingFee(e,t){let n=this.feeObject();return this.addContractCall(e,{method:ne.MethodName.streaming_fee,arguments:[n,t],typeArgs:[]})}claimFee(e,t){return this.addContractCall(e,{method:ne.MethodName.claim_fee,arguments:[this.feeObject(),t],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:ne.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},Jt=class C extends Ja{constructor(e,t){super(C.ModuleName,e,t),this.config=e,this.globals=t}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,t){let n=this.feeObject(),s=this.vaultObject(),a=this.makeObject(t.paymentCoin),i=this.makeObject(t.flatFeeCoin),o=this.clockObject();return this.addContractCall(e,{method:C.MethodName.create_stream,arguments:[n,s,a,i,t.metadata,t.recipient,t.timeStart,t.cliff,t.epochInterval,t.numEpoch,t.amountPerEpoch,t.cancelable,o],typeArgs:[t.coinType]})}setAutoClaim(e,t){let n=this.makeObject(t.streamId);return this.addContractCall(e,{method:C.MethodName.set_auto_claim,arguments:[n,t.enabled],typeArgs:[t.coinType]})}cancelStream(e,t){let n=this.makeObject(t.streamId),s=this.clockObject();return this.addContractCall(e,{method:C.MethodName.cancel_stream,arguments:[n,s],typeArgs:[t.coinType]})}claimStream(e,t){let n=this.makeObject(t.streamId),s=this.clockObject();return this.addContractCall(e,{method:C.MethodName.claim_stream,arguments:[n,s],typeArgs:[t.coinType]})}claimStreamByProxy(e,t){let n=this.makeObject(t.streamId),s=this.vaultObject(),a=this.feeObject(),i=this.clockObject();return this.addContractCall(e,{method:C.MethodName.claim_stream_by_proxy,arguments:[n,s,a,i],typeArgs:[t.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${C.ModuleName}::${C.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${C.ModuleName}::${C.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${C.ModuleName}::${C.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${C.ModuleName}::${C.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${C.ModuleName}::${C.MethodName.claim_stream_by_proxy}`}},Xa=class{constructor(r){this.globals=r;let e=r.envConfig.contract;this.feeContract=new Qa(e,r),this.streamContract=new Jt(e,r)}feeContract;streamContract;async createStreams(r){let e=sn.convertCreateStreamInfoToInternal(r);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new sn(this.globals,this.feeContract,this.streamContract)}setAutoClaim(r,e,t){let n=new Vt;return this.streamContract.setAutoClaim(n,{streamId:r,enabled:e,coinType:t})}claimStream(r,e){let t=new Vt;return this.streamContract.claimStream(t,{streamId:r,coinType:e})}claimStreamByProxy(r,e){let t=new Vt;return this.streamContract.claimStreamByProxy(t,{streamId:r,coinType:e})}cancelStream(r,e){let t=new Vt;return this.streamContract.cancelStream(t,{streamId:r,coinType:e}),t}},cu=class extends F{constructor(r,e){super(12,`Transaction failed: ${e}`,{context:{status:r,msg:e}})}},uu=1e3,lu=class{constructor(r){this.globals=r,this.coinMetaHelper=new du(r.suiClient),this.createStreamHelper=new Xa(r).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(r){if(r.effects?.status.status!=="success")throw new cu(r.effects?.status.status,r.effects?.status.error);return r.objectChanges.filter(e=>e.type==="created"&&e.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(e=>e.objectId)}calculateCreateStreamFees(r){return this.createStreamHelper.calculateCreateStreamFees(r)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(r){if(r.steps===0n)throw new N("Invalid stream steps: 0");let e=r.cliff?r.cliff:{numerator:0n,denominator:100n},t=r.totalAmount*e.numerator/e.denominator,n=(r.totalAmount-t)/r.steps,s={realTotalAmount:n*r.steps+t,cliffAmount:t,amountPerStep:n};return this.validateStreamAmount(s,r.totalAmount),s}calculateTimelineByInterval(r){if(r.steps===0n)throw new N("Invalid stream steps: 0");let e=r.timeStart.plus(r.interval.toMillis()*Number(r.steps)),t={timeStart:r.timeStart,timeEnd:e,interval:r.interval,steps:r.steps};return this.validateTimeline(t),t}calculateTimelineByTotalDuration(r){if(r.steps===0n)throw new N("Invalid stream steps: 0");let e=BigInt(r.total.toMillis())/r.steps,t=r.timeStart.plus(T.fromMillis(Number(e*r.steps))),n={timeStart:r.timeStart,timeEnd:t,interval:T.fromMillis(Number(e)),steps:r.steps};return this.validateTimeline(n),n}async getBalance(r,e){let t=await this.globals.suiClient.getBalance({owner:r,coinType:e}),n=await this.getCoinMeta(e);return{...t,coinType:rn(t.coinType),coinMeta:n}}async getAllBalance(r){let e=await this.globals.suiClient.getAllBalances({owner:r}),t=await Promise.all(e.map(n=>this.getCoinMeta(n.coinType)));return e.map((n,s)=>({...n,coinType:rn(n.coinType),coinMeta:t[s]}))}async getCoinMeta(r){return this.coinMetaHelper.getCoinMeta(r)}async simulateTransactionBlock(r){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:r,sender:await this.globals.wallet.address()})}validateStreamAmount(r,e){if(r.amountPerStep===0n)throw new N("Stream amount too small","totalAmount",e);if(r.cliffAmount>r.realTotalAmount)throw new N("Invalid cliff settings")}validateTimeline(r){if(r.interval.toMillis()<uu)throw new N("Interval shall be at least 1 second","interval",r.interval)}},du=class{constructor(r){this.suiClient=r,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(r){let e=rn(r||Xc);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let t=await this.queryCoinMeta(e);return t&&this.coinMetaReg.set(e,t),t}async queryCoinMeta(r){return await this.suiClient.getCoinMetadata({coinType:r})||void 0}},fu=class extends F{constructor(){super(7,"Connected wallet is not creator")}},oa=class extends F{constructor(){super(8,"Connected wallet is not recipient")}},ca=class extends F{constructor(r,e){super(6,r,{context:e})}},q=class extends F{constructor(r,e={}){super(0,r,e)}},hu=class extends F{constructor(r){super(5,"Stream not found",{context:{streamId:r}})}},pu=(1n<<64n)-1n,Yt=1e3;function ua(r){let e;typeof r=="number"?e=r:typeof r=="bigint"?e=Number(r):e=r.toMillis();let t=Math.round(e/Yt);return g.fromMillis(t*Yt)}function la(r){let e;typeof r=="number"?e=r:typeof r=="bigint"?e=Number(r):e=r.toMillis();let t=Math.round(e/Yt);return T.fromMillis(t*Yt)}var ln=class se{constructor(e,t,n){this.globals=e,this.streamId=t,this.rawData=n,this.streamContract=new Jt(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,t){let n=await se.fetchStreamData(e,t);return new se(e,t,n)}static fromObjectData(e,t,n){let s=se.parseRawStreamData(t,n);return new se(e,t,s)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await se.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new q("Object Id does not align");this.rawData=se.parseRawStreamData(this.streamId,e)}async historyEvents(e){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:e})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new fu;let e=new qt;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new oa;let e=new qt;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new oa;let t=new qt;return this.streamContract.setAutoClaim(t,{streamId:this.streamId,coinType:this.coinType,enabled:e}),t}async claimByProxy(){let e=new qt;return this.streamContract.claimStreamByProxy(e,{streamId:this.streamId,coinType:this.coinType}),e}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return ia(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return la(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return nn(e).groupId}get name(){let{metadata:e}=this.rawData.config;return nn(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return ua(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return la(t)}get timeEnd(){return this.timeStart.plus(this.duration)}get totalSteps(){return this.rawData.config.totalEpoch}get claimable(){return this.streamedAmount-this.claimedAmount}get nextReleaseDate(){return this.currentEpoch===-1n?this.timeStart:this.currentEpoch>=this.totalSteps||this.isCanceled?null:ua((this.currentEpoch+1n)*this.rawData.config.epochInterval+this.rawData.config.timeStart)}get nextReleaseAmount(){return this.currentEpoch===-1n?this.cliff:this.currentEpoch>=this.totalSteps||this.isCanceled?null:this.amountPerEpoch}get streamStatus(){let e=this.rawData.status.status;return e===16?"CANCELED":e===17?"SETTLED":e===1?"COMPLETED":this.currentEpoch>=this.totalSteps?"STREAMED":"STREAMING"}get streamedAmount(){return this.currentEpoch===-1n?0n:this.isCanceled?this.rawData.status.epochCanceled*this.amountPerEpoch+this.cliff:this.currentEpoch*this.amountPerEpoch+this.cliff}get claimedAmount(){return this.rawData.status.epochClaimed===pu?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=g.now().toMillis(),t=this.timeStart.toMillis();if(e<t)return-1n;let n=Math.floor((e-t)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,t){let n=await e.suiClient.getObject({id:t,options:{showContent:!0,showType:!0}});return se.parseRawStreamData(t,n)}static parseRawStreamData(e,t){if(t.error)throw t.error.code==="notExists"?new hu(e):new ca(`get stream data: ${t.error.code}`,{streamId:e,...t.error});let n=t.data.content;if(n.dataType!=="moveObject")throw new ca("Unexpected object type",{gotType:n.dataType});let{typeParams:s}=mu(n.type),a=ia(s[0]),i=n.fields,o=i.config.fields,c=i.status.fields;return{coinType:a,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(o.amount_per_epoch),cancelable:o.cancelable,cliff:BigInt(o.cliff),creator:o.creator,epochInterval:BigInt(o.epoch_interval),metadata:o.metadata,recipient:o.recipient,timeStart:BigInt(o.time_start),totalEpoch:BigInt(o.total_epoch)},status:{status:c.status,epochCanceled:BigInt(c.epoch_canceled),epochClaimed:BigInt(c.epoch_claimed)}}}},en=class extends F{constructor(r,e){super(9,`Invalid stream group: ${r}`,{context:e})}};async function gu(r){let e=[];for(;await r.hasNext();){let t=await r.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var yu=class{constructor(r){this.requester=r,this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},ei=class{constructor(r){this.requester=r,this.pager=new yu(r),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}},bu=25;async function da(r,e,t){let n=new ti(e),s=new ri(r,n,t);return await gu(s)}var ti=class{constructor(r){this.ids=r,this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},ri=class extends ei{constructor(r,e,t){super(new wu(r,e,t)),this.suiClient=r,this.idIter=e,this.options=t}},wu=class{constructor(r,e,t){this.suiClient=r,this.stringIter=e,this.options=t,this.filter=t?.filter,this.pageSize=t?.pageSize||bu,this.objectOptions=t?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let r=[];for(;r.length<this.pageSize&&await this.stringIter.hasNext();){let n=await this.stringIter.next();n&&r.push(n)}let e=await this.suiClient.multiGetObjects({ids:r,options:this.objectOptions}),t;if(this.filter){let{filter:n}=this;t=e.filter(s=>n?.(s))}else t=e;return{data:t,hasNext:await this.stringIter.hasNext()}}},Su=class Ht{constructor(e,t){if(this.globals=e,this.streams=t,t.length===0)throw new en("stream size 0");let n=t.map(s=>s.groupId);if(new Set(n).size!==1)throw new N("Stream does not have same group ID")}type="StreamGroup";static async new(e,t){let n=await da(e.suiClient,t);return n.forEach(s=>{if(!s)throw new q("stream group object data undefined")}),Ht.newFromObjectResponse(e,t,n)}static async newFromObjectResponse(e,t,n){let s=await Ht.parseGroupStreams(e,t,n);return new Ht(e,s)}static checkStreamGroup(e){let t=e.map(a=>a.groupCommonInfo),n=t[0],s=!0;return t.forEach(a=>{Tu(n,a)||(s=!1)}),s}async refresh(){let e=await da(this.globals.suiClient,this.streams.map(t=>t.streamId));this.streams.forEach((t,n)=>{t.refreshWithData(e[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(e=>e.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((e,t)=>e+t.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,t)=>e+t.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,t)=>t.nextReleaseAmount===null?e:e+t.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,t)=>e+t.totalAmount,0n),streamed:this.streams.reduce((e,t)=>e+t.streamedAmount,0n),claimed:this.streams.reduce((e,t)=>e+t.claimedAmount,0n),claimable:this.streams.reduce((e,t)=>e+t.claimable,0n),canceled:this.streams.reduce((e,t)=>e+t.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,t,n){let s=n.map((a,i)=>ln.fromObjectData(e,t[i],a)).filter(a=>!!a);if(new Set(s.map(a=>a.groupId)).size!==1)throw new en("Not same group ID");if(!this.checkStreamGroup(s))throw new en("Not same stream settings");return s}};function Tu(r,e){return r.name===e.name&&r.groupId===e.groupId&&r.creator===e.creator&&r.start.toMillis()===e.start.toMillis()&&r.interval.toMillis()===e.interval.toMillis()&&r.steps===e.steps&&r.cancelable===e.cancelable}var ma=class an{constructor(e,t){this.it=e,this.pageSize=t}static async newIncoming(e){let t=await fa.newIncoming(e);return new an(t,e.pageSize)}static async newOutgoing(e){let t=await fa.newOutgoing(e);return new an(t,e.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let e=[];for(;e.length<this.pageSize&&await this.it.hasNext();)e.push(await this.it.next());return e}},fa=class on{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let t=await ha.newIncomingQuery(e);return new on(t)}static async newOutgoing(e){let t=await ha.newOutgoingQuery(e);return new on(t)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let t=await this.requester.doNextRequest();if(t===null)throw new q("No more results");return t}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new q("No more results");return e}},ha=class cn{constructor(e,t,n,s){this.globals=e,this.recipient=t,this.groupRefs=n,this.query=s,this.current=0;let a=new ti(n.flat().map(i=>i.streamId));this.objectIter=new ri(e.suiClient,a)}current=0;objectIter;static async newIncomingQuery(e){let t=vu(e.query),n=await e.globals.walletAddress(),s=(await e.globals.backend.getIncomingStreams(n,t)).filter(i=>Kt(i.recipient)===Kt(n)),a=pa(s);return new cn(e.globals,n,a,e.query)}static async newOutgoingQuery(e){let t=Eu(e.query),n=await e.globals.walletAddress(),s=await e.globals.backend.getOutgoingStreams(n,t),a=pa(s);return new cn(e.globals,n,a,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let t=await ku(this.globals,e[0].streamId,this.objectIter);return this.current++,ni(t,this.query)?t:this.doNextRequest()}if(e.length>1){let t=await Ou(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,xu(t,this.query)?t:this.doNextRequest()}throw new q("Stream group with no stream")}};function pa(r){let e=new Map;return r.forEach(t=>{let n=e.get(t.groupId);n?(n.push(t),e.set(t.groupId,n)):e.set(t.groupId,[t])}),Array.from(e.values()).sort((t,n)=>g.fromISO(n[0].createDate).toMillis()-g.fromISO(t[0].createDate).toMillis())}function ni(r,e){if(e===void 0)return!0;let t=Iu(r,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?r.progress.claimable!==0n:r.progress.claimable===0n;return t&&n}return t}function Iu(r,e){return e===void 0?!0:Array.isArray(e)?e.includes(r.progress.status):r.progress.status===e}function xu(r,e){if(!e)return!0;let t=!1;return r.streams.forEach(n=>{ni(n,e)&&(t=!0)}),t}async function ku(r,e,t){let n=await si(t,e);return ln.fromObjectData(r,e,n)}async function Ou(r,e,t){let n=[];for(;n.length<e.length;){let s=await si(t,e[n.length]);n.push(s)}return Su.newFromObjectResponse(r,e,n)}async function si(r,e){if(!await r.hasNext())throw new q("object iterator has been consumed");let t=await r.next();if(!t||t.error||t.data===void 0||t.data===null)throw new q("object iterator undefined response",{cause:t?.error});if(t?.data?.objectId!==e)throw new q("stream id not aligned");return t}function vu(r){return{status:dn(r?.status),coinType:ai(r?.coinType),sender:ii(r?.sender)}}function Eu(r){return{status:dn(r?.status),coinType:ai(r?.coinType),recipient:ii(r?.recipient)}}function dn(r){return r===void 0||r.length===0?"all":Array.isArray(r)?r.reduce((e,t)=>{let n=dn(t);return!e||e===n?n:"all"},void 0):Cu(r)}function Cu(r){switch(r){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new N("Unknown stream filtered status")}}function ai(r){if(r)return Array.isArray(r)?r.length!==0?r.map(e=>aa(e)):void 0:aa(r)}function ii(r){if(r)return Array.isArray(r)?r.length!==0?r.map(e=>Kt(e)):void 0:Kt(r)}var Mu=class extends F{constructor(r,e,t){super(4,`Not enough balance: ${r}`,{context:{coinType:r,requestAmount:e,gotAmount:t}}),this.coinType=r,this.requestAmount=e,this.gotAmount=t}},Du=25;async function Au(r,e,t,n="0x2::sui::SUI",s=Du){let a=new Pu(r,e,n,s),i=BigInt(0),o=[];for(;await a.hasNext()&&i<t;){let c=await a.next();c&&(o.push(c),i+=BigInt(c.balance))}if(i<t)throw new Mu(n,t,i);return o}var Pu=class extends ei{constructor(r,e,t,n){super(new Nu(r,e,t,n)),this.suiClient=r,this.owner=e,this.coinType=t,this.reqPageSize=n}},Nu=class{constructor(r,e,t,n){if(this.suiClient=r,this.owner=e,this.coinType=t,this.reqPageSize=n,n<=0)throw new q("Invalid reqPageSize")}nextCursor;async doNextRequest(){let r=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=r.nextCursor,{data:r.data,hasNext:r.hasNextPage}}},Fu=class{constructor(r){this.msafe=r}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(r){return this.msafe.requestCoins(r)}},Ru=class{constructor(r){this.account=r}async address(){return this.account.address}},ju=class{constructor(r,e){this.singleWallet=r,this.suiClient=e}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(r){return Promise.all(r.map(e=>this.requestCoin(e)))}async requestCoin(r){if(Za(r.coinType,Jc))return{primaryCoin:Ka};if(r.amount<=0)throw new N("Invalid coin request","coinAmount",r.amount);let e=await Au(this.suiClient,await this.address(),r.amount,r.coinType);if(e.length===0)throw new q("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(t=>t.coinObjectId)}}},_u=class{globals;helper;constructor(r,e){this.globals=Va.new(r,e),this.helper=new lu(this.globals)}connectSingleWallet(r){let e=new ju(r,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(r){let e=new Fu(r);this.globals.connectWallet(e)}async createStream(r){return this.builder().createStreams(r)}async getStream(r){return ln.new(this.globals,r)}async getIncomingStreams(r,e=10){return ma.newIncoming({globals:this.globals,query:r,pageSize:e})}async getOutgoingStreams(r,e=10){return ma.newOutgoing({globals:this.globals,query:r,pageSize:e})}async getCoinTypesForStreamFilter(){let r=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(r)).map(e=>Qc(e))}async getRecipientsForStreamFilter(r){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,r)).map(t=>Ks(t))}async getCreatorsForStreamFilter(r){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,r)).map(t=>Ks(t))}get wallet(){return this.globals.wallet}builder(){return new Xa(this.globals)}},Bu=class{constructor(r){this.data=r}serialize(){return JSON.stringify((0,oi.default)(this.data))}},St=class extends Bu{application="mpay";getClient(r,e){let t=new _u(r==="sui:mainnet"?"prod":"dev");return t.connectSingleWallet(new Ru(e)),t}},ga=class extends St{constructor(r){super(r),this.data=r}txType=Nc.Stream;txSubType="Cancel";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).cancel()}},ya=class extends St{constructor(r){super(r),this.data=r}txType=Wu.Stream;txSubType="ClaimByProxy";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).claimByProxy()}},ba=class extends St{constructor(r){super(r),this.data=r}txType=Lu.Stream;txSubType="Claim";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).claim()}},wa=class extends St{constructor(r){super(r),this.data=r}txType=Uu.Stream;txSubType="CreateStream";async build(r){let{network:e,account:t}=r;return this.getClient(e,t).createStream(this.data)}},ci=class $t{constructor(e,t){this.moveCall=e,this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return $t.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return $t.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return BigInt(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return gt(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return $t.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Sa.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return gt(e.value.Object.ImmOrOwned.objectId)}return gt(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return gt(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return gt(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Sa.de(t,new Uint8Array(n))}typeArg(e){return Vu(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},qu=class{constructor(r,e){this.globals=r,this.txb=e}decode(){let r=this.decodeCreateStreamInfo(),e=this.createStreamHelper().calculateCreateStreamFees(r);return{type:"CreateStream",info:r,fees:e}}decodeCreateStreamInfo(){let r=this.createStreamTransactions().map(e=>this.getCreationInfoFromMoveCall(e));return this.aggregateGroupStreamInfo(r)}createStreamTransactions(){let r=this.transactions.filter(e=>e.kind==="MoveCall"&&Ae(e.target,this.contract.createStreamTarget));if(r.length===0)throw new q("No create stream transactions");return r.map(e=>new ci(e,this.txb))}getCreationInfoFromMoveCall(r){let e=r.decodeInputString(4),{name:t,groupId:n}=nn(e),s=r.decodeInputAddress(5),a=r.decodeInputU64(6),i=r.decodeInputU64(7),o=r.decodeInputU64(8),c=r.decodeInputU64(9),u=r.decodeInputU64(10),l=r.decodeInputBool(11),h=r.typeArg(0);return{name:t,groupId:n,recipient:s,timeStart:a,cliff:i,epochInterval:o,totalEpoch:c,amountPerEpoch:u,cancelable:l,coinType:h}}aggregateGroupStreamInfo(r){if(new Set(r.map(t=>JSON.stringify({name:t.name,groupId:t.groupId,timeStart:String(t.timeStart),epochInterval:String(t.epochInterval),totalEpoch:String(t.totalEpoch),cancelable:t.cancelable,coinType:t.coinType}))).size!==1)throw new N("Stream group not have common info");let e=r.map(t=>({address:t.recipient,amountPerStep:t.amountPerEpoch,cliffAmount:t.cliff}));return{name:r[0].name,coinType:r[0].coinType,recipients:e,interval:r[0].epochInterval,steps:r[0].totalEpoch,startTimeMs:r[0].timeStart,cancelable:r[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(r=>r.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new Jt(this.globals.envConfig.contract,this.globals)}get feeContract(){return new Qa(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new sn(this.globals,this.feeContract,this.contract)}getInputArg(r){if(r.kind!=="Input")throw new Error("not input type");return"value"in r?r:this.txb.blockData.inputs[r.index]}},Hu=class{constructor(r,e){this.globals=r,this.txb=e,this.contract=new Jt(r.envConfig.contract,r)}contract;decode(){if(this.isCreateStreamTransaction())return this.decodeCreateStreamTransaction();if(this.isClaimByProxyTransaction())return this.decodeClaimByProxyTransaction();if(this.isSetAutoClaimTransaction())return this.decodeSetAutoClaimTransaction();if(this.isCancelStreamTransaction())return this.decodeCancelStreamTransaction();if(this.isClaimStreamTransaction())return this.decodeClaimTransaction()}get transactions(){return this.txb.blockData.transactions}isCreateStreamTransaction(){return this.transactions.findIndex(r=>r.kind==="MoveCall"&&Ae(r.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Ae(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Ae(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Ae(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Ae(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new qu(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let r=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:r,enabled:e}}decodeClaimTransaction(){return{type:"Claim",streamId:this.helper.decodeSharedObjectId(0)}}decodeClaimByProxyTransaction(){return{type:"ClaimByProxy",streamId:this.helper.decodeSharedObjectId(0)}}decodeCancelStreamTransaction(){return{type:"Cancel",streamId:this.helper.decodeSharedObjectId(0)}}get helper(){let r=this.transactions[0];return new ci(r,this.txb)}},Ta=class extends St{constructor(r){super(r),this.data=r}txType=$u.Stream;txSubType="SetAutoClaim";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}},Gu=class{application="mpay";async deserialize(r){let{chain:e,transactionBlock:t}=r,n=Va.new(e==="sui:mainnet"?"prod":"dev"),s=new Hu(n,t).decode(),a;switch(s.type){case"CreateStream":a=new wa(s.info);break;case"SetAutoClaim":a=new Ta({streamId:s.streamId,enabled:s.enabled});break;case"Claim":a=new ba({streamId:s.streamId});break;case"ClaimByProxy":a=new ya({streamId:s.streamId});break;case"Cancel":a=new ga({streamId:s.streamId});break;default:throw new Error(`Unknown transaction type: ${s}`)}return{txType:a.txType,txSubType:a.txSubType,intentionData:a.data}}async build(r){let{intentionData:e}=r,t;switch(r.txSubType){case"CreateStream":t=new wa(e);break;case"Claim":t=new ba(e);break;case"ClaimByProxy":t=new ya(e);break;case"SetAutoClaim":t=new Ta(e);break;case"Cancel":t=new ga(e);break;default:throw new Error("not implemented")}return t.build({...r})}},ae=class{constructor(r){this.data=r}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,ui.default)(this.data))}},Ku=class li extends ae{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:t,account:n}=e;return Zu(t,this.data,n.address)}static fromData(e){return new li(e)}},Ju=class di extends ae{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:t,account:n}=e;return Yu(t,this.data,n.address)}static fromData(e){return new di(e)}},el=class mi extends ae{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:t}=e,n=Xu.from(this.data.content);if(!Qu(n.blockData.sender,t.address))throw new Error("Invalid sender address");return n}static fromData(e){return new mi(e)}},tl=class{application;constructor(){this.application=zu}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(r){let{suiClient:e,account:t}=r,n;switch(r.txSubType){case tn.assets.coin.send:n=Ku.fromData(r.intentionData);break;case tn.assets.object.send:n=Ju.fromData(r.intentionData);break;case tn.others.plain:n=el.fromData(r.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:t})}},nl={ProtocolPackage:"0xd92d9db3ae5e2e932eda336b15f97e02255d152201d0cf29a29ca0c4fb0205f3",StorageId:"0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe",Incentive:"0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821",IncentiveV2:"0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c",PriceOracle:"0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef",ReserveParentId:"0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b",pool:{sui:{name:"SUI",assetId:0,poolId:"0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5",fondPoolId:"0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4",type:"0x2::sui::SUI",coinType:"sui",reserveObjectId:"0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf",borrowBalanceParentId:"0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7",supplyBalanceParentId:"0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8"},usdc:{name:"USDC",assetId:1,coinType:"usdc",poolId:"0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8",type:"0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",reserveObjectId:"0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203",borrowBalanceParentId:"0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4",supplyBalanceParentId:"0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9"},usdt:{name:"USDT",coinType:"usdt",assetId:2,poolId:"0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103",type:"0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN",reserveObjectId:"0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322",borrowBalanceParentId:"0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f",supplyBalanceParentId:"0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257"},weth:{name:"WETH",coinType:"weth",assetId:3,poolId:"0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56",type:"0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN",reserveObjectId:"0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735",borrowBalanceParentId:"0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323",supplyBalanceParentId:"0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f"},cetus:{name:"CETUS",coinType:"cetus",assetId:4,poolId:"0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e",type:"0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS",reserveObjectId:"0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133",borrowBalanceParentId:"0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d",supplyBalanceParentId:"0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae"},voloSui:{name:"VoloSui",coinType:"voloSui",assetId:5,poolId:"0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01",fondPoolId:"0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea",type:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT",reserveObjectId:"0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2",borrowBalanceParentId:"0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984",supplyBalanceParentId:"0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841"},haSui:{name:"HaedalSui",coinType:"haSui",assetId:6,poolId:"0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a",fondPoolId:"0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51",type:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI",reserveObjectId:"0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3",borrowBalanceParentId:"0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00",supplyBalanceParentId:"0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b"},navx:{name:"NAVX",coinType:"navx",assetId:7,poolId:"0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60",fondPoolId:"0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09",type:"0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX",reserveObjectId:"0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81",borrowBalanceParentId:"0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b",supplyBalanceParentId:"0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5"}}},p=nl;function wt(r,e){return un(r)===un(e)}var sl=class{constructor(r){this.txb=r}decode(){if(this.isClaimRewardTransaction())return this.decodeClaimReward();if(this.isEntryBorrowTransaction())return this.decodeEntryBorrow();if(this.isEntryDepositTransaction())return this.decodeEntryDeposit();if(this.isEntryRepayTransaction())return this.decodeEntryRepay();if(this.isEntryWithdrawTransaction())return this.decodeEntryWithdraw();throw new Error("Unknown transaction type")}get transactions(){return this.txb.blockData.transactions}isClaimRewardTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&wt(this.transactions[0].target,`${p.ProtocolPackage}::incentive_v2::claim_reward`)}isEntryBorrowTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&wt(this.transactions[0].target,`${p.ProtocolPackage}::incentive_v2::entry_borrow`)}isEntryDepositTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&wt(this.transactions[0].target,`${p.ProtocolPackage}::incentive_v2::entry_deposit`)}isEntryRepayTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&wt(this.transactions[0].target,`${p.ProtocolPackage}::incentive_v2::entry_repay`)}isEntryWithdrawTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&wt(this.transactions[0].target,`${p.ProtocolPackage}::incentive_v2::entry_withdraw`)}findPoolByAssetId(r){let e=Object.values(p.pool).find(t=>t.assetId===r);if(!e)throw new Error("Pool not found");return e}decodeClaimReward(){let r=this.helper.decodeInputU8(4),e=this.helper.decodeInputU8(5),t=this.findPoolByAssetId(r);return{txType:yt.Other,type:"ClaimReward",intentionData:{coinType:t.coinType,option:e}}}decodeEntryBorrow(){let r=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),t=this.findPoolByAssetId(r);return{txType:yt.Other,type:"ClaimReward",intentionData:{amount:e,coinType:t.coinType}}}decodeEntryDeposit(){let r=this.helper.decodeInputU8(3),e=this.helper.decodeInputU64(5),t=this.findPoolByAssetId(r);return{txType:yt.Other,type:"ClaimReward",intentionData:{amount:e,coinType:t.coinType}}}decodeEntryRepay(){let r=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(6),t=this.findPoolByAssetId(r);return{txType:yt.Other,type:"ClaimReward",intentionData:{amount:e,coinType:t.coinType}}}decodeEntryWithdraw(){let r=this.helper.decodeInputU8(4),e=this.helper.decodeInputU64(5),t=this.findPoolByAssetId(r);return{txType:yt.Other,type:"ClaimReward",intentionData:{amount:e,coinType:t.coinType}}}get helper(){let r=this.transactions[0];return new al(r,this.txb)}},al=class Gt{constructor(e,t){this.moveCall=e,this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return Gt.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return Gt.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return Number(t)}decodeInputU8(e){let t=this.decodePureArg(e,"u8");return Number(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return bt(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return Gt.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Ia.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return bt(e.value.Object.ImmOrOwned.objectId)}return bt(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return bt(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return bt(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Ia.de(t,new Uint8Array(n))}typeArg(e){return un(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}};function xa(r,e,t,n){return r.moveCall({target:`${p.ProtocolPackage}::incentive_v2::entry_deposit`,arguments:[r.object("0x06"),r.object(p.StorageId),r.object(e.poolId),r.pure(e.assetId),t,r.pure(n),r.object(p.Incentive),r.object(p.IncentiveV2)],typeArguments:[e.type]}),r}function ol(r,e,t){return r.moveCall({target:`${p.ProtocolPackage}::incentive_v2::entry_withdraw`,arguments:[r.object("0x06"),r.object(p.PriceOracle),r.object(p.StorageId),r.object(e.poolId),r.pure(e.assetId),r.pure(t),r.object(p.Incentive),r.object(p.IncentiveV2)],typeArguments:[e.type]}),r}function cl(r,e,t){return r.moveCall({target:`${p.ProtocolPackage}::incentive_v2::entry_borrow`,arguments:[r.object("0x06"),r.object(p.PriceOracle),r.object(p.StorageId),r.object(e.poolId),r.pure(e.assetId),r.pure(t),r.object(p.IncentiveV2)],typeArguments:[e.type]}),r}function ka(r,e,t,n){return r.moveCall({target:`${p.ProtocolPackage}::incentive_v2::entry_repay`,arguments:[r.object("0x06"),r.object(p.PriceOracle),r.object(p.StorageId),r.object(e.poolId),r.pure(e.assetId),t,r.pure(n),r.object(p.IncentiveV2)],typeArguments:[e.type]}),r}function ul(r,e,t){return r.moveCall({target:`${p.ProtocolPackage}::incentive_v2::claim_reward`,arguments:[r.object("0x06"),r.object(p.IncentiveV2),r.object(e.fondPoolId),r.object(p.StorageId),r.pure(e.assetId),r.pure(t)],typeArguments:[e.type]}),r}var ll=class fi extends ae{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,option:t}=this.data,n=new il,s=p.pool[e];if(!s)throw new Error(`${e} not support, please use ${Object.keys(p.pool).join(", ")}.`);if(!s.fondPoolId)throw new Error(`${e} not support claim reward.`);return ul(n,s,t)}static fromData(e){return new fi(e)}},ml=class hi extends ae{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:t}=this.data,n=new dl,s=p.pool[e];if(!s)throw new Error(`${e} not support, please use ${Object.keys(p.pool).join(", ")}.`);return cl(n,s,t)}static fromData(e){return new hi(e)}};async function pi(r,e,t){return await r.getCoins({owner:e,coinType:t})}var hl=class gi extends ae{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:t,account:n}=e,{coinType:s,amount:a}=this.data,i=new fl;if(s==="sui"){let[l]=i.splitCoins(i.gas,[a]);return xa(i,p.pool.sui,l,a)}let o=p.pool[s];if(!o)throw new Error(`${s} not support, please use ${Object.keys(p.pool).join(", ")}.`);let c=await pi(t,n.address,o.type);if(!c.data[0])throw new Error(`Insufficient balance for ${o.name} Token`);let u=c.data[0].coinObjectId;if(c.data.length>=2){let l=1;for(;l<c.data.length;)i.mergeCoins(u,[c.data[l].coinObjectId]),l++}return xa(i,o,u,a)}static fromData(e){return new gi(e)}},gl=class yi extends ae{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:t,account:n}=e,{coinType:s,amount:a}=this.data,i=new pl;if(s==="sui"){let[l]=i.splitCoins(i.gas,[a]);return ka(i,p.pool.sui,l,a)}let o=p.pool[s];if(!o)throw new Error(`${s} not support, please use ${Object.keys(p.pool).join(", ")}.`);let c=await pi(t,n.address,o.type);if(!c.data[0])throw new Error(`Insufficient balance for ${o.name} Token`);let u=c.data[0].coinObjectId;if(c.data.length>=2){let l=1;for(;l<c.data.length;)i.mergeCoins(u,[c.data[l].coinObjectId]),l++}return ka(i,o,u,a)}static fromData(e){return new yi(e)}},bl=class bi extends ae{constructor(e){super(e),this.data=e}txType;txSubType;async build(){let{coinType:e,amount:t}=this.data,n=new yl,s=p.pool[e];if(!s)throw new Error(`${e} not support, please use ${Object.keys(p.pool).join(", ")}.`);return ol(n,s,t)}static fromData(e){return new bi(e)}},wl=class{application="navi";async deserialize(r){let{transactionBlock:e}=r,t=new sl(e).decode();return{txType:rl.Other,txSubType:t.type,intentionData:t.intentionData}}async build(r){let{suiClient:e,account:t}=r,n;switch(r.txSubType){case"EntryDeposit":n=hl.fromData(r.intentionData);break;case"EntryBorrow":n=ml.fromData(r.intentionData);break;case"EntryRepay":n=gl.fromData(r.intentionData);break;case"EntryWithdraw":n=bl.fromData(r.intentionData);break;case"ClaimReward":n=ll.fromData(r.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:t})}},Sl=class{apps;constructor(r){this.apps=new Map(r.map(e=>[e.application,e]))}getAppHelper(r){let e=this.apps.get(r);if(!e)throw new Error(`${r} not registered`);return e}},vl="msafe-plain-tx",El=Tl.others.plain,Cl=class{application;constructor(){this.application=vl}async deserialize(r){let{transactionBlock:e,suiClient:t}=r,n=await e.build({client:t});return{txType:Il.Other,txSubType:El,intentionData:{content:Ol(n)}}}async build(r){let{suiClient:e,account:t}=r,n=xl.from(kl(r.intentionData.content)),s=await e.devInspectTransactionBlock({transactionBlock:n,sender:t.address});if(s.effects.status.status!=="success")throw new Error(s.effects.status.error);return n}},Qt=new Sl([new tl,new wl,new Gu,new Cl]);import{MultiSigAccount as Ll,SigningMessageHelper as Ul,TransactionDefaultApplication as Pe,TransactionSubTypes as Ne,TransactionType as Fe,buildRejectTxb as Ei,isSameAddress as Ci}from"@msafe/sui3-utils";import{TransactionBlock as Mi}from"@mysten/sui.js/transactions";import{normalizeStructTag as Vl,toHEX as ql}from"@mysten/sui.js/utils";import{TransactionBlock as Ml}from"@mysten/sui.js/transactions";var Dl=1000n,Al=120n,Pl=100n,Nl={multiplier:{numerator:Al,denominator:Pl}};var Xt=class{constructor(e){this.globals=e}async simulate(e,t=Nl){let n=this.copyTransactionBlock(e.txb),{suiClient:s}=this.globals,a=await this.getGasPrice(t);n.setGasPrice(a);let i=await s.devInspectTransactionBlock({transactionBlock:n,sender:e.sender}),{gasUsed:o}=i.effects,c=this.toGasBudget(o,a),u=i.effects.status.status==="success",l;return u||(l=i.effects.status.error),{success:u,gasPrice:a,gasObject:i.effects.gasObject.reference,gasUsed:o,gasBudget:c,simulationError:l}}async getGasPrice(e){if(this.isFixedValue(e))return e.fixedVal;let t=await this.globals.suiClient.getReferenceGasPrice();return this.applyGasOption(t,e)}toGasBudget(e,t){let{computationCost:n,storageCost:s}=e,a=Dl*t,i=BigInt(n)+a,o=i+BigInt(s);return o>i?o:i}isFixedValue(e){return"fixedVal"in e}isMultiplier(e){return"multiplier"in e}applyGasOption(e,t){if(this.isFixedValue(t))return t.fixedVal;if(this.isMultiplier(t)){let{multiplier:n}=t;return e*n.numerator/n.denominator}throw new Error("Sanity: Unknown gas price option")}copyTransactionBlock(e){return Ml.from(e.serialize())}};import{Buffer as wi}from"buffer";function mn(r){return wi.from(r,"utf-8")}function hp(r){return`0x${Array.prototype.map.call(r,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function fn(r){return Uint8Array.from(wi.from(r.startsWith("0x")?r.slice(2):r,"hex"))}import{verifyPersonalMessage as Fl,verifyTransactionBlock as Rl}from"@mysten/sui.js/verify";import{normalizeSuiAddress as pn,normalizeStructTag as gn}from"@mysten/sui.js/utils";import{normalizeStructTag as hn}from"@mysten/sui.js/utils";var er=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let t=hn(e);if(this._coinMetaReg.has(t))return this._coinMetaReg.get(t);let n=await this.queryCoinMeta(t);return n&&this._coinMetaReg.set(t,n),n}async queryCoinMeta(e){return await this._client.getCoinMetadata({coinType:e})||void 0}},Si=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,tr=class r{static isCoin(e){return e?hn(e).match(Si)!=null:!1}static getCoinType(e){let[,t]=hn(e).match(Si)??[];return t||null}static getBalance(e){if(!r.isCoin(e.type)||e.content?.dataType!=="moveObject")return;let{balance:t}=e.content?.fields;if(t!==void 0)return BigInt(t)}};var ie=class{static normalizeSuiAddress(e){return pn(e)}static normalizeStructTag(e){return gn(e)}static isSuiAddressEqual(e,t){return pn(e)===pn(t)}static isSuiStructEqual(e,t){return gn(e)===gn(t)}static isCoinObjectType(e){return tr.isCoin(e)}};function Ti(r,e){return r.startsWith(e)?r:e+r}var Ii=class r{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?Rl(e.message,e.signature):Fl(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let t=mn(e.messageStr);return this.getPublicKeyFromSignature({message:t,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let t=await r.getPublicKeyFromSignature(e);return ie.isSuiAddressEqual(t.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let t=mn(e.messageStr);return this.verifySignature({message:t,messageType:"Personal",signature:e.signature,targetAddress:e.targetAddress})}static async verifyTransactionSignature(e){return this.verifySignature({messageType:"TransactionBlock",message:e.payload,signature:e.signature,targetAddress:e.targetAddress})}};import{PublicKeySerde as jl}from"@msafe/sui3-utils";import{parseSerializedSignature as _l}from"@mysten/sui.js/cryptography";import{MultiSigPublicKey as Bl}from"@mysten/sui.js/multisig";var Ap="0x2::sui::SUI";async function xi(r,e){let t;try{t=await r.queryTransactionBlocks({filter:{FromAddress:e},options:{showInput:!0},limit:2})}catch{return}if(t.data.length===0||!t.data[0].transaction?.txSignatures)return;let s=t.data[0].transaction?.txSignatures;for(let a=0;a!==s.length;a++){let i=s[a],o=Wl(i,e);if(o)return o}}function Wl(r,e){let t=_l(r);switch(t.signatureScheme){case"MultiSig":{let n=new Bl(t.multisig.multisig_pk).toSuiAddress();if(ie.isSuiAddressEqual(n,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(ie.isSuiAddressEqual(t.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let n=jl.de({publicKeyEncoded:t.publicKey,schema:t.signatureScheme});return ie.isSuiAddressEqual(n.toSuiAddress(),e)?n:void 0}default:throw new Error("Unknown schema")}}async function Pp(r){let e=!0,t,n=[];for(;e;){let s=await r.suiClient.getCoins({owner:r.owner,coinType:r.coinType,cursor:t});n.push(...s.data),e=s.hasNextPage,t=s.nextCursor}return n}var ki=25;async function Oi(r){let e=[];for(;await r.hasNext();){let t=await r.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var yn=class{constructor(e){this.requester=e;this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},rr=class{constructor(e){this.requester=e;this.pager=new yn(e),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}};async function vi(r,e,t){let n=new bn(r,e,t);return await Oi(n)}var bn=class extends rr{constructor(t,n,s){super(new wn(t,n,s));this.provider=t;this.owner=n;this.options=s}},wn=class{constructor(e,t,n){this.provider=e;this.owner=t;this.options=n;this.nextCursor=null,this.filter=n?.filter,this.pageSize=n?.pageSize||ki,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}nextCursor;filter;pageSize;objectOptions;async doNextRequest(){let e=await this.provider.getOwnedObjects({owner:this.owner,options:this.objectOptions,cursor:this.nextCursor,limit:this.pageSize});this.nextCursor=e.nextCursor;let t;if(this.filter){let{filter:n}=this;t=e.data.filter(s=>n?.(s))}else t=e.data;return{data:t.map(n=>n.data).filter(n=>n),hasNext:e.hasNextPage}}};var Re=class r{constructor(e,t){this.globals=e;this.info=t;this.multiSig=new Ll({threshold:t.threshold,ownersWithWeight:t.owners,creationNonce:t.creationNonce}),this.coinHelper=new er(this.suiClient),this.simulator=new Xt(e)}multiSig;coinHelper;simulator;static async New(e,t){let n=await e.backend.getMSafeAccountInfo(t);if(new r(e,n).address!==t)throw new Error("Invalid msafe config with address")}async ownedCoins(){let e=await this.suiClient.getAllBalances({owner:this.address});return Promise.all(e.map(async t=>{let n=await this.coinHelper.getCoinMeta(t.coinType),s=t.lockedBalance.number?BigInt(t.totalBalance)-BigInt(t.lockedBalance.number):BigInt(t.totalBalance);return{type:Vl(t.coinType),balance:BigInt(s),metadata:n}}))}async ownedObjects(e){let t={filter:n=>!n?.data?.type?.startsWith("0x2::coin::Coin"),...e};return vi(this.suiClient,this.address,t)}async pendingTransaction(){let e=await this.backend.getPendingTransactions({msafeAddress:this.address});if(!e.pending)return;let t=e.pending,n=e.reject;return{application:t.application,txType:t.txType,txSubType:t.txSubType,createdAt:t.createdAt,creator:t.creator,digest:t.digest,intention:t.intention,sequenceNumber:t.sequenceNumber,payload:t.payload,votes:t.votes,approvalWeight:this.calculateWeightFromVotes(t.votes),msafeAddress:t.msafeAddress,rejectDigest:n?.digest??"",rejectPayload:n?.payload??"",rejectVotes:n?.votes??[],rejectWeight:this.calculateWeightFromVotes(n?.votes??[])}}async historyTransaction(e){return this.backend.getHistoryTransactions({msafeAddress:this.address,...e})}async futureIntentions(e){return this.backend.getFutureIntentions({msafeAddress:this.address,...e})}async currentSequenceNumber(){return this.backend.getCurrentSequenceNumber(this.address)}async nextSequenceNumber(){return this.backend.getNextSequenceNumber(this.address)}async simulateIntention(e){let t=Qt.getAppHelper(e.application);if(!t)throw new Error(`Can't find app helper for application ${e.application}`);let n=await t.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async proposeIntention(e){let t=Ul.proposeIntentionMessage({msafeAddress:this.address,intention:e.intention,sn:e.sequenceNumber}),n=await this.wallet.signPersonalMessage({messageStr:t});return this.backend.proposeIntention({...e,msafeAddress:this.address,signature:n.signature})}async proposeIntentionAndBuildVote(e){let t=Qt.getAppHelper(e.application);if(!t)throw new Error(`Can't find app helper for application ${e.application}`);let n=await t.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});n.setGasPrice(e.gasPrice),n.setGasBudget(e.gasBudget),n.setSender(this.address);let s=await n.build({client:this.globals.suiClient}),a=await n.getDigest({client:this.globals.suiClient}),i=await this.wallet.signTransactionBlock({transactionBlock:s});return this.backend.proposeIntentionAndBuildVote({...e,payload:ql(s),digest:a,msafeAddress:this.address,signature:i.signature})}async simulateCoinTransferIntention(e){let t=await this.nextSequenceNumber();return this.simulateIntention({application:Pe,txType:Fe.Assets,txSubType:Ne.assets.coin.send,sequenceNumber:t,intention:e})}async proposeCoinTransferIntention(e){let t=await this.nextSequenceNumber();return this.proposeIntention({application:Pe,txType:Fe.Assets,txSubType:Ne.assets.coin.send,sequenceNumber:t,intention:e})}async simulateObjectTransferIntention(e){let t=await this.nextSequenceNumber();return this.simulateIntention({application:Pe,txType:Fe.Assets,txSubType:Ne.assets.object.send,sequenceNumber:t,intention:e})}async proposeObjectTransferIntention(e){let t=await this.nextSequenceNumber();return this.proposeIntention({application:Pe,txType:Fe.Assets,txSubType:Ne.assets.object.send,sequenceNumber:t,intention:e})}async simulatePlainPayloadIntention(e){let t=await this.nextSequenceNumber();return this.simulateIntention({application:Pe,txType:Fe.Other,txSubType:Ne.others.plain,sequenceNumber:t,intention:e})}async proposePlainPayloadIntention(e){let t=await this.nextSequenceNumber(),n=Mi.from(e.payload);if(!n.blockData.sender||!Ci(n.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:Pe,txType:Fe.Other,txSubType:Ne.others.plain,sequenceNumber:t,intention:e})}async voteForTransaction(e,t){let n=fn(t),s=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.voteForTransaction({msafeAddress:this.address,digest:e,signature:s.signature})}async proposePendingTransaction(e){let t=new Mi,n=await t.build({client:this.suiClient}),s=await t.getDigest({client:this.suiClient}),a=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.proposePendingTransaction({msafeAddress:this.address,userAddress:await this.userAddress(),intention:e,digest:s,signature:a.signature})}async simulateRejectTx(){let e=await this.pendingTransaction();if(!e||e.rejectDigest!=="")throw new Error("Already rejected");let t=e.payload,n=Ei(this.address,t);return this.simulator.simulate({txb:n,sender:this.address})}async rejectCurrentTx(e){let t=await this.pendingTransaction();if(!t||t.rejectDigest!=="")throw new Error("Already rejected");let n=t.payload,s=Ei(this.address,n),a=await s.getDigest({client:this.suiClient}),i=await s.build({client:this.suiClient}),o=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.rejectCurrentTx({msafeAddress:this.address,digest:a,signature:o.signature,...e})}async simulateBuildTransaction(){let e=await this.backend.getNextIntention({msafeAddress:this.address}),t=Qt.getAppHelper(e.application);if(!t)throw new Error(`Can't find app helper for application ${e.application}`);let n=await t.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async buildNextIntentionAndAddToPending(e){return this.backend.buildNextIntentionAndAddToPending({msafeAddress:this.address,forceBuild:e.forceBuild,gasPrice:e.gasPrice,gasBudget:e.gasBudget})}async skipNextFailedIntention(){return this.backend.skipNextFailedIntention({msafeAddress:this.address})}async executePendingTx(e,t=!1){let n=t?e.rejectVotes:e.votes,s=t?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(n)<this.info.threshold)throw new Error("Not enough signature");let a=[],i=new Map(n.map(c=>[c.userAddress,c.signature]));for(let c=0;c<this.info.owners.length;c++){let u=this.info.owners[c],l=i.get(u.address);l&&a.push(l)}let o=this.multiSig.combinePartialSignatures(a);return this.suiClient.executeTransactionBlock({transactionBlock:fn(s),signature:o,options:{showEffects:!0,showEvents:!0}})}async dashboard(){return this.backend.getDashboard({msafeAddress:this.address})}calculateWeightFromVotes(e){return this.calculateWeight(e.map(t=>t.userAddress))}calculateWeight(e){let t=0;for(let n=0;n<e.length;n++){let s=this.info.owners.find(a=>Ci(a.address,e[n]));s&&(t+=s.weight)}return t}get address(){return this.multiSig.address}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}async userAddress(){return this.globals.wallet.address()}get suiClient(){return this.globals.suiClient}};import{isSameAddress as Hl}from"@msafe/sui3-utils";import{normalizeSuiAddress as $l}from"@mysten/sui.js/utils";var nr=class{constructor(e){this.globals=e;this.knownPublicKeys=new Map}knownPublicKeys;async getPublicKey(e){let t=this.knownPublicKeys.get(e);if(t)return t;let n=await this._getPublicKey(e);return n&&this.knownPublicKeys.set(e,n),n}async getPublicKeyBatch(e){let t=new Array(e.length).fill(void 0);for(let a=0;a<e.length;a++){let i=e[a];t[a]=this.knownPublicKeys.get(i)}let n=t.map((a,i)=>a===void 0?i:-1).filter(a=>a!==-1);if(n.length===0)return t;let s=await this.globals.backend.getPublicKeyBatch(n.map(a=>e[a]));for(let a=0;a<n.length;a++){let i=n[a];t[i]=s[a]}for(let a=0;a<t.length;a++)t[a]===void 0&&(t[a]=await this.getPublicKeyFromChain(e[a]));for(let a=0;a<e.length;a++)t[a]&&this.knownPublicKeys.set(e[a],t[a]);return t}addPublicKey(e,t){if(!Hl(e,t.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set($l(e),t)}async _getPublicKey(e){let t=await this.getPublicKeyFromBackend(e);if(t)return t;let n=await this.getPublicKeyFromChain(e);if(n)return n}async getPublicKeyFromBackend(e){try{return await this.globals.backend.getPublicKey(e)}catch{return}}async getPublicKeyFromChain(e){return xi(this.globals.suiClient,e)}};var sr=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};import{SuiClient as Xl}from"@mysten/sui.js/client";import{PublicKeySerde as Di,UserMSafeStatus as Gl}from"@msafe/sui3-utils";import ar from"axios";import*as cr from"json-bigint";var ir=class r{constructor(e){this.apiURL=e}_token;async authSign(e){let t=await this.post("/auth/login",e);return this._token=t.data.accessToken,this._token}async verifyToken(e){try{return(await this.get("/auth",{headers:this.headers(e)})).status===200}catch{return!1}}setJWTToken(e){this._token=e}async getPublicKey(e){return(await this.getPublicKeyBatch([e]))[0]}async getPublicKeyBatch(e){let t={userAddressList:e};return(await this.get("/user/public-keys",{params:t,headers:this.headers()})).data?.map(s=>s?Di.de(s):void 0)}async getMSafeAccountInfo(e){let t={msafeAddress:e},n=await this.get("/msafe",{params:t,headers:this.headers()});return r.toMSafeConfig(n.data)}async getUserInfo(){return(await this.get("/user",{headers:this.headers()})).data}async getOwnedMSafeByStatus(e){let t={status:e.status??Gl.active,...e.pagination?{page:e.pagination.page.toString(),limit:e.pagination.limit.toString()}:{}},n=await this.get("/msafe/owned",{params:t,headers:this.headers()});return{data:n.data.data.map(r.toMSafeConfig),meta:n.data.meta}}async updateMSafeStatus(e){let t=e;await this.post("/msafe/status",t,{headers:this.headers()})}async getPendingTransactions(e){return(await this.get("/transaction/pending",{params:e,headers:this.headers()})).data}async getHistoryTransactions(e){return(await this.get("/transaction/history",{params:e,headers:this.headers()})).data}async getFutureIntentions(e){return(await this.get("/transaction/intention",{params:e,headers:this.headers()})).data}async getNextIntention(e){return(await this.get("/transaction/intention/next",{params:e,headers:this.headers()})).data}async getCurrentSequenceNumber(e){return(await this.get("/transaction/sn/current",{params:{msafeAddress:e},headers:this.headers()})).data}async getNextSequenceNumber(e){return(await this.get("/transaction/sn/next",{params:{msafeAddress:e},headers:this.headers()})).data}async createMSafeAccount(e){await this.post("/msafe/create",e,{headers:this.headers()})}async proposeIntention(e){await this.post("/transaction/intention",e,{headers:this.headers()})}async proposePendingTransaction(e){}async rejectCurrentTx(e){await this.post("/transaction/pending/reject",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async voteForTransaction(e){await this.post("/transaction/pending/vote",e,{headers:this.headers()})}async buildNextIntentionAndAddToPending(e){await this.post("/transaction/pending/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async proposeIntentionAndBuildVote(e){await this.post("/transaction/intention/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async skipNextFailedIntention(e){await this.post("/transaction/pending/skip",e,{headers:this.headers()})}async getAddressBookEntries(e){return(await this.get("/address-book",{headers:this.headers(),params:e})).data}async updateAddressBook(e){await this.post("/address-book",e,{headers:this.headers()})}async getAddressBookMode(){return(await this.get("/address-book/mode",{headers:this.headers()})).data}async setAddressBookMode(e){await this.post("/address-book/mode",{mode:e.mode},{headers:this.headers()})}async submitReport(e){await this.post("/report",e)}async getDashboard(e){return(await this.get("/dashboard",{params:e,headers:this.headers()})).data}headers(e){return{Authorization:`Bearer ${e||this._token}`}}static toMSafeConfig(e){return{...e,owners:e.owners.map(t=>({address:t.address,weight:t.weight,publicKey:Di.de({publicKeyEncoded:t.publicKeyEncoded,schema:t.schema})}))}}async get(e,t){let n=this.getFullUrl(e);try{return await ar.get(n,t)}catch(s){throw or.fromError(s)??s}}async post(e,t,n){let s=this.getFullUrl(e);try{return await ar.post(s,t,{...n,transformRequest:this.getTransformRequest()})}catch(a){throw or.fromError(a)??a}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${Ti(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:t}=ar.defaults;return t?t instanceof Array?e=t:e=[t]:e=[],[n=>cr.parse(cr.stringify(n)),...e]}},or=class r extends Error{constructor(t){super();this.e=t;Error.captureStackTrace(this,this.constructor)}name;static fromError(t){if(ar.isAxiosError(t)&&t?.response?.data&&"message"in t.response.data)return new r(t)}get status(){return this.e.response?.status??void 0}get message(){return`${this.respMessage()??"Unknown resp"}`}respMessage(){if(this.e.response?.data)return(this.e.response?.data).message??void 0}get endpoint(){return this.e.config?.url??""}toString(){return this.message}};var zl=(a=>(a.local="local",a.unit="unit",a.dev="dev",a.prev="prev",a.prod="prod",a))(zl||{}),Sn="https://fullnode.testnet.sui.io",Ai="https://fullnode.mainnet.sui.io",Pi="http://127.0.0.1:3000",Ni="http://127.0.0.1:3001",Zl="https://sui-dev.m-safe.link",Kl="http://13.56.226.148:81",Yl="https://sui-preview.m-safe.link",Jl="https://sui.m-safe.link",Ql=new Map([["unit",{suiClient:{url:Sn},backend:{url:Pi},syncingURL:Ni,network:"sui:testnet"}],["local",{suiClient:{url:Sn},backend:{url:Pi},syncingURL:Ni,network:"sui:testnet"}],["dev",{suiClient:{url:Sn},backend:{url:Zl},syncingURL:Kl,network:"sui:testnet"}],["prev",{suiClient:{url:Ai},backend:{url:Yl},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:Ai},backend:{url:Jl},syncingURL:"",network:"sui:mainnet"}]]);function Fi(r,e){let t=Ql.get(r);if(!t)throw new Error("Unknown environment");return e?.suiClient?.url&&(t.suiClient.url=e.suiClient.url),e?.backend?.url&&(t.backend.url=e.backend.url),t}var ur=class r{backend;suiClient;config;_wallet;constructor(e){this.backend=e.backend,this.suiClient=e.suiClient,this.config=e.config}static async New(e,t){let n=Fi(e,t),s=new Xl(n.suiClient),a=new ir(n.backend.url);return new r({backend:a,suiClient:s,config:n})}connectWallet(e){this._wallet=e}get wallet(){if(!this._wallet)throw new Error("wallet not connected");return this._wallet}set wallet(e){this._wallet=e}};var Tn=class r{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,t){let n=await ur.New(e,t);return new r(n)}async connectWallet(e){if(e.jwtToken&&await this.backend.verifyToken(e.jwtToken))return this.globals.wallet=e.wallet,this.backend.setJWTToken(e.jwtToken),e.jwtToken;let t=await this.authSign(e.wallet);return this.globals.wallet=e.wallet,this.backend.setJWTToken(t),t}async authSign(e){let t=ed.loginMessageWithTimestamp(new Date().toUTCString()),n=await e.signPersonalMessage({messageStr:t});return this.backend.authSign({address:await e.address(),message:t,signature:n.signature,walletType:e.walletType})}async userInfo(){return this.globals.backend.getUserInfo()}async ownedMSafe(e){return this.globals.backend.getOwnedMSafeByStatus({status:td.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new Re(this.globals,e)}async getMSafeAccountFromAddress(e){let t=await this.backend.getMSafeAccountInfo(e);return new Re(this.globals,t)}get creationHelper(){return this._creationHelper||(this._creationHelper=new Be(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new nr(this.globals)),this._publicKeyHelper}get config(){return this.globals.config}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}get AddressBook(){return new We(this.globals)}get Invitation(){return new It(this.globals)}get Report(){return new sr(this.globals)}async walletAddress(){return this.wallet.address()}};export{We as AddressBookSDK,Si as COIN_TYPE_ARG_REGEX,tr as Coin,er as CoinHelper,Be as CreateHelper,Zl as DEV_API_URL,Kl as DEV_SYNCING_URL,Ql as ENV_CONFIGS,ie as Formatter,fn as HexToUint8Array,Pi as LOCAL_API_URL,Ni as LOCAL_SYNCING_URL,Ai as MAINNET_RPC_URL,Re as MSafeAccount,Tn as MSafeClient,zl as MSafeEnv,ur as MSafeGlobals,Yl as PREV_API_URL,Jl as PROD_API_URL,Ap as SUI_COIN,Ii as SignatureVerifier,Sn as TESTNET_RPC_URL,hp as Uint8ArrayToHex,Ti as addPrefix,Pp as getAllCoins,Fi as getMSafeConfig,xi as getPublicKeyFromChain,mn as stringToBuffer};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|