@junobuild/core-standalone 3.4.0 → 3.4.1-next-2026-01-16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var zp=Object.defineProperty;var Yp=(e,t)=>{for(var r in t)zp(e,r,{get:t[r],enumerable:!0})};var Wc;(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"})(Wc||(Wc={}));var xr;(function(e){e.Replied="replied",e.Rejected="rejected"})(xr||(xr={}));function zc(e){return e!=null&&"reject_code"in e}function Yc(e){return e!=null&&"certificate"in e}var fi="abcdefghijklmnopqrstuvwxyz234567",Dn=Object.create(null);for(let e=0;e<fi.length;e++)Dn[fi[e]]=e;Dn[0]=Dn.o;Dn[1]=Dn.i;function Zc(e){let t=0,r=0,n="";function o(i){return t<0?r|=i>>-t:r=i<<t&248,t>3?(t-=8,1):(t<4&&(n+=fi[r>>3],t+=5),0)}for(let i=0;i<e.length;)i+=o(e[i]);return n+(t<0?fi[r>>3]:"")}function Xc(e){let t=0,r=0,n=new Uint8Array(e.length*4/3|0),o=0;function i(s){let a=Dn[s.toLowerCase()];if(a===void 0)throw new Error(`Invalid character: ${JSON.stringify(s)}`);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 s of e)i(s);return n.slice(0,o)}var Zp=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 Qc(e){let t=-1;for(let r=0;r<e.length;r++){let o=(e[r]^t)&255;t=Zp[o]^t>>>8}return(t^-1)>>>0}var hn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function At(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Gs(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function me(e,...t){if(!At(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 Js(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 tl(e,t){me(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function mn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function mi(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function yt(e,t){return e<<32-t|e>>>t}var rl=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Xp=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function j(e){if(me(e),rl)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Xp[e[r]];return t}var Jt={_0:48,_9:57,A:65,F:70,a:97,f:102};function el(e){if(e>=Jt._0&&e<=Jt._9)return e-Jt._0;if(e>=Jt.A&&e<=Jt.F)return e-(Jt.A-10);if(e>=Jt.a&&e<=Jt.f)return e-(Jt.a-10)}function Ee(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(rl)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,i=0;o<r;o++,i+=2){let s=el(e.charCodeAt(i)),a=el(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function $(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Ws(e){return typeof e=="string"&&(e=$(e)),me(e),e}function K(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];me(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let i=e[n];r.set(i,o),o+=i.length}return r}var hi=class{};function _i(e){let t=n=>e().update(Ws(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Un(e=32){if(hn&&typeof hn.getRandomValues=="function")return hn.getRandomValues(new Uint8Array(e));if(hn&&typeof hn.randomBytes=="function")return Uint8Array.from(hn.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Qp(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?4:0,u=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+u,a,n)}function nl(e,t,r){return e&t^~e&r}function ol(e,t,r){return e&t^e&r^t&r}var yo=class extends hi{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=mi(this.buffer)}update(t){Js(this),t=Ws(t),me(t);let{view:r,buffer:n,blockLen:o}=this,i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=mi(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Js(this),tl(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;r[s++]=128,mn(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let d=s;d<o;d++)r[d]=0;Qp(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=mi(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],i)}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:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Wt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),zt=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);var Ce=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var yi=BigInt(4294967295),il=BigInt(32);function ef(e,t=!1){return t?{h:Number(e&yi),l:Number(e>>il&yi)}:{h:Number(e>>il&yi)|0,l:Number(e&yi)|0}}function sl(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=ef(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var zs=(e,t,r)=>e>>>r,Ys=(e,t,r)=>e<<32-r|t>>>r,_n=(e,t,r)=>e>>>r|t<<32-r,yn=(e,t,r)=>e<<32-r|t>>>r,go=(e,t,r)=>e<<64-r|t>>>r-32,xo=(e,t,r)=>e>>>r-32|t<<64-r;function St(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var al=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),cl=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,ll=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),ul=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,dl=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),pl=(e,t,r,n,o,i)=>t+r+n+o+i+(e/2**32|0)|0;var rf=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]),br=new Uint32Array(64),gi=class extends yo{constructor(t=32){super(64,t,8,!1),this.A=Wt[0]|0,this.B=Wt[1]|0,this.C=Wt[2]|0,this.D=Wt[3]|0,this.E=Wt[4]|0,this.F=Wt[5]|0,this.G=Wt[6]|0,this.H=Wt[7]|0}get(){let{A:t,B:r,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,r,n,o,i,s,a,c]}set(t,r,n,o,i,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,r){for(let d=0;d<16;d++,r+=4)br[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){let l=br[d-15],f=br[d-2],h=yt(l,7)^yt(l,18)^l>>>3,_=yt(f,17)^yt(f,19)^f>>>10;br[d]=_+br[d-7]+h+br[d-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:u,H:p}=this;for(let d=0;d<64;d++){let l=yt(a,6)^yt(a,11)^yt(a,25),f=p+l+nl(a,c,u)+rf[d]+br[d]|0,_=(yt(n,2)^yt(n,13)^yt(n,22))+ol(n,o,i)|0;p=u,u=c,c=a,a=s+f|0,s=i,i=o,o=n,n=f+_|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+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,i,s,a,c,u,p)}roundClean(){mn(br)}destroy(){this.set(0,0,0,0,0,0,0,0),mn(this.buffer)}},Zs=class extends gi{constructor(){super(28),this.A=zt[0]|0,this.B=zt[1]|0,this.C=zt[2]|0,this.D=zt[3]|0,this.E=zt[4]|0,this.F=zt[5]|0,this.G=zt[6]|0,this.H=zt[7]|0}},fl=sl(["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))),nf=fl[0],of=fl[1],wr=new Uint32Array(80),Tr=new Uint32Array(80),Xs=class extends yo{constructor(t=64){super(128,t,16,!1),this.Ah=Ce[0]|0,this.Al=Ce[1]|0,this.Bh=Ce[2]|0,this.Bl=Ce[3]|0,this.Ch=Ce[4]|0,this.Cl=Ce[5]|0,this.Dh=Ce[6]|0,this.Dl=Ce[7]|0,this.Eh=Ce[8]|0,this.El=Ce[9]|0,this.Fh=Ce[10]|0,this.Fl=Ce[11]|0,this.Gh=Ce[12]|0,this.Gl=Ce[13]|0,this.Hh=Ce[14]|0,this.Hl=Ce[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:i,Cl:s,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,i,s,a,c,u,p,d,l,f,h,_,g]}set(t,r,n,o,i,s,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=i|0,this.Cl=s|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)wr[y]=t.getUint32(r),Tr[y]=t.getUint32(r+=4);for(let y=16;y<80;y++){let T=wr[y-15]|0,E=Tr[y-15]|0,O=_n(T,E,1)^_n(T,E,8)^zs(T,E,7),R=yn(T,E,1)^yn(T,E,8)^Ys(T,E,7),v=wr[y-2]|0,w=Tr[y-2]|0,I=_n(v,w,19)^go(v,w,61)^zs(v,w,6),F=yn(v,w,19)^xo(v,w,61)^Ys(v,w,6),S=ll(R,F,Tr[y-7],Tr[y-16]),b=ul(S,O,I,wr[y-7],wr[y-16]);wr[y]=b|0,Tr[y]=S|0}let{Ah:n,Al:o,Bh:i,Bl:s,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=_n(d,l,14)^_n(d,l,18)^go(d,l,41),E=yn(d,l,14)^yn(d,l,18)^xo(d,l,41),O=d&f^~d&_,R=l&h^~l&g,v=dl(x,E,R,of[y],Tr[y]),w=pl(v,m,T,O,nf[y],wr[y]),I=v|0,F=_n(n,o,28)^go(n,o,34)^go(n,o,39),S=yn(n,o,28)^xo(n,o,34)^xo(n,o,39),b=n&i^n&a^i&a,N=o&s^o&c^s&c;m=_|0,x=g|0,_=f|0,g=h|0,f=d|0,h=l|0,{h:d,l}=St(u|0,p|0,w|0,I|0),u=a|0,p=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let C=al(I,S,N);n=cl(C,w,F,b),o=C|0}({h:n,l:o}=St(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=St(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=St(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:p}=St(this.Dh|0,this.Dl|0,u|0,p|0),{h:d,l}=St(this.Eh|0,this.El|0,d|0,l|0),{h:f,l:h}=St(this.Fh|0,this.Fl|0,f|0,h|0),{h:_,l:g}=St(this.Gh|0,this.Gl|0,_|0,g|0),{h:m,l:x}=St(this.Hh|0,this.Hl|0,m|0,x|0),this.set(n,o,i,s,a,c,u,p,d,l,f,h,_,g,m,x)}roundClean(){mn(wr,Tr)}destroy(){mn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Ve=_i(()=>new gi),hl=_i(()=>new Zs),ml=_i(()=>new Xs);var xi="__principal__",sf=2,_l=4,af="aaaaa-aa",k=class e{static anonymous(){return new this(new Uint8Array([_l]))}static managementCanister(){return this.fromText(af)}static selfAuthenticating(t){let r=hl(t);return new this(new Uint8Array([...r,sf]))}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(Ee(t))}static fromText(t){let r=t;if(t.includes(xi)){let s=JSON.parse(t);xi in s&&(r=s[xi])}let n=r.toLowerCase().replace(/-/g,""),o=Xc(n);o=o.slice(4,o.length);let i=new this(o);if(i.toText()!==r)throw new Error(`Principal "${i.toText()}" does not have a valid checksum (original value "${r}" may not be a valid Principal ID).`);return i}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]===_l}toUint8Array(){return this._arr}toHex(){return j(this._arr).toUpperCase()}toText(){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,Qc(this._arr));let n=new Uint8Array(t),o=new Uint8Array([...n,...this._arr]),s=Zc(o).match(/.{1,5}/g);if(!s)throw new Error;return s.join("-")}toString(){return this.toText()}toJSON(){return{[xi]: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 Yt;(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"})(Yt||(Yt={}));var G=class{constructor(t=!1){this.isCertified=t}toString(){let t=this.toErrorMessage();return this.requestContext&&(t+=`
1
+ var df=Object.defineProperty;var pf=(e,t)=>{for(var r in t)df(e,r,{get:t[r],enumerable:!0})};var al;(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"})(al||(al={}));var Er;(function(e){e.Replied="replied",e.Rejected="rejected"})(Er||(Er={}));function cl(e){return e!=null&&"reject_code"in e}function ll(e){return e!=null&&"certificate"in e}var _i="abcdefghijklmnopqrstuvwxyz234567",Mn=Object.create(null);for(let e=0;e<_i.length;e++)Mn[_i[e]]=e;Mn[0]=Mn.o;Mn[1]=Mn.i;function ul(e){let t=0,r=0,n="";function o(i){return t<0?r|=i>>-t:r=i<<t&248,t>3?(t-=8,1):(t<4&&(n+=_i[r>>3],t+=5),0)}for(let i=0;i<e.length;)i+=o(e[i]);return n+(t<0?_i[r>>3]:"")}function dl(e){let t=0,r=0,n=new Uint8Array(e.length*4/3|0),o=0;function i(s){let a=Mn[s.toLowerCase()];if(a===void 0)throw new Error(`Invalid character: ${JSON.stringify(s)}`);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 s of e)i(s);return n.slice(0,o)}var ff=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 pl(e){let t=-1;for(let r=0;r<e.length;r++){let o=(e[r]^t)&255;t=ff[o]^t>>>8}return(t^-1)>>>0}var gn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function At(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function sa(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function me(e,...t){if(!At(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 aa(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 hl(e,t){me(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function xn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function gi(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function yt(e,t){return e<<32-t|e>>>t}var ml=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hf=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function j(e){if(me(e),ml)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=hf[e[r]];return t}var Qt={_0:48,_9:57,A:65,F:70,a:97,f:102};function fl(e){if(e>=Qt._0&&e<=Qt._9)return e-Qt._0;if(e>=Qt.A&&e<=Qt.F)return e-(Qt.A-10);if(e>=Qt.a&&e<=Qt.f)return e-(Qt.a-10)}function Ee(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(ml)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,i=0;o<r;o++,i+=2){let s=fl(e.charCodeAt(i)),a=fl(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function $(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ca(e){return typeof e=="string"&&(e=$(e)),me(e),e}function K(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];me(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let i=e[n];r.set(i,o),o+=i.length}return r}var yi=class{};function xi(e){let t=n=>e().update(ca(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function jn(e=32){if(gn&&typeof gn.getRandomValues=="function")return gn.getRandomValues(new Uint8Array(e));if(gn&&typeof gn.randomBytes=="function")return Uint8Array.from(gn.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function mf(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?4:0,u=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+u,a,n)}function _l(e,t,r){return e&t^~e&r}function yl(e,t,r){return e&t^e&r^t&r}var bo=class extends yi{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=gi(this.buffer)}update(t){aa(this),t=ca(t),me(t);let{view:r,buffer:n,blockLen:o}=this,i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=gi(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){aa(this),hl(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;r[s++]=128,xn(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let d=s;d<o;d++)r[d]=0;mf(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=gi(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],i)}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:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},er=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),tr=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);var Ce=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var bi=BigInt(4294967295),gl=BigInt(32);function _f(e,t=!1){return t?{h:Number(e&bi),l:Number(e>>gl&bi)}:{h:Number(e>>gl&bi)|0,l:Number(e&bi)|0}}function xl(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=_f(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var la=(e,t,r)=>e>>>r,ua=(e,t,r)=>e<<32-r|t>>>r,bn=(e,t,r)=>e>>>r|t<<32-r,wn=(e,t,r)=>e<<32-r|t>>>r,wo=(e,t,r)=>e<<64-r|t>>>r-32,To=(e,t,r)=>e>>>r-32|t<<64-r;function St(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var bl=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),wl=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Tl=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Nl=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,Ol=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),El=(e,t,r,n,o,i)=>t+r+n+o+i+(e/2**32|0)|0;var gf=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]),Rr=new Uint32Array(64),wi=class extends bo{constructor(t=32){super(64,t,8,!1),this.A=er[0]|0,this.B=er[1]|0,this.C=er[2]|0,this.D=er[3]|0,this.E=er[4]|0,this.F=er[5]|0,this.G=er[6]|0,this.H=er[7]|0}get(){let{A:t,B:r,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,r,n,o,i,s,a,c]}set(t,r,n,o,i,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,r){for(let d=0;d<16;d++,r+=4)Rr[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){let l=Rr[d-15],f=Rr[d-2],h=yt(l,7)^yt(l,18)^l>>>3,_=yt(f,17)^yt(f,19)^f>>>10;Rr[d]=_+Rr[d-7]+h+Rr[d-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:u,H:p}=this;for(let d=0;d<64;d++){let l=yt(a,6)^yt(a,11)^yt(a,25),f=p+l+_l(a,c,u)+gf[d]+Rr[d]|0,_=(yt(n,2)^yt(n,13)^yt(n,22))+yl(n,o,i)|0;p=u,u=c,c=a,a=s+f|0,s=i,i=o,o=n,n=f+_|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+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,i,s,a,c,u,p)}roundClean(){xn(Rr)}destroy(){this.set(0,0,0,0,0,0,0,0),xn(this.buffer)}},da=class extends wi{constructor(){super(28),this.A=tr[0]|0,this.B=tr[1]|0,this.C=tr[2]|0,this.D=tr[3]|0,this.E=tr[4]|0,this.F=tr[5]|0,this.G=tr[6]|0,this.H=tr[7]|0}},Rl=xl(["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))),xf=Rl[0],bf=Rl[1],Ir=new Uint32Array(80),vr=new Uint32Array(80),pa=class extends bo{constructor(t=64){super(128,t,16,!1),this.Ah=Ce[0]|0,this.Al=Ce[1]|0,this.Bh=Ce[2]|0,this.Bl=Ce[3]|0,this.Ch=Ce[4]|0,this.Cl=Ce[5]|0,this.Dh=Ce[6]|0,this.Dl=Ce[7]|0,this.Eh=Ce[8]|0,this.El=Ce[9]|0,this.Fh=Ce[10]|0,this.Fl=Ce[11]|0,this.Gh=Ce[12]|0,this.Gl=Ce[13]|0,this.Hh=Ce[14]|0,this.Hl=Ce[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:i,Cl:s,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,i,s,a,c,u,p,d,l,f,h,_,g]}set(t,r,n,o,i,s,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=i|0,this.Cl=s|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)Ir[y]=t.getUint32(r),vr[y]=t.getUint32(r+=4);for(let y=16;y<80;y++){let T=Ir[y-15]|0,E=vr[y-15]|0,O=bn(T,E,1)^bn(T,E,8)^la(T,E,7),R=wn(T,E,1)^wn(T,E,8)^ua(T,E,7),v=Ir[y-2]|0,w=vr[y-2]|0,I=bn(v,w,19)^wo(v,w,61)^la(v,w,6),F=wn(v,w,19)^To(v,w,61)^ua(v,w,6),S=Tl(R,F,vr[y-7],vr[y-16]),b=Nl(S,O,I,Ir[y-7],Ir[y-16]);Ir[y]=b|0,vr[y]=S|0}let{Ah:n,Al:o,Bh:i,Bl:s,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=bn(d,l,14)^bn(d,l,18)^wo(d,l,41),E=wn(d,l,14)^wn(d,l,18)^To(d,l,41),O=d&f^~d&_,R=l&h^~l&g,v=Ol(x,E,R,bf[y],vr[y]),w=El(v,m,T,O,xf[y],Ir[y]),I=v|0,F=bn(n,o,28)^wo(n,o,34)^wo(n,o,39),S=wn(n,o,28)^To(n,o,34)^To(n,o,39),b=n&i^n&a^i&a,N=o&s^o&c^s&c;m=_|0,x=g|0,_=f|0,g=h|0,f=d|0,h=l|0,{h:d,l}=St(u|0,p|0,w|0,I|0),u=a|0,p=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let C=bl(I,S,N);n=wl(C,w,F,b),o=C|0}({h:n,l:o}=St(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=St(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=St(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:p}=St(this.Dh|0,this.Dl|0,u|0,p|0),{h:d,l}=St(this.Eh|0,this.El|0,d|0,l|0),{h:f,l:h}=St(this.Fh|0,this.Fl|0,f|0,h|0),{h:_,l:g}=St(this.Gh|0,this.Gl|0,_|0,g|0),{h:m,l:x}=St(this.Hh|0,this.Hl|0,m|0,x|0),this.set(n,o,i,s,a,c,u,p,d,l,f,h,_,g,m,x)}roundClean(){xn(Ir,vr)}destroy(){xn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Pe=xi(()=>new wi),Il=xi(()=>new da),vl=xi(()=>new pa);var Ti="__principal__",wf=2,Al=4,Tf="aaaaa-aa",U=class e{static anonymous(){return new this(new Uint8Array([Al]))}static managementCanister(){return this.fromText(Tf)}static selfAuthenticating(t){let r=Il(t);return new this(new Uint8Array([...r,wf]))}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(Ee(t))}static fromText(t){let r=t;if(t.includes(Ti)){let s=JSON.parse(t);Ti in s&&(r=s[Ti])}let n=r.toLowerCase().replace(/-/g,""),o=dl(n);o=o.slice(4,o.length);let i=new this(o);if(i.toText()!==r)throw new Error(`Principal "${i.toText()}" does not have a valid checksum (original value "${r}" may not be a valid Principal ID).`);return i}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]===Al}toUint8Array(){return this._arr}toHex(){return j(this._arr).toUpperCase()}toText(){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,pl(this._arr));let n=new Uint8Array(t),o=new Uint8Array([...n,...this._arr]),s=ul(o).match(/.{1,5}/g);if(!s)throw new Error;return s.join("-")}toString(){return this.toText()}toJSON(){return{[Ti]: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 rr;(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"})(rr||(rr={}));var G=class{constructor(t=!1){this.isCertified=t}toString(){let t=this.toErrorMessage();return this.requestContext&&(t+=`
2
2
  Request context:
3
3
  Request ID (hex): ${this.requestContext.requestId?j(this.requestContext.requestId):"undefined"}
4
4
  Sender pubkey (hex): ${j(this.requestContext.senderPubKey)}
@@ -7,51 +7,51 @@ Request context:
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}},et=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}`}},Zt=class extends et{static fromCode(t){return new this(t)}},ke=class e extends Zt{constructor(t){super(t,Yt.Trust),this.name="TrustError",Object.setPrototypeOf(this,e.prototype)}},te=class e extends Zt{constructor(t){super(t,Yt.Protocol),this.name="ProtocolError",Object.setPrototypeOf(this,e.prototype)}},Nr=class e extends Zt{constructor(t){super(t,Yt.Reject),this.name="RejectError",Object.setPrototypeOf(this,e.prototype)}},bo=class e extends Zt{constructor(t){super(t,Yt.Transport),this.name="TransportError",Object.setPrototypeOf(this,e.prototype)}},ye=class e extends Zt{constructor(t){super(t,Yt.External),this.name="ExternalError",Object.setPrototypeOf(this,e.prototype)}};var Y=class e extends Zt{constructor(t){super(t,Yt.Input),this.name="InputError",Object.setPrototypeOf(this,e.prototype)}},ae=class e extends Zt{constructor(t){super(t,Yt.Unknown),this.name="UnknownError",Object.setPrototypeOf(this,e.prototype)}},gt=class e extends G{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+=`: ${Io(this.error)}`),`Certificate verification error: "${t}"`}},Xt=class e extends G{constructor(t,r,n,o,i){super(),this.maxAgeInMinutes=t,this.certificateTime=r,this.currentTime=n,this.timeDiffMsecs=o,this.ageType=i,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`}},bi=class e extends G{constructor(){super(),this.name="CertificateHasTooManyDelegationsErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Certificate has too many delegations"}},gn=class e extends G{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()}`}},wi=class e extends G{constructor(t){super(),this.subnetId=t,this.name="CertificateNotAuthorizedForSubnetErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The certificate is not authorized for subnet ${this.subnetId.toText()}`}},xt=class e extends G{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}`}},Ti=class e extends G{constructor(t){super(),this.message=t,this.name="MalformedLookupFoundValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},Ni=class e extends G{constructor(t){super(),this.message=t,this.name="MissingLookupValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},kn=class e extends G{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`}},Oi=class e extends G{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: ${j(this.expectedPrefix)}, but got ${j(this.actualPrefix)}`}},Ei=class e extends G{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}`}},bt=class e extends G{constructor(t){super(),this.error=t,this.name="DerDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}},wo=class e extends G{constructor(t){super(),this.error=t,this.name="DerEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}},Ri=class e extends G{constructor(t,r){super(),this.error=t,this.input=r,this.name="CborDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${Io(this.error)}, input: ${j(this.input)}`}},Ii=class e extends G{constructor(t,r){super(),this.error=t,this.value=r,this.name="CborEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${Io(this.error)}, input: ${this.value}`}};var xn=class e extends G{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}
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}`}},nr=class extends nt{static fromCode(t){return new this(t)}},Le=class e extends nr{constructor(t){super(t,rr.Trust),this.name="TrustError",Object.setPrototypeOf(this,e.prototype)}},ne=class e extends nr{constructor(t){super(t,rr.Protocol),this.name="ProtocolError",Object.setPrototypeOf(this,e.prototype)}},Ar=class e extends nr{constructor(t){super(t,rr.Reject),this.name="RejectError",Object.setPrototypeOf(this,e.prototype)}},No=class e extends nr{constructor(t){super(t,rr.Transport),this.name="TransportError",Object.setPrototypeOf(this,e.prototype)}},ye=class e extends nr{constructor(t){super(t,rr.External),this.name="ExternalError",Object.setPrototypeOf(this,e.prototype)}};var Y=class e extends nr{constructor(t){super(t,rr.Input),this.name="InputError",Object.setPrototypeOf(this,e.prototype)}},ce=class e extends nr{constructor(t){super(t,rr.Unknown),this.name="UnknownError",Object.setPrototypeOf(this,e.prototype)}},gt=class e extends G{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+=`: ${So(this.error)}`),`Certificate verification error: "${t}"`}},or=class e extends G{constructor(t,r,n,o,i){super(),this.maxAgeInMinutes=t,this.certificateTime=r,this.currentTime=n,this.timeDiffMsecs=o,this.ageType=i,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`}},Ni=class e extends G{constructor(){super(),this.name="CertificateHasTooManyDelegationsErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Certificate has too many delegations"}},Tn=class e extends G{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()}`}},Oi=class e extends G{constructor(t){super(),this.subnetId=t,this.name="CertificateNotAuthorizedForSubnetErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The certificate is not authorized for subnet ${this.subnetId.toText()}`}},xt=class e extends G{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}`}},Ei=class e extends G{constructor(t){super(),this.message=t,this.name="MalformedLookupFoundValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},Ri=class e extends G{constructor(t){super(),this.message=t,this.name="MissingLookupValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},Kn=class e extends G{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`}},Ii=class e extends G{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: ${j(this.expectedPrefix)}, but got ${j(this.actualPrefix)}`}},vi=class e extends G{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}`}},bt=class e extends G{constructor(t){super(),this.error=t,this.name="DerDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}},Oo=class e extends G{constructor(t){super(),this.error=t,this.name="DerEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}},Ai=class e extends G{constructor(t,r){super(),this.error=t,this.input=r,this.name="CborDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${So(this.error)}, input: ${j(this.input)}`}},Si=class e extends G{constructor(t,r){super(),this.error=t,this.value=r,this.name="CborEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${So(this.error)}, input: ${this.value}`}};var Nn=class e extends G{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
11
  `;return this.requestId&&(t+=` Request ID: ${j(this.requestId)}
12
12
  `),this.status&&(t+=` Request status: ${this.status}
13
- `),t}},vi=class e extends G{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?
13
+ `),t}},Ci=class e extends G{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
14
  Request ID: ${j(this.requestId)}
15
- `;return this.retryTimes!==void 0&&(t+=` Retried ${this.retryTimes} times.`),t}},Ln=class e extends G{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:
15
+ `;return this.retryTimes!==void 0&&(t+=` Retried ${this.retryTimes} times.`),t}},Hn=class e extends G{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
16
  Request ID: ${j(this.requestId)}
17
17
  Reject code: ${this.rejectCode}
18
18
  Reject text: ${this.rejectMessage}
19
19
  Error code: ${this.rejectErrorCode}
20
- `}},Ai=class e extends G{constructor(t,r,n,o,i){super(),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.signatures=i,this.name="UncertifiedRejectErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
20
+ `}},Fi=class e extends G{constructor(t,r,n,o,i){super(),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.signatures=i,this.name="UncertifiedRejectErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
21
21
  Request ID: ${j(this.requestId)}
22
22
  Reject code: ${this.rejectCode}
23
23
  Reject text: ${this.rejectMessage}
24
24
  Error code: ${this.rejectErrorCode}
25
- `}},Si=class e extends G{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:
25
+ `}},Pi=class e extends G{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
26
  Request ID: ${j(this.requestId)}
27
27
  Reject code: ${this.rejectCode}
28
28
  Reject text: ${this.rejectMessage}
29
29
  Error code: ${this.rejectErrorCode}
30
- `}},Ci=class e extends G{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:
30
+ `}},Vi=class e extends G{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
31
  Request ID: ${j(this.requestId)}
32
- `}},ot=class e extends G{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.`}},Fi=class e extends G{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}`}},qn=class e extends G{constructor(t){super(),this.error=t,this.name="HttpDefaultFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.error}},Or=class e extends G{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."}},Ct=class e extends G{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.`}},Vi=class e extends G{constructor(){super(),this.name="CreateHttpAgentErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Failed to create agent from provided agent"}},Pi=class e extends G{constructor(t){super(),this.error=t,this.name="MalformedSignatureErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}},Bi=class e extends G{constructor(){super(),this.name="MissingSignatureErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Query response did not contain any node signatures"}},Di=class e extends G{constructor(){super(),this.name="MalformedPublicKeyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Read state response contained a malformed public key"}},Ui=class e extends G{constructor(t){super(),this.nodeId=t,this.name="QuerySignatureVerificationFailedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}},Re=class e extends G{constructor(t){super(),this.error=t,this.name="UnexpectedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Unexpected error: ${Io(this.error)}`}},Er=class e extends G{constructor(t){super(),this.error=t,this.name="HashTreeDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}},To=class e extends G{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:
32
+ `}},at=class e extends G{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.`}},Bi=class e extends G{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 G{constructor(t){super(),this.error=t,this.name="HttpDefaultFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.error}},Sr=class e extends G{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."}},Ct=class e extends G{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.`}},Di=class e extends G{constructor(){super(),this.name="CreateHttpAgentErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Failed to create agent from provided agent"}},Ui=class e extends G{constructor(t){super(),this.error=t,this.name="MalformedSignatureErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}},ki=class e extends G{constructor(){super(),this.name="MissingSignatureErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Query response did not contain any node signatures"}},Li=class e extends G{constructor(){super(),this.name="MalformedPublicKeyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Read state response contained a malformed public key"}},qi=class e extends G{constructor(t){super(),this.nodeId=t,this.name="QuerySignatureVerificationFailedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}},Re=class e extends G{constructor(t){super(),this.error=t,this.name="UnexpectedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Unexpected error: ${So(this.error)}`}},Cr=class e extends G{constructor(t){super(),this.error=t,this.name="HashTreeDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}},Eo=class e extends G{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}},No=class e extends G{constructor(){super(),this.name="HttpV4ApiNotSupportedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"HTTP request failed: v4 API is not supported"}},Oo=class e extends G{constructor(t){super(),this.error=t,this.name="HttpFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to fetch HTTP request: ${Io(this.error)}`}},Eo=class e extends G{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.`}},ki=class e extends G{constructor(t){super(),this.request=t,this.name="InvalidReadStateRequestErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Invalid read state request: ${this.request}`}},Ro=class e extends G{constructor(t){super(),this.error=t,this.name="ExpiryJsonDeserializeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to deserialize expiry: ${this.error}`}};function Io(e){if(e instanceof Error)return e.stack??e.message;try{return JSON.stringify(e)}catch{return String(e)}}var it=new Error("unreachable");var Nn={};Yp(Nn,{Bool:()=>El,BoolClass:()=>Ki,ConstructType:()=>Pt,Empty:()=>Nl,EmptyClass:()=>Ao,FixedIntClass:()=>tr,FixedNatClass:()=>Vt,Float32:()=>Sl,Float64:()=>Cl,FloatClass:()=>Fo,Func:()=>Jl,FuncClass:()=>Tn,Int:()=>vl,Int16:()=>Vl,Int32:()=>Pl,Int64:()=>Bl,Int8:()=>Fl,IntClass:()=>So,Nat:()=>Al,Nat16:()=>Ul,Nat32:()=>kl,Nat64:()=>Ll,Nat8:()=>Dl,NatClass:()=>Co,Null:()=>Rl,NullClass:()=>bn,Opt:()=>Kl,OptClass:()=>vr,PrimitiveType:()=>We,Principal:()=>ql,PrincipalClass:()=>Gi,Rec:()=>Gl,RecClass:()=>st,Record:()=>Hl,RecordClass:()=>wn,Reserved:()=>Ol,ReservedClass:()=>Bt,Service:()=>Wl,ServiceClass:()=>$n,Text:()=>Il,TextClass:()=>Hi,Tuple:()=>Ml,TupleClass:()=>$i,Type:()=>jn,Unknown:()=>pf,UnknownClass:()=>ji,Variant:()=>$l,VariantClass:()=>Hn,Vec:()=>jl,VecClass:()=>Kn,Visitor:()=>oa,decode:()=>df,encode:()=>uf,resetSubtypeCache:()=>ia,subtype:()=>aa});function Z(...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 wt=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=Ft(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 Ft(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?Ft(e.buffer):new Uint8Array(e)}function Mn(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 yl(e,t){return Mn(e,t)===0}function gl(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(e.buffer,e.byteOffset,e.byteLength)}function cf(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 cf(e)}function Qs(e){let t=BigInt(e);if(e<=0)throw new RangeError("Input must be positive");return t.toString(2).length-1}function Li(e){let t=BigInt(e);if(e<0)throw new RangeError("Input must be non-negative");return BigInt(1)<<t}function xl(){throw new Error("unexpected end of buffer")}function Ir(e,t){return e.byteLength<t&&xl(),e.read(t)}function Rr(e){let t=e.readUint8();return t===void 0&&xl(),t}function oe(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:Qs(e))+1,r=new wt(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 ge(e){let t=BigInt(1),r=BigInt(0),n;do n=Rr(e),r+=BigInt(n&127).valueOf()*t,t*=BigInt(128);while(n>=128);return r}function xe(e){typeof e=="number"&&(e=BigInt(e));let t=e<BigInt(0);t&&(e=-e-BigInt(1));let r=(e===BigInt(0)?0:Qs(e))+1,n=new wt(new Uint8Array(r),0);for(;;){let i=o(e);if(e/=BigInt(128),t&&e===BigInt(0)&&(i&64)!==0||!t&&e===BigInt(0)&&(i&64)===0){n.write(new Uint8Array([i]));break}else n.write(new Uint8Array([i|128]))}function o(i){let s=i%BigInt(128);return Number(t?BigInt(128)-s-BigInt(1):s)}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 ge(e);break}let n=new Uint8Array(Ir(e,r+1)),o=BigInt(0);for(let i=n.byteLength-1;i>=0;i--)o=o*BigInt(128)+BigInt(128-(n[i]&127)-1);return-o-BigInt(1)}function bl(e,t){if(BigInt(e)<BigInt(0))throw new Error("Cannot write negative values.");return ea(e,t)}function ea(e,t){e=BigInt(e);let r=new wt(new Uint8Array(Math.min(1,t)),0),n=0,o=BigInt(256),i=BigInt(0),s=Number(e%o);for(r.write(new Uint8Array([s]));++n<t;)e<0&&i===BigInt(0)&&s!==0&&(i=BigInt(1)),s=Number((e/o-i)%BigInt(256)),r.write(new Uint8Array([s])),o*=BigInt(256);return r.buffer}function ta(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=BigInt(Rr(e)),n=BigInt(1),o=0;for(;++o<t;){n*=BigInt(256);let i=BigInt(Rr(e));r=r+n*i}return r}function wl(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=ta(e,t),n=BigInt(2)**(BigInt(8)*BigInt(t-1)+BigInt(7));return r>=n&&(r-=n*BigInt(2)),r}var Q;(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"})(Q||(Q={}));var qi="DIDL",lf=new TextEncoder().encode(qi),Tl=400;function vo(e,t,r){return e.map((n,o)=>r(n,t[o]))}var na=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 i=this._getIdxRefCount(n),s=this._getIdxRefCount(o);this._idxRefCount.set(n,i+s),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=oe(this._typs.length),r=Z(...this._typs);return Z(t,r)}indexOf(t){if(!this._idx.has(t))throw new Error("Missing type index for "+t);return xe(this._idx.get(t)||0)}},oa=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((i,s)=>[`_${s}_`,i]);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)}},H;(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__"})(H||(H={}));var jn=class{display(){return this.name}valueToString(t){return _e(t)}buildTypeTable(t){t.has(this)||this._buildTypeTableImpl(t)}},We=class extends jn{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){}},Pt=class extends jn{checkType(t){if(t instanceof st){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)}},Ao=class extends We{get typeName(){return H.EmptyClass}static[Symbol.hasInstance](t){return t.typeName===H.EmptyClass}accept(t,r){return t.visitEmpty(this,r)}covariant(t){throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(){throw new Error("Empty cannot appear as a function argument")}valueToString(){throw new Error("Empty cannot appear as a value")}encodeType(){return xe(Q.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}},ji=class extends jn{get typeName(){return H.UnknownClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(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 st?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"}},Ki=class extends We{get typeName(){return H.BoolClass}static[Symbol.hasInstance](t){return t.typeName===H.BoolClass}accept(t,r){return t.visitBool(this,r)}covariant(t){if(typeof t=="boolean")return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){return new Uint8Array([t?1:0])}encodeType(){return xe(Q.Bool)}decodeValue(t,r){switch(this.checkType(r),Rr(t)){case 0:return!1;case 1:return!0;default:throw new Error("Boolean value out of range")}}get name(){return"bool"}},bn=class extends We{get typeName(){return H.NullClass}static[Symbol.hasInstance](t){return t.typeName===H.NullClass}accept(t,r){return t.visitNull(this,r)}covariant(t){if(t===null)return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(){return new Uint8Array(0)}encodeType(){return xe(Q.Null)}decodeValue(t,r){return this.checkType(r),null}get name(){return"null"}},Bt=class extends We{get typeName(){return H.ReservedClass}static[Symbol.hasInstance](t){return t.typeName===H.ReservedClass}accept(t,r){return t.visitReserved(this,r)}covariant(t){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return xe(Q.Reserved)}decodeValue(t,r){return r.name!==this.name&&r.decodeValue(t,r),null}get name(){return"reserved"}},Hi=class extends We{get typeName(){return H.TextClass}static[Symbol.hasInstance](t){return t.typeName===H.TextClass}accept(t,r){return t.visitText(this,r)}covariant(t){if(typeof t=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){let r=new TextEncoder().encode(t),n=oe(r.byteLength);return Z(n,r)}encodeType(){return xe(Q.Text)}decodeValue(t,r){this.checkType(r);let n=ge(t),o=Ir(t,Number(n));return new TextDecoder("utf8",{fatal:!0}).decode(o)}get name(){return"text"}valueToString(t){return'"'+t+'"'}},So=class extends We{get typeName(){return H.IntClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(t)}`)}encodeValue(t){return xe(t)}encodeType(){return xe(Q.Int)}decodeValue(t,r){return this.checkType(r),Qt(t)}get name(){return"int"}valueToString(t){return t.toString()}},Co=class extends We{get typeName(){return H.NatClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(t)}`)}encodeValue(t){return oe(t)}encodeType(){return xe(Q.Nat)}decodeValue(t,r){return this.checkType(r),ge(t)}get name(){return"nat"}valueToString(t){return t.toString()}},Fo=class extends We{get typeName(){return H.FloatClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(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?Q.Float32:Q.Float64;return xe(t)}decodeValue(t,r){this.checkType(r);let n=Ir(t,this._bits/8),o=gl(n);return this._bits===32?o.getFloat32(0,!0):o.getFloat64(0,!0)}get name(){return"float"+this._bits}valueToString(t){return t.toString()}},tr=class extends We{get typeName(){return H.FixedIntClass}static[Symbol.hasInstance](t){return t.typeName===H.FixedIntClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedInt(this,r)}covariant(t){let r=Li(this._bits-1)*BigInt(-1),n=Li(this._bits-1)-BigInt(1),o=!1;if(typeof t=="bigint")o=t>=r&&t<=n;else if(Number.isInteger(t)){let i=BigInt(t);o=i>=r&&i<=n}else o=!1;if(o)return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){return ea(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return xe(-9-t)}decodeValue(t,r){this.checkType(r);let n=wl(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(t){return t.toString()}},Vt=class extends We{get typeName(){return H.FixedNatClass}static[Symbol.hasInstance](t){return t.typeName===H.FixedNatClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedNat(this,r)}covariant(t){let r=Li(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: ${_e(t)}`)}encodeValue(t){return bl(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return xe(-5-t)}decodeValue(t,r){this.checkType(r);let n=ta(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(t){return t.toString()}},Kn=class e extends Pt{get typeName(){return H.VecClass}static[Symbol.hasInstance](t){return t.typeName===H.VecClass}constructor(t){super(),this._type=t,this._blobOptimization=!1,t instanceof Vt&&t._bits===8&&(this._blobOptimization=!0)}accept(t,r){return t.visitVec(this,this._type,r)}covariant(t){let r=this._type instanceof Vt?this._type._bits:this._type instanceof tr?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(i){throw new Error(`Invalid ${this.display()} argument:
36
+ `),t}},Ro=class e extends G{constructor(){super(),this.name="HttpV4ApiNotSupportedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"HTTP request failed: v4 API is not supported"}},Io=class e extends G{constructor(t){super(),this.error=t,this.name="HttpFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to fetch HTTP request: ${So(this.error)}`}},vo=class e extends G{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.`}},Mi=class e extends G{constructor(t){super(),this.request=t,this.name="InvalidReadStateRequestErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Invalid read state request: ${this.request}`}},Ao=class e extends G{constructor(t){super(),this.error=t,this.name="ExpiryJsonDeserializeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to deserialize expiry: ${this.error}`}};function So(e){if(e instanceof Error)return e.stack??e.message;try{return JSON.stringify(e)}catch{return String(e)}}var ct=new Error("unreachable");var In={};pf(In,{Bool:()=>kl,BoolClass:()=>Gi,ConstructType:()=>Vt,Empty:()=>Dl,EmptyClass:()=>Fo,FixedIntClass:()=>ar,FixedNatClass:()=>Pt,Float32:()=>Kl,Float64:()=>Hl,FloatClass:()=>Bo,Func:()=>su,FuncClass:()=>Rn,Int:()=>Ml,Int16:()=>Gl,Int32:()=>Jl,Int64:()=>Wl,Int8:()=>$l,IntClass:()=>Po,Nat:()=>jl,Nat16:()=>Yl,Nat32:()=>Zl,Nat64:()=>Xl,Nat8:()=>zl,NatClass:()=>Vo,Null:()=>Ll,NullClass:()=>On,Opt:()=>ru,OptClass:()=>Vr,PrimitiveType:()=>ze,Principal:()=>Ql,PrincipalClass:()=>zi,Rec:()=>iu,RecClass:()=>lt,Record:()=>nu,RecordClass:()=>En,Reserved:()=>Ul,ReservedClass:()=>Bt,Service:()=>au,ServiceClass:()=>Yn,Text:()=>ql,TextClass:()=>Ji,Tuple:()=>eu,TupleClass:()=>Wi,Type:()=>Jn,Unknown:()=>If,UnknownClass:()=>$i,Variant:()=>ou,VariantClass:()=>zn,Vec:()=>tu,VecClass:()=>Wn,Visitor:()=>ga,decode:()=>Rf,encode:()=>Ef,resetSubtypeCache:()=>xa,subtype:()=>wa});function Z(...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 wt=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=Ft(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 Ft(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?Ft(e.buffer):new Uint8Array(e)}function Gn(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 Gn(e,t)===0}function Cl(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Nf(e){let r=new TextEncoder().encode(e),n=0;for(let o of r)n=(n*223+o)%2**32;return n}function qe(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 Nf(e)}function fa(e){let t=BigInt(e);if(e<=0)throw new RangeError("Input must be positive");return t.toString(2).length-1}function ji(e){let t=BigInt(e);if(e<0)throw new RangeError("Input must be non-negative");return BigInt(1)<<t}function Fl(){throw new Error("unexpected end of buffer")}function Pr(e,t){return e.byteLength<t&&Fl(),e.read(t)}function Fr(e){let t=e.readUint8();return t===void 0&&Fl(),t}function ie(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:fa(e))+1,r=new wt(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 ge(e){let t=BigInt(1),r=BigInt(0),n;do n=Fr(e),r+=BigInt(n&127).valueOf()*t,t*=BigInt(128);while(n>=128);return r}function xe(e){typeof e=="number"&&(e=BigInt(e));let t=e<BigInt(0);t&&(e=-e-BigInt(1));let r=(e===BigInt(0)?0:fa(e))+1,n=new wt(new Uint8Array(r),0);for(;;){let i=o(e);if(e/=BigInt(128),t&&e===BigInt(0)&&(i&64)!==0||!t&&e===BigInt(0)&&(i&64)===0){n.write(new Uint8Array([i]));break}else n.write(new Uint8Array([i|128]))}function o(i){let s=i%BigInt(128);return Number(t?BigInt(128)-s-BigInt(1):s)}return n.buffer}function ir(e){let t=new Uint8Array(e.buffer),r=0;for(;r<t.byteLength;r++)if(t[r]<128){if((t[r]&64)===0)return ge(e);break}let n=new Uint8Array(Pr(e,r+1)),o=BigInt(0);for(let i=n.byteLength-1;i>=0;i--)o=o*BigInt(128)+BigInt(128-(n[i]&127)-1);return-o-BigInt(1)}function Pl(e,t){if(BigInt(e)<BigInt(0))throw new Error("Cannot write negative values.");return ha(e,t)}function ha(e,t){e=BigInt(e);let r=new wt(new Uint8Array(Math.min(1,t)),0),n=0,o=BigInt(256),i=BigInt(0),s=Number(e%o);for(r.write(new Uint8Array([s]));++n<t;)e<0&&i===BigInt(0)&&s!==0&&(i=BigInt(1)),s=Number((e/o-i)%BigInt(256)),r.write(new Uint8Array([s])),o*=BigInt(256);return r.buffer}function ma(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=BigInt(Fr(e)),n=BigInt(1),o=0;for(;++o<t;){n*=BigInt(256);let i=BigInt(Fr(e));r=r+n*i}return r}function Vl(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=ma(e,t),n=BigInt(2)**(BigInt(8)*BigInt(t-1)+BigInt(7));return r>=n&&(r-=n*BigInt(2)),r}var Q;(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"})(Q||(Q={}));var Ki="DIDL",Of=new TextEncoder().encode(Ki),Bl=400;function Co(e,t,r){return e.map((n,o)=>r(n,t[o]))}var ya=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 i=this._getIdxRefCount(n),s=this._getIdxRefCount(o);this._idxRefCount.set(n,i+s),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=ie(this._typs.length),r=Z(...this._typs);return Z(t,r)}indexOf(t){if(!this._idx.has(t))throw new Error("Missing type index for "+t);return xe(this._idx.get(t)||0)}},ga=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((i,s)=>[`_${s}_`,i]);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)}},H;(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__"})(H||(H={}));var Jn=class{display(){return this.name}valueToString(t){return _e(t)}buildTypeTable(t){t.has(this)||this._buildTypeTableImpl(t)}},ze=class extends Jn{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 Jn{checkType(t){if(t instanceof lt){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)}},Fo=class extends ze{get typeName(){return H.EmptyClass}static[Symbol.hasInstance](t){return t.typeName===H.EmptyClass}accept(t,r){return t.visitEmpty(this,r)}covariant(t){throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(){throw new Error("Empty cannot appear as a function argument")}valueToString(){throw new Error("Empty cannot appear as a value")}encodeType(){return xe(Q.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}},$i=class extends Jn{get typeName(){return H.UnknownClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(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 lt?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"}},Gi=class extends ze{get typeName(){return H.BoolClass}static[Symbol.hasInstance](t){return t.typeName===H.BoolClass}accept(t,r){return t.visitBool(this,r)}covariant(t){if(typeof t=="boolean")return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){return new Uint8Array([t?1:0])}encodeType(){return xe(Q.Bool)}decodeValue(t,r){switch(this.checkType(r),Fr(t)){case 0:return!1;case 1:return!0;default:throw new Error("Boolean value out of range")}}get name(){return"bool"}},On=class extends ze{get typeName(){return H.NullClass}static[Symbol.hasInstance](t){return t.typeName===H.NullClass}accept(t,r){return t.visitNull(this,r)}covariant(t){if(t===null)return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(){return new Uint8Array(0)}encodeType(){return xe(Q.Null)}decodeValue(t,r){return this.checkType(r),null}get name(){return"null"}},Bt=class extends ze{get typeName(){return H.ReservedClass}static[Symbol.hasInstance](t){return t.typeName===H.ReservedClass}accept(t,r){return t.visitReserved(this,r)}covariant(t){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return xe(Q.Reserved)}decodeValue(t,r){return r.name!==this.name&&r.decodeValue(t,r),null}get name(){return"reserved"}},Ji=class extends ze{get typeName(){return H.TextClass}static[Symbol.hasInstance](t){return t.typeName===H.TextClass}accept(t,r){return t.visitText(this,r)}covariant(t){if(typeof t=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){let r=new TextEncoder().encode(t),n=ie(r.byteLength);return Z(n,r)}encodeType(){return xe(Q.Text)}decodeValue(t,r){this.checkType(r);let n=ge(t),o=Pr(t,Number(n));return new TextDecoder("utf8",{fatal:!0}).decode(o)}get name(){return"text"}valueToString(t){return'"'+t+'"'}},Po=class extends ze{get typeName(){return H.IntClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(t)}`)}encodeValue(t){return xe(t)}encodeType(){return xe(Q.Int)}decodeValue(t,r){return this.checkType(r),ir(t)}get name(){return"int"}valueToString(t){return t.toString()}},Vo=class extends ze{get typeName(){return H.NatClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(t)}`)}encodeValue(t){return ie(t)}encodeType(){return xe(Q.Nat)}decodeValue(t,r){return this.checkType(r),ge(t)}get name(){return"nat"}valueToString(t){return t.toString()}},Bo=class extends ze{get typeName(){return H.FloatClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(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?Q.Float32:Q.Float64;return xe(t)}decodeValue(t,r){this.checkType(r);let n=Pr(t,this._bits/8),o=Cl(n);return this._bits===32?o.getFloat32(0,!0):o.getFloat64(0,!0)}get name(){return"float"+this._bits}valueToString(t){return t.toString()}},ar=class extends ze{get typeName(){return H.FixedIntClass}static[Symbol.hasInstance](t){return t.typeName===H.FixedIntClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedInt(this,r)}covariant(t){let r=ji(this._bits-1)*BigInt(-1),n=ji(this._bits-1)-BigInt(1),o=!1;if(typeof t=="bigint")o=t>=r&&t<=n;else if(Number.isInteger(t)){let i=BigInt(t);o=i>=r&&i<=n}else o=!1;if(o)return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){return ha(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return xe(-9-t)}decodeValue(t,r){this.checkType(r);let n=Vl(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(t){return t.toString()}},Pt=class extends ze{get typeName(){return H.FixedNatClass}static[Symbol.hasInstance](t){return t.typeName===H.FixedNatClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedNat(this,r)}covariant(t){let r=ji(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: ${_e(t)}`)}encodeValue(t){return Pl(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return xe(-5-t)}decodeValue(t,r){this.checkType(r);let n=ma(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(t){return t.toString()}},Wn=class e extends Vt{get typeName(){return H.VecClass}static[Symbol.hasInstance](t){return t.typeName===H.VecClass}constructor(t){super(),this._type=t,this._blobOptimization=!1,t instanceof Pt&&t._bits===8&&(this._blobOptimization=!0)}accept(t,r){return t.visitVec(this,this._type,r)}covariant(t){let r=this._type instanceof Pt?this._type._bits:this._type instanceof ar?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(i){throw new Error(`Invalid ${this.display()} argument:
37
37
 
38
- index ${o} -> ${i.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){let r=oe(t.length);if(this._blobOptimization)return Z(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 i=0;i<t.length;i++)t instanceof Int16Array?o.setInt16(i*2,t[i],!0):o.setUint16(i*2,t[i],!0);return Z(r,new Uint8Array(o.buffer))}else if(t instanceof Int32Array||t instanceof Uint32Array){let o=new DataView(new ArrayBuffer(t.length*4));for(let i=0;i<t.length;i++)t instanceof Int32Array?o.setInt32(i*4,t[i],!0):o.setUint32(i*4,t[i],!0);return Z(r,new Uint8Array(o.buffer))}else if(t instanceof BigInt64Array||t instanceof BigUint64Array){let o=new DataView(new ArrayBuffer(t.length*8));for(let i=0;i<t.length;i++)t instanceof BigInt64Array?o.setBigInt64(i*8,t[i],!0):o.setBigUint64(i*8,t[i],!0);return Z(r,new Uint8Array(o.buffer))}else return Z(r,new Uint8Array(t.buffer,t.byteOffset,t.byteLength));let n=new wt(new Uint8Array(r.byteLength+t.length),0);n.write(r);for(let o of t){let i=this._type.encodeValue(o);n.write(new Uint8Array(i))}return n.buffer}_buildTypeTableImpl(t){this._type.buildTypeTable(t);let r=xe(Q.Vector),n=this._type.encodeType(t);t.add(this,Z(r,n))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a vector type");let o=Number(ge(t));if(this._type instanceof Vt){if(this._type._bits==8)return new Uint8Array(t.read(o));if(this._type._bits==16){let s=t.read(o*2);return new Uint16Array(s.buffer,s.byteOffset,o)}if(this._type._bits==32){let s=t.read(o*4);return new Uint32Array(s.buffer,s.byteOffset,o)}if(this._type._bits==64)return new BigUint64Array(t.read(o*8).buffer)}if(this._type instanceof tr){if(this._type._bits==8)return new Int8Array(t.read(o));if(this._type._bits==16){let s=t.read(o*2),a=new DataView(s.buffer,s.byteOffset,s.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 s=t.read(o*4),a=new DataView(s.buffer,s.byteOffset,s.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 s=t.read(o*8),a=new DataView(s.buffer,s.byteOffset,s.byteLength),c=new BigInt64Array(o);for(let u=0;u<o;u++)c[u]=a.getBigInt64(u*8,!0);return c}}let i=[];for(let s=0;s<o;s++)i.push(this._type.decodeValue(t,n._type));return i}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("; ")+"}"}},vr=class e extends Pt{get typeName(){return H.OptClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(t)}
38
+ index ${o} -> ${i.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){let r=ie(t.length);if(this._blobOptimization)return Z(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 i=0;i<t.length;i++)t instanceof Int16Array?o.setInt16(i*2,t[i],!0):o.setUint16(i*2,t[i],!0);return Z(r,new Uint8Array(o.buffer))}else if(t instanceof Int32Array||t instanceof Uint32Array){let o=new DataView(new ArrayBuffer(t.length*4));for(let i=0;i<t.length;i++)t instanceof Int32Array?o.setInt32(i*4,t[i],!0):o.setUint32(i*4,t[i],!0);return Z(r,new Uint8Array(o.buffer))}else if(t instanceof BigInt64Array||t instanceof BigUint64Array){let o=new DataView(new ArrayBuffer(t.length*8));for(let i=0;i<t.length;i++)t instanceof BigInt64Array?o.setBigInt64(i*8,t[i],!0):o.setBigUint64(i*8,t[i],!0);return Z(r,new Uint8Array(o.buffer))}else return Z(r,new Uint8Array(t.buffer,t.byteOffset,t.byteLength));let n=new wt(new Uint8Array(r.byteLength+t.length),0);n.write(r);for(let o of t){let i=this._type.encodeValue(o);n.write(new Uint8Array(i))}return n.buffer}_buildTypeTableImpl(t){this._type.buildTypeTable(t);let r=xe(Q.Vector),n=this._type.encodeType(t);t.add(this,Z(r,n))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a vector type");let o=Number(ge(t));if(this._type instanceof Pt){if(this._type._bits==8)return new Uint8Array(t.read(o));if(this._type._bits==16){let s=t.read(o*2);return new Uint16Array(s.buffer,s.byteOffset,o)}if(this._type._bits==32){let s=t.read(o*4);return new Uint32Array(s.buffer,s.byteOffset,o)}if(this._type._bits==64)return new BigUint64Array(t.read(o*8).buffer)}if(this._type instanceof ar){if(this._type._bits==8)return new Int8Array(t.read(o));if(this._type._bits==16){let s=t.read(o*2),a=new DataView(s.buffer,s.byteOffset,s.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 s=t.read(o*4),a=new DataView(s.buffer,s.byteOffset,s.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 s=t.read(o*8),a=new DataView(s.buffer,s.byteOffset,s.byteLength),c=new BigInt64Array(o);for(let u=0;u<o;u++)c[u]=a.getBigInt64(u*8,!0);return c}}let i=[];for(let s=0;s<o;s++)i.push(this._type.decodeValue(t,n._type));return i}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("; ")+"}"}},Vr=class e extends Vt{get typeName(){return H.OptClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(t)}
39
39
 
40
- -> ${r.message}`)}throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){return t.length===0?new Uint8Array([0]):Z(new Uint8Array([1]),this._type.encodeValue(t[0]))}_buildTypeTableImpl(t){this._type.buildTypeTable(t);let r=xe(Q.Opt),n=this._type.encodeType(t);t.add(this,Z(r,n))}decodeValue(t,r){if(r instanceof bn)return[];if(r instanceof Bt)return[];let n=r;if(r instanceof st){let o=r.getType();if(typeof o>"u")throw new Error("type mismatch with uninitialized type");n=o}if(n instanceof e)switch(Rr(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 bn||this._type instanceof e||this._type instanceof Bt)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])}`}},wn=class e extends Pt{get typeName(){return H.RecordClass}static[Symbol.hasInstance](t){return t.typeName===H.RecordClass||t.typeName===H.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:
40
+ -> ${r.message}`)}throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){return t.length===0?new Uint8Array([0]):Z(new Uint8Array([1]),this._type.encodeValue(t[0]))}_buildTypeTableImpl(t){this._type.buildTypeTable(t);let r=xe(Q.Opt),n=this._type.encodeType(t);t.add(this,Z(r,n))}decodeValue(t,r){if(r instanceof On)return[];if(r instanceof Bt)return[];let n=r;if(r instanceof lt){let o=r.getType();if(typeof o>"u")throw new Error("type mismatch with uninitialized type");n=o}if(n instanceof e)switch(Fr(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 On||this._type instanceof e||this._type instanceof Bt)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])}`}},En=class e extends Vt{get typeName(){return H.RecordClass}static[Symbol.hasInstance](t){return t.typeName===H.RecordClass||t.typeName===H.TupleClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((r,n)=>qe(r[0])-qe(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: ${_e(t)}`)}encodeValue(t){let r=this._fields.map(([o])=>t[o]),n=vo(this._fields,r,([,o],i)=>o.encodeValue(i));return Z(...n)}_buildTypeTableImpl(t){this._fields.forEach(([i,s])=>s.buildTypeTable(t));let r=xe(Q.Record),n=oe(this._fields.length),o=this._fields.map(([i,s])=>Z(oe(Le(i)),s.encodeType(t)));t.add(this,Z(r,n,Z(...o)))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a record type");let o={},i=0,s=0;for(;s<n._fields.length;){let[a,c]=n._fields[s];if(i>=this._fields.length){c.decodeValue(t,c),s++;continue}let[u,p]=this._fields[i],d=Le(this._fields[i][0]),l=Le(a);if(d===l)o[u]=p.decodeValue(t,c),i++,s++;else if(l>d)if(p instanceof vr||p instanceof Bt)o[u]=[],i++;else throw new Error("Cannot find required field "+u);else c.decodeValue(t,c),s++}for(let[a,c]of this._fields.slice(i))if(c instanceof vr||c instanceof Bt)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 {${vo(this._fields,r,([o,i],s)=>o+"="+i.valueToString(s)).join("; ")}}`}},$i=class e extends wn{get typeName(){return H.TupleClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(t)}`)}encodeValue(t){let r=this._fields.map(([o])=>t[o]),n=Co(this._fields,r,([,o],i)=>o.encodeValue(i));return Z(...n)}_buildTypeTableImpl(t){this._fields.forEach(([i,s])=>s.buildTypeTable(t));let r=xe(Q.Record),n=ie(this._fields.length),o=this._fields.map(([i,s])=>Z(ie(qe(i)),s.encodeType(t)));t.add(this,Z(r,n,Z(...o)))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a record type");let o={},i=0,s=0;for(;s<n._fields.length;){let[a,c]=n._fields[s];if(i>=this._fields.length){c.decodeValue(t,c),s++;continue}let[u,p]=this._fields[i],d=qe(this._fields[i][0]),l=qe(a);if(d===l)o[u]=p.decodeValue(t,c),i++,s++;else if(l>d)if(p instanceof Vr||p instanceof Bt)o[u]=[],i++;else throw new Error("Cannot find required field "+u);else c.decodeValue(t,c),s++}for(let[a,c]of this._fields.slice(i))if(c instanceof Vr||c instanceof Bt)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[qe(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 {${Co(this._fields,r,([o,i],s)=>o+"="+i.valueToString(s)).join("; ")}}`}},Wi=class e extends En{get typeName(){return H.TupleClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(t)}`)}encodeValue(t){let r=vo(this._components,t,(n,o)=>n.encodeValue(o));return Z(...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[i,s]of n._components.entries())i>=this._components.length?s.decodeValue(t,s):o.push(this._components[i].decodeValue(t,s));return o}display(){return`record {${this._components.map(r=>r.display()).join("; ")}}`}valueToString(t){return`record {${vo(this._components,t,(n,o)=>n.valueToString(o)).join("; ")}}`}},Hn=class e extends Pt{get typeName(){return H.VariantClass}static[Symbol.hasInstance](t){return t.typeName===H.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:
44
+ index ${n} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){let r=Co(this._components,t,(n,o)=>n.encodeValue(o));return Z(...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[i,s]of n._components.entries())i>=this._components.length?s.decodeValue(t,s):o.push(this._components[i].decodeValue(t,s));return o}display(){return`record {${this._components.map(r=>r.display()).join("; ")}}`}valueToString(t){return`record {${Co(this._components,t,(n,o)=>n.valueToString(o)).join("; ")}}`}},zn=class e extends Vt{get typeName(){return H.VariantClass}static[Symbol.hasInstance](t){return t.typeName===H.VariantClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((r,n)=>qe(r[0])-qe(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: ${_e(t)}`)}encodeValue(t){for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(t.hasOwnProperty(n)){let i=oe(r),s=o.encodeValue(t[n]);return Z(i,s)}}throw Error("Variant has no data: "+t)}_buildTypeTableImpl(t){this._fields.forEach(([,i])=>{i.buildTypeTable(t)});let r=xe(Q.Variant),n=oe(this._fields.length),o=this._fields.map(([i,s])=>Z(oe(Le(i)),s.encodeType(t)));t.add(this,Z(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(ge(t));if(o>=n._fields.length)throw Error("Invalid variant index: "+o);let[i,s]=n._fields[o];for(let[a,c]of this._fields)if(Le(i)===Le(a)){let u=c.decodeValue(t,s);return{[a]:u}}throw new Error("Cannot find field hash "+i)}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}},st=class e extends Pt{constructor(){super(...arguments),this._id=e._counter++}get typeName(){return H.RecClass}static{this._counter=0}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(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 sa(e){if(Rr(e)!==1)throw new Error("Cannot decode principal");let r=Number(ge(e));return k.fromUint8Array(new Uint8Array(Ir(e,r)))}var Gi=class extends We{get typeName(){return H.PrincipalClass}static[Symbol.hasInstance](t){return t.typeName===H.PrincipalClass}accept(t,r){return t.visitPrincipal(this,r)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){let r=t.toUint8Array(),n=oe(r.byteLength);return Z(new Uint8Array([1]),n,r)}encodeType(){return xe(Q.Principal)}decodeValue(t,r){return this.checkType(r),sa(t)}get name(){return"principal"}valueToString(t){return`${this.name} "${t.toText()}"`}},Tn=class extends Pt{get typeName(){return H.FuncClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(t)}`)}encodeValue([t,r]){let n=t.toUint8Array(),o=oe(n.byteLength),i=Z(new Uint8Array([1]),o,n),s=new TextEncoder().encode(r),a=oe(s.byteLength);return Z(new Uint8Array([1]),i,a,s)}_buildTypeTableImpl(t){this.argTypes.forEach(u=>u.buildTypeTable(t)),this.retTypes.forEach(u=>u.buildTypeTable(t));let r=xe(Q.Func),n=oe(this.argTypes.length),o=Z(...this.argTypes.map(u=>u.encodeType(t))),i=oe(this.retTypes.length),s=Z(...this.retTypes.map(u=>u.encodeType(t))),a=oe(this.annotations.length),c=Z(...this.annotations.map(u=>this.encodeAnnotation(u)));t.add(this,Z(r,n,o,i,s,a,c))}decodeValue(t,r){let n=r instanceof st?r.getType()??r:r;if(!aa(n,this))throw new Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if(Rr(t)!==1)throw new Error("Cannot decode function reference");let i=sa(t),s=Number(ge(t)),a=Ir(t,s),u=new TextDecoder("utf8",{fatal:!0}).decode(a);return[i,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")}},$n=class extends Pt{get typeName(){return H.ServiceClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(t)}`)}encodeValue(t){let r=t.toUint8Array(),n=oe(r.length);return Z(new Uint8Array([1]),n,r)}_buildTypeTableImpl(t){this._fields.forEach(([i,s])=>s.buildTypeTable(t));let r=xe(Q.Service),n=oe(this._fields.length),o=this._fields.map(([i,s])=>{let a=new TextEncoder().encode(i),c=oe(a.length);return Z(c,a,s.encodeType(t))});t.add(this,Z(r,n,...o))}decodeValue(t,r){let n=r instanceof st?r.getType()??r:r;if(!aa(n,this))throw new Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return sa(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 _e(e){let t=JSON.stringify(e,(r,n)=>typeof n=="bigint"?`BigInt(${n})`:n);return t&&t.length>Tl?t.substring(0,Tl-3)+"...":t}function uf(e,t){if(t.length<e.length)throw Error("Wrong number of message arguments");let r=new na;e.forEach(a=>a.buildTypeTable(r));let n=r.encode(),o=oe(t.length),i=Z(...e.map(a=>a.encodeType(r))),s=Z(...vo(e,t,(a,c)=>{try{a.covariant(c)}catch(u){throw new Error(u.message+`
46
+ variant ${r} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(t.hasOwnProperty(n)){let i=ie(r),s=o.encodeValue(t[n]);return Z(i,s)}}throw Error("Variant has no data: "+t)}_buildTypeTableImpl(t){this._fields.forEach(([,i])=>{i.buildTypeTable(t)});let r=xe(Q.Variant),n=ie(this._fields.length),o=this._fields.map(([i,s])=>Z(ie(qe(i)),s.encodeType(t)));t.add(this,Z(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(ge(t));if(o>=n._fields.length)throw Error("Invalid variant index: "+o);let[i,s]=n._fields[o];for(let[a,c]of this._fields)if(qe(i)===qe(a)){let u=c.decodeValue(t,s);return{[a]:u}}throw new Error("Cannot find field hash "+i)}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[qe(r)]=n;return t}},lt=class e extends Vt{constructor(){super(...arguments),this._id=e._counter++}get typeName(){return H.RecClass}static{this._counter=0}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(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 ba(e){if(Fr(e)!==1)throw new Error("Cannot decode principal");let r=Number(ge(e));return U.fromUint8Array(new Uint8Array(Pr(e,r)))}var zi=class extends ze{get typeName(){return H.PrincipalClass}static[Symbol.hasInstance](t){return t.typeName===H.PrincipalClass}accept(t,r){return t.visitPrincipal(this,r)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${_e(t)}`)}encodeValue(t){let r=t.toUint8Array(),n=ie(r.byteLength);return Z(new Uint8Array([1]),n,r)}encodeType(){return xe(Q.Principal)}decodeValue(t,r){return this.checkType(r),ba(t)}get name(){return"principal"}valueToString(t){return`${this.name} "${t.toText()}"`}},Rn=class extends Vt{get typeName(){return H.FuncClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(t)}`)}encodeValue([t,r]){let n=t.toUint8Array(),o=ie(n.byteLength),i=Z(new Uint8Array([1]),o,n),s=new TextEncoder().encode(r),a=ie(s.byteLength);return Z(new Uint8Array([1]),i,a,s)}_buildTypeTableImpl(t){this.argTypes.forEach(u=>u.buildTypeTable(t)),this.retTypes.forEach(u=>u.buildTypeTable(t));let r=xe(Q.Func),n=ie(this.argTypes.length),o=Z(...this.argTypes.map(u=>u.encodeType(t))),i=ie(this.retTypes.length),s=Z(...this.retTypes.map(u=>u.encodeType(t))),a=ie(this.annotations.length),c=Z(...this.annotations.map(u=>this.encodeAnnotation(u)));t.add(this,Z(r,n,o,i,s,a,c))}decodeValue(t,r){let n=r instanceof lt?r.getType()??r:r;if(!wa(n,this))throw new Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if(Fr(t)!==1)throw new Error("Cannot decode function reference");let i=ba(t),s=Number(ge(t)),a=Pr(t,s),u=new TextDecoder("utf8",{fatal:!0}).decode(a);return[i,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")}},Yn=class extends Vt{get typeName(){return H.ServiceClass}static[Symbol.hasInstance](t){return t.typeName===H.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: ${_e(t)}`)}encodeValue(t){let r=t.toUint8Array(),n=ie(r.length);return Z(new Uint8Array([1]),n,r)}_buildTypeTableImpl(t){this._fields.forEach(([i,s])=>s.buildTypeTable(t));let r=xe(Q.Service),n=ie(this._fields.length),o=this._fields.map(([i,s])=>{let a=new TextEncoder().encode(i),c=ie(a.length);return Z(c,a,s.encodeType(t))});t.add(this,Z(r,n,...o))}decodeValue(t,r){let n=r instanceof lt?r.getType()??r:r;if(!wa(n,this))throw new Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return ba(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 _e(e){let t=JSON.stringify(e,(r,n)=>typeof n=="bigint"?`BigInt(${n})`:n);return t&&t.length>Bl?t.substring(0,Bl-3)+"...":t}function Ef(e,t){if(t.length<e.length)throw Error("Wrong number of message arguments");let r=new ya;e.forEach(a=>a.buildTypeTable(r));let n=r.encode(),o=ie(t.length),i=Z(...e.map(a=>a.encodeType(r))),s=Z(...Co(e,t,(a,c)=>{try{a.covariant(c)}catch(u){throw new Error(u.message+`
47
47
 
48
- `)}return a.encodeValue(c)}));return Z(lf,n,o,i,s)}function df(e,t){let r=new wt(t);if(t.byteLength<qi.length)throw new Error("Message length smaller than magic number");let n=Ir(r,qi.length),o=new TextDecoder().decode(n);if(o!==qi)throw new Error("Wrong magic number: "+JSON.stringify(o));function i(l){let f=[],h=Number(ge(l));for(let m=0;m<h;m++){let x=Number(Qt(l));switch(x){case Q.Opt:case Q.Vector:{let y=Number(Qt(l));f.push([x,y]);break}case Q.Record:case Q.Variant:{let y=[],T=Number(ge(l)),E;for(;T--;){let O=Number(ge(l));if(O>=Math.pow(2,32))throw new Error("field id out of 32-bit range");if(typeof E=="number"&&E>=O)throw new Error("field id collision or not sorted");E=O;let R=Number(Qt(l));y.push([O,R])}f.push([x,y]);break}case Q.Func:{let y=[],T=Number(ge(l));for(;T--;)y.push(Number(Qt(l)));let E=[],O=Number(ge(l));for(;O--;)E.push(Number(Qt(l)));let R=[],v=Number(ge(l));for(;v--;)switch(Number(ge(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,[y,E,R]]);break}case Q.Service:{let y=Number(ge(l)),T=[];for(;y--;){let E=Number(ge(l)),O=new TextDecoder().decode(Ir(l,E)),R=Qt(l);T.push([O,R])}f.push([x,T]);break}default:throw new Error("Illegal op_code: "+x)}}let _=[],g=Number(ge(l));for(let m=0;m<g;m++)_.push(Number(Qt(l)));return[f,_]}let[s,a]=i(r);if(a.length<e.length)throw new Error("Wrong number of return values");let c=s.map(l=>Gl());function u(l){if(l<-24)throw new Error("future value not supported");if(l<0)switch(l){case-1:return Rl;case-2:return El;case-3:return Al;case-4:return vl;case-5:return Dl;case-6:return Ul;case-7:return kl;case-8:return Ll;case-9:return Fl;case-10:return Vl;case-11:return Pl;case-12:return Bl;case-13:return Sl;case-14:return Cl;case-15:return Il;case-16:return Ol;case-17:return Nl;case-24:return ql;default:throw new Error("Illegal op_code: "+l)}if(l>=s.length)throw new Error("type index out of range");return c[l]}function p(l){switch(l[0]){case Q.Vector:{let f=u(l[1]);return jl(f)}case Q.Opt:{let f=u(l[1]);return Kl(f)}case Q.Record:{let f={};for(let[g,m]of l[1]){let x=`_${g}_`;f[x]=u(m)}let h=Hl(f),_=h.tryAsTuple();return Array.isArray(_)?Ml(..._):h}case Q.Variant:{let f={};for(let[h,_]of l[1]){let g=`_${h}_`;f[g]=u(_)}return $l(f)}case Q.Func:{let[f,h,_]=l[1];return Jl(f.map(g=>u(g)),h.map(g=>u(g)),_)}case Q.Service:{let f={},h=l[1];for(let[_,g]of h){let m=u(g);if(m instanceof st&&(m=m.getType()),!(m instanceof Tn))throw new Error("Illegal service definition: services can only contain functions");f[_]=m}return Wl(f)}default:throw new Error("Illegal op_code: "+l[0])}}s.forEach((l,f)=>{if(l[0]===Q.Func){let h=p(l);c[f].fill(h)}}),s.forEach((l,f)=>{if(l[0]!==Q.Func){let h=p(l);c[f].fill(h)}}),ia();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{ia()}}var Nl=new Ao,Ol=new Bt,pf=new ji,El=new Ki,Rl=new bn,Il=new Hi,vl=new So,Al=new Co,Sl=new Fo(32),Cl=new Fo(64),Fl=new tr(8),Vl=new tr(16),Pl=new tr(32),Bl=new tr(64),Dl=new Vt(8),Ul=new Vt(16),kl=new Vt(32),Ll=new Vt(64),ql=new Gi;function Ml(...e){return new $i(e)}function jl(e){return new Kn(e)}function Kl(e){return new vr(e)}function Hl(e){return new wn(e)}function $l(e){return new Hn(e)}function Gl(){return new st}function Jl(e,t,r=[]){return new Tn(e,t,r)}function Wl(e){return new $n(e)}var Ji=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,i]of n)t+=`${r} ${i?":<":"!<:"} ${o}
49
- `;return t}addNames(t,r,n){let o=this.rels.get(t);if(o==null){let i=new Map;i.set(r,n),this.rels.set(t,i)}else o.set(r,n)}},Mi=new Ji;function ia(){Mi=new Ji}function ff(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 ra(e){return e instanceof vr||e instanceof bn||e instanceof Bt}function aa(e,t){let r=Mi.copy(),n=er(r,e,t);return n?Mi.add(e,t):Mi.addNegative(e,t),n}function er(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 Bt||t instanceof Ao||t instanceof Co&&r instanceof So)return!0;if(t instanceof Kn&&r instanceof Kn)return er(e,t._type,r._type);if(r instanceof vr)return!0;if(t instanceof wn&&r instanceof wn){let o=t.fieldsAsObject;for(let[i,s]of r._fields){let a=o[Le(i)];if(a){if(!er(e,a,s))return!1}else if(!ra(s))return!1}return!0}if(t instanceof Tn&&r instanceof Tn){if(!ff(t,r))return!1;for(let o=0;o<t.argTypes.length;o++){let i=t.argTypes[o];if(o<r.argTypes.length){if(!er(e,r.argTypes[o],i))return!1}else if(!ra(i))return!1}for(let o=0;o<r.retTypes.length;o++){let i=r.retTypes[o];if(o<t.retTypes.length){if(!er(e,t.retTypes[o],i))return!1}else if(!ra(i))return!1}return!0}if(t instanceof Hn&&r instanceof Hn){let o=r.alternativesAsObject;for(let[i,s]of t._fields){let a=o[Le(i)];if(!a||!er(e,s,a))return!1}return!0}if(t instanceof $n&&r instanceof $n){let o=t.fieldsAsObject();for(let[i,s]of r._fields){let a=o[i];if(!a||!er(e,a,s))return!1}return!0}return t instanceof st?er(e,t.getType(),r):r instanceof st?er(e,t,r.getType()):!1}function Gn(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?Gn(e.buffer):new Uint8Array(e)}function On(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 ca(e){if(typeof e=="string")return zl(e);if(typeof e=="number")return Ve(oe(e));if(e instanceof Uint8Array||ArrayBuffer.isView(e))return Ve(Gn(e));if(Array.isArray(e)){let t=e.map(ca);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 ca(e.toHash());if(typeof e=="object")return Vo(e);if(typeof e=="bigint")return Ve(oe(e))}throw Y.fromCode(new Fi(e))}var zl=e=>{let t=new TextEncoder().encode(e);return Ve(t)};function rr(e){return Vo(e)}function Vo(e){let n=Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>{let c=zl(s),u=ca(a);return[c,u]}).sort(([s],[a])=>Mn(s,a)),o=K(...n.map(s=>K(...s)));return Ve(o)}var la=new TextEncoder().encode("\ric-state-root"),Po=new TextEncoder().encode(`
50
- ic-request`),ua=new TextEncoder().encode("\vic-response"),da=new TextEncoder().encode("ic-request-auth-delegation");var Dt=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=rr(r);return{...n,body:{content:r,sender_pubkey:this.getPublicKey().toDer(),sender_sig:await this.sign(K(Po,o))}}}},tt=class{getPrincipal(){return k.anonymous()}async transformRequest(t){return{...t,body:{content:t.body}}}};var nr=class extends Error{constructor(t){super(t),this.name="DecodingError"}},Zl=55799,Xl=Symbol("CBOR_STOP_CODE"),Ot=(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))(Ot||{}),Ne=(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))(Ne||{}),hf=23,mf=255,_f=65535,yf=4294967295,gf=BigInt("0xffffffffffffffff"),Nt=(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))(Nt||{}),Jn=!1;function xf(e){return e==null}function Ql(e,t){let r=new Uint8Array(t);return r.set(e),r}var bf=new TextDecoder;function wf(e){return(e&224)>>5}function Tf(e){return e&31}var Uo=new Uint8Array,Bo,Et=0;function eu(e,t){Uo=e,Et=0;let r=En(t);return t?.(r)??r}function En(e){let[t,r]=Wi();switch(t){case Ne.UnsignedInteger:return Wn(r);case Ne.NegativeInteger:return Rf(r);case Ne.ByteString:return tu(r);case Ne.TextString:return fa(r);case Ne.Array:return Nf(r,e);case Ne.Map:return Ef(r,e);case Ne.Tag:return If(r,e);case Ne.Simple:return Of(r)}throw new nr(`Unsupported major type: ${t}`)}function Wi(){let e=Uo.at(Et);if(xf(e))throw new nr("Provided CBOR data is empty");let t=wf(e),r=Tf(e);return Et++,[t,r]}function Nf(e,t){let r=Wn(e);if(r===1/0){let o=[],i=En(t);for(;i!==Xl;)o.push(t?.(i)??i),i=En(t);return o}let n=new Array(r);for(let o=0;o<r;o++){let i=En(t);n[o]=t?.(i)??i}return n}function Of(e){switch(e){case Ot.False:return!1;case Ot.True:return!0;case Ot.Null:return null;case Ot.Undefined:return;case Ot.Break:return Xl}throw new nr(`Unrecognized simple type: ${e.toString(2)}`)}function Ef(e,t){let r=Wn(e),n={};if(r===1/0){let[o,i]=Wi();for(;o!==Ne.Simple&&i!==Ot.Break;){let s=fa(i),a=En(t);n[s]=t?.(a,s)??a,[o,i]=Wi()}return n}for(let o=0;o<r;o++){let[i,s]=Wi();if(i!==Ne.TextString)throw new nr("Map keys must be text strings");let a=fa(s),c=En(t);n[a]=t?.(c,a)??c}return n}function Wn(e){if(e<=Nt.Value)return e;switch(Bo=new DataView(Uo.buffer,Uo.byteOffset+Et),e){case Nt.OneByte:return Et++,Bo.getUint8(0);case Nt.TwoBytes:return Et+=2,Bo.getUint16(0,Jn);case Nt.FourBytes:return Et+=4,Bo.getUint32(0,Jn);case Nt.EightBytes:return Et+=8,Bo.getBigUint64(0,Jn);case Nt.Indefinite:return 1/0;default:throw new nr(`Unsupported integer info: ${e.toString(2)}`)}}function Rf(e){let t=Wn(e);return typeof t=="number"?-1-t:-1n-t}function tu(e){let t=Wn(e);if(t>Number.MAX_SAFE_INTEGER)throw new nr("Byte length is too large");let r=Number(t);return Et+=r,Uo.slice(Et-r,Et)}function fa(e){let t=tu(e);return bf.decode(t)}function If(e,t){let r=Wn(e);if(r===Zl)return En(t);throw new nr(`Unsupported tag: ${r}.`)}var ko=class extends Error{constructor(t){super(t),this.name="SerializationError"}},vf=2*1024,Af=100,Sf=new TextEncoder;function Do(e){return e<<5}var rt=new Uint8Array(vf),Tt=new DataView(rt.buffer),Te=0,pa=[];function ru(e,t){Te=0;let r=t?.(e)??e;return kf(Zl,r,t),rt.slice(0,Te)}function ha(e,t){if(Te>rt.length-Af&&(rt=Ql(rt,rt.length*2),Tt=new DataView(rt.buffer)),e===!1||e===!0||e===null||e===void 0){Vf(e);return}if(typeof e=="number"||typeof e=="bigint"){Uf(e);return}if(typeof e=="string"){iu(e);return}if(e instanceof Uint8Array){Yl(e);return}if(e instanceof ArrayBuffer){Yl(new Uint8Array(e));return}if(Array.isArray(e)){Cf(e,t);return}if(typeof e=="object"){Ff(e,t);return}throw new ko(`Unsupported type: ${typeof e}`)}function Cf(e,t){zn(Ne.Array,e.length),e.forEach((r,n)=>{ha(t?.(r,n.toString())??r,t)})}function Ff(e,t){pa=Object.entries(e),zn(Ne.Map,pa.length),pa.forEach(([r,n])=>{iu(r),ha(t?.(n,r)??n,t)})}function zn(e,t){if(t<=hf){Tt.setUint8(Te++,Do(e)|Number(t));return}if(t<=mf){Tt.setUint8(Te++,Do(e)|Nt.OneByte),Tt.setUint8(Te,Number(t)),Te+=1;return}if(t<=_f){Tt.setUint8(Te++,Do(e)|Nt.TwoBytes),Tt.setUint16(Te,Number(t),Jn),Te+=2;return}if(t<=yf){Tt.setUint8(Te++,Do(e)|Nt.FourBytes),Tt.setUint32(Te,Number(t),Jn),Te+=4;return}if(t<=gf){Tt.setUint8(Te++,Do(e)|Nt.EightBytes),Tt.setBigUint64(Te,BigInt(t),Jn),Te+=8;return}throw new ko(`Value too large to encode: ${t}`)}function Vf(e){zn(Ne.Simple,Pf(e))}function Pf(e){if(e===!1)return Ot.False;if(e===!0)return Ot.True;if(e===null)return Ot.Null;if(e===void 0)return Ot.Undefined;throw new ko(`Unrecognized simple value: ${e.toString()}`)}function nu(e,t){zn(e,t.length),Te>rt.length-t.length&&(rt=Ql(rt,rt.length+t.length),Tt=new DataView(rt.buffer)),rt.set(t,Te),Te+=t.length}function ou(e,t){zn(e,t)}function Bf(e){ou(Ne.UnsignedInteger,e)}function Df(e){ou(Ne.NegativeInteger,typeof e=="bigint"?-1n-e:-1-e)}function Uf(e){e>=0?Bf(e):Df(e)}function iu(e){nu(Ne.TextString,Sf.encode(e))}function Yl(e){nu(Ne.ByteString,e)}function kf(e,t,r){zn(Ne.Tag,e),ha(t,r)}function qf(e){return typeof e=="object"&&e!==null&&"toCborValue"in e}function Lo(e){try{return ru(e,t=>k.isPrincipal(t)?t.toUint8Array():Yn.isExpiry(t)?t.toBigInt():qf(t)?t.toCborValue():t)}catch(t){throw Y.fromCode(new Ii(t,e))}}function qe(e){try{return eu(e)}catch(t){throw Y.fromCode(new Ri(t,e))}}var zi={encode:Lo,decode:qe};var qo=()=>{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 or;(function(e){e.Query="read",e.ReadState="read_state",e.Call="call"})(or||(or={}));var Zi;(function(e){e.Call="call"})(Zi||(Zi={}));var Rn;(function(e){e.Query="query",e.ReadState="read_state"})(Rn||(Rn={}));function Mo(){let e=new ArrayBuffer(16),t=new DataView(e),r=qo(),n=qo(),o=qo(),i=qo();return t.setUint32(0,r),t.setUint32(4,n),t.setUint32(8,o),t.setUint32(12,i),Object.assign(new Uint8Array(e),{__nonce__:void 0})}var Xi="__expiry__",ma=BigInt(1e3),Mf=BigInt(1e6),jf=BigInt(60),_a=jf*ma,Kf=BigInt(1)*_a;function Hf(e){return e/ma*ma}function $f(e){return e/_a*_a}var Yn=class e{constructor(t){this.__expiry__=t,this._isExpiry=!0}static fromDeltaInMilliseconds(t,r=0){let n=BigInt(Date.now())+BigInt(r),o=n+BigInt(t),i=$f(o),s;return i>=n+Kf?s=i:s=Hf(o),new e(s*Mf)}toBigInt(){return this.__expiry__}toHash(){return oe(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[Xi]:this.toString()}}static fromJSON(t){let r=JSON.parse(t);if(r[Xi])try{let n=BigInt(r[Xi]);return new e(n)}catch(n){throw new Y(new Ro(`Not a valid BigInt: ${n}`))}throw new Y(new Ro(`The input does not contain the key ${Xi}`))}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 ya(e=Mo){return async t=>{let r=t.request.headers;t.request.headers=r,t.endpoint===or.Call&&(t.body.nonce=e())}}function ga(e){let t=[];return e.forEach((r,n)=>{t.push([n,r])}),t}var ba=BigInt(0),Qi=BigInt(1);function In(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}"`;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function Ar(e,t,r=""){let n=At(e),o=e?.length,i=t!==void 0;if(!n||i&&o!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return e}function su(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?ba:BigInt("0x"+e)}function ze(e){return su(j(e))}function ir(e){return me(e),su(j(Uint8Array.from(e).reverse()))}function Oe(e,t){return Ee(e.toString(16).padStart(t*2,"0"))}function wa(e,t){return Oe(e,t).reverse()}function pe(e,t,r){let n;if(typeof t=="string")try{n=Ee(t)}catch(i){throw new Error(e+" must be hex string or Uint8Array, cause: "+i)}else if(At(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 au(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 Ta(e){return Uint8Array.from(e)}var xa=e=>typeof e=="bigint"&&ba<=e;function Na(e,t,r){return xa(e)&&xa(t)&&xa(r)&&t<=e&&e<r}function es(e,t,r,n){if(!Na(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function sr(e){let t;for(t=0;e>ba;e>>=Qi,t+=1);return t}function cu(e,t){return e>>BigInt(t)&Qi}var Rt=e=>(Qi<<BigInt(e))-Qi;function lu(e){return typeof e=="function"&&Number.isSafeInteger(e.outputLen)}function ar(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(o,i,s){let a=e[o];if(s&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${c}`)}Object.entries(t).forEach(([o,i])=>n(o,i,!1)),Object.entries(r).forEach(([o,i])=>n(o,i,!0))}var Zn=()=>{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 i=e(r,...n);return t.set(r,i),i}}var Me=BigInt(0),Ie=BigInt(1),vn=BigInt(2),du=BigInt(3),pu=BigInt(4),fu=BigInt(5),Gf=BigInt(7),hu=BigInt(8),Jf=BigInt(9),mu=BigInt(16);function ce(e,t){let r=e%t;return r>=Me?r:t+r}function It(e,t,r){let n=e;for(;t-- >Me;)n*=n,n%=r;return n}function uu(e,t){if(e===Me)throw new Error("invert: expected non-zero number");if(t<=Me)throw new Error("invert: expected positive modulus, got "+t);let r=ce(e,t),n=t,o=Me,i=Ie,s=Ie,a=Me;for(;r!==Me;){let u=n/r,p=n%r,d=o-s*u,l=i-a*u;n=r,r=p,o=s,i=a,s=d,a=l}if(n!==Ie)throw new Error("invert: does not exist");return ce(o,t)}function Oa(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function _u(e,t){let r=(e.ORDER+Ie)/pu,n=e.pow(t,r);return Oa(e,n,t),n}function Wf(e,t){let r=(e.ORDER-fu)/hu,n=e.mul(t,vn),o=e.pow(n,r),i=e.mul(t,o),s=e.mul(e.mul(i,vn),o),a=e.mul(i,e.sub(s,e.ONE));return Oa(e,a,t),a}function zf(e){let t=je(e),r=yu(e),n=r(t,t.neg(t.ONE)),o=r(t,n),i=r(t,t.neg(n)),s=(e+Gf)/mu;return(a,c)=>{let u=a.pow(c,s),p=a.mul(u,n),d=a.mul(u,o),l=a.mul(u,i),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 Oa(a,g,c),g}}function yu(e){if(e<du)throw new Error("sqrt is not defined for small field");let t=e-Ie,r=0;for(;t%vn===Me;)t/=vn,r++;let n=vn,o=je(e);for(;jo(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return _u;let i=o.pow(n,t),s=(t+Ie)/vn;return function(c,u){if(c.is0(u))return u;if(jo(c,u)!==1)throw new Error("Cannot find square root");let p=r,d=c.mul(c.ONE,i),l=c.pow(u,t),f=c.pow(u,s);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=Ie<<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 Yf(e){return e%pu===du?_u:e%hu===fu?Wf:e%mu===Jf?zf(e):yu(e)}var cr=(e,t)=>(ce(e,t)&Ie)===Ie,Zf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ts(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=Zf.reduce((n,o)=>(n[o]="function",n),t);return ar(e,r),e}function Ko(e,t,r){if(r<Me)throw new Error("invalid exponent, negatives unsupported");if(r===Me)return e.ONE;if(r===Ie)return t;let n=e.ONE,o=t;for(;r>Me;)r&Ie&&(n=e.mul(n,o)),o=e.sqr(o),r>>=Ie;return n}function at(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((s,a,c)=>e.is0(a)?s:(n[c]=s,e.mul(s,a)),e.ONE),i=e.inv(o);return t.reduceRight((s,a,c)=>e.is0(a)?s:(n[c]=e.mul(s,n[c]),e.mul(s,a)),i),n}function jo(e,t){let r=(e.ORDER-Ie)/vn,n=e.pow(t,r),o=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),s=e.eql(n,e.neg(e.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Ea(e,t){t!==void 0&&Gs(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function je(e,t,r=!1,n={}){if(e<=Me)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,i,s=!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&&(i=l.sqrt),typeof l.isLE=="boolean"&&(r=l.isLE),typeof l.modFromBytes=="boolean"&&(s=l.modFromBytes),a=l.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(i=n.sqrt);let{nBitLength:c,nByteLength:u}=Ea(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:Rt(c),ZERO:Me,ONE:Ie,allowedLengths:a,create:l=>ce(l,e),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return Me<=l&&l<e},is0:l=>l===Me,isValidNot0:l=>!d.is0(l)&&d.isValid(l),isOdd:l=>(l&Ie)===Ie,neg:l=>ce(-l,e),eql:(l,f)=>l===f,sqr:l=>ce(l*l,e),add:(l,f)=>ce(l+f,e),sub:(l,f)=>ce(l-f,e),mul:(l,f)=>ce(l*f,e),pow:(l,f)=>Ko(d,l,f),div:(l,f)=>ce(l*uu(f,e),e),sqrN:l=>l*l,addN:(l,f)=>l+f,subN:(l,f)=>l-f,mulN:(l,f)=>l*f,inv:l=>uu(l,e),sqrt:i||(l=>(p||(p=Yf(e)),p(d,l))),toBytes:l=>r?wa(l,u):Oe(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?ir(l):ze(l);if(s&&(h=ce(h,e)),!f&&!d.isValid(h))throw new Error("invalid field element: outside of range 0..ORDER");return h},invertBatch:l=>at(d,l),cmov:(l,f,h)=>h?f:l});return Object.freeze(d)}function gu(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 rs(e){let t=gu(e);return t+Math.ceil(t/2)}function Ra(e,t,r=!1){let n=e.length,o=gu(t),i=rs(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=r?ir(e):ze(e),a=ce(s,t-Ie)+Ie;return r?wa(a,o):Oe(a,o)}var Xn=BigInt(0),An=BigInt(1);function Ho(e,t){let r=t.negate();return e?r:t}function ct(e,t){let r=at(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function Tu(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Ia(e,t){Tu(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,i=Rt(e),s=BigInt(e);return{windows:r,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function xu(e,t,r){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=r,a=Number(e&o),c=e>>s;a>n&&(a-=i,c+=An);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 Qf(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 eh(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 va=new WeakMap,Nu=new WeakMap;function Aa(e){return Nu.get(e)||1}function bu(e){if(e!==Xn)throw new Error("invalid wNAF")}var Qn=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>Xn;)r&An&&(n=n.add(o)),o=o.double(),r>>=An;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=Ia(r,this.bits),i=[],s=t,a=s;for(let c=0;c<n;c++){a=s,i.push(a);for(let u=1;u<o;u++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(t,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=Ia(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:p,isNeg:d,isNegF:l,offsetF:f}=xu(n,a,s);n=c,p?i=i.add(Ho(l,r[f])):o=o.add(Ho(d,r[u]))}return bu(n),{p:o,f:i}}wNAFUnsafe(t,r,n,o=this.ZERO){let i=Ia(t,this.bits);for(let s=0;s<i.windows&&n!==Xn;s++){let{nextN:a,offset:c,isZero:u,isNeg:p}=xu(n,s,i);if(n=a,!u){let d=r[c];o=o.add(p?d.negate():d)}}return bu(n),o}getPrecomputes(t,r,n){let o=va.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(o=n(o)),va.set(r,o))),o}cached(t,r,n){let o=Aa(t);return this.wNAF(o,this.getPrecomputes(o,t,n),r)}unsafe(t,r,n,o){let i=Aa(t);return i===1?this._unsafeLadder(t,r,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,n),r,o)}createCache(t,r){Tu(r,this.bits),Nu.set(t,r),va.delete(t)}hasCache(t){return Aa(t)!==1}};function Ou(e,t,r,n){let o=t,i=e.ZERO,s=e.ZERO;for(;r>Xn||n>Xn;)r&An&&(i=i.add(o)),n&An&&(s=s.add(o)),o=o.double(),r>>=An,n>>=An;return{p1:i,p2:s}}function eo(e,t,r,n){Qf(r,e),eh(n,t);let o=r.length,i=n.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");let s=e.ZERO,a=sr(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=Rt(c),p=new Array(Number(u)+1).fill(s),d=Math.floor((t.BITS-1)/c)*c,l=s;for(let f=d;f>=0;f-=c){p.fill(s);for(let _=0;_<i;_++){let g=n[_],m=Number(g>>BigInt(f)&u);p[m]=p[m].add(r[_])}let h=s;for(let _=p.length-1,g=s;_>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 wu(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ts(t),t}else return je(e,{isLE:r})}function ns(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>Xn))throw new Error(`CURVE.${c} must be positive bigint`)}let o=wu(t.p,r.Fp,n),i=wu(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:i}}var th=ze;function Cr(e,t){if($o(e),$o(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 rh(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 $o(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function Eu(e){if(!At(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or string");return typeof e=="string"?$(e):e}function nh(e,t,r,n){me(e),$o(r),t=Eu(t),t.length>255&&(t=n(K($("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:i}=n,s=Math.ceil(r/o);if(r>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=K(t,Cr(t.length,1)),c=Cr(0,i),u=Cr(r,2),p=new Array(s),d=n(K(c,e,u,Cr(0,1),a));p[0]=n(K(d,Cr(1,1),a));for(let f=1;f<=s;f++){let h=[rh(d,p[f-1]),Cr(f+1,1),a];p[f]=n(K(...h))}return K(...p).slice(0,r)}function oh(e,t,r,n,o){if(me(e),$o(r),t=Eu(t),t.length>255){let i=Math.ceil(2*n/8);t=o.create({dkLen:i}).update($("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(Cr(r,2)).update(t).update(Cr(t.length,1)).digest()}function Sa(e,t,r){ar(r,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:n,k:o,m:i,hash:s,expand:a,DST:c}=r;if(!lu(r.hash))throw new Error("expected valid hash");me(e),$o(t);let u=n.toString(2).length,p=Math.ceil((u+o)/8),d=t*i*p,l;if(a==="xmd")l=nh(e,c,d,s);else if(a==="xof")l=oh(e,c,d,o,s);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(i);for(let g=0;g<i;g++){let m=p*(g+h*i),x=l.subarray(m,m+p);_[g]=ce(th(x),n)}f[h]=_}return f}function Ca(e,t){let r=t.map(n=>Array.from(n).reverse());return(n,o)=>{let[i,s,a,c]=r.map(d=>d.reduce((l,f)=>e.add(e.mul(l,n),f))),[u,p]=at(e,[s,c],!0);return n=e.mul(i,u),o=e.mul(o,e.mul(a,p)),{x:n,y:o}}}var ih=$("HashToScalar-");function Fa(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function n(i){return e.fromAffine(t(i))}function o(i){let s=i.clearCofactor();return s.equals(e.ZERO)?e.ZERO:(s.assertValidity(),s)}return{defaults:r,hashToCurve(i,s){let a=Object.assign({},r,s),c=Sa(i,2,a),u=n(c[0]),p=n(c[1]);return o(u.add(p))},encodeToCurve(i,s){let a=r.encodeDST?{DST:r.encodeDST}:{},c=Object.assign({},r,a,s),u=Sa(i,1,c),p=n(u[0]);return o(p)},mapToCurve(i){if(!Array.isArray(i))throw new Error("expected array of bigints");for(let s of i)if(typeof s!="bigint")throw new Error("expected array of bigints");return o(n(i))},hashToScalar(i,s){let a=e.Fn.ORDER,c=Object.assign({},r,{p:a,m:1,DST:ih},s);return Sa(i,1,c)[0][0]}}}var Ru=(e,t)=>(e+(e>=0?t:-t)/lr)/t;function sh(e,t,r){let[[n,o],[i,s]]=t,a=Ru(s*e,r),c=Ru(-o*e,r),u=e-a*n-c*i,p=-a*o-c*s,d=u<Sn,l=p<Sn;d&&(u=-u),l&&(p=-p);let f=Rt(Math.ceil(sr(r)/2))+Ke;if(u<Sn||u>=f||p<Sn||p>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:u,k2neg:l,k2:p}}var Sn=BigInt(0),Ke=BigInt(1),lr=BigInt(2),to=BigInt(3),Va=BigInt(4);function Go(e,t){let{BYTES:r}=e,n;if(typeof t=="bigint")n=t;else{let o=pe("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 ah(e,t={}){let r=ns("weierstrass",e,t),{Fp:n,Fn:o}=r,i=r.CURVE,{h:s,n:a}=i;ar(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=uh(n,o);function p(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(S,b,N){let{x:C,y:B}=b.toAffine(),q=n.toBytes(C);if(In(N,"isCompressed"),N){p();let A=!n.isOdd(B);return K(ch(A),q)}else return K(Uint8Array.of(4),q,n.toBytes(B))}function l(S){Ar(S,void 0,"Point");let{publicKey:b,publicKeyUncompressed:N}=u,C=S.length,B=S[0],q=S.subarray(1);if(C===b&&(B===2||B===3)){let A=n.fromBytes(q);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");let V=_(A),P;try{P=n.sqrt(V)}catch(re){let ee=re instanceof Error?": "+re.message:"";throw new Error("bad point: is not on curve, sqrt error"+ee)}p();let D=n.isOdd(P);return(B&1)===1!==D&&(P=n.neg(P)),{x:A,y:P}}else if(C===N&&B===4){let A=n.BYTES,V=n.fromBytes(q.subarray(0,A)),P=n.fromBytes(q.subarray(A,A*2));if(!g(V,P))throw new Error("bad point: is not on curve");return{x:V,y:P}}else throw new Error(`bad point: got length ${C}, expected compressed=${b} or uncompressed=${N}`)}let f=t.toBytes||d,h=t.fromBytes||l;function _(S){let b=n.sqr(S),N=n.mul(b,S);return n.add(n.add(N,n.mul(S,i.a)),i.b)}function g(S,b){let N=n.sqr(b),C=_(S);return n.eql(N,C)}if(!g(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let m=n.mul(n.pow(i.a,to),Va),x=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(m,x)))throw new Error("bad curve params: a or b");function y(S,b,N=!1){if(!n.isValid(b)||N&&n.is0(b))throw new Error(`bad point coordinate ${S}`);return b}function T(S){if(!(S instanceof w))throw new Error("ProjectivePoint expected")}function E(S){if(!c||!c.basises)throw new Error("no endo");return sh(S,c.basises,o.ORDER)}let O=Sr((S,b)=>{let{X:N,Y:C,Z:B}=S;if(n.eql(B,n.ONE))return{x:N,y:C};let q=S.is0();b==null&&(b=q?n.ONE:n.inv(B));let A=n.mul(N,b),V=n.mul(C,b),P=n.mul(B,b);if(q)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:A,y:V}}),R=Sr(S=>{if(S.is0()){if(t.allowInfinityPoint&&!n.is0(S.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:N}=S.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(!S.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(S,b,N,C,B){return N=new w(n.mul(N.X,S),N.Y,N.Z),b=Ho(C,b),N=Ho(B,N),b.add(N)}class w{constructor(b,N,C){this.X=y("x",b),this.Y=y("y",N,!0),this.Z=y("z",C),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){let{x:N,y:C}=b||{};if(!b||!n.isValid(N)||!n.isValid(C))throw new Error("invalid affine point");if(b instanceof w)throw new Error("projective point not allowed");return n.is0(N)&&n.is0(C)?w.ZERO:new w(N,C,n.ONE)}static fromBytes(b){let N=w.fromAffine(h(Ar(b,void 0,"point")));return N.assertValidity(),N}static fromHex(b){return w.fromBytes(pe("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,N=!0){return F.createCache(this,b),N||this.multiply(to),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:N,Y:C,Z:B}=this,{X:q,Y:A,Z:V}=b,P=n.eql(n.mul(N,V),n.mul(q,B)),D=n.eql(n.mul(C,V),n.mul(A,B));return P&&D}negate(){return new w(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:N}=i,C=n.mul(N,to),{X:B,Y:q,Z:A}=this,V=n.ZERO,P=n.ZERO,D=n.ZERO,U=n.mul(B,B),re=n.mul(q,q),ee=n.mul(A,A),J=n.mul(B,q);return J=n.add(J,J),D=n.mul(B,A),D=n.add(D,D),V=n.mul(b,D),P=n.mul(C,ee),P=n.add(V,P),V=n.sub(re,P),P=n.add(re,P),P=n.mul(V,P),V=n.mul(J,V),D=n.mul(C,D),ee=n.mul(b,ee),J=n.sub(U,ee),J=n.mul(b,J),J=n.add(J,D),D=n.add(U,U),U=n.add(D,U),U=n.add(U,ee),U=n.mul(U,J),P=n.add(P,U),ee=n.mul(q,A),ee=n.add(ee,ee),U=n.mul(ee,J),V=n.sub(V,U),D=n.mul(ee,re),D=n.add(D,D),D=n.add(D,D),new w(V,P,D)}add(b){T(b);let{X:N,Y:C,Z:B}=this,{X:q,Y:A,Z:V}=b,P=n.ZERO,D=n.ZERO,U=n.ZERO,re=i.a,ee=n.mul(i.b,to),J=n.mul(N,q),se=n.mul(C,A),he=n.mul(B,V),Fe=n.add(N,C),ne=n.add(q,A);Fe=n.mul(Fe,ne),ne=n.add(J,se),Fe=n.sub(Fe,ne),ne=n.add(N,B);let de=n.add(q,V);return ne=n.mul(ne,de),de=n.add(J,he),ne=n.sub(ne,de),de=n.add(C,B),P=n.add(A,V),de=n.mul(de,P),P=n.add(se,he),de=n.sub(de,P),U=n.mul(re,ne),P=n.mul(ee,he),U=n.add(P,U),P=n.sub(se,U),U=n.add(se,U),D=n.mul(P,U),se=n.add(J,J),se=n.add(se,J),he=n.mul(re,he),ne=n.mul(ee,ne),se=n.add(se,he),he=n.sub(J,he),he=n.mul(re,he),ne=n.add(ne,he),J=n.mul(se,ne),D=n.add(D,J),J=n.mul(de,ne),P=n.mul(Fe,P),P=n.sub(P,J),J=n.mul(Fe,se),U=n.mul(de,U),U=n.add(U,J),new w(P,D,U)}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 C,B,q=A=>F.cached(this,A,V=>ct(w,V));if(N){let{k1neg:A,k1:V,k2neg:P,k2:D}=E(b),{p:U,f:re}=q(V),{p:ee,f:J}=q(D);B=re.add(J),C=v(N.beta,U,ee,A,P)}else{let{p:A,f:V}=q(b);C=A,B=V}return ct(w,[C,B])[0]}multiplyUnsafe(b){let{endo:N}=t,C=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===Sn||C.is0())return w.ZERO;if(b===Ke)return C;if(F.hasCache(this))return this.multiply(b);if(N){let{k1neg:B,k1:q,k2neg:A,k2:V}=E(b),{p1:P,p2:D}=Ou(w,C,q,V);return v(N.beta,P,D,B,A)}else return F.unsafe(C,b)}multiplyAndAddUnsafe(b,N,C){let B=this.multiplyUnsafe(N).add(b.multiplyUnsafe(C));return B.is0()?void 0:B}toAffine(b){return O(this,b)}isTorsionFree(){let{isTorsionFree:b}=t;return s===Ke?!0:b?b(w,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=t;return s===Ke?this:b?b(w,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(b=!0){return In(b,"isCompressed"),this.assertValidity(),f(w,this,b)}toHex(b=!0){return j(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 ct(w,b)}static msm(b,N){return eo(w,o,b,N)}static fromPrivateKey(b){return w.BASE.multiply(Go(o,b))}}w.BASE=new w(i.Gx,i.Gy,n.ONE),w.ZERO=new w(n.ZERO,n.ONE,n.ZERO),w.Fp=n,w.Fn=o;let I=o.BITS,F=new Qn(w,t.endo?Math.ceil(I/2):I);return w.BASE.precompute(8),w}function ch(e){return Uint8Array.of(e?2:3)}function lh(e,t){let r=e.ORDER,n=Sn;for(let h=r-Ke;h%lr===Sn;h/=lr)n+=Ke;let o=n,i=lr<<o-Ke-Ke,s=i*lr,a=(r-Ke)/s,c=(a-Ke)/lr,u=s-Ke,p=i,d=e.pow(t,a),l=e.pow(t,(a+Ke)/lr),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 E=e.eql(y,e.ONE);m=e.mul(x,l),y=e.mul(T,g),x=e.cmov(m,x,E),T=e.cmov(y,T,E);for(let O=o;O>Ke;O--){let R=O-lr;R=lr<<R-Ke;let v=e.pow(T,R),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:E,value:x}};if(e.ORDER%Va===to){let h=(e.ORDER-to)/Va,_=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 E=e.mul(T,_),O=e.mul(e.sqr(T),m),R=e.eql(O,g),v=e.cmov(E,T,R);return{isValid:R,value:v}}}return f}function Pa(e,t){ts(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 i=lh(e,o);if(!e.isOdd)throw new Error("Field does not have .isOdd()");return s=>{let a,c,u,p,d,l,f,h;a=e.sqr(s),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}=i(c,l);h=e.mul(a,s),h=e.mul(h,g),f=e.cmov(f,u,_),h=e.cmov(h,g,_);let m=e.isOdd(s)===e.isOdd(h);h=e.cmov(e.neg(h),h,m);let x=at(e,[p],!0)[0];return f=e.mul(f,x),{x:f,y:h}}}function uh(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Ba(e){let{CURVE:t,curveOpts:r}=dh(e),n=ah(t,r);return fh(e,n)}function dh(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(s=>Math.ceil(s/2)))):void 0,o=je(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),i={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:i}}function ph(e,t,r){function n(o){let i=e.sqr(o),s=e.mul(i,o);return e.add(e.add(s,e.mul(o,t)),r)}return n}function fh(e,t){let{Fp:r,Fn:n}=t;function o(s){return Na(s,Ke,n.ORDER)}let i=ph(r,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:s=>Go(n,s),weierstrassEquation:i,isWithinCurveOrder:o})}var hh=BigInt(0),os=BigInt(1),Iu=BigInt(2),ro=BigInt(3);function mh(e){let t=[];for(;e>os;e>>=os)(e&os)===hh?t.unshift(0):(e&ro)===ro?(t.unshift(-1),e+=os):t.unshift(1);return t}function Da(e){if(!Array.isArray(e)||e.length===0)throw new Error("expected non-empty array")}function _h(e,t,r,n){let{Fp2:o,Fp12:i}=e,{twistType:s,ateLoopSize:a,xNegative:c,postPrecompute:u}=n,p;if(s==="multiplicative")p=(y,T,E,O,R,v)=>i.mul014(O,y,o.mul(T,R),o.mul(E,v));else if(s==="divisive")p=(y,T,E,O,R,v)=>i.mul034(O,o.mul(E,v),o.mul(T,R),y);else throw new Error("bls: unknown twist type");let d=o.div(o.ONE,o.mul(o.ONE,Iu));function l(y,T,E,O){let R=o.sqr(E),v=o.sqr(O),w=o.mulByB(o.mul(v,ro)),I=o.mul(w,ro),F=o.sub(o.sub(o.sqr(o.add(E,O)),v),R),S=o.sub(w,R),b=o.mul(o.sqr(T),ro),N=o.neg(F);return y.push([S,b,N]),T=o.mul(o.mul(o.mul(o.sub(R,I),T),E),d),E=o.sub(o.sqr(o.mul(o.add(R,I),d)),o.mul(o.sqr(w),ro)),O=o.mul(R,F),{Rx:T,Ry:E,Rz:O}}function f(y,T,E,O,R,v){let w=o.sub(E,o.mul(v,O)),I=o.sub(T,o.mul(R,O)),F=o.sub(o.mul(w,R),o.mul(I,v)),S=o.neg(w),b=I;y.push([F,S,b]);let N=o.sqr(I),C=o.mul(N,I),B=o.mul(N,T),q=o.add(o.sub(C,o.mul(B,Iu)),o.mul(o.sqr(w),O));return T=o.mul(I,q),E=o.sub(o.mul(o.sub(B,q),w),o.mul(C,E)),O=o.mul(O,C),{Rx:T,Ry:E,Rz:O}}let h=mh(a),_=Sr(y=>{let T=y,{x:E,y:O}=T.toAffine(),R=E,v=O,w=o.neg(O),I=R,F=v,S=o.ONE,b=[];for(let N of h){let C=[];({Rx:I,Ry:F,Rz:S}=l(C,I,F,S)),N&&({Rx:I,Ry:F,Rz:S}=f(C,I,F,S,R,N===-1?w:v)),b.push(C)}if(u){let N=b[b.length-1];u(I,F,S,R,v,f.bind(null,N))}return b});function g(y,T=!1){let E=i.ONE;if(y.length){let O=y[0][0].length;for(let R=0;R<O;R++){E=i.sqr(E);for(let[v,w,I]of y)for(let[F,S,b]of v[R])E=p(F,S,b,E,w,I)}}return c&&(E=i.conjugate(E)),T?i.finalExponentiate(E):E}function m(y,T=!0){let E=[];ct(t,y.map(({g1:O})=>O)),ct(r,y.map(({g2:O})=>O));for(let{g1:O,g2:R}of y){if(O.is0()||R.is0())throw new Error("pairing is not available for ZERO point");O.assertValidity(),R.assertValidity();let v=O.toAffine();E.push([_(R),v.x,v.y])}return g(E,T)}function x(y,T,E=!0){return m([{g1:y,g2:T}],E)}return{Fp12:i,millerLoopBatch:g,pairing:x,pairingBatch:m,calcPairingPrecomputes:_}}function vu(e,t,r,n,o){let{Fp12:i,pairingBatch:s}=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=Go(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=Go(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=s([p(_,m),p(g,x)]);return i.eql(y,i.ONE)},verifyBatch(d,l,f){if(Da(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 E=g[T],O=_[T],R=m.get(O);R===void 0&&(R=[],m.set(O,R)),R.push(E)}let x=[],y=t.Point.BASE;try{for(let[T,E]of m){let O=E.reduce((R,v)=>R.add(v));x.push(p(O,T))}return x.push(p(y.negate(),h)),i.eql(s(x),i.ONE)}catch{return!1}},aggregatePublicKeys(d){Da(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){Da(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){me(d);let f=l?{DST:l}:void 0;return r.hashToCurve(d,f)},Signature:n}}function Au(e){let{Fp:t,Fr:r,Fp2:n,Fp6:o,Fp12:i}=e.fields,s=Ba(e.G1),a=Object.assign(s,Fa(s.Point,e.G1.mapToCurve,{...e.htfDefaults,...e.G1.htfDefaults})),c=Ba(e.G2),u=Object.assign(c,Fa(c.Point,e.G2.mapToCurve,{...e.htfDefaults,...e.G2.htfDefaults})),p=_h(e.fields,a.Point,u.Point,{...e.params,postPrecompute:e.postPrecompute}),{millerLoopBatch:d,pairing:l,pairingBatch:f,calcPairingPrecomputes:h}=p,_=vu(p,a,u,e.G2.Signature,!1),g=vu(p,u,a,e.G1.ShortSignature,!0),m=e.randomBytes||Un,x=()=>{let A=rs(r.ORDER);return Ra(m(A),r.ORDER)},y={randomSecretKey:x,randomPrivateKey:x,calcPairingPrecomputes:h},{ShortSignature:T}=e.G1,{Signature:E}=e.G2;function O(A,V){return A instanceof a.Point?A:g.hash(pe("point",A),V?.DST)}function R(A,V){return A instanceof u.Point?A:_.hash(pe("point",A),V?.DST)}function v(A){return _.getPublicKey(A).toBytes(!0)}function w(A){return g.getPublicKey(A).toBytes(!0)}function I(A,V,P){let D=R(A,P),U=_.sign(D,V);return A instanceof u.Point?U:E.toBytes(U)}function F(A,V,P){let D=O(A,P),U=g.sign(D,V);return A instanceof a.Point?U:T.toBytes(U)}function S(A,V,P,D){let U=R(V,D);return _.verify(A,U,P)}function b(A,V,P,D){let U=O(V,D);return g.verify(A,U,P)}function N(A){let V=_.aggregatePublicKeys(A);return A[0]instanceof a.Point?V:V.toBytes(!0)}function C(A){let V=_.aggregateSignatures(A);return A[0]instanceof u.Point?V:E.toBytes(V)}function B(A){let V=g.aggregateSignatures(A);return A[0]instanceof a.Point?V:T.toBytes(V)}function q(A,V,P,D){let U=V.map(re=>R(re,D));return _.verifyBatch(A,U,P)}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:i},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:F,verify:S,verifyShortSignature:b,aggregatePublicKeys:N,aggregateSignatures:C,aggregateShortSignatures:B,G1:a,G2:u,Signature:E,ShortSignature:T}}var Su=BigInt(0),ur=BigInt(1),He=BigInt(2),Cu=BigInt(3);function qa(e,t,r,n,o=1,i){let s=BigInt(i===void 0?n:i),a=r**BigInt(n),c=[];for(let u=0;u<o;u++){let p=BigInt(u+1),d=[];for(let l=0,f=ur;l<n;l++){let h=(p*f-p)/s%a;d.push(e.pow(t,h)),f*=r}c.push(d)}return c}function Vu(e,t,r){let n=t.pow(r,(e.ORDER-ur)/Cu),o=t.pow(r,(e.ORDER-ur)/He);function i(l,f){let h=t.mul(t.frobeniusMap(l,1),n),_=t.mul(t.frobeniusMap(f,1),o);return[h,_]}let s=t.pow(r,(e.ORDER**He-ur)/Cu),a=t.pow(r,(e.ORDER**He-ur)/He);if(!t.eql(a,t.neg(t.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(l,f){return[t.mul(l,s),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(i),d=u(c);return{psi:i,psi2:c,G2psi:p,G2psi2:d,PSI_X:n,PSI_Y:o,PSI2_X:s,PSI2_Y:a}}var Fu=(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]}},Ua=class{constructor(t,r={}){this.MASK=ur;let n=t.ORDER,o=n*n;this.Fp=t,this.ORDER=o,this.BITS=sr(o),this.BYTES=Math.ceil(sr(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,He),this.NONRESIDUE=Fu(t,r.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=qa(t,this.Fp_NONRESIDUE,t.ORDER,2)[0],this.mulByB=r.Fp2mulByB,Object.seal(this)}fromBigTuple(t){return Fu(this.Fp,t)}create(t){return t}isValid({c0:t,c1:r}){function n(o,i){return typeof o=="bigint"&&Su<=o&&o<i}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 Ko(this,t,r)}invertBatch(t){return at(this,t)}add(t,r){let{c0:n,c1:o}=t,{c0:i,c1:s}=r;return{c0:this.Fp.add(n,i),c1:this.Fp.add(o,s)}}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:i,c1:s}=n,a=o.mul(t,i),c=o.mul(r,s),u=o.sub(a,c),p=o.sub(o.mul(o.add(t,r),o.add(i,s)),o.add(a,c));return{c0:u,c1:p}}sqr({c0:t,c1:r}){let{Fp:n}=this,o=n.add(t,r),i=n.sub(t,r),s=n.add(t,t);return{c0:n.mul(o,i),c1:n.mul(s,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:i}=t;if(r.is0(i))return jo(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 s=r.sqrt(r.sub(r.sqr(o),r.mul(r.sqr(i),this.Fp_NONRESIDUE))),a=r.mul(r.add(s,o),this.Fp_div2);jo(r,a)===-1&&(a=r.sub(a,s));let u=r.sqrt(a),p=n.create({c0:u,c1:r.div(r.mul(i,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%He,i=r===Su,s=n%He;return BigInt(o||i&&s)==ur}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},i){return{c0:this.Fp.cmov(t,n,i),c1:this.Fp.cmov(r,o,i)}}reim({c0:t,c1:r}){return{re:t,im:r}}Fp4Square(t,r){let n=this,o=n.sqr(t),i=n.sqr(r);return{first:n.add(n.mulByNonresidue(i),o),second:n.sub(n.sub(n.sqr(n.add(t,r)),o),i)}}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])}}},ka=class{constructor(t){this.MASK=ur,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=qa(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:i,c2:s}){let{Fp2:a}=this;return{c0:a.add(t,o),c1:a.add(r,i),c2:a.add(n,s)}}sub({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return{c0:a.sub(t,o),c1:a.sub(r,i),c2:a.sub(n,s)}}mul({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;if(typeof o=="bigint")return{c0:i.mul(t,o),c1:i.mul(r,o),c2:i.mul(n,o)};let{c0:s,c1:a,c2:c}=o,u=i.mul(t,s),p=i.mul(r,a),d=i.mul(n,c);return{c0:i.add(u,i.mulByNonresidue(i.sub(i.mul(i.add(r,n),i.add(a,c)),i.add(p,d)))),c1:i.add(i.sub(i.mul(i.add(t,r),i.add(s,a)),i.add(u,p)),i.mulByNonresidue(d)),c2:i.sub(i.add(p,i.mul(i.add(t,n),i.add(s,c))),i.add(u,d))}}sqr({c0:t,c1:r,c2:n}){let{Fp2:o}=this,i=o.sqr(t),s=o.mul(o.mul(t,r),He),a=o.mul(o.mul(r,n),He),c=o.sqr(n);return{c0:o.add(o.mulByNonresidue(a),i),c1:o.add(o.mulByNonresidue(c),s),c2:o.sub(o.sub(o.add(o.add(s,o.sqr(o.add(o.sub(t,r),n))),a),i),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:i,c2:s}){let{Fp2:a}=this;return a.eql(t,o)&&a.eql(r,i)&&a.eql(n,s)}sqrt(t){return Zn()}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 Ko(this,t,r)}invertBatch(t){return at(this,t)}inv({c0:t,c1:r,c2:n}){let{Fp2:o}=this,i=o.sub(o.sqr(t),o.mulByNonresidue(o.mul(n,r))),s=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,s),o.mul(r,a))),o.mul(t,i)));return{c0:o.mul(c,i),c1:o.mul(c,s),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:i,c2:s},a){let{Fp2:c}=this;return{c0:c.cmov(t,o,a),c1:c.cmov(r,i,a),c2:c.cmov(n,s,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:i}=this;return{c0:i.frobeniusMap(t,o),c1:i.mul(i.frobeniusMap(r,o),this.FROBENIUS_COEFFICIENTS_1[o%6]),c2:i.mul(i.frobeniusMap(n,o),this.FROBENIUS_COEFFICIENTS_2[o%6])}}mulByFp2({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;return{c0:i.mul(t,o),c1:i.mul(r,o),c2:i.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:i}=this;return{c0:i.mulByNonresidue(i.mul(n,o)),c1:i.mul(t,o),c2:i.mul(r,o)}}mul01({c0:t,c1:r,c2:n},o,i){let{Fp2:s}=this,a=s.mul(t,o),c=s.mul(r,i);return{c0:s.add(s.mulByNonresidue(s.sub(s.mul(s.add(r,n),i),c)),a),c1:s.sub(s.sub(s.mul(s.add(o,i),s.add(t,r)),a),c),c2:s.add(s.sub(s.mul(s.add(t,n),o),a),c)}}},La=class{constructor(t,r){this.MASK=ur;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=qa(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:i}=this;return i.eql(t,n)&&i.eql(r,o)}sqrt(t){Zn()}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:i}=o;return this.mul(t,typeof r=="bigint"?i.inv(i.create(r)):this.inv(r))}pow(t,r){return Ko(this,t,r)}invertBatch(t){return at(this,t)}add({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return{c0:i.add(t,n),c1:i.add(r,o)}}sub({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return{c0:i.sub(t,n),c1:i.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:i,c1:s}=n,a=o.mul(t,i),c=o.mul(r,s);return{c0:o.add(a,o.mulByNonresidue(c)),c1:o.sub(o.mul(o.add(t,r),o.add(i,s)),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},i){let{Fp6:s}=this;return{c0:s.cmov(t,n,i),c1:s.cmov(r,o,i)}}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:i,c1:s,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(i,c),c1:o.mul(s,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,i){let{Fp6:s}=this,{Fp2:a}=s,c=s.mul01(t,n,o),u=s.mul1(r,i);return{c0:s.add(s.mulByNonresidue(u),c),c1:s.sub(s.sub(s.mul01(s.add(r,t),n,a.add(o,i)),c),u)}}mul034({c0:t,c1:r},n,o,i){let{Fp6:s}=this,{Fp2:a}=s,c=s.create({c0:a.mul(t.c0,n),c1:a.mul(t.c1,n),c2:a.mul(t.c2,n)}),u=s.mul01(r,o,i),p=s.mul01(s.add(t,r),a.add(n,o),i);return{c0:s.add(s.mulByNonresidue(u),c),c1:s.sub(p,s.add(c,u))}}_cyclotomicSquare({c0:t,c1:r}){let{Fp6:n}=this,{Fp2:o}=n,{c0:i,c1:s,c2:a}=t,{c0:c,c1:u,c2:p}=r,{first:d,second:l}=o.Fp4Square(i,u),{first:f,second:h}=o.Fp4Square(c,a),{first:_,second:g}=o.Fp4Square(s,p),m=o.mulByNonresidue(g);return{c0:n.create({c0:o.add(o.mul(o.sub(d,i),He),d),c1:o.add(o.mul(o.sub(f,s),He),f),c2:o.add(o.mul(o.sub(_,a),He),_)}),c1:n.create({c0:o.add(o.mul(o.add(m,c),He),m),c1:o.add(o.mul(o.add(l,u),He),l),c2:o.add(o.mul(o.add(h,p),He),h)})}}_cyclotomicExp(t,r){let n=this.ONE;for(let o=this.X_LEN-1;o>=0;o--)n=this._cyclotomicSquare(n),cu(r,o)&&(n=this.mul(n,t));return n}};function Pu(e){let t=je(e.ORDER),r=new Ua(t,e),n=new ka(r),o=new La(n,e);return{Fp:t,Fp2:r,Fp6:n,Fp12:o}}var Pe=BigInt(0),is=BigInt(1),lt=BigInt(2),ss=BigInt(3),Jo=BigInt(4),Fr=BigInt("0xd201000000010000"),yh=sr(Fr),Cn={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:Pe,b:Jo,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},gh=je(Cn.n,{modFromBytes:!0,isLE:!0}),{Fp:M,Fp2:W,Fp6:xh,Fp12:X}=Pu({ORDER:Cn.p,X_LEN:yh,FP2_NONRESIDUE:[is,is],Fp2mulByB:({c0:e,c1:t})=>{let r=M.mul(e,Jo),n=M.mul(t,Jo);return{c0:M.sub(r,n),c1:M.add(r,n)}},Fp12finalExponentiate:e=>{let t=Fr,r=X.div(X.frobeniusMap(e,6),e),n=X.mul(X.frobeniusMap(r,2),r),o=X.conjugate(X._cyclotomicExp(n,t)),i=X.mul(X.conjugate(X._cyclotomicSquare(n)),o),s=X.conjugate(X._cyclotomicExp(i,t)),a=X.conjugate(X._cyclotomicExp(s,t)),c=X.mul(X.conjugate(X._cyclotomicExp(a,t)),X._cyclotomicSquare(o)),u=X.conjugate(X._cyclotomicExp(c,t)),p=X.frobeniusMap(X.mul(o,a),2),d=X.frobeniusMap(X.mul(s,n),3),l=X.frobeniusMap(X.mul(c,X.conjugate(n)),1),f=X.mul(X.mul(u,X.conjugate(i)),n);return X.mul(X.mul(X.mul(p,d),l),f)}}),{G2psi:Bu,G2psi2:bh}=Vu(M,W,W.div(W.ONE,W.NONRESIDUE)),Ma=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:M.ORDER,m:2,k:128,expand:"xmd",hash:Ve}),Ha={p:W.ORDER,n:Cn.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:W.ZERO,b:W.fromBigTuple([Jo,Jo]),Gx:W.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:W.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},as=Wo(M.toBytes(Pe),{infinity:!0,compressed:!0});function cs(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 Wo(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 wh(e,t,r){let{BYTES:n,ORDER:o}=M,i=t.is0(),{x:s,y:a}=t.toAffine();if(r){if(i)return as.slice();let c=!!(a*lt/o);return Wo(Oe(s,n),{compressed:!0,sort:c})}else return i?K(Uint8Array.of(64),new Uint8Array(2*n-1)):K(Oe(s,n),Oe(a,n))}function ja(e){e.assertValidity();let{BYTES:t,ORDER:r}=M,{x:n,y:o}=e.toAffine();if(e.is0())return as.slice();let i=!!(o*lt/r);return Wo(Oe(n,t),{compressed:!0,sort:i})}function Th(e){let{compressed:t,infinity:r,sort:n,value:o}=cs(e),{BYTES:i,ORDER:s}=M;if(o.length===48&&t){let a=ze(o),c=M.create(a&Rt(M.BITS));if(r){if(c!==Pe)throw new Error("invalid G1 point: non-empty, at infinity, with compression");return{x:Pe,y:Pe}}let u=M.add(M.pow(c,ss),M.create(Cn.b)),p=M.sqrt(u);if(!p)throw new Error("invalid G1 point: compressed point");return p*lt/s!==BigInt(n)&&(p=M.neg(p)),{x:M.create(c),y:M.create(p)}}else if(o.length===96&&!t){let a=ze(o.subarray(0,i)),c=ze(o.subarray(i));if(r){if(a!==Pe||c!==Pe)throw new Error("G1: non-empty point at infinity");return zo.G1.Point.ZERO.toAffine()}return{x:M.create(a),y:M.create(c)}}else throw new Error("invalid G1 point: expected 48/96 bytes")}function Du(e){let{infinity:t,sort:r,value:n}=cs(pe("signatureHex",e,48)),o=M.ORDER,i=zo.G1.Point,s=ze(n);if(t)return i.ZERO;let a=M.create(s&Rt(M.BITS)),c=M.add(M.pow(a,ss),M.create(Cn.b)),u=M.sqrt(c);if(!u)throw new Error("invalid G1 point: compressed");let p=BigInt(r);u*lt/o!==p&&(u=M.neg(u));let d=i.fromAffine({x:a,y:u});return d.assertValidity(),d}function Nh(e,t,r){let{BYTES:n,ORDER:o}=M,i=t.is0(),{x:s,y:a}=t.toAffine();if(r){if(i)return K(as,Oe(Pe,n));let c=!!(a.c1===Pe?a.c0*lt/o:a.c1*lt/o);return K(Wo(Oe(s.c1,n),{compressed:!0,sort:c}),Oe(s.c0,n))}else{if(i)return K(Uint8Array.of(64),new Uint8Array(4*n-1));let{re:c,im:u}=W.reim(s),{re:p,im:d}=W.reim(a);return K(Oe(u,n),Oe(c,n),Oe(d,n),Oe(p,n))}}function Ka(e){e.assertValidity();let{BYTES:t}=M;if(e.is0())return K(as,Oe(Pe,t));let{x:r,y:n}=e.toAffine(),{re:o,im:i}=W.reim(r),{re:s,im:a}=W.reim(n),u=!!((a>Pe?a*lt:s*lt)/M.ORDER&is),p=o;return K(Wo(Oe(i,t),{sort:u,compressed:!0}),Oe(p,t))}function Oh(e){let{BYTES:t,ORDER:r}=M,{compressed:n,infinity:o,sort:i,value:s}=cs(e);if(!n&&!o&&i||!n&&o&&i||i&&o&&n)throw new Error("invalid encoding flag: "+(e[0]&224));let a=(c,u,p)=>ze(c.slice(u,p));if(s.length===96&&n){if(o){if(s.reduce((h,_)=>h!==0?_+1:_,0)>0)throw new Error("invalid G2 point: compressed");return{x:W.ZERO,y:W.ZERO}}let c=a(s,0,t),u=a(s,t,2*t),p=W.create({c0:M.create(u),c1:M.create(c)}),d=W.add(W.pow(p,ss),Ha.b),l=W.sqrt(d),f=l.c1===Pe?l.c0*lt/r:l.c1*lt/r?is:Pe;return l=i&&f>0?l:W.neg(l),{x:p,y:l}}else if(s.length===192&&!n){if(o){if(s.reduce((l,f)=>l!==0?f+1:f,0)>0)throw new Error("invalid G2 point: uncompressed");return{x:W.ZERO,y:W.ZERO}}let c=a(s,0*t,1*t),u=a(s,1*t,2*t),p=a(s,2*t,3*t),d=a(s,3*t,4*t);return{x:W.fromBigTuple([u,c]),y:W.fromBigTuple([d,p])}}else throw new Error("invalid G2 point: expected 96/192 bytes")}function Uu(e){let{ORDER:t}=M,{infinity:r,sort:n,value:o}=cs(pe("signatureHex",e)),i=zo.G2.Point,s=o.length/2;if(s!==48&&s!==96)throw new Error("invalid compressed signature length, expected 96/192 bytes");let a=ze(o.slice(0,s)),c=ze(o.slice(s));if(r)return i.ZERO;let u=M.create(a&Rt(M.BITS)),p=M.create(c),d=W.create({c0:p,c1:u}),l=W.add(W.pow(d,ss),Ha.b),f=W.sqrt(l);if(!f)throw new Error("Failed to find a square root");let{re:h,im:_}=W.reim(f),g=BigInt(n),m=_>Pe&&_*lt/t!==g,x=_===Pe&&h*lt/t!==g;(m||x)&&(f=W.neg(f));let y=i.fromAffine({x:d,y:f});return y.assertValidity(),y}var zo=Au({fields:{Fp:M,Fp2:W,Fp6:xh,Fp12:X,Fr:gh},G1:{...Cn,Fp:M,htfDefaults:{...Ma,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(M.mul(t.X,r),t.Y,t.Z);return t.multiplyUnsafe(Fr).negate().multiplyUnsafe(Fr).equals(n)},clearCofactor:(e,t)=>t.multiplyUnsafe(Fr).add(t),mapToCurve:Ah,fromBytes:Th,toBytes:wh,ShortSignature:{fromBytes(e){return me(e),Du(e)},fromHex(e){return Du(e)},toBytes(e){return ja(e)},toRawBytes(e){return ja(e)},toHex(e){return j(ja(e))}}},G2:{...Ha,Fp:W,hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...Ma},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:Sh,isTorsionFree:(e,t)=>t.multiplyUnsafe(Fr).negate().equals(Bu(e,t)),clearCofactor:(e,t)=>{let r=Fr,n=t.multiplyUnsafe(r).negate(),o=Bu(e,t),i=t.double();return i=bh(e,i),i=i.subtract(o),o=n.add(o),o=o.multiplyUnsafe(r).negate(),i=i.add(o),i=i.subtract(n),i.subtract(t)},fromBytes:Oh,toBytes:Nh,Signature:{fromBytes(e){return me(e),Uu(e)},fromHex(e){return Uu(e)},toBytes(e){return Ka(e)},toRawBytes(e){return Ka(e)},toHex(e){return j(Ka(e))}}},params:{ateLoopSize:Fr,r:Cn.n,xNegative:!0,twistType:"multiplicative"},htfDefaults:Ma,hash:Ve}),Eh=Ca(W,[[["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=>W.fromBigTuple(t.map(BigInt))))),Rh=Ca(M,[["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)))),Ih=Pa(M,{A:M.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:M.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:M.create(BigInt(11))}),vh=Pa(W,{A:W.create({c0:M.create(Pe),c1:M.create(BigInt(240))}),B:W.create({c0:M.create(BigInt(1012)),c1:M.create(BigInt(1012))}),Z:W.create({c0:M.create(BigInt(-2)),c1:M.create(BigInt(-1))})});function Ah(e){let{x:t,y:r}=Ih(M.create(e[0]));return Rh(t,r)}function Sh(e){let{x:t,y:r}=vh(W.fromBigTuple(e));return Eh(t,r)}function ku(e,t,r){let n=typeof e=="string"?e:j(e),o=typeof t=="string"?t:j(t),i=typeof r=="string"?r:j(r);return zo.verifyShortSignature(o,i,n)}var Fh=BigInt(1e6),$a=e=>ge(new wt(e)),Vr=e=>{let r=$a(e)/Fh;return new Date(Number(r))};var Lu=60*1e3,Vh=60,Ph=24,Bh=Ph*Vh,Dh=5,Uh=5,kh=30*Bh,fe;(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"})(fe||(fe={}));function Lh(e,t){for(let r=0;r<e.length;r++)if(e[r]>t[r])return!0;return!1}var nt=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.principal,t.blsVerify??ku,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(t,r,n,o,i=Dh,s=!1,a){this._rootKey=r,this._principal=n,this._blsVerify=o,this._maxAgeInMinutes=i,this.#e=s,this.cert=qe(t),a&&"getTimeDiffMsecs"in a&&"hasSyncedTime"in a&&"syncTime"in a&&"syncTimeWithSubnet"in a&&(this.#t=a)}lookup_path(t){return dr(t,this.cert.tree)}lookup_subtree(t){return Xo(t,this.cert.tree)}async verify(){let t=await us(this.cert.tree),r=await this._checkDelegationAndGetKey(this.cert.delegation),n=this.cert.signature,o=Mh(r),i=K(la,t),s=ve(this.lookup_path(["time"]));if(!s)throw te.fromCode(new gt("Certificate does not contain a time"));if(!this.#e){let a=this.#t?.getTimeDiffMsecs()??0,c=this._maxAgeInMinutes*Lu,u=new Date,p=u.getTime()+a,d=p-c,l=p+Uh*Lu,f=Vr(s),h=f.getTime()<d,_=f.getTime()>l;if((h||_)&&this.#t&&!this.#t.hasSyncedTime())return await this._syncTime(),await this.verify();if(h)throw ke.fromCode(new Xt(this._maxAgeInMinutes,f,u,a,"past"));if(_)throw this.#t?.hasSyncedTime()?ae.fromCode(new Re("System time has been synced with the IC network, but certificate is still too far in the future.")):ke.fromCode(new Xt(5,f,u,a,"future"))}try{if(!await this._blsVerify(o,n,i))throw ke.fromCode(new gt("Invalid signature"))}catch(a){throw ke.fromCode(new gt("Signature verification failed",a))}}async _checkDelegationAndGetKey(t){if(!t)return this._rootKey;let r=e.createUnverified({certificate:t.certificate,rootKey:this._rootKey,principal:this._principal,blsVerify:this._blsVerify,disableTimeVerification:this.#e,maxAgeInMinutes:kh,agent:this.#t});if(r.cert.delegation)throw te.fromCode(new bi);await r.verify();let n;if(Mu(this._principal)){let i=this._principal.canisterId;if(n=k.fromUint8Array(t.subnet_id),!Ga({canisterId:i,subnetId:n,tree:r.cert.tree}))throw ke.fromCode(new gn(i,n))}else if(qu(this._principal))n=this._principal.subnetId;else throw it;let o=ve(r.lookup_path(["subnet",n.toUint8Array(),"public_key"]));if(!o)throw qu(this._principal)?ke.fromCode(new wi(n)):ke.fromCode(new Ni(`Could not find subnet key for subnet ID ${n.toText()}`));return o}async _syncTime(){this.#t&&(Mu(this._principal)?await this.#t.syncTime(this._principal.canisterId):await this.#t.syncTimeWithSubnet(this._principal.subnetId))}};function qu(e){return"subnetId"in e}function Mu(e){return"canisterId"in e}var Yo=Ee("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),qh=96;function Mh(e){let t=Yo.byteLength+qh;if(e.byteLength!==t)throw te.fromCode(new kn(t,e.byteLength));let r=e.slice(0,Yo.byteLength);if(!On(r,Yo))throw te.fromCode(new Oi(Yo,r));return e.slice(Yo.byteLength)}function ve(e){if(e.status===Be.Found&&e.value instanceof Uint8Array)return e.value}async function us(e){switch(e[0]){case fe.Empty:return Ve(ls("ic-hashtree-empty"));case fe.Pruned:return e[1];case fe.Leaf:return Ve(K(ls("ic-hashtree-leaf"),e[1]));case fe.Labeled:return Ve(K(ls("ic-hashtree-labeled"),e[1],await us(e[2])));case fe.Fork:return Ve(K(ls("ic-hashtree-fork"),await us(e[1]),await us(e[2])));default:throw it}}function ls(e){let t=new Uint8Array([e.length]),r=new TextEncoder().encode(e);return K(t,r)}function ju(e){return typeof e[0]=="string"?$(e[0]):e[0]}var Be;(function(e){e.Unknown="Unknown",e.Absent="Absent",e.Found="Found",e.Error="Error"})(Be||(Be={}));var Pr;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found"})(Pr||(Pr={}));var le;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found",e.Less="Less",e.Greater="Greater"})(le||(le={}));function dr(e,t){if(e.length===0)switch(t[0]){case fe.Empty:return{status:Be.Absent};case fe.Leaf:{if(!t[1])throw ae.fromCode(new Er("Invalid tree structure for leaf"));if(t[1]instanceof Uint8Array)return{status:Be.Found,value:t[1].slice(t[1].byteOffset,t[1].byteLength+t[1].byteOffset)};throw it}case fe.Pruned:return{status:Be.Unknown};case fe.Labeled:case fe.Fork:return{status:Be.Error};default:throw it}let r=ju(e),n=Zo(r,t);switch(n.status){case le.Found:return dr(e.slice(1),n.value);case le.Absent:case le.Greater:case le.Less:return{status:Be.Absent};case le.Unknown:return{status:Be.Unknown};default:throw it}}function Xo(e,t){if(e.length===0)return{status:Pr.Found,value:t};let r=ju(e),n=Zo(r,t);switch(n.status){case le.Found:return Xo(e.slice(1),n.value);case le.Unknown:return{status:Pr.Unknown};case le.Absent:case le.Greater:case le.Less:return{status:Pr.Absent};default:throw it}}function ps(e){switch(e[0]){case fe.Empty:return[];case fe.Fork:return ps(e[1]).concat(ps(e[2]));default:return[e]}}function Zo(e,t){switch(t[0]){case fe.Labeled:return Lh(e,t[1])?{status:le.Greater}:On(e,t[1])?{status:le.Found,value:t[2]}:{status:le.Less};case fe.Fork:{let r=Zo(e,t[1]);switch(r.status){case le.Greater:{let n=Zo(e,t[2]);return n.status===le.Less?{status:le.Absent}:n}case le.Unknown:{let n=Zo(e,t[2]);return n.status===le.Less?{status:le.Unknown}:n}default:return r}}case fe.Pruned:return{status:le.Unknown};default:return{status:le.Absent}}}function ds(e,t){switch(t[0]){case fe.Empty|fe.Pruned:return[];case fe.Leaf:return[e];case fe.Fork:return ds(e,t[1]).concat(ds(e,t[2]));case fe.Labeled:{let r=t[1],n=t[2],o=[...e,r];return ds(o,n)}default:throw it}}function Ga(e){let t=jh(e),r=Ja(t),{canisterId:n}=e;return r.some(i=>i[0].ltEq(n)&&i[1].gtEq(n))}function jh(e){let{subnetId:t,tree:r,canisterId:n}=e,o=Xo(["canister_ranges",t.toUint8Array()],r);if(o.status!==Pr.Found)return Kh(t,r);let i=o.value,s=Hh(i);if(s.length===0)throw te.fromCode(new gn(n,t));s.sort(Mn);let a=$h(s,n),c=s[a];return Gh(c,i)}function Kh(e,t){let r=dr(["subnet",e.toUint8Array(),"canister_ranges"],t);if(r.status!==Be.Found)throw te.fromCode(new xt(`Could not find canister ranges for subnet ${e.toText()}`,r.status));return r.value}function Ja(e){return qe(e).map(n=>[k.fromUint8Array(n[0]),k.fromUint8Array(n[1])])}function Hh(e){let t=[];for(let r of ds([],e)){let n=r[0];if(!n)throw te.fromCode(new gt("Path is invalid"));t.push(n)}return t}function $h(e,t){let r=t.toUint8Array(),n=0,o=e.length-1;for(;n<o;){let i=Math.floor((n+o)/2);Mn(e[i],r)<=0?o=i:n=i+1}return n}function Gh(e,t){let r=dr([e],t);if(r.status!==Be.Found)throw te.fromCode(new xt(`Could not find canister range for shard ${e.toString()}`,r.status));return r.value}function Wa(e,t){return e.delegation?k.fromUint8Array(e.delegation.subnet_id):k.selfAuthenticating(t)}var Ku=k.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe");function fs(e,t){switch(t){case"raw":return e;case"leb128":return $a(e);case"cbor":return qe(e);case"hex":return j(e);case"utf-8":return new TextDecoder().decode(e)}}function Hu(e){return qe(e).map(r=>k.fromUint8Array(r))}function $u(e,t){let r=typeof e=="string"?$(e):e;return[$("canister"),t,$("metadata"),r]}function Br(e){return typeof e=="object"&&e!==null&&"key"in e&&"path"in e}function no(e,t){let r=Xo(["subnet",t.toUint8Array(),"node"],e.tree);if(r.status!==Pr.Found)throw te.fromCode(new xt("Node not found",r.status));if(r.value instanceof Uint8Array)throw ae.fromCode(new Er("Invalid node tree"));let n=ps(r.value),o=new Map;return n.forEach(i=>{let s=k.from(i[1]).toText(),a=dr(["public_key"],i[2]);if(a.status!==Be.Found)throw te.fromCode(new xt("Public key not found",a.status));let c=a.value;if(c.byteLength!==44)throw te.fromCode(new kn(44,c.byteLength));o.set(s,c)}),o}var Gu=async e=>{let{agent:t,paths:r,disableCertificateTimeVerification:n=!1}=e,o=k.from(e.canisterId),i=[...new Set(r)],s=new Map,a=i.map((c,u)=>{let p=Wh(c,o);return(async()=>{try{if(t.rootKey===null)throw ye.fromCode(new ot);let d=t.rootKey,l=await t.readState(o,{paths:[p]}),f=await nt.create({certificate:l.certificate,rootKey:d,principal:{canisterId:o},disableTimeVerification:n,agent:t}),h=(m,x)=>{if(x==="subnet"){let y=Jh(l.certificate,o,d);return{path:x,data:y}}else return{path:x,data:ve(m.lookup_path(p))}},{path:_,data:g}=h(f,i[u]);if(!g)typeof _=="string"?s.set(_,null):s.set(_.key,null);else switch(_){case"time":{s.set(_,Vr(g));break}case"controllers":{s.set(_,Hu(g));break}case"module_hash":{s.set(_,j(g));break}case"subnet":{s.set(_,g);break}case"candid":{s.set(_,new TextDecoder().decode(g));break}default:Br(_)&&s.set(_.key,fs(g,_.decodeStrategy))}}catch(d){if(d instanceof et&&(d.hasCode(gt)||d.hasCode(Xt)))throw d;Br(c)?s.set(c.key,null):s.set(c,null)}})()});return await Promise.all(a),s},Jh=(e,t,r)=>{if(!t._isPrincipal)throw Y.fromCode(new Re("Invalid canisterId"));let n=qe(e),{delegation:o}=n,i;o&&o.subnet_id?i=k.fromUint8Array(new Uint8Array(o.subnet_id)):!o&&typeof r<"u"?i=k.selfAuthenticating(new Uint8Array(r)):i=Ku;let s=no(n,i);return{subnetId:i.toText(),nodeKeys:s}},Wh=(e,t)=>{let r=t.toUint8Array();switch(e){case"time":return[$("time")];case"controllers":return[$("canister"),r,$("controllers")];case"module_hash":return[$("canister"),r,$("module_hash")];case"subnet":return[$("subnet")];case"candid":return[$("canister"),r,$("metadata"),$("candid:service")];default:if(Br(e))return typeof e.path=="string"||e.path instanceof Uint8Array?$u(e.path,r):e.path}throw ae.fromCode(new Re(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))};async function Ju(e){let{agent:t,paths:r,disableCertificateTimeVerification:n=!1}=e,o=k.from(e.subnetId),i=[...new Set(r)],s=new Map,a=i.map((c,u)=>{let p=zh(c,o);return(async()=>{try{if(t.rootKey===null)throw ye.fromCode(new ot);let d=t.rootKey,l=await t.readSubnetState(o,{paths:[p]}),f=await nt.create({certificate:l.certificate,rootKey:d,principal:{subnetId:o},disableTimeVerification:n,agent:t}),h=(m,x)=>{if(x==="nodeKeys"){let y=no(m.cert,o);return{path:x,data:y}}else return{path:x,data:ve(m.lookup_path(p))}},{path:_,data:g}=h(f,i[u]);if(!g)typeof _=="string"?s.set(_,null):s.set(_.key,null);else switch(_){case"time":{s.set(_,Vr(g));break}case"canisterRanges":{s.set(_,Ja(g));break}case"publicKey":{s.set(_,g);break}case"nodeKeys":{s.set(_,g);break}default:Br(_)&&s.set(_.key,fs(g,_.decodeStrategy))}}catch(d){if(d instanceof et&&(d.hasCode(gt)||d.hasCode(Xt)))throw d;Br(c)?s.set(c.key,null):s.set(c,null)}})()});return await Promise.all(a),s}function zh(e,t){let r=t.toUint8Array();switch(e){case"time":return[$("time")];case"canisterRanges":return[$("canister_ranges"),r];case"publicKey":return[$("subnet"),r,$("public_key")];case"nodeKeys":return[$("subnet"),r,$("node")];default:if(Br(e))if(typeof e.path=="string"||e.path instanceof Uint8Array){let n=typeof e.path=="string"?$(e.path):e.path;return[$("subnet"),r,n]}else return e.path}throw ae.fromCode(new Re(`Error while encoding your path for subnet status. Please ensure that your path ${e} was formatted correctly.`))}var Dr=BigInt(0),Ae=BigInt(1),za=BigInt(2),Yh=BigInt(8);function Zh(e,t,r,n){let o=e.sqr(r),i=e.sqr(n),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function Xh(e,t={}){let r=ns("edwards",e,t,t.FpFnLE),{Fp:n,Fn:o}=r,i=r.CURVE,{h:s}=i;ar(t,{},{uvRatio:"function"});let a=za<<BigInt(o.BYTES*8)-Ae,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:Dr}}});if(!Zh(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function p(g,m,x=!1){let y=x?Ae:Dr;return es("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,E=g.is0();m==null&&(m=E?Yh:n.inv(T));let O=c(x*m),R=c(y*m),v=n.mul(T,m);if(E)return{x:Dr,y:Ae};if(v!==Ae)throw new Error("invZ was invalid");return{x:O,y:R}}),f=Sr(g=>{let{a:m,d:x}=i;if(g.is0())throw new Error("bad point: ZERO");let{X:y,Y:T,Z:E,T:O}=g,R=c(y*y),v=c(T*T),w=c(E*E),I=c(w*w),F=c(R*m),S=c(w*c(F+v)),b=c(I+c(x*c(R*v)));if(S!==b)throw new Error("bad point: equation left != right (1)");let N=c(y*T),C=c(E*O);if(N!==C)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 i}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,Ae,c(x*y))}static fromBytes(m,x=!1){let y=n.BYTES,{a:T,d:E}=i;m=Ta(Ar(m,y,"point")),In(x,"zip215");let O=Ta(m),R=m[y-1];O[y-1]=R&-129;let v=ir(O),w=x?a:n.ORDER;es("point.y",v,Dr,w);let I=c(v*v),F=c(I-Ae),S=c(E*I-T),{isValid:b,value:N}=u(F,S);if(!b)throw new Error("bad point: invalid y coordinate");let C=(N&Ae)===Ae,B=(R&128)!==0;if(!x&&N===Dr&&B)throw new Error("bad point: x=0 and x_0=1");return B!==C&&(N=c(-N)),h.fromAffine({x:N,y:v})}static fromHex(m,x=!1){return h.fromBytes(pe("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(za),this}assertValidity(){f(this)}equals(m){d(m);let{X:x,Y:y,Z:T}=this,{X:E,Y:O,Z:R}=m,v=c(x*R),w=c(E*T),I=c(y*R),F=c(O*T);return v===w&&I===F}is0(){return this.equals(h.ZERO)}negate(){return new h(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:m}=i,{X:x,Y:y,Z:T}=this,E=c(x*x),O=c(y*y),R=c(za*c(T*T)),v=c(m*E),w=x+y,I=c(c(w*w)-E-O),F=v+O,S=F-R,b=v-O,N=c(I*S),C=c(F*b),B=c(I*b),q=c(S*F);return new h(N,C,q,B)}add(m){d(m);let{a:x,d:y}=i,{X:T,Y:E,Z:O,T:R}=this,{X:v,Y:w,Z:I,T:F}=m,S=c(T*v),b=c(E*w),N=c(R*y*F),C=c(O*I),B=c((T+E)*(v+w)-S-b),q=C-N,A=C+N,V=c(b-x*S),P=c(B*q),D=c(A*V),U=c(B*V),re=c(q*A);return new h(P,D,re,U)}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=>ct(h,T));return ct(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===Dr?h.ZERO:this.is0()||m===Ae?this:_.unsafe(this,m,y=>ct(h,y),x)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return _.unsafe(this,i.n).is0()}toAffine(m){return l(this,m)}clearCofactor(){return s===Ae?this:this.multiplyUnsafe(s)}toBytes(){let{x:m,y:x}=this.toAffine(),y=n.toBytes(x);return y[y.length-1]|=m&Ae?128:0,y}toHex(){return j(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 ct(h,m)}static msm(m,x){return eo(h,o,m,x)}_setWindowSize(m){this.precompute(m)}toRawBytes(){return this.toBytes()}}h.BASE=new h(i.Gx,i.Gy,Ae,c(i.Gx*i.Gy)),h.ZERO=new h(Dr,Ae,Ae,Dr),h.Fp=n,h.Fn=o;let _=new Qn(h,o.BITS);return h.BASE.precompute(8),h}var hs=class{constructor(t){this.ep=t}static fromBytes(t){Zn()}static fromHex(t){Zn()}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 j(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 Qh(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');ar(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:i,Fn:s}=e,a=r.randomBytes||Un,c=r.adjustScalarBytes||(w=>w),u=r.domain||((w,I,F)=>{if(In(F,"phflag"),I.length||F)throw new Error("Contexts/pre-hash are not supported");return w});function p(w){return s.create(ir(w))}function d(w){let I=y.secretKey;w=pe("private key",w,I);let F=pe("hashed private key",t(w),2*I),S=c(F.slice(0,I)),b=F.slice(I,2*I),N=p(S);return{head:S,prefix:b,scalar:N}}function l(w){let{head:I,prefix:F,scalar:S}=d(w),b=o.multiply(S),N=b.toBytes();return{head:I,prefix:F,scalar:S,point:b,pointBytes:N}}function f(w){return l(w).pointBytes}function h(w=Uint8Array.of(),...I){let F=K(...I);return p(t(u(F,pe("context",w),!!n)))}function _(w,I,F={}){w=pe("message",w),n&&(w=n(w));let{prefix:S,scalar:b,pointBytes:N}=l(I),C=h(F.context,S,w),B=o.multiply(C).toBytes(),q=h(F.context,B,N,w),A=s.create(C+q*b);if(!s.isValid(A))throw new Error("sign failed: invalid s");let V=K(B,s.toBytes(A));return Ar(V,y.signature,"result")}let g={zip215:!0};function m(w,I,F,S=g){let{context:b,zip215:N}=S,C=y.signature;w=pe("signature",w,C),I=pe("message",I),F=pe("publicKey",F,y.publicKey),N!==void 0&&In(N,"zip215"),n&&(I=n(I));let B=C/2,q=w.subarray(0,B),A=ir(w.subarray(B,C)),V,P,D;try{V=e.fromBytes(F,N),P=e.fromBytes(q,N),D=o.multiplyUnsafe(A)}catch{return!1}if(!N&&V.isSmallOrder())return!1;let U=h(b,P.toBytes(),V.toBytes(),I);return P.add(V.multiplyUnsafe(U)).subtract(D).clearCofactor().is0()}let x=i.BYTES,y={secretKey:x,publicKey:x,signature:2*x,seed:x};function T(w=a(y.seed)){return Ar(w,y.seed,"seed")}function E(w){let I=v.randomSecretKey(w);return{secretKey:I,publicKey:f(I)}}function O(w){return At(w)&&w.length===s.BYTES}function R(w,I){try{return!!e.fromBytes(w,I)}catch{return!1}}let v={getExtendedPublicKey:l,randomSecretKey:T,isValidSecretKey:O,isValidPublicKey:R,toMontgomery(w){let{y:I}=e.fromBytes(w),F=y.publicKey,S=F===32;if(!S&&F!==57)throw new Error("only defined for 25519 and 448");let b=S?i.div(Ae+I,Ae-I):i.div(I-Ae,I+Ae);return i.toBytes(b)},toMontgomerySecret(w){let I=y.secretKey;Ar(w,I);let F=t(w.subarray(0,I));return c(F).subarray(0,I)},randomPrivateKey:T,precompute(w=8,I=e.BASE){return I.precompute(w,!1)}};return Object.freeze({keygen:E,getPublicKey:f,sign:_,verify:m,utils:v,Point:e,lengths:y})}function em(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=je(t.n,e.nBitLength,!0),o={Fp:r,Fn:n,uvRatio:e.uvRatio},i={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:o,hash:e.hash,eddsaOpts:i}}function tm(e,t){let r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function Wu(e){let{CURVE:t,curveOpts:r,hash:n,eddsaOpts:o}=em(e),i=Xh(t,r),s=Qh(i,n,o);return tm(e,s)}var rm=BigInt(0),pr=BigInt(1),zu=BigInt(2),Xg=BigInt(3),nm=BigInt(5),om=BigInt(8),oo=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Qo={p:oo,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:om,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function im(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=oo,a=e*e%i*e%i,c=It(a,zu,i)*a%i,u=It(c,pr,i)*e%i,p=It(u,nm,i)*u%i,d=It(p,t,i)*p%i,l=It(d,r,i)*d%i,f=It(l,n,i)*l%i,h=It(f,o,i)*f%i,_=It(h,o,i)*f%i,g=It(_,t,i)*p%i;return{pow_p_5_8:It(g,zu,i)*e%i,b2:a}}function sm(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Ya=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Qa(e,t){let r=oo,n=ce(t*t*t,r),o=ce(n*n*t,r),i=im(e*o).pow_p_5_8,s=ce(e*n*i,r),a=ce(t*s*s,r),c=s,u=ce(s*Ya,r),p=a===e,d=a===ce(-e,r),l=a===ce(-e*Ya,r);return p&&(s=c),(d||l)&&(s=u),cr(s,r)&&(s=ce(-s,r)),{isValid:p||d,value:s}}var Ur=je(Qo.p,{isLE:!0}),am=je(Qo.n,{isLE:!0}),cm={...Qo,Fp:Ur,hash:ml,adjustScalarBytes:sm,uvRatio:Qa},$e=Wu(cm);var Za=Ya,lm=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),um=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),dm=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),pm=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Yu=e=>Qa(pr,e),fm=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Xa=e=>$e.Point.Fp.create(ir(e)&fm);function Zu(e){let{d:t}=Qo,r=oo,n=m=>Ur.create(m),o=n(Za*e*e),i=n((o+pr)*dm),s=BigInt(-1),a=n((s-t*o)*n(o+t)),{isValid:c,value:u}=Qa(i,a),p=n(u*e);cr(p,r)||(p=n(-p)),c||(u=p),c||(s=o);let d=n(s*(o-pr)*pm-a),l=u*u,f=n((u+u)*a),h=n(d*lm),_=n(pr-l),g=n(pr+l);return new $e.Point(n(f*g),n(_*h),n(h*g),n(f*_))}function hm(e){me(e,64);let t=Xa(e.subarray(0,32)),r=Zu(t),n=Xa(e.subarray(32,64)),o=Zu(n);return new fr(r.add(o))}var fr=class e extends hs{constructor(t){super(t)}static fromAffine(t){return new e($e.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static hashToCurve(t){return hm(pe("ristrettoHash",t,64))}static fromBytes(t){me(t,32);let{a:r,d:n}=Qo,o=oo,i=T=>Ur.create(T),s=Xa(t);if(!au(Ur.toBytes(s),t)||cr(s,o))throw new Error("invalid ristretto255 encoding 1");let a=i(s*s),c=i(pr+r*a),u=i(pr-r*a),p=i(c*c),d=i(u*u),l=i(r*n*p-d),{isValid:f,value:h}=Yu(i(l*d)),_=i(h*u),g=i(h*_*l),m=i((s+s)*_);cr(m,o)&&(m=i(-m));let x=i(c*g),y=i(m*x);if(!f||cr(y,o)||x===rm)throw new Error("invalid ristretto255 encoding 2");return new e(new $e.Point(m,x,pr,y))}static fromHex(t){return e.fromBytes(pe("ristrettoHex",t,32))}static msm(t,r){return eo(e,$e.Point.Fn,t,r)}toBytes(){let{X:t,Y:r,Z:n,T:o}=this.ep,i=oo,s=g=>Ur.create(g),a=s(s(n+r)*s(n-r)),c=s(t*r),u=s(c*c),{value:p}=Yu(s(a*u)),d=s(p*a),l=s(p*c),f=s(d*l*o),h;if(cr(o*f,i)){let g=s(r*Za),m=s(t*Za);t=g,r=m,h=s(d*um)}else h=l;cr(t*f,i)&&(r=s(-r));let _=s((n-r)*h);return cr(_,i)&&(_=s(-_)),Ur.toBytes(_)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:o,Y:i}=t.ep,s=u=>Ur.create(u),a=s(r*i)===s(n*o),c=s(n*i)===s(r*o);return a||c}is0(){return this.equals(e.ZERO)}};fr.BASE=new fr($e.Point.BASE);fr.ZERO=new fr($e.Point.ZERO);fr.Fp=Ur;fr.Fn=am;var Xu,Qu,ms=class{static{Xu=Symbol.iterator,Qu=Symbol.toStringTag}#e;#t;constructor(t={}){this[Xu]=this.entries.bind(this),this[Qu]="ExpirableMap";let{source:r=[],expirationTime:n=600*1e3}=t,o=Date.now();this.#e=new Map([...r].map(([i,s])=>[i,{value:s,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 ed=e=>{if(e<=127)return 1;if(e<=255)return 2;if(e<=65535)return 3;if(e<=16777215)return 4;throw Y.fromCode(new wo("Length too long (> 4 bytes)"))},td=(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 Y.fromCode(new wo("Length too long (> 4 bytes)"))},ec=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw Y.fromCode(new bt("Invalid length 0"));if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw Y.fromCode(new bt("Length too long (> 4 bytes)"))},mm=(e,t)=>{let r=ec(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 Y.fromCode(new bt("Length too long (> 4 bytes)"))},ei=Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]),Fn=Uint8Array.from([48,5,6,3,43,101,112]),nx=Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]),ox=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 Vn(e,t){let r=2+ed(e.byteLength+1),n=t.byteLength+r+e.byteLength,o=0,i=new Uint8Array(1+ed(n)+n);return i[o++]=48,o+=td(i,o,n),i.set(t,o),o+=t.byteLength,i[o++]=3,o+=td(i,o,e.byteLength+1),i[o++]=0,i.set(new Uint8Array(e),o),i}var Pn=(e,t)=>{let r=0,n=(a,c)=>{if(o[r++]!==a)throw Y.fromCode(new bt(`Expected ${c} at offset ${r}`))},o=new Uint8Array(e);if(n(48,"sequence"),r+=ec(o,r),!On(o.slice(r,r+t.byteLength),t))throw Y.fromCode(new bt("Not the expected OID."));r+=t.byteLength,n(3,"bit string");let i=mm(o,r)-1;r+=ec(o,r),n(0,"0 padding");let s=o.slice(r);if(i!==s.length)throw Y.fromCode(new Ei(i,s.length));return s};var _s=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 Vn(t,Fn)}static derDecode(t){let r=Pn(t,Fn);if(r.length!==this.RAW_KEY_LENGTH)throw Y.fromCode(new bt("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 Y.fromCode(new bt("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 tc=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))}},ys=class extends tc{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 gs=class e{#e;#t;#r;#i;#a;#d;#n;#o;#c=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:i=6e4,maxElapsedTime:s=9e5,maxIterations:a=10,date:c=Date}=t;this.#e=r,this.#t=n,this.#r=o,this.#i=i,this.#o=c,this.#a=c.now(),this.#d=s,this.#n=a}get ellapsedTimeInMsec(){return this.#o.now()-this.#a}get currentInterval(){return this.#e}get count(){return this.#c}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.#i),this.#c++,this.#e}next(){return this.ellapsedTimeInMsec>=this.#d||this.#c>=this.#n?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};var Ut;(function(e){e.Received="received",e.Processing="processing",e.Replied="replied",e.Rejected="rejected",e.Unknown="unknown",e.Done="done"})(Ut||(Ut={}));var oc=60*1e3,_m=1e6,ym=0,gm="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae";var xm="ic0.app",bm=".ic0.app",wm="icp0.io",Tm=".icp0.io",Nm="icp-api.io",Om=".icp-api.io",rc=200,Em=202,Rm=404;function Im(){let e;if(typeof window<"u")if(window.fetch)e=window.fetch.bind(window);else throw ye.fromCode(new qn("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 ye.fromCode(new qn("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 ye.fromCode(new qn("Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context."))}function vm(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,i=o?.hostname,s;i&&typeof i=="string"&&(n.some(a=>i.endsWith(a))?s=i:s=r.find(a=>i.endsWith(a))),o&&s?t=new URL(`${o.protocol}//${s}${o.port?":"+o.port:""}`):t=new URL("https://icp-api.io")}return t.toString()}var hr=class e{#e;#t;#r;#i;#a;#d;#n;#o;#c;#w;#s;#u;#f;#l;get#E(){return this.#l*oc}#h;#m;#_;#y;constructor(t={}){this.#e=null,this.#t=!1,this.#r=ym,this.#i=!1,this.#a=null,this.#d=!1,this._isAgent=!0,this.config={},this.log=new ys,this.#h=[],this.#m=[],this.#_=new ms({expirationTime:5*oc}),this.#y=!0,this.#T=(o,i)=>{if(this.#y===!1)return o;let{status:s,signatures:a=[],requestId:c}=o;for(let u of a){let{timestamp:p,identity:d}=u,l=k.fromUint8Array(d).toText(),f;if(s===xr.Replied){let{reply:x}=o;f=Vo({status:s,reply:x,timestamp:BigInt(p),request_id:c})}else if(s===xr.Rejected){let{reject_code:x,reject_message:y,error_code:T}=o;f=Vo({status:s,reject_code:x,reject_message:y,error_code:T,timestamp:BigInt(p),request_id:c})}else throw ae.fromCode(new Re(`Unknown status: ${s}`));let h=K(ua,f),_=i.get(l);if(!_)throw te.fromCode(new Di);let g=_s.fromDer(_).rawKey;if(!$e.verify(u.signature,h,g))throw ke.fromCode(new Ui(l))}return o},this.config=t,this.#o=t.fetch||Im()||fetch.bind(global),this.#c=t.fetchOptions,this.#w=t.callOptions,this.#t=t.shouldFetchRootKey??!1,this.#d=t.shouldSyncTime??!1,t.rootKey?this.rootKey=t.rootKey:this.#t?this.rootKey=null:this.rootKey=Ee(gm);let r=vm(t.host);this.host=new URL(r),t.verifyQuerySignatures!==void 0&&(this.#y=t.verifyQuerySignatures),this.#u=t.retryTimes??3;let n=()=>new gs({maxIterations:this.#u});if(this.#f=t.backoffStrategy||n,this.host.hostname.endsWith(bm)?this.host.hostname=xm:this.host.hostname.endsWith(Tm)?this.host.hostname=wm:this.host.hostname.endsWith(Om)&&(this.host.hostname=Nm),t.credentials){let{name:o,password:i}=t.credentials;this.#s=`${o}${i?":"+i:""}`}if(this.#n=Promise.resolve(t.identity||new tt),t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes>5)throw Y.fromCode(new Ct("The maximum ingress expiry time is 5 minutes.",t.ingressExpiryInMinutes));if(t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes<=0)throw Y.fromCode(new Ct("Ingress expiry time must be greater than 0.",t.ingressExpiryInMinutes));this.#l=t.ingressExpiryInMinutes||5,this.addTransform("update",ya(Mo)),t.useQueryNonces&&this.addTransform("query",ya(Mo)),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.#p(),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 Y.fromCode(new Vi)}}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.#m.findIndex(i=>(i.priority||0)<n);this.#m.splice(o>=0?o:this.#m.length,0,Object.assign(r,{priority:n}))}else if(t==="query"){let o=this.#h.findIndex(i=>(i.priority||0)<n);this.#h.splice(o>=0?o:this.#h.length,0,Object.assign(r,{priority:n}))}}async getPrincipal(){if(!this.#n)throw ye.fromCode(new Or);return(await this.#n).getPrincipal()}async call(t,r,n){let o=r.callSync??!0,i=await(n??this.#n);if(!i)throw ye.fromCode(new Or);let s=k.from(t),a=r.effectiveCanisterId?k.from(r.effectiveCanisterId):s;await this.#p(a);let c=i.getPrincipal(),u=nc(this.#l,this.#r),p={request_type:Zi.Call,canister_id:s,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:or.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 i.transformRequest(d);let h=Lo(d.body),_=this.#f(),g=rr(p);try{let y=o?()=>{let R=new URL(`/api/v4/canister/${a.toText()}/call`,this.host);return this.log.print(`fetching "${R.pathname}" with request:`,d),this.#o(R,{...this.#w,...d.request,body:h})}:()=>{let R=new URL(`/api/v2/canister/${a.toText()}/call`,this.host);return this.log.print(`fetching "${R.pathname}" with request:`,d),this.#o(R,{...this.#w,...d.request,body:h})},{responseBodyBytes:T,...E}=await this.#g({requestFn:y,backoff:_,tries:0}),O=T.byteLength>0?qe(T):null;return{requestId:g,response:{...E,body:O},requestDetails:p}}catch(m){let x;if(m instanceof et){if(m.hasCode(No))return this.log.warn("v4 api not supported. Fall back to v2"),this.call(t,{...r,callSync:!1},n);if(m.hasCode(Ct)&&!this.#i)return await this.syncTime(s),this.call(s,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=ae.fromCode(new Re(m));throw this.log.error(`Error while making call: ${x.message}`,x),x}}async#b(t){let{ecid:r,transformedRequest:n,body:o,requestId:i,backoff:s,tries:a}=t,c=a===0?0:s.next(),u=new URL(`/api/v3/canister/${r.toString()}/query`,this.host);if(this.log.print(`fetching "${u.pathname}" with tries:`,{tries:a,backoff:s,delay:c}),c===null)throw ae.fromCode(new xn(`Backoff strategy exhausted after ${a} attempts.`,i));c>0&&await new Promise(m=>setTimeout(m,c));let p;try{this.log.print(`fetching "${u.pathname}" with request:`,n),p=await this.#o(u,{...this.#c,...n.request,body:o})}catch(m){if(a<this.#u)return this.log.warn(`Caught exception while attempting to make query:
48
+ `)}return a.encodeValue(c)}));return Z(Of,n,o,i,s)}function Rf(e,t){let r=new wt(t);if(t.byteLength<Ki.length)throw new Error("Message length smaller than magic number");let n=Pr(r,Ki.length),o=new TextDecoder().decode(n);if(o!==Ki)throw new Error("Wrong magic number: "+JSON.stringify(o));function i(l){let f=[],h=Number(ge(l));for(let m=0;m<h;m++){let x=Number(ir(l));switch(x){case Q.Opt:case Q.Vector:{let y=Number(ir(l));f.push([x,y]);break}case Q.Record:case Q.Variant:{let y=[],T=Number(ge(l)),E;for(;T--;){let O=Number(ge(l));if(O>=Math.pow(2,32))throw new Error("field id out of 32-bit range");if(typeof E=="number"&&E>=O)throw new Error("field id collision or not sorted");E=O;let R=Number(ir(l));y.push([O,R])}f.push([x,y]);break}case Q.Func:{let y=[],T=Number(ge(l));for(;T--;)y.push(Number(ir(l)));let E=[],O=Number(ge(l));for(;O--;)E.push(Number(ir(l)));let R=[],v=Number(ge(l));for(;v--;)switch(Number(ge(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,[y,E,R]]);break}case Q.Service:{let y=Number(ge(l)),T=[];for(;y--;){let E=Number(ge(l)),O=new TextDecoder().decode(Pr(l,E)),R=ir(l);T.push([O,R])}f.push([x,T]);break}default:throw new Error("Illegal op_code: "+x)}}let _=[],g=Number(ge(l));for(let m=0;m<g;m++)_.push(Number(ir(l)));return[f,_]}let[s,a]=i(r);if(a.length<e.length)throw new Error("Wrong number of return values");let c=s.map(l=>iu());function u(l){if(l<-24)throw new Error("future value not supported");if(l<0)switch(l){case-1:return Ll;case-2:return kl;case-3:return jl;case-4:return Ml;case-5:return zl;case-6:return Yl;case-7:return Zl;case-8:return Xl;case-9:return $l;case-10:return Gl;case-11:return Jl;case-12:return Wl;case-13:return Kl;case-14:return Hl;case-15:return ql;case-16:return Ul;case-17:return Dl;case-24:return Ql;default:throw new Error("Illegal op_code: "+l)}if(l>=s.length)throw new Error("type index out of range");return c[l]}function p(l){switch(l[0]){case Q.Vector:{let f=u(l[1]);return tu(f)}case Q.Opt:{let f=u(l[1]);return ru(f)}case Q.Record:{let f={};for(let[g,m]of l[1]){let x=`_${g}_`;f[x]=u(m)}let h=nu(f),_=h.tryAsTuple();return Array.isArray(_)?eu(..._):h}case Q.Variant:{let f={};for(let[h,_]of l[1]){let g=`_${h}_`;f[g]=u(_)}return ou(f)}case Q.Func:{let[f,h,_]=l[1];return su(f.map(g=>u(g)),h.map(g=>u(g)),_)}case Q.Service:{let f={},h=l[1];for(let[_,g]of h){let m=u(g);if(m instanceof lt&&(m=m.getType()),!(m instanceof Rn))throw new Error("Illegal service definition: services can only contain functions");f[_]=m}return au(f)}default:throw new Error("Illegal op_code: "+l[0])}}s.forEach((l,f)=>{if(l[0]===Q.Func){let h=p(l);c[f].fill(h)}}),s.forEach((l,f)=>{if(l[0]!==Q.Func){let h=p(l);c[f].fill(h)}}),xa();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{xa()}}var Dl=new Fo,Ul=new Bt,If=new $i,kl=new Gi,Ll=new On,ql=new Ji,Ml=new Po,jl=new Vo,Kl=new Bo(32),Hl=new Bo(64),$l=new ar(8),Gl=new ar(16),Jl=new ar(32),Wl=new ar(64),zl=new Pt(8),Yl=new Pt(16),Zl=new Pt(32),Xl=new Pt(64),Ql=new zi;function eu(...e){return new Wi(e)}function tu(e){return new Wn(e)}function ru(e){return new Vr(e)}function nu(e){return new En(e)}function ou(e){return new zn(e)}function iu(){return new lt}function su(e,t,r=[]){return new Rn(e,t,r)}function au(e){return new Yn(e)}var Yi=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,i]of n)t+=`${r} ${i?":<":"!<:"} ${o}
49
+ `;return t}addNames(t,r,n){let o=this.rels.get(t);if(o==null){let i=new Map;i.set(r,n),this.rels.set(t,i)}else o.set(r,n)}},Hi=new Yi;function xa(){Hi=new Yi}function vf(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 _a(e){return e instanceof Vr||e instanceof On||e instanceof Bt}function wa(e,t){let r=Hi.copy(),n=sr(r,e,t);return n?Hi.add(e,t):Hi.addNegative(e,t),n}function sr(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 Bt||t instanceof Fo||t instanceof Vo&&r instanceof Po)return!0;if(t instanceof Wn&&r instanceof Wn)return sr(e,t._type,r._type);if(r instanceof Vr)return!0;if(t instanceof En&&r instanceof En){let o=t.fieldsAsObject;for(let[i,s]of r._fields){let a=o[qe(i)];if(a){if(!sr(e,a,s))return!1}else if(!_a(s))return!1}return!0}if(t instanceof Rn&&r instanceof Rn){if(!vf(t,r))return!1;for(let o=0;o<t.argTypes.length;o++){let i=t.argTypes[o];if(o<r.argTypes.length){if(!sr(e,r.argTypes[o],i))return!1}else if(!_a(i))return!1}for(let o=0;o<r.retTypes.length;o++){let i=r.retTypes[o];if(o<t.retTypes.length){if(!sr(e,t.retTypes[o],i))return!1}else if(!_a(i))return!1}return!0}if(t instanceof zn&&r instanceof zn){let o=r.alternativesAsObject;for(let[i,s]of t._fields){let a=o[qe(i)];if(!a||!sr(e,s,a))return!1}return!0}if(t instanceof Yn&&r instanceof Yn){let o=t.fieldsAsObject();for(let[i,s]of r._fields){let a=o[i];if(!a||!sr(e,a,s))return!1}return!0}return t instanceof lt?sr(e,t.getType(),r):r instanceof lt?sr(e,t,r.getType()):!1}function Zn(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?Zn(e.buffer):new Uint8Array(e)}function vn(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 Ta(e){if(typeof e=="string")return cu(e);if(typeof e=="number")return Pe(ie(e));if(e instanceof Uint8Array||ArrayBuffer.isView(e))return Pe(Zn(e));if(Array.isArray(e)){let t=e.map(Ta);return Pe(K(...t))}else{if(e&&typeof e=="object"&&e._isPrincipal)return Pe(e.toUint8Array());if(typeof e=="object"&&e!==null&&typeof e.toHash=="function")return Ta(e.toHash());if(typeof e=="object")return Do(e);if(typeof e=="bigint")return Pe(ie(e))}throw Y.fromCode(new Bi(e))}var cu=e=>{let t=new TextEncoder().encode(e);return Pe(t)};function cr(e){return Do(e)}function Do(e){let n=Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>{let c=cu(s),u=Ta(a);return[c,u]}).sort(([s],[a])=>Gn(s,a)),o=K(...n.map(s=>K(...s)));return Pe(o)}var Na=new TextEncoder().encode("\ric-state-root"),Uo=new TextEncoder().encode(`
50
+ ic-request`),Oa=new TextEncoder().encode("\vic-response"),Ea=new TextEncoder().encode("ic-request-auth-delegation");var Dt=class{getPrincipal(){return this._principal||(this._principal=U.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()))),this._principal}async transformRequest(t){let{body:r,...n}=t,o=cr(r);return{...n,body:{content:r,sender_pubkey:this.getPublicKey().toDer(),sender_sig:await this.sign(K(Uo,o))}}}},ot=class{getPrincipal(){return U.anonymous()}async transformRequest(t){return{...t,body:{content:t.body}}}};var lr=class extends Error{constructor(t){super(t),this.name="DecodingError"}},uu=55799,du=Symbol("CBOR_STOP_CODE"),Ot=(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))(Ot||{}),Ne=(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))(Ne||{}),Af=23,Sf=255,Cf=65535,Ff=4294967295,Pf=BigInt("0xffffffffffffffff"),Nt=(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))(Nt||{}),Xn=!1;function Vf(e){return e==null}function pu(e,t){let r=new Uint8Array(t);return r.set(e),r}var Bf=new TextDecoder;function Df(e){return(e&224)>>5}function Uf(e){return e&31}var qo=new Uint8Array,ko,Et=0;function fu(e,t){qo=e,Et=0;let r=An(t);return t?.(r)??r}function An(e){let[t,r]=Zi();switch(t){case Ne.UnsignedInteger:return Qn(r);case Ne.NegativeInteger:return Mf(r);case Ne.ByteString:return hu(r);case Ne.TextString:return Ia(r);case Ne.Array:return kf(r,e);case Ne.Map:return qf(r,e);case Ne.Tag:return jf(r,e);case Ne.Simple:return Lf(r)}throw new lr(`Unsupported major type: ${t}`)}function Zi(){let e=qo.at(Et);if(Vf(e))throw new lr("Provided CBOR data is empty");let t=Df(e),r=Uf(e);return Et++,[t,r]}function kf(e,t){let r=Qn(e);if(r===1/0){let o=[],i=An(t);for(;i!==du;)o.push(t?.(i)??i),i=An(t);return o}let n=new Array(r);for(let o=0;o<r;o++){let i=An(t);n[o]=t?.(i)??i}return n}function Lf(e){switch(e){case Ot.False:return!1;case Ot.True:return!0;case Ot.Null:return null;case Ot.Undefined:return;case Ot.Break:return du}throw new lr(`Unrecognized simple type: ${e.toString(2)}`)}function qf(e,t){let r=Qn(e),n={};if(r===1/0){let[o,i]=Zi();for(;o!==Ne.Simple&&i!==Ot.Break;){let s=Ia(i),a=An(t);n[s]=t?.(a,s)??a,[o,i]=Zi()}return n}for(let o=0;o<r;o++){let[i,s]=Zi();if(i!==Ne.TextString)throw new lr("Map keys must be text strings");let a=Ia(s),c=An(t);n[a]=t?.(c,a)??c}return n}function Qn(e){if(e<=Nt.Value)return e;switch(ko=new DataView(qo.buffer,qo.byteOffset+Et),e){case Nt.OneByte:return Et++,ko.getUint8(0);case Nt.TwoBytes:return Et+=2,ko.getUint16(0,Xn);case Nt.FourBytes:return Et+=4,ko.getUint32(0,Xn);case Nt.EightBytes:return Et+=8,ko.getBigUint64(0,Xn);case Nt.Indefinite:return 1/0;default:throw new lr(`Unsupported integer info: ${e.toString(2)}`)}}function Mf(e){let t=Qn(e);return typeof t=="number"?-1-t:-1n-t}function hu(e){let t=Qn(e);if(t>Number.MAX_SAFE_INTEGER)throw new lr("Byte length is too large");let r=Number(t);return Et+=r,qo.slice(Et-r,Et)}function Ia(e){let t=hu(e);return Bf.decode(t)}function jf(e,t){let r=Qn(e);if(r===uu)return An(t);throw new lr(`Unsupported tag: ${r}.`)}var Mo=class extends Error{constructor(t){super(t),this.name="SerializationError"}},Kf=2*1024,Hf=100,$f=new TextEncoder;function Lo(e){return e<<5}var it=new Uint8Array(Kf),Tt=new DataView(it.buffer),Te=0,Ra=[];function mu(e,t){Te=0;let r=t?.(e)??e;return Qf(uu,r,t),it.slice(0,Te)}function va(e,t){if(Te>it.length-Hf&&(it=pu(it,it.length*2),Tt=new DataView(it.buffer)),e===!1||e===!0||e===null||e===void 0){Wf(e);return}if(typeof e=="number"||typeof e=="bigint"){Xf(e);return}if(typeof e=="string"){gu(e);return}if(e instanceof Uint8Array){lu(e);return}if(e instanceof ArrayBuffer){lu(new Uint8Array(e));return}if(Array.isArray(e)){Gf(e,t);return}if(typeof e=="object"){Jf(e,t);return}throw new Mo(`Unsupported type: ${typeof e}`)}function Gf(e,t){eo(Ne.Array,e.length),e.forEach((r,n)=>{va(t?.(r,n.toString())??r,t)})}function Jf(e,t){Ra=Object.entries(e),eo(Ne.Map,Ra.length),Ra.forEach(([r,n])=>{gu(r),va(t?.(n,r)??n,t)})}function eo(e,t){if(t<=Af){Tt.setUint8(Te++,Lo(e)|Number(t));return}if(t<=Sf){Tt.setUint8(Te++,Lo(e)|Nt.OneByte),Tt.setUint8(Te,Number(t)),Te+=1;return}if(t<=Cf){Tt.setUint8(Te++,Lo(e)|Nt.TwoBytes),Tt.setUint16(Te,Number(t),Xn),Te+=2;return}if(t<=Ff){Tt.setUint8(Te++,Lo(e)|Nt.FourBytes),Tt.setUint32(Te,Number(t),Xn),Te+=4;return}if(t<=Pf){Tt.setUint8(Te++,Lo(e)|Nt.EightBytes),Tt.setBigUint64(Te,BigInt(t),Xn),Te+=8;return}throw new Mo(`Value too large to encode: ${t}`)}function Wf(e){eo(Ne.Simple,zf(e))}function zf(e){if(e===!1)return Ot.False;if(e===!0)return Ot.True;if(e===null)return Ot.Null;if(e===void 0)return Ot.Undefined;throw new Mo(`Unrecognized simple value: ${e.toString()}`)}function _u(e,t){eo(e,t.length),Te>it.length-t.length&&(it=pu(it,it.length+t.length),Tt=new DataView(it.buffer)),it.set(t,Te),Te+=t.length}function yu(e,t){eo(e,t)}function Yf(e){yu(Ne.UnsignedInteger,e)}function Zf(e){yu(Ne.NegativeInteger,typeof e=="bigint"?-1n-e:-1-e)}function Xf(e){e>=0?Yf(e):Zf(e)}function gu(e){_u(Ne.TextString,$f.encode(e))}function lu(e){_u(Ne.ByteString,e)}function Qf(e,t,r){eo(Ne.Tag,e),va(t,r)}function th(e){return typeof e=="object"&&e!==null&&"toCborValue"in e}function jo(e){try{return mu(e,t=>U.isPrincipal(t)?t.toUint8Array():to.isExpiry(t)?t.toBigInt():th(t)?t.toCborValue():t)}catch(t){throw Y.fromCode(new Si(t,e))}}function Me(e){try{return fu(e)}catch(t){throw Y.fromCode(new Ai(t,e))}}var Xi={encode:jo,decode:Me};var Ko=()=>{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 ur;(function(e){e.Query="read",e.ReadState="read_state",e.Call="call"})(ur||(ur={}));var es;(function(e){e.Call="call"})(es||(es={}));var Sn;(function(e){e.Query="query",e.ReadState="read_state"})(Sn||(Sn={}));function Ho(){let e=new ArrayBuffer(16),t=new DataView(e),r=Ko(),n=Ko(),o=Ko(),i=Ko();return t.setUint32(0,r),t.setUint32(4,n),t.setUint32(8,o),t.setUint32(12,i),Object.assign(new Uint8Array(e),{__nonce__:void 0})}var ts="__expiry__",Aa=BigInt(1e3),rh=BigInt(1e6),nh=BigInt(60),Sa=nh*Aa,oh=BigInt(1)*Sa;function ih(e){return e/Aa*Aa}function sh(e){return e/Sa*Sa}var to=class e{constructor(t){this.__expiry__=t,this._isExpiry=!0}static fromDeltaInMilliseconds(t,r=0){let n=BigInt(Date.now())+BigInt(r),o=n+BigInt(t),i=sh(o),s;return i>=n+oh?s=i:s=ih(o),new e(s*rh)}toBigInt(){return this.__expiry__}toHash(){return ie(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[ts]:this.toString()}}static fromJSON(t){let r=JSON.parse(t);if(r[ts])try{let n=BigInt(r[ts]);return new e(n)}catch(n){throw new Y(new Ao(`Not a valid BigInt: ${n}`))}throw new Y(new Ao(`The input does not contain the key ${ts}`))}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 Ca(e=Ho){return async t=>{let r=t.request.headers;t.request.headers=r,t.endpoint===ur.Call&&(t.body.nonce=e())}}function Fa(e){let t=[];return e.forEach((r,n)=>{t.push([n,r])}),t}var Va=BigInt(0),rs=BigInt(1);function Cn(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}"`;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function Br(e,t,r=""){let n=At(e),o=e?.length,i=t!==void 0;if(!n||i&&o!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return e}function xu(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Va:BigInt("0x"+e)}function Ye(e){return xu(j(e))}function dr(e){return me(e),xu(j(Uint8Array.from(e).reverse()))}function Oe(e,t){return Ee(e.toString(16).padStart(t*2,"0"))}function Ba(e,t){return Oe(e,t).reverse()}function pe(e,t,r){let n;if(typeof t=="string")try{n=Ee(t)}catch(i){throw new Error(e+" must be hex string or Uint8Array, cause: "+i)}else if(At(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 bu(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 Da(e){return Uint8Array.from(e)}var Pa=e=>typeof e=="bigint"&&Va<=e;function Ua(e,t,r){return Pa(e)&&Pa(t)&&Pa(r)&&t<=e&&e<r}function ns(e,t,r,n){if(!Ua(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function pr(e){let t;for(t=0;e>Va;e>>=rs,t+=1);return t}function wu(e,t){return e>>BigInt(t)&rs}var Rt=e=>(rs<<BigInt(e))-rs;function Tu(e){return typeof e=="function"&&Number.isSafeInteger(e.outputLen)}function fr(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(o,i,s){let a=e[o];if(s&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${c}`)}Object.entries(t).forEach(([o,i])=>n(o,i,!1)),Object.entries(r).forEach(([o,i])=>n(o,i,!0))}var ro=()=>{throw new Error("not implemented")};function Dr(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let i=e(r,...n);return t.set(r,i),i}}var je=BigInt(0),Ie=BigInt(1),Fn=BigInt(2),Ou=BigInt(3),Eu=BigInt(4),Ru=BigInt(5),ah=BigInt(7),Iu=BigInt(8),ch=BigInt(9),vu=BigInt(16);function le(e,t){let r=e%t;return r>=je?r:t+r}function It(e,t,r){let n=e;for(;t-- >je;)n*=n,n%=r;return n}function Nu(e,t){if(e===je)throw new Error("invert: expected non-zero number");if(t<=je)throw new Error("invert: expected positive modulus, got "+t);let r=le(e,t),n=t,o=je,i=Ie,s=Ie,a=je;for(;r!==je;){let u=n/r,p=n%r,d=o-s*u,l=i-a*u;n=r,r=p,o=s,i=a,s=d,a=l}if(n!==Ie)throw new Error("invert: does not exist");return le(o,t)}function ka(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function Au(e,t){let r=(e.ORDER+Ie)/Eu,n=e.pow(t,r);return ka(e,n,t),n}function lh(e,t){let r=(e.ORDER-Ru)/Iu,n=e.mul(t,Fn),o=e.pow(n,r),i=e.mul(t,o),s=e.mul(e.mul(i,Fn),o),a=e.mul(i,e.sub(s,e.ONE));return ka(e,a,t),a}function uh(e){let t=Ke(e),r=Su(e),n=r(t,t.neg(t.ONE)),o=r(t,n),i=r(t,t.neg(n)),s=(e+ah)/vu;return(a,c)=>{let u=a.pow(c,s),p=a.mul(u,n),d=a.mul(u,o),l=a.mul(u,i),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 ka(a,g,c),g}}function Su(e){if(e<Ou)throw new Error("sqrt is not defined for small field");let t=e-Ie,r=0;for(;t%Fn===je;)t/=Fn,r++;let n=Fn,o=Ke(e);for(;$o(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Au;let i=o.pow(n,t),s=(t+Ie)/Fn;return function(c,u){if(c.is0(u))return u;if($o(c,u)!==1)throw new Error("Cannot find square root");let p=r,d=c.mul(c.ONE,i),l=c.pow(u,t),f=c.pow(u,s);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=Ie<<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 dh(e){return e%Eu===Ou?Au:e%Iu===Ru?lh:e%vu===ch?uh(e):Su(e)}var hr=(e,t)=>(le(e,t)&Ie)===Ie,ph=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function os(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=ph.reduce((n,o)=>(n[o]="function",n),t);return fr(e,r),e}function Go(e,t,r){if(r<je)throw new Error("invalid exponent, negatives unsupported");if(r===je)return e.ONE;if(r===Ie)return t;let n=e.ONE,o=t;for(;r>je;)r&Ie&&(n=e.mul(n,o)),o=e.sqr(o),r>>=Ie;return n}function ut(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((s,a,c)=>e.is0(a)?s:(n[c]=s,e.mul(s,a)),e.ONE),i=e.inv(o);return t.reduceRight((s,a,c)=>e.is0(a)?s:(n[c]=e.mul(s,n[c]),e.mul(s,a)),i),n}function $o(e,t){let r=(e.ORDER-Ie)/Fn,n=e.pow(t,r),o=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),s=e.eql(n,e.neg(e.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function La(e,t){t!==void 0&&sa(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Ke(e,t,r=!1,n={}){if(e<=je)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,i,s=!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&&(i=l.sqrt),typeof l.isLE=="boolean"&&(r=l.isLE),typeof l.modFromBytes=="boolean"&&(s=l.modFromBytes),a=l.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(i=n.sqrt);let{nBitLength:c,nByteLength:u}=La(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:Rt(c),ZERO:je,ONE:Ie,allowedLengths:a,create:l=>le(l,e),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return je<=l&&l<e},is0:l=>l===je,isValidNot0:l=>!d.is0(l)&&d.isValid(l),isOdd:l=>(l&Ie)===Ie,neg:l=>le(-l,e),eql:(l,f)=>l===f,sqr:l=>le(l*l,e),add:(l,f)=>le(l+f,e),sub:(l,f)=>le(l-f,e),mul:(l,f)=>le(l*f,e),pow:(l,f)=>Go(d,l,f),div:(l,f)=>le(l*Nu(f,e),e),sqrN:l=>l*l,addN:(l,f)=>l+f,subN:(l,f)=>l-f,mulN:(l,f)=>l*f,inv:l=>Nu(l,e),sqrt:i||(l=>(p||(p=dh(e)),p(d,l))),toBytes:l=>r?Ba(l,u):Oe(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?dr(l):Ye(l);if(s&&(h=le(h,e)),!f&&!d.isValid(h))throw new Error("invalid field element: outside of range 0..ORDER");return h},invertBatch:l=>ut(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 is(e){let t=Cu(e);return t+Math.ceil(t/2)}function qa(e,t,r=!1){let n=e.length,o=Cu(t),i=is(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=r?dr(e):Ye(e),a=le(s,t-Ie)+Ie;return r?Ba(a,o):Oe(a,o)}var no=BigInt(0),Pn=BigInt(1);function Jo(e,t){let r=t.negate();return e?r:t}function dt(e,t){let r=ut(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function Bu(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Ma(e,t){Bu(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,i=Rt(e),s=BigInt(e);return{windows:r,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function Fu(e,t,r){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=r,a=Number(e&o),c=e>>s;a>n&&(a-=i,c+=Pn);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 hh(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 mh(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 ja=new WeakMap,Du=new WeakMap;function Ka(e){return Du.get(e)||1}function Pu(e){if(e!==no)throw new Error("invalid wNAF")}var oo=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>no;)r&Pn&&(n=n.add(o)),o=o.double(),r>>=Pn;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=Ma(r,this.bits),i=[],s=t,a=s;for(let c=0;c<n;c++){a=s,i.push(a);for(let u=1;u<o;u++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(t,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=Ma(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:p,isNeg:d,isNegF:l,offsetF:f}=Fu(n,a,s);n=c,p?i=i.add(Jo(l,r[f])):o=o.add(Jo(d,r[u]))}return Pu(n),{p:o,f:i}}wNAFUnsafe(t,r,n,o=this.ZERO){let i=Ma(t,this.bits);for(let s=0;s<i.windows&&n!==no;s++){let{nextN:a,offset:c,isZero:u,isNeg:p}=Fu(n,s,i);if(n=a,!u){let d=r[c];o=o.add(p?d.negate():d)}}return Pu(n),o}getPrecomputes(t,r,n){let o=ja.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(o=n(o)),ja.set(r,o))),o}cached(t,r,n){let o=Ka(t);return this.wNAF(o,this.getPrecomputes(o,t,n),r)}unsafe(t,r,n,o){let i=Ka(t);return i===1?this._unsafeLadder(t,r,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,n),r,o)}createCache(t,r){Bu(r,this.bits),Du.set(t,r),ja.delete(t)}hasCache(t){return Ka(t)!==1}};function Uu(e,t,r,n){let o=t,i=e.ZERO,s=e.ZERO;for(;r>no||n>no;)r&Pn&&(i=i.add(o)),n&Pn&&(s=s.add(o)),o=o.double(),r>>=Pn,n>>=Pn;return{p1:i,p2:s}}function io(e,t,r,n){hh(r,e),mh(n,t);let o=r.length,i=n.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");let s=e.ZERO,a=pr(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=Rt(c),p=new Array(Number(u)+1).fill(s),d=Math.floor((t.BITS-1)/c)*c,l=s;for(let f=d;f>=0;f-=c){p.fill(s);for(let _=0;_<i;_++){let g=n[_],m=Number(g>>BigInt(f)&u);p[m]=p[m].add(r[_])}let h=s;for(let _=p.length-1,g=s;_>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 Vu(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return os(t),t}else return Ke(e,{isLE:r})}function ss(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>no))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Vu(t.p,r.Fp,n),i=Vu(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:i}}var _h=Ye;function Ur(e,t){if(Wo(e),Wo(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 yh(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 Wo(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function ku(e){if(!At(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or string");return typeof e=="string"?$(e):e}function gh(e,t,r,n){me(e),Wo(r),t=ku(t),t.length>255&&(t=n(K($("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:i}=n,s=Math.ceil(r/o);if(r>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=K(t,Ur(t.length,1)),c=Ur(0,i),u=Ur(r,2),p=new Array(s),d=n(K(c,e,u,Ur(0,1),a));p[0]=n(K(d,Ur(1,1),a));for(let f=1;f<=s;f++){let h=[yh(d,p[f-1]),Ur(f+1,1),a];p[f]=n(K(...h))}return K(...p).slice(0,r)}function xh(e,t,r,n,o){if(me(e),Wo(r),t=ku(t),t.length>255){let i=Math.ceil(2*n/8);t=o.create({dkLen:i}).update($("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(Ur(r,2)).update(t).update(Ur(t.length,1)).digest()}function Ha(e,t,r){fr(r,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:n,k:o,m:i,hash:s,expand:a,DST:c}=r;if(!Tu(r.hash))throw new Error("expected valid hash");me(e),Wo(t);let u=n.toString(2).length,p=Math.ceil((u+o)/8),d=t*i*p,l;if(a==="xmd")l=gh(e,c,d,s);else if(a==="xof")l=xh(e,c,d,o,s);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(i);for(let g=0;g<i;g++){let m=p*(g+h*i),x=l.subarray(m,m+p);_[g]=le(_h(x),n)}f[h]=_}return f}function $a(e,t){let r=t.map(n=>Array.from(n).reverse());return(n,o)=>{let[i,s,a,c]=r.map(d=>d.reduce((l,f)=>e.add(e.mul(l,n),f))),[u,p]=ut(e,[s,c],!0);return n=e.mul(i,u),o=e.mul(o,e.mul(a,p)),{x:n,y:o}}}var bh=$("HashToScalar-");function Ga(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function n(i){return e.fromAffine(t(i))}function o(i){let s=i.clearCofactor();return s.equals(e.ZERO)?e.ZERO:(s.assertValidity(),s)}return{defaults:r,hashToCurve(i,s){let a=Object.assign({},r,s),c=Ha(i,2,a),u=n(c[0]),p=n(c[1]);return o(u.add(p))},encodeToCurve(i,s){let a=r.encodeDST?{DST:r.encodeDST}:{},c=Object.assign({},r,a,s),u=Ha(i,1,c),p=n(u[0]);return o(p)},mapToCurve(i){if(!Array.isArray(i))throw new Error("expected array of bigints");for(let s of i)if(typeof s!="bigint")throw new Error("expected array of bigints");return o(n(i))},hashToScalar(i,s){let a=e.Fn.ORDER,c=Object.assign({},r,{p:a,m:1,DST:bh},s);return Ha(i,1,c)[0][0]}}}var Lu=(e,t)=>(e+(e>=0?t:-t)/mr)/t;function wh(e,t,r){let[[n,o],[i,s]]=t,a=Lu(s*e,r),c=Lu(-o*e,r),u=e-a*n-c*i,p=-a*o-c*s,d=u<Vn,l=p<Vn;d&&(u=-u),l&&(p=-p);let f=Rt(Math.ceil(pr(r)/2))+He;if(u<Vn||u>=f||p<Vn||p>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:u,k2neg:l,k2:p}}var Vn=BigInt(0),He=BigInt(1),mr=BigInt(2),so=BigInt(3),Ja=BigInt(4);function zo(e,t){let{BYTES:r}=e,n;if(typeof t=="bigint")n=t;else{let o=pe("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 Th(e,t={}){let r=ss("weierstrass",e,t),{Fp:n,Fn:o}=r,i=r.CURVE,{h:s,n:a}=i;fr(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Eh(n,o);function p(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(S,b,N){let{x:C,y:B}=b.toAffine(),L=n.toBytes(C);if(Cn(N,"isCompressed"),N){p();let A=!n.isOdd(B);return K(Nh(A),L)}else return K(Uint8Array.of(4),L,n.toBytes(B))}function l(S){Br(S,void 0,"Point");let{publicKey:b,publicKeyUncompressed:N}=u,C=S.length,B=S[0],L=S.subarray(1);if(C===b&&(B===2||B===3)){let A=n.fromBytes(L);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");let P=_(A),V;try{V=n.sqrt(P)}catch(te){let ee=te instanceof Error?": "+te.message:"";throw new Error("bad point: is not on curve, sqrt error"+ee)}p();let D=n.isOdd(V);return(B&1)===1!==D&&(V=n.neg(V)),{x:A,y:V}}else if(C===N&&B===4){let A=n.BYTES,P=n.fromBytes(L.subarray(0,A)),V=n.fromBytes(L.subarray(A,A*2));if(!g(P,V))throw new Error("bad point: is not on curve");return{x:P,y:V}}else throw new Error(`bad point: got length ${C}, expected compressed=${b} or uncompressed=${N}`)}let f=t.toBytes||d,h=t.fromBytes||l;function _(S){let b=n.sqr(S),N=n.mul(b,S);return n.add(n.add(N,n.mul(S,i.a)),i.b)}function g(S,b){let N=n.sqr(b),C=_(S);return n.eql(N,C)}if(!g(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let m=n.mul(n.pow(i.a,so),Ja),x=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(m,x)))throw new Error("bad curve params: a or b");function y(S,b,N=!1){if(!n.isValid(b)||N&&n.is0(b))throw new Error(`bad point coordinate ${S}`);return b}function T(S){if(!(S instanceof w))throw new Error("ProjectivePoint expected")}function E(S){if(!c||!c.basises)throw new Error("no endo");return wh(S,c.basises,o.ORDER)}let O=Dr((S,b)=>{let{X:N,Y:C,Z:B}=S;if(n.eql(B,n.ONE))return{x:N,y:C};let L=S.is0();b==null&&(b=L?n.ONE:n.inv(B));let A=n.mul(N,b),P=n.mul(C,b),V=n.mul(B,b);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(V,n.ONE))throw new Error("invZ was invalid");return{x:A,y:P}}),R=Dr(S=>{if(S.is0()){if(t.allowInfinityPoint&&!n.is0(S.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:N}=S.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(!S.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(S,b,N,C,B){return N=new w(n.mul(N.X,S),N.Y,N.Z),b=Jo(C,b),N=Jo(B,N),b.add(N)}class w{constructor(b,N,C){this.X=y("x",b),this.Y=y("y",N,!0),this.Z=y("z",C),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){let{x:N,y:C}=b||{};if(!b||!n.isValid(N)||!n.isValid(C))throw new Error("invalid affine point");if(b instanceof w)throw new Error("projective point not allowed");return n.is0(N)&&n.is0(C)?w.ZERO:new w(N,C,n.ONE)}static fromBytes(b){let N=w.fromAffine(h(Br(b,void 0,"point")));return N.assertValidity(),N}static fromHex(b){return w.fromBytes(pe("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,N=!0){return F.createCache(this,b),N||this.multiply(so),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:N,Y:C,Z:B}=this,{X:L,Y:A,Z:P}=b,V=n.eql(n.mul(N,P),n.mul(L,B)),D=n.eql(n.mul(C,P),n.mul(A,B));return V&&D}negate(){return new w(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:N}=i,C=n.mul(N,so),{X:B,Y:L,Z:A}=this,P=n.ZERO,V=n.ZERO,D=n.ZERO,q=n.mul(B,B),te=n.mul(L,L),ee=n.mul(A,A),J=n.mul(B,L);return J=n.add(J,J),D=n.mul(B,A),D=n.add(D,D),P=n.mul(b,D),V=n.mul(C,ee),V=n.add(P,V),P=n.sub(te,V),V=n.add(te,V),V=n.mul(P,V),P=n.mul(J,P),D=n.mul(C,D),ee=n.mul(b,ee),J=n.sub(q,ee),J=n.mul(b,J),J=n.add(J,D),D=n.add(q,q),q=n.add(D,q),q=n.add(q,ee),q=n.mul(q,J),V=n.add(V,q),ee=n.mul(L,A),ee=n.add(ee,ee),q=n.mul(ee,J),P=n.sub(P,q),D=n.mul(ee,te),D=n.add(D,D),D=n.add(D,D),new w(P,V,D)}add(b){T(b);let{X:N,Y:C,Z:B}=this,{X:L,Y:A,Z:P}=b,V=n.ZERO,D=n.ZERO,q=n.ZERO,te=i.a,ee=n.mul(i.b,so),J=n.mul(N,L),ae=n.mul(C,A),he=n.mul(B,P),Fe=n.add(N,C),oe=n.add(L,A);Fe=n.mul(Fe,oe),oe=n.add(J,ae),Fe=n.sub(Fe,oe),oe=n.add(N,B);let re=n.add(L,P);return oe=n.mul(oe,re),re=n.add(J,he),oe=n.sub(oe,re),re=n.add(C,B),V=n.add(A,P),re=n.mul(re,V),V=n.add(ae,he),re=n.sub(re,V),q=n.mul(te,oe),V=n.mul(ee,he),q=n.add(V,q),V=n.sub(ae,q),q=n.add(ae,q),D=n.mul(V,q),ae=n.add(J,J),ae=n.add(ae,J),he=n.mul(te,he),oe=n.mul(ee,oe),ae=n.add(ae,he),he=n.sub(J,he),he=n.mul(te,he),oe=n.add(oe,he),J=n.mul(ae,oe),D=n.add(D,J),J=n.mul(re,oe),V=n.mul(Fe,V),V=n.sub(V,J),J=n.mul(Fe,ae),q=n.mul(re,q),q=n.add(q,J),new w(V,D,q)}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 C,B,L=A=>F.cached(this,A,P=>dt(w,P));if(N){let{k1neg:A,k1:P,k2neg:V,k2:D}=E(b),{p:q,f:te}=L(P),{p:ee,f:J}=L(D);B=te.add(J),C=v(N.beta,q,ee,A,V)}else{let{p:A,f:P}=L(b);C=A,B=P}return dt(w,[C,B])[0]}multiplyUnsafe(b){let{endo:N}=t,C=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===Vn||C.is0())return w.ZERO;if(b===He)return C;if(F.hasCache(this))return this.multiply(b);if(N){let{k1neg:B,k1:L,k2neg:A,k2:P}=E(b),{p1:V,p2:D}=Uu(w,C,L,P);return v(N.beta,V,D,B,A)}else return F.unsafe(C,b)}multiplyAndAddUnsafe(b,N,C){let B=this.multiplyUnsafe(N).add(b.multiplyUnsafe(C));return B.is0()?void 0:B}toAffine(b){return O(this,b)}isTorsionFree(){let{isTorsionFree:b}=t;return s===He?!0:b?b(w,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=t;return s===He?this:b?b(w,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(b=!0){return Cn(b,"isCompressed"),this.assertValidity(),f(w,this,b)}toHex(b=!0){return j(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 dt(w,b)}static msm(b,N){return io(w,o,b,N)}static fromPrivateKey(b){return w.BASE.multiply(zo(o,b))}}w.BASE=new w(i.Gx,i.Gy,n.ONE),w.ZERO=new w(n.ZERO,n.ONE,n.ZERO),w.Fp=n,w.Fn=o;let I=o.BITS,F=new oo(w,t.endo?Math.ceil(I/2):I);return w.BASE.precompute(8),w}function Nh(e){return Uint8Array.of(e?2:3)}function Oh(e,t){let r=e.ORDER,n=Vn;for(let h=r-He;h%mr===Vn;h/=mr)n+=He;let o=n,i=mr<<o-He-He,s=i*mr,a=(r-He)/s,c=(a-He)/mr,u=s-He,p=i,d=e.pow(t,a),l=e.pow(t,(a+He)/mr),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 E=e.eql(y,e.ONE);m=e.mul(x,l),y=e.mul(T,g),x=e.cmov(m,x,E),T=e.cmov(y,T,E);for(let O=o;O>He;O--){let R=O-mr;R=mr<<R-He;let v=e.pow(T,R),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:E,value:x}};if(e.ORDER%Ja===so){let h=(e.ORDER-so)/Ja,_=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 E=e.mul(T,_),O=e.mul(e.sqr(T),m),R=e.eql(O,g),v=e.cmov(E,T,R);return{isValid:R,value:v}}}return f}function Wa(e,t){os(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 i=Oh(e,o);if(!e.isOdd)throw new Error("Field does not have .isOdd()");return s=>{let a,c,u,p,d,l,f,h;a=e.sqr(s),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}=i(c,l);h=e.mul(a,s),h=e.mul(h,g),f=e.cmov(f,u,_),h=e.cmov(h,g,_);let m=e.isOdd(s)===e.isOdd(h);h=e.cmov(e.neg(h),h,m);let x=ut(e,[p],!0)[0];return f=e.mul(f,x),{x:f,y:h}}}function Eh(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function za(e){let{CURVE:t,curveOpts:r}=Rh(e),n=Th(t,r);return vh(e,n)}function Rh(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(s=>Math.ceil(s/2)))):void 0,o=Ke(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),i={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:i}}function Ih(e,t,r){function n(o){let i=e.sqr(o),s=e.mul(i,o);return e.add(e.add(s,e.mul(o,t)),r)}return n}function vh(e,t){let{Fp:r,Fn:n}=t;function o(s){return Ua(s,He,n.ORDER)}let i=Ih(r,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:s=>zo(n,s),weierstrassEquation:i,isWithinCurveOrder:o})}var Ah=BigInt(0),as=BigInt(1),qu=BigInt(2),ao=BigInt(3);function Sh(e){let t=[];for(;e>as;e>>=as)(e&as)===Ah?t.unshift(0):(e&ao)===ao?(t.unshift(-1),e+=as):t.unshift(1);return t}function Ya(e){if(!Array.isArray(e)||e.length===0)throw new Error("expected non-empty array")}function Ch(e,t,r,n){let{Fp2:o,Fp12:i}=e,{twistType:s,ateLoopSize:a,xNegative:c,postPrecompute:u}=n,p;if(s==="multiplicative")p=(y,T,E,O,R,v)=>i.mul014(O,y,o.mul(T,R),o.mul(E,v));else if(s==="divisive")p=(y,T,E,O,R,v)=>i.mul034(O,o.mul(E,v),o.mul(T,R),y);else throw new Error("bls: unknown twist type");let d=o.div(o.ONE,o.mul(o.ONE,qu));function l(y,T,E,O){let R=o.sqr(E),v=o.sqr(O),w=o.mulByB(o.mul(v,ao)),I=o.mul(w,ao),F=o.sub(o.sub(o.sqr(o.add(E,O)),v),R),S=o.sub(w,R),b=o.mul(o.sqr(T),ao),N=o.neg(F);return y.push([S,b,N]),T=o.mul(o.mul(o.mul(o.sub(R,I),T),E),d),E=o.sub(o.sqr(o.mul(o.add(R,I),d)),o.mul(o.sqr(w),ao)),O=o.mul(R,F),{Rx:T,Ry:E,Rz:O}}function f(y,T,E,O,R,v){let w=o.sub(E,o.mul(v,O)),I=o.sub(T,o.mul(R,O)),F=o.sub(o.mul(w,R),o.mul(I,v)),S=o.neg(w),b=I;y.push([F,S,b]);let N=o.sqr(I),C=o.mul(N,I),B=o.mul(N,T),L=o.add(o.sub(C,o.mul(B,qu)),o.mul(o.sqr(w),O));return T=o.mul(I,L),E=o.sub(o.mul(o.sub(B,L),w),o.mul(C,E)),O=o.mul(O,C),{Rx:T,Ry:E,Rz:O}}let h=Sh(a),_=Dr(y=>{let T=y,{x:E,y:O}=T.toAffine(),R=E,v=O,w=o.neg(O),I=R,F=v,S=o.ONE,b=[];for(let N of h){let C=[];({Rx:I,Ry:F,Rz:S}=l(C,I,F,S)),N&&({Rx:I,Ry:F,Rz:S}=f(C,I,F,S,R,N===-1?w:v)),b.push(C)}if(u){let N=b[b.length-1];u(I,F,S,R,v,f.bind(null,N))}return b});function g(y,T=!1){let E=i.ONE;if(y.length){let O=y[0][0].length;for(let R=0;R<O;R++){E=i.sqr(E);for(let[v,w,I]of y)for(let[F,S,b]of v[R])E=p(F,S,b,E,w,I)}}return c&&(E=i.conjugate(E)),T?i.finalExponentiate(E):E}function m(y,T=!0){let E=[];dt(t,y.map(({g1:O})=>O)),dt(r,y.map(({g2:O})=>O));for(let{g1:O,g2:R}of y){if(O.is0()||R.is0())throw new Error("pairing is not available for ZERO point");O.assertValidity(),R.assertValidity();let v=O.toAffine();E.push([_(R),v.x,v.y])}return g(E,T)}function x(y,T,E=!0){return m([{g1:y,g2:T}],E)}return{Fp12:i,millerLoopBatch:g,pairing:x,pairingBatch:m,calcPairingPrecomputes:_}}function Mu(e,t,r,n,o){let{Fp12:i,pairingBatch:s}=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=zo(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=zo(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=s([p(_,m),p(g,x)]);return i.eql(y,i.ONE)},verifyBatch(d,l,f){if(Ya(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 E=g[T],O=_[T],R=m.get(O);R===void 0&&(R=[],m.set(O,R)),R.push(E)}let x=[],y=t.Point.BASE;try{for(let[T,E]of m){let O=E.reduce((R,v)=>R.add(v));x.push(p(O,T))}return x.push(p(y.negate(),h)),i.eql(s(x),i.ONE)}catch{return!1}},aggregatePublicKeys(d){Ya(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){Ya(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){me(d);let f=l?{DST:l}:void 0;return r.hashToCurve(d,f)},Signature:n}}function ju(e){let{Fp:t,Fr:r,Fp2:n,Fp6:o,Fp12:i}=e.fields,s=za(e.G1),a=Object.assign(s,Ga(s.Point,e.G1.mapToCurve,{...e.htfDefaults,...e.G1.htfDefaults})),c=za(e.G2),u=Object.assign(c,Ga(c.Point,e.G2.mapToCurve,{...e.htfDefaults,...e.G2.htfDefaults})),p=Ch(e.fields,a.Point,u.Point,{...e.params,postPrecompute:e.postPrecompute}),{millerLoopBatch:d,pairing:l,pairingBatch:f,calcPairingPrecomputes:h}=p,_=Mu(p,a,u,e.G2.Signature,!1),g=Mu(p,u,a,e.G1.ShortSignature,!0),m=e.randomBytes||jn,x=()=>{let A=is(r.ORDER);return qa(m(A),r.ORDER)},y={randomSecretKey:x,randomPrivateKey:x,calcPairingPrecomputes:h},{ShortSignature:T}=e.G1,{Signature:E}=e.G2;function O(A,P){return A instanceof a.Point?A:g.hash(pe("point",A),P?.DST)}function R(A,P){return A instanceof u.Point?A:_.hash(pe("point",A),P?.DST)}function v(A){return _.getPublicKey(A).toBytes(!0)}function w(A){return g.getPublicKey(A).toBytes(!0)}function I(A,P,V){let D=R(A,V),q=_.sign(D,P);return A instanceof u.Point?q:E.toBytes(q)}function F(A,P,V){let D=O(A,V),q=g.sign(D,P);return A instanceof a.Point?q:T.toBytes(q)}function S(A,P,V,D){let q=R(P,D);return _.verify(A,q,V)}function b(A,P,V,D){let q=O(P,D);return g.verify(A,q,V)}function N(A){let P=_.aggregatePublicKeys(A);return A[0]instanceof a.Point?P:P.toBytes(!0)}function C(A){let P=_.aggregateSignatures(A);return A[0]instanceof u.Point?P:E.toBytes(P)}function B(A){let P=g.aggregateSignatures(A);return A[0]instanceof a.Point?P:T.toBytes(P)}function L(A,P,V,D){let q=P.map(te=>R(te,D));return _.verifyBatch(A,q,V)}return a.Point.BASE.precompute(4),{longSignatures:_,shortSignatures:g,millerLoopBatch:d,pairing:l,pairingBatch:f,verifyBatch:L,fields:{Fr:r,Fp:t,Fp2:n,Fp6:o,Fp12:i},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:F,verify:S,verifyShortSignature:b,aggregatePublicKeys:N,aggregateSignatures:C,aggregateShortSignatures:B,G1:a,G2:u,Signature:E,ShortSignature:T}}var Ku=BigInt(0),_r=BigInt(1),$e=BigInt(2),Hu=BigInt(3);function ec(e,t,r,n,o=1,i){let s=BigInt(i===void 0?n:i),a=r**BigInt(n),c=[];for(let u=0;u<o;u++){let p=BigInt(u+1),d=[];for(let l=0,f=_r;l<n;l++){let h=(p*f-p)/s%a;d.push(e.pow(t,h)),f*=r}c.push(d)}return c}function Gu(e,t,r){let n=t.pow(r,(e.ORDER-_r)/Hu),o=t.pow(r,(e.ORDER-_r)/$e);function i(l,f){let h=t.mul(t.frobeniusMap(l,1),n),_=t.mul(t.frobeniusMap(f,1),o);return[h,_]}let s=t.pow(r,(e.ORDER**$e-_r)/Hu),a=t.pow(r,(e.ORDER**$e-_r)/$e);if(!t.eql(a,t.neg(t.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(l,f){return[t.mul(l,s),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(i),d=u(c);return{psi:i,psi2:c,G2psi:p,G2psi2:d,PSI_X:n,PSI_Y:o,PSI2_X:s,PSI2_Y:a}}var $u=(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]}},Za=class{constructor(t,r={}){this.MASK=_r;let n=t.ORDER,o=n*n;this.Fp=t,this.ORDER=o,this.BITS=pr(o),this.BYTES=Math.ceil(pr(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,$e),this.NONRESIDUE=$u(t,r.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=ec(t,this.Fp_NONRESIDUE,t.ORDER,2)[0],this.mulByB=r.Fp2mulByB,Object.seal(this)}fromBigTuple(t){return $u(this.Fp,t)}create(t){return t}isValid({c0:t,c1:r}){function n(o,i){return typeof o=="bigint"&&Ku<=o&&o<i}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 Go(this,t,r)}invertBatch(t){return ut(this,t)}add(t,r){let{c0:n,c1:o}=t,{c0:i,c1:s}=r;return{c0:this.Fp.add(n,i),c1:this.Fp.add(o,s)}}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:i,c1:s}=n,a=o.mul(t,i),c=o.mul(r,s),u=o.sub(a,c),p=o.sub(o.mul(o.add(t,r),o.add(i,s)),o.add(a,c));return{c0:u,c1:p}}sqr({c0:t,c1:r}){let{Fp:n}=this,o=n.add(t,r),i=n.sub(t,r),s=n.add(t,t);return{c0:n.mul(o,i),c1:n.mul(s,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:i}=t;if(r.is0(i))return $o(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 s=r.sqrt(r.sub(r.sqr(o),r.mul(r.sqr(i),this.Fp_NONRESIDUE))),a=r.mul(r.add(s,o),this.Fp_div2);$o(r,a)===-1&&(a=r.sub(a,s));let u=r.sqrt(a),p=n.create({c0:u,c1:r.div(r.mul(i,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%$e,i=r===Ku,s=n%$e;return BigInt(o||i&&s)==_r}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},i){return{c0:this.Fp.cmov(t,n,i),c1:this.Fp.cmov(r,o,i)}}reim({c0:t,c1:r}){return{re:t,im:r}}Fp4Square(t,r){let n=this,o=n.sqr(t),i=n.sqr(r);return{first:n.add(n.mulByNonresidue(i),o),second:n.sub(n.sub(n.sqr(n.add(t,r)),o),i)}}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])}}},Xa=class{constructor(t){this.MASK=_r,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=ec(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:i,c2:s}){let{Fp2:a}=this;return{c0:a.add(t,o),c1:a.add(r,i),c2:a.add(n,s)}}sub({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return{c0:a.sub(t,o),c1:a.sub(r,i),c2:a.sub(n,s)}}mul({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;if(typeof o=="bigint")return{c0:i.mul(t,o),c1:i.mul(r,o),c2:i.mul(n,o)};let{c0:s,c1:a,c2:c}=o,u=i.mul(t,s),p=i.mul(r,a),d=i.mul(n,c);return{c0:i.add(u,i.mulByNonresidue(i.sub(i.mul(i.add(r,n),i.add(a,c)),i.add(p,d)))),c1:i.add(i.sub(i.mul(i.add(t,r),i.add(s,a)),i.add(u,p)),i.mulByNonresidue(d)),c2:i.sub(i.add(p,i.mul(i.add(t,n),i.add(s,c))),i.add(u,d))}}sqr({c0:t,c1:r,c2:n}){let{Fp2:o}=this,i=o.sqr(t),s=o.mul(o.mul(t,r),$e),a=o.mul(o.mul(r,n),$e),c=o.sqr(n);return{c0:o.add(o.mulByNonresidue(a),i),c1:o.add(o.mulByNonresidue(c),s),c2:o.sub(o.sub(o.add(o.add(s,o.sqr(o.add(o.sub(t,r),n))),a),i),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:i,c2:s}){let{Fp2:a}=this;return a.eql(t,o)&&a.eql(r,i)&&a.eql(n,s)}sqrt(t){return ro()}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 Go(this,t,r)}invertBatch(t){return ut(this,t)}inv({c0:t,c1:r,c2:n}){let{Fp2:o}=this,i=o.sub(o.sqr(t),o.mulByNonresidue(o.mul(n,r))),s=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,s),o.mul(r,a))),o.mul(t,i)));return{c0:o.mul(c,i),c1:o.mul(c,s),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:i,c2:s},a){let{Fp2:c}=this;return{c0:c.cmov(t,o,a),c1:c.cmov(r,i,a),c2:c.cmov(n,s,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:i}=this;return{c0:i.frobeniusMap(t,o),c1:i.mul(i.frobeniusMap(r,o),this.FROBENIUS_COEFFICIENTS_1[o%6]),c2:i.mul(i.frobeniusMap(n,o),this.FROBENIUS_COEFFICIENTS_2[o%6])}}mulByFp2({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;return{c0:i.mul(t,o),c1:i.mul(r,o),c2:i.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:i}=this;return{c0:i.mulByNonresidue(i.mul(n,o)),c1:i.mul(t,o),c2:i.mul(r,o)}}mul01({c0:t,c1:r,c2:n},o,i){let{Fp2:s}=this,a=s.mul(t,o),c=s.mul(r,i);return{c0:s.add(s.mulByNonresidue(s.sub(s.mul(s.add(r,n),i),c)),a),c1:s.sub(s.sub(s.mul(s.add(o,i),s.add(t,r)),a),c),c2:s.add(s.sub(s.mul(s.add(t,n),o),a),c)}}},Qa=class{constructor(t,r){this.MASK=_r;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=ec(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:i}=this;return i.eql(t,n)&&i.eql(r,o)}sqrt(t){ro()}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:i}=o;return this.mul(t,typeof r=="bigint"?i.inv(i.create(r)):this.inv(r))}pow(t,r){return Go(this,t,r)}invertBatch(t){return ut(this,t)}add({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return{c0:i.add(t,n),c1:i.add(r,o)}}sub({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return{c0:i.sub(t,n),c1:i.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:i,c1:s}=n,a=o.mul(t,i),c=o.mul(r,s);return{c0:o.add(a,o.mulByNonresidue(c)),c1:o.sub(o.mul(o.add(t,r),o.add(i,s)),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},i){let{Fp6:s}=this;return{c0:s.cmov(t,n,i),c1:s.cmov(r,o,i)}}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:i,c1:s,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(i,c),c1:o.mul(s,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,i){let{Fp6:s}=this,{Fp2:a}=s,c=s.mul01(t,n,o),u=s.mul1(r,i);return{c0:s.add(s.mulByNonresidue(u),c),c1:s.sub(s.sub(s.mul01(s.add(r,t),n,a.add(o,i)),c),u)}}mul034({c0:t,c1:r},n,o,i){let{Fp6:s}=this,{Fp2:a}=s,c=s.create({c0:a.mul(t.c0,n),c1:a.mul(t.c1,n),c2:a.mul(t.c2,n)}),u=s.mul01(r,o,i),p=s.mul01(s.add(t,r),a.add(n,o),i);return{c0:s.add(s.mulByNonresidue(u),c),c1:s.sub(p,s.add(c,u))}}_cyclotomicSquare({c0:t,c1:r}){let{Fp6:n}=this,{Fp2:o}=n,{c0:i,c1:s,c2:a}=t,{c0:c,c1:u,c2:p}=r,{first:d,second:l}=o.Fp4Square(i,u),{first:f,second:h}=o.Fp4Square(c,a),{first:_,second:g}=o.Fp4Square(s,p),m=o.mulByNonresidue(g);return{c0:n.create({c0:o.add(o.mul(o.sub(d,i),$e),d),c1:o.add(o.mul(o.sub(f,s),$e),f),c2:o.add(o.mul(o.sub(_,a),$e),_)}),c1:n.create({c0:o.add(o.mul(o.add(m,c),$e),m),c1:o.add(o.mul(o.add(l,u),$e),l),c2:o.add(o.mul(o.add(h,p),$e),h)})}}_cyclotomicExp(t,r){let n=this.ONE;for(let o=this.X_LEN-1;o>=0;o--)n=this._cyclotomicSquare(n),wu(r,o)&&(n=this.mul(n,t));return n}};function Ju(e){let t=Ke(e.ORDER),r=new Za(t,e),n=new Xa(r),o=new Qa(n,e);return{Fp:t,Fp2:r,Fp6:n,Fp12:o}}var Ve=BigInt(0),cs=BigInt(1),pt=BigInt(2),ls=BigInt(3),Yo=BigInt(4),kr=BigInt("0xd201000000010000"),Fh=pr(kr),Bn={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:Ve,b:Yo,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},Ph=Ke(Bn.n,{modFromBytes:!0,isLE:!0}),{Fp:M,Fp2:W,Fp6:Vh,Fp12:X}=Ju({ORDER:Bn.p,X_LEN:Fh,FP2_NONRESIDUE:[cs,cs],Fp2mulByB:({c0:e,c1:t})=>{let r=M.mul(e,Yo),n=M.mul(t,Yo);return{c0:M.sub(r,n),c1:M.add(r,n)}},Fp12finalExponentiate:e=>{let t=kr,r=X.div(X.frobeniusMap(e,6),e),n=X.mul(X.frobeniusMap(r,2),r),o=X.conjugate(X._cyclotomicExp(n,t)),i=X.mul(X.conjugate(X._cyclotomicSquare(n)),o),s=X.conjugate(X._cyclotomicExp(i,t)),a=X.conjugate(X._cyclotomicExp(s,t)),c=X.mul(X.conjugate(X._cyclotomicExp(a,t)),X._cyclotomicSquare(o)),u=X.conjugate(X._cyclotomicExp(c,t)),p=X.frobeniusMap(X.mul(o,a),2),d=X.frobeniusMap(X.mul(s,n),3),l=X.frobeniusMap(X.mul(c,X.conjugate(n)),1),f=X.mul(X.mul(u,X.conjugate(i)),n);return X.mul(X.mul(X.mul(p,d),l),f)}}),{G2psi:Wu,G2psi2:Bh}=Gu(M,W,W.div(W.ONE,W.NONRESIDUE)),tc=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:M.ORDER,m:2,k:128,expand:"xmd",hash:Pe}),oc={p:W.ORDER,n:Bn.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:W.ZERO,b:W.fromBigTuple([Yo,Yo]),Gx:W.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:W.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},us=Zo(M.toBytes(Ve),{infinity:!0,compressed:!0});function ds(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 Zo(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 Dh(e,t,r){let{BYTES:n,ORDER:o}=M,i=t.is0(),{x:s,y:a}=t.toAffine();if(r){if(i)return us.slice();let c=!!(a*pt/o);return Zo(Oe(s,n),{compressed:!0,sort:c})}else return i?K(Uint8Array.of(64),new Uint8Array(2*n-1)):K(Oe(s,n),Oe(a,n))}function rc(e){e.assertValidity();let{BYTES:t,ORDER:r}=M,{x:n,y:o}=e.toAffine();if(e.is0())return us.slice();let i=!!(o*pt/r);return Zo(Oe(n,t),{compressed:!0,sort:i})}function Uh(e){let{compressed:t,infinity:r,sort:n,value:o}=ds(e),{BYTES:i,ORDER:s}=M;if(o.length===48&&t){let a=Ye(o),c=M.create(a&Rt(M.BITS));if(r){if(c!==Ve)throw new Error("invalid G1 point: non-empty, at infinity, with compression");return{x:Ve,y:Ve}}let u=M.add(M.pow(c,ls),M.create(Bn.b)),p=M.sqrt(u);if(!p)throw new Error("invalid G1 point: compressed point");return p*pt/s!==BigInt(n)&&(p=M.neg(p)),{x:M.create(c),y:M.create(p)}}else if(o.length===96&&!t){let a=Ye(o.subarray(0,i)),c=Ye(o.subarray(i));if(r){if(a!==Ve||c!==Ve)throw new Error("G1: non-empty point at infinity");return Xo.G1.Point.ZERO.toAffine()}return{x:M.create(a),y:M.create(c)}}else throw new Error("invalid G1 point: expected 48/96 bytes")}function zu(e){let{infinity:t,sort:r,value:n}=ds(pe("signatureHex",e,48)),o=M.ORDER,i=Xo.G1.Point,s=Ye(n);if(t)return i.ZERO;let a=M.create(s&Rt(M.BITS)),c=M.add(M.pow(a,ls),M.create(Bn.b)),u=M.sqrt(c);if(!u)throw new Error("invalid G1 point: compressed");let p=BigInt(r);u*pt/o!==p&&(u=M.neg(u));let d=i.fromAffine({x:a,y:u});return d.assertValidity(),d}function kh(e,t,r){let{BYTES:n,ORDER:o}=M,i=t.is0(),{x:s,y:a}=t.toAffine();if(r){if(i)return K(us,Oe(Ve,n));let c=!!(a.c1===Ve?a.c0*pt/o:a.c1*pt/o);return K(Zo(Oe(s.c1,n),{compressed:!0,sort:c}),Oe(s.c0,n))}else{if(i)return K(Uint8Array.of(64),new Uint8Array(4*n-1));let{re:c,im:u}=W.reim(s),{re:p,im:d}=W.reim(a);return K(Oe(u,n),Oe(c,n),Oe(d,n),Oe(p,n))}}function nc(e){e.assertValidity();let{BYTES:t}=M;if(e.is0())return K(us,Oe(Ve,t));let{x:r,y:n}=e.toAffine(),{re:o,im:i}=W.reim(r),{re:s,im:a}=W.reim(n),u=!!((a>Ve?a*pt:s*pt)/M.ORDER&cs),p=o;return K(Zo(Oe(i,t),{sort:u,compressed:!0}),Oe(p,t))}function Lh(e){let{BYTES:t,ORDER:r}=M,{compressed:n,infinity:o,sort:i,value:s}=ds(e);if(!n&&!o&&i||!n&&o&&i||i&&o&&n)throw new Error("invalid encoding flag: "+(e[0]&224));let a=(c,u,p)=>Ye(c.slice(u,p));if(s.length===96&&n){if(o){if(s.reduce((h,_)=>h!==0?_+1:_,0)>0)throw new Error("invalid G2 point: compressed");return{x:W.ZERO,y:W.ZERO}}let c=a(s,0,t),u=a(s,t,2*t),p=W.create({c0:M.create(u),c1:M.create(c)}),d=W.add(W.pow(p,ls),oc.b),l=W.sqrt(d),f=l.c1===Ve?l.c0*pt/r:l.c1*pt/r?cs:Ve;return l=i&&f>0?l:W.neg(l),{x:p,y:l}}else if(s.length===192&&!n){if(o){if(s.reduce((l,f)=>l!==0?f+1:f,0)>0)throw new Error("invalid G2 point: uncompressed");return{x:W.ZERO,y:W.ZERO}}let c=a(s,0*t,1*t),u=a(s,1*t,2*t),p=a(s,2*t,3*t),d=a(s,3*t,4*t);return{x:W.fromBigTuple([u,c]),y:W.fromBigTuple([d,p])}}else throw new Error("invalid G2 point: expected 96/192 bytes")}function Yu(e){let{ORDER:t}=M,{infinity:r,sort:n,value:o}=ds(pe("signatureHex",e)),i=Xo.G2.Point,s=o.length/2;if(s!==48&&s!==96)throw new Error("invalid compressed signature length, expected 96/192 bytes");let a=Ye(o.slice(0,s)),c=Ye(o.slice(s));if(r)return i.ZERO;let u=M.create(a&Rt(M.BITS)),p=M.create(c),d=W.create({c0:p,c1:u}),l=W.add(W.pow(d,ls),oc.b),f=W.sqrt(l);if(!f)throw new Error("Failed to find a square root");let{re:h,im:_}=W.reim(f),g=BigInt(n),m=_>Ve&&_*pt/t!==g,x=_===Ve&&h*pt/t!==g;(m||x)&&(f=W.neg(f));let y=i.fromAffine({x:d,y:f});return y.assertValidity(),y}var Xo=ju({fields:{Fp:M,Fp2:W,Fp6:Vh,Fp12:X,Fr:Ph},G1:{...Bn,Fp:M,htfDefaults:{...tc,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(M.mul(t.X,r),t.Y,t.Z);return t.multiplyUnsafe(kr).negate().multiplyUnsafe(kr).equals(n)},clearCofactor:(e,t)=>t.multiplyUnsafe(kr).add(t),mapToCurve:Hh,fromBytes:Uh,toBytes:Dh,ShortSignature:{fromBytes(e){return me(e),zu(e)},fromHex(e){return zu(e)},toBytes(e){return rc(e)},toRawBytes(e){return rc(e)},toHex(e){return j(rc(e))}}},G2:{...oc,Fp:W,hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...tc},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:$h,isTorsionFree:(e,t)=>t.multiplyUnsafe(kr).negate().equals(Wu(e,t)),clearCofactor:(e,t)=>{let r=kr,n=t.multiplyUnsafe(r).negate(),o=Wu(e,t),i=t.double();return i=Bh(e,i),i=i.subtract(o),o=n.add(o),o=o.multiplyUnsafe(r).negate(),i=i.add(o),i=i.subtract(n),i.subtract(t)},fromBytes:Lh,toBytes:kh,Signature:{fromBytes(e){return me(e),Yu(e)},fromHex(e){return Yu(e)},toBytes(e){return nc(e)},toRawBytes(e){return nc(e)},toHex(e){return j(nc(e))}}},params:{ateLoopSize:kr,r:Bn.n,xNegative:!0,twistType:"multiplicative"},htfDefaults:tc,hash:Pe}),qh=$a(W,[[["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=>W.fromBigTuple(t.map(BigInt))))),Mh=$a(M,[["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)))),jh=Wa(M,{A:M.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:M.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:M.create(BigInt(11))}),Kh=Wa(W,{A:W.create({c0:M.create(Ve),c1:M.create(BigInt(240))}),B:W.create({c0:M.create(BigInt(1012)),c1:M.create(BigInt(1012))}),Z:W.create({c0:M.create(BigInt(-2)),c1:M.create(BigInt(-1))})});function Hh(e){let{x:t,y:r}=jh(M.create(e[0]));return Mh(t,r)}function $h(e){let{x:t,y:r}=Kh(W.fromBigTuple(e));return qh(t,r)}function Zu(e,t,r){let n=typeof e=="string"?e:j(e),o=typeof t=="string"?t:j(t),i=typeof r=="string"?r:j(r);return Xo.verifyShortSignature(o,i,n)}var Jh=BigInt(1e6),ic=e=>ge(new wt(e)),Lr=e=>{let r=ic(e)/Jh;return new Date(Number(r))};var Xu=60*1e3,Wh=60,zh=24,Yh=zh*Wh,Zh=5,Xh=5,Qh=30*Yh,fe;(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"})(fe||(fe={}));function em(e,t){for(let r=0;r<e.length;r++)if(e[r]>t[r])return!0;return!1}var st=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.principal,t.blsVerify??Zu,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(t,r,n,o,i=Zh,s=!1,a){this._rootKey=r,this._principal=n,this._blsVerify=o,this._maxAgeInMinutes=i,this.#e=s,this.cert=Me(t),a&&"getTimeDiffMsecs"in a&&"hasSyncedTime"in a&&"syncTime"in a&&"syncTimeWithSubnet"in a&&(this.#t=a)}lookup_path(t){return yr(t,this.cert.tree)}lookup_subtree(t){return ti(t,this.cert.tree)}async verify(){let t=await fs(this.cert.tree),r=await this._checkDelegationAndGetKey(this.cert.delegation),n=this.cert.signature,o=rm(r),i=K(Na,t),s=ve(this.lookup_path(["time"]));if(!s)throw ne.fromCode(new gt("Certificate does not contain a time"));if(!this.#e){let a=this.#t?.getTimeDiffMsecs()??0,c=this._maxAgeInMinutes*Xu,u=new Date,p=u.getTime()+a,d=p-c,l=p+Xh*Xu,f=Lr(s),h=f.getTime()<d,_=f.getTime()>l;if((h||_)&&this.#t&&!this.#t.hasSyncedTime())return await this._syncTime(),await this.verify();if(h)throw Le.fromCode(new or(this._maxAgeInMinutes,f,u,a,"past"));if(_)throw this.#t?.hasSyncedTime()?ce.fromCode(new Re("System time has been synced with the IC network, but certificate is still too far in the future.")):Le.fromCode(new or(5,f,u,a,"future"))}try{if(!await this._blsVerify(o,n,i))throw Le.fromCode(new gt("Invalid signature"))}catch(a){throw Le.fromCode(new gt("Signature verification failed",a))}}async _checkDelegationAndGetKey(t){if(!t)return this._rootKey;let r=e.createUnverified({certificate:t.certificate,rootKey:this._rootKey,principal:this._principal,blsVerify:this._blsVerify,disableTimeVerification:this.#e,maxAgeInMinutes:Qh,agent:this.#t});if(r.cert.delegation)throw ne.fromCode(new Ni);await r.verify();let n;if(ed(this._principal)){let i=this._principal.canisterId;if(n=U.fromUint8Array(t.subnet_id),!sc({canisterId:i,subnetId:n,tree:r.cert.tree}))throw Le.fromCode(new Tn(i,n))}else if(Qu(this._principal))n=this._principal.subnetId;else throw ct;let o=ve(r.lookup_path(["subnet",n.toUint8Array(),"public_key"]));if(!o)throw Qu(this._principal)?Le.fromCode(new Oi(n)):Le.fromCode(new Ri(`Could not find subnet key for subnet ID ${n.toText()}`));return o}async _syncTime(){this.#t&&(ed(this._principal)?await this.#t.syncTime(this._principal.canisterId):await this.#t.syncTimeWithSubnet(this._principal.subnetId))}};function Qu(e){return"subnetId"in e}function ed(e){return"canisterId"in e}var Qo=Ee("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),tm=96;function rm(e){let t=Qo.byteLength+tm;if(e.byteLength!==t)throw ne.fromCode(new Kn(t,e.byteLength));let r=e.slice(0,Qo.byteLength);if(!vn(r,Qo))throw ne.fromCode(new Ii(Qo,r));return e.slice(Qo.byteLength)}function ve(e){if(e.status===Be.Found&&e.value instanceof Uint8Array)return e.value}async function fs(e){switch(e[0]){case fe.Empty:return Pe(ps("ic-hashtree-empty"));case fe.Pruned:return e[1];case fe.Leaf:return Pe(K(ps("ic-hashtree-leaf"),e[1]));case fe.Labeled:return Pe(K(ps("ic-hashtree-labeled"),e[1],await fs(e[2])));case fe.Fork:return Pe(K(ps("ic-hashtree-fork"),await fs(e[1]),await fs(e[2])));default:throw ct}}function ps(e){let t=new Uint8Array([e.length]),r=new TextEncoder().encode(e);return K(t,r)}function td(e){return typeof e[0]=="string"?$(e[0]):e[0]}var Be;(function(e){e.Unknown="Unknown",e.Absent="Absent",e.Found="Found",e.Error="Error"})(Be||(Be={}));var qr;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found"})(qr||(qr={}));var ue;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found",e.Less="Less",e.Greater="Greater"})(ue||(ue={}));function yr(e,t){if(e.length===0)switch(t[0]){case fe.Empty:return{status:Be.Absent};case fe.Leaf:{if(!t[1])throw ce.fromCode(new Cr("Invalid tree structure for leaf"));if(t[1]instanceof Uint8Array)return{status:Be.Found,value:t[1].slice(t[1].byteOffset,t[1].byteLength+t[1].byteOffset)};throw ct}case fe.Pruned:return{status:Be.Unknown};case fe.Labeled:case fe.Fork:return{status:Be.Error};default:throw ct}let r=td(e),n=ei(r,t);switch(n.status){case ue.Found:return yr(e.slice(1),n.value);case ue.Absent:case ue.Greater:case ue.Less:return{status:Be.Absent};case ue.Unknown:return{status:Be.Unknown};default:throw ct}}function ti(e,t){if(e.length===0)return{status:qr.Found,value:t};let r=td(e),n=ei(r,t);switch(n.status){case ue.Found:return ti(e.slice(1),n.value);case ue.Unknown:return{status:qr.Unknown};case ue.Absent:case ue.Greater:case ue.Less:return{status:qr.Absent};default:throw ct}}function ms(e){switch(e[0]){case fe.Empty:return[];case fe.Fork:return ms(e[1]).concat(ms(e[2]));default:return[e]}}function ei(e,t){switch(t[0]){case fe.Labeled:return em(e,t[1])?{status:ue.Greater}:vn(e,t[1])?{status:ue.Found,value:t[2]}:{status:ue.Less};case fe.Fork:{let r=ei(e,t[1]);switch(r.status){case ue.Greater:{let n=ei(e,t[2]);return n.status===ue.Less?{status:ue.Absent}:n}case ue.Unknown:{let n=ei(e,t[2]);return n.status===ue.Less?{status:ue.Unknown}:n}default:return r}}case fe.Pruned:return{status:ue.Unknown};default:return{status:ue.Absent}}}function hs(e,t){switch(t[0]){case fe.Empty|fe.Pruned:return[];case fe.Leaf:return[e];case fe.Fork:return hs(e,t[1]).concat(hs(e,t[2]));case fe.Labeled:{let r=t[1],n=t[2],o=[...e,r];return hs(o,n)}default:throw ct}}function sc(e){let t=nm(e),r=ac(t),{canisterId:n}=e;return r.some(i=>i[0].ltEq(n)&&i[1].gtEq(n))}function nm(e){let{subnetId:t,tree:r,canisterId:n}=e,o=ti(["canister_ranges",t.toUint8Array()],r);if(o.status!==qr.Found)return om(t,r);let i=o.value,s=im(i);if(s.length===0)throw ne.fromCode(new Tn(n,t));s.sort(Gn);let a=sm(s,n),c=s[a];return am(c,i)}function om(e,t){let r=yr(["subnet",e.toUint8Array(),"canister_ranges"],t);if(r.status!==Be.Found)throw ne.fromCode(new xt(`Could not find canister ranges for subnet ${e.toText()}`,r.status));return r.value}function ac(e){return Me(e).map(n=>[U.fromUint8Array(n[0]),U.fromUint8Array(n[1])])}function im(e){let t=[];for(let r of hs([],e)){let n=r[0];if(!n)throw ne.fromCode(new gt("Path is invalid"));t.push(n)}return t}function sm(e,t){let r=t.toUint8Array(),n=0,o=e.length-1;for(;n<o;){let i=Math.floor((n+o)/2);Gn(e[i],r)<=0?o=i:n=i+1}return n}function am(e,t){let r=yr([e],t);if(r.status!==Be.Found)throw ne.fromCode(new xt(`Could not find canister range for shard ${e.toString()}`,r.status));return r.value}function cc(e,t){return e.delegation?U.fromUint8Array(e.delegation.subnet_id):U.selfAuthenticating(t)}var rd=U.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe");function _s(e,t){switch(t){case"raw":return e;case"leb128":return ic(e);case"cbor":return Me(e);case"hex":return j(e);case"utf-8":return new TextDecoder().decode(e)}}function nd(e){return Me(e).map(r=>U.fromUint8Array(r))}function od(e,t){let r=typeof e=="string"?$(e):e;return[$("canister"),t,$("metadata"),r]}function Mr(e){return typeof e=="object"&&e!==null&&"key"in e&&"path"in e}function co(e,t){let r=ti(["subnet",t.toUint8Array(),"node"],e.tree);if(r.status!==qr.Found)throw ne.fromCode(new xt("Node not found",r.status));if(r.value instanceof Uint8Array)throw ce.fromCode(new Cr("Invalid node tree"));let n=ms(r.value),o=new Map;return n.forEach(i=>{let s=U.from(i[1]).toText(),a=yr(["public_key"],i[2]);if(a.status!==Be.Found)throw ne.fromCode(new xt("Public key not found",a.status));let c=a.value;if(c.byteLength!==44)throw ne.fromCode(new Kn(44,c.byteLength));o.set(s,c)}),o}var id=async e=>{let{agent:t,paths:r,disableCertificateTimeVerification:n=!1}=e,o=U.from(e.canisterId),i=[...new Set(r)],s=new Map,a=i.map((c,u)=>{let p=lm(c,o);return(async()=>{try{if(t.rootKey===null)throw ye.fromCode(new at);let d=t.rootKey,l=await t.readState(o,{paths:[p]}),f=await st.create({certificate:l.certificate,rootKey:d,principal:{canisterId:o},disableTimeVerification:n,agent:t}),h=(m,x)=>{if(x==="subnet"){let y=cm(l.certificate,o,d);return{path:x,data:y}}else return{path:x,data:ve(m.lookup_path(p))}},{path:_,data:g}=h(f,i[u]);if(!g)typeof _=="string"?s.set(_,null):s.set(_.key,null);else switch(_){case"time":{s.set(_,Lr(g));break}case"controllers":{s.set(_,nd(g));break}case"module_hash":{s.set(_,j(g));break}case"subnet":{s.set(_,g);break}case"candid":{s.set(_,new TextDecoder().decode(g));break}default:Mr(_)&&s.set(_.key,_s(g,_.decodeStrategy))}}catch(d){if(d instanceof nt&&(d.hasCode(gt)||d.hasCode(or)))throw d;Mr(c)?s.set(c.key,null):s.set(c,null)}})()});return await Promise.all(a),s},cm=(e,t,r)=>{if(!t._isPrincipal)throw Y.fromCode(new Re("Invalid canisterId"));let n=Me(e),{delegation:o}=n,i;o&&o.subnet_id?i=U.fromUint8Array(new Uint8Array(o.subnet_id)):!o&&typeof r<"u"?i=U.selfAuthenticating(new Uint8Array(r)):i=rd;let s=co(n,i);return{subnetId:i.toText(),nodeKeys:s}},lm=(e,t)=>{let r=t.toUint8Array();switch(e){case"time":return[$("time")];case"controllers":return[$("canister"),r,$("controllers")];case"module_hash":return[$("canister"),r,$("module_hash")];case"subnet":return[$("subnet")];case"candid":return[$("canister"),r,$("metadata"),$("candid:service")];default:if(Mr(e))return typeof e.path=="string"||e.path instanceof Uint8Array?od(e.path,r):e.path}throw ce.fromCode(new Re(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))};async function sd(e){let{agent:t,paths:r,disableCertificateTimeVerification:n=!1}=e,o=U.from(e.subnetId),i=[...new Set(r)],s=new Map,a=i.map((c,u)=>{let p=um(c,o);return(async()=>{try{if(t.rootKey===null)throw ye.fromCode(new at);let d=t.rootKey,l=await t.readSubnetState(o,{paths:[p]}),f=await st.create({certificate:l.certificate,rootKey:d,principal:{subnetId:o},disableTimeVerification:n,agent:t}),h=(m,x)=>{if(x==="nodeKeys"){let y=co(m.cert,o);return{path:x,data:y}}else return{path:x,data:ve(m.lookup_path(p))}},{path:_,data:g}=h(f,i[u]);if(!g)typeof _=="string"?s.set(_,null):s.set(_.key,null);else switch(_){case"time":{s.set(_,Lr(g));break}case"canisterRanges":{s.set(_,ac(g));break}case"publicKey":{s.set(_,g);break}case"nodeKeys":{s.set(_,g);break}default:Mr(_)&&s.set(_.key,_s(g,_.decodeStrategy))}}catch(d){if(d instanceof nt&&(d.hasCode(gt)||d.hasCode(or)))throw d;Mr(c)?s.set(c.key,null):s.set(c,null)}})()});return await Promise.all(a),s}function um(e,t){let r=t.toUint8Array();switch(e){case"time":return[$("time")];case"canisterRanges":return[$("canister_ranges"),r];case"publicKey":return[$("subnet"),r,$("public_key")];case"nodeKeys":return[$("subnet"),r,$("node")];default:if(Mr(e))if(typeof e.path=="string"||e.path instanceof Uint8Array){let n=typeof e.path=="string"?$(e.path):e.path;return[$("subnet"),r,n]}else return e.path}throw ce.fromCode(new Re(`Error while encoding your path for subnet status. Please ensure that your path ${e} was formatted correctly.`))}var jr=BigInt(0),Ae=BigInt(1),lc=BigInt(2),dm=BigInt(8);function pm(e,t,r,n){let o=e.sqr(r),i=e.sqr(n),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function fm(e,t={}){let r=ss("edwards",e,t,t.FpFnLE),{Fp:n,Fn:o}=r,i=r.CURVE,{h:s}=i;fr(t,{},{uvRatio:"function"});let a=lc<<BigInt(o.BYTES*8)-Ae,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:jr}}});if(!pm(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function p(g,m,x=!1){let y=x?Ae:jr;return ns("coordinate "+g,m,y,a),m}function d(g){if(!(g instanceof h))throw new Error("ExtendedPoint expected")}let l=Dr((g,m)=>{let{X:x,Y:y,Z:T}=g,E=g.is0();m==null&&(m=E?dm:n.inv(T));let O=c(x*m),R=c(y*m),v=n.mul(T,m);if(E)return{x:jr,y:Ae};if(v!==Ae)throw new Error("invZ was invalid");return{x:O,y:R}}),f=Dr(g=>{let{a:m,d:x}=i;if(g.is0())throw new Error("bad point: ZERO");let{X:y,Y:T,Z:E,T:O}=g,R=c(y*y),v=c(T*T),w=c(E*E),I=c(w*w),F=c(R*m),S=c(w*c(F+v)),b=c(I+c(x*c(R*v)));if(S!==b)throw new Error("bad point: equation left != right (1)");let N=c(y*T),C=c(E*O);if(N!==C)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 i}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,Ae,c(x*y))}static fromBytes(m,x=!1){let y=n.BYTES,{a:T,d:E}=i;m=Da(Br(m,y,"point")),Cn(x,"zip215");let O=Da(m),R=m[y-1];O[y-1]=R&-129;let v=dr(O),w=x?a:n.ORDER;ns("point.y",v,jr,w);let I=c(v*v),F=c(I-Ae),S=c(E*I-T),{isValid:b,value:N}=u(F,S);if(!b)throw new Error("bad point: invalid y coordinate");let C=(N&Ae)===Ae,B=(R&128)!==0;if(!x&&N===jr&&B)throw new Error("bad point: x=0 and x_0=1");return B!==C&&(N=c(-N)),h.fromAffine({x:N,y:v})}static fromHex(m,x=!1){return h.fromBytes(pe("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(lc),this}assertValidity(){f(this)}equals(m){d(m);let{X:x,Y:y,Z:T}=this,{X:E,Y:O,Z:R}=m,v=c(x*R),w=c(E*T),I=c(y*R),F=c(O*T);return v===w&&I===F}is0(){return this.equals(h.ZERO)}negate(){return new h(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:m}=i,{X:x,Y:y,Z:T}=this,E=c(x*x),O=c(y*y),R=c(lc*c(T*T)),v=c(m*E),w=x+y,I=c(c(w*w)-E-O),F=v+O,S=F-R,b=v-O,N=c(I*S),C=c(F*b),B=c(I*b),L=c(S*F);return new h(N,C,L,B)}add(m){d(m);let{a:x,d:y}=i,{X:T,Y:E,Z:O,T:R}=this,{X:v,Y:w,Z:I,T:F}=m,S=c(T*v),b=c(E*w),N=c(R*y*F),C=c(O*I),B=c((T+E)*(v+w)-S-b),L=C-N,A=C+N,P=c(b-x*S),V=c(B*L),D=c(A*P),q=c(B*P),te=c(L*A);return new h(V,D,te,q)}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=>dt(h,T));return dt(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===jr?h.ZERO:this.is0()||m===Ae?this:_.unsafe(this,m,y=>dt(h,y),x)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return _.unsafe(this,i.n).is0()}toAffine(m){return l(this,m)}clearCofactor(){return s===Ae?this:this.multiplyUnsafe(s)}toBytes(){let{x:m,y:x}=this.toAffine(),y=n.toBytes(x);return y[y.length-1]|=m&Ae?128:0,y}toHex(){return j(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 dt(h,m)}static msm(m,x){return io(h,o,m,x)}_setWindowSize(m){this.precompute(m)}toRawBytes(){return this.toBytes()}}h.BASE=new h(i.Gx,i.Gy,Ae,c(i.Gx*i.Gy)),h.ZERO=new h(jr,Ae,Ae,jr),h.Fp=n,h.Fn=o;let _=new oo(h,o.BITS);return h.BASE.precompute(8),h}var ys=class{constructor(t){this.ep=t}static fromBytes(t){ro()}static fromHex(t){ro()}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 j(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 hm(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');fr(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:i,Fn:s}=e,a=r.randomBytes||jn,c=r.adjustScalarBytes||(w=>w),u=r.domain||((w,I,F)=>{if(Cn(F,"phflag"),I.length||F)throw new Error("Contexts/pre-hash are not supported");return w});function p(w){return s.create(dr(w))}function d(w){let I=y.secretKey;w=pe("private key",w,I);let F=pe("hashed private key",t(w),2*I),S=c(F.slice(0,I)),b=F.slice(I,2*I),N=p(S);return{head:S,prefix:b,scalar:N}}function l(w){let{head:I,prefix:F,scalar:S}=d(w),b=o.multiply(S),N=b.toBytes();return{head:I,prefix:F,scalar:S,point:b,pointBytes:N}}function f(w){return l(w).pointBytes}function h(w=Uint8Array.of(),...I){let F=K(...I);return p(t(u(F,pe("context",w),!!n)))}function _(w,I,F={}){w=pe("message",w),n&&(w=n(w));let{prefix:S,scalar:b,pointBytes:N}=l(I),C=h(F.context,S,w),B=o.multiply(C).toBytes(),L=h(F.context,B,N,w),A=s.create(C+L*b);if(!s.isValid(A))throw new Error("sign failed: invalid s");let P=K(B,s.toBytes(A));return Br(P,y.signature,"result")}let g={zip215:!0};function m(w,I,F,S=g){let{context:b,zip215:N}=S,C=y.signature;w=pe("signature",w,C),I=pe("message",I),F=pe("publicKey",F,y.publicKey),N!==void 0&&Cn(N,"zip215"),n&&(I=n(I));let B=C/2,L=w.subarray(0,B),A=dr(w.subarray(B,C)),P,V,D;try{P=e.fromBytes(F,N),V=e.fromBytes(L,N),D=o.multiplyUnsafe(A)}catch{return!1}if(!N&&P.isSmallOrder())return!1;let q=h(b,V.toBytes(),P.toBytes(),I);return V.add(P.multiplyUnsafe(q)).subtract(D).clearCofactor().is0()}let x=i.BYTES,y={secretKey:x,publicKey:x,signature:2*x,seed:x};function T(w=a(y.seed)){return Br(w,y.seed,"seed")}function E(w){let I=v.randomSecretKey(w);return{secretKey:I,publicKey:f(I)}}function O(w){return At(w)&&w.length===s.BYTES}function R(w,I){try{return!!e.fromBytes(w,I)}catch{return!1}}let v={getExtendedPublicKey:l,randomSecretKey:T,isValidSecretKey:O,isValidPublicKey:R,toMontgomery(w){let{y:I}=e.fromBytes(w),F=y.publicKey,S=F===32;if(!S&&F!==57)throw new Error("only defined for 25519 and 448");let b=S?i.div(Ae+I,Ae-I):i.div(I-Ae,I+Ae);return i.toBytes(b)},toMontgomerySecret(w){let I=y.secretKey;Br(w,I);let F=t(w.subarray(0,I));return c(F).subarray(0,I)},randomPrivateKey:T,precompute(w=8,I=e.BASE){return I.precompute(w,!1)}};return Object.freeze({keygen:E,getPublicKey:f,sign:_,verify:m,utils:v,Point:e,lengths:y})}function mm(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=Ke(t.n,e.nBitLength,!0),o={Fp:r,Fn:n,uvRatio:e.uvRatio},i={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:o,hash:e.hash,eddsaOpts:i}}function _m(e,t){let r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function ad(e){let{CURVE:t,curveOpts:r,hash:n,eddsaOpts:o}=mm(e),i=fm(t,r),s=hm(i,n,o);return _m(e,s)}var ym=BigInt(0),gr=BigInt(1),cd=BigInt(2),hx=BigInt(3),gm=BigInt(5),xm=BigInt(8),lo=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ri={p:lo,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:xm,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function bm(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=lo,a=e*e%i*e%i,c=It(a,cd,i)*a%i,u=It(c,gr,i)*e%i,p=It(u,gm,i)*u%i,d=It(p,t,i)*p%i,l=It(d,r,i)*d%i,f=It(l,n,i)*l%i,h=It(f,o,i)*f%i,_=It(h,o,i)*f%i,g=It(_,t,i)*p%i;return{pow_p_5_8:It(g,cd,i)*e%i,b2:a}}function wm(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var uc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function fc(e,t){let r=lo,n=le(t*t*t,r),o=le(n*n*t,r),i=bm(e*o).pow_p_5_8,s=le(e*n*i,r),a=le(t*s*s,r),c=s,u=le(s*uc,r),p=a===e,d=a===le(-e,r),l=a===le(-e*uc,r);return p&&(s=c),(d||l)&&(s=u),hr(s,r)&&(s=le(-s,r)),{isValid:p||d,value:s}}var Kr=Ke(ri.p,{isLE:!0}),Tm=Ke(ri.n,{isLE:!0}),Nm={...ri,Fp:Kr,hash:vl,adjustScalarBytes:wm,uvRatio:fc},Ge=ad(Nm);var dc=uc,Om=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Em=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Rm=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Im=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),ld=e=>fc(gr,e),vm=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),pc=e=>Ge.Point.Fp.create(dr(e)&vm);function ud(e){let{d:t}=ri,r=lo,n=m=>Kr.create(m),o=n(dc*e*e),i=n((o+gr)*Rm),s=BigInt(-1),a=n((s-t*o)*n(o+t)),{isValid:c,value:u}=fc(i,a),p=n(u*e);hr(p,r)||(p=n(-p)),c||(u=p),c||(s=o);let d=n(s*(o-gr)*Im-a),l=u*u,f=n((u+u)*a),h=n(d*Om),_=n(gr-l),g=n(gr+l);return new Ge.Point(n(f*g),n(_*h),n(h*g),n(f*_))}function Am(e){me(e,64);let t=pc(e.subarray(0,32)),r=ud(t),n=pc(e.subarray(32,64)),o=ud(n);return new xr(r.add(o))}var xr=class e extends ys{constructor(t){super(t)}static fromAffine(t){return new e(Ge.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static hashToCurve(t){return Am(pe("ristrettoHash",t,64))}static fromBytes(t){me(t,32);let{a:r,d:n}=ri,o=lo,i=T=>Kr.create(T),s=pc(t);if(!bu(Kr.toBytes(s),t)||hr(s,o))throw new Error("invalid ristretto255 encoding 1");let a=i(s*s),c=i(gr+r*a),u=i(gr-r*a),p=i(c*c),d=i(u*u),l=i(r*n*p-d),{isValid:f,value:h}=ld(i(l*d)),_=i(h*u),g=i(h*_*l),m=i((s+s)*_);hr(m,o)&&(m=i(-m));let x=i(c*g),y=i(m*x);if(!f||hr(y,o)||x===ym)throw new Error("invalid ristretto255 encoding 2");return new e(new Ge.Point(m,x,gr,y))}static fromHex(t){return e.fromBytes(pe("ristrettoHex",t,32))}static msm(t,r){return io(e,Ge.Point.Fn,t,r)}toBytes(){let{X:t,Y:r,Z:n,T:o}=this.ep,i=lo,s=g=>Kr.create(g),a=s(s(n+r)*s(n-r)),c=s(t*r),u=s(c*c),{value:p}=ld(s(a*u)),d=s(p*a),l=s(p*c),f=s(d*l*o),h;if(hr(o*f,i)){let g=s(r*dc),m=s(t*dc);t=g,r=m,h=s(d*Em)}else h=l;hr(t*f,i)&&(r=s(-r));let _=s((n-r)*h);return hr(_,i)&&(_=s(-_)),Kr.toBytes(_)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:o,Y:i}=t.ep,s=u=>Kr.create(u),a=s(r*i)===s(n*o),c=s(n*i)===s(r*o);return a||c}is0(){return this.equals(e.ZERO)}};xr.BASE=new xr(Ge.Point.BASE);xr.ZERO=new xr(Ge.Point.ZERO);xr.Fp=Kr;xr.Fn=Tm;var dd,pd,gs=class{static{dd=Symbol.iterator,pd=Symbol.toStringTag}#e;#t;constructor(t={}){this[dd]=this.entries.bind(this),this[pd]="ExpirableMap";let{source:r=[],expirationTime:n=600*1e3}=t,o=Date.now();this.#e=new Map([...r].map(([i,s])=>[i,{value:s,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 fd=e=>{if(e<=127)return 1;if(e<=255)return 2;if(e<=65535)return 3;if(e<=16777215)return 4;throw Y.fromCode(new Oo("Length too long (> 4 bytes)"))},hd=(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 Y.fromCode(new Oo("Length too long (> 4 bytes)"))},hc=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw Y.fromCode(new bt("Invalid length 0"));if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw Y.fromCode(new bt("Length too long (> 4 bytes)"))},Sm=(e,t)=>{let r=hc(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 Y.fromCode(new bt("Length too long (> 4 bytes)"))},ni=Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]),Dn=Uint8Array.from([48,5,6,3,43,101,112]),xx=Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]),bx=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 Un(e,t){let r=2+fd(e.byteLength+1),n=t.byteLength+r+e.byteLength,o=0,i=new Uint8Array(1+fd(n)+n);return i[o++]=48,o+=hd(i,o,n),i.set(t,o),o+=t.byteLength,i[o++]=3,o+=hd(i,o,e.byteLength+1),i[o++]=0,i.set(new Uint8Array(e),o),i}var kn=(e,t)=>{let r=0,n=(a,c)=>{if(o[r++]!==a)throw Y.fromCode(new bt(`Expected ${c} at offset ${r}`))},o=new Uint8Array(e);if(n(48,"sequence"),r+=hc(o,r),!vn(o.slice(r,r+t.byteLength),t))throw Y.fromCode(new bt("Not the expected OID."));r+=t.byteLength,n(3,"bit string");let i=Sm(o,r)-1;r+=hc(o,r),n(0,"0 padding");let s=o.slice(r);if(i!==s.length)throw Y.fromCode(new vi(i,s.length));return s};var xs=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 Un(t,Dn)}static derDecode(t){let r=kn(t,Dn);if(r.length!==this.RAW_KEY_LENGTH)throw Y.fromCode(new bt("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 Y.fromCode(new bt("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 mc=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))}},bs=class extends mc{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 ws=class e{#e;#t;#r;#i;#a;#d;#n;#o;#c=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:i=6e4,maxElapsedTime:s=9e5,maxIterations:a=10,date:c=Date}=t;this.#e=r,this.#t=n,this.#r=o,this.#i=i,this.#o=c,this.#a=c.now(),this.#d=s,this.#n=a}get ellapsedTimeInMsec(){return this.#o.now()-this.#a}get currentInterval(){return this.#e}get count(){return this.#c}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.#i),this.#c++,this.#e}next(){return this.ellapsedTimeInMsec>=this.#d||this.#c>=this.#n?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};var Ut;(function(e){e.Received="received",e.Processing="processing",e.Replied="replied",e.Rejected="rejected",e.Unknown="unknown",e.Done="done"})(Ut||(Ut={}));var gc=60*1e3,Cm=1e6,Fm=0,Pm="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae";var Vm="ic0.app",Bm=".ic0.app",Dm="icp0.io",Um=".icp0.io",km="icp-api.io",Lm=".icp-api.io",_c=200,qm=202,Mm=404;function jm(){let e;if(typeof window<"u")if(window.fetch)e=window.fetch.bind(window);else throw ye.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 ye.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 ye.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 Km(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,i=o?.hostname,s;i&&typeof i=="string"&&(n.some(a=>i.endsWith(a))?s=i:s=r.find(a=>i.endsWith(a))),o&&s?t=new URL(`${o.protocol}//${s}${o.port?":"+o.port:""}`):t=new URL("https://icp-api.io")}return t.toString()}var br=class e{#e;#t;#r;#i;#a;#d;#n;#o;#c;#w;#s;#u;#f;#l;get#E(){return this.#l*gc}#h;#m;#_;#y;constructor(t={}){this.#e=null,this.#t=!1,this.#r=Fm,this.#i=!1,this.#a=null,this.#d=!1,this._isAgent=!0,this.config={},this.log=new bs,this.#h=[],this.#m=[],this.#_=new gs({expirationTime:5*gc}),this.#y=!0,this.#T=(o,i)=>{if(this.#y===!1)return o;let{status:s,signatures:a=[],requestId:c}=o;for(let u of a){let{timestamp:p,identity:d}=u,l=U.fromUint8Array(d).toText(),f;if(s===Er.Replied){let{reply:x}=o;f=Do({status:s,reply:x,timestamp:BigInt(p),request_id:c})}else if(s===Er.Rejected){let{reject_code:x,reject_message:y,error_code:T}=o;f=Do({status:s,reject_code:x,reject_message:y,error_code:T,timestamp:BigInt(p),request_id:c})}else throw ce.fromCode(new Re(`Unknown status: ${s}`));let h=K(Oa,f),_=i.get(l);if(!_)throw ne.fromCode(new Li);let g=xs.fromDer(_).rawKey;if(!Ge.verify(u.signature,h,g))throw Le.fromCode(new qi(l))}return o},this.config=t,this.#o=t.fetch||jm()||fetch.bind(global),this.#c=t.fetchOptions,this.#w=t.callOptions,this.#t=t.shouldFetchRootKey??!1,this.#d=t.shouldSyncTime??!1,t.rootKey?this.rootKey=t.rootKey:this.#t?this.rootKey=null:this.rootKey=Ee(Pm);let r=Km(t.host);this.host=new URL(r),t.verifyQuerySignatures!==void 0&&(this.#y=t.verifyQuerySignatures),this.#u=t.retryTimes??3;let n=()=>new ws({maxIterations:this.#u});if(this.#f=t.backoffStrategy||n,this.host.hostname.endsWith(Bm)?this.host.hostname=Vm:this.host.hostname.endsWith(Um)?this.host.hostname=Dm:this.host.hostname.endsWith(Lm)&&(this.host.hostname=km),t.credentials){let{name:o,password:i}=t.credentials;this.#s=`${o}${i?":"+i:""}`}if(this.#n=Promise.resolve(t.identity||new ot),t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes>5)throw Y.fromCode(new Ct("The maximum ingress expiry time is 5 minutes.",t.ingressExpiryInMinutes));if(t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes<=0)throw Y.fromCode(new Ct("Ingress expiry time must be greater than 0.",t.ingressExpiryInMinutes));this.#l=t.ingressExpiryInMinutes||5,this.addTransform("update",Ca(Ho)),t.useQueryNonces&&this.addTransform("query",Ca(Ho)),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.#p(),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 Y.fromCode(new Di)}}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.#m.findIndex(i=>(i.priority||0)<n);this.#m.splice(o>=0?o:this.#m.length,0,Object.assign(r,{priority:n}))}else if(t==="query"){let o=this.#h.findIndex(i=>(i.priority||0)<n);this.#h.splice(o>=0?o:this.#h.length,0,Object.assign(r,{priority:n}))}}async getPrincipal(){if(!this.#n)throw ye.fromCode(new Sr);return(await this.#n).getPrincipal()}async call(t,r,n){let o=r.callSync??!0,i=await(n??this.#n);if(!i)throw ye.fromCode(new Sr);let s=U.from(t),a=r.effectiveCanisterId?U.from(r.effectiveCanisterId):s;await this.#p(a);let c=i.getPrincipal(),u=yc(this.#l,this.#r),p={request_type:es.Call,canister_id:s,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:ur.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 i.transformRequest(d);let h=jo(d.body),_=this.#f(),g=cr(p);try{let y=o?()=>{let R=new URL(`/api/v4/canister/${a.toText()}/call`,this.host);return this.log.print(`fetching "${R.pathname}" with request:`,d),this.#o(R,{...this.#w,...d.request,body:h})}:()=>{let R=new URL(`/api/v2/canister/${a.toText()}/call`,this.host);return this.log.print(`fetching "${R.pathname}" with request:`,d),this.#o(R,{...this.#w,...d.request,body:h})},{responseBodyBytes:T,...E}=await this.#g({requestFn:y,backoff:_,tries:0}),O=T.byteLength>0?Me(T):null;return{requestId:g,response:{...E,body:O},requestDetails:p}}catch(m){let x;if(m instanceof nt){if(m.hasCode(Ro))return this.log.warn("v4 api not supported. Fall back to v2"),this.call(t,{...r,callSync:!1},n);if(m.hasCode(Ct)&&!this.#i)return await this.syncTime(s),this.call(s,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=ce.fromCode(new Re(m));throw this.log.error(`Error while making call: ${x.message}`,x),x}}async#b(t){let{ecid:r,transformedRequest:n,body:o,requestId:i,backoff:s,tries:a}=t,c=a===0?0:s.next(),u=new URL(`/api/v3/canister/${r.toString()}/query`,this.host);if(this.log.print(`fetching "${u.pathname}" with tries:`,{tries:a,backoff:s,delay:c}),c===null)throw ce.fromCode(new Nn(`Backoff strategy exhausted after ${a} attempts.`,i));c>0&&await new Promise(m=>setTimeout(m,c));let p;try{this.log.print(`fetching "${u.pathname}" with request:`,n),p=await this.#o(u,{...this.#c,...n.request,body:o})}catch(m){if(a<this.#u)return this.log.warn(`Caught exception while attempting to make query:
51
51
  ${m}
52
- Retrying query.`),await this.#b({...t,tries:a+1});throw bo.fromCode(new Oo(m))}let d=ga(p.headers);if(p.status!==rc){let m=await p.text();if(rd(m))throw Y.fromCode(new Ct(m,this.#l));if(a<this.#u)return await this.#b({...t,tries:a+1});throw te.fromCode(new To(p.status,p.statusText,d,m))}let f={...qe(Gn(await p.arrayBuffer())),httpDetails:{ok:p.ok,status:p.status,statusText:p.statusText,headers:d},requestId:i};if(!this.#y)return f;let h=f.signatures?.[0]?.timestamp;if(!h)throw te.fromCode(new Pi("Timestamp not found in query response. This suggests a malformed or malicious response."));let _=Number(BigInt(h)/BigInt(_m));if(Date.now()+this.#r-_>this.#E){if(a<this.#u)return this.log.warn("Timestamp is older than the max ingress expiry. Retrying query.",{requestId:i,signatureTimestampMs:_}),await this.syncTime(r),await this.#b({...t,tries:a+1});throw ke.fromCode(new vi(this.#l,i,a))}return f}async#g(t){let{requestFn:r,backoff:n,tries:o}=t,i=o===0?0:n.next();if(i===null)throw te.fromCode(new xn(`Retry strategy exhausted after ${o} attempts.`));i>0&&await new Promise(p=>setTimeout(p,i));let s,a=new Uint8Array;try{s=await r(),s.status===rc&&(a=Gn(await s.clone().arrayBuffer()))}catch(p){if(o<this.#u)return this.log.warn(`Caught exception while attempting to make request:
52
+ Retrying query.`),await this.#b({...t,tries:a+1});throw No.fromCode(new Io(m))}let d=Fa(p.headers);if(p.status!==_c){let m=await p.text();if(md(m))throw Y.fromCode(new Ct(m,this.#l));if(a<this.#u)return await this.#b({...t,tries:a+1});throw ne.fromCode(new Eo(p.status,p.statusText,d,m))}let f={...Me(Zn(await p.arrayBuffer())),httpDetails:{ok:p.ok,status:p.status,statusText:p.statusText,headers:d},requestId:i};if(!this.#y)return f;let h=f.signatures?.[0]?.timestamp;if(!h)throw ne.fromCode(new Ui("Timestamp not found in query response. This suggests a malformed or malicious response."));let _=Number(BigInt(h)/BigInt(Cm));if(Date.now()+this.#r-_>this.#E){if(a<this.#u)return this.log.warn("Timestamp is older than the max ingress expiry. Retrying query.",{requestId:i,signatureTimestampMs:_}),await this.syncTime(r),await this.#b({...t,tries:a+1});throw Le.fromCode(new Ci(this.#l,i,a))}return f}async#g(t){let{requestFn:r,backoff:n,tries:o}=t,i=o===0?0:n.next();if(i===null)throw ne.fromCode(new Nn(`Retry strategy exhausted after ${o} attempts.`));i>0&&await new Promise(p=>setTimeout(p,i));let s,a=new Uint8Array;try{s=await r(),s.status===_c&&(a=Zn(await s.clone().arrayBuffer()))}catch(p){if(o<this.#u)return this.log.warn(`Caught exception while attempting to make request:
53
53
  ${p}
54
- Retrying request.`),await this.#g({requestFn:r,backoff:n,tries:o+1});throw bo.fromCode(new Oo(p))}let c=ga(s.headers);if(s.status===rc||s.status===Em)return{ok:s.ok,status:s.status,statusText:s.statusText,responseBodyBytes:a,headers:c};let u=await s.text();if(s.status===Rm&&s.url.includes("api/v4"))throw te.fromCode(new No);if(rd(u))throw Y.fromCode(new Ct(u,this.#l));if(o<this.#u)return await this.#g({requestFn:r,backoff:n,tries:o+1});throw te.fromCode(new To(s.status,s.statusText,c,u))}async query(t,r,n){let o=this.#f(),i=r.effectiveCanisterId?k.from(r.effectiveCanisterId):k.from(t);await this.#p(i),this.log.print(`ecid ${i.toString()}`),this.log.print(`canisterId ${t.toString()}`);let s,a=await(n??this.#n);if(!a)throw ye.fromCode(new Or);let c=k.from(t),u=a.getPrincipal(),p=nc(this.#l,this.#r),d={request_type:Rn.Query,canister_id:c,method_name:r.methodName,arg:r.arg,sender:u,ingress_expiry:p},l=rr(d);s=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:or.Query,body:d}),s=await a.transformRequest(s);let f=Lo(s.body),h={canister:c.toText(),ecid:i,transformedRequest:s,body:f,requestId:l,backoff:o,tries:0},_=async()=>{let m=await this.#b(h);return{requestDetails:d,...m}},g=async()=>{let m=this.#_.get(i.toString());if(m)return m;await this.fetchSubnetKeys(i.toString());let x=this.#_.get(i.toString());if(!x)throw ke.fromCode(new Bi);return x};try{if(!this.#y)return await _();let[m,x]=await Promise.all([_(),g()]);try{return this.#T(m,x)}catch{this.log.warn("Query response verification failed. Retrying with fresh subnet keys."),this.#_.delete(i.toString());let y=await g();return this.#T(m,y)}}catch(m){let x;if(m instanceof et){if(m.hasCode(Ct)&&!this.#i)return await this.syncTime(i),this.query(t,r,n);m.code.requestContext={requestId:l,senderPubKey:s.body.sender_pubkey,senderSignature:s.body.sender_sig,ingressExpiry:s.body.content.ingress_expiry},x=m}else x=ae.fromCode(new Re(m));throw this.log.error(`Error while making query: ${x.message}`,x),x}}#T;async createReadStateRequest(t,r){await this.#p();let n=await(r??this.#n);if(!n)throw ye.fromCode(new Or);let o=n.getPrincipal(),i=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:or.ReadState,body:{request_type:Rn.ReadState,paths:t.paths,sender:o,ingress_expiry:nc(this.#l,this.#r)}});return n.transformRequest(i)}async readState(t,r,n,o){await this.#x();let i=k.from(t);function s(p){for(let d of p.paths){let[l,f]=d,h=new TextEncoder().encode("request_status");if(On(l,h))return f}}let a,c;if(o)a=o;else{c=s(r);let p=await this.#n;if(!p)throw ye.fromCode(new Or);a=await this.createReadStateRequest(r,p)}let u=new URL(`/api/v3/canister/${i.toString()}/read_state`,this.host);return await this.#N(u,{canisterId:i},a,c)}async readSubnetState(t,r){await this.#x();let n=k.from(t),o=new URL(`/api/v3/subnet/${n.toString()}/read_state`,this.host),i=await this.createReadStateRequest(r,this.#n??void 0);return await this.#N(o,{subnetId:n},i)}async#N(t,r,n,o){let i=this.#f();try{let{responseBodyBytes:s}=await this.#g({requestFn:()=>this.#o(t,{...this.#c,...n.request,body:Lo(n.body)}),backoff:i,tries:0});return qe(s)}catch(s){let a;if(s instanceof et){if(s.hasCode(Ct)&&!this.#i){if("canisterId"in r)await this.syncTime(r.canisterId);else if("subnetId"in r)await this.syncTimeWithSubnet(r.subnetId);else throw it;return await this.#N(t,r,n,o)}s.code.requestContext={requestId:o??rr(n),senderPubKey:n.body.sender_pubkey,senderSignature:n.body.sender_sig,ingressExpiry:n.body.content.ingress_expiry},a=s}else a=ae.fromCode(new Re(s));throw this.log.error(`Error while making read state: ${a.message}`,a),a}}parseTimeFromResponse(t){let r;if(t.certificate){let n=qe(t.certificate);if(n&&"tree"in n)r=n.tree;else throw te.fromCode(new Er("Could not decode time from response"));let o=dr(["time"],r);if(o.status!==Be.Found)throw te.fromCode(new xt("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 Ti("Time was not in its expected format."));let i=Vr(o.value);return this.log.print("Time from response:",i),this.log.print("Time from response in milliseconds:",i.getTime()),i.getTime()}else this.log.warn("No certificate found in response");return 0}async syncTime(t){this.#a=this.#a??(async()=>{await this.#x();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 tt,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 a=(await Gu({canisterId:n,agent:o,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(a instanceof Date)return a.getTime()},[]));this.#O(r,i)}catch(n){let o=n instanceof et?n:ae.fromCode(new Re(n));throw this.log.error("Caught exception while attempting to sync time",o),o}})(),await this.#a.finally(()=>{this.#a=null})}async syncTimeWithSubnet(t){await this.#x();let r=Date.now();try{let n=e.createSync({identity:new tt,host:this.host.toString(),fetch:this.#o,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),o=await Promise.all(Array(3).fill(null).map(async()=>{let s=(await Ju({subnetId:t,agent:n,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(s instanceof Date)return s.getTime()},[]));this.#O(r,o)}catch(n){let o=n instanceof et?n:ae.fromCode(new Re(n));throw this.log.error("Caught exception while attempting to sync time with subnet",o),o}}#O(t,r){let n=r.reduce((o,i)=>typeof i=="number"&&i>o?i:o,0);n>0&&(this.#r=n-t,this.#i=!0,this.log.notify({message:`Syncing time: offset of ${this.#r}`,level:"info"}))}async status(){let t=this.#s?{Authorization:"Basic "+btoa(this.#s)}:{},r=new URL("/api/v2/status",this.host);this.log.print(`fetching "${r.pathname}"`);let n=this.#f(),{responseBodyBytes:o}=await this.#g({backoff:n,requestFn:()=>this.#o(r,{headers:t,...this.#c}),tries:0});return qe(o)}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#p(t){await Promise.all([this.#x(),this.#R(t)])}async#x(){if(!this.rootKey)if(this.rootKey===null&&this.host.toString()!=="https://icp-api.io"&&this.#t)await this.fetchRootKey();else throw ye.fromCode(new ot(this.#t))}async#R(t){this.#d&&!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.#p(r);let n=this.rootKey,o=await this.readState(r,{paths:[[$("subnet")]]}),i=await nt.create({certificate:o.certificate,rootKey:n,principal:{canisterId:r},agent:this});if(!i.cert.delegation){let c=k.selfAuthenticating(n);if(!Ga({canisterId:r,subnetId:c,tree:i.cert.tree}))throw ke.fromCode(new gn(r,c))}let s=Wa(i.cert,n),a=no(i.cert,s);return this.#_.set(r.toText(),a),a}async getSubnetIdFromCanister(t){let r=k.from(t);await this.#p(r);let n=await this.readState(r,{paths:[[$("time")]]}),o=await nt.create({certificate:n.certificate,rootKey:this.rootKey,principal:{canisterId:r},agent:this});return Wa(o.cert,this.rootKey)}_transform(t){let r=Promise.resolve(t);if(t.endpoint===or.Call)for(let n of this.#m)r=r.then(o=>n(o).then(i=>i||o));else for(let n of this.#h)r=r.then(o=>n(o).then(i=>i||o));return r}getTimeDiffMsecs(){return this.#r}hasSyncedTime(){return this.#i}};function nc(e,t){let r=e*oc;return Yn.fromDeltaInMilliseconds(r,t)}function rd(e){return e.includes("Invalid request expiry: ")}var Am=300*1e3;function nd(){return Pm(Cm(Sm(),1e3),Vm(1e3,1.2),Fm(Am))}function Sm(){let e=!0;return async()=>e?(e=!1,!0):!1}function Cm(e,t){return async(r,n,o)=>{if(await e(r,n,o))return new Promise(i=>setTimeout(i,t))}}function Fm(e){let t=Date.now()+e;return async(r,n,o)=>{if(Date.now()>t)throw te.fromCode(new xn(`Request timed out after ${e} msec`,n,o))}}function Vm(e,t){let r=e;return()=>new Promise(n=>setTimeout(()=>{r*=t,n()},r))}function Pm(...e){return async(t,r,n)=>{for(let o of e)await o(t,r,n)}}var id={preSignReadStateRequest:!1};function sd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ic(e,t){return e!==null&&typeof e=="object"&&sd(e,t)}function Dm(e,t){return sd(e,t)&&typeof e[t]=="function"}function od(e){return ic(e,"body")&&ic(e.body,"content")&&e.body.content.request_type===Rn.ReadState&&ic(e.body.content,"ingress_expiry")&&typeof e.body.content.ingress_expiry=="object"&&e.body.content.ingress_expiry!==null&&Dm(e.body.content.ingress_expiry,"toHash")}async function sc(e,t,r,n={}){let o=[$("request_status"),r],i,s;if(n.preSignReadStateRequest??!1?(s=await Um({paths:[o],agent:e,pollingOptions:n}),i=await e.readState(t,{paths:[o]},void 0,s)):i=await e.readState(t,{paths:[o]}),e.rootKey==null)throw ye.fromCode(new ot);let c=await nt.create({certificate:i.certificate,rootKey:e.rootKey,principal:{canisterId:t},blsVerify:n.blsVerify,agent:e}),u=ve(c.lookup_path([...o,$("status")])),p;switch(typeof u>"u"?p=Ut.Unknown:p=new TextDecoder().decode(u),p){case Ut.Replied:return{reply:ve(c.lookup_path([...o,"reply"])),certificate:c};case Ut.Received:case Ut.Unknown:case Ut.Processing:{let d=n.strategy??nd();return await d(t,r,p),sc(e,t,r,{...n,strategy:d,request:s})}case Ut.Rejected:{let d=new Uint8Array(ve(c.lookup_path([...o,"reject_code"])))[0],l=new TextDecoder().decode(ve(c.lookup_path([...o,"reject_message"]))),f=ve(c.lookup_path([...o,"error_code"])),h=f?new TextDecoder().decode(f):void 0;throw Nr.fromCode(new Ln(r,d,l,h))}case Ut.Done:throw ae.fromCode(new Ci(r))}throw it}async function Um(e){let{paths:t,agent:r,pollingOptions:n}=e;if(n.request&&od(n.request))return n.request;let o=await r.createReadStateRequest?.({paths:t},void 0);if(!od(o))throw Y.fromCode(new ki(o));return o}var ut=Symbol.for("ic-agent-metadata"),so=class e{static agentOf(t){return t[ut].config.agent}static interfaceOf(t){return t[ut].service}static canisterIdOf(t){return k.from(t[ut].config.canisterId)}static createActorClass(t,r){let n=t({IDL:Nn});class o extends e{constructor(s){if(!s.canisterId)throw Y.fromCode(new Eo(s.canisterId));let a=typeof s.canisterId=="string"?k.fromText(s.canisterId):s.canisterId;super({config:{...ad,...s,canisterId:a},service:n});for(let[c,u]of n._fields)r?.httpDetails&&u.annotations.push(ac),r?.certificate&&u.annotations.push(cd),this[c]=Lm(this,c,u,s.blsVerify)}}return o}static createActor(t,r){if(!r.canisterId)throw Y.fromCode(new Eo(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[ut]=Object.freeze(t)}};function io(e,t){let r=Nn.decode(e,t);switch(r.length){case 0:return;case 1:return r[0];default:return r}}var ad={pollingOptions:id},ac="http-details",cd="certificate";function Lm(e,t,r,n){let o;r.annotations.includes("query")||r.annotations.includes("composite_query")?o=async(s,...a)=>{s={...s,...e[ut].config.queryTransform?.(t,a,{...e[ut].config,...s})};let c=s.agent||e[ut].config.agent||new hr,u=k.from(s.canisterId||e[ut].config.canisterId),p=Nn.encode(r.argTypes,a),d=await c.query(u,{methodName:t,arg:p,effectiveCanisterId:s.effectiveCanisterId}),l={...d.httpDetails,requestDetails:d.requestDetails};switch(d.status){case xr.Rejected:{let f=new Ai(d.requestId,d.reject_code,d.reject_message,d.error_code,d.signatures);throw f.callContext={canisterId:u,methodName:t,httpDetails:l},Nr.fromCode(f)}case xr.Replied:return r.annotations.includes(ac)?{httpDetails:l,result:io(r.retTypes,d.reply.arg)}:io(r.retTypes,d.reply.arg)}}:o=async(s,...a)=>{s={...s,...e[ut].config.callTransform?.(t,a,{...e[ut].config,...s})};let c=s.agent||e[ut].config.agent||hr.createSync(),{canisterId:u,effectiveCanisterId:p,pollingOptions:d}={...ad,...e[ut].config,...s},l=k.from(u),f=p!==void 0?k.from(p):l,h=Nn.encode(r.argTypes,a),{requestId:_,response:g,requestDetails:m}=await c.call(l,{methodName:t,arg:h,effectiveCanisterId:f,nonce:s.nonce}),x,y;if(Yc(g.body)){if(c.rootKey==null)throw ye.fromCode(new ot);let R=g.body.certificate;y=await nt.create({certificate:R,rootKey:c.rootKey,principal:{canisterId:f},blsVerify:n,agent:c});let v=[$("request_status"),_];switch(new TextDecoder().decode(ve(y.lookup_path([...v,"status"])))){case"replied":x=ve(y.lookup_path([...v,"reply"]));break;case"rejected":{let I=new Uint8Array(ve(y.lookup_path([...v,"reject_code"])))[0],F=new TextDecoder().decode(ve(y.lookup_path([...v,"reject_message"]))),S=ve(y.lookup_path([...v,"error_code"])),b=S?new TextDecoder().decode(S):void 0,N=new Ln(_,I,F,b);throw N.callContext={canisterId:l,methodName:t,httpDetails:g},Nr.fromCode(N)}}}else if(zc(g.body)){let{reject_code:R,reject_message:v,error_code:w}=g.body,I=new Si(_,R,v,w);throw I.callContext={canisterId:l,methodName:t,httpDetails:g},Nr.fromCode(I)}if(g.status===202){let R={...d,blsVerify:n},v=await sc(c,f,_,R);y=v.certificate,x=v.reply}let T=r.annotations.includes(ac),E=r.annotations.includes(cd),O={...g,requestDetails:m};if(x!==void 0)return T&&E?{httpDetails:O,certificate:y,result:io(r.retTypes,x)}:E?{certificate:y,result:io(r.retTypes,x)}:T?{httpDetails:O,result:io(r.retTypes,x)}:io(r.retTypes,x);{let R=new Re(`Call was returned undefined. We cannot determine if the call was successful or not. Return types: [${r.retTypes.map(v=>v.display()).join(",")}].`);throw R.callContext={canisterId:l,methodName:t,httpDetails:O},ae.fromCode(R)}};let i=(...s)=>o({},...s);return i.withOptions=s=>(...a)=>o(s,...a),i}var qm=(e=>(e[e.FractionalMoreThan8Decimals=0]="FractionalMoreThan8Decimals",e[e.InvalidFormat=1]="InvalidFormat",e[e.FractionalTooManyDecimals=2]="FractionalTooManyDecimals",e))(qm||{}),pb=BigInt(1e8);var L=e=>e==null,z=e=>!L(e),ri=e=>z(e)&&e!=="",ao=e=>!ri(e);var Mm=class extends Error{},ni=(e,t)=>{if(e==null)throw new Mm(t)};var mr=e=>new Uint8Array(e),xs=e=>Array.from(e);var ud=({a:e,b:t})=>e.length===t.length&&e.every((r,n)=>r===t[n]);var ld="abcdefghijklmnopqrstuvwxyz234567",ti=Object.create(null);for(let e=0;e<ld.length;e++)ti[ld[e]]=e;ti[0]=ti.o;ti[1]=ti.i;var kr=e=>btoa(String.fromCharCode(...new Uint8Array(e))),dd=e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0)),fb=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 cc="__bigint__",lc="__principal__",uc="__uint8array__",pd=(e,t)=>typeof t=="bigint"?{[cc]:`${t}`}:z(t)&&k.isPrincipal(t)?{[lc]:k.from(t).toText()}:z(t)&&t instanceof Uint8Array?{[uc]:Array.from(t)}:t,fd=(e,t)=>{let r=n=>t[n];return z(t)&&typeof t=="object"&&cc in t?BigInt(r(cc)):z(t)&&typeof t=="object"&&lc in t?k.fromText(r(lc)):z(t)&&typeof t=="object"&&uc in t?Uint8Array.from(r(uc)):t};var ie=e=>z(e)?[e]:[],be=e=>e?.[0];var jm=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let t=e.slice(37,53),r=Km({bytes:t});return"aaguid"in r?{aaguidBytes:t,aaguidText:r.aaguid}:{unknownProvider:null}},Km=({bytes:e})=>{if(e.length!==16)return{invalidBytes:null};let t=(e instanceof Uint8Array?xs(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 Hm(e){let t=new DataView(new ArrayBuffer(2)),r=e.slice(53,55);[...new Uint8Array(r)].forEach((o,i)=>t.setUint8(i,o));let n=t.getUint16(0);return e.slice(55+n)}function $m(e){return Vn(e,ei)}var Gm=class{constructor(e){this._cose=e,this.#e=$m(e)}#e;toDer(){return this.#e}toRaw(){return new Uint8Array(this.#e)}},gd=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 kr(this.#e)}},Jm=class extends gd{#e;#t;constructor({authData:e,...t}){super(t);let r=jm({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}},Wm=class extends gd{},zm=class extends Error{},Ym=class extends Error{},Zm=class extends Error{},Xm=class extends Error{},Qm=class extends Error{},e_=class extends Error{},t_=class extends Error{},hd=class extends Error{};var r_={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},n_=6e4,xd=()=>window.crypto.getRandomValues(new Uint8Array(16)),o_=()=>xd(),i_=()=>xd(),s_=()=>{let{location:{href:e}}=window;try{let{hostname:t}=new URL(e);return t}catch{throw new zm}},bd=({appId:e})=>e?.id??s_(),a_=({appId:e,user:t}={})=>{let{document:{title:r}}=window,n=()=>({rp:{name:e?.name??r,id:bd({appId:e})}}),o=()=>({user:{id:i_(),name:t?.name??t?.displayName??r,displayName:t?.displayName??r}});return{attestation:"direct",challenge:o_(),...n(),...o(),pubKeyCredParams:Object.values(r_).map(i=>({type:"public-key",alg:i})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},c_=(e={})=>({rpId:bd(e),allowCredentials:[],userVerification:"required"}),dc=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}},Lr=(e=>(e[e.RequestingUserCredential=0]="RequestingUserCredential",e[e.FinalizingCredential=1]="FinalizingCredential",e[e.Signing=2]="Signing",e))(Lr||{}),wd=({timeout:e})=>AbortSignal.timeout(e??n_),l_=async({challenge:e,credentialIds:t,passkeyOptions:r,timeout:n})=>await navigator.credentials.get({publicKey:{...c_(r),challenge:e.buffer,allowCredentials:(t??[]).map(o=>({id:o.buffer,type:"public-key"}))},signal:wd({timeout:n})}),md=e=>{if(e.status!=="initialized")throw new Ym},_d=e=>{if(L(e))throw new Zm},yd=({type:e})=>{if(e!=="public-key")throw new Xm},pc=class oi extends Dt{#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=oi.#r({credential:new Jm(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:a_(t),signal:wd({timeout:r})});_d(o),yd(o);let{response:{attestationObject:i},rawId:s}=o;if(L(i))throw new Qm;let{authData:a}=zi.decode(mr(i)),c=Hm(a);return new oi({...n,rawId:mr(s),cose:c,authData:a})}static async createWithExistingCredential(t){return new oi(t)}getPublicKey(){md(this.#t);let{credential:t}=this.#t;return t.getPublicKey()}getCredential(){md(this.#t);let{credential:t}=this.#t;return t}async sign(t){let r=await dc({fn:async()=>{let n=await l_({challenge:t,...this.#t.status==="initialized"&&{credentialIds:[this.#t.credential.getCredentialId()]}});return _d(n),yd(n),n},step:0,onProgress:this.#e});return await dc({fn:async()=>{let{rawId:n}=r;if(this.#t.status==="initialized"){if(!ud({a:this.#t.credential.getCredentialId(),b:mr(n)}))throw new e_;return}let{retrievePublicKey:o}=this.#t,i=await o({credentialId:mr(n)});this.#t=oi.#r({credential:new Wm({rawId:mr(n),cose:i})})},step:1,onProgress:this.#e}),await dc({fn:async()=>{let{response:n}=r,{clientDataJSON:o}=n,{authenticatorData:i,signature:s}="authenticatorData"in n&&"signature"in n?n:{};if(L(i))throw new hd;if(L(s))throw new hd;let a=zi.encode({authenticator_data:i,client_data_json:new TextDecoder().decode(o),signature:mr(s)});if(L(a))throw new t_;return Object.assign(a,{__signature__:void 0}),a},step:2,onProgress:this.#e})}},u_=async()=>z(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;var co=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 De=class e extends co{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 ii=({message:e,detail:t})=>{let r=new CustomEvent(e,{detail:t,bubbles:!0});document.dispatchEvent(r)};var lo="http://127.0.0.1:5987",Td="rdmx6-jaaaa-aaaaa-aaadq-cai";var Nd=async({identity:e,container:t})=>{let n=z(t)&&t!==!1?t===!0?lo:t:"https://icp-api.io",o=z(t);return await hr.create({identity:e,shouldFetchRootKey:o,host:n})};var uo=class e{static instance;#e=void 0;constructor(){}static getInstance(){return L(e.instance)&&(e.instance=new e),e.instance}async getAgent({identity:t,...r}){let n=t.getPrincipal().toText();if(L(this.#e)||L(this.#e[n])){let o=await Nd({identity:t,...r});return this.#e={...this.#e??{},[n]:o},o}return this.#e[n]}reset(){this.#e=null}};var po=class e{static instance;#e=void 0;constructor(){}static getInstance(){return L(e.instance)&&(e.instance=new e),e.instance}async getActor({satelliteId:t,identity:r,actorKey:n,...o}){let i=`${n}#${r.getPrincipal().toText()}#${t};`;if(L(this.#e)||L(this.#e[i])){let s=await this.createActor({satelliteId:t,identity:r,...o});return this.#e={...this.#e??{},[i]:s},s}return this.#e[i]}reset(){this.#e=null}async createActor({idlFactory:t,satelliteId:r,...n}){let o=await uo.getInstance().getAgent(n);return so.createActor(t,{agent:o,canisterId:r})}};function Od(e){return e!==null&&typeof e=="object"}var si=class e{static from(t){if(typeof t=="string"){let r=Ee(t);return this.fromRaw(r)}else if(Od(t)){let r=t;if(Od(r)&&Object.hasOwnProperty.call(r,"__derEncodedPublicKey__"))return this.fromDer(r);if(ArrayBuffer.isView(r)){let n=r;return this.fromRaw(Ft(n.buffer))}else{if(r instanceof ArrayBuffer)return this.fromRaw(Ft(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=Vn(t,Fn);return r.__derEncodedPublicKey__=void 0,r}static derDecode(t){let r=Pn(t,Fn);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}},vt=class e extends Dt{static generate(t){if(t&&t.length!==32)throw new Error("Ed25519 Seed needs to be 32 bytes long.");t||(t=$e.utils.randomPrivateKey()),yl(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=$e.getPublicKey(r);return e.fromKeyPair(n,r)}static fromParsedJson(t){let[r,n]=t;return new e(si.fromDer(Ee(r)),Ee(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(si.fromRaw(t),r)}static fromSecretKey(t){let r=$e.getPublicKey(t);return e.fromKeyPair(r,t)}#e;#t;constructor(t,r){super(),this.#e=si.from(t),this.#t=r}toJSON(){return[j(this.#e.toDer()),j(this.#t)]}getKeyPair(){return{secretKey:this.#t,publicKey:this.#e}}getPublicKey(){return this.#e}async sign(t){let r=$e.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,i,s]=[t,r,n].map(a=>(typeof a=="string"&&(a=Ee(a)),Ft(a)));return $e.verify(o,i,s)}};var fc=class e extends Error{constructor(t){super(t),this.message=t,Object.setPrototypeOf(this,e.prototype)}};function Ed(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 fc("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 kt=class e extends Dt{static async generate(t){let{extractable:r=!1,keyUsages:n=["sign","verify"],subtleCrypto:o}=t??{},i=Ed(o),s=await i.generateKey({name:"ECDSA",namedCurve:"P-256"},r,n),a=Ft(await i.exportKey("spki",s.publicKey));return Object.assign(a,{__derEncodedPublicKey__:void 0}),new this(s,a,i)}static async fromKeyPair(t,r){let n=Ed(r),o=Ft(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=Ft(await this._subtleCrypto.sign(r,this._keyPair.privateKey,t));return Object.assign(n,{__signature__:void 0}),n}};var bs=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 ws(e){return e instanceof Uint8Array?j(e):j(new Uint8Array(e))}function hc(e){if(typeof e!="string"||e.length<64)throw new Error("Invalid public key.");return Ee(e)}var qr=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:ws(this.pubkey),...this.targets&&{targets:this.targets.map(t=>t.toHex())}}}};async function d_(e,t,r,n){let o=new qr(t.toDer(),BigInt(+r)*BigInt(1e6),n),i=new Uint8Array([...da,...new Uint8Array(rr({...o}))]),s=await e.sign(i);return{delegation:o,signature:s}}var _r=class e{static async create(t,r,n=new Date(Date.now()+900*1e3),o={}){let i=await d_(t,r,n,o.targets);return new e([...o.previous?.delegations||[],i],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(i=>{let{delegation:s,signature:a}=i,{pubkey:c,expiration:u,targets:p}=s;if(p!==void 0&&!Array.isArray(p))throw new Error("Invalid targets.");return{delegation:new qr(hc(c),BigInt("0x"+u),p&&p.map(d=>{if(typeof d!="string")throw new Error("Invalid target.");return k.fromHex(d)})),signature:hc(a)}});return new this(o,hc(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:ws(r.pubkey),...o&&{targets:o.map(i=>i.toHex())}},signature:ws(n)}}),publicKey:ws(this.publicKey)}}},yr=class extends Dt{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 rr(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}}}},ai=class e extends bs{#e;get delegation(){return this.#e}constructor(t,r){super(t),this.#e=r}static fromDelegation(t,r){return new e(t,r)}};function mc(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 i=o.toText();for(let{delegation:s}of e.delegations){if(s.targets===void 0)continue;let a=!0;for(let c of s.targets)if(c.toText()===i){a=!1;break}if(a)return!1}}return!0}var Rd=["mousedown","mousemove","keydown","touchstart","wheel"],ci=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),Rd.forEach(s=>{document.addEventListener(s,o,!0)});let i=(s,a)=>{let c;return(...u)=>{let p=this,d=()=>{c=void 0,s.apply(p,u)};clearTimeout(c),c=window.setTimeout(d,a)}};if(t?.captureScroll){let s=i(o,t?.scrollDebounce??100);window.addEventListener("scroll",s,!0)}o()}registerCallback(t){this.callbacks.push(t)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let t=this._resetTimer.bind(this);Rd.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 p_=(e,t)=>t.some(r=>e instanceof r),Id,vd;function f_(){return Id||(Id=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function h_(){return vd||(vd=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Ad=new WeakMap,yc=new WeakMap,Sd=new WeakMap,_c=new WeakMap,xc=new WeakMap;function m_(e){let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{r(Lt(e.result)),o()},s=()=>{n(e.error),o()};e.addEventListener("success",i),e.addEventListener("error",s)});return t.then(r=>{r instanceof IDBCursor&&Ad.set(r,e)}).catch(()=>{}),xc.set(t,e),t}function __(e){if(yc.has(e))return;let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{r(),o()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)});yc.set(e,t)}var gc={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return yc.get(e);if(t==="objectStoreNames")return e.objectStoreNames||Sd.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Lt(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 Cd(e){gc=e(gc)}function y_(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let n=e.call(Ts(this),t,...r);return Sd.set(n,t.sort?t.sort():[t]),Lt(n)}:h_().includes(e)?function(...t){return e.apply(Ts(this),t),Lt(Ad.get(this))}:function(...t){return Lt(e.apply(Ts(this),t))}}function g_(e){return typeof e=="function"?y_(e):(e instanceof IDBTransaction&&__(e),p_(e,f_())?new Proxy(e,gc):e)}function Lt(e){if(e instanceof IDBRequest)return m_(e);if(_c.has(e))return _c.get(e);let t=g_(e);return t!==e&&(_c.set(e,t),xc.set(t,e)),t}var Ts=e=>xc.get(e);function Vd(e,t,{blocked:r,upgrade:n,blocking:o,terminated:i}={}){let s=indexedDB.open(e,t),a=Lt(s);return n&&s.addEventListener("upgradeneeded",c=>{n(Lt(s.result),c.oldVersion,c.newVersion,Lt(s.transaction),c)}),r&&s.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),a.then(c=>{i&&c.addEventListener("close",()=>i()),o&&c.addEventListener("versionchange",u=>o(u.oldVersion,u.newVersion,u))}).catch(()=>{}),a}var x_=["get","getKey","getAll","getAllKeys","count"],b_=["put","add","delete","clear"],bc=new Map;function Fd(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(bc.get(t))return bc.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,o=b_.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||x_.includes(r)))return;let i=async function(s,...a){let c=this.transaction(s,o?"readwrite":"readonly"),u=c.store;return n&&(u=u.index(a.shift())),(await Promise.all([u[r](...a),o&&c.done]))[0]};return bc.set(t,i),i}Cd(e=>({...e,get:(t,r,n)=>Fd(t,r)||e.get(t,r,n),has:(t,r)=>!!Fd(t,r)||e.has(t,r)}));var Pd="auth-client-db",Bd="ic-keyval",w_=async(e=Pd,t=Bd,r)=>(globalThis.localStorage?.getItem(Ge)&&(globalThis.localStorage.removeItem(Ge),globalThis.localStorage.removeItem(Je)),await Vd(e,r,{upgrade:n=>{n.objectStoreNames.contains(t)&&n.clear(t),n.createObjectStore(t)}}));async function T_(e,t,r){return await e.get(t,r)}async function N_(e,t,r,n){return await e.put(t,n,r)}async function O_(e,t,r){return await e.delete(t,r)}var Ns=class e{constructor(t,r){this._db=t,this._storeName=r}static async create(t){let{dbName:r=Pd,storeName:n=Bd,version:o=Dd}=t??{},i=await w_(r,n,o);return new e(i,n)}async set(t,r){return await N_(this._db,this._storeName,t,r)}async get(t){return await T_(this._db,this._storeName,t)??null}async remove(t){return await O_(this._db,this._storeName,t)}};var Je="identity",Ge="delegation",Ud="iv",Dd=1,li=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}},qt=class{#e;constructor(t){this.#e=t??{}}initializedDb;get _db(){return new Promise((t,r)=>{if(this.initializedDb){t(this.initializedDb);return}Ns.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 E_=BigInt(1e9),R_=BigInt(3600),I_=E_*R_,v_="https://identity.internetcomputer.org",A_="#authorize",S_=BigInt(8)*I_,wc="ECDSA",Tc="Ed25519",C_=500,Os="UserInterrupt",ui=class e{constructor(t,r,n,o,i,s,a,c){this._identity=t,this._key=r,this._chain=n,this._storage=o,this.idleManager=i,this._createOptions=s,this._idpWindow=a,this._eventHandler=c,this._registerDefaultIdleCallback()}static async create(t={}){let r=t.storage??new qt,n=t.keyType??wc,o=null;if(t.identity)o=t.identity;else{let c=await r.get(Je);if(!c)try{let u=new li,p=await u.get(Ge),d=await u.get(Je);p&&d&&n===wc&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await r.set(Ge,p),await r.set(Je,d),c=p,await u.remove(Ge),await u.remove(Je))}catch(u){console.error(`error while attempting to recover localstorage: ${u}`)}if(c)try{typeof c=="object"?n===Tc&&typeof c=="string"?o=vt.fromJSON(c):o=await kt.fromKeyPair(c):typeof c=="string"&&(o=vt.fromJSON(c))}catch{}}let i=new tt,s=null;if(o)try{let c=await r.get(Ge);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?i=t.identity:c&&(s=_r.fromJSON(c),mc(s)?"toDer"in o?i=ai.fromDelegation(o,s):i=yr.fromDelegation(o,s):(await Nc(r),o=null))}catch(c){console.error(c),await Nc(r),o=null}let a;return t.idleOptions?.disableIdle?a=void 0:(s||t.identity)&&(a=ci.create(t.idleOptions)),o||(n===Tc?o=vt.generate():(t.storage&&n===wc&&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 '${Tc}' as the key type, as it can serialize to a string`),o=await kt.generate()),await kd(r,o)),new e(i,o,s,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 qr(a.delegation.pubkey,a.delegation.expiration,a.delegation.targets),signature:a.signature})),o=_r.fromDelegations(n,t.userPublicKey),i=this._key;if(!i)return;this._chain=o,"toDer"in i?this._identity=ai.fromDelegation(i,this._chain):this._identity=yr.fromDelegation(i,this._chain),this._idpWindow?.close();let s=this._createOptions?.idleOptions;!this.idleManager&&!s?.disableIdle&&(this.idleManager=ci.create(s),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(Ge,JSON.stringify(this._chain.toJSON())),await kd(this._storage,this._key),r?.(t)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null&&mc(this._chain)}async login(t){let r=F_(this._createOptions?.loginOptions,t),n=r?.maxTimeToLive??S_,o=new URL(r?.identityProvider?.toString()||v_);o.hash=A_,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 i=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(Os,r?.onError):setTimeout(i,C_))};i()}_getEventHandler(t,r){return async n=>{if(n.origin!==t.origin)return;let o=n.data;switch(o.kind){case"authorize-ready":{let i={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(i,t.origin);break}case"authorize-client-success":try{await this._handleSuccess(o,r?.onSuccess)}catch(i){this._handleFailure(i.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 Nc(this._storage),this._identity=new tt,this._chain=null,t.returnTo)try{window.history.pushState({},"",t.returnTo)}catch{window.location.href=t.returnTo}}};async function Nc(e){await e.remove(Je),await e.remove(Ge),await e.remove(Ud)}function F_(e,t){if(!e&&!t)return;let r=e?.customValues||t?.customValues?{...e?.customValues,...t?.customValues}:void 0;return{...e,...t,customValues:r}}function V_(e){if(e instanceof kt)return e.getKeyPair();if(e instanceof vt)return JSON.stringify(e.toJSON());throw new Error("Unsupported key type")}async function kd(e,t){let r=V_(t);await e.set(Je,r)}var Ue=class e{static#e;#t;constructor(){}static getInstance(){return L(this.#e)&&(this.#e=new e),this.#e}createAuthClient=async()=>(this.#t=await ui.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}}),this.#t);safeCreateAuthClient=async()=>(await new qt().remove(Je),await this.createAuthClient());getAuthClient=()=>this.#t;logout=async()=>{await this.#t?.logout(),this.#t=null};setAuthClientStorage=async({delegationChain:t,sessionKey:r})=>{let n=new qt;await Promise.all([n.set(Je,r.getKeyPair()),n.set(Ge,JSON.stringify(t.toJSON()))])}};var Oc=async e=>{await P_(),await Ue.getInstance().createAuthClient(),e?.windowReload!==!1&&window.location.reload()},P_=async()=>{await Ue.getInstance().logout(),De.getInstance().reset(),po.getInstance().reset(),uo.getInstance().reset()};var Ld=e=>{let t=e===!0?"./workers/auth.worker.js":e,r=new Worker(t),n=async()=>{ii({message:"junoSignOutAuthTimer"}),await Oc()};return r.onmessage=async({data:o})=>{let{msg:i,data:s}=o;switch(i){case"junoSignOutAuthTimer":await n();return;case"junoDelegationRemainingTime":ii({message:"junoDelegationRemainingTime",detail:s?.authRemainingTime})}},De.getInstance().subscribe(o=>{if(L(o)){r.postMessage({msg:"junoStopAuthTimer"});return}r.postMessage({msg:"junoStartAuthTimer"})})};var fo=class e{static#e;#t;#r;static CHANNEL_NAME="juno_core_auth_channel";static MESSAGE_LOGIN_SUCCESS="authClientLoginSuccess";constructor(){this.#t=new BroadcastChannel(e.CHANNEL_NAME),this.#r=window.crypto.randomUUID()}static getInstance(){return L(this.#e)&&(this.#e=new e),this.#e}onLoginSuccess=t=>{let{location:{origin:r}}=window;this.#t.onmessage=async({origin:n,data:o})=>{n===r&&z(o)&&o.msg==="authClientLoginSuccess"&&ri(o.emitterId)&&o.emitterId!==this.#r&&await t()}};destroy=()=>{this.#t.close(),e.#e=null};postLoginSuccess=()=>{let t={emitterId:this.#r,msg:e.MESSAGE_LOGIN_SUCCESS};this.#t.postMessage(t)};get __test__only__emitter_id__(){return this.#r}};var Se=class e extends co{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 di=async({fn:e,syncTabsOnSuccess:t})=>{let{authenticated:r}=await B_({fn:e});!r||!t||Se.getInstance().get()?.syncTabs===!1||D_()},qd=async({fn:e})=>{let{createAuthClient:t}=Ue.getInstance(),n=await(await t()).isAuthenticated();await e({authenticated:n})},B_=async({fn:e})=>{let{createAuthClient:t,safeCreateAuthClient:r}=Ue.getInstance();return await(await t()).isAuthenticated()?(await e(),{authenticated:!0}):(await r(),{authenticated:!1})},D_=()=>{try{fo.getInstance().postLoginSuccess()}catch(e){console.warn("Auth BroadcastChannel posting failed",e)}};var Ec=({error:e,type:t})=>typeof e=="string"?e.includes(t):e instanceof Error?e.message.includes(t):!1;var Md="juno.datastore.error.user.cannot_update";var Mt={certified:!1};var Es=()=>Ue.getInstance().getAuthClient()?.getIdentity(),U_=async()=>{let{getAuthClient:e,createAuthClient:t}=Ue.getInstance();return(e()??await t()).getIdentity()},k_=async()=>{let e=De.getInstance().get();if(L(e))return null;let t=Ue.getInstance().getAuthClient();return await t?.isAuthenticated()??!1?t?.getIdentity()??null:null};var ue=e=>z(e)?e:Es()??new tt;var Rc=({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({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),i=e.Variant({OpenId:o}),s=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)}),a=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),c=e.Record({doc:s,delegation:a}),u=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),p=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),d=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),l=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text}),f=e.Variant({PrepareDelegation:l,RegisterUser:e.Text}),h=e.Variant({Ok:c,Err:f}),_=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),g=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),m=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),x=e.Record({field:m,desc:e.Bool}),y=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),T=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(y),description:e.Opt(e.Text),created_at:e.Opt(y)}),E=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),O=e.Record({order:e.Opt(x),owner:e.Opt(e.Principal),matcher:e.Opt(T),paginate:e.Opt(E)}),R=e.Record({controllers:e.Vec(e.Principal)}),v=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),w=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:v,expires_at:e.Opt(e.Nat64)}),I=e.Record({version:e.Opt(e.Nat64)}),F=e.Variant({Db:e.Null,Storage:e.Null}),S=e.Record({version:e.Opt(e.Nat64)}),b=e.Record({proposal_ids:e.Vec(e.Nat)}),N=e.Record({cycles:e.Nat,destination_id:e.Principal}),C=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}),B=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),q=e.Record({key:C,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,B)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),A=e.Variant({Google:e.Null}),V=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),P=e.Record({delegation:e.Opt(V),client_id:e.Text}),D=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(A,P))}),U=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),re=e.Record({allowed_callers:e.Vec(e.Principal)}),ee=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(D),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(U),rules:e.Opt(re)}),J=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),se=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(J)}),he=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),Fe=e.Variant({Deny:e.Null,Allow:e.Null}),ne=e.Record({status_code:e.Nat16,location:e.Text}),de=e.Record({iframe:e.Opt(he),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(J),raw_access:e.Opt(Fe),redirects:e.Opt(e.Vec(e.Tuple(e.Text,ne)))}),jr=e.Record({db:e.Opt(se),authentication:e.Opt(ee),storage:de}),Kt=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),Ye=e.Variant({OpenId:Kt}),Kr=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),Hr=e.Record({signature:e.Vec(e.Nat8),delegation:Kr}),dt=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text}),$r=e.Variant({Ok:Hr,Err:dt}),Gr=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),Jr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),Ht=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),pt=e.Variant({AssetsUpgrade:Jr,SegmentsDeployment:Ht}),Ze=e.Record({status:Gr,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:pt}),Xe=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),ft=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),ht=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:Xe,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(ft),write:Xe,max_changes_per_user:e.Opt(e.Nat32)}),Wr=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)}),mt=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}),zr=e.Variant({Callback:e.Record({token:mt,callback:e.Func([],[],["query"])})}),Yr=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(zr),status_code:e.Nat16}),Zr=e.Record({token:e.Opt(mt),body:e.Vec(e.Nat8)}),_t=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}),Qe=e.Record({batch_id:e.Nat}),Xr=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,q)),items_length:e.Nat64}),Qr=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),en=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,s)),items_length:e.Nat64}),tn=e.Record({desc:e.Bool}),rn=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),nn=e.Record({order:e.Opt(tn),paginate:e.Opt(rn)}),on=e.Record({proposal_id:e.Nat}),sn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(on,Ze)),items_length:e.Nat64}),an=e.Record({include_system:e.Bool}),cn=e.Record({matcher:e.Opt(an)}),ln=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,ht)),items_length:e.Nat64}),un=e.Record({stable:e.Nat64,heap:e.Nat64}),$t=e.Record({openid:e.Opt(D),version:e.Opt(e.Nat64),internet_identity:e.Opt(U),rules:e.Opt(re)}),dn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:v,expires_at:e.Opt(e.Nat64)}),pn=e.Record({controller:dn,controllers:e.Vec(e.Principal)}),fn=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(J)}),Gt=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Hs=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),max_size:e.Opt(e.Nat),read:Xe,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(ft),write:Xe,max_changes_per_user:e.Opt(e.Nat32)}),$s=e.Record({iframe:e.Opt(he),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(J),raw_access:e.Opt(Fe),redirects:e.Opt(e.Vec(e.Tuple(e.Text,ne)))}),mo=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),_o=e.Record({chunk_id:e.Nat});return e.Service({authenticate:e.Func([i],[h],[]),commit_asset_upload:e.Func([_],[],[]),commit_proposal:e.Func([g],[e.Null],[]),commit_proposal_asset_upload:e.Func([_],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(_)],[],[]),count_assets:e.Func([e.Text,O],[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,O],[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([R],[e.Vec(e.Tuple(e.Principal,w))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,I],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,O],[],[]),del_filtered_docs:e.Func([e.Text,O],[],[]),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,I))],[],[]),del_rule:e.Func([F,e.Text,S],[],[]),delete_proposal_assets:e.Func([b],[],[]),deposit_cycles:e.Func([N],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(q)],["query"]),get_auth_config:e.Func([],[e.Opt(ee)],["query"]),get_config:e.Func([],[jr],[]),get_db_config:e.Func([],[e.Opt(se)],["query"]),get_delegation:e.Func([Ye],[$r],["query"]),get_doc:e.Func([e.Text,e.Text],[e.Opt(s)],["query"]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(q)))],["query"]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(s)))],["query"]),get_proposal:e.Func([e.Nat],[e.Opt(Ze)],["query"]),get_rule:e.Func([F,e.Text],[e.Opt(ht)],["query"]),get_storage_config:e.Func([],[de],["query"]),http_request:e.Func([Wr],[Yr],["query"]),http_request_streaming_callback:e.Func([mt],[Zr],["query"]),init_asset_upload:e.Func([_t],[Qe],[]),init_proposal:e.Func([pt],[e.Nat,Ze],[]),init_proposal_asset_upload:e.Func([_t,e.Nat],[Qe],[]),init_proposal_many_assets_upload:e.Func([e.Vec(_t),e.Nat],[e.Vec(e.Tuple(e.Text,Qe))],[]),list_assets:e.Func([e.Text,O],[Xr],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,w))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,Qr))],["query"]),list_docs:e.Func([e.Text,O],[en],["query"]),list_proposals:e.Func([nn],[sn],["query"]),list_rules:e.Func([F,cn],[ln],["query"]),memory_size:e.Func([],[un],["query"]),reject_proposal:e.Func([g],[e.Null],[]),set_asset_token:e.Func([e.Text,e.Text,e.Opt(e.Text)],[],[]),set_auth_config:e.Func([$t],[ee],[]),set_controllers:e.Func([pn],[e.Vec(e.Tuple(e.Principal,w))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([fn],[se],[]),set_doc:e.Func([e.Text,e.Text,Gt],[s],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Gt))],[e.Vec(e.Tuple(e.Text,s))],[]),set_rule:e.Func([F,e.Text,Hs],[ht],[]),set_storage_config:e.Func([$s],[de],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Ze],[]),switch_storage_system_memory:e.Func([],[],[]),upload_asset_chunk:e.Func([mo],[_o],[]),upload_proposal_asset_chunk:e.Func([mo],[_o],[])})},Ic=({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({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),i=e.Variant({OpenId:o}),s=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)}),a=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),c=e.Record({doc:s,delegation:a}),u=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),p=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),d=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),l=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text}),f=e.Variant({PrepareDelegation:l,RegisterUser:e.Text}),h=e.Variant({Ok:c,Err:f}),_=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),g=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),m=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),x=e.Record({field:m,desc:e.Bool}),y=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),T=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(y),description:e.Opt(e.Text),created_at:e.Opt(y)}),E=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),O=e.Record({order:e.Opt(x),owner:e.Opt(e.Principal),matcher:e.Opt(T),paginate:e.Opt(E)}),R=e.Record({controllers:e.Vec(e.Principal)}),v=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),w=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:v,expires_at:e.Opt(e.Nat64)}),I=e.Record({version:e.Opt(e.Nat64)}),F=e.Variant({Db:e.Null,Storage:e.Null}),S=e.Record({version:e.Opt(e.Nat64)}),b=e.Record({proposal_ids:e.Vec(e.Nat)}),N=e.Record({cycles:e.Nat,destination_id:e.Principal}),C=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}),B=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),q=e.Record({key:C,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,B)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),A=e.Variant({Google:e.Null}),V=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),P=e.Record({delegation:e.Opt(V),client_id:e.Text}),D=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(A,P))}),U=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),re=e.Record({allowed_callers:e.Vec(e.Principal)}),ee=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(D),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(U),rules:e.Opt(re)}),J=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),se=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(J)}),he=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),Fe=e.Variant({Deny:e.Null,Allow:e.Null}),ne=e.Record({status_code:e.Nat16,location:e.Text}),de=e.Record({iframe:e.Opt(he),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(J),raw_access:e.Opt(Fe),redirects:e.Opt(e.Vec(e.Tuple(e.Text,ne)))}),jr=e.Record({db:e.Opt(se),authentication:e.Opt(ee),storage:de}),Kt=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),Ye=e.Variant({OpenId:Kt}),Kr=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),Hr=e.Record({signature:e.Vec(e.Nat8),delegation:Kr}),dt=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text}),$r=e.Variant({Ok:Hr,Err:dt}),Gr=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),Jr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),Ht=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),pt=e.Variant({AssetsUpgrade:Jr,SegmentsDeployment:Ht}),Ze=e.Record({status:Gr,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:pt}),Xe=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),ft=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),ht=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:Xe,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(ft),write:Xe,max_changes_per_user:e.Opt(e.Nat32)}),Wr=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)}),mt=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}),zr=e.Variant({Callback:e.Record({token:mt,callback:e.Func([],[],[])})}),Yr=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(zr),status_code:e.Nat16}),Zr=e.Record({token:e.Opt(mt),body:e.Vec(e.Nat8)}),_t=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}),Qe=e.Record({batch_id:e.Nat}),Xr=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,q)),items_length:e.Nat64}),Qr=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),en=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,s)),items_length:e.Nat64}),tn=e.Record({desc:e.Bool}),rn=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),nn=e.Record({order:e.Opt(tn),paginate:e.Opt(rn)}),on=e.Record({proposal_id:e.Nat}),sn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(on,Ze)),items_length:e.Nat64}),an=e.Record({include_system:e.Bool}),cn=e.Record({matcher:e.Opt(an)}),ln=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,ht)),items_length:e.Nat64}),un=e.Record({stable:e.Nat64,heap:e.Nat64}),$t=e.Record({openid:e.Opt(D),version:e.Opt(e.Nat64),internet_identity:e.Opt(U),rules:e.Opt(re)}),dn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:v,expires_at:e.Opt(e.Nat64)}),pn=e.Record({controller:dn,controllers:e.Vec(e.Principal)}),fn=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(J)}),Gt=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Hs=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),max_size:e.Opt(e.Nat),read:Xe,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(ft),write:Xe,max_changes_per_user:e.Opt(e.Nat32)}),$s=e.Record({iframe:e.Opt(he),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(J),raw_access:e.Opt(Fe),redirects:e.Opt(e.Vec(e.Tuple(e.Text,ne)))}),mo=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),_o=e.Record({chunk_id:e.Nat});return e.Service({authenticate:e.Func([i],[h],[]),commit_asset_upload:e.Func([_],[],[]),commit_proposal:e.Func([g],[e.Null],[]),commit_proposal_asset_upload:e.Func([_],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(_)],[],[]),count_assets:e.Func([e.Text,O],[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,O],[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([R],[e.Vec(e.Tuple(e.Principal,w))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,I],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,O],[],[]),del_filtered_docs:e.Func([e.Text,O],[],[]),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,I))],[],[]),del_rule:e.Func([F,e.Text,S],[],[]),delete_proposal_assets:e.Func([b],[],[]),deposit_cycles:e.Func([N],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(q)],[]),get_auth_config:e.Func([],[e.Opt(ee)],[]),get_config:e.Func([],[jr],[]),get_db_config:e.Func([],[e.Opt(se)],[]),get_delegation:e.Func([Ye],[$r],[]),get_doc:e.Func([e.Text,e.Text],[e.Opt(s)],[]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(q)))],[]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(s)))],[]),get_proposal:e.Func([e.Nat],[e.Opt(Ze)],[]),get_rule:e.Func([F,e.Text],[e.Opt(ht)],[]),get_storage_config:e.Func([],[de],[]),http_request:e.Func([Wr],[Yr],[]),http_request_streaming_callback:e.Func([mt],[Zr],[]),init_asset_upload:e.Func([_t],[Qe],[]),init_proposal:e.Func([pt],[e.Nat,Ze],[]),init_proposal_asset_upload:e.Func([_t,e.Nat],[Qe],[]),init_proposal_many_assets_upload:e.Func([e.Vec(_t),e.Nat],[e.Vec(e.Tuple(e.Text,Qe))],[]),list_assets:e.Func([e.Text,O],[Xr],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,w))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,Qr))],[]),list_docs:e.Func([e.Text,O],[en],[]),list_proposals:e.Func([nn],[sn],[]),list_rules:e.Func([F,cn],[ln],[]),memory_size:e.Func([],[un],[]),reject_proposal:e.Func([g],[e.Null],[]),set_asset_token:e.Func([e.Text,e.Text,e.Opt(e.Text)],[],[]),set_auth_config:e.Func([$t],[ee],[]),set_controllers:e.Func([pn],[e.Vec(e.Tuple(e.Principal,w))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([fn],[se],[]),set_doc:e.Func([e.Text,e.Text,Gt],[s],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Gt))],[e.Vec(e.Tuple(e.Text,s))],[]),set_rule:e.Func([F,e.Text,Hs],[ht],[]),set_storage_config:e.Func([$s],[de],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Ze],[]),switch_storage_system_memory:e.Func([],[],[]),upload_asset_chunk:e.Func([mo],[_o],[]),upload_proposal_asset_chunk:e.Func([mo],[_o],[])})},L_=({IDL:e})=>{let t=e.Record({e8s:e.Nat64}),r=e.Record({mission_control_id:e.Principal,user:e.Principal}),n=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),o=e.Variant({OpenId:n}),i=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),s=e.Variant({Google:e.Null}),a=e.Record({name:e.Opt(e.Text),locale:e.Opt(e.Text),family_name:e.Opt(e.Text),email:e.Opt(e.Text),picture:e.Opt(e.Text),given_name:e.Opt(e.Text)}),c=e.Record({provider:s,data:a}),u=e.Variant({InternetIdentity:e.Null,OpenId:c}),p=e.Record({updated_at:e.Nat64,credits:t,mission_control_id:e.Opt(e.Principal),provider:e.Opt(u),owner:e.Principal,created_at:e.Nat64}),d=e.Record({delegation:i,account:p}),l=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),f=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),h=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),_=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text}),g=e.Variant({PrepareDelegation:_,RegisterUser:e.Text}),m=e.Variant({Ok:d,Err:g}),x=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),y=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),T=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),user:e.Principal}),E=e.Variant({Heap:e.Null,Stable:e.Null}),O=e.Record({system_memory:e.Opt(E)}),R=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),storage:e.Opt(O),user:e.Principal}),v=e.Record({controllers:e.Vec(e.Principal)}),w=e.Record({proposal_ids:e.Vec(e.Nat)}),I=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),F=e.Record({delegation:e.Opt(I),client_id:e.Text}),S=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(s,F))}),b=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),N=e.Record({allowed_callers:e.Vec(e.Principal)}),C=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(S),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(b),rules:e.Opt(N)}),B=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),q=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),A=e.Variant({Deny:e.Null,Allow:e.Null}),V=e.Record({status_code:e.Nat16,location:e.Text}),P=e.Record({iframe:e.Opt(B),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(q),raw_access:e.Opt(A),redirects:e.Opt(e.Vec(e.Tuple(e.Text,V)))}),D=e.Record({authentication:e.Opt(C),storage:P}),U=e.Record({user:e.Principal}),re=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),ee=e.Variant({OpenId:re}),J=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),se=e.Record({signature:e.Vec(e.Nat8),delegation:J}),he=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text}),Fe=e.Variant({Ok:se,Err:he}),ne=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),de=e.Record({clear_existing_assets:e.Opt(e.Bool)}),jr=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),Kt=e.Variant({AssetsUpgrade:de,SegmentsDeployment:jr}),Ye=e.Record({status:ne,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:Kt}),Kr=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)}),Hr=e.Variant({Heap:e.Null,Stable:e.Null}),dt=e.Record({memory:Hr,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}),$r=e.Variant({Callback:e.Record({token:dt,callback:e.Func([],[],["query"])})}),Gr=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt($r),status_code:e.Nat16}),Jr=e.Record({token:e.Opt(dt),body:e.Vec(e.Nat8)}),Ht=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}),pt=e.Record({batch_id:e.Nat}),Ze=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),Xe=e.Record({field:Ze,desc:e.Bool}),ft=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),ht=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(ft),description:e.Opt(e.Text),created_at:e.Opt(ft)}),Wr=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),mt=e.Record({order:e.Opt(Xe),owner:e.Opt(e.Principal),matcher:e.Opt(ht),paginate:e.Opt(Wr)}),zr=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}),Yr=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),Zr=e.Record({key:zr,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,Yr)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),_t=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,Zr)),items_length:e.Nat64}),Qe=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),Xr=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:Qe,expires_at:e.Opt(e.Nat64)}),Qr=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),en=e.Variant({Refunded:e.Null,Acknowledged:e.Null,Completed:e.Null}),tn=e.Record({status:en,updated_at:e.Nat64,block_index_payment:e.Nat64,mission_control_id:e.Opt(e.Principal),created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64)}),rn=e.Record({desc:e.Bool}),nn=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),on=e.Record({order:e.Opt(rn),paginate:e.Opt(nn)}),sn=e.Record({proposal_id:e.Nat}),an=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(sn,Ye)),items_length:e.Nat64}),cn=e.Record({openid:e.Opt(S),version:e.Opt(e.Nat64),internet_identity:e.Opt(b),rules:e.Opt(N)}),ln=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:Qe,expires_at:e.Opt(e.Nat64)}),un=e.Record({controller:ln,controllers:e.Vec(e.Principal)}),$t=e.Variant({Orbiter:e.Null,MissionControl:e.Null,Satellite:e.Null}),dn=e.Record({iframe:e.Opt(B),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(q),raw_access:e.Opt(A),redirects:e.Opt(e.Vec(e.Tuple(e.Text,V)))}),pn=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),fn=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Gt=e.Record({chunk_id:e.Nat});return e.Service({add_credits:e.Func([e.Principal,t],[],[]),add_invitation_code:e.Func([e.Text],[],[]),assert_mission_control_center:e.Func([r],[],["query"]),authenticate:e.Func([o],[m],[]),commit_proposal:e.Func([x],[e.Null],[]),commit_proposal_asset_upload:e.Func([y],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(y)],[],[]),count_proposals:e.Func([],[e.Nat64],["query"]),create_orbiter:e.Func([T],[e.Principal],[]),create_satellite:e.Func([R],[e.Principal],[]),del_controllers:e.Func([v],[],[]),del_custom_domain:e.Func([e.Text],[],[]),delete_proposal_assets:e.Func([w],[],[]),get_account:e.Func([],[e.Opt(p)],["query"]),get_auth_config:e.Func([],[e.Opt(C)],["query"]),get_config:e.Func([],[D],["query"]),get_create_orbiter_fee:e.Func([U],[e.Opt(t)],["query"]),get_create_satellite_fee:e.Func([U],[e.Opt(t)],["query"]),get_credits:e.Func([],[t],["query"]),get_delegation:e.Func([ee],[Fe],["query"]),get_proposal:e.Func([e.Nat],[e.Opt(Ye)],["query"]),get_storage_config:e.Func([],[P],["query"]),http_request:e.Func([Kr],[Gr],["query"]),http_request_streaming_callback:e.Func([dt],[Jr],["query"]),init_proposal:e.Func([Kt],[e.Nat,Ye],[]),init_proposal_asset_upload:e.Func([Ht,e.Nat],[pt],[]),init_proposal_many_assets_upload:e.Func([e.Vec(Ht),e.Nat],[e.Vec(e.Tuple(e.Text,pt))],[]),init_user_mission_control_center:e.Func([],[p],[]),list_accounts:e.Func([],[e.Vec(e.Tuple(e.Principal,p))],["query"]),list_assets:e.Func([e.Text,mt],[_t],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,Xr))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,Qr))],["query"]),list_payments:e.Func([],[e.Vec(e.Tuple(e.Nat64,tn))],["query"]),list_proposals:e.Func([on],[an],["query"]),reject_proposal:e.Func([x],[e.Null],[]),set_auth_config:e.Func([cn],[C],[]),set_controllers:e.Func([un],[],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_fee:e.Func([$t,t],[],[]),set_storage_config:e.Func([dn],[P],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Ye],[]),update_rate_config:e.Func([$t,pn],[],[]),upload_proposal_asset_chunk:e.Func([fn],[Gt],[])})},q_=({IDL:e})=>{let t=e.Record({e8s:e.Nat64}),r=e.Record({mission_control_id:e.Principal,user:e.Principal}),n=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),o=e.Variant({OpenId:n}),i=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),s=e.Variant({Google:e.Null}),a=e.Record({name:e.Opt(e.Text),locale:e.Opt(e.Text),family_name:e.Opt(e.Text),email:e.Opt(e.Text),picture:e.Opt(e.Text),given_name:e.Opt(e.Text)}),c=e.Record({provider:s,data:a}),u=e.Variant({InternetIdentity:e.Null,OpenId:c}),p=e.Record({updated_at:e.Nat64,credits:t,mission_control_id:e.Opt(e.Principal),provider:e.Opt(u),owner:e.Principal,created_at:e.Nat64}),d=e.Record({delegation:i,account:p}),l=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),f=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),h=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),_=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text}),g=e.Variant({PrepareDelegation:_,RegisterUser:e.Text}),m=e.Variant({Ok:d,Err:g}),x=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),y=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),T=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),user:e.Principal}),E=e.Variant({Heap:e.Null,Stable:e.Null}),O=e.Record({system_memory:e.Opt(E)}),R=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),storage:e.Opt(O),user:e.Principal}),v=e.Record({controllers:e.Vec(e.Principal)}),w=e.Record({proposal_ids:e.Vec(e.Nat)}),I=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),F=e.Record({delegation:e.Opt(I),client_id:e.Text}),S=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(s,F))}),b=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),N=e.Record({allowed_callers:e.Vec(e.Principal)}),C=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(S),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(b),rules:e.Opt(N)}),B=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),q=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),A=e.Variant({Deny:e.Null,Allow:e.Null}),V=e.Record({status_code:e.Nat16,location:e.Text}),P=e.Record({iframe:e.Opt(B),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(q),raw_access:e.Opt(A),redirects:e.Opt(e.Vec(e.Tuple(e.Text,V)))}),D=e.Record({authentication:e.Opt(C),storage:P}),U=e.Record({user:e.Principal}),re=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),ee=e.Variant({OpenId:re}),J=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),se=e.Record({signature:e.Vec(e.Nat8),delegation:J}),he=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text}),Fe=e.Variant({Ok:se,Err:he}),ne=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),de=e.Record({clear_existing_assets:e.Opt(e.Bool)}),jr=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),Kt=e.Variant({AssetsUpgrade:de,SegmentsDeployment:jr}),Ye=e.Record({status:ne,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:Kt}),Kr=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)}),Hr=e.Variant({Heap:e.Null,Stable:e.Null}),dt=e.Record({memory:Hr,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}),$r=e.Variant({Callback:e.Record({token:dt,callback:e.Func([],[],[])})}),Gr=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt($r),status_code:e.Nat16}),Jr=e.Record({token:e.Opt(dt),body:e.Vec(e.Nat8)}),Ht=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}),pt=e.Record({batch_id:e.Nat}),Ze=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),Xe=e.Record({field:Ze,desc:e.Bool}),ft=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),ht=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(ft),description:e.Opt(e.Text),created_at:e.Opt(ft)}),Wr=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),mt=e.Record({order:e.Opt(Xe),owner:e.Opt(e.Principal),matcher:e.Opt(ht),paginate:e.Opt(Wr)}),zr=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}),Yr=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),Zr=e.Record({key:zr,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,Yr)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),_t=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,Zr)),items_length:e.Nat64}),Qe=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),Xr=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:Qe,expires_at:e.Opt(e.Nat64)}),Qr=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),en=e.Variant({Refunded:e.Null,Acknowledged:e.Null,Completed:e.Null}),tn=e.Record({status:en,updated_at:e.Nat64,block_index_payment:e.Nat64,mission_control_id:e.Opt(e.Principal),created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64)}),rn=e.Record({desc:e.Bool}),nn=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),on=e.Record({order:e.Opt(rn),paginate:e.Opt(nn)}),sn=e.Record({proposal_id:e.Nat}),an=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(sn,Ye)),items_length:e.Nat64}),cn=e.Record({openid:e.Opt(S),version:e.Opt(e.Nat64),internet_identity:e.Opt(b),rules:e.Opt(N)}),ln=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:Qe,expires_at:e.Opt(e.Nat64)}),un=e.Record({controller:ln,controllers:e.Vec(e.Principal)}),$t=e.Variant({Orbiter:e.Null,MissionControl:e.Null,Satellite:e.Null}),dn=e.Record({iframe:e.Opt(B),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(q),raw_access:e.Opt(A),redirects:e.Opt(e.Vec(e.Tuple(e.Text,V)))}),pn=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),fn=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Gt=e.Record({chunk_id:e.Nat});return e.Service({add_credits:e.Func([e.Principal,t],[],[]),add_invitation_code:e.Func([e.Text],[],[]),assert_mission_control_center:e.Func([r],[],[]),authenticate:e.Func([o],[m],[]),commit_proposal:e.Func([x],[e.Null],[]),commit_proposal_asset_upload:e.Func([y],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(y)],[],[]),count_proposals:e.Func([],[e.Nat64],[]),create_orbiter:e.Func([T],[e.Principal],[]),create_satellite:e.Func([R],[e.Principal],[]),del_controllers:e.Func([v],[],[]),del_custom_domain:e.Func([e.Text],[],[]),delete_proposal_assets:e.Func([w],[],[]),get_account:e.Func([],[e.Opt(p)],[]),get_auth_config:e.Func([],[e.Opt(C)],[]),get_config:e.Func([],[D],[]),get_create_orbiter_fee:e.Func([U],[e.Opt(t)],[]),get_create_satellite_fee:e.Func([U],[e.Opt(t)],[]),get_credits:e.Func([],[t],[]),get_delegation:e.Func([ee],[Fe],[]),get_proposal:e.Func([e.Nat],[e.Opt(Ye)],[]),get_storage_config:e.Func([],[P],[]),http_request:e.Func([Kr],[Gr],[]),http_request_streaming_callback:e.Func([dt],[Jr],[]),init_proposal:e.Func([Kt],[e.Nat,Ye],[]),init_proposal_asset_upload:e.Func([Ht,e.Nat],[pt],[]),init_proposal_many_assets_upload:e.Func([e.Vec(Ht),e.Nat],[e.Vec(e.Tuple(e.Text,pt))],[]),init_user_mission_control_center:e.Func([],[p],[]),list_accounts:e.Func([],[e.Vec(e.Tuple(e.Principal,p))],[]),list_assets:e.Func([e.Text,mt],[_t],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,Xr))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,Qr))],[]),list_payments:e.Func([],[e.Vec(e.Tuple(e.Nat64,tn))],[]),list_proposals:e.Func([on],[an],[]),reject_proposal:e.Func([x],[e.Null],[]),set_auth_config:e.Func([cn],[C],[]),set_controllers:e.Func([un],[],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_fee:e.Func([$t,t],[],[]),set_storage_config:e.Func([dn],[P],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Ye],[]),update_rate_config:e.Func([$t,pn],[],[]),upload_proposal_asset_chunk:e.Func([fn],[Gt],[])})};var M_=async({identity:e,host:t,localActor:r})=>await hr.create({identity:e,host:t,retryTimes:10,shouldFetchRootKey:r}),j_=async({agent:e,...t})=>e??await K_(t),K_=async({identity:e,container:t})=>{let r=z(t)&&t!==!1;return await M_({identity:e,host:r?t===!0?"http://127.0.0.1:5987":t:"https://icp-api.io",localActor:r})};var jd=({satelliteId:e,certified:t=!1,...r})=>Hd({canisterId:e,...r,idlFactory:t?Ic:Rc});var Kd=({consoleId:e,certified:t=!1,...r})=>Hd({canisterId:e,...r,idlFactory:t?q_:L_}),Hd=({canisterId:e,idlFactory:t,...r})=>{if(L(e))throw new Error("No canister ID provided.");return H_({canisterId:e,idlFactory:t,...r})},H_=async({canisterId:e,idlFactory:t,config:r,...n})=>{let o=await j_(n);return so.createActor(t,{agent:o,canisterId:e,...r??{}})};var $d=({satelliteId:e,container:t})=>{let{satelliteId:r}=vc({satelliteId:e}),{container:n}=Ac({container:t});if(z(n)&&n!==!1){let{host:o,protocol:i}=new URL(n===!0?lo:n);return`${i}//${r??"unknown"}.${o.replace("127.0.0.1","localhost")}`}return`https://${r??"unknown"}.icp0.io`},vc=({satelliteId:e})=>z(e)?{satelliteId:e}:Se.getInstance().get()??{satelliteId:void 0},Ac=({container:e})=>z(e)?{container:e}:Se.getInstance().get()??{container:void 0};var we=({satellite:e,options:{certified:t}})=>Jd({idlFactory:t?Ic:Rc,actorKey:`stock#${t?"update":"query"}`,...e}),Gd=({idlFactory:e,...t})=>Jd({idlFactory:e,actorKey:"extended#query",...t}),Jd=async({satelliteId:e,container:t,...r})=>{let{satelliteId:n}=vc({satelliteId:e});ni(n,"No satellite ID defined. Did you initialize Juno?");let{container:o}=Ac({container:t});return await po.getInstance().getActor({satelliteId:n,container:o,...r})};var Rs=class extends Error{},gr=class extends Error{},Is=class extends Error{},vs=class extends Error{},As=class extends Error{},Ss=class extends Error{},Cs=class extends Error{},Fs=class extends Error{},Vs=class extends Error{};var Wd=e=>{if(L(e))return ie();switch(e.matcher){case"equal":return ie({Equal:e.timestamp});case"greaterThan":return ie({GreaterThan:e.timestamp});case"lessThan":return ie({LessThan:e.timestamp});case"between":return ie({Between:[e.timestamps.start,e.timestamps.end]});default:throw new Vs("Invalid list matcher for timestamp",e)}},Mr=({matcher:e,paginate:t,order:r,owner:n})=>({matcher:L(e)?[]:[{key:ie(e.key),description:ie(e.description),created_at:Wd(e.createdAt),updated_at:Wd(e.updatedAt)}],paginate:ie(L(t)?void 0:{start_after:ie(t.startAfter),limit:ie(L(t.limit)?void 0:BigInt(t.limit))}),order:ie(L(r)?void 0:{desc:r.desc,field:r.field==="created_at"?{CreatedAt:null}:r.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:ie(L(n)?void 0:typeof n=="string"?k.fromText(n):n)});var zd=async e=>{let t=new Blob([JSON.stringify(e,pd)],{type:"application/json; charset=utf-8"});return new Uint8Array(await t.arrayBuffer())},Ps=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(),fd)},Bs=()=>typeof window<"u";var Yd=async({data:e})=>{try{return await Ps(e)}catch(t){console.error("The data parsing has failed, mapping to undefined as a fallback.",t);return}};var Sc=async e=>{let{data:t,version:r,description:n}=e;return{description:ie(n),data:await zd(t),version:ie(r)}},Cc=e=>{let{version:t}=e;return{version:ie(t)}},Bn=async({doc:e,key:t})=>{let{owner:r,version:n,description:o,data:i,...s}=e;return{key:t,description:be(o),owner:r.toText(),data:await Ps(i),version:be(n),...s}};var Zd=async({collection:e,key:t,...r})=>{let{get_doc:n}=await we(r),o=be(await n(e,t));if(!L(o))return Bn({doc:o,key:t})},Xd=async({docs:e,...t})=>{let{get_many_docs:r}=await we(t),n=e.map(({collection:s,key:a})=>[s,a]),o=await r(n),i=[];for(let[s,a]of o){let c=be(a);i.push(z(c)?await Bn({key:s,doc:c}):void 0)}return i},Qd=async({collection:e,doc:t,...r})=>{let{set_doc:n}=await we(r),{key:o}=t,i=await Sc(t),s=await n(e,o,i);return await Bn({key:o,doc:s})},ep=async({docs:e,...t})=>{let{set_many_docs:r}=await we(t),n=[];for(let{collection:s,doc:a}of e){let{key:c}=a;n.push([s,c,await Sc(a)])}let o=await r(n),i=[];for(let[s,a]of o)i.push(await Bn({key:s,doc:a}));return i},tp=async({collection:e,doc:t,...r})=>{let{del_doc:n}=await we(r),{key:o}=t;return n(e,o,Cc(t))},rp=async({docs:e,...t})=>{let{del_many_docs:r}=await we(t),n=e.map(({collection:o,doc:i})=>[o,i.key,Cc(i)]);await r(n)},np=async({collection:e,filter:t,...r})=>{let{del_filtered_docs:n}=await we(r);return n(e,Mr(t))},op=async({collection:e,filter:t,...r})=>{let{list_docs:n}=await we(r),{items:o,items_page:i,items_length:s,matches_length:a,matches_pages:c}=await n(e,Mr(t)),u=[];for(let[p,d]of o){let{data:l,owner:f,description:h,version:_,...g}=d;u.push({key:p,description:be(h),owner:f.toText(),data:await Yd({data:l}),version:be(_),...g})}return{items:u,items_length:s,items_page:be(i),matches_length:a,matches_pages:be(c)}},ip=async({collection:e,filter:t,...r})=>{let{count_docs:n}=await we(r);return n(e,Mr(t))};var Ds=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await Zd({...r,satellite:{...e,identity:n},options:t??Mt})},ZT=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await Xd({...r,satellite:{...e,identity:n},options:t??Mt})},sp=async({satellite:e,...t})=>{let r=ue(e?.identity);return await Qd({...t,satellite:{...e,identity:r},options:{certified:!0}})},ap=async({satellite:e,...t})=>{let r=ue(e?.identity);return await ep({...t,satellite:{...e,identity:r},options:{certified:!0}})},XT=async({satellite:e,...t})=>{let r=ue(e?.identity);return await tp({...t,satellite:{...e,identity:r},options:{certified:!0}})},QT=async({satellite:e,...t})=>{let r=ue(e?.identity);return await rp({...t,satellite:{...e,identity:r},options:{certified:!0}})},eN=async({satellite:e,filter:t,...r})=>{let n=ue(e?.identity);return await np({...r,filter:t??{},satellite:{...e,identity:n},options:{certified:!0}})},tN=async({satellite:e,options:t,filter:r,...n})=>{let o=ue(e?.identity);return await op({...n,filter:r??{},satellite:{...e,identity:o},options:t??Mt})},rN=async({satellite:e,options:t,filter:r,...n})=>{let o=ue(e?.identity);return await ip({...n,filter:r??{},satellite:{...e,identity:o},options:t??Mt})};var cp=async({provider:e})=>{let{user:t,userId:r}=await Us();if(z(t))return t;try{return await $_({userId:r,provider:e})}catch(n){if(Ec({error:n,type:Md})){let o=await lp({userId:r});if(z(o))return o}throw n}},Us=async()=>{let e=Es();if(L(e))throw new Fs("No identity to initialize the user. Have you initialized Juno?");let t=e.getPrincipal().toText(),r=await lp({userId:t});return{userId:t,user:r}},lp=({userId:e})=>Ds({collection:"#user",key:e}),$_=({userId:e,...t})=>sp({collection:"#user",doc:{key:e,data:t}});var ks=async({syncTabsOnSuccess:e}={syncTabsOnSuccess:!1})=>{await di({fn:async()=>{let{user:r}=await Us();De.getInstance().set(r??null)},syncTabsOnSuccess:e})},up=async()=>{await qd({fn:async({authenticated:t})=>{let n=t?Us:()=>Promise.resolve({user:null}),{user:o}=await n();De.getInstance().set(o??null)}})},Ls=async({user:e})=>{await di({fn:async()=>{De.getInstance().set(e)},syncTabsOnSuccess:!0})};var dp=()=>{try{let e=fo.getInstance(),t=async()=>{await up(),ii({message:"junoSignInReload"})};return e.onLoginSuccess(t),()=>{e?.destroy()}}catch(e){console.warn("Auth BroadcastChannel initialization failed",e);return}};var pp=()=>{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()},fp=()=>{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()},hp=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_GOOGLE_CLIENT_ID??import.meta.env?.PUBLIC_GOOGLE_CLIENT_ID:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID??e():e()};var mp=BigInt(144e11),_p=!1,yp={width:576,height:576},gp={width:424,height:576};var pi="internetcomputer.org",xp="ic0.app",bp="id.ai";var wp=({width:e,height:t})=>{if(!Bs()||L(window)||L(window.top))return;let{top:{innerWidth:r,innerHeight:n}}=window,o=n/2+screenY-t/2,i=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=${i}`};var jt=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 Tp=(r=>(r[r.AuthorizingWithProvider=0]="AuthorizingWithProvider",r[r.CreatingOrRetrievingUser=1]="CreatingOrRetrievingUser",r))(Tp||{});var qs=class{async signIn({options:t,authClient:r,initAuth:n}){await jt({fn:async()=>await this.#e({options:t,authClient:r}),step:0,onProgress:t?.onProgress}),await jt({fn:async()=>await n({provider:this.id}),step:1,onProgress:t?.onProgress})}#e({options:t,authClient:r}){return new Promise(async(n,o)=>{if(L(r)){o(new gr("No client is ready to perform a sign-in. Have you initialized the Satellite?"));return}await r.login({onSuccess:n,onError:i=>{if(i===Os){o(new Is(i));return}o(new Rs(i))},maxTimeToLive:t?.maxTimeToLiveInNanoseconds??mp,allowPinAuthentication:t?.allowPin??_p,...t?.derivationOrigin!==void 0&&{derivationOrigin:t.derivationOrigin},...this.signInOptions({windowed:t?.windowed})})})}};var Ms=class extends qs{#e;constructor({domain:t}){super(),this.#e=t}get id(){return"internet_identity"}signInOptions({windowed:t}){let n=(()=>{let i=Se.getInstance().get()?.container;if(L(i)||i===!1){let p=[pi,xp].includes(this.#e??pi);return ao(this.#e)?`https://identity.${pi}`:p?`https://identity.${this.#e??pi}`:`https://${this.#e}`}let s=Se.getInstance().get(),a=z(s)&&z(s?.internetIdentityId)?s.internetIdentityId:Td,{host:c,protocol:u}=new URL(i===!0?lo:i);return/apple/i.test(navigator?.vendor)?`${u}//${c}?canisterId=${a}`:`${u}//${a}.${c.replace("127.0.0.1","localhost")}`})();return{...t!==!1&&{windowOpenerFeatures:wp((()=>{try{let{hostname:i}=new URL(n);return i.includes(bp)}catch{return!1}})()?gp:yp)},identityProvider:n}}};var Fc=class extends Error{},Vc=class extends Error{},Pc=class extends Error{},Bc=class extends Error{},Dc=class extends Error{},Uc=class extends Error{},kc=class extends Error{},Lc=class extends Error{},qc=class extends Error{},Mc=class extends Error{};var Np=({auth:e,identity:t})=>"satellite"in e?jd({...e.satellite,identity:t}):Kd({...e.console,identity:t}),G_=async({actorParams:e,args:t})=>{let{authenticate:r}=await Np(e);return await r(t)},J_=async({actorParams:e,args:t})=>{let{get_delegation:r}=await Np(e);return await r(t)},W_=({delegations:e,sessionKey:t})=>{let[r,n]=e,o=_r.fromDelegations(n,Uint8Array.from(r));return{identity:yr.fromDelegation(t,o),delegationChain:o,sessionKey:t}},jc=async({jwt:e,context:t,auth:r})=>{let n=await kt.generate({extractable:!1}),o=new Uint8Array(n.getPublicKey().toDer()),{delegations:i,data:s}=await z_({jwt:e,publicKey:o,context:t,auth:r});return{identity:W_({sessionKey:n,delegations:i}),data:s}},z_=async({jwt:e,publicKey:t,context:{caller:r,salt:n},auth:o})=>{let i=await G_({args:{OpenId:{jwt:e,session_key:t,salt:n}},actorParams:{auth:o,identity:r}});if("Err"in i)throw new Dc("Authentication failed",{cause:i});let{delegation:{user_key:s,expiration:a},...c}=i.Ok,u=await Y_({jwt:e,context:{caller:r,salt:n},auth:o,publicKey:t,expiration:a}),{delegation:p,signature:d}=u,{pubkey:l,expiration:f,targets:h}=p;return{delegations:[s,[{delegation:new qr(Uint8Array.from(l),f,be(h)),signature:Uint8Array.from(d)}]],data:c}},Y_=async({jwt:e,publicKey:t,context:{salt:r,caller:n},auth:o,expiration:i,maxRetries:s=5})=>{for(let a=0;a<s;a++){await new Promise(u=>{setInterval(u,1e3*a)});let c=await J_({args:{OpenId:{jwt:e,session_key:t,salt:r,expiration:i}},actorParams:{auth:o,identity:n}});if("Err"in c){let{Err:u}=c;if("NoSuchDelegation"in u||"GetCachedJwks"in u)continue;throw new qc("Getting delegation failed",{cause:c})}return c.Ok}throw new Mc};var Kc="juno:auth:openid",Hc={authUrl:"https://accounts.google.com/o/oauth2/v2/auth",authScopes:["openid","profile","email"],configUrl:"https://accounts.google.com/gsi/fedcm.json"};var Op=e=>kr(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Z_=()=>window.crypto.getRandomValues(new Uint8Array(32)),X_=async({salt:e,caller:t})=>{let r=t.getPrincipal().toUint8Array(),n=new Uint8Array(e.length+r.byteLength);n.set(e),n.set(r,e.length);let o=await window.crypto.subtle.digest("SHA-256",n);return Op(mr(o))},Q_=async({caller:e})=>{let t=Z_();return{nonce:await X_({salt:t,caller:e}),salt:t}},Ep="__caller__",Rp="__salt__",Ip="__state__",ey=({caller:e,state:t,salt:r})=>{let n={[Ep]:e.toJSON(),[Rp]:kr(r),[Ip]:t};return JSON.stringify(n)},ty=e=>{let{[Ep]:t,[Rp]:r,[Ip]:n}=JSON.parse(e);return{caller:vt.fromParsedJson(t),salt:dd(r),state:n}},ry=()=>Op(window.crypto.getRandomValues(new Uint8Array(12))),vp=async()=>{let e=vt.generate(),{nonce:t,salt:r}=await Q_({caller:e}),n=ry(),o=ey({caller:e,salt:r,state:n});return sessionStorage.setItem(Kc,o),{nonce:t,state:n}},Ap=()=>{let e=sessionStorage.getItem(Kc);if(L(e))throw new Vc;return ty(e)};var $c=async e=>{let t=Ap();if("credentials"in e){let{credentials:{jwt:r},auth:n}=e;return await jc({jwt:r,context:t,auth:n})}return await ny({...e,context:t})},ny=async({auth:e,context:t})=>{let{location:{hash:r}}=window;if(ao(r)||!r.startsWith("#"))throw new Uc("No hash found in the current location URL");let n=new URLSearchParams(r.slice(1)),o=n.get("state"),i=n.get("id_token"),{state:s}=t;if(ao(s)||o!==s)throw new kc("The provided state is invalid",{cause:o});if(ao(i))throw new Lc;return await jc({jwt:i,auth:e,context:t})};var Sp=({authUrl:e,clientId:t,nonce:r,loginHint:n,authScopes:o,state:i,redirectUrl:s})=>{let a=(()=>{try{return new URL(e)}catch{throw new Fc("Cannot parse authURL",{cause:e})}})();a.searchParams.set("client_id",t);let{location:{origin:c}}=window;a.searchParams.set("redirect_uri",s??c),a.searchParams.set("response_type","code id_token"),a.searchParams.set("scope",o.join(" ")),a.searchParams.set("state",i),a.searchParams.set("nonce",r),ri(n)?a.searchParams.set("login_hint",n):a.searchParams.set("prompt","select_account"),window.location.href=a.toString()},Cp=async({configUrl:e,clientId:t,nonce:r,loginHint:n,domainHint:o})=>{let i=await navigator.credentials.get({identity:{context:"use",providers:[{configURL:e,clientId:t,nonce:r,loginHint:n,domainHint:o}],mode:"active"},mediation:"required"});if(L(i))throw new Pc;let{type:s}=i;if(s!=="identity"||!("token"in i)||typeof i.token!="string")throw new Bc("Invalid credential received from FedCM API",{cause:i});let{token:a}=i;return{jwt:a}};async function Gc({google:e}){let t=await vp();if("credentials"in e){let{credentials:i}=e,{configUrl:s}=Hc;return await Cp({...i,...t,configUrl:s})}let{redirect:r}=e,{authUrl:n,authScopes:o}=Hc;Sp({...r,...t,authUrl:n,authScopes:o})}var oy=async()=>{let{satelliteId:e}=Se.getInstance().get()??{satelliteId:void 0};if(L(e))throw new gr("Satellite ID not set. Have you initialized the Satellite?");let t=Se.getInstance().get()?.container,{identity:{delegationChain:r,sessionKey:n,identity:o},data:{doc:i}}=await $c({redirect:null,auth:{satellite:{satelliteId:e,container:t}}});await Ue.getInstance().setAuthClientStorage({delegationChain:r,sessionKey:n});let s=await Bn({doc:i,key:o.getPrincipal().toText()});await Ls({user:s})};var Fp=e=>(e.preventDefault(),e.returnValue="Are you sure you want to exit?"),iy=()=>{window.addEventListener("beforeunload",Fp,{capture:!0})},sy=()=>{window.removeEventListener("beforeunload",Fp,{capture:!0})},js=async({fn:e})=>{try{return iy(),await e()}finally{sy()}};var Ks=class{async signIn({options:t={}}){let r=t?.redirect?.clientId??hp();if(L(r))throw new As;let{redirect:n}=t;await Gc({google:{redirect:{...n??{},clientId:r}}})}};var Vp=async({delegationIdentity:e,passkeyIdentity:t,satelliteId:r})=>{let n=t.getCredential().getAAGUID(),[o,i]=await ap({docs:[{collection:"#user",doc:{key:e.getPrincipal().toText(),data:{provider:"webauthn",providerData:{webauthn:{...z(n)&&{aaguid:xs(n)}}}}}},{collection:"#user-webauthn",doc:{key:t.getCredential().getCredentialIdText(),data:{publicKey:t.getPublicKey().toRaw()}}}],satellite:{identity:e,satelliteId:r}});return o};var Pp=(i=>(i[i.RequestingUserCredential=0]="RequestingUserCredential",i[i.FinalizingCredential=1]="FinalizingCredential",i[i.Signing=2]="Signing",i[i.FinalizingSession=3]="FinalizingSession",i[i.RetrievingUser=4]="RetrievingUser",i))(Pp||{}),Bp=(s=>(s[s.CreatingUserCredential=0]="CreatingUserCredential",s[s.ValidatingUserCredential=1]="ValidatingUserCredential",s[s.FinalizingCredential=2]="FinalizingCredential",s[s.Signing=3]="Signing",s[s.FinalizingSession=4]="FinalizingSession",s[s.RegisteringUser=5]="RegisteringUser",s))(Bp||{});var ho=class{async signUp({options:{onProgress:t,maxTimeToLiveInMilliseconds:r,passkey:n}={},loadAuthWithUser:o}){let{satelliteId:i}=Se.getInstance().get()??{satelliteId:void 0};if(L(i))throw new gr("Satellite ID not set. Have you initialized the Satellite?");let s=({step:_,state:g})=>{switch(_){case Lr.RequestingUserCredential:t?.({step:1,state:g});break;case Lr.FinalizingCredential:t?.({step:2,state:g});break;case Lr.Signing:t?.({step:3,state:g});break}},c=await jt({fn:async()=>await pc.createWithNewCredential({onProgress:s,passkeyOptions:n}),step:0,onProgress:t}),{delegationIdentity:u,sessionKey:p}=await this.#e({identity:c,maxTimeToLiveInMilliseconds:r}),l=await jt({fn:async()=>await Vp({delegationIdentity:u,passkeyIdentity:c,satelliteId:i}),step:5,onProgress:t});await jt({fn:async()=>await this.#t({delegationIdentity:u,sessionKey:p}),step:4,onProgress:t}),await jt({fn:async()=>await o({user:l}),step:5,onProgress:t})}async signIn({options:{onProgress:t,maxTimeToLiveInMilliseconds:r}={},loadAuth:n}){let{satelliteId:o}=Se.getInstance().get()??{satelliteId:void 0};if(L(o))throw new gr("Satellite ID not set. Have you initialized the Satellite?");let i=async({credentialId:d})=>{let l=await Ds({collection:"#user-webauthn",key:kr(d),options:{certified:!0},satellite:{identity:new tt,satelliteId:o}});if(L(l))throw new Ss("No public key found for the selected passkey.");let{data:f}=l,{publicKey:h}=f;return Pn(h,ei)},s=({step:d,state:l})=>{switch(d){case Lr.RequestingUserCredential:t?.({step:0,state:l});break;case Lr.FinalizingCredential:t?.({step:1,state:l});break;case Lr.Signing:t?.({step:2,state:l});break}},a=await pc.createWithExistingCredential({retrievePublicKey:i,onProgress:s}),{delegationIdentity:c,sessionKey:u}=await this.#e({identity:a,maxTimeToLiveInMilliseconds:r});await jt({fn:async()=>await this.#t({delegationIdentity:c,sessionKey:u}),step:3,onProgress:t}),await jt({fn:n,step:4,onProgress:t})}async#e({identity:t,maxTimeToLiveInMilliseconds:r}){let n=await kt.generate({extractable:!1}),o=r??144e5,i=await _r.create(t,n.getPublicKey(),new Date(Date.now()+o));return{delegationIdentity:yr.fromDelegation(n,i),sessionKey:n}}async#t({sessionKey:t,delegationIdentity:r}){let n=new qt;await Promise.all([n.set(Je,t.getKeyPair()),n.set(Ge,JSON.stringify(r.getDelegation().toJSON()))])}};var cy=async({provider:e})=>{await di({fn:async()=>{let r=await cp({provider:e});De.getInstance().set(r)},syncTabsOnSuccess:!0})},ly=async e=>{if("google"in e){let{google:{options:t}}=e;await Jc({fn:()=>new Ks().signIn({options:t}),context:{windowGuard:!1}});return}if("webauthn"in e){let{webauthn:{options:t,context:r}}=e;await Jc({fn:()=>new ho().signIn({options:t,loadAuth:()=>ks({syncTabsOnSuccess:!0})}),context:r});return}if("internet_identity"in e){let{internet_identity:{options:t,context:r}}=e,{domain:n,...o}=t??{};await Jc({fn:()=>new Ms({domain:n}).signIn({options:o,authClient:Ue.getInstance().getAuthClient(),initAuth:cy}),context:r});return}throw new vs("An unknown or unsupported provider was provided for sign-in.")},Jc=async({fn:e,context:t})=>{if(t?.windowGuard===!1){await e();return}await js({fn:e})};var uy=async e=>{let t=async()=>await dy(e);if(Object.values(e)?.[0].context?.windowGuard===!1){await t();return}await js({fn:t})},dy=async e=>{if("webauthn"in e){let{webauthn:{options:t}}=e;await new ho().signUp({options:t,loadAuthWithUser:Ls});return}throw new Cs("An unknown or unsupported provider was provided for sign-up.")};var E6=e=>e?.data?.provider==="webauthn",R6=e=>e?.data?.provider==="google";var S6=async({idlFactory:e,satellite:t})=>{let r=ue(t?.identity);return await Gd({idlFactory:e,...t,identity:r})};var Dp=async({asset:{data:e,headers:t,...r},actor:n,progress:o})=>{let{init_asset_upload:i,upload_asset_chunk:s,commit_asset_upload:a}=n,{batch_id:c}=await i(py(r));o?.onInitiatedBatch();let{chunkIds:u}=await my({data:e,uploadFn:s,batchId:c});o?.onUploadedFileChunks(r.fullPath),await hy({commitFn:a,batchId:c,data:e,headers:t,chunkIds:u}),o?.onCommittedBatch()};var py=({filename:e,collection:t,token:r,fullPath:n,encoding:o,description:i})=>({collection:t,full_path:n,name:e,token:ie(r),encoding_type:ie(o),description:ie(i)}),fy=({batchId:e,chunkIds:t,headers:r,data:n})=>{let o=r.find(([i,s])=>i.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:i})=>i),headers:[...r,...o??[]]}},hy=async({commitFn:e,...t})=>{let r=fy(t);await e(r)},my=async({data:e,uploadFn:t,batchId:r})=>{let n=[],o=Bs()?new Blob([await e.arrayBuffer()]):e,i=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:i}),i++}let s=[];for await(let a of _y({uploadChunks:n}))s=[...s,...a];return{chunkIds:s}};async function*_y({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=>yy(o)))}}var yy=async({batchId:e,chunk:t,uploadFn:r,orderId:n})=>r({batch_id:e,content:new Uint8Array(await t.arrayBuffer()),order_id:ie(n)});var Up=async({asset:e,...t})=>{let r=await we(t);await Dp({actor:r,asset:e})},kp=async({collection:e,filter:t,...r})=>{let{list_assets:n}=await we(r),{items:o,items_length:i,items_page:s,matches_length:a,matches_pages:c}=await n(e,Mr(t));return{items:o.map(([u,p])=>p),items_length:i,items_page:be(s),matches_length:a,matches_pages:be(c)}},Lp=async({collection:e,filter:t,...r})=>{let{count_assets:n}=await we(r);return n(e,Mr(t))},qp=async({collection:e,fullPath:t,...r})=>(await we(r)).del_asset(e,t),Mp=async({assets:e,satellite:t})=>{let{del_many_assets:r}=await we({satellite:t,options:{certified:!0}}),n=e.map(({collection:o,fullPath:i})=>[o,i]);await r(n)},jp=async({collection:e,filter:t,...r})=>{let{del_filtered_assets:n}=await we(r);return n(e,Mr(t))},Kp=async({collection:e,fullPath:t,token:r,...n})=>{let{set_asset_token:o}=await we(n);return o(e,t,ie(r))},Hp=async({collection:e,fullPath:t,...r})=>{let{get_asset:n}=await we(r);return be(await n(e,t))},$p=async({assets:e,...t})=>{let{get_many_assets:r}=await we(t),n=e.map(({collection:i,fullPath:s})=>[i,s]);return(await r(n)).map(([i,s])=>be(s))};var Gp=e=>btoa([...e].map(t=>String.fromCharCode(t)).join(""));var J6=e=>Jp(e),W6=e=>Jp({filename:e.data.name,...e}),Jp=async({filename:e,data:t,collection:r,headers:n=[],fullPath:o,token:i,satellite:s,encoding:a,description:c})=>{let u=ue(s?.identity),p=decodeURI(e),d=o??`/${r}/${p}`,l={...s,identity:u};return await Up({asset:{data:t,filename:p,collection:r,token:i,headers:n,fullPath:d,encoding:a,description:c},satellite:l,options:{certified:!0}}),{downloadUrl:Wp({satellite:l,assetKey:{fullPath:d,token:i}}),fullPath:d,...z(i)&&{token:i},name:p}},z6=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:ue(r?.identity)},{items:i,...s}=await kp({collection:e,filter:t??{},satellite:o,options:n??Mt}),a=i.map(({key:{full_path:c,token:u,name:p,owner:d,description:l},headers:f,encodings:h,created_at:_,updated_at:g})=>{let m=be(u);return{fullPath:c,description:be(l),name:p,downloadUrl:Wp({satellite:o,assetKey:{fullPath:c,token:m}}),token:m,headers:f,encodings:h.reduce((x,[y,{modified:T,sha256:E,total_length:O}])=>({...x,[y]:{modified:T,sha256:Gp(E),total_length:O}}),{}),owner:d.toText(),created_at:_,updated_at:g}});return{items:a,assets:a,...s}},Y6=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:ue(r?.identity)};return await Lp({collection:e,satellite:o,filter:t??{},options:n??Mt})},Z6=({collection:e,fullPath:t,satellite:r})=>qp({collection:e,fullPath:t,satellite:{...r,identity:ue(r?.identity)},options:{certified:!0}}),X6=({collection:e,fullPath:t,token:r,satellite:n})=>Kp({collection:e,fullPath:t,token:r,satellite:{...n,identity:ue(n?.identity)},options:{certified:!0}}),Q6=({assets:e,satellite:t})=>Mp({assets:e,satellite:{...t,identity:ue(t?.identity)},options:{certified:!0}}),e1=async({collection:e,satellite:t,filter:r})=>{let n={...t,identity:ue(t?.identity)};return await jp({collection:e,satellite:n,filter:r??{},options:{certified:!0}})},t1=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await Hp({...r,satellite:{...e,identity:n},options:t??Mt})},r1=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await $p({...r,satellite:{...e,identity:n},options:t??Mt})},Wp=({assetKey:{fullPath:e,token:t},satellite:r})=>{let n={...r,identity:ue(r?.identity)};return`${$d(n)}${e}${z(t)?`?token=${t}`:""}`};var gy=e=>{let t=e?.satelliteId??pp();ni(t,"Satellite ID is not configured. Juno cannot be initialized.");let r=e?.container??fp();return{satelliteId:t,internetIdentityId:e?.internetIdentityId,workers:e?.workers,syncTabs:e?.syncTabs,container:r}},p1=e=>xy(e),xy=async e=>{let t=gy(e);Se.getInstance().set(t),await ks();let r=t.workers?.auth!==void 0?Ld(t.workers.auth):void 0,n=t.syncTabs===!1?void 0:dp();return[...z(r)?[r]:[],...z(n)?[n]:[]]},by=e=>De.getInstance().subscribe(e),f1=by;export{Tp as AuthClientSignInProgressStep,Fs as InitError,Ms as InternetIdentityProvider,Vs as ListError,Rs as SignInError,gr as SignInInitError,As as SignInMissingClientIdError,vs as SignInProviderNotSupportedError,Is as SignInUserInterruptError,Cs as SignUpProviderNotSupportedError,Pp as WebAuthnSignInProgressStep,Ss as WebAuthnSignInRetrievePublicKeyError,Bp as WebAuthnSignUpProgressStep,f1 as authSubscribe,Y6 as countAssets,rN as countDocs,Z6 as deleteAsset,XT as deleteDoc,e1 as deleteFilteredAssets,eN as deleteFilteredDocs,Q6 as deleteManyAssets,QT as deleteManyDocs,Wp as downloadUrl,t1 as getAsset,Ds as getDoc,k_ as getIdentityOnce,r1 as getManyAssets,ZT as getManyDocs,S6 as getSatelliteExtendedActor,oy as handleRedirectCallback,p1 as initJuno,xy as initSatellite,R6 as isGoogleUser,u_ as isWebAuthnAvailable,E6 as isWebAuthnUser,z6 as listAssets,tN as listDocs,by as onAuthStateChange,X6 as setAssetToken,sp as setDoc,ap as setManyDocs,ly as signIn,Oc as signOut,uy as signUp,U_ as unsafeIdentity,J6 as uploadBlob,W6 as uploadFile};
54
+ Retrying request.`),await this.#g({requestFn:r,backoff:n,tries:o+1});throw No.fromCode(new Io(p))}let c=Fa(s.headers);if(s.status===_c||s.status===qm)return{ok:s.ok,status:s.status,statusText:s.statusText,responseBodyBytes:a,headers:c};let u=await s.text();if(s.status===Mm&&s.url.includes("api/v4"))throw ne.fromCode(new Ro);if(md(u))throw Y.fromCode(new Ct(u,this.#l));if(o<this.#u)return await this.#g({requestFn:r,backoff:n,tries:o+1});throw ne.fromCode(new Eo(s.status,s.statusText,c,u))}async query(t,r,n){let o=this.#f(),i=r.effectiveCanisterId?U.from(r.effectiveCanisterId):U.from(t);await this.#p(i),this.log.print(`ecid ${i.toString()}`),this.log.print(`canisterId ${t.toString()}`);let s,a=await(n??this.#n);if(!a)throw ye.fromCode(new Sr);let c=U.from(t),u=a.getPrincipal(),p=yc(this.#l,this.#r),d={request_type:Sn.Query,canister_id:c,method_name:r.methodName,arg:r.arg,sender:u,ingress_expiry:p},l=cr(d);s=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:ur.Query,body:d}),s=await a.transformRequest(s);let f=jo(s.body),h={canister:c.toText(),ecid:i,transformedRequest:s,body:f,requestId:l,backoff:o,tries:0},_=async()=>{let m=await this.#b(h);return{requestDetails:d,...m}},g=async()=>{let m=this.#_.get(i.toString());if(m)return m;await this.fetchSubnetKeys(i.toString());let x=this.#_.get(i.toString());if(!x)throw Le.fromCode(new ki);return x};try{if(!this.#y)return await _();let[m,x]=await Promise.all([_(),g()]);try{return this.#T(m,x)}catch{this.log.warn("Query response verification failed. Retrying with fresh subnet keys."),this.#_.delete(i.toString());let y=await g();return this.#T(m,y)}}catch(m){let x;if(m instanceof nt){if(m.hasCode(Ct)&&!this.#i)return await this.syncTime(i),this.query(t,r,n);m.code.requestContext={requestId:l,senderPubKey:s.body.sender_pubkey,senderSignature:s.body.sender_sig,ingressExpiry:s.body.content.ingress_expiry},x=m}else x=ce.fromCode(new Re(m));throw this.log.error(`Error while making query: ${x.message}`,x),x}}#T;async createReadStateRequest(t,r){await this.#p();let n=await(r??this.#n);if(!n)throw ye.fromCode(new Sr);let o=n.getPrincipal(),i=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:ur.ReadState,body:{request_type:Sn.ReadState,paths:t.paths,sender:o,ingress_expiry:yc(this.#l,this.#r)}});return n.transformRequest(i)}async readState(t,r,n,o){await this.#x();let i=U.from(t);function s(p){for(let d of p.paths){let[l,f]=d,h=new TextEncoder().encode("request_status");if(vn(l,h))return f}}let a,c;if(o)a=o;else{c=s(r);let p=await this.#n;if(!p)throw ye.fromCode(new Sr);a=await this.createReadStateRequest(r,p)}let u=new URL(`/api/v3/canister/${i.toString()}/read_state`,this.host);return await this.#N(u,{canisterId:i},a,c)}async readSubnetState(t,r){await this.#x();let n=U.from(t),o=new URL(`/api/v3/subnet/${n.toString()}/read_state`,this.host),i=await this.createReadStateRequest(r,this.#n??void 0);return await this.#N(o,{subnetId:n},i)}async#N(t,r,n,o){let i=this.#f();try{let{responseBodyBytes:s}=await this.#g({requestFn:()=>this.#o(t,{...this.#c,...n.request,body:jo(n.body)}),backoff:i,tries:0});return Me(s)}catch(s){let a;if(s instanceof nt){if(s.hasCode(Ct)&&!this.#i){if("canisterId"in r)await this.syncTime(r.canisterId);else if("subnetId"in r)await this.syncTimeWithSubnet(r.subnetId);else throw ct;return await this.#N(t,r,n,o)}s.code.requestContext={requestId:o??cr(n),senderPubKey:n.body.sender_pubkey,senderSignature:n.body.sender_sig,ingressExpiry:n.body.content.ingress_expiry},a=s}else a=ce.fromCode(new Re(s));throw this.log.error(`Error while making read state: ${a.message}`,a),a}}parseTimeFromResponse(t){let r;if(t.certificate){let n=Me(t.certificate);if(n&&"tree"in n)r=n.tree;else throw ne.fromCode(new Cr("Could not decode time from response"));let o=yr(["time"],r);if(o.status!==Be.Found)throw ne.fromCode(new xt("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 ne.fromCode(new Ei("Time was not in its expected format."));let i=Lr(o.value);return this.log.print("Time from response:",i),this.log.print("Time from response in milliseconds:",i.getTime()),i.getTime()}else this.log.warn("No certificate found in response");return 0}async syncTime(t){this.#a=this.#a??(async()=>{await this.#x();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??U.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),o=e.createSync({identity:new ot,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 a=(await id({canisterId:n,agent:o,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(a instanceof Date)return a.getTime()},[]));this.#O(r,i)}catch(n){let o=n instanceof nt?n:ce.fromCode(new Re(n));throw this.log.error("Caught exception while attempting to sync time",o),o}})(),await this.#a.finally(()=>{this.#a=null})}async syncTimeWithSubnet(t){await this.#x();let r=Date.now();try{let n=e.createSync({identity:new ot,host:this.host.toString(),fetch:this.#o,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),o=await Promise.all(Array(3).fill(null).map(async()=>{let s=(await sd({subnetId:t,agent:n,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(s instanceof Date)return s.getTime()},[]));this.#O(r,o)}catch(n){let o=n instanceof nt?n:ce.fromCode(new Re(n));throw this.log.error("Caught exception while attempting to sync time with subnet",o),o}}#O(t,r){let n=r.reduce((o,i)=>typeof i=="number"&&i>o?i:o,0);n>0&&(this.#r=n-t,this.#i=!0,this.log.notify({message:`Syncing time: offset of ${this.#r}`,level:"info"}))}async status(){let t=this.#s?{Authorization:"Basic "+btoa(this.#s)}:{},r=new URL("/api/v2/status",this.host);this.log.print(`fetching "${r.pathname}"`);let n=this.#f(),{responseBodyBytes:o}=await this.#g({backoff:n,requestFn:()=>this.#o(r,{headers:t,...this.#c}),tries:0});return Me(o)}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#p(t){await Promise.all([this.#x(),this.#R(t)])}async#x(){if(!this.rootKey)if(this.rootKey===null&&this.host.toString()!=="https://icp-api.io"&&this.#t)await this.fetchRootKey();else throw ye.fromCode(new at(this.#t))}async#R(t){this.#d&&!this.hasSyncedTime()&&await this.syncTime(t)}invalidateIdentity(){this.#n=null}replaceIdentity(t){this.#n=Promise.resolve(t)}async fetchSubnetKeys(t){let r=U.from(t);await this.#p(r);let n=this.rootKey,o=await this.readState(r,{paths:[[$("subnet")]]}),i=await st.create({certificate:o.certificate,rootKey:n,principal:{canisterId:r},agent:this});if(!i.cert.delegation){let c=U.selfAuthenticating(n);if(!sc({canisterId:r,subnetId:c,tree:i.cert.tree}))throw Le.fromCode(new Tn(r,c))}let s=cc(i.cert,n),a=co(i.cert,s);return this.#_.set(r.toText(),a),a}async getSubnetIdFromCanister(t){let r=U.from(t);await this.#p(r);let n=await this.readState(r,{paths:[[$("time")]]}),o=await st.create({certificate:n.certificate,rootKey:this.rootKey,principal:{canisterId:r},agent:this});return cc(o.cert,this.rootKey)}_transform(t){let r=Promise.resolve(t);if(t.endpoint===ur.Call)for(let n of this.#m)r=r.then(o=>n(o).then(i=>i||o));else for(let n of this.#h)r=r.then(o=>n(o).then(i=>i||o));return r}getTimeDiffMsecs(){return this.#r}hasSyncedTime(){return this.#i}};function yc(e,t){let r=e*gc;return to.fromDeltaInMilliseconds(r,t)}function md(e){return e.includes("Invalid request expiry: ")}var Hm=300*1e3;function _d(){return zm(Gm($m(),1e3),Wm(1e3,1.2),Jm(Hm))}function $m(){let e=!0;return async()=>e?(e=!1,!0):!1}function Gm(e,t){return async(r,n,o)=>{if(await e(r,n,o))return new Promise(i=>setTimeout(i,t))}}function Jm(e){let t=Date.now()+e;return async(r,n,o)=>{if(Date.now()>t)throw ne.fromCode(new Nn(`Request timed out after ${e} msec`,n,o))}}function Wm(e,t){let r=e;return()=>new Promise(n=>setTimeout(()=>{r*=t,n()},r))}function zm(...e){return async(t,r,n)=>{for(let o of e)await o(t,r,n)}}var gd={preSignReadStateRequest:!1};function xd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function xc(e,t){return e!==null&&typeof e=="object"&&xd(e,t)}function Zm(e,t){return xd(e,t)&&typeof e[t]=="function"}function yd(e){return xc(e,"body")&&xc(e.body,"content")&&e.body.content.request_type===Sn.ReadState&&xc(e.body.content,"ingress_expiry")&&typeof e.body.content.ingress_expiry=="object"&&e.body.content.ingress_expiry!==null&&Zm(e.body.content.ingress_expiry,"toHash")}async function bc(e,t,r,n={}){let o=[$("request_status"),r],i,s;if(n.preSignReadStateRequest??!1?(s=await Xm({paths:[o],agent:e,pollingOptions:n}),i=await e.readState(t,{paths:[o]},void 0,s)):i=await e.readState(t,{paths:[o]}),e.rootKey==null)throw ye.fromCode(new at);let c=await st.create({certificate:i.certificate,rootKey:e.rootKey,principal:{canisterId:t},blsVerify:n.blsVerify,agent:e}),u=ve(c.lookup_path([...o,$("status")])),p;switch(typeof u>"u"?p=Ut.Unknown:p=new TextDecoder().decode(u),p){case Ut.Replied:return{reply:ve(c.lookup_path([...o,"reply"])),certificate:c};case Ut.Received:case Ut.Unknown:case Ut.Processing:{let d=n.strategy??_d();return await d(t,r,p),bc(e,t,r,{...n,strategy:d,request:s})}case Ut.Rejected:{let d=new Uint8Array(ve(c.lookup_path([...o,"reject_code"])))[0],l=new TextDecoder().decode(ve(c.lookup_path([...o,"reject_message"]))),f=ve(c.lookup_path([...o,"error_code"])),h=f?new TextDecoder().decode(f):void 0;throw Ar.fromCode(new Hn(r,d,l,h))}case Ut.Done:throw ce.fromCode(new Vi(r))}throw ct}async function Xm(e){let{paths:t,agent:r,pollingOptions:n}=e;if(n.request&&yd(n.request))return n.request;let o=await r.createReadStateRequest?.({paths:t},void 0);if(!yd(o))throw Y.fromCode(new Mi(o));return o}var ft=Symbol.for("ic-agent-metadata"),po=class e{static agentOf(t){return t[ft].config.agent}static interfaceOf(t){return t[ft].service}static canisterIdOf(t){return U.from(t[ft].config.canisterId)}static createActorClass(t,r){let n=t({IDL:In});class o extends e{constructor(s){if(!s.canisterId)throw Y.fromCode(new vo(s.canisterId));let a=typeof s.canisterId=="string"?U.fromText(s.canisterId):s.canisterId;super({config:{...bd,...s,canisterId:a},service:n});for(let[c,u]of n._fields)r?.httpDetails&&u.annotations.push(wc),r?.certificate&&u.annotations.push(wd),this[c]=e_(this,c,u,s.blsVerify)}}return o}static createActor(t,r){if(!r.canisterId)throw Y.fromCode(new vo(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[ft]=Object.freeze(t)}};function uo(e,t){let r=In.decode(e,t);switch(r.length){case 0:return;case 1:return r[0];default:return r}}var bd={pollingOptions:gd},wc="http-details",wd="certificate";function e_(e,t,r,n){let o;r.annotations.includes("query")||r.annotations.includes("composite_query")?o=async(s,...a)=>{s={...s,...e[ft].config.queryTransform?.(t,a,{...e[ft].config,...s})};let c=s.agent||e[ft].config.agent||new br,u=U.from(s.canisterId||e[ft].config.canisterId),p=In.encode(r.argTypes,a),d=await c.query(u,{methodName:t,arg:p,effectiveCanisterId:s.effectiveCanisterId}),l={...d.httpDetails,requestDetails:d.requestDetails};switch(d.status){case Er.Rejected:{let f=new Fi(d.requestId,d.reject_code,d.reject_message,d.error_code,d.signatures);throw f.callContext={canisterId:u,methodName:t,httpDetails:l},Ar.fromCode(f)}case Er.Replied:return r.annotations.includes(wc)?{httpDetails:l,result:uo(r.retTypes,d.reply.arg)}:uo(r.retTypes,d.reply.arg)}}:o=async(s,...a)=>{s={...s,...e[ft].config.callTransform?.(t,a,{...e[ft].config,...s})};let c=s.agent||e[ft].config.agent||br.createSync(),{canisterId:u,effectiveCanisterId:p,pollingOptions:d}={...bd,...e[ft].config,...s},l=U.from(u),f=p!==void 0?U.from(p):l,h=In.encode(r.argTypes,a),{requestId:_,response:g,requestDetails:m}=await c.call(l,{methodName:t,arg:h,effectiveCanisterId:f,nonce:s.nonce}),x,y;if(ll(g.body)){if(c.rootKey==null)throw ye.fromCode(new at);let R=g.body.certificate;y=await st.create({certificate:R,rootKey:c.rootKey,principal:{canisterId:f},blsVerify:n,agent:c});let v=[$("request_status"),_];switch(new TextDecoder().decode(ve(y.lookup_path([...v,"status"])))){case"replied":x=ve(y.lookup_path([...v,"reply"]));break;case"rejected":{let I=new Uint8Array(ve(y.lookup_path([...v,"reject_code"])))[0],F=new TextDecoder().decode(ve(y.lookup_path([...v,"reject_message"]))),S=ve(y.lookup_path([...v,"error_code"])),b=S?new TextDecoder().decode(S):void 0,N=new Hn(_,I,F,b);throw N.callContext={canisterId:l,methodName:t,httpDetails:g},Ar.fromCode(N)}}}else if(cl(g.body)){let{reject_code:R,reject_message:v,error_code:w}=g.body,I=new Pi(_,R,v,w);throw I.callContext={canisterId:l,methodName:t,httpDetails:g},Ar.fromCode(I)}if(g.status===202){let R={...d,blsVerify:n},v=await bc(c,f,_,R);y=v.certificate,x=v.reply}let T=r.annotations.includes(wc),E=r.annotations.includes(wd),O={...g,requestDetails:m};if(x!==void 0)return T&&E?{httpDetails:O,certificate:y,result:uo(r.retTypes,x)}:E?{certificate:y,result:uo(r.retTypes,x)}:T?{httpDetails:O,result:uo(r.retTypes,x)}:uo(r.retTypes,x);{let R=new Re(`Call was returned undefined. We cannot determine if the call was successful or not. Return types: [${r.retTypes.map(v=>v.display()).join(",")}].`);throw R.callContext={canisterId:l,methodName:t,httpDetails:O},ce.fromCode(R)}};let i=(...s)=>o({},...s);return i.withOptions=s=>(...a)=>o(s,...a),i}var t_=(e=>(e[e.FractionalMoreThan8Decimals=0]="FractionalMoreThan8Decimals",e[e.InvalidFormat=1]="InvalidFormat",e[e.FractionalTooManyDecimals=2]="FractionalTooManyDecimals",e))(t_||{}),vb=BigInt(1e8);var k=e=>e==null,z=e=>!k(e),ii=e=>z(e)&&e!=="",Ln=e=>!ii(e);var r_=class extends Error{},si=(e,t)=>{if(e==null)throw new r_(t)};var wr=e=>new Uint8Array(e),Ts=e=>Array.from(e);var Nd=({a:e,b:t})=>e.length===t.length&&e.every((r,n)=>r===t[n]);var Td="abcdefghijklmnopqrstuvwxyz234567",oi=Object.create(null);for(let e=0;e<Td.length;e++)oi[Td[e]]=e;oi[0]=oi.o;oi[1]=oi.i;var Hr=e=>btoa(String.fromCharCode(...new Uint8Array(e))),Od=e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0)),Ab=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 Tc="__bigint__",Nc="__principal__",Oc="__uint8array__",Ed=(e,t)=>typeof t=="bigint"?{[Tc]:`${t}`}:z(t)&&U.isPrincipal(t)?{[Nc]:U.from(t).toText()}:z(t)&&t instanceof Uint8Array?{[Oc]:Array.from(t)}:t,Rd=(e,t)=>{let r=n=>t[n];return z(t)&&typeof t=="object"&&Tc in t?BigInt(r(Tc)):z(t)&&typeof t=="object"&&Nc in t?U.fromText(r(Nc)):z(t)&&typeof t=="object"&&Oc in t?Uint8Array.from(r(Oc)):t};var se=e=>z(e)?[e]:[],be=e=>e?.[0];var n_=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let t=e.slice(37,53),r=o_({bytes:t});return"aaguid"in r?{aaguidBytes:t,aaguidText:r.aaguid}:{unknownProvider:null}},o_=({bytes:e})=>{if(e.length!==16)return{invalidBytes:null};let t=(e instanceof Uint8Array?Ts(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 i_(e){let t=new DataView(new ArrayBuffer(2)),r=e.slice(53,55);[...new Uint8Array(r)].forEach((o,i)=>t.setUint8(i,o));let n=t.getUint16(0);return e.slice(55+n)}function s_(e){return Un(e,ni)}var a_=class{constructor(e){this._cose=e,this.#e=s_(e)}#e;toDer(){return this.#e}toRaw(){return new Uint8Array(this.#e)}},Cd=class{#e;#t;constructor({rawId:e,cose:t}){this.#e=e,this.#t=new a_(t)}getPublicKey(){return this.#t}getCredentialId(){return this.#e}getCredentialIdText(){return Hr(this.#e)}},c_=class extends Cd{#e;#t;constructor({authData:e,...t}){super(t);let r=n_({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}},l_=class extends Cd{},u_=class extends Error{},d_=class extends Error{},p_=class extends Error{},f_=class extends Error{},h_=class extends Error{},m_=class extends Error{},__=class extends Error{},Id=class extends Error{};var y_={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},g_=6e4,Fd=()=>window.crypto.getRandomValues(new Uint8Array(16)),x_=()=>Fd(),b_=()=>Fd(),w_=()=>{let{location:{href:e}}=window;try{let{hostname:t}=new URL(e);return t}catch{throw new u_}},Pd=({appId:e})=>e?.id??w_(),T_=({appId:e,user:t}={})=>{let{document:{title:r}}=window,n=()=>({rp:{name:e?.name??r,id:Pd({appId:e})}}),o=()=>({user:{id:b_(),name:t?.name??t?.displayName??r,displayName:t?.displayName??r}});return{attestation:"direct",challenge:x_(),...n(),...o(),pubKeyCredParams:Object.values(y_).map(i=>({type:"public-key",alg:i})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},N_=(e={})=>({rpId:Pd(e),allowCredentials:[],userVerification:"required"}),Ec=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}},$r=(e=>(e[e.RequestingUserCredential=0]="RequestingUserCredential",e[e.FinalizingCredential=1]="FinalizingCredential",e[e.Signing=2]="Signing",e))($r||{}),Vd=({timeout:e})=>AbortSignal.timeout(e??g_),O_=async({challenge:e,credentialIds:t,passkeyOptions:r,timeout:n})=>await navigator.credentials.get({publicKey:{...N_(r),challenge:e.buffer,allowCredentials:(t??[]).map(o=>({id:o.buffer,type:"public-key"}))},signal:Vd({timeout:n})}),vd=e=>{if(e.status!=="initialized")throw new d_},Ad=e=>{if(k(e))throw new p_},Sd=({type:e})=>{if(e!=="public-key")throw new f_},Rc=class ai extends Dt{#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=ai.#r({credential:new c_(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:T_(t),signal:Vd({timeout:r})});Ad(o),Sd(o);let{response:{attestationObject:i},rawId:s}=o;if(k(i))throw new h_;let{authData:a}=Xi.decode(wr(i)),c=i_(a);return new ai({...n,rawId:wr(s),cose:c,authData:a})}static async createWithExistingCredential(t){return new ai(t)}getPublicKey(){vd(this.#t);let{credential:t}=this.#t;return t.getPublicKey()}getCredential(){vd(this.#t);let{credential:t}=this.#t;return t}async sign(t){let r=await Ec({fn:async()=>{let n=await O_({challenge:t,...this.#t.status==="initialized"&&{credentialIds:[this.#t.credential.getCredentialId()]}});return Ad(n),Sd(n),n},step:0,onProgress:this.#e});return await Ec({fn:async()=>{let{rawId:n}=r;if(this.#t.status==="initialized"){if(!Nd({a:this.#t.credential.getCredentialId(),b:wr(n)}))throw new m_;return}let{retrievePublicKey:o}=this.#t,i=await o({credentialId:wr(n)});this.#t=ai.#r({credential:new l_({rawId:wr(n),cose:i})})},step:1,onProgress:this.#e}),await Ec({fn:async()=>{let{response:n}=r,{clientDataJSON:o}=n,{authenticatorData:i,signature:s}="authenticatorData"in n&&"signature"in n?n:{};if(k(i))throw new Id;if(k(s))throw new Id;let a=Xi.encode({authenticator_data:i,client_data_json:new TextDecoder().decode(o),signature:wr(s)});if(k(a))throw new __;return Object.assign(a,{__signature__:void 0}),a},step:2,onProgress:this.#e})}},E_=async()=>z(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;var fo=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 De=class e extends fo{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 ci=({message:e,detail:t})=>{let r=new CustomEvent(e,{detail:t,bubbles:!0});document.dispatchEvent(r)};var ho="http://127.0.0.1:5987",Bd="rdmx6-jaaaa-aaaaa-aaadq-cai";var Dd=async({identity:e,container:t})=>{let n=z(t)&&t!==!1?t===!0?ho:t:"https://icp-api.io",o=z(t);return await br.create({identity:e,shouldFetchRootKey:o,host:n})};var mo=class e{static instance;#e=void 0;constructor(){}static getInstance(){return k(e.instance)&&(e.instance=new e),e.instance}async getAgent({identity:t,...r}){let n=t.getPrincipal().toText();if(k(this.#e)||k(this.#e[n])){let o=await Dd({identity:t,...r});return this.#e={...this.#e??{},[n]:o},o}return this.#e[n]}reset(){this.#e=null}};var _o=class e{static instance;#e=void 0;constructor(){}static getInstance(){return k(e.instance)&&(e.instance=new e),e.instance}async getActor({satelliteId:t,identity:r,actorKey:n,...o}){let i=`${n}#${r.getPrincipal().toText()}#${t};`;if(k(this.#e)||k(this.#e[i])){let s=await this.createActor({satelliteId:t,identity:r,...o});return this.#e={...this.#e??{},[i]:s},s}return this.#e[i]}reset(){this.#e=null}async createActor({idlFactory:t,satelliteId:r,...n}){let o=await mo.getInstance().getAgent(n);return po.createActor(t,{agent:o,canisterId:r})}};function Ud(e){return e!==null&&typeof e=="object"}var li=class e{static from(t){if(typeof t=="string"){let r=Ee(t);return this.fromRaw(r)}else if(Ud(t)){let r=t;if(Ud(r)&&Object.hasOwnProperty.call(r,"__derEncodedPublicKey__"))return this.fromDer(r);if(ArrayBuffer.isView(r)){let n=r;return this.fromRaw(Ft(n.buffer))}else{if(r instanceof ArrayBuffer)return this.fromRaw(Ft(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=Un(t,Dn);return r.__derEncodedPublicKey__=void 0,r}static derDecode(t){let r=kn(t,Dn);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}},vt=class e extends Dt{static generate(t){if(t&&t.length!==32)throw new Error("Ed25519 Seed needs to be 32 bytes long.");t||(t=Ge.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=Ge.getPublicKey(r);return e.fromKeyPair(n,r)}static fromParsedJson(t){let[r,n]=t;return new e(li.fromDer(Ee(r)),Ee(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(li.fromRaw(t),r)}static fromSecretKey(t){let r=Ge.getPublicKey(t);return e.fromKeyPair(r,t)}#e;#t;constructor(t,r){super(),this.#e=li.from(t),this.#t=r}toJSON(){return[j(this.#e.toDer()),j(this.#t)]}getKeyPair(){return{secretKey:this.#t,publicKey:this.#e}}getPublicKey(){return this.#e}async sign(t){let r=Ge.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,i,s]=[t,r,n].map(a=>(typeof a=="string"&&(a=Ee(a)),Ft(a)));return Ge.verify(o,i,s)}};var Ic=class e extends Error{constructor(t){super(t),this.message=t,Object.setPrototypeOf(this,e.prototype)}};function kd(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 Ic("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 kt=class e extends Dt{static async generate(t){let{extractable:r=!1,keyUsages:n=["sign","verify"],subtleCrypto:o}=t??{},i=kd(o),s=await i.generateKey({name:"ECDSA",namedCurve:"P-256"},r,n),a=Ft(await i.exportKey("spki",s.publicKey));return Object.assign(a,{__derEncodedPublicKey__:void 0}),new this(s,a,i)}static async fromKeyPair(t,r){let n=kd(r),o=Ft(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=Ft(await this._subtleCrypto.sign(r,this._keyPair.privateKey,t));return Object.assign(n,{__signature__:void 0}),n}};var Ns=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 U.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 Os(e){return e instanceof Uint8Array?j(e):j(new Uint8Array(e))}function vc(e){if(typeof e!="string"||e.length<64)throw new Error("Invalid public key.");return Ee(e)}var Gr=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:Os(this.pubkey),...this.targets&&{targets:this.targets.map(t=>t.toHex())}}}};async function R_(e,t,r,n){let o=new Gr(t.toDer(),BigInt(+r)*BigInt(1e6),n),i=new Uint8Array([...Ea,...new Uint8Array(cr({...o}))]),s=await e.sign(i);return{delegation:o,signature:s}}var Tr=class e{static async create(t,r,n=new Date(Date.now()+900*1e3),o={}){let i=await R_(t,r,n,o.targets);return new e([...o.previous?.delegations||[],i],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(i=>{let{delegation:s,signature:a}=i,{pubkey:c,expiration:u,targets:p}=s;if(p!==void 0&&!Array.isArray(p))throw new Error("Invalid targets.");return{delegation:new Gr(vc(c),BigInt("0x"+u),p&&p.map(d=>{if(typeof d!="string")throw new Error("Invalid target.");return U.fromHex(d)})),signature:vc(a)}});return new this(o,vc(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:Os(r.pubkey),...o&&{targets:o.map(i=>i.toHex())}},signature:Os(n)}}),publicKey:Os(this.publicKey)}}},Nr=class extends Dt{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 cr(r);return{...n,body:{content:r,sender_sig:await this.sign(new Uint8Array([...Uo,...new Uint8Array(o)])),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}}}},ui=class e extends Ns{#e;get delegation(){return this.#e}constructor(t,r){super(t),this.#e=r}static fromDelegation(t,r){return new e(t,r)}};function Ac(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"?U.fromText(o):o)):r.push(typeof n=="string"?U.fromText(n):n));for(let o of r){let i=o.toText();for(let{delegation:s}of e.delegations){if(s.targets===void 0)continue;let a=!0;for(let c of s.targets)if(c.toText()===i){a=!1;break}if(a)return!1}}return!0}var Ld=["mousedown","mousemove","keydown","touchstart","wheel"],di=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),Ld.forEach(s=>{document.addEventListener(s,o,!0)});let i=(s,a)=>{let c;return(...u)=>{let p=this,d=()=>{c=void 0,s.apply(p,u)};clearTimeout(c),c=window.setTimeout(d,a)}};if(t?.captureScroll){let s=i(o,t?.scrollDebounce??100);window.addEventListener("scroll",s,!0)}o()}registerCallback(t){this.callbacks.push(t)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let t=this._resetTimer.bind(this);Ld.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 I_=(e,t)=>t.some(r=>e instanceof r),qd,Md;function v_(){return qd||(qd=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function A_(){return Md||(Md=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var jd=new WeakMap,Cc=new WeakMap,Kd=new WeakMap,Sc=new WeakMap,Pc=new WeakMap;function S_(e){let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{r(Lt(e.result)),o()},s=()=>{n(e.error),o()};e.addEventListener("success",i),e.addEventListener("error",s)});return t.then(r=>{r instanceof IDBCursor&&jd.set(r,e)}).catch(()=>{}),Pc.set(t,e),t}function C_(e){if(Cc.has(e))return;let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{r(),o()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)});Cc.set(e,t)}var Fc={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return Cc.get(e);if(t==="objectStoreNames")return e.objectStoreNames||Kd.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Lt(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 Hd(e){Fc=e(Fc)}function F_(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let n=e.call(Es(this),t,...r);return Kd.set(n,t.sort?t.sort():[t]),Lt(n)}:A_().includes(e)?function(...t){return e.apply(Es(this),t),Lt(jd.get(this))}:function(...t){return Lt(e.apply(Es(this),t))}}function P_(e){return typeof e=="function"?F_(e):(e instanceof IDBTransaction&&C_(e),I_(e,v_())?new Proxy(e,Fc):e)}function Lt(e){if(e instanceof IDBRequest)return S_(e);if(Sc.has(e))return Sc.get(e);let t=P_(e);return t!==e&&(Sc.set(e,t),Pc.set(t,e)),t}var Es=e=>Pc.get(e);function Gd(e,t,{blocked:r,upgrade:n,blocking:o,terminated:i}={}){let s=indexedDB.open(e,t),a=Lt(s);return n&&s.addEventListener("upgradeneeded",c=>{n(Lt(s.result),c.oldVersion,c.newVersion,Lt(s.transaction),c)}),r&&s.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),a.then(c=>{i&&c.addEventListener("close",()=>i()),o&&c.addEventListener("versionchange",u=>o(u.oldVersion,u.newVersion,u))}).catch(()=>{}),a}var V_=["get","getKey","getAll","getAllKeys","count"],B_=["put","add","delete","clear"],Vc=new Map;function $d(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Vc.get(t))return Vc.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,o=B_.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||V_.includes(r)))return;let i=async function(s,...a){let c=this.transaction(s,o?"readwrite":"readonly"),u=c.store;return n&&(u=u.index(a.shift())),(await Promise.all([u[r](...a),o&&c.done]))[0]};return Vc.set(t,i),i}Hd(e=>({...e,get:(t,r,n)=>$d(t,r)||e.get(t,r,n),has:(t,r)=>!!$d(t,r)||e.has(t,r)}));var Jd="auth-client-db",Wd="ic-keyval",D_=async(e=Jd,t=Wd,r)=>(globalThis.localStorage?.getItem(Je)&&(globalThis.localStorage.removeItem(Je),globalThis.localStorage.removeItem(We)),await Gd(e,r,{upgrade:n=>{n.objectStoreNames.contains(t)&&n.clear(t),n.createObjectStore(t)}}));async function U_(e,t,r){return await e.get(t,r)}async function k_(e,t,r,n){return await e.put(t,n,r)}async function L_(e,t,r){return await e.delete(t,r)}var Rs=class e{constructor(t,r){this._db=t,this._storeName=r}static async create(t){let{dbName:r=Jd,storeName:n=Wd,version:o=zd}=t??{},i=await D_(r,n,o);return new e(i,n)}async set(t,r){return await k_(this._db,this._storeName,t,r)}async get(t){return await U_(this._db,this._storeName,t)??null}async remove(t){return await L_(this._db,this._storeName,t)}};var We="identity",Je="delegation",Yd="iv",zd=1,pi=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}},qt=class{#e;constructor(t){this.#e=t??{}}initializedDb;get _db(){return new Promise((t,r)=>{if(this.initializedDb){t(this.initializedDb);return}Rs.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 q_=BigInt(1e9),M_=BigInt(3600),j_=q_*M_,K_="https://identity.internetcomputer.org",H_="#authorize",$_=BigInt(8)*j_,Bc="ECDSA",Dc="Ed25519",G_=500,Is="UserInterrupt",fi=class e{constructor(t,r,n,o,i,s,a,c){this._identity=t,this._key=r,this._chain=n,this._storage=o,this.idleManager=i,this._createOptions=s,this._idpWindow=a,this._eventHandler=c,this._registerDefaultIdleCallback()}static async create(t={}){let r=t.storage??new qt,n=t.keyType??Bc,o=null;if(t.identity)o=t.identity;else{let c=await r.get(We);if(!c)try{let u=new pi,p=await u.get(Je),d=await u.get(We);p&&d&&n===Bc&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await r.set(Je,p),await r.set(We,d),c=p,await u.remove(Je),await u.remove(We))}catch(u){console.error(`error while attempting to recover localstorage: ${u}`)}if(c)try{typeof c=="object"?n===Dc&&typeof c=="string"?o=vt.fromJSON(c):o=await kt.fromKeyPair(c):typeof c=="string"&&(o=vt.fromJSON(c))}catch{}}let i=new ot,s=null;if(o)try{let c=await r.get(Je);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?i=t.identity:c&&(s=Tr.fromJSON(c),Ac(s)?"toDer"in o?i=ui.fromDelegation(o,s):i=Nr.fromDelegation(o,s):(await Uc(r),o=null))}catch(c){console.error(c),await Uc(r),o=null}let a;return t.idleOptions?.disableIdle?a=void 0:(s||t.identity)&&(a=di.create(t.idleOptions)),o||(n===Dc?o=vt.generate():(t.storage&&n===Bc&&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 '${Dc}' as the key type, as it can serialize to a string`),o=await kt.generate()),await Zd(r,o)),new e(i,o,s,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 Gr(a.delegation.pubkey,a.delegation.expiration,a.delegation.targets),signature:a.signature})),o=Tr.fromDelegations(n,t.userPublicKey),i=this._key;if(!i)return;this._chain=o,"toDer"in i?this._identity=ui.fromDelegation(i,this._chain):this._identity=Nr.fromDelegation(i,this._chain),this._idpWindow?.close();let s=this._createOptions?.idleOptions;!this.idleManager&&!s?.disableIdle&&(this.idleManager=di.create(s),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(Je,JSON.stringify(this._chain.toJSON())),await Zd(this._storage,this._key),r?.(t)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null&&Ac(this._chain)}async login(t){let r=J_(this._createOptions?.loginOptions,t),n=r?.maxTimeToLive??$_,o=new URL(r?.identityProvider?.toString()||K_);o.hash=H_,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 i=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(Is,r?.onError):setTimeout(i,G_))};i()}_getEventHandler(t,r){return async n=>{if(n.origin!==t.origin)return;let o=n.data;switch(o.kind){case"authorize-ready":{let i={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(i,t.origin);break}case"authorize-client-success":try{await this._handleSuccess(o,r?.onSuccess)}catch(i){this._handleFailure(i.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 Uc(this._storage),this._identity=new ot,this._chain=null,t.returnTo)try{window.history.pushState({},"",t.returnTo)}catch{window.location.href=t.returnTo}}};async function Uc(e){await e.remove(We),await e.remove(Je),await e.remove(Yd)}function J_(e,t){if(!e&&!t)return;let r=e?.customValues||t?.customValues?{...e?.customValues,...t?.customValues}:void 0;return{...e,...t,customValues:r}}function W_(e){if(e instanceof kt)return e.getKeyPair();if(e instanceof vt)return JSON.stringify(e.toJSON());throw new Error("Unsupported key type")}async function Zd(e,t){let r=W_(t);await e.set(We,r)}var Ue=class e{static#e;#t;constructor(){}static getInstance(){return k(this.#e)&&(this.#e=new e),this.#e}createAuthClient=async()=>(this.#t=await fi.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}}),this.#t);safeCreateAuthClient=async()=>(await new qt().remove(We),await this.createAuthClient());getAuthClient=()=>this.#t;logout=async()=>{await this.#t?.logout(),this.#t=null};setAuthClientStorage=async({delegationChain:t,sessionKey:r})=>{let n=new qt;await Promise.all([n.set(We,r.getKeyPair()),n.set(Je,JSON.stringify(t.toJSON()))])}};var kc=async e=>{await z_(),await Ue.getInstance().createAuthClient(),e?.windowReload!==!1&&window.location.reload()},z_=async()=>{await Ue.getInstance().logout(),De.getInstance().reset(),_o.getInstance().reset(),mo.getInstance().reset()};var Xd=e=>{let t=e===!0?"./workers/auth.worker.js":e,r=new Worker(t),n=async()=>{ci({message:"junoSignOutAuthTimer"}),await kc()};return r.onmessage=async({data:o})=>{let{msg:i,data:s}=o;switch(i){case"junoSignOutAuthTimer":await n();return;case"junoDelegationRemainingTime":ci({message:"junoDelegationRemainingTime",detail:s?.authRemainingTime})}},De.getInstance().subscribe(o=>{if(k(o)){r.postMessage({msg:"junoStopAuthTimer"});return}r.postMessage({msg:"junoStartAuthTimer"})})};var yo=class e{static#e;#t;#r;static CHANNEL_NAME="juno_core_auth_channel";static MESSAGE_LOGIN_SUCCESS="authClientLoginSuccess";constructor(){this.#t=new BroadcastChannel(e.CHANNEL_NAME),this.#r=window.crypto.randomUUID()}static getInstance(){return k(this.#e)&&(this.#e=new e),this.#e}onLoginSuccess=t=>{let{location:{origin:r}}=window;this.#t.onmessage=async({origin:n,data:o})=>{n===r&&z(o)&&o.msg==="authClientLoginSuccess"&&ii(o.emitterId)&&o.emitterId!==this.#r&&await t()}};destroy=()=>{this.#t.close(),e.#e=null};postLoginSuccess=()=>{let t={emitterId:this.#r,msg:e.MESSAGE_LOGIN_SUCCESS};this.#t.postMessage(t)};get __test__only__emitter_id__(){return this.#r}};var Se=class e extends fo{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 hi=async({fn:e,syncTabsOnSuccess:t})=>{let{authenticated:r}=await Y_({fn:e});!r||!t||Se.getInstance().get()?.syncTabs===!1||Z_()},Qd=async({fn:e})=>{let{createAuthClient:t}=Ue.getInstance(),n=await(await t()).isAuthenticated();await e({authenticated:n})},Y_=async({fn:e})=>{let{createAuthClient:t,safeCreateAuthClient:r}=Ue.getInstance();return await(await t()).isAuthenticated()?(await e(),{authenticated:!0}):(await r(),{authenticated:!1})},Z_=()=>{try{yo.getInstance().postLoginSuccess()}catch(e){console.warn("Auth BroadcastChannel posting failed",e)}};var Lc=({error:e,type:t})=>typeof e=="string"?e.includes(t):e instanceof Error?e.message.includes(t):!1;var ep="juno.datastore.error.user.cannot_update";var Mt={certified:!1};var vs=()=>Ue.getInstance().getAuthClient()?.getIdentity(),X_=async()=>{let{getAuthClient:e,createAuthClient:t}=Ue.getInstance();return(e()??await t()).getIdentity()},Q_=async()=>{let e=De.getInstance().get();if(k(e))return null;let t=Ue.getInstance().getAuthClient();return await t?.isAuthenticated()??!1?t?.getIdentity()??null:null};var de=e=>z(e)?e:vs()??new ot;var qc=({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({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),i=e.Variant({OpenId:o}),s=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)}),a=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),c=e.Record({doc:s,delegation:a}),u=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),p=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),d=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),l=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text}),f=e.Variant({PrepareDelegation:l,RegisterUser:e.Text}),h=e.Variant({Ok:c,Err:f}),_=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),g=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),m=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),x=e.Record({field:m,desc:e.Bool}),y=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),T=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(y),description:e.Opt(e.Text),created_at:e.Opt(y)}),E=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),O=e.Record({order:e.Opt(x),owner:e.Opt(e.Principal),matcher:e.Opt(T),paginate:e.Opt(E)}),R=e.Record({controllers:e.Vec(e.Principal)}),v=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),w=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:v,expires_at:e.Opt(e.Nat64)}),I=e.Record({version:e.Opt(e.Nat64)}),F=e.Variant({Db:e.Null,Storage:e.Null}),S=e.Record({version:e.Opt(e.Nat64)}),b=e.Record({proposal_ids:e.Vec(e.Nat)}),N=e.Record({cycles:e.Nat,destination_id:e.Principal}),C=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}),B=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),L=e.Record({key:C,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,B)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),A=e.Variant({Google:e.Null}),P=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),V=e.Record({delegation:e.Opt(P),client_id:e.Text}),D=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(A,V))}),q=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),te=e.Record({allowed_callers:e.Vec(e.Principal)}),ee=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(D),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(q),rules:e.Opt(te)}),J=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),ae=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(J)}),he=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),Fe=e.Variant({Deny:e.Null,Allow:e.Null}),oe=e.Record({status_code:e.Nat16,location:e.Text}),re=e.Record({iframe:e.Opt(he),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(J),raw_access:e.Opt(Fe),redirects:e.Opt(e.Vec(e.Tuple(e.Text,oe)))}),Kt=e.Record({db:e.Opt(ae),authentication:e.Opt(ee),storage:re}),Wr=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),zr=e.Variant({OpenId:Wr}),Yr=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),Zr=e.Record({signature:e.Vec(e.Nat8),delegation:Yr}),Ht=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text}),Ze=e.Variant({Ok:Zr,Err:Ht}),$t=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),Xr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),Qr=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),Xe=e.Variant({AssetsUpgrade:Xr,SegmentsDeployment:Qr}),Qe=e.Record({status:$t,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:Xe}),et=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),Gt=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),tt=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:et,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(Gt),write:et,max_changes_per_user:e.Opt(e.Nat32)}),Jt=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)}),ht=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}),en=e.Variant({Callback:e.Record({token:ht,callback:e.Func([],[],["query"])})}),Wt=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(en),status_code:e.Nat16}),tn=e.Record({token:e.Opt(ht),body:e.Vec(e.Nat8)}),mt=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}),_t=e.Record({batch_id:e.Nat}),rn=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}),nn=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),on=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,s)),items_length:e.Nat64}),sn=e.Record({desc:e.Bool}),zt=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),an=e.Record({order:e.Opt(sn),paginate:e.Opt(zt)}),cn=e.Record({proposal_id:e.Nat}),Yt=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(cn,Qe)),items_length:e.Nat64}),ln=e.Record({include_system:e.Bool}),un=e.Record({matcher:e.Opt(ln)}),dn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,tt)),items_length:e.Nat64}),pn=e.Record({stable:e.Nat64,heap:e.Nat64}),fn=e.Record({openid:e.Opt(D),version:e.Opt(e.Nat64),internet_identity:e.Opt(q),rules:e.Opt(te)}),hn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:v,expires_at:e.Opt(e.Nat64)}),mn=e.Record({controller:hn,controllers:e.Vec(e.Principal)}),_n=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(J)}),Zt=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),ke=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),max_size:e.Opt(e.Nat),read:et,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(Gt),write:et,max_changes_per_user:e.Opt(e.Nat32)}),yn=e.Record({iframe:e.Opt(he),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(J),raw_access:e.Opt(Fe),redirects:e.Opt(e.Vec(e.Tuple(e.Text,oe)))}),Xt=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),rt=e.Record({chunk_id:e.Nat});return e.Service({authenticate:e.Func([i],[h],[]),commit_asset_upload:e.Func([_],[],[]),commit_proposal:e.Func([g],[e.Null],[]),commit_proposal_asset_upload:e.Func([_],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(_)],[],[]),count_assets:e.Func([e.Text,O],[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,O],[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([R],[e.Vec(e.Tuple(e.Principal,w))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,I],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,O],[],[]),del_filtered_docs:e.Func([e.Text,O],[],[]),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,I))],[],[]),del_rule:e.Func([F,e.Text,S],[],[]),delete_proposal_assets:e.Func([b],[],[]),deposit_cycles:e.Func([N],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(L)],["query"]),get_auth_config:e.Func([],[e.Opt(ee)],["query"]),get_config:e.Func([],[Kt],[]),get_db_config:e.Func([],[e.Opt(ae)],["query"]),get_delegation:e.Func([zr],[Ze],["query"]),get_doc:e.Func([e.Text,e.Text],[e.Opt(s)],["query"]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(L)))],["query"]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(s)))],["query"]),get_proposal:e.Func([e.Nat],[e.Opt(Qe)],["query"]),get_rule:e.Func([F,e.Text],[e.Opt(tt)],["query"]),get_storage_config:e.Func([],[re],["query"]),http_request:e.Func([Jt],[Wt],["query"]),http_request_streaming_callback:e.Func([ht],[tn],["query"]),init_asset_upload:e.Func([mt],[_t],[]),init_proposal:e.Func([Xe],[e.Nat,Qe],[]),init_proposal_asset_upload:e.Func([mt,e.Nat],[_t],[]),init_proposal_many_assets_upload:e.Func([e.Vec(mt),e.Nat],[e.Vec(e.Tuple(e.Text,_t))],[]),list_assets:e.Func([e.Text,O],[rn],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,w))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,nn))],["query"]),list_docs:e.Func([e.Text,O],[on],["query"]),list_proposals:e.Func([an],[Yt],["query"]),list_rules:e.Func([F,un],[dn],["query"]),memory_size:e.Func([],[pn],["query"]),reject_proposal:e.Func([g],[e.Null],[]),set_asset_token:e.Func([e.Text,e.Text,e.Opt(e.Text)],[],[]),set_auth_config:e.Func([fn],[ee],[]),set_controllers:e.Func([mn],[e.Vec(e.Tuple(e.Principal,w))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([_n],[ae],[]),set_doc:e.Func([e.Text,e.Text,Zt],[s],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Zt))],[e.Vec(e.Tuple(e.Text,s))],[]),set_rule:e.Func([F,e.Text,ke],[tt],[]),set_storage_config:e.Func([yn],[re],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Qe],[]),switch_storage_system_memory:e.Func([],[],[]),upload_asset_chunk:e.Func([Xt],[rt],[]),upload_proposal_asset_chunk:e.Func([Xt],[rt],[])})},Mc=({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({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),i=e.Variant({OpenId:o}),s=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)}),a=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),c=e.Record({doc:s,delegation:a}),u=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),p=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),d=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),l=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text}),f=e.Variant({PrepareDelegation:l,RegisterUser:e.Text}),h=e.Variant({Ok:c,Err:f}),_=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),g=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),m=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),x=e.Record({field:m,desc:e.Bool}),y=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),T=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(y),description:e.Opt(e.Text),created_at:e.Opt(y)}),E=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),O=e.Record({order:e.Opt(x),owner:e.Opt(e.Principal),matcher:e.Opt(T),paginate:e.Opt(E)}),R=e.Record({controllers:e.Vec(e.Principal)}),v=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),w=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:v,expires_at:e.Opt(e.Nat64)}),I=e.Record({version:e.Opt(e.Nat64)}),F=e.Variant({Db:e.Null,Storage:e.Null}),S=e.Record({version:e.Opt(e.Nat64)}),b=e.Record({proposal_ids:e.Vec(e.Nat)}),N=e.Record({cycles:e.Nat,destination_id:e.Principal}),C=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}),B=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),L=e.Record({key:C,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,B)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),A=e.Variant({Google:e.Null}),P=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),V=e.Record({delegation:e.Opt(P),client_id:e.Text}),D=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(A,V))}),q=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),te=e.Record({allowed_callers:e.Vec(e.Principal)}),ee=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(D),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(q),rules:e.Opt(te)}),J=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),ae=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(J)}),he=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),Fe=e.Variant({Deny:e.Null,Allow:e.Null}),oe=e.Record({status_code:e.Nat16,location:e.Text}),re=e.Record({iframe:e.Opt(he),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(J),raw_access:e.Opt(Fe),redirects:e.Opt(e.Vec(e.Tuple(e.Text,oe)))}),Kt=e.Record({db:e.Opt(ae),authentication:e.Opt(ee),storage:re}),Wr=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),zr=e.Variant({OpenId:Wr}),Yr=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),Zr=e.Record({signature:e.Vec(e.Nat8),delegation:Yr}),Ht=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text}),Ze=e.Variant({Ok:Zr,Err:Ht}),$t=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),Xr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),Qr=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),Xe=e.Variant({AssetsUpgrade:Xr,SegmentsDeployment:Qr}),Qe=e.Record({status:$t,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:Xe}),et=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),Gt=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),tt=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:et,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(Gt),write:et,max_changes_per_user:e.Opt(e.Nat32)}),Jt=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)}),ht=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}),en=e.Variant({Callback:e.Record({token:ht,callback:e.Func([],[],[])})}),Wt=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(en),status_code:e.Nat16}),tn=e.Record({token:e.Opt(ht),body:e.Vec(e.Nat8)}),mt=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}),_t=e.Record({batch_id:e.Nat}),rn=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}),nn=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),on=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,s)),items_length:e.Nat64}),sn=e.Record({desc:e.Bool}),zt=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),an=e.Record({order:e.Opt(sn),paginate:e.Opt(zt)}),cn=e.Record({proposal_id:e.Nat}),Yt=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(cn,Qe)),items_length:e.Nat64}),ln=e.Record({include_system:e.Bool}),un=e.Record({matcher:e.Opt(ln)}),dn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,tt)),items_length:e.Nat64}),pn=e.Record({stable:e.Nat64,heap:e.Nat64}),fn=e.Record({openid:e.Opt(D),version:e.Opt(e.Nat64),internet_identity:e.Opt(q),rules:e.Opt(te)}),hn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:v,expires_at:e.Opt(e.Nat64)}),mn=e.Record({controller:hn,controllers:e.Vec(e.Principal)}),_n=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(J)}),Zt=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),ke=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),max_size:e.Opt(e.Nat),read:et,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(Gt),write:et,max_changes_per_user:e.Opt(e.Nat32)}),yn=e.Record({iframe:e.Opt(he),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(J),raw_access:e.Opt(Fe),redirects:e.Opt(e.Vec(e.Tuple(e.Text,oe)))}),Xt=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),rt=e.Record({chunk_id:e.Nat});return e.Service({authenticate:e.Func([i],[h],[]),commit_asset_upload:e.Func([_],[],[]),commit_proposal:e.Func([g],[e.Null],[]),commit_proposal_asset_upload:e.Func([_],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(_)],[],[]),count_assets:e.Func([e.Text,O],[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,O],[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([R],[e.Vec(e.Tuple(e.Principal,w))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,I],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,O],[],[]),del_filtered_docs:e.Func([e.Text,O],[],[]),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,I))],[],[]),del_rule:e.Func([F,e.Text,S],[],[]),delete_proposal_assets:e.Func([b],[],[]),deposit_cycles:e.Func([N],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(L)],[]),get_auth_config:e.Func([],[e.Opt(ee)],[]),get_config:e.Func([],[Kt],[]),get_db_config:e.Func([],[e.Opt(ae)],[]),get_delegation:e.Func([zr],[Ze],[]),get_doc:e.Func([e.Text,e.Text],[e.Opt(s)],[]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(L)))],[]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(s)))],[]),get_proposal:e.Func([e.Nat],[e.Opt(Qe)],[]),get_rule:e.Func([F,e.Text],[e.Opt(tt)],[]),get_storage_config:e.Func([],[re],[]),http_request:e.Func([Jt],[Wt],[]),http_request_streaming_callback:e.Func([ht],[tn],[]),init_asset_upload:e.Func([mt],[_t],[]),init_proposal:e.Func([Xe],[e.Nat,Qe],[]),init_proposal_asset_upload:e.Func([mt,e.Nat],[_t],[]),init_proposal_many_assets_upload:e.Func([e.Vec(mt),e.Nat],[e.Vec(e.Tuple(e.Text,_t))],[]),list_assets:e.Func([e.Text,O],[rn],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,w))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,nn))],[]),list_docs:e.Func([e.Text,O],[on],[]),list_proposals:e.Func([an],[Yt],[]),list_rules:e.Func([F,un],[dn],[]),memory_size:e.Func([],[pn],[]),reject_proposal:e.Func([g],[e.Null],[]),set_asset_token:e.Func([e.Text,e.Text,e.Opt(e.Text)],[],[]),set_auth_config:e.Func([fn],[ee],[]),set_controllers:e.Func([mn],[e.Vec(e.Tuple(e.Principal,w))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([_n],[ae],[]),set_doc:e.Func([e.Text,e.Text,Zt],[s],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Zt))],[e.Vec(e.Tuple(e.Text,s))],[]),set_rule:e.Func([F,e.Text,ke],[tt],[]),set_storage_config:e.Func([yn],[re],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Qe],[]),switch_storage_system_memory:e.Func([],[],[]),upload_asset_chunk:e.Func([Xt],[rt],[]),upload_proposal_asset_chunk:e.Func([Xt],[rt],[])})},ey=({IDL:e})=>{let t=e.Record({e8s:e.Nat64}),r=e.Record({mission_control_id:e.Principal,user:e.Principal}),n=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),o=e.Variant({OpenId:n}),i=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),s=e.Variant({Google:e.Null}),a=e.Record({name:e.Opt(e.Text),locale:e.Opt(e.Text),family_name:e.Opt(e.Text),email:e.Opt(e.Text),picture:e.Opt(e.Text),given_name:e.Opt(e.Text)}),c=e.Record({provider:s,data:a}),u=e.Variant({InternetIdentity:e.Null,OpenId:c}),p=e.Record({updated_at:e.Nat64,credits:t,mission_control_id:e.Opt(e.Principal),provider:e.Opt(u),owner:e.Principal,created_at:e.Nat64}),d=e.Record({delegation:i,account:p}),l=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),f=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),h=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),_=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text}),g=e.Variant({PrepareDelegation:_,RegisterUser:e.Text}),m=e.Variant({Ok:d,Err:g}),x=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),y=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),T=e.Record({subnet_id:e.Opt(e.Principal)}),E=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),name:e.Opt(e.Text),user:e.Principal}),O=e.Variant({Heap:e.Null,Stable:e.Null}),R=e.Record({system_memory:e.Opt(O)}),v=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),storage:e.Opt(R),name:e.Opt(e.Text),user:e.Principal}),w=e.Record({controllers:e.Vec(e.Principal)}),I=e.Record({proposal_ids:e.Vec(e.Nat)}),F=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),S=e.Record({delegation:e.Opt(F),client_id:e.Text}),b=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(s,S))}),N=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),C=e.Record({allowed_callers:e.Vec(e.Principal)}),B=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(b),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(N),rules:e.Opt(C)}),L=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),A=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),P=e.Variant({Deny:e.Null,Allow:e.Null}),V=e.Record({status_code:e.Nat16,location:e.Text}),D=e.Record({iframe:e.Opt(L),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(A),raw_access:e.Opt(P),redirects:e.Opt(e.Vec(e.Tuple(e.Text,V)))}),q=e.Record({authentication:e.Opt(B),storage:D}),te=e.Record({user:e.Principal}),ee=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),J=e.Variant({OpenId:ee}),ae=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),he=e.Record({signature:e.Vec(e.Nat8),delegation:ae}),Fe=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text}),oe=e.Variant({Ok:he,Err:Fe}),re=e.Variant({Orbiter:e.Null,MissionControl:e.Null,Satellite:e.Null}),Kt=e.Record({e12s:e.Nat64}),Wr=e.Record({updated_at:e.Nat64,fee_cycles:Kt,fee_icp:e.Opt(t)}),zr=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),Yr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),Zr=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),Ht=e.Variant({AssetsUpgrade:Yr,SegmentsDeployment:Zr}),Ze=e.Record({status:zr,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:Ht}),$t=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),Xr=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)}),Qr=e.Variant({Heap:e.Null,Stable:e.Null}),Xe=e.Record({memory:Qr,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}),Qe=e.Variant({Callback:e.Record({token:Xe,callback:e.Func([],[],["query"])})}),et=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(Qe),status_code:e.Nat16}),Gt=e.Record({token:e.Opt(Xe),body:e.Vec(e.Nat8)}),tt=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}),Jt=e.Record({batch_id:e.Nat}),ht=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),en=e.Record({field:ht,desc:e.Bool}),Wt=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),tn=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(Wt),description:e.Opt(e.Text),created_at:e.Opt(Wt)}),mt=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),_t=e.Record({order:e.Opt(en),owner:e.Opt(e.Principal),matcher:e.Opt(tn),paginate:e.Opt(mt)}),rn=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}),nn=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),on=e.Record({key:rn,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,nn)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),sn=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,on)),items_length:e.Nat64}),zt=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),an=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:zt,expires_at:e.Opt(e.Nat64)}),cn=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),Yt=e.Variant({Refunded:e.Null,Acknowledged:e.Null,Completed:e.Null}),ln=e.Record({status:Yt,updated_at:e.Nat64,block_index_payment:e.Nat64,mission_control_id:e.Opt(e.Principal),created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64)}),un=e.Record({block_index:e.Nat64,ledger_id:e.Principal}),dn=e.Record({owner:e.Principal,subaccount:e.Opt(e.Vec(e.Nat8))}),pn=e.Record({status:Yt,updated_at:e.Nat64,created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64),purchaser:dn}),fn=e.Record({desc:e.Bool}),hn=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),mn=e.Record({order:e.Opt(fn),paginate:e.Opt(hn)}),_n=e.Record({proposal_id:e.Nat}),Zt=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(_n,Ze)),items_length:e.Nat64}),ke=e.Variant({Orbiter:e.Null,Satellite:e.Null}),yn=e.Record({segment_id:e.Opt(e.Principal),segment_kind:e.Opt(ke)}),Xt=e.Record({user:e.Principal,segment_id:e.Principal,segment_kind:ke}),rt=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),segment_id:e.Principal,created_at:e.Nat64}),Ys=e.Record({openid:e.Opt(b),version:e.Opt(e.Nat64),internet_identity:e.Opt(N),rules:e.Opt(C)}),Zs=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:zt,expires_at:e.Opt(e.Nat64)}),Xs=e.Record({controller:Zs,controllers:e.Vec(e.Principal)}),Qs=e.Record({fee_cycles:Kt,fee_icp:e.Opt(t)}),ea=e.Record({metadata:e.Opt(e.Vec(e.Tuple(e.Text,e.Text))),segment_id:e.Principal,segment_kind:ke}),ta=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),segment_id:e.Principal,segment_kind:ke}),ra=e.Record({iframe:e.Opt(L),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(A),raw_access:e.Opt(P),redirects:e.Opt(e.Vec(e.Tuple(e.Text,V)))}),na=e.Record({segment_id:e.Principal,segment_kind:ke}),oa=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),ia=e.Record({chunk_id:e.Nat});return e.Service({add_credits:e.Func([e.Principal,t],[],[]),add_invitation_code:e.Func([e.Text],[],[]),assert_mission_control_center:e.Func([r],[],["query"]),authenticate:e.Func([o],[m],[]),commit_proposal:e.Func([x],[e.Null],[]),commit_proposal_asset_upload:e.Func([y],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(y)],[],[]),count_proposals:e.Func([],[e.Nat64],["query"]),create_mission_control:e.Func([T],[e.Principal],[]),create_orbiter:e.Func([E],[e.Principal],[]),create_satellite:e.Func([v],[e.Principal],[]),del_controllers:e.Func([w],[],[]),del_custom_domain:e.Func([e.Text],[],[]),delete_proposal_assets:e.Func([I],[],[]),get_account:e.Func([],[e.Opt(p)],["query"]),get_auth_config:e.Func([],[e.Opt(B)],["query"]),get_config:e.Func([],[q],["query"]),get_create_orbiter_fee:e.Func([te],[e.Opt(t)],["query"]),get_create_satellite_fee:e.Func([te],[e.Opt(t)],["query"]),get_credits:e.Func([],[t],["query"]),get_delegation:e.Func([J],[oe],["query"]),get_fee:e.Func([re],[Wr],["query"]),get_or_init_account:e.Func([],[p],[]),get_proposal:e.Func([e.Nat],[e.Opt(Ze)],["query"]),get_rate_config:e.Func([re],[$t],["query"]),get_storage_config:e.Func([],[D],["query"]),http_request:e.Func([Xr],[et],["query"]),http_request_streaming_callback:e.Func([Xe],[Gt],["query"]),init_proposal:e.Func([Ht],[e.Nat,Ze],[]),init_proposal_asset_upload:e.Func([tt,e.Nat],[Jt],[]),init_proposal_many_assets_upload:e.Func([e.Vec(tt),e.Nat],[e.Vec(e.Tuple(e.Text,Jt))],[]),list_accounts:e.Func([],[e.Vec(e.Tuple(e.Principal,p))],["query"]),list_assets:e.Func([e.Text,_t],[sn],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,an))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,cn))],["query"]),list_icp_payments:e.Func([],[e.Vec(e.Tuple(e.Nat64,ln))],["query"]),list_icrc_payments:e.Func([],[e.Vec(e.Tuple(un,pn))],["query"]),list_proposals:e.Func([mn],[Zt],["query"]),list_segments:e.Func([yn],[e.Vec(e.Tuple(Xt,rt))],["query"]),reject_proposal:e.Func([x],[e.Null],[]),set_auth_config:e.Func([Ys],[B],[]),set_controllers:e.Func([Xs],[],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_fee:e.Func([re,Qs],[],[]),set_rate_config:e.Func([re,$t],[],[]),set_segment:e.Func([ea],[rt],[]),set_segment_metadata:e.Func([ta],[rt],[]),set_storage_config:e.Func([ra],[D],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Ze],[]),unset_segment:e.Func([na],[],[]),upload_proposal_asset_chunk:e.Func([oa],[ia],[])})},ty=({IDL:e})=>{let t=e.Record({e8s:e.Nat64}),r=e.Record({mission_control_id:e.Principal,user:e.Principal}),n=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),o=e.Variant({OpenId:n}),i=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),s=e.Variant({Google:e.Null}),a=e.Record({name:e.Opt(e.Text),locale:e.Opt(e.Text),family_name:e.Opt(e.Text),email:e.Opt(e.Text),picture:e.Opt(e.Text),given_name:e.Opt(e.Text)}),c=e.Record({provider:s,data:a}),u=e.Variant({InternetIdentity:e.Null,OpenId:c}),p=e.Record({updated_at:e.Nat64,credits:t,mission_control_id:e.Opt(e.Principal),provider:e.Opt(u),owner:e.Principal,created_at:e.Nat64}),d=e.Record({delegation:i,account:p}),l=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),f=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),h=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),_=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text}),g=e.Variant({PrepareDelegation:_,RegisterUser:e.Text}),m=e.Variant({Ok:d,Err:g}),x=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),y=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),T=e.Record({subnet_id:e.Opt(e.Principal)}),E=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),name:e.Opt(e.Text),user:e.Principal}),O=e.Variant({Heap:e.Null,Stable:e.Null}),R=e.Record({system_memory:e.Opt(O)}),v=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),storage:e.Opt(R),name:e.Opt(e.Text),user:e.Principal}),w=e.Record({controllers:e.Vec(e.Principal)}),I=e.Record({proposal_ids:e.Vec(e.Nat)}),F=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),S=e.Record({delegation:e.Opt(F),client_id:e.Text}),b=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(s,S))}),N=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),C=e.Record({allowed_callers:e.Vec(e.Principal)}),B=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(b),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(N),rules:e.Opt(C)}),L=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),A=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),P=e.Variant({Deny:e.Null,Allow:e.Null}),V=e.Record({status_code:e.Nat16,location:e.Text}),D=e.Record({iframe:e.Opt(L),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(A),raw_access:e.Opt(P),redirects:e.Opt(e.Vec(e.Tuple(e.Text,V)))}),q=e.Record({authentication:e.Opt(B),storage:D}),te=e.Record({user:e.Principal}),ee=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),J=e.Variant({OpenId:ee}),ae=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),he=e.Record({signature:e.Vec(e.Nat8),delegation:ae}),Fe=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text}),oe=e.Variant({Ok:he,Err:Fe}),re=e.Variant({Orbiter:e.Null,MissionControl:e.Null,Satellite:e.Null}),Kt=e.Record({e12s:e.Nat64}),Wr=e.Record({updated_at:e.Nat64,fee_cycles:Kt,fee_icp:e.Opt(t)}),zr=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),Yr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),Zr=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),Ht=e.Variant({AssetsUpgrade:Yr,SegmentsDeployment:Zr}),Ze=e.Record({status:zr,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:Ht}),$t=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),Xr=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)}),Qr=e.Variant({Heap:e.Null,Stable:e.Null}),Xe=e.Record({memory:Qr,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}),Qe=e.Variant({Callback:e.Record({token:Xe,callback:e.Func([],[],[])})}),et=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(Qe),status_code:e.Nat16}),Gt=e.Record({token:e.Opt(Xe),body:e.Vec(e.Nat8)}),tt=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}),Jt=e.Record({batch_id:e.Nat}),ht=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),en=e.Record({field:ht,desc:e.Bool}),Wt=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),tn=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(Wt),description:e.Opt(e.Text),created_at:e.Opt(Wt)}),mt=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),_t=e.Record({order:e.Opt(en),owner:e.Opt(e.Principal),matcher:e.Opt(tn),paginate:e.Opt(mt)}),rn=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}),nn=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),on=e.Record({key:rn,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,nn)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),sn=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,on)),items_length:e.Nat64}),zt=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),an=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:zt,expires_at:e.Opt(e.Nat64)}),cn=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),Yt=e.Variant({Refunded:e.Null,Acknowledged:e.Null,Completed:e.Null}),ln=e.Record({status:Yt,updated_at:e.Nat64,block_index_payment:e.Nat64,mission_control_id:e.Opt(e.Principal),created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64)}),un=e.Record({block_index:e.Nat64,ledger_id:e.Principal}),dn=e.Record({owner:e.Principal,subaccount:e.Opt(e.Vec(e.Nat8))}),pn=e.Record({status:Yt,updated_at:e.Nat64,created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64),purchaser:dn}),fn=e.Record({desc:e.Bool}),hn=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),mn=e.Record({order:e.Opt(fn),paginate:e.Opt(hn)}),_n=e.Record({proposal_id:e.Nat}),Zt=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(_n,Ze)),items_length:e.Nat64}),ke=e.Variant({Orbiter:e.Null,Satellite:e.Null}),yn=e.Record({segment_id:e.Opt(e.Principal),segment_kind:e.Opt(ke)}),Xt=e.Record({user:e.Principal,segment_id:e.Principal,segment_kind:ke}),rt=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),segment_id:e.Principal,created_at:e.Nat64}),Ys=e.Record({openid:e.Opt(b),version:e.Opt(e.Nat64),internet_identity:e.Opt(N),rules:e.Opt(C)}),Zs=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:zt,expires_at:e.Opt(e.Nat64)}),Xs=e.Record({controller:Zs,controllers:e.Vec(e.Principal)}),Qs=e.Record({fee_cycles:Kt,fee_icp:e.Opt(t)}),ea=e.Record({metadata:e.Opt(e.Vec(e.Tuple(e.Text,e.Text))),segment_id:e.Principal,segment_kind:ke}),ta=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),segment_id:e.Principal,segment_kind:ke}),ra=e.Record({iframe:e.Opt(L),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(A),raw_access:e.Opt(P),redirects:e.Opt(e.Vec(e.Tuple(e.Text,V)))}),na=e.Record({segment_id:e.Principal,segment_kind:ke}),oa=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),ia=e.Record({chunk_id:e.Nat});return e.Service({add_credits:e.Func([e.Principal,t],[],[]),add_invitation_code:e.Func([e.Text],[],[]),assert_mission_control_center:e.Func([r],[],[]),authenticate:e.Func([o],[m],[]),commit_proposal:e.Func([x],[e.Null],[]),commit_proposal_asset_upload:e.Func([y],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(y)],[],[]),count_proposals:e.Func([],[e.Nat64],[]),create_mission_control:e.Func([T],[e.Principal],[]),create_orbiter:e.Func([E],[e.Principal],[]),create_satellite:e.Func([v],[e.Principal],[]),del_controllers:e.Func([w],[],[]),del_custom_domain:e.Func([e.Text],[],[]),delete_proposal_assets:e.Func([I],[],[]),get_account:e.Func([],[e.Opt(p)],[]),get_auth_config:e.Func([],[e.Opt(B)],[]),get_config:e.Func([],[q],[]),get_create_orbiter_fee:e.Func([te],[e.Opt(t)],[]),get_create_satellite_fee:e.Func([te],[e.Opt(t)],[]),get_credits:e.Func([],[t],[]),get_delegation:e.Func([J],[oe],[]),get_fee:e.Func([re],[Wr],[]),get_or_init_account:e.Func([],[p],[]),get_proposal:e.Func([e.Nat],[e.Opt(Ze)],[]),get_rate_config:e.Func([re],[$t],[]),get_storage_config:e.Func([],[D],[]),http_request:e.Func([Xr],[et],[]),http_request_streaming_callback:e.Func([Xe],[Gt],[]),init_proposal:e.Func([Ht],[e.Nat,Ze],[]),init_proposal_asset_upload:e.Func([tt,e.Nat],[Jt],[]),init_proposal_many_assets_upload:e.Func([e.Vec(tt),e.Nat],[e.Vec(e.Tuple(e.Text,Jt))],[]),list_accounts:e.Func([],[e.Vec(e.Tuple(e.Principal,p))],[]),list_assets:e.Func([e.Text,_t],[sn],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,an))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,cn))],[]),list_icp_payments:e.Func([],[e.Vec(e.Tuple(e.Nat64,ln))],[]),list_icrc_payments:e.Func([],[e.Vec(e.Tuple(un,pn))],[]),list_proposals:e.Func([mn],[Zt],[]),list_segments:e.Func([yn],[e.Vec(e.Tuple(Xt,rt))],[]),reject_proposal:e.Func([x],[e.Null],[]),set_auth_config:e.Func([Ys],[B],[]),set_controllers:e.Func([Xs],[],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_fee:e.Func([re,Qs],[],[]),set_rate_config:e.Func([re,$t],[],[]),set_segment:e.Func([ea],[rt],[]),set_segment_metadata:e.Func([ta],[rt],[]),set_storage_config:e.Func([ra],[D],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Ze],[]),unset_segment:e.Func([na],[],[]),upload_proposal_asset_chunk:e.Func([oa],[ia],[])})};var ry=async({identity:e,host:t,localActor:r})=>await br.create({identity:e,host:t,retryTimes:10,shouldFetchRootKey:r}),ny=async({agent:e,...t})=>e??await oy(t),oy=async({identity:e,container:t})=>{let r=z(t)&&t!==!1;return await ry({identity:e,host:r?t===!0?"http://127.0.0.1:5987":t:"https://icp-api.io",localActor:r})};var tp=({satelliteId:e,certified:t=!1,...r})=>np({canisterId:e,...r,idlFactory:t?Mc:qc});var rp=({consoleId:e,certified:t=!1,...r})=>np({canisterId:e,...r,idlFactory:t?ty:ey}),np=({canisterId:e,idlFactory:t,...r})=>{if(k(e))throw new Error("No canister ID provided.");return iy({canisterId:e,idlFactory:t,...r})},iy=async({canisterId:e,idlFactory:t,config:r,...n})=>{let o=await ny(n);return po.createActor(t,{agent:o,canisterId:e,...r??{}})};var op=({satelliteId:e,container:t})=>{let{satelliteId:r}=jc({satelliteId:e}),{container:n}=Kc({container:t});if(z(n)&&n!==!1){let{host:o,protocol:i}=new URL(n===!0?ho:n);return`${i}//${r??"unknown"}.${o.replace("127.0.0.1","localhost")}`}return`https://${r??"unknown"}.icp0.io`},jc=({satelliteId:e})=>z(e)?{satelliteId:e}:Se.getInstance().get()??{satelliteId:void 0},Kc=({container:e})=>z(e)?{container:e}:Se.getInstance().get()??{container:void 0};var we=({satellite:e,options:{certified:t}})=>sp({idlFactory:t?Mc:qc,actorKey:`stock#${t?"update":"query"}`,...e}),ip=({idlFactory:e,...t})=>sp({idlFactory:e,actorKey:"extended#query",...t}),sp=async({satelliteId:e,container:t,...r})=>{let{satelliteId:n}=jc({satelliteId:e});si(n,"No satellite ID defined. Did you initialize Juno?");let{container:o}=Kc({container:t});return await _o.getInstance().getActor({satelliteId:n,container:o,...r})};var As=class extends Error{},Or=class extends Error{},Ss=class extends Error{},Cs=class extends Error{},Fs=class extends Error{},Ps=class extends Error{},Vs=class extends Error{},Bs=class extends Error{},Ds=class extends Error{};var ap=e=>{if(k(e))return se();switch(e.matcher){case"equal":return se({Equal:e.timestamp});case"greaterThan":return se({GreaterThan:e.timestamp});case"lessThan":return se({LessThan:e.timestamp});case"between":return se({Between:[e.timestamps.start,e.timestamps.end]});default:throw new Ds("Invalid list matcher for timestamp",e)}},Jr=({matcher:e,paginate:t,order:r,owner:n})=>({matcher:k(e)?[]:[{key:se(e.key),description:se(e.description),created_at:ap(e.createdAt),updated_at:ap(e.updatedAt)}],paginate:se(k(t)?void 0:{start_after:se(t.startAfter),limit:se(k(t.limit)?void 0:BigInt(t.limit))}),order:se(k(r)?void 0:{desc:r.desc,field:r.field==="created_at"?{CreatedAt:null}:r.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:se(k(n)?void 0:typeof n=="string"?U.fromText(n):n)});var cp=async e=>{let t=new Blob([JSON.stringify(e,Ed)],{type:"application/json; charset=utf-8"});return new Uint8Array(await t.arrayBuffer())},Us=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(),Rd)},ks=()=>typeof window<"u";var lp=async({data:e})=>{try{return await Us(e)}catch(t){console.error("The data parsing has failed, mapping to undefined as a fallback.",t);return}};var Hc=async e=>{let{data:t,version:r,description:n}=e;return{description:se(n),data:await cp(t),version:se(r)}},$c=e=>{let{version:t}=e;return{version:se(t)}},qn=async({doc:e,key:t})=>{let{owner:r,version:n,description:o,data:i,...s}=e;return{key:t,description:be(o),owner:r.toText(),data:await Us(i),version:be(n),...s}};var up=async({collection:e,key:t,...r})=>{let{get_doc:n}=await we(r),o=be(await n(e,t));if(!k(o))return qn({doc:o,key:t})},dp=async({docs:e,...t})=>{let{get_many_docs:r}=await we(t),n=e.map(({collection:s,key:a})=>[s,a]),o=await r(n),i=[];for(let[s,a]of o){let c=be(a);i.push(z(c)?await qn({key:s,doc:c}):void 0)}return i},pp=async({collection:e,doc:t,...r})=>{let{set_doc:n}=await we(r),{key:o}=t,i=await Hc(t),s=await n(e,o,i);return await qn({key:o,doc:s})},fp=async({docs:e,...t})=>{let{set_many_docs:r}=await we(t),n=[];for(let{collection:s,doc:a}of e){let{key:c}=a;n.push([s,c,await Hc(a)])}let o=await r(n),i=[];for(let[s,a]of o)i.push(await qn({key:s,doc:a}));return i},hp=async({collection:e,doc:t,...r})=>{let{del_doc:n}=await we(r),{key:o}=t;return n(e,o,$c(t))},mp=async({docs:e,...t})=>{let{del_many_docs:r}=await we(t),n=e.map(({collection:o,doc:i})=>[o,i.key,$c(i)]);await r(n)},_p=async({collection:e,filter:t,...r})=>{let{del_filtered_docs:n}=await we(r);return n(e,Jr(t))},yp=async({collection:e,filter:t,...r})=>{let{list_docs:n}=await we(r),{items:o,items_page:i,items_length:s,matches_length:a,matches_pages:c}=await n(e,Jr(t)),u=[];for(let[p,d]of o){let{data:l,owner:f,description:h,version:_,...g}=d;u.push({key:p,description:be(h),owner:f.toText(),data:await lp({data:l}),version:be(_),...g})}return{items:u,items_length:s,items_page:be(i),matches_length:a,matches_pages:be(c)}},gp=async({collection:e,filter:t,...r})=>{let{count_docs:n}=await we(r);return n(e,Jr(t))};var Ls=async({satellite:e,options:t,...r})=>{let n=de(e?.identity);return await up({...r,satellite:{...e,identity:n},options:t??Mt})},fN=async({satellite:e,options:t,...r})=>{let n=de(e?.identity);return await dp({...r,satellite:{...e,identity:n},options:t??Mt})},xp=async({satellite:e,...t})=>{let r=de(e?.identity);return await pp({...t,satellite:{...e,identity:r},options:{certified:!0}})},bp=async({satellite:e,...t})=>{let r=de(e?.identity);return await fp({...t,satellite:{...e,identity:r},options:{certified:!0}})},hN=async({satellite:e,...t})=>{let r=de(e?.identity);return await hp({...t,satellite:{...e,identity:r},options:{certified:!0}})},mN=async({satellite:e,...t})=>{let r=de(e?.identity);return await mp({...t,satellite:{...e,identity:r},options:{certified:!0}})},_N=async({satellite:e,filter:t,...r})=>{let n=de(e?.identity);return await _p({...r,filter:t??{},satellite:{...e,identity:n},options:{certified:!0}})},yN=async({satellite:e,options:t,filter:r,...n})=>{let o=de(e?.identity);return await yp({...n,filter:r??{},satellite:{...e,identity:o},options:t??Mt})},gN=async({satellite:e,options:t,filter:r,...n})=>{let o=de(e?.identity);return await gp({...n,filter:r??{},satellite:{...e,identity:o},options:t??Mt})};var wp=async({provider:e})=>{let{user:t,userId:r}=await qs();if(z(t))return t;try{return await sy({userId:r,provider:e})}catch(n){if(Lc({error:n,type:ep})){let o=await Tp({userId:r});if(z(o))return o}throw n}},qs=async()=>{let e=vs();if(k(e))throw new Bs("No identity to initialize the user. Have you initialized Juno?");let t=e.getPrincipal().toText(),r=await Tp({userId:t});return{userId:t,user:r}},Tp=({userId:e})=>Ls({collection:"#user",key:e}),sy=({userId:e,...t})=>xp({collection:"#user",doc:{key:e,data:t}});var Ms=async({syncTabsOnSuccess:e}={syncTabsOnSuccess:!1})=>{await hi({fn:async()=>{let{user:r}=await qs();De.getInstance().set(r??null)},syncTabsOnSuccess:e})},Np=async()=>{await Qd({fn:async({authenticated:t})=>{let n=t?qs:()=>Promise.resolve({user:null}),{user:o}=await n();De.getInstance().set(o??null)}})},js=async({user:e})=>{await hi({fn:async()=>{De.getInstance().set(e)},syncTabsOnSuccess:!0})};var Op=()=>{try{let e=yo.getInstance(),t=async()=>{await Np(),ci({message:"junoSignInReload"})};return e.onLoginSuccess(t),()=>{e?.destroy()}}catch(e){console.warn("Auth BroadcastChannel initialization failed",e);return}};var Ep=()=>{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()},Rp=()=>{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()},Ip=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_GOOGLE_CLIENT_ID??import.meta.env?.PUBLIC_GOOGLE_CLIENT_ID:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID??e():e()};var vp=BigInt(144e11),Ap=!1,Sp={width:576,height:576},Cp={width:424,height:576};var mi="internetcomputer.org",Fp="ic0.app",Pp="id.ai";var Vp=({width:e,height:t})=>{if(!ks()||k(window)||k(window.top))return;let{top:{innerWidth:r,innerHeight:n}}=window,o=n/2+screenY-t/2,i=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=${i}`};var jt=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 Bp=(r=>(r[r.AuthorizingWithProvider=0]="AuthorizingWithProvider",r[r.CreatingOrRetrievingUser=1]="CreatingOrRetrievingUser",r))(Bp||{});var Ks=class{async signIn({options:t,authClient:r,initAuth:n}){await jt({fn:async()=>await this.#e({options:t,authClient:r}),step:0,onProgress:t?.onProgress}),await jt({fn:async()=>await n({provider:this.id}),step:1,onProgress:t?.onProgress})}#e({options:t,authClient:r}){return new Promise(async(n,o)=>{if(k(r)){o(new Or("No client is ready to perform a sign-in. Have you initialized the Satellite?"));return}await r.login({onSuccess:n,onError:i=>{if(i===Is){o(new Ss(i));return}o(new As(i))},maxTimeToLive:t?.maxTimeToLiveInNanoseconds??vp,allowPinAuthentication:t?.allowPin??Ap,...t?.derivationOrigin!==void 0&&{derivationOrigin:t.derivationOrigin},...this.signInOptions({windowed:t?.windowed})})})}};var Hs=class extends Ks{#e;constructor({domain:t}){super(),this.#e=t}get id(){return"internet_identity"}signInOptions({windowed:t}){let n=(()=>{let i=Se.getInstance().get()?.container;if(k(i)||i===!1){let p=[mi,Fp].includes(this.#e??mi);return Ln(this.#e)?`https://identity.${mi}`:p?`https://identity.${this.#e??mi}`:`https://${this.#e}`}let s=Se.getInstance().get(),a=z(s)&&z(s?.internetIdentityId)?s.internetIdentityId:Bd,{host:c,protocol:u}=new URL(i===!0?ho:i);return/apple/i.test(navigator?.vendor)?`${u}//${c}?canisterId=${a}`:`${u}//${a}.${c.replace("127.0.0.1","localhost")}`})();return{...t!==!1&&{windowOpenerFeatures:Vp((()=>{try{let{hostname:i}=new URL(n);return i.includes(Pp)}catch{return!1}})()?Cp:Sp)},identityProvider:n}}};var Gc=class extends Error{},Jc=class extends Error{},Wc=class extends Error{},zc=class extends Error{},Yc=class extends Error{},Zc=class extends Error{},Xc=class extends Error{},$s=class extends Error{},Qc=class extends Error{},el=class extends Error{};var Gs=e=>Hr(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),go=({url:e})=>{try{return new URL(e)}catch{throw new Gc("Cannot parse authURL",{cause:e})}};var Dp=({initUrl:e})=>async({nonce:t})=>{let r=go({url:e});r.searchParams.set("nonce",t);let{state:n}=await fetch(r.toString(),{credentials:"include"}).then(o=>o.json());return n};var ay=()=>Gs(window.crypto.getRandomValues(new Uint8Array(12))),Up=async e=>ay();var kp=({authUrl:e,clientId:t,authScopes:r,state:n,redirectUrl:o})=>{let i=go({url:e});i.searchParams.set("client_id",t);let{location:{origin:s}}=window;i.searchParams.set("redirect_uri",o??s),i.searchParams.set("scope",r.join(" ")),i.searchParams.set("state",n),window.location.href=i.toString()};var Lp=({authUrl:e,clientId:t,nonce:r,loginHint:n,authScopes:o,state:i,redirectUrl:s})=>{let a=go({url:e});a.searchParams.set("client_id",t);let{location:{origin:c}}=window;a.searchParams.set("redirect_uri",s??c),a.searchParams.set("response_type","code id_token"),a.searchParams.set("scope",o.join(" ")),a.searchParams.set("state",i),a.searchParams.set("nonce",r),ii(n)?a.searchParams.set("login_hint",n):a.searchParams.set("prompt","select_account"),window.location.href=a.toString()},qp=async({configUrl:e,clientId:t,nonce:r,loginHint:n,domainHint:o})=>{let i=await navigator.credentials.get({identity:{context:"use",providers:[{configURL:e,clientId:t,nonce:r,loginHint:n,domainHint:o}],mode:"active"},mediation:"required"});if(k(i))throw new Wc;let{type:s}=i;if(s!=="identity"||!("token"in i)||typeof i.token!="string")throw new zc("Invalid credential received from FedCM API",{cause:i});let{token:a}=i;return{jwt:a}};var tl="juno:auth:openid",rl={authUrl:"https://accounts.google.com/o/oauth2/v2/auth",authScopes:["openid","profile","email"],configUrl:"https://accounts.google.com/gsi/fedcm.json"},Mp={authUrl:"http://accounts.google.com/o/o/oauth2/v2/auth",authScopes:["read:user","repo"],initUrl:"http://localhost:3000/v1/auth/init/github",finalizeUrl:"http://localhost:3000/v1/auth/finalize/github"};var cy=()=>window.crypto.getRandomValues(new Uint8Array(32)),ly=async({salt:e,caller:t})=>{let r=t.getPrincipal().toUint8Array(),n=new Uint8Array(e.length+r.byteLength);n.set(e),n.set(r,e.length);let o=await window.crypto.subtle.digest("SHA-256",n);return Gs(wr(o))},uy=async({caller:e})=>{let t=cy();return{nonce:await ly({salt:t,caller:e}),salt:t}},jp="__caller__",Kp="__salt__",Hp="__state__",dy=({caller:e,state:t,salt:r})=>{let n={[jp]:e.toJSON(),[Kp]:Hr(r),[Hp]:t};return JSON.stringify(n)},py=e=>{let{[jp]:t,[Kp]:r,[Hp]:n}=JSON.parse(e);return{caller:vt.fromParsedJson(t),salt:Od(r),state:n}},nl=async({generateState:e})=>{let t=vt.generate(),{nonce:r,salt:n}=await uy({caller:t}),o=await e({nonce:r}),i=dy({caller:t,salt:n,state:o});return sessionStorage.setItem(tl,i),{nonce:r,state:o}},$p=()=>{let e=sessionStorage.getItem(tl);if(k(e))throw new Jc;return py(e)};async function ol(e){if("github"in e){let{github:s}=e,{redirect:a}=s,{initUrl:c,...u}=a,{authUrl:p,authScopes:d,initUrl:l}=Mp,f=await nl({generateState:Dp({initUrl:c??l})});kp({...u,...f,authUrl:p,authScopes:d});return}let t=await nl({generateState:Up}),{google:r}=e;if("credentials"in r){let{credentials:s}=r,{configUrl:a}=rl;return await qp({...s,...t,configUrl:a})}let{redirect:n}=r,{authUrl:o,authScopes:i}=rl;Lp({...n,...t,authUrl:o,authScopes:i})}var Gp=({auth:e,identity:t})=>"satellite"in e?tp({...e.satellite,identity:t}):rp({...e.console,identity:t}),fy=async({actorParams:e,args:t})=>{let{authenticate:r}=await Gp(e);return await r(t)},hy=async({actorParams:e,args:t})=>{let{get_delegation:r}=await Gp(e);return await r(t)},my=({delegations:e,sessionKey:t})=>{let[r,n]=e,o=Tr.fromDelegations(n,Uint8Array.from(r));return{identity:Nr.fromDelegation(t,o),delegationChain:o,sessionKey:t}},Js=async({jwt:e,context:t,auth:r})=>{let n=await kt.generate({extractable:!1}),o=new Uint8Array(n.getPublicKey().toDer()),{delegations:i,data:s}=await _y({jwt:e,publicKey:o,context:t,auth:r});return{identity:my({sessionKey:n,delegations:i}),data:s}},_y=async({jwt:e,publicKey:t,context:{caller:r,salt:n},auth:o})=>{let i=await fy({args:{OpenId:{jwt:e,session_key:t,salt:n}},actorParams:{auth:o,identity:r}});if("Err"in i)throw new Yc("Authentication failed",{cause:i});let{delegation:{user_key:s,expiration:a},...c}=i.Ok,u=await yy({jwt:e,context:{caller:r,salt:n},auth:o,publicKey:t,expiration:a}),{delegation:p,signature:d}=u,{pubkey:l,expiration:f,targets:h}=p;return{delegations:[s,[{delegation:new Gr(Uint8Array.from(l),f,be(h)),signature:Uint8Array.from(d)}]],data:c}},yy=async({jwt:e,publicKey:t,context:{salt:r,caller:n},auth:o,expiration:i,maxRetries:s=5})=>{for(let a=0;a<s;a++){await new Promise(u=>{setInterval(u,1e3*a)});let c=await hy({args:{OpenId:{jwt:e,session_key:t,salt:r,expiration:i}},actorParams:{auth:o,identity:n}});if("Err"in c){let{Err:u}=c;if("NoSuchDelegation"in u||"GetCachedJwks"in u)continue;throw new Qc("Getting delegation failed",{cause:c})}return c.Ok}throw new el};var il=async e=>{let t=$p();if("github"in e){let{github:n}=e;return await xy({...n,context:t})}let{google:r}=e;if("credentials"in r){let{credentials:{jwt:n},auth:o}=r;return await Js({jwt:n,context:t,auth:o})}return await gy({...r,context:t})},gy=async({auth:e,context:t})=>{let{location:{hash:r}}=window;if(Ln(r)||!r.startsWith("#"))throw new Zc("No hash found in the current location URL");let n=new URLSearchParams(r.slice(1)),o=n.get("state"),i=n.get("id_token"),{state:s}=t;if(Ln(s)||o!==s)throw new Xc("The provided state is invalid",{cause:o});if(Ln(i))throw new $s;return await Js({jwt:i,auth:e,context:t})},xy=async({auth:e,context:t,redirect:{finalizeUrl:r}})=>{let{location:{search:n}}=window,o=new URLSearchParams(n),i=o.get("code"),s=o.get("state"),{token:a}=await fetch(r,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:i,state:s})}).then(c=>c.json());if(Ln(a))throw new $s;return await Js({jwt:a,auth:e,context:t})};var by=async()=>{let{satelliteId:e}=Se.getInstance().get()??{satelliteId:void 0};if(k(e))throw new Or("Satellite ID not set. Have you initialized the Satellite?");let t=Se.getInstance().get()?.container,{identity:{delegationChain:r,sessionKey:n,identity:o},data:{doc:i}}=await il({google:{redirect:null,auth:{satellite:{satelliteId:e,container:t}}}});await Ue.getInstance().setAuthClientStorage({delegationChain:r,sessionKey:n});let s=await qn({doc:i,key:o.getPrincipal().toText()});await js({user:s})};var Jp=e=>(e.preventDefault(),e.returnValue="Are you sure you want to exit?"),wy=()=>{window.addEventListener("beforeunload",Jp,{capture:!0})},Ty=()=>{window.removeEventListener("beforeunload",Jp,{capture:!0})},Ws=async({fn:e})=>{try{return wy(),await e()}finally{Ty()}};var zs=class{async signIn({options:t={}}){let r=t?.redirect?.clientId??Ip();if(k(r))throw new Fs;let{redirect:n}=t;await ol({google:{redirect:{...n??{},clientId:r}}})}};var Wp=async({delegationIdentity:e,passkeyIdentity:t,satelliteId:r})=>{let n=t.getCredential().getAAGUID(),[o,i]=await bp({docs:[{collection:"#user",doc:{key:e.getPrincipal().toText(),data:{provider:"webauthn",providerData:{webauthn:{...z(n)&&{aaguid:Ts(n)}}}}}},{collection:"#user-webauthn",doc:{key:t.getCredential().getCredentialIdText(),data:{publicKey:t.getPublicKey().toRaw()}}}],satellite:{identity:e,satelliteId:r}});return o};var zp=(i=>(i[i.RequestingUserCredential=0]="RequestingUserCredential",i[i.FinalizingCredential=1]="FinalizingCredential",i[i.Signing=2]="Signing",i[i.FinalizingSession=3]="FinalizingSession",i[i.RetrievingUser=4]="RetrievingUser",i))(zp||{}),Yp=(s=>(s[s.CreatingUserCredential=0]="CreatingUserCredential",s[s.ValidatingUserCredential=1]="ValidatingUserCredential",s[s.FinalizingCredential=2]="FinalizingCredential",s[s.Signing=3]="Signing",s[s.FinalizingSession=4]="FinalizingSession",s[s.RegisteringUser=5]="RegisteringUser",s))(Yp||{});var xo=class{async signUp({options:{onProgress:t,maxTimeToLiveInMilliseconds:r,passkey:n}={},loadAuthWithUser:o}){let{satelliteId:i}=Se.getInstance().get()??{satelliteId:void 0};if(k(i))throw new Or("Satellite ID not set. Have you initialized the Satellite?");let s=({step:_,state:g})=>{switch(_){case $r.RequestingUserCredential:t?.({step:1,state:g});break;case $r.FinalizingCredential:t?.({step:2,state:g});break;case $r.Signing:t?.({step:3,state:g});break}},c=await jt({fn:async()=>await Rc.createWithNewCredential({onProgress:s,passkeyOptions:n}),step:0,onProgress:t}),{delegationIdentity:u,sessionKey:p}=await this.#e({identity:c,maxTimeToLiveInMilliseconds:r}),l=await jt({fn:async()=>await Wp({delegationIdentity:u,passkeyIdentity:c,satelliteId:i}),step:5,onProgress:t});await jt({fn:async()=>await this.#t({delegationIdentity:u,sessionKey:p}),step:4,onProgress:t}),await jt({fn:async()=>await o({user:l}),step:5,onProgress:t})}async signIn({options:{onProgress:t,maxTimeToLiveInMilliseconds:r}={},loadAuth:n}){let{satelliteId:o}=Se.getInstance().get()??{satelliteId:void 0};if(k(o))throw new Or("Satellite ID not set. Have you initialized the Satellite?");let i=async({credentialId:d})=>{let l=await Ls({collection:"#user-webauthn",key:Hr(d),options:{certified:!0},satellite:{identity:new ot,satelliteId:o}});if(k(l))throw new Ps("No public key found for the selected passkey.");let{data:f}=l,{publicKey:h}=f;return kn(h,ni)},s=({step:d,state:l})=>{switch(d){case $r.RequestingUserCredential:t?.({step:0,state:l});break;case $r.FinalizingCredential:t?.({step:1,state:l});break;case $r.Signing:t?.({step:2,state:l});break}},a=await Rc.createWithExistingCredential({retrievePublicKey:i,onProgress:s}),{delegationIdentity:c,sessionKey:u}=await this.#e({identity:a,maxTimeToLiveInMilliseconds:r});await jt({fn:async()=>await this.#t({delegationIdentity:c,sessionKey:u}),step:3,onProgress:t}),await jt({fn:n,step:4,onProgress:t})}async#e({identity:t,maxTimeToLiveInMilliseconds:r}){let n=await kt.generate({extractable:!1}),o=r??144e5,i=await Tr.create(t,n.getPublicKey(),new Date(Date.now()+o));return{delegationIdentity:Nr.fromDelegation(n,i),sessionKey:n}}async#t({sessionKey:t,delegationIdentity:r}){let n=new qt;await Promise.all([n.set(We,t.getKeyPair()),n.set(Je,JSON.stringify(r.getDelegation().toJSON()))])}};var Oy=async({provider:e})=>{await hi({fn:async()=>{let r=await wp({provider:e});De.getInstance().set(r)},syncTabsOnSuccess:!0})},Ey=async e=>{if("google"in e){let{google:{options:t}}=e;await sl({fn:()=>new zs().signIn({options:t}),context:{windowGuard:!1}});return}if("webauthn"in e){let{webauthn:{options:t,context:r}}=e;await sl({fn:()=>new xo().signIn({options:t,loadAuth:()=>Ms({syncTabsOnSuccess:!0})}),context:r});return}if("internet_identity"in e){let{internet_identity:{options:t,context:r}}=e,{domain:n,...o}=t??{};await sl({fn:()=>new Hs({domain:n}).signIn({options:o,authClient:Ue.getInstance().getAuthClient(),initAuth:Oy}),context:r});return}throw new Cs("An unknown or unsupported provider was provided for sign-in.")},sl=async({fn:e,context:t})=>{if(t?.windowGuard===!1){await e();return}await Ws({fn:e})};var Ry=async e=>{let t=async()=>await Iy(e);if(Object.values(e)?.[0].context?.windowGuard===!1){await t();return}await Ws({fn:t})},Iy=async e=>{if("webauthn"in e){let{webauthn:{options:t}}=e;await new xo().signUp({options:t,loadAuthWithUser:js});return}throw new Vs("An unknown or unsupported provider was provided for sign-up.")};var o1=e=>e?.data?.provider==="webauthn",i1=e=>e?.data?.provider==="google";var l1=async({idlFactory:e,satellite:t})=>{let r=de(t?.identity);return await ip({idlFactory:e,...t,identity:r})};var Zp=async({asset:{data:e,headers:t,...r},actor:n,progress:o})=>{let{init_asset_upload:i,upload_asset_chunk:s,commit_asset_upload:a}=n,{batch_id:c}=await i(vy(r));o?.onInitiatedBatch();let{chunkIds:u}=await Cy({data:e,uploadFn:s,batchId:c});o?.onUploadedFileChunks(r.fullPath),await Sy({commitFn:a,batchId:c,data:e,headers:t,chunkIds:u}),o?.onCommittedBatch()};var vy=({filename:e,collection:t,token:r,fullPath:n,encoding:o,description:i})=>({collection:t,full_path:n,name:e,token:se(r),encoding_type:se(o),description:se(i)}),Ay=({batchId:e,chunkIds:t,headers:r,data:n})=>{let o=r.find(([i,s])=>i.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:i})=>i),headers:[...r,...o??[]]}},Sy=async({commitFn:e,...t})=>{let r=Ay(t);await e(r)},Cy=async({data:e,uploadFn:t,batchId:r})=>{let n=[],o=ks()?new Blob([await e.arrayBuffer()]):e,i=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:i}),i++}let s=[];for await(let a of Fy({uploadChunks:n}))s=[...s,...a];return{chunkIds:s}};async function*Fy({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=>Py(o)))}}var Py=async({batchId:e,chunk:t,uploadFn:r,orderId:n})=>r({batch_id:e,content:new Uint8Array(await t.arrayBuffer()),order_id:se(n)});var Xp=async({asset:e,...t})=>{let r=await we(t);await Zp({actor:r,asset:e})},Qp=async({collection:e,filter:t,...r})=>{let{list_assets:n}=await we(r),{items:o,items_length:i,items_page:s,matches_length:a,matches_pages:c}=await n(e,Jr(t));return{items:o.map(([u,p])=>p),items_length:i,items_page:be(s),matches_length:a,matches_pages:be(c)}},ef=async({collection:e,filter:t,...r})=>{let{count_assets:n}=await we(r);return n(e,Jr(t))},tf=async({collection:e,fullPath:t,...r})=>(await we(r)).del_asset(e,t),rf=async({assets:e,satellite:t})=>{let{del_many_assets:r}=await we({satellite:t,options:{certified:!0}}),n=e.map(({collection:o,fullPath:i})=>[o,i]);await r(n)},nf=async({collection:e,filter:t,...r})=>{let{del_filtered_assets:n}=await we(r);return n(e,Jr(t))},of=async({collection:e,fullPath:t,token:r,...n})=>{let{set_asset_token:o}=await we(n);return o(e,t,se(r))},sf=async({collection:e,fullPath:t,...r})=>{let{get_asset:n}=await we(r);return be(await n(e,t))},af=async({assets:e,...t})=>{let{get_many_assets:r}=await we(t),n=e.map(({collection:i,fullPath:s})=>[i,s]);return(await r(n)).map(([i,s])=>be(s))};var cf=e=>btoa([...e].map(t=>String.fromCharCode(t)).join(""));var R1=e=>lf(e),I1=e=>lf({filename:e.data.name,...e}),lf=async({filename:e,data:t,collection:r,headers:n=[],fullPath:o,token:i,satellite:s,encoding:a,description:c})=>{let u=de(s?.identity),p=decodeURI(e),d=o??`/${r}/${p}`,l={...s,identity:u};return await Xp({asset:{data:t,filename:p,collection:r,token:i,headers:n,fullPath:d,encoding:a,description:c},satellite:l,options:{certified:!0}}),{downloadUrl:uf({satellite:l,assetKey:{fullPath:d,token:i}}),fullPath:d,...z(i)&&{token:i},name:p}},v1=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:de(r?.identity)},{items:i,...s}=await Qp({collection:e,filter:t??{},satellite:o,options:n??Mt}),a=i.map(({key:{full_path:c,token:u,name:p,owner:d,description:l},headers:f,encodings:h,created_at:_,updated_at:g})=>{let m=be(u);return{fullPath:c,description:be(l),name:p,downloadUrl:uf({satellite:o,assetKey:{fullPath:c,token:m}}),token:m,headers:f,encodings:h.reduce((x,[y,{modified:T,sha256:E,total_length:O}])=>({...x,[y]:{modified:T,sha256:cf(E),total_length:O}}),{}),owner:d.toText(),created_at:_,updated_at:g}});return{items:a,assets:a,...s}},A1=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:de(r?.identity)};return await ef({collection:e,satellite:o,filter:t??{},options:n??Mt})},S1=({collection:e,fullPath:t,satellite:r})=>tf({collection:e,fullPath:t,satellite:{...r,identity:de(r?.identity)},options:{certified:!0}}),C1=({collection:e,fullPath:t,token:r,satellite:n})=>of({collection:e,fullPath:t,token:r,satellite:{...n,identity:de(n?.identity)},options:{certified:!0}}),F1=({assets:e,satellite:t})=>rf({assets:e,satellite:{...t,identity:de(t?.identity)},options:{certified:!0}}),P1=async({collection:e,satellite:t,filter:r})=>{let n={...t,identity:de(t?.identity)};return await nf({collection:e,satellite:n,filter:r??{},options:{certified:!0}})},V1=async({satellite:e,options:t,...r})=>{let n=de(e?.identity);return await sf({...r,satellite:{...e,identity:n},options:t??Mt})},B1=async({satellite:e,options:t,...r})=>{let n=de(e?.identity);return await af({...r,satellite:{...e,identity:n},options:t??Mt})},uf=({assetKey:{fullPath:e,token:t},satellite:r})=>{let n={...r,identity:de(r?.identity)};return`${op(n)}${e}${z(t)?`?token=${t}`:""}`};var Vy=e=>{let t=e?.satelliteId??Ep();si(t,"Satellite ID is not configured. Juno cannot be initialized.");let r=e?.container??Rp();return{satelliteId:t,internetIdentityId:e?.internetIdentityId,workers:e?.workers,syncTabs:e?.syncTabs,container:r}},$1=e=>By(e),By=async e=>{let t=Vy(e);Se.getInstance().set(t),await Ms();let r=t.workers?.auth!==void 0?Xd(t.workers.auth):void 0,n=t.syncTabs===!1?void 0:Op();return[...z(r)?[r]:[],...z(n)?[n]:[]]},Dy=e=>De.getInstance().subscribe(e),G1=Dy;export{Bp as AuthClientSignInProgressStep,Bs as InitError,Hs as InternetIdentityProvider,Ds as ListError,As as SignInError,Or as SignInInitError,Fs as SignInMissingClientIdError,Cs as SignInProviderNotSupportedError,Ss as SignInUserInterruptError,Vs as SignUpProviderNotSupportedError,zp as WebAuthnSignInProgressStep,Ps as WebAuthnSignInRetrievePublicKeyError,Yp as WebAuthnSignUpProgressStep,G1 as authSubscribe,A1 as countAssets,gN as countDocs,S1 as deleteAsset,hN as deleteDoc,P1 as deleteFilteredAssets,_N as deleteFilteredDocs,F1 as deleteManyAssets,mN as deleteManyDocs,uf as downloadUrl,V1 as getAsset,Ls as getDoc,Q_ as getIdentityOnce,B1 as getManyAssets,fN as getManyDocs,l1 as getSatelliteExtendedActor,by as handleRedirectCallback,$1 as initJuno,By as initSatellite,i1 as isGoogleUser,E_ as isWebAuthnAvailable,o1 as isWebAuthnUser,v1 as listAssets,yN as listDocs,Dy as onAuthStateChange,C1 as setAssetToken,xp as setDoc,bp as setManyDocs,Ey as signIn,kc as signOut,Ry as signUp,X_ as unsafeIdentity,R1 as uploadBlob,I1 as uploadFile};
55
55
  /*! Bundled license information:
56
56
 
57
57
  @noble/hashes/esm/utils.js: