@fireproof/core 0.19.114 → 0.19.115

Sign up to get free protection for your applications and to get access to all the features.
package/index.global.js CHANGED
@@ -144,6 +144,6 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
144
144
  `).map(n=>n.trim())))):this._attributes.error=G(""+e),this}WithLevel(e){return this._attributes.level=G(e),this}Ref(e,t){return typeof t=="function"?this._attributes[e]=G(t):typeof t.toString=="function"?this._attributes[e]=G(()=>t.toString()):this._attributes[e]=G("INVALID REF"),this}Bool(e,t){return this.coerceKey(e,!!t),this}Http(...e){let t=e.find(a=>typeof a=="string");e=e.filter(a=>typeof a!="string");let n=e.filter(a=>C.Is(a)&&a.isErr());if(n.length)return this.Err(n.map(a=>a.Err().message).join(`
145
145
  `)),this;let s=e.map(a=>C.Is(a)?a.Ok():a).find(a=>typeof a.status!="number"),o=e.map(a=>C.Is(a)?a.Ok():a).find(a=>typeof a.status=="number"),i;return o&&s?i={res:o,req:s}:!o&&!s?i=void 0:o?i=o:s&&(i=s),i&&this.Any(t||"Http",i),this}Pair(e){for(let t of Object.keys(e)){let n=e[t];if(n instanceof we){this._attributes[t]=n;continue}if(C.Is(n)){this.Result(t,n);continue}this.Any(t,n)}return this}Result(e,t){return t.isOk()?this._attributes[e]=G(t.Ok()):this.Err(t.Err()),this}Len(e,t="len"){return this._attributes[t]=iy(e),this}Hash(e,t="hash"){return this._attributes[t]=b1(async()=>`${iy(e).value()}:${await T1(e)}`),this}Url(e,t="url"){return this.Ref(t,()=>Ie.from(e).toString()),this}coerceKey(e,t){typeof e=="string"?this._attributes[e]=G(t):this.Pair(e)}Str(e,t){return this.coerceKey(e,t),this}Any(e,t){return this.coerceKey(e,t),this}Dur(e,t){return this._attributes[e]=G(`${t}ms`),this}Uint64(e,t){return this.coerceKey(e,t),this}Int(e,t){return this.Uint64(e,t)}async Flush(){return new Promise(e=>{this._logWriter._flush(void 0,e)})}With(){return new _1(new my({logWriter:this._logWriter,sys:this._sys,levelHandler:this._levelHandler,formatter:this._formatter,withAttributes:Jt({module:this._attributes.module},this._withAttributes)}))}_resetAttributes(e){let t=e();return Object.keys(this._attributes).forEach(n=>{delete this._attributes[n]}),Object.assign(this._attributes,this._withAttributes),t}Msg(...e){let t=this._resetAttributes(()=>{var s,o;let i=this._levelHandler.isEnabled((s=ay(this._attributes.level))==null?void 0:s.value(),(o=ay(this._attributes.module))==null?void 0:o.value());this._attributes.msg=G(e.join(" "));let a=this._attributes.msg.value();typeof a=="string"&&!a.trim().length&&delete this._attributes.msg;let c=()=>this._formatter.format(Jt({},this._attributes));if(i){let l=c();this._logWriter.write(l),c=()=>l}return c}),n=()=>new Error(this._txtEnDe.decode(t()));return{ResultError:()=>C.Err(n()),AsError:n}}},_1=class{constructor(r){this._li=r}TxtEnDe(){return this._li.TxtEnDe()}Logger(){return Object.assign(this._li._withAttributes,this._li._attributes),this._li}Attributes(){return Jt({},this._li._attributes)}SetExposeStack(r){return this._li._levelHandler.setExposeStack(r),this}SetFormatter(r){return this._li.SetFormatter(r),this}EnableLevel(r,...e){return this._li._levelHandler.enableLevel(r,...e),this}DisableLevel(r,...e){return this._li._levelHandler.enableLevel(r,...e),this}Module(r){return this._li.Module(r),this}SetDebug(...r){return this._li.SetDebug(...r),this}Http(...r){return this._li.Http(...r),this}Pair(r){return this._li.Pair(r),this}Str(r,e){return this._li.Str(r,e),this}Len(r,e){return this._li.Len(r,e),this}Hash(r,e){return this._li.Hash(r,e),this}Ref(r,e){return this._li.Ref(r,e),this}Bool(r,e){return this._li.Bool(r,e),this}Result(r,e){return this._li.Result(r,e),this}Url(r,e){return this._li.Url(r,e),this}Int(r,e){return this._li.Int(r,e),this}Log(){return this._li.Log(),this}WithLevel(r){return this._li.WithLevel(r),this}Error(){return this._li.Error(),this}Warn(){return this._li.Error(),this}Debug(){return this._li.Debug(),this}Err(r){return this._li.Err(r),this}Info(){return this._li.Info(),this}Timestamp(){return this._li.Timestamp(),this}Any(r,e){return this._li.Any(r,e),this}Dur(r,e){return this._li.Dur(r,e),this}Uint64(r,e){return this._li.Uint64(r,e),this}};NN=Object.keys({__packageVersion__:"xxxx"})[0]});var Kt={};K(Kt,{coerce:()=>qe,empty:()=>gy,equals:()=>hu,fromHex:()=>L1,fromString:()=>du,isBinary:()=>B1,toHex:()=>C1,toString:()=>pu});function C1(r){return r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function L1(r){let e=r.match(/../g);return e!=null?new Uint8Array(e.map(t=>parseInt(t,16))):gy}function hu(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function qe(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function B1(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function du(r){return new TextEncoder().encode(r)}function pu(r){return new TextDecoder().decode(r)}var gy,ar=A(()=>{"use strict";gy=new Uint8Array(0)});function P1(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var d=0,y=0,g=0,b=m.length;g!==b&&m[g]===0;)g++,d++;for(var x=(b-g)*u+1>>>0,k=new Uint8Array(x);g!==b;){for(var S=m[g],T=0,E=x-1;(S!==0||T<y)&&E!==-1;E--,T++)S+=256*k[E]>>>0,k[E]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,g++}for(var _=x-y;_!==x&&k[_]===0;)_++;for(var W=c.repeat(d);_<x;++_)W+=r.charAt(k[_]);return W}function p(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var d=0;if(m[d]!==" "){for(var y=0,g=0;m[d]===c;)y++,d++;for(var b=(m.length-d)*l+1>>>0,x=new Uint8Array(b);m[d];){var k=t[m.charCodeAt(d)];if(k===255)return;for(var S=0,T=b-1;(k!==0||S<g)&&T!==-1;T--,S++)k+=a*x[T]>>>0,x[T]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");g=S,d++}if(m[d]!==" "){for(var E=b-g;E!==b&&x[E]===0;)E++;for(var _=new Uint8Array(y+(b-E)),W=y;E!==b;)_[W++]=x[E++];return _}}}function h(m){var d=p(m);if(d)return d;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:p,decode:h}}var D1,N1,wy,by=A(()=>{"use strict";D1=P1,N1=D1,wy=N1});function xy(r,e){return new gu({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function jn({name:r,prefix:e,encode:t,decode:n}){return new wu(r,e,t,n)}function cr({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=wy(t,r);return jn({prefix:e,name:r,encode:n,decode:o=>qe(s(o))})}function M1(r,e,t,n){let s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),a=0,c=0,l=0;for(let u=0;u<o;++u){let f=s[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|f,a+=t,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function O1(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;o.length*t&7;)o+="=";return o}function te({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return jn({prefix:e,name:r,encode(s){return O1(s,n,t)},decode(s){return M1(s,n,t,r)}})}var mu,yu,gu,wu,it=A(()=>{"use strict";ar();by();mu=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},yu=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return xy(this,e)}},gu=class{decoders;constructor(e){this.decoders=e}or(e){return xy(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};wu=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new mu(e,t,n),this.decoder=new yu(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var ku={};K(ku,{base58btc:()=>J,base58flickr:()=>W1});var J,W1,Rr=A(()=>{"use strict";it();J=cr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),W1=cr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var cw=$((c8,aw)=>{"use strict";aw.exports=BE;function BE(r,e){for(var t=new Array(arguments.length-1),n=0,s=2,o=!0;s<arguments.length;)t[n++]=arguments[s++];return new Promise(function(a,c){t[n]=function(u){if(o)if(o=!1,u)c(u);else{for(var f=new Array(arguments.length-1),p=0;p<f.length;)f[p++]=arguments[p];a.apply(null,f)}};try{r.apply(e||null,t)}catch(l){o&&(o=!1,c(l))}})}});var hw=$(fw=>{"use strict";var za=fw;za.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&e.charAt(t)==="=";)++n;return Math.ceil(e.length*3)/4-n};var ss=new Array(64),uw=new Array(123);for(lt=0;lt<64;)uw[ss[lt]=lt<26?lt+65:lt<52?lt+71:lt<62?lt-4:lt-59|43]=lt++;var lt;za.encode=function(e,t,n){for(var s=null,o=[],i=0,a=0,c;t<n;){var l=e[t++];switch(a){case 0:o[i++]=ss[l>>2],c=(l&3)<<4,a=1;break;case 1:o[i++]=ss[c|l>>4],c=(l&15)<<2,a=2;break;case 2:o[i++]=ss[c|l>>6],o[i++]=ss[l&63],a=0;break}i>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),i=0)}return a&&(o[i++]=ss[c],o[i++]=61,a===1&&(o[i++]=61)),s?(i&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))};var lw="invalid encoding";za.decode=function(e,t,n){for(var s=n,o=0,i,a=0;a<e.length;){var c=e.charCodeAt(a++);if(c===61&&o>1)break;if((c=uw[c])===void 0)throw Error(lw);switch(o){case 0:i=c,o=1;break;case 1:t[n++]=i<<2|(c&48)>>4,i=c,o=2;break;case 2:t[n++]=(i&15)<<4|(c&60)>>2,i=c,o=3;break;case 3:t[n++]=(i&3)<<6|c,o=0;break}}if(o===1)throw Error(lw);return n-s};za.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var pw=$((u8,dw)=>{"use strict";dw.exports=Ha;function Ha(){this._listeners={}}Ha.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this};Ha.prototype.off=function(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],s=0;s<n.length;)n[s].fn===t?n.splice(s,1):++s;return this};Ha.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var n=[],s=1;s<arguments.length;)n.push(arguments[s++]);for(s=0;s<t.length;)t[s].fn.apply(t[s++].ctx,n)}return this}});var kw=$((f8,xw)=>{"use strict";xw.exports=mw(mw);function mw(r){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),t=new Uint8Array(e.buffer),n=t[3]===128;function s(c,l,u){e[0]=c,l[u]=t[0],l[u+1]=t[1],l[u+2]=t[2],l[u+3]=t[3]}function o(c,l,u){e[0]=c,l[u]=t[3],l[u+1]=t[2],l[u+2]=t[1],l[u+3]=t[0]}r.writeFloatLE=n?s:o,r.writeFloatBE=n?o:s;function i(c,l){return t[0]=c[l],t[1]=c[l+1],t[2]=c[l+2],t[3]=c[l+3],e[0]}function a(c,l){return t[3]=c[l],t[2]=c[l+1],t[1]=c[l+2],t[0]=c[l+3],e[0]}r.readFloatLE=n?i:a,r.readFloatBE=n?a:i}():function(){function e(n,s,o,i){var a=s<0?1:0;if(a&&(s=-s),s===0)n(1/s>0?0:2147483648,o,i);else if(isNaN(s))n(2143289344,o,i);else if(s>34028234663852886e22)n((a<<31|2139095040)>>>0,o,i);else if(s<11754943508222875e-54)n((a<<31|Math.round(s/1401298464324817e-60))>>>0,o,i);else{var c=Math.floor(Math.log(s)/Math.LN2),l=Math.round(s*Math.pow(2,-c)*8388608)&8388607;n((a<<31|c+127<<23|l)>>>0,o,i)}}r.writeFloatLE=e.bind(null,yw),r.writeFloatBE=e.bind(null,gw);function t(n,s,o){var i=n(s,o),a=(i>>31)*2+1,c=i>>>23&255,l=i&8388607;return c===255?l?NaN:a*(1/0):c===0?a*1401298464324817e-60*l:a*Math.pow(2,c-150)*(l+8388608)}r.readFloatLE=t.bind(null,ww),r.readFloatBE=t.bind(null,bw)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),t=new Uint8Array(e.buffer),n=t[7]===128;function s(c,l,u){e[0]=c,l[u]=t[0],l[u+1]=t[1],l[u+2]=t[2],l[u+3]=t[3],l[u+4]=t[4],l[u+5]=t[5],l[u+6]=t[6],l[u+7]=t[7]}function o(c,l,u){e[0]=c,l[u]=t[7],l[u+1]=t[6],l[u+2]=t[5],l[u+3]=t[4],l[u+4]=t[3],l[u+5]=t[2],l[u+6]=t[1],l[u+7]=t[0]}r.writeDoubleLE=n?s:o,r.writeDoubleBE=n?o:s;function i(c,l){return t[0]=c[l],t[1]=c[l+1],t[2]=c[l+2],t[3]=c[l+3],t[4]=c[l+4],t[5]=c[l+5],t[6]=c[l+6],t[7]=c[l+7],e[0]}function a(c,l){return t[7]=c[l],t[6]=c[l+1],t[5]=c[l+2],t[4]=c[l+3],t[3]=c[l+4],t[2]=c[l+5],t[1]=c[l+6],t[0]=c[l+7],e[0]}r.readDoubleLE=n?i:a,r.readDoubleBE=n?a:i}():function(){function e(n,s,o,i,a,c){var l=i<0?1:0;if(l&&(i=-i),i===0)n(0,a,c+s),n(1/i>0?0:2147483648,a,c+o);else if(isNaN(i))n(0,a,c+s),n(2146959360,a,c+o);else if(i>17976931348623157e292)n(0,a,c+s),n((l<<31|2146435072)>>>0,a,c+o);else{var u;if(i<22250738585072014e-324)u=i/5e-324,n(u>>>0,a,c+s),n((l<<31|u/4294967296)>>>0,a,c+o);else{var f=Math.floor(Math.log(i)/Math.LN2);f===1024&&(f=1023),u=i*Math.pow(2,-f),n(u*4503599627370496>>>0,a,c+s),n((l<<31|f+1023<<20|u*1048576&1048575)>>>0,a,c+o)}}}r.writeDoubleLE=e.bind(null,yw,0,4),r.writeDoubleBE=e.bind(null,gw,4,0);function t(n,s,o,i,a){var c=n(i,a+s),l=n(i,a+o),u=(l>>31)*2+1,f=l>>>20&2047,p=4294967296*(l&1048575)+c;return f===2047?p?NaN:u*(1/0):f===0?u*5e-324*p:u*Math.pow(2,f-1075)*(p+4503599627370496)}r.readDoubleLE=t.bind(null,ww,0,4),r.readDoubleBE=t.bind(null,bw,4,0)}(),r}function yw(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function gw(r,e,t){e[t]=r>>>24,e[t+1]=r>>>16&255,e[t+2]=r>>>8&255,e[t+3]=r&255}function ww(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0}function bw(r,e){return(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}});var Sw=$((exports,module)=>{"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(r){}return null}});var Ew=$(vw=>{"use strict";var sf=vw;sf.length=function(e){for(var t=0,n=0,s=0;s<e.length;++s)n=e.charCodeAt(s),n<128?t+=1:n<2048?t+=2:(n&64512)===55296&&(e.charCodeAt(s+1)&64512)===56320?(++s,t+=4):t+=3;return t};sf.read=function(e,t,n){var s=n-t;if(s<1)return"";for(var o=null,i=[],a=0,c;t<n;)c=e[t++],c<128?i[a++]=c:c>191&&c<224?i[a++]=(c&31)<<6|e[t++]&63:c>239&&c<365?(c=((c&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,i[a++]=55296+(c>>10),i[a++]=56320+(c&1023)):i[a++]=(c&15)<<12|(e[t++]&63)<<6|e[t++]&63,a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,i)),a=0);return o?(a&&o.push(String.fromCharCode.apply(String,i.slice(0,a))),o.join("")):String.fromCharCode.apply(String,i.slice(0,a))};sf.write=function(e,t,n){for(var s=n,o,i,a=0;a<e.length;++a)o=e.charCodeAt(a),o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=o&63|128):(o&64512)===55296&&((i=e.charCodeAt(a+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++a,t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=o&63|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=o&63|128);return n-s}});var _w=$((d8,Tw)=>{"use strict";Tw.exports=PE;function PE(r,e,t){var n=t||8192,s=n>>>1,o=null,i=n;return function(c){if(c<1||c>s)return r(c);i+c>n&&(o=r(n),i=0);var l=e.call(o,i,i+=c);return i&7&&(i=(i|7)+1),l}}});var Iw=$((p8,Aw)=>{"use strict";Aw.exports=fe;var _o=wr();function fe(r,e){this.lo=r>>>0,this.hi=e>>>0}var Vr=fe.zero=new fe(0,0);Vr.toNumber=function(){return 0};Vr.zzEncode=Vr.zzDecode=function(){return this};Vr.length=function(){return 1};var DE=fe.zeroHash="\0\0\0\0\0\0\0\0";fe.fromNumber=function(e){if(e===0)return Vr;var t=e<0;t&&(e=-e);var n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new fe(n,s)};fe.from=function(e){if(typeof e=="number")return fe.fromNumber(e);if(_o.isString(e))if(_o.Long)e=_o.Long.fromString(e);else return fe.fromNumber(parseInt(e,10));return e.low||e.high?new fe(e.low>>>0,e.high>>>0):Vr};fe.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296};fe.prototype.toLong=function(e){return _o.Long?new _o.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var gr=String.prototype.charCodeAt;fe.fromHash=function(e){return e===DE?Vr:new fe((gr.call(e,0)|gr.call(e,1)<<8|gr.call(e,2)<<16|gr.call(e,3)<<24)>>>0,(gr.call(e,4)|gr.call(e,5)<<8|gr.call(e,6)<<16|gr.call(e,7)<<24)>>>0)};fe.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};fe.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};fe.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};fe.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}});var wr=$(of=>{"use strict";var P=of;P.asPromise=cw();P.base64=hw();P.EventEmitter=pw();P.float=kw();P.inquire=Sw();P.utf8=Ew();P.pool=_w();P.LongBits=Iw();P.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);P.global=P.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||of;P.emptyArray=Object.freeze?Object.freeze([]):[];P.emptyObject=Object.freeze?Object.freeze({}):{};P.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};P.isString=function(e){return typeof e=="string"||e instanceof String};P.isObject=function(e){return e&&typeof e=="object"};P.isset=P.isSet=function(e,t){var n=e[t];return n!=null&&e.hasOwnProperty(t)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};P.Buffer=function(){try{var r=P.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();P._Buffer_from=null;P._Buffer_allocUnsafe=null;P.newBuffer=function(e){return typeof e=="number"?P.Buffer?P._Buffer_allocUnsafe(e):new P.Array(e):P.Buffer?P._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};P.Array=typeof Uint8Array<"u"?Uint8Array:Array;P.Long=P.global.dcodeIO&&P.global.dcodeIO.Long||P.global.Long||P.inquire("long");P.key2Re=/^true|false|0|1$/;P.key32Re=/^-?(?:0|[1-9][0-9]*)$/;P.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;P.longToHash=function(e){return e?P.LongBits.from(e).toHash():P.LongBits.zeroHash};P.longFromHash=function(e,t){var n=P.LongBits.fromHash(e);return P.Long?P.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function Cw(r,e,t){for(var n=Object.keys(e),s=0;s<n.length;++s)(r[n[s]]===void 0||!t)&&(r[n[s]]=e[n[s]]);return r}P.merge=Cw;P.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function Lw(r){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:new Error().stack||""}),n&&Cw(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return r},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}P.newError=Lw;P.ProtocolError=Lw("ProtocolError");P.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var s=Object.keys(this),o=s.length-1;o>-1;--o)if(t[s[o]]===1&&this[s[o]]!==void 0&&this[s[o]]!==null)return s[o]}};P.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}};P.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};P._configure=function(){var r=P.Buffer;if(!r){P._Buffer_from=P._Buffer_allocUnsafe=null;return}P._Buffer_from=r.from!==Uint8Array.from&&r.from||function(t,n){return new r(t,n)},P._Buffer_allocUnsafe=r.allocUnsafe||function(t){return new r(t)}}});var df=$((y8,Nw)=>{"use strict";Nw.exports=z;var Xe=wr(),af,ja=Xe.LongBits,Bw=Xe.base64,Pw=Xe.utf8;function Ao(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function lf(){}function NE(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function z(){this.len=0,this.head=new Ao(lf,0,0),this.tail=this.head,this.states=null}var Dw=function(){return Xe.Buffer?function(){return(z.create=function(){return new af})()}:function(){return new z}};z.create=Dw();z.alloc=function(e){return new Xe.Array(e)};Xe.Array!==Array&&(z.alloc=Xe.pool(z.alloc,Xe.Array.prototype.subarray));z.prototype._push=function(e,t,n){return this.tail=this.tail.next=new Ao(e,t,n),this.len+=t,this};function uf(r,e,t){e[t]=r&255}function ME(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function ff(r,e){this.len=r,this.next=void 0,this.val=e}ff.prototype=Object.create(Ao.prototype);ff.prototype.fn=ME;z.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new ff((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};z.prototype.int32=function(e){return e<0?this._push(hf,10,ja.fromNumber(e)):this.uint32(e)};z.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function hf(r,e,t){for(;r.hi;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}z.prototype.uint64=function(e){var t=ja.from(e);return this._push(hf,t.length(),t)};z.prototype.int64=z.prototype.uint64;z.prototype.sint64=function(e){var t=ja.from(e).zzEncode();return this._push(hf,t.length(),t)};z.prototype.bool=function(e){return this._push(uf,1,e?1:0)};function cf(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}z.prototype.fixed32=function(e){return this._push(cf,4,e>>>0)};z.prototype.sfixed32=z.prototype.fixed32;z.prototype.fixed64=function(e){var t=ja.from(e);return this._push(cf,4,t.lo)._push(cf,4,t.hi)};z.prototype.sfixed64=z.prototype.fixed64;z.prototype.float=function(e){return this._push(Xe.float.writeFloatLE,4,e)};z.prototype.double=function(e){return this._push(Xe.float.writeDoubleLE,8,e)};var OE=Xe.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var s=0;s<e.length;++s)t[n+s]=e[s]};z.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(uf,1,0);if(Xe.isString(e)){var n=z.alloc(t=Bw.length(e));Bw.decode(e,n,0),e=n}return this.uint32(t)._push(OE,t,e)};z.prototype.string=function(e){var t=Pw.length(e);return t?this.uint32(t)._push(Pw.write,t,e):this._push(uf,1,0)};z.prototype.fork=function(){return this.states=new NE(this),this.head=this.tail=new Ao(lf,0,0),this.len=0,this};z.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Ao(lf,0,0),this.len=0),this};z.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this};z.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t};z._configure=function(r){af=r,z.create=Dw(),af._configure()}});var Rw=$((g8,Ow)=>{"use strict";Ow.exports=Lt;var Mw=df();(Lt.prototype=Object.create(Mw.prototype)).constructor=Lt;var br=wr();function Lt(){Mw.call(this)}Lt._configure=function(){Lt.alloc=br._Buffer_allocUnsafe,Lt.writeBytesBuffer=br.Buffer&&br.Buffer.prototype instanceof Uint8Array&&br.Buffer.prototype.set.name==="set"?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var s=0;s<e.length;)t[n++]=e[s++]}};Lt.prototype.bytes=function(e){br.isString(e)&&(e=br._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(Lt.writeBytesBuffer,t,e),this};function RE(r,e,t){r.length<40?br.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}Lt.prototype.string=function(e){var t=br.Buffer.byteLength(e);return this.uint32(t),t&&this._push(RE,t,e),this};Lt._configure()});var yf=$((w8,zw)=>{"use strict";zw.exports=ne;var ut=wr(),mf,$w=ut.LongBits,FE=ut.utf8;function ft(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function ne(r){this.buf=r,this.pos=0,this.len=r.length}var Fw=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new ne(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new ne(e);throw Error("illegal buffer")},Kw=function(){return ut.Buffer?function(t){return(ne.create=function(s){return ut.Buffer.isBuffer(s)?new mf(s):Fw(s)})(t)}:Fw};ne.create=Kw();ne.prototype._slice=ut.Array.prototype.subarray||ut.Array.prototype.slice;ne.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ft(this,10);return e}}();ne.prototype.int32=function(){return this.uint32()|0};ne.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function pf(){var r=new $w(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return r;if(r.lo=(r.lo|(this.buf[this.pos]&127)<<28)>>>0,r.hi=(r.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return r;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw ft(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw ft(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}ne.prototype.bool=function(){return this.uint32()!==0};function Va(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}ne.prototype.fixed32=function(){if(this.pos+4>this.len)throw ft(this,4);return Va(this.buf,this.pos+=4)};ne.prototype.sfixed32=function(){if(this.pos+4>this.len)throw ft(this,4);return Va(this.buf,this.pos+=4)|0};function Uw(){if(this.pos+8>this.len)throw ft(this,8);return new $w(Va(this.buf,this.pos+=4),Va(this.buf,this.pos+=4))}ne.prototype.float=function(){if(this.pos+4>this.len)throw ft(this,4);var e=ut.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};ne.prototype.double=function(){if(this.pos+8>this.len)throw ft(this,4);var e=ut.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};ne.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ft(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,n);if(t===n){var s=ut.Buffer;return s?s.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,n)};ne.prototype.string=function(){var e=this.bytes();return FE.read(e,0,e.length)};ne.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ft(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ft(this);while(this.buf[this.pos++]&128);return this};ne.prototype.skipType=function(r){switch(r){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(r=this.uint32()&7)!==4;)this.skipType(r);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+r+" at offset "+this.pos)}return this};ne._configure=function(r){mf=r,ne.create=Kw(),mf._configure();var e=ut.Long?"toLong":"toNumber";ut.merge(ne.prototype,{int64:function(){return pf.call(this)[e](!1)},uint64:function(){return pf.call(this)[e](!0)},sint64:function(){return pf.call(this).zzDecode()[e](!1)},fixed64:function(){return Uw.call(this)[e](!0)},sfixed64:function(){return Uw.call(this)[e](!1)}})}});var Ww=$((b8,Vw)=>{"use strict";Vw.exports=Wr;var jw=yf();(Wr.prototype=Object.create(jw.prototype)).constructor=Wr;var Hw=wr();function Wr(r){jw.call(this,r)}Wr._configure=function(){Hw.Buffer&&(Wr.prototype._slice=Hw.Buffer.prototype.slice)};Wr.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Wr._configure()});var Gw=$((x8,qw)=>{"use strict";qw.exports=Io;var gf=wr();(Io.prototype=Object.create(gf.EventEmitter.prototype)).constructor=Io;function Io(r,e,t){if(typeof r!="function")throw TypeError("rpcImpl must be a function");gf.EventEmitter.call(this),this.rpcImpl=r,this.requestDelimited=!!e,this.responseDelimited=!!t}Io.prototype.rpcCall=function r(e,t,n,s,o){if(!s)throw TypeError("request must be specified");var i=this;if(!o)return gf.asPromise(r,i,e,t,n,s);if(!i.rpcImpl){setTimeout(function(){o(Error("already ended"))},0);return}try{return i.rpcImpl(e,t[i.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(c,l){if(c)return i.emit("error",c,e),o(c);if(l===null){i.end(!0);return}if(!(l instanceof n))try{l=n[i.responseDelimited?"decodeDelimited":"decode"](l)}catch(u){return i.emit("error",u,e),o(u)}return i.emit("data",l,e),o(null,l)})}catch(a){i.emit("error",a,e),setTimeout(function(){o(a)},0);return}};Io.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var Qw=$(Jw=>{"use strict";var UE=Jw;UE.Service=Gw()});var Xw=$((S8,Yw)=>{"use strict";Yw.exports={}});var tb=$(eb=>{"use strict";var Ce=eb;Ce.build="minimal";Ce.Writer=df();Ce.BufferWriter=Rw();Ce.Reader=yf();Ce.BufferReader=Ww();Ce.util=wr();Ce.rpc=Qw();Ce.roots=Xw();Ce.configure=Zw;function Zw(){Ce.util._configure(),Ce.Writer._configure(Ce.BufferWriter),Ce.Reader._configure(Ce.BufferReader)}Zw()});var nb=$((E8,rb)=>{"use strict";rb.exports=tb()});var Zb=$((Uo,lc)=>{"use strict";(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var m=0;m<h.length;m++)if(!Number.isInteger(h[m])||h[m]<0||h[m]>255)return!1;return!0}function s(h,m){return(h&65535)*m+(((h>>>16)*m&65535)<<16)}function o(h,m){return h<<m|h>>>32-m}function i(h){return h^=h>>>16,h=s(h,2246822507),h^=h>>>13,h=s(h,3266489909),h^=h>>>16,h}function a(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var d=[0,0,0,0];return d[3]+=h[3]+m[3],d[2]+=d[3]>>>16,d[3]&=65535,d[2]+=h[2]+m[2],d[1]+=d[2]>>>16,d[2]&=65535,d[1]+=h[1]+m[1],d[0]+=d[1]>>>16,d[1]&=65535,d[0]+=h[0]+m[0],d[0]&=65535,[d[0]<<16|d[1],d[2]<<16|d[3]]}function c(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var d=[0,0,0,0];return d[3]+=h[3]*m[3],d[2]+=d[3]>>>16,d[3]&=65535,d[2]+=h[2]*m[3],d[1]+=d[2]>>>16,d[2]&=65535,d[2]+=h[3]*m[2],d[1]+=d[2]>>>16,d[2]&=65535,d[1]+=h[1]*m[3],d[0]+=d[1]>>>16,d[1]&=65535,d[1]+=h[2]*m[2],d[0]+=d[1]>>>16,d[1]&=65535,d[1]+=h[3]*m[1],d[0]+=d[1]>>>16,d[1]&=65535,d[0]+=h[0]*m[3]+h[1]*m[2]+h[2]*m[1]+h[3]*m[0],d[0]&=65535,[d[0]<<16|d[1],d[2]<<16|d[3]]}function l(h,m){return m%=64,m===32?[h[1],h[0]]:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m|h[0]>>>32-m]:(m-=32,[h[1]<<m|h[0]>>>32-m,h[0]<<m|h[1]>>>32-m])}function u(h,m){return m%=64,m===0?h:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m]:[h[1]<<m-32,0]}function f(h,m){return[h[0]^m[0],h[1]^m[1]]}function p(h){return h=f(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=f(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=f(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%4,y=h.length-d,g=m,b=0,x=3432918353,k=461845907,S=0;S<y;S=S+4)b=h[S]|h[S+1]<<8|h[S+2]<<16|h[S+3]<<24,b=s(b,x),b=o(b,15),b=s(b,k),g^=b,g=o(g,13),g=s(g,5)+3864292196;switch(b=0,d){case 3:b^=h[S+2]<<16;case 2:b^=h[S+1]<<8;case 1:b^=h[S],b=s(b,x),b=o(b,15),b=s(b,k),g^=b}return g^=h.length,g=i(g),g>>>0},t.x86.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%16,y=h.length-d,g=m,b=m,x=m,k=m,S=0,T=0,E=0,_=0,W=597399067,le=2869860233,Te=951274213,Y=2716044179,R=0;R<y;R=R+16)S=h[R]|h[R+1]<<8|h[R+2]<<16|h[R+3]<<24,T=h[R+4]|h[R+5]<<8|h[R+6]<<16|h[R+7]<<24,E=h[R+8]|h[R+9]<<8|h[R+10]<<16|h[R+11]<<24,_=h[R+12]|h[R+13]<<8|h[R+14]<<16|h[R+15]<<24,S=s(S,W),S=o(S,15),S=s(S,le),g^=S,g=o(g,19),g+=b,g=s(g,5)+1444728091,T=s(T,le),T=o(T,16),T=s(T,Te),b^=T,b=o(b,17),b+=x,b=s(b,5)+197830471,E=s(E,Te),E=o(E,17),E=s(E,Y),x^=E,x=o(x,15),x+=k,x=s(x,5)+2530024501,_=s(_,Y),_=o(_,18),_=s(_,W),k^=_,k=o(k,13),k+=g,k=s(k,5)+850148119;switch(S=0,T=0,E=0,_=0,d){case 15:_^=h[R+14]<<16;case 14:_^=h[R+13]<<8;case 13:_^=h[R+12],_=s(_,Y),_=o(_,18),_=s(_,W),k^=_;case 12:E^=h[R+11]<<24;case 11:E^=h[R+10]<<16;case 10:E^=h[R+9]<<8;case 9:E^=h[R+8],E=s(E,Te),E=o(E,17),E=s(E,Y),x^=E;case 8:T^=h[R+7]<<24;case 7:T^=h[R+6]<<16;case 6:T^=h[R+5]<<8;case 5:T^=h[R+4],T=s(T,le),T=o(T,16),T=s(T,Te),b^=T;case 4:S^=h[R+3]<<24;case 3:S^=h[R+2]<<16;case 2:S^=h[R+1]<<8;case 1:S^=h[R],S=s(S,W),S=o(S,15),S=s(S,le),g^=S}return g^=h.length,b^=h.length,x^=h.length,k^=h.length,g+=b,g+=x,g+=k,b+=g,x+=g,k+=g,g=i(g),b=i(b),x=i(x),k=i(k),g+=b,g+=x,g+=k,b+=g,x+=g,k+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(k>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%16,y=h.length-d,g=[0,m],b=[0,m],x=[0,0],k=[0,0],S=[2277735313,289559509],T=[1291169091,658871167],E=0;E<y;E=E+16)x=[h[E+4]|h[E+5]<<8|h[E+6]<<16|h[E+7]<<24,h[E]|h[E+1]<<8|h[E+2]<<16|h[E+3]<<24],k=[h[E+12]|h[E+13]<<8|h[E+14]<<16|h[E+15]<<24,h[E+8]|h[E+9]<<8|h[E+10]<<16|h[E+11]<<24],x=c(x,S),x=l(x,31),x=c(x,T),g=f(g,x),g=l(g,27),g=a(g,b),g=a(c(g,[0,5]),[0,1390208809]),k=c(k,T),k=l(k,33),k=c(k,S),b=f(b,k),b=l(b,31),b=a(b,g),b=a(c(b,[0,5]),[0,944331445]);switch(x=[0,0],k=[0,0],d){case 15:k=f(k,u([0,h[E+14]],48));case 14:k=f(k,u([0,h[E+13]],40));case 13:k=f(k,u([0,h[E+12]],32));case 12:k=f(k,u([0,h[E+11]],24));case 11:k=f(k,u([0,h[E+10]],16));case 10:k=f(k,u([0,h[E+9]],8));case 9:k=f(k,[0,h[E+8]]),k=c(k,T),k=l(k,33),k=c(k,S),b=f(b,k);case 8:x=f(x,u([0,h[E+7]],56));case 7:x=f(x,u([0,h[E+6]],48));case 6:x=f(x,u([0,h[E+5]],40));case 5:x=f(x,u([0,h[E+4]],32));case 4:x=f(x,u([0,h[E+3]],24));case 3:x=f(x,u([0,h[E+2]],16));case 2:x=f(x,u([0,h[E+1]],8));case 1:x=f(x,[0,h[E]]),x=c(x,S),x=l(x,31),x=c(x,T),g=f(g,x)}return g=f(g,[0,h.length]),b=f(b,[0,h.length]),g=a(g,b),b=a(b,g),g=p(g),b=p(b),g=a(g,b),b=a(b,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof Uo<"u"?(typeof lc<"u"&&lc.exports&&(Uo=lc.exports=t),Uo.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(Uo)});var Yf=$((Q8,e0)=>{"use strict";e0.exports=Zb()});var C0=$((lU,I0)=>{"use strict";function A0(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function A_(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return A0(r,t)}catch{t.message=r.message,t.stack=r.stack;let s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(r)),A0(new s,t)}}I0.exports=A_});var G0=$((i6,q0)=>{"use strict";q0.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let n=this._internalPositionFor(e,!1);if(t===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let s=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):s=!0,this._setInternalPos(n,e,t,s),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let t=this._internalPositionFor(e,!0);if(t!==-1)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let t=0;for(;t<this.length;)e(this.get(t),t,this),t++}map(e){let t=0,n=new Array(this.length);for(;t<this.length;)n[t]=e(this.get(t),t,this),t++;return n}reduce(e,t){let n=0,s=t;for(;n<this.length;){let o=this.get(n);s=e(s,o,n),n++}return s}find(e){let t=0,n,s;for(;t<this.length&&!n;)s=this.get(t),n=e(s),t++;return n?s:void 0}_internalPositionFor(e,t){let n=this._bytePosFor(e,t);if(n>=this._bitArrays.length)return-1;let s=this._bitArrays[n],o=e-n*7;if(!((s&1<<o)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(J_,0),c=~(4294967295<<o+1),l=W0(s&c);return a+l-1}_bytePosFor(e,t){let n=Math.floor(e/7),s=n+1;for(;!t&&this._bitArrays.length<s;)this._bitArrays.push(0);return n}_setBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]|=1<<e-t*7}_unsetBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]&=~(1<<e-t*7)}_setInternalPos(e,t,n,s){let o=this._data,i=[t,n];if(s)this._sortData(),o[e]=i;else{if(o.length)if(o[o.length-1][0]>=t)o.push(i);else if(o[0][0]<=t)o.unshift(i);else{let a=Math.round(o.length/2);this._data=o.slice(0,a).concat(i).concat(o.slice(a))}else this._data.push(i);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(Q_),this._changedData=!1}bitField(){let e=[],t=8,n=0,s=0,o,i=this._bitArrays.slice();for(;i.length||n;){n===0&&(o=i.shift(),n=7);let c=Math.min(n,t),l=~(255<<c),u=o&l;s|=u<<8-t,o=o>>>c,n-=c,t-=c,(!t||!n&&!i.length)&&(e.push(s),s=0,t=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(Y_)}};function J_(r,e){return r+W0(e)}function W0(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function Q_(r,e){return r[0]-e[0]}function Y_(r){return r[1]}});var lx=$((Y6,Dh)=>{"use strict";var bA=Object.prototype.hasOwnProperty,Ee="~";function qo(){}Object.create&&(qo.prototype=Object.create(null),new qo().__proto__||(Ee=!1));function xA(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function cx(r,e,t,n,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new xA(t,n||r,s),i=Ee?Ee+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],o]:r._events[i].push(o):(r._events[i]=o,r._eventsCount++),r}function Nc(r,e){--r._eventsCount===0?r._events=new qo:delete r._events[e]}function xe(){this._events=new qo,this._eventsCount=0}xe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)bA.call(t,n)&&e.push(Ee?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};xe.prototype.listeners=function(e){var t=Ee?Ee+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,o=n.length,i=new Array(o);s<o;s++)i[s]=n[s].fn;return i};xe.prototype.listenerCount=function(e){var t=Ee?Ee+e:e,n=this._events[t];return n?n.fn?1:n.length:0};xe.prototype.emit=function(e,t,n,s,o,i){var a=Ee?Ee+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,s),!0;case 5:return c.fn.call(c.context,t,n,s,o),!0;case 6:return c.fn.call(c.context,t,n,s,o,i),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var p=c.length,h;for(f=0;f<p;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,s);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};xe.prototype.on=function(e,t,n){return cx(this,e,t,n,!1)};xe.prototype.once=function(e,t,n){return cx(this,e,t,n,!0)};xe.prototype.removeListener=function(e,t,n,s){var o=Ee?Ee+e:e;if(!this._events[o])return this;if(!t)return Nc(this,o),this;var i=this._events[o];if(i.fn)i.fn===t&&(!s||i.once)&&(!n||i.context===n)&&Nc(this,o);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||s&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[o]=c.length===1?c[0]:c:Nc(this,o)}return this};xe.prototype.removeAllListeners=function(e){var t;return e?(t=Ee?Ee+e:e,this._events[t]&&Nc(this,t)):(this._events=new qo,this._eventsCount=0),this};xe.prototype.off=xe.prototype.removeListener;xe.prototype.addListener=xe.prototype.on;xe.prefixed=Ee;xe.EventEmitter=xe;typeof Dh<"u"&&(Dh.exports=xe)});function bx(){return NA.once(()=>new py)}function OA(){return new Map([...Array.from(Object.entries(globalThis[Symbol.for("FP_PRESET_ENV")]||{}))])}function Xo(r){let e=xn({symbol:r?.env?.symbol||"FP_ENV",presetEnv:r?.env?.presetEnv||OA()});return new jh({logger:r?.logger||bx(),env:e,crypto:r?.crypto||Hn(),ctx:r?.ctx||{},pathOps:RA,txt:r?.txt||FA})}function _r(r,e,t){return r.clone({logger:H(r,e,t)})}function H(r,e,t){let n;uu(r)?n=r:r&&uu(r.logger)?n=r.logger:n=bx();let s=n.With().Module(e),o=[],i=!1;if(t){"debug"in t&&(typeof t.debug=="string"&&t.debug.length>0?o.push(t.debug):o.push(e),delete t.debug),"exposeStack"in t&&(i=!0,delete t.exposeStack),"this"in t&&(s.Str("this",r.nextId(4).str),delete t.this);for(let[c,l]of Object.entries(t))switch(typeof l){case"string":s.Str(c,l);break;case"number":s.Uint64(c,l);break;default:l instanceof Date?s.Str(c,l.toISOString()):fu(l)?s.Str(c,l.toString()):typeof l=="function"?s.Ref(c,l):s.Any(c,l);break}}return MA.once(async()=>{r.env.onSet((c,l)=>{switch(c){case"FP_FORMAT":{switch(l){case"jsonice":n.SetFormatter(new ga(n.TxtEnDe(),2));break;case"yaml":n.SetFormatter(new dy(n.TxtEnDe(),2));break;case"json":default:n.SetFormatter(new ga(n.TxtEnDe()));break}break}case"FP_DEBUG":n.SetDebug(l||[]);break;case"FP_STACK":n.SetExposeStack(!!l);break}},"FP_FORMAT","FP_DEBUG","FP_STACK")}).finally(()=>{}),o.length>0&&n.SetDebug(o),i&&n.SetExposeStack(!0),s.Logger()}function Nt(r,e,t){let n=r.getParam("store");switch(n){case"data":case"wal":case"meta":break;default:throw e.logger.Error().Url(r).Msg("store not found").AsError()}let s=n;return r.hasParam("index")&&(s=t(r.getParam("index")||"idx",s)),{store:n,name:s}}function Zo(r,e){let t=r.getParam("key");if(!t)throw e.Error().Str("url",r.toString()).Msg("key not found").AsError();return t}function UA(r,e){let t=e.getParam("name");if(!t&&(t=r.pathOps.dirname(e.pathname),t.length===0))throw r.logger.Error().Str("url",e.toString()).Msg("name not found").AsError();return t}async function ei(r){return r().catch(e=>C.Err(e))}function Mt(r){if(C.Is(r)){if(r.isOk())return!1;r=r.Err()}return r.code==="ENOENT"}function Wh(r,e,t){if(!t)if(Or().isBrowser)t=r.env.get("FP_STORAGE_URL")||"indexdb://fp";else{let n=r.env.get("HOME")||"./";t=r.env.get("FP_STORAGE_URL")||`file://${r.pathOps.join(n,".fireproof")}`}return Ie.from(t.toString()).build().setParam("name",e||"").URI()}function qh(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}var NA,MA,jh,Vh,RA,FA,Dt,ye=A(()=>{"use strict";ae();Rr();NA=new X;MA=new X,jh=class r{constructor(e){this.logger=e.logger,this.env=e.env,this.crypto=e.crypto,this.pathOps=e.pathOps,this.txt=e.txt,this.ctx={...e.ctx}}nextId(e=6){let t=this.crypto.randomBytes(e);return{str:J.encode(t),bin:t}}timeOrderedNextId(e){e=typeof e=="number"?e:new Date().getTime();let t=(281474976710656+e).toString(16).replace(/^1/,""),n=this.crypto.randomBytes(10);n[1]=n[1]&240|(n[1]|8&&11);let s=Array.from(n).map(o=>o.toString(16).padStart(2,"0")).join("");return{str:`${t.slice(0,8)}-${t.slice(8)}-7${s.slice(0,3)}-${s.slice(3,7)}-${s.slice(7,19)}`}}start(){return Promise.resolve()}clone(e){return new r({logger:e.logger||this.logger,env:xn(e.env)||this.env,crypto:e.crypto||this.crypto,pathOps:e.pathOps||this.pathOps,txt:e.txt||this.txt,ctx:{...this.ctx,...e.ctx}})}};Vh=class{join(...e){return e.map(t=>t.replace(/\/+$/,"")).join("/")}dirname(e){return e.split("/").slice(0,-1).join("/")}},RA=new Vh,FA={encode:r=>new TextEncoder().encode(r),decode:r=>new TextDecoder().decode(r)};Dt=class extends Error{constructor(){super(...arguments);this.code="ENOENT"}}});var vx=$((u4,Sx)=>{"use strict";Sx.exports=Jh;var kx=128,$A=127,KA=~$A,zA=Math.pow(2,31);function Jh(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw Jh.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=zA;)e[t++]=r&255|kx,r/=128;for(;r&KA;)e[t++]=r&255|kx,r>>>=7;return e[t]=r|0,Jh.bytes=t-n+1,e}});var _x=$((f4,Tx)=>{"use strict";Tx.exports=Qh;var HA=128,Ex=127;function Qh(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a||s>49)throw Qh.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Ex)<<s:(i&Ex)*Math.pow(2,s),s+=7}while(i>=HA);return Qh.bytes=o-n,t}});var Ix=$((h4,Ax)=>{"use strict";var jA=Math.pow(2,7),VA=Math.pow(2,14),WA=Math.pow(2,21),qA=Math.pow(2,28),GA=Math.pow(2,35),JA=Math.pow(2,42),QA=Math.pow(2,49),YA=Math.pow(2,56),XA=Math.pow(2,63);Ax.exports=function(r){return r<jA?1:r<VA?2:r<WA?3:r<qA?4:r<GA?5:r<JA?6:r<QA?7:r<YA?8:r<XA?9:10}});var Yh=$((d4,Cx)=>{"use strict";Cx.exports={encode:vx(),decode:_x(),encodingLength:Ix()}});async function li(r){let e=r.getParam("fs","node"),t;switch(e){case"mem":t=await $x.get(e).once(async()=>{let n="./node/mem-filesystem.js",{MemFileSystem:s}=await import(n);return new s});break;default:t=await $x.get(e).once(async()=>{let n="./node/node-filesystem.js",{NodeFileSystem:s}=await import(n);return new s})}return t.start()}var $x,Kx=A(()=>{"use strict";ae();$x=new _e});var zx={};K(zx,{getFileName:()=>ui,getFileSystem:()=>li,getPath:()=>tn});function tn(r,e){let t=r.pathname,n=r.getParam("name");if(n){let s=r.getParam("version");if(!s)throw e.logger.Error().Url(r).Msg("version not found").AsError();return e.pathOps.join(t,s,n)}return e.pathOps.join(t)}function ui(r,e){let t=r.getParam("key");if(!t)throw e.logger.Error().Url(r).Msg("key not found").AsError();let n=Nt(r,e,(...s)=>s.join("-"));switch(n.store){case"data":return e.pathOps.join(n.name,t+".car");case"wal":case"meta":return e.pathOps.join(n.name,t+".json");default:throw e.logger.Error().Url(r).Msg("unsupported store type").AsError()}}var fi=A(()=>{"use strict";ye();Kx()});var Hx={};K(Hx,{KeyBagProviderFile:()=>td});var td,jx=A(()=>{"use strict";ye();td=class{async _prepare(e){await this.sthis.start();let t;switch(this.url.protocol){case"file:":{let{getFileSystem:s}=await Promise.resolve().then(()=>(fi(),zx));t=await s(this.url);break}default:throw this.logger.Error().Url(this.url).Msg("unsupported protocol").AsError()}let n=this.url.pathname;return await t.mkdir(n,{recursive:!0}),{dirName:n,sysFS:t,fName:this.sthis.pathOps.join(n,`${e.replace(/[^a-zA-Z0-9]/g,"_")}.json`)}}constructor(e,t){this.url=e,this.sthis=t,this.logger=t.logger}async get(e){let t=await this._prepare(e);try{let n=await t.sysFS.readfile(t.fName);return JSON.parse(this.sthis.txt.decode(n))}catch(n){if(Mt(n))return;throw this.logger.Error().Err(n).Str("file",t.dirName).Msg("read bag failed").AsError()}}async set(e,t){let n=await this._prepare(e),s=this.sthis.txt.encode(JSON.stringify(t,null,2));await n.sysFS.writefile(n.fName,s)}}});function sI(){return Vx||(Vx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function oI(){return Wx||(Wx=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function iI(r){let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("success",o),r.removeEventListener("error",i)},o=()=>{t(rn(r.result)),s()},i=()=>{n(r.error),s()};r.addEventListener("success",o),r.addEventListener("error",i)});return Rc.set(e,r),e}function aI(r){if(od.has(r))return;let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("complete",o),r.removeEventListener("error",i),r.removeEventListener("abort",i)},o=()=>{t(),s()},i=()=>{n(r.error||new DOMException("AbortError","AbortError")),s()};r.addEventListener("complete",o),r.addEventListener("error",i),r.addEventListener("abort",i)});od.set(r,e)}function Qx(r){id=r(id)}function cI(r){return oI().includes(r)?function(...e){return r.apply(ad(this),e),rn(this.request)}:function(...e){return rn(r.apply(ad(this),e))}}function lI(r){return typeof r=="function"?cI(r):(r instanceof IDBTransaction&&aI(r),sd(r,sI())?new Proxy(r,id):r)}function rn(r){if(r instanceof IDBRequest)return iI(r);if(rd.has(r))return rd.get(r);let e=lI(r);return e!==r&&(rd.set(r,e),Rc.set(e,r)),e}function Fc(r,e,{blocked:t,upgrade:n,blocking:s,terminated:o}={}){let i=indexedDB.open(r,e),a=rn(i);return n&&i.addEventListener("upgradeneeded",c=>{n(rn(i.result),c.oldVersion,c.newVersion,rn(i.transaction),c)}),t&&i.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),a.then(c=>{o&&c.addEventListener("close",()=>o()),s&&c.addEventListener("versionchange",l=>s(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}function qx(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(nd.get(e))return nd.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,s=fI.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(s||uI.includes(t)))return;let o=async function(i,...a){let c=this.transaction(i,s?"readwrite":"readonly"),l=c.store;return n&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),s&&c.done]))[0]};return nd.set(e,o),o}async function*pI(...r){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...r)),!e)return;e=e;let t=new Proxy(e,dI);for(Yx.set(t,e),Rc.set(t,ad(e));e;)yield t,e=await(cd.get(t)||e.continue()),cd.delete(t)}function Jx(r,e){return e===Symbol.asyncIterator&&sd(r,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&sd(r,[IDBIndex,IDBObjectStore])}var sd,Vx,Wx,od,rd,Rc,id,ad,uI,fI,nd,hI,Gx,cd,Yx,dI,ld=A(()=>{"use strict";sd=(r,e)=>e.some(t=>r instanceof t);od=new WeakMap,rd=new WeakMap,Rc=new WeakMap;id={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return od.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return rn(r[e])},set(r,e,t){return r[e]=t,!0},has(r,e){return r instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in r}};ad=r=>Rc.get(r);uI=["get","getKey","getAll","getAllKeys","count"],fI=["put","add","delete","clear"],nd=new Map;Qx(r=>({...r,get:(e,t,n)=>qx(e,t)||r.get(e,t,n),has:(e,t)=>!!qx(e,t)||r.has(e,t)}));hI=["continue","continuePrimaryKey","advance"],Gx={},cd=new WeakMap,Yx=new WeakMap,dI={get(r,e){if(!hI.includes(e))return r[e];let t=Gx[e];return t||(t=Gx[e]=function(...n){cd.set(this,Yx.get(this)[e](...n))}),t}};Qx(r=>({...r,get(e,t,n){return Jx(e,t)?pI:r.get(e,t,n)},has(e,t){return Jx(e,t)||r.has(e,t)}}))});var Xx={};K(Xx,{KeyBagProviderIndexDB:()=>ud});var ud,Zx=A(()=>{"use strict";ld();fi();ae();ud=class{constructor(e,t){this._db=new X;this.sthis=t,this.logger=t.logger,this.url=e,this.dbName=tn(this.url,this.sthis)}async _prepare(){return this._db.once(async()=>await Fc(this.dbName,1,{upgrade(e){["bag"].map(t=>{e.createObjectStore(t,{autoIncrement:!1})})}}))}async get(e){let n=(await this._prepare()).transaction(["bag"],"readonly"),s=await n.objectStore("bag").get(e);if(await n.done,!!s)return s}async set(e,t){let s=(await this._prepare()).transaction(["bag"],"readwrite");await s.objectStore("bag").put(t,e),await s.done}}});var wk=$((aK,gk)=>{"use strict";function tt(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}gk.exports=tt;tt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};tt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};tt.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};tt.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};tt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};tt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};tt.prototype.start=tt.prototype.try;tt.prototype.errors=function(){return this._errors};tt.prototype.attempts=function(){return this._attempts};tt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var s=this._errors[n],o=s.message,i=(r[o]||0)+1;r[o]=i,i>=t&&(e=s,t=i)}return e}});var bk=$(nn=>{"use strict";var PI=wk();nn.operation=function(r){var e=nn.timeouts(r);return new PI(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};nn.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<e.retries;s++)n.push(this.createTimeout(s,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(s,e)),n.sort(function(o,i){return o-i}),n};nn.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};nn.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var s=0;s<t.length;s++){var o=t[s],i=r[o];r[o]=function(c){var l=nn.operation(e),u=Array.prototype.slice.call(arguments,1),f=u.pop();u.push(function(p){l.retry(p)||(p&&(arguments[0]=l.mainError()),f.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,i),r[o].options=e}}});var kk=$((lK,xk)=>{"use strict";xk.exports=bk()});var Cr,Td=A(()=>{"use strict";Cr="v0.19-file"});var Id={};K(Id,{FileGateway:()=>_d,FileTestStore:()=>Ad});var RI,_d,Ad,Cd=A(()=>{"use strict";Td();ae();ye();fi();RI=new _e,_d=class{get fs(){if(!this._fs)throw this.logger.Error().Msg("fs not initialized").AsError();return this._fs}constructor(e){this.sthis=e,this.logger=e.logger}async getVersionFromFile(e,t){return RI.get(e).once(async()=>{await this.fs.mkdir(e,{recursive:!0});let n=this.sthis.pathOps.join(e,"version"),s=await this.fs.stat(n).catch(()=>{});if(s){if(!s.isFile())throw t.Error().Str("file",n).Msg("version file is a directory").AsError()}else return await this.fs.writefile(this.sthis.pathOps.join(e,"version"),Cr),Cr;let o=await this.fs.readfile(n),i=this.sthis.txt.decode(o);return i!==Cr&&t.Warn().Str("file",n).Str("from",i).Str("expected",Cr).Msg("version mismatch"),i})}start(e){return We(async()=>{this._fs=await li(e),await this.fs.start();let t=e.build();t.defParam("version",Cr);let n=await this.buildUrl(t.URI(),"dummy"),s=this.getFilePath(n.Ok());await this.fs.mkdir(this.sthis.pathOps.dirname(s),{recursive:!0});let o=this.sthis.pathOps.dirname(s);return this.logger.Debug().Url(t.URI()).Str("dbroot",o).Msg("start"),t.setParam("version",await this.getVersionFromFile(o,this.logger)),t.URI()})}async buildUrl(e,t){return C.Ok(e.build().setParam("key",t).URI())}async close(){return C.Ok(void 0)}getFilePath(e){if(!e.getParam("key"))throw this.logger.Error().Url(e).Msg("key not found").AsError();return this.sthis.pathOps.join(tn(e,this.sthis),ui(e,this.sthis))}async put(e,t){return We(async()=>{let n=await this.getFilePath(e);this.logger.Debug().Str("url",e.toString()).Str("file",n).Msg("put"),await this.fs.writefile(n,t)})}async get(e){return ei(async()=>{let t=this.getFilePath(e);try{let n=await this.fs.readfile(t);return this.logger.Debug().Url(e.asURL()).Str("file",t).Msg("get"),C.Ok(new Uint8Array(n))}catch(n){return Mt(n)?C.Err(new Dt(`file not found: ${t}`)):C.Err(n)}})}async delete(e){return We(async()=>{await this.fs.unlink(this.getFilePath(e))})}async destroy(e){let t=await this.buildUrl(e,"x");if(t.isErr())return t;let n=this.sthis.pathOps.dirname(this.getFilePath(t.Ok())),s=[];try{s=await this.fs.readdir(n)}catch(o){if(!Mt(o))throw this.logger.Error().Err(o).Str("dir",n).Msg("destroy:readdir").AsError()}for(let o of s){let i=this.sthis.pathOps.join(n,o);try{await this.fs.unlink(i)}catch(a){if(!Mt(a))throw this.logger.Error().Err(a).Str("file",i).Msg("destroy:unlink").AsError()}}return C.Ok(void 0)}},Ad=class{constructor(e){this.logger=H(e,"FileTestStore"),this.sthis=e}async get(e,t){let n=e.build().setParam("key",t).URI(),s=this.sthis.pathOps.join(tn(n,this.sthis),ui(n,this.sthis));this.logger.Debug().Url(n).Str("dbFile",s).Msg("get");let o=await(await li(n)).readfile(s);return this.logger.Debug().Url(n).Str("dbFile",s).Len(o).Msg("got"),o}}});var Vc,Ld=A(()=>{"use strict";Vc="v0.19-indexdb"});var Ik={};K(Ik,{IndexDBGatewayImpl:()=>Bd,IndexDBTestStore:()=>Pd,getIndexDBName:()=>Ak});function Tk(r){return r.build().defParam("version",Vc).URI()}function Wc(r){return r.length===1&&(r=r[0]),r}async function _k(r,e){let t=Ak(r,e),n=await FI.get(t.fullDb).once(async()=>{let s=await Fc(t.fullDb,1,{upgrade(a){["version","data","wal","meta","idx.data","idx.wal","idx.meta"].map(c=>{a.createObjectStore(c,{autoIncrement:!1})})}}),o=await s.get("version","version"),i=Tk(r).getParam("version");return o?o.version!==i&&e.logger.Warn().Str("url",r.toString()).Str("version",i).Str("found",o.version).Msg("version mismatch"):await s.put("version",{version:i},"version"),{db:s,dbName:t,version:i,url:r}});return{...n,url:r.build().setParam("version",n.version).URI()}}function sn(...r){return r.map(e=>e.replace(/^[^a-zA-Z0-9]+/g,"").replace(/[^a-zA-Z0-9-]+/g,"_")).filter(e=>e.length).join(".")}function Ak(r,e){let t=Tk(r),n=t.pathname.replace(/^\/+/,"").replace(/\?.*$/,""),s=t.getParam("name");if(!s)throw e.logger.Error().Str("url",t.toString()).Msg("name not found").AsError();let o=sn(n,s),i=Nt(t,e,sn).name,a=[o,i].join(":");return{fullDb:o,objStore:i,connectionKey:a,dbName:s}}var FI,Bd,Pd,Ck=A(()=>{"use strict";ld();ae();Ld();ye();FI=new _e;Bd=class{constructor(e){this._db={};this.logger=H(e,"IndexDBGateway"),this.sthis=e}async start(e){return We(async()=>{this.logger.Debug().Url(e).Msg("starting"),await this.sthis.start();let t=await _k(e,this.sthis);return this._db=t.db,this.logger.Debug().Url(t.url).Msg("started"),t.url})}async close(){return C.Ok(void 0)}async destroy(e){return We(async()=>{let t=Nt(e,this.sthis,sn).name,s=this._db.transaction(t,"readwrite"),o=s.objectStore(t),i=[];for(let a=await o.openCursor();a;a=await a.continue())i.push(a.primaryKey);for(let a of i)await s.db.delete(t,a);await s.done})}buildUrl(e,t){return Promise.resolve(C.Ok(e.build().setParam("key",t).URI()))}async get(e){return ei(async()=>{let t=Zo(e,this.logger),n=Nt(e,this.sthis,sn).name;this.logger.Debug().Url(e).Str("key",t).Str("store",n).Msg("getting");let s=this._db.transaction([n],"readonly"),o=await s.objectStore(n).get(Wc(t));return await s.done,o?C.Ok(o):C.Err(new Dt(`missing ${t}`))})}async put(e,t){return We(async()=>{let n=Zo(e,this.logger),s=Nt(e,this.sthis,sn).name;this.logger.Debug().Url(e).Str("key",n).Str("store",s).Msg("putting");let o=this._db.transaction([s],"readwrite");await o.objectStore(s).put(t,Wc(n)),await o.done})}async delete(e){return We(async()=>{let t=Zo(e,this.logger),n=Nt(e,this.sthis,sn).name;this.logger.Debug().Url(e).Str("key",t).Str("store",n).Msg("deleting");let s=this._db.transaction([n],"readwrite");return await s.objectStore(n).delete(Wc(t)),await s.done,C.Ok(void 0)})}},Pd=class{constructor(e){this.sthis=e,this.logger=H(e,"IndexDBTestStore",{})}async get(e,t){let n=await _k(e,this.sthis),s=Nt(n.url,this.sthis,sn).name;this.logger.Debug().Str("key",t).Str("store",s).Msg("getting");let o=await n.db.get(s,Wc(t));return this.logger.Debug().Str("key",t).Str("store",s).Int("len",o.length).Msg("got"),typeof o=="string"&&(o=this.sthis.txt.encode(o)),o}}});function Dd(){return Promise.resolve().then(()=>(Ck(),Ik))}var Lk=A(()=>{"use strict"});var Od={};K(Od,{IndexDBGateway:()=>Nd,IndexDBTestStore:()=>Md});var UI,Nd,Md,Rd=A(()=>{"use strict";ae();Lk();UI=new X,Nd=class{constructor(e){this.sthis=e}getGateway(){return UI.once(()=>Dd().then(({IndexDBGatewayImpl:e})=>new e(this.sthis)))}buildUrl(e,t){return this.getGateway().then(n=>n.buildUrl(e,t))}start(e){return this.getGateway().then(t=>t.start(e))}close(e){return this.getGateway().then(t=>t.close(e))}destroy(e){return this.getGateway().then(t=>t.destroy(e))}put(e,t){return this.getGateway().then(n=>n.put(e,t))}get(e){return this.getGateway().then(t=>t.get(e))}delete(e){return this.getGateway().then(t=>t.delete(e))}},Md=class{constructor(e){this.loadExternal=new X;this.sthis=e}getGateway(){return this.loadExternal.once(()=>Dd().then(({IndexDBTestStore:e})=>new e(this.sthis)))}get(e,t){return this.getGateway().then(n=>n.get(e,t))}}});var jk=$(Wd=>{"use strict";Wd.encode=function(r){if(isNaN(r))return"DaN";if(r===0)return"FE 0M0";if(r===1/0)return"FF";if(r===-1/0)return"DD";var e=r.toExponential().split("e"),t=Number(e[1])+500,n=e[0]+(e[0].indexOf(".")===-1?".":"")+"0".repeat(20),s="E"+QI(String(t),3)+"M"+String(n);return r>0?"F"+s:"D"+Hk(s)};Wd.decode=function(r){if(r==="DaN")return NaN;if(r==="FF")return 1/0;if(r==="DD")return-1/0;var e=r[0]==="D",t=(e?Hk(r):r).slice(2).split("M");return+((e?"-":"")+t[1]+"e"+String(Number(t[0])-500))};function Hk(r){for(var e="",t=0;t<r.length;t++){var n=r[t];isNaN(Number(n))||n===" "?n!=="-"&&(e+=n):e+=String(9-Number(n))}return e}function QI(r,e){return" ".repeat(e-r.length).substr(0,e)+r}});var Wk=$(Vk=>{"use strict";var YI={"?":"?@","!":"??",'"':"?%"};function XI(r){return/[!"]/.test(r)?r.replace(/[\?!"]/g,function(e){return YI[e]}):r}var ZI={"?@":"?","??":"!","?%":'"'};function eC(r){return/\?[%\?@]/.test(r)?r.replace(/\?[%\?@]/g,function(e){return ZI[e]}):r}Vk.factory=function(r){return{encode:e,decode:n};function e(s){if(s===null)return"A";if(!Array.isArray(s))throw new Error("can only encode arrays");var o=s.length;if(o==0)return"K!";for(var i=t(s[0]),a=1;a<o;a++)i+='"'+t(s[a]);return"K"+i+"!"}function t(s){return typeof s=="object"?e(s):XI(r.encode(s))}function n(s){if(s==="A")return null;if(s==="K!")return[];for(var o=s.split('"'),i=[[]],a,c=0,l=o.length,u=0;u<l;u++){for(var f=o[u],p=f.length,h=0;f[h]=="K";)h++;for(var m=0;f[p-m-1]=="!";)m++;for(var d=f.slice(h,p-m),g=c+h,y=c;y<g;y++)i[y+1]=[],i[y].push(i[y+1]),c=g,a=i[c];d.length!==0&&a.push(r.decode(eC(d)));for(var g=c-m,y=g;y<c;y++)i[y+1]=[],c=g,a=i[c]}return i[0][0]}}});var Gk=$(se=>{"use strict";var tC=jk(),rC=Wk(),$z=se.flip=function(r){var e=r.toString(),t="";for(var n in e)t+=e[n]=="."?".":9-+e[n];return t};se.number=tC;se.string={encode:function(r){return/\x00|\x01/.test(r)?"J"+r.replace(/\x01/g,"").replace(/\x00/g,""):"J"+r},decode:function(r){if(r[0]==="J")return r.substring(1)}};se.encode=function(r){return se[typeof r].encode(r)};se.decode=function(r){if(r==="")return r;if(!qk[r[0]])throw new Error("no decoder for:"+JSON.stringify(r));return qk[r[0]](r)};se.object=rC.factory(se);se.boolean={encode:function(r){return r?"C":"B"},decode:function(r){return r==="C"}};se.undefined={encode:function(r){return"L"},decode:function(){}};var qk={A:se.object.decode,B:se.boolean.decode,C:se.boolean.decode,D:se.number.decode,F:se.number.decode,J:se.string.decode,K:se.object.decode,L:se.undefined.decode};se.buffer=!1;se.type="charwise"});var kC={};K(kC,{CRDT:()=>bi,Database:()=>Bs,Index:()=>tl,NotFoundError:()=>Dt,PACKAGE_VERSION:()=>xC,Result:()=>C,UInt8ArrayEqual:()=>qh,blockstore:()=>Jc,bs:()=>Jc,dataDir:()=>Wh,ensureLogger:()=>H,ensureSuperLog:()=>_r,ensureSuperThis:()=>Xo,exceptionWrapper:()=>ei,falsyToUndef:()=>Yo,fireproof:()=>wC,getKey:()=>Zo,getName:()=>UA,getStore:()=>Nt,index:()=>Ls,isFalsy:()=>Hh,isNotFoundError:()=>Mt,rt:()=>nl,runtime:()=>nl,throwFalsy:()=>me});ae();function yy(r,e=1/0,t=!1){let n=[],s=!1;async function o(){if(s||n.length===0)return;s=!0;let i=n.splice(0,e),a=i.map(c=>c.task);if(t){let c=a.map(async(l,u)=>{try{let f=await r([l]);i[u].resolve(f)}catch(f){i[u].reject(f)}});await Promise.all(c)}else try{let c=await r(a);i.forEach(l=>l.resolve(c))}catch(c){i.forEach(l=>l.reject(c))}s=!1,o()}return{push(i){return new Promise((a,c)=>{n.push({task:i,resolve:a,reject:c}),o()})}}}ae();var Cu={};K(Cu,{Block:()=>ka,create:()=>Iu,createUnsafe:()=>Iy,decode:()=>lr,encode:()=>Qn});ar();var bu={};K(bu,{base32:()=>Vn,base32hex:()=>$1,base32hexpad:()=>z1,base32hexpadupper:()=>H1,base32hexupper:()=>K1,base32pad:()=>F1,base32padupper:()=>U1,base32upper:()=>R1,base32z:()=>j1});it();var Vn=te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),R1=te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),F1=te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),U1=te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$1=te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),K1=te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),z1=te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),H1=te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),j1=te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var xu={};K(xu,{base36:()=>lo,base36upper:()=>V1});it();var lo=cr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),V1=cr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});Rr();ar();ar();var q1=vy,ky=128,G1=127,J1=~G1,Q1=Math.pow(2,31);function vy(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Q1;)e[t++]=r&255|ky,r/=128;for(;r&J1;)e[t++]=r&255|ky,r>>>=7;return e[t]=r|0,vy.bytes=t-n+1,e}var Y1=Su,X1=128,Sy=127;function Su(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Su.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Sy)<<s:(i&Sy)*Math.pow(2,s),s+=7}while(i>=X1);return Su.bytes=o-n,t}var Z1=Math.pow(2,7),ev=Math.pow(2,14),tv=Math.pow(2,21),rv=Math.pow(2,28),nv=Math.pow(2,35),sv=Math.pow(2,42),ov=Math.pow(2,49),iv=Math.pow(2,56),av=Math.pow(2,63),cv=function(r){return r<Z1?1:r<ev?2:r<tv?3:r<rv?4:r<nv?5:r<sv?6:r<ov?7:r<iv?8:r<av?9:10},lv={encode:q1,decode:Y1,encodingLength:cv},uv=lv,uo=uv;function fo(r,e=0){return[uo.decode(r,e),uo.decode.bytes]}function Wn(r,e,t=0){return uo.encode(r,e,t),e}function qn(r){return uo.encodingLength(r)}function Fr(r,e){let t=e.byteLength,n=qn(r),s=n+qn(t),o=new Uint8Array(s+t);return Wn(r,o,0),Wn(t,o,n),o.set(e,s),new Gn(r,t,e,o)}function Ur(r){let e=qe(r),[t,n]=fo(e),[s,o]=fo(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Gn(t,s,i,e)}function Ey(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&hu(r.bytes,t.bytes)}}var Gn=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function vu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return hv(t,Eu(r),e??J.encoder);default:return dv(t,Eu(r),e??Vn.encoder)}}var Ty=new WeakMap;function Eu(r){let e=Ty.get(r);if(e==null){let t=new Map;return Ty.set(r,t),t}return e}var N=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==ho)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==pv)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Fr(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Ey(e.multihash,n.multihash)}toString(e){return vu(this,e)}toJSON(){return{"/":vu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??_y(n,s,o.bytes))}else if(t[mv]===!0){let{version:n,multihash:s,code:o}=t,i=Ur(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ho)throw new Error(`Version 0 CID must use dag-pb (code: ${ho}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=_y(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ho,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=qe(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Gn(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,p]=fo(e.subarray(t));return t+=p,f},s=n(),o=ho;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=fv(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Eu(o).set(n,e),o}};function fv(r,e){switch(r[0]){case"Q":{let t=e??J;return[J.prefix,t.decode(`${J.prefix}${r}`)]}case J.prefix:{let t=e??J;return[J.prefix,t.decode(r)]}case Vn.prefix:{let t=e??Vn;return[Vn.prefix,t.decode(r)]}case lo.prefix:{let t=e??lo;return[lo.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function hv(r,e,t){let{prefix:n}=t;if(n!==J.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function dv(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var ho=112,pv=18;function _y(r,e,t){let n=qn(r),s=n+qn(e),o=new Uint8Array(s+t.byteLength);return Wn(r,o,0),Wn(e,o,n),o.set(t,s),o}var mv=Symbol.for("@ipld/js-cid/CID");function Kr({name:r,code:e,encode:t}){return new Tu(r,e,t)}var Tu=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Fr(this.code,t):t.then(n=>Fr(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ba({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*yv(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let s=[...r,t],o=N.asCID(n);o!=null?yield[s.join("/"),o]:typeof n=="object"&&(yield*_u(n,s))}else{let t=N.asCID(e);t!=null?yield[r.join("/"),t]:yield*_u(e,r)}}function*_u(r,e){if(r==null||r instanceof Uint8Array)return;let t=N.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,s]of Object.entries(r)){let o=[...e,n];yield*yv(o,s)}}function*gv(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let s=[...r,t];yield s.join("/"),typeof n=="object"&&N.asCID(n)==null&&(yield*Au(n,s))}else yield*Au(e,r)}function*Au(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let s=[...e,t];yield s.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&N.asCID(n)==null&&(yield*gv(s,n))}}function wv(r,e){let t=r;for(let[n,s]of e.entries()){if(t=t[s],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(i=>`[${JSON.stringify(i)}]`).join("")}`);let o=N.asCID(t);if(o!=null)return{value:o,remaining:e.slice(n+1).join("/")}}return{value:t}}var Se=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:ba(),bytes:ba(),value:ba(),asBlock:ba()})}links(){return _u(this.value,[])}tree(){return Au(this.value,[])}get(e="/"){return wv(this.value,e.split("/").filter(Boolean))}};async function Jn({value:r,codec:e,hasher:t}){if(typeof r>"u")throw new Error('Missing required argument "value"');if(e==null||t==null)throw new Error("Missing required argument: codec or hasher");let n=e.encode(r),s=await t.digest(n),o=N.create(1,e.code,s);return new Se({value:r,bytes:n,cid:o})}async function xa({bytes:r,codec:e,hasher:t}){if(r==null)throw new Error('Missing required argument "bytes"');if(e==null||t==null)throw new Error("Missing required argument: codec or hasher");let n=e.decode(r),s=await t.digest(r),o=N.create(1,e.code,s);return new Se({value:n,bytes:r,cid:o})}var ka=Se;async function lr({bytes:r,codec:e,hasher:t}){if(r==null)throw new Error('Missing required argument "bytes"');if(e==null||t==null)throw new Error("Missing required argument: codec or hasher");let n=await Promise.resolve(e.decode(r)),s=await t.digest(r),o=N.create(1,e.code,s);return new Se({value:n,bytes:r,cid:o})}async function Qn({value:r,codec:e,hasher:t}){if(typeof r>"u")throw new Error('Missing required argument "value"');if(e==null||t==null)throw new Error("Missing required argument: codec or hasher");let n=await Promise.resolve(e.encode(r)),s=await t.digest(n),o=N.create(1,e.code,s);return new Se({value:r,bytes:n,cid:o})}async function Iu({bytes:r,cid:e,hasher:t,codec:n}){if(r==null)throw new Error('Missing required argument "bytes"');if(t==null)throw new Error('Missing required argument "hasher"');let s=await Promise.resolve(n.decode(r)),o=await t.digest(r);if(!Kt.equals(e.multihash.bytes,o.bytes))throw new Error("CID hash does not match bytes");return Iy({bytes:r,cid:e,value:s,codec:n})}async function Iy({bytes:r,cid:e,value:t,codec:n}){let s=await Promise.resolve(t!==void 0?t:n?.decode(r));if(s===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new ka({cid:e,bytes:r,value:s})}function Cy(r){if(r==null)return!1;let e=r;return e["/"]!=null&&e["/"]===e.bytes||r.asCID===r}function Sa(r,e){return N.parse(r,e)}var Lu={};K(Lu,{sha256:()=>Q,sha512:()=>xv});function Ly(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Q=Kr({name:"sha2-256",code:18,encode:Ly("SHA-256")}),xv=Kr({name:"sha2-512",code:19,encode:Ly("SHA-512")});var re={};K(re,{code:()=>ko,decode:()=>So,decodeOptions:()=>Xv,encode:()=>Ku,encodeOptions:()=>Qv,name:()=>Zv,toByteView:()=>Mg});var kv=["string","number","bigint","symbol"],Sv=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function By(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(kv.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(vv(r))return"Buffer";let t=Ev(r);return t||"Object"}function vv(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function Ev(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(Sv.includes(e))return e}var w=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};w.uint=new w(0,"uint",!0);w.negint=new w(1,"negint",!0);w.bytes=new w(2,"bytes",!0);w.string=new w(3,"string",!0);w.array=new w(4,"array",!1);w.map=new w(5,"map",!1);w.tag=new w(6,"tag",!1);w.float=new w(7,"float",!0);w.false=new w(7,"false",!0);w.true=new w(7,"true",!0);w.null=new w(7,"null",!0);w.undefined=new w(7,"undefined",!0);w.break=new w(7,"break",!0);var v=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Yn=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Tv=new TextDecoder,_v=new TextEncoder;function va(r){return Yn&&globalThis.Buffer.isBuffer(r)}function po(r){return r instanceof Uint8Array?va(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var My=Yn?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):Dy(r,e,t):(r,e,t)=>t-e>64?Tv.decode(r.subarray(e,t)):Dy(r,e,t),Ea=Yn?r=>r.length>64?globalThis.Buffer.from(r):Py(r):r=>r.length>64?_v.encode(r):Py(r),Et=r=>Uint8Array.from(r),Xn=Yn?(r,e,t)=>va(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Oy=Yn?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),po(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let s of r)n+s.length>t.length&&(s=s.subarray(0,t.length-n)),t.set(s,n),n+=s.length;return t},Ry=Yn?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Fy(r,e){if(va(r)&&va(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function Py(r){let e=[],t=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(s=65536+((s&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128)}return e}function Dy(r,e,t){let n=[];for(;e<t;){let s=r[e],o=null,i=s>239?4:s>223?3:s>191?2:1;if(e+i<=t){let a,c,l,u;switch(i){case 1:s<128&&(o=s);break;case 2:a=r[e+1],(a&192)===128&&(u=(s&31)<<6|a&63,u>127&&(o=u));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(u=(s&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(o=u));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(s&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(o=u))}}o===null?(o=65533,i=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),e+=i}return Bu(n)}var Ny=4096;function Bu(r){let e=r.length;if(e<=Ny)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Ny));return t}var Av=256,mo=class{constructor(e=Av){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let s=t.length-(this.maxCursor-this.cursor)-1;t.set(e,s)}else{if(t){let s=t.length-(this.maxCursor-this.cursor)-1;s<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,s),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Ry(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=Xn(n,0,this.cursor)}else t=Oy(this.chunks,this.cursor);return e&&this.reset(),t}};var L="CBOR decode error:",zt="CBOR encode error:",yo=[];yo[23]=1;yo[24]=2;yo[25]=3;yo[26]=5;yo[27]=9;function Ht(r,e,t){if(r.length-e<t)throw new Error(`${L} not enough data for type`)}var ue=[24,256,65536,4294967296,BigInt("18446744073709551616")];function De(r,e,t){Ht(r,e,1);let n=r[e];if(t.strict===!0&&n<ue[0])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);return n}function Ne(r,e,t){Ht(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<ue[1])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);return n}function Me(r,e,t){Ht(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<ue[2])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);return n}function Oe(r,e,t){Ht(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],s=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],o=(BigInt(n)<<BigInt(32))+BigInt(s);if(t.strict===!0&&o<ue[3])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(t.allowBigInt===!0)return o;throw new Error(`${L} integers outside of the safe integer range are not supported`)}function Uy(r,e,t,n){return new v(w.uint,De(r,e+1,n),2)}function $y(r,e,t,n){return new v(w.uint,Ne(r,e+1,n),3)}function Ky(r,e,t,n){return new v(w.uint,Me(r,e+1,n),5)}function zy(r,e,t,n){return new v(w.uint,Oe(r,e+1,n),9)}function Ge(r,e){return de(r,0,e.value)}function de(r,e,t){if(t<ue[0]){let n=Number(t);r.push([e|n])}else if(t<ue[1]){let n=Number(t);r.push([e|24,n])}else if(t<ue[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<ue[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<ue[4]){let s=[e|27,0,0,0,0,0,0,0],o=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));s[8]=o&255,o=o>>8,s[7]=o&255,o=o>>8,s[6]=o&255,o=o>>8,s[5]=o&255,s[4]=i&255,i=i>>8,s[3]=i&255,i=i>>8,s[2]=i&255,i=i>>8,s[1]=i&255,r.push(s)}else throw new Error(`${L} encountered BigInt larger than allowable range`)}}Ge.encodedSize=function(e){return de.encodedSize(e.value)};de.encodedSize=function(e){return e<ue[0]?1:e<ue[1]?2:e<ue[2]?3:e<ue[3]?5:9};Ge.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Hy(r,e,t,n){return new v(w.negint,-1-De(r,e+1,n),2)}function jy(r,e,t,n){return new v(w.negint,-1-Ne(r,e+1,n),3)}function Vy(r,e,t,n){return new v(w.negint,-1-Me(r,e+1,n),5)}var Pu=BigInt(-1),Wy=BigInt(1);function qy(r,e,t,n){let s=Oe(r,e+1,n);if(typeof s!="bigint"){let o=-1-s;if(o>=Number.MIN_SAFE_INTEGER)return new v(w.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${L} integers outside of the safe integer range are not supported`);return new v(w.negint,Pu-BigInt(s),9)}function Ta(r,e){let t=e.value,n=typeof t=="bigint"?t*Pu-Wy:t*-1-1;de(r,e.type.majorEncoded,n)}Ta.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*Pu-Wy:t*-1-1;return n<ue[0]?1:n<ue[1]?2:n<ue[2]?3:n<ue[3]?5:9};Ta.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function go(r,e,t,n){Ht(r,e,t+n);let s=Xn(r,e+t,e+t+n);return new v(w.bytes,s,t+n)}function Gy(r,e,t,n){return go(r,e,1,t)}function Jy(r,e,t,n){return go(r,e,2,De(r,e+1,n))}function Qy(r,e,t,n){return go(r,e,3,Ne(r,e+1,n))}function Yy(r,e,t,n){return go(r,e,5,Me(r,e+1,n))}function Xy(r,e,t,n){let s=Oe(r,e+1,n);if(typeof s=="bigint")throw new Error(`${L} 64-bit integer bytes lengths not supported`);return go(r,e,9,s)}function _a(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===w.string?Ea(r.value):r.value),r.encodedBytes}function Zn(r,e){let t=_a(e);de(r,e.type.majorEncoded,t.length),r.push(t)}Zn.encodedSize=function(e){let t=_a(e);return de.encodedSize(t.length)+t.length};Zn.compareTokens=function(e,t){return Cv(_a(e),_a(t))};function Cv(r,e){return r.length<e.length?-1:r.length>e.length?1:Fy(r,e)}function wo(r,e,t,n,s){let o=t+n;Ht(r,e,o);let i=new v(w.string,My(r,e+t,e+o),o);return s.retainStringBytes===!0&&(i.byteValue=Xn(r,e+t,e+o)),i}function Zy(r,e,t,n){return wo(r,e,1,t,n)}function eg(r,e,t,n){return wo(r,e,2,De(r,e+1,n),n)}function tg(r,e,t,n){return wo(r,e,3,Ne(r,e+1,n),n)}function rg(r,e,t,n){return wo(r,e,5,Me(r,e+1,n),n)}function ng(r,e,t,n){let s=Oe(r,e+1,n);if(typeof s=="bigint")throw new Error(`${L} 64-bit integer string lengths not supported`);return wo(r,e,9,s,n)}var sg=Zn;function es(r,e,t,n){return new v(w.array,n,t)}function og(r,e,t,n){return es(r,e,1,t)}function ig(r,e,t,n){return es(r,e,2,De(r,e+1,n))}function ag(r,e,t,n){return es(r,e,3,Ne(r,e+1,n))}function cg(r,e,t,n){return es(r,e,5,Me(r,e+1,n))}function lg(r,e,t,n){let s=Oe(r,e+1,n);if(typeof s=="bigint")throw new Error(`${L} 64-bit integer array lengths not supported`);return es(r,e,9,s)}function ug(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${L} indefinite length items not allowed`);return es(r,e,1,1/0)}function Aa(r,e){de(r,w.array.majorEncoded,e.value)}Aa.compareTokens=Ge.compareTokens;Aa.encodedSize=function(e){return de.encodedSize(e.value)};function ts(r,e,t,n){return new v(w.map,n,t)}function fg(r,e,t,n){return ts(r,e,1,t)}function hg(r,e,t,n){return ts(r,e,2,De(r,e+1,n))}function dg(r,e,t,n){return ts(r,e,3,Ne(r,e+1,n))}function pg(r,e,t,n){return ts(r,e,5,Me(r,e+1,n))}function mg(r,e,t,n){let s=Oe(r,e+1,n);if(typeof s=="bigint")throw new Error(`${L} 64-bit integer map lengths not supported`);return ts(r,e,9,s)}function yg(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${L} indefinite length items not allowed`);return ts(r,e,1,1/0)}function Ia(r,e){de(r,w.map.majorEncoded,e.value)}Ia.compareTokens=Ge.compareTokens;Ia.encodedSize=function(e){return de.encodedSize(e.value)};function gg(r,e,t,n){return new v(w.tag,t,1)}function wg(r,e,t,n){return new v(w.tag,De(r,e+1,n),2)}function bg(r,e,t,n){return new v(w.tag,Ne(r,e+1,n),3)}function xg(r,e,t,n){return new v(w.tag,Me(r,e+1,n),5)}function kg(r,e,t,n){return new v(w.tag,Oe(r,e+1,n),9)}function Ca(r,e){de(r,w.tag.majorEncoded,e.value)}Ca.compareTokens=Ge.compareTokens;Ca.encodedSize=function(e){return de.encodedSize(e.value)};var Mv=20,Ov=21,Rv=22,Fv=23;function Sg(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${L} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new v(w.null,null,1):new v(w.undefined,void 0,1)}function vg(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${L} indefinite length items not allowed`);return new v(w.break,void 0,1)}function Du(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${L} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${L} Infinity values are not supported`)}return new v(w.float,r,e)}function Eg(r,e,t,n){return Du(Nu(r,e+1),3,n)}function Tg(r,e,t,n){return Du(Mu(r,e+1),5,n)}function _g(r,e,t,n){return Du(Lg(r,e+1),9,n)}function La(r,e,t){let n=e.value;if(n===!1)r.push([w.float.majorEncoded|Mv]);else if(n===!0)r.push([w.float.majorEncoded|Ov]);else if(n===null)r.push([w.float.majorEncoded|Rv]);else if(n===void 0)r.push([w.float.majorEncoded|Fv]);else{let s,o=!1;(!t||t.float64!==!0)&&(Ig(n),s=Nu(at,1),n===s||Number.isNaN(n)?(at[0]=249,r.push(at.slice(0,3)),o=!0):(Cg(n),s=Mu(at,1),n===s&&(at[0]=250,r.push(at.slice(0,5)),o=!0))),o||(Uv(n),s=Lg(at,1),at[0]=251,r.push(at.slice(0,9)))}}La.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){Ig(n);let s=Nu(at,1);if(n===s||Number.isNaN(n))return 3;if(Cg(n),s=Mu(at,1),n===s)return 5}return 9};var Ag=new ArrayBuffer(9),Je=new DataView(Ag,1),at=new Uint8Array(Ag,0);function Ig(r){if(r===1/0)Je.setUint16(0,31744,!1);else if(r===-1/0)Je.setUint16(0,64512,!1);else if(Number.isNaN(r))Je.setUint16(0,32256,!1);else{Je.setFloat32(0,r);let e=Je.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Je.setUint16(0,31744,!1);else if(t===0)Je.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let s=t-127;s<-24?Je.setUint16(0,0):s<-14?Je.setUint16(0,(e&2147483648)>>16|1<<24+s,!1):Je.setUint16(0,(e&2147483648)>>16|s+15<<10|n>>13,!1)}}}function Nu(r,e){if(r.length-e<2)throw new Error(`${L} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,s=t&1023,o;return n===0?o=s*2**-24:n!==31?o=(s+1024)*2**(n-25):o=s===0?1/0:NaN,t&32768?-o:o}function Cg(r){Je.setFloat32(0,r,!1)}function Mu(r,e){if(r.length-e<4)throw new Error(`${L} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Uv(r){Je.setFloat64(0,r,!1)}function Lg(r,e){if(r.length-e<8)throw new Error(`${L} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}La.compareTokens=Ge.compareTokens;function V(r,e,t){throw new Error(`${L} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Ba(r){return()=>{throw new Error(`${L} ${r}`)}}var I=[];for(let r=0;r<=23;r++)I[r]=V;I[24]=Uy;I[25]=$y;I[26]=Ky;I[27]=zy;I[28]=V;I[29]=V;I[30]=V;I[31]=V;for(let r=32;r<=55;r++)I[r]=V;I[56]=Hy;I[57]=jy;I[58]=Vy;I[59]=qy;I[60]=V;I[61]=V;I[62]=V;I[63]=V;for(let r=64;r<=87;r++)I[r]=Gy;I[88]=Jy;I[89]=Qy;I[90]=Yy;I[91]=Xy;I[92]=V;I[93]=V;I[94]=V;I[95]=Ba("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)I[r]=Zy;I[120]=eg;I[121]=tg;I[122]=rg;I[123]=ng;I[124]=V;I[125]=V;I[126]=V;I[127]=Ba("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)I[r]=og;I[152]=ig;I[153]=ag;I[154]=cg;I[155]=lg;I[156]=V;I[157]=V;I[158]=V;I[159]=ug;for(let r=160;r<=183;r++)I[r]=fg;I[184]=hg;I[185]=dg;I[186]=pg;I[187]=mg;I[188]=V;I[189]=V;I[190]=V;I[191]=yg;for(let r=192;r<=215;r++)I[r]=gg;I[216]=wg;I[217]=bg;I[218]=xg;I[219]=kg;I[220]=V;I[221]=V;I[222]=V;I[223]=V;for(let r=224;r<=243;r++)I[r]=Ba("simple values are not supported");I[244]=V;I[245]=V;I[246]=V;I[247]=Sg;I[248]=Ba("simple values are not supported");I[249]=Eg;I[250]=Tg;I[251]=_g;I[252]=V;I[253]=V;I[254]=V;I[255]=vg;var ct=[];for(let r=0;r<24;r++)ct[r]=new v(w.uint,r,1);for(let r=-1;r>=-24;r--)ct[31-r]=new v(w.negint,r,1);ct[64]=new v(w.bytes,new Uint8Array(0),1);ct[96]=new v(w.string,"",1);ct[128]=new v(w.array,0,1);ct[160]=new v(w.map,0,1);ct[244]=new v(w.false,!1,1);ct[245]=new v(w.true,!0,1);ct[246]=new v(w.null,null,1);function Pa(r){switch(r.type){case w.false:return Et([244]);case w.true:return Et([245]);case w.null:return Et([246]);case w.bytes:return r.value.length?void 0:Et([64]);case w.string:return r.value===""?Et([96]):void 0;case w.array:return r.value===0?Et([128]):void 0;case w.map:return r.value===0?Et([160]):void 0;case w.uint:return r.value<24?Et([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return Et([31-Number(r.value)])}}var Kv={float64:!1,mapSorter:Hv,quickEncodeToken:Pa};function Ru(){let r=[];return r[w.uint.major]=Ge,r[w.negint.major]=Ta,r[w.bytes.major]=Zn,r[w.string.major]=sg,r[w.array.major]=Aa,r[w.map.major]=Ia,r[w.tag.major]=Ca,r[w.float.major]=La,r}var Bg=Ru(),Ou=new mo,Da=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${zt} object contains circular references`);return new r(t,e)}},ur={null:new v(w.null,null),undefined:new v(w.undefined,void 0),true:new v(w.true,!0),false:new v(w.false,!1),emptyArray:new v(w.array,0),emptyMap:new v(w.map,0)},fr={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new v(w.float,r):r>=0?new v(w.uint,r):new v(w.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new v(w.uint,r):new v(w.negint,r)},Uint8Array(r,e,t,n){return new v(w.bytes,r)},string(r,e,t,n){return new v(w.string,r)},boolean(r,e,t,n){return r?ur.true:ur.false},null(r,e,t,n){return ur.null},undefined(r,e,t,n){return ur.undefined},ArrayBuffer(r,e,t,n){return new v(w.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new v(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[ur.emptyArray,new v(w.break)]:ur.emptyArray;n=Da.createCheck(n,r);let s=[],o=0;for(let i of r)s[o++]=bo(i,t,n);return t.addBreakTokens?[new v(w.array,r.length),s,new v(w.break)]:[new v(w.array,r.length),s]},Object(r,e,t,n){let s=e!=="Object",o=s?r.keys():Object.keys(r),i=s?r.size:o.length;if(!i)return t.addBreakTokens===!0?[ur.emptyMap,new v(w.break)]:ur.emptyMap;n=Da.createCheck(n,r);let a=[],c=0;for(let l of o)a[c++]=[bo(l,t,n),bo(s?r.get(l):r[l],t,n)];return zv(a,t),t.addBreakTokens?[new v(w.map,i),a,new v(w.break)]:[new v(w.map,i),a]}};fr.Map=fr.Object;fr.Buffer=fr.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))fr[`${r}Array`]=fr.DataView;function bo(r,e={},t){let n=By(r),s=e&&e.typeEncoders&&e.typeEncoders[n]||fr[n];if(typeof s=="function"){let i=s(r,n,e,t);if(i!=null)return i}let o=fr[n];if(!o)throw new Error(`${zt} unsupported type: ${n}`);return o(r,n,e,t)}function zv(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Hv(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let s=t.type.major,o=Bg[s].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function Pg(r,e,t,n){if(Array.isArray(e))for(let s of e)Pg(r,s,t,n);else t[e.type.major](r,e,n)}function Fu(r,e,t){let n=bo(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let s=t.quickEncodeToken(n);if(s)return s;let o=e[n.type.major];if(o.encodedSize){let i=o.encodedSize(n,t),a=new mo(i);if(o(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return po(a.chunks[0])}}return Ou.reset(),Pg(Ou,n,e,t),Ou.toBytes(!0)}function hr(r,e){return e=Object.assign({},Kv,e),Fu(r,Bg,e)}var jv={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Na=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=ct[e];if(t===void 0){let n=I[e];if(!n)throw new Error(`${L} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let s=e&31;t=n(this.data,this._pos,s,this.options)}return this._pos+=t.encodedLength,t}},xo=Symbol.for("DONE"),Ma=Symbol.for("BREAK");function Vv(r,e,t){let n=[];for(let s=0;s<r.value;s++){let o=rs(e,t);if(o===Ma){if(r.value===1/0)break;throw new Error(`${L} got unexpected break to lengthed array`)}if(o===xo)throw new Error(`${L} found array but not enough entries (got ${s}, expected ${r.value})`);n[s]=o}return n}function Wv(r,e,t){let n=t.useMaps===!0,s=n?void 0:{},o=n?new Map:void 0;for(let i=0;i<r.value;i++){let a=rs(e,t);if(a===Ma){if(r.value===1/0)break;throw new Error(`${L} got unexpected break to lengthed map`)}if(a===xo)throw new Error(`${L} found map but not enough entries (got ${i} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${L} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&o.has(a)||!n&&a in s))throw new Error(`${L} found repeat map key "${a}"`);let c=rs(e,t);if(c===xo)throw new Error(`${L} found map but not enough entries (got ${i} [no value], expected ${r.value})`);n?o.set(a,c):s[a]=c}return n?o:s}function rs(r,e){if(r.done())return xo;let t=r.next();if(t.type===w.break)return Ma;if(t.type.terminal)return t.value;if(t.type===w.array)return Vv(t,r,e);if(t.type===w.map)return Wv(t,r,e);if(t.type===w.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=rs(r,e);return e.tags[t.value](n)}throw new Error(`${L} tag not supported (${t.value})`)}throw new Error("unsupported")}function Uu(r,e){if(!(r instanceof Uint8Array))throw new Error(`${L} data to decode must be a Uint8Array`);e=Object.assign({},jv,e);let t=e.tokenizer||new Na(r,e),n=rs(t,e);if(n===xo)throw new Error(`${L} did not find any content to decode`);if(n===Ma)throw new Error(`${L} got unexpected break`);return[n,r.subarray(t.pos())]}function Tt(r,e){let[t,n]=Uu(r,e);if(n.length>0)throw new Error(`${L} too many terminals, data makes no sense`);return t}var Ng=42;function Mg(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function qv(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=N.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new v(w.tag,Ng),new v(w.bytes,t)]}function Gv(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Jv(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var $u={float64:!0,typeEncoders:{Object:qv,undefined:Gv,number:Jv}},Qv={...$u,typeEncoders:{...$u.typeEncoders}};function Yv(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return N.decode(r.subarray(1))}var Oa={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Oa.tags[Ng]=Yv;var Xv={...Oa,tags:Oa.tags.slice()},Zv="dag-cbor",ko=113,Ku=r=>hr(r,$u),So=r=>Tt(Mg(r),Oa);var Hr=async(r,e,t)=>{let n=new _t(r),s=new Map(e.map(i=>[i.toString(),i]));if(s.has(t.toString()))return e;let o=!1;for(let i of e)await Og(n,t,i)&&(s.delete(i.toString()),s.set(t.toString(),t),o=!0);if(o)return[...s.values()];for(let i of e)if(await Og(n,i,t))return e;return e.concat(t)},jt=class extends Se{constructor({cid:e,value:t,bytes:n,prefix:s}){super({cid:e,value:t,bytes:n}),this.prefix=s}static create(e,t){return eE({data:e,parents:t??[]})}},_t=class{constructor(e){this._blocks=e}async get(e){let t=await this._blocks.get(e);if(!t)throw new Error(`missing block: ${e}`);return zu(t.bytes)}},eE=async r=>{let{cid:e,bytes:t}=await Jn({value:r,codec:re,hasher:Q});return new Se({cid:e,value:r,bytes:t})},zu=async r=>{let{cid:e,value:t}=await xa({bytes:r,codec:re,hasher:Q});return new Se({cid:e,value:t,bytes:r})},Og=async(r,e,t)=>{if(e.toString()===t.toString())return!0;let[{value:n},{value:s}]=await Promise.all([r.get(e),r.get(t)]),o=[...n.parents],i=new Set;for(;o.length;){let a=o.shift();if(!a)break;if(a.toString()===t.toString())return!0;if(s.parents.some(l=>a.toString()===l.toString())||i.has(a.toString()))continue;i.add(a.toString());let{value:c}=await r.get(a);o.push(...c.parents)}return!1},Hu=async function*(r,e,t={}){let n=t.renderNodeLabel??(c=>tE(c.cid)),s=new _t(r);yield"digraph clock {",yield' node [shape=point fontname="Courier"]; head;';let o=await Promise.all(e.map(c=>s.get(c))),i=[],a=new Set;for(let c of o){a.add(c.cid.toString()),yield` node [shape=oval fontname="Courier"]; ${c.cid} [label="${n(c)}"];`,yield` head -> ${c.cid};`;for(let l of c.value.parents)yield` ${c.cid} -> ${l};`;i.push(...c.value.parents)}for(;i.length;){let c=i.shift();if(!c)break;if(a.has(c.toString()))continue;a.add(c.toString());let l=await s.get(c);yield` node [shape=oval]; ${c} [label="${n(l)}" fontname="Courier"];`;for(let u of l.value.parents)yield` ${c} -> ${u};`;i.push(...l.value.parents)}yield"}"},tE=r=>`${String(r).slice(0,4)}..${String(r).slice(-4)}`;var vo="ascii",rE=4096,dr=class extends Se{constructor({cid:e,value:t,bytes:n}){super({cid:e,value:t,bytes:n})}static create(e){return It(Fg(e))}},Fg=r=>({entries:[],...Vt(r)}),Vt=r=>({version:1,keyChars:r?.keyChars??vo,maxKeySize:r?.maxKeySize??rE,prefix:r?.prefix??""}),At=(r,e)=>({...Fg(e),entries:r}),Ug=new WeakMap,It=async r=>{let{cid:e,bytes:t}=await Jn({value:r,codec:re,hasher:Q}),n=new dr({cid:e,value:r,bytes:t});return Ug.set(n.bytes,n),n},nE=async r=>{let e=Ug.get(r);if(e)return e;let{cid:t,value:n}=await xa({bytes:r,codec:re,hasher:Q});if(!sE(n))throw new Error(`invalid shard: ${t}`);return new dr({cid:t,value:n,bytes:r})},sE=r=>r!=null&&typeof r=="object"&&Array.isArray(r.entries)&&r.version===1&&typeof r.maxKeySize=="number"&&typeof r.keyChars=="string"&&typeof r.prefix=="string",ju=r=>Cy(r)&&r.code===ko,Qe=class{constructor(e){this._blocks=e}async get(e){let t=await this._blocks.get(e);if(!t)throw new Error(`missing block: ${e}`);return nE(t.bytes)}},pr=(r,e)=>{let t=[];for(let[n,s]of r.entries()){let[o,i]=s;if(e[0]===o){Array.isArray(e[1])?Array.isArray(i)&&i[1]!=null&&e[1][1]==null?t.push([o,[e[1][0],i[1]]]):t.push(e):Array.isArray(i)?t.push([o,[i[0],e[1]]]):t.push(e);for(let a=n+1;a<r.length;a++)t.push(r[a]);return t}if(n===0&&e[0]<o){t.push(e);for(let a=n;a<r.length;a++)t.push(r[a]);return t}if(n>0&&e[0]>r[n-1][0]&&e[0]<o){t.push(e);for(let a=n;a<r.length;a++)t.push(r[a]);return t}t.push(s)}return t.push(e),t},Ra=r=>/^[\x20-\x7E]*$/.test(r);var Eo=async(r,e,t,n)=>{let s=new Qe(r),o=await s.get(e);if(o.value.keyChars!==vo)throw new Error(`unsupported key character set: ${o.value.keyChars}`);if(!Ra(t))throw new Error("key contains non-ASCII characters");if(new TextEncoder().encode(t).length>o.value.maxKeySize)throw new Error(`UTF-8 encoded key exceeds max size of ${o.value.maxKeySize} bytes`);let i=await Fa(s,o,t),a=i[i.length-1],c=t.slice(a.value.prefix.length),l=[c,n],u=[...a.value.entries],f=[];for(let[m,d]of u.entries()){let[y,g]=d;if(y===c)break;let b=y.length<c.length?y:c,x=b===y?c:y,k="";for(let S of b){let T=k+S;if(!x.startsWith(T))break;k=T}if(k.length){let S=[];k!==c&&(S=pr(S,[c.slice(k.length),n])),k!==y&&(S=pr(S,[y.slice(k.length),g]));let T=await It(At(S,{...a.value,prefix:a.value.prefix+k}));f.push(T);let E=[...k];for(let _=E.length-1;_>0;_--){let W={...a.value,prefix:a.value.prefix+E.slice(0,_).join("")},le;if(_===E.length-1&&k===y){if(Array.isArray(g))throw new Error("found a shard link when expecting a value");le=[T.cid,g]}else _===E.length-1&&k===c?le=[T.cid,n]:le=[T.cid];let Te=await It(At([[E[_],le]],W));f.push(Te),T=Te}if(u.splice(m,1),E.length===1&&k===y){if(Array.isArray(g))throw new Error("found a shard link when expecting a value");l=[E[0],[T.cid,g]]}else E.length===1&&k===c?l=[E[0],[T.cid,n]]:l=[E[0],[T.cid]];break}}let p=At(pr(u,l),a.value),h=await It(p);if(h.cid.toString()===a.cid.toString())return{root:e,additions:[],removals:[]};f.push(h);for(let m=i.length-2;m>=0;m--){let d=i[m],y=h.value.prefix.slice(d.value.prefix.length),g=At(d.value.entries.map(b=>{let[x,k]=b;if(x!==y)return b;if(!Array.isArray(k))throw new Error(`"${y}" is not a shard link in: ${d.cid}`);return k[1]==null?[x,[h.cid]]:[x,[h.cid,k[1]]]}),d.value);h=await It(g),f.push(h)}return{root:f[f.length-1].cid,additions:f,removals:i}},$g=async(r,e,t)=>{let n=new Qe(r),s=await n.get(e),o=await Fa(n,s,t),i=o[o.length-1],a=t.slice(i.value.prefix.length),c=i.value.entries.find(([l])=>l===a);if(c)return Array.isArray(c[1])?c[1][1]:c[1]},Wu=async(r,e,t)=>{let n=new Qe(r),s=await n.get(e),o=await Fa(n,s,t),i=o[o.length-1],a=t.slice(i.value.prefix.length),c=i.value.entries.findIndex(([m])=>m===a);if(c===-1)return{root:e,additions:[],removals:[]};let l=i.value.entries[c];if(Array.isArray(l[1])&&l[1][1]==null)return{root:e,additions:[],removals:[]};let u=[],f=[...o],p=At([...i.value.entries],i.value);if(Array.isArray(l[1]))p.entries[c]=[l[0],[l[1][0]]];else for(p.entries.splice(c,1);!p.entries.length;){let m=o[o.length-1],d=o[o.length-2];if(!d)break;o.pop(),p=At(d.value.entries.filter(y=>Array.isArray(y[1])?y[1][0].toString()!==m.cid.toString():!0),d.value)}let h=await It(p);u.push(h);for(let m=o.length-2;m>=0;m--){let d=o[m],y=h.value.prefix.slice(d.value.prefix.length),g=At(d.value.entries.map(b=>{let[x,k]=b;if(x!==y)return b;if(!Array.isArray(k))throw new Error(`"${y}" is not a shard link in: ${d.cid}`);return k[1]==null?[x,[h.cid]]:[x,[h.cid,k[1]]]}),d.value);h=await It(g),u.push(h)}return{root:u[u.length-1].cid,additions:u,removals:f}},oE=r=>{let e=r??{};return"prefix"in e&&!!e.prefix},iE=r=>{let e=r??{};return"gt"in e&&!!e.gt||"gte"in e&&!!e.gte||"lt"in e&&!!e.lt||"lte"in e&&!!e.lte},aE=r=>"gt"in r&&!!r.gt||"gte"in r&&!!r.gte,cE=r=>"gte"in r&&!!r.gte,lE=r=>"gt"in r&&!!r.gt,uE=r=>"lt"in r&&!!r.lt||"lte"in r&&!!r.lte,fE=r=>"lte"in r&&!!r.lte,hE=r=>"lt"in r&&!!r.lt,Kg=async function*(r,e,t){let n=oE(t),s=iE(t),o=s&&aE(t),i=o&&cE(t),a=o&&lE(t),c=s&&uE(t),l=c&&fE(t),u=c&&hE(t),f=o&&c,p=new Qe(r),h=await p.get(e);yield*async function*m(d){for(let y of d.value.entries){let g=d.value.prefix+y[0];if(Array.isArray(y[1])){if(y[1][1]&&(n&&g.startsWith(t.prefix)||f&&(a&&g>t.gt||i&&g>=t.gte)&&(u&&g<t.lt||l&&g<=t.lte)||a&&g>t.gt||i&&g>=t.gte||u&&g<t.lt||l&&g<=t.lte||!n&&!s)&&(yield[g,y[1][1]]),n){if(t.prefix.length<=g.length&&!g.startsWith(t.prefix)||t.prefix.length>g.length&&!t.prefix.startsWith(g))continue}else if(a&&mr(g,Math.min(g.length,t.gt.length))<mr(t.gt,Math.min(g.length,t.gt.length))||i&&mr(g,Math.min(g.length,t.gte.length))<mr(t.gte,Math.min(g.length,t.gte.length))||u&&mr(g,Math.min(g.length,t.lt.length))>mr(t.lt,Math.min(g.length,t.lt.length))||l&&mr(g,Math.min(g.length,t.lte.length))>mr(t.lte,Math.min(g.length,t.lte.length)))continue;yield*m(await p.get(y[1][0]))}else(n&&g.startsWith(t.prefix)||s&&f&&(a&&g>t.gt||i&&g>=t.gte)&&(u&&g<t.lt||l&&g<=t.lte)||s&&!f&&(a&&g>t.gt||i&&g>=t.gte||u&&g<t.lt||l&&g<=t.lte)||!n&&!s)&&(yield[g,y[1]])}}(h)},mr=(r,e)=>r.length<=e?r:r.slice(0,e),Fa=async(r,e,t)=>{for(let[n,s]of e.value.entries){if(t===n)return[e];if(t.startsWith(n)&&Array.isArray(s)){let o=await Fa(r,await r.get(s[0]),t.slice(n.length));return[e,...o]}}return[e]};var Ye=class{#e=new Map;constructor(e){e&&(this.#e=new Map(e.map(t=>[t.cid.toString(),t.bytes])))}async get(e){let t=this.#e.get(e.toString());if(t)return{cid:e,bytes:t}}async put(e,t){this.#e.set(e.toString(),t)}putSync(e,t){this.#e.set(e.toString(),t)}async delete(e){this.#e.delete(e.toString())}deleteSync(e){this.#e.delete(e.toString())}*entries(){for(let[e,t]of this.#e)yield{cid:Sa(e),bytes:t}}},Ct=class{#e;constructor(...e){this.#e=e}async get(e){for(let t of this.#e){let n=await t.get(e);if(n)return n}}};var Ua=r=>({base:r?.base,entries:[...r?.entries??[]],...Vt(r)});var qu=class r{#e=!1;constructor({blocks:e,entries:t,prefix:n,version:s,keyChars:o,maxKeySize:i,base:a}){this.blocks=e,this.prefix=n,this.entries=[...t],this.base=a,this.version=s,this.keyChars=o,this.maxKeySize=i}async put(e,t){if(this.#e)throw new jr;return Qu(this.blocks,this,e,t)}async commit(){if(this.#e)throw new jr;return this.#e=!0,$a(this)}static async create({blocks:e,link:t}){let s=await new Qe(e).get(t);return new r({blocks:e,base:s,...s.value})}},Qu=async(r,e,t,n)=>{if(e.keyChars!==vo)throw new Error(`unsupported key character set: ${e.keyChars}`);if(!Ra(t))throw new Error("key contains non-ASCII characters");if(new TextEncoder().encode(t).length>e.maxKeySize)throw new Error(`UTF-8 encoded key exceeds max size of ${e.maxKeySize} bytes`);let s=new Qe(r),o=await Gu(s,e,t);o.shard!==e&&(e=o.shard,t=o.key);let i=[o.key,n],a=[...o.shard.entries];for(let[c,l]of a.entries()){let[u,f]=l;if(u===o.key)break;let p=u.length<o.key.length?u:o.key,h=p===u?o.key:u,m="";for(let d of p){let y=m+d;if(!h.startsWith(y))break;m=y}if(m.length){let d=[];m!==o.key&&(d=pr(d,[o.key.slice(m.length),n])),m!==u&&(d=pr(d,Ju([u.slice(m.length),f])));let y=Ua({...Vt(o.shard),prefix:o.shard.prefix+m,entries:d}),g=[...m];for(let b=g.length-1;b>0;b--){let x;if(b===g.length-1&&m===u){if(Array.isArray(f))throw new Error("found a shard link when expecting a value");x=[y,f]}else b===g.length-1&&m===o.key?x=[y,n]:x=[y];y=Ua({...Vt(o.shard),prefix:o.shard.prefix+g.slice(0,b).join(""),entries:[[g[b],x]]})}if(a.splice(c,1),g.length===1&&m===u){if(Array.isArray(f))throw new Error("found a shard link when expecting a value");i=[g[0],[y,f]]}else g.length===1&&m===o.key?i=[g[0],[y,n]]:i=[g[0],[y]];break}}e.entries=pr(mE(a),Ju(i))},Gu=async(r,e,t)=>{for(let n=0;n<e.entries.length;n++){let[s,o]=e.entries[n];if(t<=s)break;if(t.startsWith(s)&&Array.isArray(o)){if(ju(o[0])){let i=await r.get(o[0]),a=Ua({base:i,...i.value});return e.entries[n]=[s,o[1]==null?[a]:[a,o[1]]],Gu(r,a,t.slice(s.length))}return Gu(r,o[0],t.slice(s.length))}}return{shard:e,key:t}},$a=async r=>{let e=[],t=[],n=[];for(let o of r.entries)if(Array.isArray(o[1])&&!ju(o[1][0])){let i=await $a(o[1][0]);n.push([o[0],o[1][1]==null?[i.root]:[i.root,o[1][1]]]),e.push(...i.additions),t.push(...i.removals)}else n.push(Ju(o));let s=await It(At(n,r));return e.push(s),r.base&&r.base.cid.toString()===s.cid.toString()?{root:s.cid,additions:[],removals:[]}:(r.base&&t.push(r.base),{root:s.cid,additions:e,removals:t})},mE=r=>r,Ju=r=>r,Yu=(r,e)=>qu.create({blocks:r,link:e}),jr=class r extends Error{constructor(e,t){super(e??"batch already committed",t),this.code=r.code}static code="ERR_BATCH_COMMITTED"};var Hg=async(r,e,t,n)=>{let s=new Ye;if(r=new Ct(s,r),!e.length){let d=await dr.create();s.putSync(d.cid,d.bytes);let y=await Eo(r,d.cid,t,n),g={type:"put",root:y.root,key:t,value:n},b=await jt.create(g,e);return e=await Hr(r,e,b.cid),{root:y.root,additions:[d,...y.additions],removals:y.removals,head:e,event:b}}let o=new _t(r),i=await Xu(o,e);if(!i)throw new Error("failed to find common ancestor event");let a=await o.get(i),{root:c}=a.value.data,l=await Wg(o,e,i),u=new Map,f=new Map;for(let{value:d}of l){let y;if(d.data.type==="put")y=await Eo(r,c,d.data.key,d.data.value);else if(d.data.type==="del")y=await Wu(r,c,d.data.key);else if(d.data.type==="batch"){let g=await Yu(r,c);for(let b of d.data.ops){if(b.type!=="put")throw new Error(`unsupported batch operation: ${b.type}`);await g.put(b.key,b.value)}y=await g.commit()}else throw new Error(`unknown operation: ${d.data.type}`);c=y.root;for(let g of y.additions)s.putSync(g.cid,g.bytes),u.set(g.cid.toString(),g);for(let g of y.removals)f.set(g.cid.toString(),g)}let p=await Eo(r,c,t,n);if(p.root.toString()===c.toString())return{root:c,additions:[],removals:[],head:e};for(let d of p.additions)s.putSync(d.cid,d.bytes),u.set(d.cid.toString(),d);for(let d of p.removals)f.set(d.cid.toString(),d);let h={type:"put",root:p.root,key:t,value:n},m=await jt.create(h,e);s.putSync(m.cid,m.bytes),e=await Hr(r,e,m.cid);for(let d of f.keys())u.has(d)&&(u.delete(d),f.delete(d));return{root:p.root,additions:[...u.values()],removals:[...f.values()],head:e,event:m}};var yr=async(r,e)=>{if(!e.length)throw new Error("cannot determine root of headless clock");let t=new Ye;r=new Ct(t,r);let n=new _t(r);if(e.length===1){let u=await n.get(e[0]),{root:f}=u.value.data;return{root:f,additions:[],removals:[]}}let s=await Xu(n,e);if(!s)throw new Error("failed to find common ancestor event");let o=await n.get(s),{root:i}=o.value.data,a=await Wg(n,e,s),c=new Map,l=new Map;for(let{value:u}of a){let f;if(u.data.type==="put")f=await Eo(r,i,u.data.key,u.data.value);else if(u.data.type==="del")f=await Wu(r,i,u.data.key);else if(u.data.type==="batch"){let p=await Yu(r,i);for(let h of u.data.ops){if(h.type!=="put")throw new Error(`unsupported batch operation: ${h.type}`);await p.put(h.key,h.value)}f=await p.commit()}else throw new Error(`unknown operation: ${u.data.type}`);i=f.root;for(let p of f.additions)t.putSync(p.cid,p.bytes),c.set(p.cid.toString(),p);for(let p of f.removals)l.set(p.cid.toString(),p)}for(let u of l.keys())c.has(u)&&(c.delete(u),l.delete(u));return{root:i,additions:[...c.values()],removals:[...l.values()]}},jg=async(r,e,t)=>{if(!e.length)return;let n=await yr(r,e);return n.additions.length&&(r=new Ct(new Ye(n.additions),r)),$g(r,n.root,t)},Vg=async function*(r,e,t){if(!e.length)return;let n=await yr(r,e);n.additions.length&&(r=new Ct(new Ye(n.additions),r)),yield*Kg(r,n.root,t)},Xu=async(r,e)=>{if(!e.length)return;let t=e.map(n=>[n]);for(;;){let n=!1;for(let s of t){let o=await yE(r,s[s.length-1]);if(!o)continue;n=!0,s.push(o);let i=gE(t);if(i)return i}if(!n)return}},yE=async(r,e)=>{let{value:t}=await r.get(e);return t.parents.length?t.parents.length===1?t.parents[0]:Xu(r,t.parents):e},gE=r=>{r=r.map(e=>[...e]);for(let e of r)for(let t of e){let n=!0;for(let s of r)if(e!==s&&(n=s.some(o=>String(o)===String(t)),!n))break;if(n)return t}},Wg=async(r,e,t)=>{if(e.length===1&&e[0].toString()===t.toString())return[];let n=new Map,s=await Promise.all(e.map(i=>qg(r,i,t)));for(let i of s)for(let{event:a,depth:c}of i){let l=n.get(a.cid.toString());l?l.weight+=c:n.set(a.cid.toString(),{event:a,weight:c})}let o=new Map;for(let{event:i,weight:a}of n.values()){let c=o.get(a);c?c.push(i):o.set(a,[i])}return Array.from(o).sort((i,a)=>a[0]-i[0]).flatMap(([,i])=>i.sort((a,c)=>String(a.cid)<String(c.cid)?-1:1))},qg=async(r,e,t,n=0)=>{let s=await r.get(e),o=[{event:s,depth:n}],{parents:i}=s.value;if(i.length===1&&String(i[0])===String(t))return o;let a=await Promise.all(i.map(c=>qg(r,c,t,n+1)));return o.concat(...a)};var Zu=class r{#e=!1;constructor({blocks:e,head:t,entries:n,prefix:s,version:o,keyChars:i,maxKeySize:a,base:c,additions:l,removals:u}){this.blocks=e,this.head=t,this.prefix=s,this.entries=[...n],this.base=c,this.version=o,this.keyChars=i,this.maxKeySize=a,this.additions=l,this.removals=u,this.ops=[]}async put(e,t){if(this.#e)throw new jr;await Qu(this.blocks,this,e,t),this.ops.push({type:"put",key:e,value:t})}async commit(){if(this.#e)throw new jr;this.#e=!0;let e=await $a(this),t={type:"batch",ops:this.ops,root:e.root},n=await jt.create(t,this.head),s=new Ye,o=new Ct(s,this.blocks);s.putSync(n.cid,n.bytes);let i=await Hr(o,this.head,n.cid),a=new Map,c=new Map;for(let l of this.additions)a.set(l.cid.toString(),l);for(let l of this.removals)c.set(l.cid.toString(),l);for(let l of e.additions)c.has(l.cid.toString())&&c.delete(l.cid.toString()),a.set(l.cid.toString(),l);for(let l of e.removals)a.has(l.cid.toString())?a.delete(l.cid.toString()):c.set(l.cid.toString(),l);return{head:i,event:n,root:e.root,additions:[...a.values()],removals:[...c.values()]}}static async create({blocks:e,head:t}){let n=new Ye;if(e=new Ct(n,e),!t.length){let l=await dr.create();return n.putSync(l.cid,l.bytes),new r({blocks:e,head:t,entries:[],base:l,additions:[l],removals:[],...Vt(l.value)})}let{root:s,additions:o,removals:i}=await yr(e,t);for(let l of o)n.putSync(l.cid,l.bytes);let c=await new Qe(e).get(s);return new r({blocks:e,head:t,entries:c.value.entries,base:c,additions:o,removals:i,...Vt(c.value)})}},Gg=(r,e)=>Zu.create({blocks:r,head:e});var Jc={};K(Jc,{BaseBlockstore:()=>Es,CarTransaction:()=>et,CompactionFetcher:()=>ci,ConnectionBase:()=>Gc,EncryptedBlockstore:()=>ai,FragmentGateway:()=>pi,Loader:()=>Ts,addCryptoKeyToGatewayMetaPayload:()=>mk,ensureStart:()=>qc,getGatewayFromURL:()=>Lr,parseCarFile:()=>ii,registerStoreProtocol:()=>$d,setCryptoKeyFromGatewayMetaPayload:()=>pk,testStoreFactory:()=>GI,toCIDBlock:()=>Jg,toStoreRuntime:()=>ed});function Jg(r){return r}ae();var zh={};K(zh,{decodeFile:()=>Kh,encodeFile:()=>$h});var ls={};K(ls,{DEFAULT_DIRECTORY_MODE:()=>cb,DEFAULT_FILE_MODE:()=>ab,NodeType:()=>O,code:()=>as,createAdvancedFile:()=>zE,createComplexFile:()=>jE,createDirectoryShard:()=>hb,createEmptyFile:()=>$E,createFileChunk:()=>KE,createFileShard:()=>HE,createFlatDirectory:()=>Ja,createRaw:()=>lb,createShardedDirectory:()=>fb,createSimpleFile:()=>ub,createSymlink:()=>pb,cumulativeContentByteLength:()=>Bt,cumulativeDagByteLength:()=>cs,decode:()=>gb,decodeMetadata:()=>qr,encode:()=>yb,encodeAdvancedFile:()=>vf,encodeComplexFile:()=>Ef,encodeDirectory:()=>Xa,encodeDirectoryMetadata:()=>If,encodeFile:()=>db,encodeFileChunk:()=>Sf,encodeFileShard:()=>VE,encodeHAMTShard:()=>Tf,encodeLink:()=>Qa,encodeMetadata:()=>Lo,encodeMode:()=>bb,encodeRaw:()=>kf,encodeSimpleFile:()=>Ya,encodeSymlink:()=>mb,filesize:()=>JE,matchFile:()=>GE,name:()=>xf});var xE=new TextDecoder;function ef(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let s=r[e++];if(t+=n<28?(s&127)<<n:(s&127)*2**n,s<128)break}return[t,e]}function Ka(r,e){let t;[t,e]=ef(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function Qg(r,e){let t;return[t,e]=ef(r,e),[t&7,t>>3,e]}function kE(r){let e={},t=r.length,n=0;for(;n<t;){let s,o;if([s,o,n]=Qg(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Ka(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Ka(r,n),e.Name=xE.decode(i)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(s!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Tsize`);[e.Tsize,n]=ef(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Yg(r){let e=r.length,t=0,n,s=!1,o;for(;t<e;){let a,c;if([a,c,t]=Qg(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=Ka(r,t),n&&(s=!0)}else if(c===2){if(s)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Ka(r,t),n.push(kE(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let i={};return o&&(i.Data=o),i.Links=n||[],i}var Zg=new TextEncoder,Xg=2**32,SE=2**31;function vE(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=To(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=Zg.encode(r.Name);t-=n.length,e.set(n,t),t=To(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=To(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function ew(r){let e=TE(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=To(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let s=r.Links.length-1;s>=0;s--){let o=vE(r.Links[s],t.subarray(0,n));n-=o,n=To(t,n,o)-1,t[n]=18}return t}function EE(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+ns(t)}if(typeof r.Name=="string"){let t=Zg.encode(r.Name).length;e+=1+t+ns(t)}return typeof r.Tsize=="number"&&(e+=1+ns(r.Tsize)),e}function TE(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+ns(t)}if(r.Links)for(let t of r.Links){let n=EE(t);e+=1+n+ns(n)}return e}function To(r,e,t){e-=ns(t);let n=e;for(;t>=SE;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function ns(r){return r%2===0&&r++,Math.floor((_E(r)+6)/7)}function _E(r){let e=0;return r>=Xg&&(r=Math.floor(r/Xg),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+AE[r]}var AE=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var IE=["Data","Links"],CE=["Hash","Name","Tsize"],tf=new TextEncoder;function rw(r,e){if(r===e)return 0;let t=r.Name?tf.encode(r.Name):[],n=e.Name?tf.encode(e.Name):[],s=t.length,o=n.length;for(let i=0,a=Math.min(s,o);i<a;++i)if(t[i]!==n[i]){s=t[i],o=n[i];break}return s<o?-1:o<s?1:0}function tw(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function LE(r){if(typeof r.asCID=="object"){let t=N.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=N.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=N.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=N.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function rf(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=tf.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(LE),e.Links.sort(rw);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function nw(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!tw(r,IE))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!tw(t,CE))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&rw(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}var nf=112;function sw(r){nw(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),ew(e)}function ow(r){let e=Yg(r),t={};return e.Data&&(t.Data=e.Data),e.Links&&(t.Links=e.Links.map(n=>{let s={};try{s.Hash=N.decode(n.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return n.Name!==void 0&&(s.Name=n.Name),n.Tsize!==void 0&&(s.Tsize=n.Tsize),s})),t}var Wt=mt(nb(),1),os=Wt.default.Reader,wf=Wt.default.Writer,D=Wt.default.util,pe=Wt.default.roots.unixfs||(Wt.default.roots.unixfs={}),is=pe.Data=(()=>{function r(e){if(this.blocksizes=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)e[t[n]]!=null&&(this[t[n]]=e[t[n]])}return r.prototype.Type=0,r.prototype.Data=D.newBuffer([]),r.prototype.filesize=D.Long?D.Long.fromBits(0,0,!0):0,r.prototype.blocksizes=D.emptyArray,r.prototype.hashType=D.Long?D.Long.fromBits(0,0,!0):0,r.prototype.fanout=D.Long?D.Long.fromBits(0,0,!0):0,r.prototype.mode=0,r.prototype.mtime=null,r.encode=function(t,n){if(n||(n=wf.create()),n.uint32(8).int32(t.Type),t.Data!=null&&Object.hasOwnProperty.call(t,"Data")&&n.uint32(18).bytes(t.Data),t.filesize!=null&&Object.hasOwnProperty.call(t,"filesize")&&n.uint32(24).uint64(t.filesize),t.blocksizes!=null&&t.blocksizes.length)for(var s=0;s<t.blocksizes.length;++s)n.uint32(32).uint64(t.blocksizes[s]);return t.hashType!=null&&Object.hasOwnProperty.call(t,"hashType")&&n.uint32(40).uint64(t.hashType),t.fanout!=null&&Object.hasOwnProperty.call(t,"fanout")&&n.uint32(48).uint64(t.fanout),t.mode!=null&&Object.hasOwnProperty.call(t,"mode")&&n.uint32(56).uint32(t.mode),t.mtime!=null&&Object.hasOwnProperty.call(t,"mtime")&&pe.UnixTime.encode(t.mtime,n.uint32(66).fork()).ldelim(),n},r.decode=function(t,n){t instanceof os||(t=os.create(t));for(var s=n===void 0?t.len:t.pos+n,o=new pe.Data;t.pos<s;){var i=t.uint32();switch(i>>>3){case 1:o.Type=t.int32();break;case 2:o.Data=t.bytes();break;case 3:o.filesize=t.uint64();break;case 4:if(o.blocksizes&&o.blocksizes.length||(o.blocksizes=[]),(i&7)===2)for(var a=t.uint32()+t.pos;t.pos<a;)o.blocksizes.push(t.uint64());else o.blocksizes.push(t.uint64());break;case 5:o.hashType=t.uint64();break;case 6:o.fanout=t.uint64();break;case 7:o.mode=t.uint32();break;case 8:o.mtime=pe.UnixTime.decode(t,t.uint32());break;default:t.skipType(i&7);break}}if(!o.hasOwnProperty("Type"))throw D.ProtocolError("missing required 'Type'",{instance:o});return o},r.fromObject=function(t){if(t instanceof pe.Data)return t;var n=new pe.Data;switch(t.Type){case"Raw":case 0:n.Type=0;break;case"Directory":case 1:n.Type=1;break;case"File":case 2:n.Type=2;break;case"Metadata":case 3:n.Type=3;break;case"Symlink":case 4:n.Type=4;break;case"HAMTShard":case 5:n.Type=5;break}if(t.Data!=null&&(typeof t.Data=="string"?D.base64.decode(t.Data,n.Data=D.newBuffer(D.base64.length(t.Data)),0):t.Data.length&&(n.Data=t.Data)),t.filesize!=null&&(D.Long?(n.filesize=D.Long.fromValue(t.filesize)).unsigned=!0:typeof t.filesize=="string"?n.filesize=parseInt(t.filesize,10):typeof t.filesize=="number"?n.filesize=t.filesize:typeof t.filesize=="object"&&(n.filesize=new D.LongBits(t.filesize.low>>>0,t.filesize.high>>>0).toNumber(!0))),t.blocksizes){if(!Array.isArray(t.blocksizes))throw TypeError(".Data.blocksizes: array expected");n.blocksizes=[];for(var s=0;s<t.blocksizes.length;++s)D.Long?(n.blocksizes[s]=D.Long.fromValue(t.blocksizes[s])).unsigned=!0:typeof t.blocksizes[s]=="string"?n.blocksizes[s]=parseInt(t.blocksizes[s],10):typeof t.blocksizes[s]=="number"?n.blocksizes[s]=t.blocksizes[s]:typeof t.blocksizes[s]=="object"&&(n.blocksizes[s]=new D.LongBits(t.blocksizes[s].low>>>0,t.blocksizes[s].high>>>0).toNumber(!0))}if(t.hashType!=null&&(D.Long?(n.hashType=D.Long.fromValue(t.hashType)).unsigned=!0:typeof t.hashType=="string"?n.hashType=parseInt(t.hashType,10):typeof t.hashType=="number"?n.hashType=t.hashType:typeof t.hashType=="object"&&(n.hashType=new D.LongBits(t.hashType.low>>>0,t.hashType.high>>>0).toNumber(!0))),t.fanout!=null&&(D.Long?(n.fanout=D.Long.fromValue(t.fanout)).unsigned=!0:typeof t.fanout=="string"?n.fanout=parseInt(t.fanout,10):typeof t.fanout=="number"?n.fanout=t.fanout:typeof t.fanout=="object"&&(n.fanout=new D.LongBits(t.fanout.low>>>0,t.fanout.high>>>0).toNumber(!0))),t.mode!=null&&(n.mode=t.mode>>>0),t.mtime!=null){if(typeof t.mtime!="object")throw TypeError(".Data.mtime: object expected");n.mtime=pe.UnixTime.fromObject(t.mtime)}return n},r.toObject=function(t,n){n||(n={});var s={};if((n.arrays||n.defaults)&&(s.blocksizes=[]),n.defaults){if(s.Type=n.enums===String?"Raw":0,n.bytes===String?s.Data="":(s.Data=[],n.bytes!==Array&&(s.Data=D.newBuffer(s.Data))),D.Long){var o=new D.Long(0,0,!0);s.filesize=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else s.filesize=n.longs===String?"0":0;if(D.Long){var o=new D.Long(0,0,!0);s.hashType=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else s.hashType=n.longs===String?"0":0;if(D.Long){var o=new D.Long(0,0,!0);s.fanout=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else s.fanout=n.longs===String?"0":0;s.mode=0,s.mtime=null}if(t.Type!=null&&t.hasOwnProperty("Type")&&(s.Type=n.enums===String?pe.Data.DataType[t.Type]:t.Type),t.Data!=null&&t.hasOwnProperty("Data")&&(s.Data=n.bytes===String?D.base64.encode(t.Data,0,t.Data.length):n.bytes===Array?Array.prototype.slice.call(t.Data):t.Data),t.filesize!=null&&t.hasOwnProperty("filesize")&&(typeof t.filesize=="number"?s.filesize=n.longs===String?String(t.filesize):t.filesize:s.filesize=n.longs===String?D.Long.prototype.toString.call(t.filesize):n.longs===Number?new D.LongBits(t.filesize.low>>>0,t.filesize.high>>>0).toNumber(!0):t.filesize),t.blocksizes&&t.blocksizes.length){s.blocksizes=[];for(var i=0;i<t.blocksizes.length;++i)typeof t.blocksizes[i]=="number"?s.blocksizes[i]=n.longs===String?String(t.blocksizes[i]):t.blocksizes[i]:s.blocksizes[i]=n.longs===String?D.Long.prototype.toString.call(t.blocksizes[i]):n.longs===Number?new D.LongBits(t.blocksizes[i].low>>>0,t.blocksizes[i].high>>>0).toNumber(!0):t.blocksizes[i]}return t.hashType!=null&&t.hasOwnProperty("hashType")&&(typeof t.hashType=="number"?s.hashType=n.longs===String?String(t.hashType):t.hashType:s.hashType=n.longs===String?D.Long.prototype.toString.call(t.hashType):n.longs===Number?new D.LongBits(t.hashType.low>>>0,t.hashType.high>>>0).toNumber(!0):t.hashType),t.fanout!=null&&t.hasOwnProperty("fanout")&&(typeof t.fanout=="number"?s.fanout=n.longs===String?String(t.fanout):t.fanout:s.fanout=n.longs===String?D.Long.prototype.toString.call(t.fanout):n.longs===Number?new D.LongBits(t.fanout.low>>>0,t.fanout.high>>>0).toNumber(!0):t.fanout),t.mode!=null&&t.hasOwnProperty("mode")&&(s.mode=t.mode),t.mtime!=null&&t.hasOwnProperty("mtime")&&(s.mtime=pe.UnixTime.toObject(t.mtime,n)),s},r.prototype.toJSON=function(){return this.constructor.toObject(this,Wt.default.util.toJSONOptions)},r.DataType=function(){let e={},t=Object.create(e);return t[e[0]="Raw"]=0,t[e[1]="Directory"]=1,t[e[2]="File"]=2,t[e[3]="Metadata"]=3,t[e[4]="Symlink"]=4,t[e[5]="HAMTShard"]=5,t}(),r})(),T8=pe.UnixTime=(()=>{function r(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)e[t[n]]!=null&&(this[t[n]]=e[t[n]])}return r.prototype.Seconds=D.Long?D.Long.fromBits(0,0,!1):0,r.prototype.FractionalNanoseconds=0,r.encode=function(t,n){return n||(n=wf.create()),n.uint32(8).int64(t.Seconds),t.FractionalNanoseconds!=null&&Object.hasOwnProperty.call(t,"FractionalNanoseconds")&&n.uint32(21).fixed32(t.FractionalNanoseconds),n},r.decode=function(t,n){t instanceof os||(t=os.create(t));for(var s=n===void 0?t.len:t.pos+n,o=new pe.UnixTime;t.pos<s;){var i=t.uint32();switch(i>>>3){case 1:o.Seconds=t.int64();break;case 2:o.FractionalNanoseconds=t.fixed32();break;default:t.skipType(i&7);break}}if(!o.hasOwnProperty("Seconds"))throw D.ProtocolError("missing required 'Seconds'",{instance:o});return o},r.fromObject=function(t){if(t instanceof pe.UnixTime)return t;var n=new pe.UnixTime;return t.Seconds!=null&&(D.Long?(n.Seconds=D.Long.fromValue(t.Seconds)).unsigned=!1:typeof t.Seconds=="string"?n.Seconds=parseInt(t.Seconds,10):typeof t.Seconds=="number"?n.Seconds=t.Seconds:typeof t.Seconds=="object"&&(n.Seconds=new D.LongBits(t.Seconds.low>>>0,t.Seconds.high>>>0).toNumber())),t.FractionalNanoseconds!=null&&(n.FractionalNanoseconds=t.FractionalNanoseconds>>>0),n},r.toObject=function(t,n){n||(n={});var s={};if(n.defaults){if(D.Long){var o=new D.Long(0,0,!1);s.Seconds=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else s.Seconds=n.longs===String?"0":0;s.FractionalNanoseconds=0}return t.Seconds!=null&&t.hasOwnProperty("Seconds")&&(typeof t.Seconds=="number"?s.Seconds=n.longs===String?String(t.Seconds):t.Seconds:s.Seconds=n.longs===String?D.Long.prototype.toString.call(t.Seconds):n.longs===Number?new D.LongBits(t.Seconds.low>>>0,t.Seconds.high>>>0).toNumber():t.Seconds),t.FractionalNanoseconds!=null&&t.hasOwnProperty("FractionalNanoseconds")&&(s.FractionalNanoseconds=t.FractionalNanoseconds),s},r.prototype.toJSON=function(){return this.constructor.toObject(this,Wt.default.util.toJSONOptions)},r})(),_8=pe.Metadata=(()=>{function r(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)e[t[n]]!=null&&(this[t[n]]=e[t[n]])}return r.prototype.MimeType="",r.encode=function(t,n){return n||(n=wf.create()),t.MimeType!=null&&Object.hasOwnProperty.call(t,"MimeType")&&n.uint32(10).string(t.MimeType),n},r.decode=function(t,n){t instanceof os||(t=os.create(t));for(var s=n===void 0?t.len:t.pos+n,o=new pe.Metadata;t.pos<s;){var i=t.uint32();switch(i>>>3){case 1:o.MimeType=t.string();break;default:t.skipType(i&7);break}}return o},r.fromObject=function(t){if(t instanceof pe.Metadata)return t;var n=new pe.Metadata;return t.MimeType!=null&&(n.MimeType=String(t.MimeType)),n},r.toObject=function(t,n){n||(n={});var s={};return n.defaults&&(s.MimeType=""),t.MimeType!=null&&t.hasOwnProperty("MimeType")&&(s.MimeType=t.MimeType),s},r.prototype.toJSON=function(){return this.constructor.toObject(this,Wt.default.util.toJSONOptions)},r})();var O=is.DataType;var ib=Object.freeze([]),bf=new Uint8Array(0),Re=Object.freeze({}),ab=parseInt("0644",8),cb=parseInt("0755",8),as=nf,xf="UnixFS",xr=(r,e)=>(Object(globalThis).debug&&console.log({data:r,links:e}),sw(rf({Data:is.encode(r).finish(),Links:e}))),lb=r=>({type:O.Raw,content:r}),$E=r=>ub(bf,r),ub=(r,e)=>({type:O.File,layout:"simple",content:r,metadata:qr(e)}),KE=r=>({type:O.File,layout:"simple",content:r}),zE=(r,e)=>({type:O.File,layout:"advanced",parts:r,metadata:qr(e)}),HE=r=>({type:O.File,layout:"advanced",parts:r}),jE=(r,e,t)=>({type:O.File,layout:"complex",content:r,parts:e,metadata:qr(t)}),Ja=(r,e)=>({type:O.Directory,metadata:qr(e),entries:r}),fb=(r,e,t,n,s=Re)=>({type:O.HAMTShard,bitfield:e,fanout:_f(t),hashType:Af(n),entries:r,metadata:qr(s)}),hb=(r,e,t,n)=>({type:O.HAMTShard,bitfield:e,fanout:_f(t),hashType:Af(n),entries:r}),kf=r=>xr({Type:O.Raw,Data:r.byteLength>0?r:void 0,filesize:r.byteLength,blocksizes:ib},[]),db=(r,e=!1)=>{let t=e?Re:Object(r).metadata;switch(r.layout){case"simple":return Ya(r.content,t);case"advanced":return vf(r.parts,t);case"complex":return Ef(r.content,r.parts,t);default:throw new TypeError(`File with unknown layout "${Object(r).layout}" was passed`)}},Sf=r=>Ya(r,Re),VE=r=>xr({Type:O.File,blocksizes:r.map(Co),filesize:Bt(r)},r.map(Qa)),vf=(r,e=Re)=>xr({Type:O.File,blocksizes:r.map(Co),filesize:Bt(r),...Lo(e)},r.map(Qa)),Qa=r=>({Name:"",Tsize:r.dagByteLength,Hash:r.cid}),Ya=(r,e=Re)=>xr({Type:O.File,Data:r.byteLength>0?r:void 0,filesize:r.byteLength,blocksizes:[],...Lo(e)},[]),Ef=(r,e,t=Re)=>xr({Type:O.File,Data:r,filesize:r.byteLength+Bt(e),blocksizes:e.map(Co)},e.map(Qa)),Xa=r=>xr({Type:r.type,...If(r.metadata||Re)},r.entries.map(wb)),Tf=({bitfield:r,fanout:e,hashType:t,entries:n,metadata:s=Re})=>xr({Type:O.HAMTShard,Data:r.byteLength>0?r:void 0,fanout:_f(e),hashType:Af(t),...If(s)},n.map(wb)),_f=r=>{if(Math.log2(r)%1===0)return r;throw new TypeError(`Expected hamt size to be a power of two instead got ${r}`)},Af=r=>{if(Number.isInteger(r))return r;throw new TypeError(`Expected an integer value instead got ${r}`)};var pb=(r,e=Re)=>({type:O.Symlink,content:r,metadata:qr(e)}),mb=(r,e=!1)=>{let t=e?Re:Object(r).metadata;return xr({Type:O.Symlink,Data:r.content,...Lo(t||Re)},[])},yb=(r,e=!0)=>{switch(r.type){case O.Raw:return kf(r.content);case O.File:return db(r);case O.Directory:return Xa(r);case O.HAMTShard:return Tf(r);case O.Symlink:return mb(r);default:throw new Error(`Unknown node type ${Object(r).type}`)}},gb=r=>{let e=ow(r),t=is.decode(e.Data),{Type:n,Data:s,mtime:o,mode:i,blocksizes:a,...c}=is.toObject(t,{defaults:!1,arrays:!0,longs:Number,objects:!1}),l={...i&&{mode:i},...WE(o)},u=e.Links;switch(t.Type){case O.Raw:return lb(s);case O.File:return u.length===0?new Wa(s,l):s.byteLength===0?new qa(sb(c.blocksizes,u),l):new Ga(s,sb(c.blocksizes,u),l);case O.Directory:return Ja(ob(u),l);case O.HAMTShard:return fb(ob(u),s||bf,c.fanout,c.hashType,l);case O.Symlink:return pb(s,l);default:throw new TypeError(`Unsupported node type ${t.Type}`)}},WE=r=>r==null?void 0:{mtime:{secs:r.Seconds,nsecs:r.FractionalNanoseconds||0}};var sb=(r,e)=>{let t=[],n=r.length,s=0;for(;s<n;)t.push({cid:e[s].Hash,dagByteLength:e[s].Tsize||0,contentByteLength:r[s]});return t},ob=r=>r.map(e=>({cid:e.Hash,name:e.Name||"",dagByteLength:e.Tsize||0})),Bt=r=>r.reduce((e,t)=>e+t.contentByteLength,0),cs=(r,e)=>e.reduce((t,n)=>t+n.dagByteLength,r.byteLength),Co=r=>r.contentByteLength,wb=({name:r,dagByteLength:e,cid:t})=>({Name:r,Tsize:e,Hash:t}),If=r=>Lo(r,cb),Lo=({mode:r,mtime:e},t=ab)=>({mode:r!=null?bb(r,t):void 0,mtime:e!=null?qE(e):void 0}),qr=r=>r==null?Re:{...r.mode==null?void 0:{mode:xb(r.mode)},...r.mtime==null?void 0:{mtime:r.mtime}},qE=r=>r==null?void 0:r.nsecs!==0?{Seconds:r.secs,FractionalNanoseconds:r.nsecs}:{Seconds:r.secs},bb=(r,e)=>{let t=r==null?void 0:xb(r);return t===e||t==null?void 0:t},xb=r=>r&4095|r&4294963200,GE=({content:r=bf,parts:e=ib,metadata:t=Re,...n})=>e.length===0?new Wa(r,t):r.byteLength===0?new qa(e,t):new Ga(r,e,t),Wa=class{constructor(e,t){this.content=e,this.metadata=t,this.layout="simple",this.type=O.File}get filesize(){return this.content.byteLength}encode(){return Ya(this.content,this.metadata)}},qa=class{constructor(e,t){this.parts=e,this.metadata=t}get layout(){return"advanced"}get type(){return O.File}get fileSize(){return Bt(this.parts)}get blockSizes(){return this.parts.map(Co)}encode(){return vf(this.parts,this.metadata)}},Ga=class{constructor(e,t,n){this.content=e,this.parts=t,this.metadata=n}get layout(){return"complex"}get type(){return O.File}get fileSize(){return this.content.byteLength+Bt(this.parts)}get blockSizes(){return this.parts.map(Co)}encode(){return Ef(this.content,this.parts,this.metadata)}},JE=r=>{switch(r.type){case O.Raw:case O.Symlink:return r.content.byteLength;case O.File:switch(r.layout){case"simple":return r.content.byteLength;case"advanced":return Bt(r.parts);case"complex":return r.content.byteLength+Bt(r.parts)}default:return 0}};var QE=function*(r){let e=yield*r;yield*ec(e)};function*Df(){return yield nc}var fs=function*(){yield sc};var Za=function*(r){let e=yield*Df();if(XE(r)){let t=!1,n;if(r.then(s=>{t=!1,n=s,kr(e)},s=>{t=!0,n=s,kr(e)}),yield*fs(),t)throw n;return n}else return rT(YE(e)),yield*fs(),r};function*YE(r){kr(r)}var XE=r=>r!=null&&typeof r.then=="function",ec=function*(r){yield r},tc=function*(r){let e=[];for(let t of Object.entries(r)){let[n,s]=t;s!==Do&&e.push(yield*ds(eT(s,n)))}yield*Mf(e)},rc=r=>r.length>0?ZE(r.map(QE)):Do;function*ZE(r){let e=[];for(let t of r)e.push(yield*ds(t));yield*Mf(e)}var eT=(r,e)=>r===Do?Do:r instanceof Bo?new Bo([...r.tags,e],r.source):new Bo([e],r),Bo=class{constructor(e,t){this.tags=e,this.source=t,this.controller}[Symbol.iterator](){return this.controller||(this.controller=this.source[Symbol.iterator]()),this}box(e){if(e.done)return e;switch(e.value){case sc:case nc:return e;default:{let t=e,{value:n}=t;for(let s of this.tags)n=tT(s,n);return t.value=n,t}}}next(e){return this.box(this.controller.next(e))}throw(e){return this.box(this.controller.throw(e))}return(e){return this.box(this.controller.return(e))}get[Symbol.toStringTag](){return"TaggedEffect"}},No=()=>Do;var tT=(r,e)=>({type:r,[r]:e});var nc=Symbol("current"),sc=Symbol("suspend");var qt=class r{static of(e){return e.group||us}static enqueue(e,t){e.group=t,t.stack.active.push(e)}constructor(e,t=[],n=new Set,s=new hs(t,n)){this.driver=e,this.parent=r.of(e),this.stack=s,this.id=++Eb}},Cf=class{constructor(){this.status=Po,this.stack=new hs,this.id=0}},hs=class{constructor(e=[],t=new Set){this.active=e,this.idle=t}static size({active:e,idle:t}){return e.length+t.size}},rT=r=>kr(r[Symbol.iterator]()),kr=r=>{let e=qt.of(r);for(e.stack.active.push(r),e.stack.idle.delete(r);e.parent;){let{idle:t,active:n}=e.parent.stack;if(t.has(e.driver))t.delete(e.driver),n.push(e.driver);else break;e=e.parent}if(us.status===Po)for(us.status=Tb;;)try{for(let t of Nf(us));us.status=Po;break}catch{us.stack.active.shift()}},nT=r=>kr(r),Nf=function*(r){let{active:e}=r.stack,t=e[0];for(r.stack.idle.delete(t);t;){let n=_b;e:for(;!n.done&&t===e[0];){let s=n.value;switch(s){case sc:r.stack.idle.add(t);break e;case nc:n=t.next(t);break;default:n=t.next(yield s);break}}e.shift(),t=e[0],r.stack.idle.delete(t)}};var ds=(r,e)=>new Pf(r,e),sT=(r,e)=>Sb(r,{ok:!0,value:e});var Lf=(r,e)=>Sb(r,{ok:!1,error:e});function*Sb(r,e){try{let t=r,n=e.ok?t.return(e.value):t.throw(e.error);if(!n.done)if(n.value===sc){let{idle:s}=qt.of(t).stack;s.add(t)}else kr(t)}catch{}}function*Mf(r){if(r.length===0)return;let e=yield*Df(),t=new qt(e),n=null;for(let s of r){let{result:o}=s;if(o){!o.ok&&!n&&(n=o);continue}oT(s,t)}try{if(n)throw n.error;for(;yield*Nf(t),hs.size(t.stack)>0;)yield*fs()}catch(s){for(let o of t.stack.active)yield*Lf(o,s);for(let o of t.stack.idle)yield*Lf(o,s),kr(o);throw s}}var oT=(r,e)=>{let t=qt.of(r);if(t!==e){let{active:n,idle:s}=t.stack,o=e.stack;if(r.group=e,s.has(r))s.delete(r),o.idle.add(r);else{let i=n.indexOf(r);i>=0&&(n.splice(i,1),o.active.push(r))}}};function*Of(r){r.status===Po&&(yield*r),r.result||(yield*Mf([r]));let e=r.result;if(e.ok)return e.value;throw e.error}var Bf=class{constructor(e){this.handler=e,this.result}get promise(){let{result:e}=this,t=e==null?new Promise((n,s)=>{this.handler.onsuccess=n,this.handler.onfailure=s}):e.ok?Promise.resolve(e.value):Promise.reject(e.error);return Object.defineProperty(this,"promise",{value:t}),t}then(e,t){return this.activate().promise.then(e,t)}catch(e){return this.activate().promise.catch(e)}finally(e){return this.activate().promise.finally(e)}activate(){return this}},Pf=class extends Bf{constructor(e,t=iT,n={},s=_b){super(n),this.id=++Eb,this.name=t.name||"",this.task=e,this.state=s,this.status=Po,this.result,this.handler=n,this.controller}*resume(){nT(this)}join(){return Of(this)}abort(e){return Lf(this,e)}exit(e){return sT(this,e)}get[Symbol.toStringTag](){return"Fork"}*[Symbol.iterator](){return this.activate()}activate(){return this.controller=this.task[Symbol.iterator](),this.status=Tb,kr(this),this}panic(e){this.result={ok:!1,error:e},this.status=kb;let{handler:t}=this;throw t.onfailure&&t.onfailure(e),e}step(e){if(this.state=e,e.done){this.result={ok:!0,value:e.value},this.status=kb;let{handler:t}=this;t.onsuccess&&t.onsuccess(e.value)}return e}next(e){try{return this.step(this.controller.next(e))}catch(t){return this.panic(t)}}return(e){try{return this.step(this.controller.return(e))}catch(t){return this.panic(t)}}throw(e){try{return this.step(this.controller.throw(e))}catch(t){return this.panic(t)}}},vb=function*(r,e){let t=yield*Df(),n=new qt(t);for(qt.enqueue(r[Symbol.iterator](),n);;){for(let s of Nf(n))qt.enqueue(e(s)[Symbol.iterator](),n);if(hs.size(n.stack)>0)yield*fs();else break}},Eb=0,Po="idle",Tb="active",kb="finished",_b={done:!1,value:nc},iT={},Do=function*(){}(),us=new Cf;function Rf(){}Object.defineProperties(Rf,{prototype:{value:new Proxy(Object.prototype,{get(r,e,t){return typeof e=="symbol"?Reflect.get(r,e,t):t.get(e)}})}});var Ff=()=>new Mo;var Ib=(r,e=0,t=r.byteLength)=>{let n=[],s=e<0?r.byteLength-e:e,o=t<0?r.byteLength-t:t;if(s===0&&o>=r.byteLength)return r;if(s>o||s>r.byteLength||o<=0)return Ff();let i=0,a=0;for(let c of r.segments){let l=a+c.byteLength;if(i===0){if(o<=l){let u=c.subarray(s-a,o-a);n.push(u),i=u.byteLength;break}else if(s<l){let u=s===a?c:c.subarray(s-a);n.push(u),i=u.byteLength}}else if(o<=l){let u=o===l?c:c.subarray(0,o-a);n.push(u),i+=u.byteLength;break}else n.push(c),i+=c.byteLength;a=l}return new Mo(n,r.byteOffset+s,i)},aT=(r,e)=>e.byteLength>0?(r.segments.push(e),new Mo(r.segments,r.byteOffset,r.byteLength+e.byteLength)):r,cT=(r,e)=>{if(e<r.byteLength){let t=0;for(let n of r.segments){if(e<t+n.byteLength)return n[e-t];t+=n.byteLength}}},lT=(r,e,t)=>{let n=t;for(let s of r.segments)e.set(s,n),n+=s.byteLength;return e};function*uT(r){for(let e of r.segments)yield*e}var Mo=class extends Rf{constructor(e=[],t=0,n=0){super(),this.segments=e,this.byteLength=n,this.length=n,this.byteOffset=t}[Symbol.iterator](){return uT(this)}slice(e,t){return Ib(this,e,t)}subarray(e,t){return Ib(this,e,t)}push(e){return aT(this,e)}get(e){return cT(this,e)}copyTo(e,t){return lT(this,e,t)}};var Oo=r=>{throw new Error(r)},Cb=(r,e,...t)=>Oo(String.raw(r,JSON.stringify(e),...t)),Lb=new Uint8Array(0),Bb=[];var Pb=r=>({config:r,buffer:Ff()}),Db=(r,e)=>e.byteLength>0?Mb(r.config,r.buffer.push(e),!1):{...r,chunks:Bb},Nb=r=>Mb(r.config,r.buffer,!0),Mb=(r,e,t)=>{let n=r.chunker,s=[],o=0;for(let i of n.cut(n.context,e,t))if(i>0){let a=e.subarray(o,o+i);s.push(a),o+=i}return{config:r,chunks:s,buffer:e.subarray(o)}};var Ob=()=>({mutable:!0,needs:{},nodes:{},links:{},linked:Kf});var zf=(r,e)=>{let t=ps(e,{});for(let n of r){let{ready:s,has:o,wants:i}=Fb(n.children,t.links);i.length===0?t=ps(t,{links:$f(void 0,o),linked:[{id:n.id,links:s}]}):t=ps(t,{needs:$f(n.id,i),nodes:{[n.id]:{children:n.children,count:i.length}}})}return t},Rb=(r,e,t)=>{let n=t.needs[r],s=t.nodes[n];if(s!=null)if(s.count===1){let{ready:o,has:i}=Fb(s.children,{...t.links,[r]:e});return ps(t,{needs:{[r]:void 0},links:$f(void 0,i),nodes:{[n]:void 0},linked:[{id:n,links:o}]})}else return ps(t,{needs:{[r]:void 0},links:{[r]:e},nodes:{[n]:{...s,count:s.count-1}}});else return ps(t,{links:{[r]:e}})},ps=(r,{needs:e,nodes:t,links:n,linked:s})=>{let o=r.mutable?r:{...r},i=r.mutable?pT:void 0;return e&&(o.needs=Uf(r.needs,e,i)),t&&(o.nodes=Uf(r.nodes,t,i)),n&&(o.links=Uf(r.links,n,i)),o.linked=s?dT(r.linked||Kf,s,Kf):r.linked||[],o},$f=(r,e)=>{let t={};for(let n of e)t[n]=r;return t},Uf=(r,e,t=r)=>{let n=r===t?{...r}:r;for(let s of Object.entries(e)){let[o,i]=s;i==null?delete n[o]:n[o]=i}return n};var dT=(r,e,t=r)=>{if(r===t)return[...r,...e];for(let n of e)r.push(n);return r},Fb=(r,e)=>{let t=[],n=[],s=[];for(let o of r){let i=e[o];i?(t.push(o),s.push(i)):n.push(o)}return{has:t,wants:n,ready:s}},Kf=Object.freeze([]),pT=Object.freeze({});var Ub=(r,e)=>{switch(r.type){case"write":return yT(e,r.bytes);case"link":return gT(e,r.link);case"block":return{state:e,effect:No()};case"close":return wT(e);case"end":return{state:e,effect:No()};default:return Cb`File Writer got unknown message ${r}`}},$b=(r,e,t)=>({status:"open",metadata:e,config:t,writer:r,chunker:Pb({chunker:t.chunker}),layout:t.fileLayout.open(),nodeQueue:Ob()}),yT=(r,e)=>{if(r.status==="open"){let{chunks:t,...n}=Db(r.chunker,e),{nodes:s,leaves:o,layout:i}=r.config.fileLayout.write(r.layout,t),{linked:a,...c}=zf(s,r.nodeQueue),l=[...Kb(o,r.config),...Hf(a,r.config)];return{state:{...r,chunker:n,layout:i,nodeQueue:c},effect:tc({link:rc(l)})}}else return Oo("Unable to perform write on closed file")},gT=(r,{id:e,link:t,block:n})=>{let{linked:s,...o}=Rb(e,t,r.nodeQueue),i=Hf(s,r.config),a=r.status==="closed"&&e===r.rootID?{...r,status:"linked",link:t,nodeQueue:o}:{...r,nodeQueue:o},c=r.status==="closed"&&e===r.rootID&&r.end?r.end.resume():No();return{state:a,effect:tc({link:rc(i),block:kT(r.writer,n),end:c})}},wT=r=>{if(r.status==="open"){let{chunks:e}=Nb(r.chunker),{layout:t,...n}=r.config.fileLayout.write(r.layout,e),{root:s,...o}=r.config.fileLayout.close(t,r.metadata),[i,a]=vT(s)?[[...n.nodes,...o.nodes],[...n.leaves,...o.leaves,s]]:[[...n.nodes,...o.nodes,s],[...n.leaves,...o.leaves]],{linked:c,...l}=zf(i,r.nodeQueue),u=[...Kb(a,r.config),...Hf(c,r.config)],f=ds(fs());return{state:{...r,chunker:null,layout:null,rootID:s.id,status:"closed",end:f,nodeQueue:l},effect:tc({link:rc(u),end:Of(f)})}}else return{state:r,effect:No()}},Kb=(r,e)=>r.map(t=>bT(e,t,e.fileChunkEncoder)),bT=function*({hasher:r,linker:e},{id:t,content:n},s){let o=s.encode(n?ST(n):Lb),i=yield*Za(r.digest(o)),a=e.createLink(s.code,i),c={cid:a,bytes:o},l={cid:a,contentByteLength:n?n.byteLength:0,dagByteLength:o.byteLength};return{id:t,block:c,link:l}},Hf=(r,e)=>r.map(t=>xT(e,t)),xT=function*(r,{id:e,links:t},n){let s=r.fileEncoder.encode({type:O.File,layout:"advanced",parts:t,metadata:n}),o=yield*Za(Promise.resolve(r.hasher.digest(s))),i=r.linker.createLink(r.fileEncoder.code,o),a={bytes:s,cid:i},c={cid:i,contentByteLength:Bt(t),dagByteLength:cs(s,t)};return{id:e,block:a,link:c}},kT=function*(r,e){(r.desiredSize||0)<=0&&(yield*Za(r.ready)),r.write(e)},ST=r=>r instanceof Uint8Array?r:r.copyTo(new Uint8Array(r.byteLength),0),vT=r=>r.children==null;var Vf={};K(Vf,{context:()=>TT,cut:()=>Hb,name:()=>zb,type:()=>_T,withMaxChunkSize:()=>jf});var zb="fixed",TT={maxChunkSize:262144},_T="Stateless",jf=r=>({type:"Stateless",context:{maxChunkSize:r},name:zb,cut:Hb}),Hb=({maxChunkSize:r},{byteLength:e},t)=>{let n=e/r|0,s=new Array(n).fill(r),o=t?e-n*r:0;return o>0&&s.push(o),s};var Ro=class{constructor(e,t,n){this.id=e,this.children=t,this.metadata=n}},oc=r=>({open:()=>IT({width:r}),write:CT,close:LT}),AT={width:174},IT=({width:r}=AT)=>({width:r,head:null,leafIndex:[],nodeIndex:[],lastID:0}),CT=(r,e)=>{if(e.length===0)return{layout:r,nodes:Le,leaves:Le};{let{lastID:t}=r,[n,s]=r.head?[null,(e.unshift(r.head),e)]:e.length===1&&r.leafIndex.length===0?[e[0],Le]:[null,e];if(s.length===0)return{layout:{...r,head:n},nodes:Le,leaves:Le};{let o=[...r.leafIndex],i=[];for(let a of s){let c={id:++t,content:a};i.push(c),o.push(c.id)}return o.length>r.width?Vb({...r,leafIndex:o,head:n,lastID:t},i):{layout:{...r,head:n,leafIndex:o,lastID:t},leaves:i,nodes:Le}}}},Vb=(r,e=Le,t=[],n=!1)=>{let{lastID:s}=r,o=r.nodeIndex.map(l=>[...l]),i=[...r.leafIndex],{width:a}=r;for(;i.length>a||i.length>0&&n;){jb(o,1);let l=new Ro(++s,i.splice(0,a));o[0].push(l.id),t.push(l)}let c=0;for(;c<o.length;){let l=o[c];for(c++;l.length>a||l.length>0&&n&&c<o.length;){let u=new Ro(++s,l.splice(0,a));jb(o,c+1),o[c].push(u.id),t.push(u)}}return{layout:{...r,lastID:s,leafIndex:i,nodeIndex:o},leaves:e,nodes:t}},LT=(r,e)=>{let t=r;if(r.head)return{root:{id:1,content:r.head,metadata:e},leaves:Le,nodes:Le};if(r.leafIndex.length===0)return{root:{id:1,metadata:e},leaves:Le,nodes:Le};{let{nodes:n,layout:s}=Vb(t,Le,[],!0),{nodeIndex:o}=s,i=o.length-1,a=o[i];if(a.length===1){let c=n[n.length-1];return n.length=n.length-1,{root:c,nodes:n,leaves:Le}}else return{root:new Ro(s.lastID+1,a,e),nodes:n,leaves:Le}}},jb=(r,e)=>{for(;r.length<e;)r.push([]);return r},Le=[];var Sr=()=>({chunker:Vf,fileChunkEncoder:Wf,smallFileEncoder:Wf,fileEncoder:ls,fileLayout:oc(174),hasher:Q,linker:{createLink:N.createV1}}),vr=r=>({...Sr(),...r}),Wf={code:as,name:xf,encode:Sf};var Fo=({writer:r,metadata:e={},settings:t=Sr()})=>new qf($b(r,e,vr(t))),Wb=async(r,e)=>(await Gb(r,ec({type:"write",bytes:e})),r),qb=async(r,{releaseLock:e=!1,closeWriter:t=!1}={})=>{await Gb(r,ec({type:"close"}));let{state:n}=r;if(n.status==="linked")return t?await r.state.writer.close():e&&r.state.writer.releaseLock(),n.link;Oo(`Expected writer to be in 'linked' state after close, but it is in "${n.status}" instead`)},Gb=(r,e)=>ds(vb(e,t=>{let{state:n,effect:s}=Ub(t,r.state);return r.state=n,s})),qf=class{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.config}write(e){return Wb(this,e)}close(e){return qb(this,e)}};var PT=Sr,Jf=({writer:r,settings:e=PT(),metadata:t={}})=>new ic({writer:r,metadata:t,settings:e,entries:new Map,closed:!1}),ac=(r,e,t,{overwrite:n=!1}={})=>{let s=Qf(r.state);if(e.includes("/"))throw new Error(`Directory entry name "${e}" contains forbidden "/" character`);if(!n&&s.entries.has(e))throw new Error(`Directory already contains entry with name "${e}"`);return s.entries.set(e,t),r},cc=(r,e)=>(Qf(r.state).entries.delete(e),r),Qf=r=>{if(r.closed)throw new Error("Can not change written directory, but you can .fork() and make changes to it");return r},Jb=async(r,{closeWriter:e=!1,releaseLock:t=!1}={})=>{let{writer:n,settings:s,metadata:o}=Qf(r.state);r.state.closed=!0;let i=[...Qb(r)],a=Ja(i,o),c=Xa(a),l=await s.hasher.digest(c),u=s.linker.createLink(as,l);return(n.desiredSize||0)<=0&&await n.ready,n.write({cid:u,bytes:c}),e?await n.close():t&&n.releaseLock(),{cid:u,dagByteLength:cs(c,i)}},Qb=function*({state:r}){for(let[e,{dagByteLength:t,cid:n}]of r.entries)yield{name:e,dagByteLength:t,cid:n}},Yb=({state:r},{writer:e=r.writer,metadata:t=r.metadata,settings:n=r.settings}={})=>new ic({writer:e,metadata:t,settings:n,entries:new Map(r.entries.entries()),closed:!1}),ic=class{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.settings}links(){return Qb(this)}set(e,t,n){return ac(this,e,t,n)}remove(e){return cc(this,e)}fork(e){return Yb(this,e)}close(e){return Jb(this,e)}entries(){return this.state.entries.entries()}has(e){return this.state.entries.has(e)}get size(){return this.state.entries.size}};var t0=mt(Yf(),1),X8=new TextEncoder,Z8=t0.default.x64.hash126;var uc=mt(Yf(),1);function MT(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var sR=Kr({name:"murmur3-32",code:35,encode:r=>MT(uc.default.x86.hash32(r))}),s0=Kr({name:"murmur3-128",code:34,encode:r=>Kt.fromHex(uc.default.x64.hash128(r))}),fc=Kr({name:"murmur3-x64-64",code:34,encode:r=>Kt.fromHex(uc.default.x64.hash128(r)).subarray(0,8)});var aR=new TextEncoder;var o0=(r,e,t)=>{let n=e/8|0,s=e%8,o=t,i=0;for(;o>0&&n<r.byteLength;){let a=r[n],c=8-s,l=c<o?c:o,u=8-s-l,p=(255>>s&a)>>u;i=(i<<l)+p,o-=l,n++,s=0}return i};var xR=new RangeError("Not Found");var FT=new TextEncoder,UT=r=>fc.encode(r),a0=({bitWidth:r=8,hash:e=UT})=>{let t=e(new Uint8Array).byteLength,n={bitWidth:r,hash:e,hashSize:t};return{at:(i,a)=>$T(i,a,n),from:i=>FT.encode(i),size:1/0}},$T=(r,e=0,{bitWidth:t=8,hash:n,hashSize:s})=>{let o=s*8,i=0,a=t,c=t*e;for(;a>0;){let l=c/o>>0,u=n(l===0?r:KT(r,l)),f=o<=c?c%o:c,p=o-f,h=p<a?p:a;i=(i<<h)+o0(u,f,h),a-=h,c+=h}return i},KT=(r,e)=>{let t=new Uint8Array(r.byteLength+1).fill(e,r.byteLength);return t.set(r),t};var c0=8,BR={bitWidth:c0,Path:a0({bitWidth:c0})};var l0=({writable:r,settings:e=Sr()})=>new Xf({writer:r.getWriter(),settings:e}),jT=async(r,{releaseLock:e=!0,closeWriter:t=!0}={})=>(t?await r.writer.close():e&&r.writer.releaseLock(),r),Xf=class{constructor({writer:e,settings:t}){this.writer=e,this.settings=vr(t)}createFileWriter({settings:e=this.settings,metadata:t}={}){return Fo({writer:this.writer,settings:e,metadata:t})}createDirectoryWriter({settings:e=this.settings,metadata:t}={}){return Jf({writer:this.writer,settings:e,metadata:t})}close(e){return jT(this,e)}},VT=1048576,WT=VT*100,u0=(r=WT)=>({highWaterMark:r,size:e=>e.bytes.length});var Gr={};K(Gr,{code:()=>$o,decode:()=>QT,encode:()=>JT,name:()=>GT});ar();var GT="raw",$o=85;function JT(r){return qe(r)}function QT(r){return qe(r)}function YT(r){return r[Symbol.asyncIterator]!=null}function XT(r){if(YT(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var f0=XT;var hc=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(e="Bad path"){super(e)}},Ze=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not found"){super(e)}},dc=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(e="No resolver"){super(e)}},ce=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(e="Not UnixFS"){super(e)}},pc=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(e="Over read"){super(e)}},mc=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(e="Under read"){super(e)}},yc=class r extends Error{static name="NoPropError";static code="ERR_NO_PROP";name=r.name;code=r.code;constructor(e="No Property found"){super(e)}},Jr=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};var Zf=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===w.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===w.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[w.uint.major](e,t){this.prefix(e);let n=String(t.value),s=[];for(let o=0;o<n.length;o++)s[o]=n.charCodeAt(o);e.push(s)}[w.negint.major](e,t){this[w.uint.major](e,t)}[w.bytes.major](e,t){throw new Error(`${zt} unsupported type: Uint8Array`)}[w.string.major](e,t){this.prefix(e);let n=Ea(JSON.stringify(t.value));e.push(n.length>32?po(n):n)}[w.array.major](e,t){this.prefix(e),this.inRecursive.push({type:w.array,elements:0}),e.push([91])}[w.map.major](e,t){this.prefix(e),this.inRecursive.push({type:w.map,elements:0}),e.push([123])}[w.tag.major](e,t){}[w.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(i.type===w.array)e.push([93]);else if(i.type===w.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${zt} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),s=[],o=!1;for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i),!o&&(s[i]===46||s[i]===101||s[i]===69)&&(o=!0);o||(s.push(46),s.push(48)),e.push(s)}};function ZT(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${zt} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==w.string||n.type!==w.string)throw new Error(`${zt} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${zt} unexpected duplicate map keys, this is not supported`)}var e_={addBreakTokens:!0,mapSorter:ZT};function eh(r,e){return e=Object.assign({},e_,e),Fu(r,new Zf,e)}var ms=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${L} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${L} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,s=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new v(w.uint,0,this._pos-e);if(s([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${L} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${L} unexpected token at position ${this._pos}`);n=!0,this._pos++,s([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,s([48,49,50,51,52,53,54,55,56,57]));let o=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(o);return n?new v(w.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new v(i>=0?w.uint:w.negint,i,this._pos-e):new v(i>=0?w.uint:w.negint,BigInt(o),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${L} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let o=this._pos,i=0;o<this.data.length&&i<65536;o++,i++){let a=this.data[o];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,o));return this._pos=o+1,new v(w.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${L} unexpected end of unicode escape sequence at position ${this._pos}`);let o=0;for(let i=0;i<4;i++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${L} unexpected unicode escape character at position ${this._pos}`);o=o*16+a,this._pos++}return o},s=()=>{let o=this.ch(),i=null,a=o>239?4:o>223?3:o>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${L} unexpected unicode sequence at position ${this._pos}`);let c,l,u,f;switch(a){case 1:o<128&&(i=o);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(o&31)<<6|c&63,f>127&&(i=f));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(f=(o&15)<<12|(c&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(i=f));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(f=(o&15)<<18|(c&63)<<12|(l&63)<<6|u&63,f>65535&&f<1114112&&(i=f))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let o=this.ch(),i;switch(o){case 92:if(this._pos++,this.done())throw new Error(`${L} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${L} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new v(w.string,Bu(t),this._pos-e);default:if(o<32)throw new Error(`${L} invalid control character at position ${this._pos}`);o<128?(t.push(o),this._pos++):s()}}throw new Error(`${L} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new v(w.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new v(w.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new v(w.null,null,4);case 102:return this.expect([102,97,108,115,101]),new v(w.false,!1,5);case 116:return this.expect([116,114,117,101]),new v(w.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${L} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new v(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${L} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new v(w.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new v(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${L} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new v(w.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${L} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${L} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function th(r,e){return e=Object.assign({tokenizer:new ms(r,e)},e),Tt(r,e)}var rh={};K(rh,{base64:()=>gc,base64pad:()=>wc,base64url:()=>r_,base64urlpad:()=>n_});it();var gc=te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),wc=te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),r_=te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),n_=te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function s_(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function o_(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=N.asCID(r);if(!e)return null;let t=e.toString();return[new v(w.map,1/0,1),new v(w.string,"/",1),new v(w.string,t,t.length),new v(w.break,void 0,1)]}function bc(r){let e=gc.encode(r).slice(1);return[new v(w.map,1/0,1),new v(w.string,"/",1),new v(w.map,1/0,1),new v(w.string,"bytes",5),new v(w.string,e,e.length),new v(w.break,void 0,1),new v(w.break,void 0,1)]}function ht(r){return bc(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function i_(r){return bc(new Uint8Array(r))}function a_(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function c_(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var l_={typeEncoders:{Object:o_,Buffer:bc,Uint8Array:bc,Int8Array:ht,Uint16Array:ht,Int16Array:ht,Uint32Array:ht,Int32Array:ht,Float32Array:ht,Float64Array:ht,Uint8ClampedArray:ht,BigInt64Array:ht,BigUint64Array:ht,DataView:ht,ArrayBuffer:i_,undefined:a_,number:c_}},nh=class extends ms{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===w.map){let t=this._next();if(t.type===w.string&&t.value==="/"){let n=this._next();if(n.type===w.string){if(this._next().type!==w.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new v(w.tag,42,0)}if(n.type===w.map){let s=this._next();if(s.type===w.string&&s.value==="bytes"){let o=this._next();if(o.type===w.string){for(let a=0;a<2;a++)if(this._next().type!==w.break)throw new Error("Invalid encoded Bytes form");let i=gc.decode(`m${o.value}`);return new v(w.bytes,i,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(s)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},sh={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};sh.tags[42]=N.parse;var h0=297,u_=r=>eh(r,l_),oh=r=>{let e=s_(r),t=Object.assign(sh,{tokenizer:new nh(e,sh)});return th(e,t)},xc=r=>f_.decode(u_(r));var f_=new TextDecoder,kc=r=>oh(h_.encode(r)),h_=new TextEncoder;var d_=new TextDecoder;function ih(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let s=r[e++];if(t+=n<28?(s&127)<<n:(s&127)*2**n,s<128)break}return[t,e]}function Sc(r,e){let t;[t,e]=ih(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function p0(r,e){let t;return[t,e]=ih(r,e),[t&7,t>>3,e]}function p_(r){let e={},t=r.length,n=0;for(;n<t;){let s,o;if([s,o,n]=p0(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Sc(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Sc(r,n),e.Name=d_.decode(i)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(s!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Tsize`);[e.Tsize,n]=ih(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function m0(r){let e=r.length,t=0,n,s=!1,o;for(;t<e;){let a,c;if([a,c,t]=p0(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=Sc(r,t),n&&(s=!0)}else if(c===2){if(s)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Sc(r,t),n.push(p_(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let i={};return o&&(i.Data=o),i.Links=n||[],i}var SF=new TextEncoder,vF=2**32,EF=2**31;var AF=new TextEncoder;function y0(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var vc=112;function Er(r){let e=y0(r),t=m0(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(s=>{let o={};try{o.Hash=N.decode(s.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return s.Name!==void 0&&(o.Name=s.Name),s.Tsize!==void 0&&(o.Tsize=s.Tsize),o})),n}var FF=new TextEncoder,m_=new TextDecoder;var w0=512;function b0(r){return JSON.parse(m_.decode(r))}var lh={};K(lh,{identity:()=>ch});ar();var x0=0,y_="identity",k0=qe;function g_(r){return Fr(x0,k0(r))}var ch={code:x0,name:y_,encode:k0,digest:g_};function ys(r,e,t,n,s,o,i){let a=r,c=s;for(;o.length>0;){let l=o[0];if(l in a){o.shift(),c=`${c}/${l}`;let u=N.asCID(a[l]);if(u!=null)return{entry:{type:"object",name:n,path:s,cid:t,node:e,depth:i,size:BigInt(e.length),content:async function*(){yield r}},next:{cid:u,name:l,path:c,toResolve:o}};a=a[l]}else throw new yc(`No property named ${l} found in node ${t}`)}return{entry:{type:"object",name:n,path:s,cid:t,node:e,depth:i,size:BigInt(e.length),content:async function*(){yield r}}}}var w_=async(r,e,t,n,s,o,i,a)=>{let c=await i.get(r,a),l=So(c);return ys(l,c,r,e,t,n,o)},S0=w_;var b_=async(r,e,t,n,s,o,i,a)=>{let c=await i.get(r,a),l=oh(c);return ys(l,c,r,e,t,n,o)},v0=b_;var ve=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function x_(r,e,t,n){let s=BigInt(r.length),o=BigInt(e+s);return t>=o||n<e?new Uint8Array(0):(n>=e&&n<o&&(r=r.subarray(0,Number(n-e))),t>=e&&t<o&&(r=r.subarray(Number(t-e))),r)}var Qr=x_;var k_=(r,e=0,t=r)=>{let n=BigInt(r),s=BigInt(e??0),o=BigInt(t);if(o!==n&&(o=s+o),o>n&&(o=n),s<0n)throw new Jr("Offset must be greater than or equal to 0");if(s>n)throw new Jr("Offset must be less than the file size");if(o<0n)throw new Jr("Length must be greater than or equal to 0");if(o>n)throw new Jr("Length must be less than the file size");return{start:s,end:o}},gs=k_;var S_=r=>{async function*e(t={}){let{start:n,end:s}=gs(r.length,t.offset,t.length),o=Qr(r,0n,n,s);t.onProgress?.(new ve("unixfs:exporter:progress:identity",{bytesRead:BigInt(o.byteLength),totalBytes:s-n,fileSize:BigInt(r.byteLength)})),yield o}return e},v_=async(r,e,t,n,s,o,i,a)=>{if(n.length>0)throw new Ze(`No link named ${t} found in raw node ${r}`);let c=Ur(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:S_(c.digest),depth:o,size:BigInt(c.digest.length),node:c.digest}}},E0=v_;var E_=async(r,e,t,n,s,o,i,a)=>{let c=await i.get(r,a),l=b0(c);return ys(l,c,r,e,t,n,o)},T0=E_;var T_=r=>{async function*e(t={}){let{start:n,end:s}=gs(r.length,t.offset,t.length),o=Qr(r,0n,n,s);t.onProgress?.(new ve("unixfs:exporter:progress:raw",{bytesRead:BigInt(o.byteLength),totalBytes:s-n,fileSize:BigInt(r.byteLength)})),yield o}return e},__=async(r,e,t,n,s,o,i,a)=>{if(n.length>0)throw new Ze(`No link named ${t} found in raw node ${r}`);let c=await i.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:T_(c),depth:o,size:BigInt(c.length),node:c}}},_0=__;var Lh=mt(C0(),1);var uh=new Float32Array([-0]),Tr=new Uint8Array(uh.buffer);function L0(r,e,t){uh[0]=r,e[t]=Tr[0],e[t+1]=Tr[1],e[t+2]=Tr[2],e[t+3]=Tr[3]}function B0(r,e){return Tr[0]=r[e],Tr[1]=r[e+1],Tr[2]=r[e+2],Tr[3]=r[e+3],uh[0]}var fh=new Float64Array([-0]),be=new Uint8Array(fh.buffer);function P0(r,e,t){fh[0]=r,e[t]=be[0],e[t+1]=be[1],e[t+2]=be[2],e[t+3]=be[3],e[t+4]=be[4],e[t+5]=be[5],e[t+6]=be[6],e[t+7]=be[7]}function D0(r,e){return be[0]=r[e],be[1]=r[e+1],be[2]=r[e+2],be[3]=r[e+3],be[4]=r[e+4],be[5]=r[e+5],be[6]=r[e+6],be[7]=r[e+7],fh[0]}var I_=BigInt(Number.MAX_SAFE_INTEGER),C_=BigInt(Number.MIN_SAFE_INTEGER),Be=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Yr;if(e<I_&&e>C_)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>N0&&(s=0n,++n>N0&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return Yr;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Yr}},Yr=new Be(0,0);Yr.toBigInt=function(){return 0n};Yr.zzEncode=Yr.zzDecode=function(){return this};Yr.length=function(){return 1};var N0=4294967296n;function M0(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function O0(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function hh(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function dt(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ec(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var dh=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,dt(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw dt(this,4);return Ec(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw dt(this,4);return Ec(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw dt(this,4);let e=B0(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw dt(this,4);let e=D0(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw dt(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return O0(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw dt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw dt(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Be(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw dt(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw dt(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw dt(this,8);let e=Ec(this.buf,this.pos+=4),t=Ec(this.buf,this.pos+=4);return new Be(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){return this.readLongVarint().toNumber(!0)}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ph(r){return new dh(r instanceof Uint8Array?r:r.subarray())}function Ko(r,e){let t=ph(r);return e.decode(t)}function Gt(r=0){return new Uint8Array(r)}var mh={};K(mh,{base10:()=>L_});it();var L_=cr({prefix:"9",name:"base10",alphabet:"0123456789"});var yh={};K(yh,{base16:()=>B_,base16upper:()=>P_});it();var B_=te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),P_=te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var gh={};K(gh,{base2:()=>D_});it();var D_=te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var wh={};K(wh,{base256emoji:()=>F_});it();var F0=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),N_=F0.reduce((r,e,t)=>(r[t]=e,r),[]),M_=F0.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function O_(r){return r.reduce((e,t)=>(e+=N_[t],e),"")}function R_(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=M_[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var F_=jn({prefix:"\u{1F680}",name:"base256emoji",encode:O_,decode:R_});Rr();var bh={};K(bh,{base8:()=>U_});it();var U_=te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var xh={};K(xh,{identity:()=>$_});ar();it();var $_=jn({prefix:"\0",name:"identity",encode:r=>pu(r),decode:r=>du(r)});var kh={...xh,...gh,...bh,...mh,...yh,...bu,...xu,...ku,...rh,...wh},_U={...Lu,...lh};function $0(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var U0=$0("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Sh=$0("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Gt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),K_={utf8:U0,"utf-8":U0,hex:kh.base16,latin1:Sh,ascii:Sh,binary:Sh,...kh},K0=K_;function Tc(r,e="utf8"){let t=K0[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function vh(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return Gt(i);s+i>e&&(n=Gt(e),s=0);let a=n.subarray(s,s+=i);return s&7&&(s=(s|7)+1),a}}var Xr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Eh(){}var _h=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},z_=vh();function H_(r){return globalThis.Buffer!=null?Gt(r):z_(r)}var jo=class{len;head;tail;states;constructor(){this.len=0,this.head=new Xr(Eh,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Xr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ah((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(zo,10,Be.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Be.fromBigInt(e);return this._push(zo,t.length(),t)}uint64Number(e){let t=Be.fromNumber(e);return this._push(zo,t.length(),t)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Be.fromBigInt(e).zzEncode();return this._push(zo,t.length(),t)}sint64Number(e){let t=Be.fromNumber(e).zzEncode();return this._push(zo,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Th,1,e?1:0)}fixed32(e){return this._push(Ho,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Be.fromBigInt(e);return this._push(Ho,4,t.lo)._push(Ho,4,t.hi)}fixed64Number(e){let t=Be.fromNumber(e);return this._push(Ho,4,t.lo)._push(Ho,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(L0,4,e)}double(e){return this._push(P0,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Th,1,0):this.uint32(t)._push(V_,t,e)}string(e){let t=M0(e);return t!==0?this.uint32(t)._push(hh,t,e):this._push(Th,1,0)}fork(){return this.states=new _h(this),this.head=this.tail=new Xr(Eh,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Xr(Eh,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=H_(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Th(r,e,t){e[t]=r&255}function j_(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ah=class extends Xr{next;constructor(e,t){super(j_,e,t),this.next=void 0}};function zo(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Ho(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function V_(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(jo.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(W_,e,r),this},jo.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(q_,e,r),this});function W_(r,e,t){e.set(r,t)}function q_(r,e,t){r.length<40?hh(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Tc(r),t)}function Ih(){return new jo}function Vo(r,e){let t=Ih();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var ws;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(ws||(ws={}));function _c(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Ch(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(o,i){let a=e(o);i.int32(a)},n=function(o){let i=o.int32();return e(i)};return _c("enum",ws.VARINT,t,n)}function Wo(r,e){return _c("message",ws.LENGTH_DELIMITED,r,e)}var pt;(function(r){let e;(function(s){s.Raw="Raw",s.Directory="Directory",s.File="File",s.Metadata="Metadata",s.Symlink="Symlink",s.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(s){s[s.Raw=0]="Raw",s[s.Directory=1]="Directory",s[s.File=2]="File",s[s.Metadata=3]="Metadata",s[s.Symlink=4]="Symlink",s[s.HAMTShard=5]="HAMTShard"})(t||(t={})),function(s){s.codec=()=>Ch(t)}(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=Wo((s,o,i={})=>{if(i.lengthDelimited!==!1&&o.fork(),s.Type!=null&&(o.uint32(8),r.DataType.codec().encode(s.Type,o)),s.Data!=null&&(o.uint32(18),o.bytes(s.Data)),s.filesize!=null&&(o.uint32(24),o.uint64(s.filesize)),s.blocksizes!=null)for(let a of s.blocksizes)o.uint32(32),o.uint64(a);s.hashType!=null&&(o.uint32(40),o.uint64(s.hashType)),s.fanout!=null&&(o.uint32(48),o.uint64(s.fanout)),s.mode!=null&&(o.uint32(56),o.uint32(s.mode)),s.mtime!=null&&(o.uint32(66),Ac.codec().encode(s.mtime,o)),i.lengthDelimited!==!1&&o.ldelim()},(s,o)=>{let i={blocksizes:[]},a=o==null?s.len:s.pos+o;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:i.Type=r.DataType.codec().decode(s);break;case 2:i.Data=s.bytes();break;case 3:i.filesize=s.uint64();break;case 4:i.blocksizes.push(s.uint64());break;case 5:i.hashType=s.uint64();break;case 6:i.fanout=s.uint64();break;case 7:i.mode=s.uint32();break;case 8:i.mtime=Ac.codec().decode(s,s.uint32());break;default:s.skipType(c&7);break}}return i})),n),r.encode=s=>Vo(s,r.codec()),r.decode=s=>Ko(s,r.codec())})(pt||(pt={}));var Ac;(function(r){let e;r.codec=()=>(e==null&&(e=Wo((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Seconds!=null&&(n.uint32(8),n.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(t.FractionalNanoseconds)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let i=t.uint32();switch(i>>>3){case 1:s.Seconds=t.int64();break;case 2:s.FractionalNanoseconds=t.fixed32();break;default:t.skipType(i&7);break}}return s})),e),r.encode=t=>Vo(t,r.codec()),r.decode=t=>Ko(t,r.codec())})(Ac||(Ac={}));var z0;(function(r){let e;r.codec=()=>(e==null&&(e=Wo((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.MimeType!=null&&(n.uint32(10),n.string(t.MimeType)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let i=t.uint32();switch(i>>>3){case 1:s.MimeType=t.string();break;default:t.skipType(i&7);break}}return s})),e),r.encode=t=>Vo(t,r.codec()),r.decode=t=>Ko(t,r.codec())})(z0||(z0={}));var H0={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},G_=["directory","hamt-sharded-directory"],j0=parseInt("0644",8),V0=parseInt("0755",8),Pt=class r{static unmarshal(e){let t=pt.decode(e),n=new r({type:H0[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:t,data:n,blockSizes:s,hashType:o,fanout:i,mtime:a,mode:c}=e;if(t!=null&&!Object.values(H0).includes(t))throw(0,Lh.default)(new Error("Type: "+t+" is not valid"),"ERR_INVALID_TYPE");this.type=t??"file",this.data=n,this.hashType=o,this.fanout=i,this.blockSizes=s??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?V0:j0:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return G_.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=pt.DataType.Raw;break;case"directory":e=pt.DataType.Directory;break;case"file":e=pt.DataType.File;break;case"metadata":e=pt.DataType.Metadata;break;case"symlink":e=pt.DataType.Symlink;break;case"hamt-sharded-directory":e=pt.DataType.HAMTShard;break;default:throw(0,Lh.default)(new Error(`Type: ${e} is not valid`),"ERR_INVALID_TYPE")}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===j0&&!this.isDirectory()&&(n=void 0),n===V0&&this.isDirectory()&&(n=void 0));let s;return this.mtime!=null&&(s={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),pt.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:s})}};var J0=mt(G0(),1);var Zr=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new J0.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((s,o,i)=>(o!=null&&(o instanceof r?s.push(o.serialize(e,t)):s.push(e(o,i))),s),n))}async asyncTransform(e,t){return Q0(this,e,t)}toJSON(){return this.serialize(Z_,eA)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?Tc(e):e),n=await t.take(this._options.bits),s=this._children.get(n);return s instanceof r?s._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:s}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let s=await n._findPlace(t.existingChild.hash);return s.bucket._putAt(s,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(X_);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function X_(r){return!!r}function Z_(r,e){return r.key}function eA(r){return r}async function Q0(r,e,t){let n=[];for(let s of r._children.compactArray())if(s instanceof Zr)await Q0(s,e,t);else{let o=await e(s);n.push({bitField:r._children.bitField(),children:o})}return t(n)}function Y0(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=Gt(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var tA=[255,254,252,248,240,224,192,128],rA=[1,3,7,15,31,63,127,255],Ic=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let s=this._value[this._currentBytePos],o=this._currentBitPos+1,i=Math.min(o,t),a=nA(s,o-i,i);n=(n<<i)+a,t-=i,this._currentBitPos-=i,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function nA(r,e,t){let n=sA(e,t);return(r&n)>>>e}function sA(r,e){return tA[r]&rA[Math.min(e+r-1,7)]}function X0(r){function e(t){return t instanceof Cc?t:new Cc(t,r)}return e}var Cc=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let s=this._buffers[this._currentBufferIndex],o=Math.min(s.availableBits(),t),i=s.take(o);n=(n<<o)+i,t-=o,this._availableBits-=o,s.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],s=Math.min(n.totalBits()-n.availableBits(),t);n.untake(s),t-=s,this._availableBits+=s,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?Y0([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new Ic(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Z0(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:X0(r.hashFn)};return new Zr(e)}var oA=async function(r){return(await s0.encode(r)).slice(0,8).reverse()},iA=async(r,e,t)=>{let n=(e.tableSize()-1).toString(16).length;await Promise.all(r.map(async s=>{if(s.Name==null)throw new Error("Unexpected Link without a Name");if(s.Name.length===n){let o=parseInt(s.Name,16);e._putObjectAt(o,new Zr({hash:t._options.hash,bits:t._options.bits},e,o));return}await t.put(s.Name.substring(2),!0)}))},ex=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),aA=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},tx=async(r,e,t,n,s)=>{if(n==null){if(r.Data==null)throw new ce("no data in PBNode");let f;try{f=Pt.unmarshal(r.Data)}catch(h){throw new ce(h.message)}if(f.type!=="hamt-sharded-directory")throw new ce("not a HAMT");if(f.fanout==null)throw new ce("missing fanout");let p=Z0({hashFn:oA,bits:Math.log2(Number(f.fanout))});n={rootBucket:p,hamtDepth:1,lastBucket:p}}let o=(n.lastBucket.tableSize()-1).toString(16).length;await iA(r.Links,n.lastBucket,n.rootBucket);let i=await n.rootBucket._findNewBucketAndPos(e),a=ex(i.pos,o),c=aA(i);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=ex(n.lastBucket._posAtParent,o));let l=r.Links.find(f=>{if(f.Name==null)return!1;let p=f.Name.substring(0,o),h=f.Name.substring(o);return!(p!==a||h!==""&&h!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(o)===e)return l.Hash;n.hamtDepth++;let u=await t.get(l.Hash,s);return r=Er(u),tx(r,e,t,n,s)},rx=tx;function cA(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Lc=cA;function lA(r){return r[Symbol.asyncIterator]!=null}function uA(r,e){let t=0;if(lA(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Lc(r),{value:s,done:o}=n.next();if(o===!0)return function*(){}();let i=e(s,t++);if(typeof i.then=="function")return async function*(){await i&&(yield s);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)}()}var nx=uA;function fA(r){return r[Symbol.asyncIterator]!=null}function hA(r,e){let t=0;if(fA(r))return async function*(){for await(let c of r)yield e(c,t++)}();let n=Lc(r),{value:s,done:o}=n.next();if(o===!0)return function*(){}();let i=e(s,t++);if(typeof i.then=="function")return async function*(){yield await i;for await(let c of n)yield e(c,t++)}();let a=e;return function*(){yield i;for(let c of n)yield a(c,t++)}()}var bs=hA;function xs(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Bc=globalThis.CustomEvent??Event;async function*en(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,s=new EventTarget,o=[],i=xs(),a=xs(),c=!1,l,u=!1;s.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(o.length===t&&(i=xs(),await i.promise),u)break;let d={done:!1};o.push(d),m().then(y=>{d.done=!0,d.ok=!0,d.value=y,s.dispatchEvent(new Bc("task-complete"))},y=>{d.done=!0,d.err=y,s.dispatchEvent(new Bc("task-complete"))})}c=!0,s.dispatchEvent(new Bc("task-complete"))}catch(m){l=m,s.dispatchEvent(new Bc("task-complete"))}});function f(){return n?o[0]?.done:!!o.find(m=>m.done)}function*p(){for(;o.length>0&&o[0].done;){let m=o[0];if(o.shift(),m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}function*h(){for(;f();)for(let m=0;m<o.length;m++)if(o[m].done){let d=o[m];if(o.splice(m,1),m--,d.ok)yield d.value;else throw u=!0,i.resolve(),d.err;i.resolve()}}for(;;){if(f()||(a=xs(),await a.promise),l!=null)throw l;if(n?yield*p():yield*h(),c&&o.length===0)break}}function Pc(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Dc=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},ks=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Dc(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Dc(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Bh=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ss(r={}){return dA(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function dA(r,e){e=e??{};let t=e.onEnd,n=new ks,s,o,i,a=Pc(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,g)=>{o=b=>{o=null,n.push(b);try{y(r(n))}catch(x){g(x)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Pc()})}},l=y=>o!=null?o(y):(n.push(y),s),u=y=>(n=new ks,o!=null?o({error:y}):(n.push({error:y}),s)),f=y=>{if(i)return s;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},p=y=>i?s:(i=!0,y!=null?u(y):l({done:!0})),h=()=>(n=new ks,p(),{done:!0}),m=y=>(p(y),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:f,end:p,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let b,x;g!=null&&(b=new Promise((k,S)=>{x=()=>{S(new Bh)},g.addEventListener("abort",x)}));try{await Promise.race([a.promise,b])}finally{x!=null&&g!=null&&g?.removeEventListener("abort",x)}}},t==null)return s;let d=s;return s={[Symbol.asyncIterator](){return this},next(){return d.next()},throw(y){return d.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return d.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(y){return d.end(y),t!=null&&(t(y),t=void 0),s},get readableLength(){return d.readableLength},onEmpty:y=>d.onEmpty(y)},s}function pA(r){return r[Symbol.asyncIterator]!=null}function mA(...r){let e=[];for(let t of r)pA(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Ss({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)t.push(s)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var sx=mA;function vs(r,...e){if(r==null)throw new Error("Empty pipeline");if(Ph(r)){let n=r;r=()=>n.source}else if(ix(r)||ox(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Ph(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Ph(t[n])&&(t[n]=gA(t[n]));return yA(...t)}var yA=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},ox=r=>r?.[Symbol.asyncIterator]!=null,ix=r=>r?.[Symbol.iterator]!=null,Ph=r=>r==null?!1:r.sink!=null&&r.source!=null,gA=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Ss({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(ox(o))s=async function*(){yield*o,n.end()};else if(ix(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return sx(n,s())}return r.source};var wA=(r,e,t,n,s,o,i)=>{async function*a(c={}){let l=c.offset??0,u=c.length??e.Links.length,f=e.Links.slice(l,u);c.onProgress?.(new ve("unixfs:exporter:walk:directory",{cid:r})),yield*vs(f,p=>bs(p,h=>async()=>{let m=h.Name??"",d=`${n}/${m}`;return(await s(h.Hash,m,d,[],o+1,i,c)).entry}),p=>en(p,{ordered:!0,concurrency:c.blockReadConcurrency}),p=>nx(p,h=>h!=null))}return a},ax=wA;var Nh=mt(lx(),1);var Go=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Mh=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},ux=r=>globalThis.DOMException===void 0?new Mh(r):new DOMException(r),fx=r=>{let e=r.reason===void 0?ux("This operation was aborted."):r.reason;return e instanceof Error?e:ux(e)};function Oh(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout}}=e,i,c=new Promise((l,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:p}=e;p.aborted&&u(fx(p)),p.addEventListener("abort",()=>{u(fx(p))})}if(t===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new Go;i=o.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(p){u(p)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?l():s instanceof Error?u(s):(f.message=s??`Promise timed out after ${t} milliseconds`,u(f))},t),(async()=>{try{l(await r)}catch(p){u(p)}})()}).finally(()=>{c.clear()});return c.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},c}function Rh(r,e,t){let n=0,s=r.length;for(;s>0;){let o=Math.trunc(s/2),i=n+o;t(r[i],e)<=0?(n=++i,s-=o+1):s=o}return n}var Jo=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let s=Rh(this.#e,n,(o,i)=>i.priority-o.priority);this.#e.splice(s,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var Qo=class extends Nh.default{#e;#o;#r=0;#d;#a;#p=0;#n;#c;#t;#m;#s=0;#l;#i;#y;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Jo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#o=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#d=e.intervalCap,this.#a=e.interval,this.#t=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#o||this.#r<this.#d}get#x(){return this.#s<this.#l}#k(){this.#s--,this.#u(),this.emit("next")}#S(){this.#w(),this.#g(),this.#c=void 0}get#v(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#r=this.#e?this.#s:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#S()},t)),!0}return!1}#u(){if(this.#t.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#v;if(this.#b&&this.#x){let t=this.#t.dequeue();return t?(this.emit("active"),t(),e&&this.#g(),!0):!1}}return!1}#g(){this.#o||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#a),this.#p=Date.now()+this.#a)}#w(){this.#r===0&&this.#s===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#r=this.#e?this.#s:0,this.#f()}#f(){for(;this.#u(););}get concurrency(){return this.#l}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#l=e,this.#f()}async#E(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#y,...t},new Promise((n,s)=>{this.#t.enqueue(async()=>{this.#s++,this.#r++;try{t.signal?.throwIfAborted();let o=e({signal:t.signal});t.timeout&&(o=Oh(Promise.resolve(o),{milliseconds:t.timeout})),t.signal&&(o=Promise.race([o,this.#E(t.signal)]));let i=await o;n(i),this.emit("completed",i)}catch(o){if(o instanceof Go&&!t.throwOnTimeout){n();return}s(o),this.emit("error",o)}finally{this.#k()}},t),this.emit("add"),this.#u()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#f(),this):this}pause(){this.#i=!0}clear(){this.#t=new this.#m}async onEmpty(){this.#t.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#t.size<e||await this.#h("next",()=>this.#t.size<e)}async onIdle(){this.#s===0&&this.#t.size===0||await this.#h("idle")}async#h(e,t){return new Promise(n=>{let s=()=>{t&&!t()||(this.off(e,s),n())};this.on(e,s)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#i}};async function hx(r,e,t,n,s,o,i){if(e instanceof Uint8Array){let l=Qr(e,n,s,o);t.push(l);return}if(e.Data==null)throw new ce("no data in PBNode");let a;try{a=Pt.unmarshal(e.Data)}catch(l){throw new ce(l.message)}if(a.data!=null){let l=a.data,u=Qr(l,n,s,o);t.push(u),n+=BigInt(u.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw new ce("Inconsistent block sizes and dag links");for(let l=0;l<e.Links.length;l++){let u=e.Links[l],f=n,p=f+a.blockSizes[l];if((s>=f&&s<p||o>=f&&o<=p||s<f&&o>p)&&c.push({link:u,blockStart:n}),n=p,n>o)break}await vs(c,l=>bs(l,u=>async()=>{let f=await r.get(u.link.Hash,i);return{...u,block:f}}),l=>en(l,{ordered:!0,concurrency:i.blockReadConcurrency}),async l=>{for await(let{link:u,block:f,blockStart:p}of l){let h;switch(u.Hash.code){case vc:h=Er(f);break;case $o:h=f;break;default:t.end(new ce(`Unsupported codec: ${u.Hash.code}`));return}let m=new Qo({concurrency:1});m.on("error",d=>{t.end(d)}),m.add(async()=>{i.onProgress?.(new ve("unixfs:exporter:walk:file",{cid:u.Hash})),await hx(r,h,t,p,s,o,i)}),await m.onIdle()}}),n>=o&&t.end()}var kA=(r,e,t,n,s,o,i)=>{async function*a(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:u,end:f}=gs(l,c.offset,c.length);if(f===0n)return;let p=0n,h=f-u,m=Ss();c.onProgress?.(new ve("unixfs:exporter:walk:file",{cid:r})),hx(i,e,m,0n,u,f,c).catch(d=>{m.end(d)});for await(let d of m)if(d!=null){if(p+=BigInt(d.byteLength),p>h)throw m.end(),new pc("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");p===h&&m.end(),c.onProgress?.(new ve("unixfs:exporter:progress:unixfs:file",{bytesRead:p,totalBytes:h,fileSize:l})),yield d}if(p<h)throw new mc("Traversed entire DAG but did not read enough bytes")}return a},Fh=kA;var SA=(r,e,t,n,s,o,i)=>{function a(c={}){return c.onProgress?.(new ve("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),dx(e,n,s,o,i,c)}return a};async function*dx(r,e,t,n,s,o){let i=r.Links;if(r.Data==null)throw new ce("no data in PBNode");let a;try{a=Pt.unmarshal(r.Data)}catch(u){throw new ce(u.message)}if(a.fanout==null)throw new ce("missing fanout");let c=(a.fanout-1n).toString(16).length,l=vs(i,u=>bs(u,f=>async()=>{let p=f.Name!=null?f.Name.substring(c):null;if(p!=null&&p!==""){let h=await t(f.Hash,p,`${e}/${p}`,[],n+1,s,o);return{entries:h.entry==null?[]:[h.entry]}}else{let h=await s.get(f.Hash,o);return r=Er(h),o.onProgress?.(new ve("unixfs:exporter:walk:hamt-sharded-directory",{cid:f.Hash})),{entries:dx(r,e,t,n,s,o)}}}),u=>en(u,{ordered:!0,concurrency:o.blockReadConcurrency}));for await(let{entries:u}of l)yield*u}var px=SA;var vA=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,EA={raw:Fh,file:Fh,directory:ax,"hamt-sharded-directory":px,metadata:(r,e,t,n,s,o,i)=>()=>[],symlink:(r,e,t,n,s,o,i)=>()=>[]},TA=async(r,e,t,n,s,o,i,a)=>{let c=await i.get(r,a),l=Er(c),u,f;if(e==null&&(e=r.toString()),l.Data==null)throw new ce("no data in PBNode");try{u=Pt.unmarshal(l.Data)}catch(h){throw new ce(h.message)}if(t==null&&(t=e),n.length>0){let h;if(u?.type==="hamt-sharded-directory"?h=await rx(l,n[0],i):h=vA(l,n[0]),h==null)throw new Ze("file does not exist");let m=n.shift(),d=`${t}/${m}`;f={cid:h,toResolve:n,name:m??"",path:d}}let p=EA[u.type](r,l,u,t,s,o,i);if(p==null)throw new Ze("could not find content exporter");return u.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:p,unixfs:u,depth:o,node:l,size:u.fileSize()},next:f}:{entry:{type:"file",name:e,path:t,cid:r,content:p,unixfs:u,depth:o,node:l,size:u.fileSize()},next:f}},mx=TA;var _A={[vc]:mx,[$o]:_0,[ko]:S0,[h0]:v0,[ch.code]:E0,[w0]:T0},yx=async(r,e,t,n,s,o,i)=>{let a=_A[r.code];if(a==null)throw new dc(`No resolver for code ${r.code}`);return a(r,e,t,n,yx,s,o,i)},gx=yx;var AA=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),IA=r=>{if(r instanceof Uint8Array)return{cid:N.decode(r),toResolve:[]};let e=N.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=AA(r);return{cid:N.parse(t[0]),toResolve:t.slice(1)}}throw new hc(`Unknown path type ${r}`)};async function*CA(r,e,t={}){let{cid:n,toResolve:s}=IA(r),o=n.toString(),i=o,a=s.length;for(;;){let c=await gx(n,o,i,s,a,e,t);if(c.entry==null&&c.next==null)throw new Ze(`Could not resolve ${r}`);if(c.entry!=null&&(yield c.entry),c.next==null)return;s=c.next.toResolve,n=c.next.cid,o=c.next.name,i=c.next.path}}async function wx(r,e,t={}){let n=await f0(CA(r,e,t));if(n==null)throw new Ze(`Could not resolve ${r}`);return n}var LA=u0(),BA=vr({fileChunkEncoder:Gr,smallFileEncoder:Gr,chunker:jf(1024*1024),fileLayout:oc(1024)});async function PA(r){let e=[];return await r.pipeTo(new WritableStream({write(t){e.push(t)}})),e}async function $h(r){let e=DA(r),t=await PA(e);return{cid:t.at(-1).cid,blocks:t}}async function Kh(r,e,t){let n=await wx(e.toString(),r,{length:t.size}),s=[];for await(let o of n.content())s.push(o);return new File(s,n.name,{type:t.type,lastModified:0})}function DA(r){let{readable:e,writable:t}=new TransformStream({},LA),n=l0({writable:t,settings:BA}),s=new Uh("",r);return(async()=>(await s.finalize(n),await n.close()))(),e}var Uh=class{#e;constructor(e,t){this.name=e,this.#e=t}async finalize(e){let t=Fo(e);return await this.#e.stream().pipeTo(new WritableStream({async write(n){await t.write(n)}})),await t.close()}};ae();function Hh(r){return r===!1&&r===null&&r===void 0}function me(r){if(Hh(r))throw new Error("value is Falsy");return r}function Yo(r){if(!Hh(r))return r}ye();var Gh=class{value;next;constructor(e){this.value=e}},ti=class{#e;#o;#r;constructor(){this.clear()}enqueue(e){let t=new Gh(e);this.#e?(this.#o.next=t,this.#o=t):(this.#e=t,this.#o=t),this.#r++}dequeue(){let e=this.#e;if(e)return this.#e=this.#e.next,this.#r--,e.value}peek(){if(this.#e)return this.#e.value}clear(){this.#e=void 0,this.#o=void 0,this.#r=0}get size(){return this.#r}*[Symbol.iterator](){let e=this.#e;for(;e;)yield e.value,e=e.next}};function Mc(r){xx(r);let e=new ti,t=0,n=()=>{t<r&&e.size>0&&(e.dequeue()(),t++)},s=()=>{t--,n()},o=async(c,l,u)=>{let f=(async()=>c(...u))();l(f);try{await f}catch{}s()},i=(c,l,u)=>{new Promise(f=>{e.enqueue(f)}).then(o.bind(void 0,c,l,u)),(async()=>(await Promise.resolve(),t<r&&n()))()},a=(c,...l)=>new Promise(u=>{i(c,u,l)});return Object.defineProperties(a,{activeCount:{get:()=>t},pendingCount:{get:()=>e.size},clearQueue:{value(){e.clear()}},concurrency:{get:()=>r,set(c){xx(c),r=c,queueMicrotask(()=>{for(;t<r&&e.size>0;)n()})}}}),a}function xx(r){if(!((Number.isInteger(r)||r===Number.POSITIVE_INFINITY)&&r>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up")}var Ar=mt(Yh(),1),Oc={SHA2_256:18,LENGTH:32,DAG_PB:112},Lx=40;function ri(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=Ar.default.decode(r);return e.seek(Ar.default.decode.bytes),t}function Bx(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}function Px(r){Ar.default.decode(r);let e=Ar.default.decode.bytes,t=Ar.default.decode(r.subarray(Ar.default.decode.bytes)),n=Ar.default.decode.bytes;return e+n+t}var Ir={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},ni={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Ir.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Ir.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=ni["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let s=e;s<r.length;s++){let o=r[s];if(o=ni["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:Ir.Int,CarV1HeaderOrV2Pragma:r=>{if(Ir.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let s=0;s<e.length;s++){let[o,i]=e[s];switch(o){case"roots":{let a=ni["CarV1HeaderOrV2Pragma > roots (anon)"](r[o]);if(a===void 0)return;if(a!==i||t!==r){if(t===r){t={};for(let c=0;c<s;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=ni.Int(r[o]);if(a===void 0)return;if(a!==i||t!==r){if(t===r){t={};for(let c=0;c<s;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},si={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Ir.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Ir.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=si["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let s=e;s<r.length;s++){let o=r[s];if(o=si["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:Ir.Int,CarV1HeaderOrV2Pragma:r=>{if(Ir.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let s=0;s<e.length;s++){let[o,i]=e[s];switch(o){case"roots":{let a=si["CarV1HeaderOrV2Pragma > roots (anon)"](i);if(a===void 0)return;if(a!==i||t!==r){if(t===r){t={};for(let c=0;c<s;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=si.Int(i);if(a===void 0)return;if(a!==i||t!==r){if(t===r){t={};for(let c=0;c<s;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},Dx={toTyped:ni.CarV1HeaderOrV2Pragma,toRepresentation:si.CarV1HeaderOrV2Pragma};async function Nx(r,e){let t=ri(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),s=So(n);if(Dx.toTyped(s)===void 0)throw new Error("Invalid CAR header format");if(s.version!==1&&s.version!==2||e!==void 0&&s.version!==e)throw new Error(`Invalid CAR version: ${s.version}${e!==void 0?` (expected ${e})`:""}`);if(s.version===1){if(!Array.isArray(s.roots))throw new Error("Invalid CAR header format");return s}if(s.roots!==void 0)throw new Error("Invalid CAR header format");let o=Bx(await r.exactly(Lx,!0));r.seek(o.dataOffset-r.pos);let i=await Nx(r,1);return Object.assign(i,o)}async function ZA(r){let e=await r.exactly(2,!1);if(e[0]===Oc.SHA2_256&&e[1]===Oc.LENGTH){let i=await r.exactly(34,!0),a=Ur(i);return N.create(0,Oc.DAG_PB,a)}let t=ri(await r.upTo(8),r);if(t!==1)throw new Error(`Unexpected CID version (${t})`);let n=ri(await r.upTo(8),r),s=await r.exactly(Px(await r.upTo(8)),!0),o=Ur(s);return N.create(t,n,o)}async function Mx(r){let e=r.pos,t=ri(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR section (zero length)");t+=r.pos-e;let n=await ZA(r),s=t-Number(r.pos-e);return{cid:n,length:t,blockLength:s}}async function eI(r){let{cid:e,blockLength:t}=await Mx(r);return{bytes:await r.exactly(t,!0),cid:e}}async function tI(r){let e=r.pos,{cid:t,length:n,blockLength:s}=await Mx(r),o={cid:t,length:n,blockLength:s,offset:e,blockOffset:r.pos};return r.seek(o.blockLength),o}function Ox(r){let e=(async()=>{let t=await Nx(r);if(t.version===2){let n=r.pos-t.dataOffset;r=nI(r,t.dataSize-n)}return t})();return{header:()=>e,async*blocks(){for(await e;(await r.upTo(8)).length>0;)yield await eI(r)},async*blocksIndex(){for(await e;(await r.upTo(8)).length>0;)yield await tI(r)}}}function Rx(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let s=r.subarray(e,e+t);return n&&(e+=t),s},seek(t){e+=t},get pos(){return e}}}function rI(r){let e=0,t=0,n=0,s=new Uint8Array(0),o=async i=>{t=s.length-n;let a=[s.subarray(n)];for(;t<i;){let l=await r();if(l==null)break;t<0?l.length>t&&a.push(l.subarray(-t)):a.push(l),t+=l.length}s=new Uint8Array(a.reduce((l,u)=>l+u.length,0));let c=0;for(let l of a)s.set(l,c),c+=l.length;n=0};return{async upTo(i){return s.length-n<i&&await o(i),s.subarray(n,n+Math.min(s.length-n,i))},async exactly(i,a=!1){if(s.length-n<i&&await o(i),s.length-n<i)throw new Error("Unexpected end of data");let c=s.subarray(n,n+i);return a&&(e+=i,n+=i),c},seek(i){e+=i,n+=i},get pos(){return e}}}function Fx(r){let e=r[Symbol.asyncIterator]();async function t(){let n=await e.next();return n.done?null:n.value}return rI(t)}function nI(r,e){let t=0;return{async upTo(n){let s=await r.upTo(n);return s.length+t>e&&(s=s.subarray(0,e-t)),s},async exactly(n,s=!1){let o=await r.exactly(n,s);if(o.length+t>e)throw new Error("Unexpected end of data");return s&&(t+=n),o},seek(n){t+=n,r.seek(n)},get pos(){return r.pos}}}var oi=class{constructor(e,t){this._header=e,this._blocks=t,this._keys=t.map(n=>n.cid.toString())}get version(){return this._header.version}async getRoots(){return this._header.roots}async has(e){return this._keys.indexOf(e.toString())>-1}async get(e){let t=this._keys.indexOf(e.toString());return t>-1?this._blocks[t]:void 0}async*blocks(){for(let e of this._blocks)yield e}async*cids(){for(let e of this._blocks)yield e.cid}static async fromBytes(e){if(!(e instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");return Ux(Rx(e))}static async fromIterable(e){if(!e||typeof e[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return Ux(Fx(e))}};async function Ux(r){let e=Ox(r),t=await e.header(),n=[];for await(let s of e.blocks())n.push(s);return new oi(t,n)}ae();async function ii(r,e){let t=await r.getRoots(),n=await r.get(t[0]);if(!n)throw e.Error().Msg("missing header block").AsError();let o=(await lr({bytes:n.bytes,hasher:Q,codec:re})).value;if(o&&!o.fp)throw e.Error().Msg("missing fp").AsError();return o.fp}ae();ye();var et=class extends Ye{constructor(e,t={add:!0,noLoader:!1}){super(),t.add&&e.transactions.add(this),this.parent=e}async get(e){return await this.superGet(e)||Yo(await this.parent.get(e))}async superGet(e){return super.get(e)}};function Xh(r,e,t,n){let s=H(r,t,n),o=e.store||{};return{applyMeta:(i,a)=>Promise.resolve(),compact:async i=>({}),autoCompact:100,public:!1,name:void 0,threshold:1e3*1e3,...e,logger:s,keyBag:e.keyBag||{},crypto:Hn(e.crypto),store:o,storeRuntime:ed(o,r)}}function Zh(r,e){return e.name?new ai(r,e):new Es(e)}var Es=class{constructor(e={}){this.transactions=new Set;this.sthis=Xo(e),this.ebOpts=Xh(this.sthis,e,"BaseBlockstore"),this.logger=this.ebOpts.logger}ready(){return Promise.resolve()}async close(){}async destroy(){}async compact(){}async get(e){if(!e)throw this.logger.Error().Msg("required cid").AsError();for(let t of this.transactions){let n=await t.superGet(e);if(n)return n}}async put(e,t){throw this.logger.Error().Msg("use a transaction to put").AsError()}async transaction(e,t){let n=new et(this,t),s=await e(n);return this.lastTxMeta=s,{t:n,meta:s}}openTransaction(e={add:!0,noLoader:!1}){return new et(this,e)}async commitTransaction(e,t,n){if(!this.loader)throw this.logger.Error().Msg("loader required to commit").AsError();let s=await this.loader?.commit(e,t,n);if(this.ebOpts.autoCompact&&this.loader.carLog.length>this.ebOpts.autoCompact&&setTimeout(()=>void this.compact(),10),s)return this.transactions.delete(e),{meta:t,cars:s,t:e};throw this.logger.Error().Msg("failed to commit car files").AsError()}async*entries(){let e=new Set;for(let t of this.transactions)for await(let n of t.entries())e.has(n.cid.toString())||(e.add(n.cid.toString()),yield n)}},ai=class extends Es{constructor(t,n){super(n);this.compacting=!1;this.logger=H(this.sthis,"EncryptedBlockstore");let{name:s}=n;if(!s)throw this.logger.Error().Msg("name required").AsError();this.name=s,this.loader=new Ts(this.name,n,t)}ready(){return this.loader.ready()}close(){return this.loader.close()}destroy(){return this.loader.destroy()}async get(t){let n=await super.get(t);if(n)return n;if(this.loader)return Yo(await this.loader.getBlock(t))}async transaction(t,n={noLoader:!1}){let{t:s,meta:o}=await super.transaction(t),i=await this.loader.commit(s,o,n);if(this.ebOpts.autoCompact&&this.loader.carLog.length>this.ebOpts.autoCompact&&setTimeout(()=>void this.compact(),10),i)return this.transactions.delete(s),{meta:o,cars:i,t:s};throw this.logger.Error().Msg("failed to commit car files").AsError()}async getFile(t,n){if(await this.ready(),!this.loader)throw this.logger.Error().Msg("loader required to get file, database must be named").AsError();let o=await(await this.loader.loadFileCar(t)).get(n);if(!o)throw this.logger.Error().Str("cid",n.toString()).Msg("Missing block").AsError();return o.bytes}async compact(){if(await this.ready(),!this.loader)throw this.logger.Error().Msg("loader required to compact").AsError();if(this.loader.carLog.length<2)return;let t=this.ebOpts.compact||(o=>this.defaultCompact(o,this.logger));if(!t||this.compacting)return;let n=new ci(this);this.compacting=!0;let s=await t(n);await this.loader?.commit(n.loggedBlocks,s,{compact:!0,noLoader:!0}),this.compacting=!1}async defaultCompact(t,n){if(!this.loader)throw n.Error().Msg("no loader").AsError();if(!this.lastTxMeta)throw n.Error().Msg("no lastTxMeta").AsError();for await(let s of this.loader.entries(!1))t.loggedBlocks.putSync(s.cid,s.bytes);for(let s of this.transactions)for await(let o of s.entries())t.loggedBlocks.putSync(o.cid,o.bytes);return this.lastTxMeta}async*entries(){for await(let t of this.loader.entries())yield t}},ci=class{constructor(e){this.blockstore=e,this.loggedBlocks=new et(e)}async get(e){let t=await this.blockstore.get(e);return t&&this.loggedBlocks.putSync(e,t.bytes),Yo(t)}};ae();var _s=class{constructor(){this.queue=[];this.processing=!1;this._waitIdleItems=new Set}waitIdle(){if(this.queue.length===0&&!this.processing)return Promise.resolve();let e=new Ds;return this._waitIdleItems.add(e),e.asPromise()}async enqueue(e){return new Promise((t,n)=>{let s=async()=>{try{t(await e())}catch(o){n(o)}finally{this.processing=!1,this.processNext()}};this.queue.push(s),this.processing||this.processNext()})}processNext(){if(this.queue.length>0&&!this.processing){this.processing=!0;let e=this.queue.shift();e&&e().finally(()=>{})}if(this.queue.length===0&&!this.processing){let e=Array.from(this._waitIdleItems);this._waitIdleItems.clear(),e.map(t=>t.resolve())}}};var fd={};K(fd,{KeyBag:()=>Uc,defaultKeyBagUrl:()=>tk,getKeyBag:()=>Fe,registerKeyBagProviderFactory:()=>mI});ae();ye();Rr();var Uc=class{constructor(e){this.rt=e;this._warnOnce=new X;this._seq=new ll;this.logger=H(e.sthis,"KeyBag"),this.logger.Debug().Msg("KeyBag created")}async subtleKey(e){let t=this.rt.url.getParam("extractKey")==="_deprecated_internal_api";return t&&this._warnOnce.once(()=>this.logger.Warn().Msg("extractKey is enabled via _deprecated_internal_api --- handle keys safely!!!")),await this.rt.crypto.importKey("raw",J.decode(e),"AES-GCM",t,["encrypt","decrypt"])}async ensureKeyFromUrl(e,t){let n=e.getParam("storekey");if(n==="insecure")return C.Ok(e);if(!n){let s=`@${t()}@`,o=await this.getNamedKey(s);if(o.isErr())return o;let i=e.build().setParam("storekey",s);return C.Ok(i.URI())}if(n.startsWith("@")&&n.endsWith("@")){let s=await this.getNamedKey(n);if(s.isErr())return s}return C.Ok(e)}async toKeyWithFingerPrint(e){let t=J.decode(e),n=await this.subtleKey(e),s=await this.rt.crypto.digestSHA256(t);return C.Ok({key:n,fingerPrint:J.encode(new Uint8Array(s))})}async setNamedKey(e,t){return this._seq.add(()=>this._setNamedKey(e,t))}async _setNamedKey(e,t){let n={name:e,key:t},s=await this.rt.getBag();return this.logger.Debug().Str("name",e).Msg("setNamedKey"),await s.set(e,n),await this.toKeyWithFingerPrint(n.key)}async getNamedExtractableKey(e,t=!1){let n=await this.getNamedKey(e,t);if(n.isErr())return n;let s=n.Ok();return C.Ok({...s,extract:async()=>{let o=new Uint8Array(await this.rt.crypto.exportKey("raw",s.key));return{key:o,keyStr:J.encode(o)}}})}async getNamedKey(e,t=!1){let n=this.rt.sthis.nextId(4).str;return this._seq.add(async()=>{let o=await(await this.rt.getBag()).get(e);if(o){let a=await this.toKeyWithFingerPrint(o.key);return this.logger.Debug().Str("id",n).Str("name",e).Result("fpr",a).Msg("fingerPrint getNamedKey"),a}if(t)return this.logger.Debug().Str("id",n).Str("name",e).Msg("failIfNotFound getNamedKey"),C.Err(new Error(`Key not found: ${e}`));let i=await this._setNamedKey(e,J.encode(this.rt.crypto.randomBytes(this.rt.keyLength)));return this.logger.Debug().Str("id",n).Str("name",e).Result("fpr",i).Msg("createKey getNamedKey-post"),i})}},ek=new Map([{protocol:"file:",factory:async(r,e)=>{let{KeyBagProviderFile:t}=await Promise.resolve().then(()=>(jx(),Hx));return new t(r,e)}},{protocol:"indexdb:",factory:async(r,e)=>{let{KeyBagProviderIndexDB:t}=await Promise.resolve().then(()=>(Zx(),Xx));return new t(r,e)}}].map(r=>[r.protocol,r]));function mI(r){let e=r.protocol.endsWith(":")?r.protocol:r.protocol+":";ek.set(e,{...r,protocol:e})}function tk(r){let e=r.env.get("FP_KEYBAG_URL"),t;return Or().isBrowser?t=Ie.from(e||"indexdb://fp-keybag"):e?t=Ie.from(e):(e=`${r.env.get("HOME")}/.fireproof/keybag`,t=Ie.from(`file://${e}`)),H(r,"defaultKeyBagUrl").Debug().Url(t).Msg("from env"),t}function yI(r,e){if(e.keyRuntime)return e.keyRuntime;let t=H(r,"KeyBag"),n;e.url?(n=Ie.from(e.url),t.Debug().Url(n).Msg("from opts")):n=tk(r);let s=ek.get(n.protocol);if(!s)throw t.Error().Url(n).Msg("unsupported protocol").AsError();let o=async()=>s.factory(n,r);if(n.hasParam("masterkey"))throw t.Error().Url(n).Msg("masterkey is not supported").AsError();return{url:n,crypto:e.crypto||Hn({}),sthis:r,logger:t,keyLength:e.keyLength||16,getBag:o,id:()=>n.toString()}}var gI=new _e;async function Fe(r,e={}){await r.start();let t=yI(r,e);return gI.get(t.id()).once(async()=>new Uc(t))}var wI=Ru(),bI={float64:!1,quickEncodeToken:Pa};function hd(r,e=wI,t=bI){if(Array.isArray(r)){let n=0;for(let s of r)n+=hd(s,e,t);return n}else{let n=e[r.type.major];if(n.encodedSize===void 0||typeof n.encodedSize!="function")throw new Error(`Encoder for ${r.type.name} does not have an encodedSize()`);return n.encodedSize(r,t)}}var hi=mt(Yh(),1),pd=class{constructor(e,t){this.bytes=e,this.byteOffset=t,this.roots=[],this.headerSize=t}addRoot(e,t){return xI(this,e,t),this}write(e){return kI(this,e),this}close(e){return SI(this,e)}},xI=(r,e,t={})=>{let{resize:n=!1}=t,{bytes:s,headerSize:o,byteOffset:i,roots:a}=r;r.roots.push(e);let c=$c(r);if(c>o)if(c-o+i<s.byteLength)if(n)nk(r,c);else throw a.pop(),new RangeError(`Header of size ${o} has no capacity for new root ${e}.
146
146
  However there is a space in the buffer and you could call addRoot(root, { resize: root }) to resize header to make a space for this root.`);else throw a.pop(),new RangeError(`Buffer has no capacity for a new root ${e}`)},di=({cid:r,bytes:e})=>{let t=r.bytes.byteLength+e.byteLength;return hi.default.encodingLength(t)+t},kI=(r,{cid:e,bytes:t})=>{let n=e.bytes.byteLength+t.byteLength,s=hi.default.encode(n);if(r.byteOffset+s.length+n>r.bytes.byteLength)throw new RangeError("Buffer has no capacity for this block");dd(r,s),dd(r,e.bytes),dd(r,t)},SI=(r,e={})=>{let{resize:t=!1}=e,{roots:n,bytes:s,byteOffset:o,headerSize:i}=r,a=Ku({version:1,roots:n}),c=hi.default.encode(a.length),l=c.length+a.byteLength;if(i-l===0)return rk(r,c,a),s.subarray(0,o);if(t)return nk(r,l),rk(r,c,a),s.subarray(0,r.byteOffset);throw new RangeError(`Header size was overestimated.
147
- You can use close({ resize: true }) to resize header`)},nk=(r,e)=>{let{bytes:t,headerSize:n}=r;t.set(t.subarray(n,r.byteOffset),e),r.byteOffset+=e-n,r.headerSize=e},dd=(r,e)=>{r.bytes.set(e,r.byteOffset),r.byteOffset+=e.length},rk=({bytes:r},e,t)=>{r.set(e),r.set(t,e.length)},vI=[new v(w.map,2),new v(w.string,"version"),new v(w.uint,1),new v(w.string,"roots")],EI=new v(w.tag,42),TI=r=>{let e=[...vI];e.push(new v(w.array,r.length));for(let n of r)e.push(EI),e.push(new v(w.bytes,{length:n+1}));let t=hd(e);return hi.default.encodingLength(t)+t},$c=({roots:r})=>TI(r.map(e=>e.bytes.byteLength));var sk=(r,e={})=>{let{roots:t=[],byteOffset:n=0,byteLength:s=r.byteLength,headerSize:o=$c({roots:t})}=e,i=new Uint8Array(r,n,s),a=new pd(i,o);for(let c of t)a.addRoot(c);return a};async function ik(r,e,t){let n=0,s=$c({roots:r});n+=s;for(let{cid:a,bytes:c}of e.entries())n+=di({cid:a,bytes:c});let o=new Uint8Array(n),i=sk(o,{headerSize:s});for(let a of r)i.addRoot(a);for(let{cid:a,bytes:c}of e.entries())i.write({cid:a,bytes:c});return i.close(),await Qn({value:i.bytes,hasher:Q,codec:t})}async function ok(r,e,t){return ik([e],t,r)}async function ak(r,e,t,n){let{files:s}=AI(n),o=[],i=(await r.keyedCrypto()).codec(),a=await II(i,s,t);for(let c of a){let{cid:l,bytes:u}=c;await r.save({cid:l,bytes:u}),await e.enqueueFile(l),o.push(l)}return o}function AI(r){let e=[];for(let[,t]of Object.entries(r.files||{}))t&&typeof t=="object"&&"cid"in t&&t!==null&&e.push(t.cid);return{...r,files:e}}async function II(r,e,t){return[await ik(e,t,r)]}function CI(r,e,t=!1){return{...t?{cars:[],compact:e}:{cars:e,compact:[]},meta:r}}async function LI(r){return await Qn({value:{fp:r},hasher:Q,codec:re})}async function ck(r,e,t,n={noLoader:!1,compact:!1}){let s=CI(t,r.carLog,!!n.compact),o=await LI(s),i=await BI(r.encoder,r.threshold,o,e),a=[];for(let l of i){let{cid:u,bytes:f}=l;await r.carStore.save({cid:u,bytes:f}),a.push(u)}let c={cars:a};return await r.WALStore.enqueue(c,n),await r.metaStore.save(c),{cgrp:a,header:s}}async function BI(r,e,t,n){let s=[];e=e||128e3*8;let o=new et(n.parent,{add:!1,noLoader:!1});o.putSync(t.cid,t.bytes);let i=di(t),a=t;for(let{cid:c,bytes:l}of n.entries())i+=di({cid:c,bytes:l}),i>=e?(s.push(await ok(r,a.cid,o)),o=new et(n.parent,{add:!1,noLoader:!1}),o.putSync(c,l),a={cid:c,bytes:l},i=di({cid:c,bytes:l})):o.putSync(c,l);return s.push(await ok(r,a.cid,o)),s}ye();var Kc=class{constructor(e,t){this.eventsWeHandled=new Set;this.queue=[];this.isProcessing=!1;this.logger=H(e,"TaskManager"),this.callback=t}async handleEvent(e,t,n){for(let s of t)this.eventsWeHandled.add(s.toString());this.queue.push({cid:e.toString(),dbMeta:n,retries:0}),this.queue=this.queue.filter(({cid:s})=>!this.eventsWeHandled.has(s)),this.processQueue()}async processQueue(){if(this.isProcessing)return;this.isProcessing=!0;let t=this.queue.filter(({cid:n})=>!this.eventsWeHandled.has(n))[0];if(t)try{await this.callback(t.dbMeta),this.eventsWeHandled.add(t.cid),this.queue=this.queue.filter(({cid:n})=>!this.eventsWeHandled.has(n))}catch(n){throw t.retries++>3&&(this.logger.Error().Str("cid",t.cid).Msg("failed to process event block after 3 retries"),this.queue=this.queue.filter(({cid:s})=>s!==t.cid)),await new Promise(s=>setTimeout(s,50)),this.logger.Error().Err(n).Msg("failed to process event block").AsError()}finally{this.isProcessing=!1,this.queue.length>0&&this.processQueue()}}};function zc(r,e){return r.some(t=>t.toString()===e.toString())}function lk(r,e=new Set){let t=new Map;for(let n of r)e.has(n.toString())||t.set(n.toString(),n);return[...t.values()]}var Ts=class{constructor(e,t,n){this.commitQueue=new _s;this.isCompacting=!1;this.carReaders=new Map;this.seenCompacted=new Set;this.processedCars=new Set;this.carLog=[];this.getBlockCache=new Map;this.seenMeta=new Set;this.writeLimit=Mc(1);this.onceReady=new X;this.name=e,this.sthis=n,this.ebOpts=Xh(n,{...t,name:e},"Loader"),this.logger=this.ebOpts.logger,this.taskManager=new Kc(n,async s=>{await this.handleDbMetasFromStore([s])})}async keyBag(){return Fe(this.sthis,this.ebOpts.keyBag)}async carStore(){return this.ebOpts.storeRuntime.makeDataStore(this)}async fileStore(){return this.ebOpts.storeRuntime.makeDataStore(this)}async WALStore(){return this.ebOpts.storeRuntime.makeWALStore(this)}async metaStore(){return this.ebOpts.storeRuntime.makeMetaStore(this)}async ready(){return this.onceReady.once(async()=>{let e=await(await this.metaStore()).load();this.ebOpts.meta?await this.handleDbMetasFromStore([this.ebOpts.meta]):e&&await this.handleDbMetasFromStore(e)})}async close(){let e=await Promise.all([this.carStore(),this.metaStore(),this.fileStore(),this.WALStore()]);await Promise.all(e.map(t=>t.close()))}async destroy(){let e=await Promise.all([this.carStore(),this.metaStore(),this.fileStore(),this.WALStore()]);await Promise.all(e.map(t=>t.destroy()))}async handleDbMetasFromStore(e){this.logger.Debug().Any("metas",e).Msg("handleDbMetasFromStore");for(let t of e)await this.writeLimit(async()=>{await this.mergeDbMetaIntoClock(t)})}async mergeDbMetaIntoClock(e){if(this.isCompacting)throw this.logger.Error().Msg("cannot merge while compacting").AsError();if(this.seenMeta.has(e.cars.toString())||(this.seenMeta.add(e.cars.toString()),zc(this.carLog,e.cars)))return;let t=await this.loadCarHeaderFromMeta(e);t.compact.map(n=>n.toString()).forEach(this.seenCompacted.add,this.seenCompacted),await this.getMoreReaders(t.cars.flat()),this.carLog=[...lk([e.cars,...this.carLog,...t.cars],this.seenCompacted)],await this.ebOpts.applyMeta?.(t.meta)}async loadCarHeaderFromMeta({cars:e}){let t=await this.loadCar(e[0]);return await ii(t,this.logger)}async commitFiles(e,t){await this.ready();let n=await this.fileStore(),s=await this.WALStore();return this.commitQueue.enqueue(()=>ak(n,s,e,t))}async loadFileCar(e){return await this.storesLoadCar(e,await this.fileStore(),this.remoteFileStore)}async commit(e,t,n={noLoader:!1,compact:!1}){await this.ready();let s=await this.fileStore(),o={encoder:(await s.keyedCrypto()).codec(),carLog:this.carLog,carStore:s,WALStore:await this.WALStore(),metaStore:await this.metaStore(),threshold:this.ebOpts.threshold};return this.commitQueue.enqueue(async()=>{await this.cacheTransaction(e);let i=await ck(o,e,t,n);return await this.updateCarLog(i.cgrp,i.header,!!n.compact),i.cgrp})}async updateCarLog(e,t,n){if(n){let s=t.compact[t.compact.length-1];t.compact.map(o=>o.toString()).forEach(this.seenCompacted.add,this.seenCompacted),this.carLog=[...lk([...this.carLog,...t.cars,e],this.seenCompacted)],await this.removeCidsForCompact(s[0]).catch(o=>o)}else this.carLog.unshift(e)}async cacheTransaction(e){for await(let t of e.entries()){let n=t.cid.toString();this.getBlockCache.has(n)||this.getBlockCache.set(n,t)}}async cacheCarReader(e,t){if(!this.processedCars.has(e)){this.processedCars.add(e);for await(let n of t.blocks()){let s=n.cid.toString();this.getBlockCache.has(s)||this.getBlockCache.set(s,n)}}}async removeCidsForCompact(e){let t=await this.loadCarHeaderFromMeta({cars:[e]});for(let n of t.compact)for(let s of n)await(await this.carStore()).remove(s)}async*entries(e=!0){if(await this.ready(),e)for(let[,t]of this.getBlockCache)yield t;else{for(let[,t]of this.getBlockCache)yield t;for(let t of this.carLog)for(let n of t){let s=await this.loadCar(n);if(!s)throw this.logger.Error().Ref("cid",n).Msg("missing car reader").AsError();for await(let o of s.blocks()){let i=o.cid.toString();this.getBlockCache.has(i)||(yield o)}}}}async getBlock(e){await this.ready();let t=e.toString();if(this.getBlockCache.has(t))return this.getBlockCache.get(t);let n=async a=>{if(this.getBlockCache.has(t))return this.getBlockCache.get(t);let c=await this.loadCar(a);if(!c)throw this.logger.Error().Ref("cid",a).Msg("missing car reader").AsError();if(await this.cacheCarReader(a.toString(),c).catch(()=>{}),this.getBlockCache.has(t))return this.getBlockCache.get(t);throw this.logger.Error().Str("cid",t).Msg("block not in reader").AsError()},s=async a=>{let c=await this.loadCar(a);if(!c)throw this.logger.Error().Str("cid",a.toString()).Msg("missing car reader").AsError();let u=(await ii(c,this.logger)).compact,f,p=5;for(let h=0;h<u.length;h+=p){let m=[];for(let d=h;d<Math.min(h+p,u.length);d++)for(let y of u[d])m.push(n(y));try{f=await Promise.any(m)}catch{}if(f)break}if(this.getBlockCache.has(t))return this.getBlockCache.get(t);throw this.logger.Error().Str("cid",t).Msg("block not in compact reader").AsError()},o,i=5;for(let a=0;a<this.carLog.length;a+=i){let l=this.carLog.slice(a,a+i).flatMap(u=>u.map(n));try{o=await Promise.any(l)}catch{}if(o)break}if(!o)try{o=await s(this.carLog[this.carLog.length-1][0])}catch{}return o}async loadCar(e){if(!this.carStore)throw this.logger.Error().Msg("car store not initialized").AsError();return await this.storesLoadCar(e,await this.carStore(),this.remoteCarStore)}async makeDecoderAndCarReader(e,t,n){let s=e.toString(),o,i=t;try{this.logger.Debug().Str("cid",s).Msg("loading car"),o=await t.load(e),this.logger.Debug().Bool("loadedCar",o).Msg("loaded")}catch(f){if(n){let p=await n.load(e);p&&(this.logger.Debug().Ref("cid",p.cid).Msg("saving remote car locally"),await t.save(p),o=p,i=n)}else this.logger.Error().Str("cid",s).Err(f).Msg("loading car")}if(!o)throw this.logger.Error().Url(t.url()).Str("cid",s).Msg("missing car files").AsError();let a=await lr({bytes:o.bytes,hasher:Q,codec:(await i.keyedCrypto()).codec()}),c=await oi.fromBytes(a.value),l=Promise.resolve(c),u=l.then(async f=>(await this.cacheCarReader(s,f).catch(p=>{this.logger.Error().Err(p).Str("cid",s).Msg("error caching car reader")}),f));return this.carReaders.set(s,u),l}async storesLoadCar(e,t,n){let s=e.toString(),o=this.carReaders.get(s);return o||(o=this.makeDecoderAndCarReader(e,t,n),this.carReaders.set(s,o)),o}async getMoreReaders(e){let t=Mc(5),n=e.filter(s=>!this.carReaders.has(s.toString()));await Promise.all(n.map(s=>t(()=>this.loadCar(s))))}};var bd={};K(bd,{BlockIvKeyIdCodec:()=>Hc,keyedCryptoFactory:()=>wd});ye();Rr();var uk={random:{calc:async(r,e,t)=>e.randomBytes(r.ivLength),verify:async(r,e,t,n)=>!0},hash:{calc:async(r,e,t)=>{let n=await Q.digest(t),s=new Uint8Array(n.bytes),o=new Uint8Array(r.ivLength);for(let i=0;i<s.length;i++)o[i%r.ivLength]^=s[i];return o},verify:async function(r,e,t,n){return r.url.getParam("ivverify")!=="disable"&&qh(t,await this.calc(r,e,n))}}};function fk(r,e){let t=e.ivCalc||r.getParam("ivhash")||"hash";return uk[t]||uk.hash}var Hc=class{constructor(e,t,n){this.code=3147065;this.name="Fireproof@encrypted-block:aes-gcm";this.ko=e,this.iv=t,this.opts=n||{}}async encode(e){let t=this.iv||await fk(this.ko.url,this.opts).calc(this.ko,this.ko.crypto,e),{iv:n}=this.ko.algo(t),s=await this.ko.fingerPrint(),o=J.decode(s);return this.ko.logger.Debug().Str("fp",s).Msg("encode"),hr({iv:n,keyId:o,data:await this.ko._encrypt({iv:n,bytes:e})})}async decode(e){let t;e instanceof Uint8Array?t=e:t=new Uint8Array(e);let{iv:n,keyId:s,data:o}=Tt(t),i=await this.ko.fingerPrint();if(this.ko.logger.Debug().Str("fp",J.encode(s)).Msg("decode"),J.encode(s)!==i)throw this.ko.logger.Error().Str("fp",i).Str("keyId",J.encode(s)).Msg("keyId mismatch").AsError();let a=await this.ko._decrypt({iv:n,bytes:o});if(!this.opts?.noIVVerify&&!await fk(this.ko.url,this.opts).verify(this.ko,this.ko.crypto,n,a))throw this.ko.logger.Error().Msg("iv missmatch").AsError();return a}},md=class{constructor(e,t,n,s){this.ivLength=12;this.isEncrypting=!0;this.logger=H(s,"keyedCrypto"),this.crypto=n,this.key=t,this.url=e}fingerPrint(){return Promise.resolve(this.key.fingerPrint)}codec(e,t){return new Hc(this,e,t)}algo(e){return{name:"AES-GCM",iv:e||this.crypto.randomBytes(this.ivLength),tagLength:128}}async _decrypt(e){return this.logger.Debug().Len(e.bytes,"bytes").Len(e.iv,"iv").Str("fp",this.key.fingerPrint).Msg("decrypting"),new Uint8Array(await this.crypto.decrypt(this.algo(e.iv),this.key.key,e.bytes))}async _encrypt(e){this.logger.Debug().Len(e.bytes).Str("fp",this.key.fingerPrint).Msg("encrypting");let t=this.algo(e.iv);return new Uint8Array(await this.crypto.encrypt(t,this.key.key,e.bytes))}},yd=class{constructor(){this.code=0;this.name="Fireproof@unencrypted-block"}encode(e){return e}decode(e){return e}},gd=class{constructor(e,t,n){this.ivLength=0;this.code=0;this.name="Fireproof@unencrypted-block";this.isEncrypting=!1;this._fingerPrint="noCrypto:"+Math.random();this.logger=H(n,"noCrypto"),this.crypto=t,this.url=e}fingerPrint(){return Promise.resolve(this._fingerPrint)}codec(e){return new yd}algo(e){return{name:"noCrypto",iv:new Uint8Array,tagLength:0}}_decrypt(){throw this.logger.Error().Msg("noCrypto.decrypt not implemented").AsError()}_encrypt(){throw this.logger.Error().Msg("noCrypto.decrypt not implemented").AsError()}};async function wd(r,e,t){let n=r.getParam("storekey");if(n&&n!=="insecure"){let s=await e.getNamedKey(n,!0);if(s.isErr())try{s=await e.toKeyWithFingerPrint(n)}catch(o){throw t.logger.Error().Err(o).Str("keybag",e.rt.id()).Str("name",n).Msg("getNamedKey failed").AsError()}return new md(r,s.Ok(),e.rt.crypto,t)}return new gd(r,e.rt.crypto,t)}ae();Rr();ye();function dk(r){let e=r.getParam("fragSize"),t=0;return e&&(t=parseInt(e)),(isNaN(t)||t<=0)&&(t=0),t}async function hk(r,e,t,n){if(!dk(r)){let f=await e.get(r);if(f.isErr())return[f];let p=f.unwrap();return[C.Ok({fid:new Uint8Array(0),ofs:0,len:p.length,data:p})]}let o=await e.get(r.build().setParam("ofs","0").URI());if(o.isErr())return[o];let i=Tt(o.unwrap()),a=i.data.length,c=[Promise.resolve(C.Ok(i))],l=J.encode(i.fid),u=r.build().setParam("fid",l).setParam("len",i.len.toString()).setParam("headerSize",t.toString());for(let f=a;f<i.len;f+=a)c.push((async(p,h)=>{let m=await e.get(p);if(m.isErr())return m;let d=Tt(m.unwrap());return J.encode(d.fid)!==l?C.Err(n.Error().Msg("Fragment fid mismatch").AsError()):d.ofs!==h?C.Err(n.Error().Uint64("ofs",h).Msg("Fragment ofs mismatch").AsError()):C.Ok(d)})(u.setParam("ofs",f.toString()).URI(),f));return Promise.all(c)}var pi=class{constructor(e,t){this.fidLength=4;this.headerSize=32;this.sthis=_r(e,"FragmentGateway"),this.logger=this.sthis.logger,this.innerGW=t}slicer(e,t){let n=dk(e);if(!n)return[this.innerGW.put(e,t)];let s=n-this.headerSize;if(s<=0)throw this.logger.Error().Uint64("fragSize",n).Uint64("headerSize",this.headerSize).Msg("Fragment size is too small").AsError();let o=[],i=this.sthis.nextId(this.fidLength),a=e.build().setParam("fid",i.str).setParam("len",t.length.toString()).setParam("headerSize",this.headerSize.toString());for(let c=0;c<t.length;c+=s){let l=hr({fid:i.bin,ofs:c,len:t.length,data:t.slice(c,c+s)});if(l.length>n)throw this.logger.Error().Uint64("block",l.length).Uint64("fragSize",n).Msg("Block size to big").AsError();o.push(this.innerGW.put(a.setParam("ofs",c.toString()).URI(),l))}return o}buildUrl(e,t){return this.innerGW.buildUrl(e,t)}async destroy(e){return this.innerGW.destroy(e)}async start(e){return this.headerSize=hr({fid:this.sthis.nextId(this.fidLength).bin,ofs:1024*1024,len:16*1024*1024,data:new Uint8Array(1024)}).length-1024,this.innerGW.start(e)}async close(e){return this.innerGW.close(e)}async put(e,t){return await Promise.all(this.slicer(e,t)),C.Ok(void 0)}async get(e){let t=await hk(e,this.innerGW,this.headerSize,this.logger),n;for(let s of t){if(s.isErr())return C.Err(s.Err());let o=s.Ok();n=n||new Uint8Array(o.len),n.set(o.data,o.ofs)}return C.Ok(n||new Uint8Array(0))}async subscribe(e,t){return this.innerGW.subscribe?this.innerGW.subscribe(e,t):C.Err(this.logger.Error().Url(e).Msg("subscribe not supported").AsError())}async delete(e){let t=await hk(e,this.innerGW,this.headerSize,this.logger);for(let n of t){if(n.isErr())return C.Err(n.Err());let s=n.Ok(),o=J.encode(s.fid),i=e.build().setParam("fid",o).setParam("len",s.len.toString()).setParam("headerSize",this.headerSize.toString()).URI();await this.innerGW.delete(i)}return C.Ok(void 0)}};ae();async function mi(r,e){let t=JSON.parse(r.txt.decode(e));return t.length?t.map?Promise.all(t.map(async n=>{let s=await zu(wc.decode(n.data)),o=kc(r.txt.decode(s.value.data.dbMeta));return{eventCid:s.cid,parents:n.parents,dbMeta:o}})):(r.logger.Debug().Str("crdtEntries",JSON.stringify(t)).Msg("No data in CRDT entries"),[]):(r.logger.Debug().Any("byteHeads",e).Msg("No CRDT entries found"),[])}async function pk(r,e,t){try{e.logger.Debug().Str("uri",r.toString()).Msg("Setting crypto key from gateway meta payload");let n=await mi(e,t);if(n.length){let s=n[0].dbMeta;if(s.key){let o=await Fe(e),i=yk(r),a=await o.setNamedKey(i,s.key);if(a.isErr())throw e.logger.Debug().Str("keyName",i).Str("dbMeta.key",s.key).Msg("Failed to set named key"),a.Err()}return e.logger.Debug().Str("dbMeta.key",s.key).Str("uri",r.toString()).Msg("Set crypto key from gateway meta payload"),C.Ok(s)}return e.logger.Debug().Any("data",t).Msg("No crypto in gateway meta payload"),C.Ok(void 0)}catch(n){return e.logger.Debug().Err(n).Msg("Failed to set crypto key from gateway meta payload"),C.Err(n)}}async function mk(r,e,t){try{e.logger.Debug().Str("uri",r.toString()).Msg("Adding crypto key to gateway meta payload");let n=yk(r),o=await(await Fe(e)).getNamedExtractableKey(n,!0);if(o.isErr())throw e.logger.Error().Str("keyName",n).Msg("Failed to get named extractable key"),o.Err();let i=await o.Ok().extract(),a=await mi(e,t),{dbMeta:c,parents:l}=a[0],u=l.map(h=>N.parse(h));c.key=i.keyStr;let f=await Promise.all([c].map(h=>xd(e,h,u))),p=await kd(e,f,u);return e.logger.Debug().Str("uri",r.toString()).Msg("Added crypto key to gateway meta payload"),C.Ok(p)}catch(n){return e.logger.Error().Err(n).Msg("Failed to add crypto key to gateway meta payload"),C.Err(n)}}function yk(r){let e=[r.getParam("localName")||r.getParam("name")],t=r.getParam("index");return t&&e.push(t),e.push("data"),`@${e.join(":")}@`}async function xd(r,e,t){return await jt.create({dbMeta:r.txt.encode(xc(e))},t)}async function kd(r,e,t){let n=e.map(s=>{let o=wc.encode(s.bytes);return{cid:s.cid.toString(),data:o,parents:t.map(i=>i.toString())}});return r.txt.encode(JSON.stringify(n))}var vk=mt(kk(),1);var DI=Object.prototype.toString,NI=r=>DI.call(r)==="[object Error]",MI=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function Sd(r){return r&&NI(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:MI.has(r.message):!1}var vd=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},Sk=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Ed(r,e){return new Promise((t,n)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let s=vk.default.operation(e),o=()=>{s.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",o),s.stop()};s.attempt(async a=>{try{let c=await r(a);i(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof vd)throw c.originalError;if(c instanceof TypeError&&!Sd(c))throw c;if(Sk(c,a,e),await e.shouldRetry(c)||(s.stop(),n(c)),await e.onFailedAttempt(c),!s.retry(c))throw s.mainError()}catch(l){Sk(l,a,e),i(),n(l)}}})})}async function yi(r,e,{concurrency:t=Number.POSITIVE_INFINITY,stopOnError:n=!0,signal:s}={}){return new Promise((o,i)=>{if(r[Symbol.iterator]===void 0&&r[Symbol.asyncIterator]===void 0)throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof r})`);if(typeof e!="function")throw new TypeError("Mapper function is required");if(!(Number.isSafeInteger(t)&&t>=1||t===Number.POSITIVE_INFINITY))throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${t}\` (${typeof t})`);let a=[],c=[],l=new Map,u=!1,f=!1,p=!1,h=0,m=0,d=r[Symbol.iterator]===void 0?r[Symbol.asyncIterator]():r[Symbol.iterator](),y=b=>{u=!0,f=!0,i(b)};s&&(s.aborted&&y(s.reason),s.addEventListener("abort",()=>{y(s.reason)}));let g=async()=>{if(f)return;let b=await d.next(),x=m;if(m++,b.done){if(p=!0,h===0&&!f){if(!n&&c.length>0){y(new AggregateError(c));return}if(f=!0,l.size===0){o(a);return}let k=[];for(let[S,T]of a.entries())l.get(S)!==Ek&&k.push(T);o(k)}return}h++,(async()=>{try{let k=await b.value;if(f)return;let S=await e(k,x);S===Ek&&l.set(x,S),a[x]=S,h--,await g()}catch(k){if(n)y(k);else{c.push(k),h--;try{await g()}catch(S){y(S)}}}})()};(async()=>{for(let b=0;b<t;b++){try{await g()}catch(x){y(x);break}if(p||u)break}})()})}var Ek=Symbol("skip");function OI(r){return r.hasParam("version")?C.Ok(r):C.Err(`missing version: ${r.toString()}`)}var gi=class{constructor(e,t,n,s,o){this._onStarted=[];this._onClosed=[];this.name=e,this._url=t,this.keybag=n.keybag,this.sthis=s,this.logger=o.With().Ref("url",()=>this._url.toString()).Str("name",e).Logger(),this.gateway=new pi(this.sthis,n.gateway),this.loader=n.loader}url(){return this._url}onStarted(e){this._onStarted.push(e)}onClosed(e){this._onClosed.push(e)}async ready(){}async keyedCrypto(){return wd(this._url,await this.keybag(),this.sthis)}async start(){this.logger.Debug().Str("storeType",this.storeType).Msg("starting-gateway-pre"),this._url=this._url.build().setParam("store",this.storeType).URI();let e=await this.gateway.start(this._url);if(e.isErr())return this.logger.Error().Result("gw-start",e).Msg("started-gateway"),e;this._url=e.Ok();let n=await(await this.keybag()).ensureKeyFromUrl(this._url,()=>{let o=this._url.getParam("index"),i=[this.name];return o&&i.push(o),i.push(this.storeType),i.join(":")});if(n.isErr())return n;this._url=n.Ok();let s=OI(this._url);if(s.isErr())return this.logger.Error().Result("version",s).Msg("guardVersion"),await this.close(),s;if(this.ready){let o=this.ready.bind(this),i=await We(o);if(i.isErr())return await this.close(),i}return this._onStarted.forEach(o=>o()),this.logger.Debug().Msg("started"),s}},As=class extends gi{constructor(t,n,s,o){super(n,s,{...o},t,H(t,"MetaStoreImpl"));this.storeType="meta";this.subscribers=new Map;this.parents=[];o.gateway.subscribe&&this.onStarted(async()=>{this.logger.Debug().Str("url",this.url().toString()).Msg("Subscribing to the gateway"),o.gateway.subscribe?.(this.url(),async i=>{this.logger.Debug().Msg("Received message from gateway");let a=await mi(this.sthis,i);await Promise.all(a.map(c=>this.loader?.taskManager?.handleEvent(c.eventCid,c.parents,c.dbMeta))),this.updateParentsFromDbMetas(a)})})}updateParentsFromDbMetas(t){let n=t.map(a=>a.eventCid),s=t.flatMap(a=>a.parents),o=new Map([...this.parents,...n].map(a=>[a.toString(),a])),i=new Set(s.map(a=>a.toString()));this.parents=Array.from(o.values()).filter(a=>!i.has(a.toString()))}async handleByteHeads(t){return await mi(this.sthis,t)}async load(){let t="main",n=await this.gateway.buildUrl(this.url(),t);if(n.isErr())throw this.logger.Error().Result("buildUrl",n).Str("branch",t).Msg("got error from gateway.buildUrl").AsError();let s=await this.gateway.get(n.Ok());if(s.isErr()){if(Mt(s))return;throw this.logger.Error().Url(n.Ok()).Result("bytes:",s).Msg("gateway get").AsError()}let o=await this.handleByteHeads(s.Ok());return await this.loader?.handleDbMetasFromStore(o.map(i=>i.dbMeta)),this.updateParentsFromDbMetas(o),o.map(i=>i.dbMeta)}async save(t,n){n=n||"main",this.logger.Debug().Str("branch",n).Any("meta",t).Msg("saving meta");let s=await xd(this.sthis,t,this.parents),o=await kd(this.sthis,[s],this.parents),i=await this.gateway.buildUrl(this.url(),n);if(i.isErr())throw this.logger.Error().Err(i.Err()).Str("branch",n).Msg("got error from gateway.buildUrl").AsError();this.parents=[s.cid];let a=await this.gateway.put(i.Ok(),o);if(a.isErr())throw this.logger.Error().Err(a.Err()).Msg("got error from gateway.put").AsError();return a}async close(){return await this.gateway.close(this.url()),this._onClosed.forEach(t=>t()),C.Ok(void 0)}async destroy(){return this.gateway.destroy(this.url())}},Is=class extends gi{constructor(t,n,s,o){super(n,s,{...o},t,H(t,"DataStoreImpl"));this.storeType="data"}async load(t){this.logger.Debug().Any("cid",t).Msg("loading");let n=await this.gateway.buildUrl(this.url(),t.toString());if(n.isErr())throw this.logger.Error().Err(n.Err()).Str("cid",t.toString()).Msg("got error from gateway.buildUrl").AsError();let s=await this.gateway.get(n.Ok());if(s.isErr())throw s.Err();return{cid:t,bytes:s.Ok()}}async save(t,n){this.logger.Debug().Any("cid",t.cid.toString()).Msg("saving");let s=await this.gateway.buildUrl(this.url(),t.cid.toString());if(s.isErr())throw this.logger.Error().Err(s.Err()).Ref("cid",t.cid).Msg("got error from gateway.buildUrl").AsError();let o=await this.gateway.put(s.Ok(),t.bytes);if(o.isErr())throw this.logger.Error().Err(o.Err()).Msg("got error from gateway.put").AsError();return o.Ok()}async remove(t){let n=await this.gateway.buildUrl(this.url(),t.toString());return n.isErr()?n:this.gateway.delete(n.Ok())}async close(){return await this.gateway.close(this.url()),this._onClosed.forEach(t=>t()),C.Ok(void 0)}destroy(){return this.gateway.destroy(this.url())}},jc=class extends gi{constructor(t,n,s){super(t.name,n,{...s},t.sthis,H(t.sthis,"WALStoreImpl"));this.storeType="wal";this._ready=new X;this.walState={operations:[],noLoaderOps:[],fileOperations:[]};this.processing=void 0;this.processQueue=new _s;this.loader=t}async ready(){return this._ready.once(async()=>{let t=await this.load().catch(n=>{this.logger.Error().Any("error",n).Msg("error loading wal")});t?(this.walState.operations=t.operations||[],this.walState.fileOperations=t.fileOperations||[]):(this.walState.operations=[],this.walState.fileOperations=[])})}async enqueue(t,n){await this.ready(),n.compact?(this.walState.operations=[],this.walState.noLoaderOps=[t]):n.noLoader?this.walState.noLoaderOps.push(t):this.walState.operations.push(t),await this.save(this.walState),n.noLoader||this.process()}async enqueueFile(t,n=!1){await this.ready(),this.walState.fileOperations.push({cid:t,public:n})}async process(){await this.ready(),this.loader.remoteCarStore&&await this.processQueue.enqueue(async()=>{try{await this._doProcess()}catch(t){this.logger.Error().Any("error",t).Msg("error processing wal")}(this.walState.operations.length||this.walState.fileOperations.length||this.walState.noLoaderOps.length)&&setTimeout(()=>void this.process(),0)})}async _doProcess(){if(!this.loader.remoteCarStore)return;let t=[...this.walState.operations],n=[...this.walState.noLoaderOps],s=[...this.walState.fileOperations];if(t.length+n.length+s.length===0)return;let o=3,i=(a,c)=>Ed(a,{retries:5,onFailedAttempt:l=>{this.logger.Warn().Msg(`Attempt ${l.attemptNumber} failed for ${c}. There are ${l.retriesLeft} retries left.`)}});try{if(await yi(n,async a=>{await i(async()=>{for(let c of a.cars){let l=await(await this.loader.carStore()).load(c);if(l)await me(this.loader.remoteCarStore).save(l);else if(zc(this.loader.carLog,a.cars))throw this.logger.Error().Ref("cid",c).Msg("missing local car").AsError()}this.walState.noLoaderOps=this.walState.noLoaderOps.filter(c=>c!==a)},`noLoaderOp with dbMeta.cars=${a.cars.toString()}`)},{concurrency:o}),await yi(t,async a=>{await i(async()=>{for(let c of a.cars){let l=await(await this.loader.carStore()).load(c);if(l)await me(this.loader.remoteCarStore).save(l);else if(zc(this.loader.carLog,a.cars))throw this.logger.Error().Ref("cid",c).Msg("missing local car").AsError()}this.walState.operations=this.walState.operations.filter(c=>c!==a)},`operation with dbMeta.cars=${a.cars.toString()}`)},{concurrency:o}),await yi(s,async({cid:a,public:c})=>{await i(async()=>{let l=await(await this.loader.fileStore()).load(a);if(!l)throw this.logger.Error().Ref("cid",a).Msg("missing file block").AsError();await this.loader.remoteFileStore?.save(l,{public:c}),this.walState.fileOperations=this.walState.fileOperations.filter(u=>u.cid!==a)},`fileOperation with cid=${a.toString()}`)},{concurrency:o}),t.length){let a=t[t.length-1];await i(async()=>{await this.loader.remoteMetaStore?.save(a)},`remoteMetaStore save with dbMeta.cars=${a.cars.toString()}`)}}catch(a){this.logger.Error().Any("error",a).Msg("Processing failed");return}finally{await this.save(this.walState)}}async load(){this.logger.Debug().Msg("loading");let t=await this.gateway.buildUrl(this.url(),"main");if(t.isErr())throw this.logger.Error().Err(t.Err()).Url(this.url()).Msg("error building url").AsError();let n=await this.gateway.get(t.Ok());if(n.isErr()){if(Mt(n))return;throw this.logger.Error().Err(n.Err()).Msg("error get").AsError()}try{return n&&kc(this.sthis.txt.decode(n.Ok()))}catch(s){throw this.logger.Error().Err(s).Msg("error parse").AsError()}}async save(t){let n=await this.gateway.buildUrl(this.url(),"main");if(n.isErr())throw this.logger.Error().Err(n.Err()).Url(this.url()).Msg("error building url").AsError();let s;try{s=xc(t)}catch(i){throw this.logger.Error().Err(i).Any("state",t).Msg("error format").AsError()}let o=await this.gateway.put(n.Ok(),this.sthis.txt.encode(s));if(o.isErr())throw this.logger.Error().Err(o.Err()).Str("filePath",n.Ok().toString()).Msg("error saving").AsError()}async close(){return await this.gateway.close(this.url()),this._onClosed.forEach(t=>t()),C.Ok(void 0)}destroy(){return this.gateway.destroy(this.url())}};ye();function $I(r,e){return e?r.build().setParam("index",e).URI():r.build().delParam("index").URI()}function Fd(r,e){return e.hasParam("name")?e:e.build().setParam("name",r).URI()}var on=new Map;function Ud(r,e){let t=e.ebOpts.store,n=Array.from(on.values()).find(i=>i.overrideBaseURL),s;return n&&n.overrideBaseURL&&(s=Ie.from(n.overrideBaseURL)),$I(Ie.from(r||s||Wh(e.sthis,e.name,t.stores?.base)),t.isIndex)}var KI=new _e;async function Lr(r,e){return KI.get(r.toString()).once(async()=>{let t=on.get(r.protocol);if(t){let n={gateway:await t.gateway(e),test:await t.test(e)},s=await n.gateway.start(r);if(s.isErr()){e.logger.Error().Result("start",s).Msg("start failed");return}return n}e.logger.Warn().Url(r).Msg("unsupported protocol")})}function $d(r){let e=r.protocol;if(e.endsWith(":")||(e+=":"),on.has(e)&&!r.overrideBaseURL&&on.get(e)!==r)throw new Error("we need a logger here");return r.overrideBaseURL&&Array.from(on.values()).forEach(t=>{t.overrideBaseURL=void 0}),on.set(e,r),()=>{on.delete(e)}}var zI=new _e;async function HI(r){let e=Fd(r.name,Ud(r.ebOpts.store.stores?.data,r)).build().setParam("store","data").URI(),t=_r(r.sthis,"dataStoreFactory",{url:e.toString()});return zI.get(e.toString()).once(async()=>{let n=await Lr(e,t);if(!n)throw t.logger.Error().Url(e).Msg("gateway not found").AsError();return new Is(t,r.name,e,{gateway:n.gateway,keybag:()=>Fe(r.sthis,{...r.ebOpts.keyBag})})})}var jI=new _e;async function VI(r){let e=Fd(r.name,Ud(r.ebOpts.store.stores?.meta,r)).build().setParam("store","meta").URI(),t=_r(r.sthis,"metaStoreFactory",{url:()=>e.toString()});return jI.get(e.toString()).once(async()=>{t.logger.Debug().Str("protocol",e.protocol).Msg("pre-protocol switch");let n=await Lr(e,t);if(!n)throw t.logger.Error().Url(e).Msg("gateway not found").AsError();return new As(r.sthis,r.name,e,{gateway:n.gateway,keybag:()=>Fe(r.sthis,{...r.ebOpts.keyBag})})})}var WI=new _e;async function qI(r){let e=Fd(r.name,Ud(r.ebOpts.store.stores?.wal,r)).build().setParam("store","wal").URI(),t=_r(r.sthis,"remoteWalFactory",{url:e.toString()});return WI.get(e.toString()).once(async()=>{let n=await Lr(e,t);if(!n)throw t.logger.Error().Url(e).Msg("gateway not found").AsError();return t.logger.Debug().Str("prepared",e.toString()).Msg("produced"),new jc(r,e,{gateway:n.gateway,keybag:()=>Fe(r.sthis,{...r.ebOpts.keyBag})})})}async function GI(r,e){e=_r(e,"testStoreFactory");let t=await Lr(r,e);if(!t)throw e.logger.Error().Url(r).Msg("gateway not found").AsError();return t.test}async function qc(r,e){let t=await r.start();if(t.isErr())throw e.Error().Result("start",t).Msg("start failed").AsError();return e.Debug().Url(t.Ok(),"prepared").Msg("produced"),r}function ed(r,e){let t=H(e,"toStoreRuntime",{});return{makeMetaStore:async n=>(t.Debug().Str("fromOpts",""+!!n.ebOpts.store.makeMetaStore).Msg("makeMetaStore"),qc(await(n.ebOpts.store.makeMetaStore||VI)(n),t)),makeDataStore:async n=>(t.Debug().Str("fromOpts",""+!!n.ebOpts.store.makeDataStore).Msg("makeDataStore"),qc(await(n.ebOpts.store.makeDataStore||HI)(n),t)),makeWALStore:async n=>(t.Debug().Str("fromOpts",""+!!n.ebOpts.store.makeWALStore).Msg("makeRemoteWAL"),qc(await(n.ebOpts.store.makeWALStore||qI)(n),t)),encodeFile:r.encodeFile||$h,decodeFile:r.decodeFile||Kh}}$d({protocol:"file:",gateway:async r=>{let{FileGateway:e}=await Promise.resolve().then(()=>(Cd(),Id));return new e(r)},test:async r=>{let{FileTestStore:e}=await Promise.resolve().then(()=>(Cd(),Id));return new e(r)}});$d({protocol:"indexdb:",gateway:async r=>{let{IndexDBGateway:e}=await Promise.resolve().then(()=>(Rd(),Od));return new e(r)},test:async r=>{let{IndexDBTestStore:e}=await Promise.resolve().then(()=>(Rd(),Od));return new e(r)}});async function Bk(r,e,t,n){let s=new Is(r,e,t,n);return await s.start(),s}async function Pk(r,e,t,n){let s=new As(r,e,t,n);return await s.start(),s}var Gc=class{constructor(e,t){this.loaded=Promise.resolve();this.logger=t,this.url=e}async refresh(){await me(me(this.loader).remoteMetaStore).load(),await(await me(this.loader).WALStore()).process()}async connect_X({loader:e}){if(!e)throw this.logger.Error().Msg("loader is required").AsError();await this.connectMeta_X({loader:e}),await this.connectStorage_X({loader:e})}async connectMeta_X({loader:e}){if(!e)throw this.logger.Error().Msg("connectMeta_X: loader is required").AsError();this.loader=e,await this.onConnect();let t=this.url.build().defParam("store","meta").URI(),n=await Lr(t,this.loader.sthis);if(!n)throw this.logger.Error().Url(t).Msg("connectMeta_X: gateway is required").AsError();let s=t.getParam("name");if(!s)throw this.logger.Error().Url(t).Msg("connectMeta_X: name is required").AsError();let o=await Pk(e.sthis,s,t,{gateway:n.gateway,keybag:()=>Fe(e.sthis,e.ebOpts.keyBag),loader:e});this.loader.remoteMetaStore=o,this.loaded=this.loader.ready().then(async()=>{o.load().then(async()=>{(await me(this.loader).WALStore()).process()})})}async connectStorage_X({loader:e}){if(!e)throw this.logger.Error().Msg("connectStorage_X: loader is required").AsError();this.loader=e;let t=this.url.build().defParam("store","data").URI(),n=await Lr(t,this.loader.sthis);if(!n)throw this.logger.Error().Url(t).Msg("connectStorage_X: gateway is required").AsError();let s=t.getParam("name");if(!s)throw this.logger.Error().Url(t).Msg("connectStorage_X: name is required").AsError;e.remoteCarStore=await Bk(e.sthis,s,this.url,{gateway:n.gateway,keybag:()=>Fe(e.sthis,this.loader?.ebOpts.keyBag)}),e.remoteFileStore=e.remoteCarStore}};function Dk(r,e){switch(typeof r){case"string":case"number":return r.toString();default:throw e.Error().Msg("Invalid key type").AsError()}}async function Rk(r,e,t,n,s){let o=null;if(n.length>1){let i=await Gg(e,t);for(let a of n){let c=await Nk(r,e,a,s);await i.put(Dk(a.id,s),c)}o=await i.commit()}else if(n.length===1){let i=await Nk(r,e,n[0],s);o=await Hg(e,t,Dk(n[0].id,s),i)}if(!o)throw s.Error().Uint64("updates.len",n.length).Msg("Missing result").AsError();if(o.event)for(let{cid:i,bytes:a}of[...o.additions,o.event])e.putSync(i,a);return{head:o.head}}async function Nk(r,e,t,n){let s;if(t.del)s={del:!0};else{if(!t.value)throw n.Error().Msg("Missing value").AsError();await JI(r,e,t.value,n),s={doc:t.value}}let o=await Qn({value:s,hasher:Q,codec:re});return e.putSync(o.cid,o.bytes),o.cid}async function JI(r,e,t,n){t._files&&await Mk(n,r,e,t._files),t._publicFiles&&await Mk(n,r,e,t._publicFiles)}async function Mk(r,e,t,n){let s=t.parent;if(!s.loader)throw r.Error().Msg("Missing loader, database name is required").AsError();let o=new et(s),i=[];for(let a in n)if(File===n[a].constructor){let c=n[a],{cid:l,blocks:u}=await e.encodeFile(c);i.push(a);for(let f of u)o.putSync(f.cid,f.bytes);n[a]={cid:l,type:c.type,size:c.size}}else{let{cid:c,type:l,size:u,car:f}=n[a];c&&l&&u&&f&&(n[a]={cid:c,type:l,size:u,car:f})}if(i.length){let a=await s.loader.commitFiles(o,{files:n});if(a)for(let c of i)n[c]={car:a,...n[c]}}}async function Fk(r,e,t,n){if(!e.length)throw n.Debug().Msg("Getting from an empty database").AsError();let s=await jg(r,e,t);if(!s)throw n.Error().Str("key",t).Msg("Missing key").AsError();return await jd(r,s,n)}function Hd(r,{doc:e}){e&&(e._files&&Ok(r,e._files),e._publicFiles&&Ok(r,e._publicFiles,!0))}function Ok(r,e,t=!1){for(let n in e){let s=e[n];s.cid&&(t&&(s.url=`https://${s.cid.toString()}.ipfs.w3s.link/`),s.car&&(s.file=async()=>await r.ebOpts.storeRuntime.decodeFile({get:async o=>await r.getFile(me(s.car),o)},s.cid,s))),e[n]=s}}async function jd(r,e,t){let n=await r.get(e);if(!n)throw t.Error().Str("link",e.toString()).Msg("Missing linked block").AsError();let{value:s}=await lr({bytes:n.bytes,hasher:Q,codec:re}),o={...s,cid:e};return Hd(r,o),o}var zd=class extends _t{constructor(e,t){super(t),this.logger=e}async get(e){try{return super.get(e)}catch(t){return this.logger.Error().Ref("link",e.toString()).Err(t).Msg("Missing event"),{value:void 0}}}};async function wi(r,e,t,n,s){let o=n.dirty?new zd(s,r):new _t(r);return{result:(await Uk(r,o,e,t,[],new Set,new Set,n.limit||1/0,s)).reverse(),head:e}}async function Uk(r,e,t,n,s=[],o,i,a,c){if(a<=0)return s;let l=t.map(u=>u.toString());for(let u of n)if(l.includes(u.toString()))return s;for(let u of t){if(i.has(u.toString()))continue;i.add(u.toString());let{value:f}=await e.get(u);if(!f)continue;let{type:p}=f.data,h=[];p==="batch"?h=f.data.ops:p==="put"&&(h=[f.data]);for(let m=h.length-1;m>=0;m--){let{key:d,value:y}=h[m];if(!o.has(d)){let g=await jd(r,y,c);s.push({id:d,value:g.doc,del:g.del,clock:u}),a--,o.add(d)}}f.parents&&(s=await Uk(r,e,f.parents,n,s,o,i,a,c))}return s}async function*Vd(r,e,t){for await(let[n,s]of Vg(r,e)){let o=await jd(r,s,t);yield{id:n,value:o.doc,del:o.del}}}async function*$k(r,e){for await(let t of Hu(r,e))yield t}var Kd=!1;async function Kk(r,e,t){if(Kd)return;Kd=!0;for(let s of e)if(!await r.get(s))throw t.Error().Ref("cid",s).Msg("Missing head block").AsError();for await(let s of Vd(r,e,t));for await(let s of Hu(r,e));let n=await yr(r,e);for(let{cid:s,bytes:o}of[...n.additions,...n.removals])r.loggedBlocks.putSync(s,o);await wi(r,e,[],{},t),Kd=!1}async function zk(r,e){let t=await r.get(Sa(e));if(!t)throw new Error(`Missing block ${e}`);let{cid:n,value:s}=await lr({bytes:t.bytes,codec:re,hasher:Q});return new ka({cid:n,value:s,bytes:t.bytes})}var dn=mt(Gk(),1);var Jk=r=>{let e=r.byteLength-4;return(r[e]|r[e+1]<<8|r[e+2]<<16)+r[e+3]*16777216};var qd=r=>{let e=Math.floor(4294967295/r);return async t=>{let n=await t.identity();if(typeof n!="number")throw new Error("Identity must be a number");return n<=e}};var cn=(r,e)=>r===e?0:r>e?1:-1;var an=class{constructor(){this._cids=new Set}add(e){if(!e.address)throw new Error("Cannot add node without address");if(e.address.then){let t=e.address.then(n=>this._cids.add(n.toString()));this._cids.add(t),t.then(()=>this._cids.delete(t))}else this._cids.add(e.address.toString())}async all(){return await Promise.all([...this._cids]),this._cids}};var Qc=class{constructor({key:e,address:t},n={}){this.key=e,this.address=t,this.codec=n.codec,this.hasher=n.hasher}get isEntry(){return!0}},Cs=class{constructor({entries:e,closed:t}){if(typeof t!="boolean")throw new Error('Missing required argument "closed"');this.entries=e,this.closed=t,this.startKey=e[0].key}find(e,t){let{entries:n}=this;for(let s=n.length-1;s>-1;s--){let o=n[s];if(t(e,o.key)>-1)return[s,o]}return null}findMany(e,t,n=!1,s=!1){let{entries:o}=this,i=new Map;n?e=[...e]:e=e.sort(t);for(let a=o.length-1;a>-1&&e.length;a--){let c=o[a],l=[];for(;e.length;){let u=e[e.length-1];u=u.key?u.key:u;let f=t(u,c.key);if(s)if(f===0)l.push(e.pop());else if(f>0)e.pop();else break;else if(f>-1)l.push(e.pop());else break}l.length&&i.set(a,[c,l])}return i}findRange(e,t,n){let{entries:s}=this,o,i=0;for(let a=s.length-1;a>-1;a--){let c=s[a];if(n(t,c.key)>0){o=a;break}}for(let a=0;a<s.length;a++){let c=s[a],l=n(e,c.key);if(l===0){i=a;break}else if(l<0)break;i=a}return{first:i,last:o,entries:s.slice(i,o+1)}}},Qk=r=>typeof r=="string"?r:JSON.stringify(r);function nC(r,e){return r.sort(({key:t},{key:n})=>e.compare(t,n))}async function sC(r,e,t){let n=[];for(let s of e){let{key:o,del:i}=s;if(t(o,r)<0)i||n.push(s);else break}return n}async function oC(r,e,{chunker:t,compare:n}){return await Br.from({entries:r.map(s=>new e.LeafEntryClass(s,e)).sort((s,o)=>n(s.key,o.key)),chunker:t,NodeClass:e.LeafClass,distance:0,opts:e})}async function iC(r,e,t,n){return await Promise.all(e.map(async s=>{let o=await s.encode();return t.blocks.push({block:o,node:s}),r.cache.set(s),new n.BranchEntryClass({key:s.key,address:await s.address},n)}))}async function aC(r,e,t,n){let s=e.root;e.blocks.push({block:await s.encode(),node:s}),r.cache.set(s);let o=n.opts,i=s.distance,a=s.entryList.startKey,c=await sC(a,t,r.compare);if(c.length){let l=await oC(c,o,r),u=await iC(r,l,e,o),p=[new o.BranchEntryClass({key:s.entryList.startKey,address:await s.address},o),...u].sort(({key:d},{key:y})=>o.compare(d,y)),h=await Br.from({...n,entries:p,chunker:r.chunker,NodeClass:o.BranchClass,distance:i+1}),m=[...h];for(;h.length>1;){let d=await Promise.all(h.map(async y=>new o.BranchEntryClass({key:y.key,address:await y.address},o)));h=await Br.from({...n,entries:d.sort(({key:y},{key:g})=>o.compare(y,g)),chunker:r.chunker,NodeClass:o.BranchClass,distance:i+1}),m=[...m,...h]}await Promise.all(m.map(async d=>{let y=await d.encode();r.cache.set(d),e.blocks.push({block:y,node:d})})),e.root=h[0],e.nodes=[...e.nodes,...m]}}var Br=class r{constructor({entryList:e,chunker:t,distance:n,getNode:s,compare:o,cache:i}){this.entryList=e,this.chunker=t,this.distance=n,this.getNode=s,this.compare=o,this.cache=i}get closed(){return this.entryList.closed}get key(){return this.entryList.startKey}async getEntry(e,t=new an){return{result:await this._getEntry(e,t),cids:t}}async _getEntry(e,t){t.add(this);let n=this;for(;!n.isLeaf;){let i=n.entryList.find(e,this.compare);if(i===null)throw new Error("Not found");let[,a]=i;n=await this.getNode(await a.address),t.add(n)}let s=n.entryList.find(e,this.compare);if(s===null||s[1].key.toString()!==e.toString())throw new Error("Not found");let[,o]=s;return o}async getAllEntries(e=new an){return{result:await this._getAllEntries(e),cids:e}}_getAllEntries(e){if(e.add(this),this.isLeaf)return this.entryList.entries;{let{entries:t}=this.entryList,n=async s=>this.getNode(await s.address).then(o=>o._getAllEntries(e)).catch(async o=>{throw o});return Promise.all(t.map(n)).then(s=>s.flat())}}async*vis(e=new Set){let t=async o=>o.isLeaf?`Leaf [${o.entryList.entries.map(a=>`[${a.key},${JSON.stringify(a.value).replace(/"/g,"'")}]`).join(", ")}]`:`Branch [${o.entryList.entries.map(a=>`[${a.key}]`).join(", ")}]`,n=o=>o.toString().slice(0,4)+o.toString().slice(-4),s=async function*(o,i,a){let c=await o.address;if(!a.has(c)){a.add(c);let l=await t(o);yield` node [shape=ellipse fontname="Courier"]; ${n(c)} [label="${l}"];`,yield` ${n(i)} -> ${n(c)};`;for(let u of o.entryList.entries)if(u.address){let f=await u.address;try{let p=await o.getNode(f);yield*await s(p,c,a)}catch(p){yield` ${n(c)} -> ${n(f)};`,yield` node [shape=ellipse fontname="Courier"]; ${n(f)} [label="Error: ${p.message}"];`}}}};yield"digraph tree {",yield' node [shape=ellipse fontname="Courier"]; rootnode;';for await(let o of s(this,"rootnode",e))yield o;yield"}"}async getEntries(e,t=!1,n=new an){return{result:await this._getEntries(e,t,n),cids:n}}async _getEntries(e,t,n){n.add(this),t||(e=e.sort(this.compare));let s=this.entryList.findMany(e,this.compare,!0,this.isLeaf);if(this.isLeaf)return[...s.values()].map(([i])=>i);let o=[];for(let[i,a]of[...s.values()].reverse()){let c=this.getNode(await i.address);o.push(c.then(l=>l._getEntries(a.reverse(),!0,n)))}return o=await Promise.all(o),o.flat()}async getRangeEntries(e,t,n=new an){return{result:await this._getRangeEntries(e,t,n),cids:n}}_getRangeEntries(e,t,n){n.add(this);let{entries:s}=this.entryList.findRange(e,t,this.compare);if(this.isLeaf)return s.filter(c=>{let l=this.compare(e,c.key),u=this.compare(t,c.key);return l<=0&&u>=0});if(!s.length)return[];let o=async c=>this.getNode(await c.address).then(l=>l._getRangeEntries(e,t,n)),i=[o(s.shift())];if(!s.length)return i[0];let a=o(s.pop());for(;s.length;){let c=async l=>this.getNode(await l.address).then(async u=>u._getAllEntries(n));i.push(c(s.shift()))}return i.push(a),Promise.all(i).then(c=>c.flat())}async transaction(e,t={}){t={codec:this.codec,hasher:this.hasher,getNode:this.getNode,compare:this.compare,cache:this.cache,...t};let n={chunker:this.chunker,opts:t},s=this.entryList.findMany(e,t.compare,!0,this.isLeaf);return this.isLeaf?await this.transactionLeaf(e,t,n,s):await this.transactionBranch(e,t,n,s)}async transactionLeaf(e,t,n,s){let{LeafClass:o,LeafEntryClass:i}=t,{entries:a,previous:c}=this.processLeafEntries(e,s,i,t),l={...n,entries:a,NodeClass:o,distance:0},u=await r.from(l);return{nodes:u,previous:c,blocks:await Promise.all(u.map(async f=>{let p=await f.encode();return this.cache.set(f),{block:p,node:f}})),distance:0}}processLeafEntries(e,t,n,s){let o=[],i=[],a={},c=new Map;for(let{key:f,del:p,value:h}of e){let m=Qk(f);p?typeof a[m]>"u"&&c.set(m,null):(a[m]={key:f,value:h},c.delete(m))}i=[...this.entryList.entries];for(let[f,[p]]of t){o.push(p);let h=Qk(p.key);c.has(h)?c.set(h,f):(i[f]=new n(a[h],s),delete a[h])}let l=0;for(let[,f]of c)f!==null&&i.splice(f-l++,1);let u=Object.values(a).map(f=>new n(f,s));return i=i.concat(u).sort(({key:f},{key:p})=>s.compare(f,p)),{entries:i,previous:o}}async transactionBranch(e,t,n,s){let{BranchClass:o,BranchEntryClass:i}=t,a=0;for(let[m,[d,y]]of s){let g=this.getNode(await d.address).then(b=>b.transaction(y.reverse(),{...t,sorted:!0})).then(b=>({entry:d,keys:y,distance:a,...b}));s.set(m,g)}let c=[...this.entryList.entries],l={previous:[],blocks:[],nodes:[]};for(let[m,d]of s){let{nodes:y,previous:g,blocks:b,distance:x}=await d;a=x,c[m]=y,g.length&&(l.previous=l.previous.concat(g)),b.length&&(l.blocks=l.blocks.concat(b)),y.length&&(l.nodes=l.nodes.concat(y))}c=c.flat();let u=await this.handlePrepend(c,t,n,l,a);a++;let f=async m=>{if(m.isEntry)return m;let d=await m.encode();return l.blocks.push({block:d,node:m}),this.cache.set(m),new i(m,t)};c=await Promise.all(u.map(f));let p={...n,entries:c,NodeClass:o,distance:a},h=await r.from(p);return await Promise.all(h.map(async m=>{let d=await m.encode();l.blocks.push({block:d,node:m}),this.cache.set(m)})),l.nodes=h,{...l,distance:a}}async handlePrepend(e,t,n,s,o){let{BranchClass:i,LeafClass:a}=t,c=[],l=null;for(let u of e)if(l){let f=await this.mergeFirstLeftEntries(u,l,n,s,o);l=null;let p=f[0].address?i:a,h={...n,entries:f.sort(({key:d},{key:y})=>t.compare(d,y)),NodeClass:p,distance:o},m=await r.from(h);m[m.length-1].closed||(l=m.pop()),m.length&&(c=c.concat(m))}else!u.isEntry&&!u.closed?l=u:c.push(u);return l&&c.push(l),c}async getNodeFirstFromBlocks(e,t){for(let{block:n,node:s}of e)if(await n.cid===t)return s;return await this.getNode(t)}async mergeFirstLeftEntries(e,t,n,s,o){let i=n.opts,{LeafClass:a,BranchClass:c,BranchEntryClass:l}=i;if(e.isEntry){let h=await e.address;e=await this.getNodeFirstFromBlocks(s.blocks,h)}let u=e.entryList.entries;if(!u.length)throw new Error("unreachable no entries");let f=(h,m)=>h.concat(m),p=async(h,m,d)=>await Promise.all(h.map(async y=>(m.blocks.push({block:await y.encode(),node:y}),this.cache.set(y),new l({key:y.key,address:await y.address},d))));if(u[0].constructor.name===t.entryList.entries[0].constructor.name)return await f(t.entryList.entries,u);{let h=u.shift();if(!h)throw new Error("unreachable no left entry");if(!h.address)throw new Error("unreachable existing leaf, no leftEntry.address");let m=await this.mergeFirstLeftEntries(h,t,n,s,o-1),d=u.shift();if(!d)return m;if(!d.address)throw new Error("unreachable existing leaf, no esf.address");let y=await this.getNodeFirstFromBlocks(s.blocks,await d.address);if(y.entryList.entries[0].address){if(m[0].address)return m.concat(y.entryList.entries);{let g=await r.from({...n,entries:m.sort(({key:S},{key:T})=>i.compare(S,T)),NodeClass:a,distance:o}),b=await p(g,s,i),x=await r.from({...n,entries:[...y.entryList.entries,...b,...u].sort(({key:S},{key:T})=>i.compare(S,T)),NodeClass:c,distance:o});return await p(x,s,i)}}else{let g=await f(m,y.entryList.entries),b=await r.from({...n,entries:g.sort(({key:k},{key:S})=>i.compare(k,S)),NodeClass:a,distance:o}),x=await p(b,s,i);return await f(x,u)}}}async bulk(e,t={},n=!0){let{BranchClass:s}=t;t={codec:this.codec,hasher:this.hasher,getNode:this.getNode,compare:this.compare,cache:this.cache,...t},t.sorted||(e=nC(e,t),t.sorted=!0);let o={chunker:this.chunker,opts:t},i=await this.transaction(e,t);for(;i.nodes.length>1;){let a=i.nodes[0].distance+1,c=await Promise.all(i.nodes.map(async u=>{let f=await u.encode();return i.blocks.push({block:f,node:u}),this.cache.set(u),new t.BranchEntryClass(u,t)})),l=await r.from({...o,entries:c,NodeClass:s,distance:a});await Promise.all(l.map(async u=>{let f=await u.encode();this.cache.set(u),i.blocks.push({block:f,node:u})})),i.nodes=l}return i.root=i.nodes[0],n&&i.root&&await aC(this,i,e,o),i.blocks=i.blocks.map(({block:a})=>a),i}static async from({entries:e,chunker:t,NodeClass:n,distance:s,opts:o}){if(!e.every(c=>c.constructor.name===e[0].constructor.name))throw new Error("all entries must be of the same type");let i=[],a=[];for(let c of e)a.push(c),await t(c,s)&&(i.push(new Cs({entries:a,closed:!0})),a=[]);return a.length&&i.push(new Cs({entries:a,closed:!1})),i.map(c=>new n({entryList:c,chunker:t,distance:s,...o}))}},Yc=class extends Br{constructor({codec:e,hasher:t,block:n,...s}){super(s),this.codec=e,this.hasher=t,n?(this.block=n,this.address=n.cid):(this.block=this.encode(),this.address=this.block.then(o=>o.cid))}async get(e){let{result:t,cids:n}=await this.getEntry(e);return{result:t.key,cids:n}}async encode(){if(this.block)return this.block;let e=await this.encodeNode(),t={codec:this.codec,hasher:this.hasher,value:e};return this.block=await Jn(t),this.block}},Xc=class extends Yc{async encodeNode(){let{entries:e}=this.entryList,t=async s=>{if(!s.address)throw new Error("entry.address required");return[s.key,await s.address]},n=await Promise.all(e.map(t));return{branch:[this.distance,n],closed:this.closed}}get isBranch(){return!0}},Zc=class extends Yc{async encodeNode(){return{leaf:await Promise.all(this.entryList.entries.map(async t=>await t.encodeNode())),closed:this.closed}}get isLeaf(){return!0}},Yk=async function*(r){let{LeafClass:e,LeafEntryClass:t,BranchClass:n,BranchEntryClass:s,list:o,chunker:i,compare:a,...c}=r;o=o.map(f=>new t(f,c)),c.compare=a;let l=await Br.from({entries:o,chunker:i,NodeClass:e,distance:0,opts:c});yield*l;let u=1;for(;l.length>1;){let f=async h=>new s({key:h.key,address:await h.address},c),p=await Promise.all(l.map(f));l=await Br.from({entries:p,chunker:i,NodeClass:n,distance:u,opts:c}),yield*l,u++}};var el=class extends Qc{async identity(){let e=await this.codec.encode(await this.encodeNode()),t=await this.hasher.encode(e);return Jk(t)}},ln=class extends el{constructor(e,t){super(e,t),this.value=e.value}encodeNode(){return[this.key,this.value]}},un=class extends el{constructor(e,t){if(!e.address)throw new Error("Cannot create MapBranchEntry without address");super(e,t)}async encodeNode(){return[this.key,await this.address]}},Xk=async(r,e)=>{let{result:t,cids:n}=await r.getEntry(e);return{result:t.value,cids:n}},Zk=async(r,e)=>{let{result:t,cids:n}=await r.getEntries(e);return{result:t.map(s=>s.value),cids:n}},fn=class extends Zc{get(e){return Xk(this,e)}getMany(e){return Zk(this,e)}bulk(e,t={},n=!0){return super.bulk(e,{...eS,...t},n)}},hn=class extends Xc{get(e){return Xk(this,e)}getMany(e){return Zk(this,e)}bulk(e,t={},n=!0){return super.bulk(e,{...eS,...t},n)}},eS={LeafClass:fn,LeafEntryClass:ln,BranchClass:hn,BranchEntryClass:un},tS=(r,e,t,n,s,o,i)=>{let a=i.LeafClass||fn,c=i.LeafEntryClass||ln,l=i.BranchClass||hn,u=i.BranchEntryClass||un,f=async h=>e.has(h)?e.get(h):r(h).then(m=>p(m)),p=cC({chunker:t,cache:e,getNode:f,codec:n,hasher:s,compare:o,LeafEntryClass:c,LeafClass:a,BranchEntryClass:u,BranchClass:l});return f},rS=({get:r,cache:e,chunker:t,list:n,codec:s,hasher:o,sorted:i,compare:a,...c})=>{i||(n=n.sort(({key:f},{key:p})=>a(f,p)));let l=tS(r,e,t,s,o,a,c),u={list:n,codec:s,hasher:o,chunker:t,getNode:l,sorted:i,compare:a,cache:e,LeafClass:c.LeafClass||fn,LeafEntryClass:c.LeafEntryClass||ln,BranchClass:c.BranchClass||hn,BranchEntryClass:c.BranchEntryClass||un};return Yk(u)},nS=({cid:r,get:e,cache:t,chunker:n,codec:s,hasher:o,compare:i,...a})=>tS(e,t,n,s,o,i,a)(r);function cC({chunker:r,cache:e,getNode:t,codec:n,hasher:s,compare:o,LeafEntryClass:i,LeafClass:a,BranchEntryClass:c,BranchClass:l}){let u={codec:n,hasher:s};return f=>{let{value:p}=f,h={chunker:r,cache:e,block:f,getNode:t,codec:n,hasher:s,compare:o},m,d;if(p.leaf)m=p.leaf.map(([b,x])=>new i({key:b,value:x},u)),d=a;else if(p.branch){let[b,x]=p.branch;h.distance=b,m=x.map(([k,S])=>new c({key:k,address:S},u)),d=l}else throw new Error("Unknown block data, does not match schema");let y=new Cs({entries:m,closed:p.closed}),g=new d({entryList:y,...h});return e.set(g),g}}var lC=(r,e)=>{let[t,n]=r,[s,o]=e,i=cn(t,s);return i!==0?i:uC(n,o)},uC=(r,e)=>{if(Number.isNaN(r))return-1;if(Number.isNaN(e))throw new Error("ref may not be Infinity or NaN");return Number.isFinite(r)?cn(r,e):1},sS=async(r,e)=>{let t=[e,NaN],n=[e,1/0],{result:s,cids:o}=await r.getRangeEntries(t,n);return{result:s.map(i=>{let[a,c]=i.key;return{id:c,key:a,row:i.value}}),cids:o}},oS=async(r,e,t)=>{e=[e,NaN],t=[t,1/0];let{result:n,cids:s}=await r.getRangeEntries(e,t);return{result:n.map(i=>{let[a,c]=i.key;return{id:c,key:a,row:i.value}}),cids:s}},Gd=class extends fn{get(e){return sS(this,e)}range(e,t){return oS(this,e,t)}bulk(e,t={},n=!0){return super.bulk(e,{...Qd,...t},n)}},Jd=class extends hn{get(e){return sS(this,e)}range(e,t){return oS(this,e,t)}bulk(e,t={},n=!0){return super.bulk(e,{...Qd,...t},n)}},fC=Gd,hC=Jd,Qd={LeafClass:fC,BranchClass:hC,LeafEntryClass:ln,BranchEntryClass:un},iS={...Qd,compare:lC},aS=r=>(r={...iS,...r},rS(r)),Yd=r=>(r={...iS,...r},nS(r));var Xd={has:()=>!1,get:()=>{throw new Error("Cannot ask for entries from nocache")},set:()=>{}};var pn=class{};function pC(r,e){if(Number.isNaN(r))return-1;if(Number.isNaN(e))throw new Error("ref may not be Infinity or NaN");return r===1/0?1:cn(r,e)}function mC(r,e){let[t,n]=r,[s,o]=e,i=cn(t,s);return i!==0?i:pC(n,o)}var ep={cache:Xd,chunker:qd(30),codec:re,hasher:Q,compare:mC},tp={cache:Xd,chunker:qd(30),codec:re,hasher:Q,compare:cn};function cS(r,e){let t=[];return r.forEach(({id:n,value:s,del:o})=>{if(o||!s)return;let i=!1,a=e({...s,_id:n},(c,l)=>{i=!0,!(typeof c>"u")&&t.push({key:[dn.default.encode(c),n],value:l||null})});!i&&a&&t.push({key:[dn.default.encode(a),n],value:null})}),t}function Zd(r){return async e=>{let t=await r.get(e);if(!t)throw new Error(`Missing block ${e.toString()}`);let{cid:n,bytes:s}=t;return Iu({cid:n,bytes:s,hasher:Q,codec:re})}}async function rp(r,e,t,n){if(!t.length)return e;if(!e.root)if(e.cid)e.root=await Yd({cid:e.cid,get:Zd(r),...n});else{let i,a;for await(let c of await aS({get:Zd(r),list:t,...n})){let l=await c.block;await r.put(l.cid,l.bytes),i=l,a=c}if(!a||!i)throw new Error("failed to create index");return{root:a,cid:i.cid}}let{root:s,blocks:o}=await e.root.bulk(t);if(s){for await(let i of o)await r.put(i.cid,i.bytes);return{root:s,cid:(await s.block).cid}}else return{root:void 0,cid:void 0}}async function np(r,e,t){return await Yd({cid:e,get:Zd(r),...t})}async function mn(r,e,t){return t.descending&&(e.result=e.result.reverse()),t.limit&&(e.result=e.result.slice(0,t.limit)),t.includeDocs&&(e.result=await Promise.all(e.result.map(async n=>{let s=await r.get(n.id),o=s?{...s.doc,_id:n.id}:void 0;return{...n,doc:o}}))),{rows:e.result.map(({key:n,...s})=>({key:dn.default.decode(n),...s}))}}function sp(r){return[dn.default.encode(r[0]),dn.default.encode(r[1])]}function op(r){return dn.default.encode(r)}ye();function Ls(r,{_crdt:e},t,n,s){if(n&&s)throw e.logger.Error().Msg("cannot provide both mapFn and meta").AsError();if(n&&n.constructor.name!=="Function")throw e.logger.Error().Msg("mapFn must be a function").AsError();if(e.indexers.has(t))e.indexers.get(t).applyMapFn(t,n,s);else{let o=new tl(r,e,t,n,s);e.indexers.set(t,o)}return e.indexers.get(t)}var tl=class{constructor(e,t,n,s,o){this.mapFnString="";this.byKey=new pn;this.byId=new pn;this.includeDocsDefault=!1;if(this.logger=H(e,"Index"),this.blockstore=t.indexBlockstore,this.crdt=t,this.applyMapFn(n,s,o),this.name=n,!(this.mapFnString||this.initError))throw this.logger.Error().Msg("missing mapFnString").AsError()}ready(){return Promise.all([this.blockstore.ready(),this.crdt.ready()]).then(()=>{})}close(){return Promise.all([this.blockstore.close(),this.crdt.close()]).then(()=>{})}destroy(){return Promise.all([this.blockstore.destroy(),this.crdt.destroy()]).then(()=>{})}applyMapFn(e,t,n){if(t&&n)throw this.logger.Error().Msg("cannot provide both mapFn and meta").AsError();if(this.name&&this.name!==e)throw this.logger.Error().Msg("cannot change name").AsError();this.name=e;try{if(n){if(this.indexHead&&this.indexHead.map(o=>o.toString()).join()!==n.head.map(o=>o.toString()).join())throw this.logger.Error().Msg("cannot apply different head meta").AsError();this.mapFnString?this.mapFnString!==n.map?this.logger.Warn().Msg(`cannot apply different mapFn meta: old mapFnString ${this.mapFnString} new mapFnString ${n.map}`):(this.byId.cid=n.byId,this.byKey.cid=n.byKey,this.indexHead=n.head):(this.mapFnString=n.map,this.byId.cid=n.byId,this.byKey.cid=n.byKey,this.indexHead=n.head)}else if(this.mapFn){if(t&&this.mapFn.toString()!==t.toString())throw this.logger.Error().Msg("cannot apply different mapFn app2").AsError()}else{if(t||(t=o=>o[e]??void 0),this.mapFnString){if(this.mapFnString!==t.toString())throw this.logger.Error().Str("mapFnString",this.mapFnString).Str("mapFn",t.toString()).Msg("cannot apply different mapFn app").AsError()}else this.mapFnString=t.toString();this.mapFn=t}let s=/=>\s*(.*)/.test(this.mapFnString);this.includeDocsDefault=s}catch(s){this.initError=s}}async query(e={}){if(await this.ready(),await this._updateIndex(),await this._hydrateIndex(),!this.byKey.root)return await mn(this.crdt,{result:[]},e);if(this.includeDocsDefault&&e.includeDocs===void 0&&(e.includeDocs=!0),e.range){let n=sp(e.range);return await mn(this.crdt,await me(this.byKey.root).range(n[0],n[1]),e)}if(e.key){let n=op(e.key);return await mn(this.crdt,await me(this.byKey.root).get(n),e)}if(Array.isArray(e.keys))return{rows:(await Promise.all(e.keys.map(async s=>{let o=op(s);return(await mn(this.crdt,await me(this.byKey.root).get(o),e)).rows}))).flat()};if(e.prefix){Array.isArray(e.prefix)||(e.prefix=[e.prefix]);let n=[...e.prefix,NaN],s=[...e.prefix,1/0],o=sp([n,s]);return await mn(this.crdt,await this.byKey.root.range(...o),e)}let t=await this.byKey.root.getAllEntries();return await mn(this.crdt,{result:t.result.map(({key:[n,s],value:o})=>({key:n,id:s,value:o}))},e)}_resetIndex(){this.byId=new pn,this.byKey=new pn,this.indexHead=void 0}async _hydrateIndex(){this.byId.root&&this.byKey.root||!this.byId.cid||!this.byKey.cid||(this.byId.root=await np(this.blockstore,this.byId.cid,tp),this.byKey.root=await np(this.blockstore,this.byKey.cid,ep))}async _updateIndex(){if(await this.ready(),this.initError)throw this.initError;if(!this.mapFn)throw this.logger.Error().Msg("No map function defined").AsError();let e,t;!this.indexHead||this.indexHead.length===0?{result:e,head:t}=await this.crdt.allDocs():{result:e,head:t}=await this.crdt.changes(this.indexHead),e.length===0&&(this.indexHead=t);let n=[],s=[];if(this.byId.root){let l=e.map(({id:f})=>f),{result:u}=await this.byId.root.getMany(l);n=u.map(f=>({key:f,del:!0})),s=u.map(f=>({key:f[1],del:!0}))}let o=cS(e,this.mapFn),i=o.map(({key:l})=>({key:l[1],value:l})),a={indexes:new Map};for(let[l,u]of this.crdt.indexers)u.indexHead&&a.indexes?.set(l,{byId:u.byId.cid,byKey:u.byKey.cid,head:u.indexHead,map:u.mapFnString,name:u.name});if(e.length===0)return a;let{meta:c}=await this.blockstore.transaction(async l=>{if(this.byId=await rp(l,this.byId,s.concat(i),tp),this.byKey=await rp(l,this.byKey,n.concat(o),ep),this.indexHead=t,this.byId.cid&&this.byKey.cid){let u={byId:this.byId.cid,byKey:this.byKey.cid,head:t,map:this.mapFnString,name:this.name};a.indexes?.set(this.name,u)}return a});return c}};ae();function lS(r,e){let t=[],n=!1;async function*s(){if(n||t.length===0)return;n=!0;let o=[];try{for(;t.length>0;){t.sort((a,c)=>c.updates?1:-1);let i=t.shift();if(i&&(await r(i.newHead,i.prevHead,i.updates!==void 0).catch(a=>{throw e.Error().Err(a).Msg("int_applyHead worker error").AsError()}),i.updates&&o.push(...i.updates),!t.some(a=>a.updates)||i.updates)){let a=t.every(c=>c.updates!==null);yield{updates:o,all:a},o.length=0}}}finally{n=!1;let i=s(),a=await i.next();for(;!a.done;)a=await i.next()}}return{push(o){return t.push(o),s()},size(){return t.length}}}ye();var rl=class{constructor(e){this.head=[];this.zoomers=new Set;this.watchers=new Set;this.emptyWatchers=new Set;this._ready=new X;this.blockstore=e,this.logger=H(e.sthis,"CRDTClock"),this.applyHeadQueue=lS(this.int_applyHead.bind(this),this.logger)}async ready(){return this._ready.once(async()=>{await this.blockstore.ready()})}async close(){await this.blockstore.close()}setHead(e){this.head=e}async applyHead(e,t,n){for await(let{updates:s,all:o}of this.applyHeadQueue.push({newHead:e,prevHead:t,updates:n}))return this.processUpdates(s,o,t)}async processUpdates(e,t,n){let s=e;this.watchers.size&&!t&&(s=(await wi(me(this.blockstore),this.head,n,{},this.logger)).result),this.zoomers.forEach(o=>o()),this.notifyWatchers(s||[])}notifyWatchers(e){this.emptyWatchers.forEach(t=>t()),this.watchers.forEach(t=>t(e||[]))}onTick(e){this.watchers.add(e)}onTock(e){this.emptyWatchers.add(e)}onZoom(e){this.zoomers.add(e)}async int_applyHead(e,t,n){let s=!n,o=ip(this.head);if(e=ip(e),uS(o,e))return;let i=ip(t);if(uS(o,i)){this.setHead(e);return}if(!this.blockstore)throw this.logger.Error().Msg("missing blockstore").AsError();await yC(this.logger,e,this.blockstore),this.transaction||(this.transaction=this.blockstore.openTransaction({noLoader:s,add:!1}));let a=this.transaction,c=await gC(this.logger,e,a,this.head),l=await yr(a,c);for(let{cid:u,bytes:f}of[...l.additions])a.putSync(u,f);s||(await this.blockstore.commitTransaction(a,{head:c},{add:!1,noLoader:s}),this.transaction=void 0),this.setHead(c)}};function ip(r){return r.sort((e,t)=>e.toString().localeCompare(t.toString()))}async function yC(r,e,t){if(!t)throw r.Error().Msg("missing blockstore");e.map(async n=>{if(!await t.get(n))throw r.Error().Str("cid",n.toString()).Msg("int_applyHead missing block").AsError()})}function uS(r,e){return r.toString()===e.toString()}async function gC(r,e,t,n){for(let s of e)try{n=await Hr(t,n,s)}catch(o){r.Debug().Err(o).Msg("failed to advance head");continue}return n}ye();var bi=class{constructor(e,t,n={}){this.indexers=new Map;this.onceReady=new X;this.sthis=e,this.name=t,this.logger=H(e,"CRDT"),this.opts=n,this.blockstore=Zh(e,{name:t,applyMeta:async s=>{let o=s;if(!o.head)throw this.logger.Error().Msg("missing head").AsError();await this.clock.applyHead(o.head,[])},compact:async s=>(await Kk(s,this.clock.head,this.logger),{head:this.clock.head}),autoCompact:this.opts.autoCompact||100,store:{...this.opts.store,isIndex:void 0},public:this.opts.public,meta:this.opts.meta,threshold:this.opts.threshold}),this.indexBlockstore=Zh(e,{name:t,applyMeta:async s=>{let o=s;if(!o.indexes)throw this.logger.Error().Msg("missing indexes").AsError();for(let[i,a]of Object.entries(o.indexes))Ls(this.sthis,{_crdt:this},i,void 0,a)},store:{...this.opts.store,isIndex:this.opts.store?.isIndex||"idx"},public:this.opts.public}),this.clock=new rl(this.blockstore),this.clock.onZoom(()=>{for(let s of this.indexers.values())s._resetIndex()})}async bulk(e){await this.ready();let t=[...this.clock.head],n=await this.blockstore.transaction(async s=>{let{head:o}=await Rk(this.blockstore.ebOpts.storeRuntime,s,this.clock.head,e,this.logger);return e=e.map(i=>(Hd(this.blockstore,{doc:i.value}),i)),{head:o}});return await this.clock.applyHead(n.meta.head,t,e),n.meta}async ready(){return this.onceReady.once(async()=>{try{await Promise.all([this.blockstore.ready(),this.indexBlockstore.ready(),this.clock.ready()])}catch(e){throw this.logger.Error().Err(e).Msg("CRDT is not ready").AsError()}})}async close(){await Promise.all([this.blockstore.close(),this.indexBlockstore.close(),this.clock.close()])}async destroy(){await Promise.all([this.blockstore.destroy(),this.indexBlockstore.destroy()])}async allDocs(){await this.ready();let e=[];for await(let t of Vd(this.blockstore,this.clock.head,this.logger))e.push(t);return{result:e,head:this.clock.head}}async vis(){await this.ready();let e=[];for await(let t of $k(this.blockstore,this.clock.head))e.push(t);return e.join(`
148
- `)}async getBlock(e){return await this.ready(),await zk(this.blockstore,e)}async get(e){await this.ready();let t=await Fk(this.blockstore,this.clock.head,e,this.logger);if(!t.del)return t}async changes(e=[],t={}){return await this.ready(),await wi(this.blockstore,this.clock.head,e,t,this.logger)}async compact(){return await this.blockstore.compact()}};ye();var Bs=class{constructor(e,t){this.opts={};this._listening=!1;this._listeners=new Set;this._noupdate_listeners=new Set;this._ready=new X;this.name=e,this.opts=t||this.opts,this.sthis=Xo(this.opts),this.logger=H(this.sthis,"Database"),this._crdt=new bi(this.sthis,e,this.opts),this.blockstore=this._crdt.blockstore,this._writeQueue=yy(async n=>await this._crdt.bulk(n)),this._crdt.clock.onTock(()=>{this._no_update_notify()})}static{this.databases=new Map}async close(){await this.ready(),await this._crdt.close(),await this.blockstore.close()}async destroy(){await this.ready(),await this._crdt.destroy(),await this.blockstore.destroy()}async ready(){return this._ready.once(async()=>{await this.sthis.start(),await this._crdt.ready(),await this.blockstore.ready()})}async get(e){if(!e)throw this.logger.Error().Str("db",this.name).Msg("Doc id is required").AsError();await this.ready(),this.logger.Debug().Str("id",e).Msg("get");let t=await this._crdt.get(e).catch(s=>{throw new Dt(`Not found: ${e} - ${s.message}`)});if(!t)throw new Dt(`Not found: ${e}`);let{doc:n}=t;return{...n,_id:e}}async put(e){await this.ready(),this.logger.Debug().Str("id",e._id).Msg("put");let{_id:t,...n}=e,s=t||this.sthis.timeOrderedNextId().str,o=await this._writeQueue.push({id:s,value:{...n,_id:s}});return{id:s,clock:o?.head,name:this.name}}async del(e){await this.ready(),this.logger.Debug().Str("id",e).Msg("del");let t=await this._writeQueue.push({id:e,del:!0});return{id:e,clock:t?.head,name:this.name}}async changes(e=[],t={}){await this.ready(),this.logger.Debug().Any("since",e).Any("opts",t).Msg("changes");let{result:n,head:s}=await this._crdt.changes(e,t);return{rows:n.map(({id:i,value:a,del:c,clock:l})=>({key:i,value:c?{_id:i,_deleted:!0}:{_id:i,...a},clock:l})),clock:s,name:this.name}}async allDocs(e={}){await this.ready(),this.logger.Debug().Msg("allDocs");let{result:t,head:n}=await this._crdt.allDocs();return{rows:t.map(({id:o,value:i,del:a})=>({key:o,value:a?{_id:o,_deleted:!0}:{_id:o,...i}})),clock:n,name:this.name}}async allDocuments(){return this.allDocs()}subscribe(e,t){return this.logger.Debug().Bool("updates",t).Msg("subscribe"),t?(this._listening||(this._listening=!0,this._crdt.clock.onTick(n=>{this._notify(n)})),this._listeners.add(e),()=>{this._listeners.delete(e)}):(this._noupdate_listeners.add(e),()=>{this._noupdate_listeners.delete(e)})}async query(e,t={}){await this.ready(),this.logger.Debug().Any("field",e).Any("opts",t).Msg("query");let n=this._crdt;return await(typeof e=="string"?Ls(this.sthis,{_crdt:n},e):Ls(this.sthis,{_crdt:n},bC(e.toString()),e)).query(t)}async compact(){await this.ready(),await this._crdt.compact()}async _notify(e){if(await this.ready(),this._listeners.size){let t=e.map(({id:n,value:s})=>({...s,_id:n}));for(let n of this._listeners)await(async()=>await n(t))().catch(s=>{this.logger.Error().Err(s).Msg("subscriber error")})}}async _no_update_notify(){if(await this.ready(),this._noupdate_listeners.size)for(let e of this._noupdate_listeners)await(async()=>await e([]))().catch(t=>{this.logger.Error().Err(t).Msg("subscriber error")})}};function fS(r){return r?Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({[e]:t})):[]}function wC(r,e){let t=JSON.stringify(fS({name:r,stores:fS(e?.store?.stores)})),n=Bs.databases.get(t);return n||(n=new Bs(r,e),Bs.databases.set(t,n)),n}function bC(r){let e=/\(([^,()]+,\s*[^,()]+|\[[^\]]+\],\s*[^,()]+)\)/g,t=null;return Array.from(r.matchAll(e),s=>s[1].trim()).length===0&&(t=/=>\s*{?\s*([^{}]+)\s*}?/.exec(r),t&&t[1].includes("return")&&(t=null)),t?t[1]:r}var nl={};K(nl,{FILESTORE_VERSION:()=>Cr,INDEXDB_VERSION:()=>Vc,files:()=>zh,getFileName:()=>ui,getFileSystem:()=>li,getPath:()=>tn,kb:()=>fd,kc:()=>bd,mf:()=>ap,runtimeFn:()=>Or});fi();var ap={};K(ap,{block:()=>Cu,codec:()=>hS});var hS={};ae();Td();Ld();ye();var xC=Object.keys({"0.19.114":"xxxx"})[0];return wS(kC);})();
147
+ You can use close({ resize: true }) to resize header`)},nk=(r,e)=>{let{bytes:t,headerSize:n}=r;t.set(t.subarray(n,r.byteOffset),e),r.byteOffset+=e-n,r.headerSize=e},dd=(r,e)=>{r.bytes.set(e,r.byteOffset),r.byteOffset+=e.length},rk=({bytes:r},e,t)=>{r.set(e),r.set(t,e.length)},vI=[new v(w.map,2),new v(w.string,"version"),new v(w.uint,1),new v(w.string,"roots")],EI=new v(w.tag,42),TI=r=>{let e=[...vI];e.push(new v(w.array,r.length));for(let n of r)e.push(EI),e.push(new v(w.bytes,{length:n+1}));let t=hd(e);return hi.default.encodingLength(t)+t},$c=({roots:r})=>TI(r.map(e=>e.bytes.byteLength));var sk=(r,e={})=>{let{roots:t=[],byteOffset:n=0,byteLength:s=r.byteLength,headerSize:o=$c({roots:t})}=e,i=new Uint8Array(r,n,s),a=new pd(i,o);for(let c of t)a.addRoot(c);return a};async function ik(r,e,t){let n=0,s=$c({roots:r});n+=s;for(let{cid:a,bytes:c}of e.entries())n+=di({cid:a,bytes:c});let o=new Uint8Array(n),i=sk(o,{headerSize:s});for(let a of r)i.addRoot(a);for(let{cid:a,bytes:c}of e.entries())i.write({cid:a,bytes:c});return i.close(),await Qn({value:i.bytes,hasher:Q,codec:t})}async function ok(r,e,t){return ik([e],t,r)}async function ak(r,e,t,n){let{files:s}=AI(n),o=[],i=(await r.keyedCrypto()).codec(),a=await II(i,s,t);for(let c of a){let{cid:l,bytes:u}=c;await r.save({cid:l,bytes:u}),await e.enqueueFile(l),o.push(l)}return o}function AI(r){let e=[];for(let[,t]of Object.entries(r.files||{}))t&&typeof t=="object"&&"cid"in t&&t!==null&&e.push(t.cid);return{...r,files:e}}async function II(r,e,t){return[await ik(e,t,r)]}function CI(r,e,t=!1){return{...t?{cars:[],compact:e}:{cars:e,compact:[]},meta:r}}async function LI(r){return await Qn({value:{fp:r},hasher:Q,codec:re})}async function ck(r,e,t,n={noLoader:!1,compact:!1}){let s=CI(t,r.carLog,!!n.compact),o=await LI(s),i=await BI(r.encoder,r.threshold,o,e),a=[];for(let l of i){let{cid:u,bytes:f}=l;await r.carStore.save({cid:u,bytes:f}),a.push(u)}let c={cars:a};return await r.WALStore.enqueue(c,n),await r.metaStore.save(c),{cgrp:a,header:s}}async function BI(r,e,t,n){let s=[];e=e||128e3*8;let o=new et(n.parent,{add:!1,noLoader:!1});o.putSync(t.cid,t.bytes);let i=di(t),a=t;for(let{cid:c,bytes:l}of n.entries())i+=di({cid:c,bytes:l}),i>=e?(s.push(await ok(r,a.cid,o)),o=new et(n.parent,{add:!1,noLoader:!1}),o.putSync(c,l),a={cid:c,bytes:l},i=di({cid:c,bytes:l})):o.putSync(c,l);return s.push(await ok(r,a.cid,o)),s}ye();var Kc=class{constructor(e,t){this.eventsWeHandled=new Set;this.queue=[];this.isProcessing=!1;this.logger=H(e,"TaskManager"),this.callback=t}async handleEvent(e,t,n){for(let s of t)this.eventsWeHandled.add(s.toString());this.queue.push({cid:e.toString(),dbMeta:n,retries:0}),this.queue=this.queue.filter(({cid:s})=>!this.eventsWeHandled.has(s)),this.processQueue()}async processQueue(){if(this.isProcessing)return;this.isProcessing=!0;let t=this.queue.filter(({cid:n})=>!this.eventsWeHandled.has(n))[0];if(t)try{await this.callback(t.dbMeta),this.eventsWeHandled.add(t.cid),this.queue=this.queue.filter(({cid:n})=>!this.eventsWeHandled.has(n))}catch(n){throw t.retries++>3&&(this.logger.Error().Str("cid",t.cid).Msg("failed to process event block after 3 retries"),this.queue=this.queue.filter(({cid:s})=>s!==t.cid)),await new Promise(s=>setTimeout(s,50)),this.logger.Error().Err(n).Msg("failed to process event block").AsError()}finally{this.isProcessing=!1,this.queue.length>0&&this.processQueue()}}};function zc(r,e){return r.some(t=>t.toString()===e.toString())}function lk(r,e=new Set){let t=new Map;for(let n of r)e.has(n.toString())||t.set(n.toString(),n);return[...t.values()]}var Ts=class{constructor(e,t,n){this.commitQueue=new _s;this.isCompacting=!1;this.carReaders=new Map;this.seenCompacted=new Set;this.processedCars=new Set;this.carLog=[];this.getBlockCache=new Map;this.seenMeta=new Set;this.writeLimit=Mc(1);this.onceReady=new X;this.name=e,this.sthis=n,this.ebOpts=Xh(n,{...t,name:e},"Loader"),this.logger=this.ebOpts.logger,this.taskManager=new Kc(n,async s=>{await this.handleDbMetasFromStore([s])})}async keyBag(){return Fe(this.sthis,this.ebOpts.keyBag)}async carStore(){return this.ebOpts.storeRuntime.makeDataStore(this)}async fileStore(){return this.ebOpts.storeRuntime.makeDataStore(this)}async WALStore(){return this.ebOpts.storeRuntime.makeWALStore(this)}async metaStore(){return this.ebOpts.storeRuntime.makeMetaStore(this)}async ready(){return this.onceReady.once(async()=>{let e=await(await this.metaStore()).load();this.ebOpts.meta?await this.handleDbMetasFromStore([this.ebOpts.meta]):e&&await this.handleDbMetasFromStore(e)})}async close(){let e=await Promise.all([this.carStore(),this.metaStore(),this.fileStore(),this.WALStore()]);await Promise.all(e.map(t=>t.close()))}async destroy(){let e=await Promise.all([this.carStore(),this.metaStore(),this.fileStore(),this.WALStore()]);await Promise.all(e.map(t=>t.destroy()))}async handleDbMetasFromStore(e){this.logger.Debug().Any("metas",e).Msg("handleDbMetasFromStore");for(let t of e)await this.writeLimit(async()=>{await this.mergeDbMetaIntoClock(t)})}async mergeDbMetaIntoClock(e){if(this.isCompacting)throw this.logger.Error().Msg("cannot merge while compacting").AsError();if(this.seenMeta.has(e.cars.toString())||(this.seenMeta.add(e.cars.toString()),zc(this.carLog,e.cars)))return;let t=await this.loadCarHeaderFromMeta(e);t.compact.map(n=>n.toString()).forEach(this.seenCompacted.add,this.seenCompacted),await this.getMoreReaders(t.cars.flat()),this.carLog=[...lk([e.cars,...this.carLog,...t.cars],this.seenCompacted)],await this.ebOpts.applyMeta?.(t.meta)}async loadCarHeaderFromMeta({cars:e}){let t=await this.loadCar(e[0]);return await ii(t,this.logger)}async commitFiles(e,t){await this.ready();let n=await this.fileStore(),s=await this.WALStore();return this.commitQueue.enqueue(()=>ak(n,s,e,t))}async loadFileCar(e){return await this.storesLoadCar(e,await this.fileStore(),this.remoteFileStore)}async commit(e,t,n={noLoader:!1,compact:!1}){await this.ready();let s=await this.fileStore(),o={encoder:(await s.keyedCrypto()).codec(),carLog:this.carLog,carStore:s,WALStore:await this.WALStore(),metaStore:await this.metaStore(),threshold:this.ebOpts.threshold};return this.commitQueue.enqueue(async()=>{await this.cacheTransaction(e);let i=await ck(o,e,t,n);return await this.updateCarLog(i.cgrp,i.header,!!n.compact),i.cgrp})}async updateCarLog(e,t,n){if(n){let s=t.compact[t.compact.length-1];t.compact.map(o=>o.toString()).forEach(this.seenCompacted.add,this.seenCompacted),this.carLog=[...lk([...this.carLog,...t.cars,e],this.seenCompacted)],await this.removeCidsForCompact(s[0]).catch(o=>o)}else this.carLog.unshift(e)}async cacheTransaction(e){for await(let t of e.entries()){let n=t.cid.toString();this.getBlockCache.has(n)||this.getBlockCache.set(n,t)}}async cacheCarReader(e,t){if(!this.processedCars.has(e)){this.processedCars.add(e);for await(let n of t.blocks()){let s=n.cid.toString();this.getBlockCache.has(s)||this.getBlockCache.set(s,n)}}}async removeCidsForCompact(e){let t=await this.loadCarHeaderFromMeta({cars:[e]});for(let n of t.compact)for(let s of n)await(await this.carStore()).remove(s)}async*entries(e=!0){if(await this.ready(),e)for(let[,t]of this.getBlockCache)yield t;else{for(let[,t]of this.getBlockCache)yield t;for(let t of this.carLog)for(let n of t){let s=await this.loadCar(n);if(!s)throw this.logger.Error().Ref("cid",n).Msg("missing car reader").AsError();for await(let o of s.blocks()){let i=o.cid.toString();this.getBlockCache.has(i)||(yield o)}}}}async getBlock(e){await this.ready();let t=e.toString();if(this.getBlockCache.has(t))return this.getBlockCache.get(t);let n=async a=>{if(this.getBlockCache.has(t))return this.getBlockCache.get(t);let c=await this.loadCar(a);if(!c)throw this.logger.Error().Ref("cid",a).Msg("missing car reader").AsError();if(await this.cacheCarReader(a.toString(),c).catch(()=>{}),this.getBlockCache.has(t))return this.getBlockCache.get(t);throw this.logger.Error().Str("cid",t).Msg("block not in reader").AsError()},s=async a=>{let c=await this.loadCar(a);if(!c)throw this.logger.Error().Str("cid",a.toString()).Msg("missing car reader").AsError();let u=(await ii(c,this.logger)).compact,f,p=5;for(let h=0;h<u.length;h+=p){let m=[];for(let d=h;d<Math.min(h+p,u.length);d++)for(let y of u[d])m.push(n(y));try{f=await Promise.any(m)}catch{}if(f)break}if(this.getBlockCache.has(t))return this.getBlockCache.get(t);throw this.logger.Error().Str("cid",t).Msg("block not in compact reader").AsError()},o,i=5;for(let a=0;a<this.carLog.length;a+=i){let l=this.carLog.slice(a,a+i).flatMap(u=>u.map(n));try{o=await Promise.any(l)}catch{}if(o)break}if(!o)try{o=await s(this.carLog[this.carLog.length-1][0])}catch{}return o}async loadCar(e){if(!this.carStore)throw this.logger.Error().Msg("car store not initialized").AsError();return await this.storesLoadCar(e,await this.carStore(),this.remoteCarStore)}async makeDecoderAndCarReader(e,t,n){let s=e.toString(),o,i=t;try{this.logger.Debug().Str("cid",s).Msg("loading car"),o=await t.load(e),this.logger.Debug().Bool("loadedCar",o).Msg("loaded")}catch(f){if(n){let p=await n.load(e);p&&(this.logger.Debug().Ref("cid",p.cid).Msg("saving remote car locally"),await t.save(p),o=p,i=n)}else this.logger.Error().Str("cid",s).Err(f).Msg("loading car")}if(!o)throw this.logger.Error().Url(t.url()).Str("cid",s).Msg("missing car files").AsError();let a=await lr({bytes:o.bytes,hasher:Q,codec:(await i.keyedCrypto()).codec()}),c=await oi.fromBytes(a.value),l=Promise.resolve(c),u=l.then(async f=>(await this.cacheCarReader(s,f).catch(p=>{this.logger.Error().Err(p).Str("cid",s).Msg("error caching car reader")}),f));return this.carReaders.set(s,u),l}async storesLoadCar(e,t,n){let s=e.toString(),o=this.carReaders.get(s);return o||(o=this.makeDecoderAndCarReader(e,t,n),this.carReaders.set(s,o)),o}async getMoreReaders(e){let t=Mc(5),n=e.filter(s=>!this.carReaders.has(s.toString()));await Promise.all(n.map(s=>t(()=>this.loadCar(s))))}};var bd={};K(bd,{BlockIvKeyIdCodec:()=>Hc,keyedCryptoFactory:()=>wd});ye();Rr();var uk={random:{calc:async(r,e,t)=>e.randomBytes(r.ivLength),verify:async(r,e,t,n)=>!0},hash:{calc:async(r,e,t)=>{let n=await Q.digest(t),s=new Uint8Array(n.bytes),o=new Uint8Array(r.ivLength);for(let i=0;i<s.length;i++)o[i%r.ivLength]^=s[i];return o},verify:async function(r,e,t,n){return r.url.getParam("ivverify")!=="disable"&&qh(t,await this.calc(r,e,n))}}};function fk(r,e){let t=e.ivCalc||r.getParam("ivhash")||"hash";return uk[t]||uk.hash}var Hc=class{constructor(e,t,n){this.code=3147065;this.name="Fireproof@encrypted-block:aes-gcm";this.ko=e,this.iv=t,this.opts=n||{}}async encode(e){let t=this.iv||await fk(this.ko.url,this.opts).calc(this.ko,this.ko.crypto,e),{iv:n}=this.ko.algo(t),s=await this.ko.fingerPrint(),o=J.decode(s);return this.ko.logger.Debug().Str("fp",s).Msg("encode"),hr({iv:n,keyId:o,data:await this.ko._encrypt({iv:n,bytes:e})})}async decode(e){let t;e instanceof Uint8Array?t=e:t=new Uint8Array(e);let{iv:n,keyId:s,data:o}=Tt(t),i=await this.ko.fingerPrint();if(this.ko.logger.Debug().Str("fp",J.encode(s)).Msg("decode"),J.encode(s)!==i)throw this.ko.logger.Error().Str("fp",i).Str("keyId",J.encode(s)).Msg("keyId mismatch").AsError();let a=await this.ko._decrypt({iv:n,bytes:o});if(!this.opts?.noIVVerify&&!await fk(this.ko.url,this.opts).verify(this.ko,this.ko.crypto,n,a))throw this.ko.logger.Error().Msg("iv missmatch").AsError();return a}},md=class{constructor(e,t,n,s){this.ivLength=12;this.isEncrypting=!0;this.logger=H(s,"keyedCrypto"),this.crypto=n,this.key=t,this.url=e}fingerPrint(){return Promise.resolve(this.key.fingerPrint)}codec(e,t){return new Hc(this,e,t)}algo(e){return{name:"AES-GCM",iv:e||this.crypto.randomBytes(this.ivLength),tagLength:128}}async _decrypt(e){return this.logger.Debug().Len(e.bytes,"bytes").Len(e.iv,"iv").Str("fp",this.key.fingerPrint).Msg("decrypting"),new Uint8Array(await this.crypto.decrypt(this.algo(e.iv),this.key.key,e.bytes))}async _encrypt(e){this.logger.Debug().Len(e.bytes).Str("fp",this.key.fingerPrint).Msg("encrypting");let t=this.algo(e.iv);return new Uint8Array(await this.crypto.encrypt(t,this.key.key,e.bytes))}},yd=class{constructor(){this.code=0;this.name="Fireproof@unencrypted-block"}encode(e){return e}decode(e){return e}},gd=class{constructor(e,t,n){this.ivLength=0;this.code=0;this.name="Fireproof@unencrypted-block";this.isEncrypting=!1;this._fingerPrint="noCrypto:"+Math.random();this.logger=H(n,"noCrypto"),this.crypto=t,this.url=e}fingerPrint(){return Promise.resolve(this._fingerPrint)}codec(e){return new yd}algo(e){return{name:"noCrypto",iv:new Uint8Array,tagLength:0}}_decrypt(){throw this.logger.Error().Msg("noCrypto.decrypt not implemented").AsError()}_encrypt(){throw this.logger.Error().Msg("noCrypto.decrypt not implemented").AsError()}};async function wd(r,e,t){let n=r.getParam("storekey");if(n&&n!=="insecure"){let s=await e.getNamedKey(n,!0);if(s.isErr())try{s=await e.toKeyWithFingerPrint(n)}catch(o){throw t.logger.Error().Err(o).Str("keybag",e.rt.id()).Str("name",n).Msg("getNamedKey failed").AsError()}return new md(r,s.Ok(),e.rt.crypto,t)}return new gd(r,e.rt.crypto,t)}ae();Rr();ye();function dk(r){let e=r.getParam("fragSize"),t=0;return e&&(t=parseInt(e)),(isNaN(t)||t<=0)&&(t=0),t}async function hk(r,e,t,n){if(!dk(r)){let f=await e.get(r);if(f.isErr())return[f];let p=f.unwrap();return[C.Ok({fid:new Uint8Array(0),ofs:0,len:p.length,data:p})]}let o=await e.get(r.build().setParam("ofs","0").URI());if(o.isErr())return[o];let i=Tt(o.unwrap()),a=i.data.length,c=[Promise.resolve(C.Ok(i))],l=J.encode(i.fid),u=r.build().setParam("fid",l).setParam("len",i.len.toString()).setParam("headerSize",t.toString());for(let f=a;f<i.len;f+=a)c.push((async(p,h)=>{let m=await e.get(p);if(m.isErr())return m;let d=Tt(m.unwrap());return J.encode(d.fid)!==l?C.Err(n.Error().Msg("Fragment fid mismatch").AsError()):d.ofs!==h?C.Err(n.Error().Uint64("ofs",h).Msg("Fragment ofs mismatch").AsError()):C.Ok(d)})(u.setParam("ofs",f.toString()).URI(),f));return Promise.all(c)}var pi=class{constructor(e,t){this.fidLength=4;this.headerSize=32;this.sthis=_r(e,"FragmentGateway"),this.logger=this.sthis.logger,this.innerGW=t}slicer(e,t){let n=dk(e);if(!n)return[this.innerGW.put(e,t)];let s=n-this.headerSize;if(s<=0)throw this.logger.Error().Uint64("fragSize",n).Uint64("headerSize",this.headerSize).Msg("Fragment size is too small").AsError();let o=[],i=this.sthis.nextId(this.fidLength),a=e.build().setParam("fid",i.str).setParam("len",t.length.toString()).setParam("headerSize",this.headerSize.toString());for(let c=0;c<t.length;c+=s){let l=hr({fid:i.bin,ofs:c,len:t.length,data:t.slice(c,c+s)});if(l.length>n)throw this.logger.Error().Uint64("block",l.length).Uint64("fragSize",n).Msg("Block size to big").AsError();o.push(this.innerGW.put(a.setParam("ofs",c.toString()).URI(),l))}return o}buildUrl(e,t){return this.innerGW.buildUrl(e,t)}async destroy(e){return this.innerGW.destroy(e)}async start(e){return this.headerSize=hr({fid:this.sthis.nextId(this.fidLength).bin,ofs:1024*1024,len:16*1024*1024,data:new Uint8Array(1024)}).length-1024,this.innerGW.start(e)}async close(e){return this.innerGW.close(e)}async put(e,t){return await Promise.all(this.slicer(e,t)),C.Ok(void 0)}async get(e){let t=await hk(e,this.innerGW,this.headerSize,this.logger),n;for(let s of t){if(s.isErr())return C.Err(s.Err());let o=s.Ok();n=n||new Uint8Array(o.len),n.set(o.data,o.ofs)}return C.Ok(n||new Uint8Array(0))}async subscribe(e,t){return this.innerGW.subscribe?this.innerGW.subscribe(e,t):C.Err(this.logger.Error().Url(e).Msg("subscribe not supported").AsError())}async delete(e){let t=await hk(e,this.innerGW,this.headerSize,this.logger);for(let n of t){if(n.isErr())return C.Err(n.Err());let s=n.Ok(),o=J.encode(s.fid),i=e.build().setParam("fid",o).setParam("len",s.len.toString()).setParam("headerSize",this.headerSize.toString()).URI();await this.innerGW.delete(i)}return C.Ok(void 0)}};ae();async function mi(r,e){let t=JSON.parse(r.txt.decode(e));return t.length?t.map?Promise.all(t.map(async n=>{let s=await zu(wc.decode(n.data)),o=kc(r.txt.decode(s.value.data.dbMeta));return{eventCid:s.cid,parents:n.parents,dbMeta:o}})):(r.logger.Debug().Str("crdtEntries",JSON.stringify(t)).Msg("No data in CRDT entries"),[]):(r.logger.Debug().Any("byteHeads",e).Msg("No CRDT entries found"),[])}async function pk(r,e,t){try{e.logger.Debug().Str("uri",r.toString()).Msg("Setting crypto key from gateway meta payload");let n=await mi(e,t);if(n.length){let s=n[0].dbMeta;if(s.key){let o=await Fe(e),i=yk(r),a=await o.setNamedKey(i,s.key);if(a.isErr())throw e.logger.Debug().Str("keyName",i).Str("dbMeta.key",s.key).Msg("Failed to set named key"),a.Err()}return e.logger.Debug().Str("dbMeta.key",s.key).Str("uri",r.toString()).Msg("Set crypto key from gateway meta payload"),C.Ok(s)}return e.logger.Debug().Any("data",t).Msg("No crypto in gateway meta payload"),C.Ok(void 0)}catch(n){return e.logger.Debug().Err(n).Msg("Failed to set crypto key from gateway meta payload"),C.Err(n)}}async function mk(r,e,t){try{e.logger.Debug().Str("uri",r.toString()).Msg("Adding crypto key to gateway meta payload");let n=yk(r),o=await(await Fe(e)).getNamedExtractableKey(n,!0);if(o.isErr())throw e.logger.Error().Str("keyName",n).Msg("Failed to get named extractable key"),o.Err();let i=await o.Ok().extract(),a=await mi(e,t),{dbMeta:c,parents:l}=a[0],u=l.map(h=>N.parse(h));c.key=i.keyStr;let f=await Promise.all([c].map(h=>xd(e,h,u))),p=await kd(e,f,u);return e.logger.Debug().Str("uri",r.toString()).Msg("Added crypto key to gateway meta payload"),C.Ok(p)}catch(n){return e.logger.Error().Err(n).Msg("Failed to add crypto key to gateway meta payload"),C.Err(n)}}function yk(r){let e=[r.getParam("localName")||r.getParam("name")],t=r.getParam("index");return t&&e.push(t),e.push("data"),`@${e.join(":")}@`}async function xd(r,e,t){return await jt.create({dbMeta:r.txt.encode(xc(e))},t)}async function kd(r,e,t){let n=e.map(s=>{let o=wc.encode(s.bytes);return{cid:s.cid.toString(),data:o,parents:t.map(i=>i.toString())}});return r.txt.encode(JSON.stringify(n))}var vk=mt(kk(),1);var DI=Object.prototype.toString,NI=r=>DI.call(r)==="[object Error]",MI=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function Sd(r){return r&&NI(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:MI.has(r.message):!1}var vd=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},Sk=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Ed(r,e){return new Promise((t,n)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let s=vk.default.operation(e),o=()=>{s.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",o),s.stop()};s.attempt(async a=>{try{let c=await r(a);i(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof vd)throw c.originalError;if(c instanceof TypeError&&!Sd(c))throw c;if(Sk(c,a,e),await e.shouldRetry(c)||(s.stop(),n(c)),await e.onFailedAttempt(c),!s.retry(c))throw s.mainError()}catch(l){Sk(l,a,e),i(),n(l)}}})})}async function yi(r,e,{concurrency:t=Number.POSITIVE_INFINITY,stopOnError:n=!0,signal:s}={}){return new Promise((o,i)=>{if(r[Symbol.iterator]===void 0&&r[Symbol.asyncIterator]===void 0)throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof r})`);if(typeof e!="function")throw new TypeError("Mapper function is required");if(!(Number.isSafeInteger(t)&&t>=1||t===Number.POSITIVE_INFINITY))throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${t}\` (${typeof t})`);let a=[],c=[],l=new Map,u=!1,f=!1,p=!1,h=0,m=0,d=r[Symbol.iterator]===void 0?r[Symbol.asyncIterator]():r[Symbol.iterator](),y=b=>{u=!0,f=!0,i(b)};s&&(s.aborted&&y(s.reason),s.addEventListener("abort",()=>{y(s.reason)}));let g=async()=>{if(f)return;let b=await d.next(),x=m;if(m++,b.done){if(p=!0,h===0&&!f){if(!n&&c.length>0){y(new AggregateError(c));return}if(f=!0,l.size===0){o(a);return}let k=[];for(let[S,T]of a.entries())l.get(S)!==Ek&&k.push(T);o(k)}return}h++,(async()=>{try{let k=await b.value;if(f)return;let S=await e(k,x);S===Ek&&l.set(x,S),a[x]=S,h--,await g()}catch(k){if(n)y(k);else{c.push(k),h--;try{await g()}catch(S){y(S)}}}})()};(async()=>{for(let b=0;b<t;b++){try{await g()}catch(x){y(x);break}if(p||u)break}})()})}var Ek=Symbol("skip");function OI(r){return r.hasParam("version")?C.Ok(r):C.Err(`missing version: ${r.toString()}`)}var gi=class{constructor(e,t,n,s,o){this._onStarted=[];this._onClosed=[];this.name=e,this._url=t,this.keybag=n.keybag,this.sthis=s,this.logger=o.With().Ref("url",()=>this._url.toString()).Str("name",e).Logger(),this.gateway=new pi(this.sthis,n.gateway),this.loader=n.loader}url(){return this._url}onStarted(e){this._onStarted.push(e)}onClosed(e){this._onClosed.push(e)}async ready(){}async keyedCrypto(){return wd(this._url,await this.keybag(),this.sthis)}async start(){this.logger.Debug().Str("storeType",this.storeType).Msg("starting-gateway-pre"),this._url=this._url.build().setParam("store",this.storeType).URI();let e=await this.gateway.start(this._url);if(e.isErr())return this.logger.Error().Result("gw-start",e).Msg("started-gateway"),e;this._url=e.Ok();let n=await(await this.keybag()).ensureKeyFromUrl(this._url,()=>{let o=this._url.getParam("index"),i=[this.name];return o&&i.push(o),i.push(this.storeType),i.join(":")});if(n.isErr())return n;this._url=n.Ok();let s=OI(this._url);if(s.isErr())return this.logger.Error().Result("version",s).Msg("guardVersion"),await this.close(),s;if(this.ready){let o=this.ready.bind(this),i=await We(o);if(i.isErr())return await this.close(),i}return this._onStarted.forEach(o=>o()),this.logger.Debug().Msg("started"),s}},As=class extends gi{constructor(t,n,s,o){super(n,s,{...o},t,H(t,"MetaStoreImpl"));this.storeType="meta";this.subscribers=new Map;this.parents=[];o.gateway.subscribe&&this.onStarted(async()=>{this.logger.Debug().Str("url",this.url().toString()).Msg("Subscribing to the gateway"),o.gateway.subscribe?.(this.url(),async i=>{this.logger.Debug().Msg("Received message from gateway");let a=await mi(this.sthis,i);await Promise.all(a.map(c=>this.loader?.taskManager?.handleEvent(c.eventCid,c.parents,c.dbMeta))),this.updateParentsFromDbMetas(a)})})}updateParentsFromDbMetas(t){let n=t.map(a=>a.eventCid),s=t.flatMap(a=>a.parents),o=new Map([...this.parents,...n].map(a=>[a.toString(),a])),i=new Set(s.map(a=>a.toString()));this.parents=Array.from(o.values()).filter(a=>!i.has(a.toString()))}async handleByteHeads(t){return await mi(this.sthis,t)}async load(){let t="main",n=await this.gateway.buildUrl(this.url(),t);if(n.isErr())throw this.logger.Error().Result("buildUrl",n).Str("branch",t).Msg("got error from gateway.buildUrl").AsError();let s=await this.gateway.get(n.Ok());if(s.isErr()){if(Mt(s))return;throw this.logger.Error().Url(n.Ok()).Result("bytes:",s).Msg("gateway get").AsError()}let o=await this.handleByteHeads(s.Ok());return await this.loader?.handleDbMetasFromStore(o.map(i=>i.dbMeta)),this.updateParentsFromDbMetas(o),o.map(i=>i.dbMeta)}async save(t,n){n=n||"main",this.logger.Debug().Str("branch",n).Any("meta",t).Msg("saving meta");let s=await xd(this.sthis,t,this.parents),o=await kd(this.sthis,[s],this.parents),i=await this.gateway.buildUrl(this.url(),n);if(i.isErr())throw this.logger.Error().Err(i.Err()).Str("branch",n).Msg("got error from gateway.buildUrl").AsError();this.parents=[s.cid];let a=await this.gateway.put(i.Ok(),o);if(a.isErr())throw this.logger.Error().Err(a.Err()).Msg("got error from gateway.put").AsError();return a}async close(){return await this.gateway.close(this.url()),this._onClosed.forEach(t=>t()),C.Ok(void 0)}async destroy(){return this.gateway.destroy(this.url())}},Is=class extends gi{constructor(t,n,s,o){super(n,s,{...o},t,H(t,"DataStoreImpl"));this.storeType="data"}async load(t){this.logger.Debug().Any("cid",t).Msg("loading");let n=await this.gateway.buildUrl(this.url(),t.toString());if(n.isErr())throw this.logger.Error().Err(n.Err()).Str("cid",t.toString()).Msg("got error from gateway.buildUrl").AsError();let s=await this.gateway.get(n.Ok());if(s.isErr())throw s.Err();return{cid:t,bytes:s.Ok()}}async save(t,n){this.logger.Debug().Any("cid",t.cid.toString()).Msg("saving");let s=await this.gateway.buildUrl(this.url(),t.cid.toString());if(s.isErr())throw this.logger.Error().Err(s.Err()).Ref("cid",t.cid).Msg("got error from gateway.buildUrl").AsError();let o=await this.gateway.put(s.Ok(),t.bytes);if(o.isErr())throw this.logger.Error().Err(o.Err()).Msg("got error from gateway.put").AsError();return o.Ok()}async remove(t){let n=await this.gateway.buildUrl(this.url(),t.toString());return n.isErr()?n:this.gateway.delete(n.Ok())}async close(){return await this.gateway.close(this.url()),this._onClosed.forEach(t=>t()),C.Ok(void 0)}destroy(){return this.gateway.destroy(this.url())}},jc=class extends gi{constructor(t,n,s){super(t.name,n,{...s},t.sthis,H(t.sthis,"WALStoreImpl"));this.storeType="wal";this._ready=new X;this.walState={operations:[],noLoaderOps:[],fileOperations:[]};this.processing=void 0;this.processQueue=new _s;this.loader=t}async ready(){return this._ready.once(async()=>{let t=await this.load().catch(n=>{this.logger.Error().Any("error",n).Msg("error loading wal")});t?(this.walState.operations=t.operations||[],this.walState.fileOperations=t.fileOperations||[]):(this.walState.operations=[],this.walState.fileOperations=[])})}async enqueue(t,n){await this.ready(),n.compact?(this.walState.operations=[],this.walState.noLoaderOps=[t]):n.noLoader?this.walState.noLoaderOps.push(t):this.walState.operations.push(t),await this.save(this.walState),n.noLoader||this.process()}async enqueueFile(t,n=!1){await this.ready(),this.walState.fileOperations.push({cid:t,public:n})}async process(){await this.ready(),this.loader.remoteCarStore&&await this.processQueue.enqueue(async()=>{try{await this._doProcess()}catch(t){this.logger.Error().Any("error",t).Msg("error processing wal")}(this.walState.operations.length||this.walState.fileOperations.length||this.walState.noLoaderOps.length)&&setTimeout(()=>void this.process(),0)})}async _doProcess(){if(!this.loader.remoteCarStore)return;let t=[...this.walState.operations],n=[...this.walState.noLoaderOps],s=[...this.walState.fileOperations];if(t.length+n.length+s.length===0)return;let o=3,i=(a,c)=>Ed(a,{retries:5,onFailedAttempt:l=>{this.logger.Warn().Msg(`Attempt ${l.attemptNumber} failed for ${c}. There are ${l.retriesLeft} retries left.`)}});try{if(await yi(n,async a=>{await i(async()=>{for(let c of a.cars){let l=await(await this.loader.carStore()).load(c);if(l)await me(this.loader.remoteCarStore).save(l);else if(zc(this.loader.carLog,a.cars))throw this.logger.Error().Ref("cid",c).Msg("missing local car").AsError()}this.walState.noLoaderOps=this.walState.noLoaderOps.filter(c=>c!==a)},`noLoaderOp with dbMeta.cars=${a.cars.toString()}`)},{concurrency:o}),await yi(t,async a=>{await i(async()=>{for(let c of a.cars){let l=await(await this.loader.carStore()).load(c);if(l)await me(this.loader.remoteCarStore).save(l);else if(zc(this.loader.carLog,a.cars))throw this.logger.Error().Ref("cid",c).Msg("missing local car").AsError()}this.walState.operations=this.walState.operations.filter(c=>c!==a)},`operation with dbMeta.cars=${a.cars.toString()}`)},{concurrency:o}),await yi(s,async({cid:a,public:c})=>{await i(async()=>{let l=await(await this.loader.fileStore()).load(a);if(!l)throw this.logger.Error().Ref("cid",a).Msg("missing file block").AsError();await this.loader.remoteFileStore?.save(l,{public:c}),this.walState.fileOperations=this.walState.fileOperations.filter(u=>u.cid!==a)},`fileOperation with cid=${a.toString()}`)},{concurrency:o}),t.length){let a=t[t.length-1];await i(async()=>{await this.loader.remoteMetaStore?.save(a)},`remoteMetaStore save with dbMeta.cars=${a.cars.toString()}`)}}catch(a){this.logger.Error().Any("error",a).Msg("Processing failed");return}finally{await this.save(this.walState)}}async load(){this.logger.Debug().Msg("loading");let t=await this.gateway.buildUrl(this.url(),"main");if(t.isErr())throw this.logger.Error().Err(t.Err()).Url(this.url()).Msg("error building url").AsError();let n=await this.gateway.get(t.Ok());if(n.isErr()){if(Mt(n))return;throw this.logger.Error().Err(n.Err()).Msg("error get").AsError()}try{return n&&kc(this.sthis.txt.decode(n.Ok()))}catch(s){throw this.logger.Error().Err(s).Msg("error parse").AsError()}}async save(t){let n=await this.gateway.buildUrl(this.url(),"main");if(n.isErr())throw this.logger.Error().Err(n.Err()).Url(this.url()).Msg("error building url").AsError();let s;try{s=xc(t)}catch(i){throw this.logger.Error().Err(i).Any("state",t).Msg("error format").AsError()}let o=await this.gateway.put(n.Ok(),this.sthis.txt.encode(s));if(o.isErr())throw this.logger.Error().Err(o.Err()).Str("filePath",n.Ok().toString()).Msg("error saving").AsError()}async close(){return await this.gateway.close(this.url()),this._onClosed.forEach(t=>t()),C.Ok(void 0)}destroy(){return this.gateway.destroy(this.url())}};ye();function $I(r,e){return e?r.build().setParam("index",e).URI():r.build().delParam("index").URI()}function Fd(r,e){return e.hasParam("name")?e:e.build().setParam("name",r).URI()}var on=new Map;function Ud(r,e){let t=e.ebOpts.store,n=Array.from(on.values()).find(i=>i.overrideBaseURL),s;return n&&n.overrideBaseURL&&(s=Ie.from(n.overrideBaseURL)),$I(Ie.from(r||s||Wh(e.sthis,e.name,t.stores?.base)),t.isIndex)}var KI=new _e;async function Lr(r,e){return KI.get(r.toString()).once(async()=>{let t=on.get(r.protocol);if(t){let n={gateway:await t.gateway(e),test:await t.test(e)},s=await n.gateway.start(r);if(s.isErr()){e.logger.Error().Result("start",s).Msg("start failed");return}return n}e.logger.Warn().Url(r).Msg("unsupported protocol")})}function $d(r){let e=r.protocol;if(e.endsWith(":")||(e+=":"),on.has(e)&&!r.overrideBaseURL&&on.get(e)!==r)throw new Error("we need a logger here");return r.overrideBaseURL&&Array.from(on.values()).forEach(t=>{t.overrideBaseURL=void 0}),on.set(e,r),()=>{on.delete(e)}}var zI=new _e;async function HI(r){let e=Fd(r.name,Ud(r.ebOpts.store.stores?.data,r)).build().setParam("store","data").URI(),t=_r(r.sthis,"dataStoreFactory",{url:e.toString()});return zI.get(e.toString()).once(async()=>{let n=await Lr(e,t);if(!n)throw t.logger.Error().Url(e).Msg("gateway not found").AsError();return new Is(t,r.name,e,{gateway:n.gateway,keybag:()=>Fe(r.sthis,{...r.ebOpts.keyBag})})})}var jI=new _e;async function VI(r){let e=Fd(r.name,Ud(r.ebOpts.store.stores?.meta,r)).build().setParam("store","meta").URI(),t=_r(r.sthis,"metaStoreFactory",{url:()=>e.toString()});return jI.get(e.toString()).once(async()=>{t.logger.Debug().Str("protocol",e.protocol).Msg("pre-protocol switch");let n=await Lr(e,t);if(!n)throw t.logger.Error().Url(e).Msg("gateway not found").AsError();return new As(r.sthis,r.name,e,{gateway:n.gateway,keybag:()=>Fe(r.sthis,{...r.ebOpts.keyBag})})})}var WI=new _e;async function qI(r){let e=Fd(r.name,Ud(r.ebOpts.store.stores?.wal,r)).build().setParam("store","wal").URI(),t=_r(r.sthis,"remoteWalFactory",{url:e.toString()});return WI.get(e.toString()).once(async()=>{let n=await Lr(e,t);if(!n)throw t.logger.Error().Url(e).Msg("gateway not found").AsError();return t.logger.Debug().Str("prepared",e.toString()).Msg("produced"),new jc(r,e,{gateway:n.gateway,keybag:()=>Fe(r.sthis,{...r.ebOpts.keyBag})})})}async function GI(r,e){e=_r(e,"testStoreFactory");let t=await Lr(r,e);if(!t)throw e.logger.Error().Url(r).Msg("gateway not found").AsError();return t.test}async function qc(r,e){let t=await r.start();if(t.isErr())throw e.Error().Result("start",t).Msg("start failed").AsError();return e.Debug().Url(t.Ok(),"prepared").Msg("produced"),r}function ed(r,e){let t=H(e,"toStoreRuntime",{});return{makeMetaStore:async n=>(t.Debug().Str("fromOpts",""+!!n.ebOpts.store.makeMetaStore).Msg("makeMetaStore"),qc(await(n.ebOpts.store.makeMetaStore||VI)(n),t)),makeDataStore:async n=>(t.Debug().Str("fromOpts",""+!!n.ebOpts.store.makeDataStore).Msg("makeDataStore"),qc(await(n.ebOpts.store.makeDataStore||HI)(n),t)),makeWALStore:async n=>(t.Debug().Str("fromOpts",""+!!n.ebOpts.store.makeWALStore).Msg("makeRemoteWAL"),qc(await(n.ebOpts.store.makeWALStore||qI)(n),t)),encodeFile:r.encodeFile||$h,decodeFile:r.decodeFile||Kh}}$d({protocol:"file:",gateway:async r=>{let{FileGateway:e}=await Promise.resolve().then(()=>(Cd(),Id));return new e(r)},test:async r=>{let{FileTestStore:e}=await Promise.resolve().then(()=>(Cd(),Id));return new e(r)}});$d({protocol:"indexdb:",gateway:async r=>{let{IndexDBGateway:e}=await Promise.resolve().then(()=>(Rd(),Od));return new e(r)},test:async r=>{let{IndexDBTestStore:e}=await Promise.resolve().then(()=>(Rd(),Od));return new e(r)}});async function Bk(r,e,t,n){let s=new Is(r,e,t,n);return await s.start(),s}async function Pk(r,e,t,n){let s=new As(r,e,t,n);return await s.start(),s}var Gc=class{constructor(e,t){this.loaded=Promise.resolve();this.logger=t,this.url=e}async refresh(){await me(me(this.loader).remoteMetaStore).load(),await(await me(this.loader).WALStore()).process()}async connect_X({loader:e}){if(!e)throw this.logger.Error().Msg("loader is required").AsError();await this.connectMeta_X({loader:e}),await this.connectStorage_X({loader:e})}async connectMeta_X({loader:e}){if(!e)throw this.logger.Error().Msg("connectMeta_X: loader is required").AsError();this.loader=e,await this.onConnect();let t=this.url.build().defParam("store","meta").URI(),n=await Lr(t,this.loader.sthis);if(!n)throw this.logger.Error().Url(t).Msg("connectMeta_X: gateway is required").AsError();let s=t.getParam("name");if(!s)throw this.logger.Error().Url(t).Msg("connectMeta_X: name is required").AsError();let o=await Pk(e.sthis,s,t,{gateway:n.gateway,keybag:()=>Fe(e.sthis,e.ebOpts.keyBag),loader:e});this.loader.remoteMetaStore=o,this.loaded=this.loader.ready().then(async()=>o.load().then(async()=>(await me(this.loader).WALStore()).process()))}async connectStorage_X({loader:e}){if(!e)throw this.logger.Error().Msg("connectStorage_X: loader is required").AsError();this.loader=e;let t=this.url.build().defParam("store","data").URI(),n=await Lr(t,this.loader.sthis);if(!n)throw this.logger.Error().Url(t).Msg("connectStorage_X: gateway is required").AsError();let s=t.getParam("name");if(!s)throw this.logger.Error().Url(t).Msg("connectStorage_X: name is required").AsError;e.remoteCarStore=await Bk(e.sthis,s,this.url,{gateway:n.gateway,keybag:()=>Fe(e.sthis,this.loader?.ebOpts.keyBag)}),e.remoteFileStore=e.remoteCarStore}};function Dk(r,e){switch(typeof r){case"string":case"number":return r.toString();default:throw e.Error().Msg("Invalid key type").AsError()}}async function Rk(r,e,t,n,s){let o=null;if(n.length>1){let i=await Gg(e,t);for(let a of n){let c=await Nk(r,e,a,s);await i.put(Dk(a.id,s),c)}o=await i.commit()}else if(n.length===1){let i=await Nk(r,e,n[0],s);o=await Hg(e,t,Dk(n[0].id,s),i)}if(!o)throw s.Error().Uint64("updates.len",n.length).Msg("Missing result").AsError();if(o.event)for(let{cid:i,bytes:a}of[...o.additions,o.event])e.putSync(i,a);return{head:o.head}}async function Nk(r,e,t,n){let s;if(t.del)s={del:!0};else{if(!t.value)throw n.Error().Msg("Missing value").AsError();await JI(r,e,t.value,n),s={doc:t.value}}let o=await Qn({value:s,hasher:Q,codec:re});return e.putSync(o.cid,o.bytes),o.cid}async function JI(r,e,t,n){t._files&&await Mk(n,r,e,t._files),t._publicFiles&&await Mk(n,r,e,t._publicFiles)}async function Mk(r,e,t,n){let s=t.parent;if(!s.loader)throw r.Error().Msg("Missing loader, database name is required").AsError();let o=new et(s),i=[];for(let a in n)if(File===n[a].constructor){let c=n[a],{cid:l,blocks:u}=await e.encodeFile(c);i.push(a);for(let f of u)o.putSync(f.cid,f.bytes);n[a]={cid:l,type:c.type,size:c.size}}else{let{cid:c,type:l,size:u,car:f}=n[a];c&&l&&u&&f&&(n[a]={cid:c,type:l,size:u,car:f})}if(i.length){let a=await s.loader.commitFiles(o,{files:n});if(a)for(let c of i)n[c]={car:a,...n[c]}}}async function Fk(r,e,t,n){if(!e.length)throw n.Debug().Msg("Getting from an empty database").AsError();let s=await jg(r,e,t);if(!s)throw n.Error().Str("key",t).Msg("Missing key").AsError();return await jd(r,s,n)}function Hd(r,{doc:e}){e&&(e._files&&Ok(r,e._files),e._publicFiles&&Ok(r,e._publicFiles,!0))}function Ok(r,e,t=!1){for(let n in e){let s=e[n];s.cid&&(t&&(s.url=`https://${s.cid.toString()}.ipfs.w3s.link/`),s.car&&(s.file=async()=>await r.ebOpts.storeRuntime.decodeFile({get:async o=>await r.getFile(me(s.car),o)},s.cid,s))),e[n]=s}}async function jd(r,e,t){let n=await r.get(e);if(!n)throw t.Error().Str("link",e.toString()).Msg("Missing linked block").AsError();let{value:s}=await lr({bytes:n.bytes,hasher:Q,codec:re}),o={...s,cid:e};return Hd(r,o),o}var zd=class extends _t{constructor(e,t){super(t),this.logger=e}async get(e){try{return super.get(e)}catch(t){return this.logger.Error().Ref("link",e.toString()).Err(t).Msg("Missing event"),{value:void 0}}}};async function wi(r,e,t,n,s){let o=n.dirty?new zd(s,r):new _t(r);return{result:(await Uk(r,o,e,t,[],new Set,new Set,n.limit||1/0,s)).reverse(),head:e}}async function Uk(r,e,t,n,s=[],o,i,a,c){if(a<=0)return s;let l=t.map(u=>u.toString());for(let u of n)if(l.includes(u.toString()))return s;for(let u of t){if(i.has(u.toString()))continue;i.add(u.toString());let{value:f}=await e.get(u);if(!f)continue;let{type:p}=f.data,h=[];p==="batch"?h=f.data.ops:p==="put"&&(h=[f.data]);for(let m=h.length-1;m>=0;m--){let{key:d,value:y}=h[m];if(!o.has(d)){let g=await jd(r,y,c);s.push({id:d,value:g.doc,del:g.del,clock:u}),a--,o.add(d)}}f.parents&&(s=await Uk(r,e,f.parents,n,s,o,i,a,c))}return s}async function*Vd(r,e,t){for await(let[n,s]of Vg(r,e)){let o=await jd(r,s,t);yield{id:n,value:o.doc,del:o.del}}}async function*$k(r,e){for await(let t of Hu(r,e))yield t}var Kd=!1;async function Kk(r,e,t){if(Kd)return;Kd=!0;for(let s of e)if(!await r.get(s))throw t.Error().Ref("cid",s).Msg("Missing head block").AsError();for await(let s of Vd(r,e,t));for await(let s of Hu(r,e));let n=await yr(r,e);for(let{cid:s,bytes:o}of[...n.additions,...n.removals])r.loggedBlocks.putSync(s,o);await wi(r,e,[],{},t),Kd=!1}async function zk(r,e){let t=await r.get(Sa(e));if(!t)throw new Error(`Missing block ${e}`);let{cid:n,value:s}=await lr({bytes:t.bytes,codec:re,hasher:Q});return new ka({cid:n,value:s,bytes:t.bytes})}var dn=mt(Gk(),1);var Jk=r=>{let e=r.byteLength-4;return(r[e]|r[e+1]<<8|r[e+2]<<16)+r[e+3]*16777216};var qd=r=>{let e=Math.floor(4294967295/r);return async t=>{let n=await t.identity();if(typeof n!="number")throw new Error("Identity must be a number");return n<=e}};var cn=(r,e)=>r===e?0:r>e?1:-1;var an=class{constructor(){this._cids=new Set}add(e){if(!e.address)throw new Error("Cannot add node without address");if(e.address.then){let t=e.address.then(n=>this._cids.add(n.toString()));this._cids.add(t),t.then(()=>this._cids.delete(t))}else this._cids.add(e.address.toString())}async all(){return await Promise.all([...this._cids]),this._cids}};var Qc=class{constructor({key:e,address:t},n={}){this.key=e,this.address=t,this.codec=n.codec,this.hasher=n.hasher}get isEntry(){return!0}},Cs=class{constructor({entries:e,closed:t}){if(typeof t!="boolean")throw new Error('Missing required argument "closed"');this.entries=e,this.closed=t,this.startKey=e[0].key}find(e,t){let{entries:n}=this;for(let s=n.length-1;s>-1;s--){let o=n[s];if(t(e,o.key)>-1)return[s,o]}return null}findMany(e,t,n=!1,s=!1){let{entries:o}=this,i=new Map;n?e=[...e]:e=e.sort(t);for(let a=o.length-1;a>-1&&e.length;a--){let c=o[a],l=[];for(;e.length;){let u=e[e.length-1];u=u.key?u.key:u;let f=t(u,c.key);if(s)if(f===0)l.push(e.pop());else if(f>0)e.pop();else break;else if(f>-1)l.push(e.pop());else break}l.length&&i.set(a,[c,l])}return i}findRange(e,t,n){let{entries:s}=this,o,i=0;for(let a=s.length-1;a>-1;a--){let c=s[a];if(n(t,c.key)>0){o=a;break}}for(let a=0;a<s.length;a++){let c=s[a],l=n(e,c.key);if(l===0){i=a;break}else if(l<0)break;i=a}return{first:i,last:o,entries:s.slice(i,o+1)}}},Qk=r=>typeof r=="string"?r:JSON.stringify(r);function nC(r,e){return r.sort(({key:t},{key:n})=>e.compare(t,n))}async function sC(r,e,t){let n=[];for(let s of e){let{key:o,del:i}=s;if(t(o,r)<0)i||n.push(s);else break}return n}async function oC(r,e,{chunker:t,compare:n}){return await Br.from({entries:r.map(s=>new e.LeafEntryClass(s,e)).sort((s,o)=>n(s.key,o.key)),chunker:t,NodeClass:e.LeafClass,distance:0,opts:e})}async function iC(r,e,t,n){return await Promise.all(e.map(async s=>{let o=await s.encode();return t.blocks.push({block:o,node:s}),r.cache.set(s),new n.BranchEntryClass({key:s.key,address:await s.address},n)}))}async function aC(r,e,t,n){let s=e.root;e.blocks.push({block:await s.encode(),node:s}),r.cache.set(s);let o=n.opts,i=s.distance,a=s.entryList.startKey,c=await sC(a,t,r.compare);if(c.length){let l=await oC(c,o,r),u=await iC(r,l,e,o),p=[new o.BranchEntryClass({key:s.entryList.startKey,address:await s.address},o),...u].sort(({key:d},{key:y})=>o.compare(d,y)),h=await Br.from({...n,entries:p,chunker:r.chunker,NodeClass:o.BranchClass,distance:i+1}),m=[...h];for(;h.length>1;){let d=await Promise.all(h.map(async y=>new o.BranchEntryClass({key:y.key,address:await y.address},o)));h=await Br.from({...n,entries:d.sort(({key:y},{key:g})=>o.compare(y,g)),chunker:r.chunker,NodeClass:o.BranchClass,distance:i+1}),m=[...m,...h]}await Promise.all(m.map(async d=>{let y=await d.encode();r.cache.set(d),e.blocks.push({block:y,node:d})})),e.root=h[0],e.nodes=[...e.nodes,...m]}}var Br=class r{constructor({entryList:e,chunker:t,distance:n,getNode:s,compare:o,cache:i}){this.entryList=e,this.chunker=t,this.distance=n,this.getNode=s,this.compare=o,this.cache=i}get closed(){return this.entryList.closed}get key(){return this.entryList.startKey}async getEntry(e,t=new an){return{result:await this._getEntry(e,t),cids:t}}async _getEntry(e,t){t.add(this);let n=this;for(;!n.isLeaf;){let i=n.entryList.find(e,this.compare);if(i===null)throw new Error("Not found");let[,a]=i;n=await this.getNode(await a.address),t.add(n)}let s=n.entryList.find(e,this.compare);if(s===null||s[1].key.toString()!==e.toString())throw new Error("Not found");let[,o]=s;return o}async getAllEntries(e=new an){return{result:await this._getAllEntries(e),cids:e}}_getAllEntries(e){if(e.add(this),this.isLeaf)return this.entryList.entries;{let{entries:t}=this.entryList,n=async s=>this.getNode(await s.address).then(o=>o._getAllEntries(e)).catch(async o=>{throw o});return Promise.all(t.map(n)).then(s=>s.flat())}}async*vis(e=new Set){let t=async o=>o.isLeaf?`Leaf [${o.entryList.entries.map(a=>`[${a.key},${JSON.stringify(a.value).replace(/"/g,"'")}]`).join(", ")}]`:`Branch [${o.entryList.entries.map(a=>`[${a.key}]`).join(", ")}]`,n=o=>o.toString().slice(0,4)+o.toString().slice(-4),s=async function*(o,i,a){let c=await o.address;if(!a.has(c)){a.add(c);let l=await t(o);yield` node [shape=ellipse fontname="Courier"]; ${n(c)} [label="${l}"];`,yield` ${n(i)} -> ${n(c)};`;for(let u of o.entryList.entries)if(u.address){let f=await u.address;try{let p=await o.getNode(f);yield*await s(p,c,a)}catch(p){yield` ${n(c)} -> ${n(f)};`,yield` node [shape=ellipse fontname="Courier"]; ${n(f)} [label="Error: ${p.message}"];`}}}};yield"digraph tree {",yield' node [shape=ellipse fontname="Courier"]; rootnode;';for await(let o of s(this,"rootnode",e))yield o;yield"}"}async getEntries(e,t=!1,n=new an){return{result:await this._getEntries(e,t,n),cids:n}}async _getEntries(e,t,n){n.add(this),t||(e=e.sort(this.compare));let s=this.entryList.findMany(e,this.compare,!0,this.isLeaf);if(this.isLeaf)return[...s.values()].map(([i])=>i);let o=[];for(let[i,a]of[...s.values()].reverse()){let c=this.getNode(await i.address);o.push(c.then(l=>l._getEntries(a.reverse(),!0,n)))}return o=await Promise.all(o),o.flat()}async getRangeEntries(e,t,n=new an){return{result:await this._getRangeEntries(e,t,n),cids:n}}_getRangeEntries(e,t,n){n.add(this);let{entries:s}=this.entryList.findRange(e,t,this.compare);if(this.isLeaf)return s.filter(c=>{let l=this.compare(e,c.key),u=this.compare(t,c.key);return l<=0&&u>=0});if(!s.length)return[];let o=async c=>this.getNode(await c.address).then(l=>l._getRangeEntries(e,t,n)),i=[o(s.shift())];if(!s.length)return i[0];let a=o(s.pop());for(;s.length;){let c=async l=>this.getNode(await l.address).then(async u=>u._getAllEntries(n));i.push(c(s.shift()))}return i.push(a),Promise.all(i).then(c=>c.flat())}async transaction(e,t={}){t={codec:this.codec,hasher:this.hasher,getNode:this.getNode,compare:this.compare,cache:this.cache,...t};let n={chunker:this.chunker,opts:t},s=this.entryList.findMany(e,t.compare,!0,this.isLeaf);return this.isLeaf?await this.transactionLeaf(e,t,n,s):await this.transactionBranch(e,t,n,s)}async transactionLeaf(e,t,n,s){let{LeafClass:o,LeafEntryClass:i}=t,{entries:a,previous:c}=this.processLeafEntries(e,s,i,t),l={...n,entries:a,NodeClass:o,distance:0},u=await r.from(l);return{nodes:u,previous:c,blocks:await Promise.all(u.map(async f=>{let p=await f.encode();return this.cache.set(f),{block:p,node:f}})),distance:0}}processLeafEntries(e,t,n,s){let o=[],i=[],a={},c=new Map;for(let{key:f,del:p,value:h}of e){let m=Qk(f);p?typeof a[m]>"u"&&c.set(m,null):(a[m]={key:f,value:h},c.delete(m))}i=[...this.entryList.entries];for(let[f,[p]]of t){o.push(p);let h=Qk(p.key);c.has(h)?c.set(h,f):(i[f]=new n(a[h],s),delete a[h])}let l=0;for(let[,f]of c)f!==null&&i.splice(f-l++,1);let u=Object.values(a).map(f=>new n(f,s));return i=i.concat(u).sort(({key:f},{key:p})=>s.compare(f,p)),{entries:i,previous:o}}async transactionBranch(e,t,n,s){let{BranchClass:o,BranchEntryClass:i}=t,a=0;for(let[m,[d,y]]of s){let g=this.getNode(await d.address).then(b=>b.transaction(y.reverse(),{...t,sorted:!0})).then(b=>({entry:d,keys:y,distance:a,...b}));s.set(m,g)}let c=[...this.entryList.entries],l={previous:[],blocks:[],nodes:[]};for(let[m,d]of s){let{nodes:y,previous:g,blocks:b,distance:x}=await d;a=x,c[m]=y,g.length&&(l.previous=l.previous.concat(g)),b.length&&(l.blocks=l.blocks.concat(b)),y.length&&(l.nodes=l.nodes.concat(y))}c=c.flat();let u=await this.handlePrepend(c,t,n,l,a);a++;let f=async m=>{if(m.isEntry)return m;let d=await m.encode();return l.blocks.push({block:d,node:m}),this.cache.set(m),new i(m,t)};c=await Promise.all(u.map(f));let p={...n,entries:c,NodeClass:o,distance:a},h=await r.from(p);return await Promise.all(h.map(async m=>{let d=await m.encode();l.blocks.push({block:d,node:m}),this.cache.set(m)})),l.nodes=h,{...l,distance:a}}async handlePrepend(e,t,n,s,o){let{BranchClass:i,LeafClass:a}=t,c=[],l=null;for(let u of e)if(l){let f=await this.mergeFirstLeftEntries(u,l,n,s,o);l=null;let p=f[0].address?i:a,h={...n,entries:f.sort(({key:d},{key:y})=>t.compare(d,y)),NodeClass:p,distance:o},m=await r.from(h);m[m.length-1].closed||(l=m.pop()),m.length&&(c=c.concat(m))}else!u.isEntry&&!u.closed?l=u:c.push(u);return l&&c.push(l),c}async getNodeFirstFromBlocks(e,t){for(let{block:n,node:s}of e)if(await n.cid===t)return s;return await this.getNode(t)}async mergeFirstLeftEntries(e,t,n,s,o){let i=n.opts,{LeafClass:a,BranchClass:c,BranchEntryClass:l}=i;if(e.isEntry){let h=await e.address;e=await this.getNodeFirstFromBlocks(s.blocks,h)}let u=e.entryList.entries;if(!u.length)throw new Error("unreachable no entries");let f=(h,m)=>h.concat(m),p=async(h,m,d)=>await Promise.all(h.map(async y=>(m.blocks.push({block:await y.encode(),node:y}),this.cache.set(y),new l({key:y.key,address:await y.address},d))));if(u[0].constructor.name===t.entryList.entries[0].constructor.name)return await f(t.entryList.entries,u);{let h=u.shift();if(!h)throw new Error("unreachable no left entry");if(!h.address)throw new Error("unreachable existing leaf, no leftEntry.address");let m=await this.mergeFirstLeftEntries(h,t,n,s,o-1),d=u.shift();if(!d)return m;if(!d.address)throw new Error("unreachable existing leaf, no esf.address");let y=await this.getNodeFirstFromBlocks(s.blocks,await d.address);if(y.entryList.entries[0].address){if(m[0].address)return m.concat(y.entryList.entries);{let g=await r.from({...n,entries:m.sort(({key:S},{key:T})=>i.compare(S,T)),NodeClass:a,distance:o}),b=await p(g,s,i),x=await r.from({...n,entries:[...y.entryList.entries,...b,...u].sort(({key:S},{key:T})=>i.compare(S,T)),NodeClass:c,distance:o});return await p(x,s,i)}}else{let g=await f(m,y.entryList.entries),b=await r.from({...n,entries:g.sort(({key:k},{key:S})=>i.compare(k,S)),NodeClass:a,distance:o}),x=await p(b,s,i);return await f(x,u)}}}async bulk(e,t={},n=!0){let{BranchClass:s}=t;t={codec:this.codec,hasher:this.hasher,getNode:this.getNode,compare:this.compare,cache:this.cache,...t},t.sorted||(e=nC(e,t),t.sorted=!0);let o={chunker:this.chunker,opts:t},i=await this.transaction(e,t);for(;i.nodes.length>1;){let a=i.nodes[0].distance+1,c=await Promise.all(i.nodes.map(async u=>{let f=await u.encode();return i.blocks.push({block:f,node:u}),this.cache.set(u),new t.BranchEntryClass(u,t)})),l=await r.from({...o,entries:c,NodeClass:s,distance:a});await Promise.all(l.map(async u=>{let f=await u.encode();this.cache.set(u),i.blocks.push({block:f,node:u})})),i.nodes=l}return i.root=i.nodes[0],n&&i.root&&await aC(this,i,e,o),i.blocks=i.blocks.map(({block:a})=>a),i}static async from({entries:e,chunker:t,NodeClass:n,distance:s,opts:o}){if(!e.every(c=>c.constructor.name===e[0].constructor.name))throw new Error("all entries must be of the same type");let i=[],a=[];for(let c of e)a.push(c),await t(c,s)&&(i.push(new Cs({entries:a,closed:!0})),a=[]);return a.length&&i.push(new Cs({entries:a,closed:!1})),i.map(c=>new n({entryList:c,chunker:t,distance:s,...o}))}},Yc=class extends Br{constructor({codec:e,hasher:t,block:n,...s}){super(s),this.codec=e,this.hasher=t,n?(this.block=n,this.address=n.cid):(this.block=this.encode(),this.address=this.block.then(o=>o.cid))}async get(e){let{result:t,cids:n}=await this.getEntry(e);return{result:t.key,cids:n}}async encode(){if(this.block)return this.block;let e=await this.encodeNode(),t={codec:this.codec,hasher:this.hasher,value:e};return this.block=await Jn(t),this.block}},Xc=class extends Yc{async encodeNode(){let{entries:e}=this.entryList,t=async s=>{if(!s.address)throw new Error("entry.address required");return[s.key,await s.address]},n=await Promise.all(e.map(t));return{branch:[this.distance,n],closed:this.closed}}get isBranch(){return!0}},Zc=class extends Yc{async encodeNode(){return{leaf:await Promise.all(this.entryList.entries.map(async t=>await t.encodeNode())),closed:this.closed}}get isLeaf(){return!0}},Yk=async function*(r){let{LeafClass:e,LeafEntryClass:t,BranchClass:n,BranchEntryClass:s,list:o,chunker:i,compare:a,...c}=r;o=o.map(f=>new t(f,c)),c.compare=a;let l=await Br.from({entries:o,chunker:i,NodeClass:e,distance:0,opts:c});yield*l;let u=1;for(;l.length>1;){let f=async h=>new s({key:h.key,address:await h.address},c),p=await Promise.all(l.map(f));l=await Br.from({entries:p,chunker:i,NodeClass:n,distance:u,opts:c}),yield*l,u++}};var el=class extends Qc{async identity(){let e=await this.codec.encode(await this.encodeNode()),t=await this.hasher.encode(e);return Jk(t)}},ln=class extends el{constructor(e,t){super(e,t),this.value=e.value}encodeNode(){return[this.key,this.value]}},un=class extends el{constructor(e,t){if(!e.address)throw new Error("Cannot create MapBranchEntry without address");super(e,t)}async encodeNode(){return[this.key,await this.address]}},Xk=async(r,e)=>{let{result:t,cids:n}=await r.getEntry(e);return{result:t.value,cids:n}},Zk=async(r,e)=>{let{result:t,cids:n}=await r.getEntries(e);return{result:t.map(s=>s.value),cids:n}},fn=class extends Zc{get(e){return Xk(this,e)}getMany(e){return Zk(this,e)}bulk(e,t={},n=!0){return super.bulk(e,{...eS,...t},n)}},hn=class extends Xc{get(e){return Xk(this,e)}getMany(e){return Zk(this,e)}bulk(e,t={},n=!0){return super.bulk(e,{...eS,...t},n)}},eS={LeafClass:fn,LeafEntryClass:ln,BranchClass:hn,BranchEntryClass:un},tS=(r,e,t,n,s,o,i)=>{let a=i.LeafClass||fn,c=i.LeafEntryClass||ln,l=i.BranchClass||hn,u=i.BranchEntryClass||un,f=async h=>e.has(h)?e.get(h):r(h).then(m=>p(m)),p=cC({chunker:t,cache:e,getNode:f,codec:n,hasher:s,compare:o,LeafEntryClass:c,LeafClass:a,BranchEntryClass:u,BranchClass:l});return f},rS=({get:r,cache:e,chunker:t,list:n,codec:s,hasher:o,sorted:i,compare:a,...c})=>{i||(n=n.sort(({key:f},{key:p})=>a(f,p)));let l=tS(r,e,t,s,o,a,c),u={list:n,codec:s,hasher:o,chunker:t,getNode:l,sorted:i,compare:a,cache:e,LeafClass:c.LeafClass||fn,LeafEntryClass:c.LeafEntryClass||ln,BranchClass:c.BranchClass||hn,BranchEntryClass:c.BranchEntryClass||un};return Yk(u)},nS=({cid:r,get:e,cache:t,chunker:n,codec:s,hasher:o,compare:i,...a})=>tS(e,t,n,s,o,i,a)(r);function cC({chunker:r,cache:e,getNode:t,codec:n,hasher:s,compare:o,LeafEntryClass:i,LeafClass:a,BranchEntryClass:c,BranchClass:l}){let u={codec:n,hasher:s};return f=>{let{value:p}=f,h={chunker:r,cache:e,block:f,getNode:t,codec:n,hasher:s,compare:o},m,d;if(p.leaf)m=p.leaf.map(([b,x])=>new i({key:b,value:x},u)),d=a;else if(p.branch){let[b,x]=p.branch;h.distance=b,m=x.map(([k,S])=>new c({key:k,address:S},u)),d=l}else throw new Error("Unknown block data, does not match schema");let y=new Cs({entries:m,closed:p.closed}),g=new d({entryList:y,...h});return e.set(g),g}}var lC=(r,e)=>{let[t,n]=r,[s,o]=e,i=cn(t,s);return i!==0?i:uC(n,o)},uC=(r,e)=>{if(Number.isNaN(r))return-1;if(Number.isNaN(e))throw new Error("ref may not be Infinity or NaN");return Number.isFinite(r)?cn(r,e):1},sS=async(r,e)=>{let t=[e,NaN],n=[e,1/0],{result:s,cids:o}=await r.getRangeEntries(t,n);return{result:s.map(i=>{let[a,c]=i.key;return{id:c,key:a,row:i.value}}),cids:o}},oS=async(r,e,t)=>{e=[e,NaN],t=[t,1/0];let{result:n,cids:s}=await r.getRangeEntries(e,t);return{result:n.map(i=>{let[a,c]=i.key;return{id:c,key:a,row:i.value}}),cids:s}},Gd=class extends fn{get(e){return sS(this,e)}range(e,t){return oS(this,e,t)}bulk(e,t={},n=!0){return super.bulk(e,{...Qd,...t},n)}},Jd=class extends hn{get(e){return sS(this,e)}range(e,t){return oS(this,e,t)}bulk(e,t={},n=!0){return super.bulk(e,{...Qd,...t},n)}},fC=Gd,hC=Jd,Qd={LeafClass:fC,BranchClass:hC,LeafEntryClass:ln,BranchEntryClass:un},iS={...Qd,compare:lC},aS=r=>(r={...iS,...r},rS(r)),Yd=r=>(r={...iS,...r},nS(r));var Xd={has:()=>!1,get:()=>{throw new Error("Cannot ask for entries from nocache")},set:()=>{}};var pn=class{};function pC(r,e){if(Number.isNaN(r))return-1;if(Number.isNaN(e))throw new Error("ref may not be Infinity or NaN");return r===1/0?1:cn(r,e)}function mC(r,e){let[t,n]=r,[s,o]=e,i=cn(t,s);return i!==0?i:pC(n,o)}var ep={cache:Xd,chunker:qd(30),codec:re,hasher:Q,compare:mC},tp={cache:Xd,chunker:qd(30),codec:re,hasher:Q,compare:cn};function cS(r,e){let t=[];return r.forEach(({id:n,value:s,del:o})=>{if(o||!s)return;let i=!1,a=e({...s,_id:n},(c,l)=>{i=!0,!(typeof c>"u")&&t.push({key:[dn.default.encode(c),n],value:l||null})});!i&&a&&t.push({key:[dn.default.encode(a),n],value:null})}),t}function Zd(r){return async e=>{let t=await r.get(e);if(!t)throw new Error(`Missing block ${e.toString()}`);let{cid:n,bytes:s}=t;return Iu({cid:n,bytes:s,hasher:Q,codec:re})}}async function rp(r,e,t,n){if(!t.length)return e;if(!e.root)if(e.cid)e.root=await Yd({cid:e.cid,get:Zd(r),...n});else{let i,a;for await(let c of await aS({get:Zd(r),list:t,...n})){let l=await c.block;await r.put(l.cid,l.bytes),i=l,a=c}if(!a||!i)throw new Error("failed to create index");return{root:a,cid:i.cid}}let{root:s,blocks:o}=await e.root.bulk(t);if(s){for await(let i of o)await r.put(i.cid,i.bytes);return{root:s,cid:(await s.block).cid}}else return{root:void 0,cid:void 0}}async function np(r,e,t){return await Yd({cid:e,get:Zd(r),...t})}async function mn(r,e,t){return t.descending&&(e.result=e.result.reverse()),t.limit&&(e.result=e.result.slice(0,t.limit)),t.includeDocs&&(e.result=await Promise.all(e.result.map(async n=>{let s=await r.get(n.id),o=s?{...s.doc,_id:n.id}:void 0;return{...n,doc:o}}))),{rows:e.result.map(({key:n,...s})=>({key:dn.default.decode(n),...s}))}}function sp(r){return[dn.default.encode(r[0]),dn.default.encode(r[1])]}function op(r){return dn.default.encode(r)}ye();function Ls(r,{_crdt:e},t,n,s){if(n&&s)throw e.logger.Error().Msg("cannot provide both mapFn and meta").AsError();if(n&&n.constructor.name!=="Function")throw e.logger.Error().Msg("mapFn must be a function").AsError();if(e.indexers.has(t))e.indexers.get(t).applyMapFn(t,n,s);else{let o=new tl(r,e,t,n,s);e.indexers.set(t,o)}return e.indexers.get(t)}var tl=class{constructor(e,t,n,s,o){this.mapFnString="";this.byKey=new pn;this.byId=new pn;this.includeDocsDefault=!1;if(this.logger=H(e,"Index"),this.blockstore=t.indexBlockstore,this.crdt=t,this.applyMapFn(n,s,o),this.name=n,!(this.mapFnString||this.initError))throw this.logger.Error().Msg("missing mapFnString").AsError()}ready(){return Promise.all([this.blockstore.ready(),this.crdt.ready()]).then(()=>{})}close(){return Promise.all([this.blockstore.close(),this.crdt.close()]).then(()=>{})}destroy(){return Promise.all([this.blockstore.destroy(),this.crdt.destroy()]).then(()=>{})}applyMapFn(e,t,n){if(t&&n)throw this.logger.Error().Msg("cannot provide both mapFn and meta").AsError();if(this.name&&this.name!==e)throw this.logger.Error().Msg("cannot change name").AsError();this.name=e;try{if(n){if(this.indexHead&&this.indexHead.map(o=>o.toString()).join()!==n.head.map(o=>o.toString()).join())throw this.logger.Error().Msg("cannot apply different head meta").AsError();this.mapFnString?this.mapFnString!==n.map?this.logger.Warn().Msg(`cannot apply different mapFn meta: old mapFnString ${this.mapFnString} new mapFnString ${n.map}`):(this.byId.cid=n.byId,this.byKey.cid=n.byKey,this.indexHead=n.head):(this.mapFnString=n.map,this.byId.cid=n.byId,this.byKey.cid=n.byKey,this.indexHead=n.head)}else if(this.mapFn){if(t&&this.mapFn.toString()!==t.toString())throw this.logger.Error().Msg("cannot apply different mapFn app2").AsError()}else{if(t||(t=o=>o[e]??void 0),this.mapFnString){if(this.mapFnString!==t.toString())throw this.logger.Error().Str("mapFnString",this.mapFnString).Str("mapFn",t.toString()).Msg("cannot apply different mapFn app").AsError()}else this.mapFnString=t.toString();this.mapFn=t}let s=/=>\s*(.*)/.test(this.mapFnString);this.includeDocsDefault=s}catch(s){this.initError=s}}async query(e={}){if(await this.ready(),await this._updateIndex(),await this._hydrateIndex(),!this.byKey.root)return await mn(this.crdt,{result:[]},e);if(this.includeDocsDefault&&e.includeDocs===void 0&&(e.includeDocs=!0),e.range){let n=sp(e.range);return await mn(this.crdt,await me(this.byKey.root).range(n[0],n[1]),e)}if(e.key){let n=op(e.key);return await mn(this.crdt,await me(this.byKey.root).get(n),e)}if(Array.isArray(e.keys))return{rows:(await Promise.all(e.keys.map(async s=>{let o=op(s);return(await mn(this.crdt,await me(this.byKey.root).get(o),e)).rows}))).flat()};if(e.prefix){Array.isArray(e.prefix)||(e.prefix=[e.prefix]);let n=[...e.prefix,NaN],s=[...e.prefix,1/0],o=sp([n,s]);return await mn(this.crdt,await this.byKey.root.range(...o),e)}let t=await this.byKey.root.getAllEntries();return await mn(this.crdt,{result:t.result.map(({key:[n,s],value:o})=>({key:n,id:s,value:o}))},e)}_resetIndex(){this.byId=new pn,this.byKey=new pn,this.indexHead=void 0}async _hydrateIndex(){this.byId.root&&this.byKey.root||!this.byId.cid||!this.byKey.cid||(this.byId.root=await np(this.blockstore,this.byId.cid,tp),this.byKey.root=await np(this.blockstore,this.byKey.cid,ep))}async _updateIndex(){if(await this.ready(),this.initError)throw this.initError;if(!this.mapFn)throw this.logger.Error().Msg("No map function defined").AsError();let e,t;!this.indexHead||this.indexHead.length===0?{result:e,head:t}=await this.crdt.allDocs():{result:e,head:t}=await this.crdt.changes(this.indexHead),e.length===0&&(this.indexHead=t);let n=[],s=[];if(this.byId.root){let l=e.map(({id:f})=>f),{result:u}=await this.byId.root.getMany(l);n=u.map(f=>({key:f,del:!0})),s=u.map(f=>({key:f[1],del:!0}))}let o=cS(e,this.mapFn),i=o.map(({key:l})=>({key:l[1],value:l})),a={indexes:new Map};for(let[l,u]of this.crdt.indexers)u.indexHead&&a.indexes?.set(l,{byId:u.byId.cid,byKey:u.byKey.cid,head:u.indexHead,map:u.mapFnString,name:u.name});if(e.length===0)return a;let{meta:c}=await this.blockstore.transaction(async l=>{if(this.byId=await rp(l,this.byId,s.concat(i),tp),this.byKey=await rp(l,this.byKey,n.concat(o),ep),this.indexHead=t,this.byId.cid&&this.byKey.cid){let u={byId:this.byId.cid,byKey:this.byKey.cid,head:t,map:this.mapFnString,name:this.name};a.indexes?.set(this.name,u)}return a});return c}};ae();function lS(r,e){let t=[],n=!1;async function*s(){if(n||t.length===0)return;n=!0;let o=[];try{for(;t.length>0;){t.sort((a,c)=>c.updates?1:-1);let i=t.shift();if(i&&(await r(i.newHead,i.prevHead,i.updates!==void 0).catch(a=>{throw e.Error().Err(a).Msg("int_applyHead worker error").AsError()}),i.updates&&o.push(...i.updates),!t.some(a=>a.updates)||i.updates)){let a=t.every(c=>c.updates!==null);yield{updates:o,all:a},o.length=0}}}finally{n=!1;let i=s(),a=await i.next();for(;!a.done;)a=await i.next()}}return{push(o){return t.push(o),s()},size(){return t.length}}}ye();var rl=class{constructor(e){this.head=[];this.zoomers=new Set;this.watchers=new Set;this.emptyWatchers=new Set;this._ready=new X;this.blockstore=e,this.logger=H(e.sthis,"CRDTClock"),this.applyHeadQueue=lS(this.int_applyHead.bind(this),this.logger)}async ready(){return this._ready.once(async()=>{await this.blockstore.ready()})}async close(){await this.blockstore.close()}setHead(e){this.head=e}async applyHead(e,t,n){for await(let{updates:s,all:o}of this.applyHeadQueue.push({newHead:e,prevHead:t,updates:n}))return this.processUpdates(s,o,t)}async processUpdates(e,t,n){let s=e;this.watchers.size&&!t&&(s=(await wi(me(this.blockstore),this.head,n,{},this.logger)).result),this.zoomers.forEach(o=>o()),this.notifyWatchers(s||[])}notifyWatchers(e){this.emptyWatchers.forEach(t=>t()),this.watchers.forEach(t=>t(e||[]))}onTick(e){this.watchers.add(e)}onTock(e){this.emptyWatchers.add(e)}onZoom(e){this.zoomers.add(e)}async int_applyHead(e,t,n){let s=!n,o=ip(this.head);if(e=ip(e),uS(o,e))return;let i=ip(t);if(uS(o,i)){this.setHead(e);return}if(!this.blockstore)throw this.logger.Error().Msg("missing blockstore").AsError();await yC(this.logger,e,this.blockstore),this.transaction||(this.transaction=this.blockstore.openTransaction({noLoader:s,add:!1}));let a=this.transaction,c=await gC(this.logger,e,a,this.head),l=await yr(a,c);for(let{cid:u,bytes:f}of[...l.additions])a.putSync(u,f);s||(await this.blockstore.commitTransaction(a,{head:c},{add:!1,noLoader:s}),this.transaction=void 0),this.setHead(c)}};function ip(r){return r.sort((e,t)=>e.toString().localeCompare(t.toString()))}async function yC(r,e,t){if(!t)throw r.Error().Msg("missing blockstore");e.map(async n=>{if(!await t.get(n))throw r.Error().Str("cid",n.toString()).Msg("int_applyHead missing block").AsError()})}function uS(r,e){return r.toString()===e.toString()}async function gC(r,e,t,n){for(let s of e)try{n=await Hr(t,n,s)}catch(o){r.Debug().Err(o).Msg("failed to advance head");continue}return n}ye();var bi=class{constructor(e,t,n={}){this.indexers=new Map;this.onceReady=new X;this.sthis=e,this.name=t,this.logger=H(e,"CRDT"),this.opts=n,this.blockstore=Zh(e,{name:t,applyMeta:async s=>{let o=s;if(!o.head)throw this.logger.Error().Msg("missing head").AsError();await this.clock.applyHead(o.head,[])},compact:async s=>(await Kk(s,this.clock.head,this.logger),{head:this.clock.head}),autoCompact:this.opts.autoCompact||100,store:{...this.opts.store,isIndex:void 0},public:this.opts.public,meta:this.opts.meta,threshold:this.opts.threshold}),this.indexBlockstore=Zh(e,{name:t,applyMeta:async s=>{let o=s;if(!o.indexes)throw this.logger.Error().Msg("missing indexes").AsError();for(let[i,a]of Object.entries(o.indexes))Ls(this.sthis,{_crdt:this},i,void 0,a)},store:{...this.opts.store,isIndex:this.opts.store?.isIndex||"idx"},public:this.opts.public}),this.clock=new rl(this.blockstore),this.clock.onZoom(()=>{for(let s of this.indexers.values())s._resetIndex()})}async bulk(e){await this.ready();let t=[...this.clock.head],n=await this.blockstore.transaction(async s=>{let{head:o}=await Rk(this.blockstore.ebOpts.storeRuntime,s,this.clock.head,e,this.logger);return e=e.map(i=>(Hd(this.blockstore,{doc:i.value}),i)),{head:o}});return await this.clock.applyHead(n.meta.head,t,e),n.meta}async ready(){return this.onceReady.once(async()=>{try{await Promise.all([this.blockstore.ready(),this.indexBlockstore.ready(),this.clock.ready()])}catch(e){throw this.logger.Error().Err(e).Msg("CRDT is not ready").AsError()}})}async close(){await Promise.all([this.blockstore.close(),this.indexBlockstore.close(),this.clock.close()])}async destroy(){await Promise.all([this.blockstore.destroy(),this.indexBlockstore.destroy()])}async allDocs(){await this.ready();let e=[];for await(let t of Vd(this.blockstore,this.clock.head,this.logger))e.push(t);return{result:e,head:this.clock.head}}async vis(){await this.ready();let e=[];for await(let t of $k(this.blockstore,this.clock.head))e.push(t);return e.join(`
148
+ `)}async getBlock(e){return await this.ready(),await zk(this.blockstore,e)}async get(e){await this.ready();let t=await Fk(this.blockstore,this.clock.head,e,this.logger);if(!t.del)return t}async changes(e=[],t={}){return await this.ready(),await wi(this.blockstore,this.clock.head,e,t,this.logger)}async compact(){return await this.blockstore.compact()}};ye();var Bs=class{constructor(e,t){this.opts={};this._listening=!1;this._listeners=new Set;this._noupdate_listeners=new Set;this._ready=new X;this.name=e,this.opts=t||this.opts,this.sthis=Xo(this.opts),this.logger=H(this.sthis,"Database"),this._crdt=new bi(this.sthis,e,this.opts),this.blockstore=this._crdt.blockstore,this._writeQueue=yy(async n=>await this._crdt.bulk(n)),this._crdt.clock.onTock(()=>{this._no_update_notify()})}static{this.databases=new Map}async close(){await this.ready(),await this._crdt.close(),await this.blockstore.close()}async destroy(){await this.ready(),await this._crdt.destroy(),await this.blockstore.destroy()}async ready(){return this._ready.once(async()=>{await this.sthis.start(),await this._crdt.ready(),await this.blockstore.ready()})}async get(e){if(!e)throw this.logger.Error().Str("db",this.name).Msg("Doc id is required").AsError();await this.ready(),this.logger.Debug().Str("id",e).Msg("get");let t=await this._crdt.get(e).catch(s=>{throw new Dt(`Not found: ${e} - ${s.message}`)});if(!t)throw new Dt(`Not found: ${e}`);let{doc:n}=t;return{...n,_id:e}}async put(e){await this.ready(),this.logger.Debug().Str("id",e._id).Msg("put");let{_id:t,...n}=e,s=t||this.sthis.timeOrderedNextId().str,o=await this._writeQueue.push({id:s,value:{...n,_id:s}});return{id:s,clock:o?.head,name:this.name}}async del(e){await this.ready(),this.logger.Debug().Str("id",e).Msg("del");let t=await this._writeQueue.push({id:e,del:!0});return{id:e,clock:t?.head,name:this.name}}async changes(e=[],t={}){await this.ready(),this.logger.Debug().Any("since",e).Any("opts",t).Msg("changes");let{result:n,head:s}=await this._crdt.changes(e,t);return{rows:n.map(({id:i,value:a,del:c,clock:l})=>({key:i,value:c?{_id:i,_deleted:!0}:{_id:i,...a},clock:l})),clock:s,name:this.name}}async allDocs(e={}){await this.ready(),this.logger.Debug().Msg("allDocs");let{result:t,head:n}=await this._crdt.allDocs();return{rows:t.map(({id:o,value:i,del:a})=>({key:o,value:a?{_id:o,_deleted:!0}:{_id:o,...i}})),clock:n,name:this.name}}async allDocuments(){return this.allDocs()}subscribe(e,t){return this.logger.Debug().Bool("updates",t).Msg("subscribe"),t?(this._listening||(this._listening=!0,this._crdt.clock.onTick(n=>{this._notify(n)})),this._listeners.add(e),()=>{this._listeners.delete(e)}):(this._noupdate_listeners.add(e),()=>{this._noupdate_listeners.delete(e)})}async query(e,t={}){await this.ready(),this.logger.Debug().Any("field",e).Any("opts",t).Msg("query");let n=this._crdt;return await(typeof e=="string"?Ls(this.sthis,{_crdt:n},e):Ls(this.sthis,{_crdt:n},bC(e.toString()),e)).query(t)}async compact(){await this.ready(),await this._crdt.compact()}async _notify(e){if(await this.ready(),this._listeners.size){let t=e.map(({id:n,value:s})=>({...s,_id:n}));for(let n of this._listeners)await(async()=>await n(t))().catch(s=>{this.logger.Error().Err(s).Msg("subscriber error")})}}async _no_update_notify(){if(await this.ready(),this._noupdate_listeners.size)for(let e of this._noupdate_listeners)await(async()=>await e([]))().catch(t=>{this.logger.Error().Err(t).Msg("subscriber error")})}};function fS(r){return r?Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({[e]:t})):[]}function wC(r,e){let t=JSON.stringify(fS({name:r,stores:fS(e?.store?.stores)})),n=Bs.databases.get(t);return n||(n=new Bs(r,e),Bs.databases.set(t,n)),n}function bC(r){let e=/\(([^,()]+,\s*[^,()]+|\[[^\]]+\],\s*[^,()]+)\)/g,t=null;return Array.from(r.matchAll(e),s=>s[1].trim()).length===0&&(t=/=>\s*{?\s*([^{}]+)\s*}?/.exec(r),t&&t[1].includes("return")&&(t=null)),t?t[1]:r}var nl={};K(nl,{FILESTORE_VERSION:()=>Cr,INDEXDB_VERSION:()=>Vc,files:()=>zh,getFileName:()=>ui,getFileSystem:()=>li,getPath:()=>tn,kb:()=>fd,kc:()=>bd,mf:()=>ap,runtimeFn:()=>Or});fi();var ap={};K(ap,{block:()=>Cu,codec:()=>hS});var hS={};ae();Td();Ld();ye();var xC=Object.keys({"0.19.115":"xxxx"})[0];return wS(kC);})();
149
149
  //# sourceMappingURL=index.global.js.map