@fireproof/core 0.19.115 → 0.19.116-dev-vendor
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.
- package/{chunk-JO62JMEP.js → chunk-2D2X6HIB.js} +1 -1
- package/chunk-2D2X6HIB.js.map +1 -0
- package/{chunk-UUOLR3GZ.js → chunk-WVN66YAN.js} +2 -2
- package/deno.json +2 -7
- package/{gateway-UT5GFV5R.js → gateway-3WGEEKVQ.js} +3 -3
- package/index.cjs +38 -28
- package/index.cjs.map +1 -1
- package/index.d.cts +6 -6
- package/index.d.ts +6 -6
- package/index.js +38 -29
- package/index.js.map +1 -1
- package/{key-bag-file-GTGVZHHM.js → key-bag-file-CBCAWTVG.js} +3 -3
- package/{key-bag-indexdb-NZMTNJLK.js → key-bag-indexdb-RTSMSGM7.js} +3 -3
- package/metafile-cjs.json +1 -1
- package/metafile-esm.json +1 -1
- package/package.json +3 -8
- package/react/index.cjs.map +1 -1
- package/react/index.d.cts +2 -2
- package/react/index.d.ts +2 -2
- package/react/index.js.map +1 -1
- package/react/metafile-cjs.json +1 -1
- package/react/metafile-esm.json +1 -1
- package/tests/blockstore/fragment-gateway.test.ts +1 -1
- package/tests/blockstore/keyed-crypto.test.ts +2 -2
- package/tests/blockstore/loader.test.ts +3 -3
- package/tests/blockstore/store.test.ts +1 -1
- package/tests/blockstore/transaction.test.ts +1 -1
- package/tests/fireproof/config.test.ts +1 -1
- package/tests/fireproof/crdt.test.ts +1 -1
- package/tests/fireproof/indexer.test.ts +1 -1
- package/tests/fireproof/utils.test.ts +1 -1
- package/{utils-5UEZAKVP.js → utils-XESRUKDJ.js} +3 -3
- package/web/gateway-impl.cjs.map +1 -1
- package/web/gateway-impl.js.map +1 -1
- package/web/metafile-cjs.json +1 -1
- package/web/metafile-esm.json +1 -1
- package/chunk-JO62JMEP.js.map +0 -1
- package/index.global.js +0 -149
- package/index.global.js.map +0 -1
- package/metafile-iife.json +0 -1
- /package/{chunk-UUOLR3GZ.js.map → chunk-WVN66YAN.js.map} +0 -0
- /package/{gateway-UT5GFV5R.js.map → gateway-3WGEEKVQ.js.map} +0 -0
- /package/{key-bag-file-GTGVZHHM.js.map → key-bag-file-CBCAWTVG.js.map} +0 -0
- /package/{key-bag-indexdb-NZMTNJLK.js.map → key-bag-indexdb-RTSMSGM7.js.map} +0 -0
- /package/{utils-5UEZAKVP.js.map → utils-XESRUKDJ.js.map} +0 -0
package/index.global.js
DELETED
@@ -1,149 +0,0 @@
|
|
1
|
-
"use strict";var Fireproof=(()=>{var dS=Object.create;var xi=Object.defineProperty;var pS=Object.getOwnPropertyDescriptor;var mS=Object.getOwnPropertyNames;var yS=Object.getPrototypeOf,gS=Object.prototype.hasOwnProperty;var A=(r,e)=>()=>(r&&(e=r(r=0)),e);var $=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),K=(r,e)=>{for(var t in e)xi(r,t,{get:e[t],enumerable:!0})},cp=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of mS(e))!gS.call(r,s)&&s!==t&&xi(r,s,{get:()=>e[s],enumerable:!(n=pS(e,s))||n.enumerable});return r};var mt=(r,e,t)=>(t=r!=null?dS(yS(r)):{},cp(e||!r||!r.__esModule?xi(t,"default",{value:r,enumerable:!0}):t,r)),wS=r=>cp(xi({},"__esModule",{value:!0}),r);function gn(){return TS}var fp,bS,xS,lp,kS,SS,hp,up,Jt,dp,pp,mp,Ue,yn,ki,vS,ES,yp,TS,Ps=A(()=>{"use strict";fp=Object.defineProperty,bS=Object.defineProperties,xS=Object.getOwnPropertyDescriptors,lp=Object.getOwnPropertySymbols,kS=Object.prototype.hasOwnProperty,SS=Object.prototype.propertyIsEnumerable,hp=r=>{throw TypeError(r)},up=(r,e,t)=>e in r?fp(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Jt=(r,e)=>{for(var t in e||(e={}))kS.call(e,t)&&up(r,t,e[t]);if(lp)for(var t of lp(e))SS.call(e,t)&&up(r,t,e[t]);return r},dp=(r,e)=>bS(r,xS(e)),pp=(r,e)=>{for(var t in e)fp(r,t,{get:e[t],enumerable:!0})},mp=(r,e,t)=>e.has(r)||hp("Cannot "+t),Ue=(r,e,t)=>(mp(r,e,"read from private field"),t?t.call(r):e.get(r)),yn=(r,e,t)=>e.has(r)?hp("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),ki=(r,e,t,n)=>(mp(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t),vS=new TextEncoder,ES=new TextDecoder,yp=class{encode(r){return vS.encode(r)}decode(r){return ES.decode(r)}},TS=new yp});function bp(r){switch(r){case"real":return new Ti;case"const":return new sl;case"step":return new wp}return new Ti}function xp(r,e){r.read().then(({done:t,value:n})=>{t||e(n).then(()=>{xp(r,e)}).catch(s=>{console.error("consumeReadableStream:writeFn",s)})}).catch(t=>{console.error("consumeReadableStream:read",t)})}function gp(r){let e=new TransformStream;return xp(e.readable.getReader(),r),e.writable}function xn(r={}){return IS.once(()=>{let e=[new _S(r),new AS(r),new Sp(r)].find(n=>n.active());if(!e)throw new Error("SysContainer:envFactory: no env available");let t=new vp(e,r);return e.register(t),t})}var _i,Ti,sl,wp,ol,il,al,cl,Si,vi,Ei,Ds,ll,X,kp,_e,wn,_S,bn,AS,Sp,IS,vp,ul=A(()=>{"use strict";Ps();_i=class{TimeSince(r){return this.Now().getTime()-r.getTime()}},Ti=class extends _i{Now(){return new Date}Sleep(r){return new Promise(e=>{setTimeout(()=>{e()},r)})}},sl=class extends _i{Now(){return new Date(2021,1,1,0,0,0,0)}Sleep(r){return Promise.resolve()}},wp=class extends _i{constructor(){super(),this._step=new sl().Now(),this._start=this._step}Now(r=1){for(let e=0;r>0&&e<r;e++)this._step=new Date(this._step.getTime()+1e3);return r<1&&(this._step=new Date(this._start.getTime()+r*-1e3)),this._step}Sleep(r){return this._step=new Date(this._step.getTime()+r),Promise.resolve()}};ol=class{constructor(r){this._step=0,this._mode=r}Random0ToValue(r){switch(this._mode){case"const":return .5*r;case"step":return this._step+=1e-4,this._step*r;case"random":return Math.random()*r;default:throw new Error("Unknown RandomMode")}}},il=class{constructor(r){this._step=0,r||(r="uuid"),this._mode=r}NextId(){switch(this._mode){case"uuid":return crypto.randomUUID();case"const":return"VeryUniqueID";case"step":return`STEPId-${this._step++}`;default:throw new Error("Unknown IDMode")}}};al=class{constructor(r){this._time=new Ti,this._idService=new il,this._randomService=new ol("random"),this._fileSystem=r.FileSystem,this._systemService=r.SystemService,this._txtEnDe=r.TxtEnDecoder;let e=this._txtEnDe;this._stdout=gp(async t=>{let n=e.decode(t);console.log(n.trimEnd())}),this._stderr=gp(async t=>{let n=e.decode(t);console.error(n.trimEnd())})}},cl=class{constructor(r,e){this._time=r._time,this._stdout=r._stdout,this._stderr=r._stderr,this._idService=r._idService,this._randomService=r._randomService,this._fileSystem=r._fileSystem,this._systemService=r._systemService,e&&(e.TimeMode&&(this._time=bp(e.TimeMode)),e.Stdout&&(this._stdout=e.Stdout),e.Stderr&&(this._stderr=e.Stderr),e.IdMode&&(this._idService=new il(e.IdMode)),e.RandomMode&&(this._randomService=new ol(e.RandomMode)),e.FileSystem&&(this._fileSystem=e.FileSystem),e.SystemService&&(this._systemService=e.SystemService))}Time(){return this._time}NextId(){return this._idService.NextId()}Random0ToValue(r){return this._randomService.Random0ToValue(r)}Stdout(){return this._stdout}Stderr(){return this._stderr}System(){return this._systemService}FileSystem(){return this._fileSystem}},Ds=class{constructor(){yn(this,Si),yn(this,vi,()=>{throw new Error("This Promise is not working as expected.")}),yn(this,Ei,()=>{throw new Error("This Promise is not working as expected.")}),ki(this,Si,new Promise((r,e)=>{ki(this,vi,r),ki(this,Ei,e)}))}async asPromise(){return Ue(this,Si)}resolve(r){Ue(this,vi).call(this,r)}reject(r){Ue(this,Ei).call(this,r)}};Si=new WeakMap;vi=new WeakMap;Ei=new WeakMap;ll=class{constructor(r){this._seqFutures=[],this.ctx=r}reset(){}async _step(r){r&&r.fn(this.ctx).then(e=>r.future.resolve(e)).catch(e=>r.future.reject(e)).finally(()=>{this._seqFutures.shift(),this._step(this._seqFutures[0])})}async add(r,e){let t=new Ds;return this._seqFutures.push({future:t,fn:r,id:e}),this._seqFutures.length===1&&this._step(this._seqFutures[0]),t.asPromise()}},X=class{constructor(r){this._onceDone=!1,this._onceFutures=[],this._onceOk=!1,this._isPromise=!1,this.ctx=r}get ready(){return this._onceDone}reset(){this._onceDone=!1,this._onceOk=!1,this._onceValue=void 0,this._onceError=void 0,this._onceFutures.length=0}once(r){if(this._onceDone){if(this._onceError){if(this._isPromise)return Promise.reject(this._onceError);throw this._onceError}if(this._onceOk)return this._isPromise?Promise.resolve(this._onceValue):this._onceValue;throw new Error("ResolveOnce.once impossible")}let e=new Ds;if(this._onceFutures.push(e),this._onceFutures.length===1){let t=s=>{this._onceValue=s,this._onceOk=!0,this._onceDone=!0,this._isPromise&&this._onceFutures.forEach(o=>o.resolve(this._onceValue)),this._onceFutures.length=0},n=s=>{this._onceError=s,this._onceOk=!1,this._onceValue=void 0,this._onceDone=!0,this._isPromise&&this._onceFutures.forEach(o=>o.reject(this._onceError)),this._onceFutures.length=0};try{let s=r(this.ctx);typeof s.then=="function"?(this._isPromise=!0,s.then(t).catch(n)):t(s)}catch(s){n(s)}}return this._isPromise?e.asPromise():this.once(r)}},kp=class{constructor(r){this._map=new Map,this.factory=r}async asyncGet(r){return this.get(await r())}get(r){typeof r=="function"&&(r=r());let e=this._map.get(r);return e||(e=this.factory(r),this._map.set(r,e)),e}unget(r){let e=this._map.get(r);e?.reset(),this._map.delete(r)}reset(){this._map.forEach(r=>r.reset()),this._map.clear()}},_e=class extends kp{constructor(){super(r=>new X(r))}},_S=class{constructor(r){yn(this,wn,globalThis),this._env=this.active()?Ue(this,wn).process.env:{}}register(r){return r}active(){return typeof Ue(this,wn)=="object"&&typeof Ue(this,wn).process=="object"&&typeof Ue(this,wn).process.env=="object"}keys(){return Object.keys(this._env)}get(r){return this._env[r]}set(r,e){e&&(this._env[r]=e)}delete(r){delete this._env[r]}};wn=new WeakMap;AS=class{constructor(r){yn(this,bn,globalThis)}get _env(){return Ue(this,bn).Deno.env}register(r){return r}active(){return typeof Ue(this,bn)=="object"&&typeof Ue(this,bn).Deno=="object"&&typeof Ue(this,bn).Deno.env=="object"}keys(){return Array.from(this._env.keys())}get(r){return this._env.get(r)}set(r,e){e&&this._env.set(r,e)}delete(r){this._env.delete(r)}};bn=new WeakMap;Sp=class{constructor(r){this.env=new Map,this.opts=r}get(r){return this.env.get(r)}set(r,e){e&&this.env.set(r,e)}delete(r){this.env.delete(r)}keys(){return Array.from(this.env.keys())}active(){return!0}register(r){let e=Symbol.for(this.opts.symbol||"CP_ENV"),t=globalThis;return t[e]=r,r}},IS=new X;vp=class{constructor(r,e={}){this._onSet=[],this._map=r,this._updatePresets(e.presetEnv)}_updatePresets(r){if(r)for(let[e,t]of r)this._map.set(e,t)}_applyOnSet(r,e,t){r.forEach(n=>{let s=[];e?s=[e]:s=this._map.keys(),s.filter(o=>!!(n.filter.size===0||n.filter.has(o))).forEach(o=>{let i;!e&&!t?i=this._map.get(o):e&&!t?i=void 0:i=t,n.fn(o,i)})})}keys(){return this._map.keys()}onSet(r,...e){let t={filter:new Set(e),fn:r};this._onSet.push(t),this._applyOnSet([t])}get(r){return this._map.get(r)}set(r,e){e&&(this._map.set(r,e),this._applyOnSet(this._onSet,r,e))}delete(r){this._map.delete(r),this._applyOnSet(this._onSet,r)}}});function Ep(r){return fl||(fl=new al({TxtEnDecoder:r?.TxtEnDecoder||gn(),FileSystem:new CS,SystemService:new LS})),new cl(fl,r)}var CS,LS,fl,Tp=A(()=>{"use strict";ul();Ps();CS=class{get baseDir(){throw new Error("basedir-Method not implemented.")}create(r){throw new Error("create-Method not implemented.")}readFileString(r){throw new Error("readFileString-Method not implemented.")}writeFileString(r,e){throw new Error("writeFileString-Method not implemented.")}abs(r){throw new Error("abs-Method not implemented.")}join(...r){throw new Error("join-Method not implemented.")}relative(r,e){throw new Error("relative-Method not implemented.")}dirname(r){throw new Error("dirname-Method not implemented.")}basename(r){throw new Error("basename-Method not implemented.")}nodeImport(r){throw new Error("nodeImport-Method not implemented.")}isAbsolute(r){throw new Error("isAbsolute-Method not implemented.")}},LS=class{Env(){return xn()}Args(){throw new Error("Args-Method not implemented.")}OnExit(r){throw new Error("OnExit-Method not implemented.")}Exit(r){throw new Error("Exit-Method not implemented.")}},fl=void 0});function BS(r,e){let t={reader:r.getReader(),streamMap:e,idx:0};return new ReadableStream({async pull(n){let{done:s,value:o}=await t.reader.read();if(s){t.streamMap.Close&&t.streamMap.Close(),n.close();return}let i=t.streamMap.Map(o,t.idx++),a;i instanceof Promise||typeof i.then=="function"?a=await i:a=i,n.enqueue(a)}})}async function PS(r){let e=r.getReader(),t=0;for(;;){let{done:n}=await e.read();if(n)break;t++}return t}function Ip(r){let e=0;return new ReadableStream({pull(t){if(e>=r.length){t.close();return}t.enqueue(r[e]),e++}})}async function Cp(r){let e=[],t=r.getReader();for(;;){let{done:n,value:s}=await t.read();if(n)break;e.push(s)}return e}async function DS(r,e){return Cp(Bp(Ip(r),e))}function _p(r,e){let t=r.reduce((c,l)=>c+l.length,0),n=r[r.length-1],s=t-n.length,o=n.subarray(e-s);r[r.length-1]=n.subarray(0,e-s);let i=new Uint8Array(e),a=0;for(let c of r)i.set(c,a),a+=c.length;return{rest:o,chunk:i}}function Lp(r,e,t){r.reader.read().then(({done:n,value:s})=>{if(n){r.tmpLen>0&&e.enqueue(_p(r.tmp,r.tmpLen).chunk),e.close(),t();return}if(r.tmpLen+s.length>r.chunkSize){r.tmp.push(s);let o=_p(r.tmp,r.chunkSize);e.enqueue(o.chunk),r.tmp=[o.rest],r.tmpLen=o.rest.length,t();return}else s.length&&(r.tmp.push(s),r.tmpLen+=s.length);Lp(r,e,t)})}function Bp(r,e){let t={reader:r.getReader(),tmp:[],tmpLen:0,chunkSize:e};return new ReadableStream({async pull(n){return new Promise(s=>{Lp(t,n,s)})}})}async function NS(r,e){if(!r)return Promise.resolve("");let t=r.getReader(),n="",s=new TextDecoder,o=0;for(;typeof e>"u"||o<e;)try{let i=await t.read();if(i.done)break;e&&o+i.value.length>e&&(i.value=i.value.slice(0,e-o));let a=s.decode(i.value,{stream:!0});o+=i.value.length,n+=a}catch(i){return Promise.reject(i)}return Promise.resolve(n)}async function MS(r){if(!r)return Promise.resolve(new Uint8Array);let e=r.getReader(),t=new Uint8Array;for(;;)try{let{done:n,value:s}=await e.read();if(n)break;t=new Uint8Array([...t,...s])}catch(n){return Promise.reject(n)}return Promise.resolve(t)}function OS(r,e=gn()){return Pp(e.encode(r))}function Pp(r){return new ReadableStream({start(e){e.enqueue(r),e.close()}})}var Ap,Dp,hl,Np,Mp=A(()=>{"use strict";Ps();Ap={};pp(Ap,{ConsoleWriterStream:()=>hl,ConsoleWriterStreamDefaultWriter:()=>Dp,FanoutWriteStream:()=>Np,array2stream:()=>Ip,devnull:()=>PS,rebuffer:()=>Bp,rebufferArray:()=>DS,stream2array:()=>Cp,stream2string:()=>NS,stream2uint8array:()=>MS,streamMap:()=>BS,string2stream:()=>OS,uint8array2stream:()=>Pp});Dp=class{constructor(r){this.stream=r,this.desiredSize=null,this.decoder=new TextDecoder,this._stream=r,this.ready=Promise.resolve(void 0),this.closed=Promise.resolve(void 0)}abort(r){throw new Error("Method not implemented.")}async close(){}releaseLock(){this._stream.locked=!1,this.ready=Promise.resolve(void 0),this.closed=Promise.resolve(void 0)}async write(r){let e=this.decoder.decode(r).trimEnd(),t="log";try{e=JSON.parse(e),t=e.level}catch{}switch(t){case"error":console.error(e);break;case"warn":console.warn(e);break;default:console.log(e)}}},hl=class{constructor(){this.locked=!1}abort(r){throw new Error("Method not implemented.")}async close(){}getWriter(){if(this.locked)throw new Error("Stream is locked");return this.locked=!0,this._writer||(this._writer=new Dp(this)),this._writer}},Np=class{constructor(r){this.desiredSize=null,this._writers=r,this.ready=Promise.all(this._writers.map(e=>e.ready)).then(()=>{}),this.closed=Promise.all(this._writers.map(e=>e.closed)).then(()=>{})}abort(r){return Promise.all(this._writers.map(e=>e.abort(r))).then(()=>{})}close(){return Promise.all(this._writers.map(r=>r.close())).then(()=>{})}releaseLock(){this._writers.map(r=>r.releaseLock())}write(r){return Promise.all(this._writers.map(e=>e.write(r))).then(()=>{})}}});function j(r){if(r&&typeof r=="object")switch(r[ke]){case rt:case Ot:return!0}return!1}function U(r){if(r&&typeof r=="object")switch(r[ke]){case Ai:case rt:case $e:case Ot:return!0}return!1}var Ai,Ii,rt,dl,$e,Ot,ke,Ke,yt,ze,F,M,He,Op,q=A(()=>{"use strict";Ai=Symbol.for("yaml.alias"),Ii=Symbol.for("yaml.document"),rt=Symbol.for("yaml.map"),dl=Symbol.for("yaml.pair"),$e=Symbol.for("yaml.scalar"),Ot=Symbol.for("yaml.seq"),ke=Symbol.for("yaml.node.type"),Ke=r=>!!r&&typeof r=="object"&&r[ke]===Ai,yt=r=>!!r&&typeof r=="object"&&r[ke]===Ii,ze=r=>!!r&&typeof r=="object"&&r[ke]===rt,F=r=>!!r&&typeof r=="object"&&r[ke]===dl,M=r=>!!r&&typeof r=="object"&&r[ke]===$e,He=r=>!!r&&typeof r=="object"&&r[ke]===Ot;Op=r=>(M(r)||j(r))&&!!r.anchor});function je(r,e){let t=Fp(e);yt(r)?kn(null,r.contents,t,Object.freeze([r]))===gt&&(r.contents=null):kn(null,r,t,Object.freeze([]))}function kn(r,e,t,n){let s=Up(r,e,t,n);if(U(s)||F(s))return $p(r,n,s),kn(r,s,t,n);if(typeof s!="symbol"){if(j(e)){n=Object.freeze(n.concat(e));for(let o=0;o<e.items.length;++o){let i=kn(o,e.items[o],t,n);if(typeof i=="number")o=i-1;else{if(i===Ae)return Ae;i===gt&&(e.items.splice(o,1),o-=1)}}}else if(F(e)){n=Object.freeze(n.concat(e));let o=kn("key",e.key,t,n);if(o===Ae)return Ae;o===gt&&(e.key=null);let i=kn("value",e.value,t,n);if(i===Ae)return Ae;i===gt&&(e.value=null)}}return s}async function Ns(r,e){let t=Fp(e);yt(r)?await Sn(null,r.contents,t,Object.freeze([r]))===gt&&(r.contents=null):await Sn(null,r,t,Object.freeze([]))}async function Sn(r,e,t,n){let s=await Up(r,e,t,n);if(U(s)||F(s))return $p(r,n,s),Sn(r,s,t,n);if(typeof s!="symbol"){if(j(e)){n=Object.freeze(n.concat(e));for(let o=0;o<e.items.length;++o){let i=await Sn(o,e.items[o],t,n);if(typeof i=="number")o=i-1;else{if(i===Ae)return Ae;i===gt&&(e.items.splice(o,1),o-=1)}}}else if(F(e)){n=Object.freeze(n.concat(e));let o=await Sn("key",e.key,t,n);if(o===Ae)return Ae;o===gt&&(e.key=null);let i=await Sn("value",e.value,t,n);if(i===Ae)return Ae;i===gt&&(e.value=null)}}return s}function Fp(r){return typeof r=="object"&&(r.Collection||r.Node||r.Value)?Object.assign({Alias:r.Node,Map:r.Node,Scalar:r.Node,Seq:r.Node},r.Value&&{Map:r.Value,Scalar:r.Value,Seq:r.Value},r.Collection&&{Map:r.Collection,Seq:r.Collection},r):r}function Up(r,e,t,n){if(typeof t=="function")return t(r,e,n);if(ze(e))return t.Map?.(r,e,n);if(He(e))return t.Seq?.(r,e,n);if(F(e))return t.Pair?.(r,e,n);if(M(e))return t.Scalar?.(r,e,n);if(Ke(e))return t.Alias?.(r,e,n)}function $p(r,e,t){let n=e[e.length-1];if(j(n))n.items[r]=t;else if(F(n))r==="key"?n.key=t:n.value=t;else if(yt(n))n.contents=t;else{let s=Ke(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}var Ae,Rp,gt,Ms=A(()=>{"use strict";q();Ae=Symbol("break visit"),Rp=Symbol("skip children"),gt=Symbol("remove node");je.BREAK=Ae;je.SKIP=Rp;je.REMOVE=gt;Ns.BREAK=Ae;Ns.SKIP=Rp;Ns.REMOVE=gt});var RS,FS,wt,pl=A(()=>{"use strict";q();Ms();RS={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},FS=r=>r.replace(/[!,[\]{}]/g,e=>RS[e]),wt=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),s=n.shift();switch(s){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[o,i]=n;return this.tags[o]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[o]=n;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let i=/^\d+\.\d+$/.test(o);return t(6,`Unsupported YAML version ${o}`,i),!1}}default:return t(0,`Unknown directive ${s}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let i=e.slice(2,-1);return i==="!"||i==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),i)}let[,n,s]=e.match(/^(.*!)([^!]*)$/s);s||t(`The ${e} tag has no suffix`);let o=this.tags[n];if(o)try{return o+decodeURIComponent(s)}catch(i){return t(String(i)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+FS(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),s;if(e&&n.length>0&&U(e.contents)){let o={};je(e.contents,(i,a)=>{U(a)&&a.tag&&(o[a.tag]=!0)}),s=Object.keys(o)}else s=[];for(let[o,i]of n)o==="!!"&&i==="tag:yaml.org,2002:"||(!e||s.some(a=>a.startsWith(i)))&&t.push(`%TAG ${o} ${i}`);return t.join(`
|
2
|
-
`)}};wt.defaultYaml={explicit:!1,version:"1.2"};wt.defaultTags={"!!":"tag:yaml.org,2002:"}});function Ci(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function ml(r){let e=new Set;return je(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function yl(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function Kp(r,e){let t=[],n=new Map,s=null;return{onAnchor:o=>{t.push(o),s||(s=ml(r));let i=yl(e,s);return s.add(i),i},setAnchors:()=>{for(let o of t){let i=n.get(o);if(typeof i=="object"&&i.anchor&&(M(i.node)||j(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=o,a}}},sourceObjects:n}}var Li=A(()=>{"use strict";q();Ms()});function Qt(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let s=0,o=n.length;s<o;++s){let i=n[s],a=Qt(r,n,String(s),i);a===void 0?delete n[s]:a!==i&&(n[s]=a)}else if(n instanceof Map)for(let s of Array.from(n.keys())){let o=n.get(s),i=Qt(r,n,s,o);i===void 0?n.delete(s):i!==o&&n.set(s,i)}else if(n instanceof Set)for(let s of Array.from(n)){let o=Qt(r,n,s,s);o===void 0?n.delete(s):o!==s&&(n.delete(s),n.add(o))}else for(let[s,o]of Object.entries(n)){let i=Qt(r,n,s,o);i===void 0?delete n[s]:i!==o&&(n[s]=i)}return r.call(e,t,n)}var gl=A(()=>{"use strict"});function ie(r,e,t){if(Array.isArray(r))return r.map((n,s)=>ie(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!Op(r))return r.toJSON(e,t);let n={aliasCount:0,count:1,res:void 0};t.anchors.set(r,n),t.onCreate=o=>{n.res=o,delete t.onCreate};let s=r.toJSON(e,t);return t.onCreate&&t.onCreate(s),s}return typeof r=="bigint"&&!t?.keep?Number(r):r}var Yt=A(()=>{"use strict";q()});var Xt,Bi=A(()=>{"use strict";gl();q();Yt();Xt=class{constructor(e){Object.defineProperty(this,ke,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:s,reviver:o}={}){if(!yt(e))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=ie(this,"",i);if(typeof s=="function")for(let{count:c,res:l}of i.anchors.values())s(l,c);return typeof o=="function"?Qt(o,{"":a},"",a):a}}});function Pi(r,e,t){if(Ke(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(j(e)){let n=0;for(let s of e.items){let o=Pi(r,s,t);o>n&&(n=o)}return n}else if(F(e)){let n=Pi(r,e.key,t),s=Pi(r,e.value,t);return Math.max(n,s)}return 1}var bt,Os=A(()=>{"use strict";Li();Ms();q();Bi();Yt();bt=class extends Xt{constructor(e){super(Ai),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e){let t;return je(e,{Node:(n,s)=>{if(s===this)return je.BREAK;s.anchor===this.source&&(t=s)}}),t}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:s,maxAliasCount:o}=t,i=this.resolve(s);if(!i){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(i);if(a||(ie(i,null,t),a=n.get(i)),!a||a.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(o>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Pi(s,i,n)),a.count*a.aliasCount>o)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){let s=`*${this.source}`;if(e){if(Ci(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(e.implicitKey)return`${s} `}return s}}});var Di,B,oe=A(()=>{"use strict";q();Bi();Yt();Di=r=>!r||typeof r!="function"&&typeof r!="object",B=class extends Xt{constructor(e){super($e),this.value=e}toJSON(e,t){return t?.keep?this.value:ie(this.value,e,t)}toString(){return String(this.value)}};B.BLOCK_FOLDED="BLOCK_FOLDED";B.BLOCK_LITERAL="BLOCK_LITERAL";B.PLAIN="PLAIN";B.QUOTE_DOUBLE="QUOTE_DOUBLE";B.QUOTE_SINGLE="QUOTE_SINGLE"});function $S(r,e,t){if(e){let n=t.filter(o=>o.tag===e),s=n.find(o=>!o.format)??n[0];if(!s)throw new Error(`Tag ${e} not found`);return s}return t.find(n=>n.identify?.(r)&&!n.format)}function Rt(r,e,t){if(yt(r)&&(r=r.contents),U(r))return r;if(F(r)){let f=t.schema[rt].createNode?.(t.schema,null,t);return f.items.push(r),f}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:s,onTagObj:o,schema:i,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return c.anchor||(c.anchor=s(r)),new bt(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=US+e.slice(2));let l=$S(r,e,i.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let f=new B(r);return c&&(c.node=f),f}l=r instanceof Map?i[rt]:Symbol.iterator in Object(r)?i[Ot]:i[rt]}o&&(o(l),delete t.onTagObj);let u=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new B(r);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}var US,Rs=A(()=>{"use strict";Os();q();oe();US="tag:yaml.org,2002:"});function Fs(r,e,t){let n=t;for(let s=e.length-1;s>=0;--s){let o=e[s];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let i=[];i[o]=n,n=i}else n=new Map([[o,n]])}return Rt(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:r,sourceObjects:new Map})}var En,vn,Ni=A(()=>{"use strict";Rs();q();Bi();En=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,vn=class extends Xt{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>U(n)||F(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(En(e))this.add(t);else{let[n,...s]=e,o=this.get(n,!0);if(j(o))o.addIn(s,t);else if(o===void 0&&this.schema)this.set(n,Fs(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let s=this.get(t,!0);if(j(s))return s.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...s]=e,o=this.get(n,!0);return s.length===0?!t&&M(o)?o.value:o:j(o)?o.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!F(t))return!1;let n=t.value;return n==null||e&&M(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let s=this.get(t,!0);return j(s)?s.hasIn(n):!1}setIn(e,t){let[n,...s]=e;if(s.length===0)this.set(n,t);else{let o=this.get(n,!0);if(j(o))o.setIn(s,t);else if(o===void 0&&this.schema)this.set(n,Fs(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}}});function Ve(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var zp,xt,Us=A(()=>{"use strict";zp=r=>r.replace(/^(?!$)(?: $)?/gm,"#");xt=(r,e,t)=>r.endsWith(`
|
3
|
-
`)?Ve(t,e):t.includes(`
|
4
|
-
`)?`
|
5
|
-
`+Ve(t,e):(r.endsWith(" ")?"":" ")+t});function Ks(r,e,t="flow",{indentAtStart:n,lineWidth:s=80,minContentWidth:o=20,onFold:i,onOverflow:a}={}){if(!s||s<0)return r;s<o&&(o=0);let c=Math.max(1+o,1+s-e.length);if(r.length<=c)return r;let l=[],u={},f=s-e.length;typeof n=="number"&&(n>s-Math.max(2,o)?l.push(0):f=s-n);let p,h,m=!1,d=-1,y=-1,g=-1;t===Mi&&(d=Hp(r,d,e.length),d!==-1&&(f=d+c));for(let x;x=r[d+=1];){if(t===$s&&x==="\\"){switch(y=d,r[d+1]){case"x":d+=3;break;case"u":d+=5;break;case"U":d+=9;break;default:d+=1}g=d}if(x===`
|
6
|
-
`)t===Mi&&(d=Hp(r,d,e.length)),f=d+e.length+c,p=void 0;else{if(x===" "&&h&&h!==" "&&h!==`
|
7
|
-
`&&h!==" "){let k=r[d+1];k&&k!==" "&&k!==`
|
8
|
-
`&&k!==" "&&(p=d)}if(d>=f)if(p)l.push(p),f=p+c,p=void 0;else if(t===$s){for(;h===" "||h===" ";)h=x,x=r[d+=1],m=!0;let k=d>g+1?d-2:y-1;if(u[k])return r;l.push(k),u[k]=!0,f=k+c,p=void 0}else m=!0}h=x}if(m&&a&&a(),l.length===0)return r;i&&i();let b=r.slice(0,l[0]);for(let x=0;x<l.length;++x){let k=l[x],S=l[x+1]||r.length;k===0?b=`
|
9
|
-
${e}${r.slice(0,S)}`:(t===$s&&u[k]&&(b+=`${r[k]}\\`),b+=`
|
10
|
-
${e}${r.slice(k+1,S)}`)}return b}function Hp(r,e,t){let n=e,s=e+1,o=r[s];for(;o===" "||o===" ";)if(e<s+t)o=r[++e];else{do o=r[++e];while(o&&o!==`
|
11
|
-
`);n=e,s=e+1,o=r[s]}return n}var wl,Mi,$s,jp=A(()=>{"use strict";wl="flow",Mi="block",$s="quoted"});function KS(r,e,t){if(!e||e<0)return!1;let n=e-t,s=r.length;if(s<=n)return!1;for(let o=0,i=0;o<s;++o)if(r[o]===`
|
12
|
-
`){if(o-i>n)return!0;if(i=o+1,s-i<=n)return!1}return!0}function zs(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,o=e.indent||(Fi(r)?" ":""),i="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(i+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{i+=t.slice(a,c);let u=t.substr(c+2,4);switch(u){case"0000":i+="\\0";break;case"0007":i+="\\a";break;case"000b":i+="\\v";break;case"001b":i+="\\e";break;case"0085":i+="\\N";break;case"00a0":i+="\\_";break;case"2028":i+="\\L";break;case"2029":i+="\\P";break;default:u.substr(0,2)==="00"?i+="\\x"+u.substr(2):i+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length<s)c+=1;else{for(i+=t.slice(a,c)+`
|
13
|
-
|
14
|
-
`;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)i+=`
|
15
|
-
`,c+=2;i+=o,t[c+2]===" "&&(i+="\\"),c+=1,a=c+1}break;default:c+=1}return i=a?i+t.slice(a):t,n?i:Ks(i,o,$s,Ri(e,!1))}function bl(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
|
16
|
-
`)||/[ \t]\n|\n[ \t]/.test(r))return zs(r,e);let t=e.indent||(Fi(r)?" ":""),n="'"+r.replace(/'/g,"''").replace(/\n+/g,`$&
|
17
|
-
${t}`)+"'";return e.implicitKey?n:Ks(n,t,wl,Ri(e,!1))}function Tn(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=zs;else{let s=r.includes('"'),o=r.includes("'");s&&!o?n=bl:o&&!s?n=zs:n=t?bl:zs}return n(r,e)}function Oi({comment:r,type:e,value:t},n,s,o){let{blockQuote:i,commentString:a,lineWidth:c}=n.options;if(!i||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return Tn(t,n);let l=n.indent||(n.forceBlockIndent||Fi(t)?" ":""),u=i==="literal"?!0:i==="folded"||e===B.BLOCK_FOLDED?!1:e===B.BLOCK_LITERAL?!0:!KS(t,c,l.length);if(!t)return u?`|
|
18
|
-
`:`>
|
19
|
-
`;let f,p;for(p=t.length;p>0;--p){let T=t[p-1];if(T!==`
|
20
|
-
`&&T!==" "&&T!==" ")break}let h=t.substring(p),m=h.indexOf(`
|
21
|
-
`);m===-1?f="-":t===h||m!==h.length-1?(f="+",o&&o()):f="",h&&(t=t.slice(0,-h.length),h[h.length-1]===`
|
22
|
-
`&&(h=h.slice(0,-1)),h=h.replace(xl,`$&${l}`));let d=!1,y,g=-1;for(y=0;y<t.length;++y){let T=t[y];if(T===" ")d=!0;else if(T===`
|
23
|
-
`)g=y;else break}let b=t.substring(0,g<y?g+1:y);b&&(t=t.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let k=(u?"|":">")+(d?l?"2":"1":"")+f;if(r&&(k+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),u)return t=t.replace(/\n+/g,`$&${l}`),`${k}
|
24
|
-
${l}${b}${t}${h}`;t=t.replace(/\n+/g,`
|
25
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`);let S=Ks(`${b}${t}${h}`,l,Mi,Ri(n,!0));return`${k}
|
26
|
-
${l}${S}`}function zS(r,e,t,n){let{type:s,value:o}=r,{actualString:i,implicitKey:a,indent:c,indentStep:l,inFlow:u}=e;if(a&&o.includes(`
|
27
|
-
`)||u&&/[[\]{},]/.test(o))return Tn(o,e);if(!o||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return a||u||!o.includes(`
|
28
|
-
`)?Tn(o,e):Oi(r,e,t,n);if(!a&&!u&&s!==B.PLAIN&&o.includes(`
|
29
|
-
`))return Oi(r,e,t,n);if(Fi(o)){if(c==="")return e.forceBlockIndent=!0,Oi(r,e,t,n);if(a&&c===l)return Tn(o,e)}let f=o.replace(/\n+/g,`$&
|
30
|
-
${c}`);if(i){let p=d=>d.default&&d.tag!=="tag:yaml.org,2002:str"&&d.test?.test(f),{compat:h,tags:m}=e.doc.schema;if(m.some(p)||h?.some(p))return Tn(o,e)}return a?f:Ks(f,c,wl,Ri(e,!1))}function Ft(r,e,t,n){let{implicitKey:s,inFlow:o}=e,i=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==B.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=B.QUOTE_DOUBLE);let c=u=>{switch(u){case B.BLOCK_FOLDED:case B.BLOCK_LITERAL:return s||o?Tn(i.value,e):Oi(i,e,t,n);case B.QUOTE_DOUBLE:return zs(i.value,e);case B.QUOTE_SINGLE:return bl(i.value,e);case B.PLAIN:return zS(i,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:f}=e.options,p=s&&u||f;if(l=c(p),l===null)throw new Error(`Unsupported default string type ${p}`)}return l}var Ri,Fi,xl,Hs=A(()=>{"use strict";oe();jp();Ri=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),Fi=r=>/^(%|---|\.\.\.)/m.test(r);try{xl=new RegExp(`(^|(?<!
|
31
|
-
))
|
32
|
-
+(?!
|
33
|
-
|$)`,"g")}catch{xl=/\n+(?!\n|$)/g}});function Ui(r,e){let t=Object.assign({blockQuote:!0,commentString:zp,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},r.schema.toStringOptions,e),n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}function HS(r,e){if(e.tag){let s=r.filter(o=>o.tag===e.tag);if(s.length>0)return s.find(o=>o.format===e.format)??s[0]}let t,n;if(M(e)){n=e.value;let s=r.filter(o=>o.identify?.(n));t=s.find(o=>o.format===e.format)??s.find(o=>!o.format)}else n=e,t=r.find(s=>s.nodeClass&&n instanceof s.nodeClass);if(!t){let s=n?.constructor?.name??typeof n;throw new Error(`Tag not resolved for ${s} value`)}return t}function jS(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],o=(M(r)||j(r))&&r.anchor;o&&Ci(o)&&(t.add(o),s.push(`&${o}`));let i=r.tag?r.tag:e.default?null:e.tag;return i&&s.push(n.directives.tagString(i)),s.join(" ")}function Ut(r,e,t,n){if(F(r))return r.toString(e,t,n);if(Ke(r)){if(e.doc.directives)return r.toString(e);if(e.resolvedAliases?.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let s,o=U(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s||(s=HS(e.doc.schema.tags,o));let i=jS(o,s,e);i.length>0&&(e.indentAtStart=(e.indentAtStart??0)+i.length+1);let a=typeof s.stringify=="function"?s.stringify(o,e,t,n):M(o)?Ft(o,e,t,n):o.toString(e,t,n);return i?M(o)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}
|
34
|
-
${e.indent}${a}`:a}var js=A(()=>{"use strict";Li();q();Us();Hs()});function Vp({key:r,value:e},t,n,s){let{allNullValues:o,doc:i,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:f}}=t,p=U(r)&&r.comment||null;if(f){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(j(r)||!U(r)&&typeof r=="object"){let E="With simple keys, collection cannot be used as a key value";throw new Error(E)}}let h=!f&&(!r||p&&e==null&&!t.inFlow||j(r)||(M(r)?r.type===B.BLOCK_FOLDED||r.type===B.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!h&&(f||!o),indent:a+c});let m=!1,d=!1,y=Ut(r,t,()=>m=!0,()=>d=!0);if(!h&&!t.inFlow&&y.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(t.inFlow){if(o||e==null)return m&&n&&n(),y===""?"?":h?`? ${y}`:y}else if(o&&!f||e==null&&h)return y=`? ${y}`,p&&!m?y+=xt(y,t.indent,l(p)):d&&s&&s(),y;m&&(p=null),h?(p&&(y+=xt(y,t.indent,l(p))),y=`? ${y}
|
35
|
-
${a}:`):(y=`${y}:`,p&&(y+=xt(y,t.indent,l(p))));let g,b,x;U(e)?(g=!!e.spaceBefore,b=e.commentBefore,x=e.comment):(g=!1,b=null,x=null,e&&typeof e=="object"&&(e=i.createNode(e))),t.implicitKey=!1,!h&&!p&&M(e)&&(t.indentAtStart=y.length+1),d=!1,!u&&c.length>=2&&!t.inFlow&&!h&&He(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let k=!1,S=Ut(e,t,()=>k=!0,()=>d=!0),T=" ";if(p||g||b){if(T=g?`
|
36
|
-
`:"",b){let E=l(b);T+=`
|
37
|
-
${Ve(E,t.indent)}`}S===""&&!t.inFlow?T===`
|
38
|
-
`&&(T=`
|
39
|
-
|
40
|
-
`):T+=`
|
41
|
-
${t.indent}`}else if(!h&&j(e)){let E=S[0],_=S.indexOf(`
|
42
|
-
`),W=_!==-1,le=t.inFlow??e.flow??e.items.length===0;if(W||!le){let Te=!1;if(W&&(E==="&"||E==="!")){let Y=S.indexOf(" ");E==="&"&&Y!==-1&&Y<_&&S[Y+1]==="!"&&(Y=S.indexOf(" ",Y+1)),(Y===-1||_<Y)&&(Te=!0)}Te||(T=`
|
43
|
-
${t.indent}`)}}else(S===""||S[0]===`
|
44
|
-
`)&&(T="");return y+=T+S,t.inFlow?k&&n&&n():x&&!k?y+=xt(y,t.indent,l(x)):d&&s&&s(),y}var Wp=A(()=>{"use strict";q();oe();js();Us()});function $i(r,e){(r==="debug"||r==="warn")&&(typeof process<"u"&&process.emitWarning?process.emitWarning(e):console.warn(e))}var kl=A(()=>{"use strict"});function Ki(r,e,{key:t,value:n}){if(r?.doc.schema.merge&&VS(t))if(n=Ke(n)?n.resolve(r.doc):n,He(n))for(let s of n.items)Sl(r,e,s);else if(Array.isArray(n))for(let s of n)Sl(r,e,s);else Sl(r,e,n);else{let s=ie(t,"",r);if(e instanceof Map)e.set(s,ie(n,s,r));else if(e instanceof Set)e.add(s);else{let o=WS(t,s,r),i=ie(n,o,r);o in e?Object.defineProperty(e,o,{value:i,writable:!0,enumerable:!0,configurable:!0}):e[o]=i}}return e}function Sl(r,e,t){let n=r&&Ke(t)?t.resolve(r.doc):t;if(!ze(n))throw new Error("Merge sources must be maps or map aliases");let s=n.toJSON(null,r,Map);for(let[o,i]of s)e instanceof Map?e.has(o)||e.set(o,i):e instanceof Set?e.add(o):Object.prototype.hasOwnProperty.call(e,o)||Object.defineProperty(e,o,{value:i,writable:!0,enumerable:!0,configurable:!0});return e}function WS(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(U(r)&&t?.doc){let n=Ui(t.doc,{});n.anchors=new Set;for(let o of t.anchors.keys())n.anchors.add(o.anchor);n.inFlow=!0,n.inStringifyKey=!0;let s=r.toString(n);if(!t.mapKeyWarned){let o=JSON.stringify(s);o.length>40&&(o=o.substring(0,36)+'..."'),$i(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return s}return JSON.stringify(e)}var qp,VS,vl=A(()=>{"use strict";kl();js();q();oe();Yt();qp="<<";VS=r=>r===qp||M(r)&&r.value===qp&&(!r.type||r.type===B.PLAIN)});function _n(r,e,t){let n=Rt(r,void 0,t),s=Rt(e,void 0,t);return new Z(n,s)}var Z,Zt=A(()=>{"use strict";Rs();Wp();vl();q();Z=class r{constructor(e,t=null){Object.defineProperty(this,ke,{value:dl}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return U(t)&&(t=t.clone(e)),U(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return Ki(t,n,this)}toString(e,t,n){return e?.doc?Vp(this,e,t,n):JSON.stringify(this)}}});function Hi(r,e,t){return(e.inFlow??r.flow?GS:qS)(r,e,t)}function qS({comment:r,items:e},t,{blockItemPrefix:n,flowChars:s,itemIndent:o,onChompKeep:i,onComment:a}){let{indent:c,options:{commentString:l}}=t,u=Object.assign({},t,{indent:o,type:null}),f=!1,p=[];for(let m=0;m<e.length;++m){let d=e[m],y=null;if(U(d))!f&&d.spaceBefore&&p.push(""),zi(t,p,d.commentBefore,f),d.comment&&(y=d.comment);else if(F(d)){let b=U(d.key)?d.key:null;b&&(!f&&b.spaceBefore&&p.push(""),zi(t,p,b.commentBefore,f))}f=!1;let g=Ut(d,u,()=>y=null,()=>f=!0);y&&(g+=xt(g,o,l(y))),f&&y&&(f=!1),p.push(n+g)}let h;if(p.length===0)h=s.start+s.end;else{h=p[0];for(let m=1;m<p.length;++m){let d=p[m];h+=d?`
|
45
|
-
${c}${d}`:`
|
46
|
-
`}}return r?(h+=`
|
47
|
-
`+Ve(l(r),c),a&&a()):f&&i&&i(),h}function GS({items:r},e,{flowChars:t,itemIndent:n}){let{indent:s,indentStep:o,flowCollectionPadding:i,options:{commentString:a}}=e;n+=o;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,u=0,f=[];for(let m=0;m<r.length;++m){let d=r[m],y=null;if(U(d))d.spaceBefore&&f.push(""),zi(e,f,d.commentBefore,!1),d.comment&&(y=d.comment);else if(F(d)){let b=U(d.key)?d.key:null;b&&(b.spaceBefore&&f.push(""),zi(e,f,b.commentBefore,!1),b.comment&&(l=!0));let x=U(d.value)?d.value:null;x?(x.comment&&(y=x.comment),x.commentBefore&&(l=!0)):d.value==null&&b?.comment&&(y=b.comment)}y&&(l=!0);let g=Ut(d,c,()=>y=null);m<r.length-1&&(g+=","),y&&(g+=xt(g,n,a(y))),!l&&(f.length>u||g.includes(`
|
48
|
-
`))&&(l=!0),f.push(g),u=f.length}let{start:p,end:h}=t;if(f.length===0)return p+h;if(!l){let m=f.reduce((d,y)=>d+y.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=p;for(let d of f)m+=d?`
|
49
|
-
${o}${s}${d}`:`
|
50
|
-
`;return`${m}
|
51
|
-
${s}${h}`}else return`${p}${i}${f.join(" ")}${i}${h}`}function zi({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let o=Ve(e(n),r);t.push(o.trimStart())}}var El=A(()=>{"use strict";q();js();Us()});function er(r,e){let t=M(e)?e.value:e;for(let n of r)if(F(n)&&(n.key===e||n.key===t||M(n.key)&&n.key.value===t))return n}var ee,tr=A(()=>{"use strict";El();vl();Ni();q();Zt();oe();ee=class extends vn{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(rt,e),this.items=[]}static from(e,t,n){let{keepUndefined:s,replacer:o}=n,i=new this(e),a=(c,l)=>{if(typeof o=="function")l=o.call(t,c,l);else if(Array.isArray(o)&&!o.includes(c))return;(l!==void 0||s)&&i.items.push(_n(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&i.items.sort(e.sortMapEntries),i}add(e,t){let n;F(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Z(e,e?.value):n=new Z(e.key,e.value);let s=er(this.items,n.key),o=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);M(s.value)&&Di(n.value)?s.value.value=n.value:s.value=n.value}else if(o){let i=this.items.findIndex(a=>o(n,a)<0);i===-1?this.items.push(n):this.items.splice(i,0,n)}else this.items.push(n)}delete(e){let t=er(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=er(this.items,e)?.value;return(!t&&M(s)?s.value:s)??void 0}has(e){return!!er(this.items,e)}set(e,t){this.add(new Z(e,t),!0)}toJSON(e,t,n){let s=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(s);for(let o of this.items)Ki(t,s,o);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!F(s))throw new Error(`Map items must all be pairs; found ${JSON.stringify(s)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Hi(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}});var nt,An=A(()=>{"use strict";q();tr();nt={collection:"map",default:!0,nodeClass:ee,tag:"tag:yaml.org,2002:map",resolve(r,e){return ze(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>ee.from(r,e,t)}});function ji(r){let e=M(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}var he,rr=A(()=>{"use strict";Rs();El();Ni();q();oe();Yt();he=class extends vn{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ot,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=ji(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=ji(e);if(typeof n!="number")return;let s=this.items[n];return!t&&M(s)?s.value:s}has(e){let t=ji(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=ji(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];M(s)&&Di(t)?s.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let s=0;for(let o of this.items)n.push(ie(o,String(s++),t));return n}toString(e,t,n){return e?Hi(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:s}=n,o=new this(e);if(t&&Symbol.iterator in Object(t)){let i=0;for(let a of t){if(typeof s=="function"){let c=t instanceof Set?a:String(i++);a=s.call(t,c,a)}o.items.push(Rt(a,void 0,n))}}return o}}});var st,In=A(()=>{"use strict";q();rr();st={collection:"seq",default:!0,nodeClass:he,tag:"tag:yaml.org,2002:seq",resolve(r,e){return He(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>he.from(r,e,t)}});var nr,Vs=A(()=>{"use strict";Hs();nr={identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify(r,e,t,n){return e=Object.assign({actualString:!0},e),Ft(r,e,t,n)}}});var Pr,Vi=A(()=>{"use strict";oe();Pr={identify:r=>r==null,createNode:()=>new B(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new B(null),stringify:({source:r},e)=>typeof r=="string"&&Pr.test.test(r)?r:e.options.nullStr}});var Ws,Tl=A(()=>{"use strict";oe();Ws={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new B(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Ws.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}}});function ge({format:r,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);let s=typeof n=="number"?n:Number(n);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let o=JSON.stringify(n);if(!r&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(o)){let i=o.indexOf(".");i<0&&(i=o.length,o+=".");let a=e-(o.length-i-1);for(;a-- >0;)o+="0"}return o}var Cn=A(()=>{"use strict"});var Wi,qi,Gi,_l=A(()=>{"use strict";oe();Cn();Wi={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ge},qi={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():ge(r)}},Gi={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new B(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:ge}});function Gp(r,e,t){let{value:n}=r;return Ji(n)&&n>=0?t+n.toString(e):ge(r)}var Ji,Al,Qi,Yi,Xi,Il=A(()=>{"use strict";Cn();Ji=r=>typeof r=="bigint"||Number.isInteger(r),Al=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);Qi={identify:r=>Ji(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>Al(r,2,8,t),stringify:r=>Gp(r,8,"0o")},Yi={identify:Ji,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>Al(r,0,10,t),stringify:ge},Xi={identify:r=>Ji(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>Al(r,2,16,t),stringify:r=>Gp(r,16,"0x")}});var Jp,Qp=A(()=>{"use strict";An();Vi();In();Vs();Tl();_l();Il();Jp=[nt,st,nr,Pr,Ws,Qi,Yi,Xi,Wi,qi,Gi]});function Yp(r){return typeof r=="bigint"||Number.isInteger(r)}var Zi,JS,QS,Xp,Zp=A(()=>{"use strict";oe();An();In();Zi=({value:r})=>JSON.stringify(r),JS=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Zi},{identify:r=>r==null,createNode:()=>new B(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Zi},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:r=>r==="true",stringify:Zi},{identify:Yp,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(r,e,{intAsBigInt:t})=>t?BigInt(r):parseInt(r,10),stringify:({value:r})=>Yp(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:Zi}],QS={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Xp=[nt,st].concat(JS,QS)});var qs,Cl=A(()=>{"use strict";oe();Hs();qs={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof Buffer=="function")return Buffer.from(r,"base64");if(typeof atob=="function"){let t=atob(r.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let s=0;s<t.length;++s)n[s]=t.charCodeAt(s);return n}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),r},stringify({comment:r,type:e,value:t},n,s,o){let i=t,a;if(typeof Buffer=="function")a=i instanceof Buffer?i.toString("base64"):Buffer.from(i.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<i.length;++l)c+=String.fromCharCode(i[l]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e||(e=B.BLOCK_LITERAL),e!==B.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(a.length/c),u=new Array(l);for(let f=0,p=0;f<l;++f,p+=c)u[f]=a.substr(p,c);a=u.join(e===B.BLOCK_LITERAL?`
|
52
|
-
`:" ")}return Ft({comment:r,type:e,value:a},n,s,o)}}});function Ll(r,e){if(He(r))for(let t=0;t<r.items.length;++t){let n=r.items[t];if(!F(n)){if(ze(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new Z(new B(null));if(n.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${n.commentBefore}
|
53
|
-
${s.key.commentBefore}`:n.commentBefore),n.comment){let o=s.value??s.key;o.comment=o.comment?`${n.comment}
|
54
|
-
${o.comment}`:n.comment}n=s}r.items[t]=F(n)?n:new Z(n)}}else e("Expected a sequence for this tag");return r}function Bl(r,e,t){let{replacer:n}=t,s=new he(r);s.tag="tag:yaml.org,2002:pairs";let o=0;if(e&&Symbol.iterator in Object(e))for(let i of e){typeof n=="function"&&(i=n.call(e,String(o++),i));let a,c;if(Array.isArray(i))if(i.length===2)a=i[0],c=i[1];else throw new TypeError(`Expected [key, value] tuple: ${i}`);else if(i&&i instanceof Object){let l=Object.keys(i);if(l.length===1)a=l[0],c=i[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=i;s.items.push(_n(a,c,t))}return s}var Gs,ea=A(()=>{"use strict";q();Zt();oe();rr();Gs={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ll,createNode:Bl}});var Ln,Js,Pl=A(()=>{"use strict";q();Yt();tr();rr();ea();Ln=class r extends he{constructor(){super(),this.add=ee.prototype.add.bind(this),this.delete=ee.prototype.delete.bind(this),this.get=ee.prototype.get.bind(this),this.has=ee.prototype.has.bind(this),this.set=ee.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let s of this.items){let o,i;if(F(s)?(o=ie(s.key,"",t),i=ie(s.value,o,t)):o=ie(s,"",t),n.has(o))throw new Error("Ordered maps must not include duplicate keys");n.set(o,i)}return n}static from(e,t,n){let s=Bl(e,t,n),o=new this;return o.items=s.items,o}};Ln.tag="tag:yaml.org,2002:omap";Js={collection:"seq",identify:r=>r instanceof Map,nodeClass:Ln,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Ll(r,e),n=[];for(let{key:s}of t.items)M(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new Ln,t)},createNode:(r,e,t)=>Ln.from(r,e,t)}});function em({value:r,source:e},t){return e&&(r?Dl:Nl).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Dl,Nl,tm=A(()=>{"use strict";oe();Dl={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new B(!0),stringify:em},Nl={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new B(!1),stringify:em}});var rm,nm,sm,om=A(()=>{"use strict";oe();Cn();rm={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ge},nm={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():ge(r)}},sm={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new B(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let n=r.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:ge}});function ta(r,e,t,{intAsBigInt:n}){let s=r[0];if((s==="-"||s==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),n){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let i=BigInt(r);return s==="-"?BigInt(-1)*i:i}let o=parseInt(r,t);return s==="-"?-1*o:o}function Ml(r,e,t){let{value:n}=r;if(Qs(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return ge(r)}var Qs,im,am,cm,lm,um=A(()=>{"use strict";Cn();Qs=r=>typeof r=="bigint"||Number.isInteger(r);im={identify:Qs,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>ta(r,2,2,t),stringify:r=>Ml(r,2,"0b")},am={identify:Qs,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>ta(r,1,8,t),stringify:r=>Ml(r,8,"0")},cm={identify:Qs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>ta(r,0,10,t),stringify:ge},lm={identify:Qs,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>ta(r,2,16,t),stringify:r=>Ml(r,16,"0x")}});var Bn,Ys,Ol=A(()=>{"use strict";q();Zt();tr();Bn=class r extends ee{constructor(e){super(e),this.tag=r.tag}add(e){let t;F(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Z(e.key,null):t=new Z(e,null),er(this.items,t.key)||this.items.push(t)}get(e,t){let n=er(this.items,e);return!t&&F(n)?M(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=er(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Z(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){let{replacer:s}=n,o=new this(e);if(t&&Symbol.iterator in Object(t))for(let i of t)typeof s=="function"&&(i=s.call(t,i,i)),o.items.push(_n(i,null,n));return o}};Bn.tag="tag:yaml.org,2002:set";Ys={collection:"map",identify:r=>r instanceof Set,nodeClass:Bn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>Bn.from(r,e,t),resolve(r,e){if(ze(r)){if(r.hasAllNullValues(!0))return Object.assign(new Bn,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}}});function Rl(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,s=i=>e?BigInt(i):Number(i),o=n.replace(/_/g,"").split(":").reduce((i,a)=>i*s(60)+s(a),s(0));return t==="-"?s(-1)*o:o}function fm(r){let{value:e}=r,t=i=>i;if(typeof e=="bigint")t=i=>BigInt(i);else if(isNaN(e)||!isFinite(e))return ge(r);let n="";e<0&&(n="-",e*=t(-1));let s=t(60),o=[e%s];return e<60?o.unshift(0):(e=(e-o[0])/s,o.unshift(e%s),e>=60&&(e=(e-o[0])/s,o.unshift(e))),n+o.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var ra,na,Pn,Fl=A(()=>{"use strict";Cn();ra={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>Rl(r,t),stringify:fm},na={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>Rl(r,!1),stringify:fm},Pn={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(Pn.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,o,i,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,o||0,i||0,a||0,c),u=e[8];if(u&&u!=="Z"){let f=Rl(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:r})=>r.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")}});var Ul,hm=A(()=>{"use strict";An();Vi();In();Vs();Cl();tm();om();um();Pl();ea();Ol();Fl();Ul=[nt,st,nr,Pr,Dl,Nl,im,am,cm,lm,rm,nm,sm,qs,Js,Gs,Ys,ra,na,Pn]});function sa(r,e){let t=dm.get(e);if(!t)if(Array.isArray(r))t=[];else{let n=Array.from(dm.keys()).filter(s=>s!=="yaml11").map(s=>JSON.stringify(s)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${n} or define customTags array`)}if(Array.isArray(r))for(let n of r)t=t.concat(n);else typeof r=="function"&&(t=r(t.slice()));return t.map(n=>{if(typeof n!="string")return n;let s=pm[n];if(s)return s;let o=Object.keys(pm).map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown custom tag "${n}"; use one of ${o}`)})}var dm,pm,mm,ym=A(()=>{"use strict";An();Vi();In();Vs();Tl();_l();Il();Qp();Zp();Cl();Pl();ea();hm();Ol();Fl();dm=new Map([["core",Jp],["failsafe",[nt,st,nr]],["json",Xp],["yaml11",Ul],["yaml-1.1",Ul]]),pm={binary:qs,bool:Ws,float:Gi,floatExp:qi,floatNaN:Wi,floatTime:na,int:Yi,intHex:Xi,intOct:Qi,intTime:ra,map:nt,null:Pr,omap:Js,pairs:Gs,seq:st,set:Ys,timestamp:Pn},mm={"tag:yaml.org,2002:binary":qs,"tag:yaml.org,2002:omap":Js,"tag:yaml.org,2002:pairs":Gs,"tag:yaml.org,2002:set":Ys,"tag:yaml.org,2002:timestamp":Pn}});var YS,Dn,$l=A(()=>{"use strict";q();An();In();Vs();ym();YS=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,Dn=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:o,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(e)?sa(e,"compat"):e?sa(null,e):null,this.merge=!!n,this.name=typeof o=="string"&&o||"core",this.knownTags=s?mm:{},this.tags=sa(t,this.name),this.toStringOptions=a??null,Object.defineProperty(this,rt,{value:nt}),Object.defineProperty(this,$e,{value:nr}),Object.defineProperty(this,Ot,{value:st}),this.sortMapEntries=typeof i=="function"?i:i===!0?YS:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}});function gm(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let s=Ui(r,e),{commentString:o}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=o(r.commentBefore);t.unshift(Ve(c,""))}let i=!1,a=null;if(r.contents){if(U(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let u=o(r.contents.commentBefore);t.push(Ve(u,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>i=!0,l=Ut(r.contents,s,()=>a=null,c);a&&(l+=xt(l,"",o(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Ut(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=o(r.comment);c.includes(`
|
55
|
-
`)?(t.push("..."),t.push(Ve(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=r.comment;c&&i&&(c=c.replace(/^\n+/,"")),c&&((!i||a)&&t[t.length-1]!==""&&t.push(""),t.push(Ve(o(c),"")))}return t.join(`
|
56
|
-
`)+`
|
57
|
-
`}var wm=A(()=>{"use strict";q();js();Us()});function Nn(r){if(j(r))return!0;throw new Error("Expected a YAML collection as document contents")}var kt,Xs=A(()=>{"use strict";Os();Ni();q();Zt();Yt();$l();wm();Li();gl();Rs();pl();kt=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ke,{value:Ii});let s=null;typeof t=="function"||Array.isArray(t)?s=t:n===void 0&&t&&(n=t,t=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,uniqueKeys:!0,version:"1.2"},n);this.options=o;let{version:i}=o;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new wt({version:i}),this.setSchema(i,n),this.contents=e===void 0?null:this.createNode(e,s,n)}clone(){let e=Object.create(r.prototype,{[ke]:{value:Ii}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=U(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Nn(this.contents)&&this.contents.add(e)}addIn(e,t){Nn(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=ml(this);e.anchor=!t||n.has(t)?yl(t||"a",n):t}return new bt(e.anchor)}createNode(e,t,n){let s;if(typeof t=="function")e=t.call({"":e},"",e),s=t;else if(Array.isArray(t)){let y=b=>typeof b=="number"||b instanceof String||b instanceof Number,g=t.filter(y).map(String);g.length>0&&(t=t.concat(g)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:o,anchorPrefix:i,flow:a,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:f,setAnchors:p,sourceObjects:h}=Kp(this,i||"a"),m={aliasDuplicateObjects:o??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:h},d=Rt(e,u,m);return a&&j(d)&&(d.flow=!0),p(),d}createPair(e,t,n={}){let s=this.createNode(e,null,n),o=this.createNode(t,null,n);return new Z(s,o)}delete(e){return Nn(this.contents)?this.contents.delete(e):!1}deleteIn(e){return En(e)?this.contents==null?!1:(this.contents=null,!0):Nn(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return j(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return En(e)?!t&&M(this.contents)?this.contents.value:this.contents:j(this.contents)?this.contents.getIn(e,t):void 0}has(e){return j(this.contents)?this.contents.has(e):!1}hasIn(e){return En(e)?this.contents!==void 0:j(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Fs(this.schema,[e],t):Nn(this.contents)&&this.contents.set(e,t)}setIn(e,t){En(e)?this.contents=t:this.contents==null?this.contents=Fs(this.schema,Array.from(e),t):Nn(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new wt({version:"1.1"}),n={merge:!0,resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new wt({version:e}),n={merge:!1,resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let s=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${s}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Dn(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:s,onAnchor:o,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},c=ie(this.contents,t??"",a);if(typeof o=="function")for(let{count:l,res:u}of a.anchors.values())o(u,l);return typeof i=="function"?Qt(i,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return gm(this,e)}}});var Mn,Pe,On,Zs,eo=A(()=>{"use strict";Mn=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},Pe=class extends Mn{constructor(e,t,n){super("YAMLParseError",e,t,n)}},On=class extends Mn{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Zs=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:s}=t.linePos[0];t.message+=` at line ${n}, column ${s}`;let o=s-1,i=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(o>=60&&i.length>80){let a=Math.min(o-39,i.length-79);i="\u2026"+i.substring(a),o-=a-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(i.substring(0,o))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
|
58
|
-
`),i=a+i}if(/[^ ]/.test(i)){let a=1,c=t.linePos[1];c&&c.line===n&&c.col>s&&(a=Math.max(1,Math.min(c.col-s,80-o)));let l=" ".repeat(o)+"^".repeat(a);t.message+=`:
|
59
|
-
|
60
|
-
${i}
|
61
|
-
${l}
|
62
|
-
`}}});function St(r,{flow:e,indicator:t,next:n,offset:s,onError:o,parentIndent:i,startOnNewline:a}){let c=!1,l=a,u=a,f="",p="",h=!1,m=!1,d=null,y=null,g=null,b=null,x=null,k=null,S=null;for(let _ of r)switch(m&&(_.type!=="space"&&_.type!=="newline"&&_.type!=="comma"&&o(_.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),d&&(l&&_.type!=="comment"&&_.type!=="newline"&&o(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),d=null),_.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&_.source.includes(" ")&&(d=_),u=!0;break;case"comment":{u||o(_,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let W=_.source.substring(1)||" ";f?f+=p+W:f=W,p="",l=!1;break}case"newline":l?f?f+=_.source:c=!0:p+=_.source,l=!0,h=!0,(y||g)&&(b=_),u=!0;break;case"anchor":y&&o(_,"MULTIPLE_ANCHORS","A node can have at most one anchor"),_.source.endsWith(":")&&o(_.offset+_.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=_,S===null&&(S=_.offset),l=!1,u=!1,m=!0;break;case"tag":{g&&o(_,"MULTIPLE_TAGS","A node can have at most one tag"),g=_,S===null&&(S=_.offset),l=!1,u=!1,m=!0;break}case t:(y||g)&&o(_,"BAD_PROP_ORDER",`Anchors and tags must be after the ${_.source} indicator`),k&&o(_,"UNEXPECTED_TOKEN",`Unexpected ${_.source} in ${e??"collection"}`),k=_,l=t==="seq-item-ind"||t==="explicit-key-ind",u=!1;break;case"comma":if(e){x&&o(_,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),x=_,l=!1,u=!1;break}default:o(_,"UNEXPECTED_TOKEN",`Unexpected ${_.type} token`),l=!1,u=!1}let T=r[r.length-1],E=T?T.offset+T.source.length:s;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&o(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),d&&(l&&d.indent<=i||n?.type==="block-map"||n?.type==="block-seq")&&o(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:x,found:k,spaceBefore:c,comment:f,hasNewline:h,anchor:y,tag:g,newlineAfterProp:b,end:E,start:S??E}}var to=A(()=>{"use strict"});function sr(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(`
|
63
|
-
`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(sr(e.key)||sr(e.value))return!0}return!1;default:return!0}}var oa=A(()=>{"use strict"});function ro(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&sr(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}var Kl=A(()=>{"use strict";oa()});function ia(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(o,i)=>o===i||M(o)&&M(i)&&o.value===i.value&&!(o.value==="<<"&&r.schema.merge);return e.some(o=>s(o.key,t))}var zl=A(()=>{"use strict";q()});function xm({composeNode:r,composeEmptyNode:e},t,n,s,o){let i=o?.nodeClass??ee,a=new i(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:f,key:p,sep:h,value:m}=u,d=St(f,{indicator:"explicit-key-ind",next:p??h?.[0],offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0}),y=!d.found;if(y){if(p&&(p.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==n.indent&&s(c,"BAD_INDENT",bm)),!d.anchor&&!d.tag&&!h){l=d.end,d.comment&&(a.comment?a.comment+=`
|
64
|
-
`+d.comment:a.comment=d.comment);continue}(d.newlineAfterProp||sr(p))&&s(p??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else d.found?.indent!==n.indent&&s(c,"BAD_INDENT",bm);let g=d.end,b=p?r(t,p,d,s):e(t,g,f,null,d,s);t.schema.compat&&ro(n.indent,p,s),ia(t,a.items,b)&&s(g,"DUPLICATE_KEY","Map keys must be unique");let x=St(h??[],{indicator:"map-value-ind",next:m,offset:b.range[2],onError:s,parentIndent:n.indent,startOnNewline:!p||p.type==="block-scalar"});if(c=x.end,x.found){y&&(m?.type==="block-map"&&!x.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&d.start<x.found.offset-1024&&s(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=m?r(t,m,x,s):e(t,c,h,null,x,s);t.schema.compat&&ro(n.indent,m,s),c=k.range[2];let S=new Z(b,k);t.options.keepSourceTokens&&(S.srcToken=u),a.items.push(S)}else{y&&s(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),x.comment&&(b.comment?b.comment+=`
|
65
|
-
`+x.comment:b.comment=x.comment);let k=new Z(b);t.options.keepSourceTokens&&(k.srcToken=u),a.items.push(k)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}var bm,km=A(()=>{"use strict";Zt();tr();to();oa();Kl();zl();bm="All mapping items must start at the same column"});function Sm({composeNode:r,composeEmptyNode:e},t,n,s,o){let i=o?.nodeClass??he,a=new i(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let{start:u,value:f}of n.items){let p=St(u,{indicator:"seq-item-ind",next:f,offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||f)f&&f.type==="block-seq"?s(p.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{l=p.end,p.comment&&(a.comment=p.comment);continue}let h=f?r(t,f,p,s):e(t,p.end,u,null,p,s);t.schema.compat&&ro(n.indent,f,s),c=h.range[2],a.items.push(h)}return a.range=[n.offset,c,l??c],a}var vm=A(()=>{"use strict";rr();to();Kl()});function vt(r,e,t,n){let s="";if(r){let o=!1,i="";for(let a of r){let{source:c,type:l}=a;switch(l){case"space":o=!0;break;case"comment":{t&&!o&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";s?s+=i+u:s=u,i="";break}case"newline":s&&(i+=c),o=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:s,offset:e}}var Rn=A(()=>{"use strict"});function Em({composeNode:r,composeEmptyNode:e},t,n,s,o){let i=n.start.source==="{",a=i?"flow map":"flow sequence",c=o?.nodeClass??(i?ee:he),l=new c(t.schema);l.flow=!0;let u=t.atRoot;u&&(t.atRoot=!1);let f=n.offset+n.start.source.length;for(let y=0;y<n.items.length;++y){let g=n.items[y],{start:b,key:x,sep:k,value:S}=g,T=St(b,{flow:a,indicator:"explicit-key-ind",next:x??k?.[0],offset:f,onError:s,parentIndent:n.indent,startOnNewline:!1});if(!T.found){if(!T.anchor&&!T.tag&&!k&&!S){y===0&&T.comma?s(T.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&s(T.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),T.comment&&(l.comment?l.comment+=`
|
66
|
-
`+T.comment:l.comment=T.comment),f=T.end;continue}!i&&t.options.strict&&sr(x)&&s(x,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)T.comma&&s(T.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(T.comma||s(T.start,"MISSING_CHAR",`Missing , between ${a} items`),T.comment){let E="";e:for(let _ of b)switch(_.type){case"comma":case"space":break;case"comment":E=_.source.substring(1);break e;default:break e}if(E){let _=l.items[l.items.length-1];F(_)&&(_=_.value??_.key),_.comment?_.comment+=`
|
67
|
-
`+E:_.comment=E,T.comment=T.comment.substring(E.length+1)}}if(!i&&!k&&!T.found){let E=S?r(t,S,T,s):e(t,T.end,k,null,T,s);l.items.push(E),f=E.range[2],jl(S)&&s(E.range,"BLOCK_IN_FLOW",Hl)}else{let E=T.end,_=x?r(t,x,T,s):e(t,E,b,null,T,s);jl(x)&&s(_.range,"BLOCK_IN_FLOW",Hl);let W=St(k??[],{flow:a,indicator:"map-value-ind",next:S,offset:_.range[2],onError:s,parentIndent:n.indent,startOnNewline:!1});if(W.found){if(!i&&!T.found&&t.options.strict){if(k)for(let Y of k){if(Y===W.found)break;if(Y.type==="newline"){s(Y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}T.start<W.found.offset-1024&&s(W.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source&&S.source[0]===":"?s(S,"MISSING_CHAR",`Missing space after : in ${a}`):s(W.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let le=S?r(t,S,W,s):W.found?e(t,W.end,k,null,W,s):null;le?jl(S)&&s(le.range,"BLOCK_IN_FLOW",Hl):W.comment&&(_.comment?_.comment+=`
|
68
|
-
`+W.comment:_.comment=W.comment);let Te=new Z(_,le);if(t.options.keepSourceTokens&&(Te.srcToken=g),i){let Y=l;ia(t,Y.items,_)&&s(E,"DUPLICATE_KEY","Map keys must be unique"),Y.items.push(Te)}else{let Y=new ee(t.schema);Y.flow=!0,Y.items.push(Te);let R=(le??_).range;Y.range=[_.range[0],R[1],R[2]],l.items.push(Y)}f=le?le.range[2]:W.end}}let p=i?"}":"]",[h,...m]=n.end,d=f;if(h&&h.source===p)d=h.offset+h.source.length;else{let y=a[0].toUpperCase()+a.substring(1),g=u?`${y} must end with a ${p}`:`${y} in block collection must be sufficiently indented and end with a ${p}`;s(f,u?"MISSING_CHAR":"BAD_INDENT",g),h&&h.source.length!==1&&m.unshift(h)}if(m.length>0){let y=vt(m,d,t.options.strict,s);y.comment&&(l.comment?l.comment+=`
|
69
|
-
`+y.comment:l.comment=y.comment),l.range=[n.offset,d,y.offset]}else l.range=[n.offset,d,d];return l}var Hl,jl,Tm=A(()=>{"use strict";q();Zt();tr();rr();Rn();to();oa();zl();Hl="Block collections are not allowed within flow collections",jl=r=>r&&(r.type==="block-map"||r.type==="block-seq")});function Vl(r,e,t,n,s,o){let i=t.type==="block-map"?xm(r,e,t,n,o):t.type==="block-seq"?Sm(r,e,t,n,o):Em(r,e,t,n,o),a=i.constructor;return s==="!"||s===a.tagName?(i.tag=a.tagName,i):(s&&(i.tag=s),i)}function _m(r,e,t,n,s){let o=n.tag,i=o?e.directives.tagName(o.source,p=>s(o,"TAG_RESOLVE_FAILED",p)):null;if(t.type==="block-seq"){let{anchor:p,newlineAfterProp:h}=n,m=p&&o?p.offset>o.offset?p:o:p??o;m&&(!h||h.offset<m.offset)&&s(m,"MISSING_CHAR","Missing newline after block sequence props")}let a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!o||!i||i==="!"||i===ee.tagName&&a==="map"||i===he.tagName&&a==="seq")return Vl(r,e,t,s,i);let c=e.schema.tags.find(p=>p.tag===i&&p.collection===a);if(!c){let p=e.schema.knownTags[i];if(p&&p.collection===a)e.schema.tags.push(Object.assign({},p,{default:!1})),c=p;else return p?.collection?s(o,"BAD_COLLECTION_TYPE",`${p.tag} used for ${a} collection, but expects ${p.collection}`,!0):s(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),Vl(r,e,t,s,i)}let l=Vl(r,e,t,s,i,c),u=c.resolve?.(l,p=>s(o,"TAG_RESOLVE_FAILED",p),e.options)??l,f=U(u)?u:new B(u);return f.range=l.range,f.tag=i,c?.format&&(f.format=c.format),f}var Am=A(()=>{"use strict";q();oe();tr();rr();km();vm();Tm()});function aa(r,e,t){let n=e.offset,s=XS(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let o=s.mode===">"?B.BLOCK_FOLDED:B.BLOCK_LITERAL,i=e.source?ZS(e.source):[],a=i.length;for(let d=i.length-1;d>=0;--d){let y=i[d][1];if(y===""||y==="\r")a=d;else break}if(a===0){let d=s.chomp==="+"&&i.length>0?`
|
70
|
-
`.repeat(Math.max(1,i.length-1)):"",y=n+s.length;return e.source&&(y+=e.source.length),{value:d,type:o,comment:s.comment,range:[n,y,y]}}let c=e.indent+s.indent,l=e.offset+s.length,u=0;for(let d=0;d<a;++d){let[y,g]=i[d];if(g===""||g==="\r")s.indent===0&&y.length>c&&(c=y.length);else{y.length<c&&t(l+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=y.length),u=d,c===0&&!r.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=y.length+g.length+1}for(let d=i.length-1;d>=a;--d)i[d][0].length>c&&(a=d+1);let f="",p="",h=!1;for(let d=0;d<u;++d)f+=i[d][0].slice(c)+`
|
71
|
-
`;for(let d=u;d<a;++d){let[y,g]=i[d];l+=y.length+g.length+1;let b=g[g.length-1]==="\r";if(b&&(g=g.slice(0,-1)),g&&y.length<c){let k=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(l-g.length-(b?2:1),"BAD_INDENT",k),y=""}o===B.BLOCK_LITERAL?(f+=p+y.slice(c)+g,p=`
|
72
|
-
`):y.length>c||g[0]===" "?(p===" "?p=`
|
73
|
-
`:!h&&p===`
|
74
|
-
`&&(p=`
|
75
|
-
|
76
|
-
`),f+=p+y.slice(c)+g,p=`
|
77
|
-
`,h=!0):g===""?p===`
|
78
|
-
`?f+=`
|
79
|
-
`:p=`
|
80
|
-
`:(f+=p+g,p=" ",h=!1)}switch(s.chomp){case"-":break;case"+":for(let d=a;d<i.length;++d)f+=`
|
81
|
-
`+i[d][0].slice(c);f[f.length-1]!==`
|
82
|
-
`&&(f+=`
|
83
|
-
`);break;default:f+=`
|
84
|
-
`}let m=n+s.length+e.source.length;return{value:f,type:o,comment:s.comment,range:[n,m,m]}}function XS({offset:r,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=e[0],o=s[0],i=0,a="",c=-1;for(let p=1;p<s.length;++p){let h=s[p];if(!a&&(h==="-"||h==="+"))a=h;else{let m=Number(h);!i&&m?i=m:c===-1&&(c=r+p)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,u="",f=s.length;for(let p=1;p<e.length;++p){let h=e[p];switch(h.type){case"space":l=!0;case"newline":f+=h.source.length;break;case"comment":t&&!l&&n(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=h.source.length,u=h.source.substring(1);break;case"error":n(h,"UNEXPECTED_TOKEN",h.message),f+=h.source.length;break;default:{let m=`Unexpected token in block scalar header: ${h.type}`;n(h,"UNEXPECTED_TOKEN",m);let d=h.source;d&&typeof d=="string"&&(f+=d.length)}}}return{mode:o,indent:i,chomp:a,comment:u,length:f}}function ZS(r){let e=r.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),o=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let i=1;i<e.length;i+=2)o.push([e[i],e[i+1]]);return o}var Wl=A(()=>{"use strict";oe()});function ca(r,e,t){let{offset:n,type:s,source:o,end:i}=r,a,c,l=(p,h,m)=>t(n+p,h,m);switch(s){case"scalar":a=B.PLAIN,c=e1(o,l);break;case"single-quoted-scalar":a=B.QUOTE_SINGLE,c=t1(o,l);break;case"double-quoted-scalar":a=B.QUOTE_DOUBLE,c=r1(o,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[n,n+o.length,n+o.length]}}let u=n+o.length,f=vt(i,u,e,t);return{value:c,type:a,comment:f.comment,range:[n,u,f.offset]}}function e1(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Im(r)}function t1(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Im(r.slice(1,-1)).replace(/''/g,"'")}function Im(r){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
85
|
-
`,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
86
|
-
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(r);if(!n)return r;let s=n[1],o=" ",i=e.lastIndex;for(t.lastIndex=i;n=t.exec(r);)n[1]===""?o===`
|
87
|
-
`?s+=o:o=`
|
88
|
-
`:(s+=o+n[1],o=" "),i=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=i,n=a.exec(r),s+o+(n?.[1]??"")}function r1(r,e){let t="";for(let n=1;n<r.length-1;++n){let s=r[n];if(!(s==="\r"&&r[n+1]===`
|
89
|
-
`))if(s===`
|
90
|
-
`){let{fold:o,offset:i}=n1(r,n);t+=o,n=i}else if(s==="\\"){let o=r[++n],i=s1[o];if(i)t+=i;else if(o===`
|
91
|
-
`)for(o=r[n+1];o===" "||o===" ";)o=r[++n+1];else if(o==="\r"&&r[n+1]===`
|
92
|
-
`)for(o=r[++n+1];o===" "||o===" ";)o=r[++n+1];else if(o==="x"||o==="u"||o==="U"){let a={x:2,u:4,U:8}[o];t+=o1(r,n+1,a,e),n+=a}else{let a=r.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(s===" "||s===" "){let o=n,i=r[n+1];for(;i===" "||i===" ";)i=r[++n+1];i!==`
|
93
|
-
`&&!(i==="\r"&&r[n+2]===`
|
94
|
-
`)&&(t+=n>o?r.slice(o,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function n1(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===`
|
95
|
-
`||n==="\r")&&!(n==="\r"&&r[e+2]!==`
|
96
|
-
`);)n===`
|
97
|
-
`&&(t+=`
|
98
|
-
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}function o1(r,e,t,n){let s=r.substr(e,t),i=s.length===t&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;if(isNaN(i)){let a=r.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(i)}var s1,ql=A(()=>{"use strict";oe();Rn();s1={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
99
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "}});function Gl(r,e,t,n){let{value:s,type:o,comment:i,range:a}=e.type==="block-scalar"?aa(r,e,n):ca(e,r.options.strict,n),c=t?r.directives.tagName(t.source,f=>n(t,"TAG_RESOLVE_FAILED",f)):null,l=t&&c?i1(r.schema,s,c,t,n):e.type==="scalar"?a1(r,s,e,n):r.schema[$e],u;try{let f=l.resolve(s,p=>n(t??e,"TAG_RESOLVE_FAILED",p),r.options);u=M(f)?f:new B(f)}catch(f){let p=f instanceof Error?f.message:String(f);n(t??e,"TAG_RESOLVE_FAILED",p),u=new B(s)}return u.range=a,u.source=s,o&&(u.type=o),c&&(u.tag=c),l.format&&(u.format=l.format),i&&(u.comment=i),u}function i1(r,e,t,n,s){if(t==="!")return r[$e];let o=[];for(let a of r.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)o.push(a);else return a;for(let a of o)if(a.test?.test(e))return a;let i=r.knownTags[t];return i&&!i.collection?(r.tags.push(Object.assign({},i,{default:!1,test:void 0})),i):(s(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[$e])}function a1({directives:r,schema:e},t,n,s){let o=e.tags.find(i=>i.default&&i.test?.test(t))||e[$e];if(e.compat){let i=e.compat.find(a=>a.default&&a.test?.test(t))??e[$e];if(o.tag!==i.tag){let a=r.tagString(o.tag),c=r.tagString(i.tag),l=`Value may be parsed as either ${a} or ${c}`;s(n,"TAG_RESOLVE_FAILED",l,!0)}}return o}var Cm=A(()=>{"use strict";q();oe();Wl();ql()});function Lm(r,e,t){if(e){t===null&&(t=e.length);for(let n=t-1;n>=0;--n){let s=e[n];switch(s.type){case"space":case"comment":case"newline":r-=s.source.length;continue}for(s=e[++n];s?.type==="space";)r+=s.source.length,s=e[++n];break}}return r}var Bm=A(()=>{"use strict"});function Jl(r,e,t,n){let{spaceBefore:s,comment:o,anchor:i,tag:a}=t,c,l=!0;switch(e.type){case"alias":c=l1(r,e,n),(i||a)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=Gl(r,e,a,n),i&&(c.anchor=i.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":c=_m(c1,r,e,t,n),i&&(c.anchor=i.source.substring(1));break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",u),c=la(r,e.offset,void 0,null,t,n),l=!1}}return i&&c.anchor===""&&n(i,"BAD_ALIAS","Anchor cannot be an empty string"),s&&(c.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?c.comment=o:c.commentBefore=o),r.options.keepSourceTokens&&l&&(c.srcToken=e),c}function la(r,e,t,n,{spaceBefore:s,comment:o,anchor:i,tag:a,end:c},l){let u={type:"scalar",offset:Lm(e,t,n),indent:-1,source:""},f=Gl(r,u,a,l);return i&&(f.anchor=i.source.substring(1),f.anchor===""&&l(i,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(f.spaceBefore=!0),o&&(f.comment=o,f.range[2]=c),f}function l1({options:r},{offset:e,source:t,end:n},s){let o=new bt(t.substring(1));o.source===""&&s(e,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&s(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=e+t.length,a=vt(n,i,r.strict,s);return o.range=[e,i,a.offset],a.comment&&(o.comment=a.comment),o}var c1,Pm=A(()=>{"use strict";Os();Am();Cm();Rn();Bm();c1={composeNode:Jl,composeEmptyNode:la}});function Dm(r,e,{offset:t,start:n,value:s,end:o},i){let a=Object.assign({_directives:e},r),c=new kt(void 0,a),l={atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=St(n,{indicator:"doc-start",next:s??o?.[0],offset:t,onError:i,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!u.hasNewline&&i(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Jl(l,s,u,i):la(l,u.end,n,null,u,i);let f=c.contents.range[2],p=vt(o,f,!1,i);return p.comment&&(c.comment=p.comment),c.range=[t,f,p.offset],c}var Nm=A(()=>{"use strict";Xs();Pm();Rn();to()});function no(r){if(typeof r=="number")return[r,r+1];if(Array.isArray(r))return r.length===2?r:[r[0],r[1]];let{offset:e,source:t}=r;return[e,e+(typeof t=="string"?t.length:1)]}function Mm(r){let e="",t=!1,n=!1;for(let s=0;s<r.length;++s){let o=r[s];switch(o[0]){case"#":e+=(e===""?"":n?`
|
100
|
-
|
101
|
-
`:`
|
102
|
-
`)+(o.substring(1)||" "),t=!0,n=!1;break;case"%":r[s+1]?.[0]!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var Dr,Ql=A(()=>{"use strict";pl();Xs();eo();q();Nm();Rn();Dr=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,o)=>{let i=no(t);o?this.warnings.push(new On(i,n,s)):this.errors.push(new Pe(i,n,s))},this.directives=new wt({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=Mm(this.prelude);if(n){let o=e.contents;if(t)e.comment=e.comment?`${e.comment}
|
103
|
-
${n}`:n;else if(s||e.directives.docStart||!o)e.commentBefore=n;else if(j(o)&&!o.flow&&o.items.length>0){let i=o.items[0];F(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${n}
|
104
|
-
${a}`:n}else{let i=o.commentBefore;o.commentBefore=i?`${n}
|
105
|
-
${i}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Mm(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let s of e)yield*this.next(s);yield*this.end(t,n)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,n,s)=>{let o=no(e);o[0]+=t,this.onError(o,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=Dm(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new Pe(no(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new Pe(no(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=vt(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
|
106
|
-
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Pe(no(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),s=new kt(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),s.range=[0,t,t],this.decorate(s,!1),yield s}}}});function Om(r,e=!0,t){if(r){let n=(s,o,i)=>{let a=typeof s=="number"?s:Array.isArray(s)?s[0]:s.offset;if(t)t(a,o,i);else throw new Pe([a,a+1],o,i)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return ca(r,e,n);case"block-scalar":return aa({options:{strict:e}},r,n)}}return null}function Rm(r,e){let{implicitKey:t=!1,indent:n,inFlow:s=!1,offset:o=-1,type:i="PLAIN"}=e,a=Ft({type:i,value:r},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
|
107
|
-
`}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
|
108
|
-
`),u=a.substring(0,l),f=a.substring(l+1)+`
|
109
|
-
`,p=[{type:"block-scalar-header",offset:o,indent:n,source:u}];return Um(p,c)||p.push({type:"newline",offset:-1,indent:n,source:`
|
110
|
-
`}),{type:"block-scalar",offset:o,indent:n,props:p,source:f}}case'"':return{type:"double-quoted-scalar",offset:o,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:o,indent:n,source:a,end:c};default:return{type:"scalar",offset:o,indent:n,source:a,end:c}}}function Fm(r,e,t={}){let{afterKey:n=!1,implicitKey:s=!1,inFlow:o=!1,type:i}=t,a="indent"in r?r.indent:null;if(n&&typeof a=="number"&&(a+=2),!i)switch(r.type){case"single-quoted-scalar":i="QUOTE_SINGLE";break;case"double-quoted-scalar":i="QUOTE_DOUBLE";break;case"block-scalar":{let l=r.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:i="PLAIN"}let c=Ft({type:i,value:e},{implicitKey:s||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":u1(r,c);break;case'"':Yl(r,c,"double-quoted-scalar");break;case"'":Yl(r,c,"single-quoted-scalar");break;default:Yl(r,c,"scalar")}}function u1(r,e){let t=e.indexOf(`
|
111
|
-
`),n=e.substring(0,t),s=e.substring(t+1)+`
|
112
|
-
`;if(r.type==="block-scalar"){let o=r.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=n,r.source=s}else{let{offset:o}=r,i="indent"in r?r.indent:-1,a=[{type:"block-scalar-header",offset:o,indent:i,source:n}];Um(a,"end"in r?r.end:void 0)||a.push({type:"newline",offset:-1,indent:i,source:`
|
113
|
-
`});for(let c of Object.keys(r))c!=="type"&&c!=="offset"&&delete r[c];Object.assign(r,{type:"block-scalar",indent:i,props:a,source:s})}}function Um(r,e){if(e)for(let t of e)switch(t.type){case"space":case"comment":r.push(t);break;case"newline":return r.push(t),!0}return!1}function Yl(r,e,t){switch(r.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":r.type=t,r.source=e;break;case"block-scalar":{let n=r.props.slice(1),s=e.length;r.props[0].type==="block-scalar-header"&&(s-=r.props[0].source.length);for(let o of n)o.offset+=s;delete r.props,Object.assign(r,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{let s={type:"newline",offset:r.offset+e.length,indent:r.indent,source:`
|
114
|
-
`};delete r.items,Object.assign(r,{type:t,source:e,end:[s]});break}default:{let n="indent"in r?r.indent:-1,s="end"in r&&Array.isArray(r.end)?r.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(r))o!=="type"&&o!=="offset"&&delete r[o];Object.assign(r,{type:t,indent:n,source:e,end:s})}}}var $m=A(()=>{"use strict";Wl();ql();eo();Hs()});function fa(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=fa(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=ua(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=ua(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=ua(r);if(r.end)for(let t of r.end)e+=t.source;return e}default:{let e=r.source;if("end"in r&&r.end)for(let t of r.end)e+=t.source;return e}}}function ua({start:r,key:e,sep:t,value:n}){let s="";for(let o of r)s+=o.source;if(e&&(s+=fa(e)),t)for(let o of t)s+=o.source;return n&&(s+=fa(n)),s}var Km,zm=A(()=>{"use strict";Km=r=>"type"in r?fa(r):ua(r)});function or(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),jm(Object.freeze([]),r,e)}function jm(r,e,t){let n=t(e,r);if(typeof n=="symbol")return n;for(let s of["key","value"]){let o=e[s];if(o&&"items"in o){for(let i=0;i<o.items.length;++i){let a=jm(Object.freeze(r.concat([[s,i]])),o.items[i],t);if(typeof a=="number")i=a-1;else{if(a===Xl)return Xl;a===Hm&&(o.items.splice(i,1),i-=1)}}typeof n=="function"&&s==="key"&&(n=n(e,r))}}return typeof n=="function"?n(e,r):n}var Xl,f1,Hm,Vm=A(()=>{"use strict";Xl=Symbol("break visit"),f1=Symbol("skip children"),Hm=Symbol("remove item");or.BREAK=Xl;or.SKIP=f1;or.REMOVE=Hm;or.itemAtPath=(r,e)=>{let t=r;for(let[n,s]of e){let o=t?.[n];if(o&&"items"in o)t=o.items[s];else return}return t};or.parentCollection=(r,e)=>{let t=or.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],s=t?.[n];if(s&&"items"in s)return s;throw new Error("Parent collection not found")}});var eu={};K(eu,{BOM:()=>so,DOCUMENT:()=>oo,FLOW_END:()=>io,SCALAR:()=>Fn,createScalarToken:()=>Rm,isCollection:()=>h1,isScalar:()=>d1,prettyToken:()=>p1,resolveAsScalar:()=>Om,setScalarValue:()=>Fm,stringify:()=>Km,tokenType:()=>Zl,visit:()=>or});function p1(r){switch(r){case so:return"<BOM>";case oo:return"<DOC>";case io:return"<FLOW_END>";case Fn:return"<SCALAR>";default:return JSON.stringify(r)}}function Zl(r){switch(r){case so:return"byte-order-mark";case oo:return"doc-mode";case io:return"flow-error-end";case Fn:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
115
|
-
`:case`\r
|
116
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}var so,oo,io,Fn,h1,d1,ha=A(()=>{"use strict";$m();zm();Vm();so="\uFEFF",oo="",io="",Fn="",h1=r=>!!r&&"items"in r,d1=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar")});function ot(r){switch(r){case void 0:case" ":case`
|
117
|
-
`:case"\r":case" ":return!0;default:return!1}}var Wm,m1,da,y1,tu,Un,ru=A(()=>{"use strict";ha();Wm=new Set("0123456789ABCDEFabcdef"),m1=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),da=new Set(",[]{}"),y1=new Set(` ,[]{}
|
118
|
-
\r `),tu=r=>!r||y1.has(r),Un=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
|
119
|
-
`?!0:t==="\r"?this.buffer[e+1]===`
|
120
|
-
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let s=this.buffer[n+e+1];if(s===`
|
121
|
-
`||!s&&!this.atEnd)return e+n+1}return t===`
|
122
|
-
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&ot(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
123
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===so&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){let o=e[n-1];if(o===" "||o===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){let o=e[t-1];if(o===" "||o===" ")t-=1;else break}let s=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-s),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield oo,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&ot(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ot(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&ot(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(tu),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let s=this.getLine();if(s===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&s[0]!=="#"||n===0&&(s.startsWith("---")||s.startsWith("..."))&&ot(s[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield io,yield*this.parseLineStart();let o=0;for(;s[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),s[o]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-o),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(tu),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||ot(i)||i===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let o=0;for(;this.buffer[t-1-o]==="\\";)o+=1;if(o%2===0)break;t=this.buffer.indexOf('"',t+1)}let n=this.buffer.substring(0,t),s=n.indexOf(`
|
124
|
-
`,this.pos);if(s!==-1){for(;s!==-1;){let o=this.continueScalar(s+1);if(o===-1)break;s=n.indexOf(`
|
125
|
-
`,o)}s!==-1&&(t=s-(n[s-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>ot(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let o=this.pos;n=this.buffer[o];++o)switch(n){case" ":t+=1;break;case`
|
126
|
-
`:e=o,t=0;break;case"\r":{let i=this.buffer[o+1];if(!i&&!this.atEnd)return this.setNext("block-scalar");if(i===`
|
127
|
-
`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let o=this.continueScalar(e+1);if(o===-1)break;e=this.buffer.indexOf(`
|
128
|
-
`,o)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let s=e+1;for(n=this.buffer[s];n===" ";)n=this.buffer[++s];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
|
129
|
-
`;)n=this.buffer[++s];e=s-1}else if(!this.blockScalarKeep)do{let o=e-1,i=this.buffer[o];i==="\r"&&(i=this.buffer[--o]);let a=o;for(;i===" ";)i=this.buffer[--o];if(i===`
|
130
|
-
`&&o>=this.pos&&o+1+t>a)e=o;else break}while(!0);return yield Fn,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,s;for(;s=this.buffer[++n];)if(s===":"){let o=this.buffer[n+1];if(ot(o)||e&&da.has(o))break;t=n}else if(ot(s)){let o=this.buffer[n+1];if(s==="\r"&&(o===`
|
131
|
-
`?(n+=1,s=`
|
132
|
-
`,o=this.buffer[n+1]):t=n),o==="#"||e&&da.has(o))break;if(s===`
|
133
|
-
`){let i=this.continueScalar(n+1);if(i===-1)break;n=Math.max(n,i-2)}}else{if(e&&da.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield Fn,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(tu))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(ot(t)||e&&da.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!ot(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(m1.has(t))t=this.buffer[++e];else if(t==="%"&&Wm.has(this.buffer[e+1])&&Wm.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
134
|
-
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
135
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}});var $n,nu=A(()=>{"use strict";$n=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let o=t+n>>1;this.lineStarts[o]<e?t=o+1:n=o}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let s=this.lineStarts[t-1];return{line:t,col:e-s+1}}}}});function Nr(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function qm(r){for(let e=0;e<r.length;++e)switch(r[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Jm(r){switch(r?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function pa(r){switch(r.type){case"document":return r.start;case"block-map":{let e=r.items[r.items.length-1];return e.sep??e.start}case"block-seq":return r.items[r.items.length-1].start;default:return[]}}function Kn(r){if(r.length===0)return[];let e=r.length;e:for(;--e>=0;)switch(r[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;r[++e]?.type==="space";);return r.splice(e,r.length)}function Gm(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!Nr(e.start,"explicit-key-ind")&&!Nr(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Jm(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}var Mr,su=A(()=>{"use strict";ha();ru();Mr=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Un,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Zl(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let n=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&(!e||e.type!=="doc-end")){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&Gm(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{let s=n.items[n.items.length-1];if(s.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(s.sep)s.value=t;else{Object.assign(s,{key:t,sep:[]}),this.onKeyLine=!s.explicitKey;return}break}case"block-seq":{let s=n.items[n.items.length-1];s.value?n.items.push({start:[],value:t}):s.value=t;break}case"flow-collection":{let s=n.items[n.items.length-1];!s||s.value?n.items.push({start:[],key:t,sep:[]}):s.sep?s.value=t:Object.assign(s,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let s=t.items[t.items.length-1];s&&!s.sep&&!s.value&&s.start.length>0&&qm(s.start)===-1&&(t.indent===0||s.start.every(o=>o.type!=="comment"||o.indent<t.indent))&&(n.type==="document"?n.end=s.start:n.items.push({start:s.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{qm(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let t=pa(this.peek(2)),n=Kn(t),s;e.end?(s=e.end,s.push(this.sourceToken),delete e.end):s=[this.sourceToken];let o={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
|
136
|
-
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
137
|
-
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(s&&t.sep&&!t.value){let i=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":i.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(o=t.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Nr(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(Jm(t.key)&&!Nr(t.sep,"newline")){let i=Kn(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:a,sep:c}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(Nr(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let i=Kn(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||s?e.items.push({start:o,key:null,sep:[this.sourceToken]}):Nr(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);s||t.value?(e.items.push({start:o,key:i,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(i):(Object.assign(t,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(e);if(i){n&&i.type!=="block-seq"&&e.items.push({start:o}),this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Nr(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:s,sep:[]}):t.sep?this.stack.push(s):Object.assign(t,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let s=pa(n),o=Kn(s);Gm(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:o,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
138
|
-
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
139
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=pa(e),n=Kn(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=pa(e),n=Kn(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}});function Qm(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new $n||null,prettyErrors:e}}function Ym(r,e={}){let{lineCounter:t,prettyErrors:n}=Qm(e),s=new Mr(t?.addNewLine),o=new Dr(e),i=Array.from(o.compose(s.parse(r)));if(n&&t)for(let a of i)a.errors.forEach(Zs(r,t)),a.warnings.forEach(Zs(r,t));return i.length>0?i:Object.assign([],{empty:!0},o.streamInfo())}function ou(r,e={}){let{lineCounter:t,prettyErrors:n}=Qm(e),s=new Mr(t?.addNewLine),o=new Dr(e),i=null;for(let a of o.compose(s.parse(r),!0,r.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new Pe(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(i.errors.forEach(Zs(r,t)),i.warnings.forEach(Zs(r,t))),i}function Xm(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=ou(r,t);if(!s)return null;if(s.warnings.forEach(o=>$i(s.options.logLevel,o)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:n},t))}function Zm(r,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let s=Math.round(t);t=s<1?void 0:s>8?{indent:8}:{indent:s}}if(r===void 0){let{keepUndefined:s}=t??e??{};if(!s)return}return new kt(r,n,t).toString(t)}var ey=A(()=>{"use strict";Ql();Xs();eo();kl();nu();su()});var iu={};K(iu,{Alias:()=>bt,CST:()=>eu,Composer:()=>Dr,Document:()=>kt,Lexer:()=>Un,LineCounter:()=>$n,Pair:()=>Z,Parser:()=>Mr,Scalar:()=>B,Schema:()=>Dn,YAMLError:()=>Mn,YAMLMap:()=>ee,YAMLParseError:()=>Pe,YAMLSeq:()=>he,YAMLWarning:()=>On,isAlias:()=>Ke,isCollection:()=>j,isDocument:()=>yt,isMap:()=>ze,isNode:()=>U,isPair:()=>F,isScalar:()=>M,isSeq:()=>He,parse:()=>Xm,parseAllDocuments:()=>Ym,parseDocument:()=>ou,stringify:()=>Zm,visit:()=>je,visitAsync:()=>Ns});var au=A(()=>{"use strict";Ql();Xs();$l();eo();Os();q();Zt();oe();tr();rr();ha();ru();nu();su();ey();Ms()});var ty,ry=A(()=>{"use strict";au();au();ty=iu});function g1(r,e,t=0){let n=new Uint8Array(r.buffer,r.byteOffset,r.byteLength),s=" ";t==0&&(t=n.length),t=Math.min(t,n.length);let o=16;for(let i=0;i<t;i+=o){i+o<=t||n.length==t||(i=n.length-n.length%o,t=n.length,s=">>");let a=[i.toString(16).padStart(4,"0"),s];for(let c=0;c<o;c++)i+c<t?a.push(n[i+c].toString(16).padStart(2,"0")):a.push(" "),a.push(" ");for(let c=0;c<o;c++)if(i+c<t){let l=n[i+c];a.push(l>=32&&l<127?String.fromCharCode(l):".")}e(a.join(""))}}function w1(r,e=0){let t=[];return g1(r,n=>{t.push(n)},e),t.join(`
|
140
|
-
`)}function b1(r){throw new Error("Not implemented")}function G(r,e=new Set([Math.random()])){switch(typeof r){case"function":return new we(r);case"string":{try{let t=JSON.parse(r);if(typeof t=="object"&&t!==null)return G(t,e)}catch{if(r.match(/[\n\r]/)){let n=r.trimEnd().split(/[\n\r]/);return new we(()=>n)}}return new we(()=>r.toString())}case"number":return new we(()=>r);case"boolean":return new we(()=>r);case"object":{if(r===null)return new we(()=>"null");if(ArrayBuffer.isView(r))try{let o=new TextDecoder().decode(r),i=JSON.parse(o);return G(i,e)}catch{return G(w1(r,512))}if(Array.isArray(r))return new we(()=>r.map(s=>G(s).value()));if(r instanceof Headers)return new we(()=>Object.fromEntries(r.entries()));if(r instanceof ReadableStream)return new we(()=>">Stream<");if(r instanceof Promise)return new we(()=>">Promise<");if(e.has(r))return new we(()=>"...");if(e.add(r),typeof r.toJSON=="function")return new we(()=>r.toJSON());let t={},n=r;for(let s in n){let o=n[s];o instanceof we?t[s]=o:typeof o!="function"&&(t[s]=G(o,e))}return new we(()=>t)}default:if(!r)return new we(()=>"--Falsy--");throw new Error(`Invalid type:${typeof r}`)}}function uu(r){return typeof r=="object"&&["Module","EnableLevel","DisableLevel","SetDebug","Str","Error","Warn","Debug","Log","WithLevel","Err","Info","Timestamp","Any","Dur","Uint64"].map(e=>typeof r[e]=="function").reduce((e,t)=>e&&t,!0)}function We(r){try{let e=r();return e instanceof Promise?e.then(t=>C.Ok(t)).catch(t=>C.Err(t)):C.Ok(e)}catch(e){return C.Err(e)}}function sy(r,e){let n=(Array.isArray(r)?r:[r]).map(s=>{if(typeof s=="string"){let o=s.replace(/[-\\[\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\^\\$\\|]/g,"\\$&");return new RegExp(`^${o}$`)}return s});return ma(void 0,n,e)}function ma(r,e,t){if(typeof t!="object"||t===null)return t;if(Array.isArray(t))return t.map(o=>ma(r,e,o));let n=Jt({},t),s=(o,i)=>{for(let a of e)if(a.test(o)||a.test(i))return!0;return!1};for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o)){let i;if(r?i=[r,o].join("."):i=o,s(o,i)){delete n[o];continue}typeof n[o]=="object"&&(Array.isArray(n[o])?n[o]=n[o].reduce((a,c,l)=>(s(o,`${i}[${l}]`)||a.push(ma(`${i}[${l}]`,e,c)),a),[]):n[o]=ma(i,e,n[o]))}return n}function ly(r,e){if(typeof r=="object"){let t=Object.keys(r);if(t.length!==1)throw new Error(`Invalid key: ${JSON.stringify(r)}`);return{key:t[0],def:r[t[0]]}}return{key:r,def:e}}function co(r){return r??void 0}function k1(r,e){if(!r)return new ir(`${e}//`);if(typeof r=="string")try{return new ir(r)}catch{return new ir(`${e}//${r}`)}else return new ir(r.toString())}function fu(r){return r instanceof URL||!!r&&typeof r.searchParams=="object"&&typeof r.searchParams.sort=="function"&&typeof r.hash=="string"}function cu(r,e,t){switch(typeof co(e)){case"undefined":return r(new ir(`${t}///`));case"string":return r(k1(e,t));case"object":if(lu.is(e))return r(new ir(e._url.toString()));if(Ie.is(e))return r(new ir(e._url.toString()));if(fu(e))return r(new ir(e.toString()));throw new Error(`unknown object type: ${e}`);default:throw new Error(`Invalid argument: ${typeof e}`)}}function fy(r,e,t=n=>`missing parameter: ${n}`){return e===void 0?C.Err(t(r)):C.Ok(e)}function hy(r,e){let t=r.flat().reduce((i,a)=>(typeof a=="string"?i.push({key:a}):typeof a=="object"&&i.push(...Object.keys(a).map(c=>({key:c,def:typeof a[c]=="string"?a[c]:void 0}))),i),[]),n=r.find(i=>typeof i=="function")||((...i)=>`missing parameters: ${i.join(",")}`),s=[],o={};for(let i of t){let a=e.getParam(i.key);a===void 0?typeof i.def=="string"?o[i.key]=i.def:s.push(i.key):o[i.key]=a}return s.length?C.Err(n(...s)):C.Ok(o)}function ao(r,e=globalThis){let[t,...n]=r.split(".");return["object","function"].includes(typeof e)&&e&&["object","function"].includes(typeof e[t])&&e[t]?n.length<=1?!0:ao(n.join("."),e[t]):!1}function Or(){let r=globalThis,e=ao("navigator.product")&&typeof r.navigator=="object"&&r.navigator.product==="ReactNative",t=!1;ao("Deno")||(t=ao("process.versions.node")&&!e);let n=ao("Deno");return{isNodeIsh:t,isBrowser:!(t||n)&&!e,isDeno:n,isReactNative:e}}function E1(){return v1}function iy(r){return Array.isArray(r)?G(()=>r.length):typeof r=="string"?G(()=>r.length):typeof r=="object"&&r!==null?typeof r.size=="number"?G(()=>r.size):typeof r.length=="number"?G(()=>r.length):G(()=>Object.keys(r).length):G(()=>-1)}function T1(r){return"not implemented"}function ay(r){if(r&&typeof r.then=="function")throw new Error("async logValue Not implemented");return r}function A1(r){let e=new Uint8Array(r);return r>0&&crypto.getRandomValues(e),e}function I1(r){return Promise.resolve(crypto.subtle.digest("SHA-256",r))}function Hn(r={}){return{importKey:r.importKey||crypto.subtle.importKey.bind(crypto.subtle),exportKey:r.exportKey||crypto.subtle.exportKey.bind(crypto.subtle),encrypt:r.encrypt||crypto.subtle.encrypt.bind(crypto.subtle),decrypt:r.decrypt||crypto.subtle.decrypt.bind(crypto.subtle),randomBytes:r.randomBytes||A1,digestSHA256:r.digestSHA256||I1}}var we,C,x1,ny,ir,lu,$t,Ie,oy,S1,v1,ga,dy,py,_1,NN,ae=A(()=>{"use strict";Tp();ul();Mp();Ps();ry();we=class{constructor(r){this.fn=r}value(){try{return this.fn()}catch(r){return`LogValue:${r.message}`}}toJSON(){return this.value()}};C=class cy{static Ok(e){return new x1(e)}static Err(e){return typeof e=="string"?new ny(new Error(e)):new ny(e)}static Is(e){if(!e)return!1;if(e instanceof cy)return!0;let t=e;return!![typeof t.is_ok,typeof t.is_err,typeof t.unwrap,typeof t.unwrap_err].every(n=>n==="function")}isOk(){return this.is_ok()}isErr(){return this.is_err()}Ok(){return this.unwrap()}Err(){return this.unwrap_err()}},x1=class extends C{constructor(r){super(),this._t=r}is_ok(){return!0}is_err(){return!1}unwrap_err(){throw new Error("Result is Ok")}unwrap(){return this._t}},ny=class extends C{constructor(r){super(),this._error=r}is_ok(){return!1}is_err(){return!0}unwrap(){throw new Error(`Result is Err: ${this._error}`)}unwrap_err(){return this._error}};ir=class uy extends URL{constructor(e){super("defect://does.not.exist");let t=e.split(":");this._hasHostpart=$t.has(t[0]);let n=["http",...t.slice(1)].join(":");if(!this._hasHostpart){let s=n.replace(/http:\/\/[/]*/,"").replace(/[#?].*$/,"");n=n.replace(/http:\/\//,`http://localhost/${s}`)}try{this._sysURL=new URL(n)}catch(s){let o=s;throw o.message=`${o.message} for URL: ${e}`,o}this._protocol=`${t[0]}:`,this._hasHostpart?this._pathname=this._sysURL.pathname:this._pathname=e.replace(new RegExp(`^${this._protocol}//`),"").replace(/[#?].*$/,""),this.hash=this._sysURL.hash}clone(){return new uy(this.toString())}get host(){if(!this._hasHostpart)throw new Error(`you can use hostname only if protocol is ${this.toString()} ${JSON.stringify(Array.from($t.keys()))}`);return this._sysURL.host}get port(){if(!this._hasHostpart)throw new Error(`you can use hostname only if protocol is ${JSON.stringify(Array.from($t.keys()))}`);return this._sysURL.port}set port(e){if(!this._hasHostpart)throw new Error(`you can use port only if protocol is ${JSON.stringify(Array.from($t.keys()))}`);this._sysURL.port=e}get hostname(){if(!this._hasHostpart)throw new Error(`you can use hostname only if protocol is ${JSON.stringify(Array.from($t.keys()))}`);return this._sysURL.hostname}set hostname(e){if(!this._hasHostpart)throw new Error(`you can use hostname only if protocol is ${JSON.stringify(Array.from($t.keys()))}`);this._sysURL.hostname=e}set pathname(e){this._pathname=e}get pathname(){return this._pathname}get protocol(){return this._protocol}set protocol(e){e.endsWith(":")||(e=`${e}:`),this._protocol=e}get searchParams(){return this._sysURL.searchParams}toString(){let e="";if(this._sysURL.searchParams.size)for(let[n,s]of Array.from(this._sysURL.searchParams.entries()).sort((o,i)=>o[0].localeCompare(i[0])))e+=`${e.length?"&":"?"}${n}=${encodeURIComponent(s)}`;let t="";return this._hasHostpart&&(t=this._sysURL.hostname,this._sysURL.port&&(t+=`:${this._sysURL.port}`),this._pathname.startsWith("/")||(t+="/")),`${this._protocol}//${t}${this._pathname}${e}`}};lu=class ya{constructor(e){this._url=e}static is(e){return e instanceof ya||!!e&&typeof e.delParam=="function"&&typeof e.setParam=="function"}static from(e,t="file:"){return cu(n=>new ya(n),e,t)}port(e){return this._url.port=e,this}hostname(e){return this._url.hostname=e,this}protocol(e){return e.endsWith(":")||(e=`${e}:`),this._url.protocol=e,this}pathname(e){return this._url.pathname=e,this}appendRelative(e){let t=Ie.from(e),n=t.pathname,s=this._url.pathname;n.startsWith("/")&&(n=n.replace(/^\//,"")),s.length>0&&(s=s.replace(/\/$/,"")),this.pathname(s+"/"+n);for(let[o,i]of t.getParams)this.setParam(o,i);return this}cleanParams(){for(let e of Array.from(this._url.searchParams.keys()))this._url.searchParams.delete(e);return this}delParam(e){return this._url.searchParams.delete(e),this}defParam(e,t){return this._url.searchParams.has(e)||this._url.searchParams.set(e,t),this}setParam(e,t){return this._url.searchParams.set(e,t),this}hasParam(e){return this._url.searchParams.has(e)}get getParams(){return this._url.searchParams.entries()}getParam(e,t){let{key:n,def:s}=ly(e,t),o=this._url.searchParams.get(n);return!co(o)&&s&&(o=s),co(o)}getParamResult(e,t){return fy(e,this.getParam(e),t)}getParamsResult(...e){return hy(e,this)}toString(){return this._url.searchParams.sort(),this._url.toString()}toJSON(){return this.toString()}asURL(){return this.URI().asURL()}asObj(...e){return this.URI().asObj(...e)}clone(){return ya.from(this.toString())}URI(){return Ie.from(this._url)}},$t=new Set(["http","https","ws","wss"]),Ie=class zn{static protocolHasHostpart(e){return e=e.replace(/:$/,""),$t.add(e),()=>{$t.delete(e)}}static merge(e,t,n="file:"){let s=lu.from(e,n),o=zn.from(t,n);s.protocol(o.protocol);let i=o.pathname;i.length===0||i==="/"||i==="./"||s.pathname(o.pathname);for(let[a,c]of o.getParams)s.setParam(a,c);return s.URI()}static is(e){return e instanceof zn||!!e&&typeof e.asURL=="function"&&typeof e.getParam=="function"&&typeof e.hasParam=="function"}static from(e,t="file:"){return cu(n=>new zn(n),e,t)}static fromResult(e,t="file:"){return We(()=>cu(n=>new zn(n),e,t))}constructor(e){this._url=e.clone()}build(){return lu.from(this._url)}get hostname(){return this._url.hostname}get port(){return this._url.port}get host(){return this._url.host}get protocol(){return this._url.protocol}get pathname(){return this._url.pathname}get getParams(){return this._url.searchParams.entries()}hasParam(e){return this._url.searchParams.has(e)}getParam(e,t){let{key:n,def:s}=ly(e,t),o=this._url.searchParams.get(n);return!co(o)&&s&&(o=s),co(o)}getParamResult(e,t){return fy(e,this.getParam(e),t)}getParamsResult(...e){return hy(e,this)}clone(){return new zn(this._url)}asURL(){return this._url.clone()}toString(){return this._url.toString()}toJSON(){return this.toString()}asObj(...e){let t={style:"path",protocol:this.protocol,pathname:this.pathname,searchParams:Object.fromEntries(this.getParams)};return $t.has(this.protocol.replace(/:$/,""))?sy(e,dp(Jt({},t),{style:"host",hostname:this.hostname,port:this.port})):sy(e,t)}};oy=class{constructor(r){this._toFlush=[],this._flushIsRunning=!1,this._flushDoneFns=[],this._out=r}write(r){let e=async()=>{try{let t=this._out.getWriter();await t.ready,await t.write(r),await t.releaseLock()}catch(t){console.error("Chunk error:",t)}};this._toFlush.push(e),this._flush()}_flush(r=void 0,e){if(e&&this._flushDoneFns.push(e),this._toFlush.length==0){this._flushIsRunning=!1,this._flushDoneFns.forEach(n=>n()),this._flushDoneFns=[];return}if(!r&&this._toFlush.length==1&&!this._flushIsRunning)this._flushIsRunning=!0;else if(!r)return;let t=this._toFlush.shift();t?.().finally(()=>{this._flush(this._toFlush)})}},S1=class{constructor(){this._globalLevels=new Set(["info","error","warn"]),this._modules=new Map,this.isStackExposed=!1}enableLevel(r,...e){if(e.length==0){this._globalLevels.add(r);return}this.forModules(r,t=>{this._modules.set(t,new Set([...this._globalLevels,r]))},...e)}disableLevel(r,...e){if(e.length==0){this._globalLevels.delete(r);return}this.forModules(r,t=>{this._modules.delete(t)},...e)}setExposeStack(r){this.isStackExposed=!!r}forModules(r,e,...t){for(let n of t.flat()){if(typeof n!="string")continue;let s=n.split(",").map(o=>o.trim()).filter(o=>o.length);for(let o of s)e(o)}}setDebug(...r){this.forModules("debug",e=>{this._modules.set(e,new Set([...this._globalLevels,"debug"]))},...r)}isEnabled(r,e){let t=r;if(typeof e=="string"){let s=this._modules.get(e);if(s&&s.has(t))return!0}let n=this._modules.get("*");return n&&typeof t=="string"&&n.has(t)||typeof t!="string"?!0:this._globalLevels.has(t)}},v1=new S1;ga=class{constructor(r,e){this._txtEnDe=r,this._space=e}format(r){let e;try{e=JSON.stringify(r,null,this._space)}catch(t){e=JSON.stringify({internal:{message:t.message,stack:t.stack}})}return this._txtEnDe.encode(e+`
|
141
|
-
`)}},dy=class{constructor(r,e){this._txtEnDe=r,this._space=e}format(r){return this._txtEnDe.encode(`---
|
142
|
-
`+ty.stringify(r,null,this._space)+`
|
143
|
-
`)}},py=class my{constructor(e){if(this._attributes={},e||(e={}),e.sys?this._sys=e.sys:this._sys=Ep(),e.txtEnDe?this._txtEnDe=e.txtEnDe:this._txtEnDe=gn(),e.formatter?this._formatter=e.formatter:this._formatter=new ga(this._txtEnDe),e.logWriter)this._logWriter=e.logWriter;else if(e.out)this._logWriter=new oy(e.out);else{let t=Or(),n;if(t.isBrowser)n=new hl;else if(t.isNodeIsh||t.isReactNative||t.isDeno)n=this._sys.Stdout();else throw new Error("No output defined for runtime");this._logWriter=new oy(n)}e.withAttributes?this._withAttributes=Jt({},e.withAttributes):this._withAttributes={},this._attributes=Jt({},this._withAttributes),e.levelHandler?this._levelHandler=e.levelHandler:this._levelHandler=E1()}TxtEnDe(){return this._txtEnDe}Attributes(){return JSON.parse(JSON.stringify(this._attributes,null))}SetExposeStack(e){return this._levelHandler.setExposeStack(e),this}EnableLevel(e,...t){return this._levelHandler.enableLevel(e,...t),this}DisableLevel(e,...t){return this._levelHandler.disableLevel(e,...t),this}Module(e){return this._attributes.module=G(e),this._withAttributes.module=G(e),this}SetDebug(...e){return this._levelHandler.setDebug(...e),this}SetFormatter(e){return this._formatter=e,this}Timestamp(){return this._attributes.ts=G(()=>this._sys.Time().Now().toISOString()),this}Warn(){return this._attributes.level=G("warn"),this}Log(){return this}Debug(){return this._attributes.level=G("debug"),this}Error(){return this._attributes.level=G("error"),this}Info(){return this._attributes.level=G("info"),this}Err(e){var t;return C.Is(e)?e.isOk()?this.Result("noerror",e):this.Result("error",e):e instanceof Error?(this._attributes.error=G(e.message),this._levelHandler.isStackExposed&&(this._attributes.stack=G((t=e.stack)==null?void 0:t.split(`
|
144
|
-
`).map(n=>n.trim())))):this._attributes.error=G(""+e),this}WithLevel(e){return this._attributes.level=G(e),this}Ref(e,t){return typeof t=="function"?this._attributes[e]=G(t):typeof t.toString=="function"?this._attributes[e]=G(()=>t.toString()):this._attributes[e]=G("INVALID REF"),this}Bool(e,t){return this.coerceKey(e,!!t),this}Http(...e){let t=e.find(a=>typeof a=="string");e=e.filter(a=>typeof a!="string");let n=e.filter(a=>C.Is(a)&&a.isErr());if(n.length)return this.Err(n.map(a=>a.Err().message).join(`
|
145
|
-
`)),this;let s=e.map(a=>C.Is(a)?a.Ok():a).find(a=>typeof a.status!="number"),o=e.map(a=>C.Is(a)?a.Ok():a).find(a=>typeof a.status=="number"),i;return o&&s?i={res:o,req:s}:!o&&!s?i=void 0:o?i=o:s&&(i=s),i&&this.Any(t||"Http",i),this}Pair(e){for(let t of Object.keys(e)){let n=e[t];if(n instanceof we){this._attributes[t]=n;continue}if(C.Is(n)){this.Result(t,n);continue}this.Any(t,n)}return this}Result(e,t){return t.isOk()?this._attributes[e]=G(t.Ok()):this.Err(t.Err()),this}Len(e,t="len"){return this._attributes[t]=iy(e),this}Hash(e,t="hash"){return this._attributes[t]=b1(async()=>`${iy(e).value()}:${await T1(e)}`),this}Url(e,t="url"){return this.Ref(t,()=>Ie.from(e).toString()),this}coerceKey(e,t){typeof e=="string"?this._attributes[e]=G(t):this.Pair(e)}Str(e,t){return this.coerceKey(e,t),this}Any(e,t){return this.coerceKey(e,t),this}Dur(e,t){return this._attributes[e]=G(`${t}ms`),this}Uint64(e,t){return this.coerceKey(e,t),this}Int(e,t){return this.Uint64(e,t)}async Flush(){return new Promise(e=>{this._logWriter._flush(void 0,e)})}With(){return new _1(new my({logWriter:this._logWriter,sys:this._sys,levelHandler:this._levelHandler,formatter:this._formatter,withAttributes:Jt({module:this._attributes.module},this._withAttributes)}))}_resetAttributes(e){let t=e();return Object.keys(this._attributes).forEach(n=>{delete this._attributes[n]}),Object.assign(this._attributes,this._withAttributes),t}Msg(...e){let t=this._resetAttributes(()=>{var s,o;let i=this._levelHandler.isEnabled((s=ay(this._attributes.level))==null?void 0:s.value(),(o=ay(this._attributes.module))==null?void 0:o.value());this._attributes.msg=G(e.join(" "));let a=this._attributes.msg.value();typeof a=="string"&&!a.trim().length&&delete this._attributes.msg;let c=()=>this._formatter.format(Jt({},this._attributes));if(i){let l=c();this._logWriter.write(l),c=()=>l}return c}),n=()=>new Error(this._txtEnDe.decode(t()));return{ResultError:()=>C.Err(n()),AsError:n}}},_1=class{constructor(r){this._li=r}TxtEnDe(){return this._li.TxtEnDe()}Logger(){return Object.assign(this._li._withAttributes,this._li._attributes),this._li}Attributes(){return Jt({},this._li._attributes)}SetExposeStack(r){return this._li._levelHandler.setExposeStack(r),this}SetFormatter(r){return this._li.SetFormatter(r),this}EnableLevel(r,...e){return this._li._levelHandler.enableLevel(r,...e),this}DisableLevel(r,...e){return this._li._levelHandler.enableLevel(r,...e),this}Module(r){return this._li.Module(r),this}SetDebug(...r){return this._li.SetDebug(...r),this}Http(...r){return this._li.Http(...r),this}Pair(r){return this._li.Pair(r),this}Str(r,e){return this._li.Str(r,e),this}Len(r,e){return this._li.Len(r,e),this}Hash(r,e){return this._li.Hash(r,e),this}Ref(r,e){return this._li.Ref(r,e),this}Bool(r,e){return this._li.Bool(r,e),this}Result(r,e){return this._li.Result(r,e),this}Url(r,e){return this._li.Url(r,e),this}Int(r,e){return this._li.Int(r,e),this}Log(){return this._li.Log(),this}WithLevel(r){return this._li.WithLevel(r),this}Error(){return this._li.Error(),this}Warn(){return this._li.Error(),this}Debug(){return this._li.Debug(),this}Err(r){return this._li.Err(r),this}Info(){return this._li.Info(),this}Timestamp(){return this._li.Timestamp(),this}Any(r,e){return this._li.Any(r,e),this}Dur(r,e){return this._li.Dur(r,e),this}Uint64(r,e){return this._li.Uint64(r,e),this}};NN=Object.keys({__packageVersion__:"xxxx"})[0]});var Kt={};K(Kt,{coerce:()=>qe,empty:()=>gy,equals:()=>hu,fromHex:()=>L1,fromString:()=>du,isBinary:()=>B1,toHex:()=>C1,toString:()=>pu});function C1(r){return r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function L1(r){let e=r.match(/../g);return e!=null?new Uint8Array(e.map(t=>parseInt(t,16))):gy}function hu(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function qe(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function B1(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function du(r){return new TextEncoder().encode(r)}function pu(r){return new TextDecoder().decode(r)}var gy,ar=A(()=>{"use strict";gy=new Uint8Array(0)});function P1(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var d=0,y=0,g=0,b=m.length;g!==b&&m[g]===0;)g++,d++;for(var x=(b-g)*u+1>>>0,k=new Uint8Array(x);g!==b;){for(var S=m[g],T=0,E=x-1;(S!==0||T<y)&&E!==-1;E--,T++)S+=256*k[E]>>>0,k[E]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,g++}for(var _=x-y;_!==x&&k[_]===0;)_++;for(var W=c.repeat(d);_<x;++_)W+=r.charAt(k[_]);return W}function p(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var d=0;if(m[d]!==" "){for(var y=0,g=0;m[d]===c;)y++,d++;for(var b=(m.length-d)*l+1>>>0,x=new Uint8Array(b);m[d];){var k=t[m.charCodeAt(d)];if(k===255)return;for(var S=0,T=b-1;(k!==0||S<g)&&T!==-1;T--,S++)k+=a*x[T]>>>0,x[T]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");g=S,d++}if(m[d]!==" "){for(var E=b-g;E!==b&&x[E]===0;)E++;for(var _=new Uint8Array(y+(b-E)),W=y;E!==b;)_[W++]=x[E++];return _}}}function h(m){var d=p(m);if(d)return d;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:p,decode:h}}var D1,N1,wy,by=A(()=>{"use strict";D1=P1,N1=D1,wy=N1});function xy(r,e){return new gu({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function jn({name:r,prefix:e,encode:t,decode:n}){return new wu(r,e,t,n)}function cr({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=wy(t,r);return jn({prefix:e,name:r,encode:n,decode:o=>qe(s(o))})}function M1(r,e,t,n){let s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),a=0,c=0,l=0;for(let u=0;u<o;++u){let f=s[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|f,a+=t,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function O1(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;o.length*t&7;)o+="=";return o}function te({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return jn({prefix:e,name:r,encode(s){return O1(s,n,t)},decode(s){return M1(s,n,t,r)}})}var mu,yu,gu,wu,it=A(()=>{"use strict";ar();by();mu=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},yu=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return xy(this,e)}},gu=class{decoders;constructor(e){this.decoders=e}or(e){return xy(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};wu=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new mu(e,t,n),this.decoder=new yu(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var ku={};K(ku,{base58btc:()=>J,base58flickr:()=>W1});var J,W1,Rr=A(()=>{"use strict";it();J=cr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),W1=cr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var cw=$((c8,aw)=>{"use strict";aw.exports=BE;function BE(r,e){for(var t=new Array(arguments.length-1),n=0,s=2,o=!0;s<arguments.length;)t[n++]=arguments[s++];return new Promise(function(a,c){t[n]=function(u){if(o)if(o=!1,u)c(u);else{for(var f=new Array(arguments.length-1),p=0;p<f.length;)f[p++]=arguments[p];a.apply(null,f)}};try{r.apply(e||null,t)}catch(l){o&&(o=!1,c(l))}})}});var hw=$(fw=>{"use strict";var za=fw;za.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&e.charAt(t)==="=";)++n;return Math.ceil(e.length*3)/4-n};var ss=new Array(64),uw=new Array(123);for(lt=0;lt<64;)uw[ss[lt]=lt<26?lt+65:lt<52?lt+71:lt<62?lt-4:lt-59|43]=lt++;var lt;za.encode=function(e,t,n){for(var s=null,o=[],i=0,a=0,c;t<n;){var l=e[t++];switch(a){case 0:o[i++]=ss[l>>2],c=(l&3)<<4,a=1;break;case 1:o[i++]=ss[c|l>>4],c=(l&15)<<2,a=2;break;case 2:o[i++]=ss[c|l>>6],o[i++]=ss[l&63],a=0;break}i>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),i=0)}return a&&(o[i++]=ss[c],o[i++]=61,a===1&&(o[i++]=61)),s?(i&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))};var lw="invalid encoding";za.decode=function(e,t,n){for(var s=n,o=0,i,a=0;a<e.length;){var c=e.charCodeAt(a++);if(c===61&&o>1)break;if((c=uw[c])===void 0)throw Error(lw);switch(o){case 0:i=c,o=1;break;case 1:t[n++]=i<<2|(c&48)>>4,i=c,o=2;break;case 2:t[n++]=(i&15)<<4|(c&60)>>2,i=c,o=3;break;case 3:t[n++]=(i&3)<<6|c,o=0;break}}if(o===1)throw Error(lw);return n-s};za.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var pw=$((u8,dw)=>{"use strict";dw.exports=Ha;function Ha(){this._listeners={}}Ha.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this};Ha.prototype.off=function(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],s=0;s<n.length;)n[s].fn===t?n.splice(s,1):++s;return this};Ha.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var n=[],s=1;s<arguments.length;)n.push(arguments[s++]);for(s=0;s<t.length;)t[s].fn.apply(t[s++].ctx,n)}return this}});var kw=$((f8,xw)=>{"use strict";xw.exports=mw(mw);function mw(r){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),t=new Uint8Array(e.buffer),n=t[3]===128;function s(c,l,u){e[0]=c,l[u]=t[0],l[u+1]=t[1],l[u+2]=t[2],l[u+3]=t[3]}function o(c,l,u){e[0]=c,l[u]=t[3],l[u+1]=t[2],l[u+2]=t[1],l[u+3]=t[0]}r.writeFloatLE=n?s:o,r.writeFloatBE=n?o:s;function i(c,l){return t[0]=c[l],t[1]=c[l+1],t[2]=c[l+2],t[3]=c[l+3],e[0]}function a(c,l){return t[3]=c[l],t[2]=c[l+1],t[1]=c[l+2],t[0]=c[l+3],e[0]}r.readFloatLE=n?i:a,r.readFloatBE=n?a:i}():function(){function e(n,s,o,i){var a=s<0?1:0;if(a&&(s=-s),s===0)n(1/s>0?0:2147483648,o,i);else if(isNaN(s))n(2143289344,o,i);else if(s>34028234663852886e22)n((a<<31|2139095040)>>>0,o,i);else if(s<11754943508222875e-54)n((a<<31|Math.round(s/1401298464324817e-60))>>>0,o,i);else{var c=Math.floor(Math.log(s)/Math.LN2),l=Math.round(s*Math.pow(2,-c)*8388608)&8388607;n((a<<31|c+127<<23|l)>>>0,o,i)}}r.writeFloatLE=e.bind(null,yw),r.writeFloatBE=e.bind(null,gw);function t(n,s,o){var i=n(s,o),a=(i>>31)*2+1,c=i>>>23&255,l=i&8388607;return c===255?l?NaN:a*(1/0):c===0?a*1401298464324817e-60*l:a*Math.pow(2,c-150)*(l+8388608)}r.readFloatLE=t.bind(null,ww),r.readFloatBE=t.bind(null,bw)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),t=new Uint8Array(e.buffer),n=t[7]===128;function s(c,l,u){e[0]=c,l[u]=t[0],l[u+1]=t[1],l[u+2]=t[2],l[u+3]=t[3],l[u+4]=t[4],l[u+5]=t[5],l[u+6]=t[6],l[u+7]=t[7]}function o(c,l,u){e[0]=c,l[u]=t[7],l[u+1]=t[6],l[u+2]=t[5],l[u+3]=t[4],l[u+4]=t[3],l[u+5]=t[2],l[u+6]=t[1],l[u+7]=t[0]}r.writeDoubleLE=n?s:o,r.writeDoubleBE=n?o:s;function i(c,l){return t[0]=c[l],t[1]=c[l+1],t[2]=c[l+2],t[3]=c[l+3],t[4]=c[l+4],t[5]=c[l+5],t[6]=c[l+6],t[7]=c[l+7],e[0]}function a(c,l){return t[7]=c[l],t[6]=c[l+1],t[5]=c[l+2],t[4]=c[l+3],t[3]=c[l+4],t[2]=c[l+5],t[1]=c[l+6],t[0]=c[l+7],e[0]}r.readDoubleLE=n?i:a,r.readDoubleBE=n?a:i}():function(){function e(n,s,o,i,a,c){var l=i<0?1:0;if(l&&(i=-i),i===0)n(0,a,c+s),n(1/i>0?0:2147483648,a,c+o);else if(isNaN(i))n(0,a,c+s),n(2146959360,a,c+o);else if(i>17976931348623157e292)n(0,a,c+s),n((l<<31|2146435072)>>>0,a,c+o);else{var u;if(i<22250738585072014e-324)u=i/5e-324,n(u>>>0,a,c+s),n((l<<31|u/4294967296)>>>0,a,c+o);else{var f=Math.floor(Math.log(i)/Math.LN2);f===1024&&(f=1023),u=i*Math.pow(2,-f),n(u*4503599627370496>>>0,a,c+s),n((l<<31|f+1023<<20|u*1048576&1048575)>>>0,a,c+o)}}}r.writeDoubleLE=e.bind(null,yw,0,4),r.writeDoubleBE=e.bind(null,gw,4,0);function t(n,s,o,i,a){var c=n(i,a+s),l=n(i,a+o),u=(l>>31)*2+1,f=l>>>20&2047,p=4294967296*(l&1048575)+c;return f===2047?p?NaN:u*(1/0):f===0?u*5e-324*p:u*Math.pow(2,f-1075)*(p+4503599627370496)}r.readDoubleLE=t.bind(null,ww,0,4),r.readDoubleBE=t.bind(null,bw,4,0)}(),r}function yw(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function gw(r,e,t){e[t]=r>>>24,e[t+1]=r>>>16&255,e[t+2]=r>>>8&255,e[t+3]=r&255}function ww(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0}function bw(r,e){return(r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}});var Sw=$((exports,module)=>{"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(r){}return null}});var Ew=$(vw=>{"use strict";var sf=vw;sf.length=function(e){for(var t=0,n=0,s=0;s<e.length;++s)n=e.charCodeAt(s),n<128?t+=1:n<2048?t+=2:(n&64512)===55296&&(e.charCodeAt(s+1)&64512)===56320?(++s,t+=4):t+=3;return t};sf.read=function(e,t,n){var s=n-t;if(s<1)return"";for(var o=null,i=[],a=0,c;t<n;)c=e[t++],c<128?i[a++]=c:c>191&&c<224?i[a++]=(c&31)<<6|e[t++]&63:c>239&&c<365?(c=((c&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,i[a++]=55296+(c>>10),i[a++]=56320+(c&1023)):i[a++]=(c&15)<<12|(e[t++]&63)<<6|e[t++]&63,a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,i)),a=0);return o?(a&&o.push(String.fromCharCode.apply(String,i.slice(0,a))),o.join("")):String.fromCharCode.apply(String,i.slice(0,a))};sf.write=function(e,t,n){for(var s=n,o,i,a=0;a<e.length;++a)o=e.charCodeAt(a),o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=o&63|128):(o&64512)===55296&&((i=e.charCodeAt(a+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++a,t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=o&63|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=o&63|128);return n-s}});var _w=$((d8,Tw)=>{"use strict";Tw.exports=PE;function PE(r,e,t){var n=t||8192,s=n>>>1,o=null,i=n;return function(c){if(c<1||c>s)return r(c);i+c>n&&(o=r(n),i=0);var l=e.call(o,i,i+=c);return i&7&&(i=(i|7)+1),l}}});var Iw=$((p8,Aw)=>{"use strict";Aw.exports=fe;var _o=wr();function fe(r,e){this.lo=r>>>0,this.hi=e>>>0}var Vr=fe.zero=new fe(0,0);Vr.toNumber=function(){return 0};Vr.zzEncode=Vr.zzDecode=function(){return this};Vr.length=function(){return 1};var DE=fe.zeroHash="\0\0\0\0\0\0\0\0";fe.fromNumber=function(e){if(e===0)return Vr;var t=e<0;t&&(e=-e);var n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new fe(n,s)};fe.from=function(e){if(typeof e=="number")return fe.fromNumber(e);if(_o.isString(e))if(_o.Long)e=_o.Long.fromString(e);else return fe.fromNumber(parseInt(e,10));return e.low||e.high?new fe(e.low>>>0,e.high>>>0):Vr};fe.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296};fe.prototype.toLong=function(e){return _o.Long?new _o.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var gr=String.prototype.charCodeAt;fe.fromHash=function(e){return e===DE?Vr:new fe((gr.call(e,0)|gr.call(e,1)<<8|gr.call(e,2)<<16|gr.call(e,3)<<24)>>>0,(gr.call(e,4)|gr.call(e,5)<<8|gr.call(e,6)<<16|gr.call(e,7)<<24)>>>0)};fe.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};fe.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};fe.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};fe.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}});var wr=$(of=>{"use strict";var P=of;P.asPromise=cw();P.base64=hw();P.EventEmitter=pw();P.float=kw();P.inquire=Sw();P.utf8=Ew();P.pool=_w();P.LongBits=Iw();P.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);P.global=P.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||of;P.emptyArray=Object.freeze?Object.freeze([]):[];P.emptyObject=Object.freeze?Object.freeze({}):{};P.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};P.isString=function(e){return typeof e=="string"||e instanceof String};P.isObject=function(e){return e&&typeof e=="object"};P.isset=P.isSet=function(e,t){var n=e[t];return n!=null&&e.hasOwnProperty(t)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};P.Buffer=function(){try{var r=P.inquire("buffer").Buffer;return r.prototype.utf8Write?r:null}catch{return null}}();P._Buffer_from=null;P._Buffer_allocUnsafe=null;P.newBuffer=function(e){return typeof e=="number"?P.Buffer?P._Buffer_allocUnsafe(e):new P.Array(e):P.Buffer?P._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};P.Array=typeof Uint8Array<"u"?Uint8Array:Array;P.Long=P.global.dcodeIO&&P.global.dcodeIO.Long||P.global.Long||P.inquire("long");P.key2Re=/^true|false|0|1$/;P.key32Re=/^-?(?:0|[1-9][0-9]*)$/;P.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;P.longToHash=function(e){return e?P.LongBits.from(e).toHash():P.LongBits.zeroHash};P.longFromHash=function(e,t){var n=P.LongBits.fromHash(e);return P.Long?P.Long.fromBits(n.lo,n.hi,t):n.toNumber(!!t)};function Cw(r,e,t){for(var n=Object.keys(e),s=0;s<n.length;++s)(r[n[s]]===void 0||!t)&&(r[n[s]]=e[n[s]]);return r}P.merge=Cw;P.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function Lw(r){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:new Error().stack||""}),n&&Cw(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return r},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}P.newError=Lw;P.ProtocolError=Lw("ProtocolError");P.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var s=Object.keys(this),o=s.length-1;o>-1;--o)if(t[s[o]]===1&&this[s[o]]!==void 0&&this[s[o]]!==null)return s[o]}};P.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}};P.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};P._configure=function(){var r=P.Buffer;if(!r){P._Buffer_from=P._Buffer_allocUnsafe=null;return}P._Buffer_from=r.from!==Uint8Array.from&&r.from||function(t,n){return new r(t,n)},P._Buffer_allocUnsafe=r.allocUnsafe||function(t){return new r(t)}}});var df=$((y8,Nw)=>{"use strict";Nw.exports=z;var Xe=wr(),af,ja=Xe.LongBits,Bw=Xe.base64,Pw=Xe.utf8;function Ao(r,e,t){this.fn=r,this.len=e,this.next=void 0,this.val=t}function lf(){}function NE(r){this.head=r.head,this.tail=r.tail,this.len=r.len,this.next=r.states}function z(){this.len=0,this.head=new Ao(lf,0,0),this.tail=this.head,this.states=null}var Dw=function(){return Xe.Buffer?function(){return(z.create=function(){return new af})()}:function(){return new z}};z.create=Dw();z.alloc=function(e){return new Xe.Array(e)};Xe.Array!==Array&&(z.alloc=Xe.pool(z.alloc,Xe.Array.prototype.subarray));z.prototype._push=function(e,t,n){return this.tail=this.tail.next=new Ao(e,t,n),this.len+=t,this};function uf(r,e,t){e[t]=r&255}function ME(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function ff(r,e){this.len=r,this.next=void 0,this.val=e}ff.prototype=Object.create(Ao.prototype);ff.prototype.fn=ME;z.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new ff((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};z.prototype.int32=function(e){return e<0?this._push(hf,10,ja.fromNumber(e)):this.uint32(e)};z.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function hf(r,e,t){for(;r.hi;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}z.prototype.uint64=function(e){var t=ja.from(e);return this._push(hf,t.length(),t)};z.prototype.int64=z.prototype.uint64;z.prototype.sint64=function(e){var t=ja.from(e).zzEncode();return this._push(hf,t.length(),t)};z.prototype.bool=function(e){return this._push(uf,1,e?1:0)};function cf(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}z.prototype.fixed32=function(e){return this._push(cf,4,e>>>0)};z.prototype.sfixed32=z.prototype.fixed32;z.prototype.fixed64=function(e){var t=ja.from(e);return this._push(cf,4,t.lo)._push(cf,4,t.hi)};z.prototype.sfixed64=z.prototype.fixed64;z.prototype.float=function(e){return this._push(Xe.float.writeFloatLE,4,e)};z.prototype.double=function(e){return this._push(Xe.float.writeDoubleLE,8,e)};var OE=Xe.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var s=0;s<e.length;++s)t[n+s]=e[s]};z.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(uf,1,0);if(Xe.isString(e)){var n=z.alloc(t=Bw.length(e));Bw.decode(e,n,0),e=n}return this.uint32(t)._push(OE,t,e)};z.prototype.string=function(e){var t=Pw.length(e);return t?this.uint32(t)._push(Pw.write,t,e):this._push(uf,1,0)};z.prototype.fork=function(){return this.states=new NE(this),this.head=this.tail=new Ao(lf,0,0),this.len=0,this};z.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Ao(lf,0,0),this.len=0),this};z.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this};z.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t};z._configure=function(r){af=r,z.create=Dw(),af._configure()}});var Rw=$((g8,Ow)=>{"use strict";Ow.exports=Lt;var Mw=df();(Lt.prototype=Object.create(Mw.prototype)).constructor=Lt;var br=wr();function Lt(){Mw.call(this)}Lt._configure=function(){Lt.alloc=br._Buffer_allocUnsafe,Lt.writeBytesBuffer=br.Buffer&&br.Buffer.prototype instanceof Uint8Array&&br.Buffer.prototype.set.name==="set"?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var s=0;s<e.length;)t[n++]=e[s++]}};Lt.prototype.bytes=function(e){br.isString(e)&&(e=br._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(Lt.writeBytesBuffer,t,e),this};function RE(r,e,t){r.length<40?br.utf8.write(r,e,t):e.utf8Write?e.utf8Write(r,t):e.write(r,t)}Lt.prototype.string=function(e){var t=br.Buffer.byteLength(e);return this.uint32(t),t&&this._push(RE,t,e),this};Lt._configure()});var yf=$((w8,zw)=>{"use strict";zw.exports=ne;var ut=wr(),mf,$w=ut.LongBits,FE=ut.utf8;function ft(r,e){return RangeError("index out of range: "+r.pos+" + "+(e||1)+" > "+r.len)}function ne(r){this.buf=r,this.pos=0,this.len=r.length}var Fw=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new ne(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new ne(e);throw Error("illegal buffer")},Kw=function(){return ut.Buffer?function(t){return(ne.create=function(s){return ut.Buffer.isBuffer(s)?new mf(s):Fw(s)})(t)}:Fw};ne.create=Kw();ne.prototype._slice=ut.Array.prototype.subarray||ut.Array.prototype.slice;ne.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ft(this,10);return e}}();ne.prototype.int32=function(){return this.uint32()|0};ne.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function pf(){var r=new $w(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return r;if(r.lo=(r.lo|(this.buf[this.pos]&127)<<28)>>>0,r.hi=(r.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return r;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw ft(this);if(r.lo=(r.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return r}return r.lo=(r.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,r}if(this.len-this.pos>4){for(;e<5;++e)if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}else for(;e<5;++e){if(this.pos>=this.len)throw ft(this);if(r.hi=(r.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return r}throw Error("invalid varint encoding")}ne.prototype.bool=function(){return this.uint32()!==0};function Va(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}ne.prototype.fixed32=function(){if(this.pos+4>this.len)throw ft(this,4);return Va(this.buf,this.pos+=4)};ne.prototype.sfixed32=function(){if(this.pos+4>this.len)throw ft(this,4);return Va(this.buf,this.pos+=4)|0};function Uw(){if(this.pos+8>this.len)throw ft(this,8);return new $w(Va(this.buf,this.pos+=4),Va(this.buf,this.pos+=4))}ne.prototype.float=function(){if(this.pos+4>this.len)throw ft(this,4);var e=ut.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};ne.prototype.double=function(){if(this.pos+8>this.len)throw ft(this,4);var e=ut.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};ne.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ft(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,n);if(t===n){var s=ut.Buffer;return s?s.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,n)};ne.prototype.string=function(){var e=this.bytes();return FE.read(e,0,e.length)};ne.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ft(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ft(this);while(this.buf[this.pos++]&128);return this};ne.prototype.skipType=function(r){switch(r){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(r=this.uint32()&7)!==4;)this.skipType(r);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+r+" at offset "+this.pos)}return this};ne._configure=function(r){mf=r,ne.create=Kw(),mf._configure();var e=ut.Long?"toLong":"toNumber";ut.merge(ne.prototype,{int64:function(){return pf.call(this)[e](!1)},uint64:function(){return pf.call(this)[e](!0)},sint64:function(){return pf.call(this).zzDecode()[e](!1)},fixed64:function(){return Uw.call(this)[e](!0)},sfixed64:function(){return Uw.call(this)[e](!1)}})}});var Ww=$((b8,Vw)=>{"use strict";Vw.exports=Wr;var jw=yf();(Wr.prototype=Object.create(jw.prototype)).constructor=Wr;var Hw=wr();function Wr(r){jw.call(this,r)}Wr._configure=function(){Hw.Buffer&&(Wr.prototype._slice=Hw.Buffer.prototype.slice)};Wr.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Wr._configure()});var Gw=$((x8,qw)=>{"use strict";qw.exports=Io;var gf=wr();(Io.prototype=Object.create(gf.EventEmitter.prototype)).constructor=Io;function Io(r,e,t){if(typeof r!="function")throw TypeError("rpcImpl must be a function");gf.EventEmitter.call(this),this.rpcImpl=r,this.requestDelimited=!!e,this.responseDelimited=!!t}Io.prototype.rpcCall=function r(e,t,n,s,o){if(!s)throw TypeError("request must be specified");var i=this;if(!o)return gf.asPromise(r,i,e,t,n,s);if(!i.rpcImpl){setTimeout(function(){o(Error("already ended"))},0);return}try{return i.rpcImpl(e,t[i.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(c,l){if(c)return i.emit("error",c,e),o(c);if(l===null){i.end(!0);return}if(!(l instanceof n))try{l=n[i.responseDelimited?"decodeDelimited":"decode"](l)}catch(u){return i.emit("error",u,e),o(u)}return i.emit("data",l,e),o(null,l)})}catch(a){i.emit("error",a,e),setTimeout(function(){o(a)},0);return}};Io.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var Qw=$(Jw=>{"use strict";var UE=Jw;UE.Service=Gw()});var Xw=$((S8,Yw)=>{"use strict";Yw.exports={}});var tb=$(eb=>{"use strict";var Ce=eb;Ce.build="minimal";Ce.Writer=df();Ce.BufferWriter=Rw();Ce.Reader=yf();Ce.BufferReader=Ww();Ce.util=wr();Ce.rpc=Qw();Ce.roots=Xw();Ce.configure=Zw;function Zw(){Ce.util._configure(),Ce.Writer._configure(Ce.BufferWriter),Ce.Reader._configure(Ce.BufferReader)}Zw()});var nb=$((E8,rb)=>{"use strict";rb.exports=tb()});var Zb=$((Uo,lc)=>{"use strict";(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var m=0;m<h.length;m++)if(!Number.isInteger(h[m])||h[m]<0||h[m]>255)return!1;return!0}function s(h,m){return(h&65535)*m+(((h>>>16)*m&65535)<<16)}function o(h,m){return h<<m|h>>>32-m}function i(h){return h^=h>>>16,h=s(h,2246822507),h^=h>>>13,h=s(h,3266489909),h^=h>>>16,h}function a(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var d=[0,0,0,0];return d[3]+=h[3]+m[3],d[2]+=d[3]>>>16,d[3]&=65535,d[2]+=h[2]+m[2],d[1]+=d[2]>>>16,d[2]&=65535,d[1]+=h[1]+m[1],d[0]+=d[1]>>>16,d[1]&=65535,d[0]+=h[0]+m[0],d[0]&=65535,[d[0]<<16|d[1],d[2]<<16|d[3]]}function c(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var d=[0,0,0,0];return d[3]+=h[3]*m[3],d[2]+=d[3]>>>16,d[3]&=65535,d[2]+=h[2]*m[3],d[1]+=d[2]>>>16,d[2]&=65535,d[2]+=h[3]*m[2],d[1]+=d[2]>>>16,d[2]&=65535,d[1]+=h[1]*m[3],d[0]+=d[1]>>>16,d[1]&=65535,d[1]+=h[2]*m[2],d[0]+=d[1]>>>16,d[1]&=65535,d[1]+=h[3]*m[1],d[0]+=d[1]>>>16,d[1]&=65535,d[0]+=h[0]*m[3]+h[1]*m[2]+h[2]*m[1]+h[3]*m[0],d[0]&=65535,[d[0]<<16|d[1],d[2]<<16|d[3]]}function l(h,m){return m%=64,m===32?[h[1],h[0]]:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m|h[0]>>>32-m]:(m-=32,[h[1]<<m|h[0]>>>32-m,h[0]<<m|h[1]>>>32-m])}function u(h,m){return m%=64,m===0?h:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m]:[h[1]<<m-32,0]}function f(h,m){return[h[0]^m[0],h[1]^m[1]]}function p(h){return h=f(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=f(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=f(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%4,y=h.length-d,g=m,b=0,x=3432918353,k=461845907,S=0;S<y;S=S+4)b=h[S]|h[S+1]<<8|h[S+2]<<16|h[S+3]<<24,b=s(b,x),b=o(b,15),b=s(b,k),g^=b,g=o(g,13),g=s(g,5)+3864292196;switch(b=0,d){case 3:b^=h[S+2]<<16;case 2:b^=h[S+1]<<8;case 1:b^=h[S],b=s(b,x),b=o(b,15),b=s(b,k),g^=b}return g^=h.length,g=i(g),g>>>0},t.x86.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%16,y=h.length-d,g=m,b=m,x=m,k=m,S=0,T=0,E=0,_=0,W=597399067,le=2869860233,Te=951274213,Y=2716044179,R=0;R<y;R=R+16)S=h[R]|h[R+1]<<8|h[R+2]<<16|h[R+3]<<24,T=h[R+4]|h[R+5]<<8|h[R+6]<<16|h[R+7]<<24,E=h[R+8]|h[R+9]<<8|h[R+10]<<16|h[R+11]<<24,_=h[R+12]|h[R+13]<<8|h[R+14]<<16|h[R+15]<<24,S=s(S,W),S=o(S,15),S=s(S,le),g^=S,g=o(g,19),g+=b,g=s(g,5)+1444728091,T=s(T,le),T=o(T,16),T=s(T,Te),b^=T,b=o(b,17),b+=x,b=s(b,5)+197830471,E=s(E,Te),E=o(E,17),E=s(E,Y),x^=E,x=o(x,15),x+=k,x=s(x,5)+2530024501,_=s(_,Y),_=o(_,18),_=s(_,W),k^=_,k=o(k,13),k+=g,k=s(k,5)+850148119;switch(S=0,T=0,E=0,_=0,d){case 15:_^=h[R+14]<<16;case 14:_^=h[R+13]<<8;case 13:_^=h[R+12],_=s(_,Y),_=o(_,18),_=s(_,W),k^=_;case 12:E^=h[R+11]<<24;case 11:E^=h[R+10]<<16;case 10:E^=h[R+9]<<8;case 9:E^=h[R+8],E=s(E,Te),E=o(E,17),E=s(E,Y),x^=E;case 8:T^=h[R+7]<<24;case 7:T^=h[R+6]<<16;case 6:T^=h[R+5]<<8;case 5:T^=h[R+4],T=s(T,le),T=o(T,16),T=s(T,Te),b^=T;case 4:S^=h[R+3]<<24;case 3:S^=h[R+2]<<16;case 2:S^=h[R+1]<<8;case 1:S^=h[R],S=s(S,W),S=o(S,15),S=s(S,le),g^=S}return g^=h.length,b^=h.length,x^=h.length,k^=h.length,g+=b,g+=x,g+=k,b+=g,x+=g,k+=g,g=i(g),b=i(b),x=i(x),k=i(k),g+=b,g+=x,g+=k,b+=g,x+=g,k+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(k>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%16,y=h.length-d,g=[0,m],b=[0,m],x=[0,0],k=[0,0],S=[2277735313,289559509],T=[1291169091,658871167],E=0;E<y;E=E+16)x=[h[E+4]|h[E+5]<<8|h[E+6]<<16|h[E+7]<<24,h[E]|h[E+1]<<8|h[E+2]<<16|h[E+3]<<24],k=[h[E+12]|h[E+13]<<8|h[E+14]<<16|h[E+15]<<24,h[E+8]|h[E+9]<<8|h[E+10]<<16|h[E+11]<<24],x=c(x,S),x=l(x,31),x=c(x,T),g=f(g,x),g=l(g,27),g=a(g,b),g=a(c(g,[0,5]),[0,1390208809]),k=c(k,T),k=l(k,33),k=c(k,S),b=f(b,k),b=l(b,31),b=a(b,g),b=a(c(b,[0,5]),[0,944331445]);switch(x=[0,0],k=[0,0],d){case 15:k=f(k,u([0,h[E+14]],48));case 14:k=f(k,u([0,h[E+13]],40));case 13:k=f(k,u([0,h[E+12]],32));case 12:k=f(k,u([0,h[E+11]],24));case 11:k=f(k,u([0,h[E+10]],16));case 10:k=f(k,u([0,h[E+9]],8));case 9:k=f(k,[0,h[E+8]]),k=c(k,T),k=l(k,33),k=c(k,S),b=f(b,k);case 8:x=f(x,u([0,h[E+7]],56));case 7:x=f(x,u([0,h[E+6]],48));case 6:x=f(x,u([0,h[E+5]],40));case 5:x=f(x,u([0,h[E+4]],32));case 4:x=f(x,u([0,h[E+3]],24));case 3:x=f(x,u([0,h[E+2]],16));case 2:x=f(x,u([0,h[E+1]],8));case 1:x=f(x,[0,h[E]]),x=c(x,S),x=l(x,31),x=c(x,T),g=f(g,x)}return g=f(g,[0,h.length]),b=f(b,[0,h.length]),g=a(g,b),b=a(b,g),g=p(g),b=p(b),g=a(g,b),b=a(b,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof Uo<"u"?(typeof lc<"u"&&lc.exports&&(Uo=lc.exports=t),Uo.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(Uo)});var Yf=$((Q8,e0)=>{"use strict";e0.exports=Zb()});var C0=$((lU,I0)=>{"use strict";function A0(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function A_(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return A0(r,t)}catch{t.message=r.message,t.stack=r.stack;let s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(r)),A0(new s,t)}}I0.exports=A_});var G0=$((i6,q0)=>{"use strict";q0.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let n=this._internalPositionFor(e,!1);if(t===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let s=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):s=!0,this._setInternalPos(n,e,t,s),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let t=this._internalPositionFor(e,!0);if(t!==-1)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let t=0;for(;t<this.length;)e(this.get(t),t,this),t++}map(e){let t=0,n=new Array(this.length);for(;t<this.length;)n[t]=e(this.get(t),t,this),t++;return n}reduce(e,t){let n=0,s=t;for(;n<this.length;){let o=this.get(n);s=e(s,o,n),n++}return s}find(e){let t=0,n,s;for(;t<this.length&&!n;)s=this.get(t),n=e(s),t++;return n?s:void 0}_internalPositionFor(e,t){let n=this._bytePosFor(e,t);if(n>=this._bitArrays.length)return-1;let s=this._bitArrays[n],o=e-n*7;if(!((s&1<<o)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(J_,0),c=~(4294967295<<o+1),l=W0(s&c);return a+l-1}_bytePosFor(e,t){let n=Math.floor(e/7),s=n+1;for(;!t&&this._bitArrays.length<s;)this._bitArrays.push(0);return n}_setBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]|=1<<e-t*7}_unsetBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]&=~(1<<e-t*7)}_setInternalPos(e,t,n,s){let o=this._data,i=[t,n];if(s)this._sortData(),o[e]=i;else{if(o.length)if(o[o.length-1][0]>=t)o.push(i);else if(o[0][0]<=t)o.unshift(i);else{let a=Math.round(o.length/2);this._data=o.slice(0,a).concat(i).concat(o.slice(a))}else this._data.push(i);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(Q_),this._changedData=!1}bitField(){let e=[],t=8,n=0,s=0,o,i=this._bitArrays.slice();for(;i.length||n;){n===0&&(o=i.shift(),n=7);let c=Math.min(n,t),l=~(255<<c),u=o&l;s|=u<<8-t,o=o>>>c,n-=c,t-=c,(!t||!n&&!i.length)&&(e.push(s),s=0,t=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(Y_)}};function J_(r,e){return r+W0(e)}function W0(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function Q_(r,e){return r[0]-e[0]}function Y_(r){return r[1]}});var lx=$((Y6,Dh)=>{"use strict";var bA=Object.prototype.hasOwnProperty,Ee="~";function qo(){}Object.create&&(qo.prototype=Object.create(null),new qo().__proto__||(Ee=!1));function xA(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function cx(r,e,t,n,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new xA(t,n||r,s),i=Ee?Ee+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],o]:r._events[i].push(o):(r._events[i]=o,r._eventsCount++),r}function Nc(r,e){--r._eventsCount===0?r._events=new qo:delete r._events[e]}function xe(){this._events=new qo,this._eventsCount=0}xe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)bA.call(t,n)&&e.push(Ee?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};xe.prototype.listeners=function(e){var t=Ee?Ee+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,o=n.length,i=new Array(o);s<o;s++)i[s]=n[s].fn;return i};xe.prototype.listenerCount=function(e){var t=Ee?Ee+e:e,n=this._events[t];return n?n.fn?1:n.length:0};xe.prototype.emit=function(e,t,n,s,o,i){var a=Ee?Ee+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,s),!0;case 5:return c.fn.call(c.context,t,n,s,o),!0;case 6:return c.fn.call(c.context,t,n,s,o,i),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var p=c.length,h;for(f=0;f<p;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,s);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};xe.prototype.on=function(e,t,n){return cx(this,e,t,n,!1)};xe.prototype.once=function(e,t,n){return cx(this,e,t,n,!0)};xe.prototype.removeListener=function(e,t,n,s){var o=Ee?Ee+e:e;if(!this._events[o])return this;if(!t)return Nc(this,o),this;var i=this._events[o];if(i.fn)i.fn===t&&(!s||i.once)&&(!n||i.context===n)&&Nc(this,o);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||s&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[o]=c.length===1?c[0]:c:Nc(this,o)}return this};xe.prototype.removeAllListeners=function(e){var t;return e?(t=Ee?Ee+e:e,this._events[t]&&Nc(this,t)):(this._events=new qo,this._eventsCount=0),this};xe.prototype.off=xe.prototype.removeListener;xe.prototype.addListener=xe.prototype.on;xe.prefixed=Ee;xe.EventEmitter=xe;typeof Dh<"u"&&(Dh.exports=xe)});function bx(){return NA.once(()=>new py)}function OA(){return new Map([...Array.from(Object.entries(globalThis[Symbol.for("FP_PRESET_ENV")]||{}))])}function Xo(r){let e=xn({symbol:r?.env?.symbol||"FP_ENV",presetEnv:r?.env?.presetEnv||OA()});return new jh({logger:r?.logger||bx(),env:e,crypto:r?.crypto||Hn(),ctx:r?.ctx||{},pathOps:RA,txt:r?.txt||FA})}function _r(r,e,t){return r.clone({logger:H(r,e,t)})}function H(r,e,t){let n;uu(r)?n=r:r&&uu(r.logger)?n=r.logger:n=bx();let s=n.With().Module(e),o=[],i=!1;if(t){"debug"in t&&(typeof t.debug=="string"&&t.debug.length>0?o.push(t.debug):o.push(e),delete t.debug),"exposeStack"in t&&(i=!0,delete t.exposeStack),"this"in t&&(s.Str("this",r.nextId(4).str),delete t.this);for(let[c,l]of Object.entries(t))switch(typeof l){case"string":s.Str(c,l);break;case"number":s.Uint64(c,l);break;default:l instanceof Date?s.Str(c,l.toISOString()):fu(l)?s.Str(c,l.toString()):typeof l=="function"?s.Ref(c,l):s.Any(c,l);break}}return MA.once(async()=>{r.env.onSet((c,l)=>{switch(c){case"FP_FORMAT":{switch(l){case"jsonice":n.SetFormatter(new ga(n.TxtEnDe(),2));break;case"yaml":n.SetFormatter(new dy(n.TxtEnDe(),2));break;case"json":default:n.SetFormatter(new ga(n.TxtEnDe()));break}break}case"FP_DEBUG":n.SetDebug(l||[]);break;case"FP_STACK":n.SetExposeStack(!!l);break}},"FP_FORMAT","FP_DEBUG","FP_STACK")}).finally(()=>{}),o.length>0&&n.SetDebug(o),i&&n.SetExposeStack(!0),s.Logger()}function Nt(r,e,t){let n=r.getParam("store");switch(n){case"data":case"wal":case"meta":break;default:throw e.logger.Error().Url(r).Msg("store not found").AsError()}let s=n;return r.hasParam("index")&&(s=t(r.getParam("index")||"idx",s)),{store:n,name:s}}function Zo(r,e){let t=r.getParam("key");if(!t)throw e.Error().Str("url",r.toString()).Msg("key not found").AsError();return t}function UA(r,e){let t=e.getParam("name");if(!t&&(t=r.pathOps.dirname(e.pathname),t.length===0))throw r.logger.Error().Str("url",e.toString()).Msg("name not found").AsError();return t}async function ei(r){return r().catch(e=>C.Err(e))}function Mt(r){if(C.Is(r)){if(r.isOk())return!1;r=r.Err()}return r.code==="ENOENT"}function Wh(r,e,t){if(!t)if(Or().isBrowser)t=r.env.get("FP_STORAGE_URL")||"indexdb://fp";else{let n=r.env.get("HOME")||"./";t=r.env.get("FP_STORAGE_URL")||`file://${r.pathOps.join(n,".fireproof")}`}return Ie.from(t.toString()).build().setParam("name",e||"").URI()}function qh(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}var NA,MA,jh,Vh,RA,FA,Dt,ye=A(()=>{"use strict";ae();Rr();NA=new X;MA=new X,jh=class r{constructor(e){this.logger=e.logger,this.env=e.env,this.crypto=e.crypto,this.pathOps=e.pathOps,this.txt=e.txt,this.ctx={...e.ctx}}nextId(e=6){let t=this.crypto.randomBytes(e);return{str:J.encode(t),bin:t}}timeOrderedNextId(e){e=typeof e=="number"?e:new Date().getTime();let t=(281474976710656+e).toString(16).replace(/^1/,""),n=this.crypto.randomBytes(10);n[1]=n[1]&240|(n[1]|8&&11);let s=Array.from(n).map(o=>o.toString(16).padStart(2,"0")).join("");return{str:`${t.slice(0,8)}-${t.slice(8)}-7${s.slice(0,3)}-${s.slice(3,7)}-${s.slice(7,19)}`}}start(){return Promise.resolve()}clone(e){return new r({logger:e.logger||this.logger,env:xn(e.env)||this.env,crypto:e.crypto||this.crypto,pathOps:e.pathOps||this.pathOps,txt:e.txt||this.txt,ctx:{...this.ctx,...e.ctx}})}};Vh=class{join(...e){return e.map(t=>t.replace(/\/+$/,"")).join("/")}dirname(e){return e.split("/").slice(0,-1).join("/")}},RA=new Vh,FA={encode:r=>new TextEncoder().encode(r),decode:r=>new TextDecoder().decode(r)};Dt=class extends Error{constructor(){super(...arguments);this.code="ENOENT"}}});var vx=$((u4,Sx)=>{"use strict";Sx.exports=Jh;var kx=128,$A=127,KA=~$A,zA=Math.pow(2,31);function Jh(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw Jh.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=zA;)e[t++]=r&255|kx,r/=128;for(;r&KA;)e[t++]=r&255|kx,r>>>=7;return e[t]=r|0,Jh.bytes=t-n+1,e}});var _x=$((f4,Tx)=>{"use strict";Tx.exports=Qh;var HA=128,Ex=127;function Qh(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a||s>49)throw Qh.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Ex)<<s:(i&Ex)*Math.pow(2,s),s+=7}while(i>=HA);return Qh.bytes=o-n,t}});var Ix=$((h4,Ax)=>{"use strict";var jA=Math.pow(2,7),VA=Math.pow(2,14),WA=Math.pow(2,21),qA=Math.pow(2,28),GA=Math.pow(2,35),JA=Math.pow(2,42),QA=Math.pow(2,49),YA=Math.pow(2,56),XA=Math.pow(2,63);Ax.exports=function(r){return r<jA?1:r<VA?2:r<WA?3:r<qA?4:r<GA?5:r<JA?6:r<QA?7:r<YA?8:r<XA?9:10}});var Yh=$((d4,Cx)=>{"use strict";Cx.exports={encode:vx(),decode:_x(),encodingLength:Ix()}});async function li(r){let e=r.getParam("fs","node"),t;switch(e){case"mem":t=await $x.get(e).once(async()=>{let n="./node/mem-filesystem.js",{MemFileSystem:s}=await import(n);return new s});break;default:t=await $x.get(e).once(async()=>{let n="./node/node-filesystem.js",{NodeFileSystem:s}=await import(n);return new s})}return t.start()}var $x,Kx=A(()=>{"use strict";ae();$x=new _e});var zx={};K(zx,{getFileName:()=>ui,getFileSystem:()=>li,getPath:()=>tn});function tn(r,e){let t=r.pathname,n=r.getParam("name");if(n){let s=r.getParam("version");if(!s)throw e.logger.Error().Url(r).Msg("version not found").AsError();return e.pathOps.join(t,s,n)}return e.pathOps.join(t)}function ui(r,e){let t=r.getParam("key");if(!t)throw e.logger.Error().Url(r).Msg("key not found").AsError();let n=Nt(r,e,(...s)=>s.join("-"));switch(n.store){case"data":return e.pathOps.join(n.name,t+".car");case"wal":case"meta":return e.pathOps.join(n.name,t+".json");default:throw e.logger.Error().Url(r).Msg("unsupported store type").AsError()}}var fi=A(()=>{"use strict";ye();Kx()});var Hx={};K(Hx,{KeyBagProviderFile:()=>td});var td,jx=A(()=>{"use strict";ye();td=class{async _prepare(e){await this.sthis.start();let t;switch(this.url.protocol){case"file:":{let{getFileSystem:s}=await Promise.resolve().then(()=>(fi(),zx));t=await s(this.url);break}default:throw this.logger.Error().Url(this.url).Msg("unsupported protocol").AsError()}let n=this.url.pathname;return await t.mkdir(n,{recursive:!0}),{dirName:n,sysFS:t,fName:this.sthis.pathOps.join(n,`${e.replace(/[^a-zA-Z0-9]/g,"_")}.json`)}}constructor(e,t){this.url=e,this.sthis=t,this.logger=t.logger}async get(e){let t=await this._prepare(e);try{let n=await t.sysFS.readfile(t.fName);return JSON.parse(this.sthis.txt.decode(n))}catch(n){if(Mt(n))return;throw this.logger.Error().Err(n).Str("file",t.dirName).Msg("read bag failed").AsError()}}async set(e,t){let n=await this._prepare(e),s=this.sthis.txt.encode(JSON.stringify(t,null,2));await n.sysFS.writefile(n.fName,s)}}});function sI(){return Vx||(Vx=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function oI(){return Wx||(Wx=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function iI(r){let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("success",o),r.removeEventListener("error",i)},o=()=>{t(rn(r.result)),s()},i=()=>{n(r.error),s()};r.addEventListener("success",o),r.addEventListener("error",i)});return Rc.set(e,r),e}function aI(r){if(od.has(r))return;let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("complete",o),r.removeEventListener("error",i),r.removeEventListener("abort",i)},o=()=>{t(),s()},i=()=>{n(r.error||new DOMException("AbortError","AbortError")),s()};r.addEventListener("complete",o),r.addEventListener("error",i),r.addEventListener("abort",i)});od.set(r,e)}function Qx(r){id=r(id)}function cI(r){return oI().includes(r)?function(...e){return r.apply(ad(this),e),rn(this.request)}:function(...e){return rn(r.apply(ad(this),e))}}function lI(r){return typeof r=="function"?cI(r):(r instanceof IDBTransaction&&aI(r),sd(r,sI())?new Proxy(r,id):r)}function rn(r){if(r instanceof IDBRequest)return iI(r);if(rd.has(r))return rd.get(r);let e=lI(r);return e!==r&&(rd.set(r,e),Rc.set(e,r)),e}function Fc(r,e,{blocked:t,upgrade:n,blocking:s,terminated:o}={}){let i=indexedDB.open(r,e),a=rn(i);return n&&i.addEventListener("upgradeneeded",c=>{n(rn(i.result),c.oldVersion,c.newVersion,rn(i.transaction),c)}),t&&i.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),a.then(c=>{o&&c.addEventListener("close",()=>o()),s&&c.addEventListener("versionchange",l=>s(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}function qx(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(nd.get(e))return nd.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,s=fI.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(s||uI.includes(t)))return;let o=async function(i,...a){let c=this.transaction(i,s?"readwrite":"readonly"),l=c.store;return n&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),s&&c.done]))[0]};return nd.set(e,o),o}async function*pI(...r){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...r)),!e)return;e=e;let t=new Proxy(e,dI);for(Yx.set(t,e),Rc.set(t,ad(e));e;)yield t,e=await(cd.get(t)||e.continue()),cd.delete(t)}function Jx(r,e){return e===Symbol.asyncIterator&&sd(r,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&sd(r,[IDBIndex,IDBObjectStore])}var sd,Vx,Wx,od,rd,Rc,id,ad,uI,fI,nd,hI,Gx,cd,Yx,dI,ld=A(()=>{"use strict";sd=(r,e)=>e.some(t=>r instanceof t);od=new WeakMap,rd=new WeakMap,Rc=new WeakMap;id={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return od.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return rn(r[e])},set(r,e,t){return r[e]=t,!0},has(r,e){return r instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in r}};ad=r=>Rc.get(r);uI=["get","getKey","getAll","getAllKeys","count"],fI=["put","add","delete","clear"],nd=new Map;Qx(r=>({...r,get:(e,t,n)=>qx(e,t)||r.get(e,t,n),has:(e,t)=>!!qx(e,t)||r.has(e,t)}));hI=["continue","continuePrimaryKey","advance"],Gx={},cd=new WeakMap,Yx=new WeakMap,dI={get(r,e){if(!hI.includes(e))return r[e];let t=Gx[e];return t||(t=Gx[e]=function(...n){cd.set(this,Yx.get(this)[e](...n))}),t}};Qx(r=>({...r,get(e,t,n){return Jx(e,t)?pI:r.get(e,t,n)},has(e,t){return Jx(e,t)||r.has(e,t)}}))});var Xx={};K(Xx,{KeyBagProviderIndexDB:()=>ud});var ud,Zx=A(()=>{"use strict";ld();fi();ae();ud=class{constructor(e,t){this._db=new X;this.sthis=t,this.logger=t.logger,this.url=e,this.dbName=tn(this.url,this.sthis)}async _prepare(){return this._db.once(async()=>await Fc(this.dbName,1,{upgrade(e){["bag"].map(t=>{e.createObjectStore(t,{autoIncrement:!1})})}}))}async get(e){let n=(await this._prepare()).transaction(["bag"],"readonly"),s=await n.objectStore("bag").get(e);if(await n.done,!!s)return s}async set(e,t){let s=(await this._prepare()).transaction(["bag"],"readwrite");await s.objectStore("bag").put(t,e),await s.done}}});var wk=$((aK,gk)=>{"use strict";function tt(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}gk.exports=tt;tt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};tt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};tt.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};tt.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};tt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};tt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};tt.prototype.start=tt.prototype.try;tt.prototype.errors=function(){return this._errors};tt.prototype.attempts=function(){return this._attempts};tt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var s=this._errors[n],o=s.message,i=(r[o]||0)+1;r[o]=i,i>=t&&(e=s,t=i)}return e}});var bk=$(nn=>{"use strict";var PI=wk();nn.operation=function(r){var e=nn.timeouts(r);return new PI(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};nn.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<e.retries;s++)n.push(this.createTimeout(s,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(s,e)),n.sort(function(o,i){return o-i}),n};nn.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};nn.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var s=0;s<t.length;s++){var o=t[s],i=r[o];r[o]=function(c){var l=nn.operation(e),u=Array.prototype.slice.call(arguments,1),f=u.pop();u.push(function(p){l.retry(p)||(p&&(arguments[0]=l.mainError()),f.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,i),r[o].options=e}}});var kk=$((lK,xk)=>{"use strict";xk.exports=bk()});var Cr,Td=A(()=>{"use strict";Cr="v0.19-file"});var Id={};K(Id,{FileGateway:()=>_d,FileTestStore:()=>Ad});var RI,_d,Ad,Cd=A(()=>{"use strict";Td();ae();ye();fi();RI=new _e,_d=class{get fs(){if(!this._fs)throw this.logger.Error().Msg("fs not initialized").AsError();return this._fs}constructor(e){this.sthis=e,this.logger=e.logger}async getVersionFromFile(e,t){return RI.get(e).once(async()=>{await this.fs.mkdir(e,{recursive:!0});let n=this.sthis.pathOps.join(e,"version"),s=await this.fs.stat(n).catch(()=>{});if(s){if(!s.isFile())throw t.Error().Str("file",n).Msg("version file is a directory").AsError()}else return await this.fs.writefile(this.sthis.pathOps.join(e,"version"),Cr),Cr;let o=await this.fs.readfile(n),i=this.sthis.txt.decode(o);return i!==Cr&&t.Warn().Str("file",n).Str("from",i).Str("expected",Cr).Msg("version mismatch"),i})}start(e){return We(async()=>{this._fs=await li(e),await this.fs.start();let t=e.build();t.defParam("version",Cr);let n=await this.buildUrl(t.URI(),"dummy"),s=this.getFilePath(n.Ok());await this.fs.mkdir(this.sthis.pathOps.dirname(s),{recursive:!0});let o=this.sthis.pathOps.dirname(s);return this.logger.Debug().Url(t.URI()).Str("dbroot",o).Msg("start"),t.setParam("version",await this.getVersionFromFile(o,this.logger)),t.URI()})}async buildUrl(e,t){return C.Ok(e.build().setParam("key",t).URI())}async close(){return C.Ok(void 0)}getFilePath(e){if(!e.getParam("key"))throw this.logger.Error().Url(e).Msg("key not found").AsError();return this.sthis.pathOps.join(tn(e,this.sthis),ui(e,this.sthis))}async put(e,t){return We(async()=>{let n=await this.getFilePath(e);this.logger.Debug().Str("url",e.toString()).Str("file",n).Msg("put"),await this.fs.writefile(n,t)})}async get(e){return ei(async()=>{let t=this.getFilePath(e);try{let n=await this.fs.readfile(t);return this.logger.Debug().Url(e.asURL()).Str("file",t).Msg("get"),C.Ok(new Uint8Array(n))}catch(n){return Mt(n)?C.Err(new Dt(`file not found: ${t}`)):C.Err(n)}})}async delete(e){return We(async()=>{await this.fs.unlink(this.getFilePath(e))})}async destroy(e){let t=await this.buildUrl(e,"x");if(t.isErr())return t;let n=this.sthis.pathOps.dirname(this.getFilePath(t.Ok())),s=[];try{s=await this.fs.readdir(n)}catch(o){if(!Mt(o))throw this.logger.Error().Err(o).Str("dir",n).Msg("destroy:readdir").AsError()}for(let o of s){let i=this.sthis.pathOps.join(n,o);try{await this.fs.unlink(i)}catch(a){if(!Mt(a))throw this.logger.Error().Err(a).Str("file",i).Msg("destroy:unlink").AsError()}}return C.Ok(void 0)}},Ad=class{constructor(e){this.logger=H(e,"FileTestStore"),this.sthis=e}async get(e,t){let n=e.build().setParam("key",t).URI(),s=this.sthis.pathOps.join(tn(n,this.sthis),ui(n,this.sthis));this.logger.Debug().Url(n).Str("dbFile",s).Msg("get");let o=await(await li(n)).readfile(s);return this.logger.Debug().Url(n).Str("dbFile",s).Len(o).Msg("got"),o}}});var Vc,Ld=A(()=>{"use strict";Vc="v0.19-indexdb"});var Ik={};K(Ik,{IndexDBGatewayImpl:()=>Bd,IndexDBTestStore:()=>Pd,getIndexDBName:()=>Ak});function Tk(r){return r.build().defParam("version",Vc).URI()}function Wc(r){return r.length===1&&(r=r[0]),r}async function _k(r,e){let t=Ak(r,e),n=await FI.get(t.fullDb).once(async()=>{let s=await Fc(t.fullDb,1,{upgrade(a){["version","data","wal","meta","idx.data","idx.wal","idx.meta"].map(c=>{a.createObjectStore(c,{autoIncrement:!1})})}}),o=await s.get("version","version"),i=Tk(r).getParam("version");return o?o.version!==i&&e.logger.Warn().Str("url",r.toString()).Str("version",i).Str("found",o.version).Msg("version mismatch"):await s.put("version",{version:i},"version"),{db:s,dbName:t,version:i,url:r}});return{...n,url:r.build().setParam("version",n.version).URI()}}function sn(...r){return r.map(e=>e.replace(/^[^a-zA-Z0-9]+/g,"").replace(/[^a-zA-Z0-9-]+/g,"_")).filter(e=>e.length).join(".")}function Ak(r,e){let t=Tk(r),n=t.pathname.replace(/^\/+/,"").replace(/\?.*$/,""),s=t.getParam("name");if(!s)throw e.logger.Error().Str("url",t.toString()).Msg("name not found").AsError();let o=sn(n,s),i=Nt(t,e,sn).name,a=[o,i].join(":");return{fullDb:o,objStore:i,connectionKey:a,dbName:s}}var FI,Bd,Pd,Ck=A(()=>{"use strict";ld();ae();Ld();ye();FI=new _e;Bd=class{constructor(e){this._db={};this.logger=H(e,"IndexDBGateway"),this.sthis=e}async start(e){return We(async()=>{this.logger.Debug().Url(e).Msg("starting"),await this.sthis.start();let t=await _k(e,this.sthis);return this._db=t.db,this.logger.Debug().Url(t.url).Msg("started"),t.url})}async close(){return C.Ok(void 0)}async destroy(e){return We(async()=>{let t=Nt(e,this.sthis,sn).name,s=this._db.transaction(t,"readwrite"),o=s.objectStore(t),i=[];for(let a=await o.openCursor();a;a=await a.continue())i.push(a.primaryKey);for(let a of i)await s.db.delete(t,a);await s.done})}buildUrl(e,t){return Promise.resolve(C.Ok(e.build().setParam("key",t).URI()))}async get(e){return ei(async()=>{let t=Zo(e,this.logger),n=Nt(e,this.sthis,sn).name;this.logger.Debug().Url(e).Str("key",t).Str("store",n).Msg("getting");let s=this._db.transaction([n],"readonly"),o=await s.objectStore(n).get(Wc(t));return await s.done,o?C.Ok(o):C.Err(new Dt(`missing ${t}`))})}async put(e,t){return We(async()=>{let n=Zo(e,this.logger),s=Nt(e,this.sthis,sn).name;this.logger.Debug().Url(e).Str("key",n).Str("store",s).Msg("putting");let o=this._db.transaction([s],"readwrite");await o.objectStore(s).put(t,Wc(n)),await o.done})}async delete(e){return We(async()=>{let t=Zo(e,this.logger),n=Nt(e,this.sthis,sn).name;this.logger.Debug().Url(e).Str("key",t).Str("store",n).Msg("deleting");let s=this._db.transaction([n],"readwrite");return await s.objectStore(n).delete(Wc(t)),await s.done,C.Ok(void 0)})}},Pd=class{constructor(e){this.sthis=e,this.logger=H(e,"IndexDBTestStore",{})}async get(e,t){let n=await _k(e,this.sthis),s=Nt(n.url,this.sthis,sn).name;this.logger.Debug().Str("key",t).Str("store",s).Msg("getting");let o=await n.db.get(s,Wc(t));return this.logger.Debug().Str("key",t).Str("store",s).Int("len",o.length).Msg("got"),typeof o=="string"&&(o=this.sthis.txt.encode(o)),o}}});function Dd(){return Promise.resolve().then(()=>(Ck(),Ik))}var Lk=A(()=>{"use strict"});var Od={};K(Od,{IndexDBGateway:()=>Nd,IndexDBTestStore:()=>Md});var UI,Nd,Md,Rd=A(()=>{"use strict";ae();Lk();UI=new X,Nd=class{constructor(e){this.sthis=e}getGateway(){return UI.once(()=>Dd().then(({IndexDBGatewayImpl:e})=>new e(this.sthis)))}buildUrl(e,t){return this.getGateway().then(n=>n.buildUrl(e,t))}start(e){return this.getGateway().then(t=>t.start(e))}close(e){return this.getGateway().then(t=>t.close(e))}destroy(e){return this.getGateway().then(t=>t.destroy(e))}put(e,t){return this.getGateway().then(n=>n.put(e,t))}get(e){return this.getGateway().then(t=>t.get(e))}delete(e){return this.getGateway().then(t=>t.delete(e))}},Md=class{constructor(e){this.loadExternal=new X;this.sthis=e}getGateway(){return this.loadExternal.once(()=>Dd().then(({IndexDBTestStore:e})=>new e(this.sthis)))}get(e,t){return this.getGateway().then(n=>n.get(e,t))}}});var jk=$(Wd=>{"use strict";Wd.encode=function(r){if(isNaN(r))return"DaN";if(r===0)return"FE 0M0";if(r===1/0)return"FF";if(r===-1/0)return"DD";var e=r.toExponential().split("e"),t=Number(e[1])+500,n=e[0]+(e[0].indexOf(".")===-1?".":"")+"0".repeat(20),s="E"+QI(String(t),3)+"M"+String(n);return r>0?"F"+s:"D"+Hk(s)};Wd.decode=function(r){if(r==="DaN")return NaN;if(r==="FF")return 1/0;if(r==="DD")return-1/0;var e=r[0]==="D",t=(e?Hk(r):r).slice(2).split("M");return+((e?"-":"")+t[1]+"e"+String(Number(t[0])-500))};function Hk(r){for(var e="",t=0;t<r.length;t++){var n=r[t];isNaN(Number(n))||n===" "?n!=="-"&&(e+=n):e+=String(9-Number(n))}return e}function QI(r,e){return" ".repeat(e-r.length).substr(0,e)+r}});var Wk=$(Vk=>{"use strict";var YI={"?":"?@","!":"??",'"':"?%"};function XI(r){return/[!"]/.test(r)?r.replace(/[\?!"]/g,function(e){return YI[e]}):r}var ZI={"?@":"?","??":"!","?%":'"'};function eC(r){return/\?[%\?@]/.test(r)?r.replace(/\?[%\?@]/g,function(e){return ZI[e]}):r}Vk.factory=function(r){return{encode:e,decode:n};function e(s){if(s===null)return"A";if(!Array.isArray(s))throw new Error("can only encode arrays");var o=s.length;if(o==0)return"K!";for(var i=t(s[0]),a=1;a<o;a++)i+='"'+t(s[a]);return"K"+i+"!"}function t(s){return typeof s=="object"?e(s):XI(r.encode(s))}function n(s){if(s==="A")return null;if(s==="K!")return[];for(var o=s.split('"'),i=[[]],a,c=0,l=o.length,u=0;u<l;u++){for(var f=o[u],p=f.length,h=0;f[h]=="K";)h++;for(var m=0;f[p-m-1]=="!";)m++;for(var d=f.slice(h,p-m),g=c+h,y=c;y<g;y++)i[y+1]=[],i[y].push(i[y+1]),c=g,a=i[c];d.length!==0&&a.push(r.decode(eC(d)));for(var g=c-m,y=g;y<c;y++)i[y+1]=[],c=g,a=i[c]}return i[0][0]}}});var Gk=$(se=>{"use strict";var tC=jk(),rC=Wk(),$z=se.flip=function(r){var e=r.toString(),t="";for(var n in e)t+=e[n]=="."?".":9-+e[n];return t};se.number=tC;se.string={encode:function(r){return/\x00|\x01/.test(r)?"J"+r.replace(/\x01/g,"").replace(/\x00/g,""):"J"+r},decode:function(r){if(r[0]==="J")return r.substring(1)}};se.encode=function(r){return se[typeof r].encode(r)};se.decode=function(r){if(r==="")return r;if(!qk[r[0]])throw new Error("no decoder for:"+JSON.stringify(r));return qk[r[0]](r)};se.object=rC.factory(se);se.boolean={encode:function(r){return r?"C":"B"},decode:function(r){return r==="C"}};se.undefined={encode:function(r){return"L"},decode:function(){}};var qk={A:se.object.decode,B:se.boolean.decode,C:se.boolean.decode,D:se.number.decode,F:se.number.decode,J:se.string.decode,K:se.object.decode,L:se.undefined.decode};se.buffer=!1;se.type="charwise"});var kC={};K(kC,{CRDT:()=>bi,Database:()=>Bs,Index:()=>tl,NotFoundError:()=>Dt,PACKAGE_VERSION:()=>xC,Result:()=>C,UInt8ArrayEqual:()=>qh,blockstore:()=>Jc,bs:()=>Jc,dataDir:()=>Wh,ensureLogger:()=>H,ensureSuperLog:()=>_r,ensureSuperThis:()=>Xo,exceptionWrapper:()=>ei,falsyToUndef:()=>Yo,fireproof:()=>wC,getKey:()=>Zo,getName:()=>UA,getStore:()=>Nt,index:()=>Ls,isFalsy:()=>Hh,isNotFoundError:()=>Mt,rt:()=>nl,runtime:()=>nl,throwFalsy:()=>me});ae();function yy(r,e=1/0,t=!1){let n=[],s=!1;async function o(){if(s||n.length===0)return;s=!0;let i=n.splice(0,e),a=i.map(c=>c.task);if(t){let c=a.map(async(l,u)=>{try{let f=await r([l]);i[u].resolve(f)}catch(f){i[u].reject(f)}});await Promise.all(c)}else try{let c=await r(a);i.forEach(l=>l.resolve(c))}catch(c){i.forEach(l=>l.reject(c))}s=!1,o()}return{push(i){return new Promise((a,c)=>{n.push({task:i,resolve:a,reject:c}),o()})}}}ae();var Cu={};K(Cu,{Block:()=>ka,create:()=>Iu,createUnsafe:()=>Iy,decode:()=>lr,encode:()=>Qn});ar();var bu={};K(bu,{base32:()=>Vn,base32hex:()=>$1,base32hexpad:()=>z1,base32hexpadupper:()=>H1,base32hexupper:()=>K1,base32pad:()=>F1,base32padupper:()=>U1,base32upper:()=>R1,base32z:()=>j1});it();var Vn=te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),R1=te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),F1=te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),U1=te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$1=te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),K1=te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),z1=te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),H1=te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),j1=te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var xu={};K(xu,{base36:()=>lo,base36upper:()=>V1});it();var lo=cr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),V1=cr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});Rr();ar();ar();var q1=vy,ky=128,G1=127,J1=~G1,Q1=Math.pow(2,31);function vy(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Q1;)e[t++]=r&255|ky,r/=128;for(;r&J1;)e[t++]=r&255|ky,r>>>=7;return e[t]=r|0,vy.bytes=t-n+1,e}var Y1=Su,X1=128,Sy=127;function Su(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Su.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Sy)<<s:(i&Sy)*Math.pow(2,s),s+=7}while(i>=X1);return Su.bytes=o-n,t}var Z1=Math.pow(2,7),ev=Math.pow(2,14),tv=Math.pow(2,21),rv=Math.pow(2,28),nv=Math.pow(2,35),sv=Math.pow(2,42),ov=Math.pow(2,49),iv=Math.pow(2,56),av=Math.pow(2,63),cv=function(r){return r<Z1?1:r<ev?2:r<tv?3:r<rv?4:r<nv?5:r<sv?6:r<ov?7:r<iv?8:r<av?9:10},lv={encode:q1,decode:Y1,encodingLength:cv},uv=lv,uo=uv;function fo(r,e=0){return[uo.decode(r,e),uo.decode.bytes]}function Wn(r,e,t=0){return uo.encode(r,e,t),e}function qn(r){return uo.encodingLength(r)}function Fr(r,e){let t=e.byteLength,n=qn(r),s=n+qn(t),o=new Uint8Array(s+t);return Wn(r,o,0),Wn(t,o,n),o.set(e,s),new Gn(r,t,e,o)}function Ur(r){let e=qe(r),[t,n]=fo(e),[s,o]=fo(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Gn(t,s,i,e)}function Ey(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&hu(r.bytes,t.bytes)}}var Gn=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function vu(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return hv(t,Eu(r),e??J.encoder);default:return dv(t,Eu(r),e??Vn.encoder)}}var Ty=new WeakMap;function Eu(r){let e=Ty.get(r);if(e==null){let t=new Map;return Ty.set(r,t),t}return e}var N=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==ho)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==pv)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Fr(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Ey(e.multihash,n.multihash)}toString(e){return vu(this,e)}toJSON(){return{"/":vu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??_y(n,s,o.bytes))}else if(t[mv]===!0){let{version:n,multihash:s,code:o}=t,i=Ur(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ho)throw new Error(`Version 0 CID must use dag-pb (code: ${ho}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=_y(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ho,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=qe(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Gn(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,p]=fo(e.subarray(t));return t+=p,f},s=n(),o=ho;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=fv(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Eu(o).set(n,e),o}};function fv(r,e){switch(r[0]){case"Q":{let t=e??J;return[J.prefix,t.decode(`${J.prefix}${r}`)]}case J.prefix:{let t=e??J;return[J.prefix,t.decode(r)]}case Vn.prefix:{let t=e??Vn;return[Vn.prefix,t.decode(r)]}case lo.prefix:{let t=e??lo;return[lo.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function hv(r,e,t){let{prefix:n}=t;if(n!==J.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function dv(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var ho=112,pv=18;function _y(r,e,t){let n=qn(r),s=n+qn(e),o=new Uint8Array(s+t.byteLength);return Wn(r,o,0),Wn(e,o,n),o.set(t,s),o}var mv=Symbol.for("@ipld/js-cid/CID");function Kr({name:r,code:e,encode:t}){return new Tu(r,e,t)}var Tu=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Fr(this.code,t):t.then(n=>Fr(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ba({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*yv(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let s=[...r,t],o=N.asCID(n);o!=null?yield[s.join("/"),o]:typeof n=="object"&&(yield*_u(n,s))}else{let t=N.asCID(e);t!=null?yield[r.join("/"),t]:yield*_u(e,r)}}function*_u(r,e){if(r==null||r instanceof Uint8Array)return;let t=N.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,s]of Object.entries(r)){let o=[...e,n];yield*yv(o,s)}}function*gv(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let s=[...r,t];yield s.join("/"),typeof n=="object"&&N.asCID(n)==null&&(yield*Au(n,s))}else yield*Au(e,r)}function*Au(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let s=[...e,t];yield s.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&N.asCID(n)==null&&(yield*gv(s,n))}}function wv(r,e){let t=r;for(let[n,s]of e.entries()){if(t=t[s],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(i=>`[${JSON.stringify(i)}]`).join("")}`);let o=N.asCID(t);if(o!=null)return{value:o,remaining:e.slice(n+1).join("/")}}return{value:t}}var Se=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:ba(),bytes:ba(),value:ba(),asBlock:ba()})}links(){return _u(this.value,[])}tree(){return Au(this.value,[])}get(e="/"){return wv(this.value,e.split("/").filter(Boolean))}};async function Jn({value:r,codec:e,hasher:t}){if(typeof r>"u")throw new Error('Missing required argument "value"');if(e==null||t==null)throw new Error("Missing required argument: codec or hasher");let n=e.encode(r),s=await t.digest(n),o=N.create(1,e.code,s);return new Se({value:r,bytes:n,cid:o})}async function xa({bytes:r,codec:e,hasher:t}){if(r==null)throw new Error('Missing required argument "bytes"');if(e==null||t==null)throw new Error("Missing required argument: codec or hasher");let n=e.decode(r),s=await t.digest(r),o=N.create(1,e.code,s);return new Se({value:n,bytes:r,cid:o})}var ka=Se;async function lr({bytes:r,codec:e,hasher:t}){if(r==null)throw new Error('Missing required argument "bytes"');if(e==null||t==null)throw new Error("Missing required argument: codec or hasher");let n=await Promise.resolve(e.decode(r)),s=await t.digest(r),o=N.create(1,e.code,s);return new Se({value:n,bytes:r,cid:o})}async function Qn({value:r,codec:e,hasher:t}){if(typeof r>"u")throw new Error('Missing required argument "value"');if(e==null||t==null)throw new Error("Missing required argument: codec or hasher");let n=await Promise.resolve(e.encode(r)),s=await t.digest(n),o=N.create(1,e.code,s);return new Se({value:r,bytes:n,cid:o})}async function Iu({bytes:r,cid:e,hasher:t,codec:n}){if(r==null)throw new Error('Missing required argument "bytes"');if(t==null)throw new Error('Missing required argument "hasher"');let s=await Promise.resolve(n.decode(r)),o=await t.digest(r);if(!Kt.equals(e.multihash.bytes,o.bytes))throw new Error("CID hash does not match bytes");return Iy({bytes:r,cid:e,value:s,codec:n})}async function Iy({bytes:r,cid:e,value:t,codec:n}){let s=await Promise.resolve(t!==void 0?t:n?.decode(r));if(s===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new ka({cid:e,bytes:r,value:s})}function Cy(r){if(r==null)return!1;let e=r;return e["/"]!=null&&e["/"]===e.bytes||r.asCID===r}function Sa(r,e){return N.parse(r,e)}var Lu={};K(Lu,{sha256:()=>Q,sha512:()=>xv});function Ly(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Q=Kr({name:"sha2-256",code:18,encode:Ly("SHA-256")}),xv=Kr({name:"sha2-512",code:19,encode:Ly("SHA-512")});var re={};K(re,{code:()=>ko,decode:()=>So,decodeOptions:()=>Xv,encode:()=>Ku,encodeOptions:()=>Qv,name:()=>Zv,toByteView:()=>Mg});var kv=["string","number","bigint","symbol"],Sv=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function By(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(kv.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(vv(r))return"Buffer";let t=Ev(r);return t||"Object"}function vv(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function Ev(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(Sv.includes(e))return e}var w=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};w.uint=new w(0,"uint",!0);w.negint=new w(1,"negint",!0);w.bytes=new w(2,"bytes",!0);w.string=new w(3,"string",!0);w.array=new w(4,"array",!1);w.map=new w(5,"map",!1);w.tag=new w(6,"tag",!1);w.float=new w(7,"float",!0);w.false=new w(7,"false",!0);w.true=new w(7,"true",!0);w.null=new w(7,"null",!0);w.undefined=new w(7,"undefined",!0);w.break=new w(7,"break",!0);var v=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Yn=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Tv=new TextDecoder,_v=new TextEncoder;function va(r){return Yn&&globalThis.Buffer.isBuffer(r)}function po(r){return r instanceof Uint8Array?va(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var My=Yn?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):Dy(r,e,t):(r,e,t)=>t-e>64?Tv.decode(r.subarray(e,t)):Dy(r,e,t),Ea=Yn?r=>r.length>64?globalThis.Buffer.from(r):Py(r):r=>r.length>64?_v.encode(r):Py(r),Et=r=>Uint8Array.from(r),Xn=Yn?(r,e,t)=>va(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Oy=Yn?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),po(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let s of r)n+s.length>t.length&&(s=s.subarray(0,t.length-n)),t.set(s,n),n+=s.length;return t},Ry=Yn?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Fy(r,e){if(va(r)&&va(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function Py(r){let e=[],t=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(s=65536+((s&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128)}return e}function Dy(r,e,t){let n=[];for(;e<t;){let s=r[e],o=null,i=s>239?4:s>223?3:s>191?2:1;if(e+i<=t){let a,c,l,u;switch(i){case 1:s<128&&(o=s);break;case 2:a=r[e+1],(a&192)===128&&(u=(s&31)<<6|a&63,u>127&&(o=u));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(u=(s&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(o=u));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(s&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(o=u))}}o===null?(o=65533,i=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),e+=i}return Bu(n)}var Ny=4096;function Bu(r){let e=r.length;if(e<=Ny)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Ny));return t}var Av=256,mo=class{constructor(e=Av){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let s=t.length-(this.maxCursor-this.cursor)-1;t.set(e,s)}else{if(t){let s=t.length-(this.maxCursor-this.cursor)-1;s<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,s),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Ry(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=Xn(n,0,this.cursor)}else t=Oy(this.chunks,this.cursor);return e&&this.reset(),t}};var L="CBOR decode error:",zt="CBOR encode error:",yo=[];yo[23]=1;yo[24]=2;yo[25]=3;yo[26]=5;yo[27]=9;function Ht(r,e,t){if(r.length-e<t)throw new Error(`${L} not enough data for type`)}var ue=[24,256,65536,4294967296,BigInt("18446744073709551616")];function De(r,e,t){Ht(r,e,1);let n=r[e];if(t.strict===!0&&n<ue[0])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);return n}function Ne(r,e,t){Ht(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<ue[1])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);return n}function Me(r,e,t){Ht(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<ue[2])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);return n}function Oe(r,e,t){Ht(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],s=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],o=(BigInt(n)<<BigInt(32))+BigInt(s);if(t.strict===!0&&o<ue[3])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(t.allowBigInt===!0)return o;throw new Error(`${L} integers outside of the safe integer range are not supported`)}function Uy(r,e,t,n){return new v(w.uint,De(r,e+1,n),2)}function $y(r,e,t,n){return new v(w.uint,Ne(r,e+1,n),3)}function Ky(r,e,t,n){return new v(w.uint,Me(r,e+1,n),5)}function zy(r,e,t,n){return new v(w.uint,Oe(r,e+1,n),9)}function Ge(r,e){return de(r,0,e.value)}function de(r,e,t){if(t<ue[0]){let n=Number(t);r.push([e|n])}else if(t<ue[1]){let n=Number(t);r.push([e|24,n])}else if(t<ue[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<ue[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<ue[4]){let s=[e|27,0,0,0,0,0,0,0],o=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));s[8]=o&255,o=o>>8,s[7]=o&255,o=o>>8,s[6]=o&255,o=o>>8,s[5]=o&255,s[4]=i&255,i=i>>8,s[3]=i&255,i=i>>8,s[2]=i&255,i=i>>8,s[1]=i&255,r.push(s)}else throw new Error(`${L} encountered BigInt larger than allowable range`)}}Ge.encodedSize=function(e){return de.encodedSize(e.value)};de.encodedSize=function(e){return e<ue[0]?1:e<ue[1]?2:e<ue[2]?3:e<ue[3]?5:9};Ge.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Hy(r,e,t,n){return new v(w.negint,-1-De(r,e+1,n),2)}function jy(r,e,t,n){return new v(w.negint,-1-Ne(r,e+1,n),3)}function Vy(r,e,t,n){return new v(w.negint,-1-Me(r,e+1,n),5)}var Pu=BigInt(-1),Wy=BigInt(1);function qy(r,e,t,n){let s=Oe(r,e+1,n);if(typeof s!="bigint"){let o=-1-s;if(o>=Number.MIN_SAFE_INTEGER)return new v(w.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${L} integers outside of the safe integer range are not supported`);return new v(w.negint,Pu-BigInt(s),9)}function Ta(r,e){let t=e.value,n=typeof t=="bigint"?t*Pu-Wy:t*-1-1;de(r,e.type.majorEncoded,n)}Ta.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*Pu-Wy:t*-1-1;return n<ue[0]?1:n<ue[1]?2:n<ue[2]?3:n<ue[3]?5:9};Ta.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function go(r,e,t,n){Ht(r,e,t+n);let s=Xn(r,e+t,e+t+n);return new v(w.bytes,s,t+n)}function Gy(r,e,t,n){return go(r,e,1,t)}function Jy(r,e,t,n){return go(r,e,2,De(r,e+1,n))}function Qy(r,e,t,n){return go(r,e,3,Ne(r,e+1,n))}function Yy(r,e,t,n){return go(r,e,5,Me(r,e+1,n))}function Xy(r,e,t,n){let s=Oe(r,e+1,n);if(typeof s=="bigint")throw new Error(`${L} 64-bit integer bytes lengths not supported`);return go(r,e,9,s)}function _a(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===w.string?Ea(r.value):r.value),r.encodedBytes}function Zn(r,e){let t=_a(e);de(r,e.type.majorEncoded,t.length),r.push(t)}Zn.encodedSize=function(e){let t=_a(e);return de.encodedSize(t.length)+t.length};Zn.compareTokens=function(e,t){return Cv(_a(e),_a(t))};function Cv(r,e){return r.length<e.length?-1:r.length>e.length?1:Fy(r,e)}function wo(r,e,t,n,s){let o=t+n;Ht(r,e,o);let i=new v(w.string,My(r,e+t,e+o),o);return s.retainStringBytes===!0&&(i.byteValue=Xn(r,e+t,e+o)),i}function Zy(r,e,t,n){return wo(r,e,1,t,n)}function eg(r,e,t,n){return wo(r,e,2,De(r,e+1,n),n)}function tg(r,e,t,n){return wo(r,e,3,Ne(r,e+1,n),n)}function rg(r,e,t,n){return wo(r,e,5,Me(r,e+1,n),n)}function ng(r,e,t,n){let s=Oe(r,e+1,n);if(typeof s=="bigint")throw new Error(`${L} 64-bit integer string lengths not supported`);return wo(r,e,9,s,n)}var sg=Zn;function es(r,e,t,n){return new v(w.array,n,t)}function og(r,e,t,n){return es(r,e,1,t)}function ig(r,e,t,n){return es(r,e,2,De(r,e+1,n))}function ag(r,e,t,n){return es(r,e,3,Ne(r,e+1,n))}function cg(r,e,t,n){return es(r,e,5,Me(r,e+1,n))}function lg(r,e,t,n){let s=Oe(r,e+1,n);if(typeof s=="bigint")throw new Error(`${L} 64-bit integer array lengths not supported`);return es(r,e,9,s)}function ug(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${L} indefinite length items not allowed`);return es(r,e,1,1/0)}function Aa(r,e){de(r,w.array.majorEncoded,e.value)}Aa.compareTokens=Ge.compareTokens;Aa.encodedSize=function(e){return de.encodedSize(e.value)};function ts(r,e,t,n){return new v(w.map,n,t)}function fg(r,e,t,n){return ts(r,e,1,t)}function hg(r,e,t,n){return ts(r,e,2,De(r,e+1,n))}function dg(r,e,t,n){return ts(r,e,3,Ne(r,e+1,n))}function pg(r,e,t,n){return ts(r,e,5,Me(r,e+1,n))}function mg(r,e,t,n){let s=Oe(r,e+1,n);if(typeof s=="bigint")throw new Error(`${L} 64-bit integer map lengths not supported`);return ts(r,e,9,s)}function yg(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${L} indefinite length items not allowed`);return ts(r,e,1,1/0)}function Ia(r,e){de(r,w.map.majorEncoded,e.value)}Ia.compareTokens=Ge.compareTokens;Ia.encodedSize=function(e){return de.encodedSize(e.value)};function gg(r,e,t,n){return new v(w.tag,t,1)}function wg(r,e,t,n){return new v(w.tag,De(r,e+1,n),2)}function bg(r,e,t,n){return new v(w.tag,Ne(r,e+1,n),3)}function xg(r,e,t,n){return new v(w.tag,Me(r,e+1,n),5)}function kg(r,e,t,n){return new v(w.tag,Oe(r,e+1,n),9)}function Ca(r,e){de(r,w.tag.majorEncoded,e.value)}Ca.compareTokens=Ge.compareTokens;Ca.encodedSize=function(e){return de.encodedSize(e.value)};var Mv=20,Ov=21,Rv=22,Fv=23;function Sg(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${L} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new v(w.null,null,1):new v(w.undefined,void 0,1)}function vg(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${L} indefinite length items not allowed`);return new v(w.break,void 0,1)}function Du(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${L} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${L} Infinity values are not supported`)}return new v(w.float,r,e)}function Eg(r,e,t,n){return Du(Nu(r,e+1),3,n)}function Tg(r,e,t,n){return Du(Mu(r,e+1),5,n)}function _g(r,e,t,n){return Du(Lg(r,e+1),9,n)}function La(r,e,t){let n=e.value;if(n===!1)r.push([w.float.majorEncoded|Mv]);else if(n===!0)r.push([w.float.majorEncoded|Ov]);else if(n===null)r.push([w.float.majorEncoded|Rv]);else if(n===void 0)r.push([w.float.majorEncoded|Fv]);else{let s,o=!1;(!t||t.float64!==!0)&&(Ig(n),s=Nu(at,1),n===s||Number.isNaN(n)?(at[0]=249,r.push(at.slice(0,3)),o=!0):(Cg(n),s=Mu(at,1),n===s&&(at[0]=250,r.push(at.slice(0,5)),o=!0))),o||(Uv(n),s=Lg(at,1),at[0]=251,r.push(at.slice(0,9)))}}La.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){Ig(n);let s=Nu(at,1);if(n===s||Number.isNaN(n))return 3;if(Cg(n),s=Mu(at,1),n===s)return 5}return 9};var Ag=new ArrayBuffer(9),Je=new DataView(Ag,1),at=new Uint8Array(Ag,0);function Ig(r){if(r===1/0)Je.setUint16(0,31744,!1);else if(r===-1/0)Je.setUint16(0,64512,!1);else if(Number.isNaN(r))Je.setUint16(0,32256,!1);else{Je.setFloat32(0,r);let e=Je.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Je.setUint16(0,31744,!1);else if(t===0)Je.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let s=t-127;s<-24?Je.setUint16(0,0):s<-14?Je.setUint16(0,(e&2147483648)>>16|1<<24+s,!1):Je.setUint16(0,(e&2147483648)>>16|s+15<<10|n>>13,!1)}}}function Nu(r,e){if(r.length-e<2)throw new Error(`${L} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,s=t&1023,o;return n===0?o=s*2**-24:n!==31?o=(s+1024)*2**(n-25):o=s===0?1/0:NaN,t&32768?-o:o}function Cg(r){Je.setFloat32(0,r,!1)}function Mu(r,e){if(r.length-e<4)throw new Error(`${L} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Uv(r){Je.setFloat64(0,r,!1)}function Lg(r,e){if(r.length-e<8)throw new Error(`${L} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}La.compareTokens=Ge.compareTokens;function V(r,e,t){throw new Error(`${L} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Ba(r){return()=>{throw new Error(`${L} ${r}`)}}var I=[];for(let r=0;r<=23;r++)I[r]=V;I[24]=Uy;I[25]=$y;I[26]=Ky;I[27]=zy;I[28]=V;I[29]=V;I[30]=V;I[31]=V;for(let r=32;r<=55;r++)I[r]=V;I[56]=Hy;I[57]=jy;I[58]=Vy;I[59]=qy;I[60]=V;I[61]=V;I[62]=V;I[63]=V;for(let r=64;r<=87;r++)I[r]=Gy;I[88]=Jy;I[89]=Qy;I[90]=Yy;I[91]=Xy;I[92]=V;I[93]=V;I[94]=V;I[95]=Ba("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)I[r]=Zy;I[120]=eg;I[121]=tg;I[122]=rg;I[123]=ng;I[124]=V;I[125]=V;I[126]=V;I[127]=Ba("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)I[r]=og;I[152]=ig;I[153]=ag;I[154]=cg;I[155]=lg;I[156]=V;I[157]=V;I[158]=V;I[159]=ug;for(let r=160;r<=183;r++)I[r]=fg;I[184]=hg;I[185]=dg;I[186]=pg;I[187]=mg;I[188]=V;I[189]=V;I[190]=V;I[191]=yg;for(let r=192;r<=215;r++)I[r]=gg;I[216]=wg;I[217]=bg;I[218]=xg;I[219]=kg;I[220]=V;I[221]=V;I[222]=V;I[223]=V;for(let r=224;r<=243;r++)I[r]=Ba("simple values are not supported");I[244]=V;I[245]=V;I[246]=V;I[247]=Sg;I[248]=Ba("simple values are not supported");I[249]=Eg;I[250]=Tg;I[251]=_g;I[252]=V;I[253]=V;I[254]=V;I[255]=vg;var ct=[];for(let r=0;r<24;r++)ct[r]=new v(w.uint,r,1);for(let r=-1;r>=-24;r--)ct[31-r]=new v(w.negint,r,1);ct[64]=new v(w.bytes,new Uint8Array(0),1);ct[96]=new v(w.string,"",1);ct[128]=new v(w.array,0,1);ct[160]=new v(w.map,0,1);ct[244]=new v(w.false,!1,1);ct[245]=new v(w.true,!0,1);ct[246]=new v(w.null,null,1);function Pa(r){switch(r.type){case w.false:return Et([244]);case w.true:return Et([245]);case w.null:return Et([246]);case w.bytes:return r.value.length?void 0:Et([64]);case w.string:return r.value===""?Et([96]):void 0;case w.array:return r.value===0?Et([128]):void 0;case w.map:return r.value===0?Et([160]):void 0;case w.uint:return r.value<24?Et([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return Et([31-Number(r.value)])}}var Kv={float64:!1,mapSorter:Hv,quickEncodeToken:Pa};function Ru(){let r=[];return r[w.uint.major]=Ge,r[w.negint.major]=Ta,r[w.bytes.major]=Zn,r[w.string.major]=sg,r[w.array.major]=Aa,r[w.map.major]=Ia,r[w.tag.major]=Ca,r[w.float.major]=La,r}var Bg=Ru(),Ou=new mo,Da=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${zt} object contains circular references`);return new r(t,e)}},ur={null:new v(w.null,null),undefined:new v(w.undefined,void 0),true:new v(w.true,!0),false:new v(w.false,!1),emptyArray:new v(w.array,0),emptyMap:new v(w.map,0)},fr={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new v(w.float,r):r>=0?new v(w.uint,r):new v(w.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new v(w.uint,r):new v(w.negint,r)},Uint8Array(r,e,t,n){return new v(w.bytes,r)},string(r,e,t,n){return new v(w.string,r)},boolean(r,e,t,n){return r?ur.true:ur.false},null(r,e,t,n){return ur.null},undefined(r,e,t,n){return ur.undefined},ArrayBuffer(r,e,t,n){return new v(w.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new v(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[ur.emptyArray,new v(w.break)]:ur.emptyArray;n=Da.createCheck(n,r);let s=[],o=0;for(let i of r)s[o++]=bo(i,t,n);return t.addBreakTokens?[new v(w.array,r.length),s,new v(w.break)]:[new v(w.array,r.length),s]},Object(r,e,t,n){let s=e!=="Object",o=s?r.keys():Object.keys(r),i=s?r.size:o.length;if(!i)return t.addBreakTokens===!0?[ur.emptyMap,new v(w.break)]:ur.emptyMap;n=Da.createCheck(n,r);let a=[],c=0;for(let l of o)a[c++]=[bo(l,t,n),bo(s?r.get(l):r[l],t,n)];return zv(a,t),t.addBreakTokens?[new v(w.map,i),a,new v(w.break)]:[new v(w.map,i),a]}};fr.Map=fr.Object;fr.Buffer=fr.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))fr[`${r}Array`]=fr.DataView;function bo(r,e={},t){let n=By(r),s=e&&e.typeEncoders&&e.typeEncoders[n]||fr[n];if(typeof s=="function"){let i=s(r,n,e,t);if(i!=null)return i}let o=fr[n];if(!o)throw new Error(`${zt} unsupported type: ${n}`);return o(r,n,e,t)}function zv(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Hv(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let s=t.type.major,o=Bg[s].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function Pg(r,e,t,n){if(Array.isArray(e))for(let s of e)Pg(r,s,t,n);else t[e.type.major](r,e,n)}function Fu(r,e,t){let n=bo(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let s=t.quickEncodeToken(n);if(s)return s;let o=e[n.type.major];if(o.encodedSize){let i=o.encodedSize(n,t),a=new mo(i);if(o(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return po(a.chunks[0])}}return Ou.reset(),Pg(Ou,n,e,t),Ou.toBytes(!0)}function hr(r,e){return e=Object.assign({},Kv,e),Fu(r,Bg,e)}var jv={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Na=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=ct[e];if(t===void 0){let n=I[e];if(!n)throw new Error(`${L} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let s=e&31;t=n(this.data,this._pos,s,this.options)}return this._pos+=t.encodedLength,t}},xo=Symbol.for("DONE"),Ma=Symbol.for("BREAK");function Vv(r,e,t){let n=[];for(let s=0;s<r.value;s++){let o=rs(e,t);if(o===Ma){if(r.value===1/0)break;throw new Error(`${L} got unexpected break to lengthed array`)}if(o===xo)throw new Error(`${L} found array but not enough entries (got ${s}, expected ${r.value})`);n[s]=o}return n}function Wv(r,e,t){let n=t.useMaps===!0,s=n?void 0:{},o=n?new Map:void 0;for(let i=0;i<r.value;i++){let a=rs(e,t);if(a===Ma){if(r.value===1/0)break;throw new Error(`${L} got unexpected break to lengthed map`)}if(a===xo)throw new Error(`${L} found map but not enough entries (got ${i} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${L} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&o.has(a)||!n&&a in s))throw new Error(`${L} found repeat map key "${a}"`);let c=rs(e,t);if(c===xo)throw new Error(`${L} found map but not enough entries (got ${i} [no value], expected ${r.value})`);n?o.set(a,c):s[a]=c}return n?o:s}function rs(r,e){if(r.done())return xo;let t=r.next();if(t.type===w.break)return Ma;if(t.type.terminal)return t.value;if(t.type===w.array)return Vv(t,r,e);if(t.type===w.map)return Wv(t,r,e);if(t.type===w.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=rs(r,e);return e.tags[t.value](n)}throw new Error(`${L} tag not supported (${t.value})`)}throw new Error("unsupported")}function Uu(r,e){if(!(r instanceof Uint8Array))throw new Error(`${L} data to decode must be a Uint8Array`);e=Object.assign({},jv,e);let t=e.tokenizer||new Na(r,e),n=rs(t,e);if(n===xo)throw new Error(`${L} did not find any content to decode`);if(n===Ma)throw new Error(`${L} got unexpected break`);return[n,r.subarray(t.pos())]}function Tt(r,e){let[t,n]=Uu(r,e);if(n.length>0)throw new Error(`${L} too many terminals, data makes no sense`);return t}var Ng=42;function Mg(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function qv(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=N.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new v(w.tag,Ng),new v(w.bytes,t)]}function Gv(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Jv(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var $u={float64:!0,typeEncoders:{Object:qv,undefined:Gv,number:Jv}},Qv={...$u,typeEncoders:{...$u.typeEncoders}};function Yv(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return N.decode(r.subarray(1))}var Oa={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Oa.tags[Ng]=Yv;var Xv={...Oa,tags:Oa.tags.slice()},Zv="dag-cbor",ko=113,Ku=r=>hr(r,$u),So=r=>Tt(Mg(r),Oa);var Hr=async(r,e,t)=>{let n=new _t(r),s=new Map(e.map(i=>[i.toString(),i]));if(s.has(t.toString()))return e;let o=!1;for(let i of e)await Og(n,t,i)&&(s.delete(i.toString()),s.set(t.toString(),t),o=!0);if(o)return[...s.values()];for(let i of e)if(await Og(n,i,t))return e;return e.concat(t)},jt=class extends Se{constructor({cid:e,value:t,bytes:n,prefix:s}){super({cid:e,value:t,bytes:n}),this.prefix=s}static create(e,t){return eE({data:e,parents:t??[]})}},_t=class{constructor(e){this._blocks=e}async get(e){let t=await this._blocks.get(e);if(!t)throw new Error(`missing block: ${e}`);return zu(t.bytes)}},eE=async r=>{let{cid:e,bytes:t}=await Jn({value:r,codec:re,hasher:Q});return new Se({cid:e,value:r,bytes:t})},zu=async r=>{let{cid:e,value:t}=await xa({bytes:r,codec:re,hasher:Q});return new Se({cid:e,value:t,bytes:r})},Og=async(r,e,t)=>{if(e.toString()===t.toString())return!0;let[{value:n},{value:s}]=await Promise.all([r.get(e),r.get(t)]),o=[...n.parents],i=new Set;for(;o.length;){let a=o.shift();if(!a)break;if(a.toString()===t.toString())return!0;if(s.parents.some(l=>a.toString()===l.toString())||i.has(a.toString()))continue;i.add(a.toString());let{value:c}=await r.get(a);o.push(...c.parents)}return!1},Hu=async function*(r,e,t={}){let n=t.renderNodeLabel??(c=>tE(c.cid)),s=new _t(r);yield"digraph clock {",yield' node [shape=point fontname="Courier"]; head;';let o=await Promise.all(e.map(c=>s.get(c))),i=[],a=new Set;for(let c of o){a.add(c.cid.toString()),yield` node [shape=oval fontname="Courier"]; ${c.cid} [label="${n(c)}"];`,yield` head -> ${c.cid};`;for(let l of c.value.parents)yield` ${c.cid} -> ${l};`;i.push(...c.value.parents)}for(;i.length;){let c=i.shift();if(!c)break;if(a.has(c.toString()))continue;a.add(c.toString());let l=await s.get(c);yield` node [shape=oval]; ${c} [label="${n(l)}" fontname="Courier"];`;for(let u of l.value.parents)yield` ${c} -> ${u};`;i.push(...l.value.parents)}yield"}"},tE=r=>`${String(r).slice(0,4)}..${String(r).slice(-4)}`;var vo="ascii",rE=4096,dr=class extends Se{constructor({cid:e,value:t,bytes:n}){super({cid:e,value:t,bytes:n})}static create(e){return It(Fg(e))}},Fg=r=>({entries:[],...Vt(r)}),Vt=r=>({version:1,keyChars:r?.keyChars??vo,maxKeySize:r?.maxKeySize??rE,prefix:r?.prefix??""}),At=(r,e)=>({...Fg(e),entries:r}),Ug=new WeakMap,It=async r=>{let{cid:e,bytes:t}=await Jn({value:r,codec:re,hasher:Q}),n=new dr({cid:e,value:r,bytes:t});return Ug.set(n.bytes,n),n},nE=async r=>{let e=Ug.get(r);if(e)return e;let{cid:t,value:n}=await xa({bytes:r,codec:re,hasher:Q});if(!sE(n))throw new Error(`invalid shard: ${t}`);return new dr({cid:t,value:n,bytes:r})},sE=r=>r!=null&&typeof r=="object"&&Array.isArray(r.entries)&&r.version===1&&typeof r.maxKeySize=="number"&&typeof r.keyChars=="string"&&typeof r.prefix=="string",ju=r=>Cy(r)&&r.code===ko,Qe=class{constructor(e){this._blocks=e}async get(e){let t=await this._blocks.get(e);if(!t)throw new Error(`missing block: ${e}`);return nE(t.bytes)}},pr=(r,e)=>{let t=[];for(let[n,s]of r.entries()){let[o,i]=s;if(e[0]===o){Array.isArray(e[1])?Array.isArray(i)&&i[1]!=null&&e[1][1]==null?t.push([o,[e[1][0],i[1]]]):t.push(e):Array.isArray(i)?t.push([o,[i[0],e[1]]]):t.push(e);for(let a=n+1;a<r.length;a++)t.push(r[a]);return t}if(n===0&&e[0]<o){t.push(e);for(let a=n;a<r.length;a++)t.push(r[a]);return t}if(n>0&&e[0]>r[n-1][0]&&e[0]<o){t.push(e);for(let a=n;a<r.length;a++)t.push(r[a]);return t}t.push(s)}return t.push(e),t},Ra=r=>/^[\x20-\x7E]*$/.test(r);var Eo=async(r,e,t,n)=>{let s=new Qe(r),o=await s.get(e);if(o.value.keyChars!==vo)throw new Error(`unsupported key character set: ${o.value.keyChars}`);if(!Ra(t))throw new Error("key contains non-ASCII characters");if(new TextEncoder().encode(t).length>o.value.maxKeySize)throw new Error(`UTF-8 encoded key exceeds max size of ${o.value.maxKeySize} bytes`);let i=await Fa(s,o,t),a=i[i.length-1],c=t.slice(a.value.prefix.length),l=[c,n],u=[...a.value.entries],f=[];for(let[m,d]of u.entries()){let[y,g]=d;if(y===c)break;let b=y.length<c.length?y:c,x=b===y?c:y,k="";for(let S of b){let T=k+S;if(!x.startsWith(T))break;k=T}if(k.length){let S=[];k!==c&&(S=pr(S,[c.slice(k.length),n])),k!==y&&(S=pr(S,[y.slice(k.length),g]));let T=await It(At(S,{...a.value,prefix:a.value.prefix+k}));f.push(T);let E=[...k];for(let _=E.length-1;_>0;_--){let W={...a.value,prefix:a.value.prefix+E.slice(0,_).join("")},le;if(_===E.length-1&&k===y){if(Array.isArray(g))throw new Error("found a shard link when expecting a value");le=[T.cid,g]}else _===E.length-1&&k===c?le=[T.cid,n]:le=[T.cid];let Te=await It(At([[E[_],le]],W));f.push(Te),T=Te}if(u.splice(m,1),E.length===1&&k===y){if(Array.isArray(g))throw new Error("found a shard link when expecting a value");l=[E[0],[T.cid,g]]}else E.length===1&&k===c?l=[E[0],[T.cid,n]]:l=[E[0],[T.cid]];break}}let p=At(pr(u,l),a.value),h=await It(p);if(h.cid.toString()===a.cid.toString())return{root:e,additions:[],removals:[]};f.push(h);for(let m=i.length-2;m>=0;m--){let d=i[m],y=h.value.prefix.slice(d.value.prefix.length),g=At(d.value.entries.map(b=>{let[x,k]=b;if(x!==y)return b;if(!Array.isArray(k))throw new Error(`"${y}" is not a shard link in: ${d.cid}`);return k[1]==null?[x,[h.cid]]:[x,[h.cid,k[1]]]}),d.value);h=await It(g),f.push(h)}return{root:f[f.length-1].cid,additions:f,removals:i}},$g=async(r,e,t)=>{let n=new Qe(r),s=await n.get(e),o=await Fa(n,s,t),i=o[o.length-1],a=t.slice(i.value.prefix.length),c=i.value.entries.find(([l])=>l===a);if(c)return Array.isArray(c[1])?c[1][1]:c[1]},Wu=async(r,e,t)=>{let n=new Qe(r),s=await n.get(e),o=await Fa(n,s,t),i=o[o.length-1],a=t.slice(i.value.prefix.length),c=i.value.entries.findIndex(([m])=>m===a);if(c===-1)return{root:e,additions:[],removals:[]};let l=i.value.entries[c];if(Array.isArray(l[1])&&l[1][1]==null)return{root:e,additions:[],removals:[]};let u=[],f=[...o],p=At([...i.value.entries],i.value);if(Array.isArray(l[1]))p.entries[c]=[l[0],[l[1][0]]];else for(p.entries.splice(c,1);!p.entries.length;){let m=o[o.length-1],d=o[o.length-2];if(!d)break;o.pop(),p=At(d.value.entries.filter(y=>Array.isArray(y[1])?y[1][0].toString()!==m.cid.toString():!0),d.value)}let h=await It(p);u.push(h);for(let m=o.length-2;m>=0;m--){let d=o[m],y=h.value.prefix.slice(d.value.prefix.length),g=At(d.value.entries.map(b=>{let[x,k]=b;if(x!==y)return b;if(!Array.isArray(k))throw new Error(`"${y}" is not a shard link in: ${d.cid}`);return k[1]==null?[x,[h.cid]]:[x,[h.cid,k[1]]]}),d.value);h=await It(g),u.push(h)}return{root:u[u.length-1].cid,additions:u,removals:f}},oE=r=>{let e=r??{};return"prefix"in e&&!!e.prefix},iE=r=>{let e=r??{};return"gt"in e&&!!e.gt||"gte"in e&&!!e.gte||"lt"in e&&!!e.lt||"lte"in e&&!!e.lte},aE=r=>"gt"in r&&!!r.gt||"gte"in r&&!!r.gte,cE=r=>"gte"in r&&!!r.gte,lE=r=>"gt"in r&&!!r.gt,uE=r=>"lt"in r&&!!r.lt||"lte"in r&&!!r.lte,fE=r=>"lte"in r&&!!r.lte,hE=r=>"lt"in r&&!!r.lt,Kg=async function*(r,e,t){let n=oE(t),s=iE(t),o=s&&aE(t),i=o&&cE(t),a=o&&lE(t),c=s&&uE(t),l=c&&fE(t),u=c&&hE(t),f=o&&c,p=new Qe(r),h=await p.get(e);yield*async function*m(d){for(let y of d.value.entries){let g=d.value.prefix+y[0];if(Array.isArray(y[1])){if(y[1][1]&&(n&&g.startsWith(t.prefix)||f&&(a&&g>t.gt||i&&g>=t.gte)&&(u&&g<t.lt||l&&g<=t.lte)||a&&g>t.gt||i&&g>=t.gte||u&&g<t.lt||l&&g<=t.lte||!n&&!s)&&(yield[g,y[1][1]]),n){if(t.prefix.length<=g.length&&!g.startsWith(t.prefix)||t.prefix.length>g.length&&!t.prefix.startsWith(g))continue}else if(a&&mr(g,Math.min(g.length,t.gt.length))<mr(t.gt,Math.min(g.length,t.gt.length))||i&&mr(g,Math.min(g.length,t.gte.length))<mr(t.gte,Math.min(g.length,t.gte.length))||u&&mr(g,Math.min(g.length,t.lt.length))>mr(t.lt,Math.min(g.length,t.lt.length))||l&&mr(g,Math.min(g.length,t.lte.length))>mr(t.lte,Math.min(g.length,t.lte.length)))continue;yield*m(await p.get(y[1][0]))}else(n&&g.startsWith(t.prefix)||s&&f&&(a&&g>t.gt||i&&g>=t.gte)&&(u&&g<t.lt||l&&g<=t.lte)||s&&!f&&(a&&g>t.gt||i&&g>=t.gte||u&&g<t.lt||l&&g<=t.lte)||!n&&!s)&&(yield[g,y[1]])}}(h)},mr=(r,e)=>r.length<=e?r:r.slice(0,e),Fa=async(r,e,t)=>{for(let[n,s]of e.value.entries){if(t===n)return[e];if(t.startsWith(n)&&Array.isArray(s)){let o=await Fa(r,await r.get(s[0]),t.slice(n.length));return[e,...o]}}return[e]};var Ye=class{#e=new Map;constructor(e){e&&(this.#e=new Map(e.map(t=>[t.cid.toString(),t.bytes])))}async get(e){let t=this.#e.get(e.toString());if(t)return{cid:e,bytes:t}}async put(e,t){this.#e.set(e.toString(),t)}putSync(e,t){this.#e.set(e.toString(),t)}async delete(e){this.#e.delete(e.toString())}deleteSync(e){this.#e.delete(e.toString())}*entries(){for(let[e,t]of this.#e)yield{cid:Sa(e),bytes:t}}},Ct=class{#e;constructor(...e){this.#e=e}async get(e){for(let t of this.#e){let n=await t.get(e);if(n)return n}}};var Ua=r=>({base:r?.base,entries:[...r?.entries??[]],...Vt(r)});var qu=class r{#e=!1;constructor({blocks:e,entries:t,prefix:n,version:s,keyChars:o,maxKeySize:i,base:a}){this.blocks=e,this.prefix=n,this.entries=[...t],this.base=a,this.version=s,this.keyChars=o,this.maxKeySize=i}async put(e,t){if(this.#e)throw new jr;return Qu(this.blocks,this,e,t)}async commit(){if(this.#e)throw new jr;return this.#e=!0,$a(this)}static async create({blocks:e,link:t}){let s=await new Qe(e).get(t);return new r({blocks:e,base:s,...s.value})}},Qu=async(r,e,t,n)=>{if(e.keyChars!==vo)throw new Error(`unsupported key character set: ${e.keyChars}`);if(!Ra(t))throw new Error("key contains non-ASCII characters");if(new TextEncoder().encode(t).length>e.maxKeySize)throw new Error(`UTF-8 encoded key exceeds max size of ${e.maxKeySize} bytes`);let s=new Qe(r),o=await Gu(s,e,t);o.shard!==e&&(e=o.shard,t=o.key);let i=[o.key,n],a=[...o.shard.entries];for(let[c,l]of a.entries()){let[u,f]=l;if(u===o.key)break;let p=u.length<o.key.length?u:o.key,h=p===u?o.key:u,m="";for(let d of p){let y=m+d;if(!h.startsWith(y))break;m=y}if(m.length){let d=[];m!==o.key&&(d=pr(d,[o.key.slice(m.length),n])),m!==u&&(d=pr(d,Ju([u.slice(m.length),f])));let y=Ua({...Vt(o.shard),prefix:o.shard.prefix+m,entries:d}),g=[...m];for(let b=g.length-1;b>0;b--){let x;if(b===g.length-1&&m===u){if(Array.isArray(f))throw new Error("found a shard link when expecting a value");x=[y,f]}else b===g.length-1&&m===o.key?x=[y,n]:x=[y];y=Ua({...Vt(o.shard),prefix:o.shard.prefix+g.slice(0,b).join(""),entries:[[g[b],x]]})}if(a.splice(c,1),g.length===1&&m===u){if(Array.isArray(f))throw new Error("found a shard link when expecting a value");i=[g[0],[y,f]]}else g.length===1&&m===o.key?i=[g[0],[y,n]]:i=[g[0],[y]];break}}e.entries=pr(mE(a),Ju(i))},Gu=async(r,e,t)=>{for(let n=0;n<e.entries.length;n++){let[s,o]=e.entries[n];if(t<=s)break;if(t.startsWith(s)&&Array.isArray(o)){if(ju(o[0])){let i=await r.get(o[0]),a=Ua({base:i,...i.value});return e.entries[n]=[s,o[1]==null?[a]:[a,o[1]]],Gu(r,a,t.slice(s.length))}return Gu(r,o[0],t.slice(s.length))}}return{shard:e,key:t}},$a=async r=>{let e=[],t=[],n=[];for(let o of r.entries)if(Array.isArray(o[1])&&!ju(o[1][0])){let i=await $a(o[1][0]);n.push([o[0],o[1][1]==null?[i.root]:[i.root,o[1][1]]]),e.push(...i.additions),t.push(...i.removals)}else n.push(Ju(o));let s=await It(At(n,r));return e.push(s),r.base&&r.base.cid.toString()===s.cid.toString()?{root:s.cid,additions:[],removals:[]}:(r.base&&t.push(r.base),{root:s.cid,additions:e,removals:t})},mE=r=>r,Ju=r=>r,Yu=(r,e)=>qu.create({blocks:r,link:e}),jr=class r extends Error{constructor(e,t){super(e??"batch already committed",t),this.code=r.code}static code="ERR_BATCH_COMMITTED"};var Hg=async(r,e,t,n)=>{let s=new Ye;if(r=new Ct(s,r),!e.length){let d=await dr.create();s.putSync(d.cid,d.bytes);let y=await Eo(r,d.cid,t,n),g={type:"put",root:y.root,key:t,value:n},b=await jt.create(g,e);return e=await Hr(r,e,b.cid),{root:y.root,additions:[d,...y.additions],removals:y.removals,head:e,event:b}}let o=new _t(r),i=await Xu(o,e);if(!i)throw new Error("failed to find common ancestor event");let a=await o.get(i),{root:c}=a.value.data,l=await Wg(o,e,i),u=new Map,f=new Map;for(let{value:d}of l){let y;if(d.data.type==="put")y=await Eo(r,c,d.data.key,d.data.value);else if(d.data.type==="del")y=await Wu(r,c,d.data.key);else if(d.data.type==="batch"){let g=await Yu(r,c);for(let b of d.data.ops){if(b.type!=="put")throw new Error(`unsupported batch operation: ${b.type}`);await g.put(b.key,b.value)}y=await g.commit()}else throw new Error(`unknown operation: ${d.data.type}`);c=y.root;for(let g of y.additions)s.putSync(g.cid,g.bytes),u.set(g.cid.toString(),g);for(let g of y.removals)f.set(g.cid.toString(),g)}let p=await Eo(r,c,t,n);if(p.root.toString()===c.toString())return{root:c,additions:[],removals:[],head:e};for(let d of p.additions)s.putSync(d.cid,d.bytes),u.set(d.cid.toString(),d);for(let d of p.removals)f.set(d.cid.toString(),d);let h={type:"put",root:p.root,key:t,value:n},m=await jt.create(h,e);s.putSync(m.cid,m.bytes),e=await Hr(r,e,m.cid);for(let d of f.keys())u.has(d)&&(u.delete(d),f.delete(d));return{root:p.root,additions:[...u.values()],removals:[...f.values()],head:e,event:m}};var yr=async(r,e)=>{if(!e.length)throw new Error("cannot determine root of headless clock");let t=new Ye;r=new Ct(t,r);let n=new _t(r);if(e.length===1){let u=await n.get(e[0]),{root:f}=u.value.data;return{root:f,additions:[],removals:[]}}let s=await Xu(n,e);if(!s)throw new Error("failed to find common ancestor event");let o=await n.get(s),{root:i}=o.value.data,a=await Wg(n,e,s),c=new Map,l=new Map;for(let{value:u}of a){let f;if(u.data.type==="put")f=await Eo(r,i,u.data.key,u.data.value);else if(u.data.type==="del")f=await Wu(r,i,u.data.key);else if(u.data.type==="batch"){let p=await Yu(r,i);for(let h of u.data.ops){if(h.type!=="put")throw new Error(`unsupported batch operation: ${h.type}`);await p.put(h.key,h.value)}f=await p.commit()}else throw new Error(`unknown operation: ${u.data.type}`);i=f.root;for(let p of f.additions)t.putSync(p.cid,p.bytes),c.set(p.cid.toString(),p);for(let p of f.removals)l.set(p.cid.toString(),p)}for(let u of l.keys())c.has(u)&&(c.delete(u),l.delete(u));return{root:i,additions:[...c.values()],removals:[...l.values()]}},jg=async(r,e,t)=>{if(!e.length)return;let n=await yr(r,e);return n.additions.length&&(r=new Ct(new Ye(n.additions),r)),$g(r,n.root,t)},Vg=async function*(r,e,t){if(!e.length)return;let n=await yr(r,e);n.additions.length&&(r=new Ct(new Ye(n.additions),r)),yield*Kg(r,n.root,t)},Xu=async(r,e)=>{if(!e.length)return;let t=e.map(n=>[n]);for(;;){let n=!1;for(let s of t){let o=await yE(r,s[s.length-1]);if(!o)continue;n=!0,s.push(o);let i=gE(t);if(i)return i}if(!n)return}},yE=async(r,e)=>{let{value:t}=await r.get(e);return t.parents.length?t.parents.length===1?t.parents[0]:Xu(r,t.parents):e},gE=r=>{r=r.map(e=>[...e]);for(let e of r)for(let t of e){let n=!0;for(let s of r)if(e!==s&&(n=s.some(o=>String(o)===String(t)),!n))break;if(n)return t}},Wg=async(r,e,t)=>{if(e.length===1&&e[0].toString()===t.toString())return[];let n=new Map,s=await Promise.all(e.map(i=>qg(r,i,t)));for(let i of s)for(let{event:a,depth:c}of i){let l=n.get(a.cid.toString());l?l.weight+=c:n.set(a.cid.toString(),{event:a,weight:c})}let o=new Map;for(let{event:i,weight:a}of n.values()){let c=o.get(a);c?c.push(i):o.set(a,[i])}return Array.from(o).sort((i,a)=>a[0]-i[0]).flatMap(([,i])=>i.sort((a,c)=>String(a.cid)<String(c.cid)?-1:1))},qg=async(r,e,t,n=0)=>{let s=await r.get(e),o=[{event:s,depth:n}],{parents:i}=s.value;if(i.length===1&&String(i[0])===String(t))return o;let a=await Promise.all(i.map(c=>qg(r,c,t,n+1)));return o.concat(...a)};var Zu=class r{#e=!1;constructor({blocks:e,head:t,entries:n,prefix:s,version:o,keyChars:i,maxKeySize:a,base:c,additions:l,removals:u}){this.blocks=e,this.head=t,this.prefix=s,this.entries=[...n],this.base=c,this.version=o,this.keyChars=i,this.maxKeySize=a,this.additions=l,this.removals=u,this.ops=[]}async put(e,t){if(this.#e)throw new jr;await Qu(this.blocks,this,e,t),this.ops.push({type:"put",key:e,value:t})}async commit(){if(this.#e)throw new jr;this.#e=!0;let e=await $a(this),t={type:"batch",ops:this.ops,root:e.root},n=await jt.create(t,this.head),s=new Ye,o=new Ct(s,this.blocks);s.putSync(n.cid,n.bytes);let i=await Hr(o,this.head,n.cid),a=new Map,c=new Map;for(let l of this.additions)a.set(l.cid.toString(),l);for(let l of this.removals)c.set(l.cid.toString(),l);for(let l of e.additions)c.has(l.cid.toString())&&c.delete(l.cid.toString()),a.set(l.cid.toString(),l);for(let l of e.removals)a.has(l.cid.toString())?a.delete(l.cid.toString()):c.set(l.cid.toString(),l);return{head:i,event:n,root:e.root,additions:[...a.values()],removals:[...c.values()]}}static async create({blocks:e,head:t}){let n=new Ye;if(e=new Ct(n,e),!t.length){let l=await dr.create();return n.putSync(l.cid,l.bytes),new r({blocks:e,head:t,entries:[],base:l,additions:[l],removals:[],...Vt(l.value)})}let{root:s,additions:o,removals:i}=await yr(e,t);for(let l of o)n.putSync(l.cid,l.bytes);let c=await new Qe(e).get(s);return new r({blocks:e,head:t,entries:c.value.entries,base:c,additions:o,removals:i,...Vt(c.value)})}},Gg=(r,e)=>Zu.create({blocks:r,head:e});var Jc={};K(Jc,{BaseBlockstore:()=>Es,CarTransaction:()=>et,CompactionFetcher:()=>ci,ConnectionBase:()=>Gc,EncryptedBlockstore:()=>ai,FragmentGateway:()=>pi,Loader:()=>Ts,addCryptoKeyToGatewayMetaPayload:()=>mk,ensureStart:()=>qc,getGatewayFromURL:()=>Lr,parseCarFile:()=>ii,registerStoreProtocol:()=>$d,setCryptoKeyFromGatewayMetaPayload:()=>pk,testStoreFactory:()=>GI,toCIDBlock:()=>Jg,toStoreRuntime:()=>ed});function Jg(r){return r}ae();var zh={};K(zh,{decodeFile:()=>Kh,encodeFile:()=>$h});var ls={};K(ls,{DEFAULT_DIRECTORY_MODE:()=>cb,DEFAULT_FILE_MODE:()=>ab,NodeType:()=>O,code:()=>as,createAdvancedFile:()=>zE,createComplexFile:()=>jE,createDirectoryShard:()=>hb,createEmptyFile:()=>$E,createFileChunk:()=>KE,createFileShard:()=>HE,createFlatDirectory:()=>Ja,createRaw:()=>lb,createShardedDirectory:()=>fb,createSimpleFile:()=>ub,createSymlink:()=>pb,cumulativeContentByteLength:()=>Bt,cumulativeDagByteLength:()=>cs,decode:()=>gb,decodeMetadata:()=>qr,encode:()=>yb,encodeAdvancedFile:()=>vf,encodeComplexFile:()=>Ef,encodeDirectory:()=>Xa,encodeDirectoryMetadata:()=>If,encodeFile:()=>db,encodeFileChunk:()=>Sf,encodeFileShard:()=>VE,encodeHAMTShard:()=>Tf,encodeLink:()=>Qa,encodeMetadata:()=>Lo,encodeMode:()=>bb,encodeRaw:()=>kf,encodeSimpleFile:()=>Ya,encodeSymlink:()=>mb,filesize:()=>JE,matchFile:()=>GE,name:()=>xf});var xE=new TextDecoder;function ef(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let s=r[e++];if(t+=n<28?(s&127)<<n:(s&127)*2**n,s<128)break}return[t,e]}function Ka(r,e){let t;[t,e]=ef(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function Qg(r,e){let t;return[t,e]=ef(r,e),[t&7,t>>3,e]}function kE(r){let e={},t=r.length,n=0;for(;n<t;){let s,o;if([s,o,n]=Qg(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Ka(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Ka(r,n),e.Name=xE.decode(i)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(s!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Tsize`);[e.Tsize,n]=ef(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Yg(r){let e=r.length,t=0,n,s=!1,o;for(;t<e;){let a,c;if([a,c,t]=Qg(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=Ka(r,t),n&&(s=!0)}else if(c===2){if(s)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Ka(r,t),n.push(kE(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let i={};return o&&(i.Data=o),i.Links=n||[],i}var Zg=new TextEncoder,Xg=2**32,SE=2**31;function vE(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=To(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=Zg.encode(r.Name);t-=n.length,e.set(n,t),t=To(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=To(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function ew(r){let e=TE(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=To(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let s=r.Links.length-1;s>=0;s--){let o=vE(r.Links[s],t.subarray(0,n));n-=o,n=To(t,n,o)-1,t[n]=18}return t}function EE(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+ns(t)}if(typeof r.Name=="string"){let t=Zg.encode(r.Name).length;e+=1+t+ns(t)}return typeof r.Tsize=="number"&&(e+=1+ns(r.Tsize)),e}function TE(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+ns(t)}if(r.Links)for(let t of r.Links){let n=EE(t);e+=1+n+ns(n)}return e}function To(r,e,t){e-=ns(t);let n=e;for(;t>=SE;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function ns(r){return r%2===0&&r++,Math.floor((_E(r)+6)/7)}function _E(r){let e=0;return r>=Xg&&(r=Math.floor(r/Xg),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+AE[r]}var AE=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var IE=["Data","Links"],CE=["Hash","Name","Tsize"],tf=new TextEncoder;function rw(r,e){if(r===e)return 0;let t=r.Name?tf.encode(r.Name):[],n=e.Name?tf.encode(e.Name):[],s=t.length,o=n.length;for(let i=0,a=Math.min(s,o);i<a;++i)if(t[i]!==n[i]){s=t[i],o=n[i];break}return s<o?-1:o<s?1:0}function tw(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function LE(r){if(typeof r.asCID=="object"){let t=N.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=N.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=N.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=N.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function rf(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=tf.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(LE),e.Links.sort(rw);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function nw(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!tw(r,IE))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!tw(t,CE))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&rw(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}var nf=112;function sw(r){nw(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),ew(e)}function ow(r){let e=Yg(r),t={};return e.Data&&(t.Data=e.Data),e.Links&&(t.Links=e.Links.map(n=>{let s={};try{s.Hash=N.decode(n.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return n.Name!==void 0&&(s.Name=n.Name),n.Tsize!==void 0&&(s.Tsize=n.Tsize),s})),t}var Wt=mt(nb(),1),os=Wt.default.Reader,wf=Wt.default.Writer,D=Wt.default.util,pe=Wt.default.roots.unixfs||(Wt.default.roots.unixfs={}),is=pe.Data=(()=>{function r(e){if(this.blocksizes=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)e[t[n]]!=null&&(this[t[n]]=e[t[n]])}return r.prototype.Type=0,r.prototype.Data=D.newBuffer([]),r.prototype.filesize=D.Long?D.Long.fromBits(0,0,!0):0,r.prototype.blocksizes=D.emptyArray,r.prototype.hashType=D.Long?D.Long.fromBits(0,0,!0):0,r.prototype.fanout=D.Long?D.Long.fromBits(0,0,!0):0,r.prototype.mode=0,r.prototype.mtime=null,r.encode=function(t,n){if(n||(n=wf.create()),n.uint32(8).int32(t.Type),t.Data!=null&&Object.hasOwnProperty.call(t,"Data")&&n.uint32(18).bytes(t.Data),t.filesize!=null&&Object.hasOwnProperty.call(t,"filesize")&&n.uint32(24).uint64(t.filesize),t.blocksizes!=null&&t.blocksizes.length)for(var s=0;s<t.blocksizes.length;++s)n.uint32(32).uint64(t.blocksizes[s]);return t.hashType!=null&&Object.hasOwnProperty.call(t,"hashType")&&n.uint32(40).uint64(t.hashType),t.fanout!=null&&Object.hasOwnProperty.call(t,"fanout")&&n.uint32(48).uint64(t.fanout),t.mode!=null&&Object.hasOwnProperty.call(t,"mode")&&n.uint32(56).uint32(t.mode),t.mtime!=null&&Object.hasOwnProperty.call(t,"mtime")&&pe.UnixTime.encode(t.mtime,n.uint32(66).fork()).ldelim(),n},r.decode=function(t,n){t instanceof os||(t=os.create(t));for(var s=n===void 0?t.len:t.pos+n,o=new pe.Data;t.pos<s;){var i=t.uint32();switch(i>>>3){case 1:o.Type=t.int32();break;case 2:o.Data=t.bytes();break;case 3:o.filesize=t.uint64();break;case 4:if(o.blocksizes&&o.blocksizes.length||(o.blocksizes=[]),(i&7)===2)for(var a=t.uint32()+t.pos;t.pos<a;)o.blocksizes.push(t.uint64());else o.blocksizes.push(t.uint64());break;case 5:o.hashType=t.uint64();break;case 6:o.fanout=t.uint64();break;case 7:o.mode=t.uint32();break;case 8:o.mtime=pe.UnixTime.decode(t,t.uint32());break;default:t.skipType(i&7);break}}if(!o.hasOwnProperty("Type"))throw D.ProtocolError("missing required 'Type'",{instance:o});return o},r.fromObject=function(t){if(t instanceof pe.Data)return t;var n=new pe.Data;switch(t.Type){case"Raw":case 0:n.Type=0;break;case"Directory":case 1:n.Type=1;break;case"File":case 2:n.Type=2;break;case"Metadata":case 3:n.Type=3;break;case"Symlink":case 4:n.Type=4;break;case"HAMTShard":case 5:n.Type=5;break}if(t.Data!=null&&(typeof t.Data=="string"?D.base64.decode(t.Data,n.Data=D.newBuffer(D.base64.length(t.Data)),0):t.Data.length&&(n.Data=t.Data)),t.filesize!=null&&(D.Long?(n.filesize=D.Long.fromValue(t.filesize)).unsigned=!0:typeof t.filesize=="string"?n.filesize=parseInt(t.filesize,10):typeof t.filesize=="number"?n.filesize=t.filesize:typeof t.filesize=="object"&&(n.filesize=new D.LongBits(t.filesize.low>>>0,t.filesize.high>>>0).toNumber(!0))),t.blocksizes){if(!Array.isArray(t.blocksizes))throw TypeError(".Data.blocksizes: array expected");n.blocksizes=[];for(var s=0;s<t.blocksizes.length;++s)D.Long?(n.blocksizes[s]=D.Long.fromValue(t.blocksizes[s])).unsigned=!0:typeof t.blocksizes[s]=="string"?n.blocksizes[s]=parseInt(t.blocksizes[s],10):typeof t.blocksizes[s]=="number"?n.blocksizes[s]=t.blocksizes[s]:typeof t.blocksizes[s]=="object"&&(n.blocksizes[s]=new D.LongBits(t.blocksizes[s].low>>>0,t.blocksizes[s].high>>>0).toNumber(!0))}if(t.hashType!=null&&(D.Long?(n.hashType=D.Long.fromValue(t.hashType)).unsigned=!0:typeof t.hashType=="string"?n.hashType=parseInt(t.hashType,10):typeof t.hashType=="number"?n.hashType=t.hashType:typeof t.hashType=="object"&&(n.hashType=new D.LongBits(t.hashType.low>>>0,t.hashType.high>>>0).toNumber(!0))),t.fanout!=null&&(D.Long?(n.fanout=D.Long.fromValue(t.fanout)).unsigned=!0:typeof t.fanout=="string"?n.fanout=parseInt(t.fanout,10):typeof t.fanout=="number"?n.fanout=t.fanout:typeof t.fanout=="object"&&(n.fanout=new D.LongBits(t.fanout.low>>>0,t.fanout.high>>>0).toNumber(!0))),t.mode!=null&&(n.mode=t.mode>>>0),t.mtime!=null){if(typeof t.mtime!="object")throw TypeError(".Data.mtime: object expected");n.mtime=pe.UnixTime.fromObject(t.mtime)}return n},r.toObject=function(t,n){n||(n={});var s={};if((n.arrays||n.defaults)&&(s.blocksizes=[]),n.defaults){if(s.Type=n.enums===String?"Raw":0,n.bytes===String?s.Data="":(s.Data=[],n.bytes!==Array&&(s.Data=D.newBuffer(s.Data))),D.Long){var o=new D.Long(0,0,!0);s.filesize=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else s.filesize=n.longs===String?"0":0;if(D.Long){var o=new D.Long(0,0,!0);s.hashType=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else s.hashType=n.longs===String?"0":0;if(D.Long){var o=new D.Long(0,0,!0);s.fanout=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else s.fanout=n.longs===String?"0":0;s.mode=0,s.mtime=null}if(t.Type!=null&&t.hasOwnProperty("Type")&&(s.Type=n.enums===String?pe.Data.DataType[t.Type]:t.Type),t.Data!=null&&t.hasOwnProperty("Data")&&(s.Data=n.bytes===String?D.base64.encode(t.Data,0,t.Data.length):n.bytes===Array?Array.prototype.slice.call(t.Data):t.Data),t.filesize!=null&&t.hasOwnProperty("filesize")&&(typeof t.filesize=="number"?s.filesize=n.longs===String?String(t.filesize):t.filesize:s.filesize=n.longs===String?D.Long.prototype.toString.call(t.filesize):n.longs===Number?new D.LongBits(t.filesize.low>>>0,t.filesize.high>>>0).toNumber(!0):t.filesize),t.blocksizes&&t.blocksizes.length){s.blocksizes=[];for(var i=0;i<t.blocksizes.length;++i)typeof t.blocksizes[i]=="number"?s.blocksizes[i]=n.longs===String?String(t.blocksizes[i]):t.blocksizes[i]:s.blocksizes[i]=n.longs===String?D.Long.prototype.toString.call(t.blocksizes[i]):n.longs===Number?new D.LongBits(t.blocksizes[i].low>>>0,t.blocksizes[i].high>>>0).toNumber(!0):t.blocksizes[i]}return t.hashType!=null&&t.hasOwnProperty("hashType")&&(typeof t.hashType=="number"?s.hashType=n.longs===String?String(t.hashType):t.hashType:s.hashType=n.longs===String?D.Long.prototype.toString.call(t.hashType):n.longs===Number?new D.LongBits(t.hashType.low>>>0,t.hashType.high>>>0).toNumber(!0):t.hashType),t.fanout!=null&&t.hasOwnProperty("fanout")&&(typeof t.fanout=="number"?s.fanout=n.longs===String?String(t.fanout):t.fanout:s.fanout=n.longs===String?D.Long.prototype.toString.call(t.fanout):n.longs===Number?new D.LongBits(t.fanout.low>>>0,t.fanout.high>>>0).toNumber(!0):t.fanout),t.mode!=null&&t.hasOwnProperty("mode")&&(s.mode=t.mode),t.mtime!=null&&t.hasOwnProperty("mtime")&&(s.mtime=pe.UnixTime.toObject(t.mtime,n)),s},r.prototype.toJSON=function(){return this.constructor.toObject(this,Wt.default.util.toJSONOptions)},r.DataType=function(){let e={},t=Object.create(e);return t[e[0]="Raw"]=0,t[e[1]="Directory"]=1,t[e[2]="File"]=2,t[e[3]="Metadata"]=3,t[e[4]="Symlink"]=4,t[e[5]="HAMTShard"]=5,t}(),r})(),T8=pe.UnixTime=(()=>{function r(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)e[t[n]]!=null&&(this[t[n]]=e[t[n]])}return r.prototype.Seconds=D.Long?D.Long.fromBits(0,0,!1):0,r.prototype.FractionalNanoseconds=0,r.encode=function(t,n){return n||(n=wf.create()),n.uint32(8).int64(t.Seconds),t.FractionalNanoseconds!=null&&Object.hasOwnProperty.call(t,"FractionalNanoseconds")&&n.uint32(21).fixed32(t.FractionalNanoseconds),n},r.decode=function(t,n){t instanceof os||(t=os.create(t));for(var s=n===void 0?t.len:t.pos+n,o=new pe.UnixTime;t.pos<s;){var i=t.uint32();switch(i>>>3){case 1:o.Seconds=t.int64();break;case 2:o.FractionalNanoseconds=t.fixed32();break;default:t.skipType(i&7);break}}if(!o.hasOwnProperty("Seconds"))throw D.ProtocolError("missing required 'Seconds'",{instance:o});return o},r.fromObject=function(t){if(t instanceof pe.UnixTime)return t;var n=new pe.UnixTime;return t.Seconds!=null&&(D.Long?(n.Seconds=D.Long.fromValue(t.Seconds)).unsigned=!1:typeof t.Seconds=="string"?n.Seconds=parseInt(t.Seconds,10):typeof t.Seconds=="number"?n.Seconds=t.Seconds:typeof t.Seconds=="object"&&(n.Seconds=new D.LongBits(t.Seconds.low>>>0,t.Seconds.high>>>0).toNumber())),t.FractionalNanoseconds!=null&&(n.FractionalNanoseconds=t.FractionalNanoseconds>>>0),n},r.toObject=function(t,n){n||(n={});var s={};if(n.defaults){if(D.Long){var o=new D.Long(0,0,!1);s.Seconds=n.longs===String?o.toString():n.longs===Number?o.toNumber():o}else s.Seconds=n.longs===String?"0":0;s.FractionalNanoseconds=0}return t.Seconds!=null&&t.hasOwnProperty("Seconds")&&(typeof t.Seconds=="number"?s.Seconds=n.longs===String?String(t.Seconds):t.Seconds:s.Seconds=n.longs===String?D.Long.prototype.toString.call(t.Seconds):n.longs===Number?new D.LongBits(t.Seconds.low>>>0,t.Seconds.high>>>0).toNumber():t.Seconds),t.FractionalNanoseconds!=null&&t.hasOwnProperty("FractionalNanoseconds")&&(s.FractionalNanoseconds=t.FractionalNanoseconds),s},r.prototype.toJSON=function(){return this.constructor.toObject(this,Wt.default.util.toJSONOptions)},r})(),_8=pe.Metadata=(()=>{function r(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)e[t[n]]!=null&&(this[t[n]]=e[t[n]])}return r.prototype.MimeType="",r.encode=function(t,n){return n||(n=wf.create()),t.MimeType!=null&&Object.hasOwnProperty.call(t,"MimeType")&&n.uint32(10).string(t.MimeType),n},r.decode=function(t,n){t instanceof os||(t=os.create(t));for(var s=n===void 0?t.len:t.pos+n,o=new pe.Metadata;t.pos<s;){var i=t.uint32();switch(i>>>3){case 1:o.MimeType=t.string();break;default:t.skipType(i&7);break}}return o},r.fromObject=function(t){if(t instanceof pe.Metadata)return t;var n=new pe.Metadata;return t.MimeType!=null&&(n.MimeType=String(t.MimeType)),n},r.toObject=function(t,n){n||(n={});var s={};return n.defaults&&(s.MimeType=""),t.MimeType!=null&&t.hasOwnProperty("MimeType")&&(s.MimeType=t.MimeType),s},r.prototype.toJSON=function(){return this.constructor.toObject(this,Wt.default.util.toJSONOptions)},r})();var O=is.DataType;var ib=Object.freeze([]),bf=new Uint8Array(0),Re=Object.freeze({}),ab=parseInt("0644",8),cb=parseInt("0755",8),as=nf,xf="UnixFS",xr=(r,e)=>(Object(globalThis).debug&&console.log({data:r,links:e}),sw(rf({Data:is.encode(r).finish(),Links:e}))),lb=r=>({type:O.Raw,content:r}),$E=r=>ub(bf,r),ub=(r,e)=>({type:O.File,layout:"simple",content:r,metadata:qr(e)}),KE=r=>({type:O.File,layout:"simple",content:r}),zE=(r,e)=>({type:O.File,layout:"advanced",parts:r,metadata:qr(e)}),HE=r=>({type:O.File,layout:"advanced",parts:r}),jE=(r,e,t)=>({type:O.File,layout:"complex",content:r,parts:e,metadata:qr(t)}),Ja=(r,e)=>({type:O.Directory,metadata:qr(e),entries:r}),fb=(r,e,t,n,s=Re)=>({type:O.HAMTShard,bitfield:e,fanout:_f(t),hashType:Af(n),entries:r,metadata:qr(s)}),hb=(r,e,t,n)=>({type:O.HAMTShard,bitfield:e,fanout:_f(t),hashType:Af(n),entries:r}),kf=r=>xr({Type:O.Raw,Data:r.byteLength>0?r:void 0,filesize:r.byteLength,blocksizes:ib},[]),db=(r,e=!1)=>{let t=e?Re:Object(r).metadata;switch(r.layout){case"simple":return Ya(r.content,t);case"advanced":return vf(r.parts,t);case"complex":return Ef(r.content,r.parts,t);default:throw new TypeError(`File with unknown layout "${Object(r).layout}" was passed`)}},Sf=r=>Ya(r,Re),VE=r=>xr({Type:O.File,blocksizes:r.map(Co),filesize:Bt(r)},r.map(Qa)),vf=(r,e=Re)=>xr({Type:O.File,blocksizes:r.map(Co),filesize:Bt(r),...Lo(e)},r.map(Qa)),Qa=r=>({Name:"",Tsize:r.dagByteLength,Hash:r.cid}),Ya=(r,e=Re)=>xr({Type:O.File,Data:r.byteLength>0?r:void 0,filesize:r.byteLength,blocksizes:[],...Lo(e)},[]),Ef=(r,e,t=Re)=>xr({Type:O.File,Data:r,filesize:r.byteLength+Bt(e),blocksizes:e.map(Co)},e.map(Qa)),Xa=r=>xr({Type:r.type,...If(r.metadata||Re)},r.entries.map(wb)),Tf=({bitfield:r,fanout:e,hashType:t,entries:n,metadata:s=Re})=>xr({Type:O.HAMTShard,Data:r.byteLength>0?r:void 0,fanout:_f(e),hashType:Af(t),...If(s)},n.map(wb)),_f=r=>{if(Math.log2(r)%1===0)return r;throw new TypeError(`Expected hamt size to be a power of two instead got ${r}`)},Af=r=>{if(Number.isInteger(r))return r;throw new TypeError(`Expected an integer value instead got ${r}`)};var pb=(r,e=Re)=>({type:O.Symlink,content:r,metadata:qr(e)}),mb=(r,e=!1)=>{let t=e?Re:Object(r).metadata;return xr({Type:O.Symlink,Data:r.content,...Lo(t||Re)},[])},yb=(r,e=!0)=>{switch(r.type){case O.Raw:return kf(r.content);case O.File:return db(r);case O.Directory:return Xa(r);case O.HAMTShard:return Tf(r);case O.Symlink:return mb(r);default:throw new Error(`Unknown node type ${Object(r).type}`)}},gb=r=>{let e=ow(r),t=is.decode(e.Data),{Type:n,Data:s,mtime:o,mode:i,blocksizes:a,...c}=is.toObject(t,{defaults:!1,arrays:!0,longs:Number,objects:!1}),l={...i&&{mode:i},...WE(o)},u=e.Links;switch(t.Type){case O.Raw:return lb(s);case O.File:return u.length===0?new Wa(s,l):s.byteLength===0?new qa(sb(c.blocksizes,u),l):new Ga(s,sb(c.blocksizes,u),l);case O.Directory:return Ja(ob(u),l);case O.HAMTShard:return fb(ob(u),s||bf,c.fanout,c.hashType,l);case O.Symlink:return pb(s,l);default:throw new TypeError(`Unsupported node type ${t.Type}`)}},WE=r=>r==null?void 0:{mtime:{secs:r.Seconds,nsecs:r.FractionalNanoseconds||0}};var sb=(r,e)=>{let t=[],n=r.length,s=0;for(;s<n;)t.push({cid:e[s].Hash,dagByteLength:e[s].Tsize||0,contentByteLength:r[s]});return t},ob=r=>r.map(e=>({cid:e.Hash,name:e.Name||"",dagByteLength:e.Tsize||0})),Bt=r=>r.reduce((e,t)=>e+t.contentByteLength,0),cs=(r,e)=>e.reduce((t,n)=>t+n.dagByteLength,r.byteLength),Co=r=>r.contentByteLength,wb=({name:r,dagByteLength:e,cid:t})=>({Name:r,Tsize:e,Hash:t}),If=r=>Lo(r,cb),Lo=({mode:r,mtime:e},t=ab)=>({mode:r!=null?bb(r,t):void 0,mtime:e!=null?qE(e):void 0}),qr=r=>r==null?Re:{...r.mode==null?void 0:{mode:xb(r.mode)},...r.mtime==null?void 0:{mtime:r.mtime}},qE=r=>r==null?void 0:r.nsecs!==0?{Seconds:r.secs,FractionalNanoseconds:r.nsecs}:{Seconds:r.secs},bb=(r,e)=>{let t=r==null?void 0:xb(r);return t===e||t==null?void 0:t},xb=r=>r&4095|r&4294963200,GE=({content:r=bf,parts:e=ib,metadata:t=Re,...n})=>e.length===0?new Wa(r,t):r.byteLength===0?new qa(e,t):new Ga(r,e,t),Wa=class{constructor(e,t){this.content=e,this.metadata=t,this.layout="simple",this.type=O.File}get filesize(){return this.content.byteLength}encode(){return Ya(this.content,this.metadata)}},qa=class{constructor(e,t){this.parts=e,this.metadata=t}get layout(){return"advanced"}get type(){return O.File}get fileSize(){return Bt(this.parts)}get blockSizes(){return this.parts.map(Co)}encode(){return vf(this.parts,this.metadata)}},Ga=class{constructor(e,t,n){this.content=e,this.parts=t,this.metadata=n}get layout(){return"complex"}get type(){return O.File}get fileSize(){return this.content.byteLength+Bt(this.parts)}get blockSizes(){return this.parts.map(Co)}encode(){return Ef(this.content,this.parts,this.metadata)}},JE=r=>{switch(r.type){case O.Raw:case O.Symlink:return r.content.byteLength;case O.File:switch(r.layout){case"simple":return r.content.byteLength;case"advanced":return Bt(r.parts);case"complex":return r.content.byteLength+Bt(r.parts)}default:return 0}};var QE=function*(r){let e=yield*r;yield*ec(e)};function*Df(){return yield nc}var fs=function*(){yield sc};var Za=function*(r){let e=yield*Df();if(XE(r)){let t=!1,n;if(r.then(s=>{t=!1,n=s,kr(e)},s=>{t=!0,n=s,kr(e)}),yield*fs(),t)throw n;return n}else return rT(YE(e)),yield*fs(),r};function*YE(r){kr(r)}var XE=r=>r!=null&&typeof r.then=="function",ec=function*(r){yield r},tc=function*(r){let e=[];for(let t of Object.entries(r)){let[n,s]=t;s!==Do&&e.push(yield*ds(eT(s,n)))}yield*Mf(e)},rc=r=>r.length>0?ZE(r.map(QE)):Do;function*ZE(r){let e=[];for(let t of r)e.push(yield*ds(t));yield*Mf(e)}var eT=(r,e)=>r===Do?Do:r instanceof Bo?new Bo([...r.tags,e],r.source):new Bo([e],r),Bo=class{constructor(e,t){this.tags=e,this.source=t,this.controller}[Symbol.iterator](){return this.controller||(this.controller=this.source[Symbol.iterator]()),this}box(e){if(e.done)return e;switch(e.value){case sc:case nc:return e;default:{let t=e,{value:n}=t;for(let s of this.tags)n=tT(s,n);return t.value=n,t}}}next(e){return this.box(this.controller.next(e))}throw(e){return this.box(this.controller.throw(e))}return(e){return this.box(this.controller.return(e))}get[Symbol.toStringTag](){return"TaggedEffect"}},No=()=>Do;var tT=(r,e)=>({type:r,[r]:e});var nc=Symbol("current"),sc=Symbol("suspend");var qt=class r{static of(e){return e.group||us}static enqueue(e,t){e.group=t,t.stack.active.push(e)}constructor(e,t=[],n=new Set,s=new hs(t,n)){this.driver=e,this.parent=r.of(e),this.stack=s,this.id=++Eb}},Cf=class{constructor(){this.status=Po,this.stack=new hs,this.id=0}},hs=class{constructor(e=[],t=new Set){this.active=e,this.idle=t}static size({active:e,idle:t}){return e.length+t.size}},rT=r=>kr(r[Symbol.iterator]()),kr=r=>{let e=qt.of(r);for(e.stack.active.push(r),e.stack.idle.delete(r);e.parent;){let{idle:t,active:n}=e.parent.stack;if(t.has(e.driver))t.delete(e.driver),n.push(e.driver);else break;e=e.parent}if(us.status===Po)for(us.status=Tb;;)try{for(let t of Nf(us));us.status=Po;break}catch{us.stack.active.shift()}},nT=r=>kr(r),Nf=function*(r){let{active:e}=r.stack,t=e[0];for(r.stack.idle.delete(t);t;){let n=_b;e:for(;!n.done&&t===e[0];){let s=n.value;switch(s){case sc:r.stack.idle.add(t);break e;case nc:n=t.next(t);break;default:n=t.next(yield s);break}}e.shift(),t=e[0],r.stack.idle.delete(t)}};var ds=(r,e)=>new Pf(r,e),sT=(r,e)=>Sb(r,{ok:!0,value:e});var Lf=(r,e)=>Sb(r,{ok:!1,error:e});function*Sb(r,e){try{let t=r,n=e.ok?t.return(e.value):t.throw(e.error);if(!n.done)if(n.value===sc){let{idle:s}=qt.of(t).stack;s.add(t)}else kr(t)}catch{}}function*Mf(r){if(r.length===0)return;let e=yield*Df(),t=new qt(e),n=null;for(let s of r){let{result:o}=s;if(o){!o.ok&&!n&&(n=o);continue}oT(s,t)}try{if(n)throw n.error;for(;yield*Nf(t),hs.size(t.stack)>0;)yield*fs()}catch(s){for(let o of t.stack.active)yield*Lf(o,s);for(let o of t.stack.idle)yield*Lf(o,s),kr(o);throw s}}var oT=(r,e)=>{let t=qt.of(r);if(t!==e){let{active:n,idle:s}=t.stack,o=e.stack;if(r.group=e,s.has(r))s.delete(r),o.idle.add(r);else{let i=n.indexOf(r);i>=0&&(n.splice(i,1),o.active.push(r))}}};function*Of(r){r.status===Po&&(yield*r),r.result||(yield*Mf([r]));let e=r.result;if(e.ok)return e.value;throw e.error}var Bf=class{constructor(e){this.handler=e,this.result}get promise(){let{result:e}=this,t=e==null?new Promise((n,s)=>{this.handler.onsuccess=n,this.handler.onfailure=s}):e.ok?Promise.resolve(e.value):Promise.reject(e.error);return Object.defineProperty(this,"promise",{value:t}),t}then(e,t){return this.activate().promise.then(e,t)}catch(e){return this.activate().promise.catch(e)}finally(e){return this.activate().promise.finally(e)}activate(){return this}},Pf=class extends Bf{constructor(e,t=iT,n={},s=_b){super(n),this.id=++Eb,this.name=t.name||"",this.task=e,this.state=s,this.status=Po,this.result,this.handler=n,this.controller}*resume(){nT(this)}join(){return Of(this)}abort(e){return Lf(this,e)}exit(e){return sT(this,e)}get[Symbol.toStringTag](){return"Fork"}*[Symbol.iterator](){return this.activate()}activate(){return this.controller=this.task[Symbol.iterator](),this.status=Tb,kr(this),this}panic(e){this.result={ok:!1,error:e},this.status=kb;let{handler:t}=this;throw t.onfailure&&t.onfailure(e),e}step(e){if(this.state=e,e.done){this.result={ok:!0,value:e.value},this.status=kb;let{handler:t}=this;t.onsuccess&&t.onsuccess(e.value)}return e}next(e){try{return this.step(this.controller.next(e))}catch(t){return this.panic(t)}}return(e){try{return this.step(this.controller.return(e))}catch(t){return this.panic(t)}}throw(e){try{return this.step(this.controller.throw(e))}catch(t){return this.panic(t)}}},vb=function*(r,e){let t=yield*Df(),n=new qt(t);for(qt.enqueue(r[Symbol.iterator](),n);;){for(let s of Nf(n))qt.enqueue(e(s)[Symbol.iterator](),n);if(hs.size(n.stack)>0)yield*fs();else break}},Eb=0,Po="idle",Tb="active",kb="finished",_b={done:!1,value:nc},iT={},Do=function*(){}(),us=new Cf;function Rf(){}Object.defineProperties(Rf,{prototype:{value:new Proxy(Object.prototype,{get(r,e,t){return typeof e=="symbol"?Reflect.get(r,e,t):t.get(e)}})}});var Ff=()=>new Mo;var Ib=(r,e=0,t=r.byteLength)=>{let n=[],s=e<0?r.byteLength-e:e,o=t<0?r.byteLength-t:t;if(s===0&&o>=r.byteLength)return r;if(s>o||s>r.byteLength||o<=0)return Ff();let i=0,a=0;for(let c of r.segments){let l=a+c.byteLength;if(i===0){if(o<=l){let u=c.subarray(s-a,o-a);n.push(u),i=u.byteLength;break}else if(s<l){let u=s===a?c:c.subarray(s-a);n.push(u),i=u.byteLength}}else if(o<=l){let u=o===l?c:c.subarray(0,o-a);n.push(u),i+=u.byteLength;break}else n.push(c),i+=c.byteLength;a=l}return new Mo(n,r.byteOffset+s,i)},aT=(r,e)=>e.byteLength>0?(r.segments.push(e),new Mo(r.segments,r.byteOffset,r.byteLength+e.byteLength)):r,cT=(r,e)=>{if(e<r.byteLength){let t=0;for(let n of r.segments){if(e<t+n.byteLength)return n[e-t];t+=n.byteLength}}},lT=(r,e,t)=>{let n=t;for(let s of r.segments)e.set(s,n),n+=s.byteLength;return e};function*uT(r){for(let e of r.segments)yield*e}var Mo=class extends Rf{constructor(e=[],t=0,n=0){super(),this.segments=e,this.byteLength=n,this.length=n,this.byteOffset=t}[Symbol.iterator](){return uT(this)}slice(e,t){return Ib(this,e,t)}subarray(e,t){return Ib(this,e,t)}push(e){return aT(this,e)}get(e){return cT(this,e)}copyTo(e,t){return lT(this,e,t)}};var Oo=r=>{throw new Error(r)},Cb=(r,e,...t)=>Oo(String.raw(r,JSON.stringify(e),...t)),Lb=new Uint8Array(0),Bb=[];var Pb=r=>({config:r,buffer:Ff()}),Db=(r,e)=>e.byteLength>0?Mb(r.config,r.buffer.push(e),!1):{...r,chunks:Bb},Nb=r=>Mb(r.config,r.buffer,!0),Mb=(r,e,t)=>{let n=r.chunker,s=[],o=0;for(let i of n.cut(n.context,e,t))if(i>0){let a=e.subarray(o,o+i);s.push(a),o+=i}return{config:r,chunks:s,buffer:e.subarray(o)}};var Ob=()=>({mutable:!0,needs:{},nodes:{},links:{},linked:Kf});var zf=(r,e)=>{let t=ps(e,{});for(let n of r){let{ready:s,has:o,wants:i}=Fb(n.children,t.links);i.length===0?t=ps(t,{links:$f(void 0,o),linked:[{id:n.id,links:s}]}):t=ps(t,{needs:$f(n.id,i),nodes:{[n.id]:{children:n.children,count:i.length}}})}return t},Rb=(r,e,t)=>{let n=t.needs[r],s=t.nodes[n];if(s!=null)if(s.count===1){let{ready:o,has:i}=Fb(s.children,{...t.links,[r]:e});return ps(t,{needs:{[r]:void 0},links:$f(void 0,i),nodes:{[n]:void 0},linked:[{id:n,links:o}]})}else return ps(t,{needs:{[r]:void 0},links:{[r]:e},nodes:{[n]:{...s,count:s.count-1}}});else return ps(t,{links:{[r]:e}})},ps=(r,{needs:e,nodes:t,links:n,linked:s})=>{let o=r.mutable?r:{...r},i=r.mutable?pT:void 0;return e&&(o.needs=Uf(r.needs,e,i)),t&&(o.nodes=Uf(r.nodes,t,i)),n&&(o.links=Uf(r.links,n,i)),o.linked=s?dT(r.linked||Kf,s,Kf):r.linked||[],o},$f=(r,e)=>{let t={};for(let n of e)t[n]=r;return t},Uf=(r,e,t=r)=>{let n=r===t?{...r}:r;for(let s of Object.entries(e)){let[o,i]=s;i==null?delete n[o]:n[o]=i}return n};var dT=(r,e,t=r)=>{if(r===t)return[...r,...e];for(let n of e)r.push(n);return r},Fb=(r,e)=>{let t=[],n=[],s=[];for(let o of r){let i=e[o];i?(t.push(o),s.push(i)):n.push(o)}return{has:t,wants:n,ready:s}},Kf=Object.freeze([]),pT=Object.freeze({});var Ub=(r,e)=>{switch(r.type){case"write":return yT(e,r.bytes);case"link":return gT(e,r.link);case"block":return{state:e,effect:No()};case"close":return wT(e);case"end":return{state:e,effect:No()};default:return Cb`File Writer got unknown message ${r}`}},$b=(r,e,t)=>({status:"open",metadata:e,config:t,writer:r,chunker:Pb({chunker:t.chunker}),layout:t.fileLayout.open(),nodeQueue:Ob()}),yT=(r,e)=>{if(r.status==="open"){let{chunks:t,...n}=Db(r.chunker,e),{nodes:s,leaves:o,layout:i}=r.config.fileLayout.write(r.layout,t),{linked:a,...c}=zf(s,r.nodeQueue),l=[...Kb(o,r.config),...Hf(a,r.config)];return{state:{...r,chunker:n,layout:i,nodeQueue:c},effect:tc({link:rc(l)})}}else return Oo("Unable to perform write on closed file")},gT=(r,{id:e,link:t,block:n})=>{let{linked:s,...o}=Rb(e,t,r.nodeQueue),i=Hf(s,r.config),a=r.status==="closed"&&e===r.rootID?{...r,status:"linked",link:t,nodeQueue:o}:{...r,nodeQueue:o},c=r.status==="closed"&&e===r.rootID&&r.end?r.end.resume():No();return{state:a,effect:tc({link:rc(i),block:kT(r.writer,n),end:c})}},wT=r=>{if(r.status==="open"){let{chunks:e}=Nb(r.chunker),{layout:t,...n}=r.config.fileLayout.write(r.layout,e),{root:s,...o}=r.config.fileLayout.close(t,r.metadata),[i,a]=vT(s)?[[...n.nodes,...o.nodes],[...n.leaves,...o.leaves,s]]:[[...n.nodes,...o.nodes,s],[...n.leaves,...o.leaves]],{linked:c,...l}=zf(i,r.nodeQueue),u=[...Kb(a,r.config),...Hf(c,r.config)],f=ds(fs());return{state:{...r,chunker:null,layout:null,rootID:s.id,status:"closed",end:f,nodeQueue:l},effect:tc({link:rc(u),end:Of(f)})}}else return{state:r,effect:No()}},Kb=(r,e)=>r.map(t=>bT(e,t,e.fileChunkEncoder)),bT=function*({hasher:r,linker:e},{id:t,content:n},s){let o=s.encode(n?ST(n):Lb),i=yield*Za(r.digest(o)),a=e.createLink(s.code,i),c={cid:a,bytes:o},l={cid:a,contentByteLength:n?n.byteLength:0,dagByteLength:o.byteLength};return{id:t,block:c,link:l}},Hf=(r,e)=>r.map(t=>xT(e,t)),xT=function*(r,{id:e,links:t},n){let s=r.fileEncoder.encode({type:O.File,layout:"advanced",parts:t,metadata:n}),o=yield*Za(Promise.resolve(r.hasher.digest(s))),i=r.linker.createLink(r.fileEncoder.code,o),a={bytes:s,cid:i},c={cid:i,contentByteLength:Bt(t),dagByteLength:cs(s,t)};return{id:e,block:a,link:c}},kT=function*(r,e){(r.desiredSize||0)<=0&&(yield*Za(r.ready)),r.write(e)},ST=r=>r instanceof Uint8Array?r:r.copyTo(new Uint8Array(r.byteLength),0),vT=r=>r.children==null;var Vf={};K(Vf,{context:()=>TT,cut:()=>Hb,name:()=>zb,type:()=>_T,withMaxChunkSize:()=>jf});var zb="fixed",TT={maxChunkSize:262144},_T="Stateless",jf=r=>({type:"Stateless",context:{maxChunkSize:r},name:zb,cut:Hb}),Hb=({maxChunkSize:r},{byteLength:e},t)=>{let n=e/r|0,s=new Array(n).fill(r),o=t?e-n*r:0;return o>0&&s.push(o),s};var Ro=class{constructor(e,t,n){this.id=e,this.children=t,this.metadata=n}},oc=r=>({open:()=>IT({width:r}),write:CT,close:LT}),AT={width:174},IT=({width:r}=AT)=>({width:r,head:null,leafIndex:[],nodeIndex:[],lastID:0}),CT=(r,e)=>{if(e.length===0)return{layout:r,nodes:Le,leaves:Le};{let{lastID:t}=r,[n,s]=r.head?[null,(e.unshift(r.head),e)]:e.length===1&&r.leafIndex.length===0?[e[0],Le]:[null,e];if(s.length===0)return{layout:{...r,head:n},nodes:Le,leaves:Le};{let o=[...r.leafIndex],i=[];for(let a of s){let c={id:++t,content:a};i.push(c),o.push(c.id)}return o.length>r.width?Vb({...r,leafIndex:o,head:n,lastID:t},i):{layout:{...r,head:n,leafIndex:o,lastID:t},leaves:i,nodes:Le}}}},Vb=(r,e=Le,t=[],n=!1)=>{let{lastID:s}=r,o=r.nodeIndex.map(l=>[...l]),i=[...r.leafIndex],{width:a}=r;for(;i.length>a||i.length>0&&n;){jb(o,1);let l=new Ro(++s,i.splice(0,a));o[0].push(l.id),t.push(l)}let c=0;for(;c<o.length;){let l=o[c];for(c++;l.length>a||l.length>0&&n&&c<o.length;){let u=new Ro(++s,l.splice(0,a));jb(o,c+1),o[c].push(u.id),t.push(u)}}return{layout:{...r,lastID:s,leafIndex:i,nodeIndex:o},leaves:e,nodes:t}},LT=(r,e)=>{let t=r;if(r.head)return{root:{id:1,content:r.head,metadata:e},leaves:Le,nodes:Le};if(r.leafIndex.length===0)return{root:{id:1,metadata:e},leaves:Le,nodes:Le};{let{nodes:n,layout:s}=Vb(t,Le,[],!0),{nodeIndex:o}=s,i=o.length-1,a=o[i];if(a.length===1){let c=n[n.length-1];return n.length=n.length-1,{root:c,nodes:n,leaves:Le}}else return{root:new Ro(s.lastID+1,a,e),nodes:n,leaves:Le}}},jb=(r,e)=>{for(;r.length<e;)r.push([]);return r},Le=[];var Sr=()=>({chunker:Vf,fileChunkEncoder:Wf,smallFileEncoder:Wf,fileEncoder:ls,fileLayout:oc(174),hasher:Q,linker:{createLink:N.createV1}}),vr=r=>({...Sr(),...r}),Wf={code:as,name:xf,encode:Sf};var Fo=({writer:r,metadata:e={},settings:t=Sr()})=>new qf($b(r,e,vr(t))),Wb=async(r,e)=>(await Gb(r,ec({type:"write",bytes:e})),r),qb=async(r,{releaseLock:e=!1,closeWriter:t=!1}={})=>{await Gb(r,ec({type:"close"}));let{state:n}=r;if(n.status==="linked")return t?await r.state.writer.close():e&&r.state.writer.releaseLock(),n.link;Oo(`Expected writer to be in 'linked' state after close, but it is in "${n.status}" instead`)},Gb=(r,e)=>ds(vb(e,t=>{let{state:n,effect:s}=Ub(t,r.state);return r.state=n,s})),qf=class{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.config}write(e){return Wb(this,e)}close(e){return qb(this,e)}};var PT=Sr,Jf=({writer:r,settings:e=PT(),metadata:t={}})=>new ic({writer:r,metadata:t,settings:e,entries:new Map,closed:!1}),ac=(r,e,t,{overwrite:n=!1}={})=>{let s=Qf(r.state);if(e.includes("/"))throw new Error(`Directory entry name "${e}" contains forbidden "/" character`);if(!n&&s.entries.has(e))throw new Error(`Directory already contains entry with name "${e}"`);return s.entries.set(e,t),r},cc=(r,e)=>(Qf(r.state).entries.delete(e),r),Qf=r=>{if(r.closed)throw new Error("Can not change written directory, but you can .fork() and make changes to it");return r},Jb=async(r,{closeWriter:e=!1,releaseLock:t=!1}={})=>{let{writer:n,settings:s,metadata:o}=Qf(r.state);r.state.closed=!0;let i=[...Qb(r)],a=Ja(i,o),c=Xa(a),l=await s.hasher.digest(c),u=s.linker.createLink(as,l);return(n.desiredSize||0)<=0&&await n.ready,n.write({cid:u,bytes:c}),e?await n.close():t&&n.releaseLock(),{cid:u,dagByteLength:cs(c,i)}},Qb=function*({state:r}){for(let[e,{dagByteLength:t,cid:n}]of r.entries)yield{name:e,dagByteLength:t,cid:n}},Yb=({state:r},{writer:e=r.writer,metadata:t=r.metadata,settings:n=r.settings}={})=>new ic({writer:e,metadata:t,settings:n,entries:new Map(r.entries.entries()),closed:!1}),ic=class{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.settings}links(){return Qb(this)}set(e,t,n){return ac(this,e,t,n)}remove(e){return cc(this,e)}fork(e){return Yb(this,e)}close(e){return Jb(this,e)}entries(){return this.state.entries.entries()}has(e){return this.state.entries.has(e)}get size(){return this.state.entries.size}};var t0=mt(Yf(),1),X8=new TextEncoder,Z8=t0.default.x64.hash126;var uc=mt(Yf(),1);function MT(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var sR=Kr({name:"murmur3-32",code:35,encode:r=>MT(uc.default.x86.hash32(r))}),s0=Kr({name:"murmur3-128",code:34,encode:r=>Kt.fromHex(uc.default.x64.hash128(r))}),fc=Kr({name:"murmur3-x64-64",code:34,encode:r=>Kt.fromHex(uc.default.x64.hash128(r)).subarray(0,8)});var aR=new TextEncoder;var o0=(r,e,t)=>{let n=e/8|0,s=e%8,o=t,i=0;for(;o>0&&n<r.byteLength;){let a=r[n],c=8-s,l=c<o?c:o,u=8-s-l,p=(255>>s&a)>>u;i=(i<<l)+p,o-=l,n++,s=0}return i};var xR=new RangeError("Not Found");var FT=new TextEncoder,UT=r=>fc.encode(r),a0=({bitWidth:r=8,hash:e=UT})=>{let t=e(new Uint8Array).byteLength,n={bitWidth:r,hash:e,hashSize:t};return{at:(i,a)=>$T(i,a,n),from:i=>FT.encode(i),size:1/0}},$T=(r,e=0,{bitWidth:t=8,hash:n,hashSize:s})=>{let o=s*8,i=0,a=t,c=t*e;for(;a>0;){let l=c/o>>0,u=n(l===0?r:KT(r,l)),f=o<=c?c%o:c,p=o-f,h=p<a?p:a;i=(i<<h)+o0(u,f,h),a-=h,c+=h}return i},KT=(r,e)=>{let t=new Uint8Array(r.byteLength+1).fill(e,r.byteLength);return t.set(r),t};var c0=8,BR={bitWidth:c0,Path:a0({bitWidth:c0})};var l0=({writable:r,settings:e=Sr()})=>new Xf({writer:r.getWriter(),settings:e}),jT=async(r,{releaseLock:e=!0,closeWriter:t=!0}={})=>(t?await r.writer.close():e&&r.writer.releaseLock(),r),Xf=class{constructor({writer:e,settings:t}){this.writer=e,this.settings=vr(t)}createFileWriter({settings:e=this.settings,metadata:t}={}){return Fo({writer:this.writer,settings:e,metadata:t})}createDirectoryWriter({settings:e=this.settings,metadata:t}={}){return Jf({writer:this.writer,settings:e,metadata:t})}close(e){return jT(this,e)}},VT=1048576,WT=VT*100,u0=(r=WT)=>({highWaterMark:r,size:e=>e.bytes.length});var Gr={};K(Gr,{code:()=>$o,decode:()=>QT,encode:()=>JT,name:()=>GT});ar();var GT="raw",$o=85;function JT(r){return qe(r)}function QT(r){return qe(r)}function YT(r){return r[Symbol.asyncIterator]!=null}function XT(r){if(YT(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var f0=XT;var hc=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(e="Bad path"){super(e)}},Ze=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not found"){super(e)}},dc=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(e="No resolver"){super(e)}},ce=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(e="Not UnixFS"){super(e)}},pc=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(e="Over read"){super(e)}},mc=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(e="Under read"){super(e)}},yc=class r extends Error{static name="NoPropError";static code="ERR_NO_PROP";name=r.name;code=r.code;constructor(e="No Property found"){super(e)}},Jr=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};var Zf=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===w.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===w.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[w.uint.major](e,t){this.prefix(e);let n=String(t.value),s=[];for(let o=0;o<n.length;o++)s[o]=n.charCodeAt(o);e.push(s)}[w.negint.major](e,t){this[w.uint.major](e,t)}[w.bytes.major](e,t){throw new Error(`${zt} unsupported type: Uint8Array`)}[w.string.major](e,t){this.prefix(e);let n=Ea(JSON.stringify(t.value));e.push(n.length>32?po(n):n)}[w.array.major](e,t){this.prefix(e),this.inRecursive.push({type:w.array,elements:0}),e.push([91])}[w.map.major](e,t){this.prefix(e),this.inRecursive.push({type:w.map,elements:0}),e.push([123])}[w.tag.major](e,t){}[w.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(i.type===w.array)e.push([93]);else if(i.type===w.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${zt} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),s=[],o=!1;for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i),!o&&(s[i]===46||s[i]===101||s[i]===69)&&(o=!0);o||(s.push(46),s.push(48)),e.push(s)}};function ZT(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${zt} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==w.string||n.type!==w.string)throw new Error(`${zt} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${zt} unexpected duplicate map keys, this is not supported`)}var e_={addBreakTokens:!0,mapSorter:ZT};function eh(r,e){return e=Object.assign({},e_,e),Fu(r,new Zf,e)}var ms=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${L} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${L} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,s=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new v(w.uint,0,this._pos-e);if(s([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${L} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${L} unexpected token at position ${this._pos}`);n=!0,this._pos++,s([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,s([48,49,50,51,52,53,54,55,56,57]));let o=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(o);return n?new v(w.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new v(i>=0?w.uint:w.negint,i,this._pos-e):new v(i>=0?w.uint:w.negint,BigInt(o),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${L} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let o=this._pos,i=0;o<this.data.length&&i<65536;o++,i++){let a=this.data[o];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,o));return this._pos=o+1,new v(w.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${L} unexpected end of unicode escape sequence at position ${this._pos}`);let o=0;for(let i=0;i<4;i++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${L} unexpected unicode escape character at position ${this._pos}`);o=o*16+a,this._pos++}return o},s=()=>{let o=this.ch(),i=null,a=o>239?4:o>223?3:o>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${L} unexpected unicode sequence at position ${this._pos}`);let c,l,u,f;switch(a){case 1:o<128&&(i=o);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(o&31)<<6|c&63,f>127&&(i=f));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(f=(o&15)<<12|(c&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(i=f));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(f=(o&15)<<18|(c&63)<<12|(l&63)<<6|u&63,f>65535&&f<1114112&&(i=f))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let o=this.ch(),i;switch(o){case 92:if(this._pos++,this.done())throw new Error(`${L} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${L} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new v(w.string,Bu(t),this._pos-e);default:if(o<32)throw new Error(`${L} invalid control character at position ${this._pos}`);o<128?(t.push(o),this._pos++):s()}}throw new Error(`${L} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new v(w.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new v(w.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new v(w.null,null,4);case 102:return this.expect([102,97,108,115,101]),new v(w.false,!1,5);case 116:return this.expect([116,114,117,101]),new v(w.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${L} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new v(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${L} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new v(w.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new v(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${L} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new v(w.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${L} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${L} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function th(r,e){return e=Object.assign({tokenizer:new ms(r,e)},e),Tt(r,e)}var rh={};K(rh,{base64:()=>gc,base64pad:()=>wc,base64url:()=>r_,base64urlpad:()=>n_});it();var gc=te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),wc=te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),r_=te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),n_=te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function s_(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function o_(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=N.asCID(r);if(!e)return null;let t=e.toString();return[new v(w.map,1/0,1),new v(w.string,"/",1),new v(w.string,t,t.length),new v(w.break,void 0,1)]}function bc(r){let e=gc.encode(r).slice(1);return[new v(w.map,1/0,1),new v(w.string,"/",1),new v(w.map,1/0,1),new v(w.string,"bytes",5),new v(w.string,e,e.length),new v(w.break,void 0,1),new v(w.break,void 0,1)]}function ht(r){return bc(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function i_(r){return bc(new Uint8Array(r))}function a_(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function c_(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var l_={typeEncoders:{Object:o_,Buffer:bc,Uint8Array:bc,Int8Array:ht,Uint16Array:ht,Int16Array:ht,Uint32Array:ht,Int32Array:ht,Float32Array:ht,Float64Array:ht,Uint8ClampedArray:ht,BigInt64Array:ht,BigUint64Array:ht,DataView:ht,ArrayBuffer:i_,undefined:a_,number:c_}},nh=class extends ms{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===w.map){let t=this._next();if(t.type===w.string&&t.value==="/"){let n=this._next();if(n.type===w.string){if(this._next().type!==w.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new v(w.tag,42,0)}if(n.type===w.map){let s=this._next();if(s.type===w.string&&s.value==="bytes"){let o=this._next();if(o.type===w.string){for(let a=0;a<2;a++)if(this._next().type!==w.break)throw new Error("Invalid encoded Bytes form");let i=gc.decode(`m${o.value}`);return new v(w.bytes,i,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(s)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},sh={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};sh.tags[42]=N.parse;var h0=297,u_=r=>eh(r,l_),oh=r=>{let e=s_(r),t=Object.assign(sh,{tokenizer:new nh(e,sh)});return th(e,t)},xc=r=>f_.decode(u_(r));var f_=new TextDecoder,kc=r=>oh(h_.encode(r)),h_=new TextEncoder;var d_=new TextDecoder;function ih(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let s=r[e++];if(t+=n<28?(s&127)<<n:(s&127)*2**n,s<128)break}return[t,e]}function Sc(r,e){let t;[t,e]=ih(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function p0(r,e){let t;return[t,e]=ih(r,e),[t&7,t>>3,e]}function p_(r){let e={},t=r.length,n=0;for(;n<t;){let s,o;if([s,o,n]=p0(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Sc(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Sc(r,n),e.Name=d_.decode(i)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(s!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Tsize`);[e.Tsize,n]=ih(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function m0(r){let e=r.length,t=0,n,s=!1,o;for(;t<e;){let a,c;if([a,c,t]=p0(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=Sc(r,t),n&&(s=!0)}else if(c===2){if(s)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Sc(r,t),n.push(p_(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let i={};return o&&(i.Data=o),i.Links=n||[],i}var SF=new TextEncoder,vF=2**32,EF=2**31;var AF=new TextEncoder;function y0(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var vc=112;function Er(r){let e=y0(r),t=m0(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(s=>{let o={};try{o.Hash=N.decode(s.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return s.Name!==void 0&&(o.Name=s.Name),s.Tsize!==void 0&&(o.Tsize=s.Tsize),o})),n}var FF=new TextEncoder,m_=new TextDecoder;var w0=512;function b0(r){return JSON.parse(m_.decode(r))}var lh={};K(lh,{identity:()=>ch});ar();var x0=0,y_="identity",k0=qe;function g_(r){return Fr(x0,k0(r))}var ch={code:x0,name:y_,encode:k0,digest:g_};function ys(r,e,t,n,s,o,i){let a=r,c=s;for(;o.length>0;){let l=o[0];if(l in a){o.shift(),c=`${c}/${l}`;let u=N.asCID(a[l]);if(u!=null)return{entry:{type:"object",name:n,path:s,cid:t,node:e,depth:i,size:BigInt(e.length),content:async function*(){yield r}},next:{cid:u,name:l,path:c,toResolve:o}};a=a[l]}else throw new yc(`No property named ${l} found in node ${t}`)}return{entry:{type:"object",name:n,path:s,cid:t,node:e,depth:i,size:BigInt(e.length),content:async function*(){yield r}}}}var w_=async(r,e,t,n,s,o,i,a)=>{let c=await i.get(r,a),l=So(c);return ys(l,c,r,e,t,n,o)},S0=w_;var b_=async(r,e,t,n,s,o,i,a)=>{let c=await i.get(r,a),l=oh(c);return ys(l,c,r,e,t,n,o)},v0=b_;var ve=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function x_(r,e,t,n){let s=BigInt(r.length),o=BigInt(e+s);return t>=o||n<e?new Uint8Array(0):(n>=e&&n<o&&(r=r.subarray(0,Number(n-e))),t>=e&&t<o&&(r=r.subarray(Number(t-e))),r)}var Qr=x_;var k_=(r,e=0,t=r)=>{let n=BigInt(r),s=BigInt(e??0),o=BigInt(t);if(o!==n&&(o=s+o),o>n&&(o=n),s<0n)throw new Jr("Offset must be greater than or equal to 0");if(s>n)throw new Jr("Offset must be less than the file size");if(o<0n)throw new Jr("Length must be greater than or equal to 0");if(o>n)throw new Jr("Length must be less than the file size");return{start:s,end:o}},gs=k_;var S_=r=>{async function*e(t={}){let{start:n,end:s}=gs(r.length,t.offset,t.length),o=Qr(r,0n,n,s);t.onProgress?.(new ve("unixfs:exporter:progress:identity",{bytesRead:BigInt(o.byteLength),totalBytes:s-n,fileSize:BigInt(r.byteLength)})),yield o}return e},v_=async(r,e,t,n,s,o,i,a)=>{if(n.length>0)throw new Ze(`No link named ${t} found in raw node ${r}`);let c=Ur(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:S_(c.digest),depth:o,size:BigInt(c.digest.length),node:c.digest}}},E0=v_;var E_=async(r,e,t,n,s,o,i,a)=>{let c=await i.get(r,a),l=b0(c);return ys(l,c,r,e,t,n,o)},T0=E_;var T_=r=>{async function*e(t={}){let{start:n,end:s}=gs(r.length,t.offset,t.length),o=Qr(r,0n,n,s);t.onProgress?.(new ve("unixfs:exporter:progress:raw",{bytesRead:BigInt(o.byteLength),totalBytes:s-n,fileSize:BigInt(r.byteLength)})),yield o}return e},__=async(r,e,t,n,s,o,i,a)=>{if(n.length>0)throw new Ze(`No link named ${t} found in raw node ${r}`);let c=await i.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:T_(c),depth:o,size:BigInt(c.length),node:c}}},_0=__;var Lh=mt(C0(),1);var uh=new Float32Array([-0]),Tr=new Uint8Array(uh.buffer);function L0(r,e,t){uh[0]=r,e[t]=Tr[0],e[t+1]=Tr[1],e[t+2]=Tr[2],e[t+3]=Tr[3]}function B0(r,e){return Tr[0]=r[e],Tr[1]=r[e+1],Tr[2]=r[e+2],Tr[3]=r[e+3],uh[0]}var fh=new Float64Array([-0]),be=new Uint8Array(fh.buffer);function P0(r,e,t){fh[0]=r,e[t]=be[0],e[t+1]=be[1],e[t+2]=be[2],e[t+3]=be[3],e[t+4]=be[4],e[t+5]=be[5],e[t+6]=be[6],e[t+7]=be[7]}function D0(r,e){return be[0]=r[e],be[1]=r[e+1],be[2]=r[e+2],be[3]=r[e+3],be[4]=r[e+4],be[5]=r[e+5],be[6]=r[e+6],be[7]=r[e+7],fh[0]}var I_=BigInt(Number.MAX_SAFE_INTEGER),C_=BigInt(Number.MIN_SAFE_INTEGER),Be=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Yr;if(e<I_&&e>C_)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>N0&&(s=0n,++n>N0&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return Yr;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Yr}},Yr=new Be(0,0);Yr.toBigInt=function(){return 0n};Yr.zzEncode=Yr.zzDecode=function(){return this};Yr.length=function(){return 1};var N0=4294967296n;function M0(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function O0(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function hh(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function dt(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ec(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var dh=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,dt(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw dt(this,4);return Ec(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw dt(this,4);return Ec(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw dt(this,4);let e=B0(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw dt(this,4);let e=D0(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw dt(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return O0(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw dt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw dt(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Be(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw dt(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw dt(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw dt(this,8);let e=Ec(this.buf,this.pos+=4),t=Ec(this.buf,this.pos+=4);return new Be(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){return this.readLongVarint().toNumber(!0)}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ph(r){return new dh(r instanceof Uint8Array?r:r.subarray())}function Ko(r,e){let t=ph(r);return e.decode(t)}function Gt(r=0){return new Uint8Array(r)}var mh={};K(mh,{base10:()=>L_});it();var L_=cr({prefix:"9",name:"base10",alphabet:"0123456789"});var yh={};K(yh,{base16:()=>B_,base16upper:()=>P_});it();var B_=te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),P_=te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var gh={};K(gh,{base2:()=>D_});it();var D_=te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var wh={};K(wh,{base256emoji:()=>F_});it();var F0=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),N_=F0.reduce((r,e,t)=>(r[t]=e,r),[]),M_=F0.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function O_(r){return r.reduce((e,t)=>(e+=N_[t],e),"")}function R_(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=M_[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var F_=jn({prefix:"\u{1F680}",name:"base256emoji",encode:O_,decode:R_});Rr();var bh={};K(bh,{base8:()=>U_});it();var U_=te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var xh={};K(xh,{identity:()=>$_});ar();it();var $_=jn({prefix:"\0",name:"identity",encode:r=>pu(r),decode:r=>du(r)});var kh={...xh,...gh,...bh,...mh,...yh,...bu,...xu,...ku,...rh,...wh},_U={...Lu,...lh};function $0(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var U0=$0("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Sh=$0("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Gt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),K_={utf8:U0,"utf-8":U0,hex:kh.base16,latin1:Sh,ascii:Sh,binary:Sh,...kh},K0=K_;function Tc(r,e="utf8"){let t=K0[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function vh(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return Gt(i);s+i>e&&(n=Gt(e),s=0);let a=n.subarray(s,s+=i);return s&7&&(s=(s|7)+1),a}}var Xr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Eh(){}var _h=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},z_=vh();function H_(r){return globalThis.Buffer!=null?Gt(r):z_(r)}var jo=class{len;head;tail;states;constructor(){this.len=0,this.head=new Xr(Eh,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Xr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ah((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(zo,10,Be.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Be.fromBigInt(e);return this._push(zo,t.length(),t)}uint64Number(e){let t=Be.fromNumber(e);return this._push(zo,t.length(),t)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Be.fromBigInt(e).zzEncode();return this._push(zo,t.length(),t)}sint64Number(e){let t=Be.fromNumber(e).zzEncode();return this._push(zo,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Th,1,e?1:0)}fixed32(e){return this._push(Ho,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Be.fromBigInt(e);return this._push(Ho,4,t.lo)._push(Ho,4,t.hi)}fixed64Number(e){let t=Be.fromNumber(e);return this._push(Ho,4,t.lo)._push(Ho,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(L0,4,e)}double(e){return this._push(P0,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Th,1,0):this.uint32(t)._push(V_,t,e)}string(e){let t=M0(e);return t!==0?this.uint32(t)._push(hh,t,e):this._push(Th,1,0)}fork(){return this.states=new _h(this),this.head=this.tail=new Xr(Eh,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Xr(Eh,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=H_(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Th(r,e,t){e[t]=r&255}function j_(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ah=class extends Xr{next;constructor(e,t){super(j_,e,t),this.next=void 0}};function zo(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Ho(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function V_(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(jo.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(W_,e,r),this},jo.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(q_,e,r),this});function W_(r,e,t){e.set(r,t)}function q_(r,e,t){r.length<40?hh(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Tc(r),t)}function Ih(){return new jo}function Vo(r,e){let t=Ih();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var ws;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(ws||(ws={}));function _c(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Ch(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(o,i){let a=e(o);i.int32(a)},n=function(o){let i=o.int32();return e(i)};return _c("enum",ws.VARINT,t,n)}function Wo(r,e){return _c("message",ws.LENGTH_DELIMITED,r,e)}var pt;(function(r){let e;(function(s){s.Raw="Raw",s.Directory="Directory",s.File="File",s.Metadata="Metadata",s.Symlink="Symlink",s.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(s){s[s.Raw=0]="Raw",s[s.Directory=1]="Directory",s[s.File=2]="File",s[s.Metadata=3]="Metadata",s[s.Symlink=4]="Symlink",s[s.HAMTShard=5]="HAMTShard"})(t||(t={})),function(s){s.codec=()=>Ch(t)}(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=Wo((s,o,i={})=>{if(i.lengthDelimited!==!1&&o.fork(),s.Type!=null&&(o.uint32(8),r.DataType.codec().encode(s.Type,o)),s.Data!=null&&(o.uint32(18),o.bytes(s.Data)),s.filesize!=null&&(o.uint32(24),o.uint64(s.filesize)),s.blocksizes!=null)for(let a of s.blocksizes)o.uint32(32),o.uint64(a);s.hashType!=null&&(o.uint32(40),o.uint64(s.hashType)),s.fanout!=null&&(o.uint32(48),o.uint64(s.fanout)),s.mode!=null&&(o.uint32(56),o.uint32(s.mode)),s.mtime!=null&&(o.uint32(66),Ac.codec().encode(s.mtime,o)),i.lengthDelimited!==!1&&o.ldelim()},(s,o)=>{let i={blocksizes:[]},a=o==null?s.len:s.pos+o;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:i.Type=r.DataType.codec().decode(s);break;case 2:i.Data=s.bytes();break;case 3:i.filesize=s.uint64();break;case 4:i.blocksizes.push(s.uint64());break;case 5:i.hashType=s.uint64();break;case 6:i.fanout=s.uint64();break;case 7:i.mode=s.uint32();break;case 8:i.mtime=Ac.codec().decode(s,s.uint32());break;default:s.skipType(c&7);break}}return i})),n),r.encode=s=>Vo(s,r.codec()),r.decode=s=>Ko(s,r.codec())})(pt||(pt={}));var Ac;(function(r){let e;r.codec=()=>(e==null&&(e=Wo((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Seconds!=null&&(n.uint32(8),n.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(t.FractionalNanoseconds)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let i=t.uint32();switch(i>>>3){case 1:s.Seconds=t.int64();break;case 2:s.FractionalNanoseconds=t.fixed32();break;default:t.skipType(i&7);break}}return s})),e),r.encode=t=>Vo(t,r.codec()),r.decode=t=>Ko(t,r.codec())})(Ac||(Ac={}));var z0;(function(r){let e;r.codec=()=>(e==null&&(e=Wo((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.MimeType!=null&&(n.uint32(10),n.string(t.MimeType)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let i=t.uint32();switch(i>>>3){case 1:s.MimeType=t.string();break;default:t.skipType(i&7);break}}return s})),e),r.encode=t=>Vo(t,r.codec()),r.decode=t=>Ko(t,r.codec())})(z0||(z0={}));var H0={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},G_=["directory","hamt-sharded-directory"],j0=parseInt("0644",8),V0=parseInt("0755",8),Pt=class r{static unmarshal(e){let t=pt.decode(e),n=new r({type:H0[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:t,data:n,blockSizes:s,hashType:o,fanout:i,mtime:a,mode:c}=e;if(t!=null&&!Object.values(H0).includes(t))throw(0,Lh.default)(new Error("Type: "+t+" is not valid"),"ERR_INVALID_TYPE");this.type=t??"file",this.data=n,this.hashType=o,this.fanout=i,this.blockSizes=s??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?V0:j0:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return G_.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=pt.DataType.Raw;break;case"directory":e=pt.DataType.Directory;break;case"file":e=pt.DataType.File;break;case"metadata":e=pt.DataType.Metadata;break;case"symlink":e=pt.DataType.Symlink;break;case"hamt-sharded-directory":e=pt.DataType.HAMTShard;break;default:throw(0,Lh.default)(new Error(`Type: ${e} is not valid`),"ERR_INVALID_TYPE")}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===j0&&!this.isDirectory()&&(n=void 0),n===V0&&this.isDirectory()&&(n=void 0));let s;return this.mtime!=null&&(s={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),pt.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:s})}};var J0=mt(G0(),1);var Zr=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new J0.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((s,o,i)=>(o!=null&&(o instanceof r?s.push(o.serialize(e,t)):s.push(e(o,i))),s),n))}async asyncTransform(e,t){return Q0(this,e,t)}toJSON(){return this.serialize(Z_,eA)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?Tc(e):e),n=await t.take(this._options.bits),s=this._children.get(n);return s instanceof r?s._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:s}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let s=await n._findPlace(t.existingChild.hash);return s.bucket._putAt(s,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(X_);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function X_(r){return!!r}function Z_(r,e){return r.key}function eA(r){return r}async function Q0(r,e,t){let n=[];for(let s of r._children.compactArray())if(s instanceof Zr)await Q0(s,e,t);else{let o=await e(s);n.push({bitField:r._children.bitField(),children:o})}return t(n)}function Y0(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=Gt(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var tA=[255,254,252,248,240,224,192,128],rA=[1,3,7,15,31,63,127,255],Ic=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let s=this._value[this._currentBytePos],o=this._currentBitPos+1,i=Math.min(o,t),a=nA(s,o-i,i);n=(n<<i)+a,t-=i,this._currentBitPos-=i,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function nA(r,e,t){let n=sA(e,t);return(r&n)>>>e}function sA(r,e){return tA[r]&rA[Math.min(e+r-1,7)]}function X0(r){function e(t){return t instanceof Cc?t:new Cc(t,r)}return e}var Cc=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let s=this._buffers[this._currentBufferIndex],o=Math.min(s.availableBits(),t),i=s.take(o);n=(n<<o)+i,t-=o,this._availableBits-=o,s.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],s=Math.min(n.totalBits()-n.availableBits(),t);n.untake(s),t-=s,this._availableBits+=s,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?Y0([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new Ic(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Z0(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:X0(r.hashFn)};return new Zr(e)}var oA=async function(r){return(await s0.encode(r)).slice(0,8).reverse()},iA=async(r,e,t)=>{let n=(e.tableSize()-1).toString(16).length;await Promise.all(r.map(async s=>{if(s.Name==null)throw new Error("Unexpected Link without a Name");if(s.Name.length===n){let o=parseInt(s.Name,16);e._putObjectAt(o,new Zr({hash:t._options.hash,bits:t._options.bits},e,o));return}await t.put(s.Name.substring(2),!0)}))},ex=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),aA=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},tx=async(r,e,t,n,s)=>{if(n==null){if(r.Data==null)throw new ce("no data in PBNode");let f;try{f=Pt.unmarshal(r.Data)}catch(h){throw new ce(h.message)}if(f.type!=="hamt-sharded-directory")throw new ce("not a HAMT");if(f.fanout==null)throw new ce("missing fanout");let p=Z0({hashFn:oA,bits:Math.log2(Number(f.fanout))});n={rootBucket:p,hamtDepth:1,lastBucket:p}}let o=(n.lastBucket.tableSize()-1).toString(16).length;await iA(r.Links,n.lastBucket,n.rootBucket);let i=await n.rootBucket._findNewBucketAndPos(e),a=ex(i.pos,o),c=aA(i);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=ex(n.lastBucket._posAtParent,o));let l=r.Links.find(f=>{if(f.Name==null)return!1;let p=f.Name.substring(0,o),h=f.Name.substring(o);return!(p!==a||h!==""&&h!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(o)===e)return l.Hash;n.hamtDepth++;let u=await t.get(l.Hash,s);return r=Er(u),tx(r,e,t,n,s)},rx=tx;function cA(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Lc=cA;function lA(r){return r[Symbol.asyncIterator]!=null}function uA(r,e){let t=0;if(lA(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Lc(r),{value:s,done:o}=n.next();if(o===!0)return function*(){}();let i=e(s,t++);if(typeof i.then=="function")return async function*(){await i&&(yield s);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)}()}var nx=uA;function fA(r){return r[Symbol.asyncIterator]!=null}function hA(r,e){let t=0;if(fA(r))return async function*(){for await(let c of r)yield e(c,t++)}();let n=Lc(r),{value:s,done:o}=n.next();if(o===!0)return function*(){}();let i=e(s,t++);if(typeof i.then=="function")return async function*(){yield await i;for await(let c of n)yield e(c,t++)}();let a=e;return function*(){yield i;for(let c of n)yield a(c,t++)}()}var bs=hA;function xs(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Bc=globalThis.CustomEvent??Event;async function*en(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,s=new EventTarget,o=[],i=xs(),a=xs(),c=!1,l,u=!1;s.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(o.length===t&&(i=xs(),await i.promise),u)break;let d={done:!1};o.push(d),m().then(y=>{d.done=!0,d.ok=!0,d.value=y,s.dispatchEvent(new Bc("task-complete"))},y=>{d.done=!0,d.err=y,s.dispatchEvent(new Bc("task-complete"))})}c=!0,s.dispatchEvent(new Bc("task-complete"))}catch(m){l=m,s.dispatchEvent(new Bc("task-complete"))}});function f(){return n?o[0]?.done:!!o.find(m=>m.done)}function*p(){for(;o.length>0&&o[0].done;){let m=o[0];if(o.shift(),m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}function*h(){for(;f();)for(let m=0;m<o.length;m++)if(o[m].done){let d=o[m];if(o.splice(m,1),m--,d.ok)yield d.value;else throw u=!0,i.resolve(),d.err;i.resolve()}}for(;;){if(f()||(a=xs(),await a.promise),l!=null)throw l;if(n?yield*p():yield*h(),c&&o.length===0)break}}function Pc(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Dc=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},ks=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Dc(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Dc(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Bh=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ss(r={}){return dA(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function dA(r,e){e=e??{};let t=e.onEnd,n=new ks,s,o,i,a=Pc(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,g)=>{o=b=>{o=null,n.push(b);try{y(r(n))}catch(x){g(x)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Pc()})}},l=y=>o!=null?o(y):(n.push(y),s),u=y=>(n=new ks,o!=null?o({error:y}):(n.push({error:y}),s)),f=y=>{if(i)return s;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},p=y=>i?s:(i=!0,y!=null?u(y):l({done:!0})),h=()=>(n=new ks,p(),{done:!0}),m=y=>(p(y),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:f,end:p,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let b,x;g!=null&&(b=new Promise((k,S)=>{x=()=>{S(new Bh)},g.addEventListener("abort",x)}));try{await Promise.race([a.promise,b])}finally{x!=null&&g!=null&&g?.removeEventListener("abort",x)}}},t==null)return s;let d=s;return s={[Symbol.asyncIterator](){return this},next(){return d.next()},throw(y){return d.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return d.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(y){return d.end(y),t!=null&&(t(y),t=void 0),s},get readableLength(){return d.readableLength},onEmpty:y=>d.onEmpty(y)},s}function pA(r){return r[Symbol.asyncIterator]!=null}function mA(...r){let e=[];for(let t of r)pA(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Ss({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)t.push(s)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var sx=mA;function vs(r,...e){if(r==null)throw new Error("Empty pipeline");if(Ph(r)){let n=r;r=()=>n.source}else if(ix(r)||ox(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Ph(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Ph(t[n])&&(t[n]=gA(t[n]));return yA(...t)}var yA=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},ox=r=>r?.[Symbol.asyncIterator]!=null,ix=r=>r?.[Symbol.iterator]!=null,Ph=r=>r==null?!1:r.sink!=null&&r.source!=null,gA=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Ss({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(ox(o))s=async function*(){yield*o,n.end()};else if(ix(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return sx(n,s())}return r.source};var wA=(r,e,t,n,s,o,i)=>{async function*a(c={}){let l=c.offset??0,u=c.length??e.Links.length,f=e.Links.slice(l,u);c.onProgress?.(new ve("unixfs:exporter:walk:directory",{cid:r})),yield*vs(f,p=>bs(p,h=>async()=>{let m=h.Name??"",d=`${n}/${m}`;return(await s(h.Hash,m,d,[],o+1,i,c)).entry}),p=>en(p,{ordered:!0,concurrency:c.blockReadConcurrency}),p=>nx(p,h=>h!=null))}return a},ax=wA;var Nh=mt(lx(),1);var Go=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Mh=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},ux=r=>globalThis.DOMException===void 0?new Mh(r):new DOMException(r),fx=r=>{let e=r.reason===void 0?ux("This operation was aborted."):r.reason;return e instanceof Error?e:ux(e)};function Oh(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout}}=e,i,c=new Promise((l,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:p}=e;p.aborted&&u(fx(p)),p.addEventListener("abort",()=>{u(fx(p))})}if(t===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new Go;i=o.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(p){u(p)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?l():s instanceof Error?u(s):(f.message=s??`Promise timed out after ${t} milliseconds`,u(f))},t),(async()=>{try{l(await r)}catch(p){u(p)}})()}).finally(()=>{c.clear()});return c.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},c}function Rh(r,e,t){let n=0,s=r.length;for(;s>0;){let o=Math.trunc(s/2),i=n+o;t(r[i],e)<=0?(n=++i,s-=o+1):s=o}return n}var Jo=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let s=Rh(this.#e,n,(o,i)=>i.priority-o.priority);this.#e.splice(s,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var Qo=class extends Nh.default{#e;#o;#r=0;#d;#a;#p=0;#n;#c;#t;#m;#s=0;#l;#i;#y;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Jo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#o=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#d=e.intervalCap,this.#a=e.interval,this.#t=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#o||this.#r<this.#d}get#x(){return this.#s<this.#l}#k(){this.#s--,this.#u(),this.emit("next")}#S(){this.#w(),this.#g(),this.#c=void 0}get#v(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#r=this.#e?this.#s:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#S()},t)),!0}return!1}#u(){if(this.#t.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#v;if(this.#b&&this.#x){let t=this.#t.dequeue();return t?(this.emit("active"),t(),e&&this.#g(),!0):!1}}return!1}#g(){this.#o||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#a),this.#p=Date.now()+this.#a)}#w(){this.#r===0&&this.#s===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#r=this.#e?this.#s:0,this.#f()}#f(){for(;this.#u(););}get concurrency(){return this.#l}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#l=e,this.#f()}async#E(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#y,...t},new Promise((n,s)=>{this.#t.enqueue(async()=>{this.#s++,this.#r++;try{t.signal?.throwIfAborted();let o=e({signal:t.signal});t.timeout&&(o=Oh(Promise.resolve(o),{milliseconds:t.timeout})),t.signal&&(o=Promise.race([o,this.#E(t.signal)]));let i=await o;n(i),this.emit("completed",i)}catch(o){if(o instanceof Go&&!t.throwOnTimeout){n();return}s(o),this.emit("error",o)}finally{this.#k()}},t),this.emit("add"),this.#u()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#f(),this):this}pause(){this.#i=!0}clear(){this.#t=new this.#m}async onEmpty(){this.#t.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#t.size<e||await this.#h("next",()=>this.#t.size<e)}async onIdle(){this.#s===0&&this.#t.size===0||await this.#h("idle")}async#h(e,t){return new Promise(n=>{let s=()=>{t&&!t()||(this.off(e,s),n())};this.on(e,s)})}get size(){return this.#t.size}sizeBy(e){return this.#t.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#i}};async function hx(r,e,t,n,s,o,i){if(e instanceof Uint8Array){let l=Qr(e,n,s,o);t.push(l);return}if(e.Data==null)throw new ce("no data in PBNode");let a;try{a=Pt.unmarshal(e.Data)}catch(l){throw new ce(l.message)}if(a.data!=null){let l=a.data,u=Qr(l,n,s,o);t.push(u),n+=BigInt(u.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw new ce("Inconsistent block sizes and dag links");for(let l=0;l<e.Links.length;l++){let u=e.Links[l],f=n,p=f+a.blockSizes[l];if((s>=f&&s<p||o>=f&&o<=p||s<f&&o>p)&&c.push({link:u,blockStart:n}),n=p,n>o)break}await vs(c,l=>bs(l,u=>async()=>{let f=await r.get(u.link.Hash,i);return{...u,block:f}}),l=>en(l,{ordered:!0,concurrency:i.blockReadConcurrency}),async l=>{for await(let{link:u,block:f,blockStart:p}of l){let h;switch(u.Hash.code){case vc:h=Er(f);break;case $o:h=f;break;default:t.end(new ce(`Unsupported codec: ${u.Hash.code}`));return}let m=new Qo({concurrency:1});m.on("error",d=>{t.end(d)}),m.add(async()=>{i.onProgress?.(new ve("unixfs:exporter:walk:file",{cid:u.Hash})),await hx(r,h,t,p,s,o,i)}),await m.onIdle()}}),n>=o&&t.end()}var kA=(r,e,t,n,s,o,i)=>{async function*a(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:u,end:f}=gs(l,c.offset,c.length);if(f===0n)return;let p=0n,h=f-u,m=Ss();c.onProgress?.(new ve("unixfs:exporter:walk:file",{cid:r})),hx(i,e,m,0n,u,f,c).catch(d=>{m.end(d)});for await(let d of m)if(d!=null){if(p+=BigInt(d.byteLength),p>h)throw m.end(),new pc("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");p===h&&m.end(),c.onProgress?.(new ve("unixfs:exporter:progress:unixfs:file",{bytesRead:p,totalBytes:h,fileSize:l})),yield d}if(p<h)throw new mc("Traversed entire DAG but did not read enough bytes")}return a},Fh=kA;var SA=(r,e,t,n,s,o,i)=>{function a(c={}){return c.onProgress?.(new ve("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),dx(e,n,s,o,i,c)}return a};async function*dx(r,e,t,n,s,o){let i=r.Links;if(r.Data==null)throw new ce("no data in PBNode");let a;try{a=Pt.unmarshal(r.Data)}catch(u){throw new ce(u.message)}if(a.fanout==null)throw new ce("missing fanout");let c=(a.fanout-1n).toString(16).length,l=vs(i,u=>bs(u,f=>async()=>{let p=f.Name!=null?f.Name.substring(c):null;if(p!=null&&p!==""){let h=await t(f.Hash,p,`${e}/${p}`,[],n+1,s,o);return{entries:h.entry==null?[]:[h.entry]}}else{let h=await s.get(f.Hash,o);return r=Er(h),o.onProgress?.(new ve("unixfs:exporter:walk:hamt-sharded-directory",{cid:f.Hash})),{entries:dx(r,e,t,n,s,o)}}}),u=>en(u,{ordered:!0,concurrency:o.blockReadConcurrency}));for await(let{entries:u}of l)yield*u}var px=SA;var vA=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,EA={raw:Fh,file:Fh,directory:ax,"hamt-sharded-directory":px,metadata:(r,e,t,n,s,o,i)=>()=>[],symlink:(r,e,t,n,s,o,i)=>()=>[]},TA=async(r,e,t,n,s,o,i,a)=>{let c=await i.get(r,a),l=Er(c),u,f;if(e==null&&(e=r.toString()),l.Data==null)throw new ce("no data in PBNode");try{u=Pt.unmarshal(l.Data)}catch(h){throw new ce(h.message)}if(t==null&&(t=e),n.length>0){let h;if(u?.type==="hamt-sharded-directory"?h=await rx(l,n[0],i):h=vA(l,n[0]),h==null)throw new Ze("file does not exist");let m=n.shift(),d=`${t}/${m}`;f={cid:h,toResolve:n,name:m??"",path:d}}let p=EA[u.type](r,l,u,t,s,o,i);if(p==null)throw new Ze("could not find content exporter");return u.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:p,unixfs:u,depth:o,node:l,size:u.fileSize()},next:f}:{entry:{type:"file",name:e,path:t,cid:r,content:p,unixfs:u,depth:o,node:l,size:u.fileSize()},next:f}},mx=TA;var _A={[vc]:mx,[$o]:_0,[ko]:S0,[h0]:v0,[ch.code]:E0,[w0]:T0},yx=async(r,e,t,n,s,o,i)=>{let a=_A[r.code];if(a==null)throw new dc(`No resolver for code ${r.code}`);return a(r,e,t,n,yx,s,o,i)},gx=yx;var AA=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),IA=r=>{if(r instanceof Uint8Array)return{cid:N.decode(r),toResolve:[]};let e=N.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=AA(r);return{cid:N.parse(t[0]),toResolve:t.slice(1)}}throw new hc(`Unknown path type ${r}`)};async function*CA(r,e,t={}){let{cid:n,toResolve:s}=IA(r),o=n.toString(),i=o,a=s.length;for(;;){let c=await gx(n,o,i,s,a,e,t);if(c.entry==null&&c.next==null)throw new Ze(`Could not resolve ${r}`);if(c.entry!=null&&(yield c.entry),c.next==null)return;s=c.next.toResolve,n=c.next.cid,o=c.next.name,i=c.next.path}}async function wx(r,e,t={}){let n=await f0(CA(r,e,t));if(n==null)throw new Ze(`Could not resolve ${r}`);return n}var LA=u0(),BA=vr({fileChunkEncoder:Gr,smallFileEncoder:Gr,chunker:jf(1024*1024),fileLayout:oc(1024)});async function PA(r){let e=[];return await r.pipeTo(new WritableStream({write(t){e.push(t)}})),e}async function $h(r){let e=DA(r),t=await PA(e);return{cid:t.at(-1).cid,blocks:t}}async function Kh(r,e,t){let n=await wx(e.toString(),r,{length:t.size}),s=[];for await(let o of n.content())s.push(o);return new File(s,n.name,{type:t.type,lastModified:0})}function DA(r){let{readable:e,writable:t}=new TransformStream({},LA),n=l0({writable:t,settings:BA}),s=new Uh("",r);return(async()=>(await s.finalize(n),await n.close()))(),e}var Uh=class{#e;constructor(e,t){this.name=e,this.#e=t}async finalize(e){let t=Fo(e);return await this.#e.stream().pipeTo(new WritableStream({async write(n){await t.write(n)}})),await t.close()}};ae();function Hh(r){return r===!1&&r===null&&r===void 0}function me(r){if(Hh(r))throw new Error("value is Falsy");return r}function Yo(r){if(!Hh(r))return r}ye();var Gh=class{value;next;constructor(e){this.value=e}},ti=class{#e;#o;#r;constructor(){this.clear()}enqueue(e){let t=new Gh(e);this.#e?(this.#o.next=t,this.#o=t):(this.#e=t,this.#o=t),this.#r++}dequeue(){let e=this.#e;if(e)return this.#e=this.#e.next,this.#r--,e.value}peek(){if(this.#e)return this.#e.value}clear(){this.#e=void 0,this.#o=void 0,this.#r=0}get size(){return this.#r}*[Symbol.iterator](){let e=this.#e;for(;e;)yield e.value,e=e.next}};function Mc(r){xx(r);let e=new ti,t=0,n=()=>{t<r&&e.size>0&&(e.dequeue()(),t++)},s=()=>{t--,n()},o=async(c,l,u)=>{let f=(async()=>c(...u))();l(f);try{await f}catch{}s()},i=(c,l,u)=>{new Promise(f=>{e.enqueue(f)}).then(o.bind(void 0,c,l,u)),(async()=>(await Promise.resolve(),t<r&&n()))()},a=(c,...l)=>new Promise(u=>{i(c,u,l)});return Object.defineProperties(a,{activeCount:{get:()=>t},pendingCount:{get:()=>e.size},clearQueue:{value(){e.clear()}},concurrency:{get:()=>r,set(c){xx(c),r=c,queueMicrotask(()=>{for(;t<r&&e.size>0;)n()})}}}),a}function xx(r){if(!((Number.isInteger(r)||r===Number.POSITIVE_INFINITY)&&r>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up")}var Ar=mt(Yh(),1),Oc={SHA2_256:18,LENGTH:32,DAG_PB:112},Lx=40;function ri(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=Ar.default.decode(r);return e.seek(Ar.default.decode.bytes),t}function Bx(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}function Px(r){Ar.default.decode(r);let e=Ar.default.decode.bytes,t=Ar.default.decode(r.subarray(Ar.default.decode.bytes)),n=Ar.default.decode.bytes;return e+n+t}var Ir={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},ni={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Ir.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Ir.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=ni["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let s=e;s<r.length;s++){let o=r[s];if(o=ni["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:Ir.Int,CarV1HeaderOrV2Pragma:r=>{if(Ir.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let s=0;s<e.length;s++){let[o,i]=e[s];switch(o){case"roots":{let a=ni["CarV1HeaderOrV2Pragma > roots (anon)"](r[o]);if(a===void 0)return;if(a!==i||t!==r){if(t===r){t={};for(let c=0;c<s;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=ni.Int(r[o]);if(a===void 0)return;if(a!==i||t!==r){if(t===r){t={};for(let c=0;c<s;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},si={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Ir.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Ir.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=si["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let s=e;s<r.length;s++){let o=r[s];if(o=si["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:Ir.Int,CarV1HeaderOrV2Pragma:r=>{if(Ir.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let s=0;s<e.length;s++){let[o,i]=e[s];switch(o){case"roots":{let a=si["CarV1HeaderOrV2Pragma > roots (anon)"](i);if(a===void 0)return;if(a!==i||t!==r){if(t===r){t={};for(let c=0;c<s;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=si.Int(i);if(a===void 0)return;if(a!==i||t!==r){if(t===r){t={};for(let c=0;c<s;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},Dx={toTyped:ni.CarV1HeaderOrV2Pragma,toRepresentation:si.CarV1HeaderOrV2Pragma};async function Nx(r,e){let t=ri(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),s=So(n);if(Dx.toTyped(s)===void 0)throw new Error("Invalid CAR header format");if(s.version!==1&&s.version!==2||e!==void 0&&s.version!==e)throw new Error(`Invalid CAR version: ${s.version}${e!==void 0?` (expected ${e})`:""}`);if(s.version===1){if(!Array.isArray(s.roots))throw new Error("Invalid CAR header format");return s}if(s.roots!==void 0)throw new Error("Invalid CAR header format");let o=Bx(await r.exactly(Lx,!0));r.seek(o.dataOffset-r.pos);let i=await Nx(r,1);return Object.assign(i,o)}async function ZA(r){let e=await r.exactly(2,!1);if(e[0]===Oc.SHA2_256&&e[1]===Oc.LENGTH){let i=await r.exactly(34,!0),a=Ur(i);return N.create(0,Oc.DAG_PB,a)}let t=ri(await r.upTo(8),r);if(t!==1)throw new Error(`Unexpected CID version (${t})`);let n=ri(await r.upTo(8),r),s=await r.exactly(Px(await r.upTo(8)),!0),o=Ur(s);return N.create(t,n,o)}async function Mx(r){let e=r.pos,t=ri(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR section (zero length)");t+=r.pos-e;let n=await ZA(r),s=t-Number(r.pos-e);return{cid:n,length:t,blockLength:s}}async function eI(r){let{cid:e,blockLength:t}=await Mx(r);return{bytes:await r.exactly(t,!0),cid:e}}async function tI(r){let e=r.pos,{cid:t,length:n,blockLength:s}=await Mx(r),o={cid:t,length:n,blockLength:s,offset:e,blockOffset:r.pos};return r.seek(o.blockLength),o}function Ox(r){let e=(async()=>{let t=await Nx(r);if(t.version===2){let n=r.pos-t.dataOffset;r=nI(r,t.dataSize-n)}return t})();return{header:()=>e,async*blocks(){for(await e;(await r.upTo(8)).length>0;)yield await eI(r)},async*blocksIndex(){for(await e;(await r.upTo(8)).length>0;)yield await tI(r)}}}function Rx(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let s=r.subarray(e,e+t);return n&&(e+=t),s},seek(t){e+=t},get pos(){return e}}}function rI(r){let e=0,t=0,n=0,s=new Uint8Array(0),o=async i=>{t=s.length-n;let a=[s.subarray(n)];for(;t<i;){let l=await r();if(l==null)break;t<0?l.length>t&&a.push(l.subarray(-t)):a.push(l),t+=l.length}s=new Uint8Array(a.reduce((l,u)=>l+u.length,0));let c=0;for(let l of a)s.set(l,c),c+=l.length;n=0};return{async upTo(i){return s.length-n<i&&await o(i),s.subarray(n,n+Math.min(s.length-n,i))},async exactly(i,a=!1){if(s.length-n<i&&await o(i),s.length-n<i)throw new Error("Unexpected end of data");let c=s.subarray(n,n+i);return a&&(e+=i,n+=i),c},seek(i){e+=i,n+=i},get pos(){return e}}}function Fx(r){let e=r[Symbol.asyncIterator]();async function t(){let n=await e.next();return n.done?null:n.value}return rI(t)}function nI(r,e){let t=0;return{async upTo(n){let s=await r.upTo(n);return s.length+t>e&&(s=s.subarray(0,e-t)),s},async exactly(n,s=!1){let o=await r.exactly(n,s);if(o.length+t>e)throw new Error("Unexpected end of data");return s&&(t+=n),o},seek(n){t+=n,r.seek(n)},get pos(){return r.pos}}}var oi=class{constructor(e,t){this._header=e,this._blocks=t,this._keys=t.map(n=>n.cid.toString())}get version(){return this._header.version}async getRoots(){return this._header.roots}async has(e){return this._keys.indexOf(e.toString())>-1}async get(e){let t=this._keys.indexOf(e.toString());return t>-1?this._blocks[t]:void 0}async*blocks(){for(let e of this._blocks)yield e}async*cids(){for(let e of this._blocks)yield e.cid}static async fromBytes(e){if(!(e instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");return Ux(Rx(e))}static async fromIterable(e){if(!e||typeof e[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return Ux(Fx(e))}};async function Ux(r){let e=Ox(r),t=await e.header(),n=[];for await(let s of e.blocks())n.push(s);return new oi(t,n)}ae();async function ii(r,e){let t=await r.getRoots(),n=await r.get(t[0]);if(!n)throw e.Error().Msg("missing header block").AsError();let o=(await lr({bytes:n.bytes,hasher:Q,codec:re})).value;if(o&&!o.fp)throw e.Error().Msg("missing fp").AsError();return o.fp}ae();ye();var et=class extends Ye{constructor(e,t={add:!0,noLoader:!1}){super(),t.add&&e.transactions.add(this),this.parent=e}async get(e){return await this.superGet(e)||Yo(await this.parent.get(e))}async superGet(e){return super.get(e)}};function Xh(r,e,t,n){let s=H(r,t,n),o=e.store||{};return{applyMeta:(i,a)=>Promise.resolve(),compact:async i=>({}),autoCompact:100,public:!1,name:void 0,threshold:1e3*1e3,...e,logger:s,keyBag:e.keyBag||{},crypto:Hn(e.crypto),store:o,storeRuntime:ed(o,r)}}function Zh(r,e){return e.name?new ai(r,e):new Es(e)}var Es=class{constructor(e={}){this.transactions=new Set;this.sthis=Xo(e),this.ebOpts=Xh(this.sthis,e,"BaseBlockstore"),this.logger=this.ebOpts.logger}ready(){return Promise.resolve()}async close(){}async destroy(){}async compact(){}async get(e){if(!e)throw this.logger.Error().Msg("required cid").AsError();for(let t of this.transactions){let n=await t.superGet(e);if(n)return n}}async put(e,t){throw this.logger.Error().Msg("use a transaction to put").AsError()}async transaction(e,t){let n=new et(this,t),s=await e(n);return this.lastTxMeta=s,{t:n,meta:s}}openTransaction(e={add:!0,noLoader:!1}){return new et(this,e)}async commitTransaction(e,t,n){if(!this.loader)throw this.logger.Error().Msg("loader required to commit").AsError();let s=await this.loader?.commit(e,t,n);if(this.ebOpts.autoCompact&&this.loader.carLog.length>this.ebOpts.autoCompact&&setTimeout(()=>void this.compact(),10),s)return this.transactions.delete(e),{meta:t,cars:s,t:e};throw this.logger.Error().Msg("failed to commit car files").AsError()}async*entries(){let e=new Set;for(let t of this.transactions)for await(let n of t.entries())e.has(n.cid.toString())||(e.add(n.cid.toString()),yield n)}},ai=class extends Es{constructor(t,n){super(n);this.compacting=!1;this.logger=H(this.sthis,"EncryptedBlockstore");let{name:s}=n;if(!s)throw this.logger.Error().Msg("name required").AsError();this.name=s,this.loader=new Ts(this.name,n,t)}ready(){return this.loader.ready()}close(){return this.loader.close()}destroy(){return this.loader.destroy()}async get(t){let n=await super.get(t);if(n)return n;if(this.loader)return Yo(await this.loader.getBlock(t))}async transaction(t,n={noLoader:!1}){let{t:s,meta:o}=await super.transaction(t),i=await this.loader.commit(s,o,n);if(this.ebOpts.autoCompact&&this.loader.carLog.length>this.ebOpts.autoCompact&&setTimeout(()=>void this.compact(),10),i)return this.transactions.delete(s),{meta:o,cars:i,t:s};throw this.logger.Error().Msg("failed to commit car files").AsError()}async getFile(t,n){if(await this.ready(),!this.loader)throw this.logger.Error().Msg("loader required to get file, database must be named").AsError();let o=await(await this.loader.loadFileCar(t)).get(n);if(!o)throw this.logger.Error().Str("cid",n.toString()).Msg("Missing block").AsError();return o.bytes}async compact(){if(await this.ready(),!this.loader)throw this.logger.Error().Msg("loader required to compact").AsError();if(this.loader.carLog.length<2)return;let t=this.ebOpts.compact||(o=>this.defaultCompact(o,this.logger));if(!t||this.compacting)return;let n=new ci(this);this.compacting=!0;let s=await t(n);await this.loader?.commit(n.loggedBlocks,s,{compact:!0,noLoader:!0}),this.compacting=!1}async defaultCompact(t,n){if(!this.loader)throw n.Error().Msg("no loader").AsError();if(!this.lastTxMeta)throw n.Error().Msg("no lastTxMeta").AsError();for await(let s of this.loader.entries(!1))t.loggedBlocks.putSync(s.cid,s.bytes);for(let s of this.transactions)for await(let o of s.entries())t.loggedBlocks.putSync(o.cid,o.bytes);return this.lastTxMeta}async*entries(){for await(let t of this.loader.entries())yield t}},ci=class{constructor(e){this.blockstore=e,this.loggedBlocks=new et(e)}async get(e){let t=await this.blockstore.get(e);return t&&this.loggedBlocks.putSync(e,t.bytes),Yo(t)}};ae();var _s=class{constructor(){this.queue=[];this.processing=!1;this._waitIdleItems=new Set}waitIdle(){if(this.queue.length===0&&!this.processing)return Promise.resolve();let e=new Ds;return this._waitIdleItems.add(e),e.asPromise()}async enqueue(e){return new Promise((t,n)=>{let s=async()=>{try{t(await e())}catch(o){n(o)}finally{this.processing=!1,this.processNext()}};this.queue.push(s),this.processing||this.processNext()})}processNext(){if(this.queue.length>0&&!this.processing){this.processing=!0;let e=this.queue.shift();e&&e().finally(()=>{})}if(this.queue.length===0&&!this.processing){let e=Array.from(this._waitIdleItems);this._waitIdleItems.clear(),e.map(t=>t.resolve())}}};var fd={};K(fd,{KeyBag:()=>Uc,defaultKeyBagUrl:()=>tk,getKeyBag:()=>Fe,registerKeyBagProviderFactory:()=>mI});ae();ye();Rr();var Uc=class{constructor(e){this.rt=e;this._warnOnce=new X;this._seq=new ll;this.logger=H(e.sthis,"KeyBag"),this.logger.Debug().Msg("KeyBag created")}async subtleKey(e){let t=this.rt.url.getParam("extractKey")==="_deprecated_internal_api";return t&&this._warnOnce.once(()=>this.logger.Warn().Msg("extractKey is enabled via _deprecated_internal_api --- handle keys safely!!!")),await this.rt.crypto.importKey("raw",J.decode(e),"AES-GCM",t,["encrypt","decrypt"])}async ensureKeyFromUrl(e,t){let n=e.getParam("storekey");if(n==="insecure")return C.Ok(e);if(!n){let s=`@${t()}@`,o=await this.getNamedKey(s);if(o.isErr())return o;let i=e.build().setParam("storekey",s);return C.Ok(i.URI())}if(n.startsWith("@")&&n.endsWith("@")){let s=await this.getNamedKey(n);if(s.isErr())return s}return C.Ok(e)}async toKeyWithFingerPrint(e){let t=J.decode(e),n=await this.subtleKey(e),s=await this.rt.crypto.digestSHA256(t);return C.Ok({key:n,fingerPrint:J.encode(new Uint8Array(s))})}async setNamedKey(e,t){return this._seq.add(()=>this._setNamedKey(e,t))}async _setNamedKey(e,t){let n={name:e,key:t},s=await this.rt.getBag();return this.logger.Debug().Str("name",e).Msg("setNamedKey"),await s.set(e,n),await this.toKeyWithFingerPrint(n.key)}async getNamedExtractableKey(e,t=!1){let n=await this.getNamedKey(e,t);if(n.isErr())return n;let s=n.Ok();return C.Ok({...s,extract:async()=>{let o=new Uint8Array(await this.rt.crypto.exportKey("raw",s.key));return{key:o,keyStr:J.encode(o)}}})}async getNamedKey(e,t=!1){let n=this.rt.sthis.nextId(4).str;return this._seq.add(async()=>{let o=await(await this.rt.getBag()).get(e);if(o){let a=await this.toKeyWithFingerPrint(o.key);return this.logger.Debug().Str("id",n).Str("name",e).Result("fpr",a).Msg("fingerPrint getNamedKey"),a}if(t)return this.logger.Debug().Str("id",n).Str("name",e).Msg("failIfNotFound getNamedKey"),C.Err(new Error(`Key not found: ${e}`));let i=await this._setNamedKey(e,J.encode(this.rt.crypto.randomBytes(this.rt.keyLength)));return this.logger.Debug().Str("id",n).Str("name",e).Result("fpr",i).Msg("createKey getNamedKey-post"),i})}},ek=new Map([{protocol:"file:",factory:async(r,e)=>{let{KeyBagProviderFile:t}=await Promise.resolve().then(()=>(jx(),Hx));return new t(r,e)}},{protocol:"indexdb:",factory:async(r,e)=>{let{KeyBagProviderIndexDB:t}=await Promise.resolve().then(()=>(Zx(),Xx));return new t(r,e)}}].map(r=>[r.protocol,r]));function mI(r){let e=r.protocol.endsWith(":")?r.protocol:r.protocol+":";ek.set(e,{...r,protocol:e})}function tk(r){let e=r.env.get("FP_KEYBAG_URL"),t;return Or().isBrowser?t=Ie.from(e||"indexdb://fp-keybag"):e?t=Ie.from(e):(e=`${r.env.get("HOME")}/.fireproof/keybag`,t=Ie.from(`file://${e}`)),H(r,"defaultKeyBagUrl").Debug().Url(t).Msg("from env"),t}function yI(r,e){if(e.keyRuntime)return e.keyRuntime;let t=H(r,"KeyBag"),n;e.url?(n=Ie.from(e.url),t.Debug().Url(n).Msg("from opts")):n=tk(r);let s=ek.get(n.protocol);if(!s)throw t.Error().Url(n).Msg("unsupported protocol").AsError();let o=async()=>s.factory(n,r);if(n.hasParam("masterkey"))throw t.Error().Url(n).Msg("masterkey is not supported").AsError();return{url:n,crypto:e.crypto||Hn({}),sthis:r,logger:t,keyLength:e.keyLength||16,getBag:o,id:()=>n.toString()}}var gI=new _e;async function Fe(r,e={}){await r.start();let t=yI(r,e);return gI.get(t.id()).once(async()=>new Uc(t))}var wI=Ru(),bI={float64:!1,quickEncodeToken:Pa};function hd(r,e=wI,t=bI){if(Array.isArray(r)){let n=0;for(let s of r)n+=hd(s,e,t);return n}else{let n=e[r.type.major];if(n.encodedSize===void 0||typeof n.encodedSize!="function")throw new Error(`Encoder for ${r.type.name} does not have an encodedSize()`);return n.encodedSize(r,t)}}var hi=mt(Yh(),1),pd=class{constructor(e,t){this.bytes=e,this.byteOffset=t,this.roots=[],this.headerSize=t}addRoot(e,t){return xI(this,e,t),this}write(e){return kI(this,e),this}close(e){return SI(this,e)}},xI=(r,e,t={})=>{let{resize:n=!1}=t,{bytes:s,headerSize:o,byteOffset:i,roots:a}=r;r.roots.push(e);let c=$c(r);if(c>o)if(c-o+i<s.byteLength)if(n)nk(r,c);else throw a.pop(),new RangeError(`Header of size ${o} has no capacity for new root ${e}.
|
146
|
-
However there is a space in the buffer and you could call addRoot(root, { resize: root }) to resize header to make a space for this root.`);else throw a.pop(),new RangeError(`Buffer has no capacity for a new root ${e}`)},di=({cid:r,bytes:e})=>{let t=r.bytes.byteLength+e.byteLength;return hi.default.encodingLength(t)+t},kI=(r,{cid:e,bytes:t})=>{let n=e.bytes.byteLength+t.byteLength,s=hi.default.encode(n);if(r.byteOffset+s.length+n>r.bytes.byteLength)throw new RangeError("Buffer has no capacity for this block");dd(r,s),dd(r,e.bytes),dd(r,t)},SI=(r,e={})=>{let{resize:t=!1}=e,{roots:n,bytes:s,byteOffset:o,headerSize:i}=r,a=Ku({version:1,roots:n}),c=hi.default.encode(a.length),l=c.length+a.byteLength;if(i-l===0)return rk(r,c,a),s.subarray(0,o);if(t)return nk(r,l),rk(r,c,a),s.subarray(0,r.byteOffset);throw new RangeError(`Header size was overestimated.
|
147
|
-
You can use close({ resize: true }) to resize header`)},nk=(r,e)=>{let{bytes:t,headerSize:n}=r;t.set(t.subarray(n,r.byteOffset),e),r.byteOffset+=e-n,r.headerSize=e},dd=(r,e)=>{r.bytes.set(e,r.byteOffset),r.byteOffset+=e.length},rk=({bytes:r},e,t)=>{r.set(e),r.set(t,e.length)},vI=[new v(w.map,2),new v(w.string,"version"),new v(w.uint,1),new v(w.string,"roots")],EI=new v(w.tag,42),TI=r=>{let e=[...vI];e.push(new v(w.array,r.length));for(let n of r)e.push(EI),e.push(new v(w.bytes,{length:n+1}));let t=hd(e);return hi.default.encodingLength(t)+t},$c=({roots:r})=>TI(r.map(e=>e.bytes.byteLength));var sk=(r,e={})=>{let{roots:t=[],byteOffset:n=0,byteLength:s=r.byteLength,headerSize:o=$c({roots:t})}=e,i=new Uint8Array(r,n,s),a=new pd(i,o);for(let c of t)a.addRoot(c);return a};async function ik(r,e,t){let n=0,s=$c({roots:r});n+=s;for(let{cid:a,bytes:c}of e.entries())n+=di({cid:a,bytes:c});let o=new Uint8Array(n),i=sk(o,{headerSize:s});for(let a of r)i.addRoot(a);for(let{cid:a,bytes:c}of e.entries())i.write({cid:a,bytes:c});return i.close(),await Qn({value:i.bytes,hasher:Q,codec:t})}async function ok(r,e,t){return ik([e],t,r)}async function ak(r,e,t,n){let{files:s}=AI(n),o=[],i=(await r.keyedCrypto()).codec(),a=await II(i,s,t);for(let c of a){let{cid:l,bytes:u}=c;await r.save({cid:l,bytes:u}),await e.enqueueFile(l),o.push(l)}return o}function AI(r){let e=[];for(let[,t]of Object.entries(r.files||{}))t&&typeof t=="object"&&"cid"in t&&t!==null&&e.push(t.cid);return{...r,files:e}}async function II(r,e,t){return[await ik(e,t,r)]}function CI(r,e,t=!1){return{...t?{cars:[],compact:e}:{cars:e,compact:[]},meta:r}}async function LI(r){return await Qn({value:{fp:r},hasher:Q,codec:re})}async function ck(r,e,t,n={noLoader:!1,compact:!1}){let s=CI(t,r.carLog,!!n.compact),o=await LI(s),i=await BI(r.encoder,r.threshold,o,e),a=[];for(let l of i){let{cid:u,bytes:f}=l;await r.carStore.save({cid:u,bytes:f}),a.push(u)}let c={cars:a};return await r.WALStore.enqueue(c,n),await r.metaStore.save(c),{cgrp:a,header:s}}async function BI(r,e,t,n){let s=[];e=e||128e3*8;let o=new et(n.parent,{add:!1,noLoader:!1});o.putSync(t.cid,t.bytes);let i=di(t),a=t;for(let{cid:c,bytes:l}of n.entries())i+=di({cid:c,bytes:l}),i>=e?(s.push(await ok(r,a.cid,o)),o=new et(n.parent,{add:!1,noLoader:!1}),o.putSync(c,l),a={cid:c,bytes:l},i=di({cid:c,bytes:l})):o.putSync(c,l);return s.push(await ok(r,a.cid,o)),s}ye();var Kc=class{constructor(e,t){this.eventsWeHandled=new Set;this.queue=[];this.isProcessing=!1;this.logger=H(e,"TaskManager"),this.callback=t}async handleEvent(e,t,n){for(let s of t)this.eventsWeHandled.add(s.toString());this.queue.push({cid:e.toString(),dbMeta:n,retries:0}),this.queue=this.queue.filter(({cid:s})=>!this.eventsWeHandled.has(s)),this.processQueue()}async processQueue(){if(this.isProcessing)return;this.isProcessing=!0;let t=this.queue.filter(({cid:n})=>!this.eventsWeHandled.has(n))[0];if(t)try{await this.callback(t.dbMeta),this.eventsWeHandled.add(t.cid),this.queue=this.queue.filter(({cid:n})=>!this.eventsWeHandled.has(n))}catch(n){throw t.retries++>3&&(this.logger.Error().Str("cid",t.cid).Msg("failed to process event block after 3 retries"),this.queue=this.queue.filter(({cid:s})=>s!==t.cid)),await new Promise(s=>setTimeout(s,50)),this.logger.Error().Err(n).Msg("failed to process event block").AsError()}finally{this.isProcessing=!1,this.queue.length>0&&this.processQueue()}}};function zc(r,e){return r.some(t=>t.toString()===e.toString())}function lk(r,e=new Set){let t=new Map;for(let n of r)e.has(n.toString())||t.set(n.toString(),n);return[...t.values()]}var Ts=class{constructor(e,t,n){this.commitQueue=new _s;this.isCompacting=!1;this.carReaders=new Map;this.seenCompacted=new Set;this.processedCars=new Set;this.carLog=[];this.getBlockCache=new Map;this.seenMeta=new Set;this.writeLimit=Mc(1);this.onceReady=new X;this.name=e,this.sthis=n,this.ebOpts=Xh(n,{...t,name:e},"Loader"),this.logger=this.ebOpts.logger,this.taskManager=new Kc(n,async s=>{await this.handleDbMetasFromStore([s])})}async keyBag(){return Fe(this.sthis,this.ebOpts.keyBag)}async carStore(){return this.ebOpts.storeRuntime.makeDataStore(this)}async fileStore(){return this.ebOpts.storeRuntime.makeDataStore(this)}async WALStore(){return this.ebOpts.storeRuntime.makeWALStore(this)}async metaStore(){return this.ebOpts.storeRuntime.makeMetaStore(this)}async ready(){return this.onceReady.once(async()=>{let e=await(await this.metaStore()).load();this.ebOpts.meta?await this.handleDbMetasFromStore([this.ebOpts.meta]):e&&await this.handleDbMetasFromStore(e)})}async close(){let e=await Promise.all([this.carStore(),this.metaStore(),this.fileStore(),this.WALStore()]);await Promise.all(e.map(t=>t.close()))}async destroy(){let e=await Promise.all([this.carStore(),this.metaStore(),this.fileStore(),this.WALStore()]);await Promise.all(e.map(t=>t.destroy()))}async handleDbMetasFromStore(e){this.logger.Debug().Any("metas",e).Msg("handleDbMetasFromStore");for(let t of e)await this.writeLimit(async()=>{await this.mergeDbMetaIntoClock(t)})}async mergeDbMetaIntoClock(e){if(this.isCompacting)throw this.logger.Error().Msg("cannot merge while compacting").AsError();if(this.seenMeta.has(e.cars.toString())||(this.seenMeta.add(e.cars.toString()),zc(this.carLog,e.cars)))return;let t=await this.loadCarHeaderFromMeta(e);t.compact.map(n=>n.toString()).forEach(this.seenCompacted.add,this.seenCompacted),await this.getMoreReaders(t.cars.flat()),this.carLog=[...lk([e.cars,...this.carLog,...t.cars],this.seenCompacted)],await this.ebOpts.applyMeta?.(t.meta)}async loadCarHeaderFromMeta({cars:e}){let t=await this.loadCar(e[0]);return await ii(t,this.logger)}async commitFiles(e,t){await this.ready();let n=await this.fileStore(),s=await this.WALStore();return this.commitQueue.enqueue(()=>ak(n,s,e,t))}async loadFileCar(e){return await this.storesLoadCar(e,await this.fileStore(),this.remoteFileStore)}async commit(e,t,n={noLoader:!1,compact:!1}){await this.ready();let s=await this.fileStore(),o={encoder:(await s.keyedCrypto()).codec(),carLog:this.carLog,carStore:s,WALStore:await this.WALStore(),metaStore:await this.metaStore(),threshold:this.ebOpts.threshold};return this.commitQueue.enqueue(async()=>{await this.cacheTransaction(e);let i=await ck(o,e,t,n);return await this.updateCarLog(i.cgrp,i.header,!!n.compact),i.cgrp})}async updateCarLog(e,t,n){if(n){let s=t.compact[t.compact.length-1];t.compact.map(o=>o.toString()).forEach(this.seenCompacted.add,this.seenCompacted),this.carLog=[...lk([...this.carLog,...t.cars,e],this.seenCompacted)],await this.removeCidsForCompact(s[0]).catch(o=>o)}else this.carLog.unshift(e)}async cacheTransaction(e){for await(let t of e.entries()){let n=t.cid.toString();this.getBlockCache.has(n)||this.getBlockCache.set(n,t)}}async cacheCarReader(e,t){if(!this.processedCars.has(e)){this.processedCars.add(e);for await(let n of t.blocks()){let s=n.cid.toString();this.getBlockCache.has(s)||this.getBlockCache.set(s,n)}}}async removeCidsForCompact(e){let t=await this.loadCarHeaderFromMeta({cars:[e]});for(let n of t.compact)for(let s of n)await(await this.carStore()).remove(s)}async*entries(e=!0){if(await this.ready(),e)for(let[,t]of this.getBlockCache)yield t;else{for(let[,t]of this.getBlockCache)yield t;for(let t of this.carLog)for(let n of t){let s=await this.loadCar(n);if(!s)throw this.logger.Error().Ref("cid",n).Msg("missing car reader").AsError();for await(let o of s.blocks()){let i=o.cid.toString();this.getBlockCache.has(i)||(yield o)}}}}async getBlock(e){await this.ready();let t=e.toString();if(this.getBlockCache.has(t))return this.getBlockCache.get(t);let n=async a=>{if(this.getBlockCache.has(t))return this.getBlockCache.get(t);let c=await this.loadCar(a);if(!c)throw this.logger.Error().Ref("cid",a).Msg("missing car reader").AsError();if(await this.cacheCarReader(a.toString(),c).catch(()=>{}),this.getBlockCache.has(t))return this.getBlockCache.get(t);throw this.logger.Error().Str("cid",t).Msg("block not in reader").AsError()},s=async a=>{let c=await this.loadCar(a);if(!c)throw this.logger.Error().Str("cid",a.toString()).Msg("missing car reader").AsError();let u=(await ii(c,this.logger)).compact,f,p=5;for(let h=0;h<u.length;h+=p){let m=[];for(let d=h;d<Math.min(h+p,u.length);d++)for(let y of u[d])m.push(n(y));try{f=await Promise.any(m)}catch{}if(f)break}if(this.getBlockCache.has(t))return this.getBlockCache.get(t);throw this.logger.Error().Str("cid",t).Msg("block not in compact reader").AsError()},o,i=5;for(let a=0;a<this.carLog.length;a+=i){let l=this.carLog.slice(a,a+i).flatMap(u=>u.map(n));try{o=await Promise.any(l)}catch{}if(o)break}if(!o)try{o=await s(this.carLog[this.carLog.length-1][0])}catch{}return o}async loadCar(e){if(!this.carStore)throw this.logger.Error().Msg("car store not initialized").AsError();return await this.storesLoadCar(e,await this.carStore(),this.remoteCarStore)}async makeDecoderAndCarReader(e,t,n){let s=e.toString(),o,i=t;try{this.logger.Debug().Str("cid",s).Msg("loading car"),o=await t.load(e),this.logger.Debug().Bool("loadedCar",o).Msg("loaded")}catch(f){if(n){let p=await n.load(e);p&&(this.logger.Debug().Ref("cid",p.cid).Msg("saving remote car locally"),await t.save(p),o=p,i=n)}else this.logger.Error().Str("cid",s).Err(f).Msg("loading car")}if(!o)throw this.logger.Error().Url(t.url()).Str("cid",s).Msg("missing car files").AsError();let a=await lr({bytes:o.bytes,hasher:Q,codec:(await i.keyedCrypto()).codec()}),c=await oi.fromBytes(a.value),l=Promise.resolve(c),u=l.then(async f=>(await this.cacheCarReader(s,f).catch(p=>{this.logger.Error().Err(p).Str("cid",s).Msg("error caching car reader")}),f));return this.carReaders.set(s,u),l}async storesLoadCar(e,t,n){let s=e.toString(),o=this.carReaders.get(s);return o||(o=this.makeDecoderAndCarReader(e,t,n),this.carReaders.set(s,o)),o}async getMoreReaders(e){let t=Mc(5),n=e.filter(s=>!this.carReaders.has(s.toString()));await Promise.all(n.map(s=>t(()=>this.loadCar(s))))}};var bd={};K(bd,{BlockIvKeyIdCodec:()=>Hc,keyedCryptoFactory:()=>wd});ye();Rr();var uk={random:{calc:async(r,e,t)=>e.randomBytes(r.ivLength),verify:async(r,e,t,n)=>!0},hash:{calc:async(r,e,t)=>{let n=await Q.digest(t),s=new Uint8Array(n.bytes),o=new Uint8Array(r.ivLength);for(let i=0;i<s.length;i++)o[i%r.ivLength]^=s[i];return o},verify:async function(r,e,t,n){return r.url.getParam("ivverify")!=="disable"&&qh(t,await this.calc(r,e,n))}}};function fk(r,e){let t=e.ivCalc||r.getParam("ivhash")||"hash";return uk[t]||uk.hash}var Hc=class{constructor(e,t,n){this.code=3147065;this.name="Fireproof@encrypted-block:aes-gcm";this.ko=e,this.iv=t,this.opts=n||{}}async encode(e){let t=this.iv||await fk(this.ko.url,this.opts).calc(this.ko,this.ko.crypto,e),{iv:n}=this.ko.algo(t),s=await this.ko.fingerPrint(),o=J.decode(s);return this.ko.logger.Debug().Str("fp",s).Msg("encode"),hr({iv:n,keyId:o,data:await this.ko._encrypt({iv:n,bytes:e})})}async decode(e){let t;e instanceof Uint8Array?t=e:t=new Uint8Array(e);let{iv:n,keyId:s,data:o}=Tt(t),i=await this.ko.fingerPrint();if(this.ko.logger.Debug().Str("fp",J.encode(s)).Msg("decode"),J.encode(s)!==i)throw this.ko.logger.Error().Str("fp",i).Str("keyId",J.encode(s)).Msg("keyId mismatch").AsError();let a=await this.ko._decrypt({iv:n,bytes:o});if(!this.opts?.noIVVerify&&!await fk(this.ko.url,this.opts).verify(this.ko,this.ko.crypto,n,a))throw this.ko.logger.Error().Msg("iv missmatch").AsError();return a}},md=class{constructor(e,t,n,s){this.ivLength=12;this.isEncrypting=!0;this.logger=H(s,"keyedCrypto"),this.crypto=n,this.key=t,this.url=e}fingerPrint(){return Promise.resolve(this.key.fingerPrint)}codec(e,t){return new Hc(this,e,t)}algo(e){return{name:"AES-GCM",iv:e||this.crypto.randomBytes(this.ivLength),tagLength:128}}async _decrypt(e){return this.logger.Debug().Len(e.bytes,"bytes").Len(e.iv,"iv").Str("fp",this.key.fingerPrint).Msg("decrypting"),new Uint8Array(await this.crypto.decrypt(this.algo(e.iv),this.key.key,e.bytes))}async _encrypt(e){this.logger.Debug().Len(e.bytes).Str("fp",this.key.fingerPrint).Msg("encrypting");let t=this.algo(e.iv);return new Uint8Array(await this.crypto.encrypt(t,this.key.key,e.bytes))}},yd=class{constructor(){this.code=0;this.name="Fireproof@unencrypted-block"}encode(e){return e}decode(e){return e}},gd=class{constructor(e,t,n){this.ivLength=0;this.code=0;this.name="Fireproof@unencrypted-block";this.isEncrypting=!1;this._fingerPrint="noCrypto:"+Math.random();this.logger=H(n,"noCrypto"),this.crypto=t,this.url=e}fingerPrint(){return Promise.resolve(this._fingerPrint)}codec(e){return new yd}algo(e){return{name:"noCrypto",iv:new Uint8Array,tagLength:0}}_decrypt(){throw this.logger.Error().Msg("noCrypto.decrypt not implemented").AsError()}_encrypt(){throw this.logger.Error().Msg("noCrypto.decrypt not implemented").AsError()}};async function wd(r,e,t){let n=r.getParam("storekey");if(n&&n!=="insecure"){let s=await e.getNamedKey(n,!0);if(s.isErr())try{s=await e.toKeyWithFingerPrint(n)}catch(o){throw t.logger.Error().Err(o).Str("keybag",e.rt.id()).Str("name",n).Msg("getNamedKey failed").AsError()}return new md(r,s.Ok(),e.rt.crypto,t)}return new gd(r,e.rt.crypto,t)}ae();Rr();ye();function dk(r){let e=r.getParam("fragSize"),t=0;return e&&(t=parseInt(e)),(isNaN(t)||t<=0)&&(t=0),t}async function hk(r,e,t,n){if(!dk(r)){let f=await e.get(r);if(f.isErr())return[f];let p=f.unwrap();return[C.Ok({fid:new Uint8Array(0),ofs:0,len:p.length,data:p})]}let o=await e.get(r.build().setParam("ofs","0").URI());if(o.isErr())return[o];let i=Tt(o.unwrap()),a=i.data.length,c=[Promise.resolve(C.Ok(i))],l=J.encode(i.fid),u=r.build().setParam("fid",l).setParam("len",i.len.toString()).setParam("headerSize",t.toString());for(let f=a;f<i.len;f+=a)c.push((async(p,h)=>{let m=await e.get(p);if(m.isErr())return m;let d=Tt(m.unwrap());return J.encode(d.fid)!==l?C.Err(n.Error().Msg("Fragment fid mismatch").AsError()):d.ofs!==h?C.Err(n.Error().Uint64("ofs",h).Msg("Fragment ofs mismatch").AsError()):C.Ok(d)})(u.setParam("ofs",f.toString()).URI(),f));return Promise.all(c)}var pi=class{constructor(e,t){this.fidLength=4;this.headerSize=32;this.sthis=_r(e,"FragmentGateway"),this.logger=this.sthis.logger,this.innerGW=t}slicer(e,t){let n=dk(e);if(!n)return[this.innerGW.put(e,t)];let s=n-this.headerSize;if(s<=0)throw this.logger.Error().Uint64("fragSize",n).Uint64("headerSize",this.headerSize).Msg("Fragment size is too small").AsError();let o=[],i=this.sthis.nextId(this.fidLength),a=e.build().setParam("fid",i.str).setParam("len",t.length.toString()).setParam("headerSize",this.headerSize.toString());for(let c=0;c<t.length;c+=s){let l=hr({fid:i.bin,ofs:c,len:t.length,data:t.slice(c,c+s)});if(l.length>n)throw this.logger.Error().Uint64("block",l.length).Uint64("fragSize",n).Msg("Block size to big").AsError();o.push(this.innerGW.put(a.setParam("ofs",c.toString()).URI(),l))}return o}buildUrl(e,t){return this.innerGW.buildUrl(e,t)}async destroy(e){return this.innerGW.destroy(e)}async start(e){return this.headerSize=hr({fid:this.sthis.nextId(this.fidLength).bin,ofs:1024*1024,len:16*1024*1024,data:new Uint8Array(1024)}).length-1024,this.innerGW.start(e)}async close(e){return this.innerGW.close(e)}async put(e,t){return await Promise.all(this.slicer(e,t)),C.Ok(void 0)}async get(e){let t=await hk(e,this.innerGW,this.headerSize,this.logger),n;for(let s of t){if(s.isErr())return C.Err(s.Err());let o=s.Ok();n=n||new Uint8Array(o.len),n.set(o.data,o.ofs)}return C.Ok(n||new Uint8Array(0))}async subscribe(e,t){return this.innerGW.subscribe?this.innerGW.subscribe(e,t):C.Err(this.logger.Error().Url(e).Msg("subscribe not supported").AsError())}async delete(e){let t=await hk(e,this.innerGW,this.headerSize,this.logger);for(let n of t){if(n.isErr())return C.Err(n.Err());let s=n.Ok(),o=J.encode(s.fid),i=e.build().setParam("fid",o).setParam("len",s.len.toString()).setParam("headerSize",this.headerSize.toString()).URI();await this.innerGW.delete(i)}return C.Ok(void 0)}};ae();async function mi(r,e){let t=JSON.parse(r.txt.decode(e));return t.length?t.map?Promise.all(t.map(async n=>{let s=await zu(wc.decode(n.data)),o=kc(r.txt.decode(s.value.data.dbMeta));return{eventCid:s.cid,parents:n.parents,dbMeta:o}})):(r.logger.Debug().Str("crdtEntries",JSON.stringify(t)).Msg("No data in CRDT entries"),[]):(r.logger.Debug().Any("byteHeads",e).Msg("No CRDT entries found"),[])}async function pk(r,e,t){try{e.logger.Debug().Str("uri",r.toString()).Msg("Setting crypto key from gateway meta payload");let n=await mi(e,t);if(n.length){let s=n[0].dbMeta;if(s.key){let o=await Fe(e),i=yk(r),a=await o.setNamedKey(i,s.key);if(a.isErr())throw e.logger.Debug().Str("keyName",i).Str("dbMeta.key",s.key).Msg("Failed to set named key"),a.Err()}return e.logger.Debug().Str("dbMeta.key",s.key).Str("uri",r.toString()).Msg("Set crypto key from gateway meta payload"),C.Ok(s)}return e.logger.Debug().Any("data",t).Msg("No crypto in gateway meta payload"),C.Ok(void 0)}catch(n){return e.logger.Debug().Err(n).Msg("Failed to set crypto key from gateway meta payload"),C.Err(n)}}async function mk(r,e,t){try{e.logger.Debug().Str("uri",r.toString()).Msg("Adding crypto key to gateway meta payload");let n=yk(r),o=await(await Fe(e)).getNamedExtractableKey(n,!0);if(o.isErr())throw e.logger.Error().Str("keyName",n).Msg("Failed to get named extractable key"),o.Err();let i=await o.Ok().extract(),a=await mi(e,t),{dbMeta:c,parents:l}=a[0],u=l.map(h=>N.parse(h));c.key=i.keyStr;let f=await Promise.all([c].map(h=>xd(e,h,u))),p=await kd(e,f,u);return e.logger.Debug().Str("uri",r.toString()).Msg("Added crypto key to gateway meta payload"),C.Ok(p)}catch(n){return e.logger.Error().Err(n).Msg("Failed to add crypto key to gateway meta payload"),C.Err(n)}}function yk(r){let e=[r.getParam("localName")||r.getParam("name")],t=r.getParam("index");return t&&e.push(t),e.push("data"),`@${e.join(":")}@`}async function xd(r,e,t){return await jt.create({dbMeta:r.txt.encode(xc(e))},t)}async function kd(r,e,t){let n=e.map(s=>{let o=wc.encode(s.bytes);return{cid:s.cid.toString(),data:o,parents:t.map(i=>i.toString())}});return r.txt.encode(JSON.stringify(n))}var vk=mt(kk(),1);var DI=Object.prototype.toString,NI=r=>DI.call(r)==="[object Error]",MI=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function Sd(r){return r&&NI(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:MI.has(r.message):!1}var vd=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},Sk=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Ed(r,e){return new Promise((t,n)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let s=vk.default.operation(e),o=()=>{s.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",o),s.stop()};s.attempt(async a=>{try{let c=await r(a);i(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof vd)throw c.originalError;if(c instanceof TypeError&&!Sd(c))throw c;if(Sk(c,a,e),await e.shouldRetry(c)||(s.stop(),n(c)),await e.onFailedAttempt(c),!s.retry(c))throw s.mainError()}catch(l){Sk(l,a,e),i(),n(l)}}})})}async function yi(r,e,{concurrency:t=Number.POSITIVE_INFINITY,stopOnError:n=!0,signal:s}={}){return new Promise((o,i)=>{if(r[Symbol.iterator]===void 0&&r[Symbol.asyncIterator]===void 0)throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof r})`);if(typeof e!="function")throw new TypeError("Mapper function is required");if(!(Number.isSafeInteger(t)&&t>=1||t===Number.POSITIVE_INFINITY))throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${t}\` (${typeof t})`);let a=[],c=[],l=new Map,u=!1,f=!1,p=!1,h=0,m=0,d=r[Symbol.iterator]===void 0?r[Symbol.asyncIterator]():r[Symbol.iterator](),y=b=>{u=!0,f=!0,i(b)};s&&(s.aborted&&y(s.reason),s.addEventListener("abort",()=>{y(s.reason)}));let g=async()=>{if(f)return;let b=await d.next(),x=m;if(m++,b.done){if(p=!0,h===0&&!f){if(!n&&c.length>0){y(new AggregateError(c));return}if(f=!0,l.size===0){o(a);return}let k=[];for(let[S,T]of a.entries())l.get(S)!==Ek&&k.push(T);o(k)}return}h++,(async()=>{try{let k=await b.value;if(f)return;let S=await e(k,x);S===Ek&&l.set(x,S),a[x]=S,h--,await g()}catch(k){if(n)y(k);else{c.push(k),h--;try{await g()}catch(S){y(S)}}}})()};(async()=>{for(let b=0;b<t;b++){try{await g()}catch(x){y(x);break}if(p||u)break}})()})}var Ek=Symbol("skip");function OI(r){return r.hasParam("version")?C.Ok(r):C.Err(`missing version: ${r.toString()}`)}var gi=class{constructor(e,t,n,s,o){this._onStarted=[];this._onClosed=[];this.name=e,this._url=t,this.keybag=n.keybag,this.sthis=s,this.logger=o.With().Ref("url",()=>this._url.toString()).Str("name",e).Logger(),this.gateway=new pi(this.sthis,n.gateway),this.loader=n.loader}url(){return this._url}onStarted(e){this._onStarted.push(e)}onClosed(e){this._onClosed.push(e)}async ready(){}async keyedCrypto(){return wd(this._url,await this.keybag(),this.sthis)}async start(){this.logger.Debug().Str("storeType",this.storeType).Msg("starting-gateway-pre"),this._url=this._url.build().setParam("store",this.storeType).URI();let e=await this.gateway.start(this._url);if(e.isErr())return this.logger.Error().Result("gw-start",e).Msg("started-gateway"),e;this._url=e.Ok();let n=await(await this.keybag()).ensureKeyFromUrl(this._url,()=>{let o=this._url.getParam("index"),i=[this.name];return o&&i.push(o),i.push(this.storeType),i.join(":")});if(n.isErr())return n;this._url=n.Ok();let s=OI(this._url);if(s.isErr())return this.logger.Error().Result("version",s).Msg("guardVersion"),await this.close(),s;if(this.ready){let o=this.ready.bind(this),i=await We(o);if(i.isErr())return await this.close(),i}return this._onStarted.forEach(o=>o()),this.logger.Debug().Msg("started"),s}},As=class extends gi{constructor(t,n,s,o){super(n,s,{...o},t,H(t,"MetaStoreImpl"));this.storeType="meta";this.subscribers=new Map;this.parents=[];o.gateway.subscribe&&this.onStarted(async()=>{this.logger.Debug().Str("url",this.url().toString()).Msg("Subscribing to the gateway"),o.gateway.subscribe?.(this.url(),async i=>{this.logger.Debug().Msg("Received message from gateway");let a=await mi(this.sthis,i);await Promise.all(a.map(c=>this.loader?.taskManager?.handleEvent(c.eventCid,c.parents,c.dbMeta))),this.updateParentsFromDbMetas(a)})})}updateParentsFromDbMetas(t){let n=t.map(a=>a.eventCid),s=t.flatMap(a=>a.parents),o=new Map([...this.parents,...n].map(a=>[a.toString(),a])),i=new Set(s.map(a=>a.toString()));this.parents=Array.from(o.values()).filter(a=>!i.has(a.toString()))}async handleByteHeads(t){return await mi(this.sthis,t)}async load(){let t="main",n=await this.gateway.buildUrl(this.url(),t);if(n.isErr())throw this.logger.Error().Result("buildUrl",n).Str("branch",t).Msg("got error from gateway.buildUrl").AsError();let s=await this.gateway.get(n.Ok());if(s.isErr()){if(Mt(s))return;throw this.logger.Error().Url(n.Ok()).Result("bytes:",s).Msg("gateway get").AsError()}let o=await this.handleByteHeads(s.Ok());return await this.loader?.handleDbMetasFromStore(o.map(i=>i.dbMeta)),this.updateParentsFromDbMetas(o),o.map(i=>i.dbMeta)}async save(t,n){n=n||"main",this.logger.Debug().Str("branch",n).Any("meta",t).Msg("saving meta");let s=await xd(this.sthis,t,this.parents),o=await kd(this.sthis,[s],this.parents),i=await this.gateway.buildUrl(this.url(),n);if(i.isErr())throw this.logger.Error().Err(i.Err()).Str("branch",n).Msg("got error from gateway.buildUrl").AsError();this.parents=[s.cid];let a=await this.gateway.put(i.Ok(),o);if(a.isErr())throw this.logger.Error().Err(a.Err()).Msg("got error from gateway.put").AsError();return a}async close(){return await this.gateway.close(this.url()),this._onClosed.forEach(t=>t()),C.Ok(void 0)}async destroy(){return this.gateway.destroy(this.url())}},Is=class extends gi{constructor(t,n,s,o){super(n,s,{...o},t,H(t,"DataStoreImpl"));this.storeType="data"}async load(t){this.logger.Debug().Any("cid",t).Msg("loading");let n=await this.gateway.buildUrl(this.url(),t.toString());if(n.isErr())throw this.logger.Error().Err(n.Err()).Str("cid",t.toString()).Msg("got error from gateway.buildUrl").AsError();let s=await this.gateway.get(n.Ok());if(s.isErr())throw s.Err();return{cid:t,bytes:s.Ok()}}async save(t,n){this.logger.Debug().Any("cid",t.cid.toString()).Msg("saving");let s=await this.gateway.buildUrl(this.url(),t.cid.toString());if(s.isErr())throw this.logger.Error().Err(s.Err()).Ref("cid",t.cid).Msg("got error from gateway.buildUrl").AsError();let o=await this.gateway.put(s.Ok(),t.bytes);if(o.isErr())throw this.logger.Error().Err(o.Err()).Msg("got error from gateway.put").AsError();return o.Ok()}async remove(t){let n=await this.gateway.buildUrl(this.url(),t.toString());return n.isErr()?n:this.gateway.delete(n.Ok())}async close(){return await this.gateway.close(this.url()),this._onClosed.forEach(t=>t()),C.Ok(void 0)}destroy(){return this.gateway.destroy(this.url())}},jc=class extends gi{constructor(t,n,s){super(t.name,n,{...s},t.sthis,H(t.sthis,"WALStoreImpl"));this.storeType="wal";this._ready=new X;this.walState={operations:[],noLoaderOps:[],fileOperations:[]};this.processing=void 0;this.processQueue=new _s;this.loader=t}async ready(){return this._ready.once(async()=>{let t=await this.load().catch(n=>{this.logger.Error().Any("error",n).Msg("error loading wal")});t?(this.walState.operations=t.operations||[],this.walState.fileOperations=t.fileOperations||[]):(this.walState.operations=[],this.walState.fileOperations=[])})}async enqueue(t,n){await this.ready(),n.compact?(this.walState.operations=[],this.walState.noLoaderOps=[t]):n.noLoader?this.walState.noLoaderOps.push(t):this.walState.operations.push(t),await this.save(this.walState),n.noLoader||this.process()}async enqueueFile(t,n=!1){await this.ready(),this.walState.fileOperations.push({cid:t,public:n})}async process(){await this.ready(),this.loader.remoteCarStore&&await this.processQueue.enqueue(async()=>{try{await this._doProcess()}catch(t){this.logger.Error().Any("error",t).Msg("error processing wal")}(this.walState.operations.length||this.walState.fileOperations.length||this.walState.noLoaderOps.length)&&setTimeout(()=>void this.process(),0)})}async _doProcess(){if(!this.loader.remoteCarStore)return;let t=[...this.walState.operations],n=[...this.walState.noLoaderOps],s=[...this.walState.fileOperations];if(t.length+n.length+s.length===0)return;let o=3,i=(a,c)=>Ed(a,{retries:5,onFailedAttempt:l=>{this.logger.Warn().Msg(`Attempt ${l.attemptNumber} failed for ${c}. There are ${l.retriesLeft} retries left.`)}});try{if(await yi(n,async a=>{await i(async()=>{for(let c of a.cars){let l=await(await this.loader.carStore()).load(c);if(l)await me(this.loader.remoteCarStore).save(l);else if(zc(this.loader.carLog,a.cars))throw this.logger.Error().Ref("cid",c).Msg("missing local car").AsError()}this.walState.noLoaderOps=this.walState.noLoaderOps.filter(c=>c!==a)},`noLoaderOp with dbMeta.cars=${a.cars.toString()}`)},{concurrency:o}),await yi(t,async a=>{await i(async()=>{for(let c of a.cars){let l=await(await this.loader.carStore()).load(c);if(l)await me(this.loader.remoteCarStore).save(l);else if(zc(this.loader.carLog,a.cars))throw this.logger.Error().Ref("cid",c).Msg("missing local car").AsError()}this.walState.operations=this.walState.operations.filter(c=>c!==a)},`operation with dbMeta.cars=${a.cars.toString()}`)},{concurrency:o}),await yi(s,async({cid:a,public:c})=>{await i(async()=>{let l=await(await this.loader.fileStore()).load(a);if(!l)throw this.logger.Error().Ref("cid",a).Msg("missing file block").AsError();await this.loader.remoteFileStore?.save(l,{public:c}),this.walState.fileOperations=this.walState.fileOperations.filter(u=>u.cid!==a)},`fileOperation with cid=${a.toString()}`)},{concurrency:o}),t.length){let a=t[t.length-1];await i(async()=>{await this.loader.remoteMetaStore?.save(a)},`remoteMetaStore save with dbMeta.cars=${a.cars.toString()}`)}}catch(a){this.logger.Error().Any("error",a).Msg("Processing failed");return}finally{await this.save(this.walState)}}async load(){this.logger.Debug().Msg("loading");let t=await this.gateway.buildUrl(this.url(),"main");if(t.isErr())throw this.logger.Error().Err(t.Err()).Url(this.url()).Msg("error building url").AsError();let n=await this.gateway.get(t.Ok());if(n.isErr()){if(Mt(n))return;throw this.logger.Error().Err(n.Err()).Msg("error get").AsError()}try{return n&&kc(this.sthis.txt.decode(n.Ok()))}catch(s){throw this.logger.Error().Err(s).Msg("error parse").AsError()}}async save(t){let n=await this.gateway.buildUrl(this.url(),"main");if(n.isErr())throw this.logger.Error().Err(n.Err()).Url(this.url()).Msg("error building url").AsError();let s;try{s=xc(t)}catch(i){throw this.logger.Error().Err(i).Any("state",t).Msg("error format").AsError()}let o=await this.gateway.put(n.Ok(),this.sthis.txt.encode(s));if(o.isErr())throw this.logger.Error().Err(o.Err()).Str("filePath",n.Ok().toString()).Msg("error saving").AsError()}async close(){return await this.gateway.close(this.url()),this._onClosed.forEach(t=>t()),C.Ok(void 0)}destroy(){return this.gateway.destroy(this.url())}};ye();function $I(r,e){return e?r.build().setParam("index",e).URI():r.build().delParam("index").URI()}function Fd(r,e){return e.hasParam("name")?e:e.build().setParam("name",r).URI()}var on=new Map;function Ud(r,e){let t=e.ebOpts.store,n=Array.from(on.values()).find(i=>i.overrideBaseURL),s;return n&&n.overrideBaseURL&&(s=Ie.from(n.overrideBaseURL)),$I(Ie.from(r||s||Wh(e.sthis,e.name,t.stores?.base)),t.isIndex)}var KI=new _e;async function Lr(r,e){return KI.get(r.toString()).once(async()=>{let t=on.get(r.protocol);if(t){let n={gateway:await t.gateway(e),test:await t.test(e)},s=await n.gateway.start(r);if(s.isErr()){e.logger.Error().Result("start",s).Msg("start failed");return}return n}e.logger.Warn().Url(r).Msg("unsupported protocol")})}function $d(r){let e=r.protocol;if(e.endsWith(":")||(e+=":"),on.has(e)&&!r.overrideBaseURL&&on.get(e)!==r)throw new Error("we need a logger here");return r.overrideBaseURL&&Array.from(on.values()).forEach(t=>{t.overrideBaseURL=void 0}),on.set(e,r),()=>{on.delete(e)}}var zI=new _e;async function HI(r){let e=Fd(r.name,Ud(r.ebOpts.store.stores?.data,r)).build().setParam("store","data").URI(),t=_r(r.sthis,"dataStoreFactory",{url:e.toString()});return zI.get(e.toString()).once(async()=>{let n=await Lr(e,t);if(!n)throw t.logger.Error().Url(e).Msg("gateway not found").AsError();return new Is(t,r.name,e,{gateway:n.gateway,keybag:()=>Fe(r.sthis,{...r.ebOpts.keyBag})})})}var jI=new _e;async function VI(r){let e=Fd(r.name,Ud(r.ebOpts.store.stores?.meta,r)).build().setParam("store","meta").URI(),t=_r(r.sthis,"metaStoreFactory",{url:()=>e.toString()});return jI.get(e.toString()).once(async()=>{t.logger.Debug().Str("protocol",e.protocol).Msg("pre-protocol switch");let n=await Lr(e,t);if(!n)throw t.logger.Error().Url(e).Msg("gateway not found").AsError();return new As(r.sthis,r.name,e,{gateway:n.gateway,keybag:()=>Fe(r.sthis,{...r.ebOpts.keyBag})})})}var WI=new _e;async function qI(r){let e=Fd(r.name,Ud(r.ebOpts.store.stores?.wal,r)).build().setParam("store","wal").URI(),t=_r(r.sthis,"remoteWalFactory",{url:e.toString()});return WI.get(e.toString()).once(async()=>{let n=await Lr(e,t);if(!n)throw t.logger.Error().Url(e).Msg("gateway not found").AsError();return t.logger.Debug().Str("prepared",e.toString()).Msg("produced"),new jc(r,e,{gateway:n.gateway,keybag:()=>Fe(r.sthis,{...r.ebOpts.keyBag})})})}async function GI(r,e){e=_r(e,"testStoreFactory");let t=await Lr(r,e);if(!t)throw e.logger.Error().Url(r).Msg("gateway not found").AsError();return t.test}async function qc(r,e){let t=await r.start();if(t.isErr())throw e.Error().Result("start",t).Msg("start failed").AsError();return e.Debug().Url(t.Ok(),"prepared").Msg("produced"),r}function ed(r,e){let t=H(e,"toStoreRuntime",{});return{makeMetaStore:async n=>(t.Debug().Str("fromOpts",""+!!n.ebOpts.store.makeMetaStore).Msg("makeMetaStore"),qc(await(n.ebOpts.store.makeMetaStore||VI)(n),t)),makeDataStore:async n=>(t.Debug().Str("fromOpts",""+!!n.ebOpts.store.makeDataStore).Msg("makeDataStore"),qc(await(n.ebOpts.store.makeDataStore||HI)(n),t)),makeWALStore:async n=>(t.Debug().Str("fromOpts",""+!!n.ebOpts.store.makeWALStore).Msg("makeRemoteWAL"),qc(await(n.ebOpts.store.makeWALStore||qI)(n),t)),encodeFile:r.encodeFile||$h,decodeFile:r.decodeFile||Kh}}$d({protocol:"file:",gateway:async r=>{let{FileGateway:e}=await Promise.resolve().then(()=>(Cd(),Id));return new e(r)},test:async r=>{let{FileTestStore:e}=await Promise.resolve().then(()=>(Cd(),Id));return new e(r)}});$d({protocol:"indexdb:",gateway:async r=>{let{IndexDBGateway:e}=await Promise.resolve().then(()=>(Rd(),Od));return new e(r)},test:async r=>{let{IndexDBTestStore:e}=await Promise.resolve().then(()=>(Rd(),Od));return new e(r)}});async function Bk(r,e,t,n){let s=new Is(r,e,t,n);return await s.start(),s}async function Pk(r,e,t,n){let s=new As(r,e,t,n);return await s.start(),s}var Gc=class{constructor(e,t){this.loaded=Promise.resolve();this.logger=t,this.url=e}async refresh(){await me(me(this.loader).remoteMetaStore).load(),await(await me(this.loader).WALStore()).process()}async connect_X({loader:e}){if(!e)throw this.logger.Error().Msg("loader is required").AsError();await this.connectMeta_X({loader:e}),await this.connectStorage_X({loader:e})}async connectMeta_X({loader:e}){if(!e)throw this.logger.Error().Msg("connectMeta_X: loader is required").AsError();this.loader=e,await this.onConnect();let t=this.url.build().defParam("store","meta").URI(),n=await Lr(t,this.loader.sthis);if(!n)throw this.logger.Error().Url(t).Msg("connectMeta_X: gateway is required").AsError();let s=t.getParam("name");if(!s)throw this.logger.Error().Url(t).Msg("connectMeta_X: name is required").AsError();let o=await Pk(e.sthis,s,t,{gateway:n.gateway,keybag:()=>Fe(e.sthis,e.ebOpts.keyBag),loader:e});this.loader.remoteMetaStore=o,this.loaded=this.loader.ready().then(async()=>o.load().then(async()=>(await me(this.loader).WALStore()).process()))}async connectStorage_X({loader:e}){if(!e)throw this.logger.Error().Msg("connectStorage_X: loader is required").AsError();this.loader=e;let t=this.url.build().defParam("store","data").URI(),n=await Lr(t,this.loader.sthis);if(!n)throw this.logger.Error().Url(t).Msg("connectStorage_X: gateway is required").AsError();let s=t.getParam("name");if(!s)throw this.logger.Error().Url(t).Msg("connectStorage_X: name is required").AsError;e.remoteCarStore=await Bk(e.sthis,s,this.url,{gateway:n.gateway,keybag:()=>Fe(e.sthis,this.loader?.ebOpts.keyBag)}),e.remoteFileStore=e.remoteCarStore}};function Dk(r,e){switch(typeof r){case"string":case"number":return r.toString();default:throw e.Error().Msg("Invalid key type").AsError()}}async function Rk(r,e,t,n,s){let o=null;if(n.length>1){let i=await Gg(e,t);for(let a of n){let c=await Nk(r,e,a,s);await i.put(Dk(a.id,s),c)}o=await i.commit()}else if(n.length===1){let i=await Nk(r,e,n[0],s);o=await Hg(e,t,Dk(n[0].id,s),i)}if(!o)throw s.Error().Uint64("updates.len",n.length).Msg("Missing result").AsError();if(o.event)for(let{cid:i,bytes:a}of[...o.additions,o.event])e.putSync(i,a);return{head:o.head}}async function Nk(r,e,t,n){let s;if(t.del)s={del:!0};else{if(!t.value)throw n.Error().Msg("Missing value").AsError();await JI(r,e,t.value,n),s={doc:t.value}}let o=await Qn({value:s,hasher:Q,codec:re});return e.putSync(o.cid,o.bytes),o.cid}async function JI(r,e,t,n){t._files&&await Mk(n,r,e,t._files),t._publicFiles&&await Mk(n,r,e,t._publicFiles)}async function Mk(r,e,t,n){let s=t.parent;if(!s.loader)throw r.Error().Msg("Missing loader, database name is required").AsError();let o=new et(s),i=[];for(let a in n)if(File===n[a].constructor){let c=n[a],{cid:l,blocks:u}=await e.encodeFile(c);i.push(a);for(let f of u)o.putSync(f.cid,f.bytes);n[a]={cid:l,type:c.type,size:c.size}}else{let{cid:c,type:l,size:u,car:f}=n[a];c&&l&&u&&f&&(n[a]={cid:c,type:l,size:u,car:f})}if(i.length){let a=await s.loader.commitFiles(o,{files:n});if(a)for(let c of i)n[c]={car:a,...n[c]}}}async function Fk(r,e,t,n){if(!e.length)throw n.Debug().Msg("Getting from an empty database").AsError();let s=await jg(r,e,t);if(!s)throw n.Error().Str("key",t).Msg("Missing key").AsError();return await jd(r,s,n)}function Hd(r,{doc:e}){e&&(e._files&&Ok(r,e._files),e._publicFiles&&Ok(r,e._publicFiles,!0))}function Ok(r,e,t=!1){for(let n in e){let s=e[n];s.cid&&(t&&(s.url=`https://${s.cid.toString()}.ipfs.w3s.link/`),s.car&&(s.file=async()=>await r.ebOpts.storeRuntime.decodeFile({get:async o=>await r.getFile(me(s.car),o)},s.cid,s))),e[n]=s}}async function jd(r,e,t){let n=await r.get(e);if(!n)throw t.Error().Str("link",e.toString()).Msg("Missing linked block").AsError();let{value:s}=await lr({bytes:n.bytes,hasher:Q,codec:re}),o={...s,cid:e};return Hd(r,o),o}var zd=class extends _t{constructor(e,t){super(t),this.logger=e}async get(e){try{return super.get(e)}catch(t){return this.logger.Error().Ref("link",e.toString()).Err(t).Msg("Missing event"),{value:void 0}}}};async function wi(r,e,t,n,s){let o=n.dirty?new zd(s,r):new _t(r);return{result:(await Uk(r,o,e,t,[],new Set,new Set,n.limit||1/0,s)).reverse(),head:e}}async function Uk(r,e,t,n,s=[],o,i,a,c){if(a<=0)return s;let l=t.map(u=>u.toString());for(let u of n)if(l.includes(u.toString()))return s;for(let u of t){if(i.has(u.toString()))continue;i.add(u.toString());let{value:f}=await e.get(u);if(!f)continue;let{type:p}=f.data,h=[];p==="batch"?h=f.data.ops:p==="put"&&(h=[f.data]);for(let m=h.length-1;m>=0;m--){let{key:d,value:y}=h[m];if(!o.has(d)){let g=await jd(r,y,c);s.push({id:d,value:g.doc,del:g.del,clock:u}),a--,o.add(d)}}f.parents&&(s=await Uk(r,e,f.parents,n,s,o,i,a,c))}return s}async function*Vd(r,e,t){for await(let[n,s]of Vg(r,e)){let o=await jd(r,s,t);yield{id:n,value:o.doc,del:o.del}}}async function*$k(r,e){for await(let t of Hu(r,e))yield t}var Kd=!1;async function Kk(r,e,t){if(Kd)return;Kd=!0;for(let s of e)if(!await r.get(s))throw t.Error().Ref("cid",s).Msg("Missing head block").AsError();for await(let s of Vd(r,e,t));for await(let s of Hu(r,e));let n=await yr(r,e);for(let{cid:s,bytes:o}of[...n.additions,...n.removals])r.loggedBlocks.putSync(s,o);await wi(r,e,[],{},t),Kd=!1}async function zk(r,e){let t=await r.get(Sa(e));if(!t)throw new Error(`Missing block ${e}`);let{cid:n,value:s}=await lr({bytes:t.bytes,codec:re,hasher:Q});return new ka({cid:n,value:s,bytes:t.bytes})}var dn=mt(Gk(),1);var Jk=r=>{let e=r.byteLength-4;return(r[e]|r[e+1]<<8|r[e+2]<<16)+r[e+3]*16777216};var qd=r=>{let e=Math.floor(4294967295/r);return async t=>{let n=await t.identity();if(typeof n!="number")throw new Error("Identity must be a number");return n<=e}};var cn=(r,e)=>r===e?0:r>e?1:-1;var an=class{constructor(){this._cids=new Set}add(e){if(!e.address)throw new Error("Cannot add node without address");if(e.address.then){let t=e.address.then(n=>this._cids.add(n.toString()));this._cids.add(t),t.then(()=>this._cids.delete(t))}else this._cids.add(e.address.toString())}async all(){return await Promise.all([...this._cids]),this._cids}};var Qc=class{constructor({key:e,address:t},n={}){this.key=e,this.address=t,this.codec=n.codec,this.hasher=n.hasher}get isEntry(){return!0}},Cs=class{constructor({entries:e,closed:t}){if(typeof t!="boolean")throw new Error('Missing required argument "closed"');this.entries=e,this.closed=t,this.startKey=e[0].key}find(e,t){let{entries:n}=this;for(let s=n.length-1;s>-1;s--){let o=n[s];if(t(e,o.key)>-1)return[s,o]}return null}findMany(e,t,n=!1,s=!1){let{entries:o}=this,i=new Map;n?e=[...e]:e=e.sort(t);for(let a=o.length-1;a>-1&&e.length;a--){let c=o[a],l=[];for(;e.length;){let u=e[e.length-1];u=u.key?u.key:u;let f=t(u,c.key);if(s)if(f===0)l.push(e.pop());else if(f>0)e.pop();else break;else if(f>-1)l.push(e.pop());else break}l.length&&i.set(a,[c,l])}return i}findRange(e,t,n){let{entries:s}=this,o,i=0;for(let a=s.length-1;a>-1;a--){let c=s[a];if(n(t,c.key)>0){o=a;break}}for(let a=0;a<s.length;a++){let c=s[a],l=n(e,c.key);if(l===0){i=a;break}else if(l<0)break;i=a}return{first:i,last:o,entries:s.slice(i,o+1)}}},Qk=r=>typeof r=="string"?r:JSON.stringify(r);function nC(r,e){return r.sort(({key:t},{key:n})=>e.compare(t,n))}async function sC(r,e,t){let n=[];for(let s of e){let{key:o,del:i}=s;if(t(o,r)<0)i||n.push(s);else break}return n}async function oC(r,e,{chunker:t,compare:n}){return await Br.from({entries:r.map(s=>new e.LeafEntryClass(s,e)).sort((s,o)=>n(s.key,o.key)),chunker:t,NodeClass:e.LeafClass,distance:0,opts:e})}async function iC(r,e,t,n){return await Promise.all(e.map(async s=>{let o=await s.encode();return t.blocks.push({block:o,node:s}),r.cache.set(s),new n.BranchEntryClass({key:s.key,address:await s.address},n)}))}async function aC(r,e,t,n){let s=e.root;e.blocks.push({block:await s.encode(),node:s}),r.cache.set(s);let o=n.opts,i=s.distance,a=s.entryList.startKey,c=await sC(a,t,r.compare);if(c.length){let l=await oC(c,o,r),u=await iC(r,l,e,o),p=[new o.BranchEntryClass({key:s.entryList.startKey,address:await s.address},o),...u].sort(({key:d},{key:y})=>o.compare(d,y)),h=await Br.from({...n,entries:p,chunker:r.chunker,NodeClass:o.BranchClass,distance:i+1}),m=[...h];for(;h.length>1;){let d=await Promise.all(h.map(async y=>new o.BranchEntryClass({key:y.key,address:await y.address},o)));h=await Br.from({...n,entries:d.sort(({key:y},{key:g})=>o.compare(y,g)),chunker:r.chunker,NodeClass:o.BranchClass,distance:i+1}),m=[...m,...h]}await Promise.all(m.map(async d=>{let y=await d.encode();r.cache.set(d),e.blocks.push({block:y,node:d})})),e.root=h[0],e.nodes=[...e.nodes,...m]}}var Br=class r{constructor({entryList:e,chunker:t,distance:n,getNode:s,compare:o,cache:i}){this.entryList=e,this.chunker=t,this.distance=n,this.getNode=s,this.compare=o,this.cache=i}get closed(){return this.entryList.closed}get key(){return this.entryList.startKey}async getEntry(e,t=new an){return{result:await this._getEntry(e,t),cids:t}}async _getEntry(e,t){t.add(this);let n=this;for(;!n.isLeaf;){let i=n.entryList.find(e,this.compare);if(i===null)throw new Error("Not found");let[,a]=i;n=await this.getNode(await a.address),t.add(n)}let s=n.entryList.find(e,this.compare);if(s===null||s[1].key.toString()!==e.toString())throw new Error("Not found");let[,o]=s;return o}async getAllEntries(e=new an){return{result:await this._getAllEntries(e),cids:e}}_getAllEntries(e){if(e.add(this),this.isLeaf)return this.entryList.entries;{let{entries:t}=this.entryList,n=async s=>this.getNode(await s.address).then(o=>o._getAllEntries(e)).catch(async o=>{throw o});return Promise.all(t.map(n)).then(s=>s.flat())}}async*vis(e=new Set){let t=async o=>o.isLeaf?`Leaf [${o.entryList.entries.map(a=>`[${a.key},${JSON.stringify(a.value).replace(/"/g,"'")}]`).join(", ")}]`:`Branch [${o.entryList.entries.map(a=>`[${a.key}]`).join(", ")}]`,n=o=>o.toString().slice(0,4)+o.toString().slice(-4),s=async function*(o,i,a){let c=await o.address;if(!a.has(c)){a.add(c);let l=await t(o);yield` node [shape=ellipse fontname="Courier"]; ${n(c)} [label="${l}"];`,yield` ${n(i)} -> ${n(c)};`;for(let u of o.entryList.entries)if(u.address){let f=await u.address;try{let p=await o.getNode(f);yield*await s(p,c,a)}catch(p){yield` ${n(c)} -> ${n(f)};`,yield` node [shape=ellipse fontname="Courier"]; ${n(f)} [label="Error: ${p.message}"];`}}}};yield"digraph tree {",yield' node [shape=ellipse fontname="Courier"]; rootnode;';for await(let o of s(this,"rootnode",e))yield o;yield"}"}async getEntries(e,t=!1,n=new an){return{result:await this._getEntries(e,t,n),cids:n}}async _getEntries(e,t,n){n.add(this),t||(e=e.sort(this.compare));let s=this.entryList.findMany(e,this.compare,!0,this.isLeaf);if(this.isLeaf)return[...s.values()].map(([i])=>i);let o=[];for(let[i,a]of[...s.values()].reverse()){let c=this.getNode(await i.address);o.push(c.then(l=>l._getEntries(a.reverse(),!0,n)))}return o=await Promise.all(o),o.flat()}async getRangeEntries(e,t,n=new an){return{result:await this._getRangeEntries(e,t,n),cids:n}}_getRangeEntries(e,t,n){n.add(this);let{entries:s}=this.entryList.findRange(e,t,this.compare);if(this.isLeaf)return s.filter(c=>{let l=this.compare(e,c.key),u=this.compare(t,c.key);return l<=0&&u>=0});if(!s.length)return[];let o=async c=>this.getNode(await c.address).then(l=>l._getRangeEntries(e,t,n)),i=[o(s.shift())];if(!s.length)return i[0];let a=o(s.pop());for(;s.length;){let c=async l=>this.getNode(await l.address).then(async u=>u._getAllEntries(n));i.push(c(s.shift()))}return i.push(a),Promise.all(i).then(c=>c.flat())}async transaction(e,t={}){t={codec:this.codec,hasher:this.hasher,getNode:this.getNode,compare:this.compare,cache:this.cache,...t};let n={chunker:this.chunker,opts:t},s=this.entryList.findMany(e,t.compare,!0,this.isLeaf);return this.isLeaf?await this.transactionLeaf(e,t,n,s):await this.transactionBranch(e,t,n,s)}async transactionLeaf(e,t,n,s){let{LeafClass:o,LeafEntryClass:i}=t,{entries:a,previous:c}=this.processLeafEntries(e,s,i,t),l={...n,entries:a,NodeClass:o,distance:0},u=await r.from(l);return{nodes:u,previous:c,blocks:await Promise.all(u.map(async f=>{let p=await f.encode();return this.cache.set(f),{block:p,node:f}})),distance:0}}processLeafEntries(e,t,n,s){let o=[],i=[],a={},c=new Map;for(let{key:f,del:p,value:h}of e){let m=Qk(f);p?typeof a[m]>"u"&&c.set(m,null):(a[m]={key:f,value:h},c.delete(m))}i=[...this.entryList.entries];for(let[f,[p]]of t){o.push(p);let h=Qk(p.key);c.has(h)?c.set(h,f):(i[f]=new n(a[h],s),delete a[h])}let l=0;for(let[,f]of c)f!==null&&i.splice(f-l++,1);let u=Object.values(a).map(f=>new n(f,s));return i=i.concat(u).sort(({key:f},{key:p})=>s.compare(f,p)),{entries:i,previous:o}}async transactionBranch(e,t,n,s){let{BranchClass:o,BranchEntryClass:i}=t,a=0;for(let[m,[d,y]]of s){let g=this.getNode(await d.address).then(b=>b.transaction(y.reverse(),{...t,sorted:!0})).then(b=>({entry:d,keys:y,distance:a,...b}));s.set(m,g)}let c=[...this.entryList.entries],l={previous:[],blocks:[],nodes:[]};for(let[m,d]of s){let{nodes:y,previous:g,blocks:b,distance:x}=await d;a=x,c[m]=y,g.length&&(l.previous=l.previous.concat(g)),b.length&&(l.blocks=l.blocks.concat(b)),y.length&&(l.nodes=l.nodes.concat(y))}c=c.flat();let u=await this.handlePrepend(c,t,n,l,a);a++;let f=async m=>{if(m.isEntry)return m;let d=await m.encode();return l.blocks.push({block:d,node:m}),this.cache.set(m),new i(m,t)};c=await Promise.all(u.map(f));let p={...n,entries:c,NodeClass:o,distance:a},h=await r.from(p);return await Promise.all(h.map(async m=>{let d=await m.encode();l.blocks.push({block:d,node:m}),this.cache.set(m)})),l.nodes=h,{...l,distance:a}}async handlePrepend(e,t,n,s,o){let{BranchClass:i,LeafClass:a}=t,c=[],l=null;for(let u of e)if(l){let f=await this.mergeFirstLeftEntries(u,l,n,s,o);l=null;let p=f[0].address?i:a,h={...n,entries:f.sort(({key:d},{key:y})=>t.compare(d,y)),NodeClass:p,distance:o},m=await r.from(h);m[m.length-1].closed||(l=m.pop()),m.length&&(c=c.concat(m))}else!u.isEntry&&!u.closed?l=u:c.push(u);return l&&c.push(l),c}async getNodeFirstFromBlocks(e,t){for(let{block:n,node:s}of e)if(await n.cid===t)return s;return await this.getNode(t)}async mergeFirstLeftEntries(e,t,n,s,o){let i=n.opts,{LeafClass:a,BranchClass:c,BranchEntryClass:l}=i;if(e.isEntry){let h=await e.address;e=await this.getNodeFirstFromBlocks(s.blocks,h)}let u=e.entryList.entries;if(!u.length)throw new Error("unreachable no entries");let f=(h,m)=>h.concat(m),p=async(h,m,d)=>await Promise.all(h.map(async y=>(m.blocks.push({block:await y.encode(),node:y}),this.cache.set(y),new l({key:y.key,address:await y.address},d))));if(u[0].constructor.name===t.entryList.entries[0].constructor.name)return await f(t.entryList.entries,u);{let h=u.shift();if(!h)throw new Error("unreachable no left entry");if(!h.address)throw new Error("unreachable existing leaf, no leftEntry.address");let m=await this.mergeFirstLeftEntries(h,t,n,s,o-1),d=u.shift();if(!d)return m;if(!d.address)throw new Error("unreachable existing leaf, no esf.address");let y=await this.getNodeFirstFromBlocks(s.blocks,await d.address);if(y.entryList.entries[0].address){if(m[0].address)return m.concat(y.entryList.entries);{let g=await r.from({...n,entries:m.sort(({key:S},{key:T})=>i.compare(S,T)),NodeClass:a,distance:o}),b=await p(g,s,i),x=await r.from({...n,entries:[...y.entryList.entries,...b,...u].sort(({key:S},{key:T})=>i.compare(S,T)),NodeClass:c,distance:o});return await p(x,s,i)}}else{let g=await f(m,y.entryList.entries),b=await r.from({...n,entries:g.sort(({key:k},{key:S})=>i.compare(k,S)),NodeClass:a,distance:o}),x=await p(b,s,i);return await f(x,u)}}}async bulk(e,t={},n=!0){let{BranchClass:s}=t;t={codec:this.codec,hasher:this.hasher,getNode:this.getNode,compare:this.compare,cache:this.cache,...t},t.sorted||(e=nC(e,t),t.sorted=!0);let o={chunker:this.chunker,opts:t},i=await this.transaction(e,t);for(;i.nodes.length>1;){let a=i.nodes[0].distance+1,c=await Promise.all(i.nodes.map(async u=>{let f=await u.encode();return i.blocks.push({block:f,node:u}),this.cache.set(u),new t.BranchEntryClass(u,t)})),l=await r.from({...o,entries:c,NodeClass:s,distance:a});await Promise.all(l.map(async u=>{let f=await u.encode();this.cache.set(u),i.blocks.push({block:f,node:u})})),i.nodes=l}return i.root=i.nodes[0],n&&i.root&&await aC(this,i,e,o),i.blocks=i.blocks.map(({block:a})=>a),i}static async from({entries:e,chunker:t,NodeClass:n,distance:s,opts:o}){if(!e.every(c=>c.constructor.name===e[0].constructor.name))throw new Error("all entries must be of the same type");let i=[],a=[];for(let c of e)a.push(c),await t(c,s)&&(i.push(new Cs({entries:a,closed:!0})),a=[]);return a.length&&i.push(new Cs({entries:a,closed:!1})),i.map(c=>new n({entryList:c,chunker:t,distance:s,...o}))}},Yc=class extends Br{constructor({codec:e,hasher:t,block:n,...s}){super(s),this.codec=e,this.hasher=t,n?(this.block=n,this.address=n.cid):(this.block=this.encode(),this.address=this.block.then(o=>o.cid))}async get(e){let{result:t,cids:n}=await this.getEntry(e);return{result:t.key,cids:n}}async encode(){if(this.block)return this.block;let e=await this.encodeNode(),t={codec:this.codec,hasher:this.hasher,value:e};return this.block=await Jn(t),this.block}},Xc=class extends Yc{async encodeNode(){let{entries:e}=this.entryList,t=async s=>{if(!s.address)throw new Error("entry.address required");return[s.key,await s.address]},n=await Promise.all(e.map(t));return{branch:[this.distance,n],closed:this.closed}}get isBranch(){return!0}},Zc=class extends Yc{async encodeNode(){return{leaf:await Promise.all(this.entryList.entries.map(async t=>await t.encodeNode())),closed:this.closed}}get isLeaf(){return!0}},Yk=async function*(r){let{LeafClass:e,LeafEntryClass:t,BranchClass:n,BranchEntryClass:s,list:o,chunker:i,compare:a,...c}=r;o=o.map(f=>new t(f,c)),c.compare=a;let l=await Br.from({entries:o,chunker:i,NodeClass:e,distance:0,opts:c});yield*l;let u=1;for(;l.length>1;){let f=async h=>new s({key:h.key,address:await h.address},c),p=await Promise.all(l.map(f));l=await Br.from({entries:p,chunker:i,NodeClass:n,distance:u,opts:c}),yield*l,u++}};var el=class extends Qc{async identity(){let e=await this.codec.encode(await this.encodeNode()),t=await this.hasher.encode(e);return Jk(t)}},ln=class extends el{constructor(e,t){super(e,t),this.value=e.value}encodeNode(){return[this.key,this.value]}},un=class extends el{constructor(e,t){if(!e.address)throw new Error("Cannot create MapBranchEntry without address");super(e,t)}async encodeNode(){return[this.key,await this.address]}},Xk=async(r,e)=>{let{result:t,cids:n}=await r.getEntry(e);return{result:t.value,cids:n}},Zk=async(r,e)=>{let{result:t,cids:n}=await r.getEntries(e);return{result:t.map(s=>s.value),cids:n}},fn=class extends Zc{get(e){return Xk(this,e)}getMany(e){return Zk(this,e)}bulk(e,t={},n=!0){return super.bulk(e,{...eS,...t},n)}},hn=class extends Xc{get(e){return Xk(this,e)}getMany(e){return Zk(this,e)}bulk(e,t={},n=!0){return super.bulk(e,{...eS,...t},n)}},eS={LeafClass:fn,LeafEntryClass:ln,BranchClass:hn,BranchEntryClass:un},tS=(r,e,t,n,s,o,i)=>{let a=i.LeafClass||fn,c=i.LeafEntryClass||ln,l=i.BranchClass||hn,u=i.BranchEntryClass||un,f=async h=>e.has(h)?e.get(h):r(h).then(m=>p(m)),p=cC({chunker:t,cache:e,getNode:f,codec:n,hasher:s,compare:o,LeafEntryClass:c,LeafClass:a,BranchEntryClass:u,BranchClass:l});return f},rS=({get:r,cache:e,chunker:t,list:n,codec:s,hasher:o,sorted:i,compare:a,...c})=>{i||(n=n.sort(({key:f},{key:p})=>a(f,p)));let l=tS(r,e,t,s,o,a,c),u={list:n,codec:s,hasher:o,chunker:t,getNode:l,sorted:i,compare:a,cache:e,LeafClass:c.LeafClass||fn,LeafEntryClass:c.LeafEntryClass||ln,BranchClass:c.BranchClass||hn,BranchEntryClass:c.BranchEntryClass||un};return Yk(u)},nS=({cid:r,get:e,cache:t,chunker:n,codec:s,hasher:o,compare:i,...a})=>tS(e,t,n,s,o,i,a)(r);function cC({chunker:r,cache:e,getNode:t,codec:n,hasher:s,compare:o,LeafEntryClass:i,LeafClass:a,BranchEntryClass:c,BranchClass:l}){let u={codec:n,hasher:s};return f=>{let{value:p}=f,h={chunker:r,cache:e,block:f,getNode:t,codec:n,hasher:s,compare:o},m,d;if(p.leaf)m=p.leaf.map(([b,x])=>new i({key:b,value:x},u)),d=a;else if(p.branch){let[b,x]=p.branch;h.distance=b,m=x.map(([k,S])=>new c({key:k,address:S},u)),d=l}else throw new Error("Unknown block data, does not match schema");let y=new Cs({entries:m,closed:p.closed}),g=new d({entryList:y,...h});return e.set(g),g}}var lC=(r,e)=>{let[t,n]=r,[s,o]=e,i=cn(t,s);return i!==0?i:uC(n,o)},uC=(r,e)=>{if(Number.isNaN(r))return-1;if(Number.isNaN(e))throw new Error("ref may not be Infinity or NaN");return Number.isFinite(r)?cn(r,e):1},sS=async(r,e)=>{let t=[e,NaN],n=[e,1/0],{result:s,cids:o}=await r.getRangeEntries(t,n);return{result:s.map(i=>{let[a,c]=i.key;return{id:c,key:a,row:i.value}}),cids:o}},oS=async(r,e,t)=>{e=[e,NaN],t=[t,1/0];let{result:n,cids:s}=await r.getRangeEntries(e,t);return{result:n.map(i=>{let[a,c]=i.key;return{id:c,key:a,row:i.value}}),cids:s}},Gd=class extends fn{get(e){return sS(this,e)}range(e,t){return oS(this,e,t)}bulk(e,t={},n=!0){return super.bulk(e,{...Qd,...t},n)}},Jd=class extends hn{get(e){return sS(this,e)}range(e,t){return oS(this,e,t)}bulk(e,t={},n=!0){return super.bulk(e,{...Qd,...t},n)}},fC=Gd,hC=Jd,Qd={LeafClass:fC,BranchClass:hC,LeafEntryClass:ln,BranchEntryClass:un},iS={...Qd,compare:lC},aS=r=>(r={...iS,...r},rS(r)),Yd=r=>(r={...iS,...r},nS(r));var Xd={has:()=>!1,get:()=>{throw new Error("Cannot ask for entries from nocache")},set:()=>{}};var pn=class{};function pC(r,e){if(Number.isNaN(r))return-1;if(Number.isNaN(e))throw new Error("ref may not be Infinity or NaN");return r===1/0?1:cn(r,e)}function mC(r,e){let[t,n]=r,[s,o]=e,i=cn(t,s);return i!==0?i:pC(n,o)}var ep={cache:Xd,chunker:qd(30),codec:re,hasher:Q,compare:mC},tp={cache:Xd,chunker:qd(30),codec:re,hasher:Q,compare:cn};function cS(r,e){let t=[];return r.forEach(({id:n,value:s,del:o})=>{if(o||!s)return;let i=!1,a=e({...s,_id:n},(c,l)=>{i=!0,!(typeof c>"u")&&t.push({key:[dn.default.encode(c),n],value:l||null})});!i&&a&&t.push({key:[dn.default.encode(a),n],value:null})}),t}function Zd(r){return async e=>{let t=await r.get(e);if(!t)throw new Error(`Missing block ${e.toString()}`);let{cid:n,bytes:s}=t;return Iu({cid:n,bytes:s,hasher:Q,codec:re})}}async function rp(r,e,t,n){if(!t.length)return e;if(!e.root)if(e.cid)e.root=await Yd({cid:e.cid,get:Zd(r),...n});else{let i,a;for await(let c of await aS({get:Zd(r),list:t,...n})){let l=await c.block;await r.put(l.cid,l.bytes),i=l,a=c}if(!a||!i)throw new Error("failed to create index");return{root:a,cid:i.cid}}let{root:s,blocks:o}=await e.root.bulk(t);if(s){for await(let i of o)await r.put(i.cid,i.bytes);return{root:s,cid:(await s.block).cid}}else return{root:void 0,cid:void 0}}async function np(r,e,t){return await Yd({cid:e,get:Zd(r),...t})}async function mn(r,e,t){return t.descending&&(e.result=e.result.reverse()),t.limit&&(e.result=e.result.slice(0,t.limit)),t.includeDocs&&(e.result=await Promise.all(e.result.map(async n=>{let s=await r.get(n.id),o=s?{...s.doc,_id:n.id}:void 0;return{...n,doc:o}}))),{rows:e.result.map(({key:n,...s})=>({key:dn.default.decode(n),...s}))}}function sp(r){return[dn.default.encode(r[0]),dn.default.encode(r[1])]}function op(r){return dn.default.encode(r)}ye();function Ls(r,{_crdt:e},t,n,s){if(n&&s)throw e.logger.Error().Msg("cannot provide both mapFn and meta").AsError();if(n&&n.constructor.name!=="Function")throw e.logger.Error().Msg("mapFn must be a function").AsError();if(e.indexers.has(t))e.indexers.get(t).applyMapFn(t,n,s);else{let o=new tl(r,e,t,n,s);e.indexers.set(t,o)}return e.indexers.get(t)}var tl=class{constructor(e,t,n,s,o){this.mapFnString="";this.byKey=new pn;this.byId=new pn;this.includeDocsDefault=!1;if(this.logger=H(e,"Index"),this.blockstore=t.indexBlockstore,this.crdt=t,this.applyMapFn(n,s,o),this.name=n,!(this.mapFnString||this.initError))throw this.logger.Error().Msg("missing mapFnString").AsError()}ready(){return Promise.all([this.blockstore.ready(),this.crdt.ready()]).then(()=>{})}close(){return Promise.all([this.blockstore.close(),this.crdt.close()]).then(()=>{})}destroy(){return Promise.all([this.blockstore.destroy(),this.crdt.destroy()]).then(()=>{})}applyMapFn(e,t,n){if(t&&n)throw this.logger.Error().Msg("cannot provide both mapFn and meta").AsError();if(this.name&&this.name!==e)throw this.logger.Error().Msg("cannot change name").AsError();this.name=e;try{if(n){if(this.indexHead&&this.indexHead.map(o=>o.toString()).join()!==n.head.map(o=>o.toString()).join())throw this.logger.Error().Msg("cannot apply different head meta").AsError();this.mapFnString?this.mapFnString!==n.map?this.logger.Warn().Msg(`cannot apply different mapFn meta: old mapFnString ${this.mapFnString} new mapFnString ${n.map}`):(this.byId.cid=n.byId,this.byKey.cid=n.byKey,this.indexHead=n.head):(this.mapFnString=n.map,this.byId.cid=n.byId,this.byKey.cid=n.byKey,this.indexHead=n.head)}else if(this.mapFn){if(t&&this.mapFn.toString()!==t.toString())throw this.logger.Error().Msg("cannot apply different mapFn app2").AsError()}else{if(t||(t=o=>o[e]??void 0),this.mapFnString){if(this.mapFnString!==t.toString())throw this.logger.Error().Str("mapFnString",this.mapFnString).Str("mapFn",t.toString()).Msg("cannot apply different mapFn app").AsError()}else this.mapFnString=t.toString();this.mapFn=t}let s=/=>\s*(.*)/.test(this.mapFnString);this.includeDocsDefault=s}catch(s){this.initError=s}}async query(e={}){if(await this.ready(),await this._updateIndex(),await this._hydrateIndex(),!this.byKey.root)return await mn(this.crdt,{result:[]},e);if(this.includeDocsDefault&&e.includeDocs===void 0&&(e.includeDocs=!0),e.range){let n=sp(e.range);return await mn(this.crdt,await me(this.byKey.root).range(n[0],n[1]),e)}if(e.key){let n=op(e.key);return await mn(this.crdt,await me(this.byKey.root).get(n),e)}if(Array.isArray(e.keys))return{rows:(await Promise.all(e.keys.map(async s=>{let o=op(s);return(await mn(this.crdt,await me(this.byKey.root).get(o),e)).rows}))).flat()};if(e.prefix){Array.isArray(e.prefix)||(e.prefix=[e.prefix]);let n=[...e.prefix,NaN],s=[...e.prefix,1/0],o=sp([n,s]);return await mn(this.crdt,await this.byKey.root.range(...o),e)}let t=await this.byKey.root.getAllEntries();return await mn(this.crdt,{result:t.result.map(({key:[n,s],value:o})=>({key:n,id:s,value:o}))},e)}_resetIndex(){this.byId=new pn,this.byKey=new pn,this.indexHead=void 0}async _hydrateIndex(){this.byId.root&&this.byKey.root||!this.byId.cid||!this.byKey.cid||(this.byId.root=await np(this.blockstore,this.byId.cid,tp),this.byKey.root=await np(this.blockstore,this.byKey.cid,ep))}async _updateIndex(){if(await this.ready(),this.initError)throw this.initError;if(!this.mapFn)throw this.logger.Error().Msg("No map function defined").AsError();let e,t;!this.indexHead||this.indexHead.length===0?{result:e,head:t}=await this.crdt.allDocs():{result:e,head:t}=await this.crdt.changes(this.indexHead),e.length===0&&(this.indexHead=t);let n=[],s=[];if(this.byId.root){let l=e.map(({id:f})=>f),{result:u}=await this.byId.root.getMany(l);n=u.map(f=>({key:f,del:!0})),s=u.map(f=>({key:f[1],del:!0}))}let o=cS(e,this.mapFn),i=o.map(({key:l})=>({key:l[1],value:l})),a={indexes:new Map};for(let[l,u]of this.crdt.indexers)u.indexHead&&a.indexes?.set(l,{byId:u.byId.cid,byKey:u.byKey.cid,head:u.indexHead,map:u.mapFnString,name:u.name});if(e.length===0)return a;let{meta:c}=await this.blockstore.transaction(async l=>{if(this.byId=await rp(l,this.byId,s.concat(i),tp),this.byKey=await rp(l,this.byKey,n.concat(o),ep),this.indexHead=t,this.byId.cid&&this.byKey.cid){let u={byId:this.byId.cid,byKey:this.byKey.cid,head:t,map:this.mapFnString,name:this.name};a.indexes?.set(this.name,u)}return a});return c}};ae();function lS(r,e){let t=[],n=!1;async function*s(){if(n||t.length===0)return;n=!0;let o=[];try{for(;t.length>0;){t.sort((a,c)=>c.updates?1:-1);let i=t.shift();if(i&&(await r(i.newHead,i.prevHead,i.updates!==void 0).catch(a=>{throw e.Error().Err(a).Msg("int_applyHead worker error").AsError()}),i.updates&&o.push(...i.updates),!t.some(a=>a.updates)||i.updates)){let a=t.every(c=>c.updates!==null);yield{updates:o,all:a},o.length=0}}}finally{n=!1;let i=s(),a=await i.next();for(;!a.done;)a=await i.next()}}return{push(o){return t.push(o),s()},size(){return t.length}}}ye();var rl=class{constructor(e){this.head=[];this.zoomers=new Set;this.watchers=new Set;this.emptyWatchers=new Set;this._ready=new X;this.blockstore=e,this.logger=H(e.sthis,"CRDTClock"),this.applyHeadQueue=lS(this.int_applyHead.bind(this),this.logger)}async ready(){return this._ready.once(async()=>{await this.blockstore.ready()})}async close(){await this.blockstore.close()}setHead(e){this.head=e}async applyHead(e,t,n){for await(let{updates:s,all:o}of this.applyHeadQueue.push({newHead:e,prevHead:t,updates:n}))return this.processUpdates(s,o,t)}async processUpdates(e,t,n){let s=e;this.watchers.size&&!t&&(s=(await wi(me(this.blockstore),this.head,n,{},this.logger)).result),this.zoomers.forEach(o=>o()),this.notifyWatchers(s||[])}notifyWatchers(e){this.emptyWatchers.forEach(t=>t()),this.watchers.forEach(t=>t(e||[]))}onTick(e){this.watchers.add(e)}onTock(e){this.emptyWatchers.add(e)}onZoom(e){this.zoomers.add(e)}async int_applyHead(e,t,n){let s=!n,o=ip(this.head);if(e=ip(e),uS(o,e))return;let i=ip(t);if(uS(o,i)){this.setHead(e);return}if(!this.blockstore)throw this.logger.Error().Msg("missing blockstore").AsError();await yC(this.logger,e,this.blockstore),this.transaction||(this.transaction=this.blockstore.openTransaction({noLoader:s,add:!1}));let a=this.transaction,c=await gC(this.logger,e,a,this.head),l=await yr(a,c);for(let{cid:u,bytes:f}of[...l.additions])a.putSync(u,f);s||(await this.blockstore.commitTransaction(a,{head:c},{add:!1,noLoader:s}),this.transaction=void 0),this.setHead(c)}};function ip(r){return r.sort((e,t)=>e.toString().localeCompare(t.toString()))}async function yC(r,e,t){if(!t)throw r.Error().Msg("missing blockstore");e.map(async n=>{if(!await t.get(n))throw r.Error().Str("cid",n.toString()).Msg("int_applyHead missing block").AsError()})}function uS(r,e){return r.toString()===e.toString()}async function gC(r,e,t,n){for(let s of e)try{n=await Hr(t,n,s)}catch(o){r.Debug().Err(o).Msg("failed to advance head");continue}return n}ye();var bi=class{constructor(e,t,n={}){this.indexers=new Map;this.onceReady=new X;this.sthis=e,this.name=t,this.logger=H(e,"CRDT"),this.opts=n,this.blockstore=Zh(e,{name:t,applyMeta:async s=>{let o=s;if(!o.head)throw this.logger.Error().Msg("missing head").AsError();await this.clock.applyHead(o.head,[])},compact:async s=>(await Kk(s,this.clock.head,this.logger),{head:this.clock.head}),autoCompact:this.opts.autoCompact||100,store:{...this.opts.store,isIndex:void 0},public:this.opts.public,meta:this.opts.meta,threshold:this.opts.threshold}),this.indexBlockstore=Zh(e,{name:t,applyMeta:async s=>{let o=s;if(!o.indexes)throw this.logger.Error().Msg("missing indexes").AsError();for(let[i,a]of Object.entries(o.indexes))Ls(this.sthis,{_crdt:this},i,void 0,a)},store:{...this.opts.store,isIndex:this.opts.store?.isIndex||"idx"},public:this.opts.public}),this.clock=new rl(this.blockstore),this.clock.onZoom(()=>{for(let s of this.indexers.values())s._resetIndex()})}async bulk(e){await this.ready();let t=[...this.clock.head],n=await this.blockstore.transaction(async s=>{let{head:o}=await Rk(this.blockstore.ebOpts.storeRuntime,s,this.clock.head,e,this.logger);return e=e.map(i=>(Hd(this.blockstore,{doc:i.value}),i)),{head:o}});return await this.clock.applyHead(n.meta.head,t,e),n.meta}async ready(){return this.onceReady.once(async()=>{try{await Promise.all([this.blockstore.ready(),this.indexBlockstore.ready(),this.clock.ready()])}catch(e){throw this.logger.Error().Err(e).Msg("CRDT is not ready").AsError()}})}async close(){await Promise.all([this.blockstore.close(),this.indexBlockstore.close(),this.clock.close()])}async destroy(){await Promise.all([this.blockstore.destroy(),this.indexBlockstore.destroy()])}async allDocs(){await this.ready();let e=[];for await(let t of Vd(this.blockstore,this.clock.head,this.logger))e.push(t);return{result:e,head:this.clock.head}}async vis(){await this.ready();let e=[];for await(let t of $k(this.blockstore,this.clock.head))e.push(t);return e.join(`
|
148
|
-
`)}async getBlock(e){return await this.ready(),await zk(this.blockstore,e)}async get(e){await this.ready();let t=await Fk(this.blockstore,this.clock.head,e,this.logger);if(!t.del)return t}async changes(e=[],t={}){return await this.ready(),await wi(this.blockstore,this.clock.head,e,t,this.logger)}async compact(){return await this.blockstore.compact()}};ye();var Bs=class{constructor(e,t){this.opts={};this._listening=!1;this._listeners=new Set;this._noupdate_listeners=new Set;this._ready=new X;this.name=e,this.opts=t||this.opts,this.sthis=Xo(this.opts),this.logger=H(this.sthis,"Database"),this._crdt=new bi(this.sthis,e,this.opts),this.blockstore=this._crdt.blockstore,this._writeQueue=yy(async n=>await this._crdt.bulk(n)),this._crdt.clock.onTock(()=>{this._no_update_notify()})}static{this.databases=new Map}async close(){await this.ready(),await this._crdt.close(),await this.blockstore.close()}async destroy(){await this.ready(),await this._crdt.destroy(),await this.blockstore.destroy()}async ready(){return this._ready.once(async()=>{await this.sthis.start(),await this._crdt.ready(),await this.blockstore.ready()})}async get(e){if(!e)throw this.logger.Error().Str("db",this.name).Msg("Doc id is required").AsError();await this.ready(),this.logger.Debug().Str("id",e).Msg("get");let t=await this._crdt.get(e).catch(s=>{throw new Dt(`Not found: ${e} - ${s.message}`)});if(!t)throw new Dt(`Not found: ${e}`);let{doc:n}=t;return{...n,_id:e}}async put(e){await this.ready(),this.logger.Debug().Str("id",e._id).Msg("put");let{_id:t,...n}=e,s=t||this.sthis.timeOrderedNextId().str,o=await this._writeQueue.push({id:s,value:{...n,_id:s}});return{id:s,clock:o?.head,name:this.name}}async del(e){await this.ready(),this.logger.Debug().Str("id",e).Msg("del");let t=await this._writeQueue.push({id:e,del:!0});return{id:e,clock:t?.head,name:this.name}}async changes(e=[],t={}){await this.ready(),this.logger.Debug().Any("since",e).Any("opts",t).Msg("changes");let{result:n,head:s}=await this._crdt.changes(e,t);return{rows:n.map(({id:i,value:a,del:c,clock:l})=>({key:i,value:c?{_id:i,_deleted:!0}:{_id:i,...a},clock:l})),clock:s,name:this.name}}async allDocs(e={}){await this.ready(),this.logger.Debug().Msg("allDocs");let{result:t,head:n}=await this._crdt.allDocs();return{rows:t.map(({id:o,value:i,del:a})=>({key:o,value:a?{_id:o,_deleted:!0}:{_id:o,...i}})),clock:n,name:this.name}}async allDocuments(){return this.allDocs()}subscribe(e,t){return this.logger.Debug().Bool("updates",t).Msg("subscribe"),t?(this._listening||(this._listening=!0,this._crdt.clock.onTick(n=>{this._notify(n)})),this._listeners.add(e),()=>{this._listeners.delete(e)}):(this._noupdate_listeners.add(e),()=>{this._noupdate_listeners.delete(e)})}async query(e,t={}){await this.ready(),this.logger.Debug().Any("field",e).Any("opts",t).Msg("query");let n=this._crdt;return await(typeof e=="string"?Ls(this.sthis,{_crdt:n},e):Ls(this.sthis,{_crdt:n},bC(e.toString()),e)).query(t)}async compact(){await this.ready(),await this._crdt.compact()}async _notify(e){if(await this.ready(),this._listeners.size){let t=e.map(({id:n,value:s})=>({...s,_id:n}));for(let n of this._listeners)await(async()=>await n(t))().catch(s=>{this.logger.Error().Err(s).Msg("subscriber error")})}}async _no_update_notify(){if(await this.ready(),this._noupdate_listeners.size)for(let e of this._noupdate_listeners)await(async()=>await e([]))().catch(t=>{this.logger.Error().Err(t).Msg("subscriber error")})}};function fS(r){return r?Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({[e]:t})):[]}function wC(r,e){let t=JSON.stringify(fS({name:r,stores:fS(e?.store?.stores)})),n=Bs.databases.get(t);return n||(n=new Bs(r,e),Bs.databases.set(t,n)),n}function bC(r){let e=/\(([^,()]+,\s*[^,()]+|\[[^\]]+\],\s*[^,()]+)\)/g,t=null;return Array.from(r.matchAll(e),s=>s[1].trim()).length===0&&(t=/=>\s*{?\s*([^{}]+)\s*}?/.exec(r),t&&t[1].includes("return")&&(t=null)),t?t[1]:r}var nl={};K(nl,{FILESTORE_VERSION:()=>Cr,INDEXDB_VERSION:()=>Vc,files:()=>zh,getFileName:()=>ui,getFileSystem:()=>li,getPath:()=>tn,kb:()=>fd,kc:()=>bd,mf:()=>ap,runtimeFn:()=>Or});fi();var ap={};K(ap,{block:()=>Cu,codec:()=>hS});var hS={};ae();Td();Ld();ye();var xC=Object.keys({"0.19.115":"xxxx"})[0];return wS(kC);})();
|
149
|
-
//# sourceMappingURL=index.global.js.map
|