@msafe/sui3-sdk 0.0.47 → 0.0.48
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 +3 -1
- package/src/core/MSafeAccount.ts +1 -1
- package/src/globals/const.ts +0 -1
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}})}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 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};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|