denotify-client 1.1.22 → 1.1.24
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.
@@ -1,4 +1,4 @@
|
|
1
1
|
var denotifyClient=function(R){var It,Xe,Me,bt,Ct,Jr,ue,de,Lr,to,vt,J,ve,er,Qn,Ft,Wr,Ze,Lt,ke,Ae,Se,Z,tr,es,rr,ts,nr,Ye,Ut,sr,ir,$l;"use strict";var Pl=Object.defineProperty;var Nl=(R,I,H)=>I in R?Pl(R,I,{enumerable:!0,configurable:!0,writable:!0,value:H}):R[I]=H;var d=(R,I,H)=>(Nl(R,typeof I!="symbol"?I+"":I,H),H),Yn=(R,I,H)=>{if(!I.has(R))throw TypeError("Cannot "+H)};var m=(R,I,H)=>(Yn(R,I,"read from private field"),H?H.call(R):I.get(R)),j=(R,I,H)=>{if(I.has(R))throw TypeError("Cannot add the same private member more than once");I instanceof WeakSet?I.add(R):I.set(R,H)},N=(R,I,H,_t)=>(Yn(R,I,"write to private field"),_t?_t.call(R,H):I.set(R,H),H),eo=(R,I,H,_t)=>({set _(Bt){N(R,I,Bt,H)},get _(){return m(R,I,_t)}}),V=(R,I,H)=>(Yn(R,I,"access private method"),H);function I(n,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in n)){const i=Object.getOwnPropertyDescriptor(r,s);i&&Object.defineProperty(n,s,i.get?i:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}var H=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})};const _t=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>H(void 0,void 0,void 0,function*(){return yield(yield Promise.resolve().then(()=>cr)).fetch(...t)}):e=fetch,(...t)=>e(...t)};class Bt extends Error{constructor(e,t="FunctionsError",r){super(e),super.name=t,this.context=r}}class ro extends Bt{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class no extends Bt{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class so extends Bt{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var io=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})};class oo{constructor(e,{headers:t={},customFetch:r}={}){this.url=e,this.headers=t,this.fetch=_t(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return io(this,void 0,void 0,function*(){try{const{headers:s,method:i,body:o}=t;let a={},c;o&&(s&&!Object.prototype.hasOwnProperty.call(s,"Content-Type")||!s)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",c=o):typeof o=="string"?(a["Content-Type"]="text/plain",c=o):typeof FormData<"u"&&o instanceof FormData?c=o:(a["Content-Type"]="application/json",c=JSON.stringify(o)));const u=yield this.fetch(`${this.url}/${e}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),s),body:c}).catch(p=>{throw new ro(p)}),l=u.headers.get("x-relay-error");if(l&&l==="true")throw new no(u);if(!u.ok)throw new so(u);let h=((r=u.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),y;return h==="application/json"?y=yield u.json():h==="application/octet-stream"?y=yield u.blob():h==="multipart/form-data"?y=yield u.formData():y=yield u.text(),{data:y,error:null}}catch(s){return{data:null,error:s}}})}}var ao=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function co(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Et={},uo={get exports(){return Et},set exports(n){Et=n}};(function(n,e){var t=typeof self<"u"?self:ao,r=function(){function i(){this.fetch=!1,this.DOMException=t.DOMException}return i.prototype=t,new i}();(function(i){(function(o){var a={searchParams:"URLSearchParams"in i,iterable:"Symbol"in i&&"iterator"in Symbol,blob:"FileReader"in i&&"Blob"in i&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in i,arrayBuffer:"ArrayBuffer"in i};function c(f){return f&&DataView.prototype.isPrototypeOf(f)}if(a.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],l=ArrayBuffer.isView||function(f){return f&&u.indexOf(Object.prototype.toString.call(f))>-1};function h(f){if(typeof f!="string"&&(f=String(f)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(f))throw new TypeError("Invalid character in header field name");return f.toLowerCase()}function y(f){return typeof f!="string"&&(f=String(f)),f}function p(f){var b={next:function(){var O=f.shift();return{done:O===void 0,value:O}}};return a.iterable&&(b[Symbol.iterator]=function(){return b}),b}function w(f){this.map={},f instanceof w?f.forEach(function(b,O){this.append(O,b)},this):Array.isArray(f)?f.forEach(function(b){this.append(b[0],b[1])},this):f&&Object.getOwnPropertyNames(f).forEach(function(b){this.append(b,f[b])},this)}w.prototype.append=function(f,b){f=h(f),b=y(b);var O=this.map[f];this.map[f]=O?O+", "+b:b},w.prototype.delete=function(f){delete this.map[h(f)]},w.prototype.get=function(f){return f=h(f),this.has(f)?this.map[f]:null},w.prototype.has=function(f){return this.map.hasOwnProperty(h(f))},w.prototype.set=function(f,b){this.map[h(f)]=y(b)},w.prototype.forEach=function(f,b){for(var O in this.map)this.map.hasOwnProperty(O)&&f.call(b,this.map[O],O,this)},w.prototype.keys=function(){var f=[];return this.forEach(function(b,O){f.push(O)}),p(f)},w.prototype.values=function(){var f=[];return this.forEach(function(b){f.push(b)}),p(f)},w.prototype.entries=function(){var f=[];return this.forEach(function(b,O){f.push([O,b])}),p(f)},a.iterable&&(w.prototype[Symbol.iterator]=w.prototype.entries);function v(f){if(f.bodyUsed)return Promise.reject(new TypeError("Already read"));f.bodyUsed=!0}function g(f){return new Promise(function(b,O){f.onload=function(){b(f.result)},f.onerror=function(){O(f.error)}})}function S(f){var b=new FileReader,O=g(b);return b.readAsArrayBuffer(f),O}function U(f){var b=new FileReader,O=g(b);return b.readAsText(f),O}function te(f){for(var b=new Uint8Array(f),O=new Array(b.length),Y=0;Y<b.length;Y++)O[Y]=String.fromCharCode(b[Y]);return O.join("")}function L(f){if(f.slice)return f.slice(0);var b=new Uint8Array(f.byteLength);return b.set(new Uint8Array(f)),b.buffer}function Re(){return this.bodyUsed=!1,this._initBody=function(f){this._bodyInit=f,f?typeof f=="string"?this._bodyText=f:a.blob&&Blob.prototype.isPrototypeOf(f)?this._bodyBlob=f:a.formData&&FormData.prototype.isPrototypeOf(f)?this._bodyFormData=f:a.searchParams&&URLSearchParams.prototype.isPrototypeOf(f)?this._bodyText=f.toString():a.arrayBuffer&&a.blob&&c(f)?(this._bodyArrayBuffer=L(f.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(f)||l(f))?this._bodyArrayBuffer=L(f):this._bodyText=f=Object.prototype.toString.call(f):this._bodyText="",this.headers.get("content-type")||(typeof f=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):a.searchParams&&URLSearchParams.prototype.isPrototypeOf(f)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a.blob&&(this.blob=function(){var f=v(this);if(f)return f;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?v(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(S)}),this.text=function(){var f=v(this);if(f)return f;if(this._bodyBlob)return U(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(te(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a.formData&&(this.formData=function(){return this.text().then(zr)}),this.json=function(){return this.text().then(JSON.parse)},this}var or=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function Vr(f){var b=f.toUpperCase();return or.indexOf(b)>-1?b:f}function _e(f,b){b=b||{};var O=b.body;if(f instanceof _e){if(f.bodyUsed)throw new TypeError("Already read");this.url=f.url,this.credentials=f.credentials,b.headers||(this.headers=new w(f.headers)),this.method=f.method,this.mode=f.mode,this.signal=f.signal,!O&&f._bodyInit!=null&&(O=f._bodyInit,f.bodyUsed=!0)}else this.url=String(f);if(this.credentials=b.credentials||this.credentials||"same-origin",(b.headers||!this.headers)&&(this.headers=new w(b.headers)),this.method=Vr(b.method||this.method||"GET"),this.mode=b.mode||this.mode||null,this.signal=b.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&O)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(O)}_e.prototype.clone=function(){return new _e(this,{body:this._bodyInit})};function zr(f){var b=new FormData;return f.trim().split("&").forEach(function(O){if(O){var Y=O.split("="),K=Y.shift().replace(/\+/g," "),F=Y.join("=").replace(/\+/g," ");b.append(decodeURIComponent(K),decodeURIComponent(F))}}),b}function M(f){var b=new w,O=f.replace(/\r?\n[\t ]+/g," ");return O.split(/\r?\n/).forEach(function(Y){var K=Y.split(":"),F=K.shift().trim();if(F){var Gr=K.join(":").trim();b.append(F,Gr)}}),b}Re.call(_e.prototype);function W(f,b){b||(b={}),this.type="default",this.status=b.status===void 0?200:b.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in b?b.statusText:"OK",this.headers=new w(b.headers),this.url=b.url||"",this._initBody(f)}Re.call(W.prototype),W.prototype.clone=function(){return new W(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new w(this.headers),url:this.url})},W.error=function(){var f=new W(null,{status:0,statusText:""});return f.type="error",f};var qr=[301,302,303,307,308];W.redirect=function(f,b){if(qr.indexOf(b)===-1)throw new RangeError("Invalid status code");return new W(null,{status:b,headers:{location:f}})},o.DOMException=i.DOMException;try{new o.DOMException}catch{o.DOMException=function(b,O){this.message=b,this.name=O;var Y=Error(b);this.stack=Y.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function jt(f,b){return new Promise(function(O,Y){var K=new _e(f,b);if(K.signal&&K.signal.aborted)return Y(new o.DOMException("Aborted","AbortError"));var F=new XMLHttpRequest;function Gr(){F.abort()}F.onload=function(){var ar={status:F.status,statusText:F.statusText,headers:M(F.getAllResponseHeaders()||"")};ar.url="responseURL"in F?F.responseURL:ar.headers.get("X-Request-URL");var Zn="response"in F?F.response:F.responseText;O(new W(Zn,ar))},F.onerror=function(){Y(new TypeError("Network request failed"))},F.ontimeout=function(){Y(new TypeError("Network request failed"))},F.onabort=function(){Y(new o.DOMException("Aborted","AbortError"))},F.open(K.method,K.url,!0),K.credentials==="include"?F.withCredentials=!0:K.credentials==="omit"&&(F.withCredentials=!1),"responseType"in F&&a.blob&&(F.responseType="blob"),K.headers.forEach(function(ar,Zn){F.setRequestHeader(Zn,ar)}),K.signal&&(K.signal.addEventListener("abort",Gr),F.onreadystatechange=function(){F.readyState===4&&K.signal.removeEventListener("abort",Gr)}),F.send(typeof K._bodyInit>"u"?null:K._bodyInit)})}return jt.polyfill=!0,i.fetch||(i.fetch=jt,i.Headers=w,i.Request=_e,i.Response=W),o.Headers=w,o.Request=_e,o.Response=W,o.fetch=jt,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var s=r;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,n.exports=e})(uo,Et);const Kr=co(Et),cr=I({__proto__:null,default:Kr},[Et]);class lo{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.allowEmpty=e.allowEmpty,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=Kr:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let s=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var o,a,c;let u=null,l=null,h=null,y=i.status,p=i.statusText;if(i.ok){if(this.method!=="HEAD"){const S=await i.text();S===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=S:l=JSON.parse(S))}const v=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),g=(a=i.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");v&&g&&g.length>1&&(h=parseInt(g[1]))}else{const v=await i.text();try{u=JSON.parse(v),Array.isArray(u)&&i.status===404&&(l=[],u=null,y=200,p="OK")}catch{i.status===404&&v===""?(y=204,p="No Content"):u={message:v}}if(u&&this.allowEmpty&&(!((c=u==null?void 0:u.details)===null||c===void 0)&&c.includes("Results contain 0 rows"))&&(u=null,y=200,p="OK"),u&&this.shouldThrowOnError)throw u}return{error:u,data:l,count:h,status:y,statusText:p}});return this.shouldThrowOnError||(s=s.catch(i=>({error:{message:`FetchError: ${i.message}`,details:"",hint:"",code:i.code||""},data:null,count:null,status:0,statusText:""}))),s.then(e,t)}}class ho extends lo{select(e){let t=!1;const r=(e??"*").split("").map(s=>/\s/.test(s)&&!t?"":(s==='"'&&(t=!t),s)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s}={}){const i=s?`${s}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t}={}){const r=typeof t>"u"?"limit":`${t}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:r}={}){const s=typeof r>"u"?"offset":`${r}.offset`,i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this.url.searchParams.set(i,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.headers.Accept="application/vnd.pgrst.object+json",this.allowEmpty=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:o="text"}={}){const a=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=this.headers.Accept;return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${c}"; options=${a};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}class xt extends ho{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){const r=t.map(s=>typeof s=="string"&&new RegExp("[,()]").test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let i="";s==="plain"?i="pl":s==="phrase"?i="ph":s==="websearch"&&(i="w");const o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t}={}){const r=t?`${t}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}}class fo{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=t,this.schema=r,this.fetch=s}select(e,{head:t=!1,count:r}={}){const s=t?"HEAD":"GET";let i=!1;const o=(e??"*").split("").map(a=>/\s/.test(a)&&!i?"":(a==='"'&&(i=!i),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new xt({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t}={}){const r="POST",s=[],i=e;if(t&&s.push(`count=${t}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),Array.isArray(e)){const o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){const a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new xt({method:r,url:this.url,headers:this.headers,schema:this.schema,body:i,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s}={}){const i="POST",o=[`resolution=${r?"ignore":"merge"}-duplicates`];t!==void 0&&this.url.searchParams.set("on_conflict",t);const a=e;return s&&o.push(`count=${s}`),this.headers.Prefer&&o.unshift(this.headers.Prefer),this.headers.Prefer=o.join(","),new xt({method:i,url:this.url,headers:this.headers,schema:this.schema,body:a,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){const r="PATCH",s=[],i=e;return t&&s.push(`count=${t}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new xt({method:r,url:this.url,headers:this.headers,schema:this.schema,body:i,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){const t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new xt({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}const po={"X-Client-Info":"postgrest-js/1.4.1"};class yo{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=Object.assign(Object.assign({},po),t),this.schema=r,this.fetch=s}from(e){const t=new URL(`${this.url}/${e}`);return new fo(t,{headers:Object.assign({},this.headers),schema:this.schema,fetch:this.fetch})}rpc(e,t={},{head:r=!1,count:s}={}){let i;const o=new URL(`${this.url}/rpc/${e}`);let a;r?(i="HEAD",Object.entries(t).forEach(([u,l])=>{o.searchParams.append(u,`${l}`)})):(i="POST",a=t);const c=Object.assign({},this.headers);return s&&(c.Prefer=`count=${s}`),new xt({method:i,url:o,headers:c,schema:this.schema,body:a,fetch:this.fetch,allowEmpty:!1})}}var Xr,rs;function mo(){if(rs)return Xr;rs=1;var n=function(){if(typeof self=="object"&&self)return self;if(typeof window=="object"&&window)return window;throw new Error("Unable to resolve global `this`")};return Xr=function(){if(this)return this;if(typeof globalThis=="object"&&globalThis)return globalThis;try{Object.defineProperty(Object.prototype,"__global__",{get:function(){return this},configurable:!0})}catch{return n()}try{return __global__||n()}finally{delete Object.prototype.__global__}}(),Xr}var go={name:"websocket",description:"Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.",keywords:["websocket","websockets","socket","networking","comet","push","RFC-6455","realtime","server","client"],author:"Brian McKelvey <theturtle32@gmail.com> (https://github.com/theturtle32)",contributors:["Iñaki Baz Castillo <ibc@aliax.net> (http://dev.sipdoc.net)"],version:"1.0.34",repository:{type:"git",url:"https://github.com/theturtle32/WebSocket-Node.git"},homepage:"https://github.com/theturtle32/WebSocket-Node",engines:{node:">=4.0.0"},dependencies:{bufferutil:"^4.0.1",debug:"^2.2.0","es5-ext":"^0.10.50","typedarray-to-buffer":"^3.1.5","utf-8-validate":"^5.0.2",yaeti:"^0.0.6"},devDependencies:{"buffer-equal":"^1.0.0",gulp:"^4.0.2","gulp-jshint":"^2.0.4","jshint-stylish":"^2.2.1",jshint:"^2.0.0",tape:"^4.9.1"},config:{verbose:!1},scripts:{test:"tape test/unit/*.js",gulp:"gulp"},main:"index",directories:{lib:"./lib"},browser:"lib/browser.js",license:"Apache-2.0"}.version,Qe;if(typeof globalThis=="object")Qe=globalThis;else try{Qe=mo()}catch{}finally{if(!Qe&&typeof window<"u"&&(Qe=window),!Qe)throw new Error("Could not determine global this")}var Ht=Qe.WebSocket||Qe.MozWebSocket,wo=go;function ns(n,e){var t;return e?t=new Ht(n,e):t=new Ht(n),t}Ht&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach(function(n){Object.defineProperty(ns,n,{get:function(){return Ht[n]}})});var bo={w3cwebsocket:Ht?ns:null,version:wo};const vo={"X-Client-Info":"realtime-js/2.6.0"},_o="1.0.0",ss=1e4,Eo=1e3;var Mt;(function(n){n[n.connecting=0]="connecting",n[n.open=1]="open",n[n.closing=2]="closing",n[n.closed=3]="closed"})(Mt||(Mt={}));var ae;(function(n){n.closed="closed",n.errored="errored",n.joined="joined",n.joining="joining",n.leaving="leaving"})(ae||(ae={}));var ye;(function(n){n.close="phx_close",n.error="phx_error",n.join="phx_join",n.reply="phx_reply",n.leave="phx_leave",n.access_token="access_token"})(ye||(ye={}));var Zr;(function(n){n.websocket="websocket"})(Zr||(Zr={}));var et;(function(n){n.Connecting="connecting",n.Open="open",n.Closing="closing",n.Closed="closed"})(et||(et={}));class is{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}class xo{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){const s=t.getUint8(1),i=t.getUint8(2);let o=this.HEADER_LENGTH+2;const a=r.decode(e.slice(o,o+s));o=o+s;const c=r.decode(e.slice(o,o+i));o=o+i;const u=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:u}}}class Yr{constructor(e,t,r={},s=ss){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null,this.rateLimited=!1}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){if(this._hasReceived("timeout"))return;this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()})==="rate limited"&&(this.rateLimited=!0)}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var os;(function(n){n.SYNC="sync",n.JOIN="join",n.LEAVE="leave"})(os||(os={}));class Vt{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(t==null?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},s=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Vt.syncState(this.state,s,i,o),this.pendingDiffs.forEach(c=>{this.state=Vt.syncDiff(this.state,c,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},s=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=Vt.syncDiff(this.state,s,i,o),a())}),this.onJoin((s,i,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:o})}),this.onLeave((s,i,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){const i=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(i,(u,l)=>{o[u]||(c[u]=l)}),this.map(o,(u,l)=>{const h=i[u];if(h){const y=l.map(g=>g.presence_ref),p=h.map(g=>g.presence_ref),w=l.filter(g=>p.indexOf(g.presence_ref)<0),v=h.filter(g=>y.indexOf(g.presence_ref)<0);w.length>0&&(a[u]=w),v.length>0&&(c[u]=v)}else a[u]=l}),this.syncDiff(i,{joins:a,leaves:c},r,s)}static syncDiff(e,t,r,s){const{joins:i,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(i,(a,c)=>{var u;const l=(u=e[a])!==null&&u!==void 0?u:[];if(e[a]=this.cloneDeep(c),l.length>0){const h=e[a].map(p=>p.presence_ref),y=l.filter(p=>h.indexOf(p.presence_ref)<0);e[a].unshift(...y)}r(a,l,c)}),this.map(o,(a,c)=>{let u=e[a];if(!u)return;const l=c.map(h=>h.presence_ref);u=u.filter(h=>l.indexOf(h.presence_ref)<0),e[a]=u,s(a,u,c),u.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const s=e[r];return"metas"in s?t[r]=s.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):t[r]=s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var D;(function(n){n.abstime="abstime",n.bool="bool",n.date="date",n.daterange="daterange",n.float4="float4",n.float8="float8",n.int2="int2",n.int4="int4",n.int4range="int4range",n.int8="int8",n.int8range="int8range",n.json="json",n.jsonb="jsonb",n.money="money",n.numeric="numeric",n.oid="oid",n.reltime="reltime",n.text="text",n.time="time",n.timestamp="timestamp",n.timestamptz="timestamptz",n.timetz="timetz",n.tsrange="tsrange",n.tstzrange="tstzrange"})(D||(D={}));const as=(n,e,t={})=>{var r;const s=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((i,o)=>(i[o]=To(o,n,e,s),i),{})},To=(n,e,t,r)=>{const s=e.find(a=>a.name===n),i=s==null?void 0:s.type,o=t[n];return i&&!r.includes(i)?cs(i,o):Qr(o)},cs=(n,e)=>{if(n.charAt(0)==="_"){const t=n.slice(1,n.length);return So(e,t)}switch(n){case D.bool:return Oo(e);case D.float4:case D.float8:case D.int2:case D.int4:case D.int8:case D.numeric:case D.oid:return ko(e);case D.json:case D.jsonb:return Ao(e);case D.timestamp:return Ro(e);case D.abstime:case D.date:case D.daterange:case D.int4range:case D.int8range:case D.money:case D.reltime:case D.text:case D.time:case D.timestamptz:case D.timetz:case D.tsrange:case D.tstzrange:return Qr(e);default:return Qr(e)}},Qr=n=>n,Oo=n=>{switch(n){case"t":return!0;case"f":return!1;default:return n}},ko=n=>{if(typeof n=="string"){const e=parseFloat(n);if(!Number.isNaN(e))return e}return n},Ao=n=>{if(typeof n=="string")try{return JSON.parse(n)}catch(e){return console.log(`JSON parse error: ${e}`),n}return n},So=(n,e)=>{if(typeof n!="string")return n;const t=n.length-1,r=n[t];if(n[0]==="{"&&r==="}"){let i;const o=n.slice(1,t);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>cs(e,a))}return n},Ro=n=>typeof n=="string"?n.replace(" ","T"):n;var us=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})},ls;(function(n){n.ALL="*",n.INSERT="INSERT",n.UPDATE="UPDATE",n.DELETE="DELETE"})(ls||(ls={}));var hs;(function(n){n.BROADCAST="broadcast",n.PRESENCE="presence",n.POSTGRES_CHANGES="postgres_changes"})(hs||(hs={}));var fs;(function(n){n.SUBSCRIBED="SUBSCRIBED",n.TIMED_OUT="TIMED_OUT",n.CLOSED="CLOSED",n.CHANNEL_ERROR="CHANNEL_ERROR"})(fs||(fs={}));class en{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=ae.closed,this.joinedOnce=!1,this.pushBuffer=[],this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""}},t.config),this.timeout=this.socket.timeout,this.joinPush=new Yr(this,ye.join,this.params,this.timeout),this.rejoinTimer=new is(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=ae.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=ae.closed,this.socket._remove(this)}),this._onError(s=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,s),this.state=ae.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=ae.errored,this.rejoinTimer.scheduleTimeout())}),this._on(ye.reply,{},(s,i)=>{this._trigger(this._replyEventName(i),s)}),this.presence=new Vt(this)}subscribe(e,t=this.timeout){var r,s;if(this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:i,presence:o}}=this.params;this._onError(u=>e&&e("CHANNEL_ERROR",u)),this._onClose(()=>e&&e("CLOSED"));const a={},c={broadcast:i,presence:o,postgres_changes:(s=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(u=>u.filter))!==null&&s!==void 0?s:[]};this.socket.accessToken&&(a.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:c},a)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:u})=>{var l;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),u===void 0){e&&e("SUBSCRIBED");return}else{const h=this.bindings.postgres_changes,y=(l=h==null?void 0:h.length)!==null&&l!==void 0?l:0,p=[];for(let w=0;w<y;w++){const v=h[w],{filter:{event:g,schema:S,table:U,filter:te}}=v,L=u&&u[w];if(L&&L.event===g&&L.schema===S&&L.table===U&&L.filter===te)p.push(Object.assign(Object.assign({},v),{id:L.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=p,e&&e("SUBSCRIBED");return}}).receive("error",u=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}track(e,t={}){return us(this,void 0,void 0,function*(){return yield this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)})}untrack(e={}){return us(this,void 0,void 0,function*(){return yield this.send({type:"presence",event:"untrack"},e)})}on(e,t,r){return this._on(e,t,r)}send(e,t={}){return new Promise(r=>{var s,i,o;const a=this._push(e.type,e,t.timeout||this.timeout);a.rateLimited&&r("rate limited"),e.type==="broadcast"&&!(!((o=(i=(s=this.params)===null||s===void 0?void 0:s.config)===null||i===void 0?void 0:i.broadcast)===null||o===void 0)&&o.ack)&&r("ok"),a.receive("ok",()=>r("ok")),a.receive("timeout",()=>r("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=ae.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(ye.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{const s=new Yr(this,ye.leave,{},e);s.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),s.send(),this._canPush()||s.trigger("ok",{})})}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new Yr(this,e,t,r);return this._canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,i;const o=e.toLocaleLowerCase(),{close:a,error:c,leave:u,join:l}=ye;if(r&&[a,c,u,l].indexOf(o)>=0&&r!==this._joinRef())return;let y=this._onMessage(o,t,r);if(t&&!y)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(p=>{var w,v,g;return((w=p.filter)===null||w===void 0?void 0:w.event)==="*"||((g=(v=p.filter)===null||v===void 0?void 0:v.event)===null||g===void 0?void 0:g.toLocaleLowerCase())===o}).map(p=>p.callback(y,r)):(i=this.bindings[o])===null||i===void 0||i.filter(p=>{var w,v,g,S,U,te;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){const L=p.id,Re=(w=p.filter)===null||w===void 0?void 0:w.event;return L&&((v=t.ids)===null||v===void 0?void 0:v.includes(L))&&(Re==="*"||(Re==null?void 0:Re.toLocaleLowerCase())===((g=t.data)===null||g===void 0?void 0:g.type.toLocaleLowerCase()))}else{const L=(U=(S=p==null?void 0:p.filter)===null||S===void 0?void 0:S.event)===null||U===void 0?void 0:U.toLocaleLowerCase();return L==="*"||L===((te=t==null?void 0:t.event)===null||te===void 0?void 0:te.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof y=="object"&&"ids"in y){const w=y.data,{schema:v,table:g,commit_timestamp:S,type:U,errors:te}=w;y=Object.assign(Object.assign({},{schema:v,table:g,commit_timestamp:S,eventType:U,new:{},old:{},errors:te}),this._getPayloadRecords(w))}p.callback(y,r)})}_isClosed(){return this.state===ae.closed}_isJoined(){return this.state===ae.joined}_isJoining(){return this.state===ae.joining}_isLeaving(){return this.state===ae.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const s=e.toLocaleLowerCase(),i={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(s=>{var i;return!(((i=s.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===r&&en.isEqual(s.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(ye.close,{},e)}_onError(e){this._on(ye.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=ae.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=as(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=as(e.columns,e.old_record)),t}}var $o=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})};const Po=()=>{};class No{constructor(e,t){var r;this.accessToken=null,this.channels=[],this.endPoint="",this.headers=vo,this.params={},this.timeout=ss,this.transport=bo.w3cwebsocket,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Po,this.conn=null,this.sendBuffer=[],this.serializer=new xo,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.eventsPerSecondLimitMs=100,this.inThrottle=!1,this.endPoint=`${e}/${Zr.websocket}`,t!=null&&t.params&&(this.params=t.params),t!=null&&t.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t!=null&&t.timeout&&(this.timeout=t.timeout),t!=null&&t.logger&&(this.logger=t.logger),t!=null&&t.transport&&(this.transport=t.transport),t!=null&&t.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);const s=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.eventsPerSecond;s&&(this.eventsPerSecondLimitMs=Math.floor(1e3/s)),this.reconnectAfterMs=t!=null&&t.reconnectAfterMs?t.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=t!=null&&t.encode?t.encode:(i,o)=>o(JSON.stringify(i)),this.decode=t!=null&&t.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new is(()=>$o(this,void 0,void 0,function*(){this.disconnect(),this.connect()}),this.reconnectAfterMs)}connect(){this.conn||(this.conn=new this.transport(this._endPointURL(),[],null,this.headers),this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e)))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}removeChannel(e){return e.unsubscribe().then(t=>(this.channels.length===0&&this.disconnect(),t))}removeAllChannels(){return Promise.all(this.channels.map(e=>e.unsubscribe())).then(e=>(this.disconnect(),e))}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case Mt.connecting:return et.Connecting;case Mt.open:return et.Open;case Mt.closing:return et.Closing;default:return et.Closed}}isConnected(){return this.connectionState()===et.Open}channel(e,t={config:{}}){this.isConnected()||this.connect();const r=new en(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){const{topic:t,event:r,payload:s,ref:i}=e;let o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};if(this.log("push",`${t} ${r} (${i})`,s),this.isConnected())if(["broadcast","presence","postgres_changes"].includes(r)){if(this._throttle(o)())return"rate limited"}else o();else this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(ye.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:_o}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:s,payload:i,ref:o}=t;(o&&o===this.pendingHeartbeatRef||s===(i==null?void 0:i.type))&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${r} ${s} ${o&&"("+o+")"||""}`,i),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(s,i,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(ye.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const r=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${r}${s}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Eo,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}_throttle(e,t=this.eventsPerSecondLimitMs){return()=>this.inThrottle?!0:(e(),t>0&&(this.inThrottle=!0,setTimeout(()=>{this.inThrottle=!1},t)),!1)}}class ds extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function re(n){return typeof n=="object"&&n!==null&&"__isStorageError"in n}class Io extends ds{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class ps extends ds{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var ys=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})};const ms=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>ys(void 0,void 0,void 0,function*(){return yield(yield Promise.resolve().then(()=>cr)).fetch(...t)}):e=fetch,(...t)=>e(...t)},Co=()=>ys(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>cr)).Response:Response});var Tt=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})};const tn=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),Fo=(n,e)=>Tt(void 0,void 0,void 0,function*(){const t=yield Co();n instanceof t?n.json().then(r=>{e(new Io(tn(r),n.status||500))}).catch(r=>{e(new ps(tn(r),r))}):e(new ps(tn(n),n))}),Do=(n,e,t,r)=>{const s={method:n,headers:(e==null?void 0:e.headers)||{}};return n==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};function ur(n,e,t,r,s,i){return Tt(this,void 0,void 0,function*(){return new Promise((o,a)=>{n(t,Do(e,r,s,i)).then(c=>{if(!c.ok)throw c;return r!=null&&r.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>Fo(c,a))})})}function rn(n,e,t,r){return Tt(this,void 0,void 0,function*(){return ur(n,"GET",e,t,r)})}function tt(n,e,t,r,s){return Tt(this,void 0,void 0,function*(){return ur(n,"POST",e,r,s,t)})}function Uo(n,e,t,r,s){return Tt(this,void 0,void 0,function*(){return ur(n,"PUT",e,r,s,t)})}function gs(n,e,t,r,s){return Tt(this,void 0,void 0,function*(){return ur(n,"DELETE",e,r,s,t)})}var Ee=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})};const jo={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Lo={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Bo{constructor(e,t={},r,s){this.url=e,this.headers=t,this.bucketId=r,this.fetch=ms(s)}uploadOrUpdate(e,t,r,s){return Ee(this,void 0,void 0,function*(){try{let i;const o=Object.assign(Object.assign({},Lo),s),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.append("cacheControl",o.cacheControl)):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);const c=this._removeEmptyFolders(t),u=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${u}`,{method:e,body:i,headers:a});return l.ok?{data:{path:c},error:null}:{data:null,error:yield l.json()}}catch(i){if(re(i))return{data:null,error:i};throw i}})}upload(e,t,r){return Ee(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}update(e,t,r){return Ee(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t){return Ee(this,void 0,void 0,function*(){try{return{data:yield tt(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers}),error:null}}catch(r){if(re(r))return{data:null,error:r};throw r}})}copy(e,t){return Ee(this,void 0,void 0,function*(){try{return{data:{path:(yield tt(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers})).Key},error:null}}catch(r){if(re(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,r){return Ee(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=yield tt(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(s){if(re(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,r){return Ee(this,void 0,void 0,function*(){try{const s=yield tt(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{data:s.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${i}`):null})),error:null}}catch(s){if(re(s))return{data:null,error:s};throw s}})}download(e,t){return Ee(this,void 0,void 0,function*(){const s=typeof(t==null?void 0:t.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),o=i?`?${i}`:"";try{const a=this._getFinalPath(e);return{data:yield(yield rn(this.fetch,`${this.url}/${s}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(re(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){const r=this._getFinalPath(e),s=[],i=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&s.push(i);const a=typeof(t==null?void 0:t.transform)<"u"?"render/image":"object",c=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});c!==""&&s.push(c);let u=s.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${u}`)}}}remove(e){return Ee(this,void 0,void 0,function*(){try{return{data:yield gs(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(re(t))return{data:null,error:t};throw t}})}list(e,t,r){return Ee(this,void 0,void 0,function*(){try{const s=Object.assign(Object.assign(Object.assign({},jo),t),{prefix:e||""});return{data:yield tt(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(s){if(re(s))return{data:null,error:s};throw s}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const Ho={"X-Client-Info":"storage-js/2.3.1"};var Ot=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})};class Mo{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Ho),t),this.fetch=ms(r)}listBuckets(){return Ot(this,void 0,void 0,function*(){try{return{data:yield rn(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(re(e))return{data:null,error:e};throw e}})}getBucket(e){return Ot(this,void 0,void 0,function*(){try{return{data:yield rn(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(re(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Ot(this,void 0,void 0,function*(){try{return{data:yield tt(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public},{headers:this.headers}),error:null}}catch(r){if(re(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Ot(this,void 0,void 0,function*(){try{return{data:yield Uo(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public},{headers:this.headers}),error:null}}catch(r){if(re(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Ot(this,void 0,void 0,function*(){try{return{data:yield tt(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(re(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Ot(this,void 0,void 0,function*(){try{return{data:yield gs(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(re(t))return{data:null,error:t};throw t}})}}class Vo extends Mo{constructor(e,t={},r){super(e,t,r)}from(e){return new Bo(this.url,this.headers,e,this.fetch)}}const zo={"X-Client-Info":"supabase-js/2.10.0"};var qo=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})};const Go=n=>{let e;return n?e=n:typeof fetch>"u"?e=Kr:e=fetch,(...t)=>e(...t)},Jo=()=>typeof Headers>"u"?Et.Headers:Headers,Wo=(n,e,t)=>{const r=Go(t),s=Jo();return(i,o)=>qo(void 0,void 0,void 0,function*(){var a;const c=(a=yield e())!==null&&a!==void 0?a:n;let u=new s(o==null?void 0:o.headers);return u.has("apikey")||u.set("apikey",n),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),r(i,Object.assign(Object.assign({},o),{headers:u}))})};function Ko(n){return n.replace(/\/$/,"")}function Xo(n,e){const{db:t,auth:r,realtime:s,global:i}=n,{db:o,auth:a,realtime:c,global:u}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},c),s),global:Object.assign(Object.assign({},u),i)}}var zt=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})};function Zo(n){return Math.round(Date.now()/1e3)+n}function Yo(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){const e=Math.random()*16|0;return(n=="x"?e:e&3|8).toString(16)})}const rt=()=>typeof document<"u",nt={tested:!1,writable:!1},nn=()=>{if(!rt())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(nt.tested)return nt.writable;const n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),nt.tested=!0,nt.writable=!0}catch{nt.tested=!0,nt.writable=!1}return nt.writable};function le(n,e){var t;e||(e=((t=window==null?void 0:window.location)===null||t===void 0?void 0:t.href)||""),n=n.replace(/[\[\]]/g,"\\$&");const r=new RegExp("[?&#]"+n+"(=([^&#]*)|&|#|$)"),s=r.exec(e);return s?s[2]?decodeURIComponent(s[2].replace(/\+/g," ")):"":null}const ws=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>zt(void 0,void 0,void 0,function*(){return yield(yield Promise.resolve().then(()=>cr)).fetch(...t)}):e=fetch,(...t)=>e(...t)},Qo=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",ea=(n,e,t)=>zt(void 0,void 0,void 0,function*(){yield n.setItem(e,JSON.stringify(t))}),bs=(n,e)=>zt(void 0,void 0,void 0,function*(){const t=yield n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}}),ta=(n,e)=>zt(void 0,void 0,void 0,function*(){yield n.removeItem(e)});function ra(n){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",r,s,i,o,a,c,u,l=0;for(n=n.replace("-","+").replace("_","/");l<n.length;)o=e.indexOf(n.charAt(l++)),a=e.indexOf(n.charAt(l++)),c=e.indexOf(n.charAt(l++)),u=e.indexOf(n.charAt(l++)),r=o<<2|a>>4,s=(a&15)<<4|c>>2,i=(c&3)<<6|u,t=t+String.fromCharCode(r),c!=64&&s!=0&&(t=t+String.fromCharCode(s)),u!=64&&i!=0&&(t=t+String.fromCharCode(i));return t}class lr{constructor(){this.promise=new lr.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}lr.promiseConstructor=Promise;function vs(n){const e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=n.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");const r=t[1];return JSON.parse(ra(r))}function na(n){return new Promise(e=>{setTimeout(()=>e(null),n)})}function sa(n,e){return new Promise((r,s)=>{zt(this,void 0,void 0,function*(){for(let i=0;i<1/0;i++)try{const o=yield n(i);if(!e(i,null,o)){r(o);return}}catch(o){if(!e(i,o)){s(o);return}}})})}class sn extends Error{constructor(e,t){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t}}function P(n){return typeof n=="object"&&n!==null&&"__isAuthError"in n}class ia extends sn{constructor(e,t){super(e,t),this.name="AuthApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}function oa(n){return P(n)&&n.name==="AuthApiError"}class _s extends sn{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class hr extends sn{constructor(e,t,r){super(e),this.name=t,this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class qt extends hr{constructor(){super("Auth session missing!","AuthSessionMissingError",400)}}class on extends hr{constructor(e){super(e,"AuthInvalidCredentialsError",400)}}class $e extends hr{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class an extends hr{constructor(e,t){super(e,"AuthRetryableFetchError",t)}}var cn=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})},aa=globalThis&&globalThis.__rest||function(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(n);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(n,r[s])&&(t[r[s]]=n[r[s]]);return t};const fr=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),ca=(n,e)=>cn(void 0,void 0,void 0,function*(){const t=[502,503,504];Qo(n)?t.includes(n.status)?e(new an(fr(n),n.status)):n.json().then(r=>{e(new ia(fr(r),n.status||500))}).catch(r=>{e(new _s(fr(r),r))}):e(new an(fr(n),0))}),ua=(n,e,t,r)=>{const s={method:n,headers:(e==null?void 0:e.headers)||{}};return n==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};function C(n,e,t,r){var s;return cn(this,void 0,void 0,function*(){const i=Object.assign({},r==null?void 0:r.headers);r!=null&&r.jwt&&(i.Authorization=`Bearer ${r.jwt}`);const o=(s=r==null?void 0:r.query)!==null&&s!==void 0?s:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=yield la(n,e,t+a,{headers:i,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(c):{data:Object.assign({},c),error:null}})}function la(n,e,t,r,s,i){return cn(this,void 0,void 0,function*(){return new Promise((o,a)=>{n(t,ua(e,r,s,i)).then(c=>{if(!c.ok)throw c;return r!=null&&r.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>ca(c,a))})})}function st(n){var e;let t=null;pa(n)&&(t=Object.assign({},n),t.expires_at=Zo(n.expires_in));const r=(e=n.user)!==null&&e!==void 0?e:n;return{data:{session:t,user:r},error:null}}function it(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function ha(n){return{data:n,error:null}}function fa(n){const{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i}=n,o=aa(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:i},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function da(n){return n}function pa(n){return n.access_token&&n.refresh_token&&n.expires_in}var xe=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})},ya=globalThis&&globalThis.__rest||function(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(n);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(n,r[s])&&(t[r[s]]=n[r[s]]);return t};class ma{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=ws(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}signOut(e){return xe(this,void 0,void 0,function*(){try{return yield C(this.fetch,"POST",`${this.url}/logout`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}inviteUserByEmail(e,t={}){return xe(this,void 0,void 0,function*(){try{return yield C(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:it})}catch(r){if(P(r))return{data:{user:null},error:r};throw r}})}generateLink(e){return xe(this,void 0,void 0,function*(){try{const{options:t}=e,r=ya(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r==null?void 0:r.newEmail,delete s.newEmail),yield C(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:fa,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(P(t))return{data:{properties:null,user:null},error:t};throw t}})}createUser(e){return xe(this,void 0,void 0,function*(){try{return yield C(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:it})}catch(t){if(P(t))return{data:{user:null},error:t};throw t}})}listUsers(e){var t,r,s,i,o,a,c;return xe(this,void 0,void 0,function*(){try{const u={nextPage:null,lastPage:0,total:0},l=yield C(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=e==null?void 0:e.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:da});if(l.error)throw l.error;const h=yield l.json(),y=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(w=>{const v=parseInt(w.split(";")[0].split("=")[1].substring(0,1)),g=JSON.parse(w.split(";")[1].split("=")[1]);u[`${g}Page`]=v}),u.total=parseInt(y)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(P(u))return{data:{users:[]},error:u};throw u}})}getUserById(e){return xe(this,void 0,void 0,function*(){try{return yield C(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:it})}catch(t){if(P(t))return{data:{user:null},error:t};throw t}})}updateUserById(e,t){return xe(this,void 0,void 0,function*(){try{return yield C(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:it})}catch(r){if(P(r))return{data:{user:null},error:r};throw r}})}deleteUser(e,t=!1){return xe(this,void 0,void 0,function*(){try{return yield C(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:it})}catch(r){if(P(r))return{data:{user:null},error:r};throw r}})}_listFactors(e){return xe(this,void 0,void 0,function*(){try{const{data:t,error:r}=yield C(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:r}}catch(t){if(P(t))return{data:null,error:t};throw t}})}_deleteFactor(e){return xe(this,void 0,void 0,function*(){try{return{data:yield C(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}}const ga="2.13.0",wa="http://localhost:9999",ba="supabase.auth.token",va={"X-Client-Info":`gotrue-js/${ga}`},_a=10,Ea={getItem:n=>nn()?globalThis.localStorage.getItem(n):null,setItem:(n,e)=>{nn()&&globalThis.localStorage.setItem(n,e)},removeItem:n=>{nn()&&globalThis.localStorage.removeItem(n)}};function xa(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var k=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})};xa();const Ta={url:wa,storageKey:ba,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:va},un=10*1e3,Oa=3;class ka{constructor(e){this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.broadcastChannel=null;const t=Object.assign(Object.assign({},Ta),e);this.inMemorySession=null,this.storageKey=t.storageKey,this.autoRefreshToken=t.autoRefreshToken,this.persistSession=t.persistSession,this.storage=t.storage||Ea,this.admin=new ma({url:t.url,headers:t.headers,fetch:t.fetch}),this.url=t.url,this.headers=t.headers,this.fetch=ws(t.fetch),this.detectSessionInUrl=t.detectSessionInUrl,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},rt()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey&&(this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey),this.broadcastChannel.addEventListener("message",r=>{this._notifyAllSubscribers(r.data.event,r.data.session,!1)})),this.initialize()}initialize(){return this.initializePromise||(this.initializePromise=this._initialize()),this.initializePromise}_initialize(){return k(this,void 0,void 0,function*(){if(this.initializePromise)return this.initializePromise;try{if(this.detectSessionInUrl&&this._isImplicitGrantFlow()){const{data:e,error:t}=yield this._getSessionFromUrl();if(t)return yield this._removeSession(),{error:t};const{session:r,redirectType:s}=e;return yield this._saveSession(r),setTimeout(()=>{this._notifyAllSubscribers("SIGNED_IN",r),s==="recovery"&&this._notifyAllSubscribers("PASSWORD_RECOVERY",r)},0),{error:null}}return yield this._recoverAndRefresh(),{error:null}}catch(e){return P(e)?{error:e}:{error:new _s("Unexpected error during initialization",e)}}finally{yield this._handleVisibilityChange()}})}signUp(e){var t,r;return k(this,void 0,void 0,function*(){try{yield this._removeSession();let s;if("email"in e){const{email:u,password:l,options:h}=e;s=yield C(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h==null?void 0:h.emailRedirectTo,body:{email:u,password:l,data:(t=h==null?void 0:h.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken}},xform:st})}else if("phone"in e){const{phone:u,password:l,options:h}=e;s=yield C(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:l,data:(r=h==null?void 0:h.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken}},xform:st})}else throw new on("You must provide either an email or phone number and a password");const{data:i,error:o}=s;if(o||!i)return{data:{user:null,session:null},error:o};const a=i.session,c=i.user;return i.session&&(yield this._saveSession(i.session),this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:c,session:a},error:null}}catch(s){if(P(s))return{data:{user:null,session:null},error:s};throw s}})}signInWithPassword(e){var t;return k(this,void 0,void 0,function*(){try{yield this._removeSession();let r;if("email"in e){const{email:o,password:a,options:c}=e;r=yield C(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:o,password:a,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken}},xform:st})}else if("phone"in e){const{phone:o,password:a,options:c}=e;r=yield C(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:o,password:a,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(t=c==null?void 0:c.channel)!==null&&t!==void 0?t:"sms"},xform:st})}else throw new on("You must provide either an email or phone number and a password");const{data:s,error:i}=r;return i||!s?{data:{user:null,session:null},error:i}:(s.session&&(yield this._saveSession(s.session),this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:s,error:i})}catch(r){if(P(r))return{data:{user:null,session:null},error:r};throw r}})}signInWithOAuth(e){var t,r,s,i;return k(this,void 0,void 0,function*(){return yield this._removeSession(),this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})})}signInWithIdToken(e){return k(this,void 0,void 0,function*(){yield this._removeSession();try{const{options:t,provider:r,token:s,nonce:i}=e,o=yield C(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,nonce:i,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:st}),{data:a,error:c}=o;return c||!a?{data:{user:null,session:null},error:c}:(a.session&&(yield this._saveSession(a.session),this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:c})}catch(t){if(P(t))return{data:{user:null,session:null},error:t};throw t}})}signInWithOtp(e){var t,r,s,i,o;return k(this,void 0,void 0,function*(){try{if(yield this._removeSession(),"email"in e){const{email:a,options:c}=e,{error:u}=yield C(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c==null?void 0:c.data)!==null&&t!==void 0?t:{},create_user:(r=c==null?void 0:c.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken}},redirectTo:c==null?void 0:c.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){const{phone:a,options:c}=e,{error:u}=yield C(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=c==null?void 0:c.data)!==null&&s!==void 0?s:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(o=c==null?void 0:c.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null},error:u}}throw new on("You must provide either an email or phone number.")}catch(a){if(P(a))return{data:{user:null,session:null},error:a};throw a}})}verifyOtp(e){var t,r;return k(this,void 0,void 0,function*(){try{yield this._removeSession();const{data:s,error:i}=yield C(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:(t=e.options)===null||t===void 0?void 0:t.captchaToken}}),redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,xform:st});if(i)throw i;if(!s)throw"An error occurred on token verification.";const o=s.session,a=s.user;return o!=null&&o.access_token&&(yield this._saveSession(o),this._notifyAllSubscribers("SIGNED_IN",o)),{data:{user:a,session:o},error:null}}catch(s){if(P(s))return{data:{user:null,session:null},error:s};throw s}})}signInWithSSO(e){var t,r,s;return k(this,void 0,void 0,function*(){try{return yield this._removeSession(),yield C(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((s=e==null?void 0:e.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0}),headers:this.headers,xform:ha})}catch(i){if(P(i))return{data:null,error:i};throw i}})}getSession(){return k(this,void 0,void 0,function*(){yield this.initializePromise;let e=null;if(this.persistSession){const i=yield bs(this.storage,this.storageKey);i!==null&&(this._isValidSession(i)?e=i:yield this._removeSession())}else e=this.inMemorySession;if(!e)return{data:{session:null},error:null};if(!(e.expires_at?e.expires_at<=Date.now()/1e3:!1))return{data:{session:e},error:null};const{session:r,error:s}=yield this._callRefreshToken(e.refresh_token);return s?{data:{session:null},error:s}:{data:{session:r},error:null}})}getUser(e){var t,r;return k(this,void 0,void 0,function*(){try{if(!e){const{data:s,error:i}=yield this.getSession();if(i)throw i;e=(r=(t=s.session)===null||t===void 0?void 0:t.access_token)!==null&&r!==void 0?r:void 0}return yield C(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:it})}catch(s){if(P(s))return{data:{user:null},error:s};throw s}})}updateUser(e,t={}){return k(this,void 0,void 0,function*(){try{const{data:r,error:s}=yield this.getSession();if(s)throw s;if(!r.session)throw new qt;const i=r.session,{data:o,error:a}=yield C(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:e,jwt:i.access_token,xform:it});if(a)throw a;return i.user=o.user,yield this._saveSession(i),this._notifyAllSubscribers("USER_UPDATED",i),{data:{user:i.user},error:null}}catch(r){if(P(r))return{data:{user:null},error:r};throw r}})}_decodeJWT(e){return vs(e)}setSession(e){return k(this,void 0,void 0,function*(){try{if(!e.access_token||!e.refresh_token)throw new qt;const t=Date.now()/1e3;let r=t,s=!0,i=null;const o=vs(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){const{session:a,error:c}=yield this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};i=a}else{const{data:a,error:c}=yield this.getUser(e.access_token);if(c)throw c;i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},yield this._saveSession(i),this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(t){if(P(t))return{data:{session:null,user:null},error:t};throw t}})}refreshSession(e){var t;return k(this,void 0,void 0,function*(){try{if(!e){const{data:i,error:o}=yield this.getSession();if(o)throw o;e=(t=i.session)!==null&&t!==void 0?t:void 0}if(!(e!=null&&e.refresh_token))throw new qt;const{session:r,error:s}=yield this._callRefreshToken(e.refresh_token);return s?{data:{user:null,session:null},error:s}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}}catch(r){if(P(r))return{data:{user:null,session:null},error:r};throw r}})}_getSessionFromUrl(){return k(this,void 0,void 0,function*(){try{if(!rt())throw new $e("No browser detected.");if(!this._isImplicitGrantFlow())throw new $e("Not a valid implicit grant flow url.");const e=le("error_description");if(e){const v=le("error_code");if(!v)throw new $e("No error_code detected.");const g=le("error");throw g?new $e(e,{error:g,code:v}):new $e("No error detected.")}const t=le("provider_token"),r=le("provider_refresh_token"),s=le("access_token");if(!s)throw new $e("No access_token detected.");const i=le("expires_in");if(!i)throw new $e("No expires_in detected.");const o=le("refresh_token");if(!o)throw new $e("No refresh_token detected.");const a=le("token_type");if(!a)throw new $e("No token_type detected.");const u=Math.round(Date.now()/1e3)+parseInt(i),{data:l,error:h}=yield this.getUser(s);if(h)throw h;const y=l.user,p={provider_token:t,provider_refresh_token:r,access_token:s,expires_in:parseInt(i),expires_at:u,refresh_token:o,token_type:a,user:y},w=le("type");return window.location.hash="",{data:{session:p,redirectType:w},error:null}}catch(e){if(P(e))return{data:{session:null,redirectType:null},error:e};throw e}})}_isImplicitGrantFlow(){return rt()&&(Boolean(le("access_token"))||Boolean(le("error_description")))}signOut(){var e;return k(this,void 0,void 0,function*(){const{data:t,error:r}=yield this.getSession();if(r)return{error:r};const s=(e=t.session)===null||e===void 0?void 0:e.access_token;if(s){const{error:i}=yield this.admin.signOut(s);if(i&&!(oa(i)&&(i.status===404||i.status===401)))return{error:i}}return yield this._removeSession(),this._notifyAllSubscribers("SIGNED_OUT",null),{error:null}})}onAuthStateChange(e){const t=Yo(),r={id:t,callback:e,unsubscribe:()=>{this.stateChangeEmitters.delete(t)}};return this.stateChangeEmitters.set(t,r),{data:{subscription:r}}}resetPasswordForEmail(e,t={}){return k(this,void 0,void 0,function*(){try{return yield C(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(r){if(P(r))return{data:null,error:r};throw r}})}_refreshAccessToken(e){return k(this,void 0,void 0,function*(){try{const t=Date.now();return yield sa(r=>k(this,void 0,void 0,function*(){return yield na(r*200),yield C(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:st})}),(r,s,i)=>i&&i.error&&i.error instanceof an&&Date.now()+(r+1)*200-t<un)}catch(t){if(P(t))return{data:{session:null,user:null},error:t};throw t}})}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}_handleProviderSignIn(e,t={}){const r=this._getUrlForProvider(e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return rt()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}_recoverAndRefresh(){var e;return k(this,void 0,void 0,function*(){try{const t=yield bs(this.storage,this.storageKey);if(!this._isValidSession(t)){t!==null&&(yield this._removeSession());return}const r=Math.round(Date.now()/1e3);if(((e=t.expires_at)!==null&&e!==void 0?e:1/0)<r+_a)if(this.autoRefreshToken&&t.refresh_token){const{error:s}=yield this._callRefreshToken(t.refresh_token);s&&(console.log(s.message),yield this._removeSession())}else yield this._removeSession();else this.persistSession&&(yield this._saveSession(t)),this._notifyAllSubscribers("SIGNED_IN",t)}catch(t){console.error(t);return}})}_callRefreshToken(e){var t,r;return k(this,void 0,void 0,function*(){if(this.refreshingDeferred)return this.refreshingDeferred.promise;try{if(this.refreshingDeferred=new lr,!e)throw new qt;const{data:s,error:i}=yield this._refreshAccessToken(e);if(i)throw i;if(!s.session)throw new qt;yield this._saveSession(s.session),this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);const o={session:s.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(s){if(P(s)){const i={session:null,error:s};return(t=this.refreshingDeferred)===null||t===void 0||t.resolve(i),i}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(s),s}finally{this.refreshingDeferred=null}})}_notifyAllSubscribers(e,t,r=!0){this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t}),this.stateChangeEmitters.forEach(s=>s.callback(e,t))}_saveSession(e){return k(this,void 0,void 0,function*(){this.persistSession||(this.inMemorySession=e),this.persistSession&&e.expires_at&&(yield this._persistSession(e))})}_persistSession(e){return ea(this.storage,this.storageKey,e)}_removeSession(){return k(this,void 0,void 0,function*(){this.persistSession?yield ta(this.storage,this.storageKey):this.inMemorySession=null})}_removeVisibilityChangedCallback(){const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&rt()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}_startAutoRefresh(){return k(this,void 0,void 0,function*(){yield this._stopAutoRefresh();const e=setInterval(()=>this._autoRefreshTokenTick(),un);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"&&e.unref(),yield this._autoRefreshTokenTick()})}_stopAutoRefresh(){return k(this,void 0,void 0,function*(){const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)})}startAutoRefresh(){return k(this,void 0,void 0,function*(){this._removeVisibilityChangedCallback(),yield this._startAutoRefresh()})}stopAutoRefresh(){return k(this,void 0,void 0,function*(){this._removeVisibilityChangedCallback(),yield this._stopAutoRefresh()})}_autoRefreshTokenTick(){return k(this,void 0,void 0,function*(){const e=Date.now();try{const{data:{session:t}}=yield this.getSession();if(!t||!t.refresh_token||!t.expires_at)return;Math.floor((t.expires_at*1e3-e)/un)<Oa&&(yield this._callRefreshToken(t.refresh_token))}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}})}_handleVisibilityChange(){return k(this,void 0,void 0,function*(){if(!rt()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=()=>k(this,void 0,void 0,function*(){return yield this._onVisibilityChanged(!1)}),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),yield this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}})}_onVisibilityChanged(e){return k(this,void 0,void 0,function*(){document.visibilityState==="visible"?(e||(yield this.initializePromise,yield this._recoverAndRefresh()),this.autoRefreshToken&&this._startAutoRefresh()):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()})}_getUrlForProvider(e,t){const r=[`provider=${encodeURIComponent(e)}`];if(t!=null&&t.redirectTo&&r.push(`redirect_to=${encodeURIComponent(t.redirectTo)}`),t!=null&&t.scopes&&r.push(`scopes=${encodeURIComponent(t.scopes)}`),t!=null&&t.queryParams){const s=new URLSearchParams(t.queryParams);r.push(s.toString())}return`${this.url}/authorize?${r.join("&")}`}_unenroll(e){var t;return k(this,void 0,void 0,function*(){try{const{data:r,error:s}=yield this.getSession();return s?{data:null,error:s}:yield C(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(t=r==null?void 0:r.session)===null||t===void 0?void 0:t.access_token})}catch(r){if(P(r))return{data:null,error:r};throw r}})}_enroll(e){var t,r;return k(this,void 0,void 0,function*(){try{const{data:s,error:i}=yield this.getSession();if(i)return{data:null,error:i};const{data:o,error:a}=yield C(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(t=s==null?void 0:s.session)===null||t===void 0?void 0:t.access_token});return a?{data:null,error:a}:(!((r=o==null?void 0:o.totp)===null||r===void 0)&&r.qr_code&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),{data:o,error:null})}catch(s){if(P(s))return{data:null,error:s};throw s}})}_verify(e){var t;return k(this,void 0,void 0,function*(){try{const{data:r,error:s}=yield this.getSession();if(s)return{data:null,error:s};const{data:i,error:o}=yield C(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(t=r==null?void 0:r.session)===null||t===void 0?void 0:t.access_token});return o?{data:null,error:o}:(yield this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+i.expires_in},i)),this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",i),{data:i,error:o})}catch(r){if(P(r))return{data:null,error:r};throw r}})}_challenge(e){var t;return k(this,void 0,void 0,function*(){try{const{data:r,error:s}=yield this.getSession();return s?{data:null,error:s}:yield C(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(t=r==null?void 0:r.session)===null||t===void 0?void 0:t.access_token})}catch(r){if(P(r))return{data:null,error:r};throw r}})}_challengeAndVerify(e){return k(this,void 0,void 0,function*(){const{data:t,error:r}=yield this._challenge({factorId:e.factorId});return r?{data:null,error:r}:yield this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})})}_listFactors(){return k(this,void 0,void 0,function*(){const{data:{user:e},error:t}=yield this.getUser();if(t)return{data:null,error:t};const r=(e==null?void 0:e.factors)||[],s=r.filter(i=>i.factor_type==="totp"&&i.status==="verified");return{data:{all:r,totp:s},error:null}})}_getAuthenticatorAssuranceLevel(){var e,t;return k(this,void 0,void 0,function*(){const{data:{session:r},error:s}=yield this.getSession();if(s)return{data:null,error:s};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const i=this._decodeJWT(r.access_token);let o=null;i.aal&&(o=i.aal);let a=o;((t=(e=r.user.factors)===null||e===void 0?void 0:e.filter(l=>l.status==="verified"))!==null&&t!==void 0?t:[]).length>0&&(a="aal2");const u=i.amr||[];return{data:{currentLevel:o,nextLevel:a,currentAuthenticationMethods:u},error:null}})}}class Aa extends ka{constructor(e){super(e)}}var Sa=globalThis&&globalThis.__awaiter||function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?i(l.value):s(l.value).then(a,c)}u((r=r.apply(n,e||[])).next())})};const Ra={headers:zo},$a={schema:"public"},Pa={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0},Na={};class Ia{constructor(e,t,r){var s,i,o,a,c,u,l,h;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");const y=Ko(e);if(this.realtimeUrl=`${y}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${y}/auth/v1`,this.storageUrl=`${y}/storage/v1`,y.match(/(supabase\.co)|(supabase\.in)/)){const S=y.split(".");this.functionsUrl=`${S[0]}.functions.${S[1]}.${S[2]}`}else this.functionsUrl=`${y}/functions/v1`;const w=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,v={db:$a,realtime:Na,auth:Object.assign(Object.assign({},Pa),{storageKey:w}),global:Ra},g=Xo(r??{},v);this.storageKey=(i=(s=g.auth)===null||s===void 0?void 0:s.storageKey)!==null&&i!==void 0?i:"",this.headers=(a=(o=g.global)===null||o===void 0?void 0:o.headers)!==null&&a!==void 0?a:{},this.auth=this._initSupabaseAuthClient((c=g.auth)!==null&&c!==void 0?c:{},this.headers,(u=g.global)===null||u===void 0?void 0:u.fetch),this.fetch=Wo(t,this._getAccessToken.bind(this),(l=g.global)===null||l===void 0?void 0:l.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},g.realtime)),this.rest=new yo(`${y}/rest/v1`,{headers:this.headers,schema:(h=g.db)===null||h===void 0?void 0:h.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new oo(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Vo(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}rpc(e,t={},r){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Sa(this,void 0,void 0,function*(){const{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,storageKey:i},o,a){const c={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Aa({url:this.authUrl,headers:Object.assign(Object.assign({},c),o),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,fetch:a})}_initRealtimeClient(e){return new No(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,r==null?void 0:r.access_token,"CLIENT")})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==t?(this.realtime.setAuth(t??null),this.changedAccessToken=t):(e==="SIGNED_OUT"||e==="USER_DELETED")&&(this.realtime.setAuth(this.supabaseKey),r=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Ca=(n,e,t)=>new Ia(n,e,t);function ot(n){this._maxSize=n,this.clear()}ot.prototype.clear=function(){this._size=0,this._values=Object.create(null)},ot.prototype.get=function(n){return this._values[n]},ot.prototype.set=function(n,e){return this._size>=this._maxSize&&this.clear(),n in this._values||this._size++,this._values[n]=e};var Fa=/[^.^\]^[]+|(?=\[\]|\.\.)/g,Es=/^\d+$/,Da=/^\d/,Ua=/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g,ja=/^\s*(['"]?)(.*?)(\1)\s*$/,ln=512,xs=new ot(ln),Ts=new ot(ln),Os=new ot(ln),at={Cache:ot,split:fn,normalizePath:hn,setter:function(n){var e=hn(n);return Ts.get(n)||Ts.set(n,function(r,s){for(var i=0,o=e.length,a=r;i<o-1;){var c=e[i];if(c==="__proto__"||c==="constructor"||c==="prototype")return r;a=a[e[i++]]}a[e[i]]=s})},getter:function(n,e){var t=hn(n);return Os.get(n)||Os.set(n,function(s){for(var i=0,o=t.length;i<o;)if(s!=null||!e)s=s[t[i++]];else return;return s})},join:function(n){return n.reduce(function(e,t){return e+(dn(t)||Es.test(t)?"["+t+"]":(e?".":"")+t)},"")},forEach:function(n,e,t){La(Array.isArray(n)?n:fn(n),e,t)}};function hn(n){return xs.get(n)||xs.set(n,fn(n).map(function(e){return e.replace(ja,"$2")}))}function fn(n){return n.match(Fa)||[""]}function La(n,e,t){var r=n.length,s,i,o,a;for(i=0;i<r;i++)s=n[i],s&&(Ma(s)&&(s='"'+s+'"'),a=dn(s),o=!a&&/^\d+$/.test(s),e.call(t,s,a,o,i,n))}function dn(n){return typeof n=="string"&&n&&["'",'"'].indexOf(n.charAt(0))!==-1}function Ba(n){return n.match(Da)&&!n.match(Es)}function Ha(n){return Ua.test(n)}function Ma(n){return!dn(n)&&(Ba(n)||Ha(n))}const Va=/[A-Z\xc0-\xd6\xd8-\xde]?[a-z\xdf-\xf6\xf8-\xff]+(?:['’](?:d|ll|m|re|s|t|ve))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde]|$)|(?:[A-Z\xc0-\xd6\xd8-\xde]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:D|LL|M|RE|S|T|VE))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde](?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])|$)|[A-Z\xc0-\xd6\xd8-\xde]?(?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:d|ll|m|re|s|t|ve))?|[A-Z\xc0-\xd6\xd8-\xde]+(?:['’](?:D|LL|M|RE|S|T|VE))?|\d*(?:1ST|2ND|3RD|(?![123])\dTH)(?=\b|[a-z_])|\d*(?:1st|2nd|3rd|(?![123])\dth)(?=\b|[A-Z_])|\d+|(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?)*/g,dr=n=>n.match(Va)||[],pr=n=>n[0].toUpperCase()+n.slice(1),pn=(n,e)=>dr(n).join(e).toLowerCase(),ks=n=>dr(n).reduce((e,t)=>`${e}${e?t[0].toUpperCase()+t.slice(1).toLowerCase():t.toLowerCase()}`,"");var yn={words:dr,upperFirst:pr,camelCase:ks,pascalCase:n=>pr(ks(n)),snakeCase:n=>pn(n,"_"),kebabCase:n=>pn(n,"-"),sentenceCase:n=>pr(pn(n," ")),titleCase:n=>dr(n).map(pr).join(" ")},yr={},za={get exports(){return yr},set exports(n){yr=n}};za.exports=function(n){return As(qa(n),n)},yr.array=As;function As(n,e){var t=n.length,r=new Array(t),s={},i=t,o=Ga(e),a=Ja(n);for(e.forEach(function(u){if(!a.has(u[0])||!a.has(u[1]))throw new Error("Unknown node. There is an unknown node in the supplied edges.")});i--;)s[i]||c(n[i],i,new Set);return r;function c(u,l,h){if(h.has(u)){var y;try{y=", node was:"+JSON.stringify(u)}catch{y=""}throw new Error("Cyclic dependency"+y)}if(!a.has(u))throw new Error("Found unknown node. Make sure to provided all involved nodes. Unknown node: "+JSON.stringify(u));if(!s[l]){s[l]=!0;var p=o.get(u)||new Set;if(p=Array.from(p),l=p.length){h.add(u);do{var w=p[--l];c(w,a.get(w),h)}while(l);h.delete(u)}r[--t]=u}}}function qa(n){for(var e=new Set,t=0,r=n.length;t<r;t++){var s=n[t];e.add(s[0]),e.add(s[1])}return Array.from(e)}function Ga(n){for(var e=new Map,t=0,r=n.length;t<r;t++){var s=n[t];e.has(s[0])||e.set(s[0],new Set),e.has(s[1])||e.set(s[1],new Set),e.get(s[0]).add(s[1])}return e}function Ja(n){for(var e=new Map,t=0,r=n.length;t<r;t++)e.set(n[t],t);return e}const Wa=Object.prototype.toString,Ka=Error.prototype.toString,Xa=RegExp.prototype.toString,Za=typeof Symbol<"u"?Symbol.prototype.toString:()=>"",Ya=/^Symbol\((.*)\)(.*)$/;function Qa(n){return n!=+n?"NaN":n===0&&1/n<0?"-0":""+n}function Ss(n,e=!1){if(n==null||n===!0||n===!1)return""+n;const t=typeof n;if(t==="number")return Qa(n);if(t==="string")return e?`"${n}"`:n;if(t==="function")return"[Function "+(n.name||"anonymous")+"]";if(t==="symbol")return Za.call(n).replace(Ya,"Symbol($1)");const r=Wa.call(n).slice(8,-1);return r==="Date"?isNaN(n.getTime())?""+n:n.toISOString(n):r==="Error"||n instanceof Error?"["+Ka.call(n)+"]":r==="RegExp"?Xa.call(n):null}function ct(n,e){let t=Ss(n,e);return t!==null?t:JSON.stringify(n,function(r,s){let i=Ss(this[r],e);return i!==null?i:s},2)}function Rs(n){return n==null?[]:[].concat(n)}let ec=/\$\{\s*(\w+)\s*\}/g;class ce extends Error{static formatError(e,t){const r=t.label||t.path||"this";return r!==t.path&&(t=Object.assign({},t,{path:r})),typeof e=="string"?e.replace(ec,(s,i)=>ct(t[i])):typeof e=="function"?e(t):e}static isError(e){return e&&e.name==="ValidationError"}constructor(e,t,r,s){super(),this.value=void 0,this.path=void 0,this.type=void 0,this.errors=void 0,this.params=void 0,this.inner=void 0,this.name="ValidationError",this.value=t,this.path=r,this.type=s,this.errors=[],this.inner=[],Rs(e).forEach(i=>{ce.isError(i)?(this.errors.push(...i.errors),this.inner=this.inner.concat(i.inner.length?i.inner:i)):this.errors.push(i)}),this.message=this.errors.length>1?`${this.errors.length} errors occurred`:this.errors[0],Error.captureStackTrace&&Error.captureStackTrace(this,ce)}}let Pe={default:"${path} is invalid",required:"${path} is a required field",defined:"${path} must be defined",notNull:"${path} cannot be null",oneOf:"${path} must be one of the following values: ${values}",notOneOf:"${path} must not be one of the following values: ${values}",notType:({path:n,type:e,value:t,originalValue:r})=>{const s=r!=null&&r!==t?` (cast from the value \`${ct(r,!0)}\`).`:".";return e!=="mixed"?`${n} must be a \`${e}\` type, but the final value was: \`${ct(t,!0)}\``+s:`${n} must match the configured type. The validated value was: \`${ct(t,!0)}\``+s}},me={length:"${path} must be exactly ${length} characters",min:"${path} must be at least ${min} characters",max:"${path} must be at most ${max} characters",matches:'${path} must match the following: "${regex}"',email:"${path} must be a valid email",url:"${path} must be a valid URL",uuid:"${path} must be a valid UUID",trim:"${path} must be a trimmed string",lowercase:"${path} must be a lowercase string",uppercase:"${path} must be a upper case string"},ze={min:"${path} must be greater than or equal to ${min}",max:"${path} must be less than or equal to ${max}",lessThan:"${path} must be less than ${less}",moreThan:"${path} must be greater than ${more}",positive:"${path} must be a positive number",negative:"${path} must be a negative number",integer:"${path} must be an integer"},mn={min:"${path} field must be later than ${min}",max:"${path} field must be at earlier than ${max}"},gn={isValue:"${path} field must be ${value}"},wn={noUnknown:"${path} field has unspecified keys: ${unknown}"},mr={min:"${path} field must have at least ${min} items",max:"${path} field must have less than or equal to ${max} items",length:"${path} must have ${length} items"};Object.assign(Object.create(null),{mixed:Pe,string:me,number:ze,date:mn,object:wn,array:mr,boolean:gn});const gr=n=>n&&n.__isYupSchema__;class wr{static fromOptions(e,t){if(!t.then&&!t.otherwise)throw new TypeError("either `then:` or `otherwise:` is required for `when()` conditions");let{is:r,then:s,otherwise:i}=t,o=typeof r=="function"?r:(...a)=>a.every(c=>c===r);return new wr(e,(a,c)=>{var u;let l=o(...a)?s:i;return(u=l==null?void 0:l(c))!=null?u:c})}constructor(e,t){this.fn=void 0,this.refs=e,this.refs=e,this.fn=t}resolve(e,t){let r=this.refs.map(i=>i.getValue(t==null?void 0:t.value,t==null?void 0:t.parent,t==null?void 0:t.context)),s=this.fn(r,e,t);if(s===void 0||s===e)return e;if(!gr(s))throw new TypeError("conditions must return a schema object");return s.resolve(t)}}const br={context:"$",value:"."};class ut{constructor(e,t={}){if(this.key=void 0,this.isContext=void 0,this.isValue=void 0,this.isSibling=void 0,this.path=void 0,this.getter=void 0,this.map=void 0,typeof e!="string")throw new TypeError("ref must be a string, got: "+e);if(this.key=e.trim(),e==="")throw new TypeError("ref must be a non-empty string");this.isContext=this.key[0]===br.context,this.isValue=this.key[0]===br.value,this.isSibling=!this.isContext&&!this.isValue;let r=this.isContext?br.context:this.isValue?br.value:"";this.path=this.key.slice(r.length),this.getter=this.path&&at.getter(this.path,!0),this.map=t.map}getValue(e,t,r){let s=this.isContext?r:this.isValue?e:t;return this.getter&&(s=this.getter(s||{})),this.map&&(s=this.map(s)),s}cast(e,t){return this.getValue(e,t==null?void 0:t.parent,t==null?void 0:t.context)}resolve(){return this}describe(){return{type:"ref",key:this.key}}toString(){return`Ref(${this.key})`}static isRef(e){return e&&e.__isYupRef}}ut.prototype.__isYupRef=!0;const he=n=>n==null;function kt(n){function e({value:t,path:r="",options:s,originalValue:i,schema:o},a,c){const{name:u,test:l,params:h,message:y,skipAbsent:p}=n;let{parent:w,context:v,abortEarly:g=o.spec.abortEarly}=s;function S(M){return ut.isRef(M)?M.getValue(t,w,v):M}function U(M={}){const W=Object.assign({value:t,originalValue:i,label:o.spec.label,path:M.path||r,spec:o.spec},h,M.params);for(const jt of Object.keys(W))W[jt]=S(W[jt]);const qr=new ce(ce.formatError(M.message||y,W),t,W.path,M.type||u);return qr.params=W,qr}const te=g?a:c;let L={path:r,parent:w,type:u,from:s.from,createError:U,resolve:S,options:s,originalValue:i,schema:o};const Re=M=>{ce.isError(M)?te(M):M?c(null):te(U())},or=M=>{ce.isError(M)?te(M):a(M)},Vr=p&&he(t);if(!s.sync){try{Promise.resolve(Vr?!0:l.call(L,t,L)).then(Re,or)}catch(M){or(M)}return}let _e;try{var zr;if(_e=Vr?!0:l.call(L,t,L),typeof((zr=_e)==null?void 0:zr.then)=="function")throw new Error(`Validation test of type: "${L.type}" returned a Promise during a synchronous validate. This test will finish after the validate call has returned`)}catch(M){or(M);return}Re(_e)}return e.OPTIONS=n,e}function tc(n,e,t,r=t){let s,i,o;return e?(at.forEach(e,(a,c,u)=>{let l=c?a.slice(1,a.length-1):a;n=n.resolve({context:r,parent:s,value:t});let h=n.type==="tuple",y=u?parseInt(l,10):0;if(n.innerType||h){if(h&&!u)throw new Error(`Yup.reach cannot implicitly index into a tuple type. the path part "${o}" must contain an index to the tuple element, e.g. "${o}[0]"`);if(t&&y>=t.length)throw new Error(`Yup.reach cannot resolve an array item at index: ${a}, in the path: ${e}. because there is no value at that index. `);s=t,t=t&&t[y],n=h?n.spec.types[y]:n.innerType}if(!u){if(!n.fields||!n.fields[l])throw new Error(`The schema does not contain the path: ${e}. (failed at: ${o} which is a type: "${n.type}")`);s=t,t=t&&t[l],n=n.fields[l]}i=l,o=c?"["+a+"]":"."+a}),{schema:n,parent:s,parentPath:i}):{parent:s,parentPath:e,schema:n}}class vr extends Set{describe(){const e=[];for(const t of this.values())e.push(ut.isRef(t)?t.describe():t);return e}resolveAll(e){let t=[];for(const r of this.values())t.push(e(r));return t}clone(){return new vr(this.values())}merge(e,t){const r=this.clone();return e.forEach(s=>r.add(s)),t.forEach(s=>r.delete(s)),r}}function At(n,e=new Map){if(gr(n)||!n||typeof n!="object")return n;if(e.has(n))return e.get(n);let t;if(n instanceof Date)t=new Date(n.getTime()),e.set(n,t);else if(n instanceof RegExp)t=new RegExp(n),e.set(n,t);else if(Array.isArray(n)){t=new Array(n.length),e.set(n,t);for(let r=0;r<n.length;r++)t[r]=At(n[r],e)}else if(n instanceof Map){t=new Map,e.set(n,t);for(const[r,s]of n.entries())t.set(r,At(s,e))}else if(n instanceof Set){t=new Set,e.set(n,t);for(const r of n)t.add(At(r,e))}else if(n instanceof Object){t={},e.set(n,t);for(const[r,s]of Object.entries(n))t[r]=At(s,e)}else throw Error(`Unable to clone ${n}`);return t}class ne{constructor(e){this.type=void 0,this.deps=[],this.tests=void 0,this.transforms=void 0,this.conditions=[],this._mutate=void 0,this.internalTests={},this._whitelist=new vr,this._blacklist=new vr,this.exclusiveTests=Object.create(null),this._typeCheck=void 0,this.spec=void 0,this.tests=[],this.transforms=[],this.withMutation(()=>{this.typeError(Pe.notType)}),this.type=e.type,this._typeCheck=e.check,this.spec=Object.assign({strip:!1,strict:!1,abortEarly:!0,recursive:!0,nullable:!1,optional:!0,coerce:!0},e==null?void 0:e.spec),this.withMutation(t=>{t.nonNullable()})}get _type(){return this.type}clone(e){if(this._mutate)return e&&Object.assign(this.spec,e),this;const t=Object.create(Object.getPrototypeOf(this));return t.type=this.type,t._typeCheck=this._typeCheck,t._whitelist=this._whitelist.clone(),t._blacklist=this._blacklist.clone(),t.internalTests=Object.assign({},this.internalTests),t.exclusiveTests=Object.assign({},this.exclusiveTests),t.deps=[...this.deps],t.conditions=[...this.conditions],t.tests=[...this.tests],t.transforms=[...this.transforms],t.spec=At(Object.assign({},this.spec,e)),t}label(e){let t=this.clone();return t.spec.label=e,t}meta(...e){if(e.length===0)return this.spec.meta;let t=this.clone();return t.spec.meta=Object.assign(t.spec.meta||{},e[0]),t}withMutation(e){let t=this._mutate;this._mutate=!0;let r=e(this);return this._mutate=t,r}concat(e){if(!e||e===this)return this;if(e.type!==this.type&&this.type!=="mixed")throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this.type} and ${e.type}`);let t=this,r=e.clone();const s=Object.assign({},t.spec,r.spec);return r.spec=s,r.internalTests=Object.assign({},t.internalTests,r.internalTests),r._whitelist=t._whitelist.merge(e._whitelist,e._blacklist),r._blacklist=t._blacklist.merge(e._blacklist,e._whitelist),r.tests=t.tests,r.exclusiveTests=t.exclusiveTests,r.withMutation(i=>{e.tests.forEach(o=>{i.test(o.OPTIONS)})}),r.transforms=[...t.transforms,...r.transforms],r}isType(e){return e==null?!!(this.spec.nullable&&e===null||this.spec.optional&&e===void 0):this._typeCheck(e)}resolve(e){let t=this;if(t.conditions.length){let r=t.conditions;t=t.clone(),t.conditions=[],t=r.reduce((s,i)=>i.resolve(s,e),t),t=t.resolve(e)}return t}resolveOptions(e){var t,r,s;return Object.assign({},e,{from:e.from||[],strict:(t=e.strict)!=null?t:this.spec.strict,abortEarly:(r=e.abortEarly)!=null?r:this.spec.abortEarly,recursive:(s=e.recursive)!=null?s:this.spec.recursive})}cast(e,t={}){let r=this.resolve(Object.assign({value:e},t)),s=t.assert==="ignore-optionality",i=r._cast(e,t);if(t.assert!==!1&&!r.isType(i)){if(s&&he(i))return i;let o=ct(e),a=ct(i);throw new TypeError(`The value of ${t.path||"field"} could not be cast to a value that satisfies the schema type: "${r.type}".
|
2
2
|
|
3
3
|
attempted value: ${o}
|
4
|
-
`+(a!==o?`result of cast: ${a}`:""))}return i}_cast(e,t){let r=e===void 0?e:this.transforms.reduce((s,i)=>i.call(this,s,e,this),e);return r===void 0&&(r=this.getDefault()),r}_validate(e,t={},r,s){let{path:i,originalValue:o=e,strict:a=this.spec.strict}=t,c=e;a||(c=this._cast(c,Object.assign({assert:!1},t)));let u=[];for(let l of Object.values(this.internalTests))l&&u.push(l);this.runTests({path:i,value:c,originalValue:o,options:t,tests:u},r,l=>{if(l.length)return s(l,c);this.runTests({path:i,value:c,originalValue:o,options:t,tests:this.tests},r,s)})}runTests(e,t,r){let s=!1,{tests:i,value:o,originalValue:a,path:c,options:u}=e,l=v=>{s||(s=!0,t(v,o))},h=v=>{s||(s=!0,r(v,o))},y=i.length,p=[];if(!y)return h([]);let w={value:o,originalValue:a,path:c,options:u,schema:this};for(let v=0;v<i.length;v++){const g=i[v];g(w,l,function(U){U&&(p=p.concat(U)),--y<=0&&h(p)})}}asNestedTest({key:e,index:t,parent:r,parentPath:s,originalParent:i,options:o}){const a=e??t;if(a==null)throw TypeError("Must include `key` or `index` for nested validations");const c=typeof a=="number";let u=r[a];const l=Object.assign({},o,{strict:!0,parent:r,value:u,originalValue:i[a],key:void 0,[c?"index":"key"]:a,path:c||a.includes(".")?`${s||""}[${u?a:`"${a}"`}]`:(s?`${s}.`:"")+e});return(h,y,p)=>this.resolve(l)._validate(u,l,y,p)}validate(e,t){let r=this.resolve(Object.assign({},t,{value:e}));return new Promise((s,i)=>r._validate(e,t,(o,a)=>{ce.isError(o)&&(o.value=a),i(o)},(o,a)=>{o.length?i(new ce(o,a)):s(a)}))}validateSync(e,t){let r=this.resolve(Object.assign({},t,{value:e})),s;return r._validate(e,Object.assign({},t,{sync:!0}),(i,o)=>{throw ce.isError(i)&&(i.value=o),i},(i,o)=>{if(i.length)throw new ce(i,e);s=o}),s}isValid(e,t){return this.validate(e,t).then(()=>!0,r=>{if(ce.isError(r))return!1;throw r})}isValidSync(e,t){try{return this.validateSync(e,t),!0}catch(r){if(ce.isError(r))return!1;throw r}}_getDefault(){let e=this.spec.default;return e==null?e:typeof e=="function"?e.call(this):At(e)}getDefault(e){return this.resolve(e||{})._getDefault()}default(e){return arguments.length===0?this._getDefault():this.clone({default:e})}strict(e=!0){return this.clone({strict:e})}nullability(e,t){const r=this.clone({nullable:e});return r.internalTests.nullable=kt({message:t,name:"nullable",test(s){return s===null?this.schema.spec.nullable:!0}}),r}optionality(e,t){const r=this.clone({optional:e});return r.internalTests.optionality=kt({message:t,name:"optionality",test(s){return s===void 0?this.schema.spec.optional:!0}}),r}optional(){return this.optionality(!0)}defined(e=Pe.defined){return this.optionality(!1,e)}nullable(){return this.nullability(!0)}nonNullable(e=Pe.notNull){return this.nullability(!1,e)}required(e=Pe.required){return this.clone().withMutation(t=>t.nonNullable(e).defined(e))}notRequired(){return this.clone().withMutation(e=>e.nullable().optional())}transform(e){let t=this.clone();return t.transforms.push(e),t}test(...e){let t;if(e.length===1?typeof e[0]=="function"?t={test:e[0]}:t=e[0]:e.length===2?t={name:e[0],test:e[1]}:t={name:e[0],message:e[1],test:e[2]},t.message===void 0&&(t.message=Pe.default),typeof t.test!="function")throw new TypeError("`test` is a required parameters");let r=this.clone(),s=kt(t),i=t.exclusive||t.name&&r.exclusiveTests[t.name]===!0;if(t.exclusive&&!t.name)throw new TypeError("Exclusive tests must provide a unique `name` identifying the test");return t.name&&(r.exclusiveTests[t.name]=!!t.exclusive),r.tests=r.tests.filter(o=>!(o.OPTIONS.name===t.name&&(i||o.OPTIONS.test===s.OPTIONS.test))),r.tests.push(s),r}when(e,t){!Array.isArray(e)&&typeof e!="string"&&(t=e,e=".");let r=this.clone(),s=Rs(e).map(i=>new ut(i));return s.forEach(i=>{i.isSibling&&r.deps.push(i.key)}),r.conditions.push(typeof t=="function"?new wr(s,t):wr.fromOptions(s,t)),r}typeError(e){let t=this.clone();return t.internalTests.typeError=kt({message:e,name:"typeError",test(r){return!he(r)&&!this.schema._typeCheck(r)?this.createError({params:{type:this.schema.type}}):!0}}),t}oneOf(e,t=Pe.oneOf){let r=this.clone();return e.forEach(s=>{r._whitelist.add(s),r._blacklist.delete(s)}),r.internalTests.whiteList=kt({message:t,name:"oneOf",skipAbsent:!0,test(s){let i=this.schema._whitelist,o=i.resolveAll(this.resolve);return o.includes(s)?!0:this.createError({params:{values:Array.from(i).join(", "),resolved:o}})}}),r}notOneOf(e,t=Pe.notOneOf){let r=this.clone();return e.forEach(s=>{r._blacklist.add(s),r._whitelist.delete(s)}),r.internalTests.blacklist=kt({message:t,name:"notOneOf",test(s){let i=this.schema._blacklist,o=i.resolveAll(this.resolve);return o.includes(s)?this.createError({params:{values:Array.from(i).join(", "),resolved:o}}):!0}}),r}strip(e=!0){let t=this.clone();return t.spec.strip=e,t}describe(e){const t=(e?this.resolve(e):this).clone(),{label:r,meta:s,optional:i,nullable:o}=t.spec;return{meta:s,label:r,optional:i,nullable:o,default:t.getDefault(e),type:t.type,oneOf:t._whitelist.describe(),notOneOf:t._blacklist.describe(),tests:t.tests.map(c=>({name:c.OPTIONS.name,params:c.OPTIONS.params})).filter((c,u,l)=>l.findIndex(h=>h.name===c.name)===u)}}}ne.prototype.__isYupSchema__=!0;for(const n of["validate","validateSync"])ne.prototype[`${n}At`]=function(e,t,r={}){const{parent:s,parentPath:i,schema:o}=tc(this,e,t,r.context);return o[n](s&&s[i],Object.assign({},r,{parent:s,path:e}))};for(const n of["equals","is"])ne.prototype[n]=ne.prototype.oneOf;for(const n of["not","nope"])ne.prototype[n]=ne.prototype.notOneOf;const rc=()=>!0;function $s(n){return new Ps(n)}class Ps extends ne{constructor(e){super(typeof e=="function"?{type:"mixed",check:e}:Object.assign({type:"mixed",check:rc},e))}}$s.prototype=Ps.prototype;function _r(){return new Ns}class Ns extends ne{constructor(){super({type:"boolean",check(e){return e instanceof Boolean&&(e=e.valueOf()),typeof e=="boolean"}}),this.withMutation(()=>{this.transform((e,t,r)=>{if(r.spec.coerce&&!r.isType(e)){if(/^(true|1)$/i.test(String(e)))return!0;if(/^(false|0)$/i.test(String(e)))return!1}return e})})}isTrue(e=gn.isValue){return this.test({message:e,name:"is-value",exclusive:!0,params:{value:"true"},test(t){return he(t)||t===!0}})}isFalse(e=gn.isValue){return this.test({message:e,name:"is-value",exclusive:!0,params:{value:"false"},test(t){return he(t)||t===!1}})}default(e){return super.default(e)}defined(e){return super.defined(e)}optional(){return super.optional()}required(e){return super.required(e)}notRequired(){return super.notRequired()}nullable(){return super.nullable()}nonNullable(e){return super.nonNullable(e)}strip(e){return super.strip(e)}}_r.prototype=Ns.prototype;let nc=/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,sc=/^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,ic=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,oc=n=>he(n)||n===n.trim(),ac={}.toString();function T(){return new Is}class Is extends ne{constructor(){super({type:"string",check(e){return e instanceof String&&(e=e.valueOf()),typeof e=="string"}}),this.withMutation(()=>{this.transform((e,t,r)=>{if(!r.spec.coerce||r.isType(e)||Array.isArray(e))return e;const s=e!=null&&e.toString?e.toString():e;return s===ac?e:s})})}required(e){return super.required(e).withMutation(t=>t.test({message:e||Pe.required,name:"required",skipAbsent:!0,test:r=>!!r.length}))}notRequired(){return super.notRequired().withMutation(e=>(e.tests=e.tests.filter(t=>t.OPTIONS.name!=="required"),e))}length(e,t=me.length){return this.test({message:t,name:"length",exclusive:!0,params:{length:e},skipAbsent:!0,test(r){return r.length===this.resolve(e)}})}min(e,t=me.min){return this.test({message:t,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(r){return r.length>=this.resolve(e)}})}max(e,t=me.max){return this.test({name:"max",exclusive:!0,message:t,params:{max:e},skipAbsent:!0,test(r){return r.length<=this.resolve(e)}})}matches(e,t){let r=!1,s,i;return t&&(typeof t=="object"?{excludeEmptyString:r=!1,message:s,name:i}=t:s=t),this.test({name:i||"matches",message:s||me.matches,params:{regex:e},skipAbsent:!0,test:o=>o===""&&r||o.search(e)!==-1})}email(e=me.email){return this.matches(nc,{name:"email",message:e,excludeEmptyString:!0})}url(e=me.url){return this.matches(sc,{name:"url",message:e,excludeEmptyString:!0})}uuid(e=me.uuid){return this.matches(ic,{name:"uuid",message:e,excludeEmptyString:!1})}ensure(){return this.default("").transform(e=>e===null?"":e)}trim(e=me.trim){return this.transform(t=>t!=null?t.trim():t).test({message:e,name:"trim",test:oc})}lowercase(e=me.lowercase){return this.transform(t=>he(t)?t:t.toLowerCase()).test({message:e,name:"string_case",exclusive:!0,skipAbsent:!0,test:t=>he(t)||t===t.toLowerCase()})}uppercase(e=me.uppercase){return this.transform(t=>he(t)?t:t.toUpperCase()).test({message:e,name:"string_case",exclusive:!0,skipAbsent:!0,test:t=>he(t)||t===t.toUpperCase()})}}T.prototype=Is.prototype;let cc=n=>n!=+n;function q(){return new Cs}class Cs extends ne{constructor(){super({type:"number",check(e){return e instanceof Number&&(e=e.valueOf()),typeof e=="number"&&!cc(e)}}),this.withMutation(()=>{this.transform((e,t,r)=>{if(!r.spec.coerce)return e;let s=e;if(typeof s=="string"){if(s=s.replace(/\s/g,""),s==="")return NaN;s=+s}return r.isType(s)?s:parseFloat(s)})})}min(e,t=ze.min){return this.test({message:t,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(r){return r>=this.resolve(e)}})}max(e,t=ze.max){return this.test({message:t,name:"max",exclusive:!0,params:{max:e},skipAbsent:!0,test(r){return r<=this.resolve(e)}})}lessThan(e,t=ze.lessThan){return this.test({message:t,name:"max",exclusive:!0,params:{less:e},skipAbsent:!0,test(r){return r<this.resolve(e)}})}moreThan(e,t=ze.moreThan){return this.test({message:t,name:"min",exclusive:!0,params:{more:e},skipAbsent:!0,test(r){return r>this.resolve(e)}})}positive(e=ze.positive){return this.moreThan(0,e)}negative(e=ze.negative){return this.lessThan(0,e)}integer(e=ze.integer){return this.test({name:"integer",message:e,skipAbsent:!0,test:t=>Number.isInteger(t)})}truncate(){return this.transform(e=>he(e)?e:e|0)}round(e){var t;let r=["ceil","floor","round","trunc"];if(e=((t=e)==null?void 0:t.toLowerCase())||"round",e==="trunc")return this.truncate();if(r.indexOf(e.toLowerCase())===-1)throw new TypeError("Only valid options for round() are: "+r.join(", "));return this.transform(s=>he(s)?s:Math[e](s))}}q.prototype=Cs.prototype;var uc=/^(\d{4}|[+\-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;function lc(n){var e=[1,4,5,6,7,10,11],t=0,r,s;if(s=uc.exec(n)){for(var i=0,o;o=e[i];++i)s[o]=+s[o]||0;s[2]=(+s[2]||1)-1,s[3]=+s[3]||1,s[7]=s[7]?String(s[7]).substr(0,3):0,(s[8]===void 0||s[8]==="")&&(s[9]===void 0||s[9]==="")?r=+new Date(s[1],s[2],s[3],s[4],s[5],s[6],s[7]):(s[8]!=="Z"&&s[9]!==void 0&&(t=s[10]*60+s[11],s[9]==="+"&&(t=0-t)),r=Date.UTC(s[1],s[2],s[3],s[4],s[5]+t,s[6],s[7]))}else r=Date.parse?Date.parse(n):NaN;return r}let hc=new Date(""),fc=n=>Object.prototype.toString.call(n)==="[object Date]";class Er extends ne{constructor(){super({type:"date",check(e){return fc(e)&&!isNaN(e.getTime())}}),this.withMutation(()=>{this.transform((e,t,r)=>!r.spec.coerce||r.isType(e)?e:(e=lc(e),isNaN(e)?Er.INVALID_DATE:new Date(e)))})}prepareParam(e,t){let r;if(ut.isRef(e))r=e;else{let s=this.cast(e);if(!this._typeCheck(s))throw new TypeError(`\`${t}\` must be a Date or a value that can be \`cast()\` to a Date`);r=s}return r}min(e,t=mn.min){let r=this.prepareParam(e,"min");return this.test({message:t,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(s){return s>=this.resolve(r)}})}max(e,t=mn.max){let r=this.prepareParam(e,"max");return this.test({message:t,name:"max",exclusive:!0,params:{max:e},skipAbsent:!0,test(s){return s<=this.resolve(r)}})}}Er.INVALID_DATE=hc,Er.prototype;function dc(n,e=[]){let t=[],r=new Set,s=new Set(e.map(([o,a])=>`${o}-${a}`));function i(o,a){let c=at.split(o)[0];r.add(c),s.has(`${a}-${c}`)||t.push([a,c])}for(const o of Object.keys(n)){let a=n[o];r.add(o),ut.isRef(a)&&a.isSibling?i(a.path,o):gr(a)&&"deps"in a&&a.deps.forEach(c=>i(c,o))}return yr.array(Array.from(r),t).reverse()}function Fs(n,e){let t=1/0;return n.some((r,s)=>{var i;if((i=e.path)!=null&&i.includes(r))return t=s,!0}),t}function Ds(n){return(e,t)=>Fs(n,e)-Fs(n,t)}const Us=(n,e,t)=>{if(typeof n!="string")return n;let r=n;try{r=JSON.parse(n)}catch{}return t.isType(r)?r:n};function xr(n){if("fields"in n){const e={};for(const[t,r]of Object.entries(n.fields))e[t]=xr(r);return n.setFields(e)}if(n.type==="array"){const e=n.optional();return e.innerType&&(e.innerType=xr(e.innerType)),e}return n.type==="tuple"?n.optional().clone({types:n.spec.types.map(xr)}):"optional"in n?n.optional():n}const pc=(n,e)=>{const t=[...at.normalizePath(e)];if(t.length===1)return t[0]in n;let r=t.pop(),s=at.getter(at.join(t),!0)(n);return!!(s&&r in s)};let js=n=>Object.prototype.toString.call(n)==="[object Object]";function yc(n,e){let t=Object.keys(n.fields);return Object.keys(e).filter(r=>t.indexOf(r)===-1)}const mc=Ds([]);function se(n){return new Ls(n)}class Ls extends ne{constructor(e){super({type:"object",check(t){return js(t)||typeof t=="function"}}),this.fields=Object.create(null),this._sortErrors=mc,this._nodes=[],this._excludedEdges=[],this.withMutation(()=>{e&&this.shape(e)})}_cast(e,t={}){var r;let s=super._cast(e,t);if(s===void 0)return this.getDefault();if(!this._typeCheck(s))return s;let i=this.fields,o=(r=t.stripUnknown)!=null?r:this.spec.noUnknown,a=[].concat(this._nodes,Object.keys(s).filter(h=>!this._nodes.includes(h))),c={},u=Object.assign({},t,{parent:c,__validating:t.__validating||!1}),l=!1;for(const h of a){let y=i[h],p=h in s;if(y){let w,v=s[h];u.path=(t.path?`${t.path}.`:"")+h,y=y.resolve({value:v,context:t.context,parent:c});let g=y instanceof ne?y.spec:void 0,S=g==null?void 0:g.strict;if(g!=null&&g.strip){l=l||h in s;continue}w=!t.__validating||!S?y.cast(s[h],u):s[h],w!==void 0&&(c[h]=w)}else p&&!o&&(c[h]=s[h]);(p!==h in c||c[h]!==s[h])&&(l=!0)}return l?c:s}_validate(e,t={},r,s){let{from:i=[],originalValue:o=e,recursive:a=this.spec.recursive}=t;t.from=[{schema:this,value:o},...i],t.__validating=!0,t.originalValue=o,super._validate(e,t,r,(c,u)=>{if(!a||!js(u)){s(c,u);return}o=o||u;let l=[];for(let h of this._nodes){let y=this.fields[h];!y||ut.isRef(y)||l.push(y.asNestedTest({options:t,key:h,parent:u,parentPath:t.path,originalParent:o}))}this.runTests({tests:l,value:u,originalValue:o,options:t},r,h=>{s(h.sort(this._sortErrors).concat(c),u)})})}clone(e){const t=super.clone(e);return t.fields=Object.assign({},this.fields),t._nodes=this._nodes,t._excludedEdges=this._excludedEdges,t._sortErrors=this._sortErrors,t}concat(e){let t=super.concat(e),r=t.fields;for(let[s,i]of Object.entries(this.fields)){const o=r[s];r[s]=o===void 0?i:o}return t.withMutation(s=>s.setFields(r,this._excludedEdges))}_getDefault(){if("default"in this.spec)return super._getDefault();if(!this._nodes.length)return;let e={};return this._nodes.forEach(t=>{const r=this.fields[t];e[t]=r&&"getDefault"in r?r.getDefault():void 0}),e}setFields(e,t){let r=this.clone();return r.fields=e,r._nodes=dc(e,t),r._sortErrors=Ds(Object.keys(e)),t&&(r._excludedEdges=t),r}shape(e,t=[]){return this.clone().withMutation(r=>{let s=r._excludedEdges;return t.length&&(Array.isArray(t[0])||(t=[t]),s=[...r._excludedEdges,...t]),r.setFields(Object.assign(r.fields,e),s)})}partial(){const e={};for(const[t,r]of Object.entries(this.fields))e[t]="optional"in r&&r.optional instanceof Function?r.optional():r;return this.setFields(e)}deepPartial(){return xr(this)}pick(e){const t={};for(const r of e)this.fields[r]&&(t[r]=this.fields[r]);return this.setFields(t)}omit(e){const t=Object.assign({},this.fields);for(const r of e)delete t[r];return this.setFields(t)}from(e,t,r){let s=at.getter(e,!0);return this.transform(i=>{if(!i)return i;let o=i;return pc(i,e)&&(o=Object.assign({},i),r||delete o[e],o[t]=s(i)),o})}json(){return this.transform(Us)}noUnknown(e=!0,t=wn.noUnknown){typeof e!="boolean"&&(t=e,e=!0);let r=this.test({name:"noUnknown",exclusive:!0,message:t,test(s){if(s==null)return!0;const i=yc(this.schema,s);return!e||i.length===0||this.createError({params:{unknown:i.join(", ")}})}});return r.spec.noUnknown=e,r}unknown(e=!0,t=wn.noUnknown){return this.noUnknown(!e,t)}transformKeys(e){return this.transform(t=>{if(!t)return t;const r={};for(const s of Object.keys(t))r[e(s)]=t[s];return r})}camelCase(){return this.transformKeys(yn.camelCase)}snakeCase(){return this.transformKeys(yn.snakeCase)}constantCase(){return this.transformKeys(e=>yn.snakeCase(e).toUpperCase())}describe(e){let t=super.describe(e);t.fields={};for(const[s,i]of Object.entries(this.fields)){var r;let o=e;(r=o)!=null&&r.value&&(o=Object.assign({},o,{parent:o.value,value:o.value[s]})),t.fields[s]=i.describe(o)}return t}}se.prototype=Ls.prototype;function lt(n){return new Bs(n)}class Bs extends ne{constructor(e){super({type:"array",check(t){return Array.isArray(t)}}),this.innerType=void 0,this.innerType=e}_cast(e,t){const r=super._cast(e,t);if(!this._typeCheck(r)||!this.innerType)return r;let s=!1;const i=r.map((o,a)=>{const c=this.innerType.cast(o,Object.assign({},t,{path:`${t.path||""}[${a}]`}));return c!==o&&(s=!0),c});return s?i:r}_validate(e,t={},r,s){var i;let o=this.innerType,a=(i=t.recursive)!=null?i:this.spec.recursive;t.originalValue!=null&&t.originalValue,super._validate(e,t,r,(c,u)=>{var l;if(!a||!o||!this._typeCheck(u)){s(c,u);return}let h=new Array(u.length);for(let p=0;p<u.length;p++){var y;h[p]=o.asNestedTest({options:t,index:p,parent:u,parentPath:t.path,originalParent:(y=t.originalValue)!=null?y:e})}this.runTests({value:u,tests:h,originalValue:(l=t.originalValue)!=null?l:e,options:t},r,p=>s(p.concat(c),u))})}clone(e){const t=super.clone(e);return t.innerType=this.innerType,t}json(){return this.transform(Us)}concat(e){let t=super.concat(e);return t.innerType=this.innerType,e.innerType&&(t.innerType=t.innerType?t.innerType.concat(e.innerType):e.innerType),t}of(e){let t=this.clone();if(!gr(e))throw new TypeError("`array.of()` sub-schema must be a valid yup schema not: "+ct(e));return t.innerType=e,t}length(e,t=mr.length){return this.test({message:t,name:"length",exclusive:!0,params:{length:e},skipAbsent:!0,test(r){return r.length===this.resolve(e)}})}min(e,t){return t=t||mr.min,this.test({message:t,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(r){return r.length>=this.resolve(e)}})}max(e,t){return t=t||mr.max,this.test({message:t,name:"max",exclusive:!0,params:{max:e},skipAbsent:!0,test(r){return r.length<=this.resolve(e)}})}ensure(){return this.default(()=>[]).transform((e,t)=>this._typeCheck(e)?e:t==null?[]:[].concat(t))}compact(e){let t=e?(r,s,i)=>!e(r,s,i):r=>!!r;return this.transform(r=>r!=null?r.filter(t):r)}describe(e){let t=super.describe(e);if(this.innerType){var r;let s=e;(r=s)!=null&&r.value&&(s=Object.assign({},s,{parent:s.value,value:s.value[0]})),t.innerType=this.innerType.describe(e)}return t}}lt.prototype=Bs.prototype;const Hs=se({url:T(),height:q(),width:q()}),gc=se({type:T().default("rich"),title:T(),color:q(),thumbnail:Hs,image:Hs,url:T()}),wc=se({url:T().url().required(),username:T(),avatar_url:T().url(),message:T().required(),embed:gc}),bc="notify_discord_webhook";class bn{static async SimpleToRaw(e){return{name:"",notify_type:bc,notify:await bn.validateCreate(e)}}static validateCreate(e){return wc.validate(e)}}const vc=se({email:T().required(),subject:T(),html:T().required()}),_c="notify_email";class vn{static async SimpleToRaw(e){return{name:"",notify_type:_c,notify:await vn.validateCreate(e)}}static async validateCreate(e){return vc.validate(e)}}const Ec=se({clientId:q().required(),content:T().required()}),xc="notify_telegram";class _n{static async SimpleToRaw(e){return{name:"",notify_type:xc,notify:await _n.validateCreate(e)}}static validateCreate(e){return Ec.validate(e)}}class En{static async SimpleToRaw(e,t){switch(e){case"Discord":return bn.SimpleToRaw(t);case"Telegram":return _n.SimpleToRaw(t);case"Email":return vn.SimpleToRaw(t)}}static RawToSimple(e){return{...e.notify,error:e.error,error_message:e.error_message,error_timestamp:e.error_timestamp}}static RawTypeToSimpleType(e){switch(e){case"notify_discord_webhook":return"Discord";case"notify_telegram":return"Telegram";case"notify_email":return"Email"}}static SimpleTypeToRawType(e){switch(e){case"Discord":return"notify_discord_webhook";case"Telegram":return"notify_telegram";case"Email":return"notify_email"}}}const Tc="handler_function_call";class Ms{static async SimpleToRaw(e,t,r){return{alertType:"event",network:t,nickname:e,type:Tc,handler:await this.validate(r)}}static validate(e){const t=([s],i)=>s==="true"?i.notRequired():i.required();return se({address:T().required(),abi:lt().required(),nBlocks:q().default(100).min(10).required(),function:T().required(),condition:T().default("true").oneOf([">",">=","<","<=","=","true"]).required(),constant:q().min(0).when("condition",t),responseArgIndex:q().min(0).when("condition",t),responseArgDecimals:q().min(0).when("condition",t)}).validateSync(e)}}const Oc="handler_onchain_event";class Vs{static async SimpleToRaw(e,t,r){return{alertType:"event",network:t,nickname:e,type:Oc,handler:await this.validate(r)}}static validate(e){const t=([s],i)=>s==="true"?i.notRequired():i.required();return se({address:T().required(),event:T().required(),abi:lt().required(),condition:T().default("true").oneOf([">",">=","<","<=","=","true"]).required(),constant:q().min(0).when("condition",t),paramsIndex:q().min(0).when("condition",t),paramsDecimals:q().min(0).when("condition",t)}).validateSync(e)}}const kc="6.1.0";function Ac(n,e,t){const r=e.split("|").map(i=>i.trim());for(let i=0;i<r.length;i++)switch(e){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof n===e)return}const s=new Error(`invalid value for type ${e}`);throw s.code="INVALID_ARGUMENT",s.argument=`value.${t}`,s.value=n,s}async function zs(n){const e=Object.keys(n);return(await Promise.all(e.map(r=>Promise.resolve(n[r])))).reduce((r,s,i)=>(r[e[i]]=s,r),{})}function A(n,e,t){for(let r in e){let s=e[r];const i=t?t[r]:null;i&&Ac(s,i,r),Object.defineProperty(n,r,{enumerable:!0,value:s,writable:!1})}}function St(n){if(n==null)return"null";if(Array.isArray(n))return"[ "+n.map(St).join(", ")+" ]";if(n instanceof Uint8Array){const e="0123456789abcdef";let t="0x";for(let r=0;r<n.length;r++)t+=e[n[r]>>4],t+=e[n[r]&15];return t}if(typeof n=="object"&&typeof n.toJSON=="function")return St(n.toJSON());switch(typeof n){case"boolean":case"symbol":return n.toString();case"bigint":return BigInt(n).toString();case"number":return n.toString();case"string":return JSON.stringify(n);case"object":{const e=Object.keys(n);return e.sort(),"{ "+e.map(t=>`${St(t)}: ${St(n[t])}`).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function Tr(n,e){return n&&n.code===e}function qs(n){return Tr(n,"CALL_EXCEPTION")}function Or(n,e,t){{const s=[];if(t){if("message"in t||"code"in t||"name"in t)throw new Error(`value will overwrite populated values: ${St(t)}`);for(const i in t){const o=t[i];s.push(i+"="+St(o))}}s.push(`code=${e}`),s.push(`version=${kc}`),s.length&&(n+=" ("+s.join(", ")+")")}let r;switch(e){case"INVALID_ARGUMENT":r=new TypeError(n);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":r=new RangeError(n);break;default:r=new Error(n)}return A(r,{code:e}),t&&Object.assign(r,t),r}function x(n,e,t,r){if(!n)throw Or(e,t,r)}function _(n,e,t,r){x(n,e,"INVALID_ARGUMENT",{argument:t,value:r})}function Gs(n,e,t){t==null&&(t=""),t&&(t=": "+t),x(n>=e,"missing arguemnt"+t,"MISSING_ARGUMENT",{count:n,expectedCount:e}),x(n<=e,"too many arguemnts"+t,"UNEXPECTED_ARGUMENT",{count:n,expectedCount:e})}const Sc=["NFD","NFC","NFKD","NFKC"].reduce((n,e)=>{try{if("test".normalize(e)!=="test")throw new Error("bad");if(e==="NFD"){const t=String.fromCharCode(233).normalize("NFD"),r=String.fromCharCode(101,769);if(t!==r)throw new Error("broken")}n.push(e)}catch{}return n},[]);function Rc(n){x(Sc.indexOf(n)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:n}})}function xn(n,e,t){if(t==null&&(t=""),n!==e){let r=t,s="new";t&&(r+=".",s+=" "+t),x(!1,`private constructor; use ${r}from* methods`,"UNSUPPORTED_OPERATION",{operation:s})}}function Js(n,e,t){if(n instanceof Uint8Array)return t?new Uint8Array(n):n;if(typeof n=="string"&&n.match(/^0x([0-9a-f][0-9a-f])*$/i)){const r=new Uint8Array((n.length-2)/2);let s=2;for(let i=0;i<r.length;i++)r[i]=parseInt(n.substring(s,s+2),16),s+=2;return r}_(!1,"invalid BytesLike value",e||"value",n)}function Ne(n,e){return Js(n,e,!1)}function Ie(n,e){return Js(n,e,!0)}function qe(n,e){return!(typeof n!="string"||!n.match(/^0x[0-9A-Fa-f]*$/)||typeof e=="number"&&n.length!==2+2*e||e===!0&&n.length%2!==0)}const Ws="0123456789abcdef";function z(n){const e=Ne(n);let t="0x";for(let r=0;r<e.length;r++){const s=e[r];t+=Ws[(s&240)>>4]+Ws[s&15]}return t}function Rt(n){return"0x"+n.map(e=>z(e).substring(2)).join("")}function $t(n,e,t){const r=Ne(n);return t!=null&&t>r.length&&x(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:r,length:r.length,offset:t}),z(r.slice(e??0,t??r.length))}function $c(n,e,t){const r=Ne(n);x(e>=r.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(r),length:e,offset:e+1});const s=new Uint8Array(e);return s.fill(0),t?s.set(r,e-r.length):s.set(r,0),z(s)}function Pc(n,e){return $c(n,e,!0)}const kr=BigInt(0),ge=BigInt(1),Pt=9007199254740991;function Nc(n,e){const t=Sr(n,"value"),r=BigInt(Ce(e,"width"));if(x(t>>r===kr,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:n}),t>>r-ge){const s=(ge<<r)-ge;return-((~t&s)+ge)}return t}function Ic(n,e){let t=ht(n,"value");const r=BigInt(Ce(e,"width")),s=ge<<r-ge;if(t<kr){t=-t,x(t<=s,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:n});const i=(ge<<r)-ge;return(~t&i)+ge}else x(t<s,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:n});return t}function Ar(n,e){const t=Sr(n,"value"),r=BigInt(Ce(e,"bits"));return t&(ge<<r)-ge}function ht(n,e){switch(typeof n){case"bigint":return n;case"number":return _(Number.isInteger(n),"underflow",e||"value",n),_(n>=-Pt&&n<=Pt,"overflow",e||"value",n),BigInt(n);case"string":try{if(n==="")throw new Error("empty string");return n[0]==="-"&&n[1]!=="-"?-BigInt(n.substring(1)):BigInt(n)}catch(t){_(!1,`invalid BigNumberish string: ${t.message}`,e||"value",n)}}_(!1,"invalid BigNumberish value",e||"value",n)}function Sr(n,e){const t=ht(n,e);return x(t>=kr,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:n}),t}const Ks="0123456789abcdef";function Xs(n){if(n instanceof Uint8Array){let e="0x0";for(const t of n)e+=Ks[t>>4],e+=Ks[t&15];return BigInt(e)}return ht(n)}function Ce(n,e){switch(typeof n){case"bigint":return _(n>=-Pt&&n<=Pt,"overflow",e||"value",n),Number(n);case"number":return _(Number.isInteger(n),"underflow",e||"value",n),_(n>=-Pt&&n<=Pt,"overflow",e||"value",n),n;case"string":try{if(n==="")throw new Error("empty string");return Ce(BigInt(n),e)}catch(t){_(!1,`invalid numeric string: ${t.message}`,e||"value",n)}}_(!1,"invalid numeric value",e||"value",n)}function Cc(n){return Ce(Xs(n))}function Zs(n,e){let r=Sr(n,"value").toString(16);if(e==null)r.length%2&&(r="0"+r);else{const s=Ce(e,"width");for(x(s*2>=r.length,`value exceeds width (${s} bits)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:n});r.length<s*2;)r="0"+r}return"0x"+r}function Fc(n){const e=Sr(n,"value");if(e===kr)return new Uint8Array([]);let t=e.toString(16);t.length%2&&(t="0"+t);const r=new Uint8Array(t.length/2);for(let s=0;s<r.length;s++){const i=s*2;r[s]=parseInt(t.substring(i,i+2),16)}return r}class Dc{constructor(e,t,r){d(this,"filter");d(this,"emitter");j(this,It,void 0);N(this,It,t),A(this,{emitter:e,filter:r})}async removeListener(){m(this,It)!=null&&await this.emitter.off(this.filter,m(this,It))}}It=new WeakMap;function Uc(n,e,t,r,s){_(!1,`invalid codepoint at offset ${e}; ${n}`,"bytes",t)}function Ys(n,e,t,r,s){if(n==="BAD_PREFIX"||n==="UNEXPECTED_CONTINUE"){let i=0;for(let o=e+1;o<t.length&&t[o]>>6===2;o++)i++;return i}return n==="OVERRUN"?t.length-e-1:0}function jc(n,e,t,r,s){return n==="OVERLONG"?(_(typeof s=="number","invalid bad code point for replacement","badCodepoint",s),r.push(s),0):(r.push(65533),Ys(n,e,t))}const Lc=Object.freeze({error:Uc,ignore:Ys,replace:jc});function Bc(n,e){e==null&&(e=Lc.error);const t=Ne(n,"bytes"),r=[];let s=0;for(;s<t.length;){const i=t[s++];if(!(i>>7)){r.push(i);continue}let o=null,a=null;if((i&224)===192)o=1,a=127;else if((i&240)===224)o=2,a=2047;else if((i&248)===240)o=3,a=65535;else{(i&192)===128?s+=e("UNEXPECTED_CONTINUE",s-1,t,r):s+=e("BAD_PREFIX",s-1,t,r);continue}if(s-1+o>=t.length){s+=e("OVERRUN",s-1,t,r);continue}let c=i&(1<<8-o-1)-1;for(let u=0;u<o;u++){let l=t[s];if((l&192)!=128){s+=e("MISSING_CONTINUE",s,t,r),c=null;break}c=c<<6|l&63,s++}if(c!==null){if(c>1114111){s+=e("OUT_OF_RANGE",s-1-o,t,r,c);continue}if(c>=55296&&c<=57343){s+=e("UTF16_SURROGATE",s-1-o,t,r,c);continue}if(c<=a){s+=e("OVERLONG",s-1-o,t,r,c);continue}r.push(c)}}return r}function Qs(n,e){e!=null&&(Rc(e),n=n.normalize(e));let t=[];for(let r=0;r<n.length;r++){const s=n.charCodeAt(r);if(s<128)t.push(s);else if(s<2048)t.push(s>>6|192),t.push(s&63|128);else if((s&64512)==55296){r++;const i=n.charCodeAt(r);_(r<n.length&&(i&64512)===56320,"invalid surrogate pair","str",n);const o=65536+((s&1023)<<10)+(i&1023);t.push(o>>18|240),t.push(o>>12&63|128),t.push(o>>6&63|128),t.push(o&63|128)}else t.push(s>>12|224),t.push(s>>6&63|128),t.push(s&63|128)}return new Uint8Array(t)}function Hc(n){return n.map(e=>e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10&1023)+55296,(e&1023)+56320))).join("")}function Mc(n,e){return Hc(Bc(n,e))}const Q=32,Tn=new Uint8Array(Q),Vc=["then"],Rr={};function $r(n,e){const t=new Error(`deferred error during ABI decoding triggered accessing ${n}`);throw t.error=e,t}const Qt=class extends Array{constructor(...t){const r=t[0];let s=t[1],i=(t[2]||[]).slice(),o=!0;r!==Rr&&(s=t,i=[],o=!1);super(s.length);j(this,Xe,void 0);s.forEach((c,u)=>{this[u]=c});const a=i.reduce((c,u)=>(typeof u=="string"&&c.set(u,(c.get(u)||0)+1),c),new Map);if(N(this,Xe,Object.freeze(s.map((c,u)=>{const l=i[u];return l!=null&&a.get(l)===1?l:null}))),!!o)return Object.freeze(this),new Proxy(this,{get:(c,u,l)=>{if(typeof u=="string"){if(u.match(/^[0-9]+$/)){const y=Ce(u,"%index");if(y<0||y>=this.length)throw new RangeError("out of result range");const p=c[y];return p instanceof Error&&$r(`index ${y}`,p),p}if(Vc.indexOf(u)>=0)return Reflect.get(c,u,l);const h=c[u];if(h instanceof Function)return function(...y){return h.apply(this===l?c:this,y)};if(!(u in c))return c.getValue.apply(this===l?c:this,[u])}return Reflect.get(c,u,l)}})}toArray(){const t=[];return this.forEach((r,s)=>{r instanceof Error&&$r(`index ${s}`,r),t.push(r)}),t}toObject(){return m(this,Xe).reduce((t,r,s)=>(x(r!=null,"value at index ${ index } unnamed","UNSUPPORTED_OPERATION",{operation:"toObject()"}),r in t||(t[r]=this.getValue(r)),t),{})}slice(t,r){t==null&&(t=0),t<0&&(t+=this.length,t<0&&(t=0)),r==null&&(r=this.length),r<0&&(r+=this.length,r<0&&(r=0)),r>this.length&&(r=this.length);const s=[],i=[];for(let o=t;o<r;o++)s.push(this[o]),i.push(m(this,Xe)[o]);return new Qt(Rr,s,i)}filter(t,r){const s=[],i=[];for(let o=0;o<this.length;o++){const a=this[o];a instanceof Error&&$r(`index ${o}`,a),t.call(r,a,o,this)&&(s.push(a),i.push(m(this,Xe)[o]))}return new Qt(Rr,s,i)}getValue(t){const r=m(this,Xe).indexOf(t);if(r===-1)return;const s=this[r];return s instanceof Error&&$r(`property ${JSON.stringify(t)}`,s.error),s}static fromItems(t,r){return new Qt(Rr,t,r)}};let Pr=Qt;Xe=new WeakMap;function ei(n){let e=Fc(n);return x(e.length<=Q,"value out-of-bounds","BUFFER_OVERRUN",{buffer:e,length:Q,offset:e.length}),e.length!==Q&&(e=Ie(Rt([Tn.slice(e.length%Q),e]))),e}class Fe{constructor(e,t,r,s){d(this,"name");d(this,"type");d(this,"localName");d(this,"dynamic");A(this,{name:e,type:t,localName:r,dynamic:s},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(e,t){_(!1,e,this.localName,t)}}class On{constructor(){j(this,Ct);j(this,Me,void 0);j(this,bt,void 0);N(this,Me,[]),N(this,bt,0)}get data(){return Rt(m(this,Me))}get length(){return m(this,bt)}appendWriter(e){return V(this,Ct,Jr).call(this,Ie(e.data))}writeBytes(e){let t=Ie(e);const r=t.length%Q;return r&&(t=Ie(Rt([t,Tn.slice(r)]))),V(this,Ct,Jr).call(this,t)}writeValue(e){return V(this,Ct,Jr).call(this,ei(e))}writeUpdatableValue(){const e=m(this,Me).length;return m(this,Me).push(Tn),N(this,bt,m(this,bt)+Q),t=>{m(this,Me)[e]=ei(t)}}}Me=new WeakMap,bt=new WeakMap,Ct=new WeakSet,Jr=function(e){return m(this,Me).push(e),N(this,bt,m(this,bt)+e.length),e.length};const Kn=class{constructor(e,t){j(this,Lr);d(this,"allowLoose");j(this,ue,void 0);j(this,de,void 0);A(this,{allowLoose:!!t}),N(this,ue,Ie(e)),N(this,de,0)}get data(){return z(m(this,ue))}get dataLength(){return m(this,ue).length}get consumed(){return m(this,de)}get bytes(){return new Uint8Array(m(this,ue))}subReader(e){return new Kn(m(this,ue).slice(m(this,de)+e),this.allowLoose)}readBytes(e,t){let r=V(this,Lr,to).call(this,0,e,!!t);return N(this,de,m(this,de)+r.length),r.slice(0,e)}readValue(){return Xs(this.readBytes(Q))}readIndex(){return Cc(this.readBytes(Q))}};let kn=Kn;ue=new WeakMap,de=new WeakMap,Lr=new WeakSet,to=function(e,t,r){let s=Math.ceil(t/Q)*Q;return m(this,de)+s>m(this,ue).length&&(this.allowLoose&&r&&m(this,de)+t<=m(this,ue).length?s=t:x(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:Ie(m(this,ue)),length:m(this,ue).length,offset:m(this,de)+s})),m(this,ue).slice(m(this,de),m(this,de)+s)};function An(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function zc(n){if(typeof n!="boolean")throw new Error(`Expected boolean, not ${n}`)}function ti(n,...e){if(!(n instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(e.length>0&&!e.includes(n.length))throw new TypeError(`Expected Uint8Array of length ${e}, not of length=${n.length}`)}function qc(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");An(n.outputLen),An(n.blockLen)}function Gc(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function Jc(n,e){ti(n);const t=e.outputLen;if(n.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}const Nt={number:An,bool:zc,bytes:ti,hash:qc,exists:Gc,output:Jc};/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Wc=n=>new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4));if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function Kc(n){if(typeof n!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof n}`);return new TextEncoder().encode(n)}function Sn(n){if(typeof n=="string"&&(n=Kc(n)),!(n instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof n})`);return n}class Xc{clone(){return this._cloneInto()}}function Zc(n){const e=r=>n().update(Sn(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function Yc(n){const e=(r,s)=>n(s).update(Sn(r)).digest(),t=n({});return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=r=>n(r),e}const Nr=BigInt(2**32-1),Rn=BigInt(32);function ri(n,e=!1){return e?{h:Number(n&Nr),l:Number(n>>Rn&Nr)}:{h:Number(n>>Rn&Nr)|0,l:Number(n&Nr)|0}}function Qc(n,e=!1){let t=new Uint32Array(n.length),r=new Uint32Array(n.length);for(let s=0;s<n.length;s++){const{h:i,l:o}=ri(n[s],e);[t[s],r[s]]=[i,o]}return[t,r]}const eu=(n,e)=>BigInt(n>>>0)<<Rn|BigInt(e>>>0),tu=(n,e,t)=>n>>>t,ru=(n,e,t)=>n<<32-t|e>>>t,nu=(n,e,t)=>n>>>t|e<<32-t,su=(n,e,t)=>n<<32-t|e>>>t,iu=(n,e,t)=>n<<64-t|e>>>t-32,ou=(n,e,t)=>n>>>t-32|e<<64-t,au=(n,e)=>e,cu=(n,e)=>n,uu=(n,e,t)=>n<<t|e>>>32-t,lu=(n,e,t)=>e<<t|n>>>32-t,hu=(n,e,t)=>e<<t-32|n>>>64-t,fu=(n,e,t)=>n<<t-32|e>>>64-t;function du(n,e,t,r){const s=(e>>>0)+(r>>>0);return{h:n+t+(s/4294967296|0)|0,l:s|0}}const Gt={fromBig:ri,split:Qc,toBig:eu,shrSH:tu,shrSL:ru,rotrSH:nu,rotrSL:su,rotrBH:iu,rotrBL:ou,rotr32H:au,rotr32L:cu,rotlSH:uu,rotlSL:lu,rotlBH:hu,rotlBL:fu,add:du,add3L:(n,e,t)=>(n>>>0)+(e>>>0)+(t>>>0),add3H:(n,e,t,r)=>e+t+r+(n/2**32|0)|0,add4L:(n,e,t,r)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0),add4H:(n,e,t,r,s)=>e+t+r+s+(n/2**32|0)|0,add5H:(n,e,t,r,s,i)=>e+t+r+s+i+(n/2**32|0)|0,add5L:(n,e,t,r,s)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0)},[ni,si,ii]=[[],[],[]],pu=BigInt(0),Jt=BigInt(1),yu=BigInt(2),mu=BigInt(7),gu=BigInt(256),wu=BigInt(113);for(let n=0,e=Jt,t=1,r=0;n<24;n++){[t,r]=[r,(2*t+3*r)%5],ni.push(2*(5*r+t)),si.push((n+1)*(n+2)/2%64);let s=pu;for(let i=0;i<7;i++)e=(e<<Jt^(e>>mu)*wu)%gu,e&yu&&(s^=Jt<<(Jt<<BigInt(i))-Jt);ii.push(s)}const[bu,vu]=Gt.split(ii,!0),oi=(n,e,t)=>t>32?Gt.rotlBH(n,e,t):Gt.rotlSH(n,e,t),ai=(n,e,t)=>t>32?Gt.rotlBL(n,e,t):Gt.rotlSL(n,e,t);function _u(n,e=24){const t=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)t[o]=n[o]^n[o+10]^n[o+20]^n[o+30]^n[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=t[c],l=t[c+1],h=oi(u,l,1)^t[a],y=ai(u,l,1)^t[a+1];for(let p=0;p<50;p+=10)n[o+p]^=h,n[o+p+1]^=y}let s=n[2],i=n[3];for(let o=0;o<24;o++){const a=si[o],c=oi(s,i,a),u=ai(s,i,a),l=ni[o];s=n[l],i=n[l+1],n[l]=c,n[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=n[o+a];for(let a=0;a<10;a++)n[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}n[0]^=bu[r],n[1]^=vu[r]}t.fill(0)}class Ir extends Xc{constructor(e,t,r,s=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=s,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Nt.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Wc(this.state)}keccak(){_u(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){Nt.exists(this);const{blockLen:t,state:r}=this;e=Sn(e);const s=e.length;for(let i=0;i<s;){const o=Math.min(t-this.pos,s-i);for(let a=0;a<o;a++)r[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:r,blockLen:s}=this;e[r]^=t,t&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Nt.exists(this,!1),Nt.bytes(e),this.finish();const t=this.state,{blockLen:r}=this;for(let s=0,i=e.length;s<i;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,i-s);e.set(t.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Nt.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Nt.output(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:s,rounds:i,enableXOF:o}=this;return e||(e=new Ir(t,r,s,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Ge=(n,e,t)=>Zc(()=>new Ir(e,n,t));Ge(6,144,28),Ge(6,136,32),Ge(6,104,48),Ge(6,72,64),Ge(1,144,28);const Eu=Ge(1,136,256/8);Ge(1,104,48),Ge(1,72,64);const ci=(n,e,t)=>Yc((r={})=>new Ir(e,n,r.dkLen===void 0?t:r.dkLen,!0));ci(31,168,16),ci(31,136,32);let ui=!1;const li=function(n){return Eu(n)};let hi=li;function Je(n){const e=Ne(n,"data");return z(hi(e))}Je._=li,Je.lock=function(){ui=!0},Je.register=function(n){if(ui)throw new TypeError("keccak256 is locked");hi=n},Object.freeze(Je);const xu=BigInt(0),Tu=BigInt(36);function fi(n){n=n.toLowerCase();const e=n.substring(2).split(""),t=new Uint8Array(40);for(let s=0;s<40;s++)t[s]=e[s].charCodeAt(0);const r=Ne(Je(t));for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&(e[s]=e[s].toUpperCase()),(r[s>>1]&15)>=8&&(e[s+1]=e[s+1].toUpperCase());return"0x"+e.join("")}const $n={};for(let n=0;n<10;n++)$n[String(n)]=String(n);for(let n=0;n<26;n++)$n[String.fromCharCode(65+n)]=String(10+n);const di=15;function Ou(n){n=n.toUpperCase(),n=n.substring(4)+n.substring(0,2)+"00";let e=n.split("").map(r=>$n[r]).join("");for(;e.length>=di;){let r=e.substring(0,di);e=parseInt(r,10)%97+e.substring(r.length)}let t=String(98-parseInt(e,10)%97);for(;t.length<2;)t="0"+t;return t}const ku=function(){const n={};for(let e=0;e<36;e++){const t="0123456789abcdefghijklmnopqrstuvwxyz"[e];n[t]=BigInt(e)}return n}();function Au(n){n=n.toLowerCase();let e=xu;for(let t=0;t<n.length;t++)e=e*Tu+ku[n[t]];return e}function ft(n){if(_(typeof n=="string","invalid address","address",n),n.match(/^(0x)?[0-9a-fA-F]{40}$/)){n.startsWith("0x")||(n="0x"+n);const e=fi(n);return _(!n.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||e===n,"bad address checksum","address",n),e}if(n.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){_(n.substring(2,4)===Ou(n),"bad icap checksum","address",n);let e=Au(n.substring(4)).toString(16);for(;e.length<40;)e="0"+e;return fi("0x"+e)}_(!1,"invalid address","address",n)}function Su(n){return n&&typeof n.getAddress=="function"}async function Pn(n,e){const t=await e;return(t==null||t==="0x0000000000000000000000000000000000000000")&&(x(typeof n!="string","unconfigured name","UNCONFIGURED_NAME",{value:n}),_(!1,"invalid AddressLike value; did not resolve to a value address","target",n)),ft(t)}function Nn(n,e){if(typeof n=="string")return n.match(/^0x[0-9a-f]{40}$/i)?ft(n):(x(e!=null,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),Pn(n,e.resolveName(n)));if(Su(n))return Pn(n,n.getAddress());if(n&&typeof n.then=="function")return Pn(n,n);_(!1,"unsupported addressable value","target",n)}const De={};function E(n,e){let t=!1;return e<0&&(t=!0,e*=-1),new X(De,`${t?"":"u"}int${e}`,n,{signed:t,width:e})}function $(n,e){return new X(De,`bytes${e||""}`,n,{size:e})}const pi=Symbol.for("_ethers_typed"),Ve=class{constructor(e,t,r,s){d(this,"type");d(this,"value");j(this,vt,void 0);d(this,"_typedSymbol");s==null&&(s=null),xn(De,e,"Typed"),A(this,{_typedSymbol:pi,type:t,value:r}),N(this,vt,s),this.format()}format(){if(this.type==="array")throw new Error("");if(this.type==="dynamicArray")throw new Error("");return this.type==="tuple"?`tuple(${this.value.map(e=>e.format()).join(",")})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return this.type==="string"}get tupleName(){if(this.type!=="tuple")throw TypeError("not a tuple");return m(this,vt)}get arrayLength(){if(this.type!=="array")throw TypeError("not an array");return m(this,vt)===!0?-1:m(this,vt)===!1?this.value.length:null}static from(e,t){return new Ve(De,e,t)}static uint8(e){return E(e,8)}static uint16(e){return E(e,16)}static uint24(e){return E(e,24)}static uint32(e){return E(e,32)}static uint40(e){return E(e,40)}static uint48(e){return E(e,48)}static uint56(e){return E(e,56)}static uint64(e){return E(e,64)}static uint72(e){return E(e,72)}static uint80(e){return E(e,80)}static uint88(e){return E(e,88)}static uint96(e){return E(e,96)}static uint104(e){return E(e,104)}static uint112(e){return E(e,112)}static uint120(e){return E(e,120)}static uint128(e){return E(e,128)}static uint136(e){return E(e,136)}static uint144(e){return E(e,144)}static uint152(e){return E(e,152)}static uint160(e){return E(e,160)}static uint168(e){return E(e,168)}static uint176(e){return E(e,176)}static uint184(e){return E(e,184)}static uint192(e){return E(e,192)}static uint200(e){return E(e,200)}static uint208(e){return E(e,208)}static uint216(e){return E(e,216)}static uint224(e){return E(e,224)}static uint232(e){return E(e,232)}static uint240(e){return E(e,240)}static uint248(e){return E(e,248)}static uint256(e){return E(e,256)}static uint(e){return E(e,256)}static int8(e){return E(e,-8)}static int16(e){return E(e,-16)}static int24(e){return E(e,-24)}static int32(e){return E(e,-32)}static int40(e){return E(e,-40)}static int48(e){return E(e,-48)}static int56(e){return E(e,-56)}static int64(e){return E(e,-64)}static int72(e){return E(e,-72)}static int80(e){return E(e,-80)}static int88(e){return E(e,-88)}static int96(e){return E(e,-96)}static int104(e){return E(e,-104)}static int112(e){return E(e,-112)}static int120(e){return E(e,-120)}static int128(e){return E(e,-128)}static int136(e){return E(e,-136)}static int144(e){return E(e,-144)}static int152(e){return E(e,-152)}static int160(e){return E(e,-160)}static int168(e){return E(e,-168)}static int176(e){return E(e,-176)}static int184(e){return E(e,-184)}static int192(e){return E(e,-192)}static int200(e){return E(e,-200)}static int208(e){return E(e,-208)}static int216(e){return E(e,-216)}static int224(e){return E(e,-224)}static int232(e){return E(e,-232)}static int240(e){return E(e,-240)}static int248(e){return E(e,-248)}static int256(e){return E(e,-256)}static int(e){return E(e,-256)}static bytes1(e){return $(e,1)}static bytes2(e){return $(e,2)}static bytes3(e){return $(e,3)}static bytes4(e){return $(e,4)}static bytes5(e){return $(e,5)}static bytes6(e){return $(e,6)}static bytes7(e){return $(e,7)}static bytes8(e){return $(e,8)}static bytes9(e){return $(e,9)}static bytes10(e){return $(e,10)}static bytes11(e){return $(e,11)}static bytes12(e){return $(e,12)}static bytes13(e){return $(e,13)}static bytes14(e){return $(e,14)}static bytes15(e){return $(e,15)}static bytes16(e){return $(e,16)}static bytes17(e){return $(e,17)}static bytes18(e){return $(e,18)}static bytes19(e){return $(e,19)}static bytes20(e){return $(e,20)}static bytes21(e){return $(e,21)}static bytes22(e){return $(e,22)}static bytes23(e){return $(e,23)}static bytes24(e){return $(e,24)}static bytes25(e){return $(e,25)}static bytes26(e){return $(e,26)}static bytes27(e){return $(e,27)}static bytes28(e){return $(e,28)}static bytes29(e){return $(e,29)}static bytes30(e){return $(e,30)}static bytes31(e){return $(e,31)}static bytes32(e){return $(e,32)}static address(e){return new Ve(De,"address",e)}static bool(e){return new Ve(De,"bool",!!e)}static bytes(e){return new Ve(De,"bytes",e)}static string(e){return new Ve(De,"string",e)}static array(e,t){throw new Error("not implemented yet")}static tuple(e,t){throw new Error("not implemented yet")}static overrides(e){return new Ve(De,"overrides",Object.assign({},e))}static isTyped(e){return e&&e._typedSymbol===pi}static dereference(e,t){if(Ve.isTyped(e)){if(e.type!==t)throw new Error(`invalid type: expecetd ${t}, got ${e.type}`);return e.value}return e}};let X=Ve;vt=new WeakMap;class Ru extends Fe{constructor(e){super("address","address",e,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(e,t){let r=X.dereference(t,"string");try{r=ft(r)}catch(s){return this._throwError(s.message,t)}return e.writeValue(r)}decode(e){return ft(Zs(e.readValue(),20))}}class $u extends Fe{constructor(t){super(t.name,t.type,"_",t.dynamic);d(this,"coder");this.coder=t}defaultValue(){return this.coder.defaultValue()}encode(t,r){return this.coder.encode(t,r)}decode(t){return this.coder.decode(t)}}function yi(n,e,t){let r=[];if(Array.isArray(t))r=t;else if(t&&typeof t=="object"){let c={};r=e.map(u=>{const l=u.localName;return x(l,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:u},value:t}),x(!c[l],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:u},value:t}),c[l]=!0,t[l]})}else _(!1,"invalid tuple value","tuple",t);_(e.length===r.length,"types/value length mismatch","tuple",t);let s=new On,i=new On,o=[];e.forEach((c,u)=>{let l=r[u];if(c.dynamic){let h=i.length;c.encode(i,l);let y=s.writeUpdatableValue();o.push(p=>{y(p+h)})}else c.encode(s,l)}),o.forEach(c=>{c(s.length)});let a=n.appendWriter(s);return a+=n.appendWriter(i),a}function mi(n,e){let t=[],r=[],s=n.subReader(0);return e.forEach(i=>{let o=null;if(i.dynamic){let a=n.readIndex(),c=s.subReader(a);try{o=i.decode(c)}catch(u){if(Tr(u,"BUFFER_OVERRUN"))throw u;o=u,o.baseType=i.name,o.name=i.localName,o.type=i.type}}else try{o=i.decode(n)}catch(a){if(Tr(a,"BUFFER_OVERRUN"))throw a;o=a,o.baseType=i.name,o.name=i.localName,o.type=i.type}if(o==null)throw new Error("investigate");t.push(o),r.push(i.localName||null)}),Pr.fromItems(t,r)}class Pu extends Fe{constructor(t,r,s){const i=t.type+"["+(r>=0?r:"")+"]",o=r===-1||t.dynamic;super("array",i,s,o);d(this,"coder");d(this,"length");A(this,{coder:t,length:r})}defaultValue(){const t=this.coder.defaultValue(),r=[];for(let s=0;s<this.length;s++)r.push(t);return r}encode(t,r){const s=X.dereference(r,"array");Array.isArray(s)||this._throwError("expected array value",s);let i=this.length;i===-1&&(i=s.length,t.writeValue(s.length)),Gs(s.length,i,"coder array"+(this.localName?" "+this.localName:""));let o=[];for(let a=0;a<s.length;a++)o.push(this.coder);return yi(t,o,s)}decode(t){let r=this.length;r===-1&&(r=t.readIndex(),x(r*Q<=t.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:t.bytes,offset:r*Q,length:t.dataLength}));let s=[];for(let i=0;i<r;i++)s.push(new $u(this.coder));return mi(t,s)}}class Nu extends Fe{constructor(e){super("bool","bool",e,!1)}defaultValue(){return!1}encode(e,t){const r=X.dereference(t,"bool");return e.writeValue(r?1:0)}decode(e){return!!e.readValue()}}class gi extends Fe{constructor(e,t){super(e,e,t,!0)}defaultValue(){return"0x"}encode(e,t){t=Ie(t);let r=e.writeValue(t.length);return r+=e.writeBytes(t),r}decode(e){return e.readBytes(e.readIndex(),!0)}}class Iu extends gi{constructor(e){super("bytes",e)}decode(e){return z(super.decode(e))}}class Cu extends Fe{constructor(t,r){let s="bytes"+String(t);super(s,s,r,!1);d(this,"size");A(this,{size:t},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+this.size*2)}encode(t,r){let s=Ie(X.dereference(r,this.type));return s.length!==this.size&&this._throwError("incorrect data length",r),t.writeBytes(s)}decode(t){return z(t.readBytes(this.size))}}const Fu=new Uint8Array([]);class Du extends Fe{constructor(e){super("null","",e,!1)}defaultValue(){return null}encode(e,t){return t!=null&&this._throwError("not null",t),e.writeBytes(Fu)}decode(e){return e.readBytes(0),null}}const Uu=BigInt(0),ju=BigInt(1),Lu=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class Bu extends Fe{constructor(t,r,s){const i=(r?"int":"uint")+t*8;super(i,i,s,!1);d(this,"size");d(this,"signed");A(this,{size:t,signed:r},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(t,r){let s=ht(X.dereference(r,this.type)),i=Ar(Lu,Q*8);if(this.signed){let o=Ar(i,this.size*8-1);(s>o||s<-(o+ju))&&this._throwError("value out-of-bounds",r),s=Ic(s,8*Q)}else(s<Uu||s>Ar(i,this.size*8))&&this._throwError("value out-of-bounds",r);return t.writeValue(s)}decode(t){let r=Ar(t.readValue(),this.size*8);return this.signed&&(r=Nc(r,this.size*8)),r}}class Hu extends gi{constructor(e){super("string",e)}defaultValue(){return""}encode(e,t){return super.encode(e,Qs(X.dereference(t,"string")))}decode(e){return Mc(super.decode(e))}}class Cr extends Fe{constructor(t,r){let s=!1;const i=[];t.forEach(a=>{a.dynamic&&(s=!0),i.push(a.type)});const o="tuple("+i.join(",")+")";super("tuple",o,r,s);d(this,"coders");A(this,{coders:Object.freeze(t.slice())})}defaultValue(){const t=[];this.coders.forEach(s=>{t.push(s.defaultValue())});const r=this.coders.reduce((s,i)=>{const o=i.localName;return o&&(s[o]||(s[o]=0),s[o]++),s},{});return this.coders.forEach((s,i)=>{let o=s.localName;!o||r[o]!==1||(o==="length"&&(o="_length"),t[o]==null&&(t[o]=t[i]))}),Object.freeze(t)}encode(t,r){const s=X.dereference(r,"tuple");return yi(t,this.coders,s)}decode(t){return mi(t,this.coders)}}function Wt(n){return Je(Qs(n))}function In(n,e){return{address:ft(n),storageKeys:e.map((t,r)=>(_(qe(t,32),"invalid slot",`storageKeys[${r}]`,t),t.toLowerCase()))}}function Mu(n){if(Array.isArray(n))return n.map((t,r)=>Array.isArray(t)?(_(t.length===2,"invalid slot set",`value[${r}]`,t),In(t[0],t[1])):(_(t!=null&&typeof t=="object","invalid address-slot set","value",n),In(t.address,t.storageKeys)));_(n!=null&&typeof n=="object","invalid access list","value",n);const e=Object.keys(n).map(t=>{const r=n[t].reduce((s,i)=>(s[i]=!0,s),{});return In(t,Object.keys(r).sort())});return e.sort((t,r)=>t.address.localeCompare(r.address)),e}function ee(n){const e=new Set;return n.forEach(t=>e.add(t)),Object.freeze(e)}const wi="constant external internal payable private public pure view",Vu=ee(wi.split(" ")),bi="constructor error event fallback function receive struct",vi=ee(bi.split(" ")),_i="calldata memory storage payable indexed",zu=ee(_i.split(" ")),qu=[bi,_i,"tuple returns",wi].join(" "),Gu=ee(qu.split(" ")),Ju={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},Wu=new RegExp("^(\\s*)"),Ku=new RegExp("^([0-9]+)"),Xu=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),Ei=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),xi=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$"),Br=class{constructor(e){j(this,er);j(this,J,void 0);j(this,ve,void 0);N(this,J,0),N(this,ve,e.slice())}get offset(){return m(this,J)}get length(){return m(this,ve).length-m(this,J)}clone(){return new Br(m(this,ve))}reset(){N(this,J,0)}popKeyword(e){const t=this.peek();if(t.type!=="KEYWORD"||!e.has(t.text))throw new Error(`expected keyword ${t.text}`);return this.pop().text}popType(e){if(this.peek().type!==e)throw new Error(`expected ${e}; got ${JSON.stringify(this.peek())}`);return this.pop().text}popParen(){const e=this.peek();if(e.type!=="OPEN_PAREN")throw new Error("bad start");const t=V(this,er,Qn).call(this,m(this,J)+1,e.match+1);return N(this,J,e.match+1),t}popParams(){const e=this.peek();if(e.type!=="OPEN_PAREN")throw new Error("bad start");const t=[];for(;m(this,J)<e.match-1;){const r=this.peek().linkNext;t.push(V(this,er,Qn).call(this,m(this,J)+1,r)),N(this,J,r)}return N(this,J,e.match+1),t}peek(){if(m(this,J)>=m(this,ve).length)throw new Error("out-of-bounds");return m(this,ve)[m(this,J)]}peekKeyword(e){const t=this.peekType("KEYWORD");return t!=null&&e.has(t)?t:null}peekType(e){if(this.length===0)return null;const t=this.peek();return t.type===e?t.text:null}pop(){const e=this.peek();return eo(this,J)._++,e}toString(){const e=[];for(let t=m(this,J);t<m(this,ve).length;t++){const r=m(this,ve)[t];e.push(`${r.type}:${r.text}`)}return`<TokenString ${e.join(" ")}>`}};let we=Br;J=new WeakMap,ve=new WeakMap,er=new WeakSet,Qn=function(e=0,t=0){return new Br(m(this,ve).slice(e,t).map(r=>Object.freeze(Object.assign({},r,{match:r.match-e,linkBack:r.linkBack-e,linkNext:r.linkNext-e}))))};function We(n){const e=[],t=o=>{const a=i<n.length?JSON.stringify(n[i]):"$EOI";throw new Error(`invalid token ${a} at ${i}: ${o}`)};let r=[],s=[],i=0;for(;i<n.length;){let o=n.substring(i),a=o.match(Wu);a&&(i+=a[1].length,o=n.substring(i));const c={depth:r.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:i,value:-1};e.push(c);let u=Ju[o[0]]||"";if(u){if(c.type=u,c.text=o[0],i++,u==="OPEN_PAREN")r.push(e.length-1),s.push(e.length-1);else if(u=="CLOSE_PAREN")r.length===0&&t("no matching open bracket"),c.match=r.pop(),e[c.match].match=e.length-1,c.depth--,c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1;else if(u==="COMMA")c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1,s.push(e.length-1);else if(u==="OPEN_BRACKET")c.type="BRACKET";else if(u==="CLOSE_BRACKET"){let l=e.pop().text;if(e.length>0&&e[e.length-1].type==="NUMBER"){const h=e.pop().text;l=h+l,e[e.length-1].value=Ce(h)}if(e.length===0||e[e.length-1].type!=="BRACKET")throw new Error("missing opening bracket");e[e.length-1].text+=l}continue}if(a=o.match(Xu),a){if(c.text=a[1],i+=c.text.length,Gu.has(c.text)){c.type="KEYWORD";continue}if(c.text.match(xi)){c.type="TYPE";continue}c.type="ID";continue}if(a=o.match(Ku),a){c.text=a[1],c.type="NUMBER",i+=c.text.length;continue}throw new Error(`unexpected token ${JSON.stringify(o[0])} at position ${i}`)}return new we(e.map(o=>Object.freeze(o)))}function Ti(n,e){let t=[];for(const r in e.keys())n.has(r)&&t.push(r);if(t.length>1)throw new Error(`conflicting types: ${t.join(", ")}`)}function Fr(n,e){if(e.peekKeyword(vi)){const t=e.pop().text;if(t!==n)throw new Error(`expected ${n}, got ${t}`)}return e.popType("ID")}function Ue(n,e){const t=new Set;for(;;){const r=n.peekType("KEYWORD");if(r==null||e&&!e.has(r))break;if(n.pop(),t.has(r))throw new Error(`duplicate keywords: ${JSON.stringify(r)}`);t.add(r)}return Object.freeze(t)}function Oi(n){let e=Ue(n,Vu);return Ti(e,ee("constant payable nonpayable".split(" "))),Ti(e,ee("pure view payable nonpayable".split(" "))),e.has("view")?"view":e.has("pure")?"pure":e.has("payable")?"payable":e.has("nonpayable")?"nonpayable":e.has("constant")?"view":"nonpayable"}function je(n,e){return n.popParams().map(t=>G.from(t,e))}function ki(n){if(n.peekType("AT")){if(n.pop(),n.peekType("NUMBER"))return ht(n.pop().text);throw new Error("invalid gas")}return null}function dt(n){if(n.length)throw new Error(`unexpected tokens: ${n.toString()}`)}const Zu=new RegExp(/^(.*)\[([0-9]*)\]$/);function Ai(n){const e=n.match(xi);if(_(e,"invalid type","type",n),n==="uint")return"uint256";if(n==="int")return"int256";if(e[2]){const t=parseInt(e[2]);_(t!==0&&t<=32,"invalid bytes length","type",n)}else if(e[3]){const t=parseInt(e[3]);_(t!==0&&t<=256&&t%8===0,"invalid numeric width","type",n)}return n}const B={},ie=Symbol.for("_ethers_internal"),Si="_ParamTypeInternal",Ri="_ErrorInternal",$i="_EventInternal",Pi="_ConstructorInternal",Ni="_FallbackInternal",Ii="_FunctionInternal",Ci="_StructInternal",pe=class{constructor(e,t,r,s,i,o,a,c){j(this,Ft);d(this,"name");d(this,"type");d(this,"baseType");d(this,"indexed");d(this,"components");d(this,"arrayLength");d(this,"arrayChildren");if(xn(e,B,"ParamType"),Object.defineProperty(this,ie,{value:Si}),o&&(o=Object.freeze(o.slice())),s==="array"){if(a==null||c==null)throw new Error("")}else if(a!=null||c!=null)throw new Error("");if(s==="tuple"){if(o==null)throw new Error("")}else if(o!=null)throw new Error("");A(this,{name:t,type:r,baseType:s,indexed:i,components:o,arrayLength:a,arrayChildren:c})}format(e){if(e==null&&(e="sighash"),e==="json"){let r={type:this.baseType==="tuple"?"tuple":this.type,name:this.name||void 0};return typeof this.indexed=="boolean"&&(r.indexed=this.indexed),this.isTuple()&&(r.components=this.components.map(s=>JSON.parse(s.format(e)))),JSON.stringify(r)}let t="";return this.isArray()?(t+=this.arrayChildren.format(e),t+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?(e!=="sighash"&&(t+=this.type),t+="("+this.components.map(r=>r.format(e)).join(e==="full"?", ":",")+")"):t+=this.type,e!=="sighash"&&(this.indexed===!0&&(t+=" indexed"),e==="full"&&this.name&&(t+=" "+this.name)),t}isArray(){return this.baseType==="array"}isTuple(){return this.baseType==="tuple"}isIndexable(){return this.indexed!=null}walk(e,t){if(this.isArray()){if(!Array.isArray(e))throw new Error("invalid array value");if(this.arrayLength!==-1&&e.length!==this.arrayLength)throw new Error("array is wrong length");const r=this;return e.map(s=>r.arrayChildren.walk(s,t))}if(this.isTuple()){if(!Array.isArray(e))throw new Error("invalid tuple value");if(e.length!==this.components.length)throw new Error("array is wrong length");const r=this;return e.map((s,i)=>r.components[i].walk(s,t))}return t(this.type,e)}async walkAsync(e,t){const r=[],s=[e];return V(this,Ft,Wr).call(this,r,e,t,i=>{s[0]=i}),r.length&&await Promise.all(r),s[0]}static from(e,t){if(pe.isParamType(e))return e;if(typeof e=="string")return pe.from(We(e),t);if(e instanceof we){let a="",c="",u=null;Ue(e,ee(["tuple"])).has("tuple")||e.peekType("OPEN_PAREN")?(c="tuple",u=e.popParams().map(v=>pe.from(v)),a=`tuple(${u.map(v=>v.format()).join(",")})`):(a=Ai(e.popType("TYPE")),c=a);let l=null,h=null;for(;e.length&&e.peekType("BRACKET");){const v=e.pop();l=new pe(B,"",a,c,null,u,h,l),h=v.value,a+=v.text,c="array",u=null}let y=null;if(Ue(e,zu).has("indexed")){if(!t)throw new Error("");y=!0}const w=e.peekType("ID")?e.pop().text:"";if(e.length)throw new Error("leftover tokens");return new pe(B,w,a,c,y,u,h,l)}const r=e.name;_(!r||typeof r=="string"&&r.match(Ei),"invalid name","obj.name",r);let s=e.indexed;s!=null&&(_(t,"parameter cannot be indexed","obj.indexed",e.indexed),s=!!s);let i=e.type,o=i.match(Zu);if(o){const a=parseInt(o[2]||"-1"),c=pe.from({type:o[1],components:e.components});return new pe(B,r||"",i,"array",s,null,a,c)}if(i==="tuple"||i.startsWith("tuple(")||i.startsWith("(")){const a=e.components!=null?e.components.map(u=>pe.from(u)):null;return new pe(B,r||"",i,"tuple",s,a,null,null)}return i=Ai(e.type),new pe(B,r||"",i,i,s,null,null,null)}static isParamType(e){return e&&e[ie]===Si}};let G=pe;Ft=new WeakSet,Wr=function(e,t,r,s){if(this.isArray()){if(!Array.isArray(t))throw new Error("invalid array value");if(this.arrayLength!==-1&&t.length!==this.arrayLength)throw new Error("array is wrong length");const o=this.arrayChildren,a=t.slice();a.forEach((c,u)=>{var l;V(l=o,Ft,Wr).call(l,e,c,r,h=>{a[u]=h})}),s(a);return}if(this.isTuple()){const o=this.components;let a;if(Array.isArray(t))a=t.slice();else{if(t==null||typeof t!="object")throw new Error("invalid tuple value");a=o.map(c=>{if(!c.name)throw new Error("cannot use object value with unnamed components");if(!(c.name in t))throw new Error(`missing value for component ${c.name}`);return t[c.name]})}if(a.length!==this.components.length)throw new Error("array is wrong length");a.forEach((c,u)=>{var l;V(l=o[u],Ft,Wr).call(l,e,c,r,h=>{a[u]=h})}),s(a);return}const i=r(this.type,t);i.then?e.push(async function(){s(await i)}()):s(i)};class pt{constructor(e,t,r){d(this,"type");d(this,"inputs");xn(e,B,"Fragment"),r=Object.freeze(r.slice()),A(this,{type:t,inputs:r})}static from(e){if(typeof e=="string"){try{pt.from(JSON.parse(e))}catch{}return pt.from(We(e))}if(e instanceof we)switch(e.peekKeyword(vi)){case"constructor":return Le.from(e);case"error":return oe.from(e);case"event":return Te.from(e);case"fallback":case"receive":return Be.from(e);case"function":return Oe.from(e);case"struct":return yt.from(e)}else if(typeof e=="object"){switch(e.type){case"constructor":return Le.from(e);case"error":return oe.from(e);case"event":return Te.from(e);case"fallback":case"receive":return Be.from(e);case"function":return Oe.from(e);case"struct":return yt.from(e)}x(!1,`unsupported type: ${e.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}_(!1,"unsupported frgament object","obj",e)}static isConstructor(e){return Le.isFragment(e)}static isError(e){return oe.isFragment(e)}static isEvent(e){return Te.isFragment(e)}static isFunction(e){return Oe.isFragment(e)}static isStruct(e){return yt.isFragment(e)}}class Dr extends pt{constructor(t,r,s,i){super(t,r,i);d(this,"name");_(typeof s=="string"&&s.match(Ei),"invalid identifier","name",s),i=Object.freeze(i.slice()),A(this,{name:s})}}function Kt(n,e){return"("+e.map(t=>t.format(n)).join(n==="full"?", ":",")+")"}class oe extends Dr{constructor(e,t,r){super(e,"error",t,r),Object.defineProperty(this,ie,{value:Ri})}get selector(){return Wt(this.format("sighash")).substring(0,10)}format(e){if(e==null&&(e="sighash"),e==="json")return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(r=>JSON.parse(r.format(e)))});const t=[];return e!=="sighash"&&t.push("error"),t.push(this.name+Kt(e,this.inputs)),t.join(" ")}static from(e){if(oe.isFragment(e))return e;if(typeof e=="string")return oe.from(We(e));if(e instanceof we){const t=Fr("error",e),r=je(e);return dt(e),new oe(B,t,r)}return new oe(B,e.name,e.inputs?e.inputs.map(G.from):[])}static isFragment(e){return e&&e[ie]===Ri}}class Te extends Dr{constructor(t,r,s,i){super(t,"event",r,s);d(this,"anonymous");Object.defineProperty(this,ie,{value:$i}),A(this,{anonymous:i})}get topicHash(){return Wt(this.format("sighash"))}format(t){if(t==null&&(t="sighash"),t==="json")return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(s=>JSON.parse(s.format(t)))});const r=[];return t!=="sighash"&&r.push("event"),r.push(this.name+Kt(t,this.inputs)),t!=="sighash"&&this.anonymous&&r.push("anonymous"),r.join(" ")}static getTopicHash(t,r){return r=(r||[]).map(i=>G.from(i)),new Te(B,t,r,!1).topicHash}static from(t){if(Te.isFragment(t))return t;if(typeof t=="string")return Te.from(We(t));if(t instanceof we){const r=Fr("event",t),s=je(t,!0),i=!!Ue(t,ee(["anonymous"])).has("anonymous");return dt(t),new Te(B,r,s,i)}return new Te(B,t.name,t.inputs?t.inputs.map(r=>G.from(r,!0)):[],!!t.anonymous)}static isFragment(t){return t&&t[ie]===$i}}class Le extends pt{constructor(t,r,s,i,o){super(t,r,s);d(this,"payable");d(this,"gas");Object.defineProperty(this,ie,{value:Pi}),A(this,{payable:i,gas:o})}format(t){if(x(t!=null&&t!=="sighash","cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),t==="json")return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(s=>JSON.parse(s.format(t)))});const r=[`constructor${Kt(t,this.inputs)}`];return r.push(this.payable?"payable":"nonpayable"),this.gas!=null&&r.push(`@${this.gas.toString()}`),r.join(" ")}static from(t){if(Le.isFragment(t))return t;if(typeof t=="string")return Le.from(We(t));if(t instanceof we){Ue(t,ee(["constructor"]));const r=je(t),s=!!Ue(t,ee(["payable"])).has("payable"),i=ki(t);return dt(t),new Le(B,"constructor",r,s,i)}return new Le(B,"constructor",t.inputs?t.inputs.map(G.from):[],!!t.payable,t.gas!=null?t.gas:null)}static isFragment(t){return t&&t[ie]===Pi}}class Be extends pt{constructor(t,r,s){super(t,"fallback",r);d(this,"payable");Object.defineProperty(this,ie,{value:Ni}),A(this,{payable:s})}format(t){const r=this.inputs.length===0?"receive":"fallback";if(t==="json"){const s=this.payable?"payable":"nonpayable";return JSON.stringify({type:r,stateMutability:s})}return`${r}()${this.payable?" payable":""}`}static from(t){if(Be.isFragment(t))return t;if(typeof t=="string")return Be.from(We(t));if(t instanceof we){const r=t.toString(),s=t.peekKeyword(ee(["fallback","receive"]));if(_(s,"type must be fallback or receive","obj",r),t.popKeyword(ee(["fallback","receive"]))==="receive"){const c=je(t);return _(c.length===0,"receive cannot have arguments","obj.inputs",c),Ue(t,ee(["payable"])),dt(t),new Be(B,[],!0)}let o=je(t);o.length?_(o.length===1&&o[0].type==="bytes","invalid fallback inputs","obj.inputs",o.map(c=>c.format("minimal")).join(", ")):o=[G.from("bytes")];const a=Oi(t);if(_(a==="nonpayable"||a==="payable","fallback cannot be constants","obj.stateMutability",a),Ue(t,ee(["returns"])).has("returns")){const c=je(t);_(c.length===1&&c[0].type==="bytes","invalid fallback outputs","obj.outputs",c.map(u=>u.format("minimal")).join(", "))}return dt(t),new Be(B,o,a==="payable")}if(t.type==="receive")return new Be(B,[],!0);if(t.type==="fallback"){const r=[G.from("bytes")],s=t.stateMutability==="payable";return new Be(B,r,s)}_(!1,"invalid fallback description","obj",t)}static isFragment(t){return t&&t[ie]===Ni}}class Oe extends Dr{constructor(t,r,s,i,o,a){super(t,"function",r,i);d(this,"constant");d(this,"outputs");d(this,"stateMutability");d(this,"payable");d(this,"gas");Object.defineProperty(this,ie,{value:Ii}),o=Object.freeze(o.slice()),A(this,{constant:s==="view"||s==="pure",gas:a,outputs:o,payable:s==="payable",stateMutability:s})}get selector(){return Wt(this.format("sighash")).substring(0,10)}format(t){if(t==null&&(t="sighash"),t==="json")return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:this.stateMutability!=="nonpayable"?this.stateMutability:void 0,payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(s=>JSON.parse(s.format(t))),outputs:this.outputs.map(s=>JSON.parse(s.format(t)))});const r=[];return t!=="sighash"&&r.push("function"),r.push(this.name+Kt(t,this.inputs)),t!=="sighash"&&(this.stateMutability!=="nonpayable"&&r.push(this.stateMutability),this.outputs&&this.outputs.length&&(r.push("returns"),r.push(Kt(t,this.outputs))),this.gas!=null&&r.push(`@${this.gas.toString()}`)),r.join(" ")}static getSelector(t,r){return r=(r||[]).map(i=>G.from(i)),new Oe(B,t,"view",r,[],null).selector}static from(t){if(Oe.isFragment(t))return t;if(typeof t=="string")return Oe.from(We(t));if(t instanceof we){const r=Fr("function",t),s=je(t),i=Oi(t);let o=[];Ue(t,ee(["returns"])).has("returns")&&(o=je(t));const a=ki(t);return dt(t),new Oe(B,r,i,s,o,a)}return new Oe(B,t.name,t.stateMutability,t.inputs?t.inputs.map(G.from):[],t.outputs?t.outputs.map(G.from):[],t.gas!=null?t.gas:null)}static isFragment(t){return t&&t[ie]===Ii}}class yt extends Dr{constructor(e,t,r){super(e,"struct",t,r),Object.defineProperty(this,ie,{value:Ci})}format(){throw new Error("@TODO")}static from(e){if(typeof e=="string")return yt.from(We(e));if(e instanceof we){const t=Fr("struct",e),r=je(e);return dt(e),new yt(B,t,r)}return new yt(B,e.name,e.inputs?e.inputs.map(G.from):[])}static isFragment(e){return e&&e[ie]===Ci}}const be=new Map;be.set(0,"GENERIC_PANIC"),be.set(1,"ASSERT_FALSE"),be.set(17,"OVERFLOW"),be.set(18,"DIVIDE_BY_ZERO"),be.set(33,"ENUM_RANGE_ERROR"),be.set(34,"BAD_STORAGE_DATA"),be.set(49,"STACK_UNDERFLOW"),be.set(50,"ARRAY_RANGE_ERROR"),be.set(65,"OUT_OF_MEMORY"),be.set(81,"UNINITIALIZED_FUNCTION_CALL");const Yu=new RegExp(/^bytes([0-9]*)$/),Qu=new RegExp(/^(u?int)([0-9]*)$/);let Cn=null;function el(n,e,t,r){let s="missing revert data",i=null;const o=null;let a=null;if(t){s="execution reverted";const u=Ne(t);if(t=z(t),u.length===0)s+=" (no data present; likely require(false) occurred",i="require(false)";else if(u.length%32!==4)s+=" (could not decode reason; invalid data length)";else if(z(u.slice(0,4))==="0x08c379a0")try{i=r.decode(["string"],u.slice(4))[0],a={signature:"Error(string)",name:"Error",args:[i]},s+=`: ${JSON.stringify(i)}`}catch{s+=" (could not decode reason; invalid string data)"}else if(z(u.slice(0,4))==="0x4e487b71")try{const l=Number(r.decode(["uint256"],u.slice(4))[0]);a={signature:"Panic(uint256)",name:"Panic",args:[l]},i=`Panic due to ${be.get(l)||"UNKNOWN"}(${l})`,s+=`: ${i}`}catch{s+=" (could not decode panic code)"}else s+=" (unknown custom error)"}const c={to:e.to?ft(e.to):null,data:e.data||"0x"};return e.from&&(c.from=ft(e.from)),Or(s,"CALL_EXCEPTION",{action:n,data:t,reason:i,transaction:c,invocation:o,revert:a})}const Hr=class{constructor(){j(this,Ze)}getDefaultValue(e){const t=e.map(s=>V(this,Ze,Lt).call(this,G.from(s)));return new Cr(t,"_").defaultValue()}encode(e,t){Gs(t.length,e.length,"types/values length mismatch");const r=e.map(o=>V(this,Ze,Lt).call(this,G.from(o))),s=new Cr(r,"_"),i=new On;return s.encode(i,t),i.data}decode(e,t,r){const s=e.map(o=>V(this,Ze,Lt).call(this,G.from(o)));return new Cr(s,"_").decode(new kn(t,r))}static defaultAbiCoder(){return Cn==null&&(Cn=new Hr),Cn}static getBuiltinCallException(e,t,r){return el(e,t,r,Hr.defaultAbiCoder())}};let Ur=Hr;Ze=new WeakSet,Lt=function(e){if(e.isArray())return new Pu(V(this,Ze,Lt).call(this,e.arrayChildren),e.arrayLength,e.name);if(e.isTuple())return new Cr(e.components.map(r=>V(this,Ze,Lt).call(this,r)),e.name);switch(e.baseType){case"address":return new Ru(e.name);case"bool":return new Nu(e.name);case"string":return new Hu(e.name);case"bytes":return new Iu(e.name);case"":return new Du(e.name)}let t=e.type.match(Qu);if(t){let r=parseInt(t[2]||"256");return _(r!==0&&r<=256&&r%8===0,"invalid "+t[1]+" bit length","param",e),new Bu(r/8,t[1]==="int",e.name)}if(t=e.type.match(Yu),t){let r=parseInt(t[1]);return _(r!==0&&r<=32,"invalid bytes length","param",e),new Cu(r,e.name)}_(!1,"invalid type","type",e.type)};class tl{constructor(e,t,r){d(this,"fragment");d(this,"name");d(this,"signature");d(this,"topic");d(this,"args");const s=e.name,i=e.format();A(this,{fragment:e,name:s,signature:i,topic:t,args:r})}}class rl{constructor(e,t,r,s){d(this,"fragment");d(this,"name");d(this,"args");d(this,"signature");d(this,"selector");d(this,"value");const i=e.name,o=e.format();A(this,{fragment:e,name:i,args:r,signature:o,selector:t,value:s})}}class nl{constructor(e,t,r){d(this,"fragment");d(this,"name");d(this,"args");d(this,"signature");d(this,"selector");const s=e.name,i=e.format();A(this,{fragment:e,name:s,args:r,signature:i,selector:t})}}class Fi{constructor(e){d(this,"hash");d(this,"_isIndexed");A(this,{hash:e,_isIndexed:!0})}static isIndexed(e){return!!(e&&e._isIndexed)}}const Di={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"},Ui={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:n=>`reverted with reason string ${JSON.stringify(n)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:n=>{let e="unknown panic code";return n>=0&&n<=255&&Di[n.toString()]&&(e=Di[n.toString()]),`reverted with panic code 0x${n.toString(16)} (${e})`}}},Dt=class{constructor(e){j(this,tr);j(this,rr);d(this,"fragments");d(this,"deploy");d(this,"fallback");d(this,"receive");j(this,ke,void 0);j(this,Ae,void 0);j(this,Se,void 0);j(this,Z,void 0);let t=[];typeof e=="string"?t=JSON.parse(e):t=e,N(this,Se,new Map),N(this,ke,new Map),N(this,Ae,new Map);const r=[];for(const o of t)try{r.push(pt.from(o))}catch(a){console.log("EE",a)}A(this,{fragments:Object.freeze(r)});let s=null,i=!1;N(this,Z,this.getAbiCoder()),this.fragments.forEach((o,a)=>{let c;switch(o.type){case"constructor":if(this.deploy){console.log("duplicate definition - constructor");return}A(this,{deploy:o});return;case"fallback":o.inputs.length===0?i=!0:(_(!s||o.payable!==s.payable,"conflicting fallback fragments",`fragments[${a}]`,o),s=o,i=s.payable);return;case"function":c=m(this,Se);break;case"event":c=m(this,Ae);break;case"error":c=m(this,ke);break;default:return}const u=o.format();c.has(u)||c.set(u,o)}),this.deploy||A(this,{deploy:Le.from("constructor()")}),A(this,{fallback:s,receive:i})}format(e){const t=e?"minimal":"full";return this.fragments.map(s=>s.format(t))}formatJson(){const e=this.fragments.map(t=>t.format("json"));return JSON.stringify(e.map(t=>JSON.parse(t)))}getAbiCoder(){return Ur.defaultAbiCoder()}getFunctionName(e){const t=V(this,tr,es).call(this,e,null,!1);return _(t,"no matching function","key",e),t.name}getFunction(e,t){return V(this,tr,es).call(this,e,t||null,!0)}forEachFunction(e){const t=Array.from(m(this,Se).keys());t.sort((r,s)=>r.localeCompare(s));for(let r=0;r<t.length;r++){const s=t[r];e(m(this,Se).get(s),r)}}getEventName(e){const t=V(this,rr,ts).call(this,e,null,!1);return _(t,"no matching event","key",e),t.name}getEvent(e,t){return V(this,rr,ts).call(this,e,t||null,!0)}forEachEvent(e){const t=Array.from(m(this,Ae).keys());t.sort((r,s)=>r.localeCompare(s));for(let r=0;r<t.length;r++){const s=t[r];e(m(this,Ae).get(s),r)}}getError(e,t){if(qe(e)){const s=e.toLowerCase();if(Ui[s])return oe.from(Ui[s].signature);for(const i of m(this,ke).values())if(s===i.selector)return i;return null}if(e.indexOf("(")===-1){const s=[];for(const[i,o]of m(this,ke))i.split("(")[0]===e&&s.push(o);if(s.length===0)return e==="Error"?oe.from("error Error(string)"):e==="Panic"?oe.from("error Panic(uint256)"):null;if(s.length>1){const i=s.map(o=>JSON.stringify(o.format())).join(", ");_(!1,`ambiguous error description (i.e. ${i})`,"name",e)}return s[0]}if(e=oe.from(e).format(),e==="Error(string)")return oe.from("error Error(string)");if(e==="Panic(uint256)")return oe.from("error Panic(uint256)");const r=m(this,ke).get(e);return r||null}forEachError(e){const t=Array.from(m(this,ke).keys());t.sort((r,s)=>r.localeCompare(s));for(let r=0;r<t.length;r++){const s=t[r];e(m(this,ke).get(s),r)}}_decodeParams(e,t){return m(this,Z).decode(e,t)}_encodeParams(e,t){return m(this,Z).encode(e,t)}encodeDeploy(e){return this._encodeParams(this.deploy.inputs,e||[])}decodeErrorResult(e,t){if(typeof e=="string"){const r=this.getError(e);_(r,"unknown error","fragment",e),e=r}return _($t(t,0,4)===e.selector,`data signature does not match error ${e.name}.`,"data",t),this._decodeParams(e.inputs,$t(t,4))}encodeErrorResult(e,t){if(typeof e=="string"){const r=this.getError(e);_(r,"unknown error","fragment",e),e=r}return Rt([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionData(e,t){if(typeof e=="string"){const r=this.getFunction(e);_(r,"unknown function","fragment",e),e=r}return _($t(t,0,4)===e.selector,`data signature does not match function ${e.name}.`,"data",t),this._decodeParams(e.inputs,$t(t,4))}encodeFunctionData(e,t){if(typeof e=="string"){const r=this.getFunction(e);_(r,"unknown function","fragment",e),e=r}return Rt([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionResult(e,t){if(typeof e=="string"){const i=this.getFunction(e);_(i,"unknown function","fragment",e),e=i}let r="invalid length for result data";const s=Ie(t);if(s.length%32===0)try{return m(this,Z).decode(e.outputs,s)}catch{r="could not decode result data"}x(!1,r,"BAD_DATA",{value:z(s),info:{method:e.name,signature:e.format()}})}makeError(e,t){const r=Ne(e,"data"),s=Ur.getBuiltinCallException("call",t,r),i="execution reverted (unknown custom error)";if(s.message.startsWith(i)){const a=z(r.slice(0,4)),c=this.getError(a);if(c)try{const u=m(this,Z).decode(c.inputs,r.slice(4));s.revert={name:c.name,signature:c.format(),args:u},s.reason=s.revert.signature,s.message=`execution reverted: ${s.reason}`}catch{s.message="execution reverted (coult not decode custom error)"}}const o=this.parseTransaction(t);return o&&(s.invocation={method:o.name,signature:o.signature,args:o.args}),s}encodeFunctionResult(e,t){if(typeof e=="string"){const r=this.getFunction(e);_(r,"unknown function","fragment",e),e=r}return z(m(this,Z).encode(e.outputs,t||[]))}encodeFilterTopics(e,t){if(typeof e=="string"){const i=this.getEvent(e);_(i,"unknown event","eventFragment",e),e=i}x(t.length<=e.inputs.length,`too many arguments for ${e.format()}`,"UNEXPECTED_ARGUMENT",{count:t.length,expectedCount:e.inputs.length});const r=[];e.anonymous||r.push(e.topicHash);const s=(i,o)=>i.type==="string"?Wt(o):i.type==="bytes"?Je(z(o)):(i.type==="bool"&&typeof o=="boolean"&&(o=o?"0x01":"0x00"),i.type.match(/^u?int/)&&(o=Zs(o)),i.type==="address"&&m(this,Z).encode(["address"],[o]),Pc(z(o),32));for(t.forEach((i,o)=>{const a=e.inputs[o];if(!a.indexed){_(i==null,"cannot filter non-indexed parameters; must be null","contract."+a.name,i);return}i==null?r.push(null):a.baseType==="array"||a.baseType==="tuple"?_(!1,"filtering with tuples or arrays not supported","contract."+a.name,i):Array.isArray(i)?r.push(i.map(c=>s(a,c))):r.push(s(a,i))});r.length&&r[r.length-1]===null;)r.pop();return r}encodeEventLog(e,t){if(typeof e=="string"){const o=this.getEvent(e);_(o,"unknown event","eventFragment",e),e=o}const r=[],s=[],i=[];return e.anonymous||r.push(e.topicHash),_(t.length===e.inputs.length,"event arguments/values mismatch","values",t),e.inputs.forEach((o,a)=>{const c=t[a];if(o.indexed)if(o.type==="string")r.push(Wt(c));else if(o.type==="bytes")r.push(Je(c));else{if(o.baseType==="tuple"||o.baseType==="array")throw new Error("not implemented");r.push(m(this,Z).encode([o.type],[c]))}else s.push(o),i.push(c)}),{data:m(this,Z).encode(s,i),topics:r}}decodeEventLog(e,t,r){if(typeof e=="string"){const p=this.getEvent(e);_(p,"unknown event","eventFragment",e),e=p}if(r!=null&&!e.anonymous){const p=e.topicHash;_(qe(r[0],32)&&r[0].toLowerCase()===p,"fragment/topic mismatch","topics[0]",r[0]),r=r.slice(1)}const s=[],i=[],o=[];e.inputs.forEach((p,w)=>{p.indexed?p.type==="string"||p.type==="bytes"||p.baseType==="tuple"||p.baseType==="array"?(s.push(G.from({type:"bytes32",name:p.name})),o.push(!0)):(s.push(p),o.push(!1)):(i.push(p),o.push(!1))});const a=r!=null?m(this,Z).decode(s,Rt(r)):null,c=m(this,Z).decode(i,t,!0),u=[],l=[];let h=0,y=0;return e.inputs.forEach((p,w)=>{let v=null;if(p.indexed)if(a==null)v=new Fi(null);else if(o[w])v=new Fi(a[y++]);else try{v=a[y++]}catch(g){v=g}else try{v=c[h++]}catch(g){v=g}u.push(v),l.push(p.name||null)}),Pr.fromItems(u,l)}parseTransaction(e){const t=Ne(e.data,"tx.data"),r=ht(e.value!=null?e.value:0,"tx.value"),s=this.getFunction(z(t.slice(0,4)));if(!s)return null;const i=m(this,Z).decode(s.inputs,t.slice(4));return new rl(s,s.selector,i,r)}parseCallResult(e){throw new Error("@TODO")}parseLog(e){const t=this.getEvent(e.topics[0]);return!t||t.anonymous?null:new tl(t,t.topicHash,this.decodeEventLog(t,e.data,e.topics))}parseError(e){const t=z(e),r=this.getError($t(t,0,4));if(!r)return null;const s=m(this,Z).decode(r.inputs,$t(t,4));return new nl(r,r.selector,s)}static from(e){return e instanceof Dt?e:typeof e=="string"?new Dt(JSON.parse(e)):typeof e.format=="function"?new Dt(e.format("json")):new Dt(e)}};let Fn=Dt;ke=new WeakMap,Ae=new WeakMap,Se=new WeakMap,Z=new WeakMap,tr=new WeakSet,es=function(e,t,r){if(qe(e)){const i=e.toLowerCase();for(const o of m(this,Se).values())if(i===o.selector)return o;return null}if(e.indexOf("(")===-1){const i=[];for(const[o,a]of m(this,Se))o.split("(")[0]===e&&i.push(a);if(t){const o=t.length>0?t[t.length-1]:null;let a=t.length,c=!0;X.isTyped(o)&&o.type==="overrides"&&(c=!1,a--);for(let u=i.length-1;u>=0;u--){const l=i[u].inputs.length;l!==a&&(!c||l!==a-1)&&i.splice(u,1)}for(let u=i.length-1;u>=0;u--){const l=i[u].inputs;for(let h=0;h<t.length;h++)if(X.isTyped(t[h])){if(h>=l.length){if(t[h].type==="overrides")continue;i.splice(u,1);break}if(t[h].type!==l[h].baseType){i.splice(u,1);break}}}}if(i.length===1&&t&&t.length!==i[0].inputs.length){const o=t[t.length-1];(o==null||Array.isArray(o)||typeof o!="object")&&i.splice(0,1)}if(i.length===0)return null;if(i.length>1&&r){const o=i.map(a=>JSON.stringify(a.format())).join(", ");_(!1,`ambiguous function description (i.e. matches ${o})`,"key",e)}return i[0]}const s=m(this,Se).get(Oe.from(e).format());return s||null},rr=new WeakSet,ts=function(e,t,r){if(qe(e)){const i=e.toLowerCase();for(const o of m(this,Ae).values())if(i===o.topicHash)return o;return null}if(e.indexOf("(")===-1){const i=[];for(const[o,a]of m(this,Ae))o.split("(")[0]===e&&i.push(a);if(t){for(let o=i.length-1;o>=0;o--)i[o].inputs.length<t.length&&i.splice(o,1);for(let o=i.length-1;o>=0;o--){const a=i[o].inputs;for(let c=0;c<t.length;c++)if(X.isTyped(t[c])&&t[c].type!==a[c].baseType){i.splice(o,1);break}}}if(i.length===0)return null;if(i.length>1&&r){const o=i.map(a=>JSON.stringify(a.format())).join(", ");_(!1,`ambiguous event description (i.e. matches ${o})`,"key",e)}return i[0]}const s=m(this,Ae).get(Te.from(e).format());return s||null};const sl=BigInt(0);function He(n){return n==null?null:n.toString()}function il(n){const e={};n.to&&(e.to=n.to),n.from&&(e.from=n.from),n.data&&(e.data=z(n.data));const t="chainId,gasLimit,gasPrice,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const s of t)!(s in n)||n[s]==null||(e[s]=ht(n[s],`request.${s}`));const r="type,nonce".split(/,/);for(const s of r)!(s in n)||n[s]==null||(e[s]=Ce(n[s],`request.${s}`));return n.accessList&&(e.accessList=Mu(n.accessList)),"blockTag"in n&&(e.blockTag=n.blockTag),"enableCcipRead"in n&&(e.enableCcipReadEnabled=!!n.enableCcipRead),"customData"in n&&(e.customData=n.customData),e}class Dn{constructor(e,t){d(this,"provider");d(this,"transactionHash");d(this,"blockHash");d(this,"blockNumber");d(this,"removed");d(this,"address");d(this,"data");d(this,"topics");d(this,"index");d(this,"transactionIndex");this.provider=t;const r=Object.freeze(e.topics.slice());A(this,{transactionHash:e.transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,removed:e.removed,address:e.address,data:e.data,topics:r,index:e.index,transactionIndex:e.transactionIndex})}toJSON(){const{address:e,blockHash:t,blockNumber:r,data:s,index:i,removed:o,topics:a,transactionHash:c,transactionIndex:u}=this;return{_type:"log",address:e,blockHash:t,blockNumber:r,data:s,index:i,removed:o,topics:a,transactionHash:c,transactionIndex:u}}async getBlock(){const e=await this.provider.getBlock(this.blockHash);return x(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransaction(){const e=await this.provider.getTransaction(this.transactionHash);return x(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransactionReceipt(){const e=await this.provider.getTransactionReceipt(this.transactionHash);return x(!!e,"failed to find transaction receipt","UNKNOWN_ERROR",{}),e}removedEvent(){return al(this)}}class ol{constructor(e,t){d(this,"provider");d(this,"to");d(this,"from");d(this,"contractAddress");d(this,"hash");d(this,"index");d(this,"blockHash");d(this,"blockNumber");d(this,"logsBloom");d(this,"gasUsed");d(this,"cumulativeGasUsed");d(this,"gasPrice");d(this,"type");d(this,"status");d(this,"root");j(this,nr,void 0);N(this,nr,Object.freeze(e.logs.map(r=>new Dn(r,t)))),A(this,{provider:t,to:e.to,from:e.from,contractAddress:e.contractAddress,hash:e.hash,index:e.index,blockHash:e.blockHash,blockNumber:e.blockNumber,logsBloom:e.logsBloom,gasUsed:e.gasUsed,cumulativeGasUsed:e.cumulativeGasUsed,gasPrice:e.effectiveGasPrice||e.gasPrice,type:e.type,status:e.status,root:e.root})}get logs(){return m(this,nr)}toJSON(){const{to:e,from:t,contractAddress:r,hash:s,index:i,blockHash:o,blockNumber:a,logsBloom:c,logs:u,status:l,root:h}=this;return{_type:"TransactionReceipt",blockHash:o,blockNumber:a,contractAddress:r,cumulativeGasUsed:He(this.cumulativeGasUsed),from:t,gasPrice:He(this.gasPrice),gasUsed:He(this.gasUsed),hash:s,index:i,logs:u,logsBloom:c,root:h,status:l,to:e}}get length(){return this.logs.length}[Symbol.iterator](){let e=0;return{next:()=>e<this.length?{value:this.logs[e++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const e=await this.provider.getBlock(this.blockHash);if(e==null)throw new Error("TODO");return e}async getTransaction(){const e=await this.provider.getTransaction(this.hash);if(e==null)throw new Error("TODO");return e}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return Li(this)}reorderedEvent(e){return x(!e||e.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),ji(this,e)}}nr=new WeakMap;const Xn=class{constructor(e,t){d(this,"provider");d(this,"blockNumber");d(this,"blockHash");d(this,"index");d(this,"hash");d(this,"type");d(this,"to");d(this,"from");d(this,"nonce");d(this,"gasLimit");d(this,"gasPrice");d(this,"maxPriorityFeePerGas");d(this,"maxFeePerGas");d(this,"data");d(this,"value");d(this,"chainId");d(this,"signature");d(this,"accessList");j(this,Ye,void 0);this.provider=t,this.blockNumber=e.blockNumber!=null?e.blockNumber:null,this.blockHash=e.blockHash!=null?e.blockHash:null,this.hash=e.hash,this.index=e.index,this.type=e.type,this.from=e.from,this.to=e.to||null,this.gasLimit=e.gasLimit,this.nonce=e.nonce,this.data=e.data,this.value=e.value,this.gasPrice=e.gasPrice,this.maxPriorityFeePerGas=e.maxPriorityFeePerGas!=null?e.maxPriorityFeePerGas:null,this.maxFeePerGas=e.maxFeePerGas!=null?e.maxFeePerGas:null,this.chainId=e.chainId,this.signature=e.signature,this.accessList=e.accessList!=null?e.accessList:null,N(this,Ye,-1)}toJSON(){const{blockNumber:e,blockHash:t,index:r,hash:s,type:i,to:o,from:a,nonce:c,data:u,signature:l,accessList:h}=this;return{_type:"TransactionReceipt",accessList:h,blockNumber:e,blockHash:t,chainId:He(this.chainId),data:u,from:a,gasLimit:He(this.gasLimit),gasPrice:He(this.gasPrice),hash:s,maxFeePerGas:He(this.maxFeePerGas),maxPriorityFeePerGas:He(this.maxPriorityFeePerGas),nonce:c,signature:l,to:o,index:r,type:i,value:He(this.value)}}async getBlock(){let e=this.blockNumber;if(e==null){const r=await this.getTransaction();r&&(e=r.blockNumber)}if(e==null)return null;const t=this.provider.getBlock(e);if(t==null)throw new Error("TODO");return t}async getTransaction(){return this.provider.getTransaction(this.hash)}async wait(e,t){const r=e??1,s=t??0;let i=m(this,Ye),o=-1,a=i===-1;const c=async()=>{if(a)return null;const{blockNumber:h,nonce:y}=await zs({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(y<this.nonce){i=h;return}if(a)return null;const p=await this.getTransaction();if(!(p&&p.blockNumber!=null))for(o===-1&&(o=i-3,o<m(this,Ye)&&(o=m(this,Ye)));o<=h;){if(a)return null;const w=await this.provider.getBlock(o,!0);if(w==null)return;for(const v of w)if(v===this.hash)return;for(let v=0;v<w.length;v++){const g=await w.getTransaction(v);if(g.from===this.from&&g.nonce===this.nonce){if(a)return null;const S=await this.provider.getTransactionReceipt(g.hash);if(S==null||h-S.blockNumber+1<r)return;let U="replaced";g.data===this.data&&g.to===this.to&&g.value===this.value?U="repriced":g.data==="0x"&&g.from===g.to&&g.value===sl&&(U="cancelled"),x(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:U==="replaced"||U==="cancelled",reason:U,replacement:g.replaceableTransaction(i),hash:g.hash,receipt:S})}}o++}},u=await this.provider.getTransactionReceipt(this.hash);if(u){if(await u.confirmations()>=r)return u}else if(await c(),r===0)return null;return await new Promise((h,y)=>{const p=[],w=()=>{p.forEach(g=>g())};if(p.push(()=>{a=!0}),s>0){const g=setTimeout(()=>{w(),y(Or("wait for transaction timeout","TIMEOUT"))},s);p.push(()=>{clearTimeout(g)})}const v=async g=>{await g.confirmations()>=r&&(w(),h(g))};if(p.push(()=>{this.provider.off(this.hash,v)}),this.provider.on(this.hash,v),i>=0){const g=async()=>{try{await c()}catch(S){if(Tr(S,"TRANSACTION_REPLACED")){w(),y(S);return}}a||this.provider.once("block",g)};p.push(()=>{this.provider.off("block",g)}),this.provider.once("block",g)}})}isMined(){return this.blockHash!=null}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}removedEvent(){return x(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),Li(this)}reorderedEvent(e){return x(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),x(!e||e.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),ji(this,e)}replaceableTransaction(e){_(Number.isInteger(e)&&e>=0,"invalid startBlock","startBlock",e);const t=new Xn(this,this.provider);return N(t,Ye,e),t}};let Un=Xn;Ye=new WeakMap;function ji(n,e){return{orphan:"reorder-transaction",tx:n,other:e}}function Li(n){return{orphan:"drop-transaction",tx:n}}function al(n){return{orphan:"drop-log",log:{transactionHash:n.transactionHash,blockHash:n.blockHash,blockNumber:n.blockNumber,address:n.address,data:n.data,topics:Object.freeze(n.topics.slice()),index:n.index}}}class jn extends Dn{constructor(t,r,s){super(t,t.provider);d(this,"interface");d(this,"fragment");d(this,"args");const i=r.decodeEventLog(s,t.data,t.topics);A(this,{args:i,fragment:s,interface:r})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class cl extends ol{constructor(t,r,s){super(s,r);j(this,Ut,void 0);N(this,Ut,t)}get logs(){return super.logs.map(t=>{const r=t.topics.length?m(this,Ut).getEvent(t.topics[0]):null;return r?new jn(t,m(this,Ut),r):t})}}Ut=new WeakMap;class Ln extends Un{constructor(t,r,s){super(s,r);j(this,sr,void 0);N(this,sr,t)}async wait(t){const r=await super.wait();return r==null?null:new cl(m(this,sr),this.provider,r)}}sr=new WeakMap;class Bi extends Dc{constructor(t,r,s,i){super(t,r,s);d(this,"log");A(this,{log:i})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class ul extends Bi{constructor(e,t,r,s,i){super(e,t,r,new jn(i,e.interface,s));const o=e.interface.decodeEventLog(s,this.log.data,this.log.topics);A(this,{args:o,fragment:s})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const Hi=BigInt(0);function Mi(n){return n&&typeof n.call=="function"}function Vi(n){return n&&typeof n.estimateGas=="function"}function Bn(n){return n&&typeof n.resolveName=="function"}function zi(n){return n&&typeof n.sendTransaction=="function"}class ll{constructor(e,t,r){j(this,ir,void 0);d(this,"fragment");if(A(this,{fragment:t}),t.inputs.length<r.length)throw new Error("too many arguments");const s=mt(e.runner,"resolveName"),i=Bn(s)?s:null;N(this,ir,async function(){const o=await Promise.all(t.inputs.map((a,c)=>r[c]==null?null:a.walkAsync(r[c],(l,h)=>l==="address"?Nn(h,i):h)));return e.interface.encodeFilterTopics(t,o)}())}getTopicFilter(){return m(this,ir)}}ir=new WeakMap;function hl(){return Function}function mt(n,e){return n==null?null:typeof n[e]=="function"?n:n.provider&&typeof n.provider[e]=="function"?n.provider:null}function gt(n){return n==null?null:n.provider||null}async function qi(n,e){const t=il(X.dereference(n,"overrides"));return _(t.to==null||(e||[]).indexOf("to")>=0,"cannot override to","overrides.to",t.to),_(t.data==null||(e||[]).indexOf("data")>=0,"cannot override data","overrides.data",t.data),t.from&&(t.from=await Nn(t.from)),t}async function fl(n,e,t){const r=mt(n,"resolveName"),s=Bn(r)?r:null;return await Promise.all(e.map((i,o)=>i.walkAsync(t[o],(a,c)=>(c=X.dereference(c,a),a==="address"?Nn(c,s):c))))}class dl{constructor(e){d(this,"_contract");return A(this,{_contract:e}),new Proxy(this,{apply:async(r,s,i)=>await r.send(...i)})}async populateTransaction(e){const t=await qi(e,["data"]);t.to=await this._contract.getAddress();const r=this._contract.interface,s=r.receive||r.fallback&&r.fallback.payable;return _(s||(t.value||Hi)===Hi,"cannot send value to non-payable contract","overrides.value",t.value),_(r.fallback||(t.data||"0x")==="0x","cannot send data to receive-only contract","overrides.data",t.data),t}async staticCall(e){const t=mt(this._contract.runner,"call");x(Mi(t),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const r=await this.populateTransaction(e);try{return await t.call(r)}catch(s){throw qs(s)&&s.data?this._contract.interface.makeError(s.data,r):s}}async send(e){const t=this._contract.runner;x(zi(t),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const r=await t.sendTransaction(await this.populateTransaction(e)),s=gt(this._contract.runner);return new Ln(this._contract.interface,s,r)}async estimateGas(e){const t=mt(this._contract.runner,"estimateGas");return x(Vi(t),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await t.estimateGas(await this.populateTransaction(e))}}class pl extends hl(){constructor(t,r){super();d(this,"name","");d(this,"_contract");d(this,"_key");return A(this,{name:t.interface.getFunctionName(r),_contract:t,_key:r}),new Proxy(this,{apply:async(i,o,a)=>i.getFragment(...a).constant?await i.staticCall(...a):await i.send(...a)})}get fragment(){const t=this._contract.interface.getFunction(this._key);return x(t,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment"}),t}getFragment(...t){const r=this._contract.interface.getFunction(this._key,t);return x(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment"}),r}async populateTransaction(...t){const r=this.getFragment(...t);let s={};if(r.inputs.length+1===t.length&&(s=await qi(t.pop())),r.inputs.length!==t.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const i=await fl(this._contract.runner,r.inputs,t);return Object.assign({},s,await zs({to:this._contract.getAddress(),data:this._contract.interface.encodeFunctionData(r,i)}))}async staticCall(...t){const r=await this.staticCallResult(...t);return r.length===1?r[0]:r}async send(...t){const r=this._contract.runner;x(zi(r),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await r.sendTransaction(await this.populateTransaction(...t)),i=gt(this._contract.runner);return new Ln(this._contract.interface,i,s)}async estimateGas(...t){const r=mt(this._contract.runner,"estimateGas");return x(Vi(r),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await r.estimateGas(await this.populateTransaction(...t))}async staticCallResult(...t){const r=mt(this._contract.runner,"call");x(Mi(r),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const s=await this.populateTransaction(...t);let i="0x";try{i=await r.call(s)}catch(a){throw qs(a)&&a.data?this._contract.interface.makeError(a.data,s):a}const o=this.getFragment(...t);return this._contract.interface.decodeFunctionResult(o,i)}}function yl(){return Function}class ml extends yl(){constructor(t,r){super();d(this,"name","");d(this,"_contract");d(this,"_key");return A(this,{name:t.interface.getEventName(r),_contract:t,_key:r}),new Proxy(this,{apply:(s,i,o)=>new ll(t,s.getFragment(...o),o)})}get fragment(){const t=this._contract.interface.getEvent(this._key);return x(t,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment"}),t}getFragment(...t){const r=this._contract.interface.getEvent(this._key,t);return x(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment"}),r}}const jr=Symbol.for("_ethersInternal_contract"),Gi=new WeakMap;function gl(n,e){Gi.set(n[jr],e)}function fe(n){return Gi.get(n[jr])}function wl(n){return n&&typeof n=="object"&&"getTopicFilter"in n&&typeof n.getTopicFilter=="function"&&n.fragment}async function Hn(n,e){let t,r=null;if(Array.isArray(e)){const i=function(o){if(qe(o,32))return o;const a=n.interface.getEvent(o);return _(a,"unknown fragment","name",o),a.topicHash};t=e.map(o=>o==null?null:Array.isArray(o)?o.map(i):i(o))}else e==="*"?t=[null]:typeof e=="string"?qe(e,32)?t=[e]:(r=n.interface.getEvent(e),_(r,"unknown fragment","event",e),t=[r.topicHash]):wl(e)?t=await e.getTopicFilter():"fragment"in e?(r=e.fragment,t=[r.topicHash]):_(!1,"unknown event name","event",e);t=t.map(i=>{if(i==null)return null;if(Array.isArray(i)){const o=Array.from(new Set(i.map(a=>a.toLowerCase())).values());return o.length===1?o[0]:(o.sort(),o)}return i.toLowerCase()});const s=t.map(i=>i==null?"null":Array.isArray(i)?i.join("|"):i).join("&");return{fragment:r,tag:s,topics:t}}async function Xt(n,e){const{subs:t}=fe(n);return t.get((await Hn(n,e)).tag)||null}async function Ji(n,e,t){const r=gt(n.runner);x(r,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:e});const{fragment:s,tag:i,topics:o}=await Hn(n,t),{addr:a,subs:c}=fe(n);let u=c.get(i);if(!u){const h={address:a||n,topics:o},y=g=>{let S=s;if(S==null)try{S=n.interface.getEvent(g.topics[0])}catch{}if(S){const U=S,te=s?n.interface.decodeEventLog(s,g.data,g.topics):[];Vn(n,t,te,L=>new ul(n,L,t,U,g))}else Vn(n,t,[],U=>new Bi(n,U,t,g))};let p=[];u={tag:i,listeners:[],start:()=>{p.length||p.push(r.on(h,y))},stop:async()=>{if(p.length==0)return;let g=p;p=[],await Promise.all(g),r.off(h,y)}},c.set(i,u)}return u}let Mn=Promise.resolve();async function bl(n,e,t,r){await Mn;const s=await Xt(n,e);if(!s)return!1;const i=s.listeners.length;return s.listeners=s.listeners.filter(({listener:o,once:a})=>{const c=Array.from(t);r&&c.push(r(a?null:o));try{o.call(n,...c)}catch{}return!a}),i>0}async function Vn(n,e,t,r){try{await Mn}catch{}const s=bl(n,e,t,r);return Mn=s,await s}const Wi=["then"],Mr=class{constructor(e,t,r,s){d(this,"target");d(this,"interface");d(this,"runner");d(this,"filters");d(this,$l);d(this,"fallback");r==null&&(r=null);const i=Fn.from(t);A(this,{target:e,runner:r,interface:i}),Object.defineProperty(this,jr,{value:{}});let o,a=null,c=null;if(s){const h=gt(r);c=new Ln(this.interface,h,s)}let u=new Map;if(typeof e=="string")if(qe(e))a=e,o=Promise.resolve(e);else{const h=mt(r,"resolveName");if(!Bn(h))throw Or("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});o=h.resolveName(e).then(y=>{if(y==null)throw new Error("TODO");return fe(this).addr=y,y})}else o=e.getAddress().then(h=>{if(h==null)throw new Error("TODO");return fe(this).addr=h,h});gl(this,{addrPromise:o,addr:a,deployTx:c,subs:u});const l=new Proxy({},{get:(h,y,p)=>{if(Wi.indexOf(y)>=0)return Reflect.get(h,y,p);const w=String(y),v=this.getEvent(w);if(v)return v;throw new Error(`unknown contract event: ${w}`)}});return A(this,{filters:l}),A(this,{fallback:i.receive||i.fallback?new dl(this):null}),new Proxy(this,{get:(h,y,p)=>{if(y in h||Wi.indexOf(y)>=0)return Reflect.get(h,y,p);const w=String(y),v=h.getFunction(w);if(v)return v;throw new Error(`unknown contract method: ${w}`)}})}connect(e){return new Mr(this.target,this.interface,e)}async getAddress(){return await fe(this).addrPromise}async getDeployedCode(){const e=gt(this.runner);x(e,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const t=await e.getCode(await this.getAddress());return t==="0x"?null:t}async waitForDeployment(){const e=this.deploymentTransaction();if(e)return await e.wait(),this;if(await this.getDeployedCode()!=null)return this;const r=gt(this.runner);return x(r!=null,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise((s,i)=>{const o=async()=>{try{if(await this.getDeployedCode()!=null)return s(this);r.once("block",o)}catch(a){i(a)}};o()})}deploymentTransaction(){return fe(this).deployTx}getFunction(e){return typeof e!="string"&&(e=e.format()),new pl(this,e)}getEvent(e){return typeof e!="string"&&(e=e.format()),new ml(this,e)}async queryTransaction(e){throw new Error("@TODO")}async queryFilter(e,t,r){t==null&&(t=0),r==null&&(r="latest");const{addr:s,addrPromise:i}=fe(this),o=s||await i,{fragment:a,topics:c}=await Hn(this,e),u={address:o,topics:c,fromBlock:t,toBlock:r},l=gt(this.runner);return x(l,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await l.getLogs(u)).map(h=>{let y=a;if(y==null)try{y=this.interface.getEvent(h.topics[0])}catch{}return y?new jn(h,this.interface,y):new Dn(h,l)})}async on(e,t){const r=await Ji(this,"on",e);return r.listeners.push({listener:t,once:!1}),r.start(),this}async once(e,t){const r=await Ji(this,"once",e);return r.listeners.push({listener:t,once:!0}),r.start(),this}async emit(e,...t){return await Vn(this,e,t,null)}async listenerCount(e){if(e){const s=await Xt(this,e);return s?s.listeners.length:0}const{subs:t}=fe(this);let r=0;for(const{listeners:s}of t.values())r+=s.length;return r}async listeners(e){if(e){const s=await Xt(this,e);return s?s.listeners.map(({listener:i})=>i):[]}const{subs:t}=fe(this);let r=[];for(const{listeners:s}of t.values())r=r.concat(s.map(({listener:i})=>i));return r}async off(e,t){const r=await Xt(this,e);if(!r)return this;if(t){const s=r.listeners.map(({listener:i})=>i).indexOf(t);s>=0&&r.listeners.splice(s,1)}return(t==null||r.listeners.length===0)&&(r.stop(),fe(this).subs.delete(r.tag)),this}async removeAllListeners(e){if(e){const t=await Xt(this,e);if(!t)return this;t.stop(),fe(this).subs.delete(t.tag)}else{const{subs:t}=fe(this);for(const{tag:r,stop:s}of t.values())s(),t.delete(r)}return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return await this.off(e,t)}static buildClass(e){class t extends Mr{constructor(s,i=null){super(s,e,i)}}return t}static from(e,t,r){return r==null&&(r=null),new this(e,t,r)}};let zn=Mr;$l=jr;function vl(){return zn}class _l extends vl(){}class wt{constructor(e){d(this,"data",[]);this.api=e}static create(e){return new wt(e)}getAbiHash(e){if(this.api===void 0)throw new Error("FunctionBuilder must be initialised with api");return this.api.getAbiHash(e)}static readFields(e,t){if(e.length===0)return[];const r=(s,i)=>{console.log(t);const o=t[i].find(a=>a.name===s.function);if(!o)throw new Error("function not in ABI");return o.outputs.map((a,c)=>({source:`function:${s.function}:${i}`,name:a.name,type:a.type,key:`func_${i}_ret_${c}`,index:c}))};return e.map((s,i)=>r(s,i))}async addFunction(e,t,r,s,i){console.log(i);const o=new _l(e,s);return o.interface.encodeFunctionData(t,r),i=i||await this.getAbiHash(s),console.log(i),this.data.push({address:e,bytecode:o.interface.encodeFunctionData(t,r),abiHash:i,function:t}),this}get(){return this.data}static schema(){return lt().of(se({address:T().required(),bytecode:T().matches(/^(0x)?([0-9a-fA-F]{2})*$/).required(),abiHash:T().matches(/^[A-Fa-f0-9]{64}/).required(),function:T().required()}))}}class Ke{static version(){return"v1"}static execute(e,t,r="v1"){const s=JSON.parse(JSON.stringify(t));let i=!0;for(const o of s){const a=Ke.process(e,o.conditions);i=Ke.execLogic(i,o.logic,a)}return i}static process(e,t,r){const s=t.shift();if(!s)return r===void 0?!0:r;const i=Ke.execCondition(e,s);if(r===void 0||s.logic==="WHERE")return Ke.process(e,t,i);if(s.logic===void 0)throw new Error("Invalid filter. FilterCondition must have logic value");const o=Ke.execLogic(r,s.logic,i);return Ke.process(e,t,o)}static execLogic(e,t,r){switch(t){case"AND":return e&&r;case"OR":return e||r;case"XOR":return(e||r)&&!(e&&r);case"NAND":return!(e&&r);case"NOR":return!(e&&r);case"WHERE":return r;default:throw new Error(`Invalid Filter. Bad logic value: ${t}`)}}static execCondition(e,t){const r=e[t.key];if(t.type==="Number"){if(typeof t.constant!="number"||typeof r!="number")throw new Error(`Invalid filter. Type miss-match. Type: ${t.type}, Variable: ${t.constant}, Data: ${r}`);const s=r,i=t.constant;switch(t.operation){case"eq":return s===i;case"!eq":return s!==i;case"gt":return s>i;case"gte":return s>=i;case"lt":return s<i;case"lte":return s<=i;default:throw new Error("Invalid Filter. Operation does not match type")}}if(t.type==="String"){if(typeof t.constant!="string"||typeof r!="string")throw new Error(`Invalid filter. Type miss-match. Type: ${t.type}, Variable: ${t.constant}, Data: ${r}`);const s=r,i=t.constant;switch(t.operation){case"contains":return s.includes(i);case"!contains":return!s.includes(i);case"is":return s===i;case"!is":return s!==i;case"isEmpty":return s==="";case"!isEmpty":return s!=="";default:throw new Error("Invalid Filter. Operation does not match type")}}if(t.type==="Address"){if(typeof t.constant!="string"||typeof r!="string")throw new Error(`Invalid filter. Type miss-match. Type: ${t.type}, Variable: ${t.constant}, Data: ${r}`);const s=r,i=t.constant;switch(t.operation){case"contains":return s.toLowerCase().includes(i.toLowerCase());case"!contains":return!s.toLowerCase().includes(i.toLowerCase());case"is":return s.toLowerCase()===i.toLowerCase();case"!is":return s.toLowerCase()!==i.toLowerCase();case"isEmpty":return s==="";case"!isEmpty":return s!=="";default:throw new Error("Invalid Filter. Operation does not match type")}}throw new Error("Invalid Filter. Unknown Type")}}class Zt{constructor(){d(this,"groups",[]);this.newGroup("WHERE")}static version(){return Ke.version()}static new(){return new Zt}newGroup(e){if(this.groups.length!==0&&e==="WHERE")throw new Error('Only the first groups can start with "WHERE"');return this.groups.push({logic:"WHERE",conditions:[]}),this}addCondition(e,t,r,s,i){const o=this.groups[this.groups.length-1];if(o.conditions.length===0&&e!=="WHERE")throw new Error('Logic for the first condition of a group must be "WHERE"');if(o.conditions.length>0&&e==="WHERE")throw new Error('Only the first condition of a group can be "WHERE"');return o.conditions.push({logic:e,key:t,type:r,operation:s,constant:i}),this}finalise(){for(const e of this.groups)if(e.conditions.length===0)throw new Error("Bad Filter. All Groups must have atleast one condition");return this.groups}static schema(){const e=T().oneOf(["AND","OR","XOR","NAND","NOR","WHERE"]).required(),t=se({logic:e,key:T().required(),type:T().oneOf(["String","Address","Number"]).required(),operation:T().when("type",([r],s)=>{switch(r){case"String":return s.oneOf(["contains","!contains","is","!is","isEmpty","!isEmpty"]);case"Address":return s.oneOf(["is","!is","isEmpty","!isEmpty"]);case"Number":return s.oneOf(["eq","!eq","gt","gte","lt","lte"]);default:throw new Error("Invalid Filter Data Type")}}).required(),constant:$s().when("type",([r])=>{switch(r){case"String":return T();case"Address":return T();case"Number":return q();default:throw new Error("Invalid Filter Data Type")}}).required()});return lt().of(se({logic:e,conditions:lt().of(t).required()}))}}const El="handler_function_call_v2",xl=/^(\d+)([SMHD])$/i,Ki=se({timeBase:T().oneOf(["blocks","time"]).required(),nBlocks:q().min(10).when("timeBase",([n],e)=>n==="blocks"?e.required():e),timePeriod:T().matches(xl,"timePeriod must be of the format n[s|m|h|d], eg 10s for 10 seconds").when("timeBase",([n],e)=>n==="time"?e.required():e),startTime:q().default(0),debounceCount:q().default(0),functions:wt.schema().required(),triggerOn:T().oneOf(["always","filter"]).default("always"),latch:_r().default(!1),filterVersion:T().when("triggerOn",([n],e)=>n==="filter"?e.default("0"):e.nullable().default(null)).required(),filter:Zt.schema().when("triggerOn",([n],e)=>n==="filter"?e.required():e.nullable().default(null)).required()});class qn{static async SimpleToRaw(e,t,r){return{alertType:"event",network:t,nickname:e,type:El,handler:await this.validate(r)}}static validate(e){return Ki.validateSync(e)}static async convertFromPartial(e){return Ki.validate(e)}static readFields(e,t){const r=[{source:"defaults",label:"Network",type:"string",key:"network"},{source:"defaults",label:"Timestamp",type:"number",key:"timestamp"},{source:"defaults",label:"Time GMT",type:"number",key:"timeStringGMT"},{source:"defaults",label:"Block",type:"number",key:"block"},{source:"defaults",label:"Time Period",type:"number",key:"timePeriod"}];if(!e.functions)return r;const s=e.functions.map(i=>t[i.abiHash]);return console.log(s),[...wt.readFields(e.functions,s),...r]}}const Tl="handler_onchain_event_v2",Ol=se({addresses:lt().of(T().required()).required(),abiHash:T().required(),event:T().required(),debounceCount:q().default(0),functions:wt.schema().nullable().default(null),triggerOn:T().oneOf(["always","filter"]).default("always"),latch:_r().default(!1),filterVersion:T().nullable().default(null),filter:Zt.schema().when("triggerOn",([n],e)=>n==="filter"?e:e.nullable().default(null)).required()}),kl=n=>n,Xi=(n,e,t=[],r="",s="")=>(n.forEach((i,o)=>{const a=i.type.includes("["),c=a?"_[]":"";if(i.components){const u=i.name===""?`${o}`:i.name;Xi(i.components,e,t,`${r}${o}${c}_`,`${u}${a?"[]":""}.`)}else t.push({source:e,label:`${s}${i.name}`,type:kl(i.type),key:`${r}${o}${c}`,index:o})}),t);class Gn{static async SimpleToRaw(e,t,r){return{alertType:"event",network:t,nickname:e,type:Tl,handler:await this.validate(r)}}static validate(e){return Ol.validateSync(e)}static readFields(e,t){let r=[{source:"defaults",label:"Network",type:"string",key:"network"},{source:"defaults",label:"Timestamp",type:"number",key:"timestamp"},{source:"defaults",label:"Time GMT",type:"string",key:"timeStringGMT"},{source:"defaults",label:"Block",type:"number",key:"block"},{source:"defaults",label:"Time Period",type:"string",key:"timePeriod"},{source:"defaults",label:"Block Hash",type:"string",key:"blockHash"},{source:"defaults",label:"Transaction Hash",type:"string",key:"txHash"},{source:"defaults",label:"Event",type:"string",key:"event"}];const s=t[e.abiHash].find(o=>o.name===e.event);if(r=Xi(s.inputs,`${e.event} Event`,r,"param_"),!e.functions)return r;const i=e.functions.map(o=>t[o.abiHash]);return[...wt.readFields(e.functions,i),...r]}}class Yt{static SimpleToRaw(e,t,r,s){switch(t){case"PollFunctionV2":return qn.SimpleToRaw(e,r,s);case"PollFunctionV1":return Ms.SimpleToRaw(e,r,s);case"OnchainEventV1":return Vs.SimpleToRaw(e,r,s);case"OnchainEventV2":return Gn.SimpleToRaw(e,r,s);default:throw new Error("Invalid Trigger ID")}}static Validate(e,t){switch(e){case"PollFunctionV2":return qn.validate(t);case"PollFunctionV1":return Ms.validate(t);case"OnchainEventV1":return Vs.validate(t);case"OnchainEventV2":return Gn.validate(t);default:throw new Error("Invalid Trigger ID")}}static RawToSimple(e){return{...{error:e.error,error_message:e.error_message,error_timestamp:e.error_timestamp},...e.handler}}static SimpleTypeToRawType(e){switch(e){case"PollFunctionV2":return"handler_function_call_v2";case"PollFunctionV1":return"handler_function_call";case"OnchainEventV1":return"handler_onchain_event";case"OnchainEventV2":return"handler_onchain_event_v2";default:throw new Error("Invalid Trigger ID")}}static RawTypeToSimpleType(e){switch(e){case"handler_function_call_v2":return"PollFunctionV2";case"handler_function_call":return"PollFunctionV1";case"handler_onchain_event":return"OnchainEventV1";case"handler_onchain_event_v2":return"OnchainEventV2";default:throw new Error("Invalid Trigger ID")}}static readFields(e,t,r){switch(e){case"PollFunctionV2":return qn.readFields(t,r);case"OnchainEventV2":return Gn.readFields(t,r);default:throw new Error("Invalid Trigger ID")}}}const Zi=n=>`https://${n}.functions.supabase.co/`,Yi=n=>`https://${n}.supabase.co/`,Qi="fdgtrxmmrtlokhgkvcjz",Al="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImZkZ3RyeG1tcnRsb2toZ2t2Y2p6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2NzMwODcwNzYsImV4cCI6MTk4ODY2MzA3Nn0.sAMxjlcJSSozBGr-LNcsudyxzUEM9e-UspMHHQLqLr4";class Jn{constructor(e,t){d(this,"headers",{});this.url=e,this.headers={Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static async create(e){var t,r;if(e.key)throw new Error("Auth by key not yet supported");if(e.email&&e.password){const s=e.projectId?Yi(e.projectId):Yi(Qi),i=e.projectId?Zi(e.projectId):Zi(Qi),o=e.anonKey?e.anonKey:Al,a=Ca(s,o),{data:c,error:u}=await a.auth.signInWithPassword({email:e.email,password:e.password});if(u)throw u;if(((t=c.session)==null?void 0:t.access_token)===void 0)throw new Error("Access token not found");return new Jn(i,(r=c.session)==null?void 0:r.access_token)}else throw new Error("Authentication Required. DeNotify supports either username/password or API key authentication")}async alertHistory(e,t){const r="alert-history",s=t||{};return e&&(s.id=e),Object.keys(s).length>0?await this.request("get",r,{params:t}):await this.request("get",r)}async getAlert(e){const t=(await this.request("get",`alerts/${e}`))[0];return await this.decode(t)}async getAlerts(){const e=await this.request("get","alerts");return Promise.all(e.map(t=>this.decode(t)))}async createAlert(e){const t=await this.encode(e);return await this.request("post","alerts",{body:t})}async updateRawTrigger(e,t){const r=await se({name:T().optional(),enabled:_r().optional()}).validate(t);await this.request("patch",`alerts/trigger/${e}`,{body:r})}async updateAlert(e,t){const r=[],{trigger:s,notification:i,...o}=t;return(o.name||o.enabled)&&r.push(this.updateRawTrigger(e,o)),s&&r.push(this.updateRawHandler(e,s)),i&&r.push(this.updateRawNotify(e,i)),await Promise.all(r),await this.getAlert(e)}async deleteAlert(e){return await this.request("delete",`alerts/${e}`)}async decode(e){return{id:e.alertId,enabled:e.trigger.enabled,name:e.trigger.nickname,network:e.trigger.network,triggerId:Yt.RawTypeToSimpleType(e.trigger.type),trigger:await Yt.RawToSimple(e.trigger),notificationId:En.RawTypeToSimpleType(e.notification.notify_type),notification:await En.RawToSimple(e.notification)}}async encode(e){return{trigger:await Yt.SimpleToRaw(e.name,e.triggerId,e.network,e.trigger),notification:await En.SimpleToRaw(e.notificationId,e.notification)}}async request(e,t,r={}){const s=new URL(`${this.url}${t}`);if(r.params)for(const a of Object.keys(r.params))s.searchParams.append(a,r.params[a]);const i={method:e,headers:this.headers};return r.body&&(i.body=JSON.stringify(r.body)),(await fetch(s.toString(),i)).json()}readFields(e,t,r){return Yt.readFields(e,t,r)}async getAbi(e,t){return await this.request("get",`abi/${e}/${t}`)}async getAbiHash(e){return(await this.request("post","abi",{body:e})).hash}async updateRawNotify(e,t){return await this.request("patch",`alerts/notify/${e}`,{body:t})}async updateRawHandler(e,t){return await this.request("patch",`alerts/trigger-handler/${e}`,{body:t})}}class Wn{constructor(e){d(this,"network");d(this,"triggerId");d(this,"trigger");d(this,"notificationId");d(this,"notification");this.name=e}static create(e){return new Wn(e)}onNetwork(e){return this.network=e,this}withTrigger(e,t){return this.triggerId=e,this.trigger=Yt.Validate(e,t),this}withNotification(e,t){return this.notificationId=e,this.notification=t,this}async config(){if(this.trigger===void 0||this.triggerId===void 0)throw new Error("Trigger not configured");if(this.notification===void 0||this.notificationId===void 0)throw new Error("Notification not configured");if(this.network===void 0)throw new Error("Network not configured");return{name:this.name,network:this.network,triggerId:this.triggerId,trigger:this.trigger,notificationId:this.notificationId,notification:this.notification}}}const Sl=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Rl=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));return R.AlertBuilder=Wn,R.DeNotifyClient=Jn,R.FilterBuilder=Zt,R.FunctionBuilder=wt,R.Notification=Rl,R.Trigger=Sl,Object.defineProperty(R,Symbol.toStringTag,{value:"Module"}),R}({});
|
4
|
+
`+(a!==o?`result of cast: ${a}`:""))}return i}_cast(e,t){let r=e===void 0?e:this.transforms.reduce((s,i)=>i.call(this,s,e,this),e);return r===void 0&&(r=this.getDefault()),r}_validate(e,t={},r,s){let{path:i,originalValue:o=e,strict:a=this.spec.strict}=t,c=e;a||(c=this._cast(c,Object.assign({assert:!1},t)));let u=[];for(let l of Object.values(this.internalTests))l&&u.push(l);this.runTests({path:i,value:c,originalValue:o,options:t,tests:u},r,l=>{if(l.length)return s(l,c);this.runTests({path:i,value:c,originalValue:o,options:t,tests:this.tests},r,s)})}runTests(e,t,r){let s=!1,{tests:i,value:o,originalValue:a,path:c,options:u}=e,l=v=>{s||(s=!0,t(v,o))},h=v=>{s||(s=!0,r(v,o))},y=i.length,p=[];if(!y)return h([]);let w={value:o,originalValue:a,path:c,options:u,schema:this};for(let v=0;v<i.length;v++){const g=i[v];g(w,l,function(U){U&&(p=p.concat(U)),--y<=0&&h(p)})}}asNestedTest({key:e,index:t,parent:r,parentPath:s,originalParent:i,options:o}){const a=e??t;if(a==null)throw TypeError("Must include `key` or `index` for nested validations");const c=typeof a=="number";let u=r[a];const l=Object.assign({},o,{strict:!0,parent:r,value:u,originalValue:i[a],key:void 0,[c?"index":"key"]:a,path:c||a.includes(".")?`${s||""}[${u?a:`"${a}"`}]`:(s?`${s}.`:"")+e});return(h,y,p)=>this.resolve(l)._validate(u,l,y,p)}validate(e,t){let r=this.resolve(Object.assign({},t,{value:e}));return new Promise((s,i)=>r._validate(e,t,(o,a)=>{ce.isError(o)&&(o.value=a),i(o)},(o,a)=>{o.length?i(new ce(o,a)):s(a)}))}validateSync(e,t){let r=this.resolve(Object.assign({},t,{value:e})),s;return r._validate(e,Object.assign({},t,{sync:!0}),(i,o)=>{throw ce.isError(i)&&(i.value=o),i},(i,o)=>{if(i.length)throw new ce(i,e);s=o}),s}isValid(e,t){return this.validate(e,t).then(()=>!0,r=>{if(ce.isError(r))return!1;throw r})}isValidSync(e,t){try{return this.validateSync(e,t),!0}catch(r){if(ce.isError(r))return!1;throw r}}_getDefault(){let e=this.spec.default;return e==null?e:typeof e=="function"?e.call(this):At(e)}getDefault(e){return this.resolve(e||{})._getDefault()}default(e){return arguments.length===0?this._getDefault():this.clone({default:e})}strict(e=!0){return this.clone({strict:e})}nullability(e,t){const r=this.clone({nullable:e});return r.internalTests.nullable=kt({message:t,name:"nullable",test(s){return s===null?this.schema.spec.nullable:!0}}),r}optionality(e,t){const r=this.clone({optional:e});return r.internalTests.optionality=kt({message:t,name:"optionality",test(s){return s===void 0?this.schema.spec.optional:!0}}),r}optional(){return this.optionality(!0)}defined(e=Pe.defined){return this.optionality(!1,e)}nullable(){return this.nullability(!0)}nonNullable(e=Pe.notNull){return this.nullability(!1,e)}required(e=Pe.required){return this.clone().withMutation(t=>t.nonNullable(e).defined(e))}notRequired(){return this.clone().withMutation(e=>e.nullable().optional())}transform(e){let t=this.clone();return t.transforms.push(e),t}test(...e){let t;if(e.length===1?typeof e[0]=="function"?t={test:e[0]}:t=e[0]:e.length===2?t={name:e[0],test:e[1]}:t={name:e[0],message:e[1],test:e[2]},t.message===void 0&&(t.message=Pe.default),typeof t.test!="function")throw new TypeError("`test` is a required parameters");let r=this.clone(),s=kt(t),i=t.exclusive||t.name&&r.exclusiveTests[t.name]===!0;if(t.exclusive&&!t.name)throw new TypeError("Exclusive tests must provide a unique `name` identifying the test");return t.name&&(r.exclusiveTests[t.name]=!!t.exclusive),r.tests=r.tests.filter(o=>!(o.OPTIONS.name===t.name&&(i||o.OPTIONS.test===s.OPTIONS.test))),r.tests.push(s),r}when(e,t){!Array.isArray(e)&&typeof e!="string"&&(t=e,e=".");let r=this.clone(),s=Rs(e).map(i=>new ut(i));return s.forEach(i=>{i.isSibling&&r.deps.push(i.key)}),r.conditions.push(typeof t=="function"?new wr(s,t):wr.fromOptions(s,t)),r}typeError(e){let t=this.clone();return t.internalTests.typeError=kt({message:e,name:"typeError",test(r){return!he(r)&&!this.schema._typeCheck(r)?this.createError({params:{type:this.schema.type}}):!0}}),t}oneOf(e,t=Pe.oneOf){let r=this.clone();return e.forEach(s=>{r._whitelist.add(s),r._blacklist.delete(s)}),r.internalTests.whiteList=kt({message:t,name:"oneOf",skipAbsent:!0,test(s){let i=this.schema._whitelist,o=i.resolveAll(this.resolve);return o.includes(s)?!0:this.createError({params:{values:Array.from(i).join(", "),resolved:o}})}}),r}notOneOf(e,t=Pe.notOneOf){let r=this.clone();return e.forEach(s=>{r._blacklist.add(s),r._whitelist.delete(s)}),r.internalTests.blacklist=kt({message:t,name:"notOneOf",test(s){let i=this.schema._blacklist,o=i.resolveAll(this.resolve);return o.includes(s)?this.createError({params:{values:Array.from(i).join(", "),resolved:o}}):!0}}),r}strip(e=!0){let t=this.clone();return t.spec.strip=e,t}describe(e){const t=(e?this.resolve(e):this).clone(),{label:r,meta:s,optional:i,nullable:o}=t.spec;return{meta:s,label:r,optional:i,nullable:o,default:t.getDefault(e),type:t.type,oneOf:t._whitelist.describe(),notOneOf:t._blacklist.describe(),tests:t.tests.map(c=>({name:c.OPTIONS.name,params:c.OPTIONS.params})).filter((c,u,l)=>l.findIndex(h=>h.name===c.name)===u)}}}ne.prototype.__isYupSchema__=!0;for(const n of["validate","validateSync"])ne.prototype[`${n}At`]=function(e,t,r={}){const{parent:s,parentPath:i,schema:o}=tc(this,e,t,r.context);return o[n](s&&s[i],Object.assign({},r,{parent:s,path:e}))};for(const n of["equals","is"])ne.prototype[n]=ne.prototype.oneOf;for(const n of["not","nope"])ne.prototype[n]=ne.prototype.notOneOf;const rc=()=>!0;function $s(n){return new Ps(n)}class Ps extends ne{constructor(e){super(typeof e=="function"?{type:"mixed",check:e}:Object.assign({type:"mixed",check:rc},e))}}$s.prototype=Ps.prototype;function _r(){return new Ns}class Ns extends ne{constructor(){super({type:"boolean",check(e){return e instanceof Boolean&&(e=e.valueOf()),typeof e=="boolean"}}),this.withMutation(()=>{this.transform((e,t,r)=>{if(r.spec.coerce&&!r.isType(e)){if(/^(true|1)$/i.test(String(e)))return!0;if(/^(false|0)$/i.test(String(e)))return!1}return e})})}isTrue(e=gn.isValue){return this.test({message:e,name:"is-value",exclusive:!0,params:{value:"true"},test(t){return he(t)||t===!0}})}isFalse(e=gn.isValue){return this.test({message:e,name:"is-value",exclusive:!0,params:{value:"false"},test(t){return he(t)||t===!1}})}default(e){return super.default(e)}defined(e){return super.defined(e)}optional(){return super.optional()}required(e){return super.required(e)}notRequired(){return super.notRequired()}nullable(){return super.nullable()}nonNullable(e){return super.nonNullable(e)}strip(e){return super.strip(e)}}_r.prototype=Ns.prototype;let nc=/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,sc=/^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,ic=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,oc=n=>he(n)||n===n.trim(),ac={}.toString();function T(){return new Is}class Is extends ne{constructor(){super({type:"string",check(e){return e instanceof String&&(e=e.valueOf()),typeof e=="string"}}),this.withMutation(()=>{this.transform((e,t,r)=>{if(!r.spec.coerce||r.isType(e)||Array.isArray(e))return e;const s=e!=null&&e.toString?e.toString():e;return s===ac?e:s})})}required(e){return super.required(e).withMutation(t=>t.test({message:e||Pe.required,name:"required",skipAbsent:!0,test:r=>!!r.length}))}notRequired(){return super.notRequired().withMutation(e=>(e.tests=e.tests.filter(t=>t.OPTIONS.name!=="required"),e))}length(e,t=me.length){return this.test({message:t,name:"length",exclusive:!0,params:{length:e},skipAbsent:!0,test(r){return r.length===this.resolve(e)}})}min(e,t=me.min){return this.test({message:t,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(r){return r.length>=this.resolve(e)}})}max(e,t=me.max){return this.test({name:"max",exclusive:!0,message:t,params:{max:e},skipAbsent:!0,test(r){return r.length<=this.resolve(e)}})}matches(e,t){let r=!1,s,i;return t&&(typeof t=="object"?{excludeEmptyString:r=!1,message:s,name:i}=t:s=t),this.test({name:i||"matches",message:s||me.matches,params:{regex:e},skipAbsent:!0,test:o=>o===""&&r||o.search(e)!==-1})}email(e=me.email){return this.matches(nc,{name:"email",message:e,excludeEmptyString:!0})}url(e=me.url){return this.matches(sc,{name:"url",message:e,excludeEmptyString:!0})}uuid(e=me.uuid){return this.matches(ic,{name:"uuid",message:e,excludeEmptyString:!1})}ensure(){return this.default("").transform(e=>e===null?"":e)}trim(e=me.trim){return this.transform(t=>t!=null?t.trim():t).test({message:e,name:"trim",test:oc})}lowercase(e=me.lowercase){return this.transform(t=>he(t)?t:t.toLowerCase()).test({message:e,name:"string_case",exclusive:!0,skipAbsent:!0,test:t=>he(t)||t===t.toLowerCase()})}uppercase(e=me.uppercase){return this.transform(t=>he(t)?t:t.toUpperCase()).test({message:e,name:"string_case",exclusive:!0,skipAbsent:!0,test:t=>he(t)||t===t.toUpperCase()})}}T.prototype=Is.prototype;let cc=n=>n!=+n;function q(){return new Cs}class Cs extends ne{constructor(){super({type:"number",check(e){return e instanceof Number&&(e=e.valueOf()),typeof e=="number"&&!cc(e)}}),this.withMutation(()=>{this.transform((e,t,r)=>{if(!r.spec.coerce)return e;let s=e;if(typeof s=="string"){if(s=s.replace(/\s/g,""),s==="")return NaN;s=+s}return r.isType(s)?s:parseFloat(s)})})}min(e,t=ze.min){return this.test({message:t,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(r){return r>=this.resolve(e)}})}max(e,t=ze.max){return this.test({message:t,name:"max",exclusive:!0,params:{max:e},skipAbsent:!0,test(r){return r<=this.resolve(e)}})}lessThan(e,t=ze.lessThan){return this.test({message:t,name:"max",exclusive:!0,params:{less:e},skipAbsent:!0,test(r){return r<this.resolve(e)}})}moreThan(e,t=ze.moreThan){return this.test({message:t,name:"min",exclusive:!0,params:{more:e},skipAbsent:!0,test(r){return r>this.resolve(e)}})}positive(e=ze.positive){return this.moreThan(0,e)}negative(e=ze.negative){return this.lessThan(0,e)}integer(e=ze.integer){return this.test({name:"integer",message:e,skipAbsent:!0,test:t=>Number.isInteger(t)})}truncate(){return this.transform(e=>he(e)?e:e|0)}round(e){var t;let r=["ceil","floor","round","trunc"];if(e=((t=e)==null?void 0:t.toLowerCase())||"round",e==="trunc")return this.truncate();if(r.indexOf(e.toLowerCase())===-1)throw new TypeError("Only valid options for round() are: "+r.join(", "));return this.transform(s=>he(s)?s:Math[e](s))}}q.prototype=Cs.prototype;var uc=/^(\d{4}|[+\-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;function lc(n){var e=[1,4,5,6,7,10,11],t=0,r,s;if(s=uc.exec(n)){for(var i=0,o;o=e[i];++i)s[o]=+s[o]||0;s[2]=(+s[2]||1)-1,s[3]=+s[3]||1,s[7]=s[7]?String(s[7]).substr(0,3):0,(s[8]===void 0||s[8]==="")&&(s[9]===void 0||s[9]==="")?r=+new Date(s[1],s[2],s[3],s[4],s[5],s[6],s[7]):(s[8]!=="Z"&&s[9]!==void 0&&(t=s[10]*60+s[11],s[9]==="+"&&(t=0-t)),r=Date.UTC(s[1],s[2],s[3],s[4],s[5]+t,s[6],s[7]))}else r=Date.parse?Date.parse(n):NaN;return r}let hc=new Date(""),fc=n=>Object.prototype.toString.call(n)==="[object Date]";class Er extends ne{constructor(){super({type:"date",check(e){return fc(e)&&!isNaN(e.getTime())}}),this.withMutation(()=>{this.transform((e,t,r)=>!r.spec.coerce||r.isType(e)?e:(e=lc(e),isNaN(e)?Er.INVALID_DATE:new Date(e)))})}prepareParam(e,t){let r;if(ut.isRef(e))r=e;else{let s=this.cast(e);if(!this._typeCheck(s))throw new TypeError(`\`${t}\` must be a Date or a value that can be \`cast()\` to a Date`);r=s}return r}min(e,t=mn.min){let r=this.prepareParam(e,"min");return this.test({message:t,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(s){return s>=this.resolve(r)}})}max(e,t=mn.max){let r=this.prepareParam(e,"max");return this.test({message:t,name:"max",exclusive:!0,params:{max:e},skipAbsent:!0,test(s){return s<=this.resolve(r)}})}}Er.INVALID_DATE=hc,Er.prototype;function dc(n,e=[]){let t=[],r=new Set,s=new Set(e.map(([o,a])=>`${o}-${a}`));function i(o,a){let c=at.split(o)[0];r.add(c),s.has(`${a}-${c}`)||t.push([a,c])}for(const o of Object.keys(n)){let a=n[o];r.add(o),ut.isRef(a)&&a.isSibling?i(a.path,o):gr(a)&&"deps"in a&&a.deps.forEach(c=>i(c,o))}return yr.array(Array.from(r),t).reverse()}function Fs(n,e){let t=1/0;return n.some((r,s)=>{var i;if((i=e.path)!=null&&i.includes(r))return t=s,!0}),t}function Ds(n){return(e,t)=>Fs(n,e)-Fs(n,t)}const Us=(n,e,t)=>{if(typeof n!="string")return n;let r=n;try{r=JSON.parse(n)}catch{}return t.isType(r)?r:n};function xr(n){if("fields"in n){const e={};for(const[t,r]of Object.entries(n.fields))e[t]=xr(r);return n.setFields(e)}if(n.type==="array"){const e=n.optional();return e.innerType&&(e.innerType=xr(e.innerType)),e}return n.type==="tuple"?n.optional().clone({types:n.spec.types.map(xr)}):"optional"in n?n.optional():n}const pc=(n,e)=>{const t=[...at.normalizePath(e)];if(t.length===1)return t[0]in n;let r=t.pop(),s=at.getter(at.join(t),!0)(n);return!!(s&&r in s)};let js=n=>Object.prototype.toString.call(n)==="[object Object]";function yc(n,e){let t=Object.keys(n.fields);return Object.keys(e).filter(r=>t.indexOf(r)===-1)}const mc=Ds([]);function se(n){return new Ls(n)}class Ls extends ne{constructor(e){super({type:"object",check(t){return js(t)||typeof t=="function"}}),this.fields=Object.create(null),this._sortErrors=mc,this._nodes=[],this._excludedEdges=[],this.withMutation(()=>{e&&this.shape(e)})}_cast(e,t={}){var r;let s=super._cast(e,t);if(s===void 0)return this.getDefault();if(!this._typeCheck(s))return s;let i=this.fields,o=(r=t.stripUnknown)!=null?r:this.spec.noUnknown,a=[].concat(this._nodes,Object.keys(s).filter(h=>!this._nodes.includes(h))),c={},u=Object.assign({},t,{parent:c,__validating:t.__validating||!1}),l=!1;for(const h of a){let y=i[h],p=h in s;if(y){let w,v=s[h];u.path=(t.path?`${t.path}.`:"")+h,y=y.resolve({value:v,context:t.context,parent:c});let g=y instanceof ne?y.spec:void 0,S=g==null?void 0:g.strict;if(g!=null&&g.strip){l=l||h in s;continue}w=!t.__validating||!S?y.cast(s[h],u):s[h],w!==void 0&&(c[h]=w)}else p&&!o&&(c[h]=s[h]);(p!==h in c||c[h]!==s[h])&&(l=!0)}return l?c:s}_validate(e,t={},r,s){let{from:i=[],originalValue:o=e,recursive:a=this.spec.recursive}=t;t.from=[{schema:this,value:o},...i],t.__validating=!0,t.originalValue=o,super._validate(e,t,r,(c,u)=>{if(!a||!js(u)){s(c,u);return}o=o||u;let l=[];for(let h of this._nodes){let y=this.fields[h];!y||ut.isRef(y)||l.push(y.asNestedTest({options:t,key:h,parent:u,parentPath:t.path,originalParent:o}))}this.runTests({tests:l,value:u,originalValue:o,options:t},r,h=>{s(h.sort(this._sortErrors).concat(c),u)})})}clone(e){const t=super.clone(e);return t.fields=Object.assign({},this.fields),t._nodes=this._nodes,t._excludedEdges=this._excludedEdges,t._sortErrors=this._sortErrors,t}concat(e){let t=super.concat(e),r=t.fields;for(let[s,i]of Object.entries(this.fields)){const o=r[s];r[s]=o===void 0?i:o}return t.withMutation(s=>s.setFields(r,this._excludedEdges))}_getDefault(){if("default"in this.spec)return super._getDefault();if(!this._nodes.length)return;let e={};return this._nodes.forEach(t=>{const r=this.fields[t];e[t]=r&&"getDefault"in r?r.getDefault():void 0}),e}setFields(e,t){let r=this.clone();return r.fields=e,r._nodes=dc(e,t),r._sortErrors=Ds(Object.keys(e)),t&&(r._excludedEdges=t),r}shape(e,t=[]){return this.clone().withMutation(r=>{let s=r._excludedEdges;return t.length&&(Array.isArray(t[0])||(t=[t]),s=[...r._excludedEdges,...t]),r.setFields(Object.assign(r.fields,e),s)})}partial(){const e={};for(const[t,r]of Object.entries(this.fields))e[t]="optional"in r&&r.optional instanceof Function?r.optional():r;return this.setFields(e)}deepPartial(){return xr(this)}pick(e){const t={};for(const r of e)this.fields[r]&&(t[r]=this.fields[r]);return this.setFields(t)}omit(e){const t=Object.assign({},this.fields);for(const r of e)delete t[r];return this.setFields(t)}from(e,t,r){let s=at.getter(e,!0);return this.transform(i=>{if(!i)return i;let o=i;return pc(i,e)&&(o=Object.assign({},i),r||delete o[e],o[t]=s(i)),o})}json(){return this.transform(Us)}noUnknown(e=!0,t=wn.noUnknown){typeof e!="boolean"&&(t=e,e=!0);let r=this.test({name:"noUnknown",exclusive:!0,message:t,test(s){if(s==null)return!0;const i=yc(this.schema,s);return!e||i.length===0||this.createError({params:{unknown:i.join(", ")}})}});return r.spec.noUnknown=e,r}unknown(e=!0,t=wn.noUnknown){return this.noUnknown(!e,t)}transformKeys(e){return this.transform(t=>{if(!t)return t;const r={};for(const s of Object.keys(t))r[e(s)]=t[s];return r})}camelCase(){return this.transformKeys(yn.camelCase)}snakeCase(){return this.transformKeys(yn.snakeCase)}constantCase(){return this.transformKeys(e=>yn.snakeCase(e).toUpperCase())}describe(e){let t=super.describe(e);t.fields={};for(const[s,i]of Object.entries(this.fields)){var r;let o=e;(r=o)!=null&&r.value&&(o=Object.assign({},o,{parent:o.value,value:o.value[s]})),t.fields[s]=i.describe(o)}return t}}se.prototype=Ls.prototype;function lt(n){return new Bs(n)}class Bs extends ne{constructor(e){super({type:"array",check(t){return Array.isArray(t)}}),this.innerType=void 0,this.innerType=e}_cast(e,t){const r=super._cast(e,t);if(!this._typeCheck(r)||!this.innerType)return r;let s=!1;const i=r.map((o,a)=>{const c=this.innerType.cast(o,Object.assign({},t,{path:`${t.path||""}[${a}]`}));return c!==o&&(s=!0),c});return s?i:r}_validate(e,t={},r,s){var i;let o=this.innerType,a=(i=t.recursive)!=null?i:this.spec.recursive;t.originalValue!=null&&t.originalValue,super._validate(e,t,r,(c,u)=>{var l;if(!a||!o||!this._typeCheck(u)){s(c,u);return}let h=new Array(u.length);for(let p=0;p<u.length;p++){var y;h[p]=o.asNestedTest({options:t,index:p,parent:u,parentPath:t.path,originalParent:(y=t.originalValue)!=null?y:e})}this.runTests({value:u,tests:h,originalValue:(l=t.originalValue)!=null?l:e,options:t},r,p=>s(p.concat(c),u))})}clone(e){const t=super.clone(e);return t.innerType=this.innerType,t}json(){return this.transform(Us)}concat(e){let t=super.concat(e);return t.innerType=this.innerType,e.innerType&&(t.innerType=t.innerType?t.innerType.concat(e.innerType):e.innerType),t}of(e){let t=this.clone();if(!gr(e))throw new TypeError("`array.of()` sub-schema must be a valid yup schema not: "+ct(e));return t.innerType=e,t}length(e,t=mr.length){return this.test({message:t,name:"length",exclusive:!0,params:{length:e},skipAbsent:!0,test(r){return r.length===this.resolve(e)}})}min(e,t){return t=t||mr.min,this.test({message:t,name:"min",exclusive:!0,params:{min:e},skipAbsent:!0,test(r){return r.length>=this.resolve(e)}})}max(e,t){return t=t||mr.max,this.test({message:t,name:"max",exclusive:!0,params:{max:e},skipAbsent:!0,test(r){return r.length<=this.resolve(e)}})}ensure(){return this.default(()=>[]).transform((e,t)=>this._typeCheck(e)?e:t==null?[]:[].concat(t))}compact(e){let t=e?(r,s,i)=>!e(r,s,i):r=>!!r;return this.transform(r=>r!=null?r.filter(t):r)}describe(e){let t=super.describe(e);if(this.innerType){var r;let s=e;(r=s)!=null&&r.value&&(s=Object.assign({},s,{parent:s.value,value:s.value[0]})),t.innerType=this.innerType.describe(e)}return t}}lt.prototype=Bs.prototype;const Hs=se({url:T(),height:q(),width:q()}),gc=se({type:T().default("rich"),title:T(),color:q(),thumbnail:Hs,image:Hs,url:T()}),wc=se({url:T().url().required(),username:T(),avatar_url:T().url(),message:T().required(),embed:gc}),bc="notify_discord_webhook";class bn{static async SimpleToRaw(e){return{name:"",notify_type:bc,notify:await bn.validateCreate(e)}}static validateCreate(e){return wc.validate(e)}}const vc=se({email:T().required(),subject:T(),html:T().required()}),_c="notify_email";class vn{static async SimpleToRaw(e){return{name:"",notify_type:_c,notify:await vn.validateCreate(e)}}static async validateCreate(e){return vc.validate(e)}}const Ec=se({clientId:q().required(),content:T().required()}),xc="notify_telegram";class _n{static async SimpleToRaw(e){return{name:"",notify_type:xc,notify:await _n.validateCreate(e)}}static validateCreate(e){return Ec.validate(e)}}class En{static async SimpleToRaw(e,t){switch(e){case"Discord":return bn.SimpleToRaw(t);case"Telegram":return _n.SimpleToRaw(t);case"Email":return vn.SimpleToRaw(t)}}static RawToSimple(e){return{...e.notify,error:e.error,error_message:e.error_message,error_timestamp:e.error_timestamp}}static RawTypeToSimpleType(e){switch(e){case"notify_discord_webhook":return"Discord";case"notify_telegram":return"Telegram";case"notify_email":return"Email"}}static SimpleTypeToRawType(e){switch(e){case"Discord":return"notify_discord_webhook";case"Telegram":return"notify_telegram";case"Email":return"notify_email"}}}const Tc="handler_function_call";class Ms{static async SimpleToRaw(e,t,r){return{alertType:"event",network:t,nickname:e,type:Tc,handler:await this.validate(r)}}static validate(e){const t=([s],i)=>s==="true"?i.notRequired():i.required();return se({address:T().required(),abi:lt().required(),nBlocks:q().default(100).min(10).required(),function:T().required(),condition:T().default("true").oneOf([">",">=","<","<=","=","true"]).required(),constant:q().min(0).when("condition",t),responseArgIndex:q().min(0).when("condition",t),responseArgDecimals:q().min(0).when("condition",t)}).validateSync(e)}}const Oc="handler_onchain_event";class Vs{static async SimpleToRaw(e,t,r){return{alertType:"event",network:t,nickname:e,type:Oc,handler:await this.validate(r)}}static validate(e){const t=([s],i)=>s==="true"?i.notRequired():i.required();return se({address:T().required(),event:T().required(),abi:lt().required(),condition:T().default("true").oneOf([">",">=","<","<=","=","true"]).required(),constant:q().min(0).when("condition",t),paramsIndex:q().min(0).when("condition",t),paramsDecimals:q().min(0).when("condition",t)}).validateSync(e)}}const kc="6.1.0";function Ac(n,e,t){const r=e.split("|").map(i=>i.trim());for(let i=0;i<r.length;i++)switch(e){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof n===e)return}const s=new Error(`invalid value for type ${e}`);throw s.code="INVALID_ARGUMENT",s.argument=`value.${t}`,s.value=n,s}async function zs(n){const e=Object.keys(n);return(await Promise.all(e.map(r=>Promise.resolve(n[r])))).reduce((r,s,i)=>(r[e[i]]=s,r),{})}function A(n,e,t){for(let r in e){let s=e[r];const i=t?t[r]:null;i&&Ac(s,i,r),Object.defineProperty(n,r,{enumerable:!0,value:s,writable:!1})}}function St(n){if(n==null)return"null";if(Array.isArray(n))return"[ "+n.map(St).join(", ")+" ]";if(n instanceof Uint8Array){const e="0123456789abcdef";let t="0x";for(let r=0;r<n.length;r++)t+=e[n[r]>>4],t+=e[n[r]&15];return t}if(typeof n=="object"&&typeof n.toJSON=="function")return St(n.toJSON());switch(typeof n){case"boolean":case"symbol":return n.toString();case"bigint":return BigInt(n).toString();case"number":return n.toString();case"string":return JSON.stringify(n);case"object":{const e=Object.keys(n);return e.sort(),"{ "+e.map(t=>`${St(t)}: ${St(n[t])}`).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function Tr(n,e){return n&&n.code===e}function qs(n){return Tr(n,"CALL_EXCEPTION")}function Or(n,e,t){{const s=[];if(t){if("message"in t||"code"in t||"name"in t)throw new Error(`value will overwrite populated values: ${St(t)}`);for(const i in t){const o=t[i];s.push(i+"="+St(o))}}s.push(`code=${e}`),s.push(`version=${kc}`),s.length&&(n+=" ("+s.join(", ")+")")}let r;switch(e){case"INVALID_ARGUMENT":r=new TypeError(n);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":r=new RangeError(n);break;default:r=new Error(n)}return A(r,{code:e}),t&&Object.assign(r,t),r}function x(n,e,t,r){if(!n)throw Or(e,t,r)}function _(n,e,t,r){x(n,e,"INVALID_ARGUMENT",{argument:t,value:r})}function Gs(n,e,t){t==null&&(t=""),t&&(t=": "+t),x(n>=e,"missing arguemnt"+t,"MISSING_ARGUMENT",{count:n,expectedCount:e}),x(n<=e,"too many arguemnts"+t,"UNEXPECTED_ARGUMENT",{count:n,expectedCount:e})}const Sc=["NFD","NFC","NFKD","NFKC"].reduce((n,e)=>{try{if("test".normalize(e)!=="test")throw new Error("bad");if(e==="NFD"){const t=String.fromCharCode(233).normalize("NFD"),r=String.fromCharCode(101,769);if(t!==r)throw new Error("broken")}n.push(e)}catch{}return n},[]);function Rc(n){x(Sc.indexOf(n)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:n}})}function xn(n,e,t){if(t==null&&(t=""),n!==e){let r=t,s="new";t&&(r+=".",s+=" "+t),x(!1,`private constructor; use ${r}from* methods`,"UNSUPPORTED_OPERATION",{operation:s})}}function Js(n,e,t){if(n instanceof Uint8Array)return t?new Uint8Array(n):n;if(typeof n=="string"&&n.match(/^0x([0-9a-f][0-9a-f])*$/i)){const r=new Uint8Array((n.length-2)/2);let s=2;for(let i=0;i<r.length;i++)r[i]=parseInt(n.substring(s,s+2),16),s+=2;return r}_(!1,"invalid BytesLike value",e||"value",n)}function Ne(n,e){return Js(n,e,!1)}function Ie(n,e){return Js(n,e,!0)}function qe(n,e){return!(typeof n!="string"||!n.match(/^0x[0-9A-Fa-f]*$/)||typeof e=="number"&&n.length!==2+2*e||e===!0&&n.length%2!==0)}const Ws="0123456789abcdef";function z(n){const e=Ne(n);let t="0x";for(let r=0;r<e.length;r++){const s=e[r];t+=Ws[(s&240)>>4]+Ws[s&15]}return t}function Rt(n){return"0x"+n.map(e=>z(e).substring(2)).join("")}function $t(n,e,t){const r=Ne(n);return t!=null&&t>r.length&&x(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:r,length:r.length,offset:t}),z(r.slice(e??0,t??r.length))}function $c(n,e,t){const r=Ne(n);x(e>=r.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(r),length:e,offset:e+1});const s=new Uint8Array(e);return s.fill(0),t?s.set(r,e-r.length):s.set(r,0),z(s)}function Pc(n,e){return $c(n,e,!0)}const kr=BigInt(0),ge=BigInt(1),Pt=9007199254740991;function Nc(n,e){const t=Sr(n,"value"),r=BigInt(Ce(e,"width"));if(x(t>>r===kr,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:n}),t>>r-ge){const s=(ge<<r)-ge;return-((~t&s)+ge)}return t}function Ic(n,e){let t=ht(n,"value");const r=BigInt(Ce(e,"width")),s=ge<<r-ge;if(t<kr){t=-t,x(t<=s,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:n});const i=(ge<<r)-ge;return(~t&i)+ge}else x(t<s,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:n});return t}function Ar(n,e){const t=Sr(n,"value"),r=BigInt(Ce(e,"bits"));return t&(ge<<r)-ge}function ht(n,e){switch(typeof n){case"bigint":return n;case"number":return _(Number.isInteger(n),"underflow",e||"value",n),_(n>=-Pt&&n<=Pt,"overflow",e||"value",n),BigInt(n);case"string":try{if(n==="")throw new Error("empty string");return n[0]==="-"&&n[1]!=="-"?-BigInt(n.substring(1)):BigInt(n)}catch(t){_(!1,`invalid BigNumberish string: ${t.message}`,e||"value",n)}}_(!1,"invalid BigNumberish value",e||"value",n)}function Sr(n,e){const t=ht(n,e);return x(t>=kr,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:n}),t}const Ks="0123456789abcdef";function Xs(n){if(n instanceof Uint8Array){let e="0x0";for(const t of n)e+=Ks[t>>4],e+=Ks[t&15];return BigInt(e)}return ht(n)}function Ce(n,e){switch(typeof n){case"bigint":return _(n>=-Pt&&n<=Pt,"overflow",e||"value",n),Number(n);case"number":return _(Number.isInteger(n),"underflow",e||"value",n),_(n>=-Pt&&n<=Pt,"overflow",e||"value",n),n;case"string":try{if(n==="")throw new Error("empty string");return Ce(BigInt(n),e)}catch(t){_(!1,`invalid numeric string: ${t.message}`,e||"value",n)}}_(!1,"invalid numeric value",e||"value",n)}function Cc(n){return Ce(Xs(n))}function Zs(n,e){let r=Sr(n,"value").toString(16);if(e==null)r.length%2&&(r="0"+r);else{const s=Ce(e,"width");for(x(s*2>=r.length,`value exceeds width (${s} bits)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:n});r.length<s*2;)r="0"+r}return"0x"+r}function Fc(n){const e=Sr(n,"value");if(e===kr)return new Uint8Array([]);let t=e.toString(16);t.length%2&&(t="0"+t);const r=new Uint8Array(t.length/2);for(let s=0;s<r.length;s++){const i=s*2;r[s]=parseInt(t.substring(i,i+2),16)}return r}class Dc{constructor(e,t,r){d(this,"filter");d(this,"emitter");j(this,It,void 0);N(this,It,t),A(this,{emitter:e,filter:r})}async removeListener(){m(this,It)!=null&&await this.emitter.off(this.filter,m(this,It))}}It=new WeakMap;function Uc(n,e,t,r,s){_(!1,`invalid codepoint at offset ${e}; ${n}`,"bytes",t)}function Ys(n,e,t,r,s){if(n==="BAD_PREFIX"||n==="UNEXPECTED_CONTINUE"){let i=0;for(let o=e+1;o<t.length&&t[o]>>6===2;o++)i++;return i}return n==="OVERRUN"?t.length-e-1:0}function jc(n,e,t,r,s){return n==="OVERLONG"?(_(typeof s=="number","invalid bad code point for replacement","badCodepoint",s),r.push(s),0):(r.push(65533),Ys(n,e,t))}const Lc=Object.freeze({error:Uc,ignore:Ys,replace:jc});function Bc(n,e){e==null&&(e=Lc.error);const t=Ne(n,"bytes"),r=[];let s=0;for(;s<t.length;){const i=t[s++];if(!(i>>7)){r.push(i);continue}let o=null,a=null;if((i&224)===192)o=1,a=127;else if((i&240)===224)o=2,a=2047;else if((i&248)===240)o=3,a=65535;else{(i&192)===128?s+=e("UNEXPECTED_CONTINUE",s-1,t,r):s+=e("BAD_PREFIX",s-1,t,r);continue}if(s-1+o>=t.length){s+=e("OVERRUN",s-1,t,r);continue}let c=i&(1<<8-o-1)-1;for(let u=0;u<o;u++){let l=t[s];if((l&192)!=128){s+=e("MISSING_CONTINUE",s,t,r),c=null;break}c=c<<6|l&63,s++}if(c!==null){if(c>1114111){s+=e("OUT_OF_RANGE",s-1-o,t,r,c);continue}if(c>=55296&&c<=57343){s+=e("UTF16_SURROGATE",s-1-o,t,r,c);continue}if(c<=a){s+=e("OVERLONG",s-1-o,t,r,c);continue}r.push(c)}}return r}function Qs(n,e){e!=null&&(Rc(e),n=n.normalize(e));let t=[];for(let r=0;r<n.length;r++){const s=n.charCodeAt(r);if(s<128)t.push(s);else if(s<2048)t.push(s>>6|192),t.push(s&63|128);else if((s&64512)==55296){r++;const i=n.charCodeAt(r);_(r<n.length&&(i&64512)===56320,"invalid surrogate pair","str",n);const o=65536+((s&1023)<<10)+(i&1023);t.push(o>>18|240),t.push(o>>12&63|128),t.push(o>>6&63|128),t.push(o&63|128)}else t.push(s>>12|224),t.push(s>>6&63|128),t.push(s&63|128)}return new Uint8Array(t)}function Hc(n){return n.map(e=>e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10&1023)+55296,(e&1023)+56320))).join("")}function Mc(n,e){return Hc(Bc(n,e))}const Q=32,Tn=new Uint8Array(Q),Vc=["then"],Rr={};function $r(n,e){const t=new Error(`deferred error during ABI decoding triggered accessing ${n}`);throw t.error=e,t}const Qt=class extends Array{constructor(...t){const r=t[0];let s=t[1],i=(t[2]||[]).slice(),o=!0;r!==Rr&&(s=t,i=[],o=!1);super(s.length);j(this,Xe,void 0);s.forEach((c,u)=>{this[u]=c});const a=i.reduce((c,u)=>(typeof u=="string"&&c.set(u,(c.get(u)||0)+1),c),new Map);if(N(this,Xe,Object.freeze(s.map((c,u)=>{const l=i[u];return l!=null&&a.get(l)===1?l:null}))),!!o)return Object.freeze(this),new Proxy(this,{get:(c,u,l)=>{if(typeof u=="string"){if(u.match(/^[0-9]+$/)){const y=Ce(u,"%index");if(y<0||y>=this.length)throw new RangeError("out of result range");const p=c[y];return p instanceof Error&&$r(`index ${y}`,p),p}if(Vc.indexOf(u)>=0)return Reflect.get(c,u,l);const h=c[u];if(h instanceof Function)return function(...y){return h.apply(this===l?c:this,y)};if(!(u in c))return c.getValue.apply(this===l?c:this,[u])}return Reflect.get(c,u,l)}})}toArray(){const t=[];return this.forEach((r,s)=>{r instanceof Error&&$r(`index ${s}`,r),t.push(r)}),t}toObject(){return m(this,Xe).reduce((t,r,s)=>(x(r!=null,"value at index ${ index } unnamed","UNSUPPORTED_OPERATION",{operation:"toObject()"}),r in t||(t[r]=this.getValue(r)),t),{})}slice(t,r){t==null&&(t=0),t<0&&(t+=this.length,t<0&&(t=0)),r==null&&(r=this.length),r<0&&(r+=this.length,r<0&&(r=0)),r>this.length&&(r=this.length);const s=[],i=[];for(let o=t;o<r;o++)s.push(this[o]),i.push(m(this,Xe)[o]);return new Qt(Rr,s,i)}filter(t,r){const s=[],i=[];for(let o=0;o<this.length;o++){const a=this[o];a instanceof Error&&$r(`index ${o}`,a),t.call(r,a,o,this)&&(s.push(a),i.push(m(this,Xe)[o]))}return new Qt(Rr,s,i)}getValue(t){const r=m(this,Xe).indexOf(t);if(r===-1)return;const s=this[r];return s instanceof Error&&$r(`property ${JSON.stringify(t)}`,s.error),s}static fromItems(t,r){return new Qt(Rr,t,r)}};let Pr=Qt;Xe=new WeakMap;function ei(n){let e=Fc(n);return x(e.length<=Q,"value out-of-bounds","BUFFER_OVERRUN",{buffer:e,length:Q,offset:e.length}),e.length!==Q&&(e=Ie(Rt([Tn.slice(e.length%Q),e]))),e}class Fe{constructor(e,t,r,s){d(this,"name");d(this,"type");d(this,"localName");d(this,"dynamic");A(this,{name:e,type:t,localName:r,dynamic:s},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(e,t){_(!1,e,this.localName,t)}}class On{constructor(){j(this,Ct);j(this,Me,void 0);j(this,bt,void 0);N(this,Me,[]),N(this,bt,0)}get data(){return Rt(m(this,Me))}get length(){return m(this,bt)}appendWriter(e){return V(this,Ct,Jr).call(this,Ie(e.data))}writeBytes(e){let t=Ie(e);const r=t.length%Q;return r&&(t=Ie(Rt([t,Tn.slice(r)]))),V(this,Ct,Jr).call(this,t)}writeValue(e){return V(this,Ct,Jr).call(this,ei(e))}writeUpdatableValue(){const e=m(this,Me).length;return m(this,Me).push(Tn),N(this,bt,m(this,bt)+Q),t=>{m(this,Me)[e]=ei(t)}}}Me=new WeakMap,bt=new WeakMap,Ct=new WeakSet,Jr=function(e){return m(this,Me).push(e),N(this,bt,m(this,bt)+e.length),e.length};const Kn=class{constructor(e,t){j(this,Lr);d(this,"allowLoose");j(this,ue,void 0);j(this,de,void 0);A(this,{allowLoose:!!t}),N(this,ue,Ie(e)),N(this,de,0)}get data(){return z(m(this,ue))}get dataLength(){return m(this,ue).length}get consumed(){return m(this,de)}get bytes(){return new Uint8Array(m(this,ue))}subReader(e){return new Kn(m(this,ue).slice(m(this,de)+e),this.allowLoose)}readBytes(e,t){let r=V(this,Lr,to).call(this,0,e,!!t);return N(this,de,m(this,de)+r.length),r.slice(0,e)}readValue(){return Xs(this.readBytes(Q))}readIndex(){return Cc(this.readBytes(Q))}};let kn=Kn;ue=new WeakMap,de=new WeakMap,Lr=new WeakSet,to=function(e,t,r){let s=Math.ceil(t/Q)*Q;return m(this,de)+s>m(this,ue).length&&(this.allowLoose&&r&&m(this,de)+t<=m(this,ue).length?s=t:x(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:Ie(m(this,ue)),length:m(this,ue).length,offset:m(this,de)+s})),m(this,ue).slice(m(this,de),m(this,de)+s)};function An(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function zc(n){if(typeof n!="boolean")throw new Error(`Expected boolean, not ${n}`)}function ti(n,...e){if(!(n instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(e.length>0&&!e.includes(n.length))throw new TypeError(`Expected Uint8Array of length ${e}, not of length=${n.length}`)}function qc(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");An(n.outputLen),An(n.blockLen)}function Gc(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function Jc(n,e){ti(n);const t=e.outputLen;if(n.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}const Nt={number:An,bool:zc,bytes:ti,hash:qc,exists:Gc,output:Jc};/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Wc=n=>new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4));if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function Kc(n){if(typeof n!="string")throw new TypeError(`utf8ToBytes expected string, got ${typeof n}`);return new TextEncoder().encode(n)}function Sn(n){if(typeof n=="string"&&(n=Kc(n)),!(n instanceof Uint8Array))throw new TypeError(`Expected input type is Uint8Array (got ${typeof n})`);return n}class Xc{clone(){return this._cloneInto()}}function Zc(n){const e=r=>n().update(Sn(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function Yc(n){const e=(r,s)=>n(s).update(Sn(r)).digest(),t=n({});return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=r=>n(r),e}const Nr=BigInt(2**32-1),Rn=BigInt(32);function ri(n,e=!1){return e?{h:Number(n&Nr),l:Number(n>>Rn&Nr)}:{h:Number(n>>Rn&Nr)|0,l:Number(n&Nr)|0}}function Qc(n,e=!1){let t=new Uint32Array(n.length),r=new Uint32Array(n.length);for(let s=0;s<n.length;s++){const{h:i,l:o}=ri(n[s],e);[t[s],r[s]]=[i,o]}return[t,r]}const eu=(n,e)=>BigInt(n>>>0)<<Rn|BigInt(e>>>0),tu=(n,e,t)=>n>>>t,ru=(n,e,t)=>n<<32-t|e>>>t,nu=(n,e,t)=>n>>>t|e<<32-t,su=(n,e,t)=>n<<32-t|e>>>t,iu=(n,e,t)=>n<<64-t|e>>>t-32,ou=(n,e,t)=>n>>>t-32|e<<64-t,au=(n,e)=>e,cu=(n,e)=>n,uu=(n,e,t)=>n<<t|e>>>32-t,lu=(n,e,t)=>e<<t|n>>>32-t,hu=(n,e,t)=>e<<t-32|n>>>64-t,fu=(n,e,t)=>n<<t-32|e>>>64-t;function du(n,e,t,r){const s=(e>>>0)+(r>>>0);return{h:n+t+(s/4294967296|0)|0,l:s|0}}const Gt={fromBig:ri,split:Qc,toBig:eu,shrSH:tu,shrSL:ru,rotrSH:nu,rotrSL:su,rotrBH:iu,rotrBL:ou,rotr32H:au,rotr32L:cu,rotlSH:uu,rotlSL:lu,rotlBH:hu,rotlBL:fu,add:du,add3L:(n,e,t)=>(n>>>0)+(e>>>0)+(t>>>0),add3H:(n,e,t,r)=>e+t+r+(n/2**32|0)|0,add4L:(n,e,t,r)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0),add4H:(n,e,t,r,s)=>e+t+r+s+(n/2**32|0)|0,add5H:(n,e,t,r,s,i)=>e+t+r+s+i+(n/2**32|0)|0,add5L:(n,e,t,r,s)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0)},[ni,si,ii]=[[],[],[]],pu=BigInt(0),Jt=BigInt(1),yu=BigInt(2),mu=BigInt(7),gu=BigInt(256),wu=BigInt(113);for(let n=0,e=Jt,t=1,r=0;n<24;n++){[t,r]=[r,(2*t+3*r)%5],ni.push(2*(5*r+t)),si.push((n+1)*(n+2)/2%64);let s=pu;for(let i=0;i<7;i++)e=(e<<Jt^(e>>mu)*wu)%gu,e&yu&&(s^=Jt<<(Jt<<BigInt(i))-Jt);ii.push(s)}const[bu,vu]=Gt.split(ii,!0),oi=(n,e,t)=>t>32?Gt.rotlBH(n,e,t):Gt.rotlSH(n,e,t),ai=(n,e,t)=>t>32?Gt.rotlBL(n,e,t):Gt.rotlSL(n,e,t);function _u(n,e=24){const t=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)t[o]=n[o]^n[o+10]^n[o+20]^n[o+30]^n[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=t[c],l=t[c+1],h=oi(u,l,1)^t[a],y=ai(u,l,1)^t[a+1];for(let p=0;p<50;p+=10)n[o+p]^=h,n[o+p+1]^=y}let s=n[2],i=n[3];for(let o=0;o<24;o++){const a=si[o],c=oi(s,i,a),u=ai(s,i,a),l=ni[o];s=n[l],i=n[l+1],n[l]=c,n[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=n[o+a];for(let a=0;a<10;a++)n[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}n[0]^=bu[r],n[1]^=vu[r]}t.fill(0)}class Ir extends Xc{constructor(e,t,r,s=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=s,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Nt.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Wc(this.state)}keccak(){_u(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){Nt.exists(this);const{blockLen:t,state:r}=this;e=Sn(e);const s=e.length;for(let i=0;i<s;){const o=Math.min(t-this.pos,s-i);for(let a=0;a<o;a++)r[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:r,blockLen:s}=this;e[r]^=t,t&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Nt.exists(this,!1),Nt.bytes(e),this.finish();const t=this.state,{blockLen:r}=this;for(let s=0,i=e.length;s<i;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,i-s);e.set(t.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Nt.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Nt.output(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:s,rounds:i,enableXOF:o}=this;return e||(e=new Ir(t,r,s,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Ge=(n,e,t)=>Zc(()=>new Ir(e,n,t));Ge(6,144,28),Ge(6,136,32),Ge(6,104,48),Ge(6,72,64),Ge(1,144,28);const Eu=Ge(1,136,256/8);Ge(1,104,48),Ge(1,72,64);const ci=(n,e,t)=>Yc((r={})=>new Ir(e,n,r.dkLen===void 0?t:r.dkLen,!0));ci(31,168,16),ci(31,136,32);let ui=!1;const li=function(n){return Eu(n)};let hi=li;function Je(n){const e=Ne(n,"data");return z(hi(e))}Je._=li,Je.lock=function(){ui=!0},Je.register=function(n){if(ui)throw new TypeError("keccak256 is locked");hi=n},Object.freeze(Je);const xu=BigInt(0),Tu=BigInt(36);function fi(n){n=n.toLowerCase();const e=n.substring(2).split(""),t=new Uint8Array(40);for(let s=0;s<40;s++)t[s]=e[s].charCodeAt(0);const r=Ne(Je(t));for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&(e[s]=e[s].toUpperCase()),(r[s>>1]&15)>=8&&(e[s+1]=e[s+1].toUpperCase());return"0x"+e.join("")}const $n={};for(let n=0;n<10;n++)$n[String(n)]=String(n);for(let n=0;n<26;n++)$n[String.fromCharCode(65+n)]=String(10+n);const di=15;function Ou(n){n=n.toUpperCase(),n=n.substring(4)+n.substring(0,2)+"00";let e=n.split("").map(r=>$n[r]).join("");for(;e.length>=di;){let r=e.substring(0,di);e=parseInt(r,10)%97+e.substring(r.length)}let t=String(98-parseInt(e,10)%97);for(;t.length<2;)t="0"+t;return t}const ku=function(){const n={};for(let e=0;e<36;e++){const t="0123456789abcdefghijklmnopqrstuvwxyz"[e];n[t]=BigInt(e)}return n}();function Au(n){n=n.toLowerCase();let e=xu;for(let t=0;t<n.length;t++)e=e*Tu+ku[n[t]];return e}function ft(n){if(_(typeof n=="string","invalid address","address",n),n.match(/^(0x)?[0-9a-fA-F]{40}$/)){n.startsWith("0x")||(n="0x"+n);const e=fi(n);return _(!n.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||e===n,"bad address checksum","address",n),e}if(n.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){_(n.substring(2,4)===Ou(n),"bad icap checksum","address",n);let e=Au(n.substring(4)).toString(16);for(;e.length<40;)e="0"+e;return fi("0x"+e)}_(!1,"invalid address","address",n)}function Su(n){return n&&typeof n.getAddress=="function"}async function Pn(n,e){const t=await e;return(t==null||t==="0x0000000000000000000000000000000000000000")&&(x(typeof n!="string","unconfigured name","UNCONFIGURED_NAME",{value:n}),_(!1,"invalid AddressLike value; did not resolve to a value address","target",n)),ft(t)}function Nn(n,e){if(typeof n=="string")return n.match(/^0x[0-9a-f]{40}$/i)?ft(n):(x(e!=null,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),Pn(n,e.resolveName(n)));if(Su(n))return Pn(n,n.getAddress());if(n&&typeof n.then=="function")return Pn(n,n);_(!1,"unsupported addressable value","target",n)}const De={};function E(n,e){let t=!1;return e<0&&(t=!0,e*=-1),new X(De,`${t?"":"u"}int${e}`,n,{signed:t,width:e})}function $(n,e){return new X(De,`bytes${e||""}`,n,{size:e})}const pi=Symbol.for("_ethers_typed"),Ve=class{constructor(e,t,r,s){d(this,"type");d(this,"value");j(this,vt,void 0);d(this,"_typedSymbol");s==null&&(s=null),xn(De,e,"Typed"),A(this,{_typedSymbol:pi,type:t,value:r}),N(this,vt,s),this.format()}format(){if(this.type==="array")throw new Error("");if(this.type==="dynamicArray")throw new Error("");return this.type==="tuple"?`tuple(${this.value.map(e=>e.format()).join(",")})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return this.type==="string"}get tupleName(){if(this.type!=="tuple")throw TypeError("not a tuple");return m(this,vt)}get arrayLength(){if(this.type!=="array")throw TypeError("not an array");return m(this,vt)===!0?-1:m(this,vt)===!1?this.value.length:null}static from(e,t){return new Ve(De,e,t)}static uint8(e){return E(e,8)}static uint16(e){return E(e,16)}static uint24(e){return E(e,24)}static uint32(e){return E(e,32)}static uint40(e){return E(e,40)}static uint48(e){return E(e,48)}static uint56(e){return E(e,56)}static uint64(e){return E(e,64)}static uint72(e){return E(e,72)}static uint80(e){return E(e,80)}static uint88(e){return E(e,88)}static uint96(e){return E(e,96)}static uint104(e){return E(e,104)}static uint112(e){return E(e,112)}static uint120(e){return E(e,120)}static uint128(e){return E(e,128)}static uint136(e){return E(e,136)}static uint144(e){return E(e,144)}static uint152(e){return E(e,152)}static uint160(e){return E(e,160)}static uint168(e){return E(e,168)}static uint176(e){return E(e,176)}static uint184(e){return E(e,184)}static uint192(e){return E(e,192)}static uint200(e){return E(e,200)}static uint208(e){return E(e,208)}static uint216(e){return E(e,216)}static uint224(e){return E(e,224)}static uint232(e){return E(e,232)}static uint240(e){return E(e,240)}static uint248(e){return E(e,248)}static uint256(e){return E(e,256)}static uint(e){return E(e,256)}static int8(e){return E(e,-8)}static int16(e){return E(e,-16)}static int24(e){return E(e,-24)}static int32(e){return E(e,-32)}static int40(e){return E(e,-40)}static int48(e){return E(e,-48)}static int56(e){return E(e,-56)}static int64(e){return E(e,-64)}static int72(e){return E(e,-72)}static int80(e){return E(e,-80)}static int88(e){return E(e,-88)}static int96(e){return E(e,-96)}static int104(e){return E(e,-104)}static int112(e){return E(e,-112)}static int120(e){return E(e,-120)}static int128(e){return E(e,-128)}static int136(e){return E(e,-136)}static int144(e){return E(e,-144)}static int152(e){return E(e,-152)}static int160(e){return E(e,-160)}static int168(e){return E(e,-168)}static int176(e){return E(e,-176)}static int184(e){return E(e,-184)}static int192(e){return E(e,-192)}static int200(e){return E(e,-200)}static int208(e){return E(e,-208)}static int216(e){return E(e,-216)}static int224(e){return E(e,-224)}static int232(e){return E(e,-232)}static int240(e){return E(e,-240)}static int248(e){return E(e,-248)}static int256(e){return E(e,-256)}static int(e){return E(e,-256)}static bytes1(e){return $(e,1)}static bytes2(e){return $(e,2)}static bytes3(e){return $(e,3)}static bytes4(e){return $(e,4)}static bytes5(e){return $(e,5)}static bytes6(e){return $(e,6)}static bytes7(e){return $(e,7)}static bytes8(e){return $(e,8)}static bytes9(e){return $(e,9)}static bytes10(e){return $(e,10)}static bytes11(e){return $(e,11)}static bytes12(e){return $(e,12)}static bytes13(e){return $(e,13)}static bytes14(e){return $(e,14)}static bytes15(e){return $(e,15)}static bytes16(e){return $(e,16)}static bytes17(e){return $(e,17)}static bytes18(e){return $(e,18)}static bytes19(e){return $(e,19)}static bytes20(e){return $(e,20)}static bytes21(e){return $(e,21)}static bytes22(e){return $(e,22)}static bytes23(e){return $(e,23)}static bytes24(e){return $(e,24)}static bytes25(e){return $(e,25)}static bytes26(e){return $(e,26)}static bytes27(e){return $(e,27)}static bytes28(e){return $(e,28)}static bytes29(e){return $(e,29)}static bytes30(e){return $(e,30)}static bytes31(e){return $(e,31)}static bytes32(e){return $(e,32)}static address(e){return new Ve(De,"address",e)}static bool(e){return new Ve(De,"bool",!!e)}static bytes(e){return new Ve(De,"bytes",e)}static string(e){return new Ve(De,"string",e)}static array(e,t){throw new Error("not implemented yet")}static tuple(e,t){throw new Error("not implemented yet")}static overrides(e){return new Ve(De,"overrides",Object.assign({},e))}static isTyped(e){return e&&e._typedSymbol===pi}static dereference(e,t){if(Ve.isTyped(e)){if(e.type!==t)throw new Error(`invalid type: expecetd ${t}, got ${e.type}`);return e.value}return e}};let X=Ve;vt=new WeakMap;class Ru extends Fe{constructor(e){super("address","address",e,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(e,t){let r=X.dereference(t,"string");try{r=ft(r)}catch(s){return this._throwError(s.message,t)}return e.writeValue(r)}decode(e){return ft(Zs(e.readValue(),20))}}class $u extends Fe{constructor(t){super(t.name,t.type,"_",t.dynamic);d(this,"coder");this.coder=t}defaultValue(){return this.coder.defaultValue()}encode(t,r){return this.coder.encode(t,r)}decode(t){return this.coder.decode(t)}}function yi(n,e,t){let r=[];if(Array.isArray(t))r=t;else if(t&&typeof t=="object"){let c={};r=e.map(u=>{const l=u.localName;return x(l,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:u},value:t}),x(!c[l],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:u},value:t}),c[l]=!0,t[l]})}else _(!1,"invalid tuple value","tuple",t);_(e.length===r.length,"types/value length mismatch","tuple",t);let s=new On,i=new On,o=[];e.forEach((c,u)=>{let l=r[u];if(c.dynamic){let h=i.length;c.encode(i,l);let y=s.writeUpdatableValue();o.push(p=>{y(p+h)})}else c.encode(s,l)}),o.forEach(c=>{c(s.length)});let a=n.appendWriter(s);return a+=n.appendWriter(i),a}function mi(n,e){let t=[],r=[],s=n.subReader(0);return e.forEach(i=>{let o=null;if(i.dynamic){let a=n.readIndex(),c=s.subReader(a);try{o=i.decode(c)}catch(u){if(Tr(u,"BUFFER_OVERRUN"))throw u;o=u,o.baseType=i.name,o.name=i.localName,o.type=i.type}}else try{o=i.decode(n)}catch(a){if(Tr(a,"BUFFER_OVERRUN"))throw a;o=a,o.baseType=i.name,o.name=i.localName,o.type=i.type}if(o==null)throw new Error("investigate");t.push(o),r.push(i.localName||null)}),Pr.fromItems(t,r)}class Pu extends Fe{constructor(t,r,s){const i=t.type+"["+(r>=0?r:"")+"]",o=r===-1||t.dynamic;super("array",i,s,o);d(this,"coder");d(this,"length");A(this,{coder:t,length:r})}defaultValue(){const t=this.coder.defaultValue(),r=[];for(let s=0;s<this.length;s++)r.push(t);return r}encode(t,r){const s=X.dereference(r,"array");Array.isArray(s)||this._throwError("expected array value",s);let i=this.length;i===-1&&(i=s.length,t.writeValue(s.length)),Gs(s.length,i,"coder array"+(this.localName?" "+this.localName:""));let o=[];for(let a=0;a<s.length;a++)o.push(this.coder);return yi(t,o,s)}decode(t){let r=this.length;r===-1&&(r=t.readIndex(),x(r*Q<=t.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:t.bytes,offset:r*Q,length:t.dataLength}));let s=[];for(let i=0;i<r;i++)s.push(new $u(this.coder));return mi(t,s)}}class Nu extends Fe{constructor(e){super("bool","bool",e,!1)}defaultValue(){return!1}encode(e,t){const r=X.dereference(t,"bool");return e.writeValue(r?1:0)}decode(e){return!!e.readValue()}}class gi extends Fe{constructor(e,t){super(e,e,t,!0)}defaultValue(){return"0x"}encode(e,t){t=Ie(t);let r=e.writeValue(t.length);return r+=e.writeBytes(t),r}decode(e){return e.readBytes(e.readIndex(),!0)}}class Iu extends gi{constructor(e){super("bytes",e)}decode(e){return z(super.decode(e))}}class Cu extends Fe{constructor(t,r){let s="bytes"+String(t);super(s,s,r,!1);d(this,"size");A(this,{size:t},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+this.size*2)}encode(t,r){let s=Ie(X.dereference(r,this.type));return s.length!==this.size&&this._throwError("incorrect data length",r),t.writeBytes(s)}decode(t){return z(t.readBytes(this.size))}}const Fu=new Uint8Array([]);class Du extends Fe{constructor(e){super("null","",e,!1)}defaultValue(){return null}encode(e,t){return t!=null&&this._throwError("not null",t),e.writeBytes(Fu)}decode(e){return e.readBytes(0),null}}const Uu=BigInt(0),ju=BigInt(1),Lu=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class Bu extends Fe{constructor(t,r,s){const i=(r?"int":"uint")+t*8;super(i,i,s,!1);d(this,"size");d(this,"signed");A(this,{size:t,signed:r},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(t,r){let s=ht(X.dereference(r,this.type)),i=Ar(Lu,Q*8);if(this.signed){let o=Ar(i,this.size*8-1);(s>o||s<-(o+ju))&&this._throwError("value out-of-bounds",r),s=Ic(s,8*Q)}else(s<Uu||s>Ar(i,this.size*8))&&this._throwError("value out-of-bounds",r);return t.writeValue(s)}decode(t){let r=Ar(t.readValue(),this.size*8);return this.signed&&(r=Nc(r,this.size*8)),r}}class Hu extends gi{constructor(e){super("string",e)}defaultValue(){return""}encode(e,t){return super.encode(e,Qs(X.dereference(t,"string")))}decode(e){return Mc(super.decode(e))}}class Cr extends Fe{constructor(t,r){let s=!1;const i=[];t.forEach(a=>{a.dynamic&&(s=!0),i.push(a.type)});const o="tuple("+i.join(",")+")";super("tuple",o,r,s);d(this,"coders");A(this,{coders:Object.freeze(t.slice())})}defaultValue(){const t=[];this.coders.forEach(s=>{t.push(s.defaultValue())});const r=this.coders.reduce((s,i)=>{const o=i.localName;return o&&(s[o]||(s[o]=0),s[o]++),s},{});return this.coders.forEach((s,i)=>{let o=s.localName;!o||r[o]!==1||(o==="length"&&(o="_length"),t[o]==null&&(t[o]=t[i]))}),Object.freeze(t)}encode(t,r){const s=X.dereference(r,"tuple");return yi(t,this.coders,s)}decode(t){return mi(t,this.coders)}}function Wt(n){return Je(Qs(n))}function In(n,e){return{address:ft(n),storageKeys:e.map((t,r)=>(_(qe(t,32),"invalid slot",`storageKeys[${r}]`,t),t.toLowerCase()))}}function Mu(n){if(Array.isArray(n))return n.map((t,r)=>Array.isArray(t)?(_(t.length===2,"invalid slot set",`value[${r}]`,t),In(t[0],t[1])):(_(t!=null&&typeof t=="object","invalid address-slot set","value",n),In(t.address,t.storageKeys)));_(n!=null&&typeof n=="object","invalid access list","value",n);const e=Object.keys(n).map(t=>{const r=n[t].reduce((s,i)=>(s[i]=!0,s),{});return In(t,Object.keys(r).sort())});return e.sort((t,r)=>t.address.localeCompare(r.address)),e}function ee(n){const e=new Set;return n.forEach(t=>e.add(t)),Object.freeze(e)}const wi="constant external internal payable private public pure view",Vu=ee(wi.split(" ")),bi="constructor error event fallback function receive struct",vi=ee(bi.split(" ")),_i="calldata memory storage payable indexed",zu=ee(_i.split(" ")),qu=[bi,_i,"tuple returns",wi].join(" "),Gu=ee(qu.split(" ")),Ju={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},Wu=new RegExp("^(\\s*)"),Ku=new RegExp("^([0-9]+)"),Xu=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),Ei=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),xi=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$"),Br=class{constructor(e){j(this,er);j(this,J,void 0);j(this,ve,void 0);N(this,J,0),N(this,ve,e.slice())}get offset(){return m(this,J)}get length(){return m(this,ve).length-m(this,J)}clone(){return new Br(m(this,ve))}reset(){N(this,J,0)}popKeyword(e){const t=this.peek();if(t.type!=="KEYWORD"||!e.has(t.text))throw new Error(`expected keyword ${t.text}`);return this.pop().text}popType(e){if(this.peek().type!==e)throw new Error(`expected ${e}; got ${JSON.stringify(this.peek())}`);return this.pop().text}popParen(){const e=this.peek();if(e.type!=="OPEN_PAREN")throw new Error("bad start");const t=V(this,er,Qn).call(this,m(this,J)+1,e.match+1);return N(this,J,e.match+1),t}popParams(){const e=this.peek();if(e.type!=="OPEN_PAREN")throw new Error("bad start");const t=[];for(;m(this,J)<e.match-1;){const r=this.peek().linkNext;t.push(V(this,er,Qn).call(this,m(this,J)+1,r)),N(this,J,r)}return N(this,J,e.match+1),t}peek(){if(m(this,J)>=m(this,ve).length)throw new Error("out-of-bounds");return m(this,ve)[m(this,J)]}peekKeyword(e){const t=this.peekType("KEYWORD");return t!=null&&e.has(t)?t:null}peekType(e){if(this.length===0)return null;const t=this.peek();return t.type===e?t.text:null}pop(){const e=this.peek();return eo(this,J)._++,e}toString(){const e=[];for(let t=m(this,J);t<m(this,ve).length;t++){const r=m(this,ve)[t];e.push(`${r.type}:${r.text}`)}return`<TokenString ${e.join(" ")}>`}};let we=Br;J=new WeakMap,ve=new WeakMap,er=new WeakSet,Qn=function(e=0,t=0){return new Br(m(this,ve).slice(e,t).map(r=>Object.freeze(Object.assign({},r,{match:r.match-e,linkBack:r.linkBack-e,linkNext:r.linkNext-e}))))};function We(n){const e=[],t=o=>{const a=i<n.length?JSON.stringify(n[i]):"$EOI";throw new Error(`invalid token ${a} at ${i}: ${o}`)};let r=[],s=[],i=0;for(;i<n.length;){let o=n.substring(i),a=o.match(Wu);a&&(i+=a[1].length,o=n.substring(i));const c={depth:r.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:i,value:-1};e.push(c);let u=Ju[o[0]]||"";if(u){if(c.type=u,c.text=o[0],i++,u==="OPEN_PAREN")r.push(e.length-1),s.push(e.length-1);else if(u=="CLOSE_PAREN")r.length===0&&t("no matching open bracket"),c.match=r.pop(),e[c.match].match=e.length-1,c.depth--,c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1;else if(u==="COMMA")c.linkBack=s.pop(),e[c.linkBack].linkNext=e.length-1,s.push(e.length-1);else if(u==="OPEN_BRACKET")c.type="BRACKET";else if(u==="CLOSE_BRACKET"){let l=e.pop().text;if(e.length>0&&e[e.length-1].type==="NUMBER"){const h=e.pop().text;l=h+l,e[e.length-1].value=Ce(h)}if(e.length===0||e[e.length-1].type!=="BRACKET")throw new Error("missing opening bracket");e[e.length-1].text+=l}continue}if(a=o.match(Xu),a){if(c.text=a[1],i+=c.text.length,Gu.has(c.text)){c.type="KEYWORD";continue}if(c.text.match(xi)){c.type="TYPE";continue}c.type="ID";continue}if(a=o.match(Ku),a){c.text=a[1],c.type="NUMBER",i+=c.text.length;continue}throw new Error(`unexpected token ${JSON.stringify(o[0])} at position ${i}`)}return new we(e.map(o=>Object.freeze(o)))}function Ti(n,e){let t=[];for(const r in e.keys())n.has(r)&&t.push(r);if(t.length>1)throw new Error(`conflicting types: ${t.join(", ")}`)}function Fr(n,e){if(e.peekKeyword(vi)){const t=e.pop().text;if(t!==n)throw new Error(`expected ${n}, got ${t}`)}return e.popType("ID")}function Ue(n,e){const t=new Set;for(;;){const r=n.peekType("KEYWORD");if(r==null||e&&!e.has(r))break;if(n.pop(),t.has(r))throw new Error(`duplicate keywords: ${JSON.stringify(r)}`);t.add(r)}return Object.freeze(t)}function Oi(n){let e=Ue(n,Vu);return Ti(e,ee("constant payable nonpayable".split(" "))),Ti(e,ee("pure view payable nonpayable".split(" "))),e.has("view")?"view":e.has("pure")?"pure":e.has("payable")?"payable":e.has("nonpayable")?"nonpayable":e.has("constant")?"view":"nonpayable"}function je(n,e){return n.popParams().map(t=>G.from(t,e))}function ki(n){if(n.peekType("AT")){if(n.pop(),n.peekType("NUMBER"))return ht(n.pop().text);throw new Error("invalid gas")}return null}function dt(n){if(n.length)throw new Error(`unexpected tokens: ${n.toString()}`)}const Zu=new RegExp(/^(.*)\[([0-9]*)\]$/);function Ai(n){const e=n.match(xi);if(_(e,"invalid type","type",n),n==="uint")return"uint256";if(n==="int")return"int256";if(e[2]){const t=parseInt(e[2]);_(t!==0&&t<=32,"invalid bytes length","type",n)}else if(e[3]){const t=parseInt(e[3]);_(t!==0&&t<=256&&t%8===0,"invalid numeric width","type",n)}return n}const B={},ie=Symbol.for("_ethers_internal"),Si="_ParamTypeInternal",Ri="_ErrorInternal",$i="_EventInternal",Pi="_ConstructorInternal",Ni="_FallbackInternal",Ii="_FunctionInternal",Ci="_StructInternal",pe=class{constructor(e,t,r,s,i,o,a,c){j(this,Ft);d(this,"name");d(this,"type");d(this,"baseType");d(this,"indexed");d(this,"components");d(this,"arrayLength");d(this,"arrayChildren");if(xn(e,B,"ParamType"),Object.defineProperty(this,ie,{value:Si}),o&&(o=Object.freeze(o.slice())),s==="array"){if(a==null||c==null)throw new Error("")}else if(a!=null||c!=null)throw new Error("");if(s==="tuple"){if(o==null)throw new Error("")}else if(o!=null)throw new Error("");A(this,{name:t,type:r,baseType:s,indexed:i,components:o,arrayLength:a,arrayChildren:c})}format(e){if(e==null&&(e="sighash"),e==="json"){let r={type:this.baseType==="tuple"?"tuple":this.type,name:this.name||void 0};return typeof this.indexed=="boolean"&&(r.indexed=this.indexed),this.isTuple()&&(r.components=this.components.map(s=>JSON.parse(s.format(e)))),JSON.stringify(r)}let t="";return this.isArray()?(t+=this.arrayChildren.format(e),t+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?(e!=="sighash"&&(t+=this.type),t+="("+this.components.map(r=>r.format(e)).join(e==="full"?", ":",")+")"):t+=this.type,e!=="sighash"&&(this.indexed===!0&&(t+=" indexed"),e==="full"&&this.name&&(t+=" "+this.name)),t}isArray(){return this.baseType==="array"}isTuple(){return this.baseType==="tuple"}isIndexable(){return this.indexed!=null}walk(e,t){if(this.isArray()){if(!Array.isArray(e))throw new Error("invalid array value");if(this.arrayLength!==-1&&e.length!==this.arrayLength)throw new Error("array is wrong length");const r=this;return e.map(s=>r.arrayChildren.walk(s,t))}if(this.isTuple()){if(!Array.isArray(e))throw new Error("invalid tuple value");if(e.length!==this.components.length)throw new Error("array is wrong length");const r=this;return e.map((s,i)=>r.components[i].walk(s,t))}return t(this.type,e)}async walkAsync(e,t){const r=[],s=[e];return V(this,Ft,Wr).call(this,r,e,t,i=>{s[0]=i}),r.length&&await Promise.all(r),s[0]}static from(e,t){if(pe.isParamType(e))return e;if(typeof e=="string")return pe.from(We(e),t);if(e instanceof we){let a="",c="",u=null;Ue(e,ee(["tuple"])).has("tuple")||e.peekType("OPEN_PAREN")?(c="tuple",u=e.popParams().map(v=>pe.from(v)),a=`tuple(${u.map(v=>v.format()).join(",")})`):(a=Ai(e.popType("TYPE")),c=a);let l=null,h=null;for(;e.length&&e.peekType("BRACKET");){const v=e.pop();l=new pe(B,"",a,c,null,u,h,l),h=v.value,a+=v.text,c="array",u=null}let y=null;if(Ue(e,zu).has("indexed")){if(!t)throw new Error("");y=!0}const w=e.peekType("ID")?e.pop().text:"";if(e.length)throw new Error("leftover tokens");return new pe(B,w,a,c,y,u,h,l)}const r=e.name;_(!r||typeof r=="string"&&r.match(Ei),"invalid name","obj.name",r);let s=e.indexed;s!=null&&(_(t,"parameter cannot be indexed","obj.indexed",e.indexed),s=!!s);let i=e.type,o=i.match(Zu);if(o){const a=parseInt(o[2]||"-1"),c=pe.from({type:o[1],components:e.components});return new pe(B,r||"",i,"array",s,null,a,c)}if(i==="tuple"||i.startsWith("tuple(")||i.startsWith("(")){const a=e.components!=null?e.components.map(u=>pe.from(u)):null;return new pe(B,r||"",i,"tuple",s,a,null,null)}return i=Ai(e.type),new pe(B,r||"",i,i,s,null,null,null)}static isParamType(e){return e&&e[ie]===Si}};let G=pe;Ft=new WeakSet,Wr=function(e,t,r,s){if(this.isArray()){if(!Array.isArray(t))throw new Error("invalid array value");if(this.arrayLength!==-1&&t.length!==this.arrayLength)throw new Error("array is wrong length");const o=this.arrayChildren,a=t.slice();a.forEach((c,u)=>{var l;V(l=o,Ft,Wr).call(l,e,c,r,h=>{a[u]=h})}),s(a);return}if(this.isTuple()){const o=this.components;let a;if(Array.isArray(t))a=t.slice();else{if(t==null||typeof t!="object")throw new Error("invalid tuple value");a=o.map(c=>{if(!c.name)throw new Error("cannot use object value with unnamed components");if(!(c.name in t))throw new Error(`missing value for component ${c.name}`);return t[c.name]})}if(a.length!==this.components.length)throw new Error("array is wrong length");a.forEach((c,u)=>{var l;V(l=o[u],Ft,Wr).call(l,e,c,r,h=>{a[u]=h})}),s(a);return}const i=r(this.type,t);i.then?e.push(async function(){s(await i)}()):s(i)};class pt{constructor(e,t,r){d(this,"type");d(this,"inputs");xn(e,B,"Fragment"),r=Object.freeze(r.slice()),A(this,{type:t,inputs:r})}static from(e){if(typeof e=="string"){try{pt.from(JSON.parse(e))}catch{}return pt.from(We(e))}if(e instanceof we)switch(e.peekKeyword(vi)){case"constructor":return Le.from(e);case"error":return oe.from(e);case"event":return Te.from(e);case"fallback":case"receive":return Be.from(e);case"function":return Oe.from(e);case"struct":return yt.from(e)}else if(typeof e=="object"){switch(e.type){case"constructor":return Le.from(e);case"error":return oe.from(e);case"event":return Te.from(e);case"fallback":case"receive":return Be.from(e);case"function":return Oe.from(e);case"struct":return yt.from(e)}x(!1,`unsupported type: ${e.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}_(!1,"unsupported frgament object","obj",e)}static isConstructor(e){return Le.isFragment(e)}static isError(e){return oe.isFragment(e)}static isEvent(e){return Te.isFragment(e)}static isFunction(e){return Oe.isFragment(e)}static isStruct(e){return yt.isFragment(e)}}class Dr extends pt{constructor(t,r,s,i){super(t,r,i);d(this,"name");_(typeof s=="string"&&s.match(Ei),"invalid identifier","name",s),i=Object.freeze(i.slice()),A(this,{name:s})}}function Kt(n,e){return"("+e.map(t=>t.format(n)).join(n==="full"?", ":",")+")"}class oe extends Dr{constructor(e,t,r){super(e,"error",t,r),Object.defineProperty(this,ie,{value:Ri})}get selector(){return Wt(this.format("sighash")).substring(0,10)}format(e){if(e==null&&(e="sighash"),e==="json")return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(r=>JSON.parse(r.format(e)))});const t=[];return e!=="sighash"&&t.push("error"),t.push(this.name+Kt(e,this.inputs)),t.join(" ")}static from(e){if(oe.isFragment(e))return e;if(typeof e=="string")return oe.from(We(e));if(e instanceof we){const t=Fr("error",e),r=je(e);return dt(e),new oe(B,t,r)}return new oe(B,e.name,e.inputs?e.inputs.map(G.from):[])}static isFragment(e){return e&&e[ie]===Ri}}class Te extends Dr{constructor(t,r,s,i){super(t,"event",r,s);d(this,"anonymous");Object.defineProperty(this,ie,{value:$i}),A(this,{anonymous:i})}get topicHash(){return Wt(this.format("sighash"))}format(t){if(t==null&&(t="sighash"),t==="json")return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(s=>JSON.parse(s.format(t)))});const r=[];return t!=="sighash"&&r.push("event"),r.push(this.name+Kt(t,this.inputs)),t!=="sighash"&&this.anonymous&&r.push("anonymous"),r.join(" ")}static getTopicHash(t,r){return r=(r||[]).map(i=>G.from(i)),new Te(B,t,r,!1).topicHash}static from(t){if(Te.isFragment(t))return t;if(typeof t=="string")return Te.from(We(t));if(t instanceof we){const r=Fr("event",t),s=je(t,!0),i=!!Ue(t,ee(["anonymous"])).has("anonymous");return dt(t),new Te(B,r,s,i)}return new Te(B,t.name,t.inputs?t.inputs.map(r=>G.from(r,!0)):[],!!t.anonymous)}static isFragment(t){return t&&t[ie]===$i}}class Le extends pt{constructor(t,r,s,i,o){super(t,r,s);d(this,"payable");d(this,"gas");Object.defineProperty(this,ie,{value:Pi}),A(this,{payable:i,gas:o})}format(t){if(x(t!=null&&t!=="sighash","cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),t==="json")return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(s=>JSON.parse(s.format(t)))});const r=[`constructor${Kt(t,this.inputs)}`];return r.push(this.payable?"payable":"nonpayable"),this.gas!=null&&r.push(`@${this.gas.toString()}`),r.join(" ")}static from(t){if(Le.isFragment(t))return t;if(typeof t=="string")return Le.from(We(t));if(t instanceof we){Ue(t,ee(["constructor"]));const r=je(t),s=!!Ue(t,ee(["payable"])).has("payable"),i=ki(t);return dt(t),new Le(B,"constructor",r,s,i)}return new Le(B,"constructor",t.inputs?t.inputs.map(G.from):[],!!t.payable,t.gas!=null?t.gas:null)}static isFragment(t){return t&&t[ie]===Pi}}class Be extends pt{constructor(t,r,s){super(t,"fallback",r);d(this,"payable");Object.defineProperty(this,ie,{value:Ni}),A(this,{payable:s})}format(t){const r=this.inputs.length===0?"receive":"fallback";if(t==="json"){const s=this.payable?"payable":"nonpayable";return JSON.stringify({type:r,stateMutability:s})}return`${r}()${this.payable?" payable":""}`}static from(t){if(Be.isFragment(t))return t;if(typeof t=="string")return Be.from(We(t));if(t instanceof we){const r=t.toString(),s=t.peekKeyword(ee(["fallback","receive"]));if(_(s,"type must be fallback or receive","obj",r),t.popKeyword(ee(["fallback","receive"]))==="receive"){const c=je(t);return _(c.length===0,"receive cannot have arguments","obj.inputs",c),Ue(t,ee(["payable"])),dt(t),new Be(B,[],!0)}let o=je(t);o.length?_(o.length===1&&o[0].type==="bytes","invalid fallback inputs","obj.inputs",o.map(c=>c.format("minimal")).join(", ")):o=[G.from("bytes")];const a=Oi(t);if(_(a==="nonpayable"||a==="payable","fallback cannot be constants","obj.stateMutability",a),Ue(t,ee(["returns"])).has("returns")){const c=je(t);_(c.length===1&&c[0].type==="bytes","invalid fallback outputs","obj.outputs",c.map(u=>u.format("minimal")).join(", "))}return dt(t),new Be(B,o,a==="payable")}if(t.type==="receive")return new Be(B,[],!0);if(t.type==="fallback"){const r=[G.from("bytes")],s=t.stateMutability==="payable";return new Be(B,r,s)}_(!1,"invalid fallback description","obj",t)}static isFragment(t){return t&&t[ie]===Ni}}class Oe extends Dr{constructor(t,r,s,i,o,a){super(t,"function",r,i);d(this,"constant");d(this,"outputs");d(this,"stateMutability");d(this,"payable");d(this,"gas");Object.defineProperty(this,ie,{value:Ii}),o=Object.freeze(o.slice()),A(this,{constant:s==="view"||s==="pure",gas:a,outputs:o,payable:s==="payable",stateMutability:s})}get selector(){return Wt(this.format("sighash")).substring(0,10)}format(t){if(t==null&&(t="sighash"),t==="json")return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:this.stateMutability!=="nonpayable"?this.stateMutability:void 0,payable:this.payable,gas:this.gas!=null?this.gas:void 0,inputs:this.inputs.map(s=>JSON.parse(s.format(t))),outputs:this.outputs.map(s=>JSON.parse(s.format(t)))});const r=[];return t!=="sighash"&&r.push("function"),r.push(this.name+Kt(t,this.inputs)),t!=="sighash"&&(this.stateMutability!=="nonpayable"&&r.push(this.stateMutability),this.outputs&&this.outputs.length&&(r.push("returns"),r.push(Kt(t,this.outputs))),this.gas!=null&&r.push(`@${this.gas.toString()}`)),r.join(" ")}static getSelector(t,r){return r=(r||[]).map(i=>G.from(i)),new Oe(B,t,"view",r,[],null).selector}static from(t){if(Oe.isFragment(t))return t;if(typeof t=="string")return Oe.from(We(t));if(t instanceof we){const r=Fr("function",t),s=je(t),i=Oi(t);let o=[];Ue(t,ee(["returns"])).has("returns")&&(o=je(t));const a=ki(t);return dt(t),new Oe(B,r,i,s,o,a)}return new Oe(B,t.name,t.stateMutability,t.inputs?t.inputs.map(G.from):[],t.outputs?t.outputs.map(G.from):[],t.gas!=null?t.gas:null)}static isFragment(t){return t&&t[ie]===Ii}}class yt extends Dr{constructor(e,t,r){super(e,"struct",t,r),Object.defineProperty(this,ie,{value:Ci})}format(){throw new Error("@TODO")}static from(e){if(typeof e=="string")return yt.from(We(e));if(e instanceof we){const t=Fr("struct",e),r=je(e);return dt(e),new yt(B,t,r)}return new yt(B,e.name,e.inputs?e.inputs.map(G.from):[])}static isFragment(e){return e&&e[ie]===Ci}}const be=new Map;be.set(0,"GENERIC_PANIC"),be.set(1,"ASSERT_FALSE"),be.set(17,"OVERFLOW"),be.set(18,"DIVIDE_BY_ZERO"),be.set(33,"ENUM_RANGE_ERROR"),be.set(34,"BAD_STORAGE_DATA"),be.set(49,"STACK_UNDERFLOW"),be.set(50,"ARRAY_RANGE_ERROR"),be.set(65,"OUT_OF_MEMORY"),be.set(81,"UNINITIALIZED_FUNCTION_CALL");const Yu=new RegExp(/^bytes([0-9]*)$/),Qu=new RegExp(/^(u?int)([0-9]*)$/);let Cn=null;function el(n,e,t,r){let s="missing revert data",i=null;const o=null;let a=null;if(t){s="execution reverted";const u=Ne(t);if(t=z(t),u.length===0)s+=" (no data present; likely require(false) occurred",i="require(false)";else if(u.length%32!==4)s+=" (could not decode reason; invalid data length)";else if(z(u.slice(0,4))==="0x08c379a0")try{i=r.decode(["string"],u.slice(4))[0],a={signature:"Error(string)",name:"Error",args:[i]},s+=`: ${JSON.stringify(i)}`}catch{s+=" (could not decode reason; invalid string data)"}else if(z(u.slice(0,4))==="0x4e487b71")try{const l=Number(r.decode(["uint256"],u.slice(4))[0]);a={signature:"Panic(uint256)",name:"Panic",args:[l]},i=`Panic due to ${be.get(l)||"UNKNOWN"}(${l})`,s+=`: ${i}`}catch{s+=" (could not decode panic code)"}else s+=" (unknown custom error)"}const c={to:e.to?ft(e.to):null,data:e.data||"0x"};return e.from&&(c.from=ft(e.from)),Or(s,"CALL_EXCEPTION",{action:n,data:t,reason:i,transaction:c,invocation:o,revert:a})}const Hr=class{constructor(){j(this,Ze)}getDefaultValue(e){const t=e.map(s=>V(this,Ze,Lt).call(this,G.from(s)));return new Cr(t,"_").defaultValue()}encode(e,t){Gs(t.length,e.length,"types/values length mismatch");const r=e.map(o=>V(this,Ze,Lt).call(this,G.from(o))),s=new Cr(r,"_"),i=new On;return s.encode(i,t),i.data}decode(e,t,r){const s=e.map(o=>V(this,Ze,Lt).call(this,G.from(o)));return new Cr(s,"_").decode(new kn(t,r))}static defaultAbiCoder(){return Cn==null&&(Cn=new Hr),Cn}static getBuiltinCallException(e,t,r){return el(e,t,r,Hr.defaultAbiCoder())}};let Ur=Hr;Ze=new WeakSet,Lt=function(e){if(e.isArray())return new Pu(V(this,Ze,Lt).call(this,e.arrayChildren),e.arrayLength,e.name);if(e.isTuple())return new Cr(e.components.map(r=>V(this,Ze,Lt).call(this,r)),e.name);switch(e.baseType){case"address":return new Ru(e.name);case"bool":return new Nu(e.name);case"string":return new Hu(e.name);case"bytes":return new Iu(e.name);case"":return new Du(e.name)}let t=e.type.match(Qu);if(t){let r=parseInt(t[2]||"256");return _(r!==0&&r<=256&&r%8===0,"invalid "+t[1]+" bit length","param",e),new Bu(r/8,t[1]==="int",e.name)}if(t=e.type.match(Yu),t){let r=parseInt(t[1]);return _(r!==0&&r<=32,"invalid bytes length","param",e),new Cu(r,e.name)}_(!1,"invalid type","type",e.type)};class tl{constructor(e,t,r){d(this,"fragment");d(this,"name");d(this,"signature");d(this,"topic");d(this,"args");const s=e.name,i=e.format();A(this,{fragment:e,name:s,signature:i,topic:t,args:r})}}class rl{constructor(e,t,r,s){d(this,"fragment");d(this,"name");d(this,"args");d(this,"signature");d(this,"selector");d(this,"value");const i=e.name,o=e.format();A(this,{fragment:e,name:i,args:r,signature:o,selector:t,value:s})}}class nl{constructor(e,t,r){d(this,"fragment");d(this,"name");d(this,"args");d(this,"signature");d(this,"selector");const s=e.name,i=e.format();A(this,{fragment:e,name:s,args:r,signature:i,selector:t})}}class Fi{constructor(e){d(this,"hash");d(this,"_isIndexed");A(this,{hash:e,_isIndexed:!0})}static isIndexed(e){return!!(e&&e._isIndexed)}}const Di={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"},Ui={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:n=>`reverted with reason string ${JSON.stringify(n)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:n=>{let e="unknown panic code";return n>=0&&n<=255&&Di[n.toString()]&&(e=Di[n.toString()]),`reverted with panic code 0x${n.toString(16)} (${e})`}}},Dt=class{constructor(e){j(this,tr);j(this,rr);d(this,"fragments");d(this,"deploy");d(this,"fallback");d(this,"receive");j(this,ke,void 0);j(this,Ae,void 0);j(this,Se,void 0);j(this,Z,void 0);let t=[];typeof e=="string"?t=JSON.parse(e):t=e,N(this,Se,new Map),N(this,ke,new Map),N(this,Ae,new Map);const r=[];for(const o of t)try{r.push(pt.from(o))}catch(a){console.log("EE",a)}A(this,{fragments:Object.freeze(r)});let s=null,i=!1;N(this,Z,this.getAbiCoder()),this.fragments.forEach((o,a)=>{let c;switch(o.type){case"constructor":if(this.deploy){console.log("duplicate definition - constructor");return}A(this,{deploy:o});return;case"fallback":o.inputs.length===0?i=!0:(_(!s||o.payable!==s.payable,"conflicting fallback fragments",`fragments[${a}]`,o),s=o,i=s.payable);return;case"function":c=m(this,Se);break;case"event":c=m(this,Ae);break;case"error":c=m(this,ke);break;default:return}const u=o.format();c.has(u)||c.set(u,o)}),this.deploy||A(this,{deploy:Le.from("constructor()")}),A(this,{fallback:s,receive:i})}format(e){const t=e?"minimal":"full";return this.fragments.map(s=>s.format(t))}formatJson(){const e=this.fragments.map(t=>t.format("json"));return JSON.stringify(e.map(t=>JSON.parse(t)))}getAbiCoder(){return Ur.defaultAbiCoder()}getFunctionName(e){const t=V(this,tr,es).call(this,e,null,!1);return _(t,"no matching function","key",e),t.name}getFunction(e,t){return V(this,tr,es).call(this,e,t||null,!0)}forEachFunction(e){const t=Array.from(m(this,Se).keys());t.sort((r,s)=>r.localeCompare(s));for(let r=0;r<t.length;r++){const s=t[r];e(m(this,Se).get(s),r)}}getEventName(e){const t=V(this,rr,ts).call(this,e,null,!1);return _(t,"no matching event","key",e),t.name}getEvent(e,t){return V(this,rr,ts).call(this,e,t||null,!0)}forEachEvent(e){const t=Array.from(m(this,Ae).keys());t.sort((r,s)=>r.localeCompare(s));for(let r=0;r<t.length;r++){const s=t[r];e(m(this,Ae).get(s),r)}}getError(e,t){if(qe(e)){const s=e.toLowerCase();if(Ui[s])return oe.from(Ui[s].signature);for(const i of m(this,ke).values())if(s===i.selector)return i;return null}if(e.indexOf("(")===-1){const s=[];for(const[i,o]of m(this,ke))i.split("(")[0]===e&&s.push(o);if(s.length===0)return e==="Error"?oe.from("error Error(string)"):e==="Panic"?oe.from("error Panic(uint256)"):null;if(s.length>1){const i=s.map(o=>JSON.stringify(o.format())).join(", ");_(!1,`ambiguous error description (i.e. ${i})`,"name",e)}return s[0]}if(e=oe.from(e).format(),e==="Error(string)")return oe.from("error Error(string)");if(e==="Panic(uint256)")return oe.from("error Panic(uint256)");const r=m(this,ke).get(e);return r||null}forEachError(e){const t=Array.from(m(this,ke).keys());t.sort((r,s)=>r.localeCompare(s));for(let r=0;r<t.length;r++){const s=t[r];e(m(this,ke).get(s),r)}}_decodeParams(e,t){return m(this,Z).decode(e,t)}_encodeParams(e,t){return m(this,Z).encode(e,t)}encodeDeploy(e){return this._encodeParams(this.deploy.inputs,e||[])}decodeErrorResult(e,t){if(typeof e=="string"){const r=this.getError(e);_(r,"unknown error","fragment",e),e=r}return _($t(t,0,4)===e.selector,`data signature does not match error ${e.name}.`,"data",t),this._decodeParams(e.inputs,$t(t,4))}encodeErrorResult(e,t){if(typeof e=="string"){const r=this.getError(e);_(r,"unknown error","fragment",e),e=r}return Rt([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionData(e,t){if(typeof e=="string"){const r=this.getFunction(e);_(r,"unknown function","fragment",e),e=r}return _($t(t,0,4)===e.selector,`data signature does not match function ${e.name}.`,"data",t),this._decodeParams(e.inputs,$t(t,4))}encodeFunctionData(e,t){if(typeof e=="string"){const r=this.getFunction(e);_(r,"unknown function","fragment",e),e=r}return Rt([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionResult(e,t){if(typeof e=="string"){const i=this.getFunction(e);_(i,"unknown function","fragment",e),e=i}let r="invalid length for result data";const s=Ie(t);if(s.length%32===0)try{return m(this,Z).decode(e.outputs,s)}catch{r="could not decode result data"}x(!1,r,"BAD_DATA",{value:z(s),info:{method:e.name,signature:e.format()}})}makeError(e,t){const r=Ne(e,"data"),s=Ur.getBuiltinCallException("call",t,r),i="execution reverted (unknown custom error)";if(s.message.startsWith(i)){const a=z(r.slice(0,4)),c=this.getError(a);if(c)try{const u=m(this,Z).decode(c.inputs,r.slice(4));s.revert={name:c.name,signature:c.format(),args:u},s.reason=s.revert.signature,s.message=`execution reverted: ${s.reason}`}catch{s.message="execution reverted (coult not decode custom error)"}}const o=this.parseTransaction(t);return o&&(s.invocation={method:o.name,signature:o.signature,args:o.args}),s}encodeFunctionResult(e,t){if(typeof e=="string"){const r=this.getFunction(e);_(r,"unknown function","fragment",e),e=r}return z(m(this,Z).encode(e.outputs,t||[]))}encodeFilterTopics(e,t){if(typeof e=="string"){const i=this.getEvent(e);_(i,"unknown event","eventFragment",e),e=i}x(t.length<=e.inputs.length,`too many arguments for ${e.format()}`,"UNEXPECTED_ARGUMENT",{count:t.length,expectedCount:e.inputs.length});const r=[];e.anonymous||r.push(e.topicHash);const s=(i,o)=>i.type==="string"?Wt(o):i.type==="bytes"?Je(z(o)):(i.type==="bool"&&typeof o=="boolean"&&(o=o?"0x01":"0x00"),i.type.match(/^u?int/)&&(o=Zs(o)),i.type==="address"&&m(this,Z).encode(["address"],[o]),Pc(z(o),32));for(t.forEach((i,o)=>{const a=e.inputs[o];if(!a.indexed){_(i==null,"cannot filter non-indexed parameters; must be null","contract."+a.name,i);return}i==null?r.push(null):a.baseType==="array"||a.baseType==="tuple"?_(!1,"filtering with tuples or arrays not supported","contract."+a.name,i):Array.isArray(i)?r.push(i.map(c=>s(a,c))):r.push(s(a,i))});r.length&&r[r.length-1]===null;)r.pop();return r}encodeEventLog(e,t){if(typeof e=="string"){const o=this.getEvent(e);_(o,"unknown event","eventFragment",e),e=o}const r=[],s=[],i=[];return e.anonymous||r.push(e.topicHash),_(t.length===e.inputs.length,"event arguments/values mismatch","values",t),e.inputs.forEach((o,a)=>{const c=t[a];if(o.indexed)if(o.type==="string")r.push(Wt(c));else if(o.type==="bytes")r.push(Je(c));else{if(o.baseType==="tuple"||o.baseType==="array")throw new Error("not implemented");r.push(m(this,Z).encode([o.type],[c]))}else s.push(o),i.push(c)}),{data:m(this,Z).encode(s,i),topics:r}}decodeEventLog(e,t,r){if(typeof e=="string"){const p=this.getEvent(e);_(p,"unknown event","eventFragment",e),e=p}if(r!=null&&!e.anonymous){const p=e.topicHash;_(qe(r[0],32)&&r[0].toLowerCase()===p,"fragment/topic mismatch","topics[0]",r[0]),r=r.slice(1)}const s=[],i=[],o=[];e.inputs.forEach((p,w)=>{p.indexed?p.type==="string"||p.type==="bytes"||p.baseType==="tuple"||p.baseType==="array"?(s.push(G.from({type:"bytes32",name:p.name})),o.push(!0)):(s.push(p),o.push(!1)):(i.push(p),o.push(!1))});const a=r!=null?m(this,Z).decode(s,Rt(r)):null,c=m(this,Z).decode(i,t,!0),u=[],l=[];let h=0,y=0;return e.inputs.forEach((p,w)=>{let v=null;if(p.indexed)if(a==null)v=new Fi(null);else if(o[w])v=new Fi(a[y++]);else try{v=a[y++]}catch(g){v=g}else try{v=c[h++]}catch(g){v=g}u.push(v),l.push(p.name||null)}),Pr.fromItems(u,l)}parseTransaction(e){const t=Ne(e.data,"tx.data"),r=ht(e.value!=null?e.value:0,"tx.value"),s=this.getFunction(z(t.slice(0,4)));if(!s)return null;const i=m(this,Z).decode(s.inputs,t.slice(4));return new rl(s,s.selector,i,r)}parseCallResult(e){throw new Error("@TODO")}parseLog(e){const t=this.getEvent(e.topics[0]);return!t||t.anonymous?null:new tl(t,t.topicHash,this.decodeEventLog(t,e.data,e.topics))}parseError(e){const t=z(e),r=this.getError($t(t,0,4));if(!r)return null;const s=m(this,Z).decode(r.inputs,$t(t,4));return new nl(r,r.selector,s)}static from(e){return e instanceof Dt?e:typeof e=="string"?new Dt(JSON.parse(e)):typeof e.format=="function"?new Dt(e.format("json")):new Dt(e)}};let Fn=Dt;ke=new WeakMap,Ae=new WeakMap,Se=new WeakMap,Z=new WeakMap,tr=new WeakSet,es=function(e,t,r){if(qe(e)){const i=e.toLowerCase();for(const o of m(this,Se).values())if(i===o.selector)return o;return null}if(e.indexOf("(")===-1){const i=[];for(const[o,a]of m(this,Se))o.split("(")[0]===e&&i.push(a);if(t){const o=t.length>0?t[t.length-1]:null;let a=t.length,c=!0;X.isTyped(o)&&o.type==="overrides"&&(c=!1,a--);for(let u=i.length-1;u>=0;u--){const l=i[u].inputs.length;l!==a&&(!c||l!==a-1)&&i.splice(u,1)}for(let u=i.length-1;u>=0;u--){const l=i[u].inputs;for(let h=0;h<t.length;h++)if(X.isTyped(t[h])){if(h>=l.length){if(t[h].type==="overrides")continue;i.splice(u,1);break}if(t[h].type!==l[h].baseType){i.splice(u,1);break}}}}if(i.length===1&&t&&t.length!==i[0].inputs.length){const o=t[t.length-1];(o==null||Array.isArray(o)||typeof o!="object")&&i.splice(0,1)}if(i.length===0)return null;if(i.length>1&&r){const o=i.map(a=>JSON.stringify(a.format())).join(", ");_(!1,`ambiguous function description (i.e. matches ${o})`,"key",e)}return i[0]}const s=m(this,Se).get(Oe.from(e).format());return s||null},rr=new WeakSet,ts=function(e,t,r){if(qe(e)){const i=e.toLowerCase();for(const o of m(this,Ae).values())if(i===o.topicHash)return o;return null}if(e.indexOf("(")===-1){const i=[];for(const[o,a]of m(this,Ae))o.split("(")[0]===e&&i.push(a);if(t){for(let o=i.length-1;o>=0;o--)i[o].inputs.length<t.length&&i.splice(o,1);for(let o=i.length-1;o>=0;o--){const a=i[o].inputs;for(let c=0;c<t.length;c++)if(X.isTyped(t[c])&&t[c].type!==a[c].baseType){i.splice(o,1);break}}}if(i.length===0)return null;if(i.length>1&&r){const o=i.map(a=>JSON.stringify(a.format())).join(", ");_(!1,`ambiguous event description (i.e. matches ${o})`,"key",e)}return i[0]}const s=m(this,Ae).get(Te.from(e).format());return s||null};const sl=BigInt(0);function He(n){return n==null?null:n.toString()}function il(n){const e={};n.to&&(e.to=n.to),n.from&&(e.from=n.from),n.data&&(e.data=z(n.data));const t="chainId,gasLimit,gasPrice,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const s of t)!(s in n)||n[s]==null||(e[s]=ht(n[s],`request.${s}`));const r="type,nonce".split(/,/);for(const s of r)!(s in n)||n[s]==null||(e[s]=Ce(n[s],`request.${s}`));return n.accessList&&(e.accessList=Mu(n.accessList)),"blockTag"in n&&(e.blockTag=n.blockTag),"enableCcipRead"in n&&(e.enableCcipReadEnabled=!!n.enableCcipRead),"customData"in n&&(e.customData=n.customData),e}class Dn{constructor(e,t){d(this,"provider");d(this,"transactionHash");d(this,"blockHash");d(this,"blockNumber");d(this,"removed");d(this,"address");d(this,"data");d(this,"topics");d(this,"index");d(this,"transactionIndex");this.provider=t;const r=Object.freeze(e.topics.slice());A(this,{transactionHash:e.transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,removed:e.removed,address:e.address,data:e.data,topics:r,index:e.index,transactionIndex:e.transactionIndex})}toJSON(){const{address:e,blockHash:t,blockNumber:r,data:s,index:i,removed:o,topics:a,transactionHash:c,transactionIndex:u}=this;return{_type:"log",address:e,blockHash:t,blockNumber:r,data:s,index:i,removed:o,topics:a,transactionHash:c,transactionIndex:u}}async getBlock(){const e=await this.provider.getBlock(this.blockHash);return x(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransaction(){const e=await this.provider.getTransaction(this.transactionHash);return x(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransactionReceipt(){const e=await this.provider.getTransactionReceipt(this.transactionHash);return x(!!e,"failed to find transaction receipt","UNKNOWN_ERROR",{}),e}removedEvent(){return al(this)}}class ol{constructor(e,t){d(this,"provider");d(this,"to");d(this,"from");d(this,"contractAddress");d(this,"hash");d(this,"index");d(this,"blockHash");d(this,"blockNumber");d(this,"logsBloom");d(this,"gasUsed");d(this,"cumulativeGasUsed");d(this,"gasPrice");d(this,"type");d(this,"status");d(this,"root");j(this,nr,void 0);N(this,nr,Object.freeze(e.logs.map(r=>new Dn(r,t)))),A(this,{provider:t,to:e.to,from:e.from,contractAddress:e.contractAddress,hash:e.hash,index:e.index,blockHash:e.blockHash,blockNumber:e.blockNumber,logsBloom:e.logsBloom,gasUsed:e.gasUsed,cumulativeGasUsed:e.cumulativeGasUsed,gasPrice:e.effectiveGasPrice||e.gasPrice,type:e.type,status:e.status,root:e.root})}get logs(){return m(this,nr)}toJSON(){const{to:e,from:t,contractAddress:r,hash:s,index:i,blockHash:o,blockNumber:a,logsBloom:c,logs:u,status:l,root:h}=this;return{_type:"TransactionReceipt",blockHash:o,blockNumber:a,contractAddress:r,cumulativeGasUsed:He(this.cumulativeGasUsed),from:t,gasPrice:He(this.gasPrice),gasUsed:He(this.gasUsed),hash:s,index:i,logs:u,logsBloom:c,root:h,status:l,to:e}}get length(){return this.logs.length}[Symbol.iterator](){let e=0;return{next:()=>e<this.length?{value:this.logs[e++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const e=await this.provider.getBlock(this.blockHash);if(e==null)throw new Error("TODO");return e}async getTransaction(){const e=await this.provider.getTransaction(this.hash);if(e==null)throw new Error("TODO");return e}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return Li(this)}reorderedEvent(e){return x(!e||e.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),ji(this,e)}}nr=new WeakMap;const Xn=class{constructor(e,t){d(this,"provider");d(this,"blockNumber");d(this,"blockHash");d(this,"index");d(this,"hash");d(this,"type");d(this,"to");d(this,"from");d(this,"nonce");d(this,"gasLimit");d(this,"gasPrice");d(this,"maxPriorityFeePerGas");d(this,"maxFeePerGas");d(this,"data");d(this,"value");d(this,"chainId");d(this,"signature");d(this,"accessList");j(this,Ye,void 0);this.provider=t,this.blockNumber=e.blockNumber!=null?e.blockNumber:null,this.blockHash=e.blockHash!=null?e.blockHash:null,this.hash=e.hash,this.index=e.index,this.type=e.type,this.from=e.from,this.to=e.to||null,this.gasLimit=e.gasLimit,this.nonce=e.nonce,this.data=e.data,this.value=e.value,this.gasPrice=e.gasPrice,this.maxPriorityFeePerGas=e.maxPriorityFeePerGas!=null?e.maxPriorityFeePerGas:null,this.maxFeePerGas=e.maxFeePerGas!=null?e.maxFeePerGas:null,this.chainId=e.chainId,this.signature=e.signature,this.accessList=e.accessList!=null?e.accessList:null,N(this,Ye,-1)}toJSON(){const{blockNumber:e,blockHash:t,index:r,hash:s,type:i,to:o,from:a,nonce:c,data:u,signature:l,accessList:h}=this;return{_type:"TransactionReceipt",accessList:h,blockNumber:e,blockHash:t,chainId:He(this.chainId),data:u,from:a,gasLimit:He(this.gasLimit),gasPrice:He(this.gasPrice),hash:s,maxFeePerGas:He(this.maxFeePerGas),maxPriorityFeePerGas:He(this.maxPriorityFeePerGas),nonce:c,signature:l,to:o,index:r,type:i,value:He(this.value)}}async getBlock(){let e=this.blockNumber;if(e==null){const r=await this.getTransaction();r&&(e=r.blockNumber)}if(e==null)return null;const t=this.provider.getBlock(e);if(t==null)throw new Error("TODO");return t}async getTransaction(){return this.provider.getTransaction(this.hash)}async wait(e,t){const r=e??1,s=t??0;let i=m(this,Ye),o=-1,a=i===-1;const c=async()=>{if(a)return null;const{blockNumber:h,nonce:y}=await zs({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(y<this.nonce){i=h;return}if(a)return null;const p=await this.getTransaction();if(!(p&&p.blockNumber!=null))for(o===-1&&(o=i-3,o<m(this,Ye)&&(o=m(this,Ye)));o<=h;){if(a)return null;const w=await this.provider.getBlock(o,!0);if(w==null)return;for(const v of w)if(v===this.hash)return;for(let v=0;v<w.length;v++){const g=await w.getTransaction(v);if(g.from===this.from&&g.nonce===this.nonce){if(a)return null;const S=await this.provider.getTransactionReceipt(g.hash);if(S==null||h-S.blockNumber+1<r)return;let U="replaced";g.data===this.data&&g.to===this.to&&g.value===this.value?U="repriced":g.data==="0x"&&g.from===g.to&&g.value===sl&&(U="cancelled"),x(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:U==="replaced"||U==="cancelled",reason:U,replacement:g.replaceableTransaction(i),hash:g.hash,receipt:S})}}o++}},u=await this.provider.getTransactionReceipt(this.hash);if(u){if(await u.confirmations()>=r)return u}else if(await c(),r===0)return null;return await new Promise((h,y)=>{const p=[],w=()=>{p.forEach(g=>g())};if(p.push(()=>{a=!0}),s>0){const g=setTimeout(()=>{w(),y(Or("wait for transaction timeout","TIMEOUT"))},s);p.push(()=>{clearTimeout(g)})}const v=async g=>{await g.confirmations()>=r&&(w(),h(g))};if(p.push(()=>{this.provider.off(this.hash,v)}),this.provider.on(this.hash,v),i>=0){const g=async()=>{try{await c()}catch(S){if(Tr(S,"TRANSACTION_REPLACED")){w(),y(S);return}}a||this.provider.once("block",g)};p.push(()=>{this.provider.off("block",g)}),this.provider.once("block",g)}})}isMined(){return this.blockHash!=null}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}removedEvent(){return x(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),Li(this)}reorderedEvent(e){return x(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),x(!e||e.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),ji(this,e)}replaceableTransaction(e){_(Number.isInteger(e)&&e>=0,"invalid startBlock","startBlock",e);const t=new Xn(this,this.provider);return N(t,Ye,e),t}};let Un=Xn;Ye=new WeakMap;function ji(n,e){return{orphan:"reorder-transaction",tx:n,other:e}}function Li(n){return{orphan:"drop-transaction",tx:n}}function al(n){return{orphan:"drop-log",log:{transactionHash:n.transactionHash,blockHash:n.blockHash,blockNumber:n.blockNumber,address:n.address,data:n.data,topics:Object.freeze(n.topics.slice()),index:n.index}}}class jn extends Dn{constructor(t,r,s){super(t,t.provider);d(this,"interface");d(this,"fragment");d(this,"args");const i=r.decodeEventLog(s,t.data,t.topics);A(this,{args:i,fragment:s,interface:r})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class cl extends ol{constructor(t,r,s){super(s,r);j(this,Ut,void 0);N(this,Ut,t)}get logs(){return super.logs.map(t=>{const r=t.topics.length?m(this,Ut).getEvent(t.topics[0]):null;return r?new jn(t,m(this,Ut),r):t})}}Ut=new WeakMap;class Ln extends Un{constructor(t,r,s){super(s,r);j(this,sr,void 0);N(this,sr,t)}async wait(t){const r=await super.wait();return r==null?null:new cl(m(this,sr),this.provider,r)}}sr=new WeakMap;class Bi extends Dc{constructor(t,r,s,i){super(t,r,s);d(this,"log");A(this,{log:i})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class ul extends Bi{constructor(e,t,r,s,i){super(e,t,r,new jn(i,e.interface,s));const o=e.interface.decodeEventLog(s,this.log.data,this.log.topics);A(this,{args:o,fragment:s})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const Hi=BigInt(0);function Mi(n){return n&&typeof n.call=="function"}function Vi(n){return n&&typeof n.estimateGas=="function"}function Bn(n){return n&&typeof n.resolveName=="function"}function zi(n){return n&&typeof n.sendTransaction=="function"}class ll{constructor(e,t,r){j(this,ir,void 0);d(this,"fragment");if(A(this,{fragment:t}),t.inputs.length<r.length)throw new Error("too many arguments");const s=mt(e.runner,"resolveName"),i=Bn(s)?s:null;N(this,ir,async function(){const o=await Promise.all(t.inputs.map((a,c)=>r[c]==null?null:a.walkAsync(r[c],(l,h)=>l==="address"?Nn(h,i):h)));return e.interface.encodeFilterTopics(t,o)}())}getTopicFilter(){return m(this,ir)}}ir=new WeakMap;function hl(){return Function}function mt(n,e){return n==null?null:typeof n[e]=="function"?n:n.provider&&typeof n.provider[e]=="function"?n.provider:null}function gt(n){return n==null?null:n.provider||null}async function qi(n,e){const t=il(X.dereference(n,"overrides"));return _(t.to==null||(e||[]).indexOf("to")>=0,"cannot override to","overrides.to",t.to),_(t.data==null||(e||[]).indexOf("data")>=0,"cannot override data","overrides.data",t.data),t.from&&(t.from=await Nn(t.from)),t}async function fl(n,e,t){const r=mt(n,"resolveName"),s=Bn(r)?r:null;return await Promise.all(e.map((i,o)=>i.walkAsync(t[o],(a,c)=>(c=X.dereference(c,a),a==="address"?Nn(c,s):c))))}class dl{constructor(e){d(this,"_contract");return A(this,{_contract:e}),new Proxy(this,{apply:async(r,s,i)=>await r.send(...i)})}async populateTransaction(e){const t=await qi(e,["data"]);t.to=await this._contract.getAddress();const r=this._contract.interface,s=r.receive||r.fallback&&r.fallback.payable;return _(s||(t.value||Hi)===Hi,"cannot send value to non-payable contract","overrides.value",t.value),_(r.fallback||(t.data||"0x")==="0x","cannot send data to receive-only contract","overrides.data",t.data),t}async staticCall(e){const t=mt(this._contract.runner,"call");x(Mi(t),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const r=await this.populateTransaction(e);try{return await t.call(r)}catch(s){throw qs(s)&&s.data?this._contract.interface.makeError(s.data,r):s}}async send(e){const t=this._contract.runner;x(zi(t),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const r=await t.sendTransaction(await this.populateTransaction(e)),s=gt(this._contract.runner);return new Ln(this._contract.interface,s,r)}async estimateGas(e){const t=mt(this._contract.runner,"estimateGas");return x(Vi(t),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await t.estimateGas(await this.populateTransaction(e))}}class pl extends hl(){constructor(t,r){super();d(this,"name","");d(this,"_contract");d(this,"_key");return A(this,{name:t.interface.getFunctionName(r),_contract:t,_key:r}),new Proxy(this,{apply:async(i,o,a)=>i.getFragment(...a).constant?await i.staticCall(...a):await i.send(...a)})}get fragment(){const t=this._contract.interface.getFunction(this._key);return x(t,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment"}),t}getFragment(...t){const r=this._contract.interface.getFunction(this._key,t);return x(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment"}),r}async populateTransaction(...t){const r=this.getFragment(...t);let s={};if(r.inputs.length+1===t.length&&(s=await qi(t.pop())),r.inputs.length!==t.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const i=await fl(this._contract.runner,r.inputs,t);return Object.assign({},s,await zs({to:this._contract.getAddress(),data:this._contract.interface.encodeFunctionData(r,i)}))}async staticCall(...t){const r=await this.staticCallResult(...t);return r.length===1?r[0]:r}async send(...t){const r=this._contract.runner;x(zi(r),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const s=await r.sendTransaction(await this.populateTransaction(...t)),i=gt(this._contract.runner);return new Ln(this._contract.interface,i,s)}async estimateGas(...t){const r=mt(this._contract.runner,"estimateGas");return x(Vi(r),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await r.estimateGas(await this.populateTransaction(...t))}async staticCallResult(...t){const r=mt(this._contract.runner,"call");x(Mi(r),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const s=await this.populateTransaction(...t);let i="0x";try{i=await r.call(s)}catch(a){throw qs(a)&&a.data?this._contract.interface.makeError(a.data,s):a}const o=this.getFragment(...t);return this._contract.interface.decodeFunctionResult(o,i)}}function yl(){return Function}class ml extends yl(){constructor(t,r){super();d(this,"name","");d(this,"_contract");d(this,"_key");return A(this,{name:t.interface.getEventName(r),_contract:t,_key:r}),new Proxy(this,{apply:(s,i,o)=>new ll(t,s.getFragment(...o),o)})}get fragment(){const t=this._contract.interface.getEvent(this._key);return x(t,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment"}),t}getFragment(...t){const r=this._contract.interface.getEvent(this._key,t);return x(r,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment"}),r}}const jr=Symbol.for("_ethersInternal_contract"),Gi=new WeakMap;function gl(n,e){Gi.set(n[jr],e)}function fe(n){return Gi.get(n[jr])}function wl(n){return n&&typeof n=="object"&&"getTopicFilter"in n&&typeof n.getTopicFilter=="function"&&n.fragment}async function Hn(n,e){let t,r=null;if(Array.isArray(e)){const i=function(o){if(qe(o,32))return o;const a=n.interface.getEvent(o);return _(a,"unknown fragment","name",o),a.topicHash};t=e.map(o=>o==null?null:Array.isArray(o)?o.map(i):i(o))}else e==="*"?t=[null]:typeof e=="string"?qe(e,32)?t=[e]:(r=n.interface.getEvent(e),_(r,"unknown fragment","event",e),t=[r.topicHash]):wl(e)?t=await e.getTopicFilter():"fragment"in e?(r=e.fragment,t=[r.topicHash]):_(!1,"unknown event name","event",e);t=t.map(i=>{if(i==null)return null;if(Array.isArray(i)){const o=Array.from(new Set(i.map(a=>a.toLowerCase())).values());return o.length===1?o[0]:(o.sort(),o)}return i.toLowerCase()});const s=t.map(i=>i==null?"null":Array.isArray(i)?i.join("|"):i).join("&");return{fragment:r,tag:s,topics:t}}async function Xt(n,e){const{subs:t}=fe(n);return t.get((await Hn(n,e)).tag)||null}async function Ji(n,e,t){const r=gt(n.runner);x(r,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:e});const{fragment:s,tag:i,topics:o}=await Hn(n,t),{addr:a,subs:c}=fe(n);let u=c.get(i);if(!u){const h={address:a||n,topics:o},y=g=>{let S=s;if(S==null)try{S=n.interface.getEvent(g.topics[0])}catch{}if(S){const U=S,te=s?n.interface.decodeEventLog(s,g.data,g.topics):[];Vn(n,t,te,L=>new ul(n,L,t,U,g))}else Vn(n,t,[],U=>new Bi(n,U,t,g))};let p=[];u={tag:i,listeners:[],start:()=>{p.length||p.push(r.on(h,y))},stop:async()=>{if(p.length==0)return;let g=p;p=[],await Promise.all(g),r.off(h,y)}},c.set(i,u)}return u}let Mn=Promise.resolve();async function bl(n,e,t,r){await Mn;const s=await Xt(n,e);if(!s)return!1;const i=s.listeners.length;return s.listeners=s.listeners.filter(({listener:o,once:a})=>{const c=Array.from(t);r&&c.push(r(a?null:o));try{o.call(n,...c)}catch{}return!a}),i>0}async function Vn(n,e,t,r){try{await Mn}catch{}const s=bl(n,e,t,r);return Mn=s,await s}const Wi=["then"],Mr=class{constructor(e,t,r,s){d(this,"target");d(this,"interface");d(this,"runner");d(this,"filters");d(this,$l);d(this,"fallback");r==null&&(r=null);const i=Fn.from(t);A(this,{target:e,runner:r,interface:i}),Object.defineProperty(this,jr,{value:{}});let o,a=null,c=null;if(s){const h=gt(r);c=new Ln(this.interface,h,s)}let u=new Map;if(typeof e=="string")if(qe(e))a=e,o=Promise.resolve(e);else{const h=mt(r,"resolveName");if(!Bn(h))throw Or("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});o=h.resolveName(e).then(y=>{if(y==null)throw new Error("TODO");return fe(this).addr=y,y})}else o=e.getAddress().then(h=>{if(h==null)throw new Error("TODO");return fe(this).addr=h,h});gl(this,{addrPromise:o,addr:a,deployTx:c,subs:u});const l=new Proxy({},{get:(h,y,p)=>{if(Wi.indexOf(y)>=0)return Reflect.get(h,y,p);const w=String(y),v=this.getEvent(w);if(v)return v;throw new Error(`unknown contract event: ${w}`)}});return A(this,{filters:l}),A(this,{fallback:i.receive||i.fallback?new dl(this):null}),new Proxy(this,{get:(h,y,p)=>{if(y in h||Wi.indexOf(y)>=0)return Reflect.get(h,y,p);const w=String(y),v=h.getFunction(w);if(v)return v;throw new Error(`unknown contract method: ${w}`)}})}connect(e){return new Mr(this.target,this.interface,e)}async getAddress(){return await fe(this).addrPromise}async getDeployedCode(){const e=gt(this.runner);x(e,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const t=await e.getCode(await this.getAddress());return t==="0x"?null:t}async waitForDeployment(){const e=this.deploymentTransaction();if(e)return await e.wait(),this;if(await this.getDeployedCode()!=null)return this;const r=gt(this.runner);return x(r!=null,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise((s,i)=>{const o=async()=>{try{if(await this.getDeployedCode()!=null)return s(this);r.once("block",o)}catch(a){i(a)}};o()})}deploymentTransaction(){return fe(this).deployTx}getFunction(e){return typeof e!="string"&&(e=e.format()),new pl(this,e)}getEvent(e){return typeof e!="string"&&(e=e.format()),new ml(this,e)}async queryTransaction(e){throw new Error("@TODO")}async queryFilter(e,t,r){t==null&&(t=0),r==null&&(r="latest");const{addr:s,addrPromise:i}=fe(this),o=s||await i,{fragment:a,topics:c}=await Hn(this,e),u={address:o,topics:c,fromBlock:t,toBlock:r},l=gt(this.runner);return x(l,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await l.getLogs(u)).map(h=>{let y=a;if(y==null)try{y=this.interface.getEvent(h.topics[0])}catch{}return y?new jn(h,this.interface,y):new Dn(h,l)})}async on(e,t){const r=await Ji(this,"on",e);return r.listeners.push({listener:t,once:!1}),r.start(),this}async once(e,t){const r=await Ji(this,"once",e);return r.listeners.push({listener:t,once:!0}),r.start(),this}async emit(e,...t){return await Vn(this,e,t,null)}async listenerCount(e){if(e){const s=await Xt(this,e);return s?s.listeners.length:0}const{subs:t}=fe(this);let r=0;for(const{listeners:s}of t.values())r+=s.length;return r}async listeners(e){if(e){const s=await Xt(this,e);return s?s.listeners.map(({listener:i})=>i):[]}const{subs:t}=fe(this);let r=[];for(const{listeners:s}of t.values())r=r.concat(s.map(({listener:i})=>i));return r}async off(e,t){const r=await Xt(this,e);if(!r)return this;if(t){const s=r.listeners.map(({listener:i})=>i).indexOf(t);s>=0&&r.listeners.splice(s,1)}return(t==null||r.listeners.length===0)&&(r.stop(),fe(this).subs.delete(r.tag)),this}async removeAllListeners(e){if(e){const t=await Xt(this,e);if(!t)return this;t.stop(),fe(this).subs.delete(t.tag)}else{const{subs:t}=fe(this);for(const{tag:r,stop:s}of t.values())s(),t.delete(r)}return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return await this.off(e,t)}static buildClass(e){class t extends Mr{constructor(s,i=null){super(s,e,i)}}return t}static from(e,t,r){return r==null&&(r=null),new this(e,t,r)}};let zn=Mr;$l=jr;function vl(){return zn}class _l extends vl(){}class wt{constructor(e){d(this,"data",[]);this.api=e}static create(e){return new wt(e)}getAbiHash(e){if(this.api===void 0)throw new Error("FunctionBuilder must be initialised with api");return this.api.getAbiHash(e)}static readFields(e,t){if(e.length===0)return[];const r=(s,i)=>{const o=t[i].find(a=>a.name===s.function);if(!o)throw new Error("function not in ABI");return o.outputs.map((a,c)=>({source:`function:${s.function}:${i}`,name:a.name,type:a.type,key:`func_${i}_ret_${c}`,index:c}))};return e.map((s,i)=>r(s,i))}async addFunction(e,t,r,s,i){const o=new _l(e,s);return o.interface.encodeFunctionData(t,r),i=i||await this.getAbiHash(s),this.data.push({address:e,bytecode:o.interface.encodeFunctionData(t,r),abiHash:i,function:t}),this}get(){return this.data}static schema(){return lt().of(se({address:T().required(),bytecode:T().matches(/^(0x)?([0-9a-fA-F]{2})*$/).required(),abiHash:T().matches(/^[A-Fa-f0-9]{64}/).required(),function:T().required()}))}}class Ke{static version(){return"v1"}static execute(e,t,r="v1"){const s=JSON.parse(JSON.stringify(t));let i=!0;for(const o of s){const a=Ke.process(e,o.conditions);i=Ke.execLogic(i,o.logic,a)}return i}static process(e,t,r){const s=t.shift();if(!s)return r===void 0?!0:r;const i=Ke.execCondition(e,s);if(r===void 0||s.logic==="WHERE")return Ke.process(e,t,i);if(s.logic===void 0)throw new Error("Invalid filter. FilterCondition must have logic value");const o=Ke.execLogic(r,s.logic,i);return Ke.process(e,t,o)}static execLogic(e,t,r){switch(t){case"AND":return e&&r;case"OR":return e||r;case"XOR":return(e||r)&&!(e&&r);case"NAND":return!(e&&r);case"NOR":return!(e&&r);case"WHERE":return r;default:throw new Error(`Invalid Filter. Bad logic value: ${t}`)}}static execCondition(e,t){const r=e[t.key];if(t.type==="Number"){if(typeof t.constant!="number"||typeof r!="number")throw new Error(`Invalid filter. Type miss-match. Type: ${t.type}, Variable: ${t.constant}, Data: ${r}`);const s=r,i=t.constant;switch(t.operation){case"eq":return s===i;case"!eq":return s!==i;case"gt":return s>i;case"gte":return s>=i;case"lt":return s<i;case"lte":return s<=i;default:throw new Error("Invalid Filter. Operation does not match type")}}if(t.type==="String"){if(typeof t.constant!="string"||typeof r!="string")throw new Error(`Invalid filter. Type miss-match. Type: ${t.type}, Variable: ${t.constant}, Data: ${r}`);const s=r,i=t.constant;switch(t.operation){case"contains":return s.includes(i);case"!contains":return!s.includes(i);case"is":return s===i;case"!is":return s!==i;case"isEmpty":return s==="";case"!isEmpty":return s!=="";default:throw new Error("Invalid Filter. Operation does not match type")}}if(t.type==="Address"){if(typeof t.constant!="string"||typeof r!="string")throw new Error(`Invalid filter. Type miss-match. Type: ${t.type}, Variable: ${t.constant}, Data: ${r}`);const s=r,i=t.constant;switch(t.operation){case"contains":return s.toLowerCase().includes(i.toLowerCase());case"!contains":return!s.toLowerCase().includes(i.toLowerCase());case"is":return s.toLowerCase()===i.toLowerCase();case"!is":return s.toLowerCase()!==i.toLowerCase();case"isEmpty":return s==="";case"!isEmpty":return s!=="";default:throw new Error("Invalid Filter. Operation does not match type")}}throw new Error("Invalid Filter. Unknown Type")}}class Zt{constructor(){d(this,"groups",[]);this.newGroup("WHERE")}static version(){return Ke.version()}static new(){return new Zt}newGroup(e){if(this.groups.length!==0&&e==="WHERE")throw new Error('Only the first groups can start with "WHERE"');return this.groups.push({logic:"WHERE",conditions:[]}),this}addCondition(e,t,r,s,i){const o=this.groups[this.groups.length-1];if(o.conditions.length===0&&e!=="WHERE")throw new Error('Logic for the first condition of a group must be "WHERE"');if(o.conditions.length>0&&e==="WHERE")throw new Error('Only the first condition of a group can be "WHERE"');return o.conditions.push({logic:e,key:t,type:r,operation:s,constant:i}),this}finalise(){for(const e of this.groups)if(e.conditions.length===0)throw new Error("Bad Filter. All Groups must have atleast one condition");return this.groups}static schema(){const e=T().oneOf(["AND","OR","XOR","NAND","NOR","WHERE"]).required(),t=se({logic:e,key:T().required(),type:T().oneOf(["String","Address","Number"]).required(),operation:T().when("type",([r],s)=>{switch(r){case"String":return s.oneOf(["contains","!contains","is","!is","isEmpty","!isEmpty"]);case"Address":return s.oneOf(["is","!is","isEmpty","!isEmpty"]);case"Number":return s.oneOf(["eq","!eq","gt","gte","lt","lte"]);default:throw new Error("Invalid Filter Data Type")}}).required(),constant:$s().when("type",([r])=>{switch(r){case"String":return T();case"Address":return T();case"Number":return q();default:throw new Error("Invalid Filter Data Type")}}).required()});return lt().of(se({logic:e,conditions:lt().of(t).required()}))}}const El="handler_function_call_v2",xl=/^(\d+)([SMHD])$/i,Ki=se({timeBase:T().oneOf(["blocks","time"]).required(),nBlocks:q().min(10).when("timeBase",([n],e)=>n==="blocks"?e.required():e),timePeriod:T().matches(xl,"timePeriod must be of the format n[s|m|h|d], eg 10s for 10 seconds").when("timeBase",([n],e)=>n==="time"?e.required():e),startTime:q().default(0),debounceCount:q().default(0),functions:wt.schema().required(),triggerOn:T().oneOf(["always","filter"]).default("always"),latch:_r().default(!1),filterVersion:T().when("triggerOn",([n],e)=>n==="filter"?e.default("0"):e.nullable().default(null)).required(),filter:Zt.schema().when("triggerOn",([n],e)=>n==="filter"?e.required():e.nullable().default(null)).required()});class qn{static async SimpleToRaw(e,t,r){return{alertType:"event",network:t,nickname:e,type:El,handler:await this.validate(r)}}static validate(e){return Ki.validateSync(e)}static async convertFromPartial(e){return Ki.validate(e)}static readFields(e,t){const r=[{source:"defaults",label:"Network",type:"string",key:"network"},{source:"defaults",label:"Timestamp",type:"number",key:"timestamp"},{source:"defaults",label:"Time GMT",type:"number",key:"timeStringGMT"},{source:"defaults",label:"Block",type:"number",key:"block"},{source:"defaults",label:"Time Period",type:"number",key:"timePeriod"}];if(!e.functions)return r;const s=e.functions.map(i=>t[i.abiHash]);return[...wt.readFields(e.functions,s),...r]}}const Tl="handler_onchain_event_v2",Ol=se({addresses:lt().of(T().required()).required(),abiHash:T().required(),event:T().required(),debounceCount:q().default(0),functions:wt.schema().nullable().default(null),triggerOn:T().oneOf(["always","filter"]).default("always"),latch:_r().default(!1),filterVersion:T().nullable().default(null),filter:Zt.schema().when("triggerOn",([n],e)=>n==="filter"?e:e.nullable().default(null)).required()}),kl=n=>n,Xi=(n,e,t=[],r="",s="")=>(n.forEach((i,o)=>{const a=i.type.includes("["),c=a?"_[]":"";if(i.components){const u=i.name===""?`${o}`:i.name;Xi(i.components,e,t,`${r}${o}${c}_`,`${u}${a?"[]":""}.`)}else t.push({source:e,label:`${s}${i.name}`,type:kl(i.type),key:`${r}${o}${c}`,index:o})}),t);class Gn{static async SimpleToRaw(e,t,r){return{alertType:"event",network:t,nickname:e,type:Tl,handler:await this.validate(r)}}static validate(e){return Ol.validateSync(e)}static readFields(e,t){let r=[{source:"defaults",label:"Network",type:"string",key:"network"},{source:"defaults",label:"Timestamp",type:"number",key:"timestamp"},{source:"defaults",label:"Time GMT",type:"string",key:"timeStringGMT"},{source:"defaults",label:"Block",type:"number",key:"block"},{source:"defaults",label:"Time Period",type:"string",key:"timePeriod"},{source:"defaults",label:"Block Hash",type:"string",key:"blockHash"},{source:"defaults",label:"Transaction Hash",type:"string",key:"txHash"},{source:"defaults",label:"Event",type:"string",key:"event"}];const s=t[e.abiHash].find(o=>o.name===e.event);if(r=Xi(s.inputs,`${e.event} Event`,r,"param_"),!e.functions)return r;const i=e.functions.map(o=>t[o.abiHash]);return[...wt.readFields(e.functions,i),...r]}}class Yt{static SimpleToRaw(e,t,r,s){switch(t){case"PollFunctionV2":return qn.SimpleToRaw(e,r,s);case"PollFunctionV1":return Ms.SimpleToRaw(e,r,s);case"OnchainEventV1":return Vs.SimpleToRaw(e,r,s);case"OnchainEventV2":return Gn.SimpleToRaw(e,r,s);default:throw new Error("Invalid Trigger ID")}}static Validate(e,t){switch(e){case"PollFunctionV2":return qn.validate(t);case"PollFunctionV1":return Ms.validate(t);case"OnchainEventV1":return Vs.validate(t);case"OnchainEventV2":return Gn.validate(t);default:throw new Error("Invalid Trigger ID")}}static RawToSimple(e){return{...{error:e.error,error_message:e.error_message,error_timestamp:e.error_timestamp},...e.handler}}static SimpleTypeToRawType(e){switch(e){case"PollFunctionV2":return"handler_function_call_v2";case"PollFunctionV1":return"handler_function_call";case"OnchainEventV1":return"handler_onchain_event";case"OnchainEventV2":return"handler_onchain_event_v2";default:throw new Error("Invalid Trigger ID")}}static RawTypeToSimpleType(e){switch(e){case"handler_function_call_v2":return"PollFunctionV2";case"handler_function_call":return"PollFunctionV1";case"handler_onchain_event":return"OnchainEventV1";case"handler_onchain_event_v2":return"OnchainEventV2";default:throw new Error("Invalid Trigger ID")}}static readFields(e,t,r){switch(e){case"PollFunctionV2":return qn.readFields(t,r);case"OnchainEventV2":return Gn.readFields(t,r);default:throw new Error("Invalid Trigger ID")}}}const Zi=n=>`https://${n}.functions.supabase.co/`,Yi=n=>`https://${n}.supabase.co/`,Qi="fdgtrxmmrtlokhgkvcjz",Al="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImZkZ3RyeG1tcnRsb2toZ2t2Y2p6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2NzMwODcwNzYsImV4cCI6MTk4ODY2MzA3Nn0.sAMxjlcJSSozBGr-LNcsudyxzUEM9e-UspMHHQLqLr4";class Jn{constructor(e,t){d(this,"headers",{});this.url=e,this.headers={Authorization:`Bearer ${t}`,"Content-Type":"application/json"}}static async create(e){var t,r;if(e.key)throw new Error("Auth by key not yet supported");if(e.email&&e.password){const s=e.projectId?Yi(e.projectId):Yi(Qi),i=e.projectId?Zi(e.projectId):Zi(Qi),o=e.anonKey?e.anonKey:Al,a=Ca(s,o),{data:c,error:u}=await a.auth.signInWithPassword({email:e.email,password:e.password});if(u)throw u;if(((t=c.session)==null?void 0:t.access_token)===void 0)throw new Error("Access token not found");return new Jn(i,(r=c.session)==null?void 0:r.access_token)}else throw new Error("Authentication Required. DeNotify supports either username/password or API key authentication")}async alertHistory(e,t){const r="alert-history",s=t||{};return e&&(s.id=e),Object.keys(s).length>0?await this.request("get",r,{params:t}):await this.request("get",r)}async getAlert(e){const t=(await this.request("get",`alerts/${e}`))[0];return await this.decode(t)}async getAlerts(){const e=await this.request("get","alerts");return Promise.all(e.map(t=>this.decode(t)))}async createAlert(e){const t=await this.encode(e);return await this.request("post","alerts",{body:t})}async updateRawTrigger(e,t){const r=await se({name:T().optional(),enabled:_r().optional()}).validate(t);await this.request("patch",`alerts/trigger/${e}`,{body:r})}async updateAlert(e,t){const r=[],{trigger:s,notification:i,...o}=t;return(o.name||o.enabled)&&r.push(this.updateRawTrigger(e,o)),s&&r.push(this.updateRawHandler(e,s)),i&&r.push(this.updateRawNotify(e,i)),await Promise.all(r),await this.getAlert(e)}async deleteAlert(e){return await this.request("delete",`alerts/${e}`)}async decode(e){return{id:e.alertId,enabled:e.trigger.enabled,name:e.trigger.nickname,network:e.trigger.network,triggerId:Yt.RawTypeToSimpleType(e.trigger.type),trigger:await Yt.RawToSimple(e.trigger),notificationId:En.RawTypeToSimpleType(e.notification.notify_type),notification:await En.RawToSimple(e.notification)}}async encode(e){return{trigger:await Yt.SimpleToRaw(e.name,e.triggerId,e.network,e.trigger),notification:await En.SimpleToRaw(e.notificationId,e.notification)}}async request(e,t,r={}){const s=new URL((void 0)(this.url,t));if(r.params)for(const a of Object.keys(r.params))s.searchParams.append(a,r.params[a]);const i={method:e,headers:this.headers};return r.body&&(i.body=JSON.stringify(r.body)),(await fetch(s.toString(),i)).json()}readFields(e,t,r){return Yt.readFields(e,t,r)}async getAbi(e,t){return await this.request("get",`abi/${e}/${t}`)}async getAbiHash(e){return(await this.request("post","abi",{body:e})).hash}async updateRawNotify(e,t){return await this.request("patch",`alerts/notify/${e}`,{body:t})}async updateRawHandler(e,t){return await this.request("patch",`alerts/trigger-handler/${e}`,{body:t})}}class Wn{constructor(e){d(this,"network");d(this,"triggerId");d(this,"trigger");d(this,"notificationId");d(this,"notification");this.name=e}static create(e){return new Wn(e)}onNetwork(e){return this.network=e,this}withTrigger(e,t){return this.triggerId=e,this.trigger=Yt.Validate(e,t),this}withNotification(e,t){return this.notificationId=e,this.notification=t,this}async config(){if(this.trigger===void 0||this.triggerId===void 0)throw new Error("Trigger not configured");if(this.notification===void 0||this.notificationId===void 0)throw new Error("Notification not configured");if(this.network===void 0)throw new Error("Network not configured");return{name:this.name,network:this.network,triggerId:this.triggerId,trigger:this.trigger,notificationId:this.notificationId,notification:this.notification}}}const Sl=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Rl=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));return R.AlertBuilder=Wn,R.DeNotifyClient=Jn,R.FilterBuilder=Zt,R.FunctionBuilder=wt,R.Notification=Rl,R.Trigger=Sl,Object.defineProperty(R,Symbol.toStringTag,{value:"Module"}),R}({});
|