@wovin/connect-nftstorage 0.1.33 → 0.1.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -58,7 +58,7 @@ ${p}`),J.pop(),`{${j}}`}case"number":return isFinite(V)?String(V):F?F(V):"null";
|
|
|
58
58
|
`+" ".repeat(--t)+o:o===","&&n===0?r+=o+`
|
|
59
59
|
`+" ".repeat(t):o==="{"&&n===0?(n++,r+=o+`
|
|
60
60
|
`+" ".repeat(t+1)):o==="}"&&n===1?(n--,r+=`
|
|
61
|
-
`+" ".repeat(t)+o):o==="{"&&n>0?(n++,r+=o):(o==="}"&&n>1&&n--,r+=o)}return r}function xk(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]instanceof qn){if(t[r]!==e[r])return!1}else if(!Je.structural(e[r],t[r]))return!1;return!0}var{WARN:Of,LOG:yC,DEBUG:Ok,VERBOSE:gC,ERROR:en}=Ae.setup(Ae.INFO,{prefix:"[thread]"});function Kr(e){return e.init!==void 0}var qn=class{constructor(e,t,r,n=[],i={}){this.name=e,this._applogs=n,this.parents=t===null?null:Xo(t),this.filters=r,Le(()=>this.parents?.length===0)&&Of("[Thread] empty parents array",e),i.skipObservable||li(this,{applogsCids:Fe,applogsCidSet:Fe,applogsByCid:Fe,insert:mt,size:Fe,isEmpty:Fe,firstLog:Fe,latestLog:Fe},{name:`Thread{${e}}`})}filters;parents;_subscribers=[];get readOnly(){return this.parents.length!==1?!0:this.parents[0].readOnly}insert(e){if(this.readOnly)throw en("[Thread] insert() called on read-only thread:",this.nameAndSizeUntracked);if(!this.parents)throw en("[Thread] insert() called on non-writable thread without parents:",this.nameAndSizeUntracked);if(this.parents?.length!==1)throw en("[Thread] insert() called on thread with multiple parents:",this.nameAndSizeUntracked);return this.parents[0].insert(e)}insertRaw(e){if(this.readOnly)throw en("[Thread] insertRaw() called on read-only thread:",this.nameAndSizeUntracked);if(!this.parents)throw en("[Thread] insertRaw() called on non-writable thread without parents:",this.nameAndSizeUntracked);if(this.parents?.length!==1)throw en("[Thread] insertRaw() called on thread with multiple parents:",this.nameAndSizeUntracked);return this.parents[0].insertRaw(e)}subscribe(e){return this._subscribers.push(e),this.unsubscribe.bind(this,e)}unsubscribe(e){let t=this._subscribers.indexOf(e);t!==-1?this._subscribers.splice(t,1):Of("unsubscribe called for non-existent",e)}notifySubscribers(e){Ok(`[thread: ${this.name}] notifying`,this._subscribers.length,"subscribers of",{...e,subs:this._subscribers});for(let t of this._subscribers)t(e)}get applogs(){return this._applogs}get applogsCids(){return this._applogs.map(e=>e.cid)}get applogsCidSet(){return new Set(this._applogs.map(e=>e.cid))}map(e){return this.applogs.map(e)}get findLast(){return this.applogs.findLast.bind(this.applogs)}get findFirst(){return this.applogs.find.bind(this.applogs)}get firstLog(){return this.applogs[0]}get latestLog(){return this.applogs[this.applogs.length-1]}hasApplog(e,t){if(t)return this.applogs.includes(e);if(!e.cid)throw en("[hasApplogs] applog without CID:",e);return this.hasApplogCid(e.cid)}hasApplogCid(e){return this.applogsCidSet.has(e.toString())}get applogsByCid(){return new Map(this.applogs.map(e=>[e.cid,e]))}getApplog(e){return this.applogsByCid.get(e.toString())}hasApplogWithDiffTs(e){return this.applogs.find(t=>t.en===e.en&&t.at===e.at&&t.vl===e.vl&&t.ag===e.ag)}get isEmpty(){return this.size===0}get size(){return this.applogs.length}get length(){return this.applogs.length}get untrackedSize(){return Le(()=>this.size)}get nameAndSizeUntracked(){return Le(()=>`${this.name} (${this.size})`)}get prettyName(){return Ek(this.name)}get hasParents(){return!!this.parents?.length}},Ak=class Ih extends qn{static fromArray(t,r){return new Ih(r||"static",null,[],t)}constructor(t,r,n,i){super(t,r,n,i,{skipObservable:!0})}get readOnly(){return!0}},Sk={};ti(Sk,{code:()=>$h,decode:()=>Pl,encode:()=>Ul,format:()=>Af,name:()=>Bk,parse:()=>Fk,stringify:()=>Af});var Ik=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(I.equals(t.type,I.array)&&(t.elements++,t.elements!==1&&e.push([44])),I.equals(t.type,I.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[I.uint.major](e,t){this.prefix(e);let r=String(t.value),n=[];for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);e.push(n)}[I.negint.major](e,t){this[I.uint.major](e,t)}[I.bytes.major](e,t){throw new Error(`${on} unsupported type: Uint8Array`)}[I.string.major](e,t){this.prefix(e);let r=Od(JSON.stringify(t.value));e.push(r.length>32?Ba(r):r)}[I.array.major](e,t){this.prefix(e),this.inRecursive.push({type:I.array,elements:0}),e.push([91])}[I.map.major](e,t){this.prefix(e),this.inRecursive.push({type:I.map,elements:0}),e.push([123])}[I.tag.major](e,t){}[I.float.major](e,t){if(t.type.name==="break"){let o=this.inRecursive.pop();if(o){if(I.equals(o.type,I.array))e.push([93]);else if(I.equals(o.type,I.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(`${on} 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 r=String(t.value),n=[],i=!1;for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o),!i&&(n[o]===46||n[o]===101||n[o]===69)&&(i=!0);i||(n.push(46),n.push(48)),e.push(n)}};function kk(e,t){if(Array.isArray(e[0])||Array.isArray(t[0]))throw new Error(`${on} complex map keys are not supported`);let r=e[0],n=t[0];if(r.type!==I.string||n.type!==I.string)throw new Error(`${on} non-string map keys are not supported`);if(r<n)return-1;if(r>n)return 1;throw new Error(`${on} unexpected duplicate map keys, this is not supported`)}var $k={addBreakTokens:!0,mapSorter:kk};function Nk(e,t){return t=Object.assign({},$k,t),Bd(e,new Ik,t)}var kh=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(`${be} 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(`${be} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,r=!1,n=a=>{for(;!this.done();){let s=this.ch();if(a.includes(s))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,r=!0;else return new ne(I.uint,0,this._pos-e);if(n([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${be} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(r)throw new Error(`${be} unexpected token at position ${this._pos}`);r=!0,this._pos++,n([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(r=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,n([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),o=parseFloat(i);return r?new ne(I.float,o,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(o)?new ne(o>=0?I.uint:I.negint,o,this._pos-e):new ne(o>=0?I.uint:I.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${be} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,o=0;i<this.data.length&&o<65536;i++,o++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let s=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new ne(I.string,s,o)}}let e=this._pos,t=[],r=()=>{if(this._pos+4>=this.data.length)throw new Error(`${be} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let o=0;o<4;o++){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(`${be} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},n=()=>{let i=this.ch(),o=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${be} unexpected unicode sequence at position ${this._pos}`);let s,u,l,f;switch(a){case 1:i<128&&(o=i);break;case 2:s=this.data[this._pos+1],(s&192)===128&&(f=(i&31)<<6|s&63,f>127&&(o=f));break;case 3:s=this.data[this._pos+1],u=this.data[this._pos+2],(s&192)===128&&(u&192)===128&&(f=(i&15)<<12|(s&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:s=this.data[this._pos+1],u=this.data[this._pos+2],l=this.data[this._pos+3],(s&192)===128&&(u&192)===128&&(l&192)===128&&(f=(i&15)<<18|(s&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(o=f))}o===null?(o=65533,a=1):o>65535&&(o-=65536,t.push(o>>>10&1023|55296),o=56320|o&1023),t.push(o),this._pos+=a};for(;!this.done();){let i=this.ch(),o;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${be} unexpected string termination at position ${this._pos}`);switch(o=this.ch(),this._pos++,o){case 34:case 39:case 92:case 47:t.push(o);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(r());break;default:throw new Error(`${be} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new ne(I.string,Av(t),this._pos-e);default:if(i<32)throw new Error(`${be} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):n()}}throw new Error(`${be} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new ne(I.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new ne(I.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new ne(I.null,null,4);case 102:return this.expect([102,97,108,115,101]),new ne(I.false,!1,5);case 116:return this.expect([116,114,117,101]),new ne(I.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(`${be} 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 ne(I.break,void 0,1);if(this.ch()!==44)throw new Error(`${be} 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 ne(I.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 ne(I.break,void 0,1);if(this.ch()!==44)throw new Error(`${be} 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 ne(I.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${be} 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(`${be} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function jk(e,t){return t=Object.assign({tokenizer:new kh(e,t)},t),N0(e,t)}function Ck(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}function Uk(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;let t=Ka.asCID(e);if(!t)return null;let r=t.toString();return[new ne(I.map,1/0,1),new ne(I.string,"/",1),new ne(I.string,r,r.length),new ne(I.break,void 0,1)]}function Ta(e){let t=al.encode(e).slice(1);return[new ne(I.map,1/0,1),new ne(I.string,"/",1),new ne(I.map,1/0,1),new ne(I.string,"bytes",5),new ne(I.string,t,t.length),new ne(I.break,void 0,1),new ne(I.break,void 0,1)]}function Ft(e){return Ta(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}function Pk(e){return Ta(new Uint8Array(e))}function Rk(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Dk(e){if(Number.isNaN(e))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(e===1/0||e===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var Mk={typeEncoders:{Object:Uk,Buffer:Ta,Uint8Array:Ta,Int8Array:Ft,Uint16Array:Ft,Int16Array:Ft,Uint32Array:Ft,Int32Array:Ft,Float32Array:Ft,Float64Array:Ft,Uint8ClampedArray:Ft,BigInt64Array:Ft,BigUint64Array:Ft,DataView:Ft,ArrayBuffer:Pk,undefined:Rk,number:Dk}},Lk=class extends kh{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===I.map){let t=this._next();if(t.type===I.string&&t.value==="/"){let r=this._next();if(r.type===I.string){if(this._next().type!==I.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(r),new ne(I.tag,42,0)}if(r.type===I.map){let n=this._next();if(n.type===I.string&&n.value==="bytes"){let i=this._next();if(i.type===I.string){for(let a=0;a<2;a++)if(this._next().type!==I.break)throw new Error("Invalid encoded Bytes form");let o=al.decode(`m${i.value}`);return new ne(I.bytes,o,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(r)}this.tokenBuffer.push(t)}return e}},fu={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};fu.tags[42]=Ka.parse;var Bk="dag-json",$h=297,Ul=e=>Nk(e,Mk),Pl=e=>{let t=Ck(e),r=Object.assign(fu,{tokenizer:new Lk(t,fu)});return jk(t,r)},Af=e=>Vk.decode(Ul(e)),Vk=new TextDecoder,Fk=e=>Pl(zk.encode(e)),zk=new TextEncoder,Mo=Or({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),mC=Or({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),bC=Or({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),vC=Or({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),wC=Or({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),_C=Or({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),TC=Or({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),EC=Or({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xC=Or({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Pr=Ga({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),OC=Ga({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Nh={};ti(Nh,{Digest:()=>ds,create:()=>Rl,decode:()=>Ch,equals:()=>Uh,hasCode:()=>u$});var qk=jh,Sf=128,Kk=127,Gk=~Kk,Hk=Math.pow(2,31);function jh(e,t,r){t=t||[],r=r||0;for(var n=r;e>=Hk;)t[r++]=e&255|Sf,e/=128;for(;e&Gk;)t[r++]=e&255|Sf,e>>>=7;return t[r]=e|0,jh.bytes=r-n+1,t}var Wk=du,Jk=128,If=127;function du(e,n){var r=0,n=n||0,i=0,o=n,a,s=e.length;do{if(o>=s)throw du.bytes=0,new RangeError("Could not decode varint");a=e[o++],r+=i<28?(a&If)<<i:(a&If)*Math.pow(2,i),i+=7}while(a>=Jk);return du.bytes=o-n,r}var Qk=Math.pow(2,7),Yk=Math.pow(2,14),Xk=Math.pow(2,21),Zk=Math.pow(2,28),e$=Math.pow(2,35),t$=Math.pow(2,42),r$=Math.pow(2,49),n$=Math.pow(2,56),i$=Math.pow(2,63),o$=function(e){return e<Qk?1:e<Yk?2:e<Xk?3:e<Zk?4:e<e$?5:e<t$?6:e<r$?7:e<n$?8:e<i$?9:10},a$={encode:qk,decode:Wk,encodingLength:o$},s$=a$,Ea=s$;function pu(e,t=0){return[Ea.decode(e,t),Ea.decode.bytes]}function xa(e,t,r=0){return Ea.encode(e,t,r),t}function Oa(e){return Ea.encodingLength(e)}function Rl(e,t){let r=t.byteLength,n=Oa(e),i=n+Oa(r),o=new Uint8Array(i+r);return xa(e,o,0),xa(r,o,n),o.set(t,i),new ds(e,r,t,o)}function Ch(e){let t=ol(e),[r,n]=pu(t),[i,o]=pu(t.subarray(n)),a=t.subarray(n+o);if(a.byteLength!==i)throw new Error("Incorrect length");return new ds(r,i,a,t)}function Uh(e,t){if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&Bw(e.bytes,r.bytes)}}var ds=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}};function u$(e,t){return e.code===t}function kf(e,t){let{bytes:r,version:n}=e;switch(n){case 0:return c$(r,hu(e),t??Pr.encoder);default:return f$(r,hu(e),t??Mo.encoder)}}var $f=new WeakMap;function hu(e){let t=$f.get(e);if(t==null){let r=new Map;return $f.set(e,r),r}return t}var or=class lt{code;version;multihash;bytes;"/";constructor(t,r,n,i){this.code=r,this.version=t,this.multihash=n,this.bytes=i,this["/"]=i}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:t,multihash:r}=this;if(t!==Oi)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==d$)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return lt.createV0(r)}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:t,digest:r}=this.multihash,n=Rl(t,r);return lt.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(t){return lt.equals(this,t)}static equals(t,r){let n=r;return n!=null&&t.code===n.code&&t.version===n.version&&Uh(t.multihash,n.multihash)}toString(t){return kf(this,t)}toJSON(){return{"/":kf(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let r=t;if(r instanceof lt)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:o,bytes:a}=r;return new lt(n,i,o,a??Nf(n,i,o.bytes))}else if(r[p$]===!0){let{version:n,multihash:i,code:o}=r,a=Ch(i);return lt.create(n,o,a)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(r!==Oi)throw new Error(`Version 0 CID must use dag-pb (code: ${Oi}) block encoding`);return new lt(t,r,n,n.bytes)}case 1:{let i=Nf(t,r,n.bytes);return new lt(t,r,n,i)}default:throw new Error("Invalid version")}}static createV0(t){return lt.create(0,Oi,t)}static createV1(t,r){return lt.create(1,t,r)}static decode(t){let[r,n]=lt.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=lt.inspectBytes(t),n=r.size-r.multihashSize,i=ol(t.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=i.subarray(r.multihashSize-r.digestSize),a=new ds(r.multihashCode,r.digestSize,o,i);return[r.version===0?lt.createV0(a):lt.createV1(r.codec,a),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[d,k]=pu(t.subarray(r));return r+=k,d},i=n(),o=Oi;if(i===18?(i=0,r=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let a=r,s=n(),u=n(),l=r+u,f=l-a;return{version:i,codec:o,multihashCode:s,digestSize:u,multihashSize:f,size:l}}static parse(t,r){let[n,i]=l$(t,r),o=lt.decode(i);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return hu(o).set(n,t),o}};function l$(e,t){switch(e[0]){case"Q":{let r=t??Pr;return[Pr.prefix,r.decode(`${Pr.prefix}${e}`)]}case Pr.prefix:{let r=t??Pr;return[Pr.prefix,r.decode(e)]}case Mo.prefix:{let r=t??Mo;return[Mo.prefix,r.decode(e)]}case Co.prefix:{let r=t??Co;return[Co.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function c$(e,t,r){let{prefix:n}=r;if(n!==Pr.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=t.get(n);if(i==null){let o=r.encode(e).slice(1);return t.set(n,o),o}else return i}function f$(e,t,r){let{prefix:n}=r,i=t.get(n);if(i==null){let o=r.encode(e);return t.set(n,o),o}else return i}var Oi=112,d$=18;function Nf(e,t,r){let n=Oa(e),i=n+Oa(t),o=new Uint8Array(i+r.byteLength);return xa(e,o,0),xa(t,o,n),o.set(r,i),o}var p$=Symbol.for("@ipld/js-cid/CID"),h$=20;function Ph({name:e,code:t,encode:r,minDigestLength:n,maxDigestLength:i}){return new y$(e,t,r,n,i)}var y$=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,i){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??h$,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?jf(r,this.code,t?.truncate):r.then(n=>jf(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function jf(e,t,r){if(r!=null&&r!==e.byteLength){if(r>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,r)}return Rl(t,e)}var et=xr(Gr(),1),Rh=xr(dT(),1),Cf=e=>et.Type.Union([e,et.Type.Null()]),Dh=/^(k51qz|baguq)[0-9a-z]{56,57}$/,g$=/^[0-9A-Fa-f]{7,8}$/g;et.FormatRegistry.Set("EntityID",e=>!!e.match(g$)||!!e.match(Dh));var m$=et.Type.String(),yu=e=>e?.enc instanceof Uint8Array;et.FormatRegistry.Set("CID",e=>!!e.match(Dh));var Mh=et.Type.String({format:"CID"}),b$=/^http([s]?):\/\/.*\..*/;et.FormatRegistry.Set("URL",e=>!!e.match(b$));var AC=et.Type.String({format:"URL"}),Lh=et.Type.Object({en:m$,at:et.Type.String(),vl:Cf(et.Type.Union([et.Type.String(),et.Type.Boolean(),et.Type.Number()])),ts:et.Type.String(),ag:et.Type.String(),pv:Cf(Mh)}),Uf=Rh.TypeCompiler.Compile(Lh),SC=Uf.Check.bind(Uf),v$=et.Type.Composite([et.Type.Object({cid:Mh}),Lh]),gu=Rh.TypeCompiler.Compile(v$),w$=e=>Array.from(gu.Errors(e)),Bh=gu.Check.bind(gu);function Vh(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var _$=Ph({name:"sha2-256",code:18,encode:Vh("SHA-256")}),IC=Ph({name:"sha2-512",code:19,encode:Vh("SHA-512")}),{WARN:Pf,LOG:kC,DEBUG:T$,VERBOSE:Aa,ERROR:Fh}=Ae.setup(Ae.INFO),E$=114;function x$(e,t=["cid"]){if(!e)throw Fh("falsy log",e);let r=e.cid;if(yu(e))return r||(r=Dl(zh(e).bytes).toString()),Pf("preparing an encrypted applog - really?"),{log:e,cid:r};let n={};for(let[i,o]of Object.entries(e))o===void 0&&(Pf(`log.${i} is undefined, which is not allowed - encoding as null`,e),o=null),t.includes(i)?Aa("excluding app log",{key:i,val:o}):n[i]=o;return{log:n,cid:r}}function O$(e){return Dl(A$(e).bytes)}function A$(e){return zh(x$(e)?.log)}function Dl(e){let t=Lw(e),r=Nh.create(_$.code,t),n=or.create(1,$h,r);return Aa("[getCidSync]",{bytes:e,hash:t,digest:r,cid:n}),n}function zh(e){T$("[encodeBlock]",e);try{let t=Ul(e);return{bytes:t,cid:Dl(t)}}catch(t){throw Fh("[encodeBlock] failed to encode:",e,t)}}function S$(e){let t=null,r=[];try{t=or.parse(e)}catch(n){Aa("[retrieveThread] couldn't parse pubID with default base"),r.push(n)}if(!t)try{t=or.parse(e,Co)}catch(n){Aa("[retrieveThread] couldn't parse pubID with base36"),r.push(n)}return{cid:t,errors:t?null:r,isIpns:t&&Ml(t)}}function Ml(e){return e.code===E$}function mu(e){return typeof e=="string"?or.parse(e):typeof e.toV1!="function"?or.decode(e.bytes):e}function qh(e,t){if(!e||!t)throw new Error(`[areCidsEqual] invalid params: ${e}, ${t}`);if(e===t)return!0;let r=mu(e),n=mu(t);return r.toV1().toString()===n.toV1().toString()}function Rf(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function I$(e,t){let r=Rf(e),n=Rf(t);return+r<+n}var{WARN:k$,LOG:$C,DEBUG:NC,VERBOSE:Sa,ERROR:Ia}=Ae.setup(Ae.INFO),$$=(e,t,r="asc")=>r==="asc"?e.localeCompare(t,"en-US"):t.localeCompare(e,"en-US"),Kh=(e,t,r)=>Je.structural(Ef(t,e),Ef(r,e)),N$=(e,t,r="asc")=>$$(e.ts,t.ts,r),jC=ik(Kh,["en","at"]);function Qi(e,t="asc"){return e.sort((r,n)=>N$(r,n,t))}var j$=(e,t)=>I$(new Date(e.ts),new Date(t.ts)),C$=()=>{k$("[removeDuplicateAppLogs] mode not set; pass 'safety' or 'cleanup' for optimal behavior")},Df=e=>{let t=new Map,r=Sa.isEnabled;for(let n of e){if(!n)throw Ia("falsy entry in applogs",e),new Error("falsy entry in applogs");if(!n.cid)throw Ia("applog with missing CID",n),new Error("applog with missing CID");let i=n.cid,o=t.get(i);o?r&&Sa("Skipping duplicate applog:",[o,n]):t.set(i,n)}return Array.from(t.values())},U$=e=>{let t=new Set,r=Sa.isEnabled,n=r?new Map:null,i=null,o=0;for(let a of e){if(!a)throw Ia("falsy entry in applogs",e),new Error("falsy entry in applogs");if(!a.cid)throw Ia("applog with missing CID",a),new Error("applog with missing CID");let s=a.cid;t.has(s)?(i||(i=e.slice(0,o)),r&&Sa("Skipping duplicate applog:",[n?.get(s),a])):(t.add(s),n&&n.set(s,a),i&&i.push(a)),o++}return i??e},Gh=(e,t)=>t?t==="safety"?U$(e):Df(e):(C$(),Df(e));function P$(e){return typeof e=="string"&&e.startsWith("?")}function R$(e){return e.slice(1)}function Hh(e,t){let r={},n={};for(let[i,o]of Object.entries(e))if(P$(o)){let a=R$(o),s=t[a];s?n[i]=s:r[i]=a}else n[i]=o;return[n,r]}function D$(e,t,r){let n;if(t){let i=typeof t;i==="string"?n=t===r:i==="function"?n=t(r):typeof t.has=="function"?n=t.has(r):Array.isArray(t)&&!Array.isArray(r)?n=t.includes(r):n=t===r}else n=t===r;return e.charAt(0)==="!"?!n:n}var Wh=function(e){for(var t=0,r=0,n=e.length;r<n;r++)t+=e[r];return t},Mf=function(e){return Wh(e)/e.length},kt={max:function(e){return Math.max.apply(null,e)},min:function(e){return Math.min.apply(null,e)},range:function(e){return kt.max(e)-kt.min(e)},midrange:function(e){return kt.range(e)/2},sum:Wh,mean:Mf,average:Mf,median:function(e){e.sort(function(r,n){return r-n});var t=e.length/2;return t%1?e[t-.5]:(e[t-1]+e[t])/2},modes:function(e){if(!e.length)return[];var t={},r=0,n=[];return e.forEach(function(i){t[i]?t[i]++:t[i]=1,t[i]>r?(n=[i],r=t[i]):t[i]===r&&(n.push(i),r=t[i])}),n},variance:function(e){var t=kt.mean(e);return kt.mean(e.map(function(r){return Math.pow(r-t,2)}))},standardDeviation:function(e){return Math.sqrt(kt.variance(e))},meanAbsoluteDeviation:function(e){var t=kt.mean(e);return kt.mean(e.map(function(r){return Math.abs(r-t)}))},zScores:function(e){var t=kt.mean(e),r=kt.standardDeviation(e);return e.map(function(n){return(n-t)/r})}};kt.average=kt.mean;function Jh(){return new Date().toISOString()}var{WARN:M$,LOG:CC,DEBUG:He,VERBOSE:UC,ERROR:ka}=Ae.setup(Ae.INFO);function L$(e,t){He(`[ensureTsPvAndFinalizeApplogs] ENTER - ${e.length} applogs, thread size=${t.size}`);let r=Jh(),n=t;He("[ensureTsPvAndFinalizeApplogs] About to map over applogs");let i=e.map((o,a)=>{He(`[ensureTsPvAndFinalizeApplogs] Processing applog ${a+1}/${e.length}`);let s=B$(o,{ts:r,threadForPv:n});return He(`[ensureTsPvAndFinalizeApplogs] Finalized applog ${a+1}/${e.length}`),s});return He(`[ensureTsPvAndFinalizeApplogs] EXIT - mapped ${i.length} applogs`),i}function B$(e,{ts:t,threadForPv:r}={}){He(`[finalizeApplogForInsert] ENTER - en=${e.en}, at=${e.at}`),He("[finalizeApplogForInsert] About to call withTs");let n=z$(e,t??Jh());He(`[finalizeApplogForInsert] About to call withPvFrom (thread size=${r?.size??"null"})`);let i=q$(n,r);He("[finalizeApplogForInsert] About to call encodeApplogAndGetCid");let o=O$(i).toString();He(`[finalizeApplogForInsert] CID created: ${o}`),e.cid&&e.cid!==o&&M$("[finalizeApplogForInsert] overwriting wrong CID",{log:e,cid:o,logWithPv:i});let a={...i,cid:o};if(He("[finalizeApplogForInsert] About to validate applog"),!Bh(a))throw ka(`Bogus Applog ${JSON.stringify(a)}`,w$(a));return He(`[finalizeApplogForInsert] EXIT - CID=${o}`),Object.freeze(a)}function V$(e){return!!e.ts}function F$(e){return!!e.pv}function z$(e,t){return V$(e)?e:{...e,ts:t}}function q$(e,t){if(He(`[withPvFrom] ENTER - en=${e.en}, at=${e.at}, hasPv=${e.pv!==void 0}`),e.pv!==void 0)return He("[withPvFrom] EXIT early - pv already set"),e;if(t){let{en:r,at:n}=e;He(`[withPvFrom] About to call thread.findLast for en=${r}, at=${n}, thread.size=${t.size}`);let i=t.findLast(a=>a.en==r&&a.at==n);if(He(`[withPvFrom] findLast completed, found=${!!i}`),He("[withPvFrom] About to check equality"),Kh(["en","at","vl","ts","ag"],e,i))throw ka("[withPvFrom] Same as previous:",{log:e,pv:i,thread:t});let o=(e.pv!==void 0?e.pv:i?.cid)??null;return He(`[withPvFrom] EXIT - prevLogCid=${o}`),{...e,pv:o}}else{if(!F$(e))throw ka("[withPvFrom] no thread and no pv:",e);return He("[withPvFrom] EXIT - no thread, returning log with existing pv"),e}}function bu(e){let t=()=>(Le(()=>e.length<2&&He(`joinThreads with count=${e.length}`)),Qi(Gh(e.flatMap(i=>{let o=i.applogs;if(!o)throw ka("falsy applogs of thread",i),new Error("falsy applogs of thread");return o}),"cleanup"))),r=Le(()=>t()),n=mt(function(i,o){return Kr(i)?{init:Le(()=>t())}:{added:i.added.filter(a=>!this.hasApplog(a,!0)),removed:i.removed?.filter(a=>!!this.parents.some(s=>s===o?!1:s.hasApplog(a,!0)))}});return new ps(Le(()=>`join(~ ${e.map(i=>i.name).join(", ")})`),e,["?"],r,n)}var{WARN:Lf,LOG:PC,DEBUG:Bf,VERBOSE:tn,ERROR:Io}=Ae.setup(Ae.INFO),ps=class vu extends qn{constructor(t,r,n,i,o,a=null,s){super(t,r,n,o?Be.array([...i],{deep:!1,name:`${t}.array`}):i),this.name=t,this._initialLogs=i,this._eventMapper=o,this._writeMapper=a,this._readOnly=s,li(this,{onParentUpdate:mt}),o&&this.subscribeToParents()}static mapWrites(t,r,n){return new vu(`${r}<${t.nameAndSizeUntracked}>`,t,t.filters,t._applogs,null,n)}static asReadOnly(t){return t.readOnly?t:new vu(`readOnly(${t.name})`,t,t.filters,t._applogs,null,null,!0)}_parentSubscriptions=null;insert(t){if(this.readOnly)throw Io("[MappedThread] insert() called on read-only thread:",this.nameAndSizeUntracked);let r=this._writeMapper?this._writeMapper(t):t;if(!(this._writeMapper&&!r))return this.parents.forEach(n=>n.insert(r))}insertRaw(t){if(this.readOnly)throw Io("[MappedThread] insertRaw() called on read-only thread:",this.nameAndSizeUntracked);let r=this._writeMapper?this._writeMapper(t):t;if(!(this._writeMapper&&!r))return this.parents.forEach(n=>n.insertRaw(r))}subscribeToParents(){this._parentSubscriptions=new Map;let t=Dt(()=>{this.parents.length||Lf("MappedThread has no parents",this),tn(`[MappedThread: ${this.name}] subscribing to parents:`,this.parents.map(n=>n.name));let r=new Set([...this._parentSubscriptions.keys()]);for(let n of this.parents){r.delete(n)&&tn(`[MappedThread: ${this.name}] Skipping re-sub to parent`,n.nameAndSizeUntracked),tn(`[MappedThread: ${this.name}] sub to new parent`,n.nameAndSizeUntracked);let i=this.onParentUpdate.bind(this,n),o=n.subscribe(i);this._parentSubscriptions.set(n,o)}for(let n of r)tn(`[MappedThread: ${this.name}] un-subscribing from old parent`,n.nameAndSizeUntracked),this._parentSubscriptions.get(n)(),this._parentSubscriptions.delete(n)})}subscribe(t){return this._parentSubscriptions||this.subscribeToParents(),super.subscribe(t)}triggerRemap(){if(!this._eventMapper)throw Io("triggerRemap on a thread that is not actually mapping?!",this.nameAndSizeUntracked);Bf(`MappedThread{${this.nameAndSizeUntracked}} triggerRemap`),this.parents.length!==1&&Lf(`MappedThread{${this.nameAndSizeUntracked}} triggerRemap with parentCount=${this.parents.length} - not meant for this`),this.parents.forEach(t=>{this.onParentUpdate(t,{init:Le(()=>br(t.applogs))})})}onParentUpdate(t,r){tn(`MappedThread{${this.nameAndSizeUntracked}} parentUpdate`,r);let n=this._eventMapper?this._eventMapper(r,t):r;if(this._eventMapper)if(tn(`MappedThread{${this.nameAndSizeUntracked}} parentUpdate => mapped`,n),Kr(n))this._applogs.replace([...n.init]);else{for(let i of n.added)this._applogs.splice(yk(this._applogs,i,"ts"),0,i);if(n.removed){for(let i of n.removed)if(!this._applogs.remove(i))if(!Kr(r)&&r.removed?.includes(i))Bf("Ignoring remove event for non-existent because it was part of parent event's removed",i,r);else throw Io(`MappedThread{${this.name}} toRemove contained log that doesn't exist`,i,{thread:this,event:r,mapResult:n})}}tn(`MappedThread{${this.nameAndSizeUntracked}} parentUpdate => deps?`,rs(this._applogs)),this.notifySubscribers(n)}get readOnly(){return this._readOnly??!1}},{WARN:RC,LOG:DC,DEBUG:MC,VERBOSE:Ms,ERROR:K$}=Ae.setup(Ae.INFO),Kn=tt("rollingFilter",function(e,t,r={}){let n=H$(t),i=Vf(n),o=Be.array(Le(function(){return i(e.applogs)}),{deep:!1,name:`${e.name} | ${r.name||`rollingFilter.array{${Ji(n)}}`}`}),a=f=>{let d;return Kr(f)?d={init:i(f.init)}:d={added:i(f.added),removed:f.removed},Ms(`rollingFilter{${e.nameAndSizeUntracked} | ${r.name?` '${r.name}'}`:""} parentUpdate`,n,f,"=>",d),d},s=new ps(`${e.name} | ${r.name||`rollingFilter{${Ji(n)}}`}`,e,[...e.filters,...r.extraFilterName?[r.extraFilterName]:[]],o,a),u=I_(()=>br(t),f=>{Ms(`rollingFilter<${e.nameAndSizeUntracked}>${r.name?` '${r.name}'`:""} patternUpdate`,n,"=>",f),n=f,i=Vf(n),s.triggerRemap()}),l=Sn(o,()=>{Ms(`rollingFilter<${Le(()=>e.name)}>${r.name?` '${r.name}'`:""} unobserve`,n),u(),l()});return s},{equals:bo,argsDebugName:(e,t,r)=>We({caller:"rollingFilter",thread:e,pattern:t,args:r})}),G$=tt("rollingMapper",function(e,t,r={}){let n=Le(()=>t.call(null,{init:e.applogs},e));if(!Kr(n))throw K$("Initial run must return init event");let i=n.init;return new ps(`${e.name} | ${r.name||"rollingMapper"}`,e,[...e.filters,...r.extraFilterName?[r.extraFilterName]:[]],i,t)},{equals:bo,argsDebugName:(e,t,r)=>We({caller:"rollingMapper",thread:e,args:r})}),LC=tt("rollingAcc",function(e,t,r,n={}){let i=mt(r);return i({init:e.applogs},t),e.subscribe(o=>{i(o,t)}),t},{argsDebugName:(e,t,r,n)=>`rollingAcc{${e.nameAndSizeUntracked}${n?.name?` | ${n?.name}`:""}}`}),H$=function(e){let t=Le(function(){return Object.fromEntries(Object.entries(br(e)).map(([r,n])=>[br(r),br(n)]))});if(!Object.entries(t).length)throw new Error("Pattern is empty");return t};function Vf(e){return function(t){return t.filter(function(r){for(let n of Object.keys(e)){let i=e[n];if(i===void 0)continue;let o=r[n.startsWith("!")?n.slice(1):n];if(!D$(n,i,o))return!1}return!0})}}var BC=ps.asReadOnly,{WARN:W$,LOG:J$,DEBUG:Ge,VERBOSE:Qh,ERROR:Lo}=Ae.setup(Ae.INFO),Q$=class extends qn{constructor(e,t=[],r){super(e,null,r,t),li(this,{insertRaw:mt,purge:mt})}purge(e){let t=this.applogs.length;return this._applogs=this.applogs.filter(r=>!e.includes(r.cid)),t-this.applogs.length}insert(e){Ge(`[WriteableThread.insert] ENTER - ${e.length} applogs for thread "${this.name}"`),Ge("[WriteableThread.insert] About to call ensureTsPvAndFinalizeApplogs");let t=L$(e,this);Ge(`[WriteableThread.insert] ensureTsPvAndFinalizeApplogs completed, mapped=${t.length} applogs`),Ge("[WriteableThread.insert] About to call insertRaw");let r=this.insertRaw(t);return Ge("[WriteableThread.insert] insertRaw completed"),r}insertMissing(e,t=!1){let r=e.filter(n=>!this.hasApplog(n,t));return r.length===0?(Qh("[insertMissing] no missing applogs"),[]):this.insertRaw(r)??[]}insertRaw(e){Ge(`[WriteableThread.insertRaw] ENTER - ${e.length} applogs for thread "${this.name}"`),Ge("[WriteableThread.insertRaw] About to deduplicate");let t=Gh(e,"safety");if(t.length!==e.length)throw Lo(`[insertRaw] duplicate applogs passed: ${e.length-t.length}`,{appLogsToInsert:e,deduplicated:t});Ge("[WriteableThread.insertRaw] Deduplication done"),Ge("[WriteableThread.insertRaw] About to validate");let r=e.filter(a=>!Bh(a));if(r.length)throw Lo(`[insertRaw] bogus applogs passed: ${r.length}`,{bogus:r});Ge("[WriteableThread.insertRaw] Validation done"),Ge("[WriteableThread.insertRaw] About to check for existing");let n=e.filter(a=>this.hasApplog(a,!1));if(n.length)throw Lo(`[insertRaw] already existing applogs passed: ${n.length}`,{existing:n});if(Ge("[WriteableThread.insertRaw] Existing check done"),!e.length){W$("[insertRaw] skipping empty insert empty logs array");return}(!this.hasParents&&!(this instanceof vo)?J$:Ge)("Inserting:",e.length===1?e[0]:e,{ds:this}),Ge("[WriteableThread.insertRaw] About to sort applogs"),Qi(e);let i=this._applogs.length&&j$(e[0],this._applogs[this._applogs.length-1]);Ge("[WriteableThread.insertRaw] About to push to _applogs array");let o=5e4;for(let a=0;a<e.length;a+=o)this._applogs.push(...e.slice(a,a+o));return i&&(Ge("[WriteableThread.insertRaw] About to sort _applogs (sortNeeded=true)"),Qi(this._applogs)),Ge("[WriteableThread.insertRaw] About to notify subscribers"),this.notifySubscribers({added:e,removed:null}),Ge("[WriteableThread.insertRaw] Subscribers notified"),Ge("[WriteableThread.insertRaw] About to call persist (void - not awaited)"),this.persist(e),Ge(`[WriteableThread.insertRaw] EXIT - returning ${e.length} applogs`),e}get readOnly(){return!1}},vo=class Bo extends Q${constructor(t,r,n,i){super(t,r,n),this._readOnly=i,li(this,{_applogs:Be.shallow})}static empty(t){return Bo.fromArray([],t??"empty in-memory",!1)}static fromArray(t,r,n=!1){return new Bo(r??"in-memory",t,[],n)}static fromReadOnlyArray(t,r){return new Bo(r??"in-memory",t,[],!0)}get readOnly(){return this._readOnly}async persist(t){if(Qh("[InMem.persist] no persist for",t),this.readOnly)throw Lo("[persist] called for readOnly thread")}},{WARN:VC,LOG:FC,DEBUG:zC,VERBOSE:qC,ERROR:KC}=Ae.setup(Ae.INFO),{WARN:GC,LOG:HC,DEBUG:WC,VERBOSE:JC,ERROR:QC}=Ae.setup(Ae.INFO),Y$=class{constructor(e,t,r=null){this.logsOfThisNode=e,this.variables=t,this.prevNode=r,li(this,{threadOfTrail:Fe})}get record(){return this.variables}get threadOfTrail(){return this.prevNode?bu([this.logsOfThisNode,this.prevNode.threadOfTrail]):this.logsOfThisNode}get trailLogs(){return this.threadOfTrail.applogs}},Yh=class{constructor(e){this.nodes=e,li(this,{threadOfAllTrails:Fe,size:Fe,isEmpty:Fe})}get size(){return this.records.length}get isEmpty(){return this.records.length===0}get untrackedSize(){return Le(()=>this.records.length)}get records(){return Ht(()=>this.nodes.map(({variables:e})=>e),{name:"QueryResult.records"})}get leafNodeThread(){return bu(Ht(()=>this.nodes.map(({logsOfThisNode:e})=>e),{name:"QueryResult.leafNodeThread"}))}get leafNodeLogSet(){return Ht(()=>this.nodes.map(({logsOfThisNode:e})=>e.applogs),{name:"QueryResult.leafNodeLogSet"})}get leafNodeLogs(){return Ht(()=>this.nodes.flatMap(({logsOfThisNode:e})=>e.applogs),{name:"QueryResult.leafNodeLogs"})}get threadOfAllTrails(){return bu(Ht(()=>this.nodes.map(e=>e.threadOfTrail),{name:"QueryResult.threadOfAllTrails"}))}get thread(){return this.threadOfAllTrails}get allApplogs(){return this.threadOfAllTrails.applogs}},{WARN:YC,LOG:hs,DEBUG:_r,VERBOSE:Se,ERROR:cn}=Ae.setup(Ae.INFO,{prefix:"[q]"}),Ls=null,XC=tt("lastWriteWins",function(e,{inverseToOnlyReturnFirstLogs:t,tolerateAlreadyFiltered:r}={}){if(Se(`lastWriteWins${t?".inversed":""} < ${e.nameAndSizeUntracked} > initializing`),e.filters.includes("lastWriteWins")){if(r)return _r("[lastWriteWins] already filtered, but tolerateAlreadyFiltered=true, so returning"),e;throw cn("thread already filtered lastWriteWins:",e.filters,{name:e.name})}let n,i=G$(e,function(o,a){let s=Kr(o),u,l=[],f=s?null:[];s?(n=new Map,u=o.init):u=o.added;let d;for(let k=t?0:u.length-1;t?k<u.length:k>=0;t?k++:k--){let E=u[k],T=E.en+"|"+E.at;if(d&&(t?d>E.ts:d<E.ts))throw cn("lastWriteWins.mapper logs not sorted:",d,t?">":"<",E.ts,{log:E,i:k,newLogs:u,inverseToOnlyReturnFirstLogs:t});d=E.ts;let B=n.get(T);(!B||(t?B.ts>E.ts:B.ts<E.ts))&&(B&&!s&&f.push(B),l.push(E),n.set(T,E))}return Qi(l),Se.isDisabled||Se(`lastWriteWins${t?".inversed":""}<${e.nameAndSizeUntracked}> mapped event`,s?{...Object.fromEntries(Object.entries(o).map(([k,E])=>[k,E?.length])),toAdd:l.length,toRemove:f}:{...o,toAdd:l,toRemove:f}),s?{init:l}:{added:l,removed:f}},{name:`lastWriteWins${t?".inversed":""}`,extraFilterName:"lastWriteWins"});return Se.isDisabled||Dt(()=>{Se(`lastWriteWins<${e.nameAndSizeUntracked}> filtered down to`,i.applogs.length)}),i},{equals:bo,argsDebugName:e=>We({caller:"lastWriteWins",thread:e})}),ZC=tt("withoutDeleted",function(e){if(Se.isEnabled&&Se(`withoutDeleted<${e.nameAndSizeUntracked}>`),e.filters.includes("withoutDeleted"))throw cn("thread already filtered withoutDeleted:",e.filters,{name:e.name});let t=Kn(e,{at:["isDeleted","relation/isDeleted","block/isDeleted"],vl:!0},{name:"isDeleted"});Se.isEnabled&&Se(`withoutDeleted<${e.nameAndSizeUntracked}> deletionLogs:`,Le(function(){return[...t.applogs]}));let r=We({caller:"allDeletedEntities",thread:e}),n=Tk(function(){return t.map(i=>i.en)},{name:r});return Se.isEnabled&&Dt(()=>{Se(`withoutDeleted<${e.nameAndSizeUntracked}> deleted:`,[...n])}),Kn(e,{"!en":n},{name:"withoutDeleted",extraFilterName:"withoutDeleted"})},{equals:bo}),Xh=tt("query",function e(t,r,n={},i={}){oN();let o=Zh(t);_r(`query<${o.nameAndSizeUntracked}>:`,r);let a=Array.isArray(r)?r:[r],s;if(a.length===1)s=null;else{let f=a.slice(0,-1);s=e(o,f,n,i)}let u=a[a.length-1],l=X$(o,s,u,i);return Se.isDisabled||Dt(()=>Se("query result:",br(l))),l},{equals:Cl,argsDebugName:(e,t,r)=>We({caller:"query",thread:e,args:r?{pattern:t,startVars:r}:t})}),X$=tt("queryStep",function(e,t,r,n={}){if(_r(`queryStep<${e.nameAndSizeUntracked}> with`,t?.untrackedSize??"all","nodes, pattern:",r),!Object.entries(r).length)throw new Error("Pattern is empty");function i(a){let[s,u]=Hh(r,a?.variables??{});Se("[queryStep.doQuery] patternWithoutVars: ",s);let l=Kn(e,s),f=ys(u),d=Ht(function(){let k=l.map(E=>({log:E,vars:f(E)}));return Se.isEnabled&&Se("[queryStep.doQuery] step node:",a?.variables," =>",k,"from:",Le(()=>l.applogs)),k.map(({log:E,vars:T})=>{let B=Object.assign({},a?.variables,T);return new Y$(Ak.fromArray([E],We({caller:"QueryNode",thread:l,pattern:`${Ji(B)}@${Ji(s)}`})),B,a)})},{name:We({caller:"doQuery.mapNodes",thread:l,pattern:r})});return Se.isEnabled&&Dt(()=>Se("[queryStep.doQuery] resultNodes:",[...d])),n.debug&&hs("[queryStep] step result:",Le(()=>d.map(({variables:k,logsOfThisNode:E})=>({variables:k,thread:E})))),d}let o=Ht(function(){return _r(`[queryStep] Running with ${t?.nodes?.length} input nodes:`),t?[...t.nodes.flatMap(i)]:[...i(null)]},{name:We({caller:"queryStep",thread:e,pattern:r})});return Se.isEnabled&&Dt(()=>Se("[queryStep] observableResultNodes:",[...o])),new Yh(o)},{equals:Cl,argsDebugName:(e,t,r)=>We({caller:"queryStep",thread:e,pattern:r})}),e5=tt("queryNot",function(e,t,r,n={}){let i=t.nodes;_r(`queryNot<${e.nameAndSizeUntracked}> from: ${i.length} nodes`);let o=Array.isArray(r)?r:[r];for(let a of o){if(!Object.entries(r).length)throw new Error("Pattern is empty");i=i.filter(function({variables:s}){let[u,l]=Hh(a,s??{});Se("[queryNot] patternWithoutVars: ",u);let f=Kn(e,u);return Se("[queryNot] step node:",s," =>",f.size,"applogs"),Se.isDisabled||Se("[queryNot] step node:",s," => empty?",Le(()=>f.applogs)),n.debug&&hs("[queryNot] node result:",s,"=>",f.applogs),f.isEmpty})}return new Yh(i)},{equals:Cl,argsDebugName:(e,t,r)=>We({caller:"queryNot",thread:e,pattern:r})}),t5=tt("filterAndMap",function(e,t,r){_r(`filterAndMap<${e.nameAndSizeUntracked}>`,t);let n=Kn(e,t);Se.isEnabled&&(Se("[filterAndMap] filtered:",n.untrackedSize),Dt(()=>Se("[filterAndMap] filtered:",n.applogs)));let i=We({thread:e,pattern:t,caller:"filterAndMap"}),o=Ht(()=>tN(n,r),{name:i});return Se.isDisabled||Dt(()=>Se("[filterAndMap] mapped:",o)),o},{equals:Je.structural,argsDebugName:(e,t)=>We({caller:"filterAndMap",thread:e,pattern:t})}),r5=tt("queryAndMap",function(e,t,r,n={}){let i=Zh(e);_r(`queryAndMap<${i.nameAndSizeUntracked}>`,{patternOrPatterns:t,variables:n,map:r});let o=We({thread:i,caller:"queryAndMap"}),a=Xh(i,t);Se("[queryAndMap] filtered count:",a.untrackedSize);let s=Ht(()=>rN(a,r),{name:o});return Se.isDisabled||Dt(()=>Se("[queryAndMap] result:",br(s))),s},{equals:Je.structural,argsDebugName:(e,t)=>We({caller:"queryAndMap",thread:e,pattern:t})}),n5=tt("queryEntity",function(e,t,r,n){_r(`queryEntity<${e.nameAndSizeUntracked}>`,r,t);let i=Kn(e,{en:r,at:nN(t,n)});return Se("queryEntity applogs:",i.applogs),Fe(()=>i.isEmpty?null:Object.fromEntries(i.map(({at:o,vl:a})=>[o.slice(t.length+1),a])))},{equals:vk,argsDebugName:(e,t,r)=>We({caller:"queryEntity",thread:e,args:{name:t,entityID:r}})}),i5=tt("agentsOfThread",function(e){_r(`agentsOfThread<${e.nameAndSizeUntracked}>`);let t=Be.map(),r=mt(i=>{for(let o of Kr(i)?i.init:i.added){let a=t.get(o.ag)??0;t.set(o.ag,a+1)}for(let o of!Kr(i)&&i.removed||[]){let a=t.get(o.ag);if(!a||a<1)throw cn("[agentsOfThread] number is now negative",{log:o,event:i,mapped:t,prev:a});t.set(o.ag,a-1)}hs(`agentsOfThread<${e.nameAndSizeUntracked}> processed event`,{event:i,mapped:t})});r({init:e.applogs});let n=e.subscribe(r);return Sn(t,n),t}),Z$=tt("entityOverlap",function(e,t){return hs(`entityOverlap<${e.nameAndSizeUntracked}, ${t.nameAndSizeUntracked}>`),Fe(()=>{let r=new Set(e.map(i=>i.en)),n=new Set(t.map(i=>i.en));return[...r].filter(i=>n.has(i))})}),o5=tt("entityOverlapCount",function(e,t){return Fe(()=>Z$(e,t).get().length)}),eN=tt("querySingle",function(e,t,r={}){let n=Xh(e,t,r);return Fe(()=>{if(n.isEmpty)return null;if(n.size>1)throw cn("[querySingle] got",n.size,"results:",n);let i=n.nodes[0].logsOfThisNode;if(i.size!=1)throw cn("[querySingle] single result, but got",i.size,"logs:",i.applogs);return i.applogs[0]})},{equals:Je.structural,argsDebugName:(e,t)=>We({caller:"querySingle",thread:e,pattern:t})}),a5=tt("querySingleAndMap",function(e,t,r,n={}){let i=eN(e,t,n);return Fe(()=>{let o=i.get();if(o)return typeof r=="string"?o[r]:ys(r)(o)})},{equals:Je.structural,argsDebugName:(e,t)=>We({caller:"querySingleAndMap",thread:e,pattern:t})}),tN=function(e,t){return typeof t=="function"?e.map(t):typeof t=="string"?e.map(r=>r[t]):e.map(ys(t))},rN=function(e,t){return typeof t=="function"?e.records.map(t):typeof t=="string"?e.nodes.map(r=>{if(!Object.hasOwn(r.record,t)){if(r.logsOfThisNode.size!==1)throw cn(`not sure what to map (it's not a var and a result node log count of ${r.logsOfThisNode.size})`);return r.logsOfThisNode.firstLog[t]}return r.record[t]}):e.nodes.map(r=>ys(t)(e))};function ys(e){return t=>Object.entries(e).reduce((r,[n,i])=>(r[i]=t[n],r),{})}function nN(e,t){return t.map(r=>iN(e,r))}function iN(e,t){return`${e}/${t}`}function Zh(e,t){return Array.isArray(e)?vo.fromArray(e,t||`threadFromArray[${e.length}]`,!0):e}function oN(){if(Ls!=null&&performance.now()>=Ls)throw new aN(Ls)}var aN=class extends Error{constructor(e){super(e)}},sN=Ze({"../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/encode.js"(e,t){"use strict";t.exports=a;var r=128,n=127,i=~n,o=Math.pow(2,31);function a(s,u,l){if(Number.MAX_SAFE_INTEGER&&s>Number.MAX_SAFE_INTEGER)throw a.bytes=0,new RangeError("Could not encode varint");u=u||[],l=l||0;for(var f=l;s>=o;)u[l++]=s&255|r,s/=128;for(;s&i;)u[l++]=s&255|r,s>>>=7;return u[l]=s|0,a.bytes=l-f+1,u}}}),uN=Ze({"../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/decode.js"(e,t){"use strict";t.exports=i;var r=128,n=127;function i(o,u){var s=0,u=u||0,l=0,f=u,d,k=o.length;do{if(f>=k||l>49)throw i.bytes=0,new RangeError("Could not decode varint");d=o[f++],s+=l<28?(d&n)<<l:(d&n)*Math.pow(2,l),l+=7}while(d>=r);return i.bytes=f-u,s}}}),lN=Ze({"../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/length.js"(e,t){"use strict";var r=Math.pow(2,7),n=Math.pow(2,14),i=Math.pow(2,21),o=Math.pow(2,28),a=Math.pow(2,35),s=Math.pow(2,42),u=Math.pow(2,49),l=Math.pow(2,56),f=Math.pow(2,63);t.exports=function(d){return d<r?1:d<n?2:d<i?3:d<o?4:d<a?5:d<s?6:d<u?7:d<l?8:d<f?9:10}}}),Ll=Ze({"../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/index.js"(e,t){"use strict";t.exports={encode:sN(),decode:uN(),encodingLength:lN()}}}),ey=42;function cN(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;let t=Ka.asCID(e);if(!t)return null;let r=new Uint8Array(t.bytes.byteLength+1);return r.set(t.bytes,1),[new ne(I.tag,ey),new ne(I.bytes,r)]}function fN(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function dN(e){if(Number.isNaN(e))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(e===1/0||e===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function pN(e){for(let t of e.keys())if(typeof t!="string"||t.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var Ff={float64:!0,typeEncoders:{Map:pN,Object:cN,undefined:fN,number:dN}},s5={...Ff,typeEncoders:{...Ff.typeEncoders}};function hN(e){if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return Ka.decode(e.subarray(1))}var wu={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};wu.tags[ey]=hN;var u5={...wu,tags:wu.tags.slice()},l5=xr(Ll(),1),Lr={Null:e=>e===null?e:void 0,Int:e=>Number.isInteger(e)?e:void 0,Float:e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,String:e=>typeof e=="string"?e:void 0,Bool:e=>typeof e=="boolean"?e:void 0,Bytes:e=>e instanceof Uint8Array?e:void 0,Link:e=>e!==null&&typeof e=="object"&&e.asCID===e?e:void 0,List:e=>Array.isArray(e)?e:void 0,Map:e=>e!==null&&typeof e=="object"&&e.asCID!==e&&!Array.isArray(e)&&!(e instanceof Uint8Array)?e:void 0},$i={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Lr.Link,"CarV1HeaderOrV2Pragma > roots (anon)":e=>{if(Lr.List(e)!==void 0){for(let t=0;t<e.length;t++){let r=e[t];if(r=$i["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](r),r===void 0)return;if(r!==e[t]){let n=e.slice(0,t);for(let i=t;i<e.length;i++){let o=e[i];if(o=$i["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return e}},Int:Lr.Int,CarV1HeaderOrV2Pragma:e=>{if(Lr.Map(e)===void 0)return;let t=Object.entries(e),r=e,n=1;for(let i=0;i<t.length;i++){let[o,a]=t[i];switch(o){case"roots":{let s=$i["CarV1HeaderOrV2Pragma > roots (anon)"](e[o]);if(s===void 0)return;if(s!==a||r!==e){if(r===e){r={};for(let u=0;u<i;u++)r[t[u][0]]=t[u][1]}r.roots=s}}break;case"version":{n--;let s=$i.Int(e[o]);if(s===void 0)return;if(s!==a||r!==e){if(r===e){r={};for(let u=0;u<i;u++)r[t[u][0]]=t[u][1]}r.version=s}}break;default:return}}if(!(n>0))return r}},Ni={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Lr.Link,"CarV1HeaderOrV2Pragma > roots (anon)":e=>{if(Lr.List(e)!==void 0){for(let t=0;t<e.length;t++){let r=e[t];if(r=Ni["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](r),r===void 0)return;if(r!==e[t]){let n=e.slice(0,t);for(let i=t;i<e.length;i++){let o=e[i];if(o=Ni["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return e}},Int:Lr.Int,CarV1HeaderOrV2Pragma:e=>{if(Lr.Map(e)===void 0)return;let t=Object.entries(e),r=e,n=1;for(let i=0;i<t.length;i++){let[o,a]=t[i];switch(o){case"roots":{let s=Ni["CarV1HeaderOrV2Pragma > roots (anon)"](a);if(s===void 0)return;if(s!==a||r!==e){if(r===e){r={};for(let u=0;u<i;u++)r[t[u][0]]=t[u][1]}r.roots=s}}break;case"version":{n--;let s=Ni.Int(a);if(s===void 0)return;if(s!==a||r!==e){if(r===e){r={};for(let u=0;u<i;u++)r[t[u][0]]=t[u][1]}r.version=s}}break;default:return}}if(!(n>0))return r}},c5={toTyped:$i.CarV1HeaderOrV2Pragma,toRepresentation:Ni.CarV1HeaderOrV2Pragma},f5=Dd(),d5=xr(Ll(),1),p5=[new ne(I.map,2),new ne(I.string,"version"),new ne(I.uint,1),new ne(I.string,"roots")],h5=new ne(I.tag,42),y5=xr(Ll(),1),{WARN:ty,LOG:g5,DEBUG:Bs,VERBOSE:Bl,ERROR:Un}=Ae.setup(Ae.INFO);async function yN(e){let t=await mN(e);return await gN(t)}async function gN({rootCID:e,blockStore:t},r=[],n){if(!e||!t)throw Un("Empty roots/blocks",{rootCID:e,blockStore:t});let i=[],o=null,a=e,s=new Set,u=null;for(;a;){let f=a.toString();if(s.has(f))throw Un("[decodePubFromBlocks] pub chain has a loop",{currentCID:f,visited:[...s]});s.add(f);let d=await Rn(t,a);if(Bl("[decodePubFromBlocks] root:",f,d,{blockStore:t}),!d)throw Un("[decodePubFromBlocks] root not found in blockStore",{blockStore:t,currentCID:f});let k;if(d?.info){u||(u=d.applogs);let B=await Rn(t,d.applogs);k=await wN(B,t),o||(o=await Rn(t,d.info),Bs("new format - infoLogs",o.logs.map(W=>({[W.toString()]:W}))))}else k=d.applogs;let E=async B=>{let W=B,D=await Rn(t,W);if(!D)throw Un("Could not find applog CID in pub blocks:",W.toString(),{cid:W,root:d,blockStore:t}),new Error(`Could not find applog CID in pub blocks: ${W.toString()}`);return D.pv instanceof or&&(D.pv=D.pv.toV1().toString()),{...D,cid:W.toV1().toString()}},T=await Promise.all(k.map(E));if(i=i.concat(T),!d.prev)break;if(n&&qh(d.prev,n)){Bs("[decodePubFromBlocks] stopping at stopAtCID:",n.toString());break}if(!await t.get(d.prev))throw Un("[decodePubFromBlocks] prev snapshot missing from blockStore",{currentCID:f,prev:d.prev.toString(),stopAtCID:n?.toString(),visited:[...s]});a=d.prev}let l={cid:e,info:o?{...o,logs:await Promise.all(o.logs.map(async f=>{let d=f,k=await Rn(t,d);if(!k)throw Un("Could not find info log CID in pub blocks:",d.toString(),{cid:d,blockStore:t}),new Error(`Could not find info log CID in pub blocks: ${d.toString()}`);return k.pv instanceof or&&(k.pv=k.pv.toV1().toString()),{...k,cid:d.toV1().toString()}}))}:null,applogsCID:u,applogs:i};return Bs("[decodePubFromBlocks] result:",l,{rootCID:e.toString(),blockStore:t,applogs:i}),l}async function mN(e){let t=(await e.getRoots()).map(n=>(typeof n.toV1=="function"?n:or.decode(n.bytes)).toV1().toString()),r=new Map;for await(let{cid:n,bytes:i}of e.blocks()){let o=typeof n.toV1=="function"?n:or.decode(n.bytes);Bl({cidFromCarblocks:n,cid:o}),r.set(o.toV1().toString(),i)}return t.length!==1&&ty("Unexpected roots count:",t),{rootCID:or.parse(t[0]),blockStore:{get:n=>r.get(n.toV1().toString())}}}async function Rn(e,t){try{var r=await e.get(t);if(!r)return ty("returning null"),null}catch(n){if(n.message==="Not Found")return null;throw n}return Pl(r)}function bN(e){return async function*(){for(;;){let{done:t,value:r}=await e.read();if(Bl("[car] chunk",{done:t,value:r}),t)break;yield r}}()}var{WARN:m5,LOG:b5,DEBUG:v5,VERBOSE:w5,ERROR:vN}=Ae.setup(Ae.INFO);async function wN(e,t){return _N(e)?(await Promise.all(e.chunks.map(async r=>{let n=await Rn(t,r);if(!n.logs)throw vN("Weird chunk",n);return n.logs}))).flat():e.logs}function _N(e){return e.chunks}var $a=Yi(ky(),1),TN=Yi($y(),1),ry=!1,ny=!1;$a.isNode&&(process?.env?.LOGGER_TIME_PREFIX&&(ry=process?.env?.LOGGER_TIME_PREFIX==="true"),process?.env?.LOGGER_PERF_PREFIX&&(ny=process?.env?.LOGGER_PERF_PREFIX==="true"));var EN={prefix:void 0,time:ry,delta:ny,dimDebugOnServer:!0,printOriginOnServer:!0,serverInspectOptions:{},customFormattersOnServer:!0,printStackLinesOnServer:!1,dim:!0},Vs=[],iy=class{sinceFirst=0;sinceLast=0;time=!1;delta=!1;constructor(e,t,r,n){Object.assign(this,{sinceFirst:e,sinceLast:t,time:r,delta:n})}toString(){let e=this.sinceFirst*.001,t=e.toFixed(e<5?2:1),r=this.sinceLast<1e3?`${this.sinceLast.toFixed(0)}`.padStart(5," "):`${`${(this.sinceLast*.001).toFixed(this.sinceLast<1e4?1:0)}`.padStart(4," ")}s`;return`[${[this.time?t:null,this.delta?r:null].filter(n=>n!=null).join(",")}]`}},oy=class{constructor(e,t){Object.assign(this,{style:e,string:t})}},ji=!1,Gn=class yt{static ERROR=2;static WARN=4;static INFO=6;static LOG=6;static DEBUG=8;static VERBOSE=10;static firstLog=0;static lastLog=0;static setup(t=yt.INFO,r={}){r=Object.assign({},EN,r),t>10&&console.debug("setup logger",{config:r});let n=this.wrapLog(console.debug,{...r,dim:r.dimDebugOnServer}),i=(...u)=>{typeof window<"u"&&window?.FORCE_DISABLE_LOGLEVEL&&n(...u)};i.isDisabled=!0,i.isEnabled=!1;let o=this.wrapLog(console.groupCollapsed,r),a=(u,l)=>{function f(...k){let E=k[k.length-1];return E===i?E():(o(...k.slice(0,-1)),(async()=>{try{let T=E();return T instanceof Promise?await T:T}finally{console.groupEnd()}})())}let d=Object.assign(l.bind({}),{isEnabled:u,isDisabled:!u,group:f,force:l});return u?d:Object.assign(i.bind({}),{isEnabled:u,isDisabled:!u,group:f,force:d})},s=a(t>=yt.ERROR,this.wrapLog(console.error,r));return{ERROR:(...u)=>(s(...u),new Error((0,TN.default)(u))),WARN:a(t>=yt.WARN,this.wrapLog(console.warn,r)),LOG:a(t>=yt.INFO,this.wrapLog(console.log,r)),DEBUG:a(t>=yt.DEBUG,this.wrapLog(console.log,{...r,dim:r.dimDebugOnServer})),VERBOSE:a(t>=yt.VERBOSE,this.wrapLog(console.debug,{...r,dim:r.dimDebugOnServer}))}}static wrapLog(t,r){if($a.isNode)return t.bind(console);{let n=[];if(r.time||r.delta){let i=$a.isBrowser&&navigator.userAgent.includes("Chrome")?["",yt.timeStr(!!r.time,!!r.delta)]:[];n.push(...i)}return r.prefix&&(ji?n.push(new oy("dim",r.prefix)):n.push(r.prefix)),t.bind(console,...n)}}static timeStr(t,r,n=0){if(!performance.now)return;let i=performance.now();yt.firstLog||(yt.firstLog=i,yt.lastLog=i);let o=new iy(i-yt.firstLog,i-yt.lastLog,t,r);return yt.lastLog=i,n?o.toString():o}static getOriginFromStack(t){let r=!1;for(let n of t.split(`
|
|
61
|
+
`+" ".repeat(t)+o):o==="{"&&n>0?(n++,r+=o):(o==="}"&&n>1&&n--,r+=o)}return r}function xk(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]instanceof qn){if(t[r]!==e[r])return!1}else if(!Je.structural(e[r],t[r]))return!1;return!0}var{WARN:Of,LOG:yC,DEBUG:Ok,VERBOSE:gC,ERROR:en}=Ae.setup(Ae.INFO,{prefix:"[thread]"});function Kr(e){return e.init!==void 0}var qn=class{constructor(e,t,r,n=[],i={}){this.name=e,this._applogs=n,this.parents=t===null?null:Xo(t),this.filters=r,Le(()=>this.parents?.length===0)&&Of("[Thread] empty parents array",e),i.skipObservable||li(this,{applogsCids:Fe,applogsCidSet:Fe,applogsByCid:Fe,insert:mt,size:Fe,isEmpty:Fe,firstLog:Fe,latestLog:Fe},{name:`Thread{${e}}`})}filters;parents;_derivedSubscribers=[];_subscribers=[];get readOnly(){return this.parents.length!==1?!0:this.parents[0].readOnly}insert(e){if(this.readOnly)throw en("[Thread] insert() called on read-only thread:",this.nameAndSizeUntracked);if(!this.parents)throw en("[Thread] insert() called on non-writable thread without parents:",this.nameAndSizeUntracked);if(this.parents?.length!==1)throw en("[Thread] insert() called on thread with multiple parents:",this.nameAndSizeUntracked);return this.parents[0].insert(e)}insertRaw(e){if(this.readOnly)throw en("[Thread] insertRaw() called on read-only thread:",this.nameAndSizeUntracked);if(!this.parents)throw en("[Thread] insertRaw() called on non-writable thread without parents:",this.nameAndSizeUntracked);if(this.parents?.length!==1)throw en("[Thread] insertRaw() called on thread with multiple parents:",this.nameAndSizeUntracked);return this.parents[0].insertRaw(e)}subscribe(e,t){return(t==="derived"?this._derivedSubscribers:this._subscribers).push(e),this.unsubscribe.bind(this,e)}unsubscribe(e){let t=this._derivedSubscribers.indexOf(e);if(t!==-1){this._derivedSubscribers.splice(t,1);return}let r=this._subscribers.indexOf(e);r!==-1?this._subscribers.splice(r,1):Of("unsubscribe called for non-existent",e)}notifySubscribers(e){Ok(`[thread: ${this.name}] notifying`,this._derivedSubscribers.length,"derived +",this._subscribers.length,"subscribers of",{...e,subs:this._subscribers});for(let t of this._derivedSubscribers)t(e);for(let t of this._subscribers)t(e)}get applogs(){return this._applogs}get applogsCids(){return this._applogs.map(e=>e.cid)}get applogsCidSet(){return new Set(this._applogs.map(e=>e.cid))}map(e){return this.applogs.map(e)}get findLast(){return this.applogs.findLast.bind(this.applogs)}get findFirst(){return this.applogs.find.bind(this.applogs)}get firstLog(){return this.applogs[0]}get latestLog(){return this.applogs[this.applogs.length-1]}hasApplog(e,t){if(t)return this.applogs.includes(e);if(!e.cid)throw en("[hasApplogs] applog without CID:",e);return this.hasApplogCid(e.cid)}hasApplogCid(e){return this.applogsCidSet.has(e.toString())}get applogsByCid(){return new Map(this.applogs.map(e=>[e.cid,e]))}getApplog(e){return this.applogsByCid.get(e.toString())}hasApplogWithDiffTs(e){return this.applogs.find(t=>t.en===e.en&&t.at===e.at&&t.vl===e.vl&&t.ag===e.ag)}get isEmpty(){return this.size===0}get size(){return this.applogs.length}get length(){return this.applogs.length}get untrackedSize(){return Le(()=>this.size)}get nameAndSizeUntracked(){return Le(()=>`${this.name} (${this.size})`)}get prettyName(){return Ek(this.name)}get hasParents(){return!!this.parents?.length}},Ak=class Ih extends qn{static fromArray(t,r){return new Ih(r||"static",null,[],t)}constructor(t,r,n,i){super(t,r,n,i,{skipObservable:!0})}get readOnly(){return!0}},Sk={};ti(Sk,{code:()=>$h,decode:()=>Pl,encode:()=>Ul,format:()=>Af,name:()=>Bk,parse:()=>Fk,stringify:()=>Af});var Ik=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(I.equals(t.type,I.array)&&(t.elements++,t.elements!==1&&e.push([44])),I.equals(t.type,I.map)&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[I.uint.major](e,t){this.prefix(e);let r=String(t.value),n=[];for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);e.push(n)}[I.negint.major](e,t){this[I.uint.major](e,t)}[I.bytes.major](e,t){throw new Error(`${on} unsupported type: Uint8Array`)}[I.string.major](e,t){this.prefix(e);let r=Od(JSON.stringify(t.value));e.push(r.length>32?Ba(r):r)}[I.array.major](e,t){this.prefix(e),this.inRecursive.push({type:I.array,elements:0}),e.push([91])}[I.map.major](e,t){this.prefix(e),this.inRecursive.push({type:I.map,elements:0}),e.push([123])}[I.tag.major](e,t){}[I.float.major](e,t){if(t.type.name==="break"){let o=this.inRecursive.pop();if(o){if(I.equals(o.type,I.array))e.push([93]);else if(I.equals(o.type,I.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(`${on} 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 r=String(t.value),n=[],i=!1;for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o),!i&&(n[o]===46||n[o]===101||n[o]===69)&&(i=!0);i||(n.push(46),n.push(48)),e.push(n)}};function kk(e,t){if(Array.isArray(e[0])||Array.isArray(t[0]))throw new Error(`${on} complex map keys are not supported`);let r=e[0],n=t[0];if(r.type!==I.string||n.type!==I.string)throw new Error(`${on} non-string map keys are not supported`);if(r<n)return-1;if(r>n)return 1;throw new Error(`${on} unexpected duplicate map keys, this is not supported`)}var $k={addBreakTokens:!0,mapSorter:kk};function Nk(e,t){return t=Object.assign({},$k,t),Bd(e,new Ik,t)}var kh=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(`${be} 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(`${be} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,r=!1,n=a=>{for(;!this.done();){let s=this.ch();if(a.includes(s))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,r=!0;else return new ne(I.uint,0,this._pos-e);if(n([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${be} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(r)throw new Error(`${be} unexpected token at position ${this._pos}`);r=!0,this._pos++,n([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(r=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,n([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),o=parseFloat(i);return r?new ne(I.float,o,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(o)?new ne(o>=0?I.uint:I.negint,o,this._pos-e):new ne(o>=0?I.uint:I.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${be} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,o=0;i<this.data.length&&o<65536;i++,o++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let s=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new ne(I.string,s,o)}}let e=this._pos,t=[],r=()=>{if(this._pos+4>=this.data.length)throw new Error(`${be} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let o=0;o<4;o++){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(`${be} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},n=()=>{let i=this.ch(),o=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${be} unexpected unicode sequence at position ${this._pos}`);let s,u,l,f;switch(a){case 1:i<128&&(o=i);break;case 2:s=this.data[this._pos+1],(s&192)===128&&(f=(i&31)<<6|s&63,f>127&&(o=f));break;case 3:s=this.data[this._pos+1],u=this.data[this._pos+2],(s&192)===128&&(u&192)===128&&(f=(i&15)<<12|(s&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(o=f));break;case 4:s=this.data[this._pos+1],u=this.data[this._pos+2],l=this.data[this._pos+3],(s&192)===128&&(u&192)===128&&(l&192)===128&&(f=(i&15)<<18|(s&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(o=f))}o===null?(o=65533,a=1):o>65535&&(o-=65536,t.push(o>>>10&1023|55296),o=56320|o&1023),t.push(o),this._pos+=a};for(;!this.done();){let i=this.ch(),o;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${be} unexpected string termination at position ${this._pos}`);switch(o=this.ch(),this._pos++,o){case 34:case 39:case 92:case 47:t.push(o);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(r());break;default:throw new Error(`${be} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new ne(I.string,Av(t),this._pos-e);default:if(i<32)throw new Error(`${be} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):n()}}throw new Error(`${be} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new ne(I.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new ne(I.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new ne(I.null,null,4);case 102:return this.expect([102,97,108,115,101]),new ne(I.false,!1,5);case 116:return this.expect([116,114,117,101]),new ne(I.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(`${be} 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 ne(I.break,void 0,1);if(this.ch()!==44)throw new Error(`${be} 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 ne(I.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 ne(I.break,void 0,1);if(this.ch()!==44)throw new Error(`${be} 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 ne(I.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${be} 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(`${be} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function jk(e,t){return t=Object.assign({tokenizer:new kh(e,t)},t),N0(e,t)}function Ck(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}function Uk(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;let t=Ka.asCID(e);if(!t)return null;let r=t.toString();return[new ne(I.map,1/0,1),new ne(I.string,"/",1),new ne(I.string,r,r.length),new ne(I.break,void 0,1)]}function Ta(e){let t=al.encode(e).slice(1);return[new ne(I.map,1/0,1),new ne(I.string,"/",1),new ne(I.map,1/0,1),new ne(I.string,"bytes",5),new ne(I.string,t,t.length),new ne(I.break,void 0,1),new ne(I.break,void 0,1)]}function Ft(e){return Ta(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}function Pk(e){return Ta(new Uint8Array(e))}function Rk(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Dk(e){if(Number.isNaN(e))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(e===1/0||e===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var Mk={typeEncoders:{Object:Uk,Buffer:Ta,Uint8Array:Ta,Int8Array:Ft,Uint16Array:Ft,Int16Array:Ft,Uint32Array:Ft,Int32Array:Ft,Float32Array:Ft,Float64Array:Ft,Uint8ClampedArray:Ft,BigInt64Array:Ft,BigUint64Array:Ft,DataView:Ft,ArrayBuffer:Pk,undefined:Rk,number:Dk}},Lk=class extends kh{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===I.map){let t=this._next();if(t.type===I.string&&t.value==="/"){let r=this._next();if(r.type===I.string){if(this._next().type!==I.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(r),new ne(I.tag,42,0)}if(r.type===I.map){let n=this._next();if(n.type===I.string&&n.value==="bytes"){let i=this._next();if(i.type===I.string){for(let a=0;a<2;a++)if(this._next().type!==I.break)throw new Error("Invalid encoded Bytes form");let o=al.decode(`m${i.value}`);return new ne(I.bytes,o,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(r)}this.tokenBuffer.push(t)}return e}},fu={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};fu.tags[42]=Ka.parse;var Bk="dag-json",$h=297,Ul=e=>Nk(e,Mk),Pl=e=>{let t=Ck(e),r=Object.assign(fu,{tokenizer:new Lk(t,fu)});return jk(t,r)},Af=e=>Vk.decode(Ul(e)),Vk=new TextDecoder,Fk=e=>Pl(zk.encode(e)),zk=new TextEncoder,Mo=Or({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),mC=Or({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),bC=Or({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),vC=Or({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),wC=Or({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),_C=Or({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),TC=Or({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),EC=Or({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xC=Or({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Pr=Ga({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),OC=Ga({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Nh={};ti(Nh,{Digest:()=>ds,create:()=>Rl,decode:()=>Ch,equals:()=>Uh,hasCode:()=>u$});var qk=jh,Sf=128,Kk=127,Gk=~Kk,Hk=Math.pow(2,31);function jh(e,t,r){t=t||[],r=r||0;for(var n=r;e>=Hk;)t[r++]=e&255|Sf,e/=128;for(;e&Gk;)t[r++]=e&255|Sf,e>>>=7;return t[r]=e|0,jh.bytes=r-n+1,t}var Wk=du,Jk=128,If=127;function du(e,n){var r=0,n=n||0,i=0,o=n,a,s=e.length;do{if(o>=s)throw du.bytes=0,new RangeError("Could not decode varint");a=e[o++],r+=i<28?(a&If)<<i:(a&If)*Math.pow(2,i),i+=7}while(a>=Jk);return du.bytes=o-n,r}var Qk=Math.pow(2,7),Yk=Math.pow(2,14),Xk=Math.pow(2,21),Zk=Math.pow(2,28),e$=Math.pow(2,35),t$=Math.pow(2,42),r$=Math.pow(2,49),n$=Math.pow(2,56),i$=Math.pow(2,63),o$=function(e){return e<Qk?1:e<Yk?2:e<Xk?3:e<Zk?4:e<e$?5:e<t$?6:e<r$?7:e<n$?8:e<i$?9:10},a$={encode:qk,decode:Wk,encodingLength:o$},s$=a$,Ea=s$;function pu(e,t=0){return[Ea.decode(e,t),Ea.decode.bytes]}function xa(e,t,r=0){return Ea.encode(e,t,r),t}function Oa(e){return Ea.encodingLength(e)}function Rl(e,t){let r=t.byteLength,n=Oa(e),i=n+Oa(r),o=new Uint8Array(i+r);return xa(e,o,0),xa(r,o,n),o.set(t,i),new ds(e,r,t,o)}function Ch(e){let t=ol(e),[r,n]=pu(t),[i,o]=pu(t.subarray(n)),a=t.subarray(n+o);if(a.byteLength!==i)throw new Error("Incorrect length");return new ds(r,i,a,t)}function Uh(e,t){if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&Bw(e.bytes,r.bytes)}}var ds=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}};function u$(e,t){return e.code===t}function kf(e,t){let{bytes:r,version:n}=e;switch(n){case 0:return c$(r,hu(e),t??Pr.encoder);default:return f$(r,hu(e),t??Mo.encoder)}}var $f=new WeakMap;function hu(e){let t=$f.get(e);if(t==null){let r=new Map;return $f.set(e,r),r}return t}var or=class lt{code;version;multihash;bytes;"/";constructor(t,r,n,i){this.code=r,this.version=t,this.multihash=n,this.bytes=i,this["/"]=i}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:t,multihash:r}=this;if(t!==Oi)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==d$)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return lt.createV0(r)}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:t,digest:r}=this.multihash,n=Rl(t,r);return lt.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(t){return lt.equals(this,t)}static equals(t,r){let n=r;return n!=null&&t.code===n.code&&t.version===n.version&&Uh(t.multihash,n.multihash)}toString(t){return kf(this,t)}toJSON(){return{"/":kf(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let r=t;if(r instanceof lt)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:o,bytes:a}=r;return new lt(n,i,o,a??Nf(n,i,o.bytes))}else if(r[p$]===!0){let{version:n,multihash:i,code:o}=r,a=Ch(i);return lt.create(n,o,a)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(r!==Oi)throw new Error(`Version 0 CID must use dag-pb (code: ${Oi}) block encoding`);return new lt(t,r,n,n.bytes)}case 1:{let i=Nf(t,r,n.bytes);return new lt(t,r,n,i)}default:throw new Error("Invalid version")}}static createV0(t){return lt.create(0,Oi,t)}static createV1(t,r){return lt.create(1,t,r)}static decode(t){let[r,n]=lt.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=lt.inspectBytes(t),n=r.size-r.multihashSize,i=ol(t.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=i.subarray(r.multihashSize-r.digestSize),a=new ds(r.multihashCode,r.digestSize,o,i);return[r.version===0?lt.createV0(a):lt.createV1(r.codec,a),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[d,k]=pu(t.subarray(r));return r+=k,d},i=n(),o=Oi;if(i===18?(i=0,r=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let a=r,s=n(),u=n(),l=r+u,f=l-a;return{version:i,codec:o,multihashCode:s,digestSize:u,multihashSize:f,size:l}}static parse(t,r){let[n,i]=l$(t,r),o=lt.decode(i);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return hu(o).set(n,t),o}};function l$(e,t){switch(e[0]){case"Q":{let r=t??Pr;return[Pr.prefix,r.decode(`${Pr.prefix}${e}`)]}case Pr.prefix:{let r=t??Pr;return[Pr.prefix,r.decode(e)]}case Mo.prefix:{let r=t??Mo;return[Mo.prefix,r.decode(e)]}case Co.prefix:{let r=t??Co;return[Co.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function c$(e,t,r){let{prefix:n}=r;if(n!==Pr.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=t.get(n);if(i==null){let o=r.encode(e).slice(1);return t.set(n,o),o}else return i}function f$(e,t,r){let{prefix:n}=r,i=t.get(n);if(i==null){let o=r.encode(e);return t.set(n,o),o}else return i}var Oi=112,d$=18;function Nf(e,t,r){let n=Oa(e),i=n+Oa(t),o=new Uint8Array(i+r.byteLength);return xa(e,o,0),xa(t,o,n),o.set(r,i),o}var p$=Symbol.for("@ipld/js-cid/CID"),h$=20;function Ph({name:e,code:t,encode:r,minDigestLength:n,maxDigestLength:i}){return new y$(e,t,r,n,i)}var y$=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,i){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??h$,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?jf(r,this.code,t?.truncate):r.then(n=>jf(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function jf(e,t,r){if(r!=null&&r!==e.byteLength){if(r>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,r)}return Rl(t,e)}var et=xr(Gr(),1),Rh=xr(dT(),1),Cf=e=>et.Type.Union([e,et.Type.Null()]),Dh=/^(k51qz|baguq)[0-9a-z]{56,57}$/,g$=/^[0-9A-Fa-f]{7,8}$/g;et.FormatRegistry.Set("EntityID",e=>!!e.match(g$)||!!e.match(Dh));var m$=et.Type.String(),yu=e=>e?.enc instanceof Uint8Array;et.FormatRegistry.Set("CID",e=>!!e.match(Dh));var Mh=et.Type.String({format:"CID"}),b$=/^http([s]?):\/\/.*\..*/;et.FormatRegistry.Set("URL",e=>!!e.match(b$));var AC=et.Type.String({format:"URL"}),Lh=et.Type.Object({en:m$,at:et.Type.String(),vl:Cf(et.Type.Union([et.Type.String(),et.Type.Boolean(),et.Type.Number()])),ts:et.Type.String(),ag:et.Type.String(),pv:Cf(Mh)}),Uf=Rh.TypeCompiler.Compile(Lh),SC=Uf.Check.bind(Uf),v$=et.Type.Composite([et.Type.Object({cid:Mh}),Lh]),gu=Rh.TypeCompiler.Compile(v$),w$=e=>Array.from(gu.Errors(e)),Bh=gu.Check.bind(gu);function Vh(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var _$=Ph({name:"sha2-256",code:18,encode:Vh("SHA-256")}),IC=Ph({name:"sha2-512",code:19,encode:Vh("SHA-512")}),{WARN:Pf,LOG:kC,DEBUG:T$,VERBOSE:Aa,ERROR:Fh}=Ae.setup(Ae.INFO),E$=114;function x$(e,t=["cid"]){if(!e)throw Fh("falsy log",e);let r=e.cid;if(yu(e))return r||(r=Dl(zh(e).bytes).toString()),Pf("preparing an encrypted applog - really?"),{log:e,cid:r};let n={};for(let[i,o]of Object.entries(e))o===void 0&&(Pf(`log.${i} is undefined, which is not allowed - encoding as null`,e),o=null),t.includes(i)?Aa("excluding app log",{key:i,val:o}):n[i]=o;return{log:n,cid:r}}function O$(e){return Dl(A$(e).bytes)}function A$(e){return zh(x$(e)?.log)}function Dl(e){let t=Lw(e),r=Nh.create(_$.code,t),n=or.create(1,$h,r);return Aa("[getCidSync]",{bytes:e,hash:t,digest:r,cid:n}),n}function zh(e){T$("[encodeBlock]",e);try{let t=Ul(e);return{bytes:t,cid:Dl(t)}}catch(t){throw Fh("[encodeBlock] failed to encode:",e,t)}}function S$(e){let t=null,r=[];try{t=or.parse(e)}catch(n){Aa("[retrieveThread] couldn't parse pubID with default base"),r.push(n)}if(!t)try{t=or.parse(e,Co)}catch(n){Aa("[retrieveThread] couldn't parse pubID with base36"),r.push(n)}return{cid:t,errors:t?null:r,isIpns:t&&Ml(t)}}function Ml(e){return e.code===E$}function mu(e){return typeof e=="string"?or.parse(e):typeof e.toV1!="function"?or.decode(e.bytes):e}function qh(e,t){if(!e||!t)throw new Error(`[areCidsEqual] invalid params: ${e}, ${t}`);if(e===t)return!0;let r=mu(e),n=mu(t);return r.toV1().toString()===n.toV1().toString()}function Rf(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function I$(e,t){let r=Rf(e),n=Rf(t);return+r<+n}var{WARN:k$,LOG:$C,DEBUG:NC,VERBOSE:Sa,ERROR:Ia}=Ae.setup(Ae.INFO),$$=(e,t,r="asc")=>r==="asc"?e.localeCompare(t,"en-US"):t.localeCompare(e,"en-US"),Kh=(e,t,r)=>Je.structural(Ef(t,e),Ef(r,e)),N$=(e,t,r="asc")=>$$(e.ts,t.ts,r),jC=ik(Kh,["en","at"]);function Qi(e,t="asc"){return e.sort((r,n)=>N$(r,n,t))}var j$=(e,t)=>I$(new Date(e.ts),new Date(t.ts)),C$=()=>{k$("[removeDuplicateAppLogs] mode not set; pass 'safety' or 'cleanup' for optimal behavior")},Df=e=>{let t=new Map,r=Sa.isEnabled;for(let n of e){if(!n)throw Ia("falsy entry in applogs",e),new Error("falsy entry in applogs");if(!n.cid)throw Ia("applog with missing CID",n),new Error("applog with missing CID");let i=n.cid,o=t.get(i);o?r&&Sa("Skipping duplicate applog:",[o,n]):t.set(i,n)}return Array.from(t.values())},U$=e=>{let t=new Set,r=Sa.isEnabled,n=r?new Map:null,i=null,o=0;for(let a of e){if(!a)throw Ia("falsy entry in applogs",e),new Error("falsy entry in applogs");if(!a.cid)throw Ia("applog with missing CID",a),new Error("applog with missing CID");let s=a.cid;t.has(s)?(i||(i=e.slice(0,o)),r&&Sa("Skipping duplicate applog:",[n?.get(s),a])):(t.add(s),n&&n.set(s,a),i&&i.push(a)),o++}return i??e},Gh=(e,t)=>t?t==="safety"?U$(e):Df(e):(C$(),Df(e));function P$(e){return typeof e=="string"&&e.startsWith("?")}function R$(e){return e.slice(1)}function Hh(e,t){let r={},n={};for(let[i,o]of Object.entries(e))if(P$(o)){let a=R$(o),s=t[a];s?n[i]=s:r[i]=a}else n[i]=o;return[n,r]}function D$(e,t,r){let n;if(t){let i=typeof t;i==="string"?n=t===r:i==="function"?n=t(r):typeof t.has=="function"?n=t.has(r):Array.isArray(t)&&!Array.isArray(r)?n=t.includes(r):n=t===r}else n=t===r;return e.charAt(0)==="!"?!n:n}var Wh=function(e){for(var t=0,r=0,n=e.length;r<n;r++)t+=e[r];return t},Mf=function(e){return Wh(e)/e.length},kt={max:function(e){return Math.max.apply(null,e)},min:function(e){return Math.min.apply(null,e)},range:function(e){return kt.max(e)-kt.min(e)},midrange:function(e){return kt.range(e)/2},sum:Wh,mean:Mf,average:Mf,median:function(e){e.sort(function(r,n){return r-n});var t=e.length/2;return t%1?e[t-.5]:(e[t-1]+e[t])/2},modes:function(e){if(!e.length)return[];var t={},r=0,n=[];return e.forEach(function(i){t[i]?t[i]++:t[i]=1,t[i]>r?(n=[i],r=t[i]):t[i]===r&&(n.push(i),r=t[i])}),n},variance:function(e){var t=kt.mean(e);return kt.mean(e.map(function(r){return Math.pow(r-t,2)}))},standardDeviation:function(e){return Math.sqrt(kt.variance(e))},meanAbsoluteDeviation:function(e){var t=kt.mean(e);return kt.mean(e.map(function(r){return Math.abs(r-t)}))},zScores:function(e){var t=kt.mean(e),r=kt.standardDeviation(e);return e.map(function(n){return(n-t)/r})}};kt.average=kt.mean;function Jh(){return new Date().toISOString()}var{WARN:M$,LOG:CC,DEBUG:He,VERBOSE:UC,ERROR:ka}=Ae.setup(Ae.INFO);function L$(e,t){He(`[ensureTsPvAndFinalizeApplogs] ENTER - ${e.length} applogs, thread size=${t.size}`);let r=Jh(),n=t;He("[ensureTsPvAndFinalizeApplogs] About to map over applogs");let i=e.map((o,a)=>{He(`[ensureTsPvAndFinalizeApplogs] Processing applog ${a+1}/${e.length}`);let s=B$(o,{ts:r,threadForPv:n});return He(`[ensureTsPvAndFinalizeApplogs] Finalized applog ${a+1}/${e.length}`),s});return He(`[ensureTsPvAndFinalizeApplogs] EXIT - mapped ${i.length} applogs`),i}function B$(e,{ts:t,threadForPv:r}={}){He(`[finalizeApplogForInsert] ENTER - en=${e.en}, at=${e.at}`),He("[finalizeApplogForInsert] About to call withTs");let n=z$(e,t??Jh());He(`[finalizeApplogForInsert] About to call withPvFrom (thread size=${r?.size??"null"})`);let i=q$(n,r);He("[finalizeApplogForInsert] About to call encodeApplogAndGetCid");let o=O$(i).toString();He(`[finalizeApplogForInsert] CID created: ${o}`),e.cid&&e.cid!==o&&M$("[finalizeApplogForInsert] overwriting wrong CID",{log:e,cid:o,logWithPv:i});let a={...i,cid:o};if(He("[finalizeApplogForInsert] About to validate applog"),!Bh(a))throw ka(`Bogus Applog ${JSON.stringify(a)}`,w$(a));return He(`[finalizeApplogForInsert] EXIT - CID=${o}`),Object.freeze(a)}function V$(e){return!!e.ts}function F$(e){return!!e.pv}function z$(e,t){return V$(e)?e:{...e,ts:t}}function q$(e,t){if(He(`[withPvFrom] ENTER - en=${e.en}, at=${e.at}, hasPv=${e.pv!==void 0}`),e.pv!==void 0)return He("[withPvFrom] EXIT early - pv already set"),e;if(t){let{en:r,at:n}=e;He(`[withPvFrom] About to call thread.findLast for en=${r}, at=${n}, thread.size=${t.size}`);let i=t.findLast(a=>a.en==r&&a.at==n);if(He(`[withPvFrom] findLast completed, found=${!!i}`),He("[withPvFrom] About to check equality"),Kh(["en","at","vl","ts","ag"],e,i))throw ka("[withPvFrom] Same as previous:",{log:e,pv:i,thread:t});let o=(e.pv!==void 0?e.pv:i?.cid)??null;return He(`[withPvFrom] EXIT - prevLogCid=${o}`),{...e,pv:o}}else{if(!F$(e))throw ka("[withPvFrom] no thread and no pv:",e);return He("[withPvFrom] EXIT - no thread, returning log with existing pv"),e}}function bu(e){let t=()=>(Le(()=>e.length<2&&He(`joinThreads with count=${e.length}`)),Qi(Gh(e.flatMap(i=>{let o=i.applogs;if(!o)throw ka("falsy applogs of thread",i),new Error("falsy applogs of thread");return o}),"cleanup"))),r=Le(()=>t()),n=mt(function(i,o){return Kr(i)?{init:Le(()=>t())}:{added:i.added.filter(a=>!this.hasApplog(a,!0)),removed:i.removed?.filter(a=>!!this.parents.some(s=>s===o?!1:s.hasApplog(a,!0)))}});return new ps(Le(()=>`join(~ ${e.map(i=>i.name).join(", ")})`),e,["?"],r,n)}var{WARN:Lf,LOG:PC,DEBUG:Bf,VERBOSE:tn,ERROR:Io}=Ae.setup(Ae.INFO),ps=class vu extends qn{constructor(t,r,n,i,o,a=null,s){super(t,r,n,o?Be.array([...i],{deep:!1,name:`${t}.array`}):i),this.name=t,this._initialLogs=i,this._eventMapper=o,this._writeMapper=a,this._readOnly=s,li(this,{onParentUpdate:mt}),o&&this.subscribeToParents()}static mapWrites(t,r,n){return new vu(`${r}<${t.nameAndSizeUntracked}>`,t,t.filters,t._applogs,null,n)}static asReadOnly(t){return t.readOnly?t:new vu(`readOnly(${t.name})`,t,t.filters,t._applogs,null,null,!0)}_parentSubscriptions=null;insert(t){if(this.readOnly)throw Io("[MappedThread] insert() called on read-only thread:",this.nameAndSizeUntracked);let r=this._writeMapper?this._writeMapper(t):t;if(!(this._writeMapper&&!r))return this.parents.forEach(n=>n.insert(r))}insertRaw(t){if(this.readOnly)throw Io("[MappedThread] insertRaw() called on read-only thread:",this.nameAndSizeUntracked);let r=this._writeMapper?this._writeMapper(t):t;if(!(this._writeMapper&&!r))return this.parents.forEach(n=>n.insertRaw(r))}subscribeToParents(){this._parentSubscriptions=new Map;let t=Dt(()=>{this.parents.length||Lf("MappedThread has no parents",this),tn(`[MappedThread: ${this.name}] subscribing to parents:`,this.parents.map(n=>n.name));let r=new Set([...this._parentSubscriptions.keys()]);for(let n of this.parents){if(r.delete(n)){tn(`[MappedThread: ${this.name}] Skipping re-sub to parent`,n.nameAndSizeUntracked);continue}tn(`[MappedThread: ${this.name}] sub to new parent`,n.nameAndSizeUntracked);let i=this.onParentUpdate.bind(this,n),o=n.subscribe(i,"derived");this._parentSubscriptions.set(n,o)}for(let n of r)tn(`[MappedThread: ${this.name}] un-subscribing from old parent`,n.nameAndSizeUntracked),this._parentSubscriptions.get(n)(),this._parentSubscriptions.delete(n)})}subscribe(t,r){return this._parentSubscriptions||this.subscribeToParents(),super.subscribe(t,r)}triggerRemap(){if(!this._eventMapper)throw Io("triggerRemap on a thread that is not actually mapping?!",this.nameAndSizeUntracked);Bf(`MappedThread{${this.nameAndSizeUntracked}} triggerRemap`),this.parents.length!==1&&Lf(`MappedThread{${this.nameAndSizeUntracked}} triggerRemap with parentCount=${this.parents.length} - not meant for this`),this.parents.forEach(t=>{this.onParentUpdate(t,{init:Le(()=>br(t.applogs))})})}onParentUpdate(t,r){tn(`MappedThread{${this.nameAndSizeUntracked}} parentUpdate`,r);let n=this._eventMapper?this._eventMapper(r,t):r;if(this._eventMapper)if(tn(`MappedThread{${this.nameAndSizeUntracked}} parentUpdate => mapped`,n),Kr(n))this._applogs.replace([...n.init]);else{for(let i of n.added)this._applogs.splice(yk(this._applogs,i,"ts"),0,i);if(n.removed){for(let i of n.removed)if(!this._applogs.remove(i))if(!Kr(r)&&r.removed?.includes(i))Bf("Ignoring remove event for non-existent because it was part of parent event's removed",i,r);else throw Io(`MappedThread{${this.name}} toRemove contained log that doesn't exist`,i,{thread:this,event:r,mapResult:n})}}tn(`MappedThread{${this.nameAndSizeUntracked}} parentUpdate => deps?`,rs(this._applogs)),this.notifySubscribers(n)}get readOnly(){return this._readOnly??!1}},{WARN:RC,LOG:DC,DEBUG:MC,VERBOSE:Ms,ERROR:K$}=Ae.setup(Ae.INFO),Kn=tt("rollingFilter",function(e,t,r={}){let n=H$(t),i=Vf(n),o=Be.array(Le(function(){return i(e.applogs)}),{deep:!1,name:`${e.name} | ${r.name||`rollingFilter.array{${Ji(n)}}`}`}),a=f=>{let d;return Kr(f)?d={init:i(f.init)}:d={added:i(f.added),removed:f.removed},Ms(`rollingFilter{${e.nameAndSizeUntracked} | ${r.name?` '${r.name}'}`:""} parentUpdate`,n,f,"=>",d),d},s=new ps(`${e.name} | ${r.name||`rollingFilter{${Ji(n)}}`}`,e,[...e.filters,...r.extraFilterName?[r.extraFilterName]:[]],o,a),u=I_(()=>br(t),f=>{Ms(`rollingFilter<${e.nameAndSizeUntracked}>${r.name?` '${r.name}'`:""} patternUpdate`,n,"=>",f),n=f,i=Vf(n),s.triggerRemap()}),l=Sn(o,()=>{Ms(`rollingFilter<${Le(()=>e.name)}>${r.name?` '${r.name}'`:""} unobserve`,n),u(),l()});return s},{equals:bo,argsDebugName:(e,t,r)=>We({caller:"rollingFilter",thread:e,pattern:t,args:r})}),G$=tt("rollingMapper",function(e,t,r={}){let n=Le(()=>t.call(null,{init:e.applogs},e));if(!Kr(n))throw K$("Initial run must return init event");let i=n.init;return new ps(`${e.name} | ${r.name||"rollingMapper"}`,e,[...e.filters,...r.extraFilterName?[r.extraFilterName]:[]],i,t)},{equals:bo,argsDebugName:(e,t,r)=>We({caller:"rollingMapper",thread:e,args:r})}),LC=tt("rollingAcc",function(e,t,r,n={}){let i=mt(r);return i({init:e.applogs},t),e.subscribe(o=>{i(o,t)},"derived"),t},{argsDebugName:(e,t,r,n)=>`rollingAcc{${e.nameAndSizeUntracked}${n?.name?` | ${n?.name}`:""}}`}),H$=function(e){let t=Le(function(){return Object.fromEntries(Object.entries(br(e)).map(([r,n])=>[br(r),br(n)]))});if(!Object.entries(t).length)throw new Error("Pattern is empty");return t};function Vf(e){return function(t){return t.filter(function(r){for(let n of Object.keys(e)){let i=e[n];if(i===void 0)continue;let o=r[n.startsWith("!")?n.slice(1):n];if(!D$(n,i,o))return!1}return!0})}}var BC=ps.asReadOnly,{WARN:W$,LOG:J$,DEBUG:Ge,VERBOSE:Qh,ERROR:Lo}=Ae.setup(Ae.INFO),Q$=class extends qn{constructor(e,t=[],r){super(e,null,r,t),li(this,{insertRaw:mt,purge:mt})}purge(e){let t=this.applogs.length;return this._applogs=this.applogs.filter(r=>!e.includes(r.cid)),t-this.applogs.length}insert(e){Ge(`[WriteableThread.insert] ENTER - ${e.length} applogs for thread "${this.name}"`),Ge("[WriteableThread.insert] About to call ensureTsPvAndFinalizeApplogs");let t=L$(e,this);Ge(`[WriteableThread.insert] ensureTsPvAndFinalizeApplogs completed, mapped=${t.length} applogs`),Ge("[WriteableThread.insert] About to call insertRaw");let r=this.insertRaw(t);return Ge("[WriteableThread.insert] insertRaw completed"),r}insertMissing(e,t=!1){let r=e.filter(n=>!this.hasApplog(n,t));return r.length===0?(Qh("[insertMissing] no missing applogs"),[]):this.insertRaw(r)??[]}insertRaw(e){Ge(`[WriteableThread.insertRaw] ENTER - ${e.length} applogs for thread "${this.name}"`),Ge("[WriteableThread.insertRaw] About to deduplicate");let t=Gh(e,"safety");if(t.length!==e.length)throw Lo(`[insertRaw] duplicate applogs passed: ${e.length-t.length}`,{appLogsToInsert:e,deduplicated:t});Ge("[WriteableThread.insertRaw] Deduplication done"),Ge("[WriteableThread.insertRaw] About to validate");let r=e.filter(a=>!Bh(a));if(r.length)throw Lo(`[insertRaw] bogus applogs passed: ${r.length}`,{bogus:r});Ge("[WriteableThread.insertRaw] Validation done"),Ge("[WriteableThread.insertRaw] About to check for existing");let n=e.filter(a=>this.hasApplog(a,!1));if(n.length)throw Lo(`[insertRaw] already existing applogs passed: ${n.length}`,{existing:n});if(Ge("[WriteableThread.insertRaw] Existing check done"),!e.length){W$("[insertRaw] skipping empty insert empty logs array");return}(!this.hasParents&&!(this instanceof vo)?J$:Ge)("Inserting:",e.length===1?e[0]:e,{ds:this}),Ge("[WriteableThread.insertRaw] About to sort applogs"),Qi(e);let i=this._applogs.length&&j$(e[0],this._applogs[this._applogs.length-1]);Ge("[WriteableThread.insertRaw] About to push to _applogs array");let o=5e4;for(let a=0;a<e.length;a+=o)this._applogs.push(...e.slice(a,a+o));return i&&(Ge("[WriteableThread.insertRaw] About to sort _applogs (sortNeeded=true)"),Qi(this._applogs)),Ge("[WriteableThread.insertRaw] About to notify subscribers"),this.notifySubscribers({added:e,removed:null}),Ge("[WriteableThread.insertRaw] Subscribers notified"),Ge("[WriteableThread.insertRaw] About to call persist (void - not awaited)"),this.persist(e),Ge(`[WriteableThread.insertRaw] EXIT - returning ${e.length} applogs`),e}get readOnly(){return!1}},vo=class Bo extends Q${constructor(t,r,n,i){super(t,r,n),this._readOnly=i,li(this,{_applogs:Be.shallow})}static empty(t){return Bo.fromArray([],t??"empty in-memory",!1)}static fromArray(t,r,n=!1){return new Bo(r??"in-memory",t,[],n)}static fromReadOnlyArray(t,r){return new Bo(r??"in-memory",t,[],!0)}get readOnly(){return this._readOnly}async persist(t){if(Qh("[InMem.persist] no persist for",t),this.readOnly)throw Lo("[persist] called for readOnly thread")}},{WARN:VC,LOG:FC,DEBUG:zC,VERBOSE:qC,ERROR:KC}=Ae.setup(Ae.INFO),{WARN:GC,LOG:HC,DEBUG:WC,VERBOSE:JC,ERROR:QC}=Ae.setup(Ae.INFO),Y$=class{constructor(e,t,r=null){this.logsOfThisNode=e,this.variables=t,this.prevNode=r,li(this,{threadOfTrail:Fe})}get record(){return this.variables}get threadOfTrail(){return this.prevNode?bu([this.logsOfThisNode,this.prevNode.threadOfTrail]):this.logsOfThisNode}get trailLogs(){return this.threadOfTrail.applogs}},Yh=class{constructor(e){this.nodes=e,li(this,{threadOfAllTrails:Fe,size:Fe,isEmpty:Fe})}get size(){return this.records.length}get isEmpty(){return this.records.length===0}get untrackedSize(){return Le(()=>this.records.length)}get records(){return Ht(()=>this.nodes.map(({variables:e})=>e),{name:"QueryResult.records"})}get leafNodeThread(){return bu(Ht(()=>this.nodes.map(({logsOfThisNode:e})=>e),{name:"QueryResult.leafNodeThread"}))}get leafNodeLogSet(){return Ht(()=>this.nodes.map(({logsOfThisNode:e})=>e.applogs),{name:"QueryResult.leafNodeLogSet"})}get leafNodeLogs(){return Ht(()=>this.nodes.flatMap(({logsOfThisNode:e})=>e.applogs),{name:"QueryResult.leafNodeLogs"})}get threadOfAllTrails(){return bu(Ht(()=>this.nodes.map(e=>e.threadOfTrail),{name:"QueryResult.threadOfAllTrails"}))}get thread(){return this.threadOfAllTrails}get allApplogs(){return this.threadOfAllTrails.applogs}},{WARN:YC,LOG:hs,DEBUG:_r,VERBOSE:Se,ERROR:cn}=Ae.setup(Ae.INFO,{prefix:"[q]"}),Ls=null,XC=tt("lastWriteWins",function(e,{inverseToOnlyReturnFirstLogs:t,tolerateAlreadyFiltered:r}={}){if(Se(`lastWriteWins${t?".inversed":""} < ${e.nameAndSizeUntracked} > initializing`),e.filters.includes("lastWriteWins")){if(r)return _r("[lastWriteWins] already filtered, but tolerateAlreadyFiltered=true, so returning"),e;throw cn("thread already filtered lastWriteWins:",e.filters,{name:e.name})}let n,i=G$(e,function(o,a){let s=Kr(o),u,l=[],f=s?null:[];s?(n=new Map,u=o.init):u=o.added;let d;for(let k=t?0:u.length-1;t?k<u.length:k>=0;t?k++:k--){let E=u[k],T=E.en+"|"+E.at;if(d&&(t?d>E.ts:d<E.ts))throw cn("lastWriteWins.mapper logs not sorted:",d,t?">":"<",E.ts,{log:E,i:k,newLogs:u,inverseToOnlyReturnFirstLogs:t});d=E.ts;let B=n.get(T);(!B||(t?B.ts>E.ts:B.ts<E.ts))&&(B&&!s&&f.push(B),l.push(E),n.set(T,E))}return Qi(l),Se.isDisabled||Se(`lastWriteWins${t?".inversed":""}<${e.nameAndSizeUntracked}> mapped event`,s?{...Object.fromEntries(Object.entries(o).map(([k,E])=>[k,E?.length])),toAdd:l.length,toRemove:f}:{...o,toAdd:l,toRemove:f}),s?{init:l}:{added:l,removed:f}},{name:`lastWriteWins${t?".inversed":""}`,extraFilterName:"lastWriteWins"});return Se.isDisabled||Dt(()=>{Se(`lastWriteWins<${e.nameAndSizeUntracked}> filtered down to`,i.applogs.length)}),i},{equals:bo,argsDebugName:e=>We({caller:"lastWriteWins",thread:e})}),ZC=tt("withoutDeleted",function(e){if(Se.isEnabled&&Se(`withoutDeleted<${e.nameAndSizeUntracked}>`),e.filters.includes("withoutDeleted"))throw cn("thread already filtered withoutDeleted:",e.filters,{name:e.name});let t=Kn(e,{at:["isDeleted","relation/isDeleted","block/isDeleted"],vl:!0},{name:"isDeleted"});Se.isEnabled&&Se(`withoutDeleted<${e.nameAndSizeUntracked}> deletionLogs:`,Le(function(){return[...t.applogs]}));let r=We({caller:"allDeletedEntities",thread:e}),n=Tk(function(){return t.map(i=>i.en)},{name:r});return Se.isEnabled&&Dt(()=>{Se(`withoutDeleted<${e.nameAndSizeUntracked}> deleted:`,[...n])}),Kn(e,{"!en":n},{name:"withoutDeleted",extraFilterName:"withoutDeleted"})},{equals:bo}),Xh=tt("query",function e(t,r,n={},i={}){oN();let o=Zh(t);_r(`query<${o.nameAndSizeUntracked}>:`,r);let a=Array.isArray(r)?r:[r],s;if(a.length===1)s=null;else{let f=a.slice(0,-1);s=e(o,f,n,i)}let u=a[a.length-1],l=X$(o,s,u,i);return Se.isDisabled||Dt(()=>Se("query result:",br(l))),l},{equals:Cl,argsDebugName:(e,t,r)=>We({caller:"query",thread:e,args:r?{pattern:t,startVars:r}:t})}),X$=tt("queryStep",function(e,t,r,n={}){if(_r(`queryStep<${e.nameAndSizeUntracked}> with`,t?.untrackedSize??"all","nodes, pattern:",r),!Object.entries(r).length)throw new Error("Pattern is empty");function i(a){let[s,u]=Hh(r,a?.variables??{});Se("[queryStep.doQuery] patternWithoutVars: ",s);let l=Kn(e,s),f=ys(u),d=Ht(function(){let k=l.map(E=>({log:E,vars:f(E)}));return Se.isEnabled&&Se("[queryStep.doQuery] step node:",a?.variables," =>",k,"from:",Le(()=>l.applogs)),k.map(({log:E,vars:T})=>{let B=Object.assign({},a?.variables,T);return new Y$(Ak.fromArray([E],We({caller:"QueryNode",thread:l,pattern:`${Ji(B)}@${Ji(s)}`})),B,a)})},{name:We({caller:"doQuery.mapNodes",thread:l,pattern:r})});return Se.isEnabled&&Dt(()=>Se("[queryStep.doQuery] resultNodes:",[...d])),n.debug&&hs("[queryStep] step result:",Le(()=>d.map(({variables:k,logsOfThisNode:E})=>({variables:k,thread:E})))),d}let o=Ht(function(){return _r(`[queryStep] Running with ${t?.nodes?.length} input nodes:`),t?[...t.nodes.flatMap(i)]:[...i(null)]},{name:We({caller:"queryStep",thread:e,pattern:r})});return Se.isEnabled&&Dt(()=>Se("[queryStep] observableResultNodes:",[...o])),new Yh(o)},{equals:Cl,argsDebugName:(e,t,r)=>We({caller:"queryStep",thread:e,pattern:r})}),e5=tt("queryNot",function(e,t,r,n={}){let i=t.nodes;_r(`queryNot<${e.nameAndSizeUntracked}> from: ${i.length} nodes`);let o=Array.isArray(r)?r:[r];for(let a of o){if(!Object.entries(r).length)throw new Error("Pattern is empty");i=i.filter(function({variables:s}){let[u,l]=Hh(a,s??{});Se("[queryNot] patternWithoutVars: ",u);let f=Kn(e,u);return Se("[queryNot] step node:",s," =>",f.size,"applogs"),Se.isDisabled||Se("[queryNot] step node:",s," => empty?",Le(()=>f.applogs)),n.debug&&hs("[queryNot] node result:",s,"=>",f.applogs),f.isEmpty})}return new Yh(i)},{equals:Cl,argsDebugName:(e,t,r)=>We({caller:"queryNot",thread:e,pattern:r})}),t5=tt("filterAndMap",function(e,t,r){_r(`filterAndMap<${e.nameAndSizeUntracked}>`,t);let n=Kn(e,t);Se.isEnabled&&(Se("[filterAndMap] filtered:",n.untrackedSize),Dt(()=>Se("[filterAndMap] filtered:",n.applogs)));let i=We({thread:e,pattern:t,caller:"filterAndMap"}),o=Ht(()=>tN(n,r),{name:i});return Se.isDisabled||Dt(()=>Se("[filterAndMap] mapped:",o)),o},{equals:Je.structural,argsDebugName:(e,t)=>We({caller:"filterAndMap",thread:e,pattern:t})}),r5=tt("queryAndMap",function(e,t,r,n={}){let i=Zh(e);_r(`queryAndMap<${i.nameAndSizeUntracked}>`,{patternOrPatterns:t,variables:n,map:r});let o=We({thread:i,caller:"queryAndMap"}),a=Xh(i,t);Se("[queryAndMap] filtered count:",a.untrackedSize);let s=Ht(()=>rN(a,r),{name:o});return Se.isDisabled||Dt(()=>Se("[queryAndMap] result:",br(s))),s},{equals:Je.structural,argsDebugName:(e,t)=>We({caller:"queryAndMap",thread:e,pattern:t})}),n5=tt("queryEntity",function(e,t,r,n){_r(`queryEntity<${e.nameAndSizeUntracked}>`,r,t);let i=Kn(e,{en:r,at:nN(t,n)});return Se("queryEntity applogs:",i.applogs),Fe(()=>i.isEmpty?null:Object.fromEntries(i.map(({at:o,vl:a})=>[o.slice(t.length+1),a])))},{equals:vk,argsDebugName:(e,t,r)=>We({caller:"queryEntity",thread:e,args:{name:t,entityID:r}})}),i5=tt("agentsOfThread",function(e){_r(`agentsOfThread<${e.nameAndSizeUntracked}>`);let t=Be.map(),r=mt(i=>{for(let o of Kr(i)?i.init:i.added){let a=t.get(o.ag)??0;t.set(o.ag,a+1)}for(let o of!Kr(i)&&i.removed||[]){let a=t.get(o.ag);if(!a||a<1)throw cn("[agentsOfThread] number is now negative",{log:o,event:i,mapped:t,prev:a});t.set(o.ag,a-1)}hs(`agentsOfThread<${e.nameAndSizeUntracked}> processed event`,{event:i,mapped:t})});r({init:e.applogs});let n=e.subscribe(r,"derived");return Sn(t,n),t}),Z$=tt("entityOverlap",function(e,t){return hs(`entityOverlap<${e.nameAndSizeUntracked}, ${t.nameAndSizeUntracked}>`),Fe(()=>{let r=new Set(e.map(i=>i.en)),n=new Set(t.map(i=>i.en));return[...r].filter(i=>n.has(i))})}),o5=tt("entityOverlapCount",function(e,t){return Fe(()=>Z$(e,t).get().length)}),eN=tt("querySingle",function(e,t,r={}){let n=Xh(e,t,r);return Fe(()=>{if(n.isEmpty)return null;if(n.size>1)throw cn("[querySingle] got",n.size,"results:",n);let i=n.nodes[0].logsOfThisNode;if(i.size!=1)throw cn("[querySingle] single result, but got",i.size,"logs:",i.applogs);return i.applogs[0]})},{equals:Je.structural,argsDebugName:(e,t)=>We({caller:"querySingle",thread:e,pattern:t})}),a5=tt("querySingleAndMap",function(e,t,r,n={}){let i=eN(e,t,n);return Fe(()=>{let o=i.get();if(o)return typeof r=="string"?o[r]:ys(r)(o)})},{equals:Je.structural,argsDebugName:(e,t)=>We({caller:"querySingleAndMap",thread:e,pattern:t})}),tN=function(e,t){return typeof t=="function"?e.map(t):typeof t=="string"?e.map(r=>r[t]):e.map(ys(t))},rN=function(e,t){return typeof t=="function"?e.records.map(t):typeof t=="string"?e.nodes.map(r=>{if(!Object.hasOwn(r.record,t)){if(r.logsOfThisNode.size!==1)throw cn(`not sure what to map (it's not a var and a result node log count of ${r.logsOfThisNode.size})`);return r.logsOfThisNode.firstLog[t]}return r.record[t]}):e.nodes.map(r=>ys(t)(e))};function ys(e){return t=>Object.entries(e).reduce((r,[n,i])=>(r[i]=t[n],r),{})}function nN(e,t){return t.map(r=>iN(e,r))}function iN(e,t){return`${e}/${t}`}function Zh(e,t){return Array.isArray(e)?vo.fromArray(e,t||`threadFromArray[${e.length}]`,!0):e}function oN(){if(Ls!=null&&performance.now()>=Ls)throw new aN(Ls)}var aN=class extends Error{constructor(e){super(e)}},sN=Ze({"../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/encode.js"(e,t){"use strict";t.exports=a;var r=128,n=127,i=~n,o=Math.pow(2,31);function a(s,u,l){if(Number.MAX_SAFE_INTEGER&&s>Number.MAX_SAFE_INTEGER)throw a.bytes=0,new RangeError("Could not encode varint");u=u||[],l=l||0;for(var f=l;s>=o;)u[l++]=s&255|r,s/=128;for(;s&i;)u[l++]=s&255|r,s>>>=7;return u[l]=s|0,a.bytes=l-f+1,u}}}),uN=Ze({"../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/decode.js"(e,t){"use strict";t.exports=i;var r=128,n=127;function i(o,u){var s=0,u=u||0,l=0,f=u,d,k=o.length;do{if(f>=k||l>49)throw i.bytes=0,new RangeError("Could not decode varint");d=o[f++],s+=l<28?(d&n)<<l:(d&n)*Math.pow(2,l),l+=7}while(d>=r);return i.bytes=f-u,s}}}),lN=Ze({"../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/length.js"(e,t){"use strict";var r=Math.pow(2,7),n=Math.pow(2,14),i=Math.pow(2,21),o=Math.pow(2,28),a=Math.pow(2,35),s=Math.pow(2,42),u=Math.pow(2,49),l=Math.pow(2,56),f=Math.pow(2,63);t.exports=function(d){return d<r?1:d<n?2:d<i?3:d<o?4:d<a?5:d<s?6:d<u?7:d<l?8:d<f?9:10}}}),Ll=Ze({"../../../node_modules/.pnpm/varint@6.0.0/node_modules/varint/index.js"(e,t){"use strict";t.exports={encode:sN(),decode:uN(),encodingLength:lN()}}}),ey=42;function cN(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;let t=Ka.asCID(e);if(!t)return null;let r=new Uint8Array(t.bytes.byteLength+1);return r.set(t.bytes,1),[new ne(I.tag,ey),new ne(I.bytes,r)]}function fN(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function dN(e){if(Number.isNaN(e))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(e===1/0||e===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function pN(e){for(let t of e.keys())if(typeof t!="string"||t.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var Ff={float64:!0,typeEncoders:{Map:pN,Object:cN,undefined:fN,number:dN}},s5={...Ff,typeEncoders:{...Ff.typeEncoders}};function hN(e){if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return Ka.decode(e.subarray(1))}var wu={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};wu.tags[ey]=hN;var u5={...wu,tags:wu.tags.slice()},l5=xr(Ll(),1),Lr={Null:e=>e===null?e:void 0,Int:e=>Number.isInteger(e)?e:void 0,Float:e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,String:e=>typeof e=="string"?e:void 0,Bool:e=>typeof e=="boolean"?e:void 0,Bytes:e=>e instanceof Uint8Array?e:void 0,Link:e=>e!==null&&typeof e=="object"&&e.asCID===e?e:void 0,List:e=>Array.isArray(e)?e:void 0,Map:e=>e!==null&&typeof e=="object"&&e.asCID!==e&&!Array.isArray(e)&&!(e instanceof Uint8Array)?e:void 0},$i={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Lr.Link,"CarV1HeaderOrV2Pragma > roots (anon)":e=>{if(Lr.List(e)!==void 0){for(let t=0;t<e.length;t++){let r=e[t];if(r=$i["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](r),r===void 0)return;if(r!==e[t]){let n=e.slice(0,t);for(let i=t;i<e.length;i++){let o=e[i];if(o=$i["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return e}},Int:Lr.Int,CarV1HeaderOrV2Pragma:e=>{if(Lr.Map(e)===void 0)return;let t=Object.entries(e),r=e,n=1;for(let i=0;i<t.length;i++){let[o,a]=t[i];switch(o){case"roots":{let s=$i["CarV1HeaderOrV2Pragma > roots (anon)"](e[o]);if(s===void 0)return;if(s!==a||r!==e){if(r===e){r={};for(let u=0;u<i;u++)r[t[u][0]]=t[u][1]}r.roots=s}}break;case"version":{n--;let s=$i.Int(e[o]);if(s===void 0)return;if(s!==a||r!==e){if(r===e){r={};for(let u=0;u<i;u++)r[t[u][0]]=t[u][1]}r.version=s}}break;default:return}}if(!(n>0))return r}},Ni={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Lr.Link,"CarV1HeaderOrV2Pragma > roots (anon)":e=>{if(Lr.List(e)!==void 0){for(let t=0;t<e.length;t++){let r=e[t];if(r=Ni["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](r),r===void 0)return;if(r!==e[t]){let n=e.slice(0,t);for(let i=t;i<e.length;i++){let o=e[i];if(o=Ni["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return e}},Int:Lr.Int,CarV1HeaderOrV2Pragma:e=>{if(Lr.Map(e)===void 0)return;let t=Object.entries(e),r=e,n=1;for(let i=0;i<t.length;i++){let[o,a]=t[i];switch(o){case"roots":{let s=Ni["CarV1HeaderOrV2Pragma > roots (anon)"](a);if(s===void 0)return;if(s!==a||r!==e){if(r===e){r={};for(let u=0;u<i;u++)r[t[u][0]]=t[u][1]}r.roots=s}}break;case"version":{n--;let s=Ni.Int(a);if(s===void 0)return;if(s!==a||r!==e){if(r===e){r={};for(let u=0;u<i;u++)r[t[u][0]]=t[u][1]}r.version=s}}break;default:return}}if(!(n>0))return r}},c5={toTyped:$i.CarV1HeaderOrV2Pragma,toRepresentation:Ni.CarV1HeaderOrV2Pragma},f5=Dd(),d5=xr(Ll(),1),p5=[new ne(I.map,2),new ne(I.string,"version"),new ne(I.uint,1),new ne(I.string,"roots")],h5=new ne(I.tag,42),y5=xr(Ll(),1),{WARN:ty,LOG:g5,DEBUG:Bs,VERBOSE:Bl,ERROR:Un}=Ae.setup(Ae.INFO);async function yN(e){let t=await mN(e);return await gN(t)}async function gN({rootCID:e,blockStore:t},r=[],n){if(!e||!t)throw Un("Empty roots/blocks",{rootCID:e,blockStore:t});let i=[],o=null,a=e,s=new Set,u=null;for(;a;){let f=a.toString();if(s.has(f))throw Un("[decodePubFromBlocks] pub chain has a loop",{currentCID:f,visited:[...s]});s.add(f);let d=await Rn(t,a);if(Bl("[decodePubFromBlocks] root:",f,d,{blockStore:t}),!d)throw Un("[decodePubFromBlocks] root not found in blockStore",{blockStore:t,currentCID:f});let k;if(d?.info){u||(u=d.applogs);let B=await Rn(t,d.applogs);k=await wN(B,t),o||(o=await Rn(t,d.info),Bs("new format - infoLogs",o.logs.map(W=>({[W.toString()]:W}))))}else k=d.applogs;let E=async B=>{let W=B,D=await Rn(t,W);if(!D)throw Un("Could not find applog CID in pub blocks:",W.toString(),{cid:W,root:d,blockStore:t}),new Error(`Could not find applog CID in pub blocks: ${W.toString()}`);return D.pv instanceof or&&(D.pv=D.pv.toV1().toString()),{...D,cid:W.toV1().toString()}},T=await Promise.all(k.map(E));if(i=i.concat(T),!d.prev)break;if(n&&qh(d.prev,n)){Bs("[decodePubFromBlocks] stopping at stopAtCID:",n.toString());break}if(!await t.get(d.prev))throw Un("[decodePubFromBlocks] prev snapshot missing from blockStore",{currentCID:f,prev:d.prev.toString(),stopAtCID:n?.toString(),visited:[...s]});a=d.prev}let l={cid:e,info:o?{...o,logs:await Promise.all(o.logs.map(async f=>{let d=f,k=await Rn(t,d);if(!k)throw Un("Could not find info log CID in pub blocks:",d.toString(),{cid:d,blockStore:t}),new Error(`Could not find info log CID in pub blocks: ${d.toString()}`);return k.pv instanceof or&&(k.pv=k.pv.toV1().toString()),{...k,cid:d.toV1().toString()}}))}:null,applogsCID:u,applogs:i};return Bs("[decodePubFromBlocks] result:",l,{rootCID:e.toString(),blockStore:t,applogs:i}),l}async function mN(e){let t=(await e.getRoots()).map(n=>(typeof n.toV1=="function"?n:or.decode(n.bytes)).toV1().toString()),r=new Map;for await(let{cid:n,bytes:i}of e.blocks()){let o=typeof n.toV1=="function"?n:or.decode(n.bytes);Bl({cidFromCarblocks:n,cid:o}),r.set(o.toV1().toString(),i)}return t.length!==1&&ty("Unexpected roots count:",t),{rootCID:or.parse(t[0]),blockStore:{get:n=>r.get(n.toV1().toString())}}}async function Rn(e,t){try{var r=await e.get(t);if(!r)return ty("returning null"),null}catch(n){if(n.message==="Not Found")return null;throw n}return Pl(r)}function bN(e){return async function*(){for(;;){let{done:t,value:r}=await e.read();if(Bl("[car] chunk",{done:t,value:r}),t)break;yield r}}()}var{WARN:m5,LOG:b5,DEBUG:v5,VERBOSE:w5,ERROR:vN}=Ae.setup(Ae.INFO);async function wN(e,t){return _N(e)?(await Promise.all(e.chunks.map(async r=>{let n=await Rn(t,r);if(!n.logs)throw vN("Weird chunk",n);return n.logs}))).flat():e.logs}function _N(e){return e.chunks}var $a=Yi(ky(),1),TN=Yi($y(),1),ry=!1,ny=!1;$a.isNode&&(process?.env?.LOGGER_TIME_PREFIX&&(ry=process?.env?.LOGGER_TIME_PREFIX==="true"),process?.env?.LOGGER_PERF_PREFIX&&(ny=process?.env?.LOGGER_PERF_PREFIX==="true"));var EN={prefix:void 0,time:ry,delta:ny,dimDebugOnServer:!0,printOriginOnServer:!0,serverInspectOptions:{},customFormattersOnServer:!0,printStackLinesOnServer:!1,dim:!0},Vs=[],iy=class{sinceFirst=0;sinceLast=0;time=!1;delta=!1;constructor(e,t,r,n){Object.assign(this,{sinceFirst:e,sinceLast:t,time:r,delta:n})}toString(){let e=this.sinceFirst*.001,t=e.toFixed(e<5?2:1),r=this.sinceLast<1e3?`${this.sinceLast.toFixed(0)}`.padStart(5," "):`${`${(this.sinceLast*.001).toFixed(this.sinceLast<1e4?1:0)}`.padStart(4," ")}s`;return`[${[this.time?t:null,this.delta?r:null].filter(n=>n!=null).join(",")}]`}},oy=class{constructor(e,t){Object.assign(this,{style:e,string:t})}},ji=!1,Gn=class yt{static ERROR=2;static WARN=4;static INFO=6;static LOG=6;static DEBUG=8;static VERBOSE=10;static firstLog=0;static lastLog=0;static setup(t=yt.INFO,r={}){r=Object.assign({},EN,r),t>10&&console.debug("setup logger",{config:r});let n=this.wrapLog(console.debug,{...r,dim:r.dimDebugOnServer}),i=(...u)=>{typeof window<"u"&&window?.FORCE_DISABLE_LOGLEVEL&&n(...u)};i.isDisabled=!0,i.isEnabled=!1;let o=this.wrapLog(console.groupCollapsed,r),a=(u,l)=>{function f(...k){let E=k[k.length-1];return E===i?E():(o(...k.slice(0,-1)),(async()=>{try{let T=E();return T instanceof Promise?await T:T}finally{console.groupEnd()}})())}let d=Object.assign(l.bind({}),{isEnabled:u,isDisabled:!u,group:f,force:l});return u?d:Object.assign(i.bind({}),{isEnabled:u,isDisabled:!u,group:f,force:d})},s=a(t>=yt.ERROR,this.wrapLog(console.error,r));return{ERROR:(...u)=>(s(...u),new Error((0,TN.default)(u))),WARN:a(t>=yt.WARN,this.wrapLog(console.warn,r)),LOG:a(t>=yt.INFO,this.wrapLog(console.log,r)),DEBUG:a(t>=yt.DEBUG,this.wrapLog(console.log,{...r,dim:r.dimDebugOnServer})),VERBOSE:a(t>=yt.VERBOSE,this.wrapLog(console.debug,{...r,dim:r.dimDebugOnServer}))}}static wrapLog(t,r){if($a.isNode)return t.bind(console);{let n=[];if(r.time||r.delta){let i=$a.isBrowser&&navigator.userAgent.includes("Chrome")?["",yt.timeStr(!!r.time,!!r.delta)]:[];n.push(...i)}return r.prefix&&(ji?n.push(new oy("dim",r.prefix)):n.push(r.prefix)),t.bind(console,...n)}}static timeStr(t,r,n=0){if(!performance.now)return;let i=performance.now();yt.firstLog||(yt.firstLog=i,yt.lastLog=i);let o=new iy(i-yt.firstLog,i-yt.lastLog,t,r);return yt.lastLog=i,n?o.toString():o}static getOriginFromStack(t){let r=!1;for(let n of t.split(`
|
|
62
62
|
`)){let i=n.match(/^\s+at\s+(.*)/);if(i){if(r)return i[1].trim().replace(__dirname,"");r=!0}}}};$a.isBrowser&&(window.devtoolsFormatters=window.devtoolsFormatters??[],window.devtoolsFormatters.push({header:e=>{if(Vs&&Vs.length){for(let t of Vs)if(t.match(e))return["span",{},t.format(e)]}return null},hasBody:()=>!0},{header:e=>{if(!(e instanceof iy))return null;ji||(ji=!0);let t=Gn.timeStr(e.time,e.delta);return["span",{style:"font-weight: light; color: grey"},t?.toString()]},hasBody:()=>!1},{header:e=>e instanceof oy?(ji||(ji=!0),["span",{style:"font-weight: light; color: grey; "},e.string]):null,hasBody:()=>!1}));var _5=new Uint8Array(0);function xN(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function Vl(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function ON(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<e.length;i++){var o=e.charAt(i),a=o.charCodeAt(0);if(r[a]!==255)throw new TypeError(o+" is ambiguous");r[a]=i}var s=e.length,u=e.charAt(0),l=Math.log(s)/Math.log(256),f=Math.log(256)/Math.log(s);function d(T){if(T instanceof Uint8Array||(ArrayBuffer.isView(T)?T=new Uint8Array(T.buffer,T.byteOffset,T.byteLength):Array.isArray(T)&&(T=Uint8Array.from(T))),!(T instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(T.length===0)return"";for(var B=0,W=0,D=0,$=T.length;D!==$&&T[D]===0;)D++,B++;for(var F=($-D)*f+1>>>0,K=new Uint8Array(F);D!==$;){for(var M=T[D],Q=0,q=F-1;(M!==0||Q<W)&&q!==-1;q--,Q++)M+=256*K[q]>>>0,K[q]=M%s>>>0,M=M/s>>>0;if(M!==0)throw new Error("Non-zero carry");W=Q,D++}for(var te=F-W;te!==F&&K[te]===0;)te++;for(var N=u.repeat(B);te<F;++te)N+=e.charAt(K[te]);return N}function k(T){if(typeof T!="string")throw new TypeError("Expected String");if(T.length===0)return new Uint8Array;var B=0;if(T[B]!==" "){for(var W=0,D=0;T[B]===u;)W++,B++;for(var $=(T.length-B)*l+1>>>0,F=new Uint8Array($);T[B];){var K=r[T.charCodeAt(B)];if(K===255)return;for(var M=0,Q=$-1;(K!==0||M<D)&&Q!==-1;Q--,M++)K+=s*F[Q]>>>0,F[Q]=K%256>>>0,K=K/256>>>0;if(K!==0)throw new Error("Non-zero carry");D=M,B++}if(T[B]!==" "){for(var q=$-D;q!==$&&F[q]===0;)q++;for(var te=new Uint8Array(W+($-q)),N=W;q!==$;)te[N++]=F[q++];return te}}}function E(T){var B=k(T);if(B)return B;throw new Error(`Non-${t} character`)}return{encode:d,decodeUnsafe:k,decode:E}}var AN=ON,SN=AN,IN=SN,kN=class{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},$N=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=r}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 ay(this,e)}},NN=class{decoders;constructor(e){this.decoders=e}or(e){return ay(this,e)}decode(e){let t=e[0],r=this.decoders[t];if(r!=null)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ay(e,t){return new NN({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var jN=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new kN(e,t,r),this.decoder=new $N(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function sy({name:e,prefix:t,encode:r,decode:n}){return new jN(e,t,r,n)}function uy({name:e,prefix:t,alphabet:r}){let{encode:n,decode:i}=IN(r,e);return sy({prefix:t,name:e,encode:n,decode:o=>Vl(i(o))})}function CN(e,t,r,n){let i={};for(let f=0;f<t.length;++f)i[t[f]]=f;let o=e.length;for(;e[o-1]==="=";)--o;let a=new Uint8Array(o*r/8|0),s=0,u=0,l=0;for(let f=0;f<o;++f){let d=i[e[f]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);u=u<<r|d,s+=r,s>=8&&(s-=8,a[l++]=255&u>>s)}if(s>=r||255&u<<8-s)throw new SyntaxError("Unexpected end of data");return a}function UN(e,t,r){let n=t[t.length-1]==="=",i=(1<<r)-1,o="",a=0,s=0;for(let u=0;u<e.length;++u)for(s=s<<8|e[u],a+=8;a>r;)a-=r,o+=t[i&s>>a];if(a!==0&&(o+=t[i&s<<r-a]),n)for(;o.length*r&7;)o+="=";return o}function Ar({name:e,prefix:t,bitsPerChar:r,alphabet:n}){return sy({prefix:t,name:e,encode(i){return UN(i,n,r)},decode(i){return CN(i,n,r,e)}})}var Vo=Ar({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),T5=Ar({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),E5=Ar({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),x5=Ar({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),O5=Ar({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),A5=Ar({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),S5=Ar({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),I5=Ar({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),k5=Ar({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Rr=uy({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),$5=uy({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),PN=ly,zf=128,RN=127,DN=~RN,MN=Math.pow(2,31);function ly(e,t,r){t=t||[],r=r||0;for(var n=r;e>=MN;)t[r++]=e&255|zf,e/=128;for(;e&DN;)t[r++]=e&255|zf,e>>>=7;return t[r]=e|0,ly.bytes=r-n+1,t}var LN=_u,BN=128,qf=127;function _u(e,n){var r=0,n=n||0,i=0,o=n,a,s=e.length;do{if(o>=s)throw _u.bytes=0,new RangeError("Could not decode varint");a=e[o++],r+=i<28?(a&qf)<<i:(a&qf)*Math.pow(2,i),i+=7}while(a>=BN);return _u.bytes=o-n,r}var VN=Math.pow(2,7),FN=Math.pow(2,14),zN=Math.pow(2,21),qN=Math.pow(2,28),KN=Math.pow(2,35),GN=Math.pow(2,42),HN=Math.pow(2,49),WN=Math.pow(2,56),JN=Math.pow(2,63),QN=function(e){return e<VN?1:e<FN?2:e<zN?3:e<qN?4:e<KN?5:e<GN?6:e<HN?7:e<WN?8:e<JN?9:10},YN={encode:PN,decode:LN,encodingLength:QN},XN=YN,Na=XN;function Tu(e,t=0){return[Na.decode(e,t),Na.decode.bytes]}function ja(e,t,r=0){return Na.encode(e,t,r),t}function Ca(e){return Na.encodingLength(e)}function ZN(e,t){let r=t.byteLength,n=Ca(e),i=n+Ca(r),o=new Uint8Array(i+r);return ja(e,o,0),ja(r,o,n),o.set(t,i),new Fl(e,r,t,o)}function ej(e){let t=Vl(e),[r,n]=Tu(t),[i,o]=Tu(t.subarray(n)),a=t.subarray(n+o);if(a.byteLength!==i)throw new Error("Incorrect length");return new Fl(r,i,a,t)}function tj(e,t){if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&xN(e.bytes,r.bytes)}}var Fl=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}};function Kf(e,t){let{bytes:r,version:n}=e;switch(n){case 0:return nj(r,Eu(e),t??Rr.encoder);default:return ij(r,Eu(e),t??Vo.encoder)}}var Gf=new WeakMap;function Eu(e){let t=Gf.get(e);if(t==null){let r=new Map;return Gf.set(e,r),r}return t}var N5=class ct{code;version;multihash;bytes;"/";constructor(t,r,n,i){this.code=r,this.version=t,this.multihash=n,this.bytes=i,this["/"]=i}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:t,multihash:r}=this;if(t!==Ai)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==oj)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ct.createV0(r)}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:t,digest:r}=this.multihash,n=ZN(t,r);return ct.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(t){return ct.equals(this,t)}static equals(t,r){let n=r;return n!=null&&t.code===n.code&&t.version===n.version&&tj(t.multihash,n.multihash)}toString(t){return Kf(this,t)}toJSON(){return{"/":Kf(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let r=t;if(r instanceof ct)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:o,bytes:a}=r;return new ct(n,i,o,a??Hf(n,i,o.bytes))}else if(r[aj]===!0){let{version:n,multihash:i,code:o}=r,a=ej(i);return ct.create(n,o,a)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(r!==Ai)throw new Error(`Version 0 CID must use dag-pb (code: ${Ai}) block encoding`);return new ct(t,r,n,n.bytes)}case 1:{let i=Hf(t,r,n.bytes);return new ct(t,r,n,i)}default:throw new Error("Invalid version")}}static createV0(t){return ct.create(0,Ai,t)}static createV1(t,r){return ct.create(1,t,r)}static decode(t){let[r,n]=ct.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=ct.inspectBytes(t),n=r.size-r.multihashSize,i=Vl(t.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=i.subarray(r.multihashSize-r.digestSize),a=new Fl(r.multihashCode,r.digestSize,o,i);return[r.version===0?ct.createV0(a):ct.createV1(r.codec,a),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[d,k]=Tu(t.subarray(r));return r+=k,d},i=n(),o=Ai;if(i===18?(i=0,r=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let a=r,s=n(),u=n(),l=r+u,f=l-a;return{version:i,codec:o,multihashCode:s,digestSize:u,multihashSize:f,size:l}}static parse(t,r){let[n,i]=rj(t,r),o=ct.decode(i);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Eu(o).set(n,t),o}};function rj(e,t){switch(e[0]){case"Q":{let r=t??Rr;return[Rr.prefix,r.decode(`${Rr.prefix}${e}`)]}case Rr.prefix:{let r=t??Rr;return[Rr.prefix,r.decode(e)]}case Vo.prefix:{let r=t??Vo;return[Vo.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function nj(e,t,r){let{prefix:n}=r;if(n!==Rr.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=t.get(n);if(i==null){let o=r.encode(e).slice(1);return t.set(n,o),o}else return i}function ij(e,t,r){let{prefix:n}=r,i=t.get(n);if(i==null){let o=r.encode(e);return t.set(n,o),o}else return i}var Ai=112,oj=18;function Hf(e,t,r){let n=Ca(e),i=n+Ca(t),o=new Uint8Array(i+r.byteLength);return ja(e,o,0),ja(t,o,n),o.set(r,i),o}var aj=Symbol.for("@ipld/js-cid/CID"),{WARN:sj,LOG:j5,DEBUG:Ri,VERBOSE:C5,ERROR:gs}=Gn.setup(Gn.INFO),zl=["https://trustless-gateway.link/","https://ipfs.4everland.io/"].map(e=>({url:e}));async function ql(e,{readOnly:t=!0,pinnedCID:r,gateways:n=zl}={}){let{cid:i,errors:o,isIpns:a}=S$(e);if(!i)throw gs("Failed to parse pubID",e,o);Ri("[retrieveThread] parsedPubID",{cid:i.toString(),errors:o,isIpns:a});let s=await cy(i),{applogs:u,info:l}=await yN(s),f=u.filter(yu);f.length&&sj(`Found ${f.length} encrypted logs - skipping`);let d=u.filter(E=>!yu(E));Qi(d);let k=vo.fromArray(d,`preview${e&&e!==i.toString()?"-"+e:""}@${i.toString()}`,t);return{cid:i,info:l,thread:k,encryptedCount:f.length}}async function cy(e,t=zl){return e=mu(e),Ri("Retrieving:",e,e.toString(),"from",t),await Kl(t,async(r,n)=>{var i=fy(r,e);n>1&&(i+=`&cache-bust=${performance.now()}`);let o=await fetch(i),a=await uj(o,i);Ri("[retrieveCar] GW result",{result:a,gateway:r});let s=await Ed.fromIterable(a);Ri("[retrieveCar] GW decodeResult",{car:s,gateway:r});let u=(await s.getRoots())[0];if(!Ml(e)&&!qh(e,u))throw gs("Fetched CAR has different CID",u.toString(),"than the one asked for:",e.toString());return s})}function fy(e,t,r="all"){let n=new URL(e.url),i=Ml(t),o=`${n}${i?"ipns/":"ipfs/"}${t.toString()}?format=car&dag-scope=${r}`;return Ri({isIpns:i,url:o}),o}async function uj(e,t){if(!e?.ok||!e?.body)throw gs("[retrieveCar] unexpected response",e?.statusText,{url:t});return bN(e.body.getReader())}async function Kl(e,t,r=1){try{return await Promise.any(Xo(e).map(async n=>{try{return await t(n,r)}catch(i){throw gs("still trying",i),i instanceof Error?i:new Error(`[retrieveCar] error: ${i}`)}}))}catch(n){if(r<3)return await Kl(e,t,r+1);throw new Error("[Gateway] no valid results after 3 attempts via: "+Xo(e).map(({url:i})=>i)+`
|
|
63
63
|
`+n.errors.map(i=>i.message))}}var{WARN:l8,LOG:c8,DEBUG:f8,VERBOSE:d8,ERROR:p8}=Ae.setup(Ae.INFO),{WARN:h8,LOG:y8,DEBUG:g8,VERBOSE:m8,ERROR:b8}=Ae.setup(Ae.INFO),{WARN:lj,LOG:v8,DEBUG:cj,VERBOSE:ms,ERROR:w8}=Ae.setup(Ae.INFO),_8=tt("queryDivergencesByPrev",function(e){cj(`queryDivergencesByPrev<${e.nameAndSizeUntracked}>`),e.filters.includes("lastWriteWins")&&lj("queryDivergencesByPrev on thread lastWriteWins",e);let t=Ht(()=>{let r=new Map,n=new Set;ms("all applogs:",e.applogs);for(let i of e.applogs){let o;i.pv&&(o=i.pv&&r.get(i.pv.toString()),n.delete(i.pv.toString())),ms("traversing log",{log:i,prevLogs:o,leafs:Array.from(n)}),r.set(i.cid,o?[...o,i]:[i]),n.add(i.cid)}return Array.from(n).map(i=>{let o=new vo(We({caller:"DivergenceLeaf",thread:e,pattern:`leaf: ${i}`}),r.get(i),e.filters,!0);return{log:o.latestLog,thread:o}})},{name:We({caller:"queryDivergencesByPrev",thread:e})});return ms.isDisabled||Dt(()=>ms("[queryDivergencesByPrev] result:",br(t))),t},{equals:Je.structural}),{WARN:T8,LOG:E8,DEBUG:x8,VERBOSE:O8,ERROR:A8}=Gn.setup(Gn.INFO);var{WARN:$8,LOG:N8,DEBUG:j8,VERBOSE:C8,ERROR:U8}=Ts.setup(Ts.INFO),fj="https://nftstorage.link";async function P8(e,{readOnly:t=!0,pinnedCID:r}={}){return ql(e,{readOnly:t,pinnedCID:r,gateways:[{url:fj}]})}export{fj as a,P8 as b};
|
|
64
64
|
/*! Bundled license information:
|
|
@@ -79,4 +79,4 @@ lodash-es/lodash.js:
|
|
|
79
79
|
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
|
|
80
80
|
*)
|
|
81
81
|
*/
|
|
82
|
-
//# sourceMappingURL=chunk-
|
|
82
|
+
//# sourceMappingURL=chunk-AQFODBKK.min.js.map
|