@junobuild/core-standalone 2.2.0 → 2.2.1-next-2025-10-22

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,57 +1,57 @@
1
- var Pd=Object.defineProperty;var Bd=(e,t)=>{for(var r in t)Pd(e,r,{get:t[r],enumerable:!0})};var Za;(function(e){e[e.SysFatal=1]="SysFatal",e[e.SysTransient=2]="SysTransient",e[e.DestinationInvalid=3]="DestinationInvalid",e[e.CanisterReject=4]="CanisterReject",e[e.CanisterError=5]="CanisterError"})(Za||(Za={}));var Gt;(function(e){e.Replied="replied",e.Rejected="rejected"})(Gt||(Gt={}));function Xa(e){return e!=null&&"reject_code"in e}function Qa(e){return e!=null&&"certificate"in e}var To="abcdefghijklmnopqrstuvwxyz234567",Kr=Object.create(null);for(let e=0;e<To.length;e++)Kr[To[e]]=e;Kr[0]=Kr.o;Kr[1]=Kr.i;function ec(e){let t=0,r=0,n="";function o(s){return t<0?r|=s>>-t:r=s<<t&248,t>3?(t-=8,1):(t<4&&(n+=To[r>>3],t+=5),0)}for(let s=0;s<e.length;)s+=o(e[s]);return n+(t<0?To[r>>3]:"")}function tc(e){let t=0,r=0,n=new Uint8Array(e.length*4/3|0),o=0;function s(i){let a=Kr[i.toLowerCase()];if(a===void 0)throw new Error(`Invalid character: ${JSON.stringify(i)}`);a<<=3,r|=a>>>t,t+=5,t>=8&&(n[o++]=r,t-=8,t>0?r=a<<5-t&255:r=0)}for(let i of e)s(i);return n.slice(0,o)}var Cd=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function rc(e){let t=-1;for(let r=0;r<e.length;r++){let o=(e[r]^t)&255;t=Cd[o]^t>>>8}return(t^-1)>>>0}var fr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ft(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function li(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ue(e,...t){if(!ft(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function ui(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function oc(e,t){ue(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function hr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Oo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function rt(e,t){return e<<32-t|e>>>t}var sc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Vd=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function M(e){if(ue(e),sc)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Vd[e[r]];return t}var Et={_0:48,_9:57,A:65,F:70,a:97,f:102};function nc(e){if(e>=Et._0&&e<=Et._9)return e-Et._0;if(e>=Et.A&&e<=Et.F)return e-(Et.A-10);if(e>=Et.a&&e<=Et.f)return e-(Et.a-10)}function be(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(sc)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=nc(e.charCodeAt(s)),a=nc(e.charCodeAt(s+1));if(i===void 0||a===void 0){let c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Q(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function di(e){return typeof e=="string"&&(e=Q(e)),ue(e),e}function K(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];ue(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let s=e[n];r.set(s,o),o+=s.length}return r}var No=class{};function Eo(e){let t=n=>e().update(di(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function $r(e=32){if(fr&&typeof fr.getRandomValues=="function")return fr.getRandomValues(new Uint8Array(e));if(fr&&typeof fr.randomBytes=="function")return Uint8Array.from(fr.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Dd(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function ic(e,t,r){return e&t^~e&r}function ac(e,t,r){return e&t^e&r^t&r}var En=class extends No{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Oo(this.buffer)}update(t){ui(this),t=di(t),ue(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Oo(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){ui(this),oc(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,hr(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let d=i;d<o;d++)r[d]=0;Dd(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Oo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,p=this.get();if(u>p.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<u;d++)a.setUint32(4*d,p[d],s)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Rt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),vt=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);var Ee=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Ro=BigInt(4294967295),cc=BigInt(32);function Ud(e,t=!1){return t?{h:Number(e&Ro),l:Number(e>>cc&Ro)}:{h:Number(e>>cc&Ro)|0,l:Number(e&Ro)|0}}function lc(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Ud(e[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var pi=(e,t,r)=>e>>>r,fi=(e,t,r)=>e<<32-r|t>>>r,mr=(e,t,r)=>e>>>r|t<<32-r,_r=(e,t,r)=>e<<32-r|t>>>r,Rn=(e,t,r)=>e<<64-r|t>>>r-32,vn=(e,t,r)=>e>>>r-32|t<<64-r;function ht(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var uc=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),dc=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,pc=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),fc=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,hc=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),mc=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0;var Ld=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),zt=new Uint32Array(64),vo=class extends En{constructor(t=32){super(64,t,8,!1),this.A=Rt[0]|0,this.B=Rt[1]|0,this.C=Rt[2]|0,this.D=Rt[3]|0,this.E=Rt[4]|0,this.F=Rt[5]|0,this.G=Rt[6]|0,this.H=Rt[7]|0}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,r){for(let d=0;d<16;d++,r+=4)zt[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){let l=zt[d-15],f=zt[d-2],h=rt(l,7)^rt(l,18)^l>>>3,_=rt(f,17)^rt(f,19)^f>>>10;zt[d]=_+zt[d-7]+h+zt[d-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:p}=this;for(let d=0;d<64;d++){let l=rt(a,6)^rt(a,11)^rt(a,25),f=p+l+ic(a,c,u)+Ld[d]+zt[d]|0,_=(rt(n,2)^rt(n,13)^rt(n,22))+ac(n,o,s)|0;p=u,u=c,c=a,a=i+f|0,i=s,s=o,o=n,n=f+_|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,p=p+this.H|0,this.set(n,o,s,i,a,c,u,p)}roundClean(){hr(zt)}destroy(){this.set(0,0,0,0,0,0,0,0),hr(this.buffer)}},hi=class extends vo{constructor(){super(28),this.A=vt[0]|0,this.B=vt[1]|0,this.C=vt[2]|0,this.D=vt[3]|0,this.E=vt[4]|0,this.F=vt[5]|0,this.G=vt[6]|0,this.H=vt[7]|0}},_c=lc(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),qd=_c[0],Md=_c[1],Wt=new Uint32Array(80),Yt=new Uint32Array(80),mi=class extends En{constructor(t=64){super(128,t,16,!1),this.Ah=Ee[0]|0,this.Al=Ee[1]|0,this.Bh=Ee[2]|0,this.Bl=Ee[3]|0,this.Ch=Ee[4]|0,this.Cl=Ee[5]|0,this.Dh=Ee[6]|0,this.Dl=Ee[7]|0,this.Eh=Ee[8]|0,this.El=Ee[9]|0,this.Fh=Ee[10]|0,this.Fl=Ee[11]|0,this.Gh=Ee[12]|0,this.Gl=Ee[13]|0,this.Hh=Ee[14]|0,this.Hl=Ee[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:p,Fh:d,Fl:l,Gh:f,Gl:h,Hh:_,Hl:g}=this;return[t,r,n,o,s,i,a,c,u,p,d,l,f,h,_,g]}set(t,r,n,o,s,i,a,c,u,p,d,l,f,h,_,g){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=p|0,this.Fh=d|0,this.Fl=l|0,this.Gh=f|0,this.Gl=h|0,this.Hh=_|0,this.Hl=g|0}process(t,r){for(let y=0;y<16;y++,r+=4)Wt[y]=t.getUint32(r),Yt[y]=t.getUint32(r+=4);for(let y=16;y<80;y++){let T=Wt[y-15]|0,O=Yt[y-15]|0,R=mr(T,O,1)^mr(T,O,8)^pi(T,O,7),E=_r(T,O,1)^_r(T,O,8)^fi(T,O,7),v=Wt[y-2]|0,w=Yt[y-2]|0,I=mr(v,w,19)^Rn(v,w,61)^pi(v,w,6),B=_r(v,w,19)^vn(v,w,61)^fi(v,w,6),A=pc(E,B,Yt[y-7],Yt[y-16]),b=fc(A,R,I,Wt[y-7],Wt[y-16]);Wt[y]=b|0,Yt[y]=A|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:p,Eh:d,El:l,Fh:f,Fl:h,Gh:_,Gl:g,Hh:m,Hl:x}=this;for(let y=0;y<80;y++){let T=mr(d,l,14)^mr(d,l,18)^Rn(d,l,41),O=_r(d,l,14)^_r(d,l,18)^vn(d,l,41),R=d&f^~d&_,E=l&h^~l&g,v=hc(x,O,E,Md[y],Yt[y]),w=mc(v,m,T,R,qd[y],Wt[y]),I=v|0,B=mr(n,o,28)^Rn(n,o,34)^Rn(n,o,39),A=_r(n,o,28)^vn(n,o,34)^vn(n,o,39),b=n&s^n&a^s&a,N=o&i^o&c^i&c;m=_|0,x=g|0,_=f|0,g=h|0,f=d|0,h=l|0,{h:d,l}=ht(u|0,p|0,w|0,I|0),u=a|0,p=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let P=uc(I,A,N);n=dc(P,w,B,b),o=P|0}({h:n,l:o}=ht(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ht(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ht(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:p}=ht(this.Dh|0,this.Dl|0,u|0,p|0),{h:d,l}=ht(this.Eh|0,this.El|0,d|0,l|0),{h:f,l:h}=ht(this.Fh|0,this.Fl|0,f|0,h|0),{h:_,l:g}=ht(this.Gh|0,this.Gl|0,_|0,g|0),{h:m,l:x}=ht(this.Hh|0,this.Hl|0,m|0,x|0),this.set(n,o,s,i,a,c,u,p,d,l,f,h,_,g,m,x)}roundClean(){hr(Wt,Yt)}destroy(){hr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var ve=Eo(()=>new vo),yc=Eo(()=>new hi),gc=Eo(()=>new mi);var Io="__principal__",jd=2,xc=4,Kd="aaaaa-aa",L=class e{static anonymous(){return new this(new Uint8Array([xc]))}static managementCanister(){return this.fromText(Kd)}static selfAuthenticating(t){let r=yc(t);return new this(new Uint8Array([...r,jd]))}static from(t){if(typeof t=="string")return e.fromText(t);if(Object.getPrototypeOf(t)===Uint8Array.prototype)return new e(t);if(e.isPrincipal(t))return new e(t._arr);throw new Error(`Impossible to convert ${JSON.stringify(t)} to Principal.`)}static fromHex(t){return new this(be(t))}static fromText(t){let r=t;if(t.includes(Io)){let i=JSON.parse(t);Io in i&&(r=i[Io])}let n=r.toLowerCase().replace(/-/g,""),o=tc(n);o=o.slice(4,o.length);let s=new this(o);if(s.toText()!==r)throw new Error(`Principal "${s.toText()}" does not have a valid checksum (original value "${r}" may not be a valid Principal ID).`);return s}static fromUint8Array(t){return new this(t)}static isPrincipal(t){return t instanceof e||typeof t=="object"&&t!==null&&"_isPrincipal"in t&&t._isPrincipal===!0&&"_arr"in t&&t._arr instanceof Uint8Array}constructor(t){this._arr=t,this._isPrincipal=!0}isAnonymous(){return this._arr.byteLength===1&&this._arr[0]===xc}toUint8Array(){return this._arr}toHex(){return M(this._arr).toUpperCase()}toText(){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,rc(this._arr));let n=new Uint8Array(t),o=new Uint8Array([...n,...this._arr]),i=ec(o).match(/.{1,5}/g);if(!i)throw new Error;return i.join("-")}toString(){return this.toText()}toJSON(){return{[Io]:this.toText()}}compareTo(t){for(let r=0;r<Math.min(this._arr.length,t._arr.length);r++){if(this._arr[r]<t._arr[r])return"lt";if(this._arr[r]>t._arr[r])return"gt"}return this._arr.length<t._arr.length?"lt":this._arr.length>t._arr.length?"gt":"eq"}ltEq(t){let r=this.compareTo(t);return r=="lt"||r=="eq"}gtEq(t){let r=this.compareTo(t);return r=="gt"||r=="eq"}};var It;(function(e){e.Trust="Trust",e.Protocol="Protocol",e.Reject="Reject",e.Transport="Transport",e.External="External",e.Limit="Limit",e.Input="Input",e.Unknown="Unknown"})(It||(It={}));var H=class{constructor(t=!1){this.isCertified=t}toString(){let t=this.toErrorMessage();return this.requestContext&&(t+=`
1
+ var Ip=Object.defineProperty;var Ap=(e,t)=>{for(var r in t)Ip(e,r,{get:t[r],enumerable:!0})};var Dc;(function(e){e[e.SysFatal=1]="SysFatal",e[e.SysTransient=2]="SysTransient",e[e.DestinationInvalid=3]="DestinationInvalid",e[e.CanisterReject=4]="CanisterReject",e[e.CanisterError=5]="CanisterError"})(Dc||(Dc={}));var ir;(function(e){e.Replied="replied",e.Rejected="rejected"})(ir||(ir={}));function Uc(e){return e!=null&&"reject_code"in e}function kc(e){return e!=null&&"certificate"in e}var zo="abcdefghijklmnopqrstuvwxyz234567",un=Object.create(null);for(let e=0;e<zo.length;e++)un[zo[e]]=e;un[0]=un.o;un[1]=un.i;function Lc(e){let t=0,r=0,n="";function o(s){return t<0?r|=s>>-t:r=s<<t&248,t>3?(t-=8,1):(t<4&&(n+=zo[r>>3],t+=5),0)}for(let s=0;s<e.length;)s+=o(e[s]);return n+(t<0?zo[r>>3]:"")}function qc(e){let t=0,r=0,n=new Uint8Array(e.length*4/3|0),o=0;function s(i){let a=un[i.toLowerCase()];if(a===void 0)throw new Error(`Invalid character: ${JSON.stringify(i)}`);a<<=3,r|=a>>>t,t+=5,t>=8&&(n[o++]=r,t-=8,t>0?r=a<<5-t&255:r=0)}for(let i of e)s(i);return n.slice(0,o)}var Sp=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function Mc(e){let t=-1;for(let r=0;r<e.length;r++){let o=(e[r]^t)&255;t=Sp[o]^t>>>8}return(t^-1)>>>0}var Fr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Tt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ki(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function de(e,...t){if(!Tt(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Hi(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Kc(e,t){de(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Br(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Jo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ut(e,t){return e<<32-t|e>>>t}var Hc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Pp=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function K(e){if(de(e),Hc)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Pp[e[r]];return t}var Bt={_0:48,_9:57,A:65,F:70,a:97,f:102};function jc(e){if(e>=Bt._0&&e<=Bt._9)return e-Bt._0;if(e>=Bt.A&&e<=Bt.F)return e-(Bt.A-10);if(e>=Bt.a&&e<=Bt.f)return e-(Bt.a-10)}function Ne(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(Hc)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=jc(e.charCodeAt(s)),a=jc(e.charCodeAt(s+1));if(i===void 0||a===void 0){let c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Q(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function $i(e){return typeof e=="string"&&(e=Q(e)),de(e),e}function M(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];de(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let s=e[n];r.set(s,o),o+=s.length}return r}var Yo=class{};function Zo(e){let t=n=>e().update($i(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function dn(e=32){if(Fr&&typeof Fr.getRandomValues=="function")return Fr.getRandomValues(new Uint8Array(e));if(Fr&&typeof Fr.randomBytes=="function")return Uint8Array.from(Fr.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Cp(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function $c(e,t,r){return e&t^~e&r}function Gc(e,t,r){return e&t^e&r^t&r}var zn=class extends Yo{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Jo(this.buffer)}update(t){Hi(this),t=$i(t),de(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Jo(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Hi(this),Kc(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,Br(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let d=i;d<o;d++)r[d]=0;Cp(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Jo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,p=this.get();if(u>p.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<u;d++)a.setUint32(4*d,p[d],s)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Vt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Dt=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);var Se=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Xo=BigInt(4294967295),Wc=BigInt(32);function Fp(e,t=!1){return t?{h:Number(e&Xo),l:Number(e>>Wc&Xo)}:{h:Number(e>>Wc&Xo)|0,l:Number(e&Xo)|0}}function zc(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Fp(e[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var Gi=(e,t,r)=>e>>>r,Wi=(e,t,r)=>e<<32-r|t>>>r,Vr=(e,t,r)=>e>>>r|t<<32-r,Dr=(e,t,r)=>e<<32-r|t>>>r,Yn=(e,t,r)=>e<<64-r|t>>>r-32,Jn=(e,t,r)=>e>>>r-32|t<<64-r;function Ot(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var Yc=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Jc=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Zc=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Xc=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,Qc=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),el=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0;var Vp=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ar=new Uint32Array(64),Qo=class extends zn{constructor(t=32){super(64,t,8,!1),this.A=Vt[0]|0,this.B=Vt[1]|0,this.C=Vt[2]|0,this.D=Vt[3]|0,this.E=Vt[4]|0,this.F=Vt[5]|0,this.G=Vt[6]|0,this.H=Vt[7]|0}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,r){for(let d=0;d<16;d++,r+=4)ar[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){let l=ar[d-15],f=ar[d-2],h=ut(l,7)^ut(l,18)^l>>>3,m=ut(f,17)^ut(f,19)^f>>>10;ar[d]=m+ar[d-7]+h+ar[d-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:p}=this;for(let d=0;d<64;d++){let l=ut(a,6)^ut(a,11)^ut(a,25),f=p+l+$c(a,c,u)+Vp[d]+ar[d]|0,m=(ut(n,2)^ut(n,13)^ut(n,22))+Gc(n,o,s)|0;p=u,u=c,c=a,a=i+f|0,i=s,s=o,o=n,n=f+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,p=p+this.H|0,this.set(n,o,s,i,a,c,u,p)}roundClean(){Br(ar)}destroy(){this.set(0,0,0,0,0,0,0,0),Br(this.buffer)}},zi=class extends Qo{constructor(){super(28),this.A=Dt[0]|0,this.B=Dt[1]|0,this.C=Dt[2]|0,this.D=Dt[3]|0,this.E=Dt[4]|0,this.F=Dt[5]|0,this.G=Dt[6]|0,this.H=Dt[7]|0}},tl=zc(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Dp=tl[0],Up=tl[1],cr=new Uint32Array(80),lr=new Uint32Array(80),Yi=class extends zn{constructor(t=64){super(128,t,16,!1),this.Ah=Se[0]|0,this.Al=Se[1]|0,this.Bh=Se[2]|0,this.Bl=Se[3]|0,this.Ch=Se[4]|0,this.Cl=Se[5]|0,this.Dh=Se[6]|0,this.Dl=Se[7]|0,this.Eh=Se[8]|0,this.El=Se[9]|0,this.Fh=Se[10]|0,this.Fl=Se[11]|0,this.Gh=Se[12]|0,this.Gl=Se[13]|0,this.Hh=Se[14]|0,this.Hl=Se[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:p,Fh:d,Fl:l,Gh:f,Gl:h,Hh:m,Hl:y}=this;return[t,r,n,o,s,i,a,c,u,p,d,l,f,h,m,y]}set(t,r,n,o,s,i,a,c,u,p,d,l,f,h,m,y){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=p|0,this.Fh=d|0,this.Fl=l|0,this.Gh=f|0,this.Gl=h|0,this.Hh=m|0,this.Hl=y|0}process(t,r){for(let g=0;g<16;g++,r+=4)cr[g]=t.getUint32(r),lr[g]=t.getUint32(r+=4);for(let g=16;g<80;g++){let T=cr[g-15]|0,N=lr[g-15]|0,E=Vr(T,N,1)^Vr(T,N,8)^Gi(T,N,7),R=Dr(T,N,1)^Dr(T,N,8)^Wi(T,N,7),I=cr[g-2]|0,w=lr[g-2]|0,v=Vr(I,w,19)^Yn(I,w,61)^Gi(I,w,6),C=Dr(I,w,19)^Jn(I,w,61)^Wi(I,w,6),A=Zc(R,C,lr[g-7],lr[g-16]),b=Xc(A,E,v,cr[g-7],cr[g-16]);cr[g]=b|0,lr[g]=A|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:p,Eh:d,El:l,Fh:f,Fl:h,Gh:m,Gl:y,Hh:_,Hl:x}=this;for(let g=0;g<80;g++){let T=Vr(d,l,14)^Vr(d,l,18)^Yn(d,l,41),N=Dr(d,l,14)^Dr(d,l,18)^Jn(d,l,41),E=d&f^~d&m,R=l&h^~l&y,I=Qc(x,N,R,Up[g],lr[g]),w=el(I,_,T,E,Dp[g],cr[g]),v=I|0,C=Vr(n,o,28)^Yn(n,o,34)^Yn(n,o,39),A=Dr(n,o,28)^Jn(n,o,34)^Jn(n,o,39),b=n&s^n&a^s&a,O=o&i^o&c^i&c;_=m|0,x=y|0,m=f|0,y=h|0,f=d|0,h=l|0,{h:d,l}=Ot(u|0,p|0,w|0,v|0),u=a|0,p=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let P=Yc(v,A,O);n=Jc(P,w,C,b),o=P|0}({h:n,l:o}=Ot(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Ot(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Ot(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:p}=Ot(this.Dh|0,this.Dl|0,u|0,p|0),{h:d,l}=Ot(this.Eh|0,this.El|0,d|0,l|0),{h:f,l:h}=Ot(this.Fh|0,this.Fl|0,f|0,h|0),{h:m,l:y}=Ot(this.Gh|0,this.Gl|0,m|0,y|0),{h:_,l:x}=Ot(this.Hh|0,this.Hl|0,_|0,x|0),this.set(n,o,s,i,a,c,u,p,d,l,f,h,m,y,_,x)}roundClean(){Br(cr,lr)}destroy(){Br(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Ce=Zo(()=>new Qo),rl=Zo(()=>new zi),nl=Zo(()=>new Yi);var es="__principal__",kp=2,ol=4,Lp="aaaaa-aa",k=class e{static anonymous(){return new this(new Uint8Array([ol]))}static managementCanister(){return this.fromText(Lp)}static selfAuthenticating(t){let r=rl(t);return new this(new Uint8Array([...r,kp]))}static from(t){if(typeof t=="string")return e.fromText(t);if(Object.getPrototypeOf(t)===Uint8Array.prototype)return new e(t);if(e.isPrincipal(t))return new e(t._arr);throw new Error(`Impossible to convert ${JSON.stringify(t)} to Principal.`)}static fromHex(t){return new this(Ne(t))}static fromText(t){let r=t;if(t.includes(es)){let i=JSON.parse(t);es in i&&(r=i[es])}let n=r.toLowerCase().replace(/-/g,""),o=qc(n);o=o.slice(4,o.length);let s=new this(o);if(s.toText()!==r)throw new Error(`Principal "${s.toText()}" does not have a valid checksum (original value "${r}" may not be a valid Principal ID).`);return s}static fromUint8Array(t){return new this(t)}static isPrincipal(t){return t instanceof e||typeof t=="object"&&t!==null&&"_isPrincipal"in t&&t._isPrincipal===!0&&"_arr"in t&&t._arr instanceof Uint8Array}constructor(t){this._arr=t,this._isPrincipal=!0}isAnonymous(){return this._arr.byteLength===1&&this._arr[0]===ol}toUint8Array(){return this._arr}toHex(){return K(this._arr).toUpperCase()}toText(){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,Mc(this._arr));let n=new Uint8Array(t),o=new Uint8Array([...n,...this._arr]),i=Lc(o).match(/.{1,5}/g);if(!i)throw new Error;return i.join("-")}toString(){return this.toText()}toJSON(){return{[es]:this.toText()}}compareTo(t){for(let r=0;r<Math.min(this._arr.length,t._arr.length);r++){if(this._arr[r]<t._arr[r])return"lt";if(this._arr[r]>t._arr[r])return"gt"}return this._arr.length<t._arr.length?"lt":this._arr.length>t._arr.length?"gt":"eq"}ltEq(t){let r=this.compareTo(t);return r=="lt"||r=="eq"}gtEq(t){let r=this.compareTo(t);return r=="gt"||r=="eq"}};var Ut;(function(e){e.Trust="Trust",e.Protocol="Protocol",e.Reject="Reject",e.Transport="Transport",e.External="External",e.Limit="Limit",e.Input="Input",e.Unknown="Unknown"})(Ut||(Ut={}));var $=class{constructor(t=!1){this.isCertified=t}toString(){let t=this.toErrorMessage();return this.requestContext&&(t+=`
2
2
  Request context:
3
- Request ID (hex): ${this.requestContext.requestId?M(this.requestContext.requestId):"undefined"}
4
- Sender pubkey (hex): ${M(this.requestContext.senderPubKey)}
5
- Sender signature (hex): ${M(this.requestContext.senderSignature)}
3
+ Request ID (hex): ${this.requestContext.requestId?K(this.requestContext.requestId):"undefined"}
4
+ Sender pubkey (hex): ${K(this.requestContext.senderPubKey)}
5
+ Sender signature (hex): ${K(this.requestContext.senderSignature)}
6
6
  Ingress expiry: ${this.requestContext.ingressExpiry.toString()}`),this.callContext&&(t+=`
7
7
  Call context:
8
8
  Canister ID: ${this.callContext.canisterId.toText()}
9
9
  Method name: ${this.callContext.methodName}
10
- HTTP details: ${JSON.stringify(this.callContext.httpDetails,null,2)}`),t}},nt=class e extends Error{get code(){return this.cause.code}set code(t){this.cause.code=t}get kind(){return this.cause.kind}set kind(t){this.cause.kind=t}get isCertified(){return this.code.isCertified}constructor(t,r){super(t.toString()),this.name="AgentError",this.cause={code:t,kind:r},Object.setPrototypeOf(this,e.prototype)}hasCode(t){return this.code instanceof t}toString(){return`${this.name} (${this.kind}): ${this.message}`}},At=class extends nt{static fromCode(t){return new this(t)}},Pe=class e extends At{constructor(t){super(t,It.Trust),this.name="TrustError",Object.setPrototypeOf(this,e.prototype)}},te=class e extends At{constructor(t){super(t,It.Protocol),this.name="ProtocolError",Object.setPrototypeOf(this,e.prototype)}},Jt=class e extends At{constructor(t){super(t,It.Reject),this.name="RejectError",Object.setPrototypeOf(this,e.prototype)}},In=class e extends At{constructor(t){super(t,It.Transport),this.name="TransportError",Object.setPrototypeOf(this,e.prototype)}},we=class e extends At{constructor(t){super(t,It.External),this.name="ExternalError",Object.setPrototypeOf(this,e.prototype)}};var W=class e extends At{constructor(t){super(t,It.Input),this.name="InputError",Object.setPrototypeOf(this,e.prototype)}},he=class e extends At{constructor(t){super(t,It.Unknown),this.name="UnknownError",Object.setPrototypeOf(this,e.prototype)}},Zt=class e extends H{constructor(t,r){super(),this.reason=t,this.error=r,this.name="CertificateVerificationErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=this.reason;return this.error&&(t+=`: ${Vn(this.error)}`),`Certificate verification error: "${t}"`}},yr=class e extends H{constructor(t,r,n,o,s){super(),this.maxAgeInMinutes=t,this.certificateTime=r,this.currentTime=n,this.timeDiffMsecs=o,this.ageType=s,this.name="CertificateTimeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Certificate is signed more than ${this.maxAgeInMinutes} minutes in the ${this.ageType}. Certificate time: ${this.certificateTime.toISOString()} Current time: ${this.currentTime.toISOString()} Clock drift: ${this.timeDiffMsecs}ms`}},Ao=class e extends H{constructor(){super(),this.name="CertificateHasTooManyDelegationsErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Certificate has too many delegations"}},Hr=class e extends H{constructor(t,r){super(),this.canisterId=t,this.subnetId=r,this.name="CertificateNotAuthorizedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The certificate contains a delegation that does not include the canister ${this.canisterId.toText()} in the canister_ranges field. Subnet ID: ${this.subnetId.toText()}`}},St=class e extends H{constructor(t,r){super(),this.message=t,this.lookupStatus=r,this.name="LookupErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`${this.message}. Lookup status: ${this.lookupStatus}`}},Gr=class e extends H{constructor(t){super(),this.message=t,this.name="MalformedLookupFoundValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},So=class e extends H{constructor(t){super(),this.message=t,this.name="MissingLookupValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},zr=class e extends H{constructor(t,r){super(),this.expectedLength=t,this.actualLength=r,this.name="DerKeyLengthMismatchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`BLS DER-encoded public key must be ${this.expectedLength} bytes long, but is ${this.actualLength} bytes long`}},Fo=class e extends H{constructor(t,r){super(),this.expectedPrefix=t,this.actualPrefix=r,this.name="DerPrefixMismatchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`BLS DER-encoded public key is invalid. Expected the following prefix: ${M(this.expectedPrefix)}, but got ${M(this.actualPrefix)}`}},Po=class e extends H{constructor(t,r){super(),this.expectedLength=t,this.actualLength=r,this.name="DerDecodeLengthMismatchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`DER payload mismatch: Expected length ${this.expectedLength}, actual length: ${this.actualLength}`}},ot=class e extends H{constructor(t){super(),this.error=t,this.name="DerDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}},An=class e extends H{constructor(t){super(),this.error=t,this.name="DerEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}},Bo=class e extends H{constructor(t,r){super(),this.error=t,this.input=r,this.name="CborDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${Vn(this.error)}, input: ${M(this.input)}`}},Co=class e extends H{constructor(t,r){super(),this.error=t,this.value=r,this.name="CborEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${Vn(this.error)}, input: ${this.value}`}};var gr=class e extends H{constructor(t,r,n){super(),this.message=t,this.requestId=r,this.status=n,this.name="TimeoutWaitingForResponseErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=`${this.message}
11
- `;return this.requestId&&(t+=` Request ID: ${M(this.requestId)}
10
+ HTTP details: ${JSON.stringify(this.callContext.httpDetails,null,2)}`),t}},dt=class e extends Error{get code(){return this.cause.code}set code(t){this.cause.code=t}get kind(){return this.cause.kind}set kind(t){this.cause.kind=t}get isCertified(){return this.code.isCertified}constructor(t,r){super(t.toString()),this.name="AgentError",this.cause={code:t,kind:r},Object.setPrototypeOf(this,e.prototype)}hasCode(t){return this.code instanceof t}toString(){return`${this.name} (${this.kind}): ${this.message}`}},kt=class extends dt{static fromCode(t){return new this(t)}},Ue=class e extends kt{constructor(t){super(t,Ut.Trust),this.name="TrustError",Object.setPrototypeOf(this,e.prototype)}},re=class e extends kt{constructor(t){super(t,Ut.Protocol),this.name="ProtocolError",Object.setPrototypeOf(this,e.prototype)}},ur=class e extends kt{constructor(t){super(t,Ut.Reject),this.name="RejectError",Object.setPrototypeOf(this,e.prototype)}},Zn=class e extends kt{constructor(t){super(t,Ut.Transport),this.name="TransportError",Object.setPrototypeOf(this,e.prototype)}},Ee=class e extends kt{constructor(t){super(t,Ut.External),this.name="ExternalError",Object.setPrototypeOf(this,e.prototype)}};var z=class e extends kt{constructor(t){super(t,Ut.Input),this.name="InputError",Object.setPrototypeOf(this,e.prototype)}},ge=class e extends kt{constructor(t){super(t,Ut.Unknown),this.name="UnknownError",Object.setPrototypeOf(this,e.prototype)}},dr=class e extends ${constructor(t,r){super(),this.reason=t,this.error=r,this.name="CertificateVerificationErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=this.reason;return this.error&&(t+=`: ${oo(this.error)}`),`Certificate verification error: "${t}"`}},Ur=class e extends ${constructor(t,r,n,o,s){super(),this.maxAgeInMinutes=t,this.certificateTime=r,this.currentTime=n,this.timeDiffMsecs=o,this.ageType=s,this.name="CertificateTimeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Certificate is signed more than ${this.maxAgeInMinutes} minutes in the ${this.ageType}. Certificate time: ${this.certificateTime.toISOString()} Current time: ${this.currentTime.toISOString()} Clock drift: ${this.timeDiffMsecs}ms`}},ts=class e extends ${constructor(){super(),this.name="CertificateHasTooManyDelegationsErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Certificate has too many delegations"}},pn=class e extends ${constructor(t,r){super(),this.canisterId=t,this.subnetId=r,this.name="CertificateNotAuthorizedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The certificate contains a delegation that does not include the canister ${this.canisterId.toText()} in the canister_ranges field. Subnet ID: ${this.subnetId.toText()}`}},Lt=class e extends ${constructor(t,r){super(),this.message=t,this.lookupStatus=r,this.name="LookupErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`${this.message}. Lookup status: ${this.lookupStatus}`}},fn=class e extends ${constructor(t){super(),this.message=t,this.name="MalformedLookupFoundValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},rs=class e extends ${constructor(t){super(),this.message=t,this.name="MissingLookupValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},hn=class e extends ${constructor(t,r){super(),this.expectedLength=t,this.actualLength=r,this.name="DerKeyLengthMismatchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`BLS DER-encoded public key must be ${this.expectedLength} bytes long, but is ${this.actualLength} bytes long`}},ns=class e extends ${constructor(t,r){super(),this.expectedPrefix=t,this.actualPrefix=r,this.name="DerPrefixMismatchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`BLS DER-encoded public key is invalid. Expected the following prefix: ${K(this.expectedPrefix)}, but got ${K(this.actualPrefix)}`}},os=class e extends ${constructor(t,r){super(),this.expectedLength=t,this.actualLength=r,this.name="DerDecodeLengthMismatchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`DER payload mismatch: Expected length ${this.expectedLength}, actual length: ${this.actualLength}`}},pt=class e extends ${constructor(t){super(),this.error=t,this.name="DerDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}},Xn=class e extends ${constructor(t){super(),this.error=t,this.name="DerEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}},ss=class e extends ${constructor(t,r){super(),this.error=t,this.input=r,this.name="CborDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${oo(this.error)}, input: ${K(this.input)}`}},is=class e extends ${constructor(t,r){super(),this.error=t,this.value=r,this.name="CborEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${oo(this.error)}, input: ${this.value}`}};var kr=class e extends ${constructor(t,r,n){super(),this.message=t,this.requestId=r,this.status=n,this.name="TimeoutWaitingForResponseErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=`${this.message}
11
+ `;return this.requestId&&(t+=` Request ID: ${K(this.requestId)}
12
12
  `),this.status&&(t+=` Request status: ${this.status}
13
- `),t}},Vo=class e extends H{constructor(t,r,n){super(),this.maxIngressExpiryInMinutes=t,this.requestId=r,this.retryTimes=n,this.name="CertificateOutdatedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=`Certificate is stale (over ${this.maxIngressExpiryInMinutes} minutes). Is the computer's clock synchronized?
14
- Request ID: ${M(this.requestId)}
15
- `;return this.retryTimes!==void 0&&(t+=` Retried ${this.retryTimes} times.`),t}},Wr=class e extends H{constructor(t,r,n,o){super(!0),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.name="CertifiedRejectErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
16
- Request ID: ${M(this.requestId)}
13
+ `),t}},as=class e extends ${constructor(t,r,n){super(),this.maxIngressExpiryInMinutes=t,this.requestId=r,this.retryTimes=n,this.name="CertificateOutdatedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=`Certificate is stale (over ${this.maxIngressExpiryInMinutes} minutes). Is the computer's clock synchronized?
14
+ Request ID: ${K(this.requestId)}
15
+ `;return this.retryTimes!==void 0&&(t+=` Retried ${this.retryTimes} times.`),t}},mn=class e extends ${constructor(t,r,n,o){super(!0),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.name="CertifiedRejectErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
16
+ Request ID: ${K(this.requestId)}
17
17
  Reject code: ${this.rejectCode}
18
18
  Reject text: ${this.rejectMessage}
19
19
  Error code: ${this.rejectErrorCode}
20
- `}},Do=class e extends H{constructor(t,r,n,o,s){super(),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.signatures=s,this.name="UncertifiedRejectErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
21
- Request ID: ${M(this.requestId)}
20
+ `}},cs=class e extends ${constructor(t,r,n,o,s){super(),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.signatures=s,this.name="UncertifiedRejectErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
21
+ Request ID: ${K(this.requestId)}
22
22
  Reject code: ${this.rejectCode}
23
23
  Reject text: ${this.rejectMessage}
24
24
  Error code: ${this.rejectErrorCode}
25
- `}},Uo=class e extends H{constructor(t,r,n,o){super(),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.name="UncertifiedRejectUpdateErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
26
- Request ID: ${M(this.requestId)}
25
+ `}},ls=class e extends ${constructor(t,r,n,o){super(),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.name="UncertifiedRejectUpdateErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
26
+ Request ID: ${K(this.requestId)}
27
27
  Reject code: ${this.rejectCode}
28
28
  Reject text: ${this.rejectMessage}
29
29
  Error code: ${this.rejectErrorCode}
30
- `}},ko=class e extends H{constructor(t){super(),this.requestId=t,this.name="RequestStatusDoneNoReplyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Call was marked as done but we never saw the reply:
31
- Request ID: ${M(this.requestId)}
32
- `}},mt=class e extends H{constructor(t){super(),this.shouldFetchRootKey=t,this.name="MissingRootKeyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.shouldFetchRootKey===void 0?"Agent is missing root key":`Agent is missing root key and the shouldFetchRootKey value is set to ${this.shouldFetchRootKey}. The root key should only be unknown if you are in local development. Otherwise you should avoid fetching and use the default IC Root Key or the known root key of your environment.`}},Lo=class e extends H{constructor(t){super(),this.value=t,this.name="HashValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Attempt to hash a value of unsupported type: ${this.value}`}},Yr=class e extends H{constructor(t){super(),this.error=t,this.name="HttpDefaultFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.error}},Xt=class e extends H{constructor(){super(),this.name="IdentityInvalidErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"This identity has expired due this application's security policy. Please refresh your authentication."}},xr=class e extends H{constructor(t,r){super(),this.message=t,this.providedIngressExpiryInMinutes=r,this.name="IngressExpiryInvalidErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`${this.message}. Provided ingress expiry time is ${this.providedIngressExpiryInMinutes} minutes.`}},qo=class e extends H{constructor(){super(),this.name="CreateHttpAgentErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Failed to create agent from provided agent"}},Mo=class e extends H{constructor(t){super(),this.error=t,this.name="MalformedSignatureErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}},jo=class e extends H{constructor(){super(),this.name="MissingSignatureErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Query response did not contain any node signatures"}},Ko=class e extends H{constructor(){super(),this.name="MalformedPublicKeyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Read state response contained a malformed public key"}},$o=class e extends H{constructor(t){super(),this.nodeId=t,this.name="QuerySignatureVerificationFailedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}},Be=class e extends H{constructor(t){super(),this.error=t,this.name="UnexpectedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Unexpected error: ${Vn(this.error)}`}},Qt=class e extends H{constructor(t){super(),this.error=t,this.name="HashTreeDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}},Sn=class e extends H{constructor(t,r,n,o){super(),this.status=t,this.statusText=r,this.headers=n,this.bodyText=o,this.name="HttpErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=`HTTP request failed:
30
+ `}},us=class e extends ${constructor(t){super(),this.requestId=t,this.name="RequestStatusDoneNoReplyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Call was marked as done but we never saw the reply:
31
+ Request ID: ${K(this.requestId)}
32
+ `}},Nt=class e extends ${constructor(t){super(),this.shouldFetchRootKey=t,this.name="MissingRootKeyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.shouldFetchRootKey===void 0?"Agent is missing root key":`Agent is missing root key and the shouldFetchRootKey value is set to ${this.shouldFetchRootKey}. The root key should only be unknown if you are in local development. Otherwise you should avoid fetching and use the default IC Root Key or the known root key of your environment.`}},ds=class e extends ${constructor(t){super(),this.value=t,this.name="HashValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Attempt to hash a value of unsupported type: ${this.value}`}},_n=class e extends ${constructor(t){super(),this.error=t,this.name="HttpDefaultFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.error}},pr=class e extends ${constructor(){super(),this.name="IdentityInvalidErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"This identity has expired due this application's security policy. Please refresh your authentication."}},Lr=class e extends ${constructor(t,r){super(),this.message=t,this.providedIngressExpiryInMinutes=r,this.name="IngressExpiryInvalidErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`${this.message}. Provided ingress expiry time is ${this.providedIngressExpiryInMinutes} minutes.`}},ps=class e extends ${constructor(){super(),this.name="CreateHttpAgentErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Failed to create agent from provided agent"}},fs=class e extends ${constructor(t){super(),this.error=t,this.name="MalformedSignatureErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}},hs=class e extends ${constructor(){super(),this.name="MissingSignatureErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Query response did not contain any node signatures"}},ms=class e extends ${constructor(){super(),this.name="MalformedPublicKeyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Read state response contained a malformed public key"}},_s=class e extends ${constructor(t){super(),this.nodeId=t,this.name="QuerySignatureVerificationFailedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}},ke=class e extends ${constructor(t){super(),this.error=t,this.name="UnexpectedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Unexpected error: ${oo(this.error)}`}},fr=class e extends ${constructor(t){super(),this.error=t,this.name="HashTreeDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}},Qn=class e extends ${constructor(t,r,n,o){super(),this.status=t,this.statusText=r,this.headers=n,this.bodyText=o,this.name="HttpErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=`HTTP request failed:
33
33
  Status: ${this.status} (${this.statusText})
34
34
  Headers: ${JSON.stringify(this.headers)}
35
35
  `;return this.bodyText&&(t+=` Body: ${this.bodyText}
36
- `),t}},Fn=class e extends H{constructor(){super(),this.name="HttpV3ApiNotSupportedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"HTTP request failed: v3 API is not supported"}},Pn=class e extends H{constructor(t){super(),this.error=t,this.name="HttpFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to fetch HTTP request: ${Vn(this.error)}`}},Bn=class e extends H{constructor(t){super(),this.receivedCanisterId=t,this.name="MissingCanisterIdErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Canister ID is required, but received ${typeof this.receivedCanisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`}},Ho=class e extends H{constructor(t){super(),this.request=t,this.name="InvalidReadStateRequestErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Invalid read state request: ${this.request}`}},Cn=class e extends H{constructor(t){super(),this.error=t,this.name="ExpiryJsonDeserializeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to deserialize expiry: ${this.error}`}};function Vn(e){if(e instanceof Error)return e.stack??e.message;try{return JSON.stringify(e)}catch{return String(e)}}var er=new Error("unreachable");var Nr={};Bd(Nr,{Bool:()=>Ic,BoolClass:()=>Jo,ConstructType:()=>gt,Empty:()=>Rc,EmptyClass:()=>Un,FixedIntClass:()=>Bt,FixedNatClass:()=>yt,Float32:()=>Bc,Float64:()=>Cc,FloatClass:()=>qn,Func:()=>Jc,FuncClass:()=>Tr,Int:()=>Fc,Int16:()=>Dc,Int32:()=>Uc,Int64:()=>kc,Int8:()=>Vc,IntClass:()=>kn,Nat:()=>Pc,Nat16:()=>qc,Nat32:()=>Mc,Nat64:()=>jc,Nat8:()=>Lc,NatClass:()=>Ln,Null:()=>Ac,NullClass:()=>br,Opt:()=>Gc,OptClass:()=>nr,PrimitiveType:()=>Me,Principal:()=>Kc,PrincipalClass:()=>Qo,Rec:()=>Yc,RecClass:()=>We,Record:()=>zc,RecordClass:()=>wr,Reserved:()=>vc,ReservedClass:()=>xt,Service:()=>Zc,ServiceClass:()=>Qr,Text:()=>Sc,TextClass:()=>Zo,Tuple:()=>$c,TupleClass:()=>Xo,Type:()=>Jr,Unknown:()=>zd,UnknownClass:()=>Yo,Variant:()=>Wc,VariantClass:()=>Xr,Vec:()=>Hc,VecClass:()=>Zr,Visitor:()=>Ti,decode:()=>Gd,encode:()=>Hd,resetSubtypeCache:()=>Ni,subtype:()=>Ei});function Y(...e){let t=new Uint8Array(e.reduce((n,o)=>n+o.byteLength,0)),r=0;for(let n of e)t.set(n,r),r+=n.byteLength;return t}var st=class{save(){return this._view}restore(t){if(!(t instanceof Uint8Array))throw new Error("Checkpoint must be a Uint8Array");this._view=t}constructor(t,r=t?.byteLength||0){if(t&&!(t instanceof Uint8Array))try{t=_t(t)}catch{throw new Error("Buffer must be a Uint8Array")}if(r<0||!Number.isInteger(r))throw new Error("Length must be a non-negative integer");if(t&&r>t.byteLength)throw new Error("Length cannot exceed buffer length");this._buffer=t||new Uint8Array(0),this._view=new Uint8Array(this._buffer.buffer,0,r)}get buffer(){return this._view.slice()}get byteLength(){return this._view.byteLength}read(t){let r=this._view.subarray(0,t);return this._view=this._view.subarray(t),r.slice()}readUint8(){if(this._view.byteLength===0)return;let t=this._view[0];return this._view=this._view.subarray(1),t}write(t){if(!(t instanceof Uint8Array))throw new Error("Buffer must be a Uint8Array");let r=this._view.byteLength;this._view.byteOffset+this._view.byteLength+t.byteLength>=this._buffer.byteLength?this.alloc(t.byteLength):this._view=new Uint8Array(this._buffer.buffer,this._view.byteOffset,this._view.byteLength+t.byteLength),this._view.set(t,r)}get end(){return this._view.byteLength===0}alloc(t){if(t<=0||!Number.isInteger(t))throw new Error("Amount must be a positive integer");let r=new Uint8Array((this._buffer.byteLength+t)*1.2|0),n=new Uint8Array(r.buffer,0,this._view.byteLength+t);n.set(this._view),this._buffer=r,this._view=n}};function _t(e){if(!e)throw new Error("Input cannot be null or undefined");return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):"buffer"in e?_t(e.buffer):new Uint8Array(e)}function _i(e,t){if(e.byteLength!==t.byteLength)return e.byteLength-t.byteLength;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return e[r]-t[r];return 0}function bc(e,t){return _i(e,t)===0}function wc(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(e.buffer,e.byteOffset,e.byteLength)}function $d(e){let r=new TextEncoder().encode(e),n=0;for(let o of r)n=(n*223+o)%2**32;return n}function Ce(e){if(/^_\d+_$/.test(e)||/^_0x[0-9a-fA-F]+_$/.test(e)){let t=+e.slice(1,-1);if(Number.isSafeInteger(t)&&t>=0&&t<2**32)return t}return $d(e)}function yi(e){let t=BigInt(e);if(e<=0)throw new RangeError("Input must be positive");return t.toString(2).length-1}function Go(e){let t=BigInt(e);if(e<0)throw new RangeError("Input must be non-negative");return BigInt(1)<<t}function Tc(){throw new Error("unexpected end of buffer")}function rr(e,t){return e.byteLength<t&&Tc(),e.read(t)}function tr(e){let t=e.readUint8();return t===void 0&&Tc(),t}function re(e){if(typeof e=="number"&&(e=BigInt(e)),e<BigInt(0))throw new Error("Cannot leb encode negative values.");let t=(e===BigInt(0)?0:yi(e))+1,r=new st(new Uint8Array(t),0);for(;;){let n=Number(e&BigInt(127));if(e/=BigInt(128),e===BigInt(0)){r.write(new Uint8Array([n]));break}else r.write(new Uint8Array([n|128]))}return r.buffer}function pe(e){let t=BigInt(1),r=BigInt(0),n;do n=tr(e),r+=BigInt(n&127).valueOf()*t,t*=BigInt(128);while(n>=128);return r}function fe(e){typeof e=="number"&&(e=BigInt(e));let t=e<BigInt(0);t&&(e=-e-BigInt(1));let r=(e===BigInt(0)?0:yi(e))+1,n=new st(new Uint8Array(r),0);for(;;){let s=o(e);if(e/=BigInt(128),t&&e===BigInt(0)&&(s&64)!==0||!t&&e===BigInt(0)&&(s&64)===0){n.write(new Uint8Array([s]));break}else n.write(new Uint8Array([s|128]))}function o(s){let i=s%BigInt(128);return Number(t?BigInt(128)-i-BigInt(1):i)}return n.buffer}function Ft(e){let t=new Uint8Array(e.buffer),r=0;for(;r<t.byteLength;r++)if(t[r]<128){if((t[r]&64)===0)return pe(e);break}let n=new Uint8Array(rr(e,r+1)),o=BigInt(0);for(let s=n.byteLength-1;s>=0;s--)o=o*BigInt(128)+BigInt(128-(n[s]&127)-1);return-o-BigInt(1)}function Nc(e,t){if(BigInt(e)<BigInt(0))throw new Error("Cannot write negative values.");return gi(e,t)}function gi(e,t){e=BigInt(e);let r=new st(new Uint8Array(Math.min(1,t)),0),n=0,o=BigInt(256),s=BigInt(0),i=Number(e%o);for(r.write(new Uint8Array([i]));++n<t;)e<0&&s===BigInt(0)&&i!==0&&(s=BigInt(1)),i=Number((e/o-s)%BigInt(256)),r.write(new Uint8Array([i])),o*=BigInt(256);return r.buffer}function xi(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=BigInt(tr(e)),n=BigInt(1),o=0;for(;++o<t;){n*=BigInt(256);let s=BigInt(tr(e));r=r+n*s}return r}function Oc(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=xi(e,t),n=BigInt(2)**(BigInt(8)*BigInt(t-1)+BigInt(7));return r>=n&&(r-=n*BigInt(2)),r}var Z;(function(e){e[e.Null=-1]="Null",e[e.Bool=-2]="Bool",e[e.Nat=-3]="Nat",e[e.Int=-4]="Int",e[e.Float32=-13]="Float32",e[e.Float64=-14]="Float64",e[e.Text=-15]="Text",e[e.Reserved=-16]="Reserved",e[e.Empty=-17]="Empty",e[e.Opt=-18]="Opt",e[e.Vector=-19]="Vector",e[e.Record=-20]="Record",e[e.Variant=-21]="Variant",e[e.Func=-22]="Func",e[e.Service=-23]="Service",e[e.Principal=-24]="Principal"})(Z||(Z={}));var zo="DIDL",Ec=400;function Dn(e,t,r){return e.map((n,o)=>r(n,t[o]))}var wi=class{constructor(){this._typs=[],this._idx=new Map,this._idxRefCount=new Map}has(t){return this._idx.has(t.name)}add(t,r){let n=this._typs.length;this._idx.set(t.name,n),this._idxRefCount.set(n,1),this._typs.push(r)}merge(t,r){let n=this._idx.get(t.name),o=this._idx.get(r);if(n===void 0)throw new Error("Missing type index for "+t);if(o===void 0)throw new Error("Missing type index for "+r);this._typs[n]=this._typs[o];let s=this._getIdxRefCount(o);this._idxRefCount.set(o,s-1),this._idx.delete(r),this._compactFromEnd()}_getIdxRefCount(t){return this._idxRefCount.get(t)||0}_compactFromEnd(){for(;this._typs.length>0;){let t=this._typs.length-1;if(this._getIdxRefCount(t)>0)break;this._typs.pop(),this._idxRefCount.delete(t)}}encode(){let t=re(this._typs.length),r=Y(...this._typs);return Y(t,r)}indexOf(t){if(!this._idx.has(t))throw new Error("Missing type index for "+t);return fe(this._idx.get(t)||0)}},Ti=class{visitType(t,r){throw new Error("Not implemented")}visitPrimitive(t,r){return this.visitType(t,r)}visitEmpty(t,r){return this.visitPrimitive(t,r)}visitBool(t,r){return this.visitPrimitive(t,r)}visitNull(t,r){return this.visitPrimitive(t,r)}visitReserved(t,r){return this.visitPrimitive(t,r)}visitText(t,r){return this.visitPrimitive(t,r)}visitNumber(t,r){return this.visitPrimitive(t,r)}visitInt(t,r){return this.visitNumber(t,r)}visitNat(t,r){return this.visitNumber(t,r)}visitFloat(t,r){return this.visitPrimitive(t,r)}visitFixedInt(t,r){return this.visitNumber(t,r)}visitFixedNat(t,r){return this.visitNumber(t,r)}visitPrincipal(t,r){return this.visitPrimitive(t,r)}visitConstruct(t,r){return this.visitType(t,r)}visitVec(t,r,n){return this.visitConstruct(t,n)}visitOpt(t,r,n){return this.visitConstruct(t,n)}visitRecord(t,r,n){return this.visitConstruct(t,n)}visitTuple(t,r,n){let o=r.map((s,i)=>[`_${i}_`,s]);return this.visitRecord(t,o,n)}visitVariant(t,r,n){return this.visitConstruct(t,n)}visitRec(t,r,n){return this.visitConstruct(r,n)}visitFunc(t,r){return this.visitConstruct(t,r)}visitService(t,r){return this.visitConstruct(t,r)}},$;(function(e){e.EmptyClass="__IDL_EmptyClass__",e.UnknownClass="__IDL_UnknownClass__",e.BoolClass="__IDL_BoolClass__",e.NullClass="__IDL_NullClass__",e.ReservedClass="__IDL_ReservedClass__",e.TextClass="__IDL_TextClass__",e.IntClass="__IDL_IntClass__",e.NatClass="__IDL_NatClass__",e.FloatClass="__IDL_FloatClass__",e.FixedIntClass="__IDL_FixedIntClass__",e.FixedNatClass="__IDL_FixedNatClass__",e.VecClass="__IDL_VecClass__",e.OptClass="__IDL_OptClass__",e.RecordClass="__IDL_RecordClass__",e.TupleClass="__IDL_TupleClass__",e.VariantClass="__IDL_VariantClass__",e.RecClass="__IDL_RecClass__",e.PrincipalClass="__IDL_PrincipalClass__",e.FuncClass="__IDL_FuncClass__",e.ServiceClass="__IDL_ServiceClass__"})($||($={}));var Jr=class{display(){return this.name}valueToString(t){return de(t)}buildTypeTable(t){t.has(this)||this._buildTypeTableImpl(t)}},Me=class extends Jr{checkType(t){if(this.name!==t.name)throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`);return t}_buildTypeTableImpl(t){}},gt=class extends Jr{checkType(t){if(t instanceof We){let r=t.getType();if(typeof r>"u")throw new Error("type mismatch with uninitialized type");return r}throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`)}encodeType(t){return t.indexOf(this.name)}},Un=class extends Me{get typeName(){return $.EmptyClass}static[Symbol.hasInstance](t){return t.typeName===$.EmptyClass}accept(t,r){return t.visitEmpty(this,r)}covariant(t){throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(){throw new Error("Empty cannot appear as a function argument")}valueToString(){throw new Error("Empty cannot appear as a value")}encodeType(){return fe(Z.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}},Yo=class extends Jr{get typeName(){return $.UnknownClass}static[Symbol.hasInstance](t){return t.typeName===$.UnknownClass}checkType(t){throw new Error("Method not implemented for unknown.")}accept(t,r){throw t.visitType(this,r)}covariant(t){throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(){throw new Error("Unknown cannot appear as a function argument")}valueToString(){throw new Error("Unknown cannot appear as a value")}encodeType(){throw new Error("Unknown cannot be serialized")}decodeValue(t,r){let n=r.decodeValue(t,r);Object(n)!==n&&(n=Object(n));let o;return r instanceof We?o=()=>r.getType():o=()=>r,Object.defineProperty(n,"type",{value:o,writable:!0,enumerable:!1,configurable:!0}),n}_buildTypeTableImpl(){throw new Error("Unknown cannot be serialized")}get name(){return"Unknown"}},Jo=class extends Me{get typeName(){return $.BoolClass}static[Symbol.hasInstance](t){return t.typeName===$.BoolClass}accept(t,r){return t.visitBool(this,r)}covariant(t){if(typeof t=="boolean")return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){return new Uint8Array([t?1:0])}encodeType(){return fe(Z.Bool)}decodeValue(t,r){switch(this.checkType(r),tr(t)){case 0:return!1;case 1:return!0;default:throw new Error("Boolean value out of range")}}get name(){return"bool"}},br=class extends Me{get typeName(){return $.NullClass}static[Symbol.hasInstance](t){return t.typeName===$.NullClass}accept(t,r){return t.visitNull(this,r)}covariant(t){if(t===null)return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(){return new Uint8Array(0)}encodeType(){return fe(Z.Null)}decodeValue(t,r){return this.checkType(r),null}get name(){return"null"}},xt=class extends Me{get typeName(){return $.ReservedClass}static[Symbol.hasInstance](t){return t.typeName===$.ReservedClass}accept(t,r){return t.visitReserved(this,r)}covariant(t){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return fe(Z.Reserved)}decodeValue(t,r){return r.name!==this.name&&r.decodeValue(t,r),null}get name(){return"reserved"}},Zo=class extends Me{get typeName(){return $.TextClass}static[Symbol.hasInstance](t){return t.typeName===$.TextClass}accept(t,r){return t.visitText(this,r)}covariant(t){if(typeof t=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){let r=new TextEncoder().encode(t),n=re(r.byteLength);return Y(n,r)}encodeType(){return fe(Z.Text)}decodeValue(t,r){this.checkType(r);let n=pe(t),o=rr(t,Number(n));return new TextDecoder("utf8",{fatal:!0}).decode(o)}get name(){return"text"}valueToString(t){return'"'+t+'"'}},kn=class extends Me{get typeName(){return $.IntClass}static[Symbol.hasInstance](t){return t.typeName===$.IntClass}accept(t,r){return t.visitInt(this,r)}covariant(t){if(typeof t=="bigint"||Number.isInteger(t))return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){return fe(t)}encodeType(){return fe(Z.Int)}decodeValue(t,r){return this.checkType(r),Ft(t)}get name(){return"int"}valueToString(t){return t.toString()}},Ln=class extends Me{get typeName(){return $.NatClass}static[Symbol.hasInstance](t){return t.typeName===$.NatClass}accept(t,r){return t.visitNat(this,r)}covariant(t){if(typeof t=="bigint"&&t>=BigInt(0)||Number.isInteger(t)&&t>=0)return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){return re(t)}encodeType(){return fe(Z.Nat)}decodeValue(t,r){return this.checkType(r),pe(t)}get name(){return"nat"}valueToString(t){return t.toString()}},qn=class extends Me{get typeName(){return $.FloatClass}static[Symbol.hasInstance](t){return t.typeName===$.FloatClass}constructor(t){if(super(),this._bits=t,t!==32&&t!==64)throw new Error("not a valid float type")}accept(t,r){return t.visitFloat(this,r)}covariant(t){if(typeof t=="number"||t instanceof Number)return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){let r=new ArrayBuffer(this._bits/8),n=new DataView(r);return this._bits===32?n.setFloat32(0,t,!0):n.setFloat64(0,t,!0),new Uint8Array(r)}encodeType(){let t=this._bits===32?Z.Float32:Z.Float64;return fe(t)}decodeValue(t,r){this.checkType(r);let n=rr(t,this._bits/8),o=wc(n);return this._bits===32?o.getFloat32(0,!0):o.getFloat64(0,!0)}get name(){return"float"+this._bits}valueToString(t){return t.toString()}},Bt=class extends Me{get typeName(){return $.FixedIntClass}static[Symbol.hasInstance](t){return t.typeName===$.FixedIntClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedInt(this,r)}covariant(t){let r=Go(this._bits-1)*BigInt(-1),n=Go(this._bits-1)-BigInt(1),o=!1;if(typeof t=="bigint")o=t>=r&&t<=n;else if(Number.isInteger(t)){let s=BigInt(t);o=s>=r&&s<=n}else o=!1;if(o)return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){return gi(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return fe(-9-t)}decodeValue(t,r){this.checkType(r);let n=Oc(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(t){return t.toString()}},yt=class extends Me{get typeName(){return $.FixedNatClass}static[Symbol.hasInstance](t){return t.typeName===$.FixedNatClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedNat(this,r)}covariant(t){let r=Go(this._bits),n=!1;if(typeof t=="bigint"&&t>=BigInt(0)?n=t<r:Number.isInteger(t)&&t>=0?n=BigInt(t)<r:n=!1,n)return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){return Nc(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return fe(-5-t)}decodeValue(t,r){this.checkType(r);let n=xi(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(t){return t.toString()}},Zr=class e extends gt{get typeName(){return $.VecClass}static[Symbol.hasInstance](t){return t.typeName===$.VecClass}constructor(t){super(),this._type=t,this._blobOptimization=!1,t instanceof yt&&t._bits===8&&(this._blobOptimization=!0)}accept(t,r){return t.visitVec(this,this._type,r)}covariant(t){let r=this._type instanceof yt?this._type._bits:this._type instanceof Bt?this._type._bits:0;if(ArrayBuffer.isView(t)&&r==t.BYTES_PER_ELEMENT*8||Array.isArray(t)&&t.every((n,o)=>{try{return this._type.covariant(n)}catch(s){throw new Error(`Invalid ${this.display()} argument:
36
+ `),t}},eo=class e extends ${constructor(){super(),this.name="HttpV3ApiNotSupportedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"HTTP request failed: v3 API is not supported"}},to=class e extends ${constructor(t){super(),this.error=t,this.name="HttpFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to fetch HTTP request: ${oo(this.error)}`}},ro=class e extends ${constructor(t){super(),this.receivedCanisterId=t,this.name="MissingCanisterIdErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Canister ID is required, but received ${typeof this.receivedCanisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`}},ys=class e extends ${constructor(t){super(),this.request=t,this.name="InvalidReadStateRequestErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Invalid read state request: ${this.request}`}},no=class e extends ${constructor(t){super(),this.error=t,this.name="ExpiryJsonDeserializeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to deserialize expiry: ${this.error}`}};function oo(e){if(e instanceof Error)return e.stack??e.message;try{return JSON.stringify(e)}catch{return String(e)}}var hr=new Error("unreachable");var Kr={};Ap(Kr,{Bool:()=>fl,BoolClass:()=>Ts,ConstructType:()=>vt,Empty:()=>dl,EmptyClass:()=>io,FixedIntClass:()=>jt,FixedNatClass:()=>Rt,Float32:()=>gl,Float64:()=>xl,FloatClass:()=>lo,Func:()=>Vl,FuncClass:()=>jr,Int:()=>_l,Int16:()=>wl,Int32:()=>Tl,Int64:()=>Ol,Int8:()=>bl,IntClass:()=>ao,Nat:()=>yl,Nat16:()=>El,Nat32:()=>Rl,Nat64:()=>vl,Nat8:()=>Nl,NatClass:()=>co,Null:()=>hl,NullClass:()=>qr,Opt:()=>Pl,OptClass:()=>yr,PrimitiveType:()=>Ge,Principal:()=>Il,PrincipalClass:()=>Es,Rec:()=>Bl,RecClass:()=>tt,Record:()=>Cl,RecordClass:()=>Mr,Reserved:()=>pl,ReservedClass:()=>It,Service:()=>Dl,ServiceClass:()=>bn,Text:()=>ml,TextClass:()=>Os,Tuple:()=>Al,TupleClass:()=>Ns,Type:()=>yn,Unknown:()=>Kp,UnknownClass:()=>ws,Variant:()=>Fl,VariantClass:()=>xn,Vec:()=>Sl,VecClass:()=>gn,Visitor:()=>ra,decode:()=>jp,encode:()=>Mp,resetSubtypeCache:()=>na,subtype:()=>sa});function Y(...e){let t=new Uint8Array(e.reduce((n,o)=>n+o.byteLength,0)),r=0;for(let n of e)t.set(n,r),r+=n.byteLength;return t}var ft=class{save(){return this._view}restore(t){if(!(t instanceof Uint8Array))throw new Error("Checkpoint must be a Uint8Array");this._view=t}constructor(t,r=t?.byteLength||0){if(t&&!(t instanceof Uint8Array))try{t=Et(t)}catch{throw new Error("Buffer must be a Uint8Array")}if(r<0||!Number.isInteger(r))throw new Error("Length must be a non-negative integer");if(t&&r>t.byteLength)throw new Error("Length cannot exceed buffer length");this._buffer=t||new Uint8Array(0),this._view=new Uint8Array(this._buffer.buffer,0,r)}get buffer(){return this._view.slice()}get byteLength(){return this._view.byteLength}read(t){let r=this._view.subarray(0,t);return this._view=this._view.subarray(t),r.slice()}readUint8(){if(this._view.byteLength===0)return;let t=this._view[0];return this._view=this._view.subarray(1),t}write(t){if(!(t instanceof Uint8Array))throw new Error("Buffer must be a Uint8Array");let r=this._view.byteLength;this._view.byteOffset+this._view.byteLength+t.byteLength>=this._buffer.byteLength?this.alloc(t.byteLength):this._view=new Uint8Array(this._buffer.buffer,this._view.byteOffset,this._view.byteLength+t.byteLength),this._view.set(t,r)}get end(){return this._view.byteLength===0}alloc(t){if(t<=0||!Number.isInteger(t))throw new Error("Amount must be a positive integer");let r=new Uint8Array((this._buffer.byteLength+t)*1.2|0),n=new Uint8Array(r.buffer,0,this._view.byteLength+t);n.set(this._view),this._buffer=r,this._view=n}};function Et(e){if(!e)throw new Error("Input cannot be null or undefined");return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):"buffer"in e?Et(e.buffer):new Uint8Array(e)}function Ji(e,t){if(e.byteLength!==t.byteLength)return e.byteLength-t.byteLength;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return e[r]-t[r];return 0}function sl(e,t){return Ji(e,t)===0}function il(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(e.buffer,e.byteOffset,e.byteLength)}function qp(e){let r=new TextEncoder().encode(e),n=0;for(let o of r)n=(n*223+o)%2**32;return n}function Le(e){if(/^_\d+_$/.test(e)||/^_0x[0-9a-fA-F]+_$/.test(e)){let t=+e.slice(1,-1);if(Number.isSafeInteger(t)&&t>=0&&t<2**32)return t}return qp(e)}function Zi(e){let t=BigInt(e);if(e<=0)throw new RangeError("Input must be positive");return t.toString(2).length-1}function gs(e){let t=BigInt(e);if(e<0)throw new RangeError("Input must be non-negative");return BigInt(1)<<t}function al(){throw new Error("unexpected end of buffer")}function _r(e,t){return e.byteLength<t&&al(),e.read(t)}function mr(e){let t=e.readUint8();return t===void 0&&al(),t}function ne(e){if(typeof e=="number"&&(e=BigInt(e)),e<BigInt(0))throw new Error("Cannot leb encode negative values.");let t=(e===BigInt(0)?0:Zi(e))+1,r=new ft(new Uint8Array(t),0);for(;;){let n=Number(e&BigInt(127));if(e/=BigInt(128),e===BigInt(0)){r.write(new Uint8Array([n]));break}else r.write(new Uint8Array([n|128]))}return r.buffer}function he(e){let t=BigInt(1),r=BigInt(0),n;do n=mr(e),r+=BigInt(n&127).valueOf()*t,t*=BigInt(128);while(n>=128);return r}function me(e){typeof e=="number"&&(e=BigInt(e));let t=e<BigInt(0);t&&(e=-e-BigInt(1));let r=(e===BigInt(0)?0:Zi(e))+1,n=new ft(new Uint8Array(r),0);for(;;){let s=o(e);if(e/=BigInt(128),t&&e===BigInt(0)&&(s&64)!==0||!t&&e===BigInt(0)&&(s&64)===0){n.write(new Uint8Array([s]));break}else n.write(new Uint8Array([s|128]))}function o(s){let i=s%BigInt(128);return Number(t?BigInt(128)-i-BigInt(1):i)}return n.buffer}function qt(e){let t=new Uint8Array(e.buffer),r=0;for(;r<t.byteLength;r++)if(t[r]<128){if((t[r]&64)===0)return he(e);break}let n=new Uint8Array(_r(e,r+1)),o=BigInt(0);for(let s=n.byteLength-1;s>=0;s--)o=o*BigInt(128)+BigInt(128-(n[s]&127)-1);return-o-BigInt(1)}function cl(e,t){if(BigInt(e)<BigInt(0))throw new Error("Cannot write negative values.");return Xi(e,t)}function Xi(e,t){e=BigInt(e);let r=new ft(new Uint8Array(Math.min(1,t)),0),n=0,o=BigInt(256),s=BigInt(0),i=Number(e%o);for(r.write(new Uint8Array([i]));++n<t;)e<0&&s===BigInt(0)&&i!==0&&(s=BigInt(1)),i=Number((e/o-s)%BigInt(256)),r.write(new Uint8Array([i])),o*=BigInt(256);return r.buffer}function Qi(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=BigInt(mr(e)),n=BigInt(1),o=0;for(;++o<t;){n*=BigInt(256);let s=BigInt(mr(e));r=r+n*s}return r}function ll(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=Qi(e,t),n=BigInt(2)**(BigInt(8)*BigInt(t-1)+BigInt(7));return r>=n&&(r-=n*BigInt(2)),r}var Z;(function(e){e[e.Null=-1]="Null",e[e.Bool=-2]="Bool",e[e.Nat=-3]="Nat",e[e.Int=-4]="Int",e[e.Float32=-13]="Float32",e[e.Float64=-14]="Float64",e[e.Text=-15]="Text",e[e.Reserved=-16]="Reserved",e[e.Empty=-17]="Empty",e[e.Opt=-18]="Opt",e[e.Vector=-19]="Vector",e[e.Record=-20]="Record",e[e.Variant=-21]="Variant",e[e.Func=-22]="Func",e[e.Service=-23]="Service",e[e.Principal=-24]="Principal"})(Z||(Z={}));var xs="DIDL",ul=400;function so(e,t,r){return e.map((n,o)=>r(n,t[o]))}var ta=class{constructor(){this._typs=[],this._idx=new Map,this._idxRefCount=new Map}has(t){return this._idx.has(t.name)}add(t,r){let n=this._typs.length;this._idx.set(t.name,n),this._idxRefCount.set(n,1),this._typs.push(r)}merge(t,r){let n=this._idx.get(t.name),o=this._idx.get(r);if(n===void 0)throw new Error("Missing type index for "+t);if(o===void 0)throw new Error("Missing type index for "+r);this._typs[n]=this._typs[o];let s=this._getIdxRefCount(n),i=this._getIdxRefCount(o);this._idxRefCount.set(n,s+i),this._idx.set(r,n),this._idxRefCount.set(o,0),this._compactFromEnd()}_getIdxRefCount(t){return this._idxRefCount.get(t)||0}_compactFromEnd(){for(;this._typs.length>0;){let t=this._typs.length-1;if(this._getIdxRefCount(t)>0)break;this._typs.pop(),this._idxRefCount.delete(t)}}encode(){let t=ne(this._typs.length),r=Y(...this._typs);return Y(t,r)}indexOf(t){if(!this._idx.has(t))throw new Error("Missing type index for "+t);return me(this._idx.get(t)||0)}},ra=class{visitType(t,r){throw new Error("Not implemented")}visitPrimitive(t,r){return this.visitType(t,r)}visitEmpty(t,r){return this.visitPrimitive(t,r)}visitBool(t,r){return this.visitPrimitive(t,r)}visitNull(t,r){return this.visitPrimitive(t,r)}visitReserved(t,r){return this.visitPrimitive(t,r)}visitText(t,r){return this.visitPrimitive(t,r)}visitNumber(t,r){return this.visitPrimitive(t,r)}visitInt(t,r){return this.visitNumber(t,r)}visitNat(t,r){return this.visitNumber(t,r)}visitFloat(t,r){return this.visitPrimitive(t,r)}visitFixedInt(t,r){return this.visitNumber(t,r)}visitFixedNat(t,r){return this.visitNumber(t,r)}visitPrincipal(t,r){return this.visitPrimitive(t,r)}visitConstruct(t,r){return this.visitType(t,r)}visitVec(t,r,n){return this.visitConstruct(t,n)}visitOpt(t,r,n){return this.visitConstruct(t,n)}visitRecord(t,r,n){return this.visitConstruct(t,n)}visitTuple(t,r,n){let o=r.map((s,i)=>[`_${i}_`,s]);return this.visitRecord(t,o,n)}visitVariant(t,r,n){return this.visitConstruct(t,n)}visitRec(t,r,n){return this.visitConstruct(r,n)}visitFunc(t,r){return this.visitConstruct(t,r)}visitService(t,r){return this.visitConstruct(t,r)}},j;(function(e){e.EmptyClass="__IDL_EmptyClass__",e.UnknownClass="__IDL_UnknownClass__",e.BoolClass="__IDL_BoolClass__",e.NullClass="__IDL_NullClass__",e.ReservedClass="__IDL_ReservedClass__",e.TextClass="__IDL_TextClass__",e.IntClass="__IDL_IntClass__",e.NatClass="__IDL_NatClass__",e.FloatClass="__IDL_FloatClass__",e.FixedIntClass="__IDL_FixedIntClass__",e.FixedNatClass="__IDL_FixedNatClass__",e.VecClass="__IDL_VecClass__",e.OptClass="__IDL_OptClass__",e.RecordClass="__IDL_RecordClass__",e.TupleClass="__IDL_TupleClass__",e.VariantClass="__IDL_VariantClass__",e.RecClass="__IDL_RecClass__",e.PrincipalClass="__IDL_PrincipalClass__",e.FuncClass="__IDL_FuncClass__",e.ServiceClass="__IDL_ServiceClass__"})(j||(j={}));var yn=class{display(){return this.name}valueToString(t){return pe(t)}buildTypeTable(t){t.has(this)||this._buildTypeTableImpl(t)}},Ge=class extends yn{checkType(t){if(this.name!==t.name)throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`);return t}_buildTypeTableImpl(t){}},vt=class extends yn{checkType(t){if(t instanceof tt){let r=t.getType();if(typeof r>"u")throw new Error("type mismatch with uninitialized type");return r}throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`)}encodeType(t){return t.indexOf(this.name)}},io=class extends Ge{get typeName(){return j.EmptyClass}static[Symbol.hasInstance](t){return t.typeName===j.EmptyClass}accept(t,r){return t.visitEmpty(this,r)}covariant(t){throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(){throw new Error("Empty cannot appear as a function argument")}valueToString(){throw new Error("Empty cannot appear as a value")}encodeType(){return me(Z.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}},ws=class extends yn{get typeName(){return j.UnknownClass}static[Symbol.hasInstance](t){return t.typeName===j.UnknownClass}checkType(t){throw new Error("Method not implemented for unknown.")}accept(t,r){throw t.visitType(this,r)}covariant(t){throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(){throw new Error("Unknown cannot appear as a function argument")}valueToString(){throw new Error("Unknown cannot appear as a value")}encodeType(){throw new Error("Unknown cannot be serialized")}decodeValue(t,r){let n=r.decodeValue(t,r);Object(n)!==n&&(n=Object(n));let o;return r instanceof tt?o=()=>r.getType():o=()=>r,Object.defineProperty(n,"type",{value:o,writable:!0,enumerable:!1,configurable:!0}),n}_buildTypeTableImpl(){throw new Error("Unknown cannot be serialized")}get name(){return"Unknown"}},Ts=class extends Ge{get typeName(){return j.BoolClass}static[Symbol.hasInstance](t){return t.typeName===j.BoolClass}accept(t,r){return t.visitBool(this,r)}covariant(t){if(typeof t=="boolean")return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){return new Uint8Array([t?1:0])}encodeType(){return me(Z.Bool)}decodeValue(t,r){switch(this.checkType(r),mr(t)){case 0:return!1;case 1:return!0;default:throw new Error("Boolean value out of range")}}get name(){return"bool"}},qr=class extends Ge{get typeName(){return j.NullClass}static[Symbol.hasInstance](t){return t.typeName===j.NullClass}accept(t,r){return t.visitNull(this,r)}covariant(t){if(t===null)return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(){return new Uint8Array(0)}encodeType(){return me(Z.Null)}decodeValue(t,r){return this.checkType(r),null}get name(){return"null"}},It=class extends Ge{get typeName(){return j.ReservedClass}static[Symbol.hasInstance](t){return t.typeName===j.ReservedClass}accept(t,r){return t.visitReserved(this,r)}covariant(t){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return me(Z.Reserved)}decodeValue(t,r){return r.name!==this.name&&r.decodeValue(t,r),null}get name(){return"reserved"}},Os=class extends Ge{get typeName(){return j.TextClass}static[Symbol.hasInstance](t){return t.typeName===j.TextClass}accept(t,r){return t.visitText(this,r)}covariant(t){if(typeof t=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){let r=new TextEncoder().encode(t),n=ne(r.byteLength);return Y(n,r)}encodeType(){return me(Z.Text)}decodeValue(t,r){this.checkType(r);let n=he(t),o=_r(t,Number(n));return new TextDecoder("utf8",{fatal:!0}).decode(o)}get name(){return"text"}valueToString(t){return'"'+t+'"'}},ao=class extends Ge{get typeName(){return j.IntClass}static[Symbol.hasInstance](t){return t.typeName===j.IntClass}accept(t,r){return t.visitInt(this,r)}covariant(t){if(typeof t=="bigint"||Number.isInteger(t))return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){return me(t)}encodeType(){return me(Z.Int)}decodeValue(t,r){return this.checkType(r),qt(t)}get name(){return"int"}valueToString(t){return t.toString()}},co=class extends Ge{get typeName(){return j.NatClass}static[Symbol.hasInstance](t){return t.typeName===j.NatClass}accept(t,r){return t.visitNat(this,r)}covariant(t){if(typeof t=="bigint"&&t>=BigInt(0)||Number.isInteger(t)&&t>=0)return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){return ne(t)}encodeType(){return me(Z.Nat)}decodeValue(t,r){return this.checkType(r),he(t)}get name(){return"nat"}valueToString(t){return t.toString()}},lo=class extends Ge{get typeName(){return j.FloatClass}static[Symbol.hasInstance](t){return t.typeName===j.FloatClass}constructor(t){if(super(),this._bits=t,t!==32&&t!==64)throw new Error("not a valid float type")}accept(t,r){return t.visitFloat(this,r)}covariant(t){if(typeof t=="number"||t instanceof Number)return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){let r=new ArrayBuffer(this._bits/8),n=new DataView(r);return this._bits===32?n.setFloat32(0,t,!0):n.setFloat64(0,t,!0),new Uint8Array(r)}encodeType(){let t=this._bits===32?Z.Float32:Z.Float64;return me(t)}decodeValue(t,r){this.checkType(r);let n=_r(t,this._bits/8),o=il(n);return this._bits===32?o.getFloat32(0,!0):o.getFloat64(0,!0)}get name(){return"float"+this._bits}valueToString(t){return t.toString()}},jt=class extends Ge{get typeName(){return j.FixedIntClass}static[Symbol.hasInstance](t){return t.typeName===j.FixedIntClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedInt(this,r)}covariant(t){let r=gs(this._bits-1)*BigInt(-1),n=gs(this._bits-1)-BigInt(1),o=!1;if(typeof t=="bigint")o=t>=r&&t<=n;else if(Number.isInteger(t)){let s=BigInt(t);o=s>=r&&s<=n}else o=!1;if(o)return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){return Xi(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return me(-9-t)}decodeValue(t,r){this.checkType(r);let n=ll(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(t){return t.toString()}},Rt=class extends Ge{get typeName(){return j.FixedNatClass}static[Symbol.hasInstance](t){return t.typeName===j.FixedNatClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedNat(this,r)}covariant(t){let r=gs(this._bits),n=!1;if(typeof t=="bigint"&&t>=BigInt(0)?n=t<r:Number.isInteger(t)&&t>=0?n=BigInt(t)<r:n=!1,n)return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){return cl(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return me(-5-t)}decodeValue(t,r){this.checkType(r);let n=Qi(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(t){return t.toString()}},gn=class e extends vt{get typeName(){return j.VecClass}static[Symbol.hasInstance](t){return t.typeName===j.VecClass}constructor(t){super(),this._type=t,this._blobOptimization=!1,t instanceof Rt&&t._bits===8&&(this._blobOptimization=!0)}accept(t,r){return t.visitVec(this,this._type,r)}covariant(t){let r=this._type instanceof Rt?this._type._bits:this._type instanceof jt?this._type._bits:0;if(ArrayBuffer.isView(t)&&r==t.BYTES_PER_ELEMENT*8||Array.isArray(t)&&t.every((n,o)=>{try{return this._type.covariant(n)}catch(s){throw new Error(`Invalid ${this.display()} argument:
37
37
 
38
- index ${o} -> ${s.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){let r=re(t.length);if(this._blobOptimization)return Y(r,new Uint8Array(t));if(ArrayBuffer.isView(t))if(t instanceof Int16Array||t instanceof Uint16Array){let o=new DataView(new ArrayBuffer(t.length*2));for(let s=0;s<t.length;s++)t instanceof Int16Array?o.setInt16(s*2,t[s],!0):o.setUint16(s*2,t[s],!0);return Y(r,new Uint8Array(o.buffer))}else if(t instanceof Int32Array||t instanceof Uint32Array){let o=new DataView(new ArrayBuffer(t.length*4));for(let s=0;s<t.length;s++)t instanceof Int32Array?o.setInt32(s*4,t[s],!0):o.setUint32(s*4,t[s],!0);return Y(r,new Uint8Array(o.buffer))}else if(t instanceof BigInt64Array||t instanceof BigUint64Array){let o=new DataView(new ArrayBuffer(t.length*8));for(let s=0;s<t.length;s++)t instanceof BigInt64Array?o.setBigInt64(s*8,t[s],!0):o.setBigUint64(s*8,t[s],!0);return Y(r,new Uint8Array(o.buffer))}else return Y(r,new Uint8Array(t.buffer,t.byteOffset,t.byteLength));let n=new st(new Uint8Array(r.byteLength+t.length),0);n.write(r);for(let o of t){let s=this._type.encodeValue(o);n.write(new Uint8Array(s))}return n.buffer}_buildTypeTableImpl(t){this._type.buildTypeTable(t);let r=fe(Z.Vector),n=this._type.encodeType(t);t.add(this,Y(r,n))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a vector type");let o=Number(pe(t));if(this._type instanceof yt){if(this._type._bits==8)return new Uint8Array(t.read(o));if(this._type._bits==16){let i=t.read(o*2);return new Uint16Array(i.buffer,i.byteOffset,o)}if(this._type._bits==32){let i=t.read(o*4);return new Uint32Array(i.buffer,i.byteOffset,o)}if(this._type._bits==64)return new BigUint64Array(t.read(o*8).buffer)}if(this._type instanceof Bt){if(this._type._bits==8)return new Int8Array(t.read(o));if(this._type._bits==16){let i=t.read(o*2),a=new DataView(i.buffer,i.byteOffset,i.byteLength),c=new Int16Array(o);for(let u=0;u<o;u++)c[u]=a.getInt16(u*2,!0);return c}if(this._type._bits==32){let i=t.read(o*4),a=new DataView(i.buffer,i.byteOffset,i.byteLength),c=new Int32Array(o);for(let u=0;u<o;u++)c[u]=a.getInt32(u*4,!0);return c}if(this._type._bits==64){let i=t.read(o*8),a=new DataView(i.buffer,i.byteOffset,i.byteLength),c=new BigInt64Array(o);for(let u=0;u<o;u++)c[u]=a.getBigInt64(u*8,!0);return c}}let s=[];for(let i=0;i<o;i++)s.push(this._type.decodeValue(t,n._type));return s}get name(){return`vec ${this._type.name}`}display(){return`vec ${this._type.display()}`}valueToString(t){return"vec {"+t.map(n=>this._type.valueToString(n)).join("; ")+"}"}},nr=class e extends gt{get typeName(){return $.OptClass}static[Symbol.hasInstance](t){return t.typeName===$.OptClass}constructor(t){super(),this._type=t}accept(t,r){return t.visitOpt(this,this._type,r)}covariant(t){try{if(Array.isArray(t)&&(t.length===0||t.length===1&&this._type.covariant(t[0])))return!0}catch(r){throw new Error(`Invalid ${this.display()} argument: ${de(t)}
38
+ index ${o} -> ${s.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){let r=ne(t.length);if(this._blobOptimization)return Y(r,new Uint8Array(t));if(ArrayBuffer.isView(t))if(t instanceof Int16Array||t instanceof Uint16Array){let o=new DataView(new ArrayBuffer(t.length*2));for(let s=0;s<t.length;s++)t instanceof Int16Array?o.setInt16(s*2,t[s],!0):o.setUint16(s*2,t[s],!0);return Y(r,new Uint8Array(o.buffer))}else if(t instanceof Int32Array||t instanceof Uint32Array){let o=new DataView(new ArrayBuffer(t.length*4));for(let s=0;s<t.length;s++)t instanceof Int32Array?o.setInt32(s*4,t[s],!0):o.setUint32(s*4,t[s],!0);return Y(r,new Uint8Array(o.buffer))}else if(t instanceof BigInt64Array||t instanceof BigUint64Array){let o=new DataView(new ArrayBuffer(t.length*8));for(let s=0;s<t.length;s++)t instanceof BigInt64Array?o.setBigInt64(s*8,t[s],!0):o.setBigUint64(s*8,t[s],!0);return Y(r,new Uint8Array(o.buffer))}else return Y(r,new Uint8Array(t.buffer,t.byteOffset,t.byteLength));let n=new ft(new Uint8Array(r.byteLength+t.length),0);n.write(r);for(let o of t){let s=this._type.encodeValue(o);n.write(new Uint8Array(s))}return n.buffer}_buildTypeTableImpl(t){this._type.buildTypeTable(t);let r=me(Z.Vector),n=this._type.encodeType(t);t.add(this,Y(r,n))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a vector type");let o=Number(he(t));if(this._type instanceof Rt){if(this._type._bits==8)return new Uint8Array(t.read(o));if(this._type._bits==16){let i=t.read(o*2);return new Uint16Array(i.buffer,i.byteOffset,o)}if(this._type._bits==32){let i=t.read(o*4);return new Uint32Array(i.buffer,i.byteOffset,o)}if(this._type._bits==64)return new BigUint64Array(t.read(o*8).buffer)}if(this._type instanceof jt){if(this._type._bits==8)return new Int8Array(t.read(o));if(this._type._bits==16){let i=t.read(o*2),a=new DataView(i.buffer,i.byteOffset,i.byteLength),c=new Int16Array(o);for(let u=0;u<o;u++)c[u]=a.getInt16(u*2,!0);return c}if(this._type._bits==32){let i=t.read(o*4),a=new DataView(i.buffer,i.byteOffset,i.byteLength),c=new Int32Array(o);for(let u=0;u<o;u++)c[u]=a.getInt32(u*4,!0);return c}if(this._type._bits==64){let i=t.read(o*8),a=new DataView(i.buffer,i.byteOffset,i.byteLength),c=new BigInt64Array(o);for(let u=0;u<o;u++)c[u]=a.getBigInt64(u*8,!0);return c}}let s=[];for(let i=0;i<o;i++)s.push(this._type.decodeValue(t,n._type));return s}get name(){return`vec ${this._type.name}`}display(){return`vec ${this._type.display()}`}valueToString(t){return"vec {"+t.map(n=>this._type.valueToString(n)).join("; ")+"}"}},yr=class e extends vt{get typeName(){return j.OptClass}static[Symbol.hasInstance](t){return t.typeName===j.OptClass}constructor(t){super(),this._type=t}accept(t,r){return t.visitOpt(this,this._type,r)}covariant(t){try{if(Array.isArray(t)&&(t.length===0||t.length===1&&this._type.covariant(t[0])))return!0}catch(r){throw new Error(`Invalid ${this.display()} argument: ${pe(t)}
39
39
 
40
- -> ${r.message}`)}throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){return t.length===0?new Uint8Array([0]):Y(new Uint8Array([1]),this._type.encodeValue(t[0]))}_buildTypeTableImpl(t){this._type.buildTypeTable(t);let r=fe(Z.Opt),n=this._type.encodeType(t);t.add(this,Y(r,n))}decodeValue(t,r){if(r instanceof br)return[];if(r instanceof xt)return[];let n=r;if(r instanceof We){let o=r.getType();if(typeof o>"u")throw new Error("type mismatch with uninitialized type");n=o}if(n instanceof e)switch(tr(t)){case 0:return[];case 1:{let o=t.save();try{return[this._type.decodeValue(t,n._type)]}catch{return t.restore(o),n._type.decodeValue(t,n._type),[]}}default:throw new Error("Not an option value")}else{if(this._type instanceof br||this._type instanceof e||this._type instanceof xt)return n.decodeValue(t,n),[];{let o=t.save();try{return[this._type.decodeValue(t,r)]}catch{return t.restore(o),n.decodeValue(t,r),[]}}}}get name(){return`opt ${this._type.name}`}display(){return`opt ${this._type.display()}`}valueToString(t){return t.length===0?"null":`opt ${this._type.valueToString(t[0])}`}},wr=class e extends gt{get typeName(){return $.RecordClass}static[Symbol.hasInstance](t){return t.typeName===$.RecordClass||t.typeName===$.TupleClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((r,n)=>Ce(r[0])-Ce(n[0]))}accept(t,r){return t.visitRecord(this,this._fields,r)}tryAsTuple(){let t=[];for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(n!==`_${r}_`)return null;t.push(o)}return t}covariant(t){if(typeof t=="object"&&this._fields.every(([r,n])=>{if(!t.hasOwnProperty(r))throw new Error(`Record is missing key "${r}".`);try{return n.covariant(t[r])}catch(o){throw new Error(`Invalid ${this.display()} argument:
40
+ -> ${r.message}`)}throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){return t.length===0?new Uint8Array([0]):Y(new Uint8Array([1]),this._type.encodeValue(t[0]))}_buildTypeTableImpl(t){this._type.buildTypeTable(t);let r=me(Z.Opt),n=this._type.encodeType(t);t.add(this,Y(r,n))}decodeValue(t,r){if(r instanceof qr)return[];if(r instanceof It)return[];let n=r;if(r instanceof tt){let o=r.getType();if(typeof o>"u")throw new Error("type mismatch with uninitialized type");n=o}if(n instanceof e)switch(mr(t)){case 0:return[];case 1:{let o=t.save();try{return[this._type.decodeValue(t,n._type)]}catch{return t.restore(o),n._type.decodeValue(t,n._type),[]}}default:throw new Error("Not an option value")}else{if(this._type instanceof qr||this._type instanceof e||this._type instanceof It)return n.decodeValue(t,n),[];{let o=t.save();try{return[this._type.decodeValue(t,r)]}catch{return t.restore(o),n.decodeValue(t,r),[]}}}}get name(){return`opt ${this._type.name}`}display(){return`opt ${this._type.display()}`}valueToString(t){return t.length===0?"null":`opt ${this._type.valueToString(t[0])}`}},Mr=class e extends vt{get typeName(){return j.RecordClass}static[Symbol.hasInstance](t){return t.typeName===j.RecordClass||t.typeName===j.TupleClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((r,n)=>Le(r[0])-Le(n[0]))}accept(t,r){return t.visitRecord(this,this._fields,r)}tryAsTuple(){let t=[];for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(n!==`_${r}_`)return null;t.push(o)}return t}covariant(t){if(typeof t=="object"&&this._fields.every(([r,n])=>{if(!t.hasOwnProperty(r))throw new Error(`Record is missing key "${r}".`);try{return n.covariant(t[r])}catch(o){throw new Error(`Invalid ${this.display()} argument:
41
41
 
42
- field ${r} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){let r=this._fields.map(([o])=>t[o]),n=Dn(this._fields,r,([,o],s)=>o.encodeValue(s));return Y(...n)}_buildTypeTableImpl(t){this._fields.forEach(([s,i])=>i.buildTypeTable(t));let r=fe(Z.Record),n=re(this._fields.length),o=this._fields.map(([s,i])=>Y(re(Ce(s)),i.encodeType(t)));t.add(this,Y(r,n,Y(...o)))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a record type");let o={},s=0,i=0;for(;i<n._fields.length;){let[a,c]=n._fields[i];if(s>=this._fields.length){c.decodeValue(t,c),i++;continue}let[u,p]=this._fields[s],d=Ce(this._fields[s][0]),l=Ce(a);if(d===l)o[u]=p.decodeValue(t,c),s++,i++;else if(l>d)if(p instanceof nr||p instanceof xt)o[u]=[],s++;else throw new Error("Cannot find required field "+u);else c.decodeValue(t,c),i++}for(let[a,c]of this._fields.slice(s))if(c instanceof nr||c instanceof xt)o[a]=[];else throw new Error("Cannot find required field "+a);return o}get fieldsAsObject(){let t={};for(let[r,n]of this._fields)t[Ce(r)]=n;return t}get name(){return`record {${this._fields.map(([r,n])=>r+":"+n.name).join("; ")}}`}display(){return`record {${this._fields.map(([r,n])=>r+":"+n.display()).join("; ")}}`}valueToString(t){let r=this._fields.map(([o])=>t[o]);return`record {${Dn(this._fields,r,([o,s],i)=>o+"="+s.valueToString(i)).join("; ")}}`}},Xo=class e extends wr{get typeName(){return $.TupleClass}static[Symbol.hasInstance](t){return t.typeName===$.TupleClass}constructor(t){let r={};t.forEach((n,o)=>r["_"+o+"_"]=n),super(r),this._components=t}accept(t,r){return t.visitTuple(this,this._components,r)}covariant(t){if(Array.isArray(t)&&t.length>=this._fields.length&&this._components.every((r,n)=>{try{return r.covariant(t[n])}catch(o){throw new Error(`Invalid ${this.display()} argument:
42
+ field ${r} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){let r=this._fields.map(([o])=>t[o]),n=so(this._fields,r,([,o],s)=>o.encodeValue(s));return Y(...n)}_buildTypeTableImpl(t){this._fields.forEach(([s,i])=>i.buildTypeTable(t));let r=me(Z.Record),n=ne(this._fields.length),o=this._fields.map(([s,i])=>Y(ne(Le(s)),i.encodeType(t)));t.add(this,Y(r,n,Y(...o)))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a record type");let o={},s=0,i=0;for(;i<n._fields.length;){let[a,c]=n._fields[i];if(s>=this._fields.length){c.decodeValue(t,c),i++;continue}let[u,p]=this._fields[s],d=Le(this._fields[s][0]),l=Le(a);if(d===l)o[u]=p.decodeValue(t,c),s++,i++;else if(l>d)if(p instanceof yr||p instanceof It)o[u]=[],s++;else throw new Error("Cannot find required field "+u);else c.decodeValue(t,c),i++}for(let[a,c]of this._fields.slice(s))if(c instanceof yr||c instanceof It)o[a]=[];else throw new Error("Cannot find required field "+a);return o}get fieldsAsObject(){let t={};for(let[r,n]of this._fields)t[Le(r)]=n;return t}get name(){return`record {${this._fields.map(([r,n])=>r+":"+n.name).join("; ")}}`}display(){return`record {${this._fields.map(([r,n])=>r+":"+n.display()).join("; ")}}`}valueToString(t){let r=this._fields.map(([o])=>t[o]);return`record {${so(this._fields,r,([o,s],i)=>o+"="+s.valueToString(i)).join("; ")}}`}},Ns=class e extends Mr{get typeName(){return j.TupleClass}static[Symbol.hasInstance](t){return t.typeName===j.TupleClass}constructor(t){let r={};t.forEach((n,o)=>r["_"+o+"_"]=n),super(r),this._components=t}accept(t,r){return t.visitTuple(this,this._components,r)}covariant(t){if(Array.isArray(t)&&t.length>=this._fields.length&&this._components.every((r,n)=>{try{return r.covariant(t[n])}catch(o){throw new Error(`Invalid ${this.display()} argument:
43
43
 
44
- index ${n} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){let r=Dn(this._components,t,(n,o)=>n.encodeValue(o));return Y(...r)}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("not a tuple type");if(n._components.length<this._components.length)throw new Error("tuple mismatch");let o=[];for(let[s,i]of n._components.entries())s>=this._components.length?i.decodeValue(t,i):o.push(this._components[s].decodeValue(t,i));return o}display(){return`record {${this._components.map(r=>r.display()).join("; ")}}`}valueToString(t){return`record {${Dn(this._components,t,(n,o)=>n.valueToString(o)).join("; ")}}`}},Xr=class e extends gt{get typeName(){return $.VariantClass}static[Symbol.hasInstance](t){return t.typeName===$.VariantClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((r,n)=>Ce(r[0])-Ce(n[0]))}accept(t,r){return t.visitVariant(this,this._fields,r)}covariant(t){if(typeof t=="object"&&Object.entries(t).length===1&&this._fields.every(([r,n])=>{try{return!t.hasOwnProperty(r)||n.covariant(t[r])}catch(o){throw new Error(`Invalid ${this.display()} argument:
44
+ index ${n} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){let r=so(this._components,t,(n,o)=>n.encodeValue(o));return Y(...r)}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("not a tuple type");if(n._components.length<this._components.length)throw new Error("tuple mismatch");let o=[];for(let[s,i]of n._components.entries())s>=this._components.length?i.decodeValue(t,i):o.push(this._components[s].decodeValue(t,i));return o}display(){return`record {${this._components.map(r=>r.display()).join("; ")}}`}valueToString(t){return`record {${so(this._components,t,(n,o)=>n.valueToString(o)).join("; ")}}`}},xn=class e extends vt{get typeName(){return j.VariantClass}static[Symbol.hasInstance](t){return t.typeName===j.VariantClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((r,n)=>Le(r[0])-Le(n[0]))}accept(t,r){return t.visitVariant(this,this._fields,r)}covariant(t){if(typeof t=="object"&&Object.entries(t).length===1&&this._fields.every(([r,n])=>{try{return!t.hasOwnProperty(r)||n.covariant(t[r])}catch(o){throw new Error(`Invalid ${this.display()} argument:
45
45
 
46
- variant ${r} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(t.hasOwnProperty(n)){let s=re(r),i=o.encodeValue(t[n]);return Y(s,i)}}throw Error("Variant has no data: "+t)}_buildTypeTableImpl(t){this._fields.forEach(([,s])=>{s.buildTypeTable(t)});let r=fe(Z.Variant),n=re(this._fields.length),o=this._fields.map(([s,i])=>Y(re(Ce(s)),i.encodeType(t)));t.add(this,Y(r,n,...o))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a variant type");let o=Number(pe(t));if(o>=n._fields.length)throw Error("Invalid variant index: "+o);let[s,i]=n._fields[o];for(let[a,c]of this._fields)if(Ce(s)===Ce(a)){let u=c.decodeValue(t,i);return{[a]:u}}throw new Error("Cannot find field hash "+s)}get name(){return`variant {${this._fields.map(([r,n])=>r+":"+n.name).join("; ")}}`}display(){return`variant {${this._fields.map(([r,n])=>r+(n.name==="null"?"":`:${n.display()}`)).join("; ")}}`}valueToString(t){for(let[r,n]of this._fields)if(t.hasOwnProperty(r)){let o=n.valueToString(t[r]);return o==="null"?`variant {${r}}`:`variant {${r}=${o}}`}throw new Error("Variant has no data: "+t)}get alternativesAsObject(){let t={};for(let[r,n]of this._fields)t[Ce(r)]=n;return t}},We=class e extends gt{constructor(){super(...arguments),this._id=e._counter++}get typeName(){return $.RecClass}static{this._counter=0}static[Symbol.hasInstance](t){return t.typeName===$.RecClass}accept(t,r){if(!this._type)throw Error("Recursive type uninitialized.");return t.visitRec(this,this._type,r)}fill(t){this._type=t}getType(){return this._type}covariant(t){if(this._type&&this._type.covariant(t))return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.encodeValue(t)}_buildTypeTableImpl(t){if(!this._type)throw Error("Recursive type uninitialized.");t.add(this,new Uint8Array([])),this._type.buildTypeTable(t),t.merge(this,this._type.name)}decodeValue(t,r){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.decodeValue(t,r)}get name(){return`rec_${this._id}`}display(){if(!this._type)throw Error("Recursive type uninitialized.");return`\u03BC${this.name}.${this._type.name}`}valueToString(t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.valueToString(t)}};function Oi(e){if(tr(e)!==1)throw new Error("Cannot decode principal");let r=Number(pe(e));return L.fromUint8Array(new Uint8Array(rr(e,r)))}var Qo=class extends Me{get typeName(){return $.PrincipalClass}static[Symbol.hasInstance](t){return t.typeName===$.PrincipalClass}accept(t,r){return t.visitPrincipal(this,r)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){let r=t.toUint8Array(),n=re(r.byteLength);return Y(new Uint8Array([1]),n,r)}encodeType(){return fe(Z.Principal)}decodeValue(t,r){return this.checkType(r),Oi(t)}get name(){return"principal"}valueToString(t){return`${this.name} "${t.toText()}"`}},Tr=class extends gt{get typeName(){return $.FuncClass}static[Symbol.hasInstance](t){return t.typeName===$.FuncClass}static argsToString(t,r){if(t.length!==r.length)throw new Error("arity mismatch");return"("+t.map((n,o)=>n.valueToString(r[o])).join(", ")+")"}constructor(t,r,n=[]){super(),this.argTypes=t,this.retTypes=r,this.annotations=n}accept(t,r){return t.visitFunc(this,r)}covariant(t){if(Array.isArray(t)&&t.length===2&&t[0]&&t[0]._isPrincipal&&typeof t[1]=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue([t,r]){let n=t.toUint8Array(),o=re(n.byteLength),s=Y(new Uint8Array([1]),o,n),i=new TextEncoder().encode(r),a=re(i.byteLength);return Y(new Uint8Array([1]),s,a,i)}_buildTypeTableImpl(t){this.argTypes.forEach(u=>u.buildTypeTable(t)),this.retTypes.forEach(u=>u.buildTypeTable(t));let r=fe(Z.Func),n=re(this.argTypes.length),o=Y(...this.argTypes.map(u=>u.encodeType(t))),s=re(this.retTypes.length),i=Y(...this.retTypes.map(u=>u.encodeType(t))),a=re(this.annotations.length),c=Y(...this.annotations.map(u=>this.encodeAnnotation(u)));t.add(this,Y(r,n,o,s,i,a,c))}decodeValue(t,r){let n=r instanceof We?r.getType()??r:r;if(!Ei(n,this))throw new Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if(tr(t)!==1)throw new Error("Cannot decode function reference");let s=Oi(t),i=Number(pe(t)),a=rr(t,i),u=new TextDecoder("utf8",{fatal:!0}).decode(a);return[s,u]}get name(){let t=this.argTypes.map(o=>o.name).join(", "),r=this.retTypes.map(o=>o.name).join(", "),n=" "+this.annotations.join(" ");return`(${t}) -> (${r})${n}`}valueToString([t,r]){return`func "${t.toText()}".${r}`}display(){let t=this.argTypes.map(o=>o.display()).join(", "),r=this.retTypes.map(o=>o.display()).join(", "),n=" "+this.annotations.join(" ");return`(${t}) \u2192 (${r})${n}`}encodeAnnotation(t){if(t==="query")return new Uint8Array([1]);if(t==="oneway")return new Uint8Array([2]);if(t==="composite_query")return new Uint8Array([3]);throw new Error("Illegal function annotation")}},Qr=class extends gt{get typeName(){return $.ServiceClass}static[Symbol.hasInstance](t){return t.typeName===$.ServiceClass}constructor(t){super(),this._fields=Object.entries(t).sort((r,n)=>r[0]<n[0]?-1:r[0]>n[0]?1:0)}accept(t,r){return t.visitService(this,r)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${de(t)}`)}encodeValue(t){let r=t.toUint8Array(),n=re(r.length);return Y(new Uint8Array([1]),n,r)}_buildTypeTableImpl(t){this._fields.forEach(([s,i])=>i.buildTypeTable(t));let r=fe(Z.Service),n=re(this._fields.length),o=this._fields.map(([s,i])=>{let a=new TextEncoder().encode(s),c=re(a.length);return Y(c,a,i.encodeType(t))});t.add(this,Y(r,n,...o))}decodeValue(t,r){let n=r instanceof We?r.getType()??r:r;if(!Ei(n,this))throw new Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return Oi(t)}get name(){return`service {${this._fields.map(([r,n])=>r+":"+n.name).join("; ")}}`}valueToString(t){return`service "${t.toText()}"`}fieldsAsObject(){let t={};for(let[r,n]of this._fields)t[r]=n;return t}};function de(e){let t=JSON.stringify(e,(r,n)=>typeof n=="bigint"?`BigInt(${n})`:n);return t&&t.length>Ec?t.substring(0,Ec-3)+"...":t}function Hd(e,t){if(t.length<e.length)throw Error("Wrong number of message arguments");let r=new wi;e.forEach(c=>c.buildTypeTable(r));let n=new TextEncoder().encode(zo),o=r.encode(),s=re(t.length),i=Y(...e.map(c=>c.encodeType(r))),a=Y(...Dn(e,t,(c,u)=>{try{c.covariant(u)}catch(p){throw new Error(p.message+`
46
+ variant ${r} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(t.hasOwnProperty(n)){let s=ne(r),i=o.encodeValue(t[n]);return Y(s,i)}}throw Error("Variant has no data: "+t)}_buildTypeTableImpl(t){this._fields.forEach(([,s])=>{s.buildTypeTable(t)});let r=me(Z.Variant),n=ne(this._fields.length),o=this._fields.map(([s,i])=>Y(ne(Le(s)),i.encodeType(t)));t.add(this,Y(r,n,...o))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a variant type");let o=Number(he(t));if(o>=n._fields.length)throw Error("Invalid variant index: "+o);let[s,i]=n._fields[o];for(let[a,c]of this._fields)if(Le(s)===Le(a)){let u=c.decodeValue(t,i);return{[a]:u}}throw new Error("Cannot find field hash "+s)}get name(){return`variant {${this._fields.map(([r,n])=>r+":"+n.name).join("; ")}}`}display(){return`variant {${this._fields.map(([r,n])=>r+(n.name==="null"?"":`:${n.display()}`)).join("; ")}}`}valueToString(t){for(let[r,n]of this._fields)if(t.hasOwnProperty(r)){let o=n.valueToString(t[r]);return o==="null"?`variant {${r}}`:`variant {${r}=${o}}`}throw new Error("Variant has no data: "+t)}get alternativesAsObject(){let t={};for(let[r,n]of this._fields)t[Le(r)]=n;return t}},tt=class e extends vt{constructor(){super(...arguments),this._id=e._counter++}get typeName(){return j.RecClass}static{this._counter=0}static[Symbol.hasInstance](t){return t.typeName===j.RecClass}accept(t,r){if(!this._type)throw Error("Recursive type uninitialized.");return t.visitRec(this,this._type,r)}fill(t){this._type=t}getType(){return this._type}covariant(t){if(this._type&&this._type.covariant(t))return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.encodeValue(t)}_buildTypeTableImpl(t){if(!this._type)throw Error("Recursive type uninitialized.");t.add(this,new Uint8Array([])),this._type.buildTypeTable(t),t.merge(this,this._type.name)}decodeValue(t,r){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.decodeValue(t,r)}get name(){return`rec_${this._id}`}display(){if(!this._type)throw Error("Recursive type uninitialized.");return`\u03BC${this.name}.${this._type.name}`}valueToString(t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.valueToString(t)}};function oa(e){if(mr(e)!==1)throw new Error("Cannot decode principal");let r=Number(he(e));return k.fromUint8Array(new Uint8Array(_r(e,r)))}var Es=class extends Ge{get typeName(){return j.PrincipalClass}static[Symbol.hasInstance](t){return t.typeName===j.PrincipalClass}accept(t,r){return t.visitPrincipal(this,r)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){let r=t.toUint8Array(),n=ne(r.byteLength);return Y(new Uint8Array([1]),n,r)}encodeType(){return me(Z.Principal)}decodeValue(t,r){return this.checkType(r),oa(t)}get name(){return"principal"}valueToString(t){return`${this.name} "${t.toText()}"`}},jr=class extends vt{get typeName(){return j.FuncClass}static[Symbol.hasInstance](t){return t.typeName===j.FuncClass}static argsToString(t,r){if(t.length!==r.length)throw new Error("arity mismatch");return"("+t.map((n,o)=>n.valueToString(r[o])).join(", ")+")"}constructor(t,r,n=[]){super(),this.argTypes=t,this.retTypes=r,this.annotations=n}accept(t,r){return t.visitFunc(this,r)}covariant(t){if(Array.isArray(t)&&t.length===2&&t[0]&&t[0]._isPrincipal&&typeof t[1]=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue([t,r]){let n=t.toUint8Array(),o=ne(n.byteLength),s=Y(new Uint8Array([1]),o,n),i=new TextEncoder().encode(r),a=ne(i.byteLength);return Y(new Uint8Array([1]),s,a,i)}_buildTypeTableImpl(t){this.argTypes.forEach(u=>u.buildTypeTable(t)),this.retTypes.forEach(u=>u.buildTypeTable(t));let r=me(Z.Func),n=ne(this.argTypes.length),o=Y(...this.argTypes.map(u=>u.encodeType(t))),s=ne(this.retTypes.length),i=Y(...this.retTypes.map(u=>u.encodeType(t))),a=ne(this.annotations.length),c=Y(...this.annotations.map(u=>this.encodeAnnotation(u)));t.add(this,Y(r,n,o,s,i,a,c))}decodeValue(t,r){let n=r instanceof tt?r.getType()??r:r;if(!sa(n,this))throw new Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if(mr(t)!==1)throw new Error("Cannot decode function reference");let s=oa(t),i=Number(he(t)),a=_r(t,i),u=new TextDecoder("utf8",{fatal:!0}).decode(a);return[s,u]}get name(){let t=this.argTypes.map(o=>o.name).join(", "),r=this.retTypes.map(o=>o.name).join(", "),n=" "+this.annotations.join(" ");return`(${t}) -> (${r})${n}`}valueToString([t,r]){return`func "${t.toText()}".${r}`}display(){let t=this.argTypes.map(o=>o.display()).join(", "),r=this.retTypes.map(o=>o.display()).join(", "),n=" "+this.annotations.join(" ");return`(${t}) \u2192 (${r})${n}`}encodeAnnotation(t){if(t==="query")return new Uint8Array([1]);if(t==="oneway")return new Uint8Array([2]);if(t==="composite_query")return new Uint8Array([3]);throw new Error("Illegal function annotation")}},bn=class extends vt{get typeName(){return j.ServiceClass}static[Symbol.hasInstance](t){return t.typeName===j.ServiceClass}constructor(t){super(),this._fields=Object.entries(t).sort((r,n)=>r[0]<n[0]?-1:r[0]>n[0]?1:0)}accept(t,r){return t.visitService(this,r)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${pe(t)}`)}encodeValue(t){let r=t.toUint8Array(),n=ne(r.length);return Y(new Uint8Array([1]),n,r)}_buildTypeTableImpl(t){this._fields.forEach(([s,i])=>i.buildTypeTable(t));let r=me(Z.Service),n=ne(this._fields.length),o=this._fields.map(([s,i])=>{let a=new TextEncoder().encode(s),c=ne(a.length);return Y(c,a,i.encodeType(t))});t.add(this,Y(r,n,...o))}decodeValue(t,r){let n=r instanceof tt?r.getType()??r:r;if(!sa(n,this))throw new Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return oa(t)}get name(){return`service {${this._fields.map(([r,n])=>r+":"+n.name).join("; ")}}`}valueToString(t){return`service "${t.toText()}"`}fieldsAsObject(){let t={};for(let[r,n]of this._fields)t[r]=n;return t}};function pe(e){let t=JSON.stringify(e,(r,n)=>typeof n=="bigint"?`BigInt(${n})`:n);return t&&t.length>ul?t.substring(0,ul-3)+"...":t}function Mp(e,t){if(t.length<e.length)throw Error("Wrong number of message arguments");let r=new ta;e.forEach(c=>c.buildTypeTable(r));let n=new TextEncoder().encode(xs),o=r.encode(),s=ne(t.length),i=Y(...e.map(c=>c.encodeType(r))),a=Y(...so(e,t,(c,u)=>{try{c.covariant(u)}catch(p){throw new Error(p.message+`
47
47
 
48
- `)}return c.encodeValue(u)}));return Y(n,o,s,i,a)}function Gd(e,t){let r=new st(t);if(t.byteLength<zo.length)throw new Error("Message length smaller than magic number");let n=rr(r,zo.length),o=new TextDecoder().decode(n);if(o!==zo)throw new Error("Wrong magic number: "+JSON.stringify(o));function s(l){let f=[],h=Number(pe(l));for(let m=0;m<h;m++){let x=Number(Ft(l));switch(x){case Z.Opt:case Z.Vector:{let y=Number(Ft(l));f.push([x,y]);break}case Z.Record:case Z.Variant:{let y=[],T=Number(pe(l)),O;for(;T--;){let R=Number(pe(l));if(R>=Math.pow(2,32))throw new Error("field id out of 32-bit range");if(typeof O=="number"&&O>=R)throw new Error("field id collision or not sorted");O=R;let E=Number(Ft(l));y.push([R,E])}f.push([x,y]);break}case Z.Func:{let y=[],T=Number(pe(l));for(;T--;)y.push(Number(Ft(l)));let O=[],R=Number(pe(l));for(;R--;)O.push(Number(Ft(l)));let E=[],v=Number(pe(l));for(;v--;)switch(Number(pe(l))){case 1:{E.push("query");break}case 2:{E.push("oneway");break}case 3:{E.push("composite_query");break}default:throw new Error("unknown annotation")}f.push([x,[y,O,E]]);break}case Z.Service:{let y=Number(pe(l)),T=[];for(;y--;){let O=Number(pe(l)),R=new TextDecoder().decode(rr(l,O)),E=Ft(l);T.push([R,E])}f.push([x,T]);break}default:throw new Error("Illegal op_code: "+x)}}let _=[],g=Number(pe(l));for(let m=0;m<g;m++)_.push(Number(Ft(l)));return[f,_]}let[i,a]=s(r);if(a.length<e.length)throw new Error("Wrong number of return values");let c=i.map(l=>Yc());function u(l){if(l<-24)throw new Error("future value not supported");if(l<0)switch(l){case-1:return Ac;case-2:return Ic;case-3:return Pc;case-4:return Fc;case-5:return Lc;case-6:return qc;case-7:return Mc;case-8:return jc;case-9:return Vc;case-10:return Dc;case-11:return Uc;case-12:return kc;case-13:return Bc;case-14:return Cc;case-15:return Sc;case-16:return vc;case-17:return Rc;case-24:return Kc;default:throw new Error("Illegal op_code: "+l)}if(l>=i.length)throw new Error("type index out of range");return c[l]}function p(l){switch(l[0]){case Z.Vector:{let f=u(l[1]);return Hc(f)}case Z.Opt:{let f=u(l[1]);return Gc(f)}case Z.Record:{let f={};for(let[g,m]of l[1]){let x=`_${g}_`;f[x]=u(m)}let h=zc(f),_=h.tryAsTuple();return Array.isArray(_)?$c(..._):h}case Z.Variant:{let f={};for(let[h,_]of l[1]){let g=`_${h}_`;f[g]=u(_)}return Wc(f)}case Z.Func:{let[f,h,_]=l[1];return Jc(f.map(g=>u(g)),h.map(g=>u(g)),_)}case Z.Service:{let f={},h=l[1];for(let[_,g]of h){let m=u(g);if(m instanceof We&&(m=m.getType()),!(m instanceof Tr))throw new Error("Illegal service definition: services can only contain functions");f[_]=m}return Zc(f)}default:throw new Error("Illegal op_code: "+l[0])}}i.forEach((l,f)=>{if(l[0]===Z.Func){let h=p(l);c[f].fill(h)}}),i.forEach((l,f)=>{if(l[0]!==Z.Func){let h=p(l);c[f].fill(h)}}),Ni();let d=a.map(l=>u(l));try{let l=e.map((f,h)=>f.decodeValue(r,d[h]));for(let f=e.length;f<d.length;f++)d[f].decodeValue(r,d[f]);if(r.byteLength>0)throw new Error("decode: Left-over bytes");return l}finally{Ni()}}var Rc=new Un,vc=new xt,zd=new Yo,Ic=new Jo,Ac=new br,Sc=new Zo,Fc=new kn,Pc=new Ln,Bc=new qn(32),Cc=new qn(64),Vc=new Bt(8),Dc=new Bt(16),Uc=new Bt(32),kc=new Bt(64),Lc=new yt(8),qc=new yt(16),Mc=new yt(32),jc=new yt(64),Kc=new Qo;function $c(...e){return new Xo(e)}function Hc(e){return new Zr(e)}function Gc(e){return new nr(e)}function zc(e){return new wr(e)}function Wc(e){return new Xr(e)}function Yc(){return new We}function Jc(e,t,r=[]){return new Tr(e,t,r)}function Zc(e){return new Qr(e)}var es=class e{constructor(t=new Map){this.rels=t}copy(){let t=new Map;for(let[r,n]of this.rels.entries()){let o=new Map(n);t.set(r,o)}return new e(t)}known(t,r){return this.rels.get(t.name)?.get(r.name)}addNegative(t,r){this.addNames(t.name,r.name,!1)}add(t,r){this.addNames(t.name,r.name,!0)}display(){let t="";for(let[r,n]of this.rels)for(let[o,s]of n)t+=`${r} ${s?":<":"!<:"} ${o}
49
- `;return t}addNames(t,r,n){let o=this.rels.get(t);if(o==null){let s=new Map;s.set(r,n),this.rels.set(t,s)}else o.set(r,n)}},Wo=new es;function Ni(){Wo=new es}function Wd(e,t){let r=new Set(e.annotations),n=new Set(t.annotations);if(r.size!==n.size)return!1;for(let o of r)if(!n.has(o))return!1;return!0}function bi(e){return e instanceof nr||e instanceof br||e instanceof xt}function Ei(e,t){let r=Wo.copy(),n=Pt(r,e,t);return n?Wo.add(e,t):Wo.addNegative(e,t),n}function Pt(e,t,r){if(t.name===r.name)return!0;let n=e.known(t,r);if(n!==void 0)return n;if(e.add(t,r),r instanceof xt||t instanceof Un||t instanceof Ln&&r instanceof kn)return!0;if(t instanceof Zr&&r instanceof Zr)return Pt(e,t._type,r._type);if(r instanceof nr)return!0;if(t instanceof wr&&r instanceof wr){let o=t.fieldsAsObject;for(let[s,i]of r._fields){let a=o[Ce(s)];if(a){if(!Pt(e,a,i))return!1}else if(!bi(i))return!1}return!0}if(t instanceof Tr&&r instanceof Tr){if(!Wd(t,r))return!1;for(let o=0;o<t.argTypes.length;o++){let s=t.argTypes[o];if(o<r.argTypes.length){if(!Pt(e,r.argTypes[o],s))return!1}else if(!bi(s))return!1}for(let o=0;o<r.retTypes.length;o++){let s=r.retTypes[o];if(o<t.retTypes.length){if(!Pt(e,t.retTypes[o],s))return!1}else if(!bi(s))return!1}return!0}if(t instanceof Xr&&r instanceof Xr){let o=r.alternativesAsObject;for(let[s,i]of t._fields){let a=o[Ce(s)];if(!a||!Pt(e,i,a))return!1}return!0}if(t instanceof Qr&&r instanceof Qr){let o=t.fieldsAsObject();for(let[s,i]of r._fields){let a=o[s];if(!a||!Pt(e,a,i))return!1}return!0}return t instanceof We?Pt(e,t.getType(),r):r instanceof We?Pt(e,t,r.getType()):!1}function en(e){if(!e)throw new Error("Input cannot be null or undefined");return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):"buffer"in e?en(e.buffer):new Uint8Array(e)}function Or(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function Ri(e){if(typeof e=="string")return Xc(e);if(typeof e=="number")return ve(re(e));if(e instanceof Uint8Array||ArrayBuffer.isView(e))return ve(en(e));if(Array.isArray(e)){let t=e.map(Ri);return ve(K(...t))}else{if(e&&typeof e=="object"&&e._isPrincipal)return ve(e.toUint8Array());if(typeof e=="object"&&e!==null&&typeof e.toHash=="function")return Ri(e.toHash());if(typeof e=="object")return Mn(e);if(typeof e=="bigint")return ve(re(e))}throw W.fromCode(new Lo(e))}var Xc=e=>{let t=new TextEncoder().encode(e);return ve(t)};function Ct(e){return Mn(e)}function Mn(e){let n=Object.entries(e).filter(([,i])=>i!==void 0).map(([i,a])=>{let c=Xc(i),u=Ri(a);return[c,u]}).sort(([i],[a])=>_i(i,a)),o=K(...n.map(i=>K(...i)));return ve(o)}var jn=new TextEncoder().encode(`
50
- ic-request`),vi=new TextEncoder().encode("\vic-response"),Ii=new TextEncoder().encode("ic-request-auth-delegation");var bt=class{getPrincipal(){return this._principal||(this._principal=L.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()))),this._principal}async transformRequest(t){let{body:r,...n}=t,o=Ct(r);return{...n,body:{content:r,sender_pubkey:this.getPublicKey().toDer(),sender_sig:await this.sign(K(jn,o))}}}},Ye=class{getPrincipal(){return L.anonymous()}async transformRequest(t){return{...t,body:{content:t.body}}}};var Vt=class extends Error{constructor(t){super(t),this.name="DecodingError"}},el=55799,tl=Symbol("CBOR_STOP_CODE"),ct=(e=>(e[e.False=20]="False",e[e.True=21]="True",e[e.Null=22]="Null",e[e.Undefined=23]="Undefined",e[e.Break=31]="Break",e))(ct||{}),_e=(e=>(e[e.UnsignedInteger=0]="UnsignedInteger",e[e.NegativeInteger=1]="NegativeInteger",e[e.ByteString=2]="ByteString",e[e.TextString=3]="TextString",e[e.Array=4]="Array",e[e.Map=5]="Map",e[e.Tag=6]="Tag",e[e.Simple=7]="Simple",e))(_e||{}),Yd=23,Jd=255,Zd=65535,Xd=4294967295,Qd=BigInt("0xffffffffffffffff"),at=(e=>(e[e.Value=23]="Value",e[e.OneByte=24]="OneByte",e[e.TwoBytes=25]="TwoBytes",e[e.FourBytes=26]="FourBytes",e[e.EightBytes=27]="EightBytes",e[e.Indefinite=31]="Indefinite",e))(at||{}),tn=!1;function ep(e){return e==null}function rl(e,t){let r=new Uint8Array(t);return r.set(e),r}var tp=new TextDecoder;function rp(e){return(e&224)>>5}function np(e){return e&31}var Hn=new Uint8Array,Kn,lt=0;function nl(e,t){Hn=e,lt=0;let r=Er(t);return t?.(r)??r}function Er(e){let[t,r]=ts();switch(t){case _e.UnsignedInteger:return rn(r);case _e.NegativeInteger:return ap(r);case _e.ByteString:return ol(r);case _e.TextString:return Si(r);case _e.Array:return op(r,e);case _e.Map:return ip(r,e);case _e.Tag:return cp(r,e);case _e.Simple:return sp(r)}throw new Vt(`Unsupported major type: ${t}`)}function ts(){let e=Hn.at(lt);if(ep(e))throw new Vt("Provided CBOR data is empty");let t=rp(e),r=np(e);return lt++,[t,r]}function op(e,t){let r=rn(e);if(r===1/0){let o=[],s=Er(t);for(;s!==tl;)o.push(t?.(s)??s),s=Er(t);return o}let n=new Array(r);for(let o=0;o<r;o++){let s=Er(t);n[o]=t?.(s)??s}return n}function sp(e){switch(e){case ct.False:return!1;case ct.True:return!0;case ct.Null:return null;case ct.Undefined:return;case ct.Break:return tl}throw new Vt(`Unrecognized simple type: ${e.toString(2)}`)}function ip(e,t){let r=rn(e),n={};if(r===1/0){let[o,s]=ts();for(;o!==_e.Simple&&s!==ct.Break;){let i=Si(s),a=Er(t);n[i]=t?.(a,i)??a,[o,s]=ts()}return n}for(let o=0;o<r;o++){let[s,i]=ts();if(s!==_e.TextString)throw new Vt("Map keys must be text strings");let a=Si(i),c=Er(t);n[a]=t?.(c,a)??c}return n}function rn(e){if(e<=at.Value)return e;switch(Kn=new DataView(Hn.buffer,Hn.byteOffset+lt),e){case at.OneByte:return lt++,Kn.getUint8(0);case at.TwoBytes:return lt+=2,Kn.getUint16(0,tn);case at.FourBytes:return lt+=4,Kn.getUint32(0,tn);case at.EightBytes:return lt+=8,Kn.getBigUint64(0,tn);case at.Indefinite:return 1/0;default:throw new Vt(`Unsupported integer info: ${e.toString(2)}`)}}function ap(e){let t=rn(e);return typeof t=="number"?-1-t:-1n-t}function ol(e){let t=rn(e);if(t>Number.MAX_SAFE_INTEGER)throw new Vt("Byte length is too large");let r=Number(t);return lt+=r,Hn.slice(lt-r,lt)}function Si(e){let t=ol(e);return tp.decode(t)}function cp(e,t){let r=rn(e);if(r===el)return Er(t);throw new Vt(`Unsupported tag: ${r}.`)}var Gn=class extends Error{constructor(t){super(t),this.name="SerializationError"}},lp=2*1024,up=100,dp=new TextEncoder;function $n(e){return e<<5}var He=new Uint8Array(lp),it=new DataView(He.buffer),me=0,Ai=[];function sl(e,t){me=0;let r=t?.(e)??e;return xp(el,r,t),He.slice(0,me)}function Fi(e,t){if(me>He.length-up&&(He=rl(He,He.length*2),it=new DataView(He.buffer)),e===!1||e===!0||e===null||e===void 0){hp(e);return}if(typeof e=="number"||typeof e=="bigint"){gp(e);return}if(typeof e=="string"){cl(e);return}if(e instanceof Uint8Array){Qc(e);return}if(e instanceof ArrayBuffer){Qc(new Uint8Array(e));return}if(Array.isArray(e)){pp(e,t);return}if(typeof e=="object"){fp(e,t);return}throw new Gn(`Unsupported type: ${typeof e}`)}function pp(e,t){nn(_e.Array,e.length),e.forEach((r,n)=>{Fi(t?.(r,n.toString())??r,t)})}function fp(e,t){Ai=Object.entries(e),nn(_e.Map,Ai.length),Ai.forEach(([r,n])=>{cl(r),Fi(t?.(n,r)??n,t)})}function nn(e,t){if(t<=Yd){it.setUint8(me++,$n(e)|Number(t));return}if(t<=Jd){it.setUint8(me++,$n(e)|at.OneByte),it.setUint8(me,Number(t)),me+=1;return}if(t<=Zd){it.setUint8(me++,$n(e)|at.TwoBytes),it.setUint16(me,Number(t),tn),me+=2;return}if(t<=Xd){it.setUint8(me++,$n(e)|at.FourBytes),it.setUint32(me,Number(t),tn),me+=4;return}if(t<=Qd){it.setUint8(me++,$n(e)|at.EightBytes),it.setBigUint64(me,BigInt(t),tn),me+=8;return}throw new Gn(`Value too large to encode: ${t}`)}function hp(e){nn(_e.Simple,mp(e))}function mp(e){if(e===!1)return ct.False;if(e===!0)return ct.True;if(e===null)return ct.Null;if(e===void 0)return ct.Undefined;throw new Gn(`Unrecognized simple value: ${e.toString()}`)}function il(e,t){nn(e,t.length),me>He.length-t.length&&(He=rl(He,He.length+t.length),it=new DataView(He.buffer)),He.set(t,me),me+=t.length}function al(e,t){nn(e,t)}function _p(e){al(_e.UnsignedInteger,e)}function yp(e){al(_e.NegativeInteger,typeof e=="bigint"?-1n-e:-1-e)}function gp(e){e>=0?_p(e):yp(e)}function cl(e){il(_e.TextString,dp.encode(e))}function Qc(e){il(_e.ByteString,e)}function xp(e,t,r){nn(_e.Tag,e),Fi(t,r)}function wp(e){return typeof e=="object"&&e!==null&&"toCborValue"in e}function zn(e){try{return sl(e,t=>L.isPrincipal(t)?t.toUint8Array():on.isExpiry(t)?t.toBigInt():wp(t)?t.toCborValue():t)}catch(t){throw W.fromCode(new Co(t,e))}}function je(e){try{return nl(e)}catch(t){throw W.fromCode(new Bo(t,e))}}var rs={encode:zn,decode:je};var Wn=()=>{if(typeof window<"u"&&window.crypto&&window.crypto.getRandomValues){let e=new Uint32Array(1);return window.crypto.getRandomValues(e),e[0]}if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return typeof crypto<"u"&&crypto.randomInt?crypto.randomInt(0,4294967295):Math.floor(Math.random()*4294967295)};var Dt;(function(e){e.Query="read",e.ReadState="read_state",e.Call="call"})(Dt||(Dt={}));var ns;(function(e){e.Call="call"})(ns||(ns={}));var Rr;(function(e){e.Query="query",e.ReadState="read_state"})(Rr||(Rr={}));function Yn(){let e=new ArrayBuffer(16),t=new DataView(e),r=Wn(),n=Wn(),o=Wn(),s=Wn();return t.setUint32(0,r),t.setUint32(4,n),t.setUint32(8,o),t.setUint32(12,s),Object.assign(new Uint8Array(e),{__nonce__:void 0})}var os="__expiry__",Bi=BigInt(1e3),Tp=BigInt(1e6),ll=BigInt(60),Np=BigInt(90)*Bi;function ul(e){return e/Bi}function Op(e){return ul(e)/ll}var on=class e{constructor(t){this.__expiry__=t,this._isExpiry=!0}static fromDeltaInMilliseconds(t,r=0){let n=BigInt(t),o=BigInt(Date.now())+n+BigInt(r),s;return n<Np?s=ul(o):s=Op(o)*ll,new e(s*Bi*Tp)}toBigInt(){return this.__expiry__}toHash(){return re(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[os]:this.toString()}}static fromJSON(t){let r=JSON.parse(t);if(r[os])try{let n=BigInt(r[os]);return new e(n)}catch(n){throw new W(new Cn(`Not a valid BigInt: ${n}`))}throw new W(new Cn(`The input does not contain the key ${os}`))}static isExpiry(t){return t instanceof e||typeof t=="object"&&t!==null&&"_isExpiry"in t&&t._isExpiry===!0&&"__expiry__"in t&&typeof t.__expiry__=="bigint"}};function Ci(e=Yn){return async t=>{let r=t.request.headers;t.request.headers=r,t.endpoint===Dt.Call&&(t.body.nonce=e())}}function ss(e){let t=[];return e.forEach((r,n)=>{t.push([n,r])}),t}var Di=BigInt(0),is=BigInt(1);function vr(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}"`;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function or(e,t,r=""){let n=ft(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function dl(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Di:BigInt("0x"+e)}function Ke(e){return dl(M(e))}function Ut(e){return ue(e),dl(M(Uint8Array.from(e).reverse()))}function ye(e,t){return be(e.toString(16).padStart(t*2,"0"))}function Ui(e,t){return ye(e,t).reverse()}function ae(e,t,r){let n;if(typeof t=="string")try{n=be(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(ft(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let o=n.length;if(typeof r=="number"&&o!==r)throw new Error(e+" of length "+r+" expected, got "+o);return n}function pl(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function ki(e){return Uint8Array.from(e)}var Vi=e=>typeof e=="bigint"&&Di<=e;function Li(e,t,r){return Vi(e)&&Vi(t)&&Vi(r)&&t<=e&&e<r}function as(e,t,r,n){if(!Li(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function kt(e){let t;for(t=0;e>Di;e>>=is,t+=1);return t}function fl(e,t){return e>>BigInt(t)&is}var ut=e=>(is<<BigInt(e))-is;function hl(e){return typeof e=="function"&&Number.isSafeInteger(e.outputLen)}function Lt(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(o,s,i){let a=e[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}var sn=()=>{throw new Error("not implemented")};function sr(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}var Ve=BigInt(0),Te=BigInt(1),Ir=BigInt(2),_l=BigInt(3),yl=BigInt(4),gl=BigInt(5),Ep=BigInt(7),xl=BigInt(8),Rp=BigInt(9),bl=BigInt(16);function se(e,t){let r=e%t;return r>=Ve?r:t+r}function dt(e,t,r){let n=e;for(;t-- >Ve;)n*=n,n%=r;return n}function ml(e,t){if(e===Ve)throw new Error("invert: expected non-zero number");if(t<=Ve)throw new Error("invert: expected positive modulus, got "+t);let r=se(e,t),n=t,o=Ve,s=Te,i=Te,a=Ve;for(;r!==Ve;){let u=n/r,p=n%r,d=o-i*u,l=s-a*u;n=r,r=p,o=i,s=a,i=d,a=l}if(n!==Te)throw new Error("invert: does not exist");return se(o,t)}function qi(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function wl(e,t){let r=(e.ORDER+Te)/yl,n=e.pow(t,r);return qi(e,n,t),n}function vp(e,t){let r=(e.ORDER-gl)/xl,n=e.mul(t,Ir),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,Ir),o),a=e.mul(s,e.sub(i,e.ONE));return qi(e,a,t),a}function Ip(e){let t=De(e),r=Tl(e),n=r(t,t.neg(t.ONE)),o=r(t,n),s=r(t,t.neg(n)),i=(e+Ep)/bl;return(a,c)=>{let u=a.pow(c,i),p=a.mul(u,n),d=a.mul(u,o),l=a.mul(u,s),f=a.eql(a.sqr(p),c),h=a.eql(a.sqr(d),c);u=a.cmov(u,p,f),p=a.cmov(l,d,h);let _=a.eql(a.sqr(p),c),g=a.cmov(u,p,_);return qi(a,g,c),g}}function Tl(e){if(e<_l)throw new Error("sqrt is not defined for small field");let t=e-Te,r=0;for(;t%Ir===Ve;)t/=Ir,r++;let n=Ir,o=De(e);for(;Jn(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return wl;let s=o.pow(n,t),i=(t+Te)/Ir;return function(c,u){if(c.is0(u))return u;if(Jn(c,u)!==1)throw new Error("Cannot find square root");let p=r,d=c.mul(c.ONE,s),l=c.pow(u,t),f=c.pow(u,i);for(;!c.eql(l,c.ONE);){if(c.is0(l))return c.ZERO;let h=1,_=c.sqr(l);for(;!c.eql(_,c.ONE);)if(h++,_=c.sqr(_),h===p)throw new Error("Cannot find square root");let g=Te<<BigInt(p-h-1),m=c.pow(d,g);p=h,d=c.sqr(m),l=c.mul(l,d),f=c.mul(f,m)}return f}}function Ap(e){return e%yl===_l?wl:e%xl===gl?vp:e%bl===Rp?Ip(e):Tl(e)}var qt=(e,t)=>(se(e,t)&Te)===Te,Sp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function cs(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=Sp.reduce((n,o)=>(n[o]="function",n),t);return Lt(e,r),e}function Zn(e,t,r){if(r<Ve)throw new Error("invalid exponent, negatives unsupported");if(r===Ve)return e.ONE;if(r===Te)return t;let n=e.ONE,o=t;for(;r>Ve;)r&Te&&(n=e.mul(n,o)),o=e.sqr(o),r>>=Te;return n}function Je(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function Jn(e,t){let r=(e.ORDER-Te)/Ir,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Mi(e,t){t!==void 0&&li(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function De(e,t,r=!1,n={}){if(e<=Ve)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let l=t;l.BITS&&(o=l.BITS),l.sqrt&&(s=l.sqrt),typeof l.isLE=="boolean"&&(r=l.isLE),typeof l.modFromBytes=="boolean"&&(i=l.modFromBytes),a=l.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:u}=Mi(e,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let p,d=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:u,MASK:ut(c),ZERO:Ve,ONE:Te,allowedLengths:a,create:l=>se(l,e),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return Ve<=l&&l<e},is0:l=>l===Ve,isValidNot0:l=>!d.is0(l)&&d.isValid(l),isOdd:l=>(l&Te)===Te,neg:l=>se(-l,e),eql:(l,f)=>l===f,sqr:l=>se(l*l,e),add:(l,f)=>se(l+f,e),sub:(l,f)=>se(l-f,e),mul:(l,f)=>se(l*f,e),pow:(l,f)=>Zn(d,l,f),div:(l,f)=>se(l*ml(f,e),e),sqrN:l=>l*l,addN:(l,f)=>l+f,subN:(l,f)=>l-f,mulN:(l,f)=>l*f,inv:l=>ml(l,e),sqrt:s||(l=>(p||(p=Ap(e)),p(d,l))),toBytes:l=>r?Ui(l,u):ye(l,u),fromBytes:(l,f=!0)=>{if(a){if(!a.includes(l.length)||l.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+l.length);let _=new Uint8Array(u);_.set(l,r?0:_.length-l.length),l=_}if(l.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+l.length);let h=r?Ut(l):Ke(l);if(i&&(h=se(h,e)),!f&&!d.isValid(h))throw new Error("invalid field element: outside of range 0..ORDER");return h},invertBatch:l=>Je(d,l),cmov:(l,f,h)=>h?f:l});return Object.freeze(d)}function Nl(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function ls(e){let t=Nl(e);return t+Math.ceil(t/2)}function ji(e,t,r=!1){let n=e.length,o=Nl(t),s=ls(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?Ut(e):Ke(e),a=se(i,t-Te)+Te;return r?Ui(a,o):ye(a,o)}var an=BigInt(0),Ar=BigInt(1);function Xn(e,t){let r=t.negate();return e?r:t}function Ze(e,t){let r=Je(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function vl(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Ki(e,t){vl(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=ut(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Ol(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=Ar);let u=t*n,p=u+Math.abs(a)-1,d=a===0,l=a<0,f=t%2!==0;return{nextN:c,offset:p,isZero:d,isNeg:l,isNegF:f,offsetF:u}}function Pp(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function Bp(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}var $i=new WeakMap,Il=new WeakMap;function Hi(e){return Il.get(e)||1}function El(e){if(e!==an)throw new Error("invalid wNAF")}var cn=class{constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let o=t;for(;r>an;)r&Ar&&(n=n.add(o)),o=o.double(),r>>=Ar;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=Ki(r,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Ki(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:p,isNeg:d,isNegF:l,offsetF:f}=Ol(n,a,i);n=c,p?s=s.add(Xn(l,r[f])):o=o.add(Xn(d,r[u]))}return El(n),{p:o,f:s}}wNAFUnsafe(t,r,n,o=this.ZERO){let s=Ki(t,this.bits);for(let i=0;i<s.windows&&n!==an;i++){let{nextN:a,offset:c,isZero:u,isNeg:p}=Ol(n,i,s);if(n=a,!u){let d=r[c];o=o.add(p?d.negate():d)}}return El(n),o}getPrecomputes(t,r,n){let o=$i.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(o=n(o)),$i.set(r,o))),o}cached(t,r,n){let o=Hi(t);return this.wNAF(o,this.getPrecomputes(o,t,n),r)}unsafe(t,r,n,o){let s=Hi(t);return s===1?this._unsafeLadder(t,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),r,o)}createCache(t,r){vl(r,this.bits),Il.set(t,r),$i.delete(t)}hasCache(t){return Hi(t)!==1}};function Al(e,t,r,n){let o=t,s=e.ZERO,i=e.ZERO;for(;r>an||n>an;)r&Ar&&(s=s.add(o)),n&Ar&&(i=i.add(o)),o=o.double(),r>>=Ar,n>>=Ar;return{p1:s,p2:i}}function ln(e,t,r,n){Pp(r,e),Bp(n,t);let o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=e.ZERO,a=kt(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=ut(c),p=new Array(Number(u)+1).fill(i),d=Math.floor((t.BITS-1)/c)*c,l=i;for(let f=d;f>=0;f-=c){p.fill(i);for(let _=0;_<s;_++){let g=n[_],m=Number(g>>BigInt(f)&u);p[m]=p[m].add(r[_])}let h=i;for(let _=p.length-1,g=i;_>0;_--)g=g.add(p[_]),h=h.add(g);if(l=l.add(h),f!==0)for(let _=0;_<c;_++)l=l.double()}return l}function Rl(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return cs(t),t}else return De(e,{isLE:r})}function us(e,t,r={},n){if(n===void 0&&(n=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u=="bigint"&&u>an))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Rl(t.p,r.Fp,n),s=Rl(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}var Cp=Ke;function ir(e,t){if(Qn(e),Qn(t),e<0||e>=1<<8*t)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function Vp(e,t){let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function Qn(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function Sl(e){if(!ft(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or string");return typeof e=="string"?Q(e):e}function Dp(e,t,r,n){ue(e),Qn(r),t=Sl(t),t.length>255&&(t=n(K(Q("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(r/o);if(r>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=K(t,ir(t.length,1)),c=ir(0,s),u=ir(r,2),p=new Array(i),d=n(K(c,e,u,ir(0,1),a));p[0]=n(K(d,ir(1,1),a));for(let f=1;f<=i;f++){let h=[Vp(d,p[f-1]),ir(f+1,1),a];p[f]=n(K(...h))}return K(...p).slice(0,r)}function Up(e,t,r,n,o){if(ue(e),Qn(r),t=Sl(t),t.length>255){let s=Math.ceil(2*n/8);t=o.create({dkLen:s}).update(Q("H2C-OVERSIZE-DST-")).update(t).digest()}if(r>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return o.create({dkLen:r}).update(e).update(ir(r,2)).update(t).update(ir(t.length,1)).digest()}function Gi(e,t,r){Lt(r,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:n,k:o,m:s,hash:i,expand:a,DST:c}=r;if(!hl(r.hash))throw new Error("expected valid hash");ue(e),Qn(t);let u=n.toString(2).length,p=Math.ceil((u+o)/8),d=t*s*p,l;if(a==="xmd")l=Dp(e,c,d,i);else if(a==="xof")l=Up(e,c,d,o,i);else if(a==="_internal_pass")l=e;else throw new Error('expand must be "xmd" or "xof"');let f=new Array(t);for(let h=0;h<t;h++){let _=new Array(s);for(let g=0;g<s;g++){let m=p*(g+h*s),x=l.subarray(m,m+p);_[g]=se(Cp(x),n)}f[h]=_}return f}function zi(e,t){let r=t.map(n=>Array.from(n).reverse());return(n,o)=>{let[s,i,a,c]=r.map(d=>d.reduce((l,f)=>e.add(e.mul(l,n),f))),[u,p]=Je(e,[i,c],!0);return n=e.mul(s,u),o=e.mul(o,e.mul(a,p)),{x:n,y:o}}}var kp=Q("HashToScalar-");function Wi(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function n(s){return e.fromAffine(t(s))}function o(s){let i=s.clearCofactor();return i.equals(e.ZERO)?e.ZERO:(i.assertValidity(),i)}return{defaults:r,hashToCurve(s,i){let a=Object.assign({},r,i),c=Gi(s,2,a),u=n(c[0]),p=n(c[1]);return o(u.add(p))},encodeToCurve(s,i){let a=r.encodeDST?{DST:r.encodeDST}:{},c=Object.assign({},r,a,i),u=Gi(s,1,c),p=n(u[0]);return o(p)},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(let i of s)if(typeof i!="bigint")throw new Error("expected array of bigints");return o(n(s))},hashToScalar(s,i){let a=e.Fn.ORDER,c=Object.assign({},r,{p:a,m:1,DST:kp},i);return Gi(s,1,c)[0][0]}}}var Fl=(e,t)=>(e+(e>=0?t:-t)/Mt)/t;function Lp(e,t,r){let[[n,o],[s,i]]=t,a=Fl(i*e,r),c=Fl(-o*e,r),u=e-a*n-c*s,p=-a*o-c*i,d=u<Sr,l=p<Sr;d&&(u=-u),l&&(p=-p);let f=ut(Math.ceil(kt(r)/2))+Ue;if(u<Sr||u>=f||p<Sr||p>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:u,k2neg:l,k2:p}}var Sr=BigInt(0),Ue=BigInt(1),Mt=BigInt(2),un=BigInt(3),Yi=BigInt(4);function eo(e,t){let{BYTES:r}=e,n;if(typeof t=="bigint")n=t;else{let o=ae("private key",t);try{n=e.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function qp(e,t={}){let r=us("weierstrass",e,t),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;Lt(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Kp(n,o);function p(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(A,b,N){let{x:P,y:V}=b.toAffine(),q=n.toBytes(P);if(vr(N,"isCompressed"),N){p();let S=!n.isOdd(V);return K(Mp(S),q)}else return K(Uint8Array.of(4),q,n.toBytes(V))}function l(A){or(A,void 0,"Point");let{publicKey:b,publicKeyUncompressed:N}=u,P=A.length,V=A[0],q=A.subarray(1);if(P===b&&(V===2||V===3)){let S=n.fromBytes(q);if(!n.isValid(S))throw new Error("bad point: is not on curve, wrong x");let F=_(S),C;try{C=n.sqrt(F)}catch(ee){let ne=ee instanceof Error?": "+ee.message:"";throw new Error("bad point: is not on curve, sqrt error"+ne)}p();let D=n.isOdd(C);return(V&1)===1!==D&&(C=n.neg(C)),{x:S,y:C}}else if(P===N&&V===4){let S=n.BYTES,F=n.fromBytes(q.subarray(0,S)),C=n.fromBytes(q.subarray(S,S*2));if(!g(F,C))throw new Error("bad point: is not on curve");return{x:F,y:C}}else throw new Error(`bad point: got length ${P}, expected compressed=${b} or uncompressed=${N}`)}let f=t.toBytes||d,h=t.fromBytes||l;function _(A){let b=n.sqr(A),N=n.mul(b,A);return n.add(n.add(N,n.mul(A,s.a)),s.b)}function g(A,b){let N=n.sqr(b),P=_(A);return n.eql(N,P)}if(!g(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let m=n.mul(n.pow(s.a,un),Yi),x=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(m,x)))throw new Error("bad curve params: a or b");function y(A,b,N=!1){if(!n.isValid(b)||N&&n.is0(b))throw new Error(`bad point coordinate ${A}`);return b}function T(A){if(!(A instanceof w))throw new Error("ProjectivePoint expected")}function O(A){if(!c||!c.basises)throw new Error("no endo");return Lp(A,c.basises,o.ORDER)}let R=sr((A,b)=>{let{X:N,Y:P,Z:V}=A;if(n.eql(V,n.ONE))return{x:N,y:P};let q=A.is0();b==null&&(b=q?n.ONE:n.inv(V));let S=n.mul(N,b),F=n.mul(P,b),C=n.mul(V,b);if(q)return{x:n.ZERO,y:n.ZERO};if(!n.eql(C,n.ONE))throw new Error("invZ was invalid");return{x:S,y:F}}),E=sr(A=>{if(A.is0()){if(t.allowInfinityPoint&&!n.is0(A.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:N}=A.toAffine();if(!n.isValid(b)||!n.isValid(N))throw new Error("bad point: x or y not field elements");if(!g(b,N))throw new Error("bad point: equation left != right");if(!A.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(A,b,N,P,V){return N=new w(n.mul(N.X,A),N.Y,N.Z),b=Xn(P,b),N=Xn(V,N),b.add(N)}class w{constructor(b,N,P){this.X=y("x",b),this.Y=y("y",N,!0),this.Z=y("z",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){let{x:N,y:P}=b||{};if(!b||!n.isValid(N)||!n.isValid(P))throw new Error("invalid affine point");if(b instanceof w)throw new Error("projective point not allowed");return n.is0(N)&&n.is0(P)?w.ZERO:new w(N,P,n.ONE)}static fromBytes(b){let N=w.fromAffine(h(or(b,void 0,"point")));return N.assertValidity(),N}static fromHex(b){return w.fromBytes(ae("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,N=!0){return B.createCache(this,b),N||this.multiply(un),this}assertValidity(){E(this)}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){T(b);let{X:N,Y:P,Z:V}=this,{X:q,Y:S,Z:F}=b,C=n.eql(n.mul(N,F),n.mul(q,V)),D=n.eql(n.mul(P,F),n.mul(S,V));return C&&D}negate(){return new w(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:N}=s,P=n.mul(N,un),{X:V,Y:q,Z:S}=this,F=n.ZERO,C=n.ZERO,D=n.ZERO,k=n.mul(V,V),ee=n.mul(q,q),ne=n.mul(S,S),z=n.mul(V,q);return z=n.add(z,z),D=n.mul(V,S),D=n.add(D,D),F=n.mul(b,D),C=n.mul(P,ne),C=n.add(F,C),F=n.sub(ee,C),C=n.add(ee,C),C=n.mul(F,C),F=n.mul(z,F),D=n.mul(P,D),ne=n.mul(b,ne),z=n.sub(k,ne),z=n.mul(b,z),z=n.add(z,D),D=n.add(k,k),k=n.add(D,k),k=n.add(k,ne),k=n.mul(k,z),C=n.add(C,k),ne=n.mul(q,S),ne=n.add(ne,ne),k=n.mul(ne,z),F=n.sub(F,k),D=n.mul(ne,ee),D=n.add(D,D),D=n.add(D,D),new w(F,C,D)}add(b){T(b);let{X:N,Y:P,Z:V}=this,{X:q,Y:S,Z:F}=b,C=n.ZERO,D=n.ZERO,k=n.ZERO,ee=s.a,ne=n.mul(s.b,un),z=n.mul(N,q),Se=n.mul(P,S),Fe=n.mul(V,F),pt=n.add(N,P),oe=n.add(q,S);pt=n.mul(pt,oe),oe=n.add(z,Se),pt=n.sub(pt,oe),oe=n.add(N,V);let xe=n.add(q,F);return oe=n.mul(oe,xe),xe=n.add(z,Fe),oe=n.sub(oe,xe),xe=n.add(P,V),C=n.add(S,F),xe=n.mul(xe,C),C=n.add(Se,Fe),xe=n.sub(xe,C),k=n.mul(ee,oe),C=n.mul(ne,Fe),k=n.add(C,k),C=n.sub(Se,k),k=n.add(Se,k),D=n.mul(C,k),Se=n.add(z,z),Se=n.add(Se,z),Fe=n.mul(ee,Fe),oe=n.mul(ne,oe),Se=n.add(Se,Fe),Fe=n.sub(z,Fe),Fe=n.mul(ee,Fe),oe=n.add(oe,Fe),z=n.mul(Se,oe),D=n.add(D,z),z=n.mul(xe,oe),C=n.mul(pt,C),C=n.sub(C,z),z=n.mul(pt,Se),k=n.mul(xe,k),k=n.add(k,z),new w(C,D,k)}subtract(b){return this.add(b.negate())}is0(){return this.equals(w.ZERO)}multiply(b){let{endo:N}=t;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let P,V,q=S=>B.cached(this,S,F=>Ze(w,F));if(N){let{k1neg:S,k1:F,k2neg:C,k2:D}=O(b),{p:k,f:ee}=q(F),{p:ne,f:z}=q(D);V=ee.add(z),P=v(N.beta,k,ne,S,C)}else{let{p:S,f:F}=q(b);P=S,V=F}return Ze(w,[P,V])[0]}multiplyUnsafe(b){let{endo:N}=t,P=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===Sr||P.is0())return w.ZERO;if(b===Ue)return P;if(B.hasCache(this))return this.multiply(b);if(N){let{k1neg:V,k1:q,k2neg:S,k2:F}=O(b),{p1:C,p2:D}=Al(w,P,q,F);return v(N.beta,C,D,V,S)}else return B.unsafe(P,b)}multiplyAndAddUnsafe(b,N,P){let V=this.multiplyUnsafe(N).add(b.multiplyUnsafe(P));return V.is0()?void 0:V}toAffine(b){return R(this,b)}isTorsionFree(){let{isTorsionFree:b}=t;return i===Ue?!0:b?b(w,this):B.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=t;return i===Ue?this:b?b(w,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return vr(b,"isCompressed"),this.assertValidity(),f(w,this,b)}toHex(b=!0){return M(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return Ze(w,b)}static msm(b,N){return ln(w,o,b,N)}static fromPrivateKey(b){return w.BASE.multiply(eo(o,b))}}w.BASE=new w(s.Gx,s.Gy,n.ONE),w.ZERO=new w(n.ZERO,n.ONE,n.ZERO),w.Fp=n,w.Fn=o;let I=o.BITS,B=new cn(w,t.endo?Math.ceil(I/2):I);return w.BASE.precompute(8),w}function Mp(e){return Uint8Array.of(e?2:3)}function jp(e,t){let r=e.ORDER,n=Sr;for(let h=r-Ue;h%Mt===Sr;h/=Mt)n+=Ue;let o=n,s=Mt<<o-Ue-Ue,i=s*Mt,a=(r-Ue)/i,c=(a-Ue)/Mt,u=i-Ue,p=s,d=e.pow(t,a),l=e.pow(t,(a+Ue)/Mt),f=(h,_)=>{let g=d,m=e.pow(_,u),x=e.sqr(m);x=e.mul(x,_);let y=e.mul(h,x);y=e.pow(y,c),y=e.mul(y,m),m=e.mul(y,_),x=e.mul(y,h);let T=e.mul(x,m);y=e.pow(T,p);let O=e.eql(y,e.ONE);m=e.mul(x,l),y=e.mul(T,g),x=e.cmov(m,x,O),T=e.cmov(y,T,O);for(let R=o;R>Ue;R--){let E=R-Mt;E=Mt<<E-Ue;let v=e.pow(T,E),w=e.eql(v,e.ONE);m=e.mul(x,g),g=e.mul(g,g),v=e.mul(T,g),x=e.cmov(m,x,w),T=e.cmov(v,T,w)}return{isValid:O,value:x}};if(e.ORDER%Yi===un){let h=(e.ORDER-un)/Yi,_=e.sqrt(e.neg(t));f=(g,m)=>{let x=e.sqr(m),y=e.mul(g,m);x=e.mul(x,y);let T=e.pow(x,h);T=e.mul(T,y);let O=e.mul(T,_),R=e.mul(e.sqr(T),m),E=e.eql(R,g),v=e.cmov(O,T,E);return{isValid:E,value:v}}}return f}function Ji(e,t){cs(e);let{A:r,B:n,Z:o}=t;if(!e.isValid(r)||!e.isValid(n)||!e.isValid(o))throw new Error("mapToCurveSimpleSWU: invalid opts");let s=jp(e,o);if(!e.isOdd)throw new Error("Field does not have .isOdd()");return i=>{let a,c,u,p,d,l,f,h;a=e.sqr(i),a=e.mul(a,o),c=e.sqr(a),c=e.add(c,a),u=e.add(c,e.ONE),u=e.mul(u,n),p=e.cmov(o,e.neg(c),!e.eql(c,e.ZERO)),p=e.mul(p,r),c=e.sqr(u),l=e.sqr(p),d=e.mul(l,r),c=e.add(c,d),c=e.mul(c,u),l=e.mul(l,p),d=e.mul(l,n),c=e.add(c,d),f=e.mul(a,u);let{isValid:_,value:g}=s(c,l);h=e.mul(a,i),h=e.mul(h,g),f=e.cmov(f,u,_),h=e.cmov(h,g,_);let m=e.isOdd(i)===e.isOdd(h);h=e.cmov(e.neg(h),h,m);let x=Je(e,[p],!0)[0];return f=e.mul(f,x),{x:f,y:h}}}function Kp(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Zi(e){let{CURVE:t,curveOpts:r}=$p(e),n=qp(t,r);return Gp(e,n)}function $p(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=De(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),s={Fp:r,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function Hp(e,t,r){function n(o){let s=e.sqr(o),i=e.mul(s,o);return e.add(e.add(i,e.mul(o,t)),r)}return n}function Gp(e,t){let{Fp:r,Fn:n}=t;function o(i){return Li(i,Ue,n.ORDER)}let s=Hp(r,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:i=>eo(n,i),weierstrassEquation:s,isWithinCurveOrder:o})}var zp=BigInt(0),ds=BigInt(1),Pl=BigInt(2),dn=BigInt(3);function Wp(e){let t=[];for(;e>ds;e>>=ds)(e&ds)===zp?t.unshift(0):(e&dn)===dn?(t.unshift(-1),e+=ds):t.unshift(1);return t}function Xi(e){if(!Array.isArray(e)||e.length===0)throw new Error("expected non-empty array")}function Yp(e,t,r,n){let{Fp2:o,Fp12:s}=e,{twistType:i,ateLoopSize:a,xNegative:c,postPrecompute:u}=n,p;if(i==="multiplicative")p=(y,T,O,R,E,v)=>s.mul014(R,y,o.mul(T,E),o.mul(O,v));else if(i==="divisive")p=(y,T,O,R,E,v)=>s.mul034(R,o.mul(O,v),o.mul(T,E),y);else throw new Error("bls: unknown twist type");let d=o.div(o.ONE,o.mul(o.ONE,Pl));function l(y,T,O,R){let E=o.sqr(O),v=o.sqr(R),w=o.mulByB(o.mul(v,dn)),I=o.mul(w,dn),B=o.sub(o.sub(o.sqr(o.add(O,R)),v),E),A=o.sub(w,E),b=o.mul(o.sqr(T),dn),N=o.neg(B);return y.push([A,b,N]),T=o.mul(o.mul(o.mul(o.sub(E,I),T),O),d),O=o.sub(o.sqr(o.mul(o.add(E,I),d)),o.mul(o.sqr(w),dn)),R=o.mul(E,B),{Rx:T,Ry:O,Rz:R}}function f(y,T,O,R,E,v){let w=o.sub(O,o.mul(v,R)),I=o.sub(T,o.mul(E,R)),B=o.sub(o.mul(w,E),o.mul(I,v)),A=o.neg(w),b=I;y.push([B,A,b]);let N=o.sqr(I),P=o.mul(N,I),V=o.mul(N,T),q=o.add(o.sub(P,o.mul(V,Pl)),o.mul(o.sqr(w),R));return T=o.mul(I,q),O=o.sub(o.mul(o.sub(V,q),w),o.mul(P,O)),R=o.mul(R,P),{Rx:T,Ry:O,Rz:R}}let h=Wp(a),_=sr(y=>{let T=y,{x:O,y:R}=T.toAffine(),E=O,v=R,w=o.neg(R),I=E,B=v,A=o.ONE,b=[];for(let N of h){let P=[];({Rx:I,Ry:B,Rz:A}=l(P,I,B,A)),N&&({Rx:I,Ry:B,Rz:A}=f(P,I,B,A,E,N===-1?w:v)),b.push(P)}if(u){let N=b[b.length-1];u(I,B,A,E,v,f.bind(null,N))}return b});function g(y,T=!1){let O=s.ONE;if(y.length){let R=y[0][0].length;for(let E=0;E<R;E++){O=s.sqr(O);for(let[v,w,I]of y)for(let[B,A,b]of v[E])O=p(B,A,b,O,w,I)}}return c&&(O=s.conjugate(O)),T?s.finalExponentiate(O):O}function m(y,T=!0){let O=[];Ze(t,y.map(({g1:R})=>R)),Ze(r,y.map(({g2:R})=>R));for(let{g1:R,g2:E}of y){if(R.is0()||E.is0())throw new Error("pairing is not available for ZERO point");R.assertValidity(),E.assertValidity();let v=R.toAffine();O.push([_(E),v.x,v.y])}return g(O,T)}function x(y,T,O=!0){return m([{g1:y,g2:T}],O)}return{Fp12:s,millerLoopBatch:g,pairing:x,pairingBatch:m,calcPairingPrecomputes:_}}function Bl(e,t,r,n,o){let{Fp12:s,pairingBatch:i}=e;function a(d){return d instanceof t.Point?d:t.Point.fromHex(d)}function c(d){return d instanceof r.Point?d:r.Point.fromHex(d)}function u(d){if(!(d instanceof r.Point))throw new Error(`expected valid message hashed to ${o?"G1":"G2"} curve`);return d}let p=o?(d,l)=>({g1:l,g2:d}):(d,l)=>({g1:d,g2:l});return{getPublicKey(d){let l=eo(t.Point.Fn,d);return t.Point.BASE.multiply(l)},sign(d,l,f){if(f!=null)throw new Error("sign() expects 2 arguments");let h=eo(t.Point.Fn,l);return u(d).assertValidity(),d.multiply(h)},verify(d,l,f,h){if(h!=null)throw new Error("verify() expects 3 arguments");d=c(d),f=a(f);let _=f.negate(),g=t.Point.BASE,m=u(l),x=d,y=i([p(_,m),p(g,x)]);return s.eql(y,s.ONE)},verifyBatch(d,l,f){if(Xi(l),f.length!==l.length)throw new Error("amount of public keys and messages should be equal");let h=c(d),_=l,g=f.map(a),m=new Map;for(let T=0;T<g.length;T++){let O=g[T],R=_[T],E=m.get(R);E===void 0&&(E=[],m.set(R,E)),E.push(O)}let x=[],y=t.Point.BASE;try{for(let[T,O]of m){let R=O.reduce((E,v)=>E.add(v));x.push(p(R,T))}return x.push(p(y.negate(),h)),s.eql(i(x),s.ONE)}catch{return!1}},aggregatePublicKeys(d){Xi(d),d=d.map(f=>a(f));let l=d.reduce((f,h)=>f.add(h),t.Point.ZERO);return l.assertValidity(),l},aggregateSignatures(d){Xi(d),d=d.map(f=>c(f));let l=d.reduce((f,h)=>f.add(h),r.Point.ZERO);return l.assertValidity(),l},hash(d,l){ue(d);let f=l?{DST:l}:void 0;return r.hashToCurve(d,f)},Signature:n}}function Cl(e){let{Fp:t,Fr:r,Fp2:n,Fp6:o,Fp12:s}=e.fields,i=Zi(e.G1),a=Object.assign(i,Wi(i.Point,e.G1.mapToCurve,{...e.htfDefaults,...e.G1.htfDefaults})),c=Zi(e.G2),u=Object.assign(c,Wi(c.Point,e.G2.mapToCurve,{...e.htfDefaults,...e.G2.htfDefaults})),p=Yp(e.fields,a.Point,u.Point,{...e.params,postPrecompute:e.postPrecompute}),{millerLoopBatch:d,pairing:l,pairingBatch:f,calcPairingPrecomputes:h}=p,_=Bl(p,a,u,e.G2.Signature,!1),g=Bl(p,u,a,e.G1.ShortSignature,!0),m=e.randomBytes||$r,x=()=>{let S=ls(r.ORDER);return ji(m(S),r.ORDER)},y={randomSecretKey:x,randomPrivateKey:x,calcPairingPrecomputes:h},{ShortSignature:T}=e.G1,{Signature:O}=e.G2;function R(S,F){return S instanceof a.Point?S:g.hash(ae("point",S),F?.DST)}function E(S,F){return S instanceof u.Point?S:_.hash(ae("point",S),F?.DST)}function v(S){return _.getPublicKey(S).toBytes(!0)}function w(S){return g.getPublicKey(S).toBytes(!0)}function I(S,F,C){let D=E(S,C),k=_.sign(D,F);return S instanceof u.Point?k:O.toBytes(k)}function B(S,F,C){let D=R(S,C),k=g.sign(D,F);return S instanceof a.Point?k:T.toBytes(k)}function A(S,F,C,D){let k=E(F,D);return _.verify(S,k,C)}function b(S,F,C,D){let k=R(F,D);return g.verify(S,k,C)}function N(S){let F=_.aggregatePublicKeys(S);return S[0]instanceof a.Point?F:F.toBytes(!0)}function P(S){let F=_.aggregateSignatures(S);return S[0]instanceof u.Point?F:O.toBytes(F)}function V(S){let F=g.aggregateSignatures(S);return S[0]instanceof a.Point?F:T.toBytes(F)}function q(S,F,C,D){let k=F.map(ee=>E(ee,D));return _.verifyBatch(S,k,C)}return a.Point.BASE.precompute(4),{longSignatures:_,shortSignatures:g,millerLoopBatch:d,pairing:l,pairingBatch:f,verifyBatch:q,fields:{Fr:r,Fp:t,Fp2:n,Fp6:o,Fp12:s},params:{ateLoopSize:e.params.ateLoopSize,twistType:e.params.twistType,r:e.params.r,G1b:e.G1.b,G2b:e.G2.b},utils:y,getPublicKey:v,getPublicKeyForShortSignatures:w,sign:I,signShortSignature:B,verify:A,verifyShortSignature:b,aggregatePublicKeys:N,aggregateSignatures:P,aggregateShortSignatures:V,G1:a,G2:u,Signature:O,ShortSignature:T}}var Vl=BigInt(0),jt=BigInt(1),ke=BigInt(2),Dl=BigInt(3);function ra(e,t,r,n,o=1,s){let i=BigInt(s===void 0?n:s),a=r**BigInt(n),c=[];for(let u=0;u<o;u++){let p=BigInt(u+1),d=[];for(let l=0,f=jt;l<n;l++){let h=(p*f-p)/i%a;d.push(e.pow(t,h)),f*=r}c.push(d)}return c}function kl(e,t,r){let n=t.pow(r,(e.ORDER-jt)/Dl),o=t.pow(r,(e.ORDER-jt)/ke);function s(l,f){let h=t.mul(t.frobeniusMap(l,1),n),_=t.mul(t.frobeniusMap(f,1),o);return[h,_]}let i=t.pow(r,(e.ORDER**ke-jt)/Dl),a=t.pow(r,(e.ORDER**ke-jt)/ke);if(!t.eql(a,t.neg(t.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(l,f){return[t.mul(l,i),t.neg(f)]}let u=l=>(f,h)=>{let _=h.toAffine(),g=l(_.x,_.y);return f.fromAffine({x:g[0],y:g[1]})},p=u(s),d=u(c);return{psi:s,psi2:c,G2psi:p,G2psi2:d,PSI_X:n,PSI_Y:o,PSI2_X:i,PSI2_Y:a}}var Ul=(e,t)=>{if(t.length!==2)throw new Error("invalid tuple");let r=t.map(n=>e.create(n));return{c0:r[0],c1:r[1]}},Qi=class{constructor(t,r={}){this.MASK=jt;let n=t.ORDER,o=n*n;this.Fp=t,this.ORDER=o,this.BITS=kt(o),this.BYTES=Math.ceil(kt(o)/8),this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO},this.Fp_NONRESIDUE=t.create(r.NONRESIDUE||BigInt(-1)),this.Fp_div2=t.div(t.ONE,ke),this.NONRESIDUE=Ul(t,r.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=ra(t,this.Fp_NONRESIDUE,t.ORDER,2)[0],this.mulByB=r.Fp2mulByB,Object.seal(this)}fromBigTuple(t){return Ul(this.Fp,t)}create(t){return t}isValid({c0:t,c1:r}){function n(o,s){return typeof o=="bigint"&&Vl<=o&&o<s}return n(t,this.ORDER)&&n(r,this.ORDER)}is0({c0:t,c1:r}){return this.Fp.is0(t)&&this.Fp.is0(r)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}eql({c0:t,c1:r},{c0:n,c1:o}){return this.Fp.eql(t,n)&&this.Fp.eql(r,o)}neg({c0:t,c1:r}){return{c0:this.Fp.neg(t),c1:this.Fp.neg(r)}}pow(t,r){return Zn(this,t,r)}invertBatch(t){return Je(this,t)}add(t,r){let{c0:n,c1:o}=t,{c0:s,c1:i}=r;return{c0:this.Fp.add(n,s),c1:this.Fp.add(o,i)}}sub({c0:t,c1:r},{c0:n,c1:o}){return{c0:this.Fp.sub(t,n),c1:this.Fp.sub(r,o)}}mul({c0:t,c1:r},n){let{Fp:o}=this;if(typeof n=="bigint")return{c0:o.mul(t,n),c1:o.mul(r,n)};let{c0:s,c1:i}=n,a=o.mul(t,s),c=o.mul(r,i),u=o.sub(a,c),p=o.sub(o.mul(o.add(t,r),o.add(s,i)),o.add(a,c));return{c0:u,c1:p}}sqr({c0:t,c1:r}){let{Fp:n}=this,o=n.add(t,r),s=n.sub(t,r),i=n.add(t,t);return{c0:n.mul(o,s),c1:n.mul(i,r)}}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}div(t,r){let{Fp:n}=this;return this.mul(t,typeof r=="bigint"?n.inv(n.create(r)):this.inv(r))}inv({c0:t,c1:r}){let{Fp:n}=this,o=n.inv(n.create(t*t+r*r));return{c0:n.mul(o,n.create(t)),c1:n.mul(o,n.create(-r))}}sqrt(t){let{Fp:r}=this,n=this,{c0:o,c1:s}=t;if(r.is0(s))return Jn(r,o)===1?n.create({c0:r.sqrt(o),c1:r.ZERO}):n.create({c0:r.ZERO,c1:r.sqrt(r.div(o,this.Fp_NONRESIDUE))});let i=r.sqrt(r.sub(r.sqr(o),r.mul(r.sqr(s),this.Fp_NONRESIDUE))),a=r.mul(r.add(i,o),this.Fp_div2);Jn(r,a)===-1&&(a=r.sub(a,i));let u=r.sqrt(a),p=n.create({c0:u,c1:r.div(r.mul(s,this.Fp_div2),u)});if(!n.eql(n.sqr(p),t))throw new Error("Cannot find square root");let d=p,l=n.neg(d),{re:f,im:h}=n.reim(d),{re:_,im:g}=n.reim(l);return h>g||h===g&&f>_?d:l}isOdd(t){let{re:r,im:n}=this.reim(t),o=r%ke,s=r===Vl,i=n%ke;return BigInt(o||s&&i)==jt}fromBytes(t){let{Fp:r}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return{c0:r.fromBytes(t.subarray(0,r.BYTES)),c1:r.fromBytes(t.subarray(r.BYTES))}}toBytes({c0:t,c1:r}){return K(this.Fp.toBytes(t),this.Fp.toBytes(r))}cmov({c0:t,c1:r},{c0:n,c1:o},s){return{c0:this.Fp.cmov(t,n,s),c1:this.Fp.cmov(r,o,s)}}reim({c0:t,c1:r}){return{re:t,im:r}}Fp4Square(t,r){let n=this,o=n.sqr(t),s=n.sqr(r);return{first:n.add(n.mulByNonresidue(s),o),second:n.sub(n.sub(n.sqr(n.add(t,r)),o),s)}}mulByNonresidue({c0:t,c1:r}){return this.mul({c0:t,c1:r},this.NONRESIDUE)}frobeniusMap({c0:t,c1:r},n){return{c0:t,c1:this.Fp.mul(r,this.FROBENIUS_COEFFICIENTS[n%2])}}},ea=class{constructor(t){this.MASK=jt,this.Fp2=t,this.ORDER=t.ORDER,this.BITS=3*t.BITS,this.BYTES=3*t.BYTES,this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO,c2:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO,c2:t.ZERO};let{Fp:r}=t,n=ra(t,t.NONRESIDUE,r.ORDER,6,2,3);this.FROBENIUS_COEFFICIENTS_1=n[0],this.FROBENIUS_COEFFICIENTS_2=n[1],Object.seal(this)}add({c0:t,c1:r,c2:n},{c0:o,c1:s,c2:i}){let{Fp2:a}=this;return{c0:a.add(t,o),c1:a.add(r,s),c2:a.add(n,i)}}sub({c0:t,c1:r,c2:n},{c0:o,c1:s,c2:i}){let{Fp2:a}=this;return{c0:a.sub(t,o),c1:a.sub(r,s),c2:a.sub(n,i)}}mul({c0:t,c1:r,c2:n},o){let{Fp2:s}=this;if(typeof o=="bigint")return{c0:s.mul(t,o),c1:s.mul(r,o),c2:s.mul(n,o)};let{c0:i,c1:a,c2:c}=o,u=s.mul(t,i),p=s.mul(r,a),d=s.mul(n,c);return{c0:s.add(u,s.mulByNonresidue(s.sub(s.mul(s.add(r,n),s.add(a,c)),s.add(p,d)))),c1:s.add(s.sub(s.mul(s.add(t,r),s.add(i,a)),s.add(u,p)),s.mulByNonresidue(d)),c2:s.sub(s.add(p,s.mul(s.add(t,n),s.add(i,c))),s.add(u,d))}}sqr({c0:t,c1:r,c2:n}){let{Fp2:o}=this,s=o.sqr(t),i=o.mul(o.mul(t,r),ke),a=o.mul(o.mul(r,n),ke),c=o.sqr(n);return{c0:o.add(o.mulByNonresidue(a),s),c1:o.add(o.mulByNonresidue(c),i),c2:o.sub(o.sub(o.add(o.add(i,o.sqr(o.add(o.sub(t,r),n))),a),s),c)}}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}create(t){return t}isValid({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return o.isValid(t)&&o.isValid(r)&&o.isValid(n)}is0({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return o.is0(t)&&o.is0(r)&&o.is0(n)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return{c0:o.neg(t),c1:o.neg(r),c2:o.neg(n)}}eql({c0:t,c1:r,c2:n},{c0:o,c1:s,c2:i}){let{Fp2:a}=this;return a.eql(t,o)&&a.eql(r,s)&&a.eql(n,i)}sqrt(t){return sn()}div(t,r){let{Fp2:n}=this,{Fp:o}=n;return this.mul(t,typeof r=="bigint"?o.inv(o.create(r)):this.inv(r))}pow(t,r){return Zn(this,t,r)}invertBatch(t){return Je(this,t)}inv({c0:t,c1:r,c2:n}){let{Fp2:o}=this,s=o.sub(o.sqr(t),o.mulByNonresidue(o.mul(n,r))),i=o.sub(o.mulByNonresidue(o.sqr(n)),o.mul(t,r)),a=o.sub(o.sqr(r),o.mul(t,n)),c=o.inv(o.add(o.mulByNonresidue(o.add(o.mul(n,i),o.mul(r,a))),o.mul(t,s)));return{c0:o.mul(c,s),c1:o.mul(c,i),c2:o.mul(c,a)}}fromBytes(t){let{Fp2:r}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);let n=r.BYTES;return{c0:r.fromBytes(t.subarray(0,n)),c1:r.fromBytes(t.subarray(n,n*2)),c2:r.fromBytes(t.subarray(2*n))}}toBytes({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return K(o.toBytes(t),o.toBytes(r),o.toBytes(n))}cmov({c0:t,c1:r,c2:n},{c0:o,c1:s,c2:i},a){let{Fp2:c}=this;return{c0:c.cmov(t,o,a),c1:c.cmov(r,s,a),c2:c.cmov(n,i,a)}}fromBigSix(t){let{Fp2:r}=this;if(!Array.isArray(t)||t.length!==6)throw new Error("invalid Fp6 usage");return{c0:r.fromBigTuple(t.slice(0,2)),c1:r.fromBigTuple(t.slice(2,4)),c2:r.fromBigTuple(t.slice(4,6))}}frobeniusMap({c0:t,c1:r,c2:n},o){let{Fp2:s}=this;return{c0:s.frobeniusMap(t,o),c1:s.mul(s.frobeniusMap(r,o),this.FROBENIUS_COEFFICIENTS_1[o%6]),c2:s.mul(s.frobeniusMap(n,o),this.FROBENIUS_COEFFICIENTS_2[o%6])}}mulByFp2({c0:t,c1:r,c2:n},o){let{Fp2:s}=this;return{c0:s.mul(t,o),c1:s.mul(r,o),c2:s.mul(n,o)}}mulByNonresidue({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return{c0:o.mulByNonresidue(n),c1:t,c2:r}}mul1({c0:t,c1:r,c2:n},o){let{Fp2:s}=this;return{c0:s.mulByNonresidue(s.mul(n,o)),c1:s.mul(t,o),c2:s.mul(r,o)}}mul01({c0:t,c1:r,c2:n},o,s){let{Fp2:i}=this,a=i.mul(t,o),c=i.mul(r,s);return{c0:i.add(i.mulByNonresidue(i.sub(i.mul(i.add(r,n),s),c)),a),c1:i.sub(i.sub(i.mul(i.add(o,s),i.add(t,r)),a),c),c2:i.add(i.sub(i.mul(i.add(t,n),o),a),c)}}},ta=class{constructor(t,r){this.MASK=jt;let{Fp2:n}=t,{Fp:o}=n;this.Fp6=t,this.ORDER=n.ORDER,this.BITS=2*t.BITS,this.BYTES=2*t.BYTES,this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO},this.FROBENIUS_COEFFICIENTS=ra(n,n.NONRESIDUE,o.ORDER,12,1,6)[0],this.X_LEN=r.X_LEN,this.finalExponentiate=r.Fp12finalExponentiate}create(t){return t}isValid({c0:t,c1:r}){let{Fp6:n}=this;return n.isValid(t)&&n.isValid(r)}is0({c0:t,c1:r}){let{Fp6:n}=this;return n.is0(t)&&n.is0(r)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:r}){let{Fp6:n}=this;return{c0:n.neg(t),c1:n.neg(r)}}eql({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:s}=this;return s.eql(t,n)&&s.eql(r,o)}sqrt(t){sn()}inv({c0:t,c1:r}){let{Fp6:n}=this,o=n.inv(n.sub(n.sqr(t),n.mulByNonresidue(n.sqr(r))));return{c0:n.mul(t,o),c1:n.neg(n.mul(r,o))}}div(t,r){let{Fp6:n}=this,{Fp2:o}=n,{Fp:s}=o;return this.mul(t,typeof r=="bigint"?s.inv(s.create(r)):this.inv(r))}pow(t,r){return Zn(this,t,r)}invertBatch(t){return Je(this,t)}add({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:s}=this;return{c0:s.add(t,n),c1:s.add(r,o)}}sub({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:s}=this;return{c0:s.sub(t,n),c1:s.sub(r,o)}}mul({c0:t,c1:r},n){let{Fp6:o}=this;if(typeof n=="bigint")return{c0:o.mul(t,n),c1:o.mul(r,n)};let{c0:s,c1:i}=n,a=o.mul(t,s),c=o.mul(r,i);return{c0:o.add(a,o.mulByNonresidue(c)),c1:o.sub(o.mul(o.add(t,r),o.add(s,i)),o.add(a,c))}}sqr({c0:t,c1:r}){let{Fp6:n}=this,o=n.mul(t,r);return{c0:n.sub(n.sub(n.mul(n.add(n.mulByNonresidue(r),t),n.add(t,r)),o),n.mulByNonresidue(o)),c1:n.add(o,o)}}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}fromBytes(t){let{Fp6:r}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return{c0:r.fromBytes(t.subarray(0,r.BYTES)),c1:r.fromBytes(t.subarray(r.BYTES))}}toBytes({c0:t,c1:r}){let{Fp6:n}=this;return K(n.toBytes(t),n.toBytes(r))}cmov({c0:t,c1:r},{c0:n,c1:o},s){let{Fp6:i}=this;return{c0:i.cmov(t,n,s),c1:i.cmov(r,o,s)}}fromBigTwelve(t){let{Fp6:r}=this;return{c0:r.fromBigSix(t.slice(0,6)),c1:r.fromBigSix(t.slice(6,12))}}frobeniusMap(t,r){let{Fp6:n}=this,{Fp2:o}=n,{c0:s,c1:i,c2:a}=n.frobeniusMap(t.c1,r),c=this.FROBENIUS_COEFFICIENTS[r%12];return{c0:n.frobeniusMap(t.c0,r),c1:n.create({c0:o.mul(s,c),c1:o.mul(i,c),c2:o.mul(a,c)})}}mulByFp2({c0:t,c1:r},n){let{Fp6:o}=this;return{c0:o.mulByFp2(t,n),c1:o.mulByFp2(r,n)}}conjugate({c0:t,c1:r}){return{c0:t,c1:this.Fp6.neg(r)}}mul014({c0:t,c1:r},n,o,s){let{Fp6:i}=this,{Fp2:a}=i,c=i.mul01(t,n,o),u=i.mul1(r,s);return{c0:i.add(i.mulByNonresidue(u),c),c1:i.sub(i.sub(i.mul01(i.add(r,t),n,a.add(o,s)),c),u)}}mul034({c0:t,c1:r},n,o,s){let{Fp6:i}=this,{Fp2:a}=i,c=i.create({c0:a.mul(t.c0,n),c1:a.mul(t.c1,n),c2:a.mul(t.c2,n)}),u=i.mul01(r,o,s),p=i.mul01(i.add(t,r),a.add(n,o),s);return{c0:i.add(i.mulByNonresidue(u),c),c1:i.sub(p,i.add(c,u))}}_cyclotomicSquare({c0:t,c1:r}){let{Fp6:n}=this,{Fp2:o}=n,{c0:s,c1:i,c2:a}=t,{c0:c,c1:u,c2:p}=r,{first:d,second:l}=o.Fp4Square(s,u),{first:f,second:h}=o.Fp4Square(c,a),{first:_,second:g}=o.Fp4Square(i,p),m=o.mulByNonresidue(g);return{c0:n.create({c0:o.add(o.mul(o.sub(d,s),ke),d),c1:o.add(o.mul(o.sub(f,i),ke),f),c2:o.add(o.mul(o.sub(_,a),ke),_)}),c1:n.create({c0:o.add(o.mul(o.add(m,c),ke),m),c1:o.add(o.mul(o.add(l,u),ke),l),c2:o.add(o.mul(o.add(h,p),ke),h)})}}_cyclotomicExp(t,r){let n=this.ONE;for(let o=this.X_LEN-1;o>=0;o--)n=this._cyclotomicSquare(n),fl(r,o)&&(n=this.mul(n,t));return n}};function Ll(e){let t=De(e.ORDER),r=new Qi(t,e),n=new ea(r),o=new ta(n,e);return{Fp:t,Fp2:r,Fp6:n,Fp12:o}}var Ie=BigInt(0),ps=BigInt(1),Xe=BigInt(2),fs=BigInt(3),to=BigInt(4),ar=BigInt("0xd201000000010000"),Jp=kt(ar),Fr={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:Ie,b:to,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},Zp=De(Fr.n,{modFromBytes:!0,isLE:!0}),{Fp:U,Fp2:G,Fp6:Xp,Fp12:J}=Ll({ORDER:Fr.p,X_LEN:Jp,FP2_NONRESIDUE:[ps,ps],Fp2mulByB:({c0:e,c1:t})=>{let r=U.mul(e,to),n=U.mul(t,to);return{c0:U.sub(r,n),c1:U.add(r,n)}},Fp12finalExponentiate:e=>{let t=ar,r=J.div(J.frobeniusMap(e,6),e),n=J.mul(J.frobeniusMap(r,2),r),o=J.conjugate(J._cyclotomicExp(n,t)),s=J.mul(J.conjugate(J._cyclotomicSquare(n)),o),i=J.conjugate(J._cyclotomicExp(s,t)),a=J.conjugate(J._cyclotomicExp(i,t)),c=J.mul(J.conjugate(J._cyclotomicExp(a,t)),J._cyclotomicSquare(o)),u=J.conjugate(J._cyclotomicExp(c,t)),p=J.frobeniusMap(J.mul(o,a),2),d=J.frobeniusMap(J.mul(i,n),3),l=J.frobeniusMap(J.mul(c,J.conjugate(n)),1),f=J.mul(J.mul(u,J.conjugate(s)),n);return J.mul(J.mul(J.mul(p,d),l),f)}}),{G2psi:ql,G2psi2:Qp}=kl(U,G,G.div(G.ONE,G.NONRESIDUE)),na=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:U.ORDER,m:2,k:128,expand:"xmd",hash:ve}),ia={p:G.ORDER,n:Fr.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:G.ZERO,b:G.fromBigTuple([to,to]),Gx:G.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:G.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},hs=ro(U.toBytes(Ie),{infinity:!0,compressed:!0});function ms(e){e=e.slice();let t=e[0]&224,r=!!(t>>7&1),n=!!(t>>6&1),o=!!(t>>5&1);return e[0]&=31,{compressed:r,infinity:n,sort:o,value:e}}function ro(e,t){if(e[0]&224)throw new Error("setMask: non-empty mask");return t.compressed&&(e[0]|=128),t.infinity&&(e[0]|=64),t.sort&&(e[0]|=32),e}function ef(e,t,r){let{BYTES:n,ORDER:o}=U,s=t.is0(),{x:i,y:a}=t.toAffine();if(r){if(s)return hs.slice();let c=!!(a*Xe/o);return ro(ye(i,n),{compressed:!0,sort:c})}else return s?K(Uint8Array.of(64),new Uint8Array(2*n-1)):K(ye(i,n),ye(a,n))}function oa(e){e.assertValidity();let{BYTES:t,ORDER:r}=U,{x:n,y:o}=e.toAffine();if(e.is0())return hs.slice();let s=!!(o*Xe/r);return ro(ye(n,t),{compressed:!0,sort:s})}function tf(e){let{compressed:t,infinity:r,sort:n,value:o}=ms(e),{BYTES:s,ORDER:i}=U;if(o.length===48&&t){let a=Ke(o),c=U.create(a&ut(U.BITS));if(r){if(c!==Ie)throw new Error("invalid G1 point: non-empty, at infinity, with compression");return{x:Ie,y:Ie}}let u=U.add(U.pow(c,fs),U.create(Fr.b)),p=U.sqrt(u);if(!p)throw new Error("invalid G1 point: compressed point");return p*Xe/i!==BigInt(n)&&(p=U.neg(p)),{x:U.create(c),y:U.create(p)}}else if(o.length===96&&!t){let a=Ke(o.subarray(0,s)),c=Ke(o.subarray(s));if(r){if(a!==Ie||c!==Ie)throw new Error("G1: non-empty point at infinity");return no.G1.Point.ZERO.toAffine()}return{x:U.create(a),y:U.create(c)}}else throw new Error("invalid G1 point: expected 48/96 bytes")}function Ml(e){let{infinity:t,sort:r,value:n}=ms(ae("signatureHex",e,48)),o=U.ORDER,s=no.G1.Point,i=Ke(n);if(t)return s.ZERO;let a=U.create(i&ut(U.BITS)),c=U.add(U.pow(a,fs),U.create(Fr.b)),u=U.sqrt(c);if(!u)throw new Error("invalid G1 point: compressed");let p=BigInt(r);u*Xe/o!==p&&(u=U.neg(u));let d=s.fromAffine({x:a,y:u});return d.assertValidity(),d}function rf(e,t,r){let{BYTES:n,ORDER:o}=U,s=t.is0(),{x:i,y:a}=t.toAffine();if(r){if(s)return K(hs,ye(Ie,n));let c=!!(a.c1===Ie?a.c0*Xe/o:a.c1*Xe/o);return K(ro(ye(i.c1,n),{compressed:!0,sort:c}),ye(i.c0,n))}else{if(s)return K(Uint8Array.of(64),new Uint8Array(4*n-1));let{re:c,im:u}=G.reim(i),{re:p,im:d}=G.reim(a);return K(ye(u,n),ye(c,n),ye(d,n),ye(p,n))}}function sa(e){e.assertValidity();let{BYTES:t}=U;if(e.is0())return K(hs,ye(Ie,t));let{x:r,y:n}=e.toAffine(),{re:o,im:s}=G.reim(r),{re:i,im:a}=G.reim(n),u=!!((a>Ie?a*Xe:i*Xe)/U.ORDER&ps),p=o;return K(ro(ye(s,t),{sort:u,compressed:!0}),ye(p,t))}function nf(e){let{BYTES:t,ORDER:r}=U,{compressed:n,infinity:o,sort:s,value:i}=ms(e);if(!n&&!o&&s||!n&&o&&s||s&&o&&n)throw new Error("invalid encoding flag: "+(e[0]&224));let a=(c,u,p)=>Ke(c.slice(u,p));if(i.length===96&&n){if(o){if(i.reduce((h,_)=>h!==0?_+1:_,0)>0)throw new Error("invalid G2 point: compressed");return{x:G.ZERO,y:G.ZERO}}let c=a(i,0,t),u=a(i,t,2*t),p=G.create({c0:U.create(u),c1:U.create(c)}),d=G.add(G.pow(p,fs),ia.b),l=G.sqrt(d),f=l.c1===Ie?l.c0*Xe/r:l.c1*Xe/r?ps:Ie;return l=s&&f>0?l:G.neg(l),{x:p,y:l}}else if(i.length===192&&!n){if(o){if(i.reduce((l,f)=>l!==0?f+1:f,0)>0)throw new Error("invalid G2 point: uncompressed");return{x:G.ZERO,y:G.ZERO}}let c=a(i,0*t,1*t),u=a(i,1*t,2*t),p=a(i,2*t,3*t),d=a(i,3*t,4*t);return{x:G.fromBigTuple([u,c]),y:G.fromBigTuple([d,p])}}else throw new Error("invalid G2 point: expected 96/192 bytes")}function jl(e){let{ORDER:t}=U,{infinity:r,sort:n,value:o}=ms(ae("signatureHex",e)),s=no.G2.Point,i=o.length/2;if(i!==48&&i!==96)throw new Error("invalid compressed signature length, expected 96/192 bytes");let a=Ke(o.slice(0,i)),c=Ke(o.slice(i));if(r)return s.ZERO;let u=U.create(a&ut(U.BITS)),p=U.create(c),d=G.create({c0:p,c1:u}),l=G.add(G.pow(d,fs),ia.b),f=G.sqrt(l);if(!f)throw new Error("Failed to find a square root");let{re:h,im:_}=G.reim(f),g=BigInt(n),m=_>Ie&&_*Xe/t!==g,x=_===Ie&&h*Xe/t!==g;(m||x)&&(f=G.neg(f));let y=s.fromAffine({x:d,y:f});return y.assertValidity(),y}var no=Cl({fields:{Fp:U,Fp2:G,Fp6:Xp,Fp12:J,Fr:Zp},G1:{...Fr,Fp:U,htfDefaults:{...na,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(e,t)=>{let r=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),n=new e(U.mul(t.X,r),t.Y,t.Z);return t.multiplyUnsafe(ar).negate().multiplyUnsafe(ar).equals(n)},clearCofactor:(e,t)=>t.multiplyUnsafe(ar).add(t),mapToCurve:lf,fromBytes:tf,toBytes:ef,ShortSignature:{fromBytes(e){return ue(e),Ml(e)},fromHex(e){return Ml(e)},toBytes(e){return oa(e)},toRawBytes(e){return oa(e)},toHex(e){return M(oa(e))}}},G2:{...ia,Fp:G,hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...na},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:uf,isTorsionFree:(e,t)=>t.multiplyUnsafe(ar).negate().equals(ql(e,t)),clearCofactor:(e,t)=>{let r=ar,n=t.multiplyUnsafe(r).negate(),o=ql(e,t),s=t.double();return s=Qp(e,s),s=s.subtract(o),o=n.add(o),o=o.multiplyUnsafe(r).negate(),s=s.add(o),s=s.subtract(n),s.subtract(t)},fromBytes:nf,toBytes:rf,Signature:{fromBytes(e){return ue(e),jl(e)},fromHex(e){return jl(e)},toBytes(e){return sa(e)},toRawBytes(e){return sa(e)},toHex(e){return M(sa(e))}}},params:{ateLoopSize:ar,r:Fr.n,xNegative:!0,twistType:"multiplicative"},htfDefaults:na,hash:ve}),of=zi(G,[[["0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6"],["0x0","0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d"],["0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1","0x0"]],[["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63"],["0xc","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f"],["0x1","0x0"]],[["0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706","0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706"],["0x0","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f"],["0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10","0x0"]],[["0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb"],["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3"],["0x12","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99"],["0x1","0x0"]]].map(e=>e.map(t=>G.fromBigTuple(t.map(BigInt))))),sf=zi(U,[["0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7","0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb","0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0","0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861","0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9","0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983","0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84","0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e","0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317","0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e","0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b","0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229"],["0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c","0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff","0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19","0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8","0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e","0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5","0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a","0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e","0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641","0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"],["0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33","0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696","0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6","0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb","0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb","0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0","0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2","0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29","0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587","0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30","0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132","0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e","0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8","0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133","0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b","0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604"],["0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1","0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d","0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2","0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416","0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d","0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac","0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c","0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9","0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a","0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55","0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8","0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092","0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc","0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7","0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),af=Ji(U,{A:U.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:U.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:U.create(BigInt(11))}),cf=Ji(G,{A:G.create({c0:U.create(Ie),c1:U.create(BigInt(240))}),B:G.create({c0:U.create(BigInt(1012)),c1:U.create(BigInt(1012))}),Z:G.create({c0:U.create(BigInt(-2)),c1:U.create(BigInt(-1))})});function lf(e){let{x:t,y:r}=af(U.create(e[0]));return sf(t,r)}function uf(e){let{x:t,y:r}=cf(G.fromBigTuple(e));return of(t,r)}function Kl(e,t,r){let n=typeof e=="string"?e:M(e),o=typeof t=="string"?t:M(t),s=typeof r=="string"?r:M(r);return no.verifyShortSignature(o,s,n)}var pf=BigInt(1e6),aa=e=>pe(new st(e)),pn=e=>{let r=aa(e)/pf;return new Date(Number(r))};var $l=60*1e3,ff=60,hf=24,mf=hf*ff,_f=5,yf=5,gf=30*mf,Re;(function(e){e[e.Empty=0]="Empty",e[e.Fork=1]="Fork",e[e.Labeled=2]="Labeled",e[e.Leaf=3]="Leaf",e[e.Pruned=4]="Pruned"})(Re||(Re={}));function xf(e,t){for(let r=0;r<e.length;r++)if(e[r]>t[r])return!0;return!1}var cr=class e{#e=!1;#t=void 0;static async create(t){let r=e.createUnverified(t);return await r.verify(),r}static createUnverified(t){return new e(t.certificate,t.rootKey,t.canisterId,t.blsVerify??Kl,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(t,r,n,o,s=_f,i=!1,a){this._rootKey=r,this._canisterId=n,this._blsVerify=o,this._maxAgeInMinutes=s,this.#e=i,this.cert=je(t),a&&"getTimeDiffMsecs"in a&&"hasSyncedTime"in a&&"syncTime"in a&&(this.#t=a)}lookup_path(t){return Br(t,this.cert.tree)}lookup_subtree(t){return gs(t,this.cert.tree)}async verify(){let t=await _s(this.cert.tree),r=await this._checkDelegationAndGetKey(this.cert.delegation),n=this.cert.signature,o=wf(r),s=K(so("ic-state-root"),t),i=Ae(this.lookup_path(["time"]));if(!i)throw te.fromCode(new Zt("Certificate does not contain a time"));if(!this.#e){let a=this.#t?.getTimeDiffMsecs()??0,c=this._maxAgeInMinutes*$l,u=new Date,p=u.getTime()+a,d=p-c,l=p+yf*$l,f=pn(i),h=f.getTime()<d,_=f.getTime()>l;if((h||_)&&this.#t&&!this.#t.hasSyncedTime())return await this.#t.syncTime(this._canisterId),await this.verify();if(h)throw Pe.fromCode(new yr(this._maxAgeInMinutes,f,u,a,"past"));if(_)throw this.#t?.hasSyncedTime()?he.fromCode(new Be("System time has been synced with the IC network, but certificate is still too far in the future.")):Pe.fromCode(new yr(5,f,u,a,"future"))}try{if(!await this._blsVerify(o,n,s))throw Pe.fromCode(new Zt("Invalid signature"))}catch(a){throw Pe.fromCode(new Zt("Signature verification failed",a))}}async _checkDelegationAndGetKey(t){if(!t)return this._rootKey;let r=e.createUnverified({certificate:t.certificate,rootKey:this._rootKey,canisterId:this._canisterId,blsVerify:this._blsVerify,disableTimeVerification:this.#e,maxAgeInMinutes:gf,agent:this.#t});if(r.cert.delegation)throw te.fromCode(new Ao);await r.verify();let n=t.subnet_id,o=L.fromUint8Array(n);if(!ca({canisterId:this._canisterId,subnetId:o,tree:r.cert.tree}))throw Pe.fromCode(new Hr(this._canisterId,o));let i=Ae(r.lookup_path(["subnet",n,"public_key"]));if(!i)throw Pe.fromCode(new So(`Could not find subnet key for subnet ID ${o.toText()}`));return i}},oo=be("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),bf=96;function wf(e){let t=oo.byteLength+bf;if(e.byteLength!==t)throw te.fromCode(new zr(t,e.byteLength));let r=e.slice(0,oo.byteLength);if(!Or(r,oo))throw te.fromCode(new Fo(oo,r));return e.slice(oo.byteLength)}function Ae(e){if(e.status===$e.Found&&e.value instanceof Uint8Array)return e.value}async function _s(e){switch(e[0]){case Re.Empty:return ve(so("ic-hashtree-empty"));case Re.Pruned:return e[1];case Re.Leaf:return ve(K(so("ic-hashtree-leaf"),e[1]));case Re.Labeled:return ve(K(so("ic-hashtree-labeled"),e[1],await _s(e[2])));case Re.Fork:return ve(K(so("ic-hashtree-fork"),await _s(e[1]),await _s(e[2])));default:throw er}}function so(e){let t=new Uint8Array([e.length]),r=new TextEncoder().encode(e);return K(t,r)}function Hl(e){return typeof e[0]=="string"?Q(e[0]):e[0]}var $e;(function(e){e.Unknown="Unknown",e.Absent="Absent",e.Found="Found",e.Error="Error"})($e||($e={}));var Pr;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found"})(Pr||(Pr={}));var ie;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found",e.Less="Less",e.Greater="Greater"})(ie||(ie={}));function Br(e,t){if(e.length===0)switch(t[0]){case Re.Empty:return{status:$e.Absent};case Re.Leaf:{if(!t[1])throw he.fromCode(new Qt("Invalid tree structure for leaf"));if(t[1]instanceof Uint8Array)return{status:$e.Found,value:t[1].slice(t[1].byteOffset,t[1].byteLength+t[1].byteOffset)};throw er}case Re.Pruned:return{status:$e.Unknown};case Re.Labeled:case Re.Fork:return{status:$e.Error};default:throw er}let r=Hl(e),n=io(r,t);switch(n.status){case ie.Found:return Br(e.slice(1),n.value);case ie.Absent:case ie.Greater:case ie.Less:return{status:$e.Absent};case ie.Unknown:return{status:$e.Unknown};default:throw er}}function gs(e,t){if(e.length===0)return{status:Pr.Found,value:t};let r=Hl(e),n=io(r,t);switch(n.status){case ie.Found:return gs(e.slice(1),n.value);case ie.Unknown:return{status:Pr.Unknown};case ie.Absent:case ie.Greater:case ie.Less:return{status:Pr.Absent};default:throw er}}function ys(e){switch(e[0]){case Re.Empty:return[];case Re.Fork:return ys(e[1]).concat(ys(e[2]));default:return[e]}}function io(e,t){switch(t[0]){case Re.Labeled:return xf(e,t[1])?{status:ie.Greater}:Or(e,t[1])?{status:ie.Found,value:t[2]}:{status:ie.Less};case Re.Fork:{let r=io(e,t[1]);switch(r.status){case ie.Greater:{let n=io(e,t[2]);return n.status===ie.Less?{status:ie.Absent}:n}case ie.Unknown:{let n=io(e,t[2]);return n.status===ie.Less?{status:ie.Unknown}:n}default:return r}}case Re.Pruned:return{status:ie.Unknown};default:return{status:ie.Absent}}}function ca(e){let{canisterId:t,subnetId:r,tree:n}=e,o=Br(["subnet",r.toUint8Array(),"canister_ranges"],n);if(o.status!==$e.Found)throw te.fromCode(new St(`Could not find canister ranges for subnet ${r.toText()}`,o.status));if(!(o.value instanceof Uint8Array))throw te.fromCode(new Gr(`Could not find canister ranges for subnet ${r.toText()}`));return je(o.value).map(c=>[L.fromUint8Array(c[0]),L.fromUint8Array(c[1])]).some(c=>c[0].ltEq(t)&&c[1].gtEq(t))}var la=async e=>{let{agent:t,paths:r,disableCertificateTimeVerification:n=!1}=e,o=L.from(e.canisterId),s=[...new Set(r)],i=new Map,a=s.map((c,u)=>{let p=Nf(c,o);return(async()=>{try{if(t.rootKey===null)throw we.fromCode(new mt);let d=t.rootKey,l=await t.readState(o,{paths:[p]}),f=await cr.create({certificate:l.certificate,rootKey:d,canisterId:o,disableTimeVerification:n,agent:t}),h=(m,x)=>{if(x==="subnet"){let y=Tf(l.certificate,o,d);return{path:x,data:y}}else return{path:x,data:Ae(m.lookup_path(p))}},{path:_,data:g}=h(f,s[u]);if(!g)console.warn(`Expected to find result for path ${_}, but instead found nothing.`),typeof _=="string"?i.set(_,null):i.set(_.key,null);else switch(_){case"time":{i.set(_,pn(g));break}case"controllers":{i.set(_,Of(g));break}case"module_hash":{i.set(_,M(g));break}case"subnet":{i.set(_,g);break}case"candid":{i.set(_,new TextDecoder().decode(g));break}default:if(typeof _!="string"&&"key"in _&&"path"in _)switch(_.decodeStrategy){case"raw":i.set(_.key,g);break;case"leb128":{i.set(_.key,aa(g));break}case"cbor":{i.set(_.key,je(g));break}case"hex":{i.set(_.key,M(g));break}case"utf-8":i.set(_.key,new TextDecoder().decode(g))}}}catch(d){if(d instanceof nt&&(d.hasCode(Zt)||d.hasCode(yr)))throw d;typeof c!="string"&&"key"in c&&"path"in c?i.set(c.key,null):i.set(c,null),console.group(),console.warn(`Expected to find result for path ${c}, but instead found nothing.`),console.warn(d),console.groupEnd()}})()});return await Promise.all(a),i},Tf=(e,t,r)=>{if(!t._isPrincipal)throw W.fromCode(new Be("Invalid canisterId"));let n=je(e),o=n.tree,s=n.delegation,i;if(s&&s.subnet_id?i=L.fromUint8Array(new Uint8Array(s.subnet_id)):!s&&typeof r<"u"?(i=L.selfAuthenticating(new Uint8Array(r)),s={subnet_id:i.toUint8Array(),certificate:new Uint8Array(0)}):(i=L.selfAuthenticating(L.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe").toUint8Array()),s={subnet_id:i.toUint8Array(),certificate:new Uint8Array(0)}),!ca({canisterId:t,subnetId:i,tree:o}))throw Pe.fromCode(new Hr(t,i));let c=gs(["subnet",s.subnet_id,"node"],o);if(c.status!==Pr.Found)throw te.fromCode(new St("Node not found",c.status));if(c.value instanceof Uint8Array)throw he.fromCode(new Qt("Invalid node tree"));let u=ys(c.value),p=new Map;return u.forEach(d=>{let l=L.from(d[1]).toText(),f=Br(["public_key"],d[2]);if(f.status!==$e.Found)throw te.fromCode(new St("Public key not found",f.status));let h=f.value;if(h.byteLength!==44)throw te.fromCode(new zr(44,h.byteLength));p.set(l,h)}),{subnetId:L.fromUint8Array(new Uint8Array(s.subnet_id)).toText(),nodeKeys:p}},Nf=(e,t)=>{let r=t.toUint8Array();switch(e){case"time":return[Q("time")];case"controllers":return[Q("canister"),r,Q("controllers")];case"module_hash":return[Q("canister"),r,Q("module_hash")];case"subnet":return[Q("subnet")];case"candid":return[Q("canister"),r,Q("metadata"),Q("candid:service")];default:if("key"in e&&"path"in e)if(typeof e.path=="string"||e.path instanceof Uint8Array){let n=e.path,o=typeof n=="string"?Q(n):n;return[Q("canister"),r,Q("metadata"),o]}else return e.path}throw he.fromCode(new Be(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))},Of=e=>je(e).map(r=>L.fromUint8Array(r));var lr=BigInt(0),Ne=BigInt(1),ua=BigInt(2),Ef=BigInt(8);function Rf(e,t,r,n){let o=e.sqr(r),s=e.sqr(n),i=e.add(e.mul(t.a,o),s),a=e.add(e.ONE,e.mul(t.d,e.mul(o,s)));return e.eql(i,a)}function vf(e,t={}){let r=us("edwards",e,t,t.FpFnLE),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i}=s;Lt(t,{},{uvRatio:"function"});let a=ua<<BigInt(o.BYTES*8)-Ne,c=g=>n.create(g),u=t.uvRatio||((g,m)=>{try{return{isValid:!0,value:n.sqrt(n.div(g,m))}}catch{return{isValid:!1,value:lr}}});if(!Rf(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function p(g,m,x=!1){let y=x?Ne:lr;return as("coordinate "+g,m,y,a),m}function d(g){if(!(g instanceof h))throw new Error("ExtendedPoint expected")}let l=sr((g,m)=>{let{X:x,Y:y,Z:T}=g,O=g.is0();m==null&&(m=O?Ef:n.inv(T));let R=c(x*m),E=c(y*m),v=n.mul(T,m);if(O)return{x:lr,y:Ne};if(v!==Ne)throw new Error("invZ was invalid");return{x:R,y:E}}),f=sr(g=>{let{a:m,d:x}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:y,Y:T,Z:O,T:R}=g,E=c(y*y),v=c(T*T),w=c(O*O),I=c(w*w),B=c(E*m),A=c(w*c(B+v)),b=c(I+c(x*c(E*v)));if(A!==b)throw new Error("bad point: equation left != right (1)");let N=c(y*T),P=c(O*R);if(N!==P)throw new Error("bad point: equation left != right (2)");return!0});class h{constructor(m,x,y,T){this.X=p("x",m),this.Y=p("y",x),this.Z=p("z",y,!0),this.T=p("t",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x,y}=m||{};return p("x",x),p("y",y),new h(x,y,Ne,c(x*y))}static fromBytes(m,x=!1){let y=n.BYTES,{a:T,d:O}=s;m=ki(or(m,y,"point")),vr(x,"zip215");let R=ki(m),E=m[y-1];R[y-1]=E&-129;let v=Ut(R),w=x?a:n.ORDER;as("point.y",v,lr,w);let I=c(v*v),B=c(I-Ne),A=c(O*I-T),{isValid:b,value:N}=u(B,A);if(!b)throw new Error("bad point: invalid y coordinate");let P=(N&Ne)===Ne,V=(E&128)!==0;if(!x&&N===lr&&V)throw new Error("bad point: x=0 and x_0=1");return V!==P&&(N=c(-N)),h.fromAffine({x:N,y:v})}static fromHex(m,x=!1){return h.fromBytes(ae("point",m),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,x=!0){return _.createCache(this,m),x||this.multiply(ua),this}assertValidity(){f(this)}equals(m){d(m);let{X:x,Y:y,Z:T}=this,{X:O,Y:R,Z:E}=m,v=c(x*E),w=c(O*T),I=c(y*E),B=c(R*T);return v===w&&I===B}is0(){return this.equals(h.ZERO)}negate(){return new h(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:m}=s,{X:x,Y:y,Z:T}=this,O=c(x*x),R=c(y*y),E=c(ua*c(T*T)),v=c(m*O),w=x+y,I=c(c(w*w)-O-R),B=v+R,A=B-E,b=v-R,N=c(I*A),P=c(B*b),V=c(I*b),q=c(A*B);return new h(N,P,q,V)}add(m){d(m);let{a:x,d:y}=s,{X:T,Y:O,Z:R,T:E}=this,{X:v,Y:w,Z:I,T:B}=m,A=c(T*v),b=c(O*w),N=c(E*y*B),P=c(R*I),V=c((T+O)*(v+w)-A-b),q=P-N,S=P+N,F=c(b-x*A),C=c(V*q),D=c(S*F),k=c(V*F),ee=c(q*S);return new h(C,D,ee,k)}subtract(m){return this.add(m.negate())}multiply(m){if(!o.isValidNot0(m))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:y}=_.cached(this,m,T=>Ze(h,T));return Ze(h,[x,y])[0]}multiplyUnsafe(m,x=h.ZERO){if(!o.isValid(m))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return m===lr?h.ZERO:this.is0()||m===Ne?this:_.unsafe(this,m,y=>Ze(h,y),x)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return _.unsafe(this,s.n).is0()}toAffine(m){return l(this,m)}clearCofactor(){return i===Ne?this:this.multiplyUnsafe(i)}toBytes(){let{x:m,y:x}=this.toAffine(),y=n.toBytes(x);return y[y.length-1]|=m&Ne?128:0,y}toHex(){return M(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(m){return Ze(h,m)}static msm(m,x){return ln(h,o,m,x)}_setWindowSize(m){this.precompute(m)}toRawBytes(){return this.toBytes()}}h.BASE=new h(s.Gx,s.Gy,Ne,c(s.Gx*s.Gy)),h.ZERO=new h(lr,Ne,Ne,lr),h.Fp=n,h.Fn=o;let _=new cn(h,o.BITS);return h.BASE.precompute(8),h}var xs=class{constructor(t){this.ep=t}static fromBytes(t){sn()}static fromHex(t){sn()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return M(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,r){return this.init(this.ep.precompute(t,r))}toRawBytes(){return this.toBytes()}};function If(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');Lt(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=e,a=r.randomBytes||$r,c=r.adjustScalarBytes||(w=>w),u=r.domain||((w,I,B)=>{if(vr(B,"phflag"),I.length||B)throw new Error("Contexts/pre-hash are not supported");return w});function p(w){return i.create(Ut(w))}function d(w){let I=y.secretKey;w=ae("private key",w,I);let B=ae("hashed private key",t(w),2*I),A=c(B.slice(0,I)),b=B.slice(I,2*I),N=p(A);return{head:A,prefix:b,scalar:N}}function l(w){let{head:I,prefix:B,scalar:A}=d(w),b=o.multiply(A),N=b.toBytes();return{head:I,prefix:B,scalar:A,point:b,pointBytes:N}}function f(w){return l(w).pointBytes}function h(w=Uint8Array.of(),...I){let B=K(...I);return p(t(u(B,ae("context",w),!!n)))}function _(w,I,B={}){w=ae("message",w),n&&(w=n(w));let{prefix:A,scalar:b,pointBytes:N}=l(I),P=h(B.context,A,w),V=o.multiply(P).toBytes(),q=h(B.context,V,N,w),S=i.create(P+q*b);if(!i.isValid(S))throw new Error("sign failed: invalid s");let F=K(V,i.toBytes(S));return or(F,y.signature,"result")}let g={zip215:!0};function m(w,I,B,A=g){let{context:b,zip215:N}=A,P=y.signature;w=ae("signature",w,P),I=ae("message",I),B=ae("publicKey",B,y.publicKey),N!==void 0&&vr(N,"zip215"),n&&(I=n(I));let V=P/2,q=w.subarray(0,V),S=Ut(w.subarray(V,P)),F,C,D;try{F=e.fromBytes(B,N),C=e.fromBytes(q,N),D=o.multiplyUnsafe(S)}catch{return!1}if(!N&&F.isSmallOrder())return!1;let k=h(b,C.toBytes(),F.toBytes(),I);return C.add(F.multiplyUnsafe(k)).subtract(D).clearCofactor().is0()}let x=s.BYTES,y={secretKey:x,publicKey:x,signature:2*x,seed:x};function T(w=a(y.seed)){return or(w,y.seed,"seed")}function O(w){let I=v.randomSecretKey(w);return{secretKey:I,publicKey:f(I)}}function R(w){return ft(w)&&w.length===i.BYTES}function E(w,I){try{return!!e.fromBytes(w,I)}catch{return!1}}let v={getExtendedPublicKey:l,randomSecretKey:T,isValidSecretKey:R,isValidPublicKey:E,toMontgomery(w){let{y:I}=e.fromBytes(w),B=y.publicKey,A=B===32;if(!A&&B!==57)throw new Error("only defined for 25519 and 448");let b=A?s.div(Ne+I,Ne-I):s.div(I-Ne,I+Ne);return s.toBytes(b)},toMontgomerySecret(w){let I=y.secretKey;or(w,I);let B=t(w.subarray(0,I));return c(B).subarray(0,I)},randomPrivateKey:T,precompute(w=8,I=e.BASE){return I.precompute(w,!1)}};return Object.freeze({keygen:O,getPublicKey:f,sign:_,verify:m,utils:v,Point:e,lengths:y})}function Af(e){let t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=De(t.n,e.nBitLength,!0),o={Fp:r,Fn:n,uvRatio:e.uvRatio},s={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:o,hash:e.hash,eddsaOpts:s}}function Sf(e,t){let r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function Gl(e){let{CURVE:t,curveOpts:r,hash:n,eddsaOpts:o}=Af(e),s=vf(t,r),i=If(s,n,o);return Sf(e,i)}var Ff=BigInt(0),Kt=BigInt(1),zl=BigInt(2),Hy=BigInt(3),Pf=BigInt(5),Bf=BigInt(8),fn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ao={p:fn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Bf,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Cf(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=fn,a=e*e%s*e%s,c=dt(a,zl,s)*a%s,u=dt(c,Kt,s)*e%s,p=dt(u,Pf,s)*u%s,d=dt(p,t,s)*p%s,l=dt(d,r,s)*d%s,f=dt(l,n,s)*l%s,h=dt(f,o,s)*f%s,_=dt(h,o,s)*f%s,g=dt(_,t,s)*p%s;return{pow_p_5_8:dt(g,zl,s)*e%s,b2:a}}function Vf(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var da=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ha(e,t){let r=fn,n=se(t*t*t,r),o=se(n*n*t,r),s=Cf(e*o).pow_p_5_8,i=se(e*n*s,r),a=se(t*i*i,r),c=i,u=se(i*da,r),p=a===e,d=a===se(-e,r),l=a===se(-e*da,r);return p&&(i=c),(d||l)&&(i=u),qt(i,r)&&(i=se(-i,r)),{isValid:p||d,value:i}}var ur=De(ao.p,{isLE:!0}),Df=De(ao.n,{isLE:!0}),Uf={...ao,Fp:ur,hash:gc,adjustScalarBytes:Vf,uvRatio:ha},Le=Gl(Uf);var pa=da,kf=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Lf=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),qf=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Mf=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Wl=e=>ha(Kt,e),jf=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),fa=e=>Le.Point.Fp.create(Ut(e)&jf);function Yl(e){let{d:t}=ao,r=fn,n=m=>ur.create(m),o=n(pa*e*e),s=n((o+Kt)*qf),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:u}=ha(s,a),p=n(u*e);qt(p,r)||(p=n(-p)),c||(u=p),c||(i=o);let d=n(i*(o-Kt)*Mf-a),l=u*u,f=n((u+u)*a),h=n(d*kf),_=n(Kt-l),g=n(Kt+l);return new Le.Point(n(f*g),n(_*h),n(h*g),n(f*_))}function Kf(e){ue(e,64);let t=fa(e.subarray(0,32)),r=Yl(t),n=fa(e.subarray(32,64)),o=Yl(n);return new $t(r.add(o))}var $t=class e extends xs{constructor(t){super(t)}static fromAffine(t){return new e(Le.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static hashToCurve(t){return Kf(ae("ristrettoHash",t,64))}static fromBytes(t){ue(t,32);let{a:r,d:n}=ao,o=fn,s=T=>ur.create(T),i=fa(t);if(!pl(ur.toBytes(i),t)||qt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Kt+r*a),u=s(Kt-r*a),p=s(c*c),d=s(u*u),l=s(r*n*p-d),{isValid:f,value:h}=Wl(s(l*d)),_=s(h*u),g=s(h*_*l),m=s((i+i)*_);qt(m,o)&&(m=s(-m));let x=s(c*g),y=s(m*x);if(!f||qt(y,o)||x===Ff)throw new Error("invalid ristretto255 encoding 2");return new e(new Le.Point(m,x,Kt,y))}static fromHex(t){return e.fromBytes(ae("ristrettoHex",t,32))}static msm(t,r){return ln(e,Le.Point.Fn,t,r)}toBytes(){let{X:t,Y:r,Z:n,T:o}=this.ep,s=fn,i=g=>ur.create(g),a=i(i(n+r)*i(n-r)),c=i(t*r),u=i(c*c),{value:p}=Wl(i(a*u)),d=i(p*a),l=i(p*c),f=i(d*l*o),h;if(qt(o*f,s)){let g=i(r*pa),m=i(t*pa);t=g,r=m,h=i(d*Lf)}else h=l;qt(t*f,s)&&(r=i(-r));let _=i((n-r)*h);return qt(_,s)&&(_=i(-_)),ur.toBytes(_)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=u=>ur.create(u),a=i(r*s)===i(n*o),c=i(n*s)===i(r*o);return a||c}is0(){return this.equals(e.ZERO)}};$t.BASE=new $t(Le.Point.BASE);$t.ZERO=new $t(Le.Point.ZERO);$t.Fp=ur;$t.Fn=Df;var Jl,Zl,bs=class{static{Jl=Symbol.iterator,Zl=Symbol.toStringTag}#e;#t;constructor(t={}){this[Jl]=this.entries.bind(this),this[Zl]="ExpirableMap";let{source:r=[],expirationTime:n=600*1e3}=t,o=Date.now();this.#e=new Map([...r].map(([s,i])=>[s,{value:i,timestamp:o}])),this.#t=n}prune(){let t=Date.now();for(let[r,n]of this.#e.entries())t-n.timestamp>this.#t&&this.#e.delete(r);return this}set(t,r){this.prune();let n={value:r,timestamp:Date.now()};return this.#e.set(t,n),this}get(t){let r=this.#e.get(t);if(r!==void 0){if(Date.now()-r.timestamp>this.#t){this.#e.delete(t);return}return r.value}}clear(){this.#e.clear()}entries(){let t=this.#e.entries();return function*(){for(let[n,o]of t)yield[n,o.value]}()}values(){let t=this.#e.values();return function*(){for(let n of t)yield n.value}()}keys(){return this.#e.keys()}forEach(t,r){for(let[n,o]of this.#e.entries())t.call(r,o.value,n,this)}has(t){return this.#e.has(t)}delete(t){return this.#e.delete(t)}get size(){return this.#e.size}};var Xl=e=>{if(e<=127)return 1;if(e<=255)return 2;if(e<=65535)return 3;if(e<=16777215)return 4;throw W.fromCode(new An("Length too long (> 4 bytes)"))},Ql=(e,t,r)=>{if(r<=127)return e[t]=r,1;if(r<=255)return e[t]=129,e[t+1]=r,2;if(r<=65535)return e[t]=130,e[t+1]=r>>8,e[t+2]=r,3;if(r<=16777215)return e[t]=131,e[t+1]=r>>16,e[t+2]=r>>8,e[t+3]=r,4;throw W.fromCode(new An("Length too long (> 4 bytes)"))},ma=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw W.fromCode(new ot("Invalid length 0"));if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw W.fromCode(new ot("Length too long (> 4 bytes)"))},$f=(e,t)=>{let r=ma(e,t);if(r===1)return e[t];if(r===2)return e[t+1];if(r===3)return(e[t+1]<<8)+e[t+2];if(r===4)return(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];throw W.fromCode(new ot("Length too long (> 4 bytes)"))},co=Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]),Cr=Uint8Array.from([48,5,6,3,43,101,112]),Jy=Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]),Zy=Uint8Array.from([48,29,6,13,43,6,1,4,1,130,220,124,5,3,1,2,1,6,12,43,6,1,4,1,130,220,124,5,3,2,1]);function Vr(e,t){let r=2+Xl(e.byteLength+1),n=t.byteLength+r+e.byteLength,o=0,s=new Uint8Array(1+Xl(n)+n);return s[o++]=48,o+=Ql(s,o,n),s.set(t,o),o+=t.byteLength,s[o++]=3,o+=Ql(s,o,e.byteLength+1),s[o++]=0,s.set(new Uint8Array(e),o),s}var Dr=(e,t)=>{let r=0,n=(a,c)=>{if(o[r++]!==a)throw W.fromCode(new ot(`Expected ${c} at offset ${r}`))},o=new Uint8Array(e);if(n(48,"sequence"),r+=ma(o,r),!Or(o.slice(r,r+t.byteLength),t))throw W.fromCode(new ot("Not the expected OID."));r+=t.byteLength,n(3,"bit string");let s=$f(o,r)-1;r+=ma(o,r),n(0,"0 padding");let i=o.slice(r);if(s!==i.length)throw W.fromCode(new Po(s,i.length));return i};var ws=class e{static from(t){return this.fromDer(t.toDer())}static fromRaw(t){return new e(t)}static fromDer(t){return new e(this.derDecode(t))}static{this.RAW_KEY_LENGTH=32}static derEncode(t){return Vr(t,Cr)}static derDecode(t){let r=Dr(t,Cr);if(r.length!==this.RAW_KEY_LENGTH)throw W.fromCode(new ot("An Ed25519 public key must be exactly 32 bytes long"));return r}#e;get rawKey(){return this.#e}#t;get derKey(){return this.#t}constructor(t){if(t.byteLength!==e.RAW_KEY_LENGTH)throw W.fromCode(new ot("An Ed25519 public key must be exactly 32 bytes long"));this.#e=t,this.#t=e.derEncode(t)}toDer(){return this.derKey}toRaw(){return this.rawKey}};var _a=class{constructor(){this.observers=[]}subscribe(t){this.observers.push(t)}unsubscribe(t){this.observers=this.observers.filter(r=>r!==t)}notify(t,...r){this.observers.forEach(n=>n(t,...r))}},Ts=class extends _a{constructor(){super()}print(t,...r){this.notify({message:t,level:"info"},...r)}warn(t,...r){this.notify({message:t,level:"warn"},...r)}error(t,r,...n){this.notify({message:t,level:"error",error:r},...n)}};var Ns=class e{#e;#t;#r;#c;#i;#u;#n;#o;#a=0;static{this.default={initialInterval:500,randomizationFactor:.5,multiplier:1.5,maxInterval:6e4,maxElapsedTime:9e5,maxIterations:10,date:Date}}constructor(t=e.default){let{initialInterval:r=500,randomizationFactor:n=.5,multiplier:o=1.5,maxInterval:s=6e4,maxElapsedTime:i=9e5,maxIterations:a=10,date:c=Date}=t;this.#e=r,this.#t=n,this.#r=o,this.#c=s,this.#o=c,this.#i=c.now(),this.#u=i,this.#n=a}get ellapsedTimeInMsec(){return this.#o.now()-this.#i}get currentInterval(){return this.#e}get count(){return this.#a}get randomValueFromInterval(){let t=this.#t*this.#e,r=this.#e-t,n=this.#e+t;return Math.random()*(n-r)+r}incrementCurrentInterval(){return this.#e=Math.min(this.#e*this.#r,this.#c),this.#a++,this.#e}next(){return this.ellapsedTimeInMsec>=this.#u||this.#a>=this.#n?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};var wt;(function(e){e.Received="received",e.Processing="processing",e.Replied="replied",e.Rejected="rejected",e.Unknown="unknown",e.Done="done"})(wt||(wt={}));var xa=60*1e3,Hf=1e6,Gf=0,zf="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae";var Wf="ic0.app",Yf=".ic0.app",Jf="icp0.io",Zf=".icp0.io",Xf="icp-api.io",Qf=".icp-api.io",ya=200,eh=202,th=404;function rh(){let e;if(typeof window<"u")if(window.fetch)e=window.fetch.bind(window);else throw we.fromCode(new Yr("Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present."));else if(typeof global<"u")if(global.fetch)e=global.fetch.bind(global);else throw we.fromCode(new Yr("Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available."));else typeof self<"u"&&self.fetch&&(e=self.fetch.bind(self));if(e)return e;throw we.fromCode(new Yr("Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context."))}function nh(e){let t;if(e!==void 0)!e.match(/^[a-z]+:/)&&typeof window<"u"?t=new URL(window.location.protocol+"//"+e):t=new URL(e);else{let r=["ic0.app","icp0.io","127.0.0.1","localhost"],n=[".github.dev",".gitpod.io"],o=typeof window<"u"?window.location:void 0,s=o?.hostname,i;s&&typeof s=="string"&&(n.some(a=>s.endsWith(a))?i=s:i=r.find(a=>s.endsWith(a))),o&&i?t=new URL(`${o.protocol}//${i}${o.port?":"+o.port:""}`):t=new URL("https://icp-api.io")}return t.toString()}var Ur=class e{#e;#t;#r;#c;#i;#u;#n;#o;#a;#x;#s;#d;#p;#l;get#N(){return this.#l*xa}#f;#h;#m;#_;constructor(t={}){this.#e=null,this.#t=!1,this.#r=Gf,this.#c=!1,this.#i=null,this.#u=!1,this._isAgent=!0,this.config={},this.log=new Ts,this.#f=[],this.#h=[],this.#m=new bs({expirationTime:5*xa}),this.#_=!0,this.#w=(o,s)=>{if(this.#_===!1)return o;let{status:i,signatures:a=[],requestId:c}=o;for(let u of a){let{timestamp:p,identity:d}=u,l=L.fromUint8Array(d).toText(),f;if(i===Gt.Replied){let{reply:x}=o;f=Mn({status:i,reply:x,timestamp:BigInt(p),request_id:c})}else if(i===Gt.Rejected){let{reject_code:x,reject_message:y,error_code:T}=o;f=Mn({status:i,reject_code:x,reject_message:y,error_code:T,timestamp:BigInt(p),request_id:c})}else throw he.fromCode(new Be(`Unknown status: ${i}`));let h=K(vi,f),_=s.nodeKeys.get(l);if(!_)throw te.fromCode(new Ko);let g=ws.fromDer(_).rawKey;if(Le.verify(u.signature,h,g))return o;throw Pe.fromCode(new $o(l))}return o},this.config=t,this.#o=t.fetch||rh()||fetch.bind(global),this.#a=t.fetchOptions,this.#x=t.callOptions,this.#t=t.shouldFetchRootKey??!1,this.#u=t.shouldSyncTime??!1,t.rootKey?this.rootKey=t.rootKey:this.#t?this.rootKey=null:this.rootKey=be(zf);let r=nh(t.host);this.host=new URL(r),t.verifyQuerySignatures!==void 0&&(this.#_=t.verifyQuerySignatures),this.#d=t.retryTimes??3;let n=()=>new Ns({maxIterations:this.#d});if(this.#p=t.backoffStrategy||n,this.host.hostname.endsWith(Yf)?this.host.hostname=Wf:this.host.hostname.endsWith(Zf)?this.host.hostname=Jf:this.host.hostname.endsWith(Qf)&&(this.host.hostname=Xf),t.credentials){let{name:o,password:s}=t.credentials;this.#s=`${o}${s?":"+s:""}`}if(this.#n=Promise.resolve(t.identity||new Ye),t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes>5)throw W.fromCode(new xr("The maximum ingress expiry time is 5 minutes.",t.ingressExpiryInMinutes));if(t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes<=0)throw W.fromCode(new xr("Ingress expiry time must be greater than 0.",t.ingressExpiryInMinutes));this.#l=t.ingressExpiryInMinutes||5,this.addTransform("update",Ci(Yn)),t.useQueryNonces&&this.addTransform("query",Ci(Yn)),t.logToConsole&&this.log.subscribe(o=>{o.level==="error"?console.error(o.message):o.level==="warn"?console.warn(o.message):console.log(o.message)})}static createSync(t={}){return new this({...t})}static async create(t={}){let r=e.createSync(t);return await r.#g(),r}static async from(t){try{return"config"in t?await e.create(t.config):await e.create({fetch:t._fetch,fetchOptions:t._fetchOptions,callOptions:t._callOptions,host:t._host.toString(),identity:t._identity??void 0})}catch{throw W.fromCode(new qo)}}isLocal(){let t=this.host.hostname;return t==="127.0.0.1"||t.endsWith("127.0.0.1")}addTransform(t,r,n=r.priority||0){if(t==="update"){let o=this.#h.findIndex(s=>(s.priority||0)<n);this.#h.splice(o>=0?o:this.#h.length,0,Object.assign(r,{priority:n}))}else if(t==="query"){let o=this.#f.findIndex(s=>(s.priority||0)<n);this.#f.splice(o>=0?o:this.#f.length,0,Object.assign(r,{priority:n}))}}async getPrincipal(){if(!this.#n)throw we.fromCode(new Xt);return(await this.#n).getPrincipal()}async call(t,r,n){let o=r.callSync??!0,s=await(n??this.#n);if(!s)throw we.fromCode(new Xt);let i=L.from(t),a=r.effectiveCanisterId?L.from(r.effectiveCanisterId):i;await this.#g(a);let c=s.getPrincipal(),u=ga(this.#l,this.#r),p={request_type:ns.Call,canister_id:i,method_name:r.methodName,arg:r.arg,sender:c,ingress_expiry:u},d=await this._transform({request:{body:null,method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:Dt.Call,body:p}),l;r?.nonce?l=f(r.nonce):d.body.nonce?l=f(d.body.nonce):l=void 0,p.nonce=l;function f(m){return Object.assign(m,{__nonce__:void 0})}d=await s.transformRequest(d);let h=zn(d.body),_=this.#p(),g=Ct(p);try{let y=o?()=>(this.log.print(`fetching "/api/v3/canister/${a.toText()}/call" with request:`,d),this.#o(""+new URL(`/api/v3/canister/${a.toText()}/call`,this.host),{...this.#x,...d.request,body:h})):()=>(this.log.print(`fetching "/api/v2/canister/${a.toText()}/call" with request:`,d),this.#o(""+new URL(`/api/v2/canister/${a.toText()}/call`,this.host),{...this.#x,...d.request,body:h})),{responseBodyBytes:T,...O}=await this.#y({requestFn:y,backoff:_,tries:0}),R=T.byteLength>0?je(T):null;return{requestId:g,response:{...O,body:R},requestDetails:p}}catch(m){let x;if(m instanceof nt){if(m.hasCode(Fn))return this.log.warn("v3 api not supported. Fall back to v2"),this.call(t,{...r,callSync:!1},n);if(m.hasCode(xr)&&!this.#c)return await this.syncTime(i),this.call(i,r,n);m.code.requestContext={requestId:g,senderPubKey:d.body.sender_pubkey,senderSignature:d.body.sender_sig,ingressExpiry:d.body.content.ingress_expiry},x=m}else x=he.fromCode(new Be(m));throw this.log.error(`Error while making call: ${x.message}`,x),x}}async#b(t){let{ecid:r,transformedRequest:n,body:o,requestId:s,backoff:i,tries:a}=t,c=a===0?0:i.next();if(this.log.print(`fetching "/api/v2/canister/${r.toString()}/query" with tries:`,{tries:a,backoff:i,delay:c}),c===null)throw he.fromCode(new gr(`Backoff strategy exhausted after ${a} attempts.`,s));c>0&&await new Promise(f=>setTimeout(f,c));let u;try{this.log.print(`fetching "/api/v2/canister/${r.toString()}/query" with request:`,n);let f=await this.#o(""+new URL(`/api/v2/canister/${r.toString()}/query`,this.host),{...this.#a,...n.request,body:o});if(f.status===ya)u={...je(en(await f.arrayBuffer())),httpDetails:{ok:f.ok,status:f.status,statusText:f.statusText,headers:ss(f.headers)},requestId:s};else throw te.fromCode(new Sn(f.status,f.statusText,ss(f.headers),await f.text()))}catch(f){if(a<this.#d)return this.log.warn(`Caught exception while attempting to make query:
48
+ `)}return c.encodeValue(u)}));return Y(n,o,s,i,a)}function jp(e,t){let r=new ft(t);if(t.byteLength<xs.length)throw new Error("Message length smaller than magic number");let n=_r(r,xs.length),o=new TextDecoder().decode(n);if(o!==xs)throw new Error("Wrong magic number: "+JSON.stringify(o));function s(l){let f=[],h=Number(he(l));for(let _=0;_<h;_++){let x=Number(qt(l));switch(x){case Z.Opt:case Z.Vector:{let g=Number(qt(l));f.push([x,g]);break}case Z.Record:case Z.Variant:{let g=[],T=Number(he(l)),N;for(;T--;){let E=Number(he(l));if(E>=Math.pow(2,32))throw new Error("field id out of 32-bit range");if(typeof N=="number"&&N>=E)throw new Error("field id collision or not sorted");N=E;let R=Number(qt(l));g.push([E,R])}f.push([x,g]);break}case Z.Func:{let g=[],T=Number(he(l));for(;T--;)g.push(Number(qt(l)));let N=[],E=Number(he(l));for(;E--;)N.push(Number(qt(l)));let R=[],I=Number(he(l));for(;I--;)switch(Number(he(l))){case 1:{R.push("query");break}case 2:{R.push("oneway");break}case 3:{R.push("composite_query");break}default:throw new Error("unknown annotation")}f.push([x,[g,N,R]]);break}case Z.Service:{let g=Number(he(l)),T=[];for(;g--;){let N=Number(he(l)),E=new TextDecoder().decode(_r(l,N)),R=qt(l);T.push([E,R])}f.push([x,T]);break}default:throw new Error("Illegal op_code: "+x)}}let m=[],y=Number(he(l));for(let _=0;_<y;_++)m.push(Number(qt(l)));return[f,m]}let[i,a]=s(r);if(a.length<e.length)throw new Error("Wrong number of return values");let c=i.map(l=>Bl());function u(l){if(l<-24)throw new Error("future value not supported");if(l<0)switch(l){case-1:return hl;case-2:return fl;case-3:return yl;case-4:return _l;case-5:return Nl;case-6:return El;case-7:return Rl;case-8:return vl;case-9:return bl;case-10:return wl;case-11:return Tl;case-12:return Ol;case-13:return gl;case-14:return xl;case-15:return ml;case-16:return pl;case-17:return dl;case-24:return Il;default:throw new Error("Illegal op_code: "+l)}if(l>=i.length)throw new Error("type index out of range");return c[l]}function p(l){switch(l[0]){case Z.Vector:{let f=u(l[1]);return Sl(f)}case Z.Opt:{let f=u(l[1]);return Pl(f)}case Z.Record:{let f={};for(let[y,_]of l[1]){let x=`_${y}_`;f[x]=u(_)}let h=Cl(f),m=h.tryAsTuple();return Array.isArray(m)?Al(...m):h}case Z.Variant:{let f={};for(let[h,m]of l[1]){let y=`_${h}_`;f[y]=u(m)}return Fl(f)}case Z.Func:{let[f,h,m]=l[1];return Vl(f.map(y=>u(y)),h.map(y=>u(y)),m)}case Z.Service:{let f={},h=l[1];for(let[m,y]of h){let _=u(y);if(_ instanceof tt&&(_=_.getType()),!(_ instanceof jr))throw new Error("Illegal service definition: services can only contain functions");f[m]=_}return Dl(f)}default:throw new Error("Illegal op_code: "+l[0])}}i.forEach((l,f)=>{if(l[0]===Z.Func){let h=p(l);c[f].fill(h)}}),i.forEach((l,f)=>{if(l[0]!==Z.Func){let h=p(l);c[f].fill(h)}}),na();let d=a.map(l=>u(l));try{let l=e.map((f,h)=>f.decodeValue(r,d[h]));for(let f=e.length;f<d.length;f++)d[f].decodeValue(r,d[f]);if(r.byteLength>0)throw new Error("decode: Left-over bytes");return l}finally{na()}}var dl=new io,pl=new It,Kp=new ws,fl=new Ts,hl=new qr,ml=new Os,_l=new ao,yl=new co,gl=new lo(32),xl=new lo(64),bl=new jt(8),wl=new jt(16),Tl=new jt(32),Ol=new jt(64),Nl=new Rt(8),El=new Rt(16),Rl=new Rt(32),vl=new Rt(64),Il=new Es;function Al(...e){return new Ns(e)}function Sl(e){return new gn(e)}function Pl(e){return new yr(e)}function Cl(e){return new Mr(e)}function Fl(e){return new xn(e)}function Bl(){return new tt}function Vl(e,t,r=[]){return new jr(e,t,r)}function Dl(e){return new bn(e)}var Rs=class e{constructor(t=new Map){this.rels=t}copy(){let t=new Map;for(let[r,n]of this.rels.entries()){let o=new Map(n);t.set(r,o)}return new e(t)}known(t,r){return this.rels.get(t.name)?.get(r.name)}addNegative(t,r){this.addNames(t.name,r.name,!1)}add(t,r){this.addNames(t.name,r.name,!0)}display(){let t="";for(let[r,n]of this.rels)for(let[o,s]of n)t+=`${r} ${s?":<":"!<:"} ${o}
49
+ `;return t}addNames(t,r,n){let o=this.rels.get(t);if(o==null){let s=new Map;s.set(r,n),this.rels.set(t,s)}else o.set(r,n)}},bs=new Rs;function na(){bs=new Rs}function Hp(e,t){let r=new Set(e.annotations),n=new Set(t.annotations);if(r.size!==n.size)return!1;for(let o of r)if(!n.has(o))return!1;return!0}function ea(e){return e instanceof yr||e instanceof qr||e instanceof It}function sa(e,t){let r=bs.copy(),n=Mt(r,e,t);return n?bs.add(e,t):bs.addNegative(e,t),n}function Mt(e,t,r){if(t.name===r.name)return!0;let n=e.known(t,r);if(n!==void 0)return n;if(e.add(t,r),r instanceof It||t instanceof io||t instanceof co&&r instanceof ao)return!0;if(t instanceof gn&&r instanceof gn)return Mt(e,t._type,r._type);if(r instanceof yr)return!0;if(t instanceof Mr&&r instanceof Mr){let o=t.fieldsAsObject;for(let[s,i]of r._fields){let a=o[Le(s)];if(a){if(!Mt(e,a,i))return!1}else if(!ea(i))return!1}return!0}if(t instanceof jr&&r instanceof jr){if(!Hp(t,r))return!1;for(let o=0;o<t.argTypes.length;o++){let s=t.argTypes[o];if(o<r.argTypes.length){if(!Mt(e,r.argTypes[o],s))return!1}else if(!ea(s))return!1}for(let o=0;o<r.retTypes.length;o++){let s=r.retTypes[o];if(o<t.retTypes.length){if(!Mt(e,t.retTypes[o],s))return!1}else if(!ea(s))return!1}return!0}if(t instanceof xn&&r instanceof xn){let o=r.alternativesAsObject;for(let[s,i]of t._fields){let a=o[Le(s)];if(!a||!Mt(e,i,a))return!1}return!0}if(t instanceof bn&&r instanceof bn){let o=t.fieldsAsObject();for(let[s,i]of r._fields){let a=o[s];if(!a||!Mt(e,a,i))return!1}return!0}return t instanceof tt?Mt(e,t.getType(),r):r instanceof tt?Mt(e,t,r.getType()):!1}function wn(e){if(!e)throw new Error("Input cannot be null or undefined");return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):"buffer"in e?wn(e.buffer):new Uint8Array(e)}function Hr(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function ia(e){if(typeof e=="string")return Ul(e);if(typeof e=="number")return Ce(ne(e));if(e instanceof Uint8Array||ArrayBuffer.isView(e))return Ce(wn(e));if(Array.isArray(e)){let t=e.map(ia);return Ce(M(...t))}else{if(e&&typeof e=="object"&&e._isPrincipal)return Ce(e.toUint8Array());if(typeof e=="object"&&e!==null&&typeof e.toHash=="function")return ia(e.toHash());if(typeof e=="object")return uo(e);if(typeof e=="bigint")return Ce(ne(e))}throw z.fromCode(new ds(e))}var Ul=e=>{let t=new TextEncoder().encode(e);return Ce(t)};function Kt(e){return uo(e)}function uo(e){let n=Object.entries(e).filter(([,i])=>i!==void 0).map(([i,a])=>{let c=Ul(i),u=ia(a);return[c,u]}).sort(([i],[a])=>Ji(i,a)),o=M(...n.map(i=>M(...i)));return Ce(o)}var po=new TextEncoder().encode(`
50
+ ic-request`),aa=new TextEncoder().encode("\vic-response"),ca=new TextEncoder().encode("ic-request-auth-delegation");var At=class{getPrincipal(){return this._principal||(this._principal=k.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()))),this._principal}async transformRequest(t){let{body:r,...n}=t,o=Kt(r);return{...n,body:{content:r,sender_pubkey:this.getPublicKey().toDer(),sender_sig:await this.sign(M(po,o))}}}},rt=class{getPrincipal(){return k.anonymous()}async transformRequest(t){return{...t,body:{content:t.body}}}};var Ht=class extends Error{constructor(t){super(t),this.name="DecodingError"}},Ll=55799,ql=Symbol("CBOR_STOP_CODE"),_t=(e=>(e[e.False=20]="False",e[e.True=21]="True",e[e.Null=22]="Null",e[e.Undefined=23]="Undefined",e[e.Break=31]="Break",e))(_t||{}),be=(e=>(e[e.UnsignedInteger=0]="UnsignedInteger",e[e.NegativeInteger=1]="NegativeInteger",e[e.ByteString=2]="ByteString",e[e.TextString=3]="TextString",e[e.Array=4]="Array",e[e.Map=5]="Map",e[e.Tag=6]="Tag",e[e.Simple=7]="Simple",e))(be||{}),$p=23,Gp=255,Wp=65535,zp=4294967295,Yp=BigInt("0xffffffffffffffff"),mt=(e=>(e[e.Value=23]="Value",e[e.OneByte=24]="OneByte",e[e.TwoBytes=25]="TwoBytes",e[e.FourBytes=26]="FourBytes",e[e.EightBytes=27]="EightBytes",e[e.Indefinite=31]="Indefinite",e))(mt||{}),Tn=!1;function Jp(e){return e==null}function Ml(e,t){let r=new Uint8Array(t);return r.set(e),r}var Zp=new TextDecoder;function Xp(e){return(e&224)>>5}function Qp(e){return e&31}var mo=new Uint8Array,fo,yt=0;function jl(e,t){mo=e,yt=0;let r=$r(t);return t?.(r)??r}function $r(e){let[t,r]=vs();switch(t){case be.UnsignedInteger:return On(r);case be.NegativeInteger:return nf(r);case be.ByteString:return Kl(r);case be.TextString:return ua(r);case be.Array:return ef(r,e);case be.Map:return rf(r,e);case be.Tag:return of(r,e);case be.Simple:return tf(r)}throw new Ht(`Unsupported major type: ${t}`)}function vs(){let e=mo.at(yt);if(Jp(e))throw new Ht("Provided CBOR data is empty");let t=Xp(e),r=Qp(e);return yt++,[t,r]}function ef(e,t){let r=On(e);if(r===1/0){let o=[],s=$r(t);for(;s!==ql;)o.push(t?.(s)??s),s=$r(t);return o}let n=new Array(r);for(let o=0;o<r;o++){let s=$r(t);n[o]=t?.(s)??s}return n}function tf(e){switch(e){case _t.False:return!1;case _t.True:return!0;case _t.Null:return null;case _t.Undefined:return;case _t.Break:return ql}throw new Ht(`Unrecognized simple type: ${e.toString(2)}`)}function rf(e,t){let r=On(e),n={};if(r===1/0){let[o,s]=vs();for(;o!==be.Simple&&s!==_t.Break;){let i=ua(s),a=$r(t);n[i]=t?.(a,i)??a,[o,s]=vs()}return n}for(let o=0;o<r;o++){let[s,i]=vs();if(s!==be.TextString)throw new Ht("Map keys must be text strings");let a=ua(i),c=$r(t);n[a]=t?.(c,a)??c}return n}function On(e){if(e<=mt.Value)return e;switch(fo=new DataView(mo.buffer,mo.byteOffset+yt),e){case mt.OneByte:return yt++,fo.getUint8(0);case mt.TwoBytes:return yt+=2,fo.getUint16(0,Tn);case mt.FourBytes:return yt+=4,fo.getUint32(0,Tn);case mt.EightBytes:return yt+=8,fo.getBigUint64(0,Tn);case mt.Indefinite:return 1/0;default:throw new Ht(`Unsupported integer info: ${e.toString(2)}`)}}function nf(e){let t=On(e);return typeof t=="number"?-1-t:-1n-t}function Kl(e){let t=On(e);if(t>Number.MAX_SAFE_INTEGER)throw new Ht("Byte length is too large");let r=Number(t);return yt+=r,mo.slice(yt-r,yt)}function ua(e){let t=Kl(e);return Zp.decode(t)}function of(e,t){let r=On(e);if(r===Ll)return $r(t);throw new Ht(`Unsupported tag: ${r}.`)}var _o=class extends Error{constructor(t){super(t),this.name="SerializationError"}},sf=2*1024,af=100,cf=new TextEncoder;function ho(e){return e<<5}var Qe=new Uint8Array(sf),ht=new DataView(Qe.buffer),xe=0,la=[];function Hl(e,t){xe=0;let r=t?.(e)??e;return _f(Ll,r,t),Qe.slice(0,xe)}function da(e,t){if(xe>Qe.length-af&&(Qe=Ml(Qe,Qe.length*2),ht=new DataView(Qe.buffer)),e===!1||e===!0||e===null||e===void 0){df(e);return}if(typeof e=="number"||typeof e=="bigint"){mf(e);return}if(typeof e=="string"){Wl(e);return}if(e instanceof Uint8Array){kl(e);return}if(e instanceof ArrayBuffer){kl(new Uint8Array(e));return}if(Array.isArray(e)){lf(e,t);return}if(typeof e=="object"){uf(e,t);return}throw new _o(`Unsupported type: ${typeof e}`)}function lf(e,t){Nn(be.Array,e.length),e.forEach((r,n)=>{da(t?.(r,n.toString())??r,t)})}function uf(e,t){la=Object.entries(e),Nn(be.Map,la.length),la.forEach(([r,n])=>{Wl(r),da(t?.(n,r)??n,t)})}function Nn(e,t){if(t<=$p){ht.setUint8(xe++,ho(e)|Number(t));return}if(t<=Gp){ht.setUint8(xe++,ho(e)|mt.OneByte),ht.setUint8(xe,Number(t)),xe+=1;return}if(t<=Wp){ht.setUint8(xe++,ho(e)|mt.TwoBytes),ht.setUint16(xe,Number(t),Tn),xe+=2;return}if(t<=zp){ht.setUint8(xe++,ho(e)|mt.FourBytes),ht.setUint32(xe,Number(t),Tn),xe+=4;return}if(t<=Yp){ht.setUint8(xe++,ho(e)|mt.EightBytes),ht.setBigUint64(xe,BigInt(t),Tn),xe+=8;return}throw new _o(`Value too large to encode: ${t}`)}function df(e){Nn(be.Simple,pf(e))}function pf(e){if(e===!1)return _t.False;if(e===!0)return _t.True;if(e===null)return _t.Null;if(e===void 0)return _t.Undefined;throw new _o(`Unrecognized simple value: ${e.toString()}`)}function $l(e,t){Nn(e,t.length),xe>Qe.length-t.length&&(Qe=Ml(Qe,Qe.length+t.length),ht=new DataView(Qe.buffer)),Qe.set(t,xe),xe+=t.length}function Gl(e,t){Nn(e,t)}function ff(e){Gl(be.UnsignedInteger,e)}function hf(e){Gl(be.NegativeInteger,typeof e=="bigint"?-1n-e:-1-e)}function mf(e){e>=0?ff(e):hf(e)}function Wl(e){$l(be.TextString,cf.encode(e))}function kl(e){$l(be.ByteString,e)}function _f(e,t,r){Nn(be.Tag,e),da(t,r)}function gf(e){return typeof e=="object"&&e!==null&&"toCborValue"in e}function yo(e){try{return Hl(e,t=>k.isPrincipal(t)?t.toUint8Array():En.isExpiry(t)?t.toBigInt():gf(t)?t.toCborValue():t)}catch(t){throw z.fromCode(new is(t,e))}}function We(e){try{return jl(e)}catch(t){throw z.fromCode(new ss(t,e))}}var Is={encode:yo,decode:We};var go=()=>{if(typeof window<"u"&&window.crypto&&window.crypto.getRandomValues){let e=new Uint32Array(1);return window.crypto.getRandomValues(e),e[0]}if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return typeof crypto<"u"&&crypto.randomInt?crypto.randomInt(0,4294967295):Math.floor(Math.random()*4294967295)};var $t;(function(e){e.Query="read",e.ReadState="read_state",e.Call="call"})($t||($t={}));var As;(function(e){e.Call="call"})(As||(As={}));var Gr;(function(e){e.Query="query",e.ReadState="read_state"})(Gr||(Gr={}));function xo(){let e=new ArrayBuffer(16),t=new DataView(e),r=go(),n=go(),o=go(),s=go();return t.setUint32(0,r),t.setUint32(4,n),t.setUint32(8,o),t.setUint32(12,s),Object.assign(new Uint8Array(e),{__nonce__:void 0})}var Ss="__expiry__",fa=BigInt(1e3),xf=BigInt(1e6),zl=BigInt(60),bf=BigInt(90)*fa;function Yl(e){return e/fa}function wf(e){return Yl(e)/zl}var En=class e{constructor(t){this.__expiry__=t,this._isExpiry=!0}static fromDeltaInMilliseconds(t,r=0){let n=BigInt(t),o=BigInt(Date.now())+n+BigInt(r),s;return n<bf?s=Yl(o):s=wf(o)*zl,new e(s*fa*xf)}toBigInt(){return this.__expiry__}toHash(){return ne(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[Ss]:this.toString()}}static fromJSON(t){let r=JSON.parse(t);if(r[Ss])try{let n=BigInt(r[Ss]);return new e(n)}catch(n){throw new z(new no(`Not a valid BigInt: ${n}`))}throw new z(new no(`The input does not contain the key ${Ss}`))}static isExpiry(t){return t instanceof e||typeof t=="object"&&t!==null&&"_isExpiry"in t&&t._isExpiry===!0&&"__expiry__"in t&&typeof t.__expiry__=="bigint"}};function ha(e=xo){return async t=>{let r=t.request.headers;t.request.headers=r,t.endpoint===$t.Call&&(t.body.nonce=e())}}function Ps(e){let t=[];return e.forEach((r,n)=>{t.push([n,r])}),t}var _a=BigInt(0),Cs=BigInt(1);function Wr(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}"`;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function gr(e,t,r=""){let n=Tt(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function Jl(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?_a:BigInt("0x"+e)}function ze(e){return Jl(K(e))}function Gt(e){return de(e),Jl(K(Uint8Array.from(e).reverse()))}function we(e,t){return Ne(e.toString(16).padStart(t*2,"0"))}function ya(e,t){return we(e,t).reverse()}function ce(e,t,r){let n;if(typeof t=="string")try{n=Ne(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(Tt(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let o=n.length;if(typeof r=="number"&&o!==r)throw new Error(e+" of length "+r+" expected, got "+o);return n}function Zl(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function ga(e){return Uint8Array.from(e)}var ma=e=>typeof e=="bigint"&&_a<=e;function xa(e,t,r){return ma(e)&&ma(t)&&ma(r)&&t<=e&&e<r}function Fs(e,t,r,n){if(!xa(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Wt(e){let t;for(t=0;e>_a;e>>=Cs,t+=1);return t}function Xl(e,t){return e>>BigInt(t)&Cs}var gt=e=>(Cs<<BigInt(e))-Cs;function Ql(e){return typeof e=="function"&&Number.isSafeInteger(e.outputLen)}function zt(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(o,s,i){let a=e[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}var Rn=()=>{throw new Error("not implemented")};function xr(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}var qe=BigInt(0),Re=BigInt(1),zr=BigInt(2),tu=BigInt(3),ru=BigInt(4),nu=BigInt(5),Tf=BigInt(7),ou=BigInt(8),Of=BigInt(9),su=BigInt(16);function oe(e,t){let r=e%t;return r>=qe?r:t+r}function xt(e,t,r){let n=e;for(;t-- >qe;)n*=n,n%=r;return n}function eu(e,t){if(e===qe)throw new Error("invert: expected non-zero number");if(t<=qe)throw new Error("invert: expected positive modulus, got "+t);let r=oe(e,t),n=t,o=qe,s=Re,i=Re,a=qe;for(;r!==qe;){let u=n/r,p=n%r,d=o-i*u,l=s-a*u;n=r,r=p,o=i,s=a,i=d,a=l}if(n!==Re)throw new Error("invert: does not exist");return oe(o,t)}function ba(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function iu(e,t){let r=(e.ORDER+Re)/ru,n=e.pow(t,r);return ba(e,n,t),n}function Nf(e,t){let r=(e.ORDER-nu)/ou,n=e.mul(t,zr),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,zr),o),a=e.mul(s,e.sub(i,e.ONE));return ba(e,a,t),a}function Ef(e){let t=Me(e),r=au(e),n=r(t,t.neg(t.ONE)),o=r(t,n),s=r(t,t.neg(n)),i=(e+Tf)/su;return(a,c)=>{let u=a.pow(c,i),p=a.mul(u,n),d=a.mul(u,o),l=a.mul(u,s),f=a.eql(a.sqr(p),c),h=a.eql(a.sqr(d),c);u=a.cmov(u,p,f),p=a.cmov(l,d,h);let m=a.eql(a.sqr(p),c),y=a.cmov(u,p,m);return ba(a,y,c),y}}function au(e){if(e<tu)throw new Error("sqrt is not defined for small field");let t=e-Re,r=0;for(;t%zr===qe;)t/=zr,r++;let n=zr,o=Me(e);for(;bo(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return iu;let s=o.pow(n,t),i=(t+Re)/zr;return function(c,u){if(c.is0(u))return u;if(bo(c,u)!==1)throw new Error("Cannot find square root");let p=r,d=c.mul(c.ONE,s),l=c.pow(u,t),f=c.pow(u,i);for(;!c.eql(l,c.ONE);){if(c.is0(l))return c.ZERO;let h=1,m=c.sqr(l);for(;!c.eql(m,c.ONE);)if(h++,m=c.sqr(m),h===p)throw new Error("Cannot find square root");let y=Re<<BigInt(p-h-1),_=c.pow(d,y);p=h,d=c.sqr(_),l=c.mul(l,d),f=c.mul(f,_)}return f}}function Rf(e){return e%ru===tu?iu:e%ou===nu?Nf:e%su===Of?Ef(e):au(e)}var Yt=(e,t)=>(oe(e,t)&Re)===Re,vf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Bs(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=vf.reduce((n,o)=>(n[o]="function",n),t);return zt(e,r),e}function wo(e,t,r){if(r<qe)throw new Error("invalid exponent, negatives unsupported");if(r===qe)return e.ONE;if(r===Re)return t;let n=e.ONE,o=t;for(;r>qe;)r&Re&&(n=e.mul(n,o)),o=e.sqr(o),r>>=Re;return n}function nt(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function bo(e,t){let r=(e.ORDER-Re)/zr,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function wa(e,t){t!==void 0&&Ki(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Me(e,t,r=!1,n={}){if(e<=qe)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let l=t;l.BITS&&(o=l.BITS),l.sqrt&&(s=l.sqrt),typeof l.isLE=="boolean"&&(r=l.isLE),typeof l.modFromBytes=="boolean"&&(i=l.modFromBytes),a=l.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:u}=wa(e,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let p,d=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:u,MASK:gt(c),ZERO:qe,ONE:Re,allowedLengths:a,create:l=>oe(l,e),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return qe<=l&&l<e},is0:l=>l===qe,isValidNot0:l=>!d.is0(l)&&d.isValid(l),isOdd:l=>(l&Re)===Re,neg:l=>oe(-l,e),eql:(l,f)=>l===f,sqr:l=>oe(l*l,e),add:(l,f)=>oe(l+f,e),sub:(l,f)=>oe(l-f,e),mul:(l,f)=>oe(l*f,e),pow:(l,f)=>wo(d,l,f),div:(l,f)=>oe(l*eu(f,e),e),sqrN:l=>l*l,addN:(l,f)=>l+f,subN:(l,f)=>l-f,mulN:(l,f)=>l*f,inv:l=>eu(l,e),sqrt:s||(l=>(p||(p=Rf(e)),p(d,l))),toBytes:l=>r?ya(l,u):we(l,u),fromBytes:(l,f=!0)=>{if(a){if(!a.includes(l.length)||l.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+l.length);let m=new Uint8Array(u);m.set(l,r?0:m.length-l.length),l=m}if(l.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+l.length);let h=r?Gt(l):ze(l);if(i&&(h=oe(h,e)),!f&&!d.isValid(h))throw new Error("invalid field element: outside of range 0..ORDER");return h},invertBatch:l=>nt(d,l),cmov:(l,f,h)=>h?f:l});return Object.freeze(d)}function cu(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function Vs(e){let t=cu(e);return t+Math.ceil(t/2)}function Ta(e,t,r=!1){let n=e.length,o=cu(t),s=Vs(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?Gt(e):ze(e),a=oe(i,t-Re)+Re;return r?ya(a,o):we(a,o)}var vn=BigInt(0),Yr=BigInt(1);function To(e,t){let r=t.negate();return e?r:t}function ot(e,t){let r=nt(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function pu(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Oa(e,t){pu(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=gt(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function lu(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=Yr);let u=t*n,p=u+Math.abs(a)-1,d=a===0,l=a<0,f=t%2!==0;return{nextN:c,offset:p,isZero:d,isNeg:l,isNegF:f,offsetF:u}}function Af(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function Sf(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}var Na=new WeakMap,fu=new WeakMap;function Ea(e){return fu.get(e)||1}function uu(e){if(e!==vn)throw new Error("invalid wNAF")}var In=class{constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let o=t;for(;r>vn;)r&Yr&&(n=n.add(o)),o=o.double(),r>>=Yr;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=Oa(r,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Oa(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:p,isNeg:d,isNegF:l,offsetF:f}=lu(n,a,i);n=c,p?s=s.add(To(l,r[f])):o=o.add(To(d,r[u]))}return uu(n),{p:o,f:s}}wNAFUnsafe(t,r,n,o=this.ZERO){let s=Oa(t,this.bits);for(let i=0;i<s.windows&&n!==vn;i++){let{nextN:a,offset:c,isZero:u,isNeg:p}=lu(n,i,s);if(n=a,!u){let d=r[c];o=o.add(p?d.negate():d)}}return uu(n),o}getPrecomputes(t,r,n){let o=Na.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(o=n(o)),Na.set(r,o))),o}cached(t,r,n){let o=Ea(t);return this.wNAF(o,this.getPrecomputes(o,t,n),r)}unsafe(t,r,n,o){let s=Ea(t);return s===1?this._unsafeLadder(t,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),r,o)}createCache(t,r){pu(r,this.bits),fu.set(t,r),Na.delete(t)}hasCache(t){return Ea(t)!==1}};function hu(e,t,r,n){let o=t,s=e.ZERO,i=e.ZERO;for(;r>vn||n>vn;)r&Yr&&(s=s.add(o)),n&Yr&&(i=i.add(o)),o=o.double(),r>>=Yr,n>>=Yr;return{p1:s,p2:i}}function An(e,t,r,n){Af(r,e),Sf(n,t);let o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=e.ZERO,a=Wt(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=gt(c),p=new Array(Number(u)+1).fill(i),d=Math.floor((t.BITS-1)/c)*c,l=i;for(let f=d;f>=0;f-=c){p.fill(i);for(let m=0;m<s;m++){let y=n[m],_=Number(y>>BigInt(f)&u);p[_]=p[_].add(r[m])}let h=i;for(let m=p.length-1,y=i;m>0;m--)y=y.add(p[m]),h=h.add(y);if(l=l.add(h),f!==0)for(let m=0;m<c;m++)l=l.double()}return l}function du(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Bs(t),t}else return Me(e,{isLE:r})}function Ds(e,t,r={},n){if(n===void 0&&(n=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u=="bigint"&&u>vn))throw new Error(`CURVE.${c} must be positive bigint`)}let o=du(t.p,r.Fp,n),s=du(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}var Pf=ze;function br(e,t){if(Oo(e),Oo(t),e<0||e>=1<<8*t)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function Cf(e,t){let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function Oo(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function mu(e){if(!Tt(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or string");return typeof e=="string"?Q(e):e}function Ff(e,t,r,n){de(e),Oo(r),t=mu(t),t.length>255&&(t=n(M(Q("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(r/o);if(r>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=M(t,br(t.length,1)),c=br(0,s),u=br(r,2),p=new Array(i),d=n(M(c,e,u,br(0,1),a));p[0]=n(M(d,br(1,1),a));for(let f=1;f<=i;f++){let h=[Cf(d,p[f-1]),br(f+1,1),a];p[f]=n(M(...h))}return M(...p).slice(0,r)}function Bf(e,t,r,n,o){if(de(e),Oo(r),t=mu(t),t.length>255){let s=Math.ceil(2*n/8);t=o.create({dkLen:s}).update(Q("H2C-OVERSIZE-DST-")).update(t).digest()}if(r>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return o.create({dkLen:r}).update(e).update(br(r,2)).update(t).update(br(t.length,1)).digest()}function Ra(e,t,r){zt(r,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:n,k:o,m:s,hash:i,expand:a,DST:c}=r;if(!Ql(r.hash))throw new Error("expected valid hash");de(e),Oo(t);let u=n.toString(2).length,p=Math.ceil((u+o)/8),d=t*s*p,l;if(a==="xmd")l=Ff(e,c,d,i);else if(a==="xof")l=Bf(e,c,d,o,i);else if(a==="_internal_pass")l=e;else throw new Error('expand must be "xmd" or "xof"');let f=new Array(t);for(let h=0;h<t;h++){let m=new Array(s);for(let y=0;y<s;y++){let _=p*(y+h*s),x=l.subarray(_,_+p);m[y]=oe(Pf(x),n)}f[h]=m}return f}function va(e,t){let r=t.map(n=>Array.from(n).reverse());return(n,o)=>{let[s,i,a,c]=r.map(d=>d.reduce((l,f)=>e.add(e.mul(l,n),f))),[u,p]=nt(e,[i,c],!0);return n=e.mul(s,u),o=e.mul(o,e.mul(a,p)),{x:n,y:o}}}var Vf=Q("HashToScalar-");function Ia(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function n(s){return e.fromAffine(t(s))}function o(s){let i=s.clearCofactor();return i.equals(e.ZERO)?e.ZERO:(i.assertValidity(),i)}return{defaults:r,hashToCurve(s,i){let a=Object.assign({},r,i),c=Ra(s,2,a),u=n(c[0]),p=n(c[1]);return o(u.add(p))},encodeToCurve(s,i){let a=r.encodeDST?{DST:r.encodeDST}:{},c=Object.assign({},r,a,i),u=Ra(s,1,c),p=n(u[0]);return o(p)},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(let i of s)if(typeof i!="bigint")throw new Error("expected array of bigints");return o(n(s))},hashToScalar(s,i){let a=e.Fn.ORDER,c=Object.assign({},r,{p:a,m:1,DST:Vf},i);return Ra(s,1,c)[0][0]}}}var _u=(e,t)=>(e+(e>=0?t:-t)/Jt)/t;function Df(e,t,r){let[[n,o],[s,i]]=t,a=_u(i*e,r),c=_u(-o*e,r),u=e-a*n-c*s,p=-a*o-c*i,d=u<Jr,l=p<Jr;d&&(u=-u),l&&(p=-p);let f=gt(Math.ceil(Wt(r)/2))+je;if(u<Jr||u>=f||p<Jr||p>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:u,k2neg:l,k2:p}}var Jr=BigInt(0),je=BigInt(1),Jt=BigInt(2),Sn=BigInt(3),Aa=BigInt(4);function No(e,t){let{BYTES:r}=e,n;if(typeof t=="bigint")n=t;else{let o=ce("private key",t);try{n=e.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Uf(e,t={}){let r=Ds("weierstrass",e,t),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;zt(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=qf(n,o);function p(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(A,b,O){let{x:P,y:V}=b.toAffine(),L=n.toBytes(P);if(Wr(O,"isCompressed"),O){p();let S=!n.isOdd(V);return M(kf(S),L)}else return M(Uint8Array.of(4),L,n.toBytes(V))}function l(A){gr(A,void 0,"Point");let{publicKey:b,publicKeyUncompressed:O}=u,P=A.length,V=A[0],L=A.subarray(1);if(P===b&&(V===2||V===3)){let S=n.fromBytes(L);if(!n.isValid(S))throw new Error("bad point: is not on curve, wrong x");let F=m(S),B;try{B=n.sqrt(F)}catch(ee){let te=ee instanceof Error?": "+ee.message:"";throw new Error("bad point: is not on curve, sqrt error"+te)}p();let q=n.isOdd(B);return(V&1)===1!==q&&(B=n.neg(B)),{x:S,y:B}}else if(P===O&&V===4){let S=n.BYTES,F=n.fromBytes(L.subarray(0,S)),B=n.fromBytes(L.subarray(S,S*2));if(!y(F,B))throw new Error("bad point: is not on curve");return{x:F,y:B}}else throw new Error(`bad point: got length ${P}, expected compressed=${b} or uncompressed=${O}`)}let f=t.toBytes||d,h=t.fromBytes||l;function m(A){let b=n.sqr(A),O=n.mul(b,A);return n.add(n.add(O,n.mul(A,s.a)),s.b)}function y(A,b){let O=n.sqr(b),P=m(A);return n.eql(O,P)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let _=n.mul(n.pow(s.a,Sn),Aa),x=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(_,x)))throw new Error("bad curve params: a or b");function g(A,b,O=!1){if(!n.isValid(b)||O&&n.is0(b))throw new Error(`bad point coordinate ${A}`);return b}function T(A){if(!(A instanceof w))throw new Error("ProjectivePoint expected")}function N(A){if(!c||!c.basises)throw new Error("no endo");return Df(A,c.basises,o.ORDER)}let E=xr((A,b)=>{let{X:O,Y:P,Z:V}=A;if(n.eql(V,n.ONE))return{x:O,y:P};let L=A.is0();b==null&&(b=L?n.ONE:n.inv(V));let S=n.mul(O,b),F=n.mul(P,b),B=n.mul(V,b);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x:S,y:F}}),R=xr(A=>{if(A.is0()){if(t.allowInfinityPoint&&!n.is0(A.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:O}=A.toAffine();if(!n.isValid(b)||!n.isValid(O))throw new Error("bad point: x or y not field elements");if(!y(b,O))throw new Error("bad point: equation left != right");if(!A.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function I(A,b,O,P,V){return O=new w(n.mul(O.X,A),O.Y,O.Z),b=To(P,b),O=To(V,O),b.add(O)}class w{constructor(b,O,P){this.X=g("x",b),this.Y=g("y",O,!0),this.Z=g("z",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){let{x:O,y:P}=b||{};if(!b||!n.isValid(O)||!n.isValid(P))throw new Error("invalid affine point");if(b instanceof w)throw new Error("projective point not allowed");return n.is0(O)&&n.is0(P)?w.ZERO:new w(O,P,n.ONE)}static fromBytes(b){let O=w.fromAffine(h(gr(b,void 0,"point")));return O.assertValidity(),O}static fromHex(b){return w.fromBytes(ce("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,O=!0){return C.createCache(this,b),O||this.multiply(Sn),this}assertValidity(){R(this)}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){T(b);let{X:O,Y:P,Z:V}=this,{X:L,Y:S,Z:F}=b,B=n.eql(n.mul(O,F),n.mul(L,V)),q=n.eql(n.mul(P,F),n.mul(S,V));return B&&q}negate(){return new w(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:O}=s,P=n.mul(O,Sn),{X:V,Y:L,Z:S}=this,F=n.ZERO,B=n.ZERO,q=n.ZERO,D=n.mul(V,V),ee=n.mul(L,L),te=n.mul(S,S),W=n.mul(V,L);return W=n.add(W,W),q=n.mul(V,S),q=n.add(q,q),F=n.mul(b,q),B=n.mul(P,te),B=n.add(F,B),F=n.sub(ee,B),B=n.add(ee,B),B=n.mul(F,B),F=n.mul(W,F),q=n.mul(P,q),te=n.mul(b,te),W=n.sub(D,te),W=n.mul(b,W),W=n.add(W,q),q=n.add(D,D),D=n.add(q,D),D=n.add(D,te),D=n.mul(D,W),B=n.add(B,D),te=n.mul(L,S),te=n.add(te,te),D=n.mul(te,W),F=n.sub(F,D),q=n.mul(te,ee),q=n.add(q,q),q=n.add(q,q),new w(F,B,q)}add(b){T(b);let{X:O,Y:P,Z:V}=this,{X:L,Y:S,Z:F}=b,B=n.ZERO,q=n.ZERO,D=n.ZERO,ee=s.a,te=n.mul(s.b,Sn),W=n.mul(O,L),De=n.mul(P,S),_e=n.mul(V,F),wt=n.add(O,P),ye=n.add(L,S);wt=n.mul(wt,ye),ye=n.add(W,De),wt=n.sub(wt,ye),ye=n.add(O,V);let $e=n.add(L,F);return ye=n.mul(ye,$e),$e=n.add(W,_e),ye=n.sub(ye,$e),$e=n.add(P,V),B=n.add(S,F),$e=n.mul($e,B),B=n.add(De,_e),$e=n.sub($e,B),D=n.mul(ee,ye),B=n.mul(te,_e),D=n.add(B,D),B=n.sub(De,D),D=n.add(De,D),q=n.mul(B,D),De=n.add(W,W),De=n.add(De,W),_e=n.mul(ee,_e),ye=n.mul(te,ye),De=n.add(De,_e),_e=n.sub(W,_e),_e=n.mul(ee,_e),ye=n.add(ye,_e),W=n.mul(De,ye),q=n.add(q,W),W=n.mul($e,ye),B=n.mul(wt,B),B=n.sub(B,W),W=n.mul(wt,De),D=n.mul($e,D),D=n.add(D,W),new w(B,q,D)}subtract(b){return this.add(b.negate())}is0(){return this.equals(w.ZERO)}multiply(b){let{endo:O}=t;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let P,V,L=S=>C.cached(this,S,F=>ot(w,F));if(O){let{k1neg:S,k1:F,k2neg:B,k2:q}=N(b),{p:D,f:ee}=L(F),{p:te,f:W}=L(q);V=ee.add(W),P=I(O.beta,D,te,S,B)}else{let{p:S,f:F}=L(b);P=S,V=F}return ot(w,[P,V])[0]}multiplyUnsafe(b){let{endo:O}=t,P=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===Jr||P.is0())return w.ZERO;if(b===je)return P;if(C.hasCache(this))return this.multiply(b);if(O){let{k1neg:V,k1:L,k2neg:S,k2:F}=N(b),{p1:B,p2:q}=hu(w,P,L,F);return I(O.beta,B,q,V,S)}else return C.unsafe(P,b)}multiplyAndAddUnsafe(b,O,P){let V=this.multiplyUnsafe(O).add(b.multiplyUnsafe(P));return V.is0()?void 0:V}toAffine(b){return E(this,b)}isTorsionFree(){let{isTorsionFree:b}=t;return i===je?!0:b?b(w,this):C.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=t;return i===je?this:b?b(w,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return Wr(b,"isCompressed"),this.assertValidity(),f(w,this,b)}toHex(b=!0){return K(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return ot(w,b)}static msm(b,O){return An(w,o,b,O)}static fromPrivateKey(b){return w.BASE.multiply(No(o,b))}}w.BASE=new w(s.Gx,s.Gy,n.ONE),w.ZERO=new w(n.ZERO,n.ONE,n.ZERO),w.Fp=n,w.Fn=o;let v=o.BITS,C=new In(w,t.endo?Math.ceil(v/2):v);return w.BASE.precompute(8),w}function kf(e){return Uint8Array.of(e?2:3)}function Lf(e,t){let r=e.ORDER,n=Jr;for(let h=r-je;h%Jt===Jr;h/=Jt)n+=je;let o=n,s=Jt<<o-je-je,i=s*Jt,a=(r-je)/i,c=(a-je)/Jt,u=i-je,p=s,d=e.pow(t,a),l=e.pow(t,(a+je)/Jt),f=(h,m)=>{let y=d,_=e.pow(m,u),x=e.sqr(_);x=e.mul(x,m);let g=e.mul(h,x);g=e.pow(g,c),g=e.mul(g,_),_=e.mul(g,m),x=e.mul(g,h);let T=e.mul(x,_);g=e.pow(T,p);let N=e.eql(g,e.ONE);_=e.mul(x,l),g=e.mul(T,y),x=e.cmov(_,x,N),T=e.cmov(g,T,N);for(let E=o;E>je;E--){let R=E-Jt;R=Jt<<R-je;let I=e.pow(T,R),w=e.eql(I,e.ONE);_=e.mul(x,y),y=e.mul(y,y),I=e.mul(T,y),x=e.cmov(_,x,w),T=e.cmov(I,T,w)}return{isValid:N,value:x}};if(e.ORDER%Aa===Sn){let h=(e.ORDER-Sn)/Aa,m=e.sqrt(e.neg(t));f=(y,_)=>{let x=e.sqr(_),g=e.mul(y,_);x=e.mul(x,g);let T=e.pow(x,h);T=e.mul(T,g);let N=e.mul(T,m),E=e.mul(e.sqr(T),_),R=e.eql(E,y),I=e.cmov(N,T,R);return{isValid:R,value:I}}}return f}function Sa(e,t){Bs(e);let{A:r,B:n,Z:o}=t;if(!e.isValid(r)||!e.isValid(n)||!e.isValid(o))throw new Error("mapToCurveSimpleSWU: invalid opts");let s=Lf(e,o);if(!e.isOdd)throw new Error("Field does not have .isOdd()");return i=>{let a,c,u,p,d,l,f,h;a=e.sqr(i),a=e.mul(a,o),c=e.sqr(a),c=e.add(c,a),u=e.add(c,e.ONE),u=e.mul(u,n),p=e.cmov(o,e.neg(c),!e.eql(c,e.ZERO)),p=e.mul(p,r),c=e.sqr(u),l=e.sqr(p),d=e.mul(l,r),c=e.add(c,d),c=e.mul(c,u),l=e.mul(l,p),d=e.mul(l,n),c=e.add(c,d),f=e.mul(a,u);let{isValid:m,value:y}=s(c,l);h=e.mul(a,i),h=e.mul(h,y),f=e.cmov(f,u,m),h=e.cmov(h,y,m);let _=e.isOdd(i)===e.isOdd(h);h=e.cmov(e.neg(h),h,_);let x=nt(e,[p],!0)[0];return f=e.mul(f,x),{x:f,y:h}}}function qf(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Pa(e){let{CURVE:t,curveOpts:r}=Mf(e),n=Uf(t,r);return Kf(e,n)}function Mf(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=Me(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),s={Fp:r,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function jf(e,t,r){function n(o){let s=e.sqr(o),i=e.mul(s,o);return e.add(e.add(i,e.mul(o,t)),r)}return n}function Kf(e,t){let{Fp:r,Fn:n}=t;function o(i){return xa(i,je,n.ORDER)}let s=jf(r,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:i=>No(n,i),weierstrassEquation:s,isWithinCurveOrder:o})}var Hf=BigInt(0),Us=BigInt(1),yu=BigInt(2),Pn=BigInt(3);function $f(e){let t=[];for(;e>Us;e>>=Us)(e&Us)===Hf?t.unshift(0):(e&Pn)===Pn?(t.unshift(-1),e+=Us):t.unshift(1);return t}function Ca(e){if(!Array.isArray(e)||e.length===0)throw new Error("expected non-empty array")}function Gf(e,t,r,n){let{Fp2:o,Fp12:s}=e,{twistType:i,ateLoopSize:a,xNegative:c,postPrecompute:u}=n,p;if(i==="multiplicative")p=(g,T,N,E,R,I)=>s.mul014(E,g,o.mul(T,R),o.mul(N,I));else if(i==="divisive")p=(g,T,N,E,R,I)=>s.mul034(E,o.mul(N,I),o.mul(T,R),g);else throw new Error("bls: unknown twist type");let d=o.div(o.ONE,o.mul(o.ONE,yu));function l(g,T,N,E){let R=o.sqr(N),I=o.sqr(E),w=o.mulByB(o.mul(I,Pn)),v=o.mul(w,Pn),C=o.sub(o.sub(o.sqr(o.add(N,E)),I),R),A=o.sub(w,R),b=o.mul(o.sqr(T),Pn),O=o.neg(C);return g.push([A,b,O]),T=o.mul(o.mul(o.mul(o.sub(R,v),T),N),d),N=o.sub(o.sqr(o.mul(o.add(R,v),d)),o.mul(o.sqr(w),Pn)),E=o.mul(R,C),{Rx:T,Ry:N,Rz:E}}function f(g,T,N,E,R,I){let w=o.sub(N,o.mul(I,E)),v=o.sub(T,o.mul(R,E)),C=o.sub(o.mul(w,R),o.mul(v,I)),A=o.neg(w),b=v;g.push([C,A,b]);let O=o.sqr(v),P=o.mul(O,v),V=o.mul(O,T),L=o.add(o.sub(P,o.mul(V,yu)),o.mul(o.sqr(w),E));return T=o.mul(v,L),N=o.sub(o.mul(o.sub(V,L),w),o.mul(P,N)),E=o.mul(E,P),{Rx:T,Ry:N,Rz:E}}let h=$f(a),m=xr(g=>{let T=g,{x:N,y:E}=T.toAffine(),R=N,I=E,w=o.neg(E),v=R,C=I,A=o.ONE,b=[];for(let O of h){let P=[];({Rx:v,Ry:C,Rz:A}=l(P,v,C,A)),O&&({Rx:v,Ry:C,Rz:A}=f(P,v,C,A,R,O===-1?w:I)),b.push(P)}if(u){let O=b[b.length-1];u(v,C,A,R,I,f.bind(null,O))}return b});function y(g,T=!1){let N=s.ONE;if(g.length){let E=g[0][0].length;for(let R=0;R<E;R++){N=s.sqr(N);for(let[I,w,v]of g)for(let[C,A,b]of I[R])N=p(C,A,b,N,w,v)}}return c&&(N=s.conjugate(N)),T?s.finalExponentiate(N):N}function _(g,T=!0){let N=[];ot(t,g.map(({g1:E})=>E)),ot(r,g.map(({g2:E})=>E));for(let{g1:E,g2:R}of g){if(E.is0()||R.is0())throw new Error("pairing is not available for ZERO point");E.assertValidity(),R.assertValidity();let I=E.toAffine();N.push([m(R),I.x,I.y])}return y(N,T)}function x(g,T,N=!0){return _([{g1:g,g2:T}],N)}return{Fp12:s,millerLoopBatch:y,pairing:x,pairingBatch:_,calcPairingPrecomputes:m}}function gu(e,t,r,n,o){let{Fp12:s,pairingBatch:i}=e;function a(d){return d instanceof t.Point?d:t.Point.fromHex(d)}function c(d){return d instanceof r.Point?d:r.Point.fromHex(d)}function u(d){if(!(d instanceof r.Point))throw new Error(`expected valid message hashed to ${o?"G1":"G2"} curve`);return d}let p=o?(d,l)=>({g1:l,g2:d}):(d,l)=>({g1:d,g2:l});return{getPublicKey(d){let l=No(t.Point.Fn,d);return t.Point.BASE.multiply(l)},sign(d,l,f){if(f!=null)throw new Error("sign() expects 2 arguments");let h=No(t.Point.Fn,l);return u(d).assertValidity(),d.multiply(h)},verify(d,l,f,h){if(h!=null)throw new Error("verify() expects 3 arguments");d=c(d),f=a(f);let m=f.negate(),y=t.Point.BASE,_=u(l),x=d,g=i([p(m,_),p(y,x)]);return s.eql(g,s.ONE)},verifyBatch(d,l,f){if(Ca(l),f.length!==l.length)throw new Error("amount of public keys and messages should be equal");let h=c(d),m=l,y=f.map(a),_=new Map;for(let T=0;T<y.length;T++){let N=y[T],E=m[T],R=_.get(E);R===void 0&&(R=[],_.set(E,R)),R.push(N)}let x=[],g=t.Point.BASE;try{for(let[T,N]of _){let E=N.reduce((R,I)=>R.add(I));x.push(p(E,T))}return x.push(p(g.negate(),h)),s.eql(i(x),s.ONE)}catch{return!1}},aggregatePublicKeys(d){Ca(d),d=d.map(f=>a(f));let l=d.reduce((f,h)=>f.add(h),t.Point.ZERO);return l.assertValidity(),l},aggregateSignatures(d){Ca(d),d=d.map(f=>c(f));let l=d.reduce((f,h)=>f.add(h),r.Point.ZERO);return l.assertValidity(),l},hash(d,l){de(d);let f=l?{DST:l}:void 0;return r.hashToCurve(d,f)},Signature:n}}function xu(e){let{Fp:t,Fr:r,Fp2:n,Fp6:o,Fp12:s}=e.fields,i=Pa(e.G1),a=Object.assign(i,Ia(i.Point,e.G1.mapToCurve,{...e.htfDefaults,...e.G1.htfDefaults})),c=Pa(e.G2),u=Object.assign(c,Ia(c.Point,e.G2.mapToCurve,{...e.htfDefaults,...e.G2.htfDefaults})),p=Gf(e.fields,a.Point,u.Point,{...e.params,postPrecompute:e.postPrecompute}),{millerLoopBatch:d,pairing:l,pairingBatch:f,calcPairingPrecomputes:h}=p,m=gu(p,a,u,e.G2.Signature,!1),y=gu(p,u,a,e.G1.ShortSignature,!0),_=e.randomBytes||dn,x=()=>{let S=Vs(r.ORDER);return Ta(_(S),r.ORDER)},g={randomSecretKey:x,randomPrivateKey:x,calcPairingPrecomputes:h},{ShortSignature:T}=e.G1,{Signature:N}=e.G2;function E(S,F){return S instanceof a.Point?S:y.hash(ce("point",S),F?.DST)}function R(S,F){return S instanceof u.Point?S:m.hash(ce("point",S),F?.DST)}function I(S){return m.getPublicKey(S).toBytes(!0)}function w(S){return y.getPublicKey(S).toBytes(!0)}function v(S,F,B){let q=R(S,B),D=m.sign(q,F);return S instanceof u.Point?D:N.toBytes(D)}function C(S,F,B){let q=E(S,B),D=y.sign(q,F);return S instanceof a.Point?D:T.toBytes(D)}function A(S,F,B,q){let D=R(F,q);return m.verify(S,D,B)}function b(S,F,B,q){let D=E(F,q);return y.verify(S,D,B)}function O(S){let F=m.aggregatePublicKeys(S);return S[0]instanceof a.Point?F:F.toBytes(!0)}function P(S){let F=m.aggregateSignatures(S);return S[0]instanceof u.Point?F:N.toBytes(F)}function V(S){let F=y.aggregateSignatures(S);return S[0]instanceof a.Point?F:T.toBytes(F)}function L(S,F,B,q){let D=F.map(ee=>R(ee,q));return m.verifyBatch(S,D,B)}return a.Point.BASE.precompute(4),{longSignatures:m,shortSignatures:y,millerLoopBatch:d,pairing:l,pairingBatch:f,verifyBatch:L,fields:{Fr:r,Fp:t,Fp2:n,Fp6:o,Fp12:s},params:{ateLoopSize:e.params.ateLoopSize,twistType:e.params.twistType,r:e.params.r,G1b:e.G1.b,G2b:e.G2.b},utils:g,getPublicKey:I,getPublicKeyForShortSignatures:w,sign:v,signShortSignature:C,verify:A,verifyShortSignature:b,aggregatePublicKeys:O,aggregateSignatures:P,aggregateShortSignatures:V,G1:a,G2:u,Signature:N,ShortSignature:T}}var bu=BigInt(0),Zt=BigInt(1),Ke=BigInt(2),wu=BigInt(3);function Da(e,t,r,n,o=1,s){let i=BigInt(s===void 0?n:s),a=r**BigInt(n),c=[];for(let u=0;u<o;u++){let p=BigInt(u+1),d=[];for(let l=0,f=Zt;l<n;l++){let h=(p*f-p)/i%a;d.push(e.pow(t,h)),f*=r}c.push(d)}return c}function Ou(e,t,r){let n=t.pow(r,(e.ORDER-Zt)/wu),o=t.pow(r,(e.ORDER-Zt)/Ke);function s(l,f){let h=t.mul(t.frobeniusMap(l,1),n),m=t.mul(t.frobeniusMap(f,1),o);return[h,m]}let i=t.pow(r,(e.ORDER**Ke-Zt)/wu),a=t.pow(r,(e.ORDER**Ke-Zt)/Ke);if(!t.eql(a,t.neg(t.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(l,f){return[t.mul(l,i),t.neg(f)]}let u=l=>(f,h)=>{let m=h.toAffine(),y=l(m.x,m.y);return f.fromAffine({x:y[0],y:y[1]})},p=u(s),d=u(c);return{psi:s,psi2:c,G2psi:p,G2psi2:d,PSI_X:n,PSI_Y:o,PSI2_X:i,PSI2_Y:a}}var Tu=(e,t)=>{if(t.length!==2)throw new Error("invalid tuple");let r=t.map(n=>e.create(n));return{c0:r[0],c1:r[1]}},Fa=class{constructor(t,r={}){this.MASK=Zt;let n=t.ORDER,o=n*n;this.Fp=t,this.ORDER=o,this.BITS=Wt(o),this.BYTES=Math.ceil(Wt(o)/8),this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO},this.Fp_NONRESIDUE=t.create(r.NONRESIDUE||BigInt(-1)),this.Fp_div2=t.div(t.ONE,Ke),this.NONRESIDUE=Tu(t,r.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=Da(t,this.Fp_NONRESIDUE,t.ORDER,2)[0],this.mulByB=r.Fp2mulByB,Object.seal(this)}fromBigTuple(t){return Tu(this.Fp,t)}create(t){return t}isValid({c0:t,c1:r}){function n(o,s){return typeof o=="bigint"&&bu<=o&&o<s}return n(t,this.ORDER)&&n(r,this.ORDER)}is0({c0:t,c1:r}){return this.Fp.is0(t)&&this.Fp.is0(r)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}eql({c0:t,c1:r},{c0:n,c1:o}){return this.Fp.eql(t,n)&&this.Fp.eql(r,o)}neg({c0:t,c1:r}){return{c0:this.Fp.neg(t),c1:this.Fp.neg(r)}}pow(t,r){return wo(this,t,r)}invertBatch(t){return nt(this,t)}add(t,r){let{c0:n,c1:o}=t,{c0:s,c1:i}=r;return{c0:this.Fp.add(n,s),c1:this.Fp.add(o,i)}}sub({c0:t,c1:r},{c0:n,c1:o}){return{c0:this.Fp.sub(t,n),c1:this.Fp.sub(r,o)}}mul({c0:t,c1:r},n){let{Fp:o}=this;if(typeof n=="bigint")return{c0:o.mul(t,n),c1:o.mul(r,n)};let{c0:s,c1:i}=n,a=o.mul(t,s),c=o.mul(r,i),u=o.sub(a,c),p=o.sub(o.mul(o.add(t,r),o.add(s,i)),o.add(a,c));return{c0:u,c1:p}}sqr({c0:t,c1:r}){let{Fp:n}=this,o=n.add(t,r),s=n.sub(t,r),i=n.add(t,t);return{c0:n.mul(o,s),c1:n.mul(i,r)}}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}div(t,r){let{Fp:n}=this;return this.mul(t,typeof r=="bigint"?n.inv(n.create(r)):this.inv(r))}inv({c0:t,c1:r}){let{Fp:n}=this,o=n.inv(n.create(t*t+r*r));return{c0:n.mul(o,n.create(t)),c1:n.mul(o,n.create(-r))}}sqrt(t){let{Fp:r}=this,n=this,{c0:o,c1:s}=t;if(r.is0(s))return bo(r,o)===1?n.create({c0:r.sqrt(o),c1:r.ZERO}):n.create({c0:r.ZERO,c1:r.sqrt(r.div(o,this.Fp_NONRESIDUE))});let i=r.sqrt(r.sub(r.sqr(o),r.mul(r.sqr(s),this.Fp_NONRESIDUE))),a=r.mul(r.add(i,o),this.Fp_div2);bo(r,a)===-1&&(a=r.sub(a,i));let u=r.sqrt(a),p=n.create({c0:u,c1:r.div(r.mul(s,this.Fp_div2),u)});if(!n.eql(n.sqr(p),t))throw new Error("Cannot find square root");let d=p,l=n.neg(d),{re:f,im:h}=n.reim(d),{re:m,im:y}=n.reim(l);return h>y||h===y&&f>m?d:l}isOdd(t){let{re:r,im:n}=this.reim(t),o=r%Ke,s=r===bu,i=n%Ke;return BigInt(o||s&&i)==Zt}fromBytes(t){let{Fp:r}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return{c0:r.fromBytes(t.subarray(0,r.BYTES)),c1:r.fromBytes(t.subarray(r.BYTES))}}toBytes({c0:t,c1:r}){return M(this.Fp.toBytes(t),this.Fp.toBytes(r))}cmov({c0:t,c1:r},{c0:n,c1:o},s){return{c0:this.Fp.cmov(t,n,s),c1:this.Fp.cmov(r,o,s)}}reim({c0:t,c1:r}){return{re:t,im:r}}Fp4Square(t,r){let n=this,o=n.sqr(t),s=n.sqr(r);return{first:n.add(n.mulByNonresidue(s),o),second:n.sub(n.sub(n.sqr(n.add(t,r)),o),s)}}mulByNonresidue({c0:t,c1:r}){return this.mul({c0:t,c1:r},this.NONRESIDUE)}frobeniusMap({c0:t,c1:r},n){return{c0:t,c1:this.Fp.mul(r,this.FROBENIUS_COEFFICIENTS[n%2])}}},Ba=class{constructor(t){this.MASK=Zt,this.Fp2=t,this.ORDER=t.ORDER,this.BITS=3*t.BITS,this.BYTES=3*t.BYTES,this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO,c2:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO,c2:t.ZERO};let{Fp:r}=t,n=Da(t,t.NONRESIDUE,r.ORDER,6,2,3);this.FROBENIUS_COEFFICIENTS_1=n[0],this.FROBENIUS_COEFFICIENTS_2=n[1],Object.seal(this)}add({c0:t,c1:r,c2:n},{c0:o,c1:s,c2:i}){let{Fp2:a}=this;return{c0:a.add(t,o),c1:a.add(r,s),c2:a.add(n,i)}}sub({c0:t,c1:r,c2:n},{c0:o,c1:s,c2:i}){let{Fp2:a}=this;return{c0:a.sub(t,o),c1:a.sub(r,s),c2:a.sub(n,i)}}mul({c0:t,c1:r,c2:n},o){let{Fp2:s}=this;if(typeof o=="bigint")return{c0:s.mul(t,o),c1:s.mul(r,o),c2:s.mul(n,o)};let{c0:i,c1:a,c2:c}=o,u=s.mul(t,i),p=s.mul(r,a),d=s.mul(n,c);return{c0:s.add(u,s.mulByNonresidue(s.sub(s.mul(s.add(r,n),s.add(a,c)),s.add(p,d)))),c1:s.add(s.sub(s.mul(s.add(t,r),s.add(i,a)),s.add(u,p)),s.mulByNonresidue(d)),c2:s.sub(s.add(p,s.mul(s.add(t,n),s.add(i,c))),s.add(u,d))}}sqr({c0:t,c1:r,c2:n}){let{Fp2:o}=this,s=o.sqr(t),i=o.mul(o.mul(t,r),Ke),a=o.mul(o.mul(r,n),Ke),c=o.sqr(n);return{c0:o.add(o.mulByNonresidue(a),s),c1:o.add(o.mulByNonresidue(c),i),c2:o.sub(o.sub(o.add(o.add(i,o.sqr(o.add(o.sub(t,r),n))),a),s),c)}}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}create(t){return t}isValid({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return o.isValid(t)&&o.isValid(r)&&o.isValid(n)}is0({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return o.is0(t)&&o.is0(r)&&o.is0(n)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return{c0:o.neg(t),c1:o.neg(r),c2:o.neg(n)}}eql({c0:t,c1:r,c2:n},{c0:o,c1:s,c2:i}){let{Fp2:a}=this;return a.eql(t,o)&&a.eql(r,s)&&a.eql(n,i)}sqrt(t){return Rn()}div(t,r){let{Fp2:n}=this,{Fp:o}=n;return this.mul(t,typeof r=="bigint"?o.inv(o.create(r)):this.inv(r))}pow(t,r){return wo(this,t,r)}invertBatch(t){return nt(this,t)}inv({c0:t,c1:r,c2:n}){let{Fp2:o}=this,s=o.sub(o.sqr(t),o.mulByNonresidue(o.mul(n,r))),i=o.sub(o.mulByNonresidue(o.sqr(n)),o.mul(t,r)),a=o.sub(o.sqr(r),o.mul(t,n)),c=o.inv(o.add(o.mulByNonresidue(o.add(o.mul(n,i),o.mul(r,a))),o.mul(t,s)));return{c0:o.mul(c,s),c1:o.mul(c,i),c2:o.mul(c,a)}}fromBytes(t){let{Fp2:r}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);let n=r.BYTES;return{c0:r.fromBytes(t.subarray(0,n)),c1:r.fromBytes(t.subarray(n,n*2)),c2:r.fromBytes(t.subarray(2*n))}}toBytes({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return M(o.toBytes(t),o.toBytes(r),o.toBytes(n))}cmov({c0:t,c1:r,c2:n},{c0:o,c1:s,c2:i},a){let{Fp2:c}=this;return{c0:c.cmov(t,o,a),c1:c.cmov(r,s,a),c2:c.cmov(n,i,a)}}fromBigSix(t){let{Fp2:r}=this;if(!Array.isArray(t)||t.length!==6)throw new Error("invalid Fp6 usage");return{c0:r.fromBigTuple(t.slice(0,2)),c1:r.fromBigTuple(t.slice(2,4)),c2:r.fromBigTuple(t.slice(4,6))}}frobeniusMap({c0:t,c1:r,c2:n},o){let{Fp2:s}=this;return{c0:s.frobeniusMap(t,o),c1:s.mul(s.frobeniusMap(r,o),this.FROBENIUS_COEFFICIENTS_1[o%6]),c2:s.mul(s.frobeniusMap(n,o),this.FROBENIUS_COEFFICIENTS_2[o%6])}}mulByFp2({c0:t,c1:r,c2:n},o){let{Fp2:s}=this;return{c0:s.mul(t,o),c1:s.mul(r,o),c2:s.mul(n,o)}}mulByNonresidue({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return{c0:o.mulByNonresidue(n),c1:t,c2:r}}mul1({c0:t,c1:r,c2:n},o){let{Fp2:s}=this;return{c0:s.mulByNonresidue(s.mul(n,o)),c1:s.mul(t,o),c2:s.mul(r,o)}}mul01({c0:t,c1:r,c2:n},o,s){let{Fp2:i}=this,a=i.mul(t,o),c=i.mul(r,s);return{c0:i.add(i.mulByNonresidue(i.sub(i.mul(i.add(r,n),s),c)),a),c1:i.sub(i.sub(i.mul(i.add(o,s),i.add(t,r)),a),c),c2:i.add(i.sub(i.mul(i.add(t,n),o),a),c)}}},Va=class{constructor(t,r){this.MASK=Zt;let{Fp2:n}=t,{Fp:o}=n;this.Fp6=t,this.ORDER=n.ORDER,this.BITS=2*t.BITS,this.BYTES=2*t.BYTES,this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO},this.FROBENIUS_COEFFICIENTS=Da(n,n.NONRESIDUE,o.ORDER,12,1,6)[0],this.X_LEN=r.X_LEN,this.finalExponentiate=r.Fp12finalExponentiate}create(t){return t}isValid({c0:t,c1:r}){let{Fp6:n}=this;return n.isValid(t)&&n.isValid(r)}is0({c0:t,c1:r}){let{Fp6:n}=this;return n.is0(t)&&n.is0(r)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:r}){let{Fp6:n}=this;return{c0:n.neg(t),c1:n.neg(r)}}eql({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:s}=this;return s.eql(t,n)&&s.eql(r,o)}sqrt(t){Rn()}inv({c0:t,c1:r}){let{Fp6:n}=this,o=n.inv(n.sub(n.sqr(t),n.mulByNonresidue(n.sqr(r))));return{c0:n.mul(t,o),c1:n.neg(n.mul(r,o))}}div(t,r){let{Fp6:n}=this,{Fp2:o}=n,{Fp:s}=o;return this.mul(t,typeof r=="bigint"?s.inv(s.create(r)):this.inv(r))}pow(t,r){return wo(this,t,r)}invertBatch(t){return nt(this,t)}add({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:s}=this;return{c0:s.add(t,n),c1:s.add(r,o)}}sub({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:s}=this;return{c0:s.sub(t,n),c1:s.sub(r,o)}}mul({c0:t,c1:r},n){let{Fp6:o}=this;if(typeof n=="bigint")return{c0:o.mul(t,n),c1:o.mul(r,n)};let{c0:s,c1:i}=n,a=o.mul(t,s),c=o.mul(r,i);return{c0:o.add(a,o.mulByNonresidue(c)),c1:o.sub(o.mul(o.add(t,r),o.add(s,i)),o.add(a,c))}}sqr({c0:t,c1:r}){let{Fp6:n}=this,o=n.mul(t,r);return{c0:n.sub(n.sub(n.mul(n.add(n.mulByNonresidue(r),t),n.add(t,r)),o),n.mulByNonresidue(o)),c1:n.add(o,o)}}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}fromBytes(t){let{Fp6:r}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return{c0:r.fromBytes(t.subarray(0,r.BYTES)),c1:r.fromBytes(t.subarray(r.BYTES))}}toBytes({c0:t,c1:r}){let{Fp6:n}=this;return M(n.toBytes(t),n.toBytes(r))}cmov({c0:t,c1:r},{c0:n,c1:o},s){let{Fp6:i}=this;return{c0:i.cmov(t,n,s),c1:i.cmov(r,o,s)}}fromBigTwelve(t){let{Fp6:r}=this;return{c0:r.fromBigSix(t.slice(0,6)),c1:r.fromBigSix(t.slice(6,12))}}frobeniusMap(t,r){let{Fp6:n}=this,{Fp2:o}=n,{c0:s,c1:i,c2:a}=n.frobeniusMap(t.c1,r),c=this.FROBENIUS_COEFFICIENTS[r%12];return{c0:n.frobeniusMap(t.c0,r),c1:n.create({c0:o.mul(s,c),c1:o.mul(i,c),c2:o.mul(a,c)})}}mulByFp2({c0:t,c1:r},n){let{Fp6:o}=this;return{c0:o.mulByFp2(t,n),c1:o.mulByFp2(r,n)}}conjugate({c0:t,c1:r}){return{c0:t,c1:this.Fp6.neg(r)}}mul014({c0:t,c1:r},n,o,s){let{Fp6:i}=this,{Fp2:a}=i,c=i.mul01(t,n,o),u=i.mul1(r,s);return{c0:i.add(i.mulByNonresidue(u),c),c1:i.sub(i.sub(i.mul01(i.add(r,t),n,a.add(o,s)),c),u)}}mul034({c0:t,c1:r},n,o,s){let{Fp6:i}=this,{Fp2:a}=i,c=i.create({c0:a.mul(t.c0,n),c1:a.mul(t.c1,n),c2:a.mul(t.c2,n)}),u=i.mul01(r,o,s),p=i.mul01(i.add(t,r),a.add(n,o),s);return{c0:i.add(i.mulByNonresidue(u),c),c1:i.sub(p,i.add(c,u))}}_cyclotomicSquare({c0:t,c1:r}){let{Fp6:n}=this,{Fp2:o}=n,{c0:s,c1:i,c2:a}=t,{c0:c,c1:u,c2:p}=r,{first:d,second:l}=o.Fp4Square(s,u),{first:f,second:h}=o.Fp4Square(c,a),{first:m,second:y}=o.Fp4Square(i,p),_=o.mulByNonresidue(y);return{c0:n.create({c0:o.add(o.mul(o.sub(d,s),Ke),d),c1:o.add(o.mul(o.sub(f,i),Ke),f),c2:o.add(o.mul(o.sub(m,a),Ke),m)}),c1:n.create({c0:o.add(o.mul(o.add(_,c),Ke),_),c1:o.add(o.mul(o.add(l,u),Ke),l),c2:o.add(o.mul(o.add(h,p),Ke),h)})}}_cyclotomicExp(t,r){let n=this.ONE;for(let o=this.X_LEN-1;o>=0;o--)n=this._cyclotomicSquare(n),Xl(r,o)&&(n=this.mul(n,t));return n}};function Nu(e){let t=Me(e.ORDER),r=new Fa(t,e),n=new Ba(r),o=new Va(n,e);return{Fp:t,Fp2:r,Fp6:n,Fp12:o}}var Fe=BigInt(0),ks=BigInt(1),st=BigInt(2),Ls=BigInt(3),Eo=BigInt(4),wr=BigInt("0xd201000000010000"),Wf=Wt(wr),Zr={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:Fe,b:Eo,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},zf=Me(Zr.n,{modFromBytes:!0,isLE:!0}),{Fp:U,Fp2:G,Fp6:Yf,Fp12:J}=Nu({ORDER:Zr.p,X_LEN:Wf,FP2_NONRESIDUE:[ks,ks],Fp2mulByB:({c0:e,c1:t})=>{let r=U.mul(e,Eo),n=U.mul(t,Eo);return{c0:U.sub(r,n),c1:U.add(r,n)}},Fp12finalExponentiate:e=>{let t=wr,r=J.div(J.frobeniusMap(e,6),e),n=J.mul(J.frobeniusMap(r,2),r),o=J.conjugate(J._cyclotomicExp(n,t)),s=J.mul(J.conjugate(J._cyclotomicSquare(n)),o),i=J.conjugate(J._cyclotomicExp(s,t)),a=J.conjugate(J._cyclotomicExp(i,t)),c=J.mul(J.conjugate(J._cyclotomicExp(a,t)),J._cyclotomicSquare(o)),u=J.conjugate(J._cyclotomicExp(c,t)),p=J.frobeniusMap(J.mul(o,a),2),d=J.frobeniusMap(J.mul(i,n),3),l=J.frobeniusMap(J.mul(c,J.conjugate(n)),1),f=J.mul(J.mul(u,J.conjugate(s)),n);return J.mul(J.mul(J.mul(p,d),l),f)}}),{G2psi:Eu,G2psi2:Jf}=Ou(U,G,G.div(G.ONE,G.NONRESIDUE)),Ua=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:U.ORDER,m:2,k:128,expand:"xmd",hash:Ce}),qa={p:G.ORDER,n:Zr.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:G.ZERO,b:G.fromBigTuple([Eo,Eo]),Gx:G.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:G.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},qs=Ro(U.toBytes(Fe),{infinity:!0,compressed:!0});function Ms(e){e=e.slice();let t=e[0]&224,r=!!(t>>7&1),n=!!(t>>6&1),o=!!(t>>5&1);return e[0]&=31,{compressed:r,infinity:n,sort:o,value:e}}function Ro(e,t){if(e[0]&224)throw new Error("setMask: non-empty mask");return t.compressed&&(e[0]|=128),t.infinity&&(e[0]|=64),t.sort&&(e[0]|=32),e}function Zf(e,t,r){let{BYTES:n,ORDER:o}=U,s=t.is0(),{x:i,y:a}=t.toAffine();if(r){if(s)return qs.slice();let c=!!(a*st/o);return Ro(we(i,n),{compressed:!0,sort:c})}else return s?M(Uint8Array.of(64),new Uint8Array(2*n-1)):M(we(i,n),we(a,n))}function ka(e){e.assertValidity();let{BYTES:t,ORDER:r}=U,{x:n,y:o}=e.toAffine();if(e.is0())return qs.slice();let s=!!(o*st/r);return Ro(we(n,t),{compressed:!0,sort:s})}function Xf(e){let{compressed:t,infinity:r,sort:n,value:o}=Ms(e),{BYTES:s,ORDER:i}=U;if(o.length===48&&t){let a=ze(o),c=U.create(a&gt(U.BITS));if(r){if(c!==Fe)throw new Error("invalid G1 point: non-empty, at infinity, with compression");return{x:Fe,y:Fe}}let u=U.add(U.pow(c,Ls),U.create(Zr.b)),p=U.sqrt(u);if(!p)throw new Error("invalid G1 point: compressed point");return p*st/i!==BigInt(n)&&(p=U.neg(p)),{x:U.create(c),y:U.create(p)}}else if(o.length===96&&!t){let a=ze(o.subarray(0,s)),c=ze(o.subarray(s));if(r){if(a!==Fe||c!==Fe)throw new Error("G1: non-empty point at infinity");return vo.G1.Point.ZERO.toAffine()}return{x:U.create(a),y:U.create(c)}}else throw new Error("invalid G1 point: expected 48/96 bytes")}function Ru(e){let{infinity:t,sort:r,value:n}=Ms(ce("signatureHex",e,48)),o=U.ORDER,s=vo.G1.Point,i=ze(n);if(t)return s.ZERO;let a=U.create(i&gt(U.BITS)),c=U.add(U.pow(a,Ls),U.create(Zr.b)),u=U.sqrt(c);if(!u)throw new Error("invalid G1 point: compressed");let p=BigInt(r);u*st/o!==p&&(u=U.neg(u));let d=s.fromAffine({x:a,y:u});return d.assertValidity(),d}function Qf(e,t,r){let{BYTES:n,ORDER:o}=U,s=t.is0(),{x:i,y:a}=t.toAffine();if(r){if(s)return M(qs,we(Fe,n));let c=!!(a.c1===Fe?a.c0*st/o:a.c1*st/o);return M(Ro(we(i.c1,n),{compressed:!0,sort:c}),we(i.c0,n))}else{if(s)return M(Uint8Array.of(64),new Uint8Array(4*n-1));let{re:c,im:u}=G.reim(i),{re:p,im:d}=G.reim(a);return M(we(u,n),we(c,n),we(d,n),we(p,n))}}function La(e){e.assertValidity();let{BYTES:t}=U;if(e.is0())return M(qs,we(Fe,t));let{x:r,y:n}=e.toAffine(),{re:o,im:s}=G.reim(r),{re:i,im:a}=G.reim(n),u=!!((a>Fe?a*st:i*st)/U.ORDER&ks),p=o;return M(Ro(we(s,t),{sort:u,compressed:!0}),we(p,t))}function eh(e){let{BYTES:t,ORDER:r}=U,{compressed:n,infinity:o,sort:s,value:i}=Ms(e);if(!n&&!o&&s||!n&&o&&s||s&&o&&n)throw new Error("invalid encoding flag: "+(e[0]&224));let a=(c,u,p)=>ze(c.slice(u,p));if(i.length===96&&n){if(o){if(i.reduce((h,m)=>h!==0?m+1:m,0)>0)throw new Error("invalid G2 point: compressed");return{x:G.ZERO,y:G.ZERO}}let c=a(i,0,t),u=a(i,t,2*t),p=G.create({c0:U.create(u),c1:U.create(c)}),d=G.add(G.pow(p,Ls),qa.b),l=G.sqrt(d),f=l.c1===Fe?l.c0*st/r:l.c1*st/r?ks:Fe;return l=s&&f>0?l:G.neg(l),{x:p,y:l}}else if(i.length===192&&!n){if(o){if(i.reduce((l,f)=>l!==0?f+1:f,0)>0)throw new Error("invalid G2 point: uncompressed");return{x:G.ZERO,y:G.ZERO}}let c=a(i,0*t,1*t),u=a(i,1*t,2*t),p=a(i,2*t,3*t),d=a(i,3*t,4*t);return{x:G.fromBigTuple([u,c]),y:G.fromBigTuple([d,p])}}else throw new Error("invalid G2 point: expected 96/192 bytes")}function vu(e){let{ORDER:t}=U,{infinity:r,sort:n,value:o}=Ms(ce("signatureHex",e)),s=vo.G2.Point,i=o.length/2;if(i!==48&&i!==96)throw new Error("invalid compressed signature length, expected 96/192 bytes");let a=ze(o.slice(0,i)),c=ze(o.slice(i));if(r)return s.ZERO;let u=U.create(a&gt(U.BITS)),p=U.create(c),d=G.create({c0:p,c1:u}),l=G.add(G.pow(d,Ls),qa.b),f=G.sqrt(l);if(!f)throw new Error("Failed to find a square root");let{re:h,im:m}=G.reim(f),y=BigInt(n),_=m>Fe&&m*st/t!==y,x=m===Fe&&h*st/t!==y;(_||x)&&(f=G.neg(f));let g=s.fromAffine({x:d,y:f});return g.assertValidity(),g}var vo=xu({fields:{Fp:U,Fp2:G,Fp6:Yf,Fp12:J,Fr:zf},G1:{...Zr,Fp:U,htfDefaults:{...Ua,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(e,t)=>{let r=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),n=new e(U.mul(t.X,r),t.Y,t.Z);return t.multiplyUnsafe(wr).negate().multiplyUnsafe(wr).equals(n)},clearCofactor:(e,t)=>t.multiplyUnsafe(wr).add(t),mapToCurve:sh,fromBytes:Xf,toBytes:Zf,ShortSignature:{fromBytes(e){return de(e),Ru(e)},fromHex(e){return Ru(e)},toBytes(e){return ka(e)},toRawBytes(e){return ka(e)},toHex(e){return K(ka(e))}}},G2:{...qa,Fp:G,hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...Ua},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:ih,isTorsionFree:(e,t)=>t.multiplyUnsafe(wr).negate().equals(Eu(e,t)),clearCofactor:(e,t)=>{let r=wr,n=t.multiplyUnsafe(r).negate(),o=Eu(e,t),s=t.double();return s=Jf(e,s),s=s.subtract(o),o=n.add(o),o=o.multiplyUnsafe(r).negate(),s=s.add(o),s=s.subtract(n),s.subtract(t)},fromBytes:eh,toBytes:Qf,Signature:{fromBytes(e){return de(e),vu(e)},fromHex(e){return vu(e)},toBytes(e){return La(e)},toRawBytes(e){return La(e)},toHex(e){return K(La(e))}}},params:{ateLoopSize:wr,r:Zr.n,xNegative:!0,twistType:"multiplicative"},htfDefaults:Ua,hash:Ce}),th=va(G,[[["0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6"],["0x0","0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d"],["0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1","0x0"]],[["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63"],["0xc","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f"],["0x1","0x0"]],[["0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706","0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706"],["0x0","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f"],["0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10","0x0"]],[["0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb"],["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3"],["0x12","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99"],["0x1","0x0"]]].map(e=>e.map(t=>G.fromBigTuple(t.map(BigInt))))),rh=va(U,[["0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7","0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb","0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0","0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861","0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9","0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983","0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84","0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e","0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317","0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e","0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b","0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229"],["0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c","0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff","0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19","0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8","0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e","0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5","0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a","0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e","0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641","0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"],["0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33","0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696","0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6","0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb","0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb","0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0","0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2","0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29","0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587","0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30","0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132","0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e","0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8","0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133","0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b","0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604"],["0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1","0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d","0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2","0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416","0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d","0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac","0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c","0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9","0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a","0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55","0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8","0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092","0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc","0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7","0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),nh=Sa(U,{A:U.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:U.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:U.create(BigInt(11))}),oh=Sa(G,{A:G.create({c0:U.create(Fe),c1:U.create(BigInt(240))}),B:G.create({c0:U.create(BigInt(1012)),c1:U.create(BigInt(1012))}),Z:G.create({c0:U.create(BigInt(-2)),c1:U.create(BigInt(-1))})});function sh(e){let{x:t,y:r}=nh(U.create(e[0]));return rh(t,r)}function ih(e){let{x:t,y:r}=oh(G.fromBigTuple(e));return th(t,r)}function Iu(e,t,r){let n=typeof e=="string"?e:K(e),o=typeof t=="string"?t:K(t),s=typeof r=="string"?r:K(r);return vo.verifyShortSignature(o,s,n)}var ch=BigInt(1e6),Ma=e=>he(new ft(e)),Cn=e=>{let r=Ma(e)/ch;return new Date(Number(r))};var Au=60*1e3,lh=60,uh=24,dh=uh*lh,ph=5,fh=5,hh=30*dh,Pe;(function(e){e[e.Empty=0]="Empty",e[e.Fork=1]="Fork",e[e.Labeled=2]="Labeled",e[e.Leaf=3]="Leaf",e[e.Pruned=4]="Pruned"})(Pe||(Pe={}));function mh(e,t){for(let r=0;r<e.length;r++)if(e[r]>t[r])return!0;return!1}var Tr=class e{#e=!1;#t=void 0;static async create(t){let r=e.createUnverified(t);return await r.verify(),r}static createUnverified(t){return new e(t.certificate,t.rootKey,t.canisterId,t.blsVerify??Iu,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(t,r,n,o,s=ph,i=!1,a){this._rootKey=r,this._canisterId=n,this._blsVerify=o,this._maxAgeInMinutes=s,this.#e=i,this.cert=We(t),a&&"getTimeDiffMsecs"in a&&"hasSyncedTime"in a&&"syncTime"in a&&(this.#t=a)}lookup_path(t){return Qr(t,this.cert.tree)}lookup_subtree(t){return Hs(t,this.cert.tree)}async verify(){let t=await js(this.cert.tree),r=await this._checkDelegationAndGetKey(this.cert.delegation),n=this.cert.signature,o=yh(r),s=M(Ao("ic-state-root"),t),i=Be(this.lookup_path(["time"]));if(!i)throw re.fromCode(new dr("Certificate does not contain a time"));if(!this.#e){let a=this.#t?.getTimeDiffMsecs()??0,c=this._maxAgeInMinutes*Au,u=new Date,p=u.getTime()+a,d=p-c,l=p+fh*Au,f=Cn(i),h=f.getTime()<d,m=f.getTime()>l;if((h||m)&&this.#t&&!this.#t.hasSyncedTime())return await this.#t.syncTime(this._canisterId),await this.verify();if(h)throw Ue.fromCode(new Ur(this._maxAgeInMinutes,f,u,a,"past"));if(m)throw this.#t?.hasSyncedTime()?ge.fromCode(new ke("System time has been synced with the IC network, but certificate is still too far in the future.")):Ue.fromCode(new Ur(5,f,u,a,"future"))}try{if(!await this._blsVerify(o,n,s))throw Ue.fromCode(new dr("Invalid signature"))}catch(a){throw Ue.fromCode(new dr("Signature verification failed",a))}}async _checkDelegationAndGetKey(t){if(!t)return this._rootKey;let r=e.createUnverified({certificate:t.certificate,rootKey:this._rootKey,canisterId:this._canisterId,blsVerify:this._blsVerify,disableTimeVerification:this.#e,maxAgeInMinutes:hh,agent:this.#t});if(r.cert.delegation)throw re.fromCode(new ts);await r.verify();let n=t.subnet_id,o=k.fromUint8Array(n);if(!ja({canisterId:this._canisterId,subnetId:o,tree:r.cert.tree}))throw Ue.fromCode(new pn(this._canisterId,o));let i=Be(r.lookup_path(["subnet",n,"public_key"]));if(!i)throw Ue.fromCode(new rs(`Could not find subnet key for subnet ID ${o.toText()}`));return i}},Io=Ne("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),_h=96;function yh(e){let t=Io.byteLength+_h;if(e.byteLength!==t)throw re.fromCode(new hn(t,e.byteLength));let r=e.slice(0,Io.byteLength);if(!Hr(r,Io))throw re.fromCode(new ns(Io,r));return e.slice(Io.byteLength)}function Be(e){if(e.status===Ye.Found&&e.value instanceof Uint8Array)return e.value}async function js(e){switch(e[0]){case Pe.Empty:return Ce(Ao("ic-hashtree-empty"));case Pe.Pruned:return e[1];case Pe.Leaf:return Ce(M(Ao("ic-hashtree-leaf"),e[1]));case Pe.Labeled:return Ce(M(Ao("ic-hashtree-labeled"),e[1],await js(e[2])));case Pe.Fork:return Ce(M(Ao("ic-hashtree-fork"),await js(e[1]),await js(e[2])));default:throw hr}}function Ao(e){let t=new Uint8Array([e.length]),r=new TextEncoder().encode(e);return M(t,r)}function Su(e){return typeof e[0]=="string"?Q(e[0]):e[0]}var Ye;(function(e){e.Unknown="Unknown",e.Absent="Absent",e.Found="Found",e.Error="Error"})(Ye||(Ye={}));var Xr;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found"})(Xr||(Xr={}));var se;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found",e.Less="Less",e.Greater="Greater"})(se||(se={}));function Qr(e,t){if(e.length===0)switch(t[0]){case Pe.Empty:return{status:Ye.Absent};case Pe.Leaf:{if(!t[1])throw ge.fromCode(new fr("Invalid tree structure for leaf"));if(t[1]instanceof Uint8Array)return{status:Ye.Found,value:t[1].slice(t[1].byteOffset,t[1].byteLength+t[1].byteOffset)};throw hr}case Pe.Pruned:return{status:Ye.Unknown};case Pe.Labeled:case Pe.Fork:return{status:Ye.Error};default:throw hr}let r=Su(e),n=So(r,t);switch(n.status){case se.Found:return Qr(e.slice(1),n.value);case se.Absent:case se.Greater:case se.Less:return{status:Ye.Absent};case se.Unknown:return{status:Ye.Unknown};default:throw hr}}function Hs(e,t){if(e.length===0)return{status:Xr.Found,value:t};let r=Su(e),n=So(r,t);switch(n.status){case se.Found:return Hs(e.slice(1),n.value);case se.Unknown:return{status:Xr.Unknown};case se.Absent:case se.Greater:case se.Less:return{status:Xr.Absent};default:throw hr}}function Ks(e){switch(e[0]){case Pe.Empty:return[];case Pe.Fork:return Ks(e[1]).concat(Ks(e[2]));default:return[e]}}function So(e,t){switch(t[0]){case Pe.Labeled:return mh(e,t[1])?{status:se.Greater}:Hr(e,t[1])?{status:se.Found,value:t[2]}:{status:se.Less};case Pe.Fork:{let r=So(e,t[1]);switch(r.status){case se.Greater:{let n=So(e,t[2]);return n.status===se.Less?{status:se.Absent}:n}case se.Unknown:{let n=So(e,t[2]);return n.status===se.Less?{status:se.Unknown}:n}default:return r}}case Pe.Pruned:return{status:se.Unknown};default:return{status:se.Absent}}}function ja(e){let{canisterId:t,subnetId:r,tree:n}=e,o=Qr(["subnet",r.toUint8Array(),"canister_ranges"],n);if(o.status!==Ye.Found)throw re.fromCode(new Lt(`Could not find canister ranges for subnet ${r.toText()}`,o.status));if(!(o.value instanceof Uint8Array))throw re.fromCode(new fn(`Could not find canister ranges for subnet ${r.toText()}`));return We(o.value).map(c=>[k.fromUint8Array(c[0]),k.fromUint8Array(c[1])]).some(c=>c[0].ltEq(t)&&c[1].gtEq(t))}var Ka=async e=>{let{agent:t,paths:r,disableCertificateTimeVerification:n=!1}=e,o=k.from(e.canisterId),s=[...new Set(r)],i=new Map,a=s.map((c,u)=>{let p=xh(c,o);return(async()=>{try{if(t.rootKey===null)throw Ee.fromCode(new Nt);let d=t.rootKey,l=await t.readState(o,{paths:[p]}),f=await Tr.create({certificate:l.certificate,rootKey:d,canisterId:o,disableTimeVerification:n,agent:t}),h=(_,x)=>{if(x==="subnet"){let g=gh(l.certificate,o,d);return{path:x,data:g}}else return{path:x,data:Be(_.lookup_path(p))}},{path:m,data:y}=h(f,s[u]);if(!y)console.warn(`Expected to find result for path ${m}, but instead found nothing.`),typeof m=="string"?i.set(m,null):i.set(m.key,null);else switch(m){case"time":{i.set(m,Cn(y));break}case"controllers":{i.set(m,bh(y));break}case"module_hash":{i.set(m,K(y));break}case"subnet":{i.set(m,y);break}case"candid":{i.set(m,new TextDecoder().decode(y));break}default:if(typeof m!="string"&&"key"in m&&"path"in m)switch(m.decodeStrategy){case"raw":i.set(m.key,y);break;case"leb128":{i.set(m.key,Ma(y));break}case"cbor":{i.set(m.key,We(y));break}case"hex":{i.set(m.key,K(y));break}case"utf-8":i.set(m.key,new TextDecoder().decode(y))}}}catch(d){if(d instanceof dt&&(d.hasCode(dr)||d.hasCode(Ur)))throw d;typeof c!="string"&&"key"in c&&"path"in c?i.set(c.key,null):i.set(c,null),console.group(),console.warn(`Expected to find result for path ${c}, but instead found nothing.`),console.warn(d),console.groupEnd()}})()});return await Promise.all(a),i},gh=(e,t,r)=>{if(!t._isPrincipal)throw z.fromCode(new ke("Invalid canisterId"));let n=We(e),o=n.tree,s=n.delegation,i;if(s&&s.subnet_id?i=k.fromUint8Array(new Uint8Array(s.subnet_id)):!s&&typeof r<"u"?(i=k.selfAuthenticating(new Uint8Array(r)),s={subnet_id:i.toUint8Array(),certificate:new Uint8Array(0)}):(i=k.selfAuthenticating(k.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe").toUint8Array()),s={subnet_id:i.toUint8Array(),certificate:new Uint8Array(0)}),!ja({canisterId:t,subnetId:i,tree:o}))throw Ue.fromCode(new pn(t,i));let c=Hs(["subnet",s.subnet_id,"node"],o);if(c.status!==Xr.Found)throw re.fromCode(new Lt("Node not found",c.status));if(c.value instanceof Uint8Array)throw ge.fromCode(new fr("Invalid node tree"));let u=Ks(c.value),p=new Map;return u.forEach(d=>{let l=k.from(d[1]).toText(),f=Qr(["public_key"],d[2]);if(f.status!==Ye.Found)throw re.fromCode(new Lt("Public key not found",f.status));let h=f.value;if(h.byteLength!==44)throw re.fromCode(new hn(44,h.byteLength));p.set(l,h)}),{subnetId:k.fromUint8Array(new Uint8Array(s.subnet_id)).toText(),nodeKeys:p}},xh=(e,t)=>{let r=t.toUint8Array();switch(e){case"time":return[Q("time")];case"controllers":return[Q("canister"),r,Q("controllers")];case"module_hash":return[Q("canister"),r,Q("module_hash")];case"subnet":return[Q("subnet")];case"candid":return[Q("canister"),r,Q("metadata"),Q("candid:service")];default:if("key"in e&&"path"in e)if(typeof e.path=="string"||e.path instanceof Uint8Array){let n=e.path,o=typeof n=="string"?Q(n):n;return[Q("canister"),r,Q("metadata"),o]}else return e.path}throw ge.fromCode(new ke(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))},bh=e=>We(e).map(r=>k.fromUint8Array(r));var Or=BigInt(0),ve=BigInt(1),Ha=BigInt(2),wh=BigInt(8);function Th(e,t,r,n){let o=e.sqr(r),s=e.sqr(n),i=e.add(e.mul(t.a,o),s),a=e.add(e.ONE,e.mul(t.d,e.mul(o,s)));return e.eql(i,a)}function Oh(e,t={}){let r=Ds("edwards",e,t,t.FpFnLE),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i}=s;zt(t,{},{uvRatio:"function"});let a=Ha<<BigInt(o.BYTES*8)-ve,c=y=>n.create(y),u=t.uvRatio||((y,_)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,_))}}catch{return{isValid:!1,value:Or}}});if(!Th(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function p(y,_,x=!1){let g=x?ve:Or;return Fs("coordinate "+y,_,g,a),_}function d(y){if(!(y instanceof h))throw new Error("ExtendedPoint expected")}let l=xr((y,_)=>{let{X:x,Y:g,Z:T}=y,N=y.is0();_==null&&(_=N?wh:n.inv(T));let E=c(x*_),R=c(g*_),I=n.mul(T,_);if(N)return{x:Or,y:ve};if(I!==ve)throw new Error("invZ was invalid");return{x:E,y:R}}),f=xr(y=>{let{a:_,d:x}=s;if(y.is0())throw new Error("bad point: ZERO");let{X:g,Y:T,Z:N,T:E}=y,R=c(g*g),I=c(T*T),w=c(N*N),v=c(w*w),C=c(R*_),A=c(w*c(C+I)),b=c(v+c(x*c(R*I)));if(A!==b)throw new Error("bad point: equation left != right (1)");let O=c(g*T),P=c(N*E);if(O!==P)throw new Error("bad point: equation left != right (2)");return!0});class h{constructor(_,x,g,T){this.X=p("x",_),this.Y=p("y",x),this.Z=p("z",g,!0),this.T=p("t",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(_){if(_ instanceof h)throw new Error("extended point not allowed");let{x,y:g}=_||{};return p("x",x),p("y",g),new h(x,g,ve,c(x*g))}static fromBytes(_,x=!1){let g=n.BYTES,{a:T,d:N}=s;_=ga(gr(_,g,"point")),Wr(x,"zip215");let E=ga(_),R=_[g-1];E[g-1]=R&-129;let I=Gt(E),w=x?a:n.ORDER;Fs("point.y",I,Or,w);let v=c(I*I),C=c(v-ve),A=c(N*v-T),{isValid:b,value:O}=u(C,A);if(!b)throw new Error("bad point: invalid y coordinate");let P=(O&ve)===ve,V=(R&128)!==0;if(!x&&O===Or&&V)throw new Error("bad point: x=0 and x_0=1");return V!==P&&(O=c(-O)),h.fromAffine({x:O,y:I})}static fromHex(_,x=!1){return h.fromBytes(ce("point",_),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,x=!0){return m.createCache(this,_),x||this.multiply(Ha),this}assertValidity(){f(this)}equals(_){d(_);let{X:x,Y:g,Z:T}=this,{X:N,Y:E,Z:R}=_,I=c(x*R),w=c(N*T),v=c(g*R),C=c(E*T);return I===w&&v===C}is0(){return this.equals(h.ZERO)}negate(){return new h(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:_}=s,{X:x,Y:g,Z:T}=this,N=c(x*x),E=c(g*g),R=c(Ha*c(T*T)),I=c(_*N),w=x+g,v=c(c(w*w)-N-E),C=I+E,A=C-R,b=I-E,O=c(v*A),P=c(C*b),V=c(v*b),L=c(A*C);return new h(O,P,L,V)}add(_){d(_);let{a:x,d:g}=s,{X:T,Y:N,Z:E,T:R}=this,{X:I,Y:w,Z:v,T:C}=_,A=c(T*I),b=c(N*w),O=c(R*g*C),P=c(E*v),V=c((T+N)*(I+w)-A-b),L=P-O,S=P+O,F=c(b-x*A),B=c(V*L),q=c(S*F),D=c(V*F),ee=c(L*S);return new h(B,q,ee,D)}subtract(_){return this.add(_.negate())}multiply(_){if(!o.isValidNot0(_))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:g}=m.cached(this,_,T=>ot(h,T));return ot(h,[x,g])[0]}multiplyUnsafe(_,x=h.ZERO){if(!o.isValid(_))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return _===Or?h.ZERO:this.is0()||_===ve?this:m.unsafe(this,_,g=>ot(h,g),x)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(_){return l(this,_)}clearCofactor(){return i===ve?this:this.multiplyUnsafe(i)}toBytes(){let{x:_,y:x}=this.toAffine(),g=n.toBytes(x);return g[g.length-1]|=_&ve?128:0,g}toHex(){return K(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(_){return ot(h,_)}static msm(_,x){return An(h,o,_,x)}_setWindowSize(_){this.precompute(_)}toRawBytes(){return this.toBytes()}}h.BASE=new h(s.Gx,s.Gy,ve,c(s.Gx*s.Gy)),h.ZERO=new h(Or,ve,ve,Or),h.Fp=n,h.Fn=o;let m=new In(h,o.BITS);return h.BASE.precompute(8),h}var $s=class{constructor(t){this.ep=t}static fromBytes(t){Rn()}static fromHex(t){Rn()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return K(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,r){return this.init(this.ep.precompute(t,r))}toRawBytes(){return this.toBytes()}};function Nh(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');zt(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=e,a=r.randomBytes||dn,c=r.adjustScalarBytes||(w=>w),u=r.domain||((w,v,C)=>{if(Wr(C,"phflag"),v.length||C)throw new Error("Contexts/pre-hash are not supported");return w});function p(w){return i.create(Gt(w))}function d(w){let v=g.secretKey;w=ce("private key",w,v);let C=ce("hashed private key",t(w),2*v),A=c(C.slice(0,v)),b=C.slice(v,2*v),O=p(A);return{head:A,prefix:b,scalar:O}}function l(w){let{head:v,prefix:C,scalar:A}=d(w),b=o.multiply(A),O=b.toBytes();return{head:v,prefix:C,scalar:A,point:b,pointBytes:O}}function f(w){return l(w).pointBytes}function h(w=Uint8Array.of(),...v){let C=M(...v);return p(t(u(C,ce("context",w),!!n)))}function m(w,v,C={}){w=ce("message",w),n&&(w=n(w));let{prefix:A,scalar:b,pointBytes:O}=l(v),P=h(C.context,A,w),V=o.multiply(P).toBytes(),L=h(C.context,V,O,w),S=i.create(P+L*b);if(!i.isValid(S))throw new Error("sign failed: invalid s");let F=M(V,i.toBytes(S));return gr(F,g.signature,"result")}let y={zip215:!0};function _(w,v,C,A=y){let{context:b,zip215:O}=A,P=g.signature;w=ce("signature",w,P),v=ce("message",v),C=ce("publicKey",C,g.publicKey),O!==void 0&&Wr(O,"zip215"),n&&(v=n(v));let V=P/2,L=w.subarray(0,V),S=Gt(w.subarray(V,P)),F,B,q;try{F=e.fromBytes(C,O),B=e.fromBytes(L,O),q=o.multiplyUnsafe(S)}catch{return!1}if(!O&&F.isSmallOrder())return!1;let D=h(b,B.toBytes(),F.toBytes(),v);return B.add(F.multiplyUnsafe(D)).subtract(q).clearCofactor().is0()}let x=s.BYTES,g={secretKey:x,publicKey:x,signature:2*x,seed:x};function T(w=a(g.seed)){return gr(w,g.seed,"seed")}function N(w){let v=I.randomSecretKey(w);return{secretKey:v,publicKey:f(v)}}function E(w){return Tt(w)&&w.length===i.BYTES}function R(w,v){try{return!!e.fromBytes(w,v)}catch{return!1}}let I={getExtendedPublicKey:l,randomSecretKey:T,isValidSecretKey:E,isValidPublicKey:R,toMontgomery(w){let{y:v}=e.fromBytes(w),C=g.publicKey,A=C===32;if(!A&&C!==57)throw new Error("only defined for 25519 and 448");let b=A?s.div(ve+v,ve-v):s.div(v-ve,v+ve);return s.toBytes(b)},toMontgomerySecret(w){let v=g.secretKey;gr(w,v);let C=t(w.subarray(0,v));return c(C).subarray(0,v)},randomPrivateKey:T,precompute(w=8,v=e.BASE){return v.precompute(w,!1)}};return Object.freeze({keygen:N,getPublicKey:f,sign:m,verify:_,utils:I,Point:e,lengths:g})}function Eh(e){let t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=Me(t.n,e.nBitLength,!0),o={Fp:r,Fn:n,uvRatio:e.uvRatio},s={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:o,hash:e.hash,eddsaOpts:s}}function Rh(e,t){let r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function Pu(e){let{CURVE:t,curveOpts:r,hash:n,eddsaOpts:o}=Eh(e),s=Oh(t,r),i=Nh(s,n,o);return Rh(e,i)}var vh=BigInt(0),Xt=BigInt(1),Cu=BigInt(2),H0=BigInt(3),Ih=BigInt(5),Ah=BigInt(8),Fn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Po={p:Fn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ah,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Sh(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Fn,a=e*e%s*e%s,c=xt(a,Cu,s)*a%s,u=xt(c,Xt,s)*e%s,p=xt(u,Ih,s)*u%s,d=xt(p,t,s)*p%s,l=xt(d,r,s)*d%s,f=xt(l,n,s)*l%s,h=xt(f,o,s)*f%s,m=xt(h,o,s)*f%s,y=xt(m,t,s)*p%s;return{pow_p_5_8:xt(y,Cu,s)*e%s,b2:a}}function Ph(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var $a=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function za(e,t){let r=Fn,n=oe(t*t*t,r),o=oe(n*n*t,r),s=Sh(e*o).pow_p_5_8,i=oe(e*n*s,r),a=oe(t*i*i,r),c=i,u=oe(i*$a,r),p=a===e,d=a===oe(-e,r),l=a===oe(-e*$a,r);return p&&(i=c),(d||l)&&(i=u),Yt(i,r)&&(i=oe(-i,r)),{isValid:p||d,value:i}}var Nr=Me(Po.p,{isLE:!0}),Ch=Me(Po.n,{isLE:!0}),Fh={...Po,Fp:Nr,hash:nl,adjustScalarBytes:Ph,uvRatio:za},He=Pu(Fh);var Ga=$a,Bh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Vh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Dh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Uh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Fu=e=>za(Xt,e),kh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Wa=e=>He.Point.Fp.create(Gt(e)&kh);function Bu(e){let{d:t}=Po,r=Fn,n=_=>Nr.create(_),o=n(Ga*e*e),s=n((o+Xt)*Dh),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:u}=za(s,a),p=n(u*e);Yt(p,r)||(p=n(-p)),c||(u=p),c||(i=o);let d=n(i*(o-Xt)*Uh-a),l=u*u,f=n((u+u)*a),h=n(d*Bh),m=n(Xt-l),y=n(Xt+l);return new He.Point(n(f*y),n(m*h),n(h*y),n(f*m))}function Lh(e){de(e,64);let t=Wa(e.subarray(0,32)),r=Bu(t),n=Wa(e.subarray(32,64)),o=Bu(n);return new Qt(r.add(o))}var Qt=class e extends $s{constructor(t){super(t)}static fromAffine(t){return new e(He.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static hashToCurve(t){return Lh(ce("ristrettoHash",t,64))}static fromBytes(t){de(t,32);let{a:r,d:n}=Po,o=Fn,s=T=>Nr.create(T),i=Wa(t);if(!Zl(Nr.toBytes(i),t)||Yt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Xt+r*a),u=s(Xt-r*a),p=s(c*c),d=s(u*u),l=s(r*n*p-d),{isValid:f,value:h}=Fu(s(l*d)),m=s(h*u),y=s(h*m*l),_=s((i+i)*m);Yt(_,o)&&(_=s(-_));let x=s(c*y),g=s(_*x);if(!f||Yt(g,o)||x===vh)throw new Error("invalid ristretto255 encoding 2");return new e(new He.Point(_,x,Xt,g))}static fromHex(t){return e.fromBytes(ce("ristrettoHex",t,32))}static msm(t,r){return An(e,He.Point.Fn,t,r)}toBytes(){let{X:t,Y:r,Z:n,T:o}=this.ep,s=Fn,i=y=>Nr.create(y),a=i(i(n+r)*i(n-r)),c=i(t*r),u=i(c*c),{value:p}=Fu(i(a*u)),d=i(p*a),l=i(p*c),f=i(d*l*o),h;if(Yt(o*f,s)){let y=i(r*Ga),_=i(t*Ga);t=y,r=_,h=i(d*Vh)}else h=l;Yt(t*f,s)&&(r=i(-r));let m=i((n-r)*h);return Yt(m,s)&&(m=i(-m)),Nr.toBytes(m)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=u=>Nr.create(u),a=i(r*s)===i(n*o),c=i(n*s)===i(r*o);return a||c}is0(){return this.equals(e.ZERO)}};Qt.BASE=new Qt(He.Point.BASE);Qt.ZERO=new Qt(He.Point.ZERO);Qt.Fp=Nr;Qt.Fn=Ch;var Vu,Du,Gs=class{static{Vu=Symbol.iterator,Du=Symbol.toStringTag}#e;#t;constructor(t={}){this[Vu]=this.entries.bind(this),this[Du]="ExpirableMap";let{source:r=[],expirationTime:n=600*1e3}=t,o=Date.now();this.#e=new Map([...r].map(([s,i])=>[s,{value:i,timestamp:o}])),this.#t=n}prune(){let t=Date.now();for(let[r,n]of this.#e.entries())t-n.timestamp>this.#t&&this.#e.delete(r);return this}set(t,r){this.prune();let n={value:r,timestamp:Date.now()};return this.#e.set(t,n),this}get(t){let r=this.#e.get(t);if(r!==void 0){if(Date.now()-r.timestamp>this.#t){this.#e.delete(t);return}return r.value}}clear(){this.#e.clear()}entries(){let t=this.#e.entries();return function*(){for(let[n,o]of t)yield[n,o.value]}()}values(){let t=this.#e.values();return function*(){for(let n of t)yield n.value}()}keys(){return this.#e.keys()}forEach(t,r){for(let[n,o]of this.#e.entries())t.call(r,o.value,n,this)}has(t){return this.#e.has(t)}delete(t){return this.#e.delete(t)}get size(){return this.#e.size}};var Uu=e=>{if(e<=127)return 1;if(e<=255)return 2;if(e<=65535)return 3;if(e<=16777215)return 4;throw z.fromCode(new Xn("Length too long (> 4 bytes)"))},ku=(e,t,r)=>{if(r<=127)return e[t]=r,1;if(r<=255)return e[t]=129,e[t+1]=r,2;if(r<=65535)return e[t]=130,e[t+1]=r>>8,e[t+2]=r,3;if(r<=16777215)return e[t]=131,e[t+1]=r>>16,e[t+2]=r>>8,e[t+3]=r,4;throw z.fromCode(new Xn("Length too long (> 4 bytes)"))},Ya=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw z.fromCode(new pt("Invalid length 0"));if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw z.fromCode(new pt("Length too long (> 4 bytes)"))},qh=(e,t)=>{let r=Ya(e,t);if(r===1)return e[t];if(r===2)return e[t+1];if(r===3)return(e[t+1]<<8)+e[t+2];if(r===4)return(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];throw z.fromCode(new pt("Length too long (> 4 bytes)"))},Co=Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]),en=Uint8Array.from([48,5,6,3,43,101,112]),Y0=Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]),J0=Uint8Array.from([48,29,6,13,43,6,1,4,1,130,220,124,5,3,1,2,1,6,12,43,6,1,4,1,130,220,124,5,3,2,1]);function tn(e,t){let r=2+Uu(e.byteLength+1),n=t.byteLength+r+e.byteLength,o=0,s=new Uint8Array(1+Uu(n)+n);return s[o++]=48,o+=ku(s,o,n),s.set(t,o),o+=t.byteLength,s[o++]=3,o+=ku(s,o,e.byteLength+1),s[o++]=0,s.set(new Uint8Array(e),o),s}var rn=(e,t)=>{let r=0,n=(a,c)=>{if(o[r++]!==a)throw z.fromCode(new pt(`Expected ${c} at offset ${r}`))},o=new Uint8Array(e);if(n(48,"sequence"),r+=Ya(o,r),!Hr(o.slice(r,r+t.byteLength),t))throw z.fromCode(new pt("Not the expected OID."));r+=t.byteLength,n(3,"bit string");let s=qh(o,r)-1;r+=Ya(o,r),n(0,"0 padding");let i=o.slice(r);if(s!==i.length)throw z.fromCode(new os(s,i.length));return i};var Ws=class e{static from(t){return this.fromDer(t.toDer())}static fromRaw(t){return new e(t)}static fromDer(t){return new e(this.derDecode(t))}static{this.RAW_KEY_LENGTH=32}static derEncode(t){return tn(t,en)}static derDecode(t){let r=rn(t,en);if(r.length!==this.RAW_KEY_LENGTH)throw z.fromCode(new pt("An Ed25519 public key must be exactly 32 bytes long"));return r}#e;get rawKey(){return this.#e}#t;get derKey(){return this.#t}constructor(t){if(t.byteLength!==e.RAW_KEY_LENGTH)throw z.fromCode(new pt("An Ed25519 public key must be exactly 32 bytes long"));this.#e=t,this.#t=e.derEncode(t)}toDer(){return this.derKey}toRaw(){return this.rawKey}};var Ja=class{constructor(){this.observers=[]}subscribe(t){this.observers.push(t)}unsubscribe(t){this.observers=this.observers.filter(r=>r!==t)}notify(t,...r){this.observers.forEach(n=>n(t,...r))}},zs=class extends Ja{constructor(){super()}print(t,...r){this.notify({message:t,level:"info"},...r)}warn(t,...r){this.notify({message:t,level:"warn"},...r)}error(t,r,...n){this.notify({message:t,level:"error",error:r},...n)}};var Ys=class e{#e;#t;#r;#c;#i;#u;#n;#o;#a=0;static{this.default={initialInterval:500,randomizationFactor:.5,multiplier:1.5,maxInterval:6e4,maxElapsedTime:9e5,maxIterations:10,date:Date}}constructor(t=e.default){let{initialInterval:r=500,randomizationFactor:n=.5,multiplier:o=1.5,maxInterval:s=6e4,maxElapsedTime:i=9e5,maxIterations:a=10,date:c=Date}=t;this.#e=r,this.#t=n,this.#r=o,this.#c=s,this.#o=c,this.#i=c.now(),this.#u=i,this.#n=a}get ellapsedTimeInMsec(){return this.#o.now()-this.#i}get currentInterval(){return this.#e}get count(){return this.#a}get randomValueFromInterval(){let t=this.#t*this.#e,r=this.#e-t,n=this.#e+t;return Math.random()*(n-r)+r}incrementCurrentInterval(){return this.#e=Math.min(this.#e*this.#r,this.#c),this.#a++,this.#e}next(){return this.ellapsedTimeInMsec>=this.#u||this.#a>=this.#n?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};var St;(function(e){e.Received="received",e.Processing="processing",e.Replied="replied",e.Rejected="rejected",e.Unknown="unknown",e.Done="done"})(St||(St={}));var Qa=60*1e3,Mh=1e6,jh=0,Kh="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae";var Hh="ic0.app",$h=".ic0.app",Gh="icp0.io",Wh=".icp0.io",zh="icp-api.io",Yh=".icp-api.io",Za=200,Jh=202,Zh=404;function Xh(){let e;if(typeof window<"u")if(window.fetch)e=window.fetch.bind(window);else throw Ee.fromCode(new _n("Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present."));else if(typeof global<"u")if(global.fetch)e=global.fetch.bind(global);else throw Ee.fromCode(new _n("Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available."));else typeof self<"u"&&self.fetch&&(e=self.fetch.bind(self));if(e)return e;throw Ee.fromCode(new _n("Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context."))}function Qh(e){let t;if(e!==void 0)!e.match(/^[a-z]+:/)&&typeof window<"u"?t=new URL(window.location.protocol+"//"+e):t=new URL(e);else{let r=["ic0.app","icp0.io","127.0.0.1","localhost"],n=[".github.dev",".gitpod.io"],o=typeof window<"u"?window.location:void 0,s=o?.hostname,i;s&&typeof s=="string"&&(n.some(a=>s.endsWith(a))?i=s:i=r.find(a=>s.endsWith(a))),o&&i?t=new URL(`${o.protocol}//${i}${o.port?":"+o.port:""}`):t=new URL("https://icp-api.io")}return t.toString()}var nn=class e{#e;#t;#r;#c;#i;#u;#n;#o;#a;#x;#s;#d;#p;#l;get#O(){return this.#l*Qa}#f;#h;#m;#_;constructor(t={}){this.#e=null,this.#t=!1,this.#r=jh,this.#c=!1,this.#i=null,this.#u=!1,this._isAgent=!0,this.config={},this.log=new zs,this.#f=[],this.#h=[],this.#m=new Gs({expirationTime:5*Qa}),this.#_=!0,this.#w=(o,s)=>{if(this.#_===!1)return o;let{status:i,signatures:a=[],requestId:c}=o;for(let u of a){let{timestamp:p,identity:d}=u,l=k.fromUint8Array(d).toText(),f;if(i===ir.Replied){let{reply:x}=o;f=uo({status:i,reply:x,timestamp:BigInt(p),request_id:c})}else if(i===ir.Rejected){let{reject_code:x,reject_message:g,error_code:T}=o;f=uo({status:i,reject_code:x,reject_message:g,error_code:T,timestamp:BigInt(p),request_id:c})}else throw ge.fromCode(new ke(`Unknown status: ${i}`));let h=M(aa,f),m=s.nodeKeys.get(l);if(!m)throw re.fromCode(new ms);let y=Ws.fromDer(m).rawKey;if(He.verify(u.signature,h,y))return o;throw Ue.fromCode(new _s(l))}return o},this.config=t,this.#o=t.fetch||Xh()||fetch.bind(global),this.#a=t.fetchOptions,this.#x=t.callOptions,this.#t=t.shouldFetchRootKey??!1,this.#u=t.shouldSyncTime??!1,t.rootKey?this.rootKey=t.rootKey:this.#t?this.rootKey=null:this.rootKey=Ne(Kh);let r=Qh(t.host);this.host=new URL(r),t.verifyQuerySignatures!==void 0&&(this.#_=t.verifyQuerySignatures),this.#d=t.retryTimes??3;let n=()=>new Ys({maxIterations:this.#d});if(this.#p=t.backoffStrategy||n,this.host.hostname.endsWith($h)?this.host.hostname=Hh:this.host.hostname.endsWith(Wh)?this.host.hostname=Gh:this.host.hostname.endsWith(Yh)&&(this.host.hostname=zh),t.credentials){let{name:o,password:s}=t.credentials;this.#s=`${o}${s?":"+s:""}`}if(this.#n=Promise.resolve(t.identity||new rt),t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes>5)throw z.fromCode(new Lr("The maximum ingress expiry time is 5 minutes.",t.ingressExpiryInMinutes));if(t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes<=0)throw z.fromCode(new Lr("Ingress expiry time must be greater than 0.",t.ingressExpiryInMinutes));this.#l=t.ingressExpiryInMinutes||5,this.addTransform("update",ha(xo)),t.useQueryNonces&&this.addTransform("query",ha(xo)),t.logToConsole&&this.log.subscribe(o=>{o.level==="error"?console.error(o.message):o.level==="warn"?console.warn(o.message):console.log(o.message)})}static createSync(t={}){return new this({...t})}static async create(t={}){let r=e.createSync(t);return await r.#g(),r}static async from(t){try{return"config"in t?await e.create(t.config):await e.create({fetch:t._fetch,fetchOptions:t._fetchOptions,callOptions:t._callOptions,host:t._host.toString(),identity:t._identity??void 0})}catch{throw z.fromCode(new ps)}}isLocal(){let t=this.host.hostname;return t==="127.0.0.1"||t.endsWith("127.0.0.1")}addTransform(t,r,n=r.priority||0){if(t==="update"){let o=this.#h.findIndex(s=>(s.priority||0)<n);this.#h.splice(o>=0?o:this.#h.length,0,Object.assign(r,{priority:n}))}else if(t==="query"){let o=this.#f.findIndex(s=>(s.priority||0)<n);this.#f.splice(o>=0?o:this.#f.length,0,Object.assign(r,{priority:n}))}}async getPrincipal(){if(!this.#n)throw Ee.fromCode(new pr);return(await this.#n).getPrincipal()}async call(t,r,n){let o=r.callSync??!0,s=await(n??this.#n);if(!s)throw Ee.fromCode(new pr);let i=k.from(t),a=r.effectiveCanisterId?k.from(r.effectiveCanisterId):i;await this.#g(a);let c=s.getPrincipal(),u=Xa(this.#l,this.#r),p={request_type:As.Call,canister_id:i,method_name:r.methodName,arg:r.arg,sender:c,ingress_expiry:u},d=await this._transform({request:{body:null,method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:$t.Call,body:p}),l;r?.nonce?l=f(r.nonce):d.body.nonce?l=f(d.body.nonce):l=void 0,p.nonce=l;function f(_){return Object.assign(_,{__nonce__:void 0})}d=await s.transformRequest(d);let h=yo(d.body),m=this.#p(),y=Kt(p);try{let g=o?()=>(this.log.print(`fetching "/api/v3/canister/${a.toText()}/call" with request:`,d),this.#o(""+new URL(`/api/v3/canister/${a.toText()}/call`,this.host),{...this.#x,...d.request,body:h})):()=>(this.log.print(`fetching "/api/v2/canister/${a.toText()}/call" with request:`,d),this.#o(""+new URL(`/api/v2/canister/${a.toText()}/call`,this.host),{...this.#x,...d.request,body:h})),{responseBodyBytes:T,...N}=await this.#y({requestFn:g,backoff:m,tries:0}),E=T.byteLength>0?We(T):null;return{requestId:y,response:{...N,body:E},requestDetails:p}}catch(_){let x;if(_ instanceof dt){if(_.hasCode(eo))return this.log.warn("v3 api not supported. Fall back to v2"),this.call(t,{...r,callSync:!1},n);if(_.hasCode(Lr)&&!this.#c)return await this.syncTime(i),this.call(i,r,n);_.code.requestContext={requestId:y,senderPubKey:d.body.sender_pubkey,senderSignature:d.body.sender_sig,ingressExpiry:d.body.content.ingress_expiry},x=_}else x=ge.fromCode(new ke(_));throw this.log.error(`Error while making call: ${x.message}`,x),x}}async#b(t){let{ecid:r,transformedRequest:n,body:o,requestId:s,backoff:i,tries:a}=t,c=a===0?0:i.next();if(this.log.print(`fetching "/api/v2/canister/${r.toString()}/query" with tries:`,{tries:a,backoff:i,delay:c}),c===null)throw ge.fromCode(new kr(`Backoff strategy exhausted after ${a} attempts.`,s));c>0&&await new Promise(f=>setTimeout(f,c));let u;try{this.log.print(`fetching "/api/v2/canister/${r.toString()}/query" with request:`,n);let f=await this.#o(""+new URL(`/api/v2/canister/${r.toString()}/query`,this.host),{...this.#a,...n.request,body:o});if(f.status===Za)u={...We(wn(await f.arrayBuffer())),httpDetails:{ok:f.ok,status:f.status,statusText:f.statusText,headers:Ps(f.headers)},requestId:s};else throw re.fromCode(new Qn(f.status,f.statusText,Ps(f.headers),await f.text()))}catch(f){if(a<this.#d)return this.log.warn(`Caught exception while attempting to make query:
51
51
  ${f}
52
- Retrying query.`),await this.#b({...t,tries:a+1});throw f instanceof nt?f:In.fromCode(new Pn(f))}if(!this.#_)return u;let p=u.signatures?.[0]?.timestamp;if(!p)throw te.fromCode(new Mo("Timestamp not found in query response. This suggests a malformed or malicious response."));let d=Number(BigInt(p)/BigInt(Hf));if(Date.now()+this.#r-d>this.#N){if(a<this.#d)return this.log.warn("Timestamp is older than the max ingress expiry. Retrying query.",{requestId:s,signatureTimestampMs:d}),await this.#b({...t,tries:a+1});throw Pe.fromCode(new Vo(this.#l,s,a))}return u}async#y(t){let{requestFn:r,backoff:n,tries:o}=t,s=o===0?0:n.next();if(s===null)throw te.fromCode(new gr(`Retry strategy exhausted after ${o} attempts.`));s>0&&await new Promise(p=>setTimeout(p,s));let i,a=new Uint8Array;try{i=await r(),i.status===ya&&(a=en(await i.clone().arrayBuffer()))}catch(p){if(o<this.#d)return this.log.warn(`Caught exception while attempting to make request:
52
+ Retrying query.`),await this.#b({...t,tries:a+1});throw f instanceof dt?f:Zn.fromCode(new to(f))}if(!this.#_)return u;let p=u.signatures?.[0]?.timestamp;if(!p)throw re.fromCode(new fs("Timestamp not found in query response. This suggests a malformed or malicious response."));let d=Number(BigInt(p)/BigInt(Mh));if(Date.now()+this.#r-d>this.#O){if(a<this.#d)return this.log.warn("Timestamp is older than the max ingress expiry. Retrying query.",{requestId:s,signatureTimestampMs:d}),await this.#b({...t,tries:a+1});throw Ue.fromCode(new as(this.#l,s,a))}return u}async#y(t){let{requestFn:r,backoff:n,tries:o}=t,s=o===0?0:n.next();if(s===null)throw re.fromCode(new kr(`Retry strategy exhausted after ${o} attempts.`));s>0&&await new Promise(p=>setTimeout(p,s));let i,a=new Uint8Array;try{i=await r(),i.status===Za&&(a=wn(await i.clone().arrayBuffer()))}catch(p){if(o<this.#d)return this.log.warn(`Caught exception while attempting to make request:
53
53
  ${p}
54
- Retrying request.`),await this.#y({requestFn:r,backoff:n,tries:o+1});throw In.fromCode(new Pn(p))}let c=ss(i.headers);if(i.status===ya||i.status===eh)return{ok:i.ok,status:i.status,statusText:i.statusText,responseBodyBytes:a,headers:c};let u=await i.text();if(i.status===th&&i.url.includes("api/v3"))throw te.fromCode(new Fn);if(u.startsWith("Invalid request expiry: "))throw W.fromCode(new xr(u,this.#l));if(o<this.#d)return await this.#y({requestFn:r,backoff:n,tries:o+1});throw te.fromCode(new Sn(i.status,i.statusText,c,u))}async query(t,r,n){let o=this.#p(),s=r.effectiveCanisterId?L.from(r.effectiveCanisterId):L.from(t);await this.#g(s),this.log.print(`ecid ${s.toString()}`),this.log.print(`canisterId ${t.toString()}`);let i,a=await(n??this.#n);if(!a)throw we.fromCode(new Xt);let c=L.from(t),u=a.getPrincipal(),p=ga(this.#l,this.#r),d={request_type:Rr.Query,canister_id:c,method_name:r.methodName,arg:r.arg,sender:u,ingress_expiry:p},l=Ct(d);i=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:Dt.Query,body:d}),i=await a.transformRequest(i);let f=zn(i.body),h={canister:c.toText(),ecid:s,transformedRequest:i,body:f,requestId:l,backoff:o,tries:0},_=async()=>{let m=await this.#b(h);return{requestDetails:d,...m}},g=async()=>{let m=this.#m.get(s.toString());if(m)return m;await this.fetchSubnetKeys(s.toString());let x=this.#m.get(s.toString());if(!x)throw Pe.fromCode(new jo);return x};try{if(!this.#_)return await _();let[m,x]=await Promise.all([_(),g()]);try{return this.#w(m,x)}catch{this.log.warn("Query response verification failed. Retrying with fresh subnet keys."),this.#m.delete(s.toString());let y=await g();return this.#w(m,y)}}catch(m){let x;throw m instanceof nt?(m.code.requestContext={requestId:l,senderPubKey:i.body.sender_pubkey,senderSignature:i.body.sender_sig,ingressExpiry:i.body.content.ingress_expiry},x=m):x=he.fromCode(new Be(m)),this.log.error(`Error while making query: ${x.message}`,x),x}}#w;async createReadStateRequest(t,r){await this.#g();let n=await(r??this.#n);if(!n)throw we.fromCode(new Xt);let o=n.getPrincipal(),s=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:Dt.ReadState,body:{request_type:Rr.ReadState,paths:t.paths,sender:o,ingress_expiry:ga(this.#l,this.#r)}});return n.transformRequest(s)}async readState(t,r,n,o){await this.#T();let s=L.from(t);function i(p){for(let d of p.paths){let[l,f]=d,h=new TextEncoder().encode("request_status");if(Or(l,h))return f}}let a,c;if(o)a=o,c=Ct(a);else{c=i(r);let p=await this.#n;if(!p)throw we.fromCode(new Xt);a=await this.createReadStateRequest(r,p)}this.log.print(`fetching "/api/v2/canister/${s}/read_state" with request:`,a);let u=this.#p();try{let{responseBodyBytes:p}=await this.#y({requestFn:()=>this.#o(""+new URL(`/api/v2/canister/${s.toString()}/read_state`,this.host),{...this.#a,...a.request,body:zn(a.body)}),backoff:u,tries:0}),d=je(p);return this.log.print("Read state response:",d),d}catch(p){let d;throw p instanceof nt?(p.code.requestContext={requestId:c,senderPubKey:a.body.sender_pubkey,senderSignature:a.body.sender_sig,ingressExpiry:a.body.content.ingress_expiry},d=p):d=he.fromCode(new Be(p)),this.log.error(`Error while making read state: ${d.message}`,d),d}}parseTimeFromResponse(t){let r;if(t.certificate){let n=je(t.certificate);if(n&&"tree"in n)r=n.tree;else throw te.fromCode(new Qt("Could not decode time from response"));let o=Br(["time"],r);if(o.status!==$e.Found)throw te.fromCode(new St("Time was not found in the response or was not in its expected format.",o.status));if(!(o.value instanceof Uint8Array)&&!ArrayBuffer.isView(o))throw te.fromCode(new Gr("Time was not in its expected format."));let s=pn(o.value);return this.log.print("Time from response:",s),this.log.print("Time from response in milliseconds:",s.getTime()),s.getTime()}else this.log.warn("No certificate found in response");return 0}async syncTime(t){this.#i=this.#i??(async()=>{await this.#T();let r=Date.now();try{t||this.log.print("Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai");let n=t??L.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),o=e.createSync({identity:new Ye,host:this.host.toString(),fetch:this.#o,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),i=(await Promise.all(Array(3).fill(null).map(async()=>{let c=(await la({canisterId:n,agent:o,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(c instanceof Date)return c.getTime()},[]))).reduce((a,c)=>typeof c=="number"&&c>a?c:a,0);i>0&&(this.#r=i-r,this.#c=!0,this.log.notify({message:`Syncing time: offset of ${this.#r}`,level:"info"}))}catch(n){let o=n instanceof nt?n:he.fromCode(new Be(n));throw this.log.error("Caught exception while attempting to sync time",o),o}})(),await this.#i.finally(()=>{this.#i=null})}async status(){let t=this.#s?{Authorization:"Basic "+btoa(this.#s)}:{};this.log.print('fetching "/api/v2/status"');let r=this.#p(),{responseBodyBytes:n}=await this.#y({backoff:r,requestFn:()=>this.#o(""+new URL("/api/v2/status",this.host),{headers:t,...this.#a}),tries:0});return je(n)}async fetchRootKey(){return this.#e=this.#e??(async()=>{let t=await this.status();return this.rootKey=t.root_key,this.rootKey})(),await this.#e.finally(()=>{this.#e=null})}async#g(t){await Promise.all([this.#T(),this.#O(t)])}async#T(){if(!this.rootKey)if(this.rootKey===null&&this.host.toString()!=="https://icp-api.io"&&this.#t)await this.fetchRootKey();else throw we.fromCode(new mt(this.#t))}async#O(t){this.#u&&!this.hasSyncedTime()&&await this.syncTime(t)}invalidateIdentity(){this.#n=null}replaceIdentity(t){this.#n=Promise.resolve(t)}async fetchSubnetKeys(t){let r=L.from(t);await this.#g(r);let o=(await la({canisterId:r,paths:["subnet"],agent:this})).get("subnet");if(o&&typeof o=="object"&&"nodeKeys"in o)return this.#m.set(r.toText(),o),o}_transform(t){let r=Promise.resolve(t);if(t.endpoint===Dt.Call)for(let n of this.#h)r=r.then(o=>n(o).then(s=>s||o));else for(let n of this.#f)r=r.then(o=>n(o).then(s=>s||o));return r}getTimeDiffMsecs(){return this.#r}hasSyncedTime(){return this.#c}};function ga(e,t){let r=e*xa;return on.fromDeltaInMilliseconds(r,t)}var oh=300*1e3;function eu(){return lh(ih(sh(),1e3),ch(1e3,1.2),ah(oh))}function sh(){let e=!0;return async()=>e?(e=!1,!0):!1}function ih(e,t){return async(r,n,o)=>{if(await e(r,n,o))return new Promise(s=>setTimeout(s,t))}}function ah(e){let t=Date.now()+e;return async(r,n,o)=>{if(Date.now()>t)throw te.fromCode(new gr(`Request timed out after ${e} msec`,n,o))}}function ch(e,t){let r=e;return()=>new Promise(n=>setTimeout(()=>{r*=t,n()},r))}function lh(...e){return async(t,r,n)=>{for(let o of e)await o(t,r,n)}}var ru={preSignReadStateRequest:!1};function nu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ba(e,t){return e!==null&&typeof e=="object"&&nu(e,t)}function dh(e,t){return nu(e,t)&&typeof e[t]=="function"}function tu(e){return ba(e,"body")&&ba(e.body,"content")&&e.body.content.request_type===Rr.ReadState&&ba(e.body.content,"ingress_expiry")&&typeof e.body.content.ingress_expiry=="object"&&e.body.content.ingress_expiry!==null&&dh(e.body.content.ingress_expiry,"toHash")}async function wa(e,t,r,n={}){let o=[Q("request_status"),r],s,i;if(n.preSignReadStateRequest??!1?(i=await ph({paths:[o],agent:e,pollingOptions:n}),s=await e.readState(t,{paths:[o]},void 0,i)):s=await e.readState(t,{paths:[o]}),e.rootKey==null)throw we.fromCode(new mt);let c=await cr.create({certificate:s.certificate,rootKey:e.rootKey,canisterId:t,blsVerify:n.blsVerify,agent:e}),u=Ae(c.lookup_path([...o,Q("status")])),p;switch(typeof u>"u"?p=wt.Unknown:p=new TextDecoder().decode(u),p){case wt.Replied:return{reply:Ae(c.lookup_path([...o,"reply"])),certificate:c};case wt.Received:case wt.Unknown:case wt.Processing:{let d=n.strategy??eu();return await d(t,r,p),wa(e,t,r,{...n,strategy:d,request:i})}case wt.Rejected:{let d=new Uint8Array(Ae(c.lookup_path([...o,"reject_code"])))[0],l=new TextDecoder().decode(Ae(c.lookup_path([...o,"reject_message"]))),f=Ae(c.lookup_path([...o,"error_code"])),h=f?new TextDecoder().decode(f):void 0;throw Jt.fromCode(new Wr(r,d,l,h))}case wt.Done:throw he.fromCode(new ko(r))}throw er}async function ph(e){let{paths:t,agent:r,pollingOptions:n}=e;if(n.request&&tu(n.request))return n.request;let o=await r.createReadStateRequest?.({paths:t},void 0);if(!tu(o))throw W.fromCode(new Ho(o));return o}var Qe=Symbol.for("ic-agent-metadata"),Os=class e{static agentOf(t){return t[Qe].config.agent}static interfaceOf(t){return t[Qe].service}static canisterIdOf(t){return L.from(t[Qe].config.canisterId)}static createActorClass(t,r){let n=t({IDL:Nr});class o extends e{constructor(i){if(!i.canisterId)throw W.fromCode(new Bn(i.canisterId));let a=typeof i.canisterId=="string"?L.fromText(i.canisterId):i.canisterId;super({config:{...ou,...i,canisterId:a},service:n});for(let[c,u]of n._fields)r?.httpDetails&&u.annotations.push(Ta),r?.certificate&&u.annotations.push(su),this[c]=hh(this,c,u,i.blsVerify)}}return o}static createActor(t,r){if(!r.canisterId)throw W.fromCode(new Bn(r.canisterId));return new(this.createActorClass(t))(r)}static createActorWithHttpDetails(t,r){return new(this.createActorClass(t,{httpDetails:!0}))(r)}static createActorWithExtendedDetails(t,r,n={httpDetails:!0,certificate:!0}){return new(this.createActorClass(t,n))(r)}constructor(t){this[Qe]=Object.freeze(t)}};function hn(e,t){let r=Nr.decode(e,t);switch(r.length){case 0:return;case 1:return r[0];default:return r}}var ou={pollingOptions:ru},Ta="http-details",su="certificate";function hh(e,t,r,n){let o;r.annotations.includes("query")||r.annotations.includes("composite_query")?o=async(i,...a)=>{i={...i,...e[Qe].config.queryTransform?.(t,a,{...e[Qe].config,...i})};let c=i.agent||e[Qe].config.agent||new Ur,u=L.from(i.canisterId||e[Qe].config.canisterId),p=Nr.encode(r.argTypes,a),d=await c.query(u,{methodName:t,arg:p,effectiveCanisterId:i.effectiveCanisterId}),l={...d.httpDetails,requestDetails:d.requestDetails};switch(d.status){case Gt.Rejected:{let f=new Do(d.requestId,d.reject_code,d.reject_message,d.error_code,d.signatures);throw f.callContext={canisterId:u,methodName:t,httpDetails:l},Jt.fromCode(f)}case Gt.Replied:return r.annotations.includes(Ta)?{httpDetails:l,result:hn(r.retTypes,d.reply.arg)}:hn(r.retTypes,d.reply.arg)}}:o=async(i,...a)=>{i={...i,...e[Qe].config.callTransform?.(t,a,{...e[Qe].config,...i})};let c=i.agent||e[Qe].config.agent||Ur.createSync(),{canisterId:u,effectiveCanisterId:p,pollingOptions:d}={...ou,...e[Qe].config,...i},l=L.from(u),f=p!==void 0?L.from(p):l,h=Nr.encode(r.argTypes,a),{requestId:_,response:g,requestDetails:m}=await c.call(l,{methodName:t,arg:h,effectiveCanisterId:f,nonce:i.nonce}),x,y;if(Qa(g.body)){if(c.rootKey==null)throw we.fromCode(new mt);let E=g.body.certificate;y=await cr.create({certificate:E,rootKey:c.rootKey,canisterId:f,blsVerify:n,agent:c});let v=[Q("request_status"),_];switch(new TextDecoder().decode(Ae(y.lookup_path([...v,"status"])))){case"replied":x=Ae(y.lookup_path([...v,"reply"]));break;case"rejected":{let I=new Uint8Array(Ae(y.lookup_path([...v,"reject_code"])))[0],B=new TextDecoder().decode(Ae(y.lookup_path([...v,"reject_message"]))),A=Ae(y.lookup_path([...v,"error_code"])),b=A?new TextDecoder().decode(A):void 0,N=new Wr(_,I,B,b);throw N.callContext={canisterId:l,methodName:t,httpDetails:g},Jt.fromCode(N)}}}else if(Xa(g.body)){let{reject_code:E,reject_message:v,error_code:w}=g.body,I=new Uo(_,E,v,w);throw I.callContext={canisterId:l,methodName:t,httpDetails:g},Jt.fromCode(I)}if(g.status===202){let E={...d,blsVerify:n},v=await wa(c,f,_,E);y=v.certificate,x=v.reply}let T=r.annotations.includes(Ta),O=r.annotations.includes(su),R={...g,requestDetails:m};if(x!==void 0)return T&&O?{httpDetails:R,certificate:y,result:hn(r.retTypes,x)}:O?{certificate:y,result:hn(r.retTypes,x)}:T?{httpDetails:R,result:hn(r.retTypes,x)}:hn(r.retTypes,x);{let E=new Be(`Call was returned undefined. We cannot determine if the call was successful or not. Return types: [${r.retTypes.map(v=>v.display()).join(",")}].`);throw E.callContext={canisterId:l,methodName:t,httpDetails:R},he.fromCode(E)}};let s=(...i)=>o({},...i);return s.withOptions=i=>(...a)=>o(i,...a),s}var mh=(e=>(e[e.FractionalMoreThan8Decimals=0]="FractionalMoreThan8Decimals",e[e.InvalidFormat=1]="InvalidFormat",e[e.FractionalTooManyDecimals=2]="FractionalTooManyDecimals",e))(mh||{}),ig=BigInt(1e8);var j=e=>e==null,X=e=>!j(e),_h=e=>X(e)&&e!=="",au=e=>!_h(e);var yh=class extends Error{},uo=(e,t)=>{if(e==null)throw new yh(t)};var kr=e=>new Uint8Array(e),Es=e=>Array.from(e);var cu=({a:e,b:t})=>e.length===t.length&&e.every((r,n)=>r===t[n]);var iu="abcdefghijklmnopqrstuvwxyz234567",lo=Object.create(null);for(let e=0;e<iu.length;e++)lo[iu[e]]=e;lo[0]=lo.o;lo[1]=lo.i;var Rs=e=>btoa(String.fromCharCode(...new Uint8Array(e)));var ag=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);var Na="__bigint__",Oa="__principal__",Ea="__uint8array__",lu=(e,t)=>typeof t=="bigint"?{[Na]:`${t}`}:X(t)&&L.isPrincipal(t)?{[Oa]:L.from(t).toText()}:X(t)&&t instanceof Uint8Array?{[Ea]:Array.from(t)}:t,uu=(e,t)=>{let r=n=>t[n];return X(t)&&typeof t=="object"&&Na in t?BigInt(r(Na)):X(t)&&typeof t=="object"&&Oa in t?L.fromText(r(Oa)):X(t)&&typeof t=="object"&&Ea in t?Uint8Array.from(r(Ea)):t};var ce=e=>X(e)?[e]:[],Oe=e=>e?.[0];var gh=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let t=e.slice(37,53),r=xh({bytes:t});return"aaguid"in r?{aaguidBytes:t,aaguidText:r.aaguid}:{unknownProvider:null}},xh=({bytes:e})=>{if(e.length!==16)return{invalidBytes:null};let t=(e instanceof Uint8Array?Es(e):e).map(r=>r.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5");return t==="00000000-0000-0000-0000-000000000000"?{unknownProvider:null}:{aaguid:t}};function bh(e){let t=new DataView(new ArrayBuffer(2)),r=e.slice(53,55);[...new Uint8Array(r)].forEach((o,s)=>t.setUint8(s,o));let n=t.getUint16(0);return e.slice(55+n)}function wh(e){return Vr(e,co)}var Th=class{constructor(e){this._cose=e,this.#e=wh(e)}#e;toDer(){return this.#e}toRaw(){return new Uint8Array(this.#e)}},mu=class{#e;#t;constructor({rawId:e,cose:t}){this.#e=e,this.#t=new Th(t)}getPublicKey(){return this.#t}getCredentialId(){return this.#e}getCredentialIdText(){return Rs(this.#e)}},Nh=class extends mu{#e;#t;constructor({authData:e,...t}){super(t);let r=gh({authData:e});this.#e="aaguidText"in r?r.aaguidText:void 0,this.#t="aaguidBytes"in r?r.aaguidBytes:void 0}getAAGUID(){return this.#t}getAAGUIDText(){return this.#e}},Oh=class extends mu{},Eh=class extends Error{},Rh=class extends Error{},vh=class extends Error{},Ih=class extends Error{},Ah=class extends Error{},Sh=class extends Error{},Fh=class extends Error{},du=class extends Error{};var Ph={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},Bh=6e4,_u=()=>window.crypto.getRandomValues(new Uint8Array(16)),Ch=()=>_u(),Vh=()=>_u(),Dh=()=>{let{location:{href:e}}=window,t=URL.parse(e);if(j(t))throw new Eh;let{hostname:r}=t;return r},yu=({appId:e})=>e?.id??Dh(),Uh=({appId:e,user:t}={})=>{let{document:{title:r}}=window,n=()=>({rp:{name:e?.name??r,id:yu({appId:e})}}),o=()=>({user:{id:Vh(),name:t?.name??t?.displayName??r,displayName:t?.displayName??r}});return{attestation:"direct",challenge:Ch(),...n(),...o(),pubKeyCredParams:Object.values(Ph).map(s=>({type:"public-key",alg:s})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},kh=(e={})=>({rpId:yu(e),allowCredentials:[],userVerification:"required"}),Ra=async({fn:e,step:t,onProgress:r})=>{r?.({step:t,state:"in_progress"});try{let n=await e();return r?.({step:t,state:"success"}),n}catch(n){throw r?.({step:t,state:"error"}),n}},dr=(e=>(e[e.RequestingUserCredential=0]="RequestingUserCredential",e[e.FinalizingCredential=1]="FinalizingCredential",e[e.Signing=2]="Signing",e))(dr||{}),gu=({timeout:e})=>AbortSignal.timeout(e??Bh),Lh=async({challenge:e,credentialIds:t,passkeyOptions:r,timeout:n})=>await navigator.credentials.get({publicKey:{...kh(r),challenge:e.buffer,allowCredentials:(t??[]).map(o=>({id:o.buffer,type:"public-key"}))},signal:gu({timeout:n})}),pu=e=>{if(e.status!=="initialized")throw new Rh},fu=e=>{if(j(e))throw new vh},hu=({type:e})=>{if(e!=="public-key")throw new Ih},va=class po extends bt{#e;#t;constructor({onProgress:t,...r}){if(super(),this.#e=t,"retrievePublicKey"in r){let{retrievePublicKey:n}=r;this.#t={status:"pending",retrievePublicKey:n};return}this.#t=po.#r({credential:new Nh(r)})}static#r({credential:t}){return{status:"initialized",credential:t}}static async createWithNewCredential({passkeyOptions:t,timeout:r,...n}={}){let o=await navigator.credentials.create({publicKey:Uh(t),signal:gu({timeout:r})});fu(o),hu(o);let{response:{attestationObject:s},rawId:i}=o;if(j(s))throw new Ah;let{authData:a}=rs.decode(kr(s)),c=bh(a);return new po({...n,rawId:kr(i),cose:c,authData:a})}static async createWithExistingCredential(t){return new po(t)}getPublicKey(){pu(this.#t);let{credential:t}=this.#t;return t.getPublicKey()}getCredential(){pu(this.#t);let{credential:t}=this.#t;return t}async sign(t){let r=await Ra({fn:async()=>{let n=await Lh({challenge:t,...this.#t.status==="initialized"&&{credentialIds:[this.#t.credential.getCredentialId()]}});return fu(n),hu(n),n},step:0,onProgress:this.#e});return await Ra({fn:async()=>{let{rawId:n}=r;if(this.#t.status==="initialized"){if(!cu({a:this.#t.credential.getCredentialId(),b:kr(n)}))throw new Sh;return}let{retrievePublicKey:o}=this.#t,s=await o({credentialId:kr(n)});this.#t=po.#r({credential:new Oh({rawId:kr(n),cose:s})})},step:1,onProgress:this.#e}),await Ra({fn:async()=>{let{response:n}=r,{clientDataJSON:o}=n,{authenticatorData:s,signature:i}="authenticatorData"in n&&"signature"in n?n:{};if(j(s))throw new du;if(j(i))throw new du;let a=rs.encode({authenticator_data:s,client_data_json:new TextDecoder().decode(o),signature:kr(i)});if(j(a))throw new Fh;return Object.assign(a,{__signature__:void 0}),a},step:2,onProgress:this.#e})}},qh=async()=>X(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;var mn=class{callbacks=[];populate(t){this.callbacks.forEach(({callback:r})=>r(t))}subscribe(t){let r=Symbol();return this.callbacks.push({id:r,callback:t}),()=>this.callbacks=this.callbacks.filter(({id:n})=>n!==r)}};var et=class e extends mn{static instance;authUser=null;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(t){this.authUser=t,this.populate(t)}get(){return this.authUser}subscribe(t){let r=super.subscribe(t);return t(this.authUser),r}reset(){this.authUser=null,this.populate(this.authUser)}};var Ia=({message:e,detail:t})=>{let r=new CustomEvent(e,{detail:t,bubbles:!0});document.dispatchEvent(r)};var _n="http://127.0.0.1:5987",xu="rdmx6-jaaaa-aaaaa-aaadq-cai";var bu=async({identity:e,container:t})=>{let n=X(t)&&t!==!1?t===!0?_n:t:"https://icp-api.io",o=X(t);return await Ur.create({identity:e,shouldFetchRootKey:o,host:n})};var yn=class e{static instance;#e=void 0;constructor(){}static getInstance(){return j(e.instance)&&(e.instance=new e),e.instance}async getAgent({identity:t,...r}){let n=t.getPrincipal().toText();if(j(this.#e)||j(this.#e[n])){let o=await bu({identity:t,...r});return this.#e={...this.#e??{},[n]:o},o}return this.#e[n]}reset(){this.#e=null}};var gn=class e{static instance;#e=void 0;constructor(){}static getInstance(){return j(e.instance)&&(e.instance=new e),e.instance}async getActor({satelliteId:t,identity:r,actorKey:n,...o}){let s=`${n}#${r.getPrincipal().toText()}#${t};`;if(j(this.#e)||j(this.#e[s])){let i=await this.createActor({satelliteId:t,identity:r,...o});return this.#e={...this.#e??{},[s]:i},i}return this.#e[s]}reset(){this.#e=null}async createActor({idlFactory:t,satelliteId:r,...n}){let o=await yn.getInstance().getAgent(n);return Os.createActor(t,{agent:o,canisterId:r})}};var wu=e=>(e.preventDefault(),e.returnValue="Are you sure you want to exit?"),Mh=()=>{window.addEventListener("beforeunload",wu,{capture:!0})},jh=()=>{window.removeEventListener("beforeunload",wu,{capture:!0})},Aa=async({fn:e})=>{try{return Mh(),await e()}finally{jh()}};var Ge=class e extends mn{static instance;env;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(t){this.env=t,this.populate(t)}get(){return this.env}reset(){this.env=null}subscribe(t){let r=super.subscribe(t);return t(this.env),r}};var Tu=BigInt(144e11),Nu=!1,Ou={width:576,height:576},Eu={width:424,height:576},Ru={width:505,height:705},fo="internetcomputer.org",vu="ic0.app",Iu="id.ai";var Au=async e=>{let t=new Blob([JSON.stringify(e,lu)],{type:"application/json; charset=utf-8"});return new Uint8Array(await t.arrayBuffer())},vs=async e=>{let t=new Blob([e instanceof Uint8Array?e:new Uint8Array(e)],{type:"application/json; charset=utf-8"});return JSON.parse(await t.text(),uu)},Is=()=>typeof window<"u";var As=({width:e,height:t})=>{if(!Is()||j(window)||j(window.top))return;let{top:{innerWidth:r,innerHeight:n}}=window,o=n/2+screenY-t/2,s=r/2+screenX-e/2;return`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=${e}, height=${t}, top=${o}, left=${s}`};function Su(e){return e!==null&&typeof e=="object"}var ho=class e{static from(t){if(typeof t=="string"){let r=be(t);return this.fromRaw(r)}else if(Su(t)){let r=t;if(Su(r)&&Object.hasOwnProperty.call(r,"__derEncodedPublicKey__"))return this.fromDer(r);if(ArrayBuffer.isView(r)){let n=r;return this.fromRaw(_t(n.buffer))}else{if(r instanceof ArrayBuffer)return this.fromRaw(_t(r));if("rawKey"in r&&r.rawKey instanceof Uint8Array)return this.fromRaw(r.rawKey);if("derKey"in r)return this.fromDer(r.derKey);if("toDer"in r)return this.fromDer(r.toDer())}}throw new Error("Cannot construct Ed25519PublicKey from the provided key.")}static fromRaw(t){return new e(t)}static fromDer(t){return new e(this.derDecode(t))}static{this.RAW_KEY_LENGTH=32}static derEncode(t){let r=Vr(t,Cr);return r.__derEncodedPublicKey__=void 0,r}static derDecode(t){let r=Dr(t,Cr);if(r.length!==this.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");return r}#e;get rawKey(){return this.#e}#t;get derKey(){return this.#t}constructor(t){if(t.byteLength!==e.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");this.#e=t,this.#t=e.derEncode(t)}toDer(){return this.derKey}toRaw(){return this.rawKey}},xn=class e extends bt{static generate(t){if(t&&t.length!==32)throw new Error("Ed25519 Seed needs to be 32 bytes long.");t||(t=Le.utils.randomPrivateKey()),bc(t,new Uint8Array(new Array(32).fill(0)))&&console.warn("Seed is all zeros. This is not a secure seed. Please provide a seed with sufficient entropy if this is a production environment.");let r=new Uint8Array(32);for(let o=0;o<32;o++)r[o]=t[o];let n=Le.getPublicKey(r);return e.fromKeyPair(n,r)}static fromParsedJson(t){let[r,n]=t;return new e(ho.fromDer(be(r)),be(n))}static fromJSON(t){let r=JSON.parse(t);if(Array.isArray(r)){if(typeof r[0]=="string"&&typeof r[1]=="string")return this.fromParsedJson([r[0],r[1]]);throw new Error("Deserialization error: JSON must have at least 2 items.")}throw new Error(`Deserialization error: Invalid JSON type for string: ${JSON.stringify(t)}`)}static fromKeyPair(t,r){return new e(ho.fromRaw(t),r)}static fromSecretKey(t){let r=Le.getPublicKey(t);return e.fromKeyPair(r,t)}#e;#t;constructor(t,r){super(),this.#e=ho.from(t),this.#t=r}toJSON(){return[M(this.#e.toDer()),M(this.#t)]}getKeyPair(){return{secretKey:this.#t,publicKey:this.#e}}getPublicKey(){return this.#e}async sign(t){let r=Le.sign(t,this.#t.slice(0,32));return Object.defineProperty(r,"__signature__",{enumerable:!1,value:void 0}),r}static verify(t,r,n){let[o,s,i]=[t,r,n].map(a=>(typeof a=="string"&&(a=be(a)),_t(a)));return Le.verify(o,s,i)}};var Sa=class e extends Error{constructor(t){super(t),this.message=t,Object.setPrototypeOf(this,e.prototype)}};function Fu(e){if(typeof global<"u"&&global.crypto&&global.crypto.subtle)return global.crypto.subtle;if(e)return e;if(typeof crypto<"u"&&crypto.subtle)return crypto.subtle;throw new Sa("Global crypto was not available and none was provided. Please inlcude a SubtleCrypto implementation. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto")}var Lr=class e extends bt{static async generate(t){let{extractable:r=!1,keyUsages:n=["sign","verify"],subtleCrypto:o}=t??{},s=Fu(o),i=await s.generateKey({name:"ECDSA",namedCurve:"P-256"},r,n),a=_t(await s.exportKey("spki",i.publicKey));return Object.assign(a,{__derEncodedPublicKey__:void 0}),new this(i,a,s)}static async fromKeyPair(t,r){let n=Fu(r),o=_t(await n.exportKey("spki",t.publicKey));return Object.assign(o,{__derEncodedPublicKey__:void 0}),new e(t,o,n)}constructor(t,r,n){super(),this._keyPair=t,this._derKey=r,this._subtleCrypto=n}getKeyPair(){return this._keyPair}getPublicKey(){let t=this._derKey,r=Object.create(this._keyPair.publicKey);return r.toDer=function(){return t},r}async sign(t){let r={name:"ECDSA",hash:{name:"SHA-256"}},n=_t(await this._subtleCrypto.sign(r,this._keyPair.privateKey,t));return Object.assign(n,{__signature__:void 0}),n}};var Ss=class{#e;get rawKey(){return this.#e.rawKey}get derKey(){return this.#e.derKey}toDer(){return this.#e.toDer()}getPublicKey(){return this.#e}getPrincipal(){if(!this.#e.rawKey)throw new Error("Cannot get principal from a public key without a raw key.");return L.fromUint8Array(new Uint8Array(this.#e.rawKey))}transformRequest(){return Promise.reject("Not implemented. You are attempting to use a partial identity to sign calls, but this identity only has access to the public key.To sign calls, use a DelegationIdentity instead.")}constructor(t){this.#e=t}};function Fa(e){if(typeof e!="string"||e.length<64)throw new Error("Invalid public key.");return be(e)}var bn=class{constructor(t,r,n){this.pubkey=t,this.expiration=r,this.targets=n}toCborValue(){return{pubkey:this.pubkey,expiration:this.expiration,...this.targets&&{targets:this.targets}}}toJSON(){return{expiration:this.expiration.toString(16),pubkey:M(this.pubkey),...this.targets&&{targets:this.targets.map(t=>t.toHex())}}}};async function Kh(e,t,r,n){let o=new bn(t.toDer(),BigInt(+r)*BigInt(1e6),n),s=new Uint8Array([...Ii,...new Uint8Array(Ct({...o}))]),i=await e.sign(s);return{delegation:o,signature:i}}var qr=class e{static async create(t,r,n=new Date(Date.now()+900*1e3),o={}){let s=await Kh(t,r,n,o.targets);return new e([...o.previous?.delegations||[],s],o.previous?.publicKey||t.getPublicKey().toDer())}static fromJSON(t){let{publicKey:r,delegations:n}=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(n))throw new Error("Invalid delegations.");let o=n.map(s=>{let{delegation:i,signature:a}=s,{pubkey:c,expiration:u,targets:p}=i;if(p!==void 0&&!Array.isArray(p))throw new Error("Invalid targets.");return{delegation:new bn(Fa(c),BigInt("0x"+u),p&&p.map(d=>{if(typeof d!="string")throw new Error("Invalid target.");return L.fromHex(d)})),signature:Fa(a)}});return new this(o,Fa(r))}static fromDelegations(t,r){return new this(t,r)}constructor(t,r){this.delegations=t,this.publicKey=r}toJSON(){return{delegations:this.delegations.map(t=>{let{delegation:r,signature:n}=t,{targets:o}=r;return{delegation:{expiration:r.expiration.toString(16),pubkey:M(r.pubkey),...o&&{targets:o.map(s=>s.toHex())}},signature:M(n)}}),publicKey:M(this.publicKey)}}},Mr=class extends bt{static fromDelegation(t,r){return new this(t,r)}constructor(t,r){super(),this._inner=t,this._delegation=r}getDelegation(){return this._delegation}getPublicKey(){return{derKey:this._delegation.publicKey,toDer:()=>this._delegation.publicKey}}sign(t){return this._inner.sign(t)}async transformRequest(t){let{body:r,...n}=t,o=await Ct(r);return{...n,body:{content:r,sender_sig:await this.sign(new Uint8Array([...jn,...new Uint8Array(o)])),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}}}},mo=class e extends Ss{#e;get delegation(){return this.#e}constructor(t,r){super(t),this.#e=r}static fromDelegation(t,r){return new e(t,r)}};function Pa(e,t){for(let{delegation:o}of e.delegations)if(+new Date(Number(o.expiration/BigInt(1e6)))<=+Date.now())return!1;let r=[],n=t?.scope;n&&(Array.isArray(n)?r.push(...n.map(o=>typeof o=="string"?L.fromText(o):o)):r.push(typeof n=="string"?L.fromText(n):n));for(let o of r){let s=o.toText();for(let{delegation:i}of e.delegations){if(i.targets===void 0)continue;let a=!0;for(let c of i.targets)if(c.toText()===s){a=!1;break}if(a)return!1}}return!0}var Pu=["mousedown","mousemove","keydown","touchstart","wheel"],_o=class{callbacks=[];idleTimeout=600*1e3;timeoutID=void 0;static create(t={}){return new this(t)}constructor(t={}){let{onIdle:r,idleTimeout:n=600*1e3}=t||{};this.callbacks=r?[r]:[],this.idleTimeout=n;let o=this._resetTimer.bind(this);window.addEventListener("load",o,!0),Pu.forEach(function(i){document.addEventListener(i,o,!0)});let s=(i,a)=>{let c;return(...u)=>{let p=this,d=function(){c=void 0,i.apply(p,u)};clearTimeout(c),c=window.setTimeout(d,a)}};if(t?.captureScroll){let i=s(o,t?.scrollDebounce??100);window.addEventListener("scroll",i,!0)}o()}registerCallback(t){this.callbacks.push(t)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let t=this._resetTimer.bind(this);Pu.forEach(function(r){document.removeEventListener(r,t,!0)}),this.callbacks.forEach(r=>r())}_resetTimer(){let t=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(t,this.idleTimeout)}};var $h=(e,t)=>t.some(r=>e instanceof r),Bu,Cu;function Hh(){return Bu||(Bu=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Gh(){return Cu||(Cu=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Vu=new WeakMap,Ca=new WeakMap,Du=new WeakMap,Ba=new WeakMap,Da=new WeakMap;function zh(e){let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{r(Tt(e.result)),o()},i=()=>{n(e.error),o()};e.addEventListener("success",s),e.addEventListener("error",i)});return t.then(r=>{r instanceof IDBCursor&&Vu.set(r,e)}).catch(()=>{}),Da.set(t,e),t}function Wh(e){if(Ca.has(e))return;let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{r(),o()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)});Ca.set(e,t)}var Va={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return Ca.get(e);if(t==="objectStoreNames")return e.objectStoreNames||Du.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Tt(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function Uu(e){Va=e(Va)}function Yh(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let n=e.call(Fs(this),t,...r);return Du.set(n,t.sort?t.sort():[t]),Tt(n)}:Gh().includes(e)?function(...t){return e.apply(Fs(this),t),Tt(Vu.get(this))}:function(...t){return Tt(e.apply(Fs(this),t))}}function Jh(e){return typeof e=="function"?Yh(e):(e instanceof IDBTransaction&&Wh(e),$h(e,Hh())?new Proxy(e,Va):e)}function Tt(e){if(e instanceof IDBRequest)return zh(e);if(Ba.has(e))return Ba.get(e);let t=Jh(e);return t!==e&&(Ba.set(e,t),Da.set(t,e)),t}var Fs=e=>Da.get(e);function Lu(e,t,{blocked:r,upgrade:n,blocking:o,terminated:s}={}){let i=indexedDB.open(e,t),a=Tt(i);return n&&i.addEventListener("upgradeneeded",c=>{n(Tt(i.result),c.oldVersion,c.newVersion,Tt(i.transaction),c)}),r&&i.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),o&&c.addEventListener("versionchange",u=>o(u.oldVersion,u.newVersion,u))}).catch(()=>{}),a}var Zh=["get","getKey","getAll","getAllKeys","count"],Xh=["put","add","delete","clear"],Ua=new Map;function ku(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Ua.get(t))return Ua.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,o=Xh.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||Zh.includes(r)))return;let s=async function(i,...a){let c=this.transaction(i,o?"readwrite":"readonly"),u=c.store;return n&&(u=u.index(a.shift())),(await Promise.all([u[r](...a),o&&c.done]))[0]};return Ua.set(t,s),s}Uu(e=>({...e,get:(t,r,n)=>ku(t,r)||e.get(t,r,n),has:(t,r)=>!!ku(t,r)||e.has(t,r)}));var qu="auth-client-db",Mu="ic-keyval",Qh=async(e=qu,t=Mu,r)=>(Ps&&localStorage?.getItem(ze)&&(localStorage.removeItem(ze),localStorage.removeItem(qe)),await Lu(e,r,{upgrade:n=>{n.objectStoreNames.contains(t)&&n.clear(t),n.createObjectStore(t)}}));async function em(e,t,r){return await e.get(t,r)}async function tm(e,t,r,n){return await e.put(t,n,r)}async function rm(e,t,r){return await e.delete(t,r)}var yo=class e{_db;_storeName;static async create(t){let{dbName:r=qu,storeName:n=Mu,version:o=ju}=t??{},s=await Qh(r,n,o);return new e(s,n)}constructor(t,r){this._db=t,this._storeName=r}async set(t,r){return await tm(this._db,this._storeName,t,r)}async get(t){return await em(this._db,this._storeName,t)??null}async remove(t){return await rm(this._db,this._storeName,t)}};var qe="identity",ze="delegation",Ku="iv",ju=1,Ps=typeof window<"u",go=class{prefix;_localStorage;constructor(t="ic-",r){this.prefix=t,this._localStorage=r}get(t){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+t))}set(t,r){return this._getLocalStorage().setItem(this.prefix+t,r),Promise.resolve()}remove(t){return this._getLocalStorage().removeItem(this.prefix+t),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let t=typeof window>"u"?typeof global>"u"?typeof self>"u"?void 0:self.localStorage:global.localStorage:window.localStorage;if(!t)throw new Error("Could not find local storage.");return t}},Ht=class{#e;constructor(t){this.#e=t??{}}initializedDb;get _db(){return new Promise(t=>{if(this.initializedDb){t(this.initializedDb);return}yo.create(this.#e).then(r=>{this.initializedDb=r,t(r)})})}async get(t){return await(await this._db).get(t)}async set(t,r){await(await this._db).set(t,r)}async remove(t){await(await this._db).remove(t)}};var nm=BigInt(1e9),om=BigInt(3600),sm=nm*om,im="https://identity.internetcomputer.org",am="#authorize",cm=BigInt(8)*sm,ka="ECDSA",La="Ed25519",lm=500,Ma="UserInterrupt",Bs=class{_identity;_key;_chain;_storage;idleManager;_createOptions;_idpWindow;_eventHandler;static async create(t={}){let r=t.storage??new Ht,n=t.keyType??ka,o=null;if(t.identity)o=t.identity;else{let c=await r.get(qe);if(!c&&Ps)try{let u=new go,p=await u.get(ze),d=await u.get(qe);p&&d&&n===ka&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await r.set(ze,p),await r.set(qe,d),c=p,await u.remove(ze),await u.remove(qe))}catch(u){console.error("error while attempting to recover localstorage: "+u)}if(c)try{typeof c=="object"?n===La&&typeof c=="string"?o=xn.fromJSON(c):o=await Lr.fromKeyPair(c):typeof c=="string"&&(o=xn.fromJSON(c))}catch{}}let s=new Ye,i=null;if(o)try{let c=await r.get(ze);if(typeof c=="object"&&c!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");t.identity?s=t.identity:c&&(i=qr.fromJSON(c),Pa(i)?"toDer"in o?s=mo.fromDelegation(o,i):s=Mr.fromDelegation(o,i):(await qa(r),o=null))}catch(c){console.error(c),await qa(r),o=null}let a;return t.idleOptions?.disableIdle?a=void 0:(i||t.identity)&&(a=_o.create(t.idleOptions)),o||(n===La?(o=xn.generate(),await r.set(qe,JSON.stringify(o.toJSON()))):(t.storage&&n===ka&&console.warn(`You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${La}' as the key type, as it can serialize to a string`),o=await Lr.generate(),await r.set(qe,o.getKeyPair()))),new this(s,o,i,r,a,t)}constructor(t,r,n,o,s,i,a,c){this._identity=t,this._key=r,this._chain=n,this._storage=o,this.idleManager=s,this._createOptions=i,this._idpWindow=a,this._eventHandler=c,this._registerDefaultIdleCallback()}_registerDefaultIdleCallback(){let t=this._createOptions?.idleOptions;!t?.onIdle&&!t?.disableDefaultIdleCallback&&this.idleManager?.registerCallback(()=>{this.logout(),location.reload()})}async _handleSuccess(t,r){let n=t.delegations.map(a=>({delegation:new bn(a.delegation.pubkey,a.delegation.expiration,a.delegation.targets),signature:a.signature})),o=qr.fromDelegations(n,t.userPublicKey),s=this._key;if(!s)return;this._chain=o,"toDer"in s?this._identity=mo.fromDelegation(s,this._chain):this._identity=Mr.fromDelegation(s,this._chain),this._idpWindow?.close();let i=this._createOptions?.idleOptions;!this.idleManager&&!i?.disableIdle&&(this.idleManager=_o.create(i),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(ze,JSON.stringify(this._chain.toJSON())),r?.(t)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null&&Pa(this._chain)}async login(t){let r=um(this._createOptions?.loginOptions,t),n=r?.maxTimeToLive??cm,o=new URL(r?.identityProvider?.toString()||im);o.hash=am,this._idpWindow?.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(o,{maxTimeToLive:n,...r}),window.addEventListener("message",this._eventHandler),this._idpWindow=window.open(o.toString(),"idpWindow",r?.windowOpenerFeatures)??void 0;let s=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(Ma,r?.onError):setTimeout(s,lm))};s()}_getEventHandler(t,r){return async n=>{if(n.origin!==t.origin)return;let o=n.data;switch(o.kind){case"authorize-ready":{let s={kind:"authorize-client",sessionPublicKey:new Uint8Array(this._key?.getPublicKey().toDer()),maxTimeToLive:r?.maxTimeToLive,allowPinAuthentication:r?.allowPinAuthentication,derivationOrigin:r?.derivationOrigin?.toString(),...r?.customValues};this._idpWindow?.postMessage(s,t.origin);break}case"authorize-client-success":try{await this._handleSuccess(o,r?.onSuccess)}catch(s){this._handleFailure(s.message,r?.onError)}break;case"authorize-client-failure":this._handleFailure(o.text,r?.onError);break;default:break}}}_handleFailure(t,r){this._idpWindow?.close(),r?.(t),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(t={}){if(await qa(this._storage),this._identity=new Ye,this._chain=null,t.returnTo)try{window.history.pushState({},"",t.returnTo)}catch{window.location.href=t.returnTo}}};async function qa(e){await e.remove(qe),await e.remove(ze),await e.remove(Ku)}function um(e,t){if(!e&&!t)return;let r=e?.customValues||t?.customValues?{...e?.customValues,...t?.customValues}:void 0;return{...e,...t,customValues:r}}var Nt=async({fn:e,step:t,onProgress:r})=>{r?.({step:t,state:"in_progress"});try{let n=await e();return r?.({step:t,state:"success"}),n}catch(n){throw r?.({step:t,state:"error"}),n}};var $u=(r=>(r[r.AuthorizingWithProvider=0]="AuthorizingWithProvider",r[r.CreatingOrRetrievingUser=1]="CreatingOrRetrievingUser",r))($u||{});var Cs=class extends Error{},jr=class extends Error{},Vs=class extends Error{},Ds=class extends Error{},Us=class extends Error{},ks=class extends Error{},Ls=class extends Error{},qs=class extends Error{};var wn=class{async signIn({options:t,authClient:r,initAuth:n}){await Nt({fn:async()=>await this.#e({options:t,authClient:r}),step:0,onProgress:t?.onProgress}),await Nt({fn:async()=>await n({provider:this.id}),step:1,onProgress:t?.onProgress})}#e({options:t,authClient:r}){return new Promise(async(n,o)=>{if(j(r)){o(new jr("No client is ready to perform a sign-in. Have you initialized the Satellite?"));return}await r.login({onSuccess:n,onError:s=>{if(s===Ma){o(new Vs(s));return}o(new Cs(s))},maxTimeToLive:t?.maxTimeToLiveInNanoseconds??Tu,allowPinAuthentication:t?.allowPin??Nu,...t?.derivationOrigin!==void 0&&{derivationOrigin:t.derivationOrigin},...this.signInOptions({windowed:t?.windowed})})})}};var Ms=class extends wn{#e;constructor({domain:t}){super(),this.#e=t}get id(){return"internet_identity"}signInOptions({windowed:t}){let n=(()=>{let s=Ge.getInstance().get()?.container;if(j(s)||s===!1){let p=[fo,vu].includes(this.#e??fo);return au(this.#e)?`https://identity.${fo}`:p?`https://identity.${this.#e??fo}`:`https://${this.#e}`}let i=Ge.getInstance().get(),a=X(i)&&X(i?.internetIdentityId)?i.internetIdentityId:xu,{host:c,protocol:u}=new URL(s===!0?_n:s);return/apple/i.test(navigator?.vendor)?`${u}//${c}?canisterId=${a}`:`${u}//${a}.${c.replace("127.0.0.1","localhost")}`})(),o=URL.parse(n)?.hostname?.includes(Iu)===!0;return{...t!==!1&&{windowOpenerFeatures:As(o?Eu:Ou)},identityProvider:n}}};var js=class extends wn{#e;#t;constructor({appName:t,logoUrl:r}){super(),this.#e=t,this.#t=r}get id(){return"nfid"}signInOptions({windowed:t}){return{...t!==!1&&{windowOpenerFeatures:As(Ru)},identityProvider:`https://nfid.one/authenticate/?applicationName=${encodeURI(this.#e)}&applicationLogo=${encodeURI(this.#t)}`}}};var Ot={certified:!1};var le=e=>X(e)?e:Ks()??new Ye;var Hu=({IDL:e})=>{let t=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),r=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),n=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),o=e.Record({field:n,desc:e.Bool}),s=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),i=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(s),description:e.Opt(e.Text),created_at:e.Opt(s)}),a=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),c=e.Record({order:e.Opt(o),owner:e.Opt(e.Principal),matcher:e.Opt(i),paginate:e.Opt(a)}),u=e.Record({controllers:e.Vec(e.Principal)}),p=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),d=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:p,expires_at:e.Opt(e.Nat64)}),l=e.Record({version:e.Opt(e.Nat64)}),f=e.Variant({Db:e.Null,Storage:e.Null}),h=e.Record({version:e.Opt(e.Nat64)}),_=e.Record({proposal_ids:e.Vec(e.Nat)}),g=e.Record({cycles:e.Nat,destination_id:e.Principal}),m=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),x=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),y=e.Record({key:m,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,x)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),T=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),O=e.Record({allowed_callers:e.Vec(e.Principal)}),R=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(T),rules:e.Opt(O)}),E=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),v=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(E)}),w=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),I=e.Variant({Deny:e.Null,Allow:e.Null}),B=e.Record({status_code:e.Nat16,location:e.Text}),A=e.Record({iframe:e.Opt(w),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(E),raw_access:e.Opt(I),redirects:e.Opt(e.Vec(e.Tuple(e.Text,B)))}),b=e.Record({db:e.Opt(v),authentication:e.Opt(R),storage:A}),N=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64,version:e.Opt(e.Nat64)}),P=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),V=e.Record({clear_existing_assets:e.Opt(e.Bool)}),q=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),S=e.Variant({AssetsUpgrade:V,SegmentsDeployment:q}),F=e.Record({status:P,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:S}),C=e.Variant({Heap:e.Null,Stable:e.Null}),D=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),k=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),ee=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(C),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:D,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(k),write:D,max_changes_per_user:e.Opt(e.Nat32)}),ne=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),z=e.Record({memory:C,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),Se=e.Variant({Callback:e.Record({token:z,callback:e.Func([],[],["query"])})}),Fe=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(Se),status_code:e.Nat16}),pt=e.Record({token:e.Opt(z),body:e.Vec(e.Nat8)}),oe=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),xe=e.Record({batch_id:e.Nat}),Hs=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,y)),items_length:e.Nat64}),Gs=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),zs=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,N)),items_length:e.Nat64}),Ws=e.Record({desc:e.Bool}),Ys=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),Js=e.Record({order:e.Opt(Ws),paginate:e.Opt(Ys)}),Zs=e.Record({proposal_id:e.Nat}),Xs=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(Zs,F)),items_length:e.Nat64}),Qs=e.Record({include_system:e.Bool}),ei=e.Record({matcher:e.Opt(Qs)}),ti=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,ee)),items_length:e.Nat64}),ri=e.Record({stable:e.Nat64,heap:e.Nat64}),ni=e.Record({version:e.Opt(e.Nat64),internet_identity:e.Opt(T),rules:e.Opt(O)}),oi=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:p,expires_at:e.Opt(e.Nat64)}),si=e.Record({controller:oi,controllers:e.Vec(e.Principal)}),ii=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(E)}),Tn=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),ai=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(C),max_size:e.Opt(e.Nat),read:D,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(k),write:D,max_changes_per_user:e.Opt(e.Nat32)}),ci=e.Record({iframe:e.Opt(w),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(E),raw_access:e.Opt(I),redirects:e.Opt(e.Vec(e.Tuple(e.Text,B)))}),Nn=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),On=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([t],[],[]),commit_proposal:e.Func([r],[e.Null],[]),commit_proposal_asset_upload:e.Func([t],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(t)],[],[]),count_assets:e.Func([e.Text,c],[e.Nat64],["query"]),count_collection_assets:e.Func([e.Text],[e.Nat64],["query"]),count_collection_docs:e.Func([e.Text],[e.Nat64],["query"]),count_docs:e.Func([e.Text,c],[e.Nat64],["query"]),count_proposals:e.Func([],[e.Nat64],["query"]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controllers:e.Func([u],[e.Vec(e.Tuple(e.Principal,d))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,l],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,c],[],[]),del_filtered_docs:e.Func([e.Text,c],[],[]),del_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[],[]),del_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,l))],[],[]),del_rule:e.Func([f,e.Text,h],[],[]),delete_proposal_assets:e.Func([_],[],[]),deposit_cycles:e.Func([g],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(y)],["query"]),get_auth_config:e.Func([],[e.Opt(R)],["query"]),get_config:e.Func([],[b],[]),get_db_config:e.Func([],[e.Opt(v)],["query"]),get_doc:e.Func([e.Text,e.Text],[e.Opt(N)],["query"]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(y)))],["query"]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(N)))],["query"]),get_proposal:e.Func([e.Nat],[e.Opt(F)],["query"]),get_rule:e.Func([f,e.Text],[e.Opt(ee)],["query"]),get_storage_config:e.Func([],[A],["query"]),http_request:e.Func([ne],[Fe],["query"]),http_request_streaming_callback:e.Func([z],[pt],["query"]),init_asset_upload:e.Func([oe],[xe],[]),init_proposal:e.Func([S],[e.Nat,F],[]),init_proposal_asset_upload:e.Func([oe,e.Nat],[xe],[]),init_proposal_many_assets_upload:e.Func([e.Vec(oe),e.Nat],[e.Vec(e.Tuple(e.Text,xe))],[]),list_assets:e.Func([e.Text,c],[Hs],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,d))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,Gs))],["query"]),list_docs:e.Func([e.Text,c],[zs],["query"]),list_proposals:e.Func([Js],[Xs],["query"]),list_rules:e.Func([f,ei],[ti],["query"]),memory_size:e.Func([],[ri],["query"]),reject_proposal:e.Func([r],[e.Null],[]),set_auth_config:e.Func([ni],[R],[]),set_controllers:e.Func([si],[e.Vec(e.Tuple(e.Principal,d))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([ii],[v],[]),set_doc:e.Func([e.Text,e.Text,Tn],[N],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Tn))],[e.Vec(e.Tuple(e.Text,N))],[]),set_rule:e.Func([f,e.Text,ai],[ee],[]),set_storage_config:e.Func([ci],[A],[]),submit_proposal:e.Func([e.Nat],[e.Nat,F],[]),upload_asset_chunk:e.Func([Nn],[On],[]),upload_proposal_asset_chunk:e.Func([Nn],[On],[])})},Gu=({IDL:e})=>{let t=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),r=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),n=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),o=e.Record({field:n,desc:e.Bool}),s=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),i=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(s),description:e.Opt(e.Text),created_at:e.Opt(s)}),a=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),c=e.Record({order:e.Opt(o),owner:e.Opt(e.Principal),matcher:e.Opt(i),paginate:e.Opt(a)}),u=e.Record({controllers:e.Vec(e.Principal)}),p=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),d=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:p,expires_at:e.Opt(e.Nat64)}),l=e.Record({version:e.Opt(e.Nat64)}),f=e.Variant({Db:e.Null,Storage:e.Null}),h=e.Record({version:e.Opt(e.Nat64)}),_=e.Record({proposal_ids:e.Vec(e.Nat)}),g=e.Record({cycles:e.Nat,destination_id:e.Principal}),m=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),x=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),y=e.Record({key:m,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,x)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),T=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),O=e.Record({allowed_callers:e.Vec(e.Principal)}),R=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(T),rules:e.Opt(O)}),E=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),v=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(E)}),w=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),I=e.Variant({Deny:e.Null,Allow:e.Null}),B=e.Record({status_code:e.Nat16,location:e.Text}),A=e.Record({iframe:e.Opt(w),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(E),raw_access:e.Opt(I),redirects:e.Opt(e.Vec(e.Tuple(e.Text,B)))}),b=e.Record({db:e.Opt(v),authentication:e.Opt(R),storage:A}),N=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64,version:e.Opt(e.Nat64)}),P=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),V=e.Record({clear_existing_assets:e.Opt(e.Bool)}),q=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),S=e.Variant({AssetsUpgrade:V,SegmentsDeployment:q}),F=e.Record({status:P,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:S}),C=e.Variant({Heap:e.Null,Stable:e.Null}),D=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),k=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),ee=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(C),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:D,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(k),write:D,max_changes_per_user:e.Opt(e.Nat32)}),ne=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),z=e.Record({memory:C,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),Se=e.Variant({Callback:e.Record({token:z,callback:e.Func([],[],[])})}),Fe=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(Se),status_code:e.Nat16}),pt=e.Record({token:e.Opt(z),body:e.Vec(e.Nat8)}),oe=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),xe=e.Record({batch_id:e.Nat}),Hs=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,y)),items_length:e.Nat64}),Gs=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),zs=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,N)),items_length:e.Nat64}),Ws=e.Record({desc:e.Bool}),Ys=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),Js=e.Record({order:e.Opt(Ws),paginate:e.Opt(Ys)}),Zs=e.Record({proposal_id:e.Nat}),Xs=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(Zs,F)),items_length:e.Nat64}),Qs=e.Record({include_system:e.Bool}),ei=e.Record({matcher:e.Opt(Qs)}),ti=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,ee)),items_length:e.Nat64}),ri=e.Record({stable:e.Nat64,heap:e.Nat64}),ni=e.Record({version:e.Opt(e.Nat64),internet_identity:e.Opt(T),rules:e.Opt(O)}),oi=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:p,expires_at:e.Opt(e.Nat64)}),si=e.Record({controller:oi,controllers:e.Vec(e.Principal)}),ii=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(E)}),Tn=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),ai=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(C),max_size:e.Opt(e.Nat),read:D,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(k),write:D,max_changes_per_user:e.Opt(e.Nat32)}),ci=e.Record({iframe:e.Opt(w),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(E),raw_access:e.Opt(I),redirects:e.Opt(e.Vec(e.Tuple(e.Text,B)))}),Nn=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),On=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([t],[],[]),commit_proposal:e.Func([r],[e.Null],[]),commit_proposal_asset_upload:e.Func([t],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(t)],[],[]),count_assets:e.Func([e.Text,c],[e.Nat64],[]),count_collection_assets:e.Func([e.Text],[e.Nat64],[]),count_collection_docs:e.Func([e.Text],[e.Nat64],[]),count_docs:e.Func([e.Text,c],[e.Nat64],[]),count_proposals:e.Func([],[e.Nat64],[]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controllers:e.Func([u],[e.Vec(e.Tuple(e.Principal,d))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,l],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,c],[],[]),del_filtered_docs:e.Func([e.Text,c],[],[]),del_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[],[]),del_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,l))],[],[]),del_rule:e.Func([f,e.Text,h],[],[]),delete_proposal_assets:e.Func([_],[],[]),deposit_cycles:e.Func([g],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(y)],[]),get_auth_config:e.Func([],[e.Opt(R)],[]),get_config:e.Func([],[b],[]),get_db_config:e.Func([],[e.Opt(v)],[]),get_doc:e.Func([e.Text,e.Text],[e.Opt(N)],[]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(y)))],[]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(N)))],[]),get_proposal:e.Func([e.Nat],[e.Opt(F)],[]),get_rule:e.Func([f,e.Text],[e.Opt(ee)],[]),get_storage_config:e.Func([],[A],[]),http_request:e.Func([ne],[Fe],[]),http_request_streaming_callback:e.Func([z],[pt],[]),init_asset_upload:e.Func([oe],[xe],[]),init_proposal:e.Func([S],[e.Nat,F],[]),init_proposal_asset_upload:e.Func([oe,e.Nat],[xe],[]),init_proposal_many_assets_upload:e.Func([e.Vec(oe),e.Nat],[e.Vec(e.Tuple(e.Text,xe))],[]),list_assets:e.Func([e.Text,c],[Hs],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,d))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,Gs))],[]),list_docs:e.Func([e.Text,c],[zs],[]),list_proposals:e.Func([Js],[Xs],[]),list_rules:e.Func([f,ei],[ti],[]),memory_size:e.Func([],[ri],[]),reject_proposal:e.Func([r],[e.Null],[]),set_auth_config:e.Func([ni],[R],[]),set_controllers:e.Func([si],[e.Vec(e.Tuple(e.Principal,d))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([ii],[v],[]),set_doc:e.Func([e.Text,e.Text,Tn],[N],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Tn))],[e.Vec(e.Tuple(e.Text,N))],[]),set_rule:e.Func([f,e.Text,ai],[ee],[]),set_storage_config:e.Func([ci],[A],[]),submit_proposal:e.Func([e.Nat],[e.Nat,F],[]),upload_asset_chunk:e.Func([Nn],[On],[]),upload_proposal_asset_chunk:e.Func([Nn],[On],[])})};var zu=({satelliteId:e,container:t})=>{let{satelliteId:r}=ja({satelliteId:e}),{container:n}=Ka({container:t});if(X(n)&&n!==!1){let{host:o,protocol:s}=new URL(n===!0?_n:n);return`${s}//${r??"unknown"}.${o.replace("127.0.0.1","localhost")}`}return`https://${r??"unknown"}.icp0.io`},ja=({satelliteId:e})=>X(e)?{satelliteId:e}:Ge.getInstance().get()??{satelliteId:void 0},Ka=({container:e})=>X(e)?{container:e}:Ge.getInstance().get()??{container:void 0};var ge=({satellite:e,options:{certified:t}})=>Yu({idlFactory:t?Gu:Hu,actorKey:`stock#${t?"update":"query"}`,...e}),Wu=({idlFactory:e,...t})=>Yu({idlFactory:e,actorKey:"extended#query",...t}),Yu=async({satelliteId:e,container:t,...r})=>{let{satelliteId:n}=ja({satelliteId:e});uo(n,"No satellite ID defined. Did you initialize Juno?");let{container:o}=Ka({container:t});return await gn.getInstance().getActor({satelliteId:n,container:o,...r})};var Ju=e=>{if(j(e))return ce();switch(e.matcher){case"equal":return ce({Equal:e.timestamp});case"greaterThan":return ce({GreaterThan:e.timestamp});case"lessThan":return ce({LessThan:e.timestamp});case"between":return ce({Between:[e.timestamps.start,e.timestamps.end]});default:throw new qs("Invalid list matcher for timestamp",e)}},pr=({matcher:e,paginate:t,order:r,owner:n})=>({matcher:j(e)?[]:[{key:ce(e.key),description:ce(e.description),created_at:Ju(e.createdAt),updated_at:Ju(e.updatedAt)}],paginate:ce(j(t)?void 0:{start_after:ce(t.startAfter),limit:ce(j(t.limit)?void 0:BigInt(t.limit))}),order:ce(j(r)?void 0:{desc:r.desc,field:r.field==="created_at"?{CreatedAt:null}:r.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:ce(j(n)?void 0:typeof n=="string"?L.fromText(n):n)});var Zu=async({data:e})=>{try{return await vs(e)}catch(t){console.error("The data parsing has failed, mapping to undefined as a fallback.",t);return}};var $a=async e=>{let{data:t,version:r,description:n}=e;return{description:ce(n),data:await Au(t),version:ce(r)}},Ha=e=>{let{version:t}=e;return{version:ce(t)}},xo=async({doc:e,key:t})=>{let{owner:r,version:n,description:o,data:s,...i}=e;return{key:t,description:Oe(o),owner:r.toText(),data:await vs(s),version:Oe(n),...i}};var Xu=async({collection:e,key:t,...r})=>{let{get_doc:n}=await ge(r),o=Oe(await n(e,t));if(!j(o))return xo({doc:o,key:t})},Qu=async({docs:e,...t})=>{let{get_many_docs:r}=await ge(t),n=e.map(({collection:i,key:a})=>[i,a]),o=await r(n),s=[];for(let[i,a]of o){let c=Oe(a);s.push(X(c)?await xo({key:i,doc:c}):void 0)}return s},ed=async({collection:e,doc:t,...r})=>{let{set_doc:n}=await ge(r),{key:o}=t,s=await $a(t),i=await n(e,o,s);return await xo({key:o,doc:i})},td=async({docs:e,...t})=>{let{set_many_docs:r}=await ge(t),n=[];for(let{collection:i,doc:a}of e){let{key:c}=a;n.push([i,c,await $a(a)])}let o=await r(n),s=[];for(let[i,a]of o)s.push(await xo({key:i,doc:a}));return s},rd=async({collection:e,doc:t,...r})=>{let{del_doc:n}=await ge(r),{key:o}=t;return n(e,o,Ha(t))},nd=async({docs:e,...t})=>{let{del_many_docs:r}=await ge(t),n=e.map(({collection:o,doc:s})=>[o,s.key,Ha(s)]);await r(n)},od=async({collection:e,filter:t,...r})=>{let{del_filtered_docs:n}=await ge(r);return n(e,pr(t))},sd=async({collection:e,filter:t,...r})=>{let{list_docs:n}=await ge(r),{items:o,items_page:s,items_length:i,matches_length:a,matches_pages:c}=await n(e,pr(t)),u=[];for(let[p,d]of o){let{data:l,owner:f,description:h,version:_,...g}=d;u.push({key:p,description:Oe(h),owner:f.toText(),data:await Zu({data:l}),version:Oe(_),...g})}return{items:u,items_length:i,items_page:Oe(s),matches_length:a,matches_pages:Oe(c)}},id=async({collection:e,filter:t,...r})=>{let{count_docs:n}=await ge(r);return n(e,pr(t))};var $s=async({satellite:e,options:t,...r})=>{let n=le(e?.identity);return await Xu({...r,satellite:{...e,identity:n},options:t??Ot})},Hb=async({satellite:e,options:t,...r})=>{let n=le(e?.identity);return await Qu({...r,satellite:{...e,identity:n},options:t??Ot})},ad=async({satellite:e,...t})=>{let r=le(e?.identity);return await ed({...t,satellite:{...e,identity:r},options:{certified:!0}})},cd=async({satellite:e,...t})=>{let r=le(e?.identity);return await td({...t,satellite:{...e,identity:r},options:{certified:!0}})},Gb=async({satellite:e,...t})=>{let r=le(e?.identity);return await rd({...t,satellite:{...e,identity:r},options:{certified:!0}})},zb=async({satellite:e,...t})=>{let r=le(e?.identity);return await nd({...t,satellite:{...e,identity:r},options:{certified:!0}})},Wb=async({satellite:e,filter:t,...r})=>{let n=le(e?.identity);return await od({...r,filter:t??{},satellite:{...e,identity:n},options:{certified:!0}})},Yb=async({satellite:e,options:t,filter:r,...n})=>{let o=le(e?.identity);return await sd({...n,filter:r??{},satellite:{...e,identity:o},options:t??Ot})},Jb=async({satellite:e,options:t,filter:r,...n})=>{let o=le(e?.identity);return await id({...n,filter:r??{},satellite:{...e,identity:o},options:t??Ot})};var ld=async({delegationIdentity:e,passkeyIdentity:t,satelliteId:r})=>{let n=t.getCredential().getAAGUID(),[o,s]=await cd({docs:[{collection:"#user",doc:{key:e.getPrincipal().toText(),data:{provider:"webauthn",providerData:{webauthn:{...X(n)&&{aaguid:Es(n)}}}}}},{collection:"#user-webauthn",doc:{key:t.getCredential().getCredentialIdText(),data:{publicKey:t.getPublicKey().toRaw()}}}],satellite:{identity:e,satelliteId:r}});return o};var ud=(s=>(s[s.RequestingUserCredential=0]="RequestingUserCredential",s[s.FinalizingCredential=1]="FinalizingCredential",s[s.Signing=2]="Signing",s[s.FinalizingSession=3]="FinalizingSession",s[s.RetrievingUser=4]="RetrievingUser",s))(ud||{}),dd=(i=>(i[i.CreatingUserCredential=0]="CreatingUserCredential",i[i.ValidatingUserCredential=1]="ValidatingUserCredential",i[i.FinalizingCredential=2]="FinalizingCredential",i[i.Signing=3]="Signing",i[i.FinalizingSession=4]="FinalizingSession",i[i.RegisteringUser=5]="RegisteringUser",i))(dd||{});var bo=class{get id(){return"webauthn"}async signUp({options:{onProgress:t,maxTimeToLiveInMilliseconds:r,passkey:n}={},loadAuthWithUser:o}){let{satelliteId:s}=Ge.getInstance().get()??{satelliteId:void 0};if(j(s))throw new jr("Satellite ID not set. Have you initialized the Satellite?");let i=({step:_,state:g})=>{switch(_){case dr.RequestingUserCredential:t?.({step:1,state:g});break;case dr.FinalizingCredential:t?.({step:2,state:g});break;case dr.Signing:t?.({step:3,state:g});break}},c=await Nt({fn:async()=>await va.createWithNewCredential({onProgress:i,passkeyOptions:n}),step:0,onProgress:t}),{delegationIdentity:u,sessionKey:p}=await this.#e({identity:c,maxTimeToLiveInMilliseconds:r}),l=await Nt({fn:async()=>await ld({delegationIdentity:u,passkeyIdentity:c,satelliteId:s}),step:5,onProgress:t});await Nt({fn:async()=>await this.#t({delegationIdentity:u,sessionKey:p}),step:4,onProgress:t}),await Nt({fn:async()=>await o({user:l}),step:5,onProgress:t})}async signIn({options:{onProgress:t,maxTimeToLiveInMilliseconds:r}={},loadAuth:n}){let{satelliteId:o}=Ge.getInstance().get()??{satelliteId:void 0};if(j(o))throw new jr("Satellite ID not set. Have you initialized the Satellite?");let s=async({credentialId:d})=>{let l=await $s({collection:"#user-webauthn",key:Rs(d),options:{certified:!0},satellite:{identity:new Ye,satelliteId:o}});if(j(l))throw new Us("No public key found for the selected passkey.");let{data:f}=l,{publicKey:h}=f;return Dr(h,co)},i=({step:d,state:l})=>{switch(d){case dr.RequestingUserCredential:t?.({step:0,state:l});break;case dr.FinalizingCredential:t?.({step:1,state:l});break;case dr.Signing:t?.({step:2,state:l});break}},a=await va.createWithExistingCredential({retrievePublicKey:s,onProgress:i}),{delegationIdentity:c,sessionKey:u}=await this.#e({identity:a,maxTimeToLiveInMilliseconds:r});await Nt({fn:async()=>await this.#t({delegationIdentity:c,sessionKey:u}),step:3,onProgress:t}),await Nt({fn:n,step:4,onProgress:t})}async#e({identity:t,maxTimeToLiveInMilliseconds:r}){let n=await Lr.generate({extractable:!1}),o=r??144e5,s=await qr.create(t,n.getPublicKey(),new Date(Date.now()+o));return{delegationIdentity:Mr.fromDelegation(n,s),sessionKey:n}}async#t({sessionKey:t,delegationIdentity:r}){let n=new Ht;await Promise.all([n.set(qe,t.getKeyPair()),n.set(ze,JSON.stringify(r.getDelegation().toJSON()))])}};var wo=()=>Bs.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}}),pd=async()=>(await new Ht().remove(qe),await wo());var Ga=({error:e,type:t})=>typeof e=="string"?e.includes(t):e instanceof Error?e.message.includes(t):!1;var fd="juno.datastore.error.user.cannot_update";var hd=async({provider:e})=>{let{user:t,userId:r}=await za();if(X(t))return t;try{return await pm({userId:r,provider:e})}catch(n){if(Ga({error:n,type:fd})){let o=await md({userId:r});if(X(o))return o}throw n}},za=async()=>{let e=Ks();if(j(e))throw new Ls("No identity to initialize the user. Have you initialized Juno?");let t=e.getPrincipal().toText(),r=await md({userId:t});return{userId:t,user:r}},md=({userId:e})=>$s({collection:"#user",key:e}),pm=({userId:e,...t})=>ad({collection:"#user",doc:{key:e,data:t}});var tt,Wa=async()=>{await Ya({fn:async()=>{let{user:t}=await za();et.getInstance().set(t??null)}})},fm=async({user:e})=>{await Ya({fn:async()=>{et.getInstance().set(e)}})},_d=async({provider:e})=>{await Ya({fn:async()=>{let r=await hd({provider:e});et.getInstance().set(r)}})},Ya=async({fn:e})=>{if(tt=await wo(),!await tt.isAuthenticated()){tt=await pd();return}await e()},hm=async e=>{let t=async()=>await _m(e);if(Object.values(e)[0].context?.windowGuard===!1){await t();return}await Aa({fn:t})},mm=async e=>{let t=async()=>await ym(e);if(Object.values(e)?.[0].context?.windowGuard===!1){await t();return}await Aa({fn:t})},_m=async e=>{if("webauthn"in e){let{webauthn:{options:t}}=e;await new bo().signIn({options:t,loadAuth:Wa});return}if("nfid"in e){let{nfid:{options:t}}=e,{appName:r,logoUrl:n,...o}=t??{};await new js({appName:r,logoUrl:n}).signIn({options:o,authClient:tt,initAuth:_d});return}if("internet_identity"in e){let{internet_identity:{options:t}}=e,{domain:r,...n}=t??{};await new Ms({domain:r}).signIn({options:n,authClient:tt,initAuth:_d});return}throw new Ds("An unknown or unsupported provider was provided for sign-in.")},ym=async e=>{if("webauthn"in e){let{webauthn:{options:t}}=e;await new bo().signUp({options:t,loadAuthWithUser:fm});return}throw new ks("An unknown or unsupported provider was provided for sign-up.")},Ja=async e=>{await gm(),tt=await wo(),e?.windowReload!==!1&&window.location.reload()},gm=async()=>{await tt?.logout(),tt=null,et.getInstance().reset(),gn.getInstance().reset(),yn.getInstance().reset()},Ks=()=>tt?.getIdentity(),xm=async()=>(tt??await wo()).getIdentity(),bm=async()=>{let e=et.getInstance().get();return j(e)||!(await tt?.isAuthenticated()??!1)?null:tt?.getIdentity()??null};var yd=e=>{let t=e===!0?"./workers/auth.worker.js":e,r=new Worker(t),n=async()=>{Ia({message:"junoSignOutAuthTimer"}),await Ja()};return r.onmessage=async({data:o})=>{let{msg:s,data:i}=o;switch(s){case"junoSignOutAuthTimer":await n();return;case"junoDelegationRemainingTime":Ia({message:"junoDelegationRemainingTime",detail:i?.authRemainingTime});return}},et.getInstance().subscribe(o=>{if(j(o)){r.postMessage({msg:"junoStopAuthTimer"});return}r.postMessage({msg:"junoStartAuthTimer"})})};var gd=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_SATELLITE_ID??import.meta.env?.PUBLIC_SATELLITE_ID:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SATELLITE_ID??e():e()},xd=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_CONTAINER??import.meta.env?.PUBLIC_CONTAINER:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_CONTAINER??e():e()};var Gw=async({idlFactory:e,satellite:t})=>{let r=le(t?.identity);return await Wu({idlFactory:e,...t,identity:r})};var bd=async({asset:{data:e,headers:t,...r},actor:n,progress:o})=>{let{init_asset_upload:s,upload_asset_chunk:i,commit_asset_upload:a}=n,{batch_id:c}=await s(wm(r));o?.onInitiatedBatch();let{chunkIds:u}=await Om({data:e,uploadFn:i,batchId:c});o?.onUploadedFileChunks(r.fullPath),await Nm({commitFn:a,batchId:c,data:e,headers:t,chunkIds:u}),o?.onCommittedBatch()};var wm=({filename:e,collection:t,token:r,fullPath:n,encoding:o,description:s})=>({collection:t,full_path:n,name:e,token:ce(r),encoding_type:ce(o),description:ce(s)}),Tm=({batchId:e,chunkIds:t,headers:r,data:n})=>{let o=r.find(([s,i])=>s.toLowerCase()==="content-type")===void 0&&n.type!==void 0&&n.type!==""?[["Content-Type",n.type]]:void 0;return{batch_id:e,chunk_ids:t.map(({chunk_id:s})=>s),headers:[...r,...o??[]]}},Nm=async({commitFn:e,...t})=>{let r=Tm(t);await e(r)},Om=async({data:e,uploadFn:t,batchId:r})=>{let n=[],o=Is()?new Blob([await e.arrayBuffer()]):e,s=0n;for(let a=0;a<o.size;a+=19e5){let c=o.slice(a,a+19e5);n.push({batchId:r,chunk:c,uploadFn:t,orderId:s}),s++}let i=[];for await(let a of Em({uploadChunks:n}))i=[...i,...a];return{chunkIds:i}};async function*Em({uploadChunks:e,limit:t=12}){for(let r=0;r<e.length;r=r+t){let n=e.slice(r,r+t);yield await Promise.all(n.map(o=>Rm(o)))}}var Rm=async({batchId:e,chunk:t,uploadFn:r,orderId:n})=>r({batch_id:e,content:new Uint8Array(await t.arrayBuffer()),order_id:ce(n)});var wd=async({asset:e,...t})=>{let r=await ge(t);await bd({actor:r,asset:e})},Td=async({collection:e,filter:t,...r})=>{let{list_assets:n}=await ge(r),{items:o,items_length:s,items_page:i,matches_length:a,matches_pages:c}=await n(e,pr(t));return{items:o.map(([u,p])=>p),items_length:s,items_page:Oe(i),matches_length:a,matches_pages:Oe(c)}},Nd=async({collection:e,filter:t,...r})=>{let{count_assets:n}=await ge(r);return n(e,pr(t))},Od=async({collection:e,fullPath:t,...r})=>(await ge(r)).del_asset(e,t),Ed=async({assets:e,satellite:t})=>{let{del_many_assets:r}=await ge({satellite:t,options:{certified:!0}}),n=e.map(({collection:o,fullPath:s})=>[o,s]);await r(n)},Rd=async({collection:e,filter:t,...r})=>{let{del_filtered_assets:n}=await ge(r);return n(e,pr(t))},vd=async({collection:e,fullPath:t,...r})=>{let{get_asset:n}=await ge(r);return Oe(await n(e,t))},Id=async({assets:e,...t})=>{let{get_many_assets:r}=await ge(t),n=e.map(({collection:s,fullPath:i})=>[s,i]);return(await r(n)).map(([s,i])=>Oe(i))};var Ad=e=>btoa([...e].map(t=>String.fromCharCode(t)).join(""));var lT=e=>Sd(e),uT=e=>Sd({filename:e.data.name,...e}),Sd=async({filename:e,data:t,collection:r,headers:n=[],fullPath:o,token:s,satellite:i,encoding:a,description:c})=>{let u=le(i?.identity),p=decodeURI(e),d=o??`/${r}/${p}`,l={...i,identity:u};return await wd({asset:{data:t,filename:p,collection:r,token:s,headers:n,fullPath:d,encoding:a,description:c},satellite:l,options:{certified:!0}}),{downloadUrl:Fd({satellite:l,assetKey:{fullPath:d,token:s}}),fullPath:d,name:p}},dT=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:le(r?.identity)},{items:s,...i}=await Td({collection:e,filter:t??{},satellite:o,options:n??Ot}),a=s.map(({key:{full_path:c,token:u,name:p,owner:d,description:l},headers:f,encodings:h,created_at:_,updated_at:g})=>{let m=Oe(u);return{fullPath:c,description:Oe(l),name:p,downloadUrl:Fd({satellite:o,assetKey:{fullPath:c,token:m}}),token:m,headers:f,encodings:h.reduce((x,[y,{modified:T,sha256:O,total_length:R}])=>({...x,[y]:{modified:T,sha256:Ad(O),total_length:R}}),{}),owner:d.toText(),created_at:_,updated_at:g}});return{items:a,assets:a,...i}},pT=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:le(r?.identity)};return await Nd({collection:e,satellite:o,filter:t??{},options:n??Ot})},fT=({collection:e,fullPath:t,satellite:r})=>Od({collection:e,fullPath:t,satellite:{...r,identity:le(r?.identity)},options:{certified:!0}}),hT=({assets:e,satellite:t})=>Ed({assets:e,satellite:{...t,identity:le(t?.identity)},options:{certified:!0}}),mT=async({collection:e,satellite:t,filter:r})=>{let n={...t,identity:le(t?.identity)};return await Rd({collection:e,satellite:n,filter:r??{},options:{certified:!0}})},_T=async({satellite:e,options:t,...r})=>{let n=le(e?.identity);return await vd({...r,satellite:{...e,identity:n},options:t??Ot})},yT=async({satellite:e,options:t,...r})=>{let n=le(e?.identity);return await Id({...r,satellite:{...e,identity:n},options:t??Ot})},Fd=({assetKey:{fullPath:e,token:t},satellite:r})=>{let n={...r,identity:le(r?.identity)};return`${zu(n)}${e}${X(t)?`?token=${t}`:""}`};var vm=e=>{let t=e?.satelliteId??gd();uo(t,"Satellite ID is not configured. Juno cannot be initialized.");let r=e?.container??xd();return{satelliteId:t,internetIdentityId:e?.internetIdentityId,workers:e?.workers,container:r}},RT=e=>Im(e),Im=async e=>{let t=vm(e);Ge.getInstance().set(t),await Wa();let r=t.workers?.auth!==void 0?yd(t.workers.auth):void 0;return[...r?[r]:[]]},Am=e=>et.getInstance().subscribe(e),vT=Am;export{$u as AuthClientSignInProgressStep,Ls as InitError,Ms as InternetIdentityProvider,qs as ListError,js as NFIDProvider,Cs as SignInError,jr as SignInInitError,Ds as SignInProviderNotSupportedError,Vs as SignInUserInterruptError,ks as SignUpProviderNotSupportedError,ud as WebAuthnSignInProgressStep,Us as WebAuthnSignInRetrievePublicKeyError,dd as WebAuthnSignUpProgressStep,vT as authSubscribe,pT as countAssets,Jb as countDocs,fT as deleteAsset,Gb as deleteDoc,mT as deleteFilteredAssets,Wb as deleteFilteredDocs,hT as deleteManyAssets,zb as deleteManyDocs,Fd as downloadUrl,_T as getAsset,$s as getDoc,bm as getIdentityOnce,yT as getManyAssets,Hb as getManyDocs,Gw as getSatelliteExtendedActor,RT as initJuno,Im as initSatellite,qh as isWebAuthnAvailable,dT as listAssets,Yb as listDocs,Am as onAuthStateChange,ad as setDoc,cd as setManyDocs,hm as signIn,Ja as signOut,mm as signUp,xm as unsafeIdentity,lT as uploadBlob,uT as uploadFile};
54
+ Retrying request.`),await this.#y({requestFn:r,backoff:n,tries:o+1});throw Zn.fromCode(new to(p))}let c=Ps(i.headers);if(i.status===Za||i.status===Jh)return{ok:i.ok,status:i.status,statusText:i.statusText,responseBodyBytes:a,headers:c};let u=await i.text();if(i.status===Zh&&i.url.includes("api/v3"))throw re.fromCode(new eo);if(u.startsWith("Invalid request expiry: "))throw z.fromCode(new Lr(u,this.#l));if(o<this.#d)return await this.#y({requestFn:r,backoff:n,tries:o+1});throw re.fromCode(new Qn(i.status,i.statusText,c,u))}async query(t,r,n){let o=this.#p(),s=r.effectiveCanisterId?k.from(r.effectiveCanisterId):k.from(t);await this.#g(s),this.log.print(`ecid ${s.toString()}`),this.log.print(`canisterId ${t.toString()}`);let i,a=await(n??this.#n);if(!a)throw Ee.fromCode(new pr);let c=k.from(t),u=a.getPrincipal(),p=Xa(this.#l,this.#r),d={request_type:Gr.Query,canister_id:c,method_name:r.methodName,arg:r.arg,sender:u,ingress_expiry:p},l=Kt(d);i=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:$t.Query,body:d}),i=await a.transformRequest(i);let f=yo(i.body),h={canister:c.toText(),ecid:s,transformedRequest:i,body:f,requestId:l,backoff:o,tries:0},m=async()=>{let _=await this.#b(h);return{requestDetails:d,..._}},y=async()=>{let _=this.#m.get(s.toString());if(_)return _;await this.fetchSubnetKeys(s.toString());let x=this.#m.get(s.toString());if(!x)throw Ue.fromCode(new hs);return x};try{if(!this.#_)return await m();let[_,x]=await Promise.all([m(),y()]);try{return this.#w(_,x)}catch{this.log.warn("Query response verification failed. Retrying with fresh subnet keys."),this.#m.delete(s.toString());let g=await y();return this.#w(_,g)}}catch(_){let x;throw _ instanceof dt?(_.code.requestContext={requestId:l,senderPubKey:i.body.sender_pubkey,senderSignature:i.body.sender_sig,ingressExpiry:i.body.content.ingress_expiry},x=_):x=ge.fromCode(new ke(_)),this.log.error(`Error while making query: ${x.message}`,x),x}}#w;async createReadStateRequest(t,r){await this.#g();let n=await(r??this.#n);if(!n)throw Ee.fromCode(new pr);let o=n.getPrincipal(),s=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:$t.ReadState,body:{request_type:Gr.ReadState,paths:t.paths,sender:o,ingress_expiry:Xa(this.#l,this.#r)}});return n.transformRequest(s)}async readState(t,r,n,o){await this.#T();let s=k.from(t);function i(p){for(let d of p.paths){let[l,f]=d,h=new TextEncoder().encode("request_status");if(Hr(l,h))return f}}let a,c;if(o)a=o,c=Kt(a);else{c=i(r);let p=await this.#n;if(!p)throw Ee.fromCode(new pr);a=await this.createReadStateRequest(r,p)}this.log.print(`fetching "/api/v2/canister/${s}/read_state" with request:`,a);let u=this.#p();try{let{responseBodyBytes:p}=await this.#y({requestFn:()=>this.#o(""+new URL(`/api/v2/canister/${s.toString()}/read_state`,this.host),{...this.#a,...a.request,body:yo(a.body)}),backoff:u,tries:0}),d=We(p);return this.log.print("Read state response:",d),d}catch(p){let d;throw p instanceof dt?(p.code.requestContext={requestId:c,senderPubKey:a.body.sender_pubkey,senderSignature:a.body.sender_sig,ingressExpiry:a.body.content.ingress_expiry},d=p):d=ge.fromCode(new ke(p)),this.log.error(`Error while making read state: ${d.message}`,d),d}}parseTimeFromResponse(t){let r;if(t.certificate){let n=We(t.certificate);if(n&&"tree"in n)r=n.tree;else throw re.fromCode(new fr("Could not decode time from response"));let o=Qr(["time"],r);if(o.status!==Ye.Found)throw re.fromCode(new Lt("Time was not found in the response or was not in its expected format.",o.status));if(!(o.value instanceof Uint8Array)&&!ArrayBuffer.isView(o))throw re.fromCode(new fn("Time was not in its expected format."));let s=Cn(o.value);return this.log.print("Time from response:",s),this.log.print("Time from response in milliseconds:",s.getTime()),s.getTime()}else this.log.warn("No certificate found in response");return 0}async syncTime(t){this.#i=this.#i??(async()=>{await this.#T();let r=Date.now();try{t||this.log.print("Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai");let n=t??k.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),o=e.createSync({identity:new rt,host:this.host.toString(),fetch:this.#o,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),i=(await Promise.all(Array(3).fill(null).map(async()=>{let c=(await Ka({canisterId:n,agent:o,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(c instanceof Date)return c.getTime()},[]))).reduce((a,c)=>typeof c=="number"&&c>a?c:a,0);i>0&&(this.#r=i-r,this.#c=!0,this.log.notify({message:`Syncing time: offset of ${this.#r}`,level:"info"}))}catch(n){let o=n instanceof dt?n:ge.fromCode(new ke(n));throw this.log.error("Caught exception while attempting to sync time",o),o}})(),await this.#i.finally(()=>{this.#i=null})}async status(){let t=this.#s?{Authorization:"Basic "+btoa(this.#s)}:{};this.log.print('fetching "/api/v2/status"');let r=this.#p(),{responseBodyBytes:n}=await this.#y({backoff:r,requestFn:()=>this.#o(""+new URL("/api/v2/status",this.host),{headers:t,...this.#a}),tries:0});return We(n)}async fetchRootKey(){return this.#e=this.#e??(async()=>{let t=await this.status();return this.rootKey=t.root_key,this.rootKey})(),await this.#e.finally(()=>{this.#e=null})}async#g(t){await Promise.all([this.#T(),this.#N(t)])}async#T(){if(!this.rootKey)if(this.rootKey===null&&this.host.toString()!=="https://icp-api.io"&&this.#t)await this.fetchRootKey();else throw Ee.fromCode(new Nt(this.#t))}async#N(t){this.#u&&!this.hasSyncedTime()&&await this.syncTime(t)}invalidateIdentity(){this.#n=null}replaceIdentity(t){this.#n=Promise.resolve(t)}async fetchSubnetKeys(t){let r=k.from(t);await this.#g(r);let o=(await Ka({canisterId:r,paths:["subnet"],agent:this})).get("subnet");if(o&&typeof o=="object"&&"nodeKeys"in o)return this.#m.set(r.toText(),o),o}_transform(t){let r=Promise.resolve(t);if(t.endpoint===$t.Call)for(let n of this.#h)r=r.then(o=>n(o).then(s=>s||o));else for(let n of this.#f)r=r.then(o=>n(o).then(s=>s||o));return r}getTimeDiffMsecs(){return this.#r}hasSyncedTime(){return this.#c}};function Xa(e,t){let r=e*Qa;return En.fromDeltaInMilliseconds(r,t)}var em=300*1e3;function Lu(){return sm(rm(tm(),1e3),om(1e3,1.2),nm(em))}function tm(){let e=!0;return async()=>e?(e=!1,!0):!1}function rm(e,t){return async(r,n,o)=>{if(await e(r,n,o))return new Promise(s=>setTimeout(s,t))}}function nm(e){let t=Date.now()+e;return async(r,n,o)=>{if(Date.now()>t)throw re.fromCode(new kr(`Request timed out after ${e} msec`,n,o))}}function om(e,t){let r=e;return()=>new Promise(n=>setTimeout(()=>{r*=t,n()},r))}function sm(...e){return async(t,r,n)=>{for(let o of e)await o(t,r,n)}}var Mu={preSignReadStateRequest:!1};function ju(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ec(e,t){return e!==null&&typeof e=="object"&&ju(e,t)}function am(e,t){return ju(e,t)&&typeof e[t]=="function"}function qu(e){return ec(e,"body")&&ec(e.body,"content")&&e.body.content.request_type===Gr.ReadState&&ec(e.body.content,"ingress_expiry")&&typeof e.body.content.ingress_expiry=="object"&&e.body.content.ingress_expiry!==null&&am(e.body.content.ingress_expiry,"toHash")}async function tc(e,t,r,n={}){let o=[Q("request_status"),r],s,i;if(n.preSignReadStateRequest??!1?(i=await cm({paths:[o],agent:e,pollingOptions:n}),s=await e.readState(t,{paths:[o]},void 0,i)):s=await e.readState(t,{paths:[o]}),e.rootKey==null)throw Ee.fromCode(new Nt);let c=await Tr.create({certificate:s.certificate,rootKey:e.rootKey,canisterId:t,blsVerify:n.blsVerify,agent:e}),u=Be(c.lookup_path([...o,Q("status")])),p;switch(typeof u>"u"?p=St.Unknown:p=new TextDecoder().decode(u),p){case St.Replied:return{reply:Be(c.lookup_path([...o,"reply"])),certificate:c};case St.Received:case St.Unknown:case St.Processing:{let d=n.strategy??Lu();return await d(t,r,p),tc(e,t,r,{...n,strategy:d,request:i})}case St.Rejected:{let d=new Uint8Array(Be(c.lookup_path([...o,"reject_code"])))[0],l=new TextDecoder().decode(Be(c.lookup_path([...o,"reject_message"]))),f=Be(c.lookup_path([...o,"error_code"])),h=f?new TextDecoder().decode(f):void 0;throw ur.fromCode(new mn(r,d,l,h))}case St.Done:throw ge.fromCode(new us(r))}throw hr}async function cm(e){let{paths:t,agent:r,pollingOptions:n}=e;if(n.request&&qu(n.request))return n.request;let o=await r.createReadStateRequest?.({paths:t},void 0);if(!qu(o))throw z.fromCode(new ys(o));return o}var it=Symbol.for("ic-agent-metadata"),Js=class e{static agentOf(t){return t[it].config.agent}static interfaceOf(t){return t[it].service}static canisterIdOf(t){return k.from(t[it].config.canisterId)}static createActorClass(t,r){let n=t({IDL:Kr});class o extends e{constructor(i){if(!i.canisterId)throw z.fromCode(new ro(i.canisterId));let a=typeof i.canisterId=="string"?k.fromText(i.canisterId):i.canisterId;super({config:{...Ku,...i,canisterId:a},service:n});for(let[c,u]of n._fields)r?.httpDetails&&u.annotations.push(rc),r?.certificate&&u.annotations.push(Hu),this[c]=um(this,c,u,i.blsVerify)}}return o}static createActor(t,r){if(!r.canisterId)throw z.fromCode(new ro(r.canisterId));return new(this.createActorClass(t))(r)}static createActorWithHttpDetails(t,r){return new(this.createActorClass(t,{httpDetails:!0}))(r)}static createActorWithExtendedDetails(t,r,n={httpDetails:!0,certificate:!0}){return new(this.createActorClass(t,n))(r)}constructor(t){this[it]=Object.freeze(t)}};function Bn(e,t){let r=Kr.decode(e,t);switch(r.length){case 0:return;case 1:return r[0];default:return r}}var Ku={pollingOptions:Mu},rc="http-details",Hu="certificate";function um(e,t,r,n){let o;r.annotations.includes("query")||r.annotations.includes("composite_query")?o=async(i,...a)=>{i={...i,...e[it].config.queryTransform?.(t,a,{...e[it].config,...i})};let c=i.agent||e[it].config.agent||new nn,u=k.from(i.canisterId||e[it].config.canisterId),p=Kr.encode(r.argTypes,a),d=await c.query(u,{methodName:t,arg:p,effectiveCanisterId:i.effectiveCanisterId}),l={...d.httpDetails,requestDetails:d.requestDetails};switch(d.status){case ir.Rejected:{let f=new cs(d.requestId,d.reject_code,d.reject_message,d.error_code,d.signatures);throw f.callContext={canisterId:u,methodName:t,httpDetails:l},ur.fromCode(f)}case ir.Replied:return r.annotations.includes(rc)?{httpDetails:l,result:Bn(r.retTypes,d.reply.arg)}:Bn(r.retTypes,d.reply.arg)}}:o=async(i,...a)=>{i={...i,...e[it].config.callTransform?.(t,a,{...e[it].config,...i})};let c=i.agent||e[it].config.agent||nn.createSync(),{canisterId:u,effectiveCanisterId:p,pollingOptions:d}={...Ku,...e[it].config,...i},l=k.from(u),f=p!==void 0?k.from(p):l,h=Kr.encode(r.argTypes,a),{requestId:m,response:y,requestDetails:_}=await c.call(l,{methodName:t,arg:h,effectiveCanisterId:f,nonce:i.nonce}),x,g;if(kc(y.body)){if(c.rootKey==null)throw Ee.fromCode(new Nt);let R=y.body.certificate;g=await Tr.create({certificate:R,rootKey:c.rootKey,canisterId:f,blsVerify:n,agent:c});let I=[Q("request_status"),m];switch(new TextDecoder().decode(Be(g.lookup_path([...I,"status"])))){case"replied":x=Be(g.lookup_path([...I,"reply"]));break;case"rejected":{let v=new Uint8Array(Be(g.lookup_path([...I,"reject_code"])))[0],C=new TextDecoder().decode(Be(g.lookup_path([...I,"reject_message"]))),A=Be(g.lookup_path([...I,"error_code"])),b=A?new TextDecoder().decode(A):void 0,O=new mn(m,v,C,b);throw O.callContext={canisterId:l,methodName:t,httpDetails:y},ur.fromCode(O)}}}else if(Uc(y.body)){let{reject_code:R,reject_message:I,error_code:w}=y.body,v=new ls(m,R,I,w);throw v.callContext={canisterId:l,methodName:t,httpDetails:y},ur.fromCode(v)}if(y.status===202){let R={...d,blsVerify:n},I=await tc(c,f,m,R);g=I.certificate,x=I.reply}let T=r.annotations.includes(rc),N=r.annotations.includes(Hu),E={...y,requestDetails:_};if(x!==void 0)return T&&N?{httpDetails:E,certificate:g,result:Bn(r.retTypes,x)}:N?{certificate:g,result:Bn(r.retTypes,x)}:T?{httpDetails:E,result:Bn(r.retTypes,x)}:Bn(r.retTypes,x);{let R=new ke(`Call was returned undefined. We cannot determine if the call was successful or not. Return types: [${r.retTypes.map(I=>I.display()).join(",")}].`);throw R.callContext={canisterId:l,methodName:t,httpDetails:E},ge.fromCode(R)}};let s=(...i)=>o({},...i);return s.withOptions=i=>(...a)=>o(i,...a),s}var dm=(e=>(e[e.FractionalMoreThan8Decimals=0]="FractionalMoreThan8Decimals",e[e.InvalidFormat=1]="InvalidFormat",e[e.FractionalTooManyDecimals=2]="FractionalTooManyDecimals",e))(dm||{}),sx=BigInt(1e8);var H=e=>e==null,X=e=>!H(e),pm=e=>X(e)&&e!=="",Gu=e=>!pm(e);var fm=class extends Error{},Bo=(e,t)=>{if(e==null)throw new fm(t)};var on=e=>new Uint8Array(e),Zs=e=>Array.from(e);var Wu=({a:e,b:t})=>e.length===t.length&&e.every((r,n)=>r===t[n]);var $u="abcdefghijklmnopqrstuvwxyz234567",Fo=Object.create(null);for(let e=0;e<$u.length;e++)Fo[$u[e]]=e;Fo[0]=Fo.o;Fo[1]=Fo.i;var Xs=e=>btoa(String.fromCharCode(...new Uint8Array(e)));var ix=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);var nc="__bigint__",oc="__principal__",sc="__uint8array__",zu=(e,t)=>typeof t=="bigint"?{[nc]:`${t}`}:X(t)&&k.isPrincipal(t)?{[oc]:k.from(t).toText()}:X(t)&&t instanceof Uint8Array?{[sc]:Array.from(t)}:t,Yu=(e,t)=>{let r=n=>t[n];return X(t)&&typeof t=="object"&&nc in t?BigInt(r(nc)):X(t)&&typeof t=="object"&&oc in t?k.fromText(r(oc)):X(t)&&typeof t=="object"&&sc in t?Uint8Array.from(r(sc)):t};var le=e=>X(e)?[e]:[],Ie=e=>e?.[0];var hm=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let t=e.slice(37,53),r=mm({bytes:t});return"aaguid"in r?{aaguidBytes:t,aaguidText:r.aaguid}:{unknownProvider:null}},mm=({bytes:e})=>{if(e.length!==16)return{invalidBytes:null};let t=(e instanceof Uint8Array?Zs(e):e).map(r=>r.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5");return t==="00000000-0000-0000-0000-000000000000"?{unknownProvider:null}:{aaguid:t}};function _m(e){let t=new DataView(new ArrayBuffer(2)),r=e.slice(53,55);[...new Uint8Array(r)].forEach((o,s)=>t.setUint8(s,o));let n=t.getUint16(0);return e.slice(55+n)}function ym(e){return tn(e,Co)}var gm=class{constructor(e){this._cose=e,this.#e=ym(e)}#e;toDer(){return this.#e}toRaw(){return new Uint8Array(this.#e)}},ed=class{#e;#t;constructor({rawId:e,cose:t}){this.#e=e,this.#t=new gm(t)}getPublicKey(){return this.#t}getCredentialId(){return this.#e}getCredentialIdText(){return Xs(this.#e)}},xm=class extends ed{#e;#t;constructor({authData:e,...t}){super(t);let r=hm({authData:e});this.#e="aaguidText"in r?r.aaguidText:void 0,this.#t="aaguidBytes"in r?r.aaguidBytes:void 0}getAAGUID(){return this.#t}getAAGUIDText(){return this.#e}},bm=class extends ed{},wm=class extends Error{},Tm=class extends Error{},Om=class extends Error{},Nm=class extends Error{},Em=class extends Error{},Rm=class extends Error{},vm=class extends Error{},Ju=class extends Error{};var Im={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},Am=6e4,td=()=>window.crypto.getRandomValues(new Uint8Array(16)),Sm=()=>td(),Pm=()=>td(),Cm=()=>{let{location:{href:e}}=window;try{let{hostname:t}=new URL(e);return t}catch{throw new wm}},rd=({appId:e})=>e?.id??Cm(),Fm=({appId:e,user:t}={})=>{let{document:{title:r}}=window,n=()=>({rp:{name:e?.name??r,id:rd({appId:e})}}),o=()=>({user:{id:Pm(),name:t?.name??t?.displayName??r,displayName:t?.displayName??r}});return{attestation:"direct",challenge:Sm(),...n(),...o(),pubKeyCredParams:Object.values(Im).map(s=>({type:"public-key",alg:s})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},Bm=(e={})=>({rpId:rd(e),allowCredentials:[],userVerification:"required"}),ic=async({fn:e,step:t,onProgress:r})=>{r?.({step:t,state:"in_progress"});try{let n=await e();return r?.({step:t,state:"success"}),n}catch(n){throw r?.({step:t,state:"error"}),n}},Er=(e=>(e[e.RequestingUserCredential=0]="RequestingUserCredential",e[e.FinalizingCredential=1]="FinalizingCredential",e[e.Signing=2]="Signing",e))(Er||{}),nd=({timeout:e})=>AbortSignal.timeout(e??Am),Vm=async({challenge:e,credentialIds:t,passkeyOptions:r,timeout:n})=>await navigator.credentials.get({publicKey:{...Bm(r),challenge:e.buffer,allowCredentials:(t??[]).map(o=>({id:o.buffer,type:"public-key"}))},signal:nd({timeout:n})}),Zu=e=>{if(e.status!=="initialized")throw new Tm},Xu=e=>{if(H(e))throw new Om},Qu=({type:e})=>{if(e!=="public-key")throw new Nm},ac=class Vo extends At{#e;#t;constructor({onProgress:t,...r}){if(super(),this.#e=t,"retrievePublicKey"in r){let{retrievePublicKey:n}=r;this.#t={status:"pending",retrievePublicKey:n};return}this.#t=Vo.#r({credential:new xm(r)})}static#r({credential:t}){return{status:"initialized",credential:t}}static async createWithNewCredential({passkeyOptions:t,timeout:r,...n}={}){let o=await navigator.credentials.create({publicKey:Fm(t),signal:nd({timeout:r})});Xu(o),Qu(o);let{response:{attestationObject:s},rawId:i}=o;if(H(s))throw new Em;let{authData:a}=Is.decode(on(s)),c=_m(a);return new Vo({...n,rawId:on(i),cose:c,authData:a})}static async createWithExistingCredential(t){return new Vo(t)}getPublicKey(){Zu(this.#t);let{credential:t}=this.#t;return t.getPublicKey()}getCredential(){Zu(this.#t);let{credential:t}=this.#t;return t}async sign(t){let r=await ic({fn:async()=>{let n=await Vm({challenge:t,...this.#t.status==="initialized"&&{credentialIds:[this.#t.credential.getCredentialId()]}});return Xu(n),Qu(n),n},step:0,onProgress:this.#e});return await ic({fn:async()=>{let{rawId:n}=r;if(this.#t.status==="initialized"){if(!Wu({a:this.#t.credential.getCredentialId(),b:on(n)}))throw new Rm;return}let{retrievePublicKey:o}=this.#t,s=await o({credentialId:on(n)});this.#t=Vo.#r({credential:new bm({rawId:on(n),cose:s})})},step:1,onProgress:this.#e}),await ic({fn:async()=>{let{response:n}=r,{clientDataJSON:o}=n,{authenticatorData:s,signature:i}="authenticatorData"in n&&"signature"in n?n:{};if(H(s))throw new Ju;if(H(i))throw new Ju;let a=Is.encode({authenticator_data:s,client_data_json:new TextDecoder().decode(o),signature:on(i)});if(H(a))throw new vm;return Object.assign(a,{__signature__:void 0}),a},step:2,onProgress:this.#e})}},Dm=async()=>X(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;var Vn=class{callbacks=[];populate(t){this.callbacks.forEach(({callback:r})=>r(t))}subscribe(t){let r=Symbol();return this.callbacks.push({id:r,callback:t}),()=>this.callbacks=this.callbacks.filter(({id:n})=>n!==r)}};var at=class e extends Vn{static instance;authUser=null;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(t){this.authUser=t,this.populate(t)}get(){return this.authUser}subscribe(t){let r=super.subscribe(t);return t(this.authUser),r}reset(){this.authUser=null,this.populate(this.authUser)}};var cc=({message:e,detail:t})=>{let r=new CustomEvent(e,{detail:t,bubbles:!0});document.dispatchEvent(r)};var Dn="http://127.0.0.1:5987",od="rdmx6-jaaaa-aaaaa-aaadq-cai";var sd=async({identity:e,container:t})=>{let n=X(t)&&t!==!1?t===!0?Dn:t:"https://icp-api.io",o=X(t);return await nn.create({identity:e,shouldFetchRootKey:o,host:n})};var Un=class e{static instance;#e=void 0;constructor(){}static getInstance(){return H(e.instance)&&(e.instance=new e),e.instance}async getAgent({identity:t,...r}){let n=t.getPrincipal().toText();if(H(this.#e)||H(this.#e[n])){let o=await sd({identity:t,...r});return this.#e={...this.#e??{},[n]:o},o}return this.#e[n]}reset(){this.#e=null}};var kn=class e{static instance;#e=void 0;constructor(){}static getInstance(){return H(e.instance)&&(e.instance=new e),e.instance}async getActor({satelliteId:t,identity:r,actorKey:n,...o}){let s=`${n}#${r.getPrincipal().toText()}#${t};`;if(H(this.#e)||H(this.#e[s])){let i=await this.createActor({satelliteId:t,identity:r,...o});return this.#e={...this.#e??{},[s]:i},i}return this.#e[s]}reset(){this.#e=null}async createActor({idlFactory:t,satelliteId:r,...n}){let o=await Un.getInstance().getAgent(n);return Js.createActor(t,{agent:o,canisterId:r})}};var id=e=>(e.preventDefault(),e.returnValue="Are you sure you want to exit?"),Um=()=>{window.addEventListener("beforeunload",id,{capture:!0})},km=()=>{window.removeEventListener("beforeunload",id,{capture:!0})},lc=async({fn:e})=>{try{return Um(),await e()}finally{km()}};var et=class e extends Vn{static instance;env;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(t){this.env=t,this.populate(t)}get(){return this.env}reset(){this.env=null}subscribe(t){let r=super.subscribe(t);return t(this.env),r}};var ad=BigInt(144e11),cd=!1,ld={width:576,height:576},ud={width:424,height:576},dd={width:505,height:705},Do="internetcomputer.org",pd="ic0.app",fd="id.ai";var hd=async e=>{let t=new Blob([JSON.stringify(e,zu)],{type:"application/json; charset=utf-8"});return new Uint8Array(await t.arrayBuffer())},Qs=async e=>{let t=new Blob([e instanceof Uint8Array?e:new Uint8Array(e)],{type:"application/json; charset=utf-8"});return JSON.parse(await t.text(),Yu)},ei=()=>typeof window<"u";var ti=({width:e,height:t})=>{if(!ei()||H(window)||H(window.top))return;let{top:{innerWidth:r,innerHeight:n}}=window,o=n/2+screenY-t/2,s=r/2+screenX-e/2;return`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=${e}, height=${t}, top=${o}, left=${s}`};function md(e){return e!==null&&typeof e=="object"}var Uo=class e{static from(t){if(typeof t=="string"){let r=Ne(t);return this.fromRaw(r)}else if(md(t)){let r=t;if(md(r)&&Object.hasOwnProperty.call(r,"__derEncodedPublicKey__"))return this.fromDer(r);if(ArrayBuffer.isView(r)){let n=r;return this.fromRaw(Et(n.buffer))}else{if(r instanceof ArrayBuffer)return this.fromRaw(Et(r));if("rawKey"in r&&r.rawKey instanceof Uint8Array)return this.fromRaw(r.rawKey);if("derKey"in r)return this.fromDer(r.derKey);if("toDer"in r)return this.fromDer(r.toDer())}}throw new Error("Cannot construct Ed25519PublicKey from the provided key.")}static fromRaw(t){return new e(t)}static fromDer(t){return new e(this.derDecode(t))}static{this.RAW_KEY_LENGTH=32}static derEncode(t){let r=tn(t,en);return r.__derEncodedPublicKey__=void 0,r}static derDecode(t){let r=rn(t,en);if(r.length!==this.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");return r}#e;get rawKey(){return this.#e}#t;get derKey(){return this.#t}constructor(t){if(t.byteLength!==e.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");this.#e=t,this.#t=e.derEncode(t)}toDer(){return this.derKey}toRaw(){return this.rawKey}},sn=class e extends At{static generate(t){if(t&&t.length!==32)throw new Error("Ed25519 Seed needs to be 32 bytes long.");t||(t=He.utils.randomPrivateKey()),sl(t,new Uint8Array(new Array(32).fill(0)))&&console.warn("Seed is all zeros. This is not a secure seed. Please provide a seed with sufficient entropy if this is a production environment.");let r=new Uint8Array(32);for(let o=0;o<32;o++)r[o]=t[o];let n=He.getPublicKey(r);return e.fromKeyPair(n,r)}static fromParsedJson(t){let[r,n]=t;return new e(Uo.fromDer(Ne(r)),Ne(n))}static fromJSON(t){let r=JSON.parse(t);if(Array.isArray(r)){if(typeof r[0]=="string"&&typeof r[1]=="string")return this.fromParsedJson([r[0],r[1]]);throw new Error("Deserialization error: JSON must have at least 2 items.")}throw new Error(`Deserialization error: Invalid JSON type for string: ${JSON.stringify(t)}`)}static fromKeyPair(t,r){return new e(Uo.fromRaw(t),r)}static fromSecretKey(t){let r=He.getPublicKey(t);return e.fromKeyPair(r,t)}#e;#t;constructor(t,r){super(),this.#e=Uo.from(t),this.#t=r}toJSON(){return[K(this.#e.toDer()),K(this.#t)]}getKeyPair(){return{secretKey:this.#t,publicKey:this.#e}}getPublicKey(){return this.#e}async sign(t){let r=He.sign(t,this.#t.slice(0,32));return Object.defineProperty(r,"__signature__",{enumerable:!1,value:void 0}),r}static verify(t,r,n){let[o,s,i]=[t,r,n].map(a=>(typeof a=="string"&&(a=Ne(a)),Et(a)));return He.verify(o,s,i)}};var uc=class e extends Error{constructor(t){super(t),this.message=t,Object.setPrototypeOf(this,e.prototype)}};function _d(e){if(typeof global<"u"&&global.crypto&&global.crypto.subtle)return global.crypto.subtle;if(e)return e;if(typeof crypto<"u"&&crypto.subtle)return crypto.subtle;throw new uc("Global crypto was not available and none was provided. Please inlcude a SubtleCrypto implementation. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto")}var Rr=class e extends At{static async generate(t){let{extractable:r=!1,keyUsages:n=["sign","verify"],subtleCrypto:o}=t??{},s=_d(o),i=await s.generateKey({name:"ECDSA",namedCurve:"P-256"},r,n),a=Et(await s.exportKey("spki",i.publicKey));return Object.assign(a,{__derEncodedPublicKey__:void 0}),new this(i,a,s)}static async fromKeyPair(t,r){let n=_d(r),o=Et(await n.exportKey("spki",t.publicKey));return Object.assign(o,{__derEncodedPublicKey__:void 0}),new e(t,o,n)}constructor(t,r,n){super(),this._keyPair=t,this._derKey=r,this._subtleCrypto=n}getKeyPair(){return this._keyPair}getPublicKey(){let t=this._derKey,r=Object.create(this._keyPair.publicKey);return r.toDer=function(){return t},r}async sign(t){let r={name:"ECDSA",hash:{name:"SHA-256"}},n=Et(await this._subtleCrypto.sign(r,this._keyPair.privateKey,t));return Object.assign(n,{__signature__:void 0}),n}};var ri=class{#e;get rawKey(){return this.#e.rawKey}get derKey(){return this.#e.derKey}toDer(){return this.#e.toDer()}getPublicKey(){return this.#e}getPrincipal(){if(!this.#e.rawKey)throw new Error("Cannot get principal from a public key without a raw key.");return k.fromUint8Array(new Uint8Array(this.#e.rawKey))}transformRequest(){return Promise.reject("Not implemented. You are attempting to use a partial identity to sign calls, but this identity only has access to the public key.To sign calls, use a DelegationIdentity instead.")}constructor(t){this.#e=t}};function ni(e){return e instanceof Uint8Array?K(e):K(new Uint8Array(e))}function dc(e){if(typeof e!="string"||e.length<64)throw new Error("Invalid public key.");return Ne(e)}var vr=class{constructor(t,r,n){this.pubkey=t,this.expiration=r,this.targets=n}toCborValue(){return{pubkey:this.pubkey,expiration:this.expiration,...this.targets&&{targets:this.targets}}}toJSON(){return{expiration:this.expiration.toString(16),pubkey:ni(this.pubkey),...this.targets&&{targets:this.targets.map(t=>t.toHex())}}}};async function Lm(e,t,r,n){let o=new vr(t.toDer(),BigInt(+r)*BigInt(1e6),n),s=new Uint8Array([...ca,...new Uint8Array(Kt({...o}))]),i=await e.sign(s);return{delegation:o,signature:i}}var er=class e{static async create(t,r,n=new Date(Date.now()+900*1e3),o={}){let s=await Lm(t,r,n,o.targets);return new e([...o.previous?.delegations||[],s],o.previous?.publicKey||t.getPublicKey().toDer())}static fromJSON(t){let{publicKey:r,delegations:n}=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(n))throw new Error("Invalid delegations.");let o=n.map(s=>{let{delegation:i,signature:a}=s,{pubkey:c,expiration:u,targets:p}=i;if(p!==void 0&&!Array.isArray(p))throw new Error("Invalid targets.");return{delegation:new vr(dc(c),BigInt("0x"+u),p&&p.map(d=>{if(typeof d!="string")throw new Error("Invalid target.");return k.fromHex(d)})),signature:dc(a)}});return new this(o,dc(r))}static fromDelegations(t,r){return new this(t,r)}constructor(t,r){this.delegations=t,this.publicKey=r}toJSON(){return{delegations:this.delegations.map(t=>{let{delegation:r,signature:n}=t,{targets:o}=r;return{delegation:{expiration:r.expiration.toString(16),pubkey:ni(r.pubkey),...o&&{targets:o.map(s=>s.toHex())}},signature:ni(n)}}),publicKey:ni(this.publicKey)}}},Ir=class extends At{static fromDelegation(t,r){return new this(t,r)}constructor(t,r){super(),this._inner=t,this._delegation=r}getDelegation(){return this._delegation}getPublicKey(){return{derKey:this._delegation.publicKey,toDer:()=>this._delegation.publicKey}}sign(t){return this._inner.sign(t)}async transformRequest(t){let{body:r,...n}=t,o=await Kt(r);return{...n,body:{content:r,sender_sig:await this.sign(new Uint8Array([...po,...new Uint8Array(o)])),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}}}},Ln=class e extends ri{#e;get delegation(){return this.#e}constructor(t,r){super(t),this.#e=r}static fromDelegation(t,r){return new e(t,r)}};function pc(e,t){for(let{delegation:o}of e.delegations)if(+new Date(Number(o.expiration/BigInt(1e6)))<=+Date.now())return!1;let r=[],n=t?.scope;n&&(Array.isArray(n)?r.push(...n.map(o=>typeof o=="string"?k.fromText(o):o)):r.push(typeof n=="string"?k.fromText(n):n));for(let o of r){let s=o.toText();for(let{delegation:i}of e.delegations){if(i.targets===void 0)continue;let a=!0;for(let c of i.targets)if(c.toText()===s){a=!1;break}if(a)return!1}}return!0}var tr=e=>{if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(e,"base64");if(typeof globalThis.atob<"u")return Uint8Array.from(globalThis.atob(e),t=>t.charCodeAt(0));throw Error("Could not decode base64 string")},qn=e=>{if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(e).toString("base64");if(typeof globalThis.btoa<"u")return btoa(Array.from({length:Math.ceil(e.byteLength/1e5)}).map((t,r)=>String.fromCharCode(...new Uint8Array(e.slice(r*1e5,(r+1)*1e5)))).join(""));throw Error("Could not encode base64 string")};var Mn=function(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},fe=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},Ve,rr,jn,oi,cn=class e extends Error{constructor(t){super(t.message),Object.setPrototypeOf(this,e.prototype),this.code=t.code,this.data=t.data}},yd=e=>new cn({code:4e3,message:e instanceof Error?e.message:"Network error"}),an=e=>{if("error"in e)throw new cn(e.error);if("result"in e)return e.result;throw new cn({code:4e3,message:"Invalid response"})},ii=class{constructor(t){Ve.set(this,void 0),rr.set(this,void 0),jn.set(this,void 0),oi.set(this,void 0),Mn(this,Ve,Object.assign({autoCloseTransportChannel:!0,closeTransportChannelAfter:200,crypto:globalThis.crypto},t),"f")}get transport(){return fe(this,Ve,"f").transport}async openChannel(){if(clearTimeout(fe(this,oi,"f")),fe(this,jn,"f")&&await fe(this,jn,"f"),fe(this,rr,"f")&&!fe(this,rr,"f").closed)return fe(this,rr,"f");let t=fe(this,Ve,"f").transport.establishChannel();return Mn(this,jn,t.then(()=>{}).catch(()=>{}),"f"),Mn(this,rr,void 0,"f"),Mn(this,rr,await t.catch(r=>{throw yd(r)}),"f"),Mn(this,jn,void 0,"f"),fe(this,rr,"f")}async closeChannel(){var t;await((t=fe(this,rr,"f"))===null||t===void 0?void 0:t.close())}async transformRequest(t){return fe(this,Ve,"f").derivationOrigin?Object.assign(Object.assign({},t),{params:Object.assign(Object.assign({},t.params),{icrc95DerivationOrigin:fe(this,Ve,"f").derivationOrigin})}):t}async sendRequest(t){let r=await this.openChannel();return new Promise(async(n,o)=>{let s=r.addEventListener("response",async a=>{a.id===t.id&&(s(),i(),n(a),fe(this,Ve,"f").autoCloseTransportChannel&&Mn(this,oi,setTimeout(()=>{r.closed||r.close()},fe(this,Ve,"f").closeTransportChannelAfter),"f"))}),i=r.addEventListener("close",()=>{s(),i(),o(new cn({code:4e3,message:"Channel was closed before a response was received"}))});try{await r.send(await this.transformRequest(t))}catch(a){s(),i(),o(yd(a))}})}async supportedStandards(){let t=await this.sendRequest({id:fe(this,Ve,"f").crypto.randomUUID(),jsonrpc:"2.0",method:"icrc25_supported_standards"});return an(t).supportedStandards}async requestPermissions(t){let r=await this.sendRequest({id:fe(this,Ve,"f").crypto.randomUUID(),jsonrpc:"2.0",method:"icrc25_request_permissions",params:{scopes:t}});return an(r).scopes}async permissions(){let t=await this.sendRequest({id:fe(this,Ve,"f").crypto.randomUUID(),jsonrpc:"2.0",method:"icrc25_permissions"});return an(t).scopes}async accounts(){let t=await this.sendRequest({id:fe(this,Ve,"f").crypto.randomUUID(),jsonrpc:"2.0",method:"icrc27_accounts"});return an(t).accounts.map(({owner:n,subaccount:o})=>({owner:k.fromText(n),subaccount:o===void 0?void 0:tr(o)}))}async delegation(t){var r;let n=await this.sendRequest({id:fe(this,Ve,"f").crypto.randomUUID(),jsonrpc:"2.0",method:"icrc34_delegation",params:{publicKey:qn(t.publicKey),targets:(r=t.targets)===null||r===void 0?void 0:r.map(s=>s.toText()),maxTimeToLive:t.maxTimeToLive===void 0?void 0:String(t.maxTimeToLive)}}),o=an(n);return er.fromDelegations(o.signerDelegation.map(s=>{var i;return{delegation:new vr(tr(s.delegation.pubkey),BigInt(s.delegation.expiration),(i=s.delegation.targets)===null||i===void 0?void 0:i.map(a=>k.fromText(a))),signature:tr(s.signature)}}),tr(o.publicKey))}async callCanister(t){let r=await this.sendRequest({id:fe(this,Ve,"f").crypto.randomUUID(),jsonrpc:"2.0",method:"icrc49_call_canister",params:{canisterId:t.canisterId.toText(),sender:t.sender.toText(),method:t.method,arg:qn(t.arg),nonce:t.nonce?qn(t.nonce):void 0}}),n=an(r),o=tr(n.contentMap),s=tr(n.certificate);return{contentMap:o,certificate:s}}async batchCallCanister(t){var r;let n=await this.sendRequest({id:fe(this,Ve,"f").crypto.randomUUID(),jsonrpc:"2.0",method:"icrc112_batch_call_canister",params:{sender:t.sender.toText(),validationCanisterId:(r=t.validationCanisterId)===null||r===void 0?void 0:r.toText(),requests:t.requests.map(s=>s.map(i=>({canisterId:i.canisterId.toText(),method:i.method,arg:qn(i.arg),nonce:i.nonce?qn(i.nonce):void 0})))}}),o=an(n);if(t.requests.length!==o.responses.length||t.requests.some((s,i)=>s.length!==o.responses[i].length))throw new cn({code:4e3,message:"Invalid batch call canister response, structure does not match request structure"});return o.responses.map(s=>s.map(i=>({result:{contentMap:tr(i.contentMap),certificate:tr(i.certificate)}})))}};Ve=new WeakMap,rr=new WeakMap,jn=new WeakMap,oi=new WeakMap;var gd=e=>typeof e=="object"&&!!e&&"jsonrpc"in e&&e.jsonrpc==="2.0",xd=e=>gd(e)&&"method"in e&&typeof e.method=="string",ai=e=>gd(e)&&"id"in e&&(typeof e.id=="string"||typeof e.id=="number");var fc=function(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},ie=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},ko,Ae,Kn,Lo,ci=class{constructor(t){ko.set(this,new Set),Ae.set(this,void 0),Kn.set(this,!1),Lo.set(this,[]),fc(this,Ae,Object.assign({signerStatus:"ready",window:globalThis.window,manageFocus:!0},t),"f")}get closed(){return ie(this,Kn,"f")}addEventListener(...[t,r]){switch(t){case"close":return ie(this,ko,"f").add(r),()=>{ie(this,ko,"f").delete(r)};case"response":let n=async o=>{o.source!==ie(this,Ae,"f").signerWindow||o.origin!==ie(this,Ae,"f").signerOrigin||!ai(o.data)||r(o.data)};return ie(this,Ae,"f").window.addEventListener("message",n),()=>{ie(this,Ae,"f").window.removeEventListener("message",n)}}}async send(t){if(ie(this,Kn,"f"))throw new nr("Communication channel is closed");if(ie(this,Ae,"f").signerStatus==="pending"){ie(this,Lo,"f").push(t);return}ie(this,Ae,"f").signerWindow.postMessage(t,ie(this,Ae,"f").signerOrigin),ie(this,Ae,"f").manageFocus&&ie(this,Ae,"f").signerWindow.focus()}async close(){ie(this,Kn,"f")||(fc(this,Kn,!0,"f"),ie(this,Ae,"f").signerWindow.close(),ie(this,Ae,"f").manageFocus&&ie(this,Ae,"f").window.focus(),ie(this,ko,"f").forEach(t=>t()))}changeStatus(t){if(ie(this,Ae,"f").signerStatus=t,t==="ready"){let r=ie(this,Lo,"f");fc(this,Lo,[],"f"),r.forEach((n,o)=>{ie(this,Ae,"f").signerWindow.postMessage(n,ie(this,Ae,"f").signerOrigin)})}}};ko=new WeakMap,Ae=new WeakMap,Kn=new WeakMap,Lo=new WeakMap;var bd=e=>{try{let t=new URL(e);return t.protocol==="https:"||t.hostname==="127.0.0.1"||t.hostname.split(".").slice(-1)[0]==="localhost"}catch{return!1}};var _c=function(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},ae=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},Ar,Te,qo,Td,wd,hc,mc,li=class{constructor(t){Ar.add(this),Te.set(this,void 0),qo.set(this,void 0),_c(this,Te,Object.assign({establishTimeout:1e4,pendingTimeout:3e5,disconnectTimeout:2e3,statusPollingRate:300,window:globalThis.window,crypto:globalThis.crypto},t),"f"),ae(this,Ar,"m",Td).call(this)}};Te=new WeakMap,qo=new WeakMap,Ar=new WeakSet,Td=function(){let t=[],r=()=>{let i=ae(this,Te,"f").crypto.randomUUID();return t.push(i),i},n=ae(this,Ar,"m",hc).call(this,i=>{"result"in i.data&&t.includes(i.data.id)&&(t=[],n(),clearInterval(s),clearTimeout(o),_c(this,qo,i.data.result,"f"),ae(this,Te,"f").onEstablish(i.origin,i.data.result),ae(this,Ar,"m",wd).call(this,i.origin,i.data.result))}),o=setTimeout(()=>{n(),clearInterval(s),ae(this,Te,"f").onEstablishTimeout()},ae(this,Te,"f").establishTimeout),s=setInterval(()=>ae(this,Ar,"m",mc).call(this,r()),ae(this,Te,"f").statusPollingRate)},wd=function(t,r){let n,o,s=[],i=p=>{let d=s.findIndex(l=>l.id===p);return d>-1&&s.splice(d,1),d>-1},a=()=>{let p=ae(this,Te,"f").crypto.randomUUID(),d=new Date().getTime();return s=s.filter(l=>d-ae(this,Te,"f").disconnectTimeout>l.time),s.push({id:p,time:d}),p},c=p=>{clearTimeout(o),o=setTimeout(()=>{u(),clearInterval(n),ae(this,Te,"f").onDisconnect()},p==="pending"?ae(this,Te,"f").pendingTimeout:ae(this,Te,"f").disconnectTimeout)},u=ae(this,Ar,"m",hc).call(this,p=>{"result"in p.data&&p.origin===t&&i(p.data.id)&&(c(p.data.result),ae(this,qo,"f")!==p.data.result&&(_c(this,qo,p.data.result,"f"),ae(this,Te,"f").onStatusChange(p.data.result)))});c(r),n=setInterval(()=>ae(this,Ar,"m",mc).call(this,a()),ae(this,Te,"f").statusPollingRate)},hc=function(t){let r=n=>{(n.source===ae(this,Te,"f").signerWindow&&ai(n.data)&&"result"in n.data&&n.data.result==="pending"||n.data.result==="ready")&&t(n)};return ae(this,Te,"f").window.addEventListener("message",r),()=>ae(this,Te,"f").window.removeEventListener("message",r)},mc=function(t){ae(this,Te,"f").signerWindow.postMessage({jsonrpc:"2.0",id:t,method:"icrc29_status"},"*")};var Je=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},Mo,bt,qm,Od,yc,Nd;bt=new WeakMap,Mo=new WeakSet,qm=function(){let t=Je(this,Mo,"m",yc).call(this,n=>{n.source&&(t(),clearTimeout(r),Je(this,bt,"f").onEstablish(n.origin,n.source),Je(this,Mo,"m",Od).call(this,n.origin,n.source))}),r=setTimeout(()=>{t(),Je(this,bt,"f").onEstablishTimeout()},Je(this,bt,"f").establishTimeout)},Od=function(t,r){let n,o=()=>{clearTimeout(n),n=setTimeout(()=>{s(),Je(this,bt,"f").onDisconnect()},Je(this,bt,"f").disconnectTimeout)};o();let s=Je(this,Mo,"m",yc).call(this,i=>{i.origin===t&&i.source===r&&i.data.id!==void 0&&(o(),Je(this,Mo,"m",Nd).call(this,i.data.id,i.origin,i.source))})},yc=function(t){let r=n=>{xd(n.data)&&n.data.method==="icrc29_status"&&(!Je(this,bt,"f").allowedOrigin||Je(this,bt,"f").allowedOrigin===n.origin)&&t(n)};return Je(this,bt,"f").window.addEventListener("message",r),()=>Je(this,bt,"f").window.removeEventListener("message",r)},Nd=function(t,r,n){n.postMessage({jsonrpc:"2.0",id:t,result:Je(this,bt,"f").status},r)};var Mm=function(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},or=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},ct,jm="https://github.com/slide-computer/signer-js/blob/main/packages/signer-web/README.md#channels-must-be-established-in-a-click-handler",nr=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}},gc=!1;globalThis.window&&(globalThis.window.addEventListener("click",()=>gc=!0,!0),globalThis.window.addEventListener("click",()=>gc=!1));var ui=class{constructor(t){if(ct.set(this,void 0),!bd(t.url))throw new nr("Invalid signer RPC url");Mm(this,ct,Object.assign({windowOpenerFeatures:"",window:globalThis.window,establishTimeout:12e4,pendingTimeout:3e5,disconnectTimeout:2e3,statusPollingRate:300,crypto:globalThis.crypto,manageFocus:!0,closeOnEstablishTimeout:!0,closeOnPendingTimeout:!0,detectNonClickEstablishment:!0},t),"f")}async establishChannel(){if(or(this,ct,"f").detectNonClickEstablishment&&!gc)throw new nr(`Signer window should not be opened outside of click handler, see: ${jm}`);let t=or(this,ct,"f").window.open(or(this,ct,"f").url,`${new URL(or(this,ct,"f").url).origin}-signer-window`,or(this,ct,"f").windowOpenerFeatures);if(!t)throw new nr("Signer window could not be opened");return new Promise((r,n)=>{let o;new li(Object.assign(Object.assign({},or(this,ct,"f")),{signerWindow:t,onEstablish:(s,i)=>{o=new ci(Object.assign(Object.assign({},or(this,ct,"f")),{signerOrigin:s,signerWindow:t,signerStatus:i})),r(o)},onEstablishTimeout:()=>{or(this,ct,"f").closeOnEstablishTimeout&&t.close(),n(new nr("Communication channel could not be established within a reasonable time"))},onPendingTimeout:()=>{or(this,ct,"f").closeOnPendingTimeout&&t.close(),n(new nr("Communication channel was pending for too long"))},onDisconnect:()=>o.close(),onStatusChange:s=>o.changeStatus(s)}))})}};ct=new WeakMap;var Ed=["mousedown","mousemove","keydown","touchstart","wheel"],jo=class e{callbacks=[];idleTimeout=600*1e3;timeoutID=void 0;static create(t={}){return new e(t)}constructor(t={}){let{onIdle:r,idleTimeout:n=600*1e3}=t||{};this.callbacks=r?[r]:[],this.idleTimeout=n;let o=this._resetTimer.bind(this);window.addEventListener("load",o,!0),Ed.forEach(i=>{document.addEventListener(i,o,!0)});let s=(i,a)=>{let c;return(...u)=>{let p=this,d=()=>{c=void 0,i.apply(p,u)};clearTimeout(c),c=window.setTimeout(d,a)}};if(t?.captureScroll){let i=s(o,t?.scrollDebounce??100);window.addEventListener("scroll",i,!0)}o()}registerCallback(t){this.callbacks.push(t)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let t=this._resetTimer.bind(this);Ed.forEach(r=>{document.removeEventListener(r,t,!0)}),this.callbacks.forEach(r=>{r()})}_resetTimer(){let t=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(t,this.idleTimeout)}};var Km=(e,t)=>t.some(r=>e instanceof r),Rd,vd;function Hm(){return Rd||(Rd=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function $m(){return vd||(vd=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Id=new WeakMap,bc=new WeakMap,Ad=new WeakMap,xc=new WeakMap,Tc=new WeakMap;function Gm(e){let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{r(Pt(e.result)),o()},i=()=>{n(e.error),o()};e.addEventListener("success",s),e.addEventListener("error",i)});return t.then(r=>{r instanceof IDBCursor&&Id.set(r,e)}).catch(()=>{}),Tc.set(t,e),t}function Wm(e){if(bc.has(e))return;let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{r(),o()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)});bc.set(e,t)}var wc={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return bc.get(e);if(t==="objectStoreNames")return e.objectStoreNames||Ad.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Pt(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function Sd(e){wc=e(wc)}function zm(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let n=e.call(di(this),t,...r);return Ad.set(n,t.sort?t.sort():[t]),Pt(n)}:$m().includes(e)?function(...t){return e.apply(di(this),t),Pt(Id.get(this))}:function(...t){return Pt(e.apply(di(this),t))}}function Ym(e){return typeof e=="function"?zm(e):(e instanceof IDBTransaction&&Wm(e),Km(e,Hm())?new Proxy(e,wc):e)}function Pt(e){if(e instanceof IDBRequest)return Gm(e);if(xc.has(e))return xc.get(e);let t=Ym(e);return t!==e&&(xc.set(e,t),Tc.set(t,e)),t}var di=e=>Tc.get(e);function Cd(e,t,{blocked:r,upgrade:n,blocking:o,terminated:s}={}){let i=indexedDB.open(e,t),a=Pt(i);return n&&i.addEventListener("upgradeneeded",c=>{n(Pt(i.result),c.oldVersion,c.newVersion,Pt(i.transaction),c)}),r&&i.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),o&&c.addEventListener("versionchange",u=>o(u.oldVersion,u.newVersion,u))}).catch(()=>{}),a}var Jm=["get","getKey","getAll","getAllKeys","count"],Zm=["put","add","delete","clear"],Oc=new Map;function Pd(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Oc.get(t))return Oc.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,o=Zm.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||Jm.includes(r)))return;let s=async function(i,...a){let c=this.transaction(i,o?"readwrite":"readonly"),u=c.store;return n&&(u=u.index(a.shift())),(await Promise.all([u[r](...a),o&&c.done]))[0]};return Oc.set(t,s),s}Sd(e=>({...e,get:(t,r,n)=>Pd(t,r)||e.get(t,r,n),has:(t,r)=>!!Pd(t,r)||e.has(t,r)}));var Fd="auth-client-db",Bd="ic-keyval",Xm=async(e=Fd,t=Bd,r)=>(globalThis.localStorage?.getItem(Ze)&&(globalThis.localStorage.removeItem(Ze),globalThis.localStorage.removeItem(Xe)),await Cd(e,r,{upgrade:n=>{n.objectStoreNames.contains(t)&&n.clear(t),n.createObjectStore(t)}}));async function Qm(e,t,r){return await e.get(t,r)}async function e_(e,t,r,n){return await e.put(t,n,r)}async function t_(e,t,r){return await e.delete(t,r)}var pi=class e{constructor(t,r){this._db=t,this._storeName=r}static async create(t){let{dbName:r=Fd,storeName:n=Bd,version:o=Vd}=t??{},s=await Xm(r,n,o);return new e(s,n)}async set(t,r){return await e_(this._db,this._storeName,t,r)}async get(t){return await Qm(this._db,this._storeName,t)??null}async remove(t){return await t_(this._db,this._storeName,t)}};var Xe="identity",Ze="delegation",Dd="iv",Vd=1,Ko=class{constructor(t="ic-",r){this.prefix=t,this._localStorage=r}get(t){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+t))}set(t,r){return this._getLocalStorage().setItem(this.prefix+t,r),Promise.resolve()}remove(t){return this._getLocalStorage().removeItem(this.prefix+t),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let t=globalThis.localStorage;if(!t)throw new Error("Could not find local storage.");return t}},sr=class{#e;constructor(t){this.#e=t??{}}initializedDb;get _db(){return new Promise((t,r)=>{if(this.initializedDb){t(this.initializedDb);return}pi.create(this.#e).then(n=>{this.initializedDb=n,t(n)}).catch(r)})}async get(t){return await(await this._db).get(t)}async set(t,r){await(await this._db).set(t,r)}async remove(t){await(await this._db).remove(t)}};var r_=BigInt(1e9),n_=BigInt(3600),o_=r_*n_,s_="https://identity.internetcomputer.org",i_="#authorize",a_="https://id.ai/authorize",Ud=BigInt(8)*o_,Nc="ECDSA",Ec="Ed25519",c_=500,fi="UserInterrupt",Ho=class e{constructor(t,r,n,o,s,i,a,c){this._identity=t,this._key=r,this._chain=n,this._storage=o,this.idleManager=s,this._createOptions=i,this._idpWindow=a,this._eventHandler=c,this._registerDefaultIdleCallback()}_signer=void 0;static async create(t={}){let r=t.storage??new sr,n=t.keyType??Nc,o=null;if(t.identity)o=t.identity;else{let c=await r.get(Xe);if(!c)try{let u=new Ko,p=await u.get(Ze),d=await u.get(Xe);p&&d&&n===Nc&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await r.set(Ze,p),await r.set(Xe,d),c=p,await u.remove(Ze),await u.remove(Xe))}catch(u){console.error(`error while attempting to recover localstorage: ${u}`)}if(c)try{typeof c=="object"?n===Ec&&typeof c=="string"?o=sn.fromJSON(c):o=await Rr.fromKeyPair(c):typeof c=="string"&&(o=sn.fromJSON(c))}catch{}}let s=new rt,i=null;if(o)try{let c=await r.get(Ze);if(typeof c=="object"&&c!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");t.identity?s=t.identity:c&&(i=er.fromJSON(c),pc(i)?"toDer"in o?s=Ln.fromDelegation(o,i):s=Ir.fromDelegation(o,i):(await Rc(r),o=null))}catch(c){console.error(c),await Rc(r),o=null}let a;return t.idleOptions?.disableIdle?a=void 0:(i||t.identity)&&(a=jo.create(t.idleOptions)),o||(n===Ec?o=sn.generate():(t.storage&&n===Nc&&console.warn(`You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${Ec}' as the key type, as it can serialize to a string`),o=await Rr.generate()),await Ld(r,o)),new e(s,o,i,r,a,t)}_registerDefaultIdleCallback(){let t=this._createOptions?.idleOptions;!t?.onIdle&&!t?.disableDefaultIdleCallback&&this.idleManager?.registerCallback(()=>{this.logout(),location.reload()})}async _handleSuccess(t,r){let n=t.delegations.map(a=>({delegation:new vr(a.delegation.pubkey,a.delegation.expiration,a.delegation.targets),signature:a.signature})),o=er.fromDelegations(n,t.userPublicKey),s=this._key;if(!s)return;this._chain=o,"toDer"in s?this._identity=Ln.fromDelegation(s,this._chain):this._identity=Ir.fromDelegation(s,this._chain),this._idpWindow?.close();let i=this._createOptions?.idleOptions;!this.idleManager&&!i?.disableIdle&&(this.idleManager=jo.create(i),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(Ze,JSON.stringify(this._chain.toJSON())),await Ld(this._storage,this._key),r?.(t)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null&&pc(this._chain)}async login(t){let r=kd(this._createOptions?.loginOptions,t),n=r?.maxTimeToLive??Ud,o=new URL(r?.identityProvider?.toString()||s_);o.hash=i_,this._idpWindow?.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(o,{maxTimeToLive:n,...r}),window.addEventListener("message",this._eventHandler),this._idpWindow=window.open(o.toString(),"idpWindow",r?.windowOpenerFeatures)??void 0;let s=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(fi,r?.onError):setTimeout(s,c_))};s()}async loginWithIcrc29(t){let r=kd(this._createOptions?.loginOptions,t),n=r?.maxTimeToLive??Ud,o=new URL(r?.identityProvider?.toString()||a_);this._signer?.closeChannel();let s=new ui({url:o.toString(),windowOpenerFeatures:r?.windowOpenerFeatures});this._signer=new ii({transport:s,derivationOrigin:r?.derivationOrigin?.toString()});let i=this._key;if(!i)return;let a=await this._signer.delegation({publicKey:this._key.getPublicKey().toDer(),maxTimeToLive:n});this._chain=a,"toDer"in i?this._identity=Ln.fromDelegation(i,this._chain):this._identity=Ir.fromDelegation(i,this._chain),this._chain&&await this._storage.set(Ze,JSON.stringify(this._chain.toJSON())),t?.onSuccess?.({kind:"authorize-client-success",delegations:a.delegations,userPublicKey:this._key?.getPublicKey().toDer(),authnMethod:"passkey"})}_getEventHandler(t,r){return async n=>{if(n.origin!==t.origin)return;let o=n.data;switch(o.kind){case"authorize-ready":{let s={kind:"authorize-client",sessionPublicKey:new Uint8Array(this._key?.getPublicKey().toDer()),maxTimeToLive:r?.maxTimeToLive,allowPinAuthentication:r?.allowPinAuthentication,derivationOrigin:r?.derivationOrigin?.toString(),...r?.customValues};this._idpWindow?.postMessage(s,t.origin);break}case"authorize-client-success":try{await this._handleSuccess(o,r?.onSuccess)}catch(s){this._handleFailure(s.message,r?.onError)}break;case"authorize-client-failure":this._handleFailure(o.text,r?.onError);break}}}_handleFailure(t,r){this._idpWindow?.close(),r?.(t),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(t={}){if(await Rc(this._storage),this._identity=new rt,this._chain=null,t.returnTo)try{window.history.pushState({},"",t.returnTo)}catch{window.location.href=t.returnTo}}};async function Rc(e){await e.remove(Xe),await e.remove(Ze),await e.remove(Dd)}function kd(e,t){if(!e&&!t)return;let r=e?.customValues||t?.customValues?{...e?.customValues,...t?.customValues}:void 0;return{...e,...t,customValues:r}}function l_(e){if(e instanceof Rr)return e.getKeyPair();if(e instanceof sn)return JSON.stringify(e.toJSON());throw new Error("Unsupported key type")}async function Ld(e,t){let r=l_(t);await e.set(Xe,r)}var Ct=async({fn:e,step:t,onProgress:r})=>{r?.({step:t,state:"in_progress"});try{let n=await e();return r?.({step:t,state:"success"}),n}catch(n){throw r?.({step:t,state:"error"}),n}};var qd=(r=>(r[r.AuthorizingWithProvider=0]="AuthorizingWithProvider",r[r.CreatingOrRetrievingUser=1]="CreatingOrRetrievingUser",r))(qd||{});var hi=class extends Error{},ln=class extends Error{},mi=class extends Error{},_i=class extends Error{},yi=class extends Error{},gi=class extends Error{},xi=class extends Error{},bi=class extends Error{};var Hn=class{async signIn({options:t,authClient:r,initAuth:n}){await Ct({fn:async()=>await this.#e({options:t,authClient:r}),step:0,onProgress:t?.onProgress}),await Ct({fn:async()=>await n({provider:this.id}),step:1,onProgress:t?.onProgress})}#e({options:t,authClient:r}){return new Promise(async(n,o)=>{if(H(r)){o(new ln("No client is ready to perform a sign-in. Have you initialized the Satellite?"));return}await r.login({onSuccess:n,onError:s=>{if(s===fi){o(new mi(s));return}o(new hi(s))},maxTimeToLive:t?.maxTimeToLiveInNanoseconds??ad,allowPinAuthentication:t?.allowPin??cd,...t?.derivationOrigin!==void 0&&{derivationOrigin:t.derivationOrigin},...this.signInOptions({windowed:t?.windowed})})})}};var wi=class extends Hn{#e;constructor({domain:t}){super(),this.#e=t}get id(){return"internet_identity"}signInOptions({windowed:t}){let n=(()=>{let s=et.getInstance().get()?.container;if(H(s)||s===!1){let p=[Do,pd].includes(this.#e??Do);return Gu(this.#e)?`https://identity.${Do}`:p?`https://identity.${this.#e??Do}`:`https://${this.#e}`}let i=et.getInstance().get(),a=X(i)&&X(i?.internetIdentityId)?i.internetIdentityId:od,{host:c,protocol:u}=new URL(s===!0?Dn:s);return/apple/i.test(navigator?.vendor)?`${u}//${c}?canisterId=${a}`:`${u}//${a}.${c.replace("127.0.0.1","localhost")}`})();return{...t!==!1&&{windowOpenerFeatures:ti((()=>{try{let{hostname:s}=new URL(n);return s.includes(fd)}catch{return!1}})()?ud:ld)},identityProvider:n}}};var Ti=class extends Hn{#e;#t;constructor({appName:t,logoUrl:r}){super(),this.#e=t,this.#t=r}get id(){return"nfid"}signInOptions({windowed:t}){return{...t!==!1&&{windowOpenerFeatures:ti(dd)},identityProvider:`https://nfid.one/authenticate/?applicationName=${encodeURI(this.#e)}&applicationLogo=${encodeURI(this.#t)}`}}};var Ft={certified:!1};var ue=e=>X(e)?e:Oi()??new rt;var Md=({IDL:e})=>{let t=e.Variant({Heap:e.Null,Stable:e.Null}),r=e.Record({system_memory:e.Opt(t)}),n=e.Record({controllers:e.Vec(e.Principal),storage:e.Opt(r)}),o=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),s=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),i=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),a=e.Record({field:i,desc:e.Bool}),c=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),u=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(c),description:e.Opt(e.Text),created_at:e.Opt(c)}),p=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),d=e.Record({order:e.Opt(a),owner:e.Opt(e.Principal),matcher:e.Opt(u),paginate:e.Opt(p)}),l=e.Record({controllers:e.Vec(e.Principal)}),f=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),h=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:f,expires_at:e.Opt(e.Nat64)}),m=e.Record({version:e.Opt(e.Nat64)}),y=e.Variant({Db:e.Null,Storage:e.Null}),_=e.Record({version:e.Opt(e.Nat64)}),x=e.Record({proposal_ids:e.Vec(e.Nat)}),g=e.Record({cycles:e.Nat,destination_id:e.Principal}),T=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),N=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),E=e.Record({key:T,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,N)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),R=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),I=e.Record({allowed_callers:e.Vec(e.Principal)}),w=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(R),rules:e.Opt(I)}),v=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),C=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(v)}),A=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),b=e.Variant({Deny:e.Null,Allow:e.Null}),O=e.Record({status_code:e.Nat16,location:e.Text}),P=e.Record({iframe:e.Opt(A),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(v),raw_access:e.Opt(b),redirects:e.Opt(e.Vec(e.Tuple(e.Text,O)))}),V=e.Record({db:e.Opt(C),authentication:e.Opt(w),storage:P}),L=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64,version:e.Opt(e.Nat64)}),S=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),F=e.Record({clear_existing_assets:e.Opt(e.Bool)}),B=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),q=e.Variant({AssetsUpgrade:F,SegmentsDeployment:B}),D=e.Record({status:S,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:q}),ee=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),te=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),W=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:ee,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(te),write:ee,max_changes_per_user:e.Opt(e.Nat32)}),De=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),_e=e.Record({memory:t,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),wt=e.Variant({Callback:e.Record({token:_e,callback:e.Func([],[],["query"])})}),ye=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(wt),status_code:e.Nat16}),$e=e.Record({token:e.Opt(_e),body:e.Vec(e.Nat8)}),Pr=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),Cr=e.Record({batch_id:e.Nat}),Ei=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,E)),items_length:e.Nat64}),Ri=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),vi=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,L)),items_length:e.Nat64}),Ii=e.Record({desc:e.Bool}),Ai=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),Si=e.Record({order:e.Opt(Ii),paginate:e.Opt(Ai)}),Pi=e.Record({proposal_id:e.Nat}),Ci=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(Pi,D)),items_length:e.Nat64}),Fi=e.Record({include_system:e.Bool}),Bi=e.Record({matcher:e.Opt(Fi)}),Vi=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,W)),items_length:e.Nat64}),Di=e.Record({stable:e.Nat64,heap:e.Nat64}),Ui=e.Record({version:e.Opt(e.Nat64),internet_identity:e.Opt(R),rules:e.Opt(I)}),ki=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:f,expires_at:e.Opt(e.Nat64)}),Li=e.Record({controller:ki,controllers:e.Vec(e.Principal)}),qi=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(v)}),$n=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Mi=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),max_size:e.Opt(e.Nat),read:ee,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(te),write:ee,max_changes_per_user:e.Opt(e.Nat32)}),ji=e.Record({iframe:e.Opt(A),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(v),raw_access:e.Opt(b),redirects:e.Opt(e.Vec(e.Tuple(e.Text,O)))}),Gn=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Wn=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([o],[],[]),commit_proposal:e.Func([s],[e.Null],[]),commit_proposal_asset_upload:e.Func([o],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(o)],[],[]),count_assets:e.Func([e.Text,d],[e.Nat64],["query"]),count_collection_assets:e.Func([e.Text],[e.Nat64],["query"]),count_collection_docs:e.Func([e.Text],[e.Nat64],["query"]),count_docs:e.Func([e.Text,d],[e.Nat64],["query"]),count_proposals:e.Func([],[e.Nat64],["query"]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controllers:e.Func([l],[e.Vec(e.Tuple(e.Principal,h))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,m],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,d],[],[]),del_filtered_docs:e.Func([e.Text,d],[],[]),del_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[],[]),del_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,m))],[],[]),del_rule:e.Func([y,e.Text,_],[],[]),delete_proposal_assets:e.Func([x],[],[]),deposit_cycles:e.Func([g],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(E)],["query"]),get_auth_config:e.Func([],[e.Opt(w)],["query"]),get_config:e.Func([],[V],[]),get_db_config:e.Func([],[e.Opt(C)],["query"]),get_doc:e.Func([e.Text,e.Text],[e.Opt(L)],["query"]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(E)))],["query"]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(L)))],["query"]),get_proposal:e.Func([e.Nat],[e.Opt(D)],["query"]),get_rule:e.Func([y,e.Text],[e.Opt(W)],["query"]),get_storage_config:e.Func([],[P],["query"]),http_request:e.Func([De],[ye],["query"]),http_request_streaming_callback:e.Func([_e],[$e],["query"]),init_asset_upload:e.Func([Pr],[Cr],[]),init_proposal:e.Func([q],[e.Nat,D],[]),init_proposal_asset_upload:e.Func([Pr,e.Nat],[Cr],[]),init_proposal_many_assets_upload:e.Func([e.Vec(Pr),e.Nat],[e.Vec(e.Tuple(e.Text,Cr))],[]),list_assets:e.Func([e.Text,d],[Ei],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,h))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,Ri))],["query"]),list_docs:e.Func([e.Text,d],[vi],["query"]),list_proposals:e.Func([Si],[Ci],["query"]),list_rules:e.Func([y,Bi],[Vi],["query"]),memory_size:e.Func([],[Di],["query"]),reject_proposal:e.Func([s],[e.Null],[]),set_auth_config:e.Func([Ui],[w],[]),set_controllers:e.Func([Li],[e.Vec(e.Tuple(e.Principal,h))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([qi],[C],[]),set_doc:e.Func([e.Text,e.Text,$n],[L],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,$n))],[e.Vec(e.Tuple(e.Text,L))],[]),set_rule:e.Func([y,e.Text,Mi],[W],[]),set_storage_config:e.Func([ji],[P],[]),submit_proposal:e.Func([e.Nat],[e.Nat,D],[]),switch_storage_system_memory:e.Func([],[],[]),upload_asset_chunk:e.Func([Gn],[Wn],[]),upload_proposal_asset_chunk:e.Func([Gn],[Wn],[])})},jd=({IDL:e})=>{let t=e.Variant({Heap:e.Null,Stable:e.Null}),r=e.Record({system_memory:e.Opt(t)}),n=e.Record({controllers:e.Vec(e.Principal),storage:e.Opt(r)}),o=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),s=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),i=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),a=e.Record({field:i,desc:e.Bool}),c=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),u=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(c),description:e.Opt(e.Text),created_at:e.Opt(c)}),p=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),d=e.Record({order:e.Opt(a),owner:e.Opt(e.Principal),matcher:e.Opt(u),paginate:e.Opt(p)}),l=e.Record({controllers:e.Vec(e.Principal)}),f=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),h=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:f,expires_at:e.Opt(e.Nat64)}),m=e.Record({version:e.Opt(e.Nat64)}),y=e.Variant({Db:e.Null,Storage:e.Null}),_=e.Record({version:e.Opt(e.Nat64)}),x=e.Record({proposal_ids:e.Vec(e.Nat)}),g=e.Record({cycles:e.Nat,destination_id:e.Principal}),T=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),N=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),E=e.Record({key:T,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,N)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),R=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),I=e.Record({allowed_callers:e.Vec(e.Principal)}),w=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(R),rules:e.Opt(I)}),v=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),C=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(v)}),A=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),b=e.Variant({Deny:e.Null,Allow:e.Null}),O=e.Record({status_code:e.Nat16,location:e.Text}),P=e.Record({iframe:e.Opt(A),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(v),raw_access:e.Opt(b),redirects:e.Opt(e.Vec(e.Tuple(e.Text,O)))}),V=e.Record({db:e.Opt(C),authentication:e.Opt(w),storage:P}),L=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64,version:e.Opt(e.Nat64)}),S=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),F=e.Record({clear_existing_assets:e.Opt(e.Bool)}),B=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),q=e.Variant({AssetsUpgrade:F,SegmentsDeployment:B}),D=e.Record({status:S,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:q}),ee=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),te=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),W=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:ee,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(te),write:ee,max_changes_per_user:e.Opt(e.Nat32)}),De=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),_e=e.Record({memory:t,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),wt=e.Variant({Callback:e.Record({token:_e,callback:e.Func([],[],[])})}),ye=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(wt),status_code:e.Nat16}),$e=e.Record({token:e.Opt(_e),body:e.Vec(e.Nat8)}),Pr=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),Cr=e.Record({batch_id:e.Nat}),Ei=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,E)),items_length:e.Nat64}),Ri=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),vi=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,L)),items_length:e.Nat64}),Ii=e.Record({desc:e.Bool}),Ai=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),Si=e.Record({order:e.Opt(Ii),paginate:e.Opt(Ai)}),Pi=e.Record({proposal_id:e.Nat}),Ci=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(Pi,D)),items_length:e.Nat64}),Fi=e.Record({include_system:e.Bool}),Bi=e.Record({matcher:e.Opt(Fi)}),Vi=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,W)),items_length:e.Nat64}),Di=e.Record({stable:e.Nat64,heap:e.Nat64}),Ui=e.Record({version:e.Opt(e.Nat64),internet_identity:e.Opt(R),rules:e.Opt(I)}),ki=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:f,expires_at:e.Opt(e.Nat64)}),Li=e.Record({controller:ki,controllers:e.Vec(e.Principal)}),qi=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(v)}),$n=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Mi=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),max_size:e.Opt(e.Nat),read:ee,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(te),write:ee,max_changes_per_user:e.Opt(e.Nat32)}),ji=e.Record({iframe:e.Opt(A),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(v),raw_access:e.Opt(b),redirects:e.Opt(e.Vec(e.Tuple(e.Text,O)))}),Gn=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Wn=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([o],[],[]),commit_proposal:e.Func([s],[e.Null],[]),commit_proposal_asset_upload:e.Func([o],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(o)],[],[]),count_assets:e.Func([e.Text,d],[e.Nat64],[]),count_collection_assets:e.Func([e.Text],[e.Nat64],[]),count_collection_docs:e.Func([e.Text],[e.Nat64],[]),count_docs:e.Func([e.Text,d],[e.Nat64],[]),count_proposals:e.Func([],[e.Nat64],[]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controllers:e.Func([l],[e.Vec(e.Tuple(e.Principal,h))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,m],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,d],[],[]),del_filtered_docs:e.Func([e.Text,d],[],[]),del_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[],[]),del_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,m))],[],[]),del_rule:e.Func([y,e.Text,_],[],[]),delete_proposal_assets:e.Func([x],[],[]),deposit_cycles:e.Func([g],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(E)],[]),get_auth_config:e.Func([],[e.Opt(w)],[]),get_config:e.Func([],[V],[]),get_db_config:e.Func([],[e.Opt(C)],[]),get_doc:e.Func([e.Text,e.Text],[e.Opt(L)],[]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(E)))],[]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(L)))],[]),get_proposal:e.Func([e.Nat],[e.Opt(D)],[]),get_rule:e.Func([y,e.Text],[e.Opt(W)],[]),get_storage_config:e.Func([],[P],[]),http_request:e.Func([De],[ye],[]),http_request_streaming_callback:e.Func([_e],[$e],[]),init_asset_upload:e.Func([Pr],[Cr],[]),init_proposal:e.Func([q],[e.Nat,D],[]),init_proposal_asset_upload:e.Func([Pr,e.Nat],[Cr],[]),init_proposal_many_assets_upload:e.Func([e.Vec(Pr),e.Nat],[e.Vec(e.Tuple(e.Text,Cr))],[]),list_assets:e.Func([e.Text,d],[Ei],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,h))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,Ri))],[]),list_docs:e.Func([e.Text,d],[vi],[]),list_proposals:e.Func([Si],[Ci],[]),list_rules:e.Func([y,Bi],[Vi],[]),memory_size:e.Func([],[Di],[]),reject_proposal:e.Func([s],[e.Null],[]),set_auth_config:e.Func([Ui],[w],[]),set_controllers:e.Func([Li],[e.Vec(e.Tuple(e.Principal,h))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([qi],[C],[]),set_doc:e.Func([e.Text,e.Text,$n],[L],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,$n))],[e.Vec(e.Tuple(e.Text,L))],[]),set_rule:e.Func([y,e.Text,Mi],[W],[]),set_storage_config:e.Func([ji],[P],[]),submit_proposal:e.Func([e.Nat],[e.Nat,D],[]),switch_storage_system_memory:e.Func([],[],[]),upload_asset_chunk:e.Func([Gn],[Wn],[]),upload_proposal_asset_chunk:e.Func([Gn],[Wn],[])})};var Kd=({satelliteId:e,container:t})=>{let{satelliteId:r}=vc({satelliteId:e}),{container:n}=Ic({container:t});if(X(n)&&n!==!1){let{host:o,protocol:s}=new URL(n===!0?Dn:n);return`${s}//${r??"unknown"}.${o.replace("127.0.0.1","localhost")}`}return`https://${r??"unknown"}.icp0.io`},vc=({satelliteId:e})=>X(e)?{satelliteId:e}:et.getInstance().get()??{satelliteId:void 0},Ic=({container:e})=>X(e)?{container:e}:et.getInstance().get()??{container:void 0};var Oe=({satellite:e,options:{certified:t}})=>$d({idlFactory:t?jd:Md,actorKey:`stock#${t?"update":"query"}`,...e}),Hd=({idlFactory:e,...t})=>$d({idlFactory:e,actorKey:"extended#query",...t}),$d=async({satelliteId:e,container:t,...r})=>{let{satelliteId:n}=vc({satelliteId:e});Bo(n,"No satellite ID defined. Did you initialize Juno?");let{container:o}=Ic({container:t});return await kn.getInstance().getActor({satelliteId:n,container:o,...r})};var Gd=e=>{if(H(e))return le();switch(e.matcher){case"equal":return le({Equal:e.timestamp});case"greaterThan":return le({GreaterThan:e.timestamp});case"lessThan":return le({LessThan:e.timestamp});case"between":return le({Between:[e.timestamps.start,e.timestamps.end]});default:throw new bi("Invalid list matcher for timestamp",e)}},Sr=({matcher:e,paginate:t,order:r,owner:n})=>({matcher:H(e)?[]:[{key:le(e.key),description:le(e.description),created_at:Gd(e.createdAt),updated_at:Gd(e.updatedAt)}],paginate:le(H(t)?void 0:{start_after:le(t.startAfter),limit:le(H(t.limit)?void 0:BigInt(t.limit))}),order:le(H(r)?void 0:{desc:r.desc,field:r.field==="created_at"?{CreatedAt:null}:r.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:le(H(n)?void 0:typeof n=="string"?k.fromText(n):n)});var Wd=async({data:e})=>{try{return await Qs(e)}catch(t){console.error("The data parsing has failed, mapping to undefined as a fallback.",t);return}};var Ac=async e=>{let{data:t,version:r,description:n}=e;return{description:le(n),data:await hd(t),version:le(r)}},Sc=e=>{let{version:t}=e;return{version:le(t)}},$o=async({doc:e,key:t})=>{let{owner:r,version:n,description:o,data:s,...i}=e;return{key:t,description:Ie(o),owner:r.toText(),data:await Qs(s),version:Ie(n),...i}};var zd=async({collection:e,key:t,...r})=>{let{get_doc:n}=await Oe(r),o=Ie(await n(e,t));if(!H(o))return $o({doc:o,key:t})},Yd=async({docs:e,...t})=>{let{get_many_docs:r}=await Oe(t),n=e.map(({collection:i,key:a})=>[i,a]),o=await r(n),s=[];for(let[i,a]of o){let c=Ie(a);s.push(X(c)?await $o({key:i,doc:c}):void 0)}return s},Jd=async({collection:e,doc:t,...r})=>{let{set_doc:n}=await Oe(r),{key:o}=t,s=await Ac(t),i=await n(e,o,s);return await $o({key:o,doc:i})},Zd=async({docs:e,...t})=>{let{set_many_docs:r}=await Oe(t),n=[];for(let{collection:i,doc:a}of e){let{key:c}=a;n.push([i,c,await Ac(a)])}let o=await r(n),s=[];for(let[i,a]of o)s.push(await $o({key:i,doc:a}));return s},Xd=async({collection:e,doc:t,...r})=>{let{del_doc:n}=await Oe(r),{key:o}=t;return n(e,o,Sc(t))},Qd=async({docs:e,...t})=>{let{del_many_docs:r}=await Oe(t),n=e.map(({collection:o,doc:s})=>[o,s.key,Sc(s)]);await r(n)},ep=async({collection:e,filter:t,...r})=>{let{del_filtered_docs:n}=await Oe(r);return n(e,Sr(t))},tp=async({collection:e,filter:t,...r})=>{let{list_docs:n}=await Oe(r),{items:o,items_page:s,items_length:i,matches_length:a,matches_pages:c}=await n(e,Sr(t)),u=[];for(let[p,d]of o){let{data:l,owner:f,description:h,version:m,...y}=d;u.push({key:p,description:Ie(h),owner:f.toText(),data:await Wd({data:l}),version:Ie(m),...y})}return{items:u,items_length:i,items_page:Ie(s),matches_length:a,matches_pages:Ie(c)}},rp=async({collection:e,filter:t,...r})=>{let{count_docs:n}=await Oe(r);return n(e,Sr(t))};var Ni=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await zd({...r,satellite:{...e,identity:n},options:t??Ft})},YT=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await Yd({...r,satellite:{...e,identity:n},options:t??Ft})},np=async({satellite:e,...t})=>{let r=ue(e?.identity);return await Jd({...t,satellite:{...e,identity:r},options:{certified:!0}})},op=async({satellite:e,...t})=>{let r=ue(e?.identity);return await Zd({...t,satellite:{...e,identity:r},options:{certified:!0}})},JT=async({satellite:e,...t})=>{let r=ue(e?.identity);return await Xd({...t,satellite:{...e,identity:r},options:{certified:!0}})},ZT=async({satellite:e,...t})=>{let r=ue(e?.identity);return await Qd({...t,satellite:{...e,identity:r},options:{certified:!0}})},XT=async({satellite:e,filter:t,...r})=>{let n=ue(e?.identity);return await ep({...r,filter:t??{},satellite:{...e,identity:n},options:{certified:!0}})},QT=async({satellite:e,options:t,filter:r,...n})=>{let o=ue(e?.identity);return await tp({...n,filter:r??{},satellite:{...e,identity:o},options:t??Ft})},eO=async({satellite:e,options:t,filter:r,...n})=>{let o=ue(e?.identity);return await rp({...n,filter:r??{},satellite:{...e,identity:o},options:t??Ft})};var sp=async({delegationIdentity:e,passkeyIdentity:t,satelliteId:r})=>{let n=t.getCredential().getAAGUID(),[o,s]=await op({docs:[{collection:"#user",doc:{key:e.getPrincipal().toText(),data:{provider:"webauthn",providerData:{webauthn:{...X(n)&&{aaguid:Zs(n)}}}}}},{collection:"#user-webauthn",doc:{key:t.getCredential().getCredentialIdText(),data:{publicKey:t.getPublicKey().toRaw()}}}],satellite:{identity:e,satelliteId:r}});return o};var ip=(s=>(s[s.RequestingUserCredential=0]="RequestingUserCredential",s[s.FinalizingCredential=1]="FinalizingCredential",s[s.Signing=2]="Signing",s[s.FinalizingSession=3]="FinalizingSession",s[s.RetrievingUser=4]="RetrievingUser",s))(ip||{}),ap=(i=>(i[i.CreatingUserCredential=0]="CreatingUserCredential",i[i.ValidatingUserCredential=1]="ValidatingUserCredential",i[i.FinalizingCredential=2]="FinalizingCredential",i[i.Signing=3]="Signing",i[i.FinalizingSession=4]="FinalizingSession",i[i.RegisteringUser=5]="RegisteringUser",i))(ap||{});var Go=class{get id(){return"webauthn"}async signUp({options:{onProgress:t,maxTimeToLiveInMilliseconds:r,passkey:n}={},loadAuthWithUser:o}){let{satelliteId:s}=et.getInstance().get()??{satelliteId:void 0};if(H(s))throw new ln("Satellite ID not set. Have you initialized the Satellite?");let i=({step:m,state:y})=>{switch(m){case Er.RequestingUserCredential:t?.({step:1,state:y});break;case Er.FinalizingCredential:t?.({step:2,state:y});break;case Er.Signing:t?.({step:3,state:y});break}},c=await Ct({fn:async()=>await ac.createWithNewCredential({onProgress:i,passkeyOptions:n}),step:0,onProgress:t}),{delegationIdentity:u,sessionKey:p}=await this.#e({identity:c,maxTimeToLiveInMilliseconds:r}),l=await Ct({fn:async()=>await sp({delegationIdentity:u,passkeyIdentity:c,satelliteId:s}),step:5,onProgress:t});await Ct({fn:async()=>await this.#t({delegationIdentity:u,sessionKey:p}),step:4,onProgress:t}),await Ct({fn:async()=>await o({user:l}),step:5,onProgress:t})}async signIn({options:{onProgress:t,maxTimeToLiveInMilliseconds:r}={},loadAuth:n}){let{satelliteId:o}=et.getInstance().get()??{satelliteId:void 0};if(H(o))throw new ln("Satellite ID not set. Have you initialized the Satellite?");let s=async({credentialId:d})=>{let l=await Ni({collection:"#user-webauthn",key:Xs(d),options:{certified:!0},satellite:{identity:new rt,satelliteId:o}});if(H(l))throw new yi("No public key found for the selected passkey.");let{data:f}=l,{publicKey:h}=f;return rn(h,Co)},i=({step:d,state:l})=>{switch(d){case Er.RequestingUserCredential:t?.({step:0,state:l});break;case Er.FinalizingCredential:t?.({step:1,state:l});break;case Er.Signing:t?.({step:2,state:l});break}},a=await ac.createWithExistingCredential({retrievePublicKey:s,onProgress:i}),{delegationIdentity:c,sessionKey:u}=await this.#e({identity:a,maxTimeToLiveInMilliseconds:r});await Ct({fn:async()=>await this.#t({delegationIdentity:c,sessionKey:u}),step:3,onProgress:t}),await Ct({fn:n,step:4,onProgress:t})}async#e({identity:t,maxTimeToLiveInMilliseconds:r}){let n=await Rr.generate({extractable:!1}),o=r??144e5,s=await er.create(t,n.getPublicKey(),new Date(Date.now()+o));return{delegationIdentity:Ir.fromDelegation(n,s),sessionKey:n}}async#t({sessionKey:t,delegationIdentity:r}){let n=new sr;await Promise.all([n.set(Xe,t.getKeyPair()),n.set(Ze,JSON.stringify(r.getDelegation().toJSON()))])}};var Wo=()=>Ho.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}}),cp=async()=>(await new sr().remove(Xe),await Wo());var Pc=({error:e,type:t})=>typeof e=="string"?e.includes(t):e instanceof Error?e.message.includes(t):!1;var lp="juno.datastore.error.user.cannot_update";var up=async({provider:e})=>{let{user:t,userId:r}=await Cc();if(X(t))return t;try{return await d_({userId:r,provider:e})}catch(n){if(Pc({error:n,type:lp})){let o=await dp({userId:r});if(X(o))return o}throw n}},Cc=async()=>{let e=Oi();if(H(e))throw new xi("No identity to initialize the user. Have you initialized Juno?");let t=e.getPrincipal().toText(),r=await dp({userId:t});return{userId:t,user:r}},dp=({userId:e})=>Ni({collection:"#user",key:e}),d_=({userId:e,...t})=>np({collection:"#user",doc:{key:e,data:t}});var lt,Fc=async()=>{await Bc({fn:async()=>{let{user:t}=await Cc();at.getInstance().set(t??null)}})},p_=async({user:e})=>{await Bc({fn:async()=>{at.getInstance().set(e)}})},pp=async({provider:e})=>{await Bc({fn:async()=>{let r=await up({provider:e});at.getInstance().set(r)}})},Bc=async({fn:e})=>{if(lt=await Wo(),!await lt.isAuthenticated()){lt=await cp();return}await e()},f_=async e=>{let t=async()=>await m_(e);if(Object.values(e)[0].context?.windowGuard===!1){await t();return}await lc({fn:t})},h_=async e=>{let t=async()=>await __(e);if(Object.values(e)?.[0].context?.windowGuard===!1){await t();return}await lc({fn:t})},m_=async e=>{if("webauthn"in e){let{webauthn:{options:t}}=e;await new Go().signIn({options:t,loadAuth:Fc});return}if("nfid"in e){let{nfid:{options:t}}=e,{appName:r,logoUrl:n,...o}=t??{};await new Ti({appName:r,logoUrl:n}).signIn({options:o,authClient:lt,initAuth:pp});return}if("internet_identity"in e){let{internet_identity:{options:t}}=e,{domain:r,...n}=t??{};await new wi({domain:r}).signIn({options:n,authClient:lt,initAuth:pp});return}throw new _i("An unknown or unsupported provider was provided for sign-in.")},__=async e=>{if("webauthn"in e){let{webauthn:{options:t}}=e;await new Go().signUp({options:t,loadAuthWithUser:p_});return}throw new gi("An unknown or unsupported provider was provided for sign-up.")},Vc=async e=>{await y_(),lt=await Wo(),e?.windowReload!==!1&&window.location.reload()},y_=async()=>{await lt?.logout(),lt=null,at.getInstance().reset(),kn.getInstance().reset(),Un.getInstance().reset()},Oi=()=>lt?.getIdentity(),g_=async()=>(lt??await Wo()).getIdentity(),x_=async()=>{let e=at.getInstance().get();return H(e)||!(await lt?.isAuthenticated()??!1)?null:lt?.getIdentity()??null};var fp=e=>{let t=e===!0?"./workers/auth.worker.js":e,r=new Worker(t),n=async()=>{cc({message:"junoSignOutAuthTimer"}),await Vc()};return r.onmessage=async({data:o})=>{let{msg:s,data:i}=o;switch(s){case"junoSignOutAuthTimer":await n();return;case"junoDelegationRemainingTime":cc({message:"junoDelegationRemainingTime",detail:i?.authRemainingTime});return}},at.getInstance().subscribe(o=>{if(H(o)){r.postMessage({msg:"junoStopAuthTimer"});return}r.postMessage({msg:"junoStartAuthTimer"})})};var hp=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_SATELLITE_ID??import.meta.env?.PUBLIC_SATELLITE_ID:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SATELLITE_ID??e():e()},mp=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_CONTAINER??import.meta.env?.PUBLIC_CONTAINER:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_CONTAINER??e():e()};var JO=async({idlFactory:e,satellite:t})=>{let r=ue(t?.identity);return await Hd({idlFactory:e,...t,identity:r})};var _p=async({asset:{data:e,headers:t,...r},actor:n,progress:o})=>{let{init_asset_upload:s,upload_asset_chunk:i,commit_asset_upload:a}=n,{batch_id:c}=await s(b_(r));o?.onInitiatedBatch();let{chunkIds:u}=await O_({data:e,uploadFn:i,batchId:c});o?.onUploadedFileChunks(r.fullPath),await T_({commitFn:a,batchId:c,data:e,headers:t,chunkIds:u}),o?.onCommittedBatch()};var b_=({filename:e,collection:t,token:r,fullPath:n,encoding:o,description:s})=>({collection:t,full_path:n,name:e,token:le(r),encoding_type:le(o),description:le(s)}),w_=({batchId:e,chunkIds:t,headers:r,data:n})=>{let o=r.find(([s,i])=>s.toLowerCase()==="content-type")===void 0&&n.type!==void 0&&n.type!==""?[["Content-Type",n.type]]:void 0;return{batch_id:e,chunk_ids:t.map(({chunk_id:s})=>s),headers:[...r,...o??[]]}},T_=async({commitFn:e,...t})=>{let r=w_(t);await e(r)},O_=async({data:e,uploadFn:t,batchId:r})=>{let n=[],o=ei()?new Blob([await e.arrayBuffer()]):e,s=0n;for(let a=0;a<o.size;a+=19e5){let c=o.slice(a,a+19e5);n.push({batchId:r,chunk:c,uploadFn:t,orderId:s}),s++}let i=[];for await(let a of N_({uploadChunks:n}))i=[...i,...a];return{chunkIds:i}};async function*N_({uploadChunks:e,limit:t=12}){for(let r=0;r<e.length;r=r+t){let n=e.slice(r,r+t);yield await Promise.all(n.map(o=>E_(o)))}}var E_=async({batchId:e,chunk:t,uploadFn:r,orderId:n})=>r({batch_id:e,content:new Uint8Array(await t.arrayBuffer()),order_id:le(n)});var yp=async({asset:e,...t})=>{let r=await Oe(t);await _p({actor:r,asset:e})},gp=async({collection:e,filter:t,...r})=>{let{list_assets:n}=await Oe(r),{items:o,items_length:s,items_page:i,matches_length:a,matches_pages:c}=await n(e,Sr(t));return{items:o.map(([u,p])=>p),items_length:s,items_page:Ie(i),matches_length:a,matches_pages:Ie(c)}},xp=async({collection:e,filter:t,...r})=>{let{count_assets:n}=await Oe(r);return n(e,Sr(t))},bp=async({collection:e,fullPath:t,...r})=>(await Oe(r)).del_asset(e,t),wp=async({assets:e,satellite:t})=>{let{del_many_assets:r}=await Oe({satellite:t,options:{certified:!0}}),n=e.map(({collection:o,fullPath:s})=>[o,s]);await r(n)},Tp=async({collection:e,filter:t,...r})=>{let{del_filtered_assets:n}=await Oe(r);return n(e,Sr(t))},Op=async({collection:e,fullPath:t,...r})=>{let{get_asset:n}=await Oe(r);return Ie(await n(e,t))},Np=async({assets:e,...t})=>{let{get_many_assets:r}=await Oe(t),n=e.map(({collection:s,fullPath:i})=>[s,i]);return(await r(n)).map(([s,i])=>Ie(i))};var Ep=e=>btoa([...e].map(t=>String.fromCharCode(t)).join(""));var f1=e=>Rp(e),h1=e=>Rp({filename:e.data.name,...e}),Rp=async({filename:e,data:t,collection:r,headers:n=[],fullPath:o,token:s,satellite:i,encoding:a,description:c})=>{let u=ue(i?.identity),p=decodeURI(e),d=o??`/${r}/${p}`,l={...i,identity:u};return await yp({asset:{data:t,filename:p,collection:r,token:s,headers:n,fullPath:d,encoding:a,description:c},satellite:l,options:{certified:!0}}),{downloadUrl:vp({satellite:l,assetKey:{fullPath:d,token:s}}),fullPath:d,name:p}},m1=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:ue(r?.identity)},{items:s,...i}=await gp({collection:e,filter:t??{},satellite:o,options:n??Ft}),a=s.map(({key:{full_path:c,token:u,name:p,owner:d,description:l},headers:f,encodings:h,created_at:m,updated_at:y})=>{let _=Ie(u);return{fullPath:c,description:Ie(l),name:p,downloadUrl:vp({satellite:o,assetKey:{fullPath:c,token:_}}),token:_,headers:f,encodings:h.reduce((x,[g,{modified:T,sha256:N,total_length:E}])=>({...x,[g]:{modified:T,sha256:Ep(N),total_length:E}}),{}),owner:d.toText(),created_at:m,updated_at:y}});return{items:a,assets:a,...i}},_1=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:ue(r?.identity)};return await xp({collection:e,satellite:o,filter:t??{},options:n??Ft})},y1=({collection:e,fullPath:t,satellite:r})=>bp({collection:e,fullPath:t,satellite:{...r,identity:ue(r?.identity)},options:{certified:!0}}),g1=({assets:e,satellite:t})=>wp({assets:e,satellite:{...t,identity:ue(t?.identity)},options:{certified:!0}}),x1=async({collection:e,satellite:t,filter:r})=>{let n={...t,identity:ue(t?.identity)};return await Tp({collection:e,satellite:n,filter:r??{},options:{certified:!0}})},b1=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await Op({...r,satellite:{...e,identity:n},options:t??Ft})},w1=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await Np({...r,satellite:{...e,identity:n},options:t??Ft})},vp=({assetKey:{fullPath:e,token:t},satellite:r})=>{let n={...r,identity:ue(r?.identity)};return`${Kd(n)}${e}${X(t)?`?token=${t}`:""}`};var R_=e=>{let t=e?.satelliteId??hp();Bo(t,"Satellite ID is not configured. Juno cannot be initialized.");let r=e?.container??mp();return{satelliteId:t,internetIdentityId:e?.internetIdentityId,workers:e?.workers,container:r}},S1=e=>v_(e),v_=async e=>{let t=R_(e);et.getInstance().set(t),await Fc();let r=t.workers?.auth!==void 0?fp(t.workers.auth):void 0;return[...r?[r]:[]]},I_=e=>at.getInstance().subscribe(e),P1=I_;export{qd as AuthClientSignInProgressStep,xi as InitError,wi as InternetIdentityProvider,bi as ListError,Ti as NFIDProvider,hi as SignInError,ln as SignInInitError,_i as SignInProviderNotSupportedError,mi as SignInUserInterruptError,gi as SignUpProviderNotSupportedError,ip as WebAuthnSignInProgressStep,yi as WebAuthnSignInRetrievePublicKeyError,ap as WebAuthnSignUpProgressStep,P1 as authSubscribe,_1 as countAssets,eO as countDocs,y1 as deleteAsset,JT as deleteDoc,x1 as deleteFilteredAssets,XT as deleteFilteredDocs,g1 as deleteManyAssets,ZT as deleteManyDocs,vp as downloadUrl,b1 as getAsset,Ni as getDoc,x_ as getIdentityOnce,w1 as getManyAssets,YT as getManyDocs,JO as getSatelliteExtendedActor,S1 as initJuno,v_ as initSatellite,Dm as isWebAuthnAvailable,m1 as listAssets,QT as listDocs,I_ as onAuthStateChange,np as setDoc,op as setManyDocs,f_ as signIn,Vc as signOut,h_ as signUp,g_ as unsafeIdentity,f1 as uploadBlob,h1 as uploadFile};
55
55
  /*! Bundled license information:
56
56
 
57
57
  @noble/hashes/esm/utils.js: