@enbox/agent 0.7.2 → 0.7.3

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/dist/browser.mjs CHANGED
@@ -7,7 +7,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
7
7
  || ${s} === "boolean" || ${i} === null`).assign(o,(0,$t._)`[${i}]`)}}}function tie({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,$t._)`${e} !== undefined`,()=>r.assign((0,$t._)`${e}[${t}]`,n))}function PD(r,e,t,n=Ay.Correct){let i=n===Ay.Correct?$t.operators.EQ:$t.operators.NEQ,a;switch(r){case"null":return(0,$t._)`${e} ${i} null`;case"array":a=(0,$t._)`Array.isArray(${e})`;break;case"object":a=(0,$t._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":a=s((0,$t._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":a=s();break;default:return(0,$t._)`typeof ${e} ${i} ${r}`}return n===Ay.Correct?a:(0,$t.not)(a);function s(o=$t.nil){return(0,$t.and)((0,$t._)`typeof ${e} == "number"`,o,t?(0,$t._)`isFinite(${e})`:$t.nil)}}gs.checkDataType=PD;function xD(r,e,t,n){if(r.length===1)return PD(r[0],e,t,n);let i,a=(0,nN.toHash)(r);if(a.array&&a.object){let s=(0,$t._)`typeof ${e} != "object"`;i=a.null?s:(0,$t._)`!${e} || ${s}`,delete a.null,delete a.array,delete a.object}else i=$t.nil;a.number&&delete a.integer;for(let s in a)i=(0,$t.and)(i,PD(s,e,t,n));return i}gs.checkDataTypes=xD;var rie={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,$t._)`{type: ${r}}`:(0,$t._)`{type: ${e}}`};function ED(r){let e=nie(r);(0,Zne.reportError)(e,rie)}gs.reportTypeError=ED;function nie(r){let{gen:e,data:t,schema:n}=r,i=(0,nN.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var aN=ke(Ox=>{"use strict";g();Object.defineProperty(Ox,"__esModule",{value:!0});Ox.assignDefaults=void 0;var Ty=Dt(),iie=Vt();function sie(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)oN(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,a)=>oN(r,a,i.default))}Ox.assignDefaults=sie;function oN(r,e,t){let{gen:n,compositeRule:i,data:a,opts:s}=r;if(t===void 0)return;let o=(0,Ty._)`${a}${(0,Ty.getProperty)(e)}`;if(i){(0,iie.checkStrictMode)(r,`default is ignored for: ${o}`);return}let c=(0,Ty._)`${o} === undefined`;s.useDefaults==="empty"&&(c=(0,Ty._)`${c} || ${o} === null || ${o} === ""`),n.if(c,(0,Ty._)`${o} = ${(0,Ty.stringify)(t)}`)}});var Pa=ke(Mr=>{"use strict";g();Object.defineProperty(Mr,"__esModule",{value:!0});Mr.validateUnion=Mr.validateArray=Mr.usePattern=Mr.callValidateCode=Mr.schemaProperties=Mr.allSchemaProperties=Mr.noPropertyInData=Mr.propertyInData=Mr.isOwnProperty=Mr.hasPropFunc=Mr.reportMissingProp=Mr.checkMissingProp=Mr.checkReportMissingProp=void 0;var an=Dt(),SD=Vt(),Qu=ba(),oie=Vt();function aie(r,e){let{gen:t,data:n,it:i}=r;t.if(_D(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,an._)`${e}`},!0),r.error()})}Mr.checkReportMissingProp=aie;function cie({gen:r,data:e,it:{opts:t}},n,i){return(0,an.or)(...n.map(a=>(0,an.and)(_D(r,e,a,t.ownProperties),(0,an._)`${i} = ${a}`)))}Mr.checkMissingProp=cie;function die(r,e){r.setParams({missingProperty:e},!0),r.error()}Mr.reportMissingProp=die;function cN(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,an._)`Object.prototype.hasOwnProperty`})}Mr.hasPropFunc=cN;function kD(r,e,t){return(0,an._)`${cN(r)}.call(${e}, ${t})`}Mr.isOwnProperty=kD;function lie(r,e,t,n){let i=(0,an._)`${e}${(0,an.getProperty)(t)} !== undefined`;return n?(0,an._)`${i} && ${kD(r,e,t)}`:i}Mr.propertyInData=lie;function _D(r,e,t,n){let i=(0,an._)`${e}${(0,an.getProperty)(t)} === undefined`;return n?(0,an.or)(i,(0,an.not)(kD(r,e,t))):i}Mr.noPropertyInData=_D;function dN(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}Mr.allSchemaProperties=dN;function uie(r,e){return dN(e).filter(t=>!(0,SD.alwaysValidSchema)(r,e[t]))}Mr.schemaProperties=uie;function fie({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:a},it:s},o,c,l){let d=l?(0,an._)`${r}, ${e}, ${n}${i}`:e,u=[[Qu.default.instancePath,(0,an.strConcat)(Qu.default.instancePath,a)],[Qu.default.parentData,s.parentData],[Qu.default.parentDataProperty,s.parentDataProperty],[Qu.default.rootData,Qu.default.rootData]];s.opts.dynamicRef&&u.push([Qu.default.dynamicAnchors,Qu.default.dynamicAnchors]);let f=(0,an._)`${d}, ${t.object(...u)}`;return c!==an.nil?(0,an._)`${o}.call(${c}, ${f})`:(0,an._)`${o}(${f})`}Mr.callValidateCode=fie;var pie=(0,an._)`new RegExp`;function hie({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,a=i(t,n);return r.scopeValue("pattern",{key:a.toString(),ref:a,code:(0,an._)`${i.code==="new RegExp"?pie:(0,oie.useFunc)(r,i)}(${t}, ${n})`})}Mr.usePattern=hie;function mie(r){let{gen:e,data:t,keyword:n,it:i}=r,a=e.name("valid");if(i.allErrors){let o=e.let("valid",!0);return s(()=>e.assign(o,!1)),o}return e.var(a,!0),s(()=>e.break()),a;function s(o){let c=e.const("len",(0,an._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:SD.Type.Num},a),e.if((0,an.not)(a),o)})}}Mr.validateArray=mie;function yie(r){let{gen:e,schema:t,keyword:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(c=>(0,SD.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let s=e.let("valid",!1),o=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let d=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},o);e.assign(s,(0,an._)`${s} || ${o}`),r.mergeValidEvaluated(d,o)||e.if((0,an.not)(s))})),r.result(s,()=>r.reset(),()=>r.error(!0))}Mr.validateUnion=yie});var fN=ke(bd=>{"use strict";g();Object.defineProperty(bd,"__esModule",{value:!0});bd.validateKeywordUsage=bd.validSchemaType=bd.funcKeywordCode=bd.macroKeywordCode=void 0;var Gs=Dt(),Yp=ba(),gie=Pa(),wie=t0();function vie(r,e){let{gen:t,keyword:n,schema:i,parentSchema:a,it:s}=r,o=e.macro.call(s.self,i,a,s),c=uN(t,n,o);s.opts.validateSchema!==!1&&s.self.validateSchema(o,!0);let l=t.name("valid");r.subschema({schema:o,schemaPath:Gs.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}bd.macroKeywordCode=vie;function bie(r,e){var t;let{gen:n,keyword:i,schema:a,parentSchema:s,$data:o,it:c}=r;xie(c,e);let l=!o&&e.compile?e.compile.call(c.self,a,s,c):e.validate,d=uN(n,i,l),u=n.let("valid");r.block$data(u,f),r.ok((t=e.valid)!==null&&t!==void 0?t:u);function f(){if(e.errors===!1)m(),e.modifying&&lN(r),y(()=>r.error());else{let v=e.async?p():h();e.modifying&&lN(r),y(()=>Pie(r,v))}}function p(){let v=n.let("ruleErrs",null);return n.try(()=>m((0,Gs._)`await `),w=>n.assign(u,!1).if((0,Gs._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Gs._)`${w}.errors`),()=>n.throw(w))),v}function h(){let v=(0,Gs._)`${d}.errors`;return n.assign(v,null),m(Gs.nil),v}function m(v=e.async?(0,Gs._)`await `:Gs.nil){let w=c.opts.passContext?Yp.default.this:Yp.default.self,E=!("compile"in e&&!o||e.schema===!1);n.assign(u,(0,Gs._)`${v}${(0,gie.callValidateCode)(r,d,w,E)}`,e.modifying)}function y(v){var w;n.if((0,Gs.not)((w=e.valid)!==null&&w!==void 0?w:u),v)}}bd.funcKeywordCode=bie;function lN(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,Gs._)`${n.parentData}[${n.parentDataProperty}]`))}function Pie(r,e){let{gen:t}=r;t.if((0,Gs._)`Array.isArray(${e})`,()=>{t.assign(Yp.default.vErrors,(0,Gs._)`${Yp.default.vErrors} === null ? ${e} : ${Yp.default.vErrors}.concat(${e})`).assign(Yp.default.errors,(0,Gs._)`${Yp.default.vErrors}.length`),(0,wie.extendErrors)(r)},()=>r.error())}function xie({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function uN(r,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return r.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0,Gs.stringify)(t)})}function Eie(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r>"u")}bd.validSchemaType=Eie;function Sie({schema:r,opts:e,self:t,errSchemaPath:n},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw new Error("ajv implementation error");let s=i.dependencies;if(s?.some(o=>!Object.prototype.hasOwnProperty.call(r,o)))throw new Error(`parent schema must have dependencies of ${a}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(r[a])){let c=`keyword "${a}" value is invalid at path "${n}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(c);else throw new Error(c)}}bd.validateKeywordUsage=Sie});var hN=ke(ef=>{"use strict";g();Object.defineProperty(ef,"__esModule",{value:!0});ef.extendSubschemaMode=ef.extendSubschemaData=ef.getSubschema=void 0;var Pd=Dt(),pN=Vt();function kie(r,{keyword:e,schemaProp:t,schema:n,schemaPath:i,errSchemaPath:a,topSchemaRef:s}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let o=r.schema[e];return t===void 0?{schema:o,schemaPath:(0,Pd._)`${r.schemaPath}${(0,Pd.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:o[t],schemaPath:(0,Pd._)`${r.schemaPath}${(0,Pd.getProperty)(e)}${(0,Pd.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,pN.escapeFragment)(t)}`}}if(n!==void 0){if(i===void 0||a===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:s,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')}ef.getSubschema=kie;function _ie(r,e,{dataProp:t,dataPropType:n,data:i,dataTypes:a,propertyName:s}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:o}=e;if(t!==void 0){let{errorPath:l,dataPathArr:d,opts:u}=e,f=o.let("data",(0,Pd._)`${e.data}${(0,Pd.getProperty)(t)}`,!0);c(f),r.errorPath=(0,Pd.str)`${l}${(0,pN.getErrorPath)(t,n,u.jsPropertySyntax)}`,r.parentDataProperty=(0,Pd._)`${t}`,r.dataPathArr=[...d,r.parentDataProperty]}if(i!==void 0){let l=i instanceof Pd.Name?i:o.let("data",i,!0);c(l),s!==void 0&&(r.propertyName=s)}a&&(r.dataTypes=a);function c(l){r.data=l,r.dataLevel=e.dataLevel+1,r.dataTypes=[],e.definedProperties=new Set,r.parentData=e.data,r.dataNames=[...e.dataNames,l]}}ef.extendSubschemaData=_ie;function Aie(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:i,allErrors:a}){n!==void 0&&(r.compositeRule=n),i!==void 0&&(r.createErrors=i),a!==void 0&&(r.allErrors=a),r.jtdDiscriminator=e,r.jtdMetadata=t}ef.extendSubschemaMode=Aie});var AD=ke((p4e,mN)=>{"use strict";g();mN.exports=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var n,i,a;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(i=n;i--!==0;)if(!r(e[i],t[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(a=Object.keys(e),n=a.length,n!==Object.keys(t).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,a[i]))return!1;for(i=n;i--!==0;){var s=a[i];if(!r(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}});var gN=ke((m4e,yN)=>{"use strict";g();var tf=yN.exports=function(r,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var n=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};jx(e,n,i,r,"",r)};tf.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};tf.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};tf.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};tf.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function jx(r,e,t,n,i,a,s,o,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,a,s,o,c,l);for(var d in n){var u=n[d];if(Array.isArray(u)){if(d in tf.arrayKeywords)for(var f=0;f<u.length;f++)jx(r,e,t,u[f],i+"/"+d+"/"+f,a,i,d,n,f)}else if(d in tf.propsKeywords){if(u&&typeof u=="object")for(var p in u)jx(r,e,t,u[p],i+"/"+d+"/"+Tie(p),a,i,d,n,p)}else(d in tf.keywords||r.allKeys&&!(d in tf.skipKeywords))&&jx(r,e,t,u,i+"/"+d,a,i,d,n)}t(n,i,a,s,o,c,l)}}function Tie(r){return r.replace(/~/g,"~0").replace(/\//g,"~1")}});var n0=ke(po=>{"use strict";g();Object.defineProperty(po,"__esModule",{value:!0});po.getSchemaRefs=po.resolveUrl=po.normalizeId=po._getFullPath=po.getFullPath=po.inlineRef=void 0;var Iie=Vt(),Die=AD(),Rie=gN(),Cie=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function $ie(r,e=!0){return typeof r=="boolean"?!0:e===!0?!TD(r):e?wN(r)<=e:!1}po.inlineRef=$ie;var Bie=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function TD(r){for(let e in r){if(Bie.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(TD)||typeof t=="object"&&TD(t))return!0}return!1}function wN(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!Cie.has(t)&&(typeof r[t]=="object"&&(0,Iie.eachItem)(r[t],n=>e+=wN(n)),e===1/0))return 1/0}return e}function vN(r,e="",t){t!==!1&&(e=Iy(e));let n=r.parse(e);return bN(r,n)}po.getFullPath=vN;function bN(r,e){return r.serialize(e).split("#")[0]+"#"}po._getFullPath=bN;var Oie=/#\/?$/;function Iy(r){return r?r.replace(Oie,""):""}po.normalizeId=Iy;function jie(r,e,t){return t=Iy(t),r.resolve(e,t)}po.resolveUrl=jie;var Mie=/^[a-z_][-a-z0-9._]*$/i;function Kie(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Iy(r[t]||e),a={"":i},s=vN(n,i,!1),o={},c=new Set;return Rie(r,{allKeys:!0},(u,f,p,h)=>{if(h===void 0)return;let m=s+f,y=a[h];typeof u[t]=="string"&&(y=v.call(this,u[t])),w.call(this,u.$anchor),w.call(this,u.$dynamicAnchor),a[f]=y;function v(E){let _=this.opts.uriResolver.resolve;if(E=Iy(y?_(y,E):E),c.has(E))throw d(E);c.add(E);let A=this.refs[E];return typeof A=="string"&&(A=this.refs[A]),typeof A=="object"?l(u,A.schema,E):E!==Iy(m)&&(E[0]==="#"?(l(u,o[E],E),o[E]=u):this.refs[E]=m),E}function w(E){if(typeof E=="string"){if(!Mie.test(E))throw new Error(`invalid anchor "${E}"`);v.call(this,`#${E}`)}}}),o;function l(u,f,p){if(f!==void 0&&!Die(u,f))throw d(p)}function d(u){return new Error(`reference "${u}" resolves to more than one schema`)}}po.getSchemaRefs=Kie});var o0=ke(rf=>{"use strict";g();Object.defineProperty(rf,"__esModule",{value:!0});rf.getData=rf.KeywordCxt=rf.validateFunctionCode=void 0;var kN=eN(),PN=r0(),DD=bD(),Mx=r0(),Uie=aN(),s0=fN(),ID=hN(),Ze=Dt(),Et=ba(),Nie=n0(),$l=Vt(),i0=t0();function Lie(r){if(TN(r)&&(IN(r),AN(r))){Fie(r);return}_N(r,()=>(0,kN.topBoolOrEmptySchema)(r))}rf.validateFunctionCode=Lie;function _N({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},a){i.code.es5?r.func(e,(0,Ze._)`${Et.default.data}, ${Et.default.valCxt}`,n.$async,()=>{r.code((0,Ze._)`"use strict"; ${xN(t,i)}`),zie(r,i),r.code(a)}):r.func(e,(0,Ze._)`${Et.default.data}, ${qie(i)}`,n.$async,()=>r.code(xN(t,i)).code(a))}function qie(r){return(0,Ze._)`{${Et.default.instancePath}="", ${Et.default.parentData}, ${Et.default.parentDataProperty}, ${Et.default.rootData}=${Et.default.data}${r.dynamicRef?(0,Ze._)`, ${Et.default.dynamicAnchors}={}`:Ze.nil}}={}`}function zie(r,e){r.if(Et.default.valCxt,()=>{r.var(Et.default.instancePath,(0,Ze._)`${Et.default.valCxt}.${Et.default.instancePath}`),r.var(Et.default.parentData,(0,Ze._)`${Et.default.valCxt}.${Et.default.parentData}`),r.var(Et.default.parentDataProperty,(0,Ze._)`${Et.default.valCxt}.${Et.default.parentDataProperty}`),r.var(Et.default.rootData,(0,Ze._)`${Et.default.valCxt}.${Et.default.rootData}`),e.dynamicRef&&r.var(Et.default.dynamicAnchors,(0,Ze._)`${Et.default.valCxt}.${Et.default.dynamicAnchors}`)},()=>{r.var(Et.default.instancePath,(0,Ze._)`""`),r.var(Et.default.parentData,(0,Ze._)`undefined`),r.var(Et.default.parentDataProperty,(0,Ze._)`undefined`),r.var(Et.default.rootData,Et.default.data),e.dynamicRef&&r.var(Et.default.dynamicAnchors,(0,Ze._)`{}`)})}function Fie(r){let{schema:e,opts:t,gen:n}=r;_N(r,()=>{t.$comment&&e.$comment&&RN(r),Jie(r),n.let(Et.default.vErrors,null),n.let(Et.default.errors,0),t.unevaluated&&Gie(r),DN(r),Xie(r)})}function Gie(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,Ze._)`${t}.evaluated`),e.if((0,Ze._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,Ze._)`${r.evaluated}.props`,(0,Ze._)`undefined`)),e.if((0,Ze._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,Ze._)`${r.evaluated}.items`,(0,Ze._)`undefined`))}function xN(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,Ze._)`/*# sourceURL=${t} */`:Ze.nil}function Hie(r,e){if(TN(r)&&(IN(r),AN(r))){Vie(r,e);return}(0,kN.boolOrEmptySchema)(r,e)}function AN({schema:r,self:e}){if(typeof r=="boolean")return!r;for(let t in r)if(e.RULES.all[t])return!0;return!1}function TN(r){return typeof r.schema!="boolean"}function Vie(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&RN(r),Zie(r),Yie(r);let a=n.const("_errs",Et.default.errors);DN(r,a),n.var(e,(0,Ze._)`${a} === ${Et.default.errors}`)}function IN(r){(0,$l.checkUnknownRules)(r),Wie(r)}function DN(r,e){if(r.opts.jtd)return EN(r,[],!1,e);let t=(0,PN.getSchemaTypes)(r.schema),n=(0,PN.coerceAndCheckDataType)(r,t);EN(r,t,!n,e)}function Wie(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,$l.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function Jie(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,$l.checkStrictMode)(r,"default is ignored in the schema root")}function Zie(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,Nie.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function Yie(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function RN({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let a=t.$comment;if(i.$comment===!0)r.code((0,Ze._)`${Et.default.self}.logger.log(${a})`);else if(typeof i.$comment=="function"){let s=(0,Ze.str)`${n}/$comment`,o=r.scopeValue("root",{ref:e.root});r.code((0,Ze._)`${Et.default.self}.opts.$comment(${a}, ${s}, ${o}.schema)`)}}function Xie(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:a}=r;t.$async?e.if((0,Ze._)`${Et.default.errors} === 0`,()=>e.return(Et.default.data),()=>e.throw((0,Ze._)`new ${i}(${Et.default.vErrors})`)):(e.assign((0,Ze._)`${n}.errors`,Et.default.vErrors),a.unevaluated&&Qie(r),e.return((0,Ze._)`${Et.default.errors} === 0`))}function Qie({gen:r,evaluated:e,props:t,items:n}){t instanceof Ze.Name&&r.assign((0,Ze._)`${e}.props`,t),n instanceof Ze.Name&&r.assign((0,Ze._)`${e}.items`,n)}function EN(r,e,t,n){let{gen:i,schema:a,data:s,allErrors:o,opts:c,self:l}=r,{RULES:d}=l;if(a.$ref&&(c.ignoreKeywordsWithRef||!(0,$l.schemaHasRulesButRef)(a,d))){i.block(()=>$N(r,"$ref",d.all.$ref.definition));return}c.jtd||ese(r,e),i.block(()=>{for(let f of d.rules)u(f);u(d.post)});function u(f){(0,DD.shouldUseGroup)(a,f)&&(f.type?(i.if((0,Mx.checkDataType)(f.type,s,c.strictNumbers)),SN(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Mx.reportTypeError)(r)),i.endIf()):SN(r,f),o||i.if((0,Ze._)`${Et.default.errors} === ${n||0}`))}}function SN(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,Uie.assignDefaults)(r,e.type),t.block(()=>{for(let a of e.rules)(0,DD.shouldUseRule)(n,a)&&$N(r,a.keyword,a.definition,e.type)})}function ese(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(tse(r,e),r.opts.allowUnionTypes||rse(r,e),nse(r,r.dataTypes))}function tse(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{CN(r.dataTypes,t)||RD(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),sse(r,e)}}function rse(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&RD(r,"use allowUnionTypes to allow union type keyword")}function nse(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,DD.shouldUseRule)(r.schema,i)){let{type:a}=i.definition;a.length&&!a.some(s=>ise(e,s))&&RD(r,`missing type "${a.join(",")}" for keyword "${n}"`)}}}function ise(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function CN(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function sse(r,e){let t=[];for(let n of r.dataTypes)CN(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function RD(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,$l.checkStrictMode)(r,e,r.opts.strictTypes)}var Kx=class{constructor(e,t,n){if((0,s0.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,$l.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",BN(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,s0.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Et.default.errors))}result(e,t,n){this.failResult((0,Ze.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,Ze.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,Ze._)`${t} !== undefined && (${(0,Ze.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?i0.reportExtraError:i0.reportError)(this,this.def.error,t)}$dataError(){(0,i0.reportError)(this,this.def.$dataError||i0.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,i0.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=Ze.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=Ze.nil,t=Ze.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:a,def:s}=this;n.if((0,Ze.or)((0,Ze._)`${i} === undefined`,t)),e!==Ze.nil&&n.assign(e,!0),(a.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Ze.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:a}=this;return(0,Ze.or)(s(),o());function s(){if(n.length){if(!(t instanceof Ze.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Ze._)`${(0,Mx.checkDataTypes)(c,t,a.opts.strictNumbers,Mx.DataType.Wrong)}`}return Ze.nil}function o(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,Ze._)`!${c}(${t})`}return Ze.nil}}subschema(e,t){let n=(0,ID.getSubschema)(this.it,e);(0,ID.extendSubschemaData)(n,this.it,e),(0,ID.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return Hie(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=$l.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=$l.mergeEvaluated.items(i,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,Ze.Name)),!0}};rf.KeywordCxt=Kx;function $N(r,e,t,n){let i=new Kx(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,s0.funcKeywordCode)(i,t):"macro"in t?(0,s0.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,s0.funcKeywordCode)(i,t)}var ose=/^\/(?:[^~]|~0|~1)*$/,ase=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function BN(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,a;if(r==="")return Et.default.rootData;if(r[0]==="/"){if(!ose.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,a=Et.default.rootData}else{let l=ase.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let d=+l[1];if(i=l[2],i==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(a=t[e-d],!i)return a}let s=a,o=i.split("/");for(let l of o)l&&(a=(0,Ze._)`${a}${(0,Ze.getProperty)((0,$l.unescapeJsonPointer)(l))}`,s=(0,Ze._)`${s} && ${a}`);return s;function c(l,d){return`Cannot access ${l} ${d} levels up, current level is ${e}`}}rf.getData=BN});var Ux=ke($D=>{"use strict";g();Object.defineProperty($D,"__esModule",{value:!0});var CD=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};$D.default=CD});var a0=ke(jD=>{"use strict";g();Object.defineProperty(jD,"__esModule",{value:!0});var BD=n0(),OD=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,BD.resolveUrl)(e,t,n),this.missingSchema=(0,BD.normalizeId)((0,BD.getFullPath)(e,this.missingRef))}};jD.default=OD});var c0=ke(xa=>{"use strict";g();Object.defineProperty(xa,"__esModule",{value:!0});xa.resolveSchema=xa.getCompilingSchema=xa.resolveRef=xa.compileSchema=xa.SchemaEnv=void 0;var Sc=Dt(),cse=Ux(),Xp=ba(),kc=n0(),ON=Vt(),dse=o0(),Dy=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,kc.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};xa.SchemaEnv=Dy;function KD(r){let e=jN.call(this,r);if(e)return e;let t=(0,kc.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:a}=this.opts,s=new Sc.CodeGen(this.scope,{es5:n,lines:i,ownProperties:a}),o;r.$async&&(o=s.scopeValue("Error",{ref:cse.default,code:(0,Sc._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");r.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Xp.default.data,parentData:Xp.default.parentData,parentDataProperty:Xp.default.parentDataProperty,dataNames:[Xp.default.data],dataPathArr:[Sc.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Sc.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:o,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Sc.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Sc._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(r),(0,dse.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let u=s.toString();d=`${s.scopeRefs(Xp.default.scope)}return ${u}`,this.opts.code.process&&(d=this.opts.code.process(d,r));let p=new Function(`${Xp.default.self}`,`${Xp.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=r.schema,p.schemaEnv=r,r.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:u,scopeValues:s._values}),this.opts.unevaluated){let{props:h,items:m}=l;p.evaluated={props:h instanceof Sc.Name?void 0:h,items:m instanceof Sc.Name?void 0:m,dynamicProps:h instanceof Sc.Name,dynamicItems:m instanceof Sc.Name},p.source&&(p.source.evaluated=(0,Sc.stringify)(p.evaluated))}return r.validate=p,r}catch(u){throw delete r.validate,delete r.validateName,d&&this.logger.error("Error compiling schema, function code:",d),u}finally{this._compilations.delete(r)}}xa.compileSchema=KD;function lse(r,e,t){var n;t=(0,kc.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let a=pse.call(this,r,t);if(a===void 0){let s=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:o}=this.opts;s&&(a=new Dy({schema:s,schemaId:o,root:r,baseId:e}))}if(a!==void 0)return r.refs[t]=use.call(this,a)}xa.resolveRef=lse;function use(r){return(0,kc.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:KD.call(this,r)}function jN(r){for(let e of this._compilations)if(fse(e,r))return e}xa.getCompilingSchema=jN;function fse(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function pse(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Nx.call(this,r,e)}function Nx(r,e){let t=this.opts.uriResolver.parse(e),n=(0,kc._getFullPath)(this.opts.uriResolver,t),i=(0,kc.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return MD.call(this,t,r);let a=(0,kc.normalizeId)(n),s=this.refs[a]||this.schemas[a];if(typeof s=="string"){let o=Nx.call(this,r,s);return typeof o?.schema!="object"?void 0:MD.call(this,t,o)}if(typeof s?.schema=="object"){if(s.validate||KD.call(this,s),a===(0,kc.normalizeId)(e)){let{schema:o}=s,{schemaId:c}=this.opts,l=o[c];return l&&(i=(0,kc.resolveUrl)(this.opts.uriResolver,i,l)),new Dy({schema:o,schemaId:c,root:r,baseId:i})}return MD.call(this,t,s)}}xa.resolveSchema=Nx;var hse=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function MD(r,{baseId:e,schema:t,root:n}){var i;if(((i=r.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let o of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let c=t[(0,ON.unescapeFragment)(o)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!hse.has(o)&&l&&(e=(0,kc.resolveUrl)(this.opts.uriResolver,e,l))}let a;if(typeof t!="boolean"&&t.$ref&&!(0,ON.schemaHasRulesButRef)(t,this.RULES)){let o=(0,kc.resolveUrl)(this.opts.uriResolver,e,t.$ref);a=Nx.call(this,n,o)}let{schemaId:s}=this.opts;if(a=a||new Dy({schema:t,schemaId:s,root:n,baseId:e}),a.schema!==a.root.schema)return a}});var MN=ke((A4e,mse)=>{mse.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var ND=ke((T4e,LN)=>{"use strict";g();var yse=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),UN=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function UD(r){let e="",t=0,n=0;for(n=0;n<r.length;n++)if(t=r[n].charCodeAt(0),t!==48){if(!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n];break}for(n+=1;n<r.length;n++){if(t=r[n].charCodeAt(0),!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n]}return e}var gse=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function KN(r){return r.length=0,!0}function wse(r,e,t){if(r.length){let n=UD(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function vse(r){let e=0,t={error:!1,address:"",zone:""},n=[],i=[],a=!1,s=!1,o=wse;for(let c=0;c<r.length;c++){let l=r[c];if(!(l==="["||l==="]"))if(l===":"){if(a===!0&&(s=!0),!o(i,n,t))break;if(++e>7){t.error=!0;break}c>0&&r[c-1]===":"&&(a=!0),n.push(":");continue}else if(l==="%"){if(!o(i,n,t))break;o=KN}else{i.push(l);continue}}return i.length&&(o===KN?t.zone=i.join(""):s?n.push(i.join("")):n.push(UD(i))),t.address=n.join(""),t}function NN(r){if(bse(r,":")<2)return{host:r,isIPV6:!1};let e=vse(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:n}}}function bse(r,e){let t=0;for(let n=0;n<r.length;n++)r[n]===e&&t++;return t}function Pse(r){let e=r,t=[],n=-1,i=0;for(;i=e.length;){if(i===1){if(e===".")break;if(e==="/"){t.push("/");break}else{t.push(e);break}}else if(i===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){t.push("/");break}}else if(i===3&&e==="/.."){t.length!==0&&t.pop(),t.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),t.length!==0&&t.pop();continue}}if((n=e.indexOf("/",1))===-1){t.push(e);break}else t.push(e.slice(0,n)),e=e.slice(n)}return t.join("")}function xse(r,e){let t=e!==!0?escape:unescape;return r.scheme!==void 0&&(r.scheme=t(r.scheme)),r.userinfo!==void 0&&(r.userinfo=t(r.userinfo)),r.host!==void 0&&(r.host=t(r.host)),r.path!==void 0&&(r.path=t(r.path)),r.query!==void 0&&(r.query=t(r.query)),r.fragment!==void 0&&(r.fragment=t(r.fragment)),r}function Ese(r){let e=[];if(r.userinfo!==void 0&&(e.push(r.userinfo),e.push("@")),r.host!==void 0){let t=unescape(r.host);if(!UN(t)){let n=NN(t);n.isIPV6===!0?t=`[${n.escapedHost}]`:t=r.host}e.push(t)}return(typeof r.port=="number"||typeof r.port=="string")&&(e.push(":"),e.push(String(r.port))),e.length?e.join(""):void 0}LN.exports={nonSimpleDomain:gse,recomposeAuthority:Ese,normalizeComponentEncoding:xse,removeDotSegments:Pse,isIPv4:UN,isUUID:yse,normalizeIPv6:NN,stringArrayToHexStripped:UD}});var HN=ke((D4e,GN)=>{"use strict";g();var{isUUID:Sse}=ND(),kse=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,_se=["http","https","ws","wss","urn","urn:uuid"];function Ase(r){return _se.indexOf(r)!==-1}function LD(r){return r.secure===!0?!0:r.secure===!1?!1:r.scheme?r.scheme.length===3&&(r.scheme[0]==="w"||r.scheme[0]==="W")&&(r.scheme[1]==="s"||r.scheme[1]==="S")&&(r.scheme[2]==="s"||r.scheme[2]==="S"):!1}function qN(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function zN(r){let e=String(r.scheme).toLowerCase()==="https";return(r.port===(e?443:80)||r.port==="")&&(r.port=void 0),r.path||(r.path="/"),r}function Tse(r){return r.secure=LD(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function Ise(r){if((r.port===(LD(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function Dse(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(kse);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,a=qD(i);r.path=void 0,a&&(r=a.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function Rse(r,e){if(r.nid===void 0)throw new Error("URN without nid cannot be serialized");let t=e.scheme||r.scheme||"urn",n=r.nid.toLowerCase(),i=`${t}:${e.nid||n}`,a=qD(i);a&&(r=a.serialize(r,e));let s=r,o=r.nss;return s.path=`${n||e.nid}:${o}`,e.skipEscape=!0,s}function Cse(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!Sse(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function $se(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var FN={scheme:"http",domainHost:!0,parse:qN,serialize:zN},Bse={scheme:"https",domainHost:FN.domainHost,parse:qN,serialize:zN},Lx={scheme:"ws",domainHost:!0,parse:Tse,serialize:Ise},Ose={scheme:"wss",domainHost:Lx.domainHost,parse:Lx.parse,serialize:Lx.serialize},jse={scheme:"urn",parse:Dse,serialize:Rse,skipNormalize:!0},Mse={scheme:"urn:uuid",parse:Cse,serialize:$se,skipNormalize:!0},qx={http:FN,https:Bse,ws:Lx,wss:Ose,urn:jse,"urn:uuid":Mse};Object.setPrototypeOf(qx,null);function qD(r){return r&&(qx[r]||qx[r.toLowerCase()])||void 0}GN.exports={wsIsSecure:LD,SCHEMES:qx,isValidSchemeName:Ase,getSchemeHandler:qD}});var JN=ke((C4e,Fx)=>{"use strict";g();var{normalizeIPv6:Kse,removeDotSegments:d0,recomposeAuthority:Use,normalizeComponentEncoding:zx,isIPv4:Nse,nonSimpleDomain:Lse}=ND(),{SCHEMES:qse,getSchemeHandler:VN}=HN();function zse(r,e){return typeof r=="string"?r=xd(Bl(r,e),e):typeof r=="object"&&(r=Bl(xd(r,e),e)),r}function Fse(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},i=WN(Bl(r,n),Bl(e,n),n,!0);return n.skipEscape=!0,xd(i,n)}function WN(r,e,t,n){let i={};return n||(r=Bl(xd(r,t),t),e=Bl(xd(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=d0(e.path||""),i.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=d0(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=d0(e.path):((r.userinfo!==void 0||r.host!==void 0||r.port!==void 0)&&!r.path?i.path="/"+e.path:r.path?i.path=r.path.slice(0,r.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=d0(i.path)),i.query=e.query):(i.path=r.path,e.query!==void 0?i.query=e.query:i.query=r.query),i.userinfo=r.userinfo,i.host=r.host,i.port=r.port),i.scheme=r.scheme),i.fragment=e.fragment,i}function Gse(r,e,t){return typeof r=="string"?(r=unescape(r),r=xd(zx(Bl(r,t),!0),{...t,skipEscape:!0})):typeof r=="object"&&(r=xd(zx(r,!0),{...t,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=xd(zx(Bl(e,t),!0),{...t,skipEscape:!0})):typeof e=="object"&&(e=xd(zx(e,!0),{...t,skipEscape:!0})),r.toLowerCase()===e.toLowerCase()}function xd(r,e){let t={host:r.host,scheme:r.scheme,userinfo:r.userinfo,port:r.port,path:r.path,query:r.query,nid:r.nid,nss:r.nss,uuid:r.uuid,fragment:r.fragment,reference:r.reference,resourceName:r.resourceName,secure:r.secure,error:""},n=Object.assign({},e),i=[],a=VN(n.scheme||t.scheme);a&&a.serialize&&a.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=unescape(t.path):(t.path=escape(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&i.push(t.scheme,":");let s=Use(t);if(s!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(s),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let o=t.path;!n.absolutePath&&(!a||!a.absolutePath)&&(o=d0(o)),s===void 0&&o[0]==="/"&&o[1]==="/"&&(o="/%2F"+o.slice(2)),i.push(o)}return t.query!==void 0&&i.push("?",t.query),t.fragment!==void 0&&i.push("#",t.fragment),i.join("")}var Hse=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Bl(r,e){let t=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let a=r.match(Hse);if(a){if(n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]),n.host)if(Nse(n.host)===!1){let c=Kse(n.host);n.host=c.host.toLowerCase(),i=c.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==n.reference&&(n.error=n.error||"URI is not a "+t.reference+" reference.");let s=VN(t.scheme||n.scheme);if(!t.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(t.domainHost||s&&s.domainHost)&&i===!1&&Lse(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(o){n.error=n.error||"Host's domain name can not be converted to ASCII: "+o}(!s||s&&!s.skipNormalize)&&(r.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s&&s.parse&&s.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return n}var zD={SCHEMES:qse,normalize:zse,resolve:Fse,resolveComponent:WN,equal:Gse,serialize:xd,parse:Bl};Fx.exports=zD;Fx.exports.default=zD;Fx.exports.fastUri=zD});var YN=ke(FD=>{"use strict";g();Object.defineProperty(FD,"__esModule",{value:!0});var ZN=JN();ZN.code='require("ajv/dist/runtime/uri").default';FD.default=ZN});var sL=ke(Wi=>{"use strict";g();Object.defineProperty(Wi,"__esModule",{value:!0});Wi.CodeGen=Wi.Name=Wi.nil=Wi.stringify=Wi.str=Wi._=Wi.KeywordCxt=void 0;var Vse=o0();Object.defineProperty(Wi,"KeywordCxt",{enumerable:!0,get:function(){return Vse.KeywordCxt}});var Ry=Dt();Object.defineProperty(Wi,"_",{enumerable:!0,get:function(){return Ry._}});Object.defineProperty(Wi,"str",{enumerable:!0,get:function(){return Ry.str}});Object.defineProperty(Wi,"stringify",{enumerable:!0,get:function(){return Ry.stringify}});Object.defineProperty(Wi,"nil",{enumerable:!0,get:function(){return Ry.nil}});Object.defineProperty(Wi,"Name",{enumerable:!0,get:function(){return Ry.Name}});Object.defineProperty(Wi,"CodeGen",{enumerable:!0,get:function(){return Ry.CodeGen}});var Wse=Ux(),rL=a0(),Jse=vD(),l0=c0(),Zse=Dt(),u0=n0(),Gx=r0(),HD=Vt(),XN=MN(),Yse=YN(),nL=(r,e)=>new RegExp(r,e);nL.code="new RegExp";var Xse=["removeAdditional","useDefaults","coerceTypes"],Qse=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),eoe={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},toe={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},QN=200;function roe(r){var e,t,n,i,a,s,o,c,l,d,u,f,p,h,m,y,v,w,E,_,A,D,M,C,z;let L=r.strict,B=(e=r.code)===null||e===void 0?void 0:e.optimize,W=B===!0||B===void 0?1:B||0,ee=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:nL,R=(i=r.uriResolver)!==null&&i!==void 0?i:Yse.default;return{strictSchema:(s=(a=r.strictSchema)!==null&&a!==void 0?a:L)!==null&&s!==void 0?s:!0,strictNumbers:(c=(o=r.strictNumbers)!==null&&o!==void 0?o:L)!==null&&c!==void 0?c:!0,strictTypes:(d=(l=r.strictTypes)!==null&&l!==void 0?l:L)!==null&&d!==void 0?d:"log",strictTuples:(f=(u=r.strictTuples)!==null&&u!==void 0?u:L)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=r.strictRequired)!==null&&p!==void 0?p:L)!==null&&h!==void 0?h:!1,code:r.code?{...r.code,optimize:W,regExp:ee}:{optimize:W,regExp:ee},loopRequired:(m=r.loopRequired)!==null&&m!==void 0?m:QN,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:QN,meta:(v=r.meta)!==null&&v!==void 0?v:!0,messages:(w=r.messages)!==null&&w!==void 0?w:!0,inlineRefs:(E=r.inlineRefs)!==null&&E!==void 0?E:!0,schemaId:(_=r.schemaId)!==null&&_!==void 0?_:"$id",addUsedSchema:(A=r.addUsedSchema)!==null&&A!==void 0?A:!0,validateSchema:(D=r.validateSchema)!==null&&D!==void 0?D:!0,validateFormats:(M=r.validateFormats)!==null&&M!==void 0?M:!0,unicodeRegExp:(C=r.unicodeRegExp)!==null&&C!==void 0?C:!0,int32range:(z=r.int32range)!==null&&z!==void 0?z:!0,uriResolver:R}}var f0=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...roe(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new Zse.ValueScope({scope:{},prefixes:Qse,es5:t,lines:n}),this.logger=coe(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Jse.getRules)(),eL.call(this,eoe,e,"NOT SUPPORTED"),eL.call(this,toe,e,"DEPRECATED","warn"),this._metaOpts=ooe.call(this),e.formats&&ioe.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&soe.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),noe.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=XN;n==="id"&&(i={...XN},i.id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let i=n(t);return"$async"in n||(this.errors=n.errors),i}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,e,t);async function i(d,u){await a.call(this,d.$schema);let f=this._addSchema(d,u);return f.validate||s.call(this,f)}async function a(d){d&&!this.getSchema(d)&&await i.call(this,{$ref:d},!0)}async function s(d){try{return this._compileSchemaEnv(d)}catch(u){if(!(u instanceof rL.default))throw u;return o.call(this,u),await c.call(this,u.missingSchema),s.call(this,d)}}function o({missingSchema:d,missingRef:u}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${u} cannot be resolved`)}async function c(d){let u=await l.call(this,d);this.refs[d]||await a.call(this,u.$schema),this.refs[d]||this.addSchema(u,d,t)}async function l(d){let u=this._loading[d];if(u)return u;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,t,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,n,i);return this}let a;if(typeof e=="object"){let{schemaId:s}=this.opts;if(a=e[s],a!==void 0&&typeof a!="string")throw new Error(`schema ${s} must be string`)}return t=(0,u0.normalizeId)(t||a),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,i,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,e);if(!i&&t){let a="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(a);else throw new Error(a)}return i}getSchema(e){let t;for(;typeof(t=tL.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new l0.SchemaEnv({schema:{},schemaId:n});if(t=l0.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=tL.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,u0.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e=="string")n=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else if(typeof e=="object"&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(loe.call(this,n,t),!t)return(0,HD.eachItem)(n,a=>GD.call(this,a)),this;foe.call(this,t);let i={...t,type:(0,Gx.getJSONTypes)(t.type),schemaType:(0,Gx.getJSONTypes)(t.schemaType)};return(0,HD.eachItem)(n,i.type.length===0?a=>GD.call(this,a,i):a=>i.type.forEach(s=>GD.call(this,a,i,s))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let i=n.rules.findIndex(a=>a.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,a)=>i+t+a)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let a=i.split("/").slice(1),s=e;for(let o of a)s=s[o];for(let o in n){let c=n[o];if(typeof c!="object")continue;let{$data:l}=c.definition,d=s[o];l&&d&&(s[o]=iL(d))}}return e}_removeAllSchemas(e,t){for(let n in e){let i=e[n];(!t||t.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,t,n,i=this.opts.validateSchema,a=this.opts.addUsedSchema){let s,{schemaId:o}=this.opts;if(typeof e=="object")s=e[o];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,u0.normalizeId)(s||n);let l=u0.getSchemaRefs.call(this,e,n);return c=new l0.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:n,localRefs:l}),this._cache.set(c.schema,c),a&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):l0.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{l0.compileSchema.call(this,e)}finally{this.opts=t}}};f0.ValidationError=Wse.default;f0.MissingRefError=rL.default;Wi.default=f0;function eL(r,e,t,n="error"){for(let i in r){let a=i;a in e&&this.logger[n](`${t}: option ${i}. ${r[a]}`)}}function tL(r){return r=(0,u0.normalizeId)(r),this.schemas[r]||this.refs[r]}function noe(){let r=this.opts.schemas;if(r)if(Array.isArray(r))this.addSchema(r);else for(let e in r)this.addSchema(r[e],e)}function ioe(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function soe(r){if(Array.isArray(r)){this.addVocabulary(r);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in r){let t=r[e];t.keyword||(t.keyword=e),this.addKeyword(t)}}function ooe(){let r={...this.opts};for(let e of Xse)delete r[e];return r}var aoe={log(){},warn(){},error(){}};function coe(r){if(r===!1)return aoe;if(r===void 0)return console;if(r.log&&r.warn&&r.error)return r;throw new Error("logger must implement log, warn and error methods")}var doe=/^[a-z_$][a-z0-9_$:-]*$/i;function loe(r,e){let{RULES:t}=this;if((0,HD.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!doe.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function GD(r,e,t){var n;let i=e?.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,s=i?a.post:a.rules.find(({type:c})=>c===t);if(s||(s={type:t,rules:[]},a.rules.push(s)),a.keywords[r]=!0,!e)return;let o={keyword:r,definition:{...e,type:(0,Gx.getJSONTypes)(e.type),schemaType:(0,Gx.getJSONTypes)(e.schemaType)}};e.before?uoe.call(this,s,o,e.before):s.rules.push(o),a.all[r]=o,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function uoe(r,e,t){let n=r.rules.findIndex(i=>i.keyword===t);n>=0?r.rules.splice(n,0,e):(r.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function foe(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=iL(e)),r.validateSchema=this.compile(e,!0))}var poe={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function iL(r){return{anyOf:[r,poe]}}});var oL=ke(VD=>{"use strict";g();Object.defineProperty(VD,"__esModule",{value:!0});var hoe={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};VD.default=hoe});var Wx=ke(Qp=>{"use strict";g();Object.defineProperty(Qp,"__esModule",{value:!0});Qp.callRef=Qp.getValidate=void 0;var moe=a0(),aL=Pa(),ho=Dt(),Cy=ba(),cL=c0(),Hx=Vt(),yoe={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:n}=r,{baseId:i,schemaEnv:a,validateName:s,opts:o,self:c}=n,{root:l}=a;if((t==="#"||t==="#/")&&i===l.baseId)return u();let d=cL.resolveRef.call(c,l,i,t);if(d===void 0)throw new moe.default(n.opts.uriResolver,i,t);if(d instanceof cL.SchemaEnv)return f(d);return p(d);function u(){if(a===l)return Vx(r,s,a,a.$async);let h=e.scopeValue("root",{ref:l});return Vx(r,(0,ho._)`${h}.validate`,l,l.$async)}function f(h){let m=dL(r,h);Vx(r,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",o.code.source===!0?{ref:h,code:(0,ho.stringify)(h)}:{ref:h}),y=e.name("valid"),v=r.subschema({schema:h,dataTypes:[],schemaPath:ho.nil,topSchemaRef:m,errSchemaPath:t},y);r.mergeEvaluated(v),r.ok(y)}}};function dL(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,ho._)`${t.scopeValue("wrapper",{ref:e})}.validate`}Qp.getValidate=dL;function Vx(r,e,t,n){let{gen:i,it:a}=r,{allErrors:s,schemaEnv:o,opts:c}=a,l=c.passContext?Cy.default.this:ho.nil;n?d():u();function d(){if(!o.$async)throw new Error("async schema referenced by sync schema");let h=i.let("valid");i.try(()=>{i.code((0,ho._)`await ${(0,aL.callValidateCode)(r,e,l)}`),p(e),s||i.assign(h,!0)},m=>{i.if((0,ho._)`!(${m} instanceof ${a.ValidationError})`,()=>i.throw(m)),f(m),s||i.assign(h,!1)}),r.ok(h)}function u(){r.result((0,aL.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(h){let m=(0,ho._)`${h}.errors`;i.assign(Cy.default.vErrors,(0,ho._)`${Cy.default.vErrors} === null ? ${m} : ${Cy.default.vErrors}.concat(${m})`),i.assign(Cy.default.errors,(0,ho._)`${Cy.default.vErrors}.length`)}function p(h){var m;if(!a.opts.unevaluated)return;let y=(m=t?.validate)===null||m===void 0?void 0:m.evaluated;if(a.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(a.props=Hx.mergeEvaluated.props(i,y.props,a.props));else{let v=i.var("props",(0,ho._)`${h}.evaluated.props`);a.props=Hx.mergeEvaluated.props(i,v,a.props,ho.Name)}if(a.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(a.items=Hx.mergeEvaluated.items(i,y.items,a.items));else{let v=i.var("items",(0,ho._)`${h}.evaluated.items`);a.items=Hx.mergeEvaluated.items(i,v,a.items,ho.Name)}}}Qp.callRef=Vx;Qp.default=yoe});var lL=ke(WD=>{"use strict";g();Object.defineProperty(WD,"__esModule",{value:!0});var goe=oL(),woe=Wx(),voe=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",goe.default,woe.default];WD.default=voe});var uL=ke(JD=>{"use strict";g();Object.defineProperty(JD,"__esModule",{value:!0});var Jx=Dt(),nf=Jx.operators,Zx={maximum:{okStr:"<=",ok:nf.LTE,fail:nf.GT},minimum:{okStr:">=",ok:nf.GTE,fail:nf.LT},exclusiveMaximum:{okStr:"<",ok:nf.LT,fail:nf.GTE},exclusiveMinimum:{okStr:">",ok:nf.GT,fail:nf.LTE}},boe={message:({keyword:r,schemaCode:e})=>(0,Jx.str)`must be ${Zx[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Jx._)`{comparison: ${Zx[r].okStr}, limit: ${e}}`},Poe={keyword:Object.keys(Zx),type:"number",schemaType:"number",$data:!0,error:boe,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,Jx._)`${t} ${Zx[e].fail} ${n} || isNaN(${t})`)}};JD.default=Poe});var fL=ke(ZD=>{"use strict";g();Object.defineProperty(ZD,"__esModule",{value:!0});var p0=Dt(),xoe={message:({schemaCode:r})=>(0,p0.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,p0._)`{multipleOf: ${r}}`},Eoe={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:xoe,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,a=i.opts.multipleOfPrecision,s=e.let("res"),o=a?(0,p0._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${a}`:(0,p0._)`${s} !== parseInt(${s})`;r.fail$data((0,p0._)`(${n} === 0 || (${s} = ${t}/${n}, ${o}))`)}};ZD.default=Eoe});var pL=ke(YD=>{"use strict";g();Object.defineProperty(YD,"__esModule",{value:!0});var eh=Dt(),Soe=Vt(),koe=Yk(),_oe={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,eh.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,eh._)`{limit: ${r}}`},Aoe={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:_oe,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,a=e==="maxLength"?eh.operators.GT:eh.operators.LT,s=i.opts.unicode===!1?(0,eh._)`${t}.length`:(0,eh._)`${(0,Soe.useFunc)(r.gen,koe.default)}(${t})`;r.fail$data((0,eh._)`${s} ${a} ${n}`)}};YD.default=Aoe});var hL=ke(XD=>{"use strict";g();Object.defineProperty(XD,"__esModule",{value:!0});var Toe=Pa(),Ioe=Vt(),$y=Dt(),Doe={message:({schemaCode:r})=>(0,$y.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,$y._)`{pattern: ${r}}`},Roe={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Doe,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:a,it:s}=r,o=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,$y._)`new RegExp`:(0,Ioe.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,$y._)`${l}(${a}, ${o}).test(${t})`),()=>e.assign(d,!1)),r.fail$data((0,$y._)`!${d}`)}else{let c=(0,Toe.usePattern)(r,i);r.fail$data((0,$y._)`!${c}.test(${t})`)}}};XD.default=Roe});var mL=ke(QD=>{"use strict";g();Object.defineProperty(QD,"__esModule",{value:!0});var h0=Dt(),Coe={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,h0.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,h0._)`{limit: ${r}}`},$oe={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Coe,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?h0.operators.GT:h0.operators.LT;r.fail$data((0,h0._)`Object.keys(${t}).length ${i} ${n}`)}};QD.default=$oe});var yL=ke(eR=>{"use strict";g();Object.defineProperty(eR,"__esModule",{value:!0});var m0=Pa(),y0=Dt(),Boe=Vt(),Ooe={message:({params:{missingProperty:r}})=>(0,y0.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,y0._)`{missingProperty: ${r}}`},joe={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Ooe,code(r){let{gen:e,schema:t,schemaCode:n,data:i,$data:a,it:s}=r,{opts:o}=s;if(!a&&t.length===0)return;let c=t.length>=o.loopRequired;if(s.allErrors?l():d(),o.strictRequired){let p=r.parentSchema.properties,{definedProperties:h}=r.it;for(let m of t)if(p?.[m]===void 0&&!h.has(m)){let y=s.schemaEnv.baseId+s.errSchemaPath,v=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,Boe.checkStrictMode)(s,v,s.opts.strictRequired)}}function l(){if(c||a)r.block$data(y0.nil,u);else for(let p of t)(0,m0.checkReportMissingProp)(r,p)}function d(){let p=e.let("missing");if(c||a){let h=e.let("valid",!0);r.block$data(h,()=>f(p,h)),r.ok(h)}else e.if((0,m0.checkMissingProp)(r,t,p)),(0,m0.reportMissingProp)(r,p),e.else()}function u(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,m0.noPropertyInData)(e,i,p,o.ownProperties),()=>r.error())})}function f(p,h){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(h,(0,m0.propertyInData)(e,i,p,o.ownProperties)),e.if((0,y0.not)(h),()=>{r.error(),e.break()})},y0.nil)}}};eR.default=joe});var gL=ke(tR=>{"use strict";g();Object.defineProperty(tR,"__esModule",{value:!0});var g0=Dt(),Moe={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,g0.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,g0._)`{limit: ${r}}`},Koe={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Moe,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?g0.operators.GT:g0.operators.LT;r.fail$data((0,g0._)`${t}.length ${i} ${n}`)}};tR.default=Koe});var Yx=ke(rR=>{"use strict";g();Object.defineProperty(rR,"__esModule",{value:!0});var wL=AD();wL.code='require("ajv/dist/runtime/equal").default';rR.default=wL});var vL=ke(iR=>{"use strict";g();Object.defineProperty(iR,"__esModule",{value:!0});var nR=r0(),Ji=Dt(),Uoe=Vt(),Noe=Yx(),Loe={message:({params:{i:r,j:e}})=>(0,Ji.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,Ji._)`{i: ${r}, j: ${e}}`},qoe={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Loe,code(r){let{gen:e,data:t,$data:n,schema:i,parentSchema:a,schemaCode:s,it:o}=r;if(!n&&!i)return;let c=e.let("valid"),l=a.items?(0,nR.getSchemaTypes)(a.items):[];r.block$data(c,d,(0,Ji._)`${s} === false`),r.ok(c);function d(){let h=e.let("i",(0,Ji._)`${t}.length`),m=e.let("j");r.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,Ji._)`${h} > 1`,()=>(u()?f:p)(h,m))}function u(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function f(h,m){let y=e.name("item"),v=(0,nR.checkDataTypes)(l,y,o.opts.strictNumbers,nR.DataType.Wrong),w=e.const("indices",(0,Ji._)`{}`);e.for((0,Ji._)`;${h}--;`,()=>{e.let(y,(0,Ji._)`${t}[${h}]`),e.if(v,(0,Ji._)`continue`),l.length>1&&e.if((0,Ji._)`typeof ${y} == "string"`,(0,Ji._)`${y} += "_"`),e.if((0,Ji._)`typeof ${w}[${y}] == "number"`,()=>{e.assign(m,(0,Ji._)`${w}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,Ji._)`${w}[${y}] = ${h}`)})}function p(h,m){let y=(0,Uoe.useFunc)(e,Noe.default),v=e.name("outer");e.label(v).for((0,Ji._)`;${h}--;`,()=>e.for((0,Ji._)`${m} = ${h}; ${m}--;`,()=>e.if((0,Ji._)`${y}(${t}[${h}], ${t}[${m}])`,()=>{r.error(),e.assign(c,!1).break(v)})))}}};iR.default=qoe});var bL=ke(oR=>{"use strict";g();Object.defineProperty(oR,"__esModule",{value:!0});var sR=Dt(),zoe=Vt(),Foe=Yx(),Goe={message:"must be equal to constant",params:({schemaCode:r})=>(0,sR._)`{allowedValue: ${r}}`},Hoe={keyword:"const",$data:!0,error:Goe,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:a}=r;n||a&&typeof a=="object"?r.fail$data((0,sR._)`!${(0,zoe.useFunc)(e,Foe.default)}(${t}, ${i})`):r.fail((0,sR._)`${a} !== ${t}`)}};oR.default=Hoe});var PL=ke(aR=>{"use strict";g();Object.defineProperty(aR,"__esModule",{value:!0});var w0=Dt(),Voe=Vt(),Woe=Yx(),Joe={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,w0._)`{allowedValues: ${r}}`},Zoe={keyword:"enum",schemaType:"array",$data:!0,error:Joe,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:a,it:s}=r;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let o=i.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,Voe.useFunc)(e,Woe.default)),d;if(o||n)d=e.let("valid"),r.block$data(d,u);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",a);d=(0,w0.or)(...i.map((h,m)=>f(p,m)))}r.pass(d);function u(){e.assign(d,!1),e.forOf("v",a,p=>e.if((0,w0._)`${l()}(${t}, ${p})`,()=>e.assign(d,!0).break()))}function f(p,h){let m=i[h];return typeof m=="object"&&m!==null?(0,w0._)`${l()}(${t}, ${p}[${h}])`:(0,w0._)`${t} === ${m}`}}};aR.default=Zoe});var xL=ke(cR=>{"use strict";g();Object.defineProperty(cR,"__esModule",{value:!0});var Yoe=uL(),Xoe=fL(),Qoe=pL(),eae=hL(),tae=mL(),rae=yL(),nae=gL(),iae=vL(),sae=bL(),oae=PL(),aae=[Yoe.default,Xoe.default,Qoe.default,eae.default,tae.default,rae.default,nae.default,iae.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},sae.default,oae.default];cR.default=aae});var lR=ke(v0=>{"use strict";g();Object.defineProperty(v0,"__esModule",{value:!0});v0.validateAdditionalItems=void 0;var th=Dt(),dR=Vt(),cae={message:({params:{len:r}})=>(0,th.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,th._)`{limit: ${r}}`},dae={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:cae,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,dR.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}EL(r,n)}};function EL(r,e){let{gen:t,schema:n,data:i,keyword:a,it:s}=r;s.items=!0;let o=t.const("len",(0,th._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,th._)`${o} <= ${e.length}`);else if(typeof n=="object"&&!(0,dR.alwaysValidSchema)(s,n)){let l=t.var("valid",(0,th._)`${o} <= ${e.length}`);t.if((0,th.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,o,d=>{r.subschema({keyword:a,dataProp:d,dataPropType:dR.Type.Num},l),s.allErrors||t.if((0,th.not)(l),()=>t.break())})}}v0.validateAdditionalItems=EL;v0.default=dae});var uR=ke(b0=>{"use strict";g();Object.defineProperty(b0,"__esModule",{value:!0});b0.validateTuple=void 0;var SL=Dt(),Xx=Vt(),lae=Pa(),uae={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return kL(r,"additionalItems",e);t.items=!0,!(0,Xx.alwaysValidSchema)(t,e)&&r.ok((0,lae.validateArray)(r))}};function kL(r,e,t=r.schema){let{gen:n,parentSchema:i,data:a,keyword:s,it:o}=r;d(i),o.opts.unevaluated&&t.length&&o.items!==!0&&(o.items=Xx.mergeEvaluated.items(n,t.length,o.items));let c=n.name("valid"),l=n.const("len",(0,SL._)`${a}.length`);t.forEach((u,f)=>{(0,Xx.alwaysValidSchema)(o,u)||(n.if((0,SL._)`${l} > ${f}`,()=>r.subschema({keyword:s,schemaProp:f,dataProp:f},c)),r.ok(c))});function d(u){let{opts:f,errSchemaPath:p}=o,h=t.length,m=h===u.minItems&&(h===u.maxItems||u[e]===!1);if(f.strictTuples&&!m){let y=`"${s}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Xx.checkStrictMode)(o,y,f.strictTuples)}}}b0.validateTuple=kL;b0.default=uae});var _L=ke(fR=>{"use strict";g();Object.defineProperty(fR,"__esModule",{value:!0});var fae=uR(),pae={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,fae.validateTuple)(r,"items")};fR.default=pae});var TL=ke(pR=>{"use strict";g();Object.defineProperty(pR,"__esModule",{value:!0});var AL=Dt(),hae=Vt(),mae=Pa(),yae=lR(),gae={message:({params:{len:r}})=>(0,AL.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,AL._)`{limit: ${r}}`},wae={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:gae,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,hae.alwaysValidSchema)(n,e)&&(i?(0,yae.validateAdditionalItems)(r,i):r.ok((0,mae.validateArray)(r)))}};pR.default=wae});var IL=ke(hR=>{"use strict";g();Object.defineProperty(hR,"__esModule",{value:!0});var Ea=Dt(),Qx=Vt(),vae={message:({params:{min:r,max:e}})=>e===void 0?(0,Ea.str)`must contain at least ${r} valid item(s)`:(0,Ea.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Ea._)`{minContains: ${r}}`:(0,Ea._)`{minContains: ${r}, maxContains: ${e}}`},bae={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:vae,code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:a}=r,s,o,{minContains:c,maxContains:l}=n;a.opts.next?(s=c===void 0?1:c,o=l):s=1;let d=e.const("len",(0,Ea._)`${i}.length`);if(r.setParams({min:s,max:o}),o===void 0&&s===0){(0,Qx.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(o!==void 0&&s>o){(0,Qx.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,Qx.alwaysValidSchema)(a,t)){let m=(0,Ea._)`${d} >= ${s}`;o!==void 0&&(m=(0,Ea._)`${m} && ${d} <= ${o}`),r.pass(m);return}a.items=!0;let u=e.name("valid");o===void 0&&s===1?p(u,()=>e.if(u,()=>e.break())):s===0?(e.let(u,!0),o!==void 0&&e.if((0,Ea._)`${i}.length > 0`,f)):(e.let(u,!1),f()),r.result(u,()=>r.reset());function f(){let m=e.name("_valid"),y=e.let("count",0);p(m,()=>e.if(m,()=>h(y)))}function p(m,y){e.forRange("i",0,d,v=>{r.subschema({keyword:"contains",dataProp:v,dataPropType:Qx.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,Ea._)`${m}++`),o===void 0?e.if((0,Ea._)`${m} >= ${s}`,()=>e.assign(u,!0).break()):(e.if((0,Ea._)`${m} > ${o}`,()=>e.assign(u,!1).break()),s===1?e.assign(u,!0):e.if((0,Ea._)`${m} >= ${s}`,()=>e.assign(u,!0)))}}};hR.default=bae});var e2=ke(Ed=>{"use strict";g();Object.defineProperty(Ed,"__esModule",{value:!0});Ed.validateSchemaDeps=Ed.validatePropertyDeps=Ed.error=void 0;var mR=Dt(),Pae=Vt(),P0=Pa();Ed.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,mR.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,mR._)`{property: ${r},
8
8
  missingProperty: ${n},
9
9
  depsCount: ${e},
10
- deps: ${t}}`};var xae={keyword:"dependencies",type:"object",schemaType:"object",error:Ed.error,code(r){let[e,t]=Eae(r);DL(r,e),RL(r,t)}};function Eae({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let i=Array.isArray(r[n])?e:t;i[n]=r[n]}return[e,t]}function DL(r,e=r.schema){let{gen:t,data:n,it:i}=r;if(Object.keys(e).length===0)return;let a=t.let("missing");for(let s in e){let o=e[s];if(o.length===0)continue;let c=(0,P0.propertyInData)(t,n,s,i.opts.ownProperties);r.setParams({property:s,depsCount:o.length,deps:o.join(", ")}),i.allErrors?t.if(c,()=>{for(let l of o)(0,P0.checkReportMissingProp)(r,l)}):(t.if((0,mR._)`${c} && (${(0,P0.checkMissingProp)(r,o,a)})`),(0,P0.reportMissingProp)(r,a),t.else())}}Ed.validatePropertyDeps=DL;function RL(r,e=r.schema){let{gen:t,data:n,keyword:i,it:a}=r,s=t.name("valid");for(let o in e)(0,Pae.alwaysValidSchema)(a,e[o])||(t.if((0,P0.propertyInData)(t,n,o,a.opts.ownProperties),()=>{let c=r.subschema({keyword:i,schemaProp:o},s);r.mergeValidEvaluated(c,s)},()=>t.var(s,!0)),r.ok(s))}Ed.validateSchemaDeps=RL;Ed.default=xae});var $L=ke(yR=>{"use strict";g();Object.defineProperty(yR,"__esModule",{value:!0});var CL=Dt(),Sae=Vt(),kae={message:"property name must be valid",params:({params:r})=>(0,CL._)`{propertyName: ${r.propertyName}}`},_ae={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:kae,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,Sae.alwaysValidSchema)(i,t))return;let a=e.name("valid");e.forIn("key",n,s=>{r.setParams({propertyName:s}),r.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},a),e.if((0,CL.not)(a),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(a)}};yR.default=_ae});var wR=ke(gR=>{"use strict";g();Object.defineProperty(gR,"__esModule",{value:!0});var t2=Pa(),_c=Dt(),Aae=ba(),r2=Vt(),Tae={message:"must NOT have additional properties",params:({params:r})=>(0,_c._)`{additionalProperty: ${r.additionalProperty}}`},Iae={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Tae,code(r){let{gen:e,schema:t,parentSchema:n,data:i,errsCount:a,it:s}=r;if(!a)throw new Error("ajv implementation error");let{allErrors:o,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,r2.alwaysValidSchema)(s,t))return;let l=(0,t2.allSchemaProperties)(n.properties),d=(0,t2.allSchemaProperties)(n.patternProperties);u(),r.ok((0,_c._)`${a} === ${Aae.default.errors}`);function u(){e.forIn("key",i,y=>{!l.length&&!d.length?h(y):e.if(f(y),()=>h(y))})}function f(y){let v;if(l.length>8){let w=(0,r2.schemaRefOrVal)(s,n.properties,"properties");v=(0,t2.isOwnProperty)(e,w,y)}else l.length?v=(0,_c.or)(...l.map(w=>(0,_c._)`${y} === ${w}`)):v=_c.nil;return d.length&&(v=(0,_c.or)(v,...d.map(w=>(0,_c._)`${(0,t2.usePattern)(r,w)}.test(${y})`))),(0,_c.not)(v)}function p(y){e.code((0,_c._)`delete ${i}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),o||e.break();return}if(typeof t=="object"&&!(0,r2.alwaysValidSchema)(s,t)){let v=e.name("valid");c.removeAdditional==="failing"?(m(y,v,!1),e.if((0,_c.not)(v),()=>{r.reset(),p(y)})):(m(y,v),o||e.if((0,_c.not)(v),()=>e.break()))}}function m(y,v,w){let E={keyword:"additionalProperties",dataProp:y,dataPropType:r2.Type.Str};w===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(E,v)}}};gR.default=Iae});var jL=ke(bR=>{"use strict";g();Object.defineProperty(bR,"__esModule",{value:!0});var Dae=o0(),BL=Pa(),vR=Vt(),OL=wR(),Rae={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:a}=r;a.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&OL.default.code(new Dae.KeywordCxt(a,OL.default,"additionalProperties"));let s=(0,BL.allSchemaProperties)(t);for(let u of s)a.definedProperties.add(u);a.opts.unevaluated&&s.length&&a.props!==!0&&(a.props=vR.mergeEvaluated.props(e,(0,vR.toHash)(s),a.props));let o=s.filter(u=>!(0,vR.alwaysValidSchema)(a,t[u]));if(o.length===0)return;let c=e.name("valid");for(let u of o)l(u)?d(u):(e.if((0,BL.propertyInData)(e,i,u,a.opts.ownProperties)),d(u),a.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(u),r.ok(c);function l(u){return a.opts.useDefaults&&!a.compositeRule&&t[u].default!==void 0}function d(u){r.subschema({keyword:"properties",schemaProp:u,dataProp:u},c)}}};bR.default=Rae});var NL=ke(PR=>{"use strict";g();Object.defineProperty(PR,"__esModule",{value:!0});var ML=Pa(),n2=Dt(),KL=Vt(),UL=Vt(),Cae={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:i,it:a}=r,{opts:s}=a,o=(0,ML.allSchemaProperties)(t),c=o.filter(m=>(0,KL.alwaysValidSchema)(a,t[m]));if(o.length===0||c.length===o.length&&(!a.opts.unevaluated||a.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&i.properties,d=e.name("valid");a.props!==!0&&!(a.props instanceof n2.Name)&&(a.props=(0,UL.evaluatedPropsToName)(e,a.props));let{props:u}=a;f();function f(){for(let m of o)l&&p(m),a.allErrors?h(m):(e.var(d,!0),h(m),e.if(d))}function p(m){for(let y in l)new RegExp(m).test(y)&&(0,KL.checkStrictMode)(a,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,n2._)`${(0,ML.usePattern)(r,m)}.test(${y})`,()=>{let v=c.includes(m);v||r.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:UL.Type.Str},d),a.opts.unevaluated&&u!==!0?e.assign((0,n2._)`${u}[${y}]`,!0):!v&&!a.allErrors&&e.if((0,n2.not)(d),()=>e.break())})})}}};PR.default=Cae});var LL=ke(xR=>{"use strict";g();Object.defineProperty(xR,"__esModule",{value:!0});var $ae=Vt(),Bae={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,$ae.alwaysValidSchema)(n,t)){r.fail();return}let i=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};xR.default=Bae});var qL=ke(ER=>{"use strict";g();Object.defineProperty(ER,"__esModule",{value:!0});var Oae=Pa(),jae={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Oae.validateUnion,error:{message:"must match a schema in anyOf"}};ER.default=jae});var zL=ke(SR=>{"use strict";g();Object.defineProperty(SR,"__esModule",{value:!0});var i2=Dt(),Mae=Vt(),Kae={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,i2._)`{passingSchemas: ${r.passing}}`},Uae={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Kae,code(r){let{gen:e,schema:t,parentSchema:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let a=t,s=e.let("valid",!1),o=e.let("passing",null),c=e.name("_valid");r.setParams({passing:o}),e.block(l),r.result(s,()=>r.reset(),()=>r.error(!0));function l(){a.forEach((d,u)=>{let f;(0,Mae.alwaysValidSchema)(i,d)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},c),u>0&&e.if((0,i2._)`${c} && ${s}`).assign(s,!1).assign(o,(0,i2._)`[${o}, ${u}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(o,u),f&&r.mergeEvaluated(f,i2.Name)})})}}};SR.default=Uae});var FL=ke(kR=>{"use strict";g();Object.defineProperty(kR,"__esModule",{value:!0});var Nae=Vt(),Lae={keyword:"allOf",schemaType:"array",code(r){let{gen:e,schema:t,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");let i=e.name("valid");t.forEach((a,s)=>{if((0,Nae.alwaysValidSchema)(n,a))return;let o=r.subschema({keyword:"allOf",schemaProp:s},i);r.ok(i),r.mergeEvaluated(o)})}};kR.default=Lae});var VL=ke(_R=>{"use strict";g();Object.defineProperty(_R,"__esModule",{value:!0});var s2=Dt(),HL=Vt(),qae={message:({params:r})=>(0,s2.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,s2._)`{failingKeyword: ${r.ifClause}}`},zae={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:qae,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,HL.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=GL(n,"then"),a=GL(n,"else");if(!i&&!a)return;let s=e.let("valid",!0),o=e.name("_valid");if(c(),r.reset(),i&&a){let d=e.let("ifClause");r.setParams({ifClause:d}),e.if(o,l("then",d),l("else",d))}else i?e.if(o,l("then")):e.if((0,s2.not)(o),l("else"));r.pass(s,()=>r.error(!0));function c(){let d=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},o);r.mergeEvaluated(d)}function l(d,u){return()=>{let f=r.subschema({keyword:d},o);e.assign(s,o),r.mergeValidEvaluated(f,s),u?e.assign(u,(0,s2._)`${d}`):r.setParams({ifClause:d})}}}};function GL(r,e){let t=r.schema[e];return t!==void 0&&!(0,HL.alwaysValidSchema)(r,t)}_R.default=zae});var WL=ke(AR=>{"use strict";g();Object.defineProperty(AR,"__esModule",{value:!0});var Fae=Vt(),Gae={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,Fae.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};AR.default=Gae});var JL=ke(TR=>{"use strict";g();Object.defineProperty(TR,"__esModule",{value:!0});var Hae=lR(),Vae=_L(),Wae=uR(),Jae=TL(),Zae=IL(),Yae=e2(),Xae=$L(),Qae=wR(),ece=jL(),tce=NL(),rce=LL(),nce=qL(),ice=zL(),sce=FL(),oce=VL(),ace=WL();function cce(r=!1){let e=[rce.default,nce.default,ice.default,sce.default,oce.default,ace.default,Xae.default,Qae.default,Yae.default,ece.default,tce.default];return r?e.push(Vae.default,Jae.default):e.push(Hae.default,Wae.default),e.push(Zae.default),e}TR.default=cce});var DR=ke(x0=>{"use strict";g();Object.defineProperty(x0,"__esModule",{value:!0});x0.dynamicAnchor=void 0;var IR=Dt(),dce=ba(),ZL=c0(),lce=Wx(),uce={keyword:"$dynamicAnchor",schemaType:"string",code:r=>YL(r,r.schema)};function YL(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,IR._)`${dce.default.dynamicAnchors}${(0,IR.getProperty)(e)}`,a=n.errSchemaPath==="#"?n.validateName:fce(r);t.if((0,IR._)`!${i}`,()=>t.assign(i,a))}x0.dynamicAnchor=YL;function fce(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:i,baseId:a,localRefs:s,meta:o}=e.root,{schemaId:c}=n.opts,l=new ZL.SchemaEnv({schema:t,schemaId:c,root:i,baseId:a,localRefs:s,meta:o});return ZL.compileSchema.call(n,l),(0,lce.getValidate)(r,l)}x0.default=uce});var RR=ke(E0=>{"use strict";g();Object.defineProperty(E0,"__esModule",{value:!0});E0.dynamicRef=void 0;var XL=Dt(),pce=ba(),QL=Wx(),hce={keyword:"$dynamicRef",schemaType:"string",code:r=>e9(r,r.schema)};function e9(r,e){let{gen:t,keyword:n,it:i}=r;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let a=e.slice(1);if(i.allErrors)s();else{let c=t.let("valid",!1);s(c),r.ok(c)}function s(c){if(i.schemaEnv.root.dynamicAnchors[a]){let l=t.let("_v",(0,XL._)`${pce.default.dynamicAnchors}${(0,XL.getProperty)(a)}`);t.if(l,o(l,c),o(i.validateName,c))}else o(i.validateName,c)()}function o(c,l){return l?()=>t.block(()=>{(0,QL.callRef)(r,c),t.let(l,!0)}):()=>(0,QL.callRef)(r,c)}}E0.dynamicRef=e9;E0.default=hce});var t9=ke(CR=>{"use strict";g();Object.defineProperty(CR,"__esModule",{value:!0});var mce=DR(),yce=Vt(),gce={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,mce.dynamicAnchor)(r,""):(0,yce.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};CR.default=gce});var r9=ke($R=>{"use strict";g();Object.defineProperty($R,"__esModule",{value:!0});var wce=RR(),vce={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,wce.dynamicRef)(r,r.schema)};$R.default=vce});var n9=ke(BR=>{"use strict";g();Object.defineProperty(BR,"__esModule",{value:!0});var bce=DR(),Pce=RR(),xce=t9(),Ece=r9(),Sce=[bce.default,Pce.default,xce.default,Ece.default];BR.default=Sce});var s9=ke(OR=>{"use strict";g();Object.defineProperty(OR,"__esModule",{value:!0});var i9=e2(),kce={keyword:"dependentRequired",type:"object",schemaType:"object",error:i9.error,code:r=>(0,i9.validatePropertyDeps)(r)};OR.default=kce});var o9=ke(jR=>{"use strict";g();Object.defineProperty(jR,"__esModule",{value:!0});var _ce=e2(),Ace={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,_ce.validateSchemaDeps)(r)};jR.default=Ace});var a9=ke(MR=>{"use strict";g();Object.defineProperty(MR,"__esModule",{value:!0});var Tce=Vt(),Ice={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,Tce.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};MR.default=Ice});var c9=ke(KR=>{"use strict";g();Object.defineProperty(KR,"__esModule",{value:!0});var Dce=s9(),Rce=o9(),Cce=a9(),$ce=[Dce.default,Rce.default,Cce.default];KR.default=$ce});var l9=ke(UR=>{"use strict";g();Object.defineProperty(UR,"__esModule",{value:!0});var sf=Dt(),d9=Vt(),Bce=ba(),Oce={message:"must NOT have unevaluated properties",params:({params:r})=>(0,sf._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},jce={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Oce,code(r){let{gen:e,schema:t,data:n,errsCount:i,it:a}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:s,props:o}=a;o instanceof sf.Name?e.if((0,sf._)`${o} !== true`,()=>e.forIn("key",n,u=>e.if(l(o,u),()=>c(u)))):o!==!0&&e.forIn("key",n,u=>o===void 0?c(u):e.if(d(o,u),()=>c(u))),a.props=!0,r.ok((0,sf._)`${i} === ${Bce.default.errors}`);function c(u){if(t===!1){r.setParams({unevaluatedProperty:u}),r.error(),s||e.break();return}if(!(0,d9.alwaysValidSchema)(a,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:d9.Type.Str},f),s||e.if((0,sf.not)(f),()=>e.break())}}function l(u,f){return(0,sf._)`!${u} || !${u}[${f}]`}function d(u,f){let p=[];for(let h in u)u[h]===!0&&p.push((0,sf._)`${f} !== ${h}`);return(0,sf.and)(...p)}}};UR.default=jce});var f9=ke(NR=>{"use strict";g();Object.defineProperty(NR,"__esModule",{value:!0});var rh=Dt(),u9=Vt(),Mce={message:({params:{len:r}})=>(0,rh.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,rh._)`{limit: ${r}}`},Kce={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Mce,code(r){let{gen:e,schema:t,data:n,it:i}=r,a=i.items||0;if(a===!0)return;let s=e.const("len",(0,rh._)`${n}.length`);if(t===!1)r.setParams({len:a}),r.fail((0,rh._)`${s} > ${a}`);else if(typeof t=="object"&&!(0,u9.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,rh._)`${s} <= ${a}`);e.if((0,rh.not)(c),()=>o(c,a)),r.ok(c)}i.items=!0;function o(c,l){e.forRange("i",l,s,d=>{r.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:u9.Type.Num},c),i.allErrors||e.if((0,rh.not)(c),()=>e.break())})}}};NR.default=Kce});var p9=ke(LR=>{"use strict";g();Object.defineProperty(LR,"__esModule",{value:!0});var Uce=l9(),Nce=f9(),Lce=[Uce.default,Nce.default];LR.default=Lce});var h9=ke(qR=>{"use strict";g();Object.defineProperty(qR,"__esModule",{value:!0});var zn=Dt(),qce={message:({schemaCode:r})=>(0,zn.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,zn._)`{format: ${r}}`},zce={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:qce,code(r,e){let{gen:t,data:n,$data:i,schema:a,schemaCode:s,it:o}=r,{opts:c,errSchemaPath:l,schemaEnv:d,self:u}=o;if(!c.validateFormats)return;i?f():p();function f(){let h=t.scopeValue("formats",{ref:u.formats,code:c.code.formats}),m=t.const("fDef",(0,zn._)`${h}[${s}]`),y=t.let("fType"),v=t.let("format");t.if((0,zn._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(y,(0,zn._)`${m}.type || "string"`).assign(v,(0,zn._)`${m}.validate`),()=>t.assign(y,(0,zn._)`"string"`).assign(v,m)),r.fail$data((0,zn.or)(w(),E()));function w(){return c.strictSchema===!1?zn.nil:(0,zn._)`${s} && !${v}`}function E(){let _=d.$async?(0,zn._)`(${m}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,zn._)`${v}(${n})`,A=(0,zn._)`(typeof ${v} == "function" ? ${_} : ${v}.test(${n}))`;return(0,zn._)`${v} && ${v} !== true && ${y} === ${e} && !${A}`}}function p(){let h=u.formats[a];if(!h){w();return}if(h===!0)return;let[m,y,v]=E(h);m===e&&r.pass(_());function w(){if(c.strictSchema===!1){u.logger.warn(A());return}throw new Error(A());function A(){return`unknown format "${a}" ignored in schema at path "${l}"`}}function E(A){let D=A instanceof RegExp?(0,zn.regexpCode)(A):c.code.formats?(0,zn._)`${c.code.formats}${(0,zn.getProperty)(a)}`:void 0,M=t.scopeValue("formats",{key:a,ref:A,code:D});return typeof A=="object"&&!(A instanceof RegExp)?[A.type||"string",A.validate,(0,zn._)`${M}.validate`]:["string",A,M]}function _(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,zn._)`await ${v}(${n})`}return typeof y=="function"?(0,zn._)`${v}(${n})`:(0,zn._)`${v}.test(${n})`}}}};qR.default=zce});var m9=ke(zR=>{"use strict";g();Object.defineProperty(zR,"__esModule",{value:!0});var Fce=h9(),Gce=[Fce.default];zR.default=Gce});var y9=ke(By=>{"use strict";g();Object.defineProperty(By,"__esModule",{value:!0});By.contentVocabulary=By.metadataVocabulary=void 0;By.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];By.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var w9=ke(FR=>{"use strict";g();Object.defineProperty(FR,"__esModule",{value:!0});var Hce=lL(),Vce=xL(),Wce=JL(),Jce=n9(),Zce=c9(),Yce=p9(),Xce=m9(),g9=y9(),Qce=[Jce.default,Hce.default,Vce.default,(0,Wce.default)(!0),Xce.default,g9.metadataVocabulary,g9.contentVocabulary,Zce.default,Yce.default];FR.default=Qce});var b9=ke(o2=>{"use strict";g();Object.defineProperty(o2,"__esModule",{value:!0});o2.DiscrError=void 0;var v9;(function(r){r.Tag="tag",r.Mapping="mapping"})(v9||(o2.DiscrError=v9={}))});var x9=ke(HR=>{"use strict";g();Object.defineProperty(HR,"__esModule",{value:!0});var Oy=Dt(),GR=b9(),P9=c0(),ede=a0(),tde=Vt(),rde={message:({params:{discrError:r,tagName:e}})=>r===GR.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Oy._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},nde={keyword:"discriminator",type:"object",schemaType:"object",error:rde,code(r){let{gen:e,data:t,schema:n,parentSchema:i,it:a}=r,{oneOf:s}=i;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let o=n.propertyName;if(typeof o!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Oy._)`${t}${(0,Oy.getProperty)(o)}`);e.if((0,Oy._)`typeof ${l} == "string"`,()=>d(),()=>r.error(!1,{discrError:GR.DiscrError.Tag,tag:l,tagName:o})),r.ok(c);function d(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,Oy._)`${l} === ${h}`),e.assign(c,u(p[h]));e.else(),r.error(!1,{discrError:GR.DiscrError.Mapping,tag:l,tagName:o}),e.endIf()}function u(p){let h=e.name("valid"),m=r.subschema({keyword:"oneOf",schemaProp:p},h);return r.mergeEvaluated(m,Oy.Name),h}function f(){var p;let h={},m=v(i),y=!0;for(let _=0;_<s.length;_++){let A=s[_];if(A?.$ref&&!(0,tde.schemaHasRulesButRef)(A,a.self.RULES)){let M=A.$ref;if(A=P9.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,M),A instanceof P9.SchemaEnv&&(A=A.schema),A===void 0)throw new ede.default(a.opts.uriResolver,a.baseId,M)}let D=(p=A?.properties)===null||p===void 0?void 0:p[o];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${o}"`);y=y&&(m||v(A)),w(D,_)}if(!y)throw new Error(`discriminator: "${o}" must be required`);return h;function v({required:_}){return Array.isArray(_)&&_.includes(o)}function w(_,A){if(_.const)E(_.const,A);else if(_.enum)for(let D of _.enum)E(D,A);else throw new Error(`discriminator: "properties/${o}" must have "const" or "enum"`)}function E(_,A){if(typeof _!="string"||_ in h)throw new Error(`discriminator: "${o}" values must be unique strings`);h[_]=A}}}};HR.default=nde});var E9=ke((Dje,ide)=>{ide.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var S9=ke((Rje,sde)=>{sde.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var k9=ke((Cje,ode)=>{ode.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var _9=ke(($je,ade)=>{ade.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var A9=ke((Bje,cde)=>{cde.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var T9=ke((Oje,dde)=>{dde.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var I9=ke((jje,lde)=>{lde.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var D9=ke((Mje,ude)=>{ude.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var R9=ke(VR=>{"use strict";g();Object.defineProperty(VR,"__esModule",{value:!0});var fde=E9(),pde=S9(),hde=k9(),mde=_9(),yde=A9(),gde=T9(),wde=I9(),vde=D9(),bde=["/properties"];function Pde(r){return[fde,pde,hde,mde,yde,e(this,gde),wde,e(this,vde)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,bde):n}}VR.default=Pde});var ZR=ke((cn,JR)=>{"use strict";g();Object.defineProperty(cn,"__esModule",{value:!0});cn.MissingRefError=cn.ValidationError=cn.CodeGen=cn.Name=cn.nil=cn.stringify=cn.str=cn._=cn.KeywordCxt=cn.Ajv2020=void 0;var xde=sL(),Ede=w9(),Sde=x9(),kde=R9(),WR="https://json-schema.org/draft/2020-12/schema",jy=class extends xde.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Ede.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Sde.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(kde.default.call(this,e),this.refs["http://json-schema.org/schema"]=WR)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(WR)?WR:void 0)}};cn.Ajv2020=jy;JR.exports=cn=jy;JR.exports.Ajv2020=jy;Object.defineProperty(cn,"__esModule",{value:!0});cn.default=jy;var _de=o0();Object.defineProperty(cn,"KeywordCxt",{enumerable:!0,get:function(){return _de.KeywordCxt}});var My=Dt();Object.defineProperty(cn,"_",{enumerable:!0,get:function(){return My._}});Object.defineProperty(cn,"str",{enumerable:!0,get:function(){return My.str}});Object.defineProperty(cn,"stringify",{enumerable:!0,get:function(){return My.stringify}});Object.defineProperty(cn,"nil",{enumerable:!0,get:function(){return My.nil}});Object.defineProperty(cn,"Name",{enumerable:!0,get:function(){return My.Name}});Object.defineProperty(cn,"CodeGen",{enumerable:!0,get:function(){return My.CodeGen}});var Ade=Ux();Object.defineProperty(cn,"ValidationError",{enumerable:!0,get:function(){return Ade.default}});var Tde=a0();Object.defineProperty(cn,"MissingRefError",{enumerable:!0,get:function(){return Tde.default}})});var of,a2=G(()=>{"use strict";g();CP();vt();of=class r{static async authorizeConfigure(e){let{protocolsConfigureMessage:t,expectedGrantor:n,expectedGrantee:i,permissionGrant:a,messageStore:s}=e;await jo.performBaseValidation({incomingMessage:t,expectedGrantor:n,expectedGrantee:i,permissionGrant:a,messageStore:s}),r.verifyScope(t,a.scope)}static async authorizeQuery(e){let{expectedGrantee:t,expectedGrantor:n,incomingMessage:i,permissionGrant:a,messageStore:s}=e;await jo.performBaseValidation({incomingMessage:i,expectedGrantor:n,expectedGrantee:t,permissionGrant:a,messageStore:s});let c=a.scope.protocol,l=i.descriptor.filter?.protocol;if(c!==void 0&&l!==c)throw new ne(re.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch,`Grant protocol scope ${c} does not match protocol in message ${l}`)}static verifyScope(e,t){if(t.protocol!==void 0&&t.protocol!==e.descriptor.definition.protocol)throw new ne(re.ProtocolsGrantAuthorizationScopeProtocolMismatch,"Grant scope specifies different protocol than what appears in the configure message.")}}});function Hs(r){let e=r.indexOf(":");if(e===-1)return;let t=r.substring(0,e),n=r.substring(e+1);return{alias:t,protocolPath:n}}function af(r){return r.includes(":")}function c2(r){return r.split("/").slice(-1)[0]}function kd(r,e){let t=r.split("/"),n,i=e;for(let a of t){if(!Object.hasOwn(i,a))return;n=i[a],i=n}return n}var Sd,nh=G(()=>{"use strict";g();bn();Hm();Sd=class{static async deriveAndInjectPublicEncryptionKeys(e,t,n){let i=JSON.parse(JSON.stringify(e));if(typeof t!="string"){let l=t,d=[xt.ProtocolPath,e.protocol];async function u(f,p){for(let h in f)if(!h.startsWith("$")){let m=[...p,h],y=f[h];if(y.$ref!==void 0){await u(y,m);continue}let v=await l.derivePublicKey(m);y.$encryption={rootKeyId:l.rootKeyId,publicKeyJwk:v},await u(y,m)}}return await u(i.structure,d),i}let a=t;async function s(l,d){for(let u in l)if(!u.startsWith("$")){let f=await ji.derivePrivateKey(d,[u]),p=l[u];if(p.$ref!==void 0){await s(p,f);continue}let h=await kt.getPublicKey({key:f.derivedPrivateKey});p.$encryption={rootKeyId:a,publicKeyJwk:h},await s(p,f)}}let o={derivationScheme:xt.ProtocolPath,derivedPrivateKey:n,rootKeyId:a},c=await ji.derivePrivateKey(o,[xt.ProtocolPath,e.protocol]);return await s(i.structure,c),i}}});var C9,Sa,d2=G(()=>{"use strict";g();xc();C9=An(ZR(),1);yr();lc();a2();qs();vt();ar();nh();ma();Lg();Sa=class r extends Bn{static async parse(e){return ye.validateJsonSchema(e),r.validateProtocolDefinition(e.descriptor.definition),await ye.validateSignatureStructure(e.authorization.signature,e.descriptor),_t.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:ve.Protocols,method:me.Configure,messageTimestamp:e.messageTimestamp??_t.getCurrentTimestamp(),definition:r.normalizeDefinition(e.definition),...e.permissionGrantId!==void 0&&{permissionGrantId:e.permissionGrantId}},n=await ye.createAuthorization({descriptor:t,signer:e.signer,delegatedGrant:e.delegatedGrant,permissionGrantId:e.permissionGrantId}),i={descriptor:t,authorization:n};return ye.validateJsonSchema(i),r.validateProtocolDefinition(i.descriptor.definition),new r(i)}async authorizeAuthorDelegate(e){let t=kr.parse(this.message.authorization.authorDelegatedGrant);await of.authorizeConfigure({protocolsConfigureMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:t,messageStore:e})}static validateProtocolDefinition(e){let{protocol:t,types:n,uses:i}=e;di(t);for(let a in n){let s=n[a].schema;s!==void 0&&nd(s)}i!==void 0&&r.validateUses(i,t),r.validateStructure(e)}static validateUses(e,t){let n=/^[a-zA-Z][a-zA-Z0-9_-]*$/;for(let i in e){if(!n.test(i))throw new ne(re.ProtocolsConfigureInvalidUsesAlias,`invalid 'uses' alias '${i}': must match pattern ${n.toString()}.`);try{di(e[i])}catch{throw new ne(re.ProtocolsConfigureInvalidUsesProtocolUrl,`invalid 'uses' protocol URL for alias '${i}': '${e[i]}' is not a valid normalized protocol URL.`)}if(e[i]===t)throw new ne(re.ProtocolsConfigureInvalidUsesSelfReference,`'uses' alias '${i}' references the protocol's own URI '${t}'. a protocol cannot compose itself.`)}}static validateStructure(e){let{uses:t}=e,n=Object.keys(e.types),i=r.fetchAllRolePathsRecursively("",e.structure,[]);r.validateRuleSetRecursively({ruleSet:e.structure,ruleSetProtocolPath:"",recordTypes:n,roles:i,uses:t,types:e.types})}static fetchAllRolePathsRecursively(e,t,n){if(e.split("/").length>10)throw new ne(re.ProtocolsConfigureRecordNestingDepthExceeded,"Record nesting depth exceeded 10 levels.");for(let i in t){if(i.startsWith("$"))continue;let a=t[i],s;e===""?s=i:s=`${e}/${i}`,a.$role?n.push(s):r.fetchAllRolePathsRecursively(s,a,n)}return n}static validateRuleSetRecursively(e){let{ruleSet:t,ruleSetProtocolPath:n,recordTypes:i,roles:a,uses:s,types:o}=e;if(t.$ref!==void 0){if(n.includes("/"))throw new ne(re.ProtocolsConfigureInvalidRefNotAtRoot,`'$ref' at protocol path '${n}' is not allowed: '$ref' nodes are only supported at the root level of the structure.`);r.validateRefNode(t,n,s)}if(t.$size!==void 0){let{min:l=0,max:d}=t.$size;if(d!==void 0&&d<l)throw new ne(re.ProtocolsConfigureInvalidSize,`Invalid size range found: max limit ${d} less than min limit ${l} at protocol path '${n}'`)}if(t.$recordLimit!==void 0){let{max:l,strategy:d}=t.$recordLimit;if(!Number.isInteger(l)||l<1)throw new ne(re.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.max value ${l} at protocol path '${n}': must be an integer >= 1.`);let u=Object.values(Zl);if(!u.includes(d))throw new ne(re.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.strategy '${d}' at protocol path '${n}': must be one of ${u.join(", ")}.`)}if(t.$tags){let l=new C9.default.default,{$allowUndefinedTags:d,$requiredTags:u,...f}=t.$tags;for(let p in f){let h=f[p];if(!l.validateSchema(h)){let m=l.errorsText(l.errors,{dataVar:`${n}/$tags/${p}`});throw new ne(re.ProtocolsConfigureInvalidTagSchema,`tags schema validation error: ${m}`)}}}let c=t.$actions??[];for(let l=0;l<c.length;l++){let d=c[l];if(d.role!==void 0){if(af(d.role))r.validateCrossProtocolAlias(d.role,s,n,"role");else if(!a.includes(d.role))throw new ne(re.ProtocolsConfigureRoleDoesNotExistAtGivenPath,`Role in action ${JSON.stringify(d)} for rule set ${n} does not exist.`)}if(d.who==="anyone"&&d.of)throw new ne(re.ProtocolsConfigureInvalidActionOfNotAllowed,`'of' is not allowed at rule set protocol path (${n})`);if(d.who===Bc.Recipient&&d.of===void 0&&d.can.some(f=>![vr.CoUpdate,vr.CoDelete,vr.CoPrune].includes(f)))throw new ne(re.ProtocolsConfigureInvalidRecipientOfAction,"Rules for `recipient` without `of` property must have `can` containing only `co-update`, `co-delete`, and `co-prune`.");if(d.who===Bc.Author&&!d.of)throw new ne(re.ProtocolsConfigureInvalidActionMissingOf,"'of' is required when 'author' is specified as 'who'");if(d.of!==void 0&&n!==""){if(af(d.of))r.validateCrossProtocolAlias(d.of,s,n,"of");else if(!(n===d.of||n.startsWith(d.of+"/")))throw new ne(re.ProtocolsConfigureInvalidActionOfNotAnAncestor,`'of' value '${d.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(d)}.`)}if(d.can!==void 0){if(d.can.includes(vr.Update)&&!d.can.includes(vr.Create))throw new ne(re.ProtocolsConfigureInvalidActionUpdateWithoutCreate,`Action rule ${JSON.stringify(d)} contains 'update' action but missing the required 'create' action.`);if(d.can.includes(vr.Delete)&&!d.can.includes(vr.Create))throw new ne(re.ProtocolsConfigureInvalidActionDeleteWithoutCreate,`Action rule ${JSON.stringify(d)} contains 'delete' action but missing the required 'create' action.`);if(d.can.includes(vr.Prune)&&!d.can.includes(vr.Create))throw new ne(re.ProtocolsConfigureInvalidActionPruneWithoutCreate,`Action rule ${JSON.stringify(d)} contains 'prune' action but missing the required 'create' action.`)}for(let u=l+1;u<c.length;u++){let f=c[u];if(d.who===void 0){if(d.role===f.role)throw new ne(re.ProtocolsConfigureDuplicateRoleInRuleSet,`More than one action rule per role ${d.role} not allowed within a rule set: ${JSON.stringify(d)}`)}else if(d.who===f.who&&d.of===f.of)throw new ne(re.ProtocolsConfigureDuplicateActorInRuleSet,`More than one action rule per actor ${d.who} of ${d.of} not allowed within a rule set: ${JSON.stringify(d)}`)}}if(n!==""){let l=n.split("/").pop();o[l]?.encryptionRequired===!0&&c.some(f=>f.who===Bc.Anyone&&f.can.includes(vr.Read))&&console.warn(`ProtocolsConfigure: type '${l}' at path '${n}' has encryptionRequired: true but allows { who: 'anyone', can: ['read'] }. Anyone can read the record but no one outside the key holders can decrypt it.`)}t.$delivery!==void 0&&(t.$actions===void 0||t.$actions.length===0)&&console.warn(`ProtocolsConfigure: protocol path '${n}' has $delivery: '${t.$delivery}' but no $actions rules. The server uses $actions to determine delivery targets \u2014 without $actions, no participants can be resolved for delivery.`),t.$immutable===!0&&c.length>0&&c.some(d=>d.can.includes(vr.Update)||d.can.includes(vr.CoUpdate))&&console.warn(`ProtocolsConfigure: protocol path '${n}' has $immutable: true but $actions include 'update' or 'co-update'. The $immutable directive takes precedence \u2014 updates will always be rejected regardless of action rules.`);for(let l in t){if(l.startsWith("$"))continue;let d=t[l];if(d.$ref===void 0&&!i.includes(l))throw new ne(re.ProtocolsConfigureInvalidRuleSetRecordType,`Rule set ${l} is not declared as an allowed type in the protocol definition.`);let u;n===""?u=l:u=`${n}/${l}`,r.validateRuleSetRecursively({ruleSet:d,ruleSetProtocolPath:u,recordTypes:i,roles:a,uses:s,types:o})}}static validateRefNode(e,t,n){let i=e.$ref,a=Hs(i);if(a===void 0)throw new ne(re.ProtocolsConfigureInvalidRefAlias,`'$ref' value '${i}' at protocol path '${t}' must be in 'alias:typePath' format.`);if(n?.[a.alias]===void 0)throw new ne(re.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${a.alias}' at protocol path '${t}' does not exist in the 'uses' map.`);let s=["$actions","$role","$size","$tags","$encryption","$recordLimit","$immutable","$delivery","$squash"];for(let o of s)if(e[o]!==void 0)throw new ne(re.ProtocolsConfigureInvalidRefNodeHasDirectives,`'$ref' node at protocol path '${t}' must not have '${o}'. $ref nodes are pure attachment points \u2014 directives belong on child rule sets.`)}static validateCrossProtocolAlias(e,t,n,i){let a=Hs(e);if(a===void 0){let s=i==="role"?re.ProtocolsConfigureInvalidCrossProtocolRole:re.ProtocolsConfigureInvalidCrossProtocolOf;throw new ne(s,`cross-protocol '${i}' reference '${e}' at protocol path '${n}' could not be parsed as a valid 'alias:path' format.`)}if(t?.[a.alias]===void 0){let s=i==="role"?re.ProtocolsConfigureInvalidCrossProtocolRole:re.ProtocolsConfigureInvalidCrossProtocolOf;throw new ne(s,`cross-protocol '${i}' alias '${a.alias}' in '${e}' at protocol path '${n}' does not exist in the 'uses' map.`)}}static normalizeDefinition(e){let t={};for(let i in e.types)t[i]={...e.types[i]};for(let i in t){let a=t[i].schema;a!==void 0&&(t[i].schema=Tp(a))}let n;if(e.uses!==void 0){n={};for(let i in e.uses)try{n[i]=js(e.uses[i])}catch{n[i]=e.uses[i]}}return{...e,protocol:js(e.protocol),types:t,...n!==void 0&&{uses:n}}}}});var l2,$9=G(()=>{"use strict";g();qo();yr();zo();Fo();d2();a2();vt();ar();nh();l2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Sa.parse(t)}catch(d){return mt(d,400)}try{await mn(t.authorization,this.deps.didResolver),await r.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(d){return mt(d,401)}try{await r.validateCompositionDependencies(e,t.descriptor.definition,this.deps.messageStore)}catch(d){return mt(d,400)}let i={interface:ve.Protocols,method:me.Configure,protocol:t.descriptor.definition.protocol},{messages:a}=await this.deps.messageStore.query(e,[i]),s=await ye.getCid(t);for(let d of a)if(await ye.getCid(d)===s)return{status:{code:409,detail:"Conflict"}};let o=await ye.getNewestMessage(a),c=!1;(o===void 0||await ye.isNewer(t,o))&&(c=!0,o=t);let l;if(c){let d=r.constructIndexes(n,!0);await this.deps.messageStore.put(e,t,d);let u=await ye.getCid(t);await this.deps.stateIndex.insert(e,u,d),this.deps.eventLog!==void 0&&await this.deps.eventLog.emit(e,{message:t},d,u),l={status:{code:202,detail:"Accepted"}}}else{let d=r.constructIndexes(n,!1);await this.deps.messageStore.put(e,t,d);let u=await ye.getCid(t);await this.deps.stateIndex.insert(e,u,d),l={status:{code:202,detail:"Accepted"}}}for(let d of a)if(d!==o){let u=await Sa.parse(d),f=r.constructIndexes(u,!1),p=await ye.getCid(d);await this.deps.messageStore.delete(e,p),await this.deps.messageStore.put(e,d,f)}return l}static constructIndexes(e,t){let{definition:n,...i}=e.message.descriptor,{author:a}=e;return{...i,author:a,protocol:n.protocol,published:n.published,isLatestBaseState:t}}static async authorizeProtocolsConfigure(e,t,n){if(t.isSignedByAuthorDelegate&&await t.authorizeAuthorDelegate(n),t.author!==e)if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let i=await et.fetchGrant(e,n,t.signaturePayload.permissionGrantId);await of.authorizeConfigure({protocolsConfigureMessage:t.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:i,messageStore:n})}else throw new ne(re.ProtocolsConfigureAuthorizationFailed,"message failed authorization")}static async validateCompositionDependencies(e,t,n){let{uses:i}=t;if(i===void 0)return;let a=new Map;for(let s in i){let o=i[s],c=await r.fetchInstalledProtocolDefinition(e,o,n);if(c===void 0)throw new ne(re.ProtocolsConfigureComposedProtocolNotInstalled,`composed protocol '${o}' (alias '${s}') is not installed for tenant '${e}'.`);a.set(s,c)}r.validateRefsAndRolesRecursively(t.structure,"",a)}static async fetchInstalledProtocolDefinition(e,t,n){let i={interface:ve.Protocols,method:me.Configure,protocol:t,isLatestBaseState:!0},{messages:a}=await n.query(e,[i]);if(a.length!==0)return a[0].descriptor.definition}static validateRefsAndRolesRecursively(e,t,n){for(let i in e){if(i.startsWith("$"))continue;let a=e[i],s=t===""?i:`${t}/${i}`;if(a.$ref!==void 0){let c=Hs(a.$ref);if(c!==void 0){let l=n.get(c.alias);if(l===void 0)throw new ne(re.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${c.alias}' at protocol path '${s}' was not found in the referenced definitions map.`);let d=c.protocolPath.split("/"),u=l.structure;for(let f=0;f<d.length;f++){let p=d[f],h=u[p];if(h===void 0)throw new ne(re.ProtocolsConfigureInvalidRefProtocolPath,`'$ref' at protocol path '${s}' references type path '${c.protocolPath}' which does not exist in protocol '${l.protocol}'.`);if(h.$ref!==void 0){let m=d.slice(0,f+1).join("/");throw new ne(re.ProtocolsConfigureInvalidRefTargetThroughRef,`'$ref' at protocol path '${s}' references type path '${c.protocolPath}' in protocol '${l.protocol}', but the node '${m}' is itself a '$ref' composition point. multi-level composition (chaining through '$ref' nodes) is not supported.`)}u=h}}}let o=a.$actions??[];for(let c of o){if(c.role!==void 0){let l=Hs(c.role);if(l!==void 0){let d=n.get(l.alias);if(d===void 0)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role alias '${l.alias}' in '${c.role}' at protocol path '${s}' was not found in the referenced definitions map.`);if(!kd(l.protocolPath,d.structure)?.$role)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role '${c.role}' at protocol path '${s}' does not point to a valid role ($role: true) in protocol '${d.protocol}'.`)}}if(c.of!==void 0){let l=Hs(c.of);if(l!==void 0){let d=n.get(l.alias);if(d===void 0)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' alias '${l.alias}' in '${c.of}' at protocol path '${s}' was not found in the referenced definitions map.`);if(kd(l.protocolPath,d.structure)===void 0)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' reference '${c.of}' at protocol path '${s}' does not point to a valid type path in protocol '${d.protocol}'.`)}}}r.validateRefsAndRolesRecursively(a,s,n)}}}});var ka,u2=G(()=>{"use strict";g();xc();yr();Fo();a2();st();qs();vt();ar();ma();ka=class r extends Bn{static async parse(e){return e.authorization!==void 0&&await ye.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&di(e.descriptor.filter.protocol),_t.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:ve.Protocols,method:me.Query,messageTimestamp:e.messageTimestamp??_t.getCurrentTimestamp(),filter:e.filter?r.normalizeFilter(e.filter):void 0,permissionGrantId:e.permissionGrantId};Wt(t);let n;e.signer!==void 0&&(n=await ye.createAuthorization({descriptor:t,signer:e.signer,permissionGrantId:e.permissionGrantId}));let i={descriptor:t,authorization:n};return ye.validateJsonSchema(i),new r(i)}static normalizeFilter(e){return{...e,protocol:js(e.protocol)}}async authorize(e,t){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await et.fetchGrant(e,t,this.signaturePayload.permissionGrantId);await of.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:t})}else throw new ne(re.ProtocolsQueryUnauthorized,"The ProtocolsQuery failed authorization")}}});var f2,B9=G(()=>{"use strict";g();qo();vt();zo();u2();st();ar();f2=class{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await ka.parse(t)}catch(s){return mt(s,400)}try{await mn(t.authorization,this.deps.didResolver),await n.authorize(e,this.deps.messageStore)}catch(s){if(s.code===re.AuthenticateJwsMissing||s.code===re.ProtocolsQueryUnauthorized||s.code===re.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch){let o=await this.fetchPublishedProtocolsConfigure(e,n);return{status:{code:200,detail:"OK"},entries:o}}else return mt(s,401)}let i={...t.descriptor.filter,interface:ve.Protocols,method:me.Configure,isLatestBaseState:!0};Wt(i);let{messages:a}=await this.deps.messageStore.query(e,[i]);return{status:{code:200,detail:"OK"},entries:a}}async fetchPublishedProtocolsConfigure(e,t){let n={...t.message.descriptor.filter,interface:ve.Protocols,method:me.Configure,published:!0,isLatestBaseState:!0},{messages:i}=await this.deps.messageStore.query(e,[n]);return i}}});async function S0(r,e,t,n,i,a,s,o){let c=e.signaturePayload?.protocolRole;if(c===void 0)return;let l=t,d=c;if(af(c)){let h=Hs(c);if(h===void 0)throw new ne(re.ProtocolAuthorizationNotARole,`Cross-protocol role '${c}' could not be parsed as a valid 'alias:path' format.`);if(i.uses?.[h.alias]===void 0)throw new ne(re.ProtocolAuthorizationNotARole,`Cross-protocol role alias '${h.alias}' in '${c}' does not exist in the protocol's 'uses' map.`);l=i.uses[h.alias],d=h.protocolPath;let m=await s(r,l,a,o);if(!kd(d,m.structure)?.$role)throw new ne(re.ProtocolAuthorizationNotARole,`Cross-protocol role path ${c} does not match role record type.`)}else if(!kd(c,i.structure)?.$role)throw new ne(re.ProtocolAuthorizationNotARole,`Protocol path ${c} does not match role record type.`);let u={interface:ve.Records,method:me.Write,protocol:l,protocolPath:d,recipient:e.author,isLatestBaseState:!0},f=d.split("/").length-1;if(n===void 0&&f>0)throw new ne(re.ProtocolAuthorizationMissingContextId,"Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=Xt.constructPrefixFilterAsRangeFilter(m);u.contextId=y}let{messages:p}=await a.query(r,[u]);if(p.length===0)throw new ne(re.ProtocolAuthorizationMatchingRoleRecordNotFound,`No matching role record found for protocol path ${d}`)}async function Ide(r,e,t){switch(e.message.descriptor.method){case me.Delete:let n=e,i=n.message.descriptor.recordId,a=await Pt.fetchInitialRecordsWrite(t,r,i);if(a===void 0)return[];let s=[];return n.message.descriptor.prune?(s.push(vr.CoPrune),e.author===a.author&&s.push(vr.Prune)):(s.push(vr.CoDelete),e.author===a.author&&s.push(vr.Delete)),s;case me.Count:return[vr.Read];case me.Query:return[vr.Read];case me.Read:return[vr.Read];case me.Subscribe:return[vr.Read];case me.Write:let c=e;if(await c.isInitialWrite())return c.message.descriptor.squash===!0?[vr.Squash,vr.Create]:[vr.Create];{let l=e.message.recordId,d=await Pt.fetchInitialRecordsWrite(t,r,l);return d===void 0?[]:e.author===d.author?[vr.CoUpdate,vr.Update]:[vr.CoUpdate]}}return[]}async function k0(r,e,t,n,i,a){let s=e.message.descriptor.method,o=await Ide(r,e,i),c=e.author,l=t.$actions;if(l===void 0)throw new ne(re.ProtocolAuthorizationActionRulesNotFound,`no action rule defined for Records${s}, ${c} is unauthorized`);let d=e.signaturePayload?.protocolRole;for(let u of l){if(!u.can.some(h=>o.includes(h)))continue;if(u.who===Bc.Anyone)return;if(c===void 0)continue;if(d!==void 0){if(u.role===d)return;continue}if(u.who===Bc.Recipient&&u.of===void 0){let h;if(e.message.descriptor.method===me.Write?h=e.message:h=n[n.length-1],h.descriptor.recipient===c)return;continue}if(await Dde(c,u,n,a))return}throw new ne(re.ProtocolAuthorizationActionNotAllowed,`Inbound message action Records${s} by author ${e.author} not allowed.`)}async function Dde(r,e,t,n){let i=e.of;if(i===void 0)return!1;let a;if(af(i)&&n?.uses!==void 0){let s=Hs(i);if(s!==void 0){let o=n.uses[s.alias];o!==void 0&&(a=t.find(c=>c.descriptor.protocol===o&&c.descriptor.protocolPath===s.protocolPath))}}else a=t.find(s=>s.descriptor.protocolPath===i);if(a===void 0)return!1;if(e.who===Bc.Recipient)return r===a.descriptor.recipient;{let s=(await Pt.parse(a)).author;return r===s}}var O9=G(()=>{"use strict";g();gc();zs();vt();ar();nh();Lg()});async function Ky(r,e,t){let n={interface:ve.Records,method:me.Write,recordId:e},{messages:i}=await t.query(r,[n]);return i.length===0?void 0:await Pt.getInitialWrite(i)}async function _0(r,e,t){if(e===void 0)return[];let n=[],i=e;for(;i!==void 0;){let a=await Ky(r,i,t);if(a===void 0)throw new ne(re.ProtocolAuthorizationParentNotFoundConstructingRecordChain,`Unexpected error that should never trigger: no parent found with ID ${i} when constructing record chain.`);n.push(a),i=a.descriptor.parentId}return n.reverse()}async function YR(r,e,t){let n=await Ky(r,e.message.recordId,t);if(n!==void 0)return n.descriptor.messageTimestamp}var j9=G(()=>{"use strict";g();zs();vt();ar()});async function K9(r,e,t,n,i){let a=e.message.descriptor.protocolPath,s=c2(a),o=e.message.descriptor.parentId;if(o===void 0){if(a!==s)throw new ne(re.ProtocolAuthorizationParentlessIncorrectProtocolPath,`Declared protocol path '${a}' is not valid for records with no parent'.`);return}let c=e.message.descriptor.protocol,l=await Rde(r,c,a,t,n,i),d={isLatestBaseState:!0,interface:ve.Records,method:me.Write,protocol:l,recordId:o},{messages:u}=await t.query(r,[d]),f=u[0];if(f===void 0)throw l!==c?new ne(re.ProtocolAuthorizationCrossProtocolParentNotFound,`Could not find parent record '${o}' in protocol '${l}' for cross-protocol child at path '${a}'.`):new ne(re.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${a}'.`);if(`${f.descriptor.protocolPath}/${s}`!==a)throw new ne(re.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${a}'.`);let m=`${f.contextId}/${e.message.recordId}`,y=e.message.contextId;if(y!==m)throw new ne(re.ProtocolAuthorizationIncorrectContextId,`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function Rde(r,e,t,n,i,a){let s=t.split("/");if(s.length<=1)return e;let o=await i(r,e,n,a),c=o.structure[s[0]];if(c?.$ref!==void 0){let l=Hs(c.$ref);if(l!==void 0&&o.uses!==void 0){let d=o.uses[l.alias];if(d!==void 0)return s.length===2?d:e}}return e}async function U9(r,e,t,n,i,a){let s=e.descriptor.protocolPath,o=c2(s),c=await Cde(r,s,t,n,i,a);$de(e,c,o)}async function Cde(r,e,t,n,i,a){let s=e.split("/"),o=t.structure[s[0]];if(o?.$ref!==void 0&&s.length===1){let c=Hs(o.$ref);if(c!==void 0&&t.uses!==void 0){let l=t.uses[c.alias];if(l!==void 0)return(await i(r,l,n,a)).types}}return t.types}function $de(r,e,t){let n=t??c2(r.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new ne(re.ProtocolAuthorizationInvalidType,`record with type ${n} not allowed in protocol`);let a=e[n],{schema:s}=r.descriptor;if(a.schema!==void 0&&a.schema!==s)throw new ne(re.ProtocolAuthorizationInvalidSchema,`type '${n}' must have schema '${a.schema}', instead has '${s}'`);let{dataFormat:o}=r.descriptor;if(a.dataFormats!==void 0&&!a.dataFormats.includes(o))throw new ne(re.ProtocolAuthorizationIncorrectDataFormat,`type '${n}' must have data format in (${a.dataFormats}), instead has '${o}'`);if(a.encryptionRequired===!0&&r.encryption===void 0)throw new ne(re.ProtocolAuthorizationEncryptionRequired,`type '${n}' requires encryption but message has no encryption metadata`)}function N9(r,e){let{min:t=0,max:n}=e.$size||{},i=r.message.descriptor.dataSize;if(i<t)throw new ne(re.ProtocolAuthorizationMinSizeInvalid,`data size ${i} is less than allowed ${t}`);if(n!==void 0&&i>n)throw new ne(re.ProtocolAuthorizationMaxSizeInvalid,`data size ${i} is more than allowed ${n}`)}function L9(r,e){if(e.$tags!==void 0){let{tags:t={},protocol:n,protocolPath:i}=r.message.descriptor,{$allowUndefinedTags:a,$requiredTags:s,...o}=e.$tags,c=a||!1,l=s||[],d=new M9.default.default,u=d.compile({type:"object",properties:o,required:l,additionalProperties:c});if(!u(t)){let p=d.errorsText(u.errors,{dataVar:`${n}/${i}/$tags`});throw new ne(re.ProtocolAuthorizationTagsInvalidSchema,`tags schema validation error: ${p}`)}}}async function q9(r,e,t,n){if(!t.$role)return;let i=e,a=i.message.descriptor.recipient;if(a===void 0)throw new ne(re.ProtocolAuthorizationRoleMissingRecipient,"Role records must have a recipient");let s=i.message.descriptor.protocolPath,o={interface:ve.Records,method:me.Write,isLatestBaseState:!0,protocol:i.message.descriptor.protocol,protocolPath:s,recipient:a},c=Ae.getParentContextFromOfContextId(i.message.contextId);if(c!==""){let f=Xt.constructPrefixFilterAsRangeFilter(c);o.contextId=f}let{messages:l}=await n.query(r,[o]);if(l.filter(f=>f.recordId!==i.message.recordId).length>0)throw new ne(re.ProtocolAuthorizationDuplicateRoleRecipient,`DID '${a}' is already recipient of a role record at protocol path '${s} under the parent context ${c}.`)}async function z9(r,e,t,n){if(t.$recordLimit===void 0||!await e.isInitialWrite())return;let{max:a,strategy:s}=t.$recordLimit,o=e.message.descriptor.protocolPath,c={interface:ve.Records,method:me.Write,isLatestBaseState:!0,protocol:e.message.descriptor.protocol,protocolPath:o},l=Ae.getParentContextFromOfContextId(e.message.contextId);if(l!==""){let u=Xt.constructPrefixFilterAsRangeFilter(l);c.contextId=u}if(await n.count(r,[c])>=a)throw s===Zl.Reject?new ne(re.ProtocolAuthorizationRecordLimitExceeded,`record limit of ${a} reached at protocol path '${o}'${l===""?"":` under parent context '${l}'`}: new records are rejected until existing records are deleted.`):new ne(re.ProtocolAuthorizationRecordLimitStrategyNotImplemented,`record limit strategy '${s}' is not yet implemented.`)}async function F9(r,e){if(r.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new ne(re.ProtocolAuthorizationSquashNotEnabled,`squash writes are not enabled at protocol path '${r.message.descriptor.protocolPath}': rule set must have $squash: true.`);if(!await r.isInitialWrite())throw new ne(re.ProtocolAuthorizationSquashNotInitialWrite,"squash write must be an initial write (a new record): updates cannot be squash writes.")}async function G9(r,e){if(!(e.$immutable!==!0||await r.isInitialWrite()))throw new ne(re.ProtocolAuthorizationImmutableRecord,`record at protocol path '${r.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var M9,H9=G(()=>{"use strict";g();Lg();M9=An(ZR(),1);gc();Qn();vt();ar();nh()});var ws,ih=G(()=>{"use strict";g();nh();rd();vt();ar();O9();j9();H9();ws=class r{static async validateReferentialIntegrity(e,t,n,i){let a=await YR(e,t,n),s=await r.fetchProtocolDefinition(e,t.message.descriptor.protocol,n,a,i),o=r.createBoundFetchDefinition(i);await U9(e,t.message,s,n,o,a),await K9(e,t,n,o,a);let c=r.getRuleSet(t.message.descriptor.protocolPath,s);await q9(e,t,c,n),N9(t,c),L9(t,c),await G9(t,c),await F9(t,c),await z9(e,t,c,n)}static async authorizeWrite(e,t,n,i){let a=await Ky(e,t.message.recordId,n),s;a===void 0?s=await _0(e,t.message.descriptor.parentId,n):s=await _0(e,t.message.recordId,n);let o=await YR(e,t,n),c=await r.fetchProtocolDefinition(e,t.message.descriptor.protocol,n,o,i),l=r.getRuleSet(t.message.descriptor.protocolPath,c),d=r.createBoundFetchDefinition(i);await S0(e,t,t.message.descriptor.protocol,t.message.contextId,c,n,d,o),await k0(e,t,l,s,n,c)}static async authorizeRead(e,t,n,i,a){let s=await _0(e,n.message.recordId,i),o=await Ky(e,n.message.recordId,i),c=o===void 0?n.message.descriptor.messageTimestamp:o.descriptor.messageTimestamp,l=await r.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,c,a),d=r.getRuleSet(n.message.descriptor.protocolPath,l),u=r.createBoundFetchDefinition(a);await S0(e,t,n.message.descriptor.protocol,n.message.contextId,l,i,u,c),await k0(e,t,d,s,i,l)}static async authorizeQueryOrSubscribe(e,t,n,i){let{protocol:a,protocolPath:s,contextId:o}=t.message.descriptor.filter,c=await r.fetchProtocolDefinition(e,a,n,void 0,i),l=r.getRuleSet(s,c),d=r.createBoundFetchDefinition(i);await S0(e,t,a,o,c,n,d),await k0(e,t,l,[],n,c)}static async authorizeDelete(e,t,n,i,a){let s=await _0(e,t.message.descriptor.recordId,i),o=await Ky(e,t.message.descriptor.recordId,i),c=o===void 0?n.message.descriptor.messageTimestamp:o.descriptor.messageTimestamp,l=await r.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,c,a),d=r.getRuleSet(n.message.descriptor.protocolPath,l),u=r.createBoundFetchDefinition(a);await S0(e,t,n.message.descriptor.protocol,n.message.contextId,l,i,u,c),await k0(e,t,d,s,i,l)}static async fetchProtocolDefinition(e,t,n,i,a){if(a!==void 0){let l=a.getDefinition(t);if(l!==void 0)return l}let s={interface:ve.Protocols,method:me.Configure,protocol:t};i===void 0?s.isLatestBaseState=!0:s.messageTimestamp={lte:i};let{messages:o}=await n.query(e,[s],{messageTimestamp:At.Descending},{limit:1});if(o.length===0)throw new ne(re.ProtocolAuthorizationProtocolNotFound,`unable to find protocol definition for ${t}`);return o[0].descriptor.definition}static createBoundFetchDefinition(e){return(t,n,i,a)=>r.fetchProtocolDefinition(t,n,i,a,e)}static getRuleSet(e,t){let n=kd(e,t.structure);if(n===void 0)throw new ne(re.ProtocolAuthorizationMissingRuleSet,`No rule set defined for protocolPath ${e}`);return n}}});var p2,V9=G(()=>{"use strict";g();qo();yr();zo();ih();Qn();gx();ar();p2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await yd.parse(t)}catch(a){return mt(a,400)}let i;if(Ae.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)i=await this.countPublishedRecords(e,n);else{try{await mn(t.authorization,this.deps.didResolver),await r.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(a){return mt(a,401)}n.author===e?i=await this.countRecordsAsOwner(e,n):i=await this.countRecordsAsNonOwner(e,n)}return{status:{code:200,detail:"OK"},count:i}}async countRecordsAsOwner(e,t){let{filter:n}=t.message.descriptor,i={...Ae.convertFilter(n),interface:ve.Records,method:me.Write,isLatestBaseState:!0};return this.deps.messageStore.count(e,[i])}async countRecordsAsNonOwner(e,t){let{filter:n}=t.message.descriptor,i=[];return Ae.filterIncludesPublishedRecords(n)&&i.push(r.buildPublishedRecordsFilter(t)),Ae.filterIncludesUnpublishedRecords(n)&&(Ae.shouldBuildUnpublishedAuthorFilter(n,t.author)&&i.push(r.buildUnpublishedRecordsByCountAuthorFilter(t)),Ae.shouldProtocolAuthorize(t.signaturePayload)&&i.push(r.buildUnpublishedProtocolAuthorizedRecordsFilter(t)),Ae.shouldBuildUnpublishedRecipientFilter(n,t.author)&&i.push(r.buildUnpublishedRecordsForCountAuthorFilter(t))),this.deps.messageStore.count(e,i)}async countPublishedRecords(e,t){let n=r.buildPublishedRecordsFilter(t);return this.deps.messageStore.count(e,[n])}static buildPublishedRecordsFilter(e){let{filter:t}=e.message.descriptor;return{...Ae.convertFilter(t),interface:ve.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:t}=e.message.descriptor;return{...Ae.convertFilter(t),interface:ve.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:t}=e.message.descriptor;return{...Ae.convertFilter(t),interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:t}=e.message.descriptor;return{...Ae.convertFilter(t),author:e.author,interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),Ae.shouldProtocolAuthorize(t.signaturePayload)&&await ws.authorizeQueryOrSubscribe(e,t,n,i)}}});var _a,A0=G(()=>{"use strict";g();xc();yr();lc();Qn();id();st();qs();ar();_a=class r extends Bn{static async parse(e){let t;return e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Ae.validateDelegatedGrantReferentialIntegrity(e,t),_t.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t=e.recordId,n=_t.getCurrentTimestamp(),i={interface:ve.Records,method:me.Delete,messageTimestamp:e.messageTimestamp??n,recordId:t,prune:e.prune??!1},a=await ye.createAuthorization({descriptor:i,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),s={descriptor:i,authorization:a};return ye.validateJsonSchema(s),new r(s)}constructIndexes(e){let n={...this.message.descriptor},{protocol:i,protocolPath:a,recipient:s,schema:o,parentId:c,dateCreated:l}=e.descriptor,d={isLatestBaseState:!0,protocol:i,protocolPath:a,recipient:s,schema:o,parentId:c,dateCreated:l,contextId:e.contextId,author:this.author,...n};return Wt(d),d}async authorizeDelegate(e,t){let n=kr.parse(this.message.authorization.authorDelegatedGrant);await Un.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:t})}}});var cf,h2,m2=G(()=>{"use strict";g();(function(r){r.RecordsDelete="RecordsDelete",r.RecordsSquash="RecordsSquash"})(cf||(cf={}));h2=class r{resumableTaskStore;static timeoutExtensionFrequencyInSeconds=30;resumableTaskBatchSize=100;resumableTaskHandlers;constructor(e,t){this.resumableTaskStore=e,this.resumableTaskHandlers={[cf.RecordsDelete]:async n=>await t.performRecordsDelete(n),[cf.RecordsSquash]:async n=>await t.performRecordsSquash(n)}}async run(e){let t=r.timeoutExtensionFrequencyInSeconds*2,n=await this.resumableTaskStore.register(e,t);await this.runWithAutomaticTimeoutExtension(n)}async runWithAutomaticTimeoutExtension(e){let t=r.timeoutExtensionFrequencyInSeconds*2,n;try{n=setInterval(()=>{this.resumableTaskStore.extend(e.id,t)},r.timeoutExtensionFrequencyInSeconds*1e3);let i=this.resumableTaskHandlers[e.task.name];await i(e.task.data),await this.resumableTaskStore.delete(e.id)}finally{r.clearTimeoutExtensionTimer(n)}}static clearTimeoutExtensionTimer(e){clearInterval(e)}async resumeTasksAndWaitForCompletion(){for(;;){let e=await this.resumableTaskStore.grab(this.resumableTaskBatchSize);if(e===void 0||e.length===0)break;await this.retryTasksUntilCompletion(e)}}async retryTasksUntilCompletion(e){let t=e;for(;t.length>0;){let n=t;t=[];for(let i of n)try{await this.runWithAutomaticTimeoutExtension(i)}catch(a){console.error("Error while running resumable task:",a),console.error("Resumable task:",i),t.push(i)}}}}});var y2,W9=G(()=>{"use strict";g();qo();ar();yr();zo();Fo();ih();Qn();A0();id();zs();m2();y2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await _a.parse(t)}catch(l){return mt(l,400)}try{await mn(t.authorization,this.deps.didResolver)}catch(l){return mt(l,401)}let i={interface:ve.Records,recordId:t.descriptor.recordId},{messages:a}=await this.deps.messageStore.query(e,[i]),s=await ye.getNewestMessage(a);if(!Ae.canPerformDeleteAgainstRecord(t,s))return{status:{code:404,detail:"Not Found"}};if(!await ye.isNewer(t,s))return{status:{code:409,detail:"Conflict"}};try{let l=await Pt.fetchInitialRecordsWrite(this.deps.messageStore,e,t.descriptor.recordId);await r.authorizeRecordsDelete(e,n,l,this.deps.messageStore,this.deps.coreProtocols)}catch(l){return mt(l,401)}return await this.deps.resumableTaskManager.run({name:cf.RecordsDelete,data:{tenant:e,message:t}}),{status:{code:202,detail:"Accepted"}}}static async authorizeRecordsDelete(e,t,n,i,a){if(ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n.message,i),t.author!==e)if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let s=await et.fetchGrant(e,i,t.signaturePayload.permissionGrantId);await Un.authorizeDelete({recordsDeleteMessage:t.message,recordsWriteToDelete:n.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:s,messageStore:i})}else await ws.authorizeDelete(e,t,n,i,a)}}});var g2,J9=G(()=>{"use strict";g();qo();Pp();yr();zo();ih();Qn();wx();zs();rd();ar();g2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await wa.parse(t)}catch(s){return mt(s,400)}let i,a;if(Ae.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0){let s=await this.fetchPublishedRecords(e,n);i=s.messages,a=s.cursor}else{try{await mn(t.authorization,this.deps.didResolver),await r.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(s){return mt(s,401)}if(n.author===e){let s=await this.fetchRecordsAsOwner(e,n);i=s.messages,a=s.cursor}else{let s=await this.fetchRecordsAsNonOwner(e,n);i=s.messages,a=s.cursor}}for(let s of i)if(!await Pt.isInitialWrite(s)){let c=(await this.deps.messageStore.query(e,[{recordId:s.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete c.encodedData,s.initialWrite=c}return{status:{code:200,detail:"OK"},entries:i,cursor:a}}convertDateSort(e){switch(e){case Ot.CreatedAscending:return{dateCreated:At.Ascending};case Ot.CreatedDescending:return{dateCreated:At.Descending};case Ot.PublishedAscending:return{datePublished:At.Ascending};case Ot.PublishedDescending:return{datePublished:At.Descending};case Ot.UpdatedAscending:return{messageTimestamp:At.Ascending};case Ot.UpdatedDescending:return{messageTimestamp:At.Descending};default:return{dateCreated:At.Ascending}}}async fetchRecordsAsOwner(e,t){let{dateSort:n,filter:i,pagination:a}=t.message.descriptor,s={...Ae.convertFilter(i,n),interface:ve.Records,method:me.Write,isLatestBaseState:!0},o=this.convertDateSort(n);return this.deps.messageStore.query(e,[s],o,a)}async fetchRecordsAsNonOwner(e,t){let{dateSort:n,pagination:i,filter:a}=t.message.descriptor,s=[];Ae.filterIncludesPublishedRecords(a)&&s.push(r.buildPublishedRecordsFilter(t)),Ae.filterIncludesUnpublishedRecords(a)&&(Ae.shouldBuildUnpublishedAuthorFilter(a,t.author)&&s.push(r.buildUnpublishedRecordsByQueryAuthorFilter(t)),Ae.shouldProtocolAuthorize(t.signaturePayload)&&s.push(r.buildUnpublishedProtocolAuthorizedRecordsFilter(t)),Ae.shouldBuildUnpublishedRecipientFilter(a,t.author)&&s.push(r.buildUnpublishedRecordsForQueryAuthorFilter(t)));let o=this.convertDateSort(n);return this.deps.messageStore.query(e,s,o,i)}async fetchPublishedRecords(e,t){let{dateSort:n,pagination:i}=t.message.descriptor,a=r.buildPublishedRecordsFilter(t),s=this.convertDateSort(n);return this.deps.messageStore.query(e,[a],s,i)}static buildPublishedRecordsFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ae.convertFilter(n,t),interface:ve.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ae.convertFilter(n,t),interface:ve.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ae.convertFilter(n,t),interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ae.convertFilter(n,t),author:e.author,interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),Ae.shouldProtocolAuthorize(t.signaturePayload)&&await ws.authorizeQueryOrSubscribe(e,t,n,i)}}});var _d,XR=G(()=>{"use strict";g();xc();Pp();yr();lc();Qn();id();st();qs();vt();ar();_d=class r extends Bn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort===Ot.PublishedAscending||e.descriptor.dateSort===Ot.PublishedDescending))throw new ne(re.RecordsReadParseFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let t;return e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Ae.validateDelegatedGrantReferentialIntegrity(e,t),_t.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let{filter:t,signer:n,permissionGrantId:i,protocolRole:a,dateSort:s}=e,o=_t.getCurrentTimestamp();if(e.filter.published===!1&&(s===Ot.PublishedAscending||s===Ot.PublishedDescending))throw new ne(re.RecordsReadCreateFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${s}`);let c={interface:ve.Records,method:me.Read,filter:Ae.normalizeFilter(t),messageTimestamp:e.messageTimestamp??o,permissionGrantId:i,dateSort:s};Wt(c);let l;n!==void 0&&(l=await ye.createAuthorization({descriptor:c,signer:n,permissionGrantId:i,protocolRole:a,delegatedGrant:e.delegatedGrant}));let d={descriptor:c,authorization:l};return ye.validateJsonSchema(d),new r(d)}async authorizeDelegate(e,t){let n=kr.parse(this.message.authorization.authorDelegatedGrant);await Un.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:t})}}});var w2,Z9=G(()=>{"use strict";g();qo();wu();Tn();yr();zo();Fo();ih();Qn();id();XR();zs();vt();ar();w2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await _d.parse(t)}catch(u){return mt(u,400)}try{n.author!==void 0&&await mn(t.authorization,this.deps.didResolver)}catch(u){return mt(u,401)}let i={interface:ve.Records,isLatestBaseState:!0,...Ae.convertFilter(t.descriptor.filter)},a=Ae.convertDateSort(t.descriptor.dateSort),{messages:s}=await this.deps.messageStore.query(e,[i],a,{limit:1});if(s.length===0)return{status:{code:404,detail:"Not Found"}};let o=s[0];if(o.descriptor.method===me.Delete){let u=o,f=u.descriptor.recordId,p=await Pt.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(p===void 0)return mt(new ne(re.RecordsReadInitialWriteNotFound,"initial write for deleted record not found"),400);let h;try{h=await Pt.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{h=p}let m=await Pt.parse(h);try{await r.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return mt(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:u,initialWrite:p}}}let c=o;try{let u=await Pt.parse(c);await r.authorizeRecordsRead(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return mt(u,401)}let l;if(c.encodedData===void 0){let u=await this.deps.dataStore.get(e,c.recordId,c.descriptor.dataCid);if(u?.dataStream===void 0)return{status:{code:410,detail:"Record data not available"},entry:{recordsWrite:c}};l=u.dataStream}else{let u=Ie.base64UrlToBytes(c.encodedData);l=zt.fromBytes(u),delete c.encodedData}let d={status:{code:200,detail:"OK"},entry:{recordsWrite:c,data:l}};if(!await Pt.isInitialWrite(c)){let f=(await this.deps.messageStore.query(e,[{recordId:c.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete f.encodedData,d.entry.initialWrite=f}return d}static async authorizeRecordsRead(e,t,n,i,a){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n.message,i);let{descriptor:s}=n.message;if(t.author!==e){if(s.published===!0)return;if(t.author!==void 0&&(t.author===s.recipient||t.author===n.author))return;if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let o=await et.fetchGrant(e,i,t.signaturePayload.permissionGrantId);await Un.authorizeRead({recordsReadMessage:t.message,recordsWriteMessageToBeRead:n.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:o,messageStore:i})}else await ws.authorizeRead(e,t,n,i,a)}}}});var Aa,v2=G(()=>{"use strict";g();xc();yr();lc();Qn();id();st();qs();vt();ar();ma();Aa=class r extends Bn{static async parse(e){let t;if(e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Ae.validateDelegatedGrantReferentialIntegrity(e,t),t?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne(re.RecordsSubscribeFilterMissingRequiredProperties,"Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&di(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&nd(e.descriptor.filter.schema),_t.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:ve.Records,method:me.Subscribe,messageTimestamp:e.messageTimestamp??_t.getCurrentTimestamp(),filter:Ae.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};Wt(t);let n=e.signer,i;n&&(i=await ye.createAuthorization({descriptor:t,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:t,authorization:i};return ye.validateJsonSchema(a),new r(a)}async authorizeDelegate(e){let t=kr.parse(this.message.authorization.authorDelegatedGrant);await Un.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:t,messageStore:e})}}});var b2,Y9=G(()=>{"use strict";g();qo();Pp();yr();zo();ih();Qn();v2();zs();rd();vt();ar();b2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return mt(new ne(re.RecordsSubscribeEventLogUnimplemented,"Subscriptions are not supported"),501);let i;try{i=await Aa.parse(t)}catch(f){return mt(f,400)}let a=[],s=[];if(Ae.filterIncludesPublishedRecords(i.message.descriptor.filter)&&i.author===void 0)a=[r.buildPublishedEventFilter(i)],s=[r.buildPublishedQueryFilter(i)],delete t.authorization;else{try{await mn(t.authorization,this.deps.didResolver),await r.authorizeRecordsSubscribe(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return mt(f,401)}i.author===e?(a=r.buildOwnerEventFilters(i),s=r.buildOwnerQueryFilters(i)):(a=r.buildNonOwnerEventFilters(i),s=r.buildNonOwnerQueryFilters(i))}let o=await ye.getCid(t),{cursor:c}=i.message.descriptor;if(c!==void 0)try{let f=await this.deps.eventLog.subscribe(e,o,n,{cursor:c,filters:a});return{status:{code:200,detail:"OK"},subscription:f}}catch(f){if(f instanceof ne&&f.code===re.EventLogProgressGap){let p=f.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:p===void 0?void 0:{code:"ProgressGap",...p}}}return mt(f,500)}let l=await this.deps.eventLog.subscribe(e,o,n,{filters:a}),d,u;try{let{dateSort:f,pagination:p}=i.message.descriptor,h=r.convertDateSort(f),m=await this.deps.messageStore.query(e,s,h,p);d=m.messages,u=m.cursor;for(let y of d)if(!await Pt.isInitialWrite(y)){let w=(await this.deps.messageStore.query(e,[{recordId:y.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete w.encodedData,y.initialWrite=w}}catch(f){return await l.close(),mt(f,500)}return{status:{code:200,detail:"OK"},subscription:l,entries:d,cursor:u}}static convertDateSort(e){switch(e){case Ot.CreatedAscending:return{dateCreated:At.Ascending};case Ot.CreatedDescending:return{dateCreated:At.Descending};case Ot.PublishedAscending:return{datePublished:At.Ascending};case Ot.PublishedDescending:return{datePublished:At.Descending};case Ot.UpdatedAscending:return{messageTimestamp:At.Ascending};case Ot.UpdatedDescending:return{messageTimestamp:At.Descending};default:return{dateCreated:At.Ascending}}}static buildOwnerEventFilters(e){let{filter:t}=e.message.descriptor;return[{...Ae.convertFilter(t),interface:ve.Records,method:[me.Write,me.Delete]}]}static buildNonOwnerEventFilters(e){let t=[],{filter:n}=e.message.descriptor;return Ae.filterIncludesPublishedRecords(n)&&t.push(r.buildPublishedEventFilter(e)),Ae.filterIncludesUnpublishedRecords(n)&&(Ae.shouldBuildUnpublishedAuthorFilter(n,e.author)&&t.push({...Ae.convertFilter(n),author:e.author,interface:ve.Records,method:[me.Write,me.Delete],published:!1}),Ae.shouldProtocolAuthorize(e.signaturePayload)&&t.push({...Ae.convertFilter(n),interface:ve.Records,method:[me.Write,me.Delete],published:!1}),Ae.shouldBuildUnpublishedRecipientFilter(n,e.author)&&t.push({...Ae.convertFilter(n),interface:ve.Records,method:[me.Write,me.Delete],recipient:e.author,published:!1})),t}static buildPublishedEventFilter(e){return{...Ae.convertFilter(e.message.descriptor.filter),interface:ve.Records,method:[me.Write,me.Delete],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:t,filter:n}=e.message.descriptor;return[{...Ae.convertFilter(n,t),interface:ve.Records,method:me.Write,isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let t=[],{dateSort:n,filter:i}=e.message.descriptor;return Ae.filterIncludesPublishedRecords(i)&&t.push(r.buildPublishedQueryFilter(e)),Ae.filterIncludesUnpublishedRecords(i)&&(Ae.shouldBuildUnpublishedAuthorFilter(i,e.author)&&t.push({...Ae.convertFilter(i,n),author:e.author,interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}),Ae.shouldProtocolAuthorize(e.signaturePayload)&&t.push({...Ae.convertFilter(i,n),interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}),Ae.shouldBuildUnpublishedRecipientFilter(i,e.author)&&t.push({...Ae.convertFilter(i,n),interface:ve.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1})),t}static buildPublishedQueryFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ae.convertFilter(n,t),interface:ve.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),Ae.shouldProtocolAuthorize(t.signaturePayload)&&await ws.authorizeQueryOrSubscribe(e,t,n,i)}}});var Uy,QR=G(()=>{"use strict";g();Py();gc();yr();Qn();A0();zs();ar();Uy=class r{messageStore;dataStore;stateIndex;eventLog;constructor({messageStore:e,dataStore:t,stateIndex:n,eventLog:i}){this.messageStore=e,this.dataStore=t,this.stateIndex=n,this.eventLog=i}async performRecordsDelete({tenant:e,message:t}){let n={interface:ve.Records,recordId:t.descriptor.recordId},{messages:i}=await this.messageStore.query(e,[n]),a=await ye.getNewestMessage(i);if(!Ae.canPerformDeleteAgainstRecord(t,a))return;let s=await _a.parse(t),o=await Pt.getInitialWrite(i),c=s.constructIndexes(o),l=await ye.getCid(t);await this.messageStore.put(e,t,c),await this.stateIndex.insert(e,l,c),this.eventLog!==void 0&&await this.eventLog.emit(e,{message:t,initialWrite:o},c,l),t.descriptor.prune&&await r.purgeRecordDescendants(e,t.descriptor.recordId,this.messageStore,this.dataStore,this.stateIndex),await r.deleteAllOlderMessagesButKeepInitialWrite(e,i,t,this.messageStore,this.dataStore,this.stateIndex)}async performRecordsSquash({tenant:e,message:t}){let{protocol:n,protocolPath:i,messageTimestamp:a}=t.descriptor,s={interface:ve.Records,protocol:n,protocolPath:i},o=Ae.getParentContextFromOfContextId(t.contextId);if(o!==void 0&&o!==""){let d=Xt.constructPrefixFilterAsRangeFilter(o);s.contextId=d}let{messages:c}=await this.messageStore.query(e,[s]),l=new Map;for(let d of c){let u;Ae.isRecordsWrite(d)?u=d.recordId:u=d.descriptor.recordId;let f=l.get(u);f===void 0?l.set(u,[d]):f.push(d)}for(let[d,u]of l){if(d===t.recordId)continue;let f=await ye.getNewestMessage(u);if(f===void 0)continue;f.descriptor.messageTimestamp<a&&await r.purgeRecordMessages(e,u,this.messageStore,this.dataStore,this.stateIndex)}}static async deleteFromDataStoreIfNeeded(e,t,n,i){if(n.descriptor.method!==me.Write)return;let a=n;a.descriptor.dataSize<=co.maxDataSizeAllowedToBeEncoded||a.descriptor.dataCid!==i.descriptor.dataCid&&await e.delete(t,a.recordId,a.descriptor.dataCid)}static async purgeRecordDescendants(e,t,n,i,a){let s={interface:ve.Records,parentId:t},{messages:o}=await n.query(e,[s]),c=new Map;for(let l of o){let d;Ae.isRecordsWrite(l)?d=l.recordId:d=l.descriptor.recordId;let u=c.get(d);u?u.push(l):c.set(d,[l])}for(let l of c.keys())await r.purgeRecordDescendants(e,l,n,i,a);for(let l of c.keys())await r.purgeRecordMessages(e,c.get(l),n,i,a)}static async purgeRecordMessages(e,t,n,i,a){let s=t.filter(l=>l.descriptor.method===me.Write),o=await ye.getNewestMessage(s);await i.delete(e,o.recordId,o.descriptor.dataCid);let c=await Promise.all(t.map(l=>ye.getCid(l)));await a.delete(e,c),await Promise.all(c.map(l=>n.delete(e,l)))}static async deleteAllOlderMessagesButKeepInitialWrite(e,t,n,i,a,s){let o=[];for(let c of t){if(await ye.isOlder(c,n)){await r.deleteFromDataStoreIfNeeded(a,e,c,n);let d=await ye.getCid(c);if(await i.delete(e,d),await Pt.isInitialWrite(c)){let h=await(await Pt.parse(c)).constructIndexes(!1),m=c;delete m.encodedData,await i.put(e,m,h)}else{let f=await ye.getCid(c);o.push(f)}}await s.delete(e,o)}}}});var P2,X9=G(()=>{"use strict";g();qo();fl();wu();Py();Tn();gc();yr();zo();Fo();ih();Qn();id();zs();m2();rd();QR();vt();ar();P2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t,dataStream:n}){let i;try{i=await Pt.parse(t),await ws.validateReferentialIntegrity(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(h){return mt(h,400)}try{await mn(t.authorization,this.deps.didResolver,t.attestation),await this.authorizeRecordsWrite(e,i,this.deps.messageStore)}catch(h){return mt(h,401)}let a={interface:ve.Records,recordId:t.recordId},{messages:s}=await this.deps.messageStore.query(e,[a]),o=await i.isInitialWrite(),c;if(!o)try{c=await Pt.getInitialWrite(s),Pt.verifyEqualityOfImmutableProperties(c,t)}catch(h){return mt(h,400)}try{await this.enforceSquashBackstop(e,t)}catch(h){return mt(h,409)}let l=await ye.getNewestMessage(s),d=!1,u;if(l===void 0||await ye.isNewer(t,l)?(d=!0,u=t):u=l,!d){let h=!1;if(l!==void 0&&n!==void 0&&await Pt.isInitialWrite(l)){let y=!!l.encodedData,v=this.deps.dataStore?!!await this.deps.dataStore.get(e,i.message.recordId,t.descriptor.dataCid):!1;h=!y&&!v}if(!h)return{status:{code:409,detail:"Conflict"}}}let f=t.descriptor.protocol===void 0?void 0:this.deps.coreProtocols?.get(t.descriptor.protocol);try{if(l?.descriptor.method===me.Delete)throw new ne(re.RecordsWriteNotAllowedAfterDelete,"RecordsWrite is not allowed after a RecordsDelete.");f?.preProcessWrite!==void 0&&await f.preProcessWrite(e,t,this.deps.messageStore);let h=!1,m=t;if(n===void 0){if(!o){let w=l;m=await this.processMessageWithoutDataStream(e,t,w),h=!0}}else m=await this.processMessageWithDataStream(e,t,n),h=!0;let y=await i.constructIndexes(h);await this.deps.messageStore.put(e,m,y);let v=await ye.getCid(t);await this.deps.stateIndex.insert(e,v,y),this.deps.eventLog!==void 0&&h&&await this.deps.eventLog.emit(e,{message:m,initialWrite:c},y,v)}catch(h){if(h instanceof ne&&(h.code===re.RecordsWriteMissingEncodedDataInPrevious||h.code===re.RecordsWriteMissingDataInPrevious||h.code===re.RecordsWriteNotAllowedAfterDelete||h.code===re.RecordsWriteDataCidMismatch||h.code===re.RecordsWriteDataSizeMismatch||h.code.startsWith("SchemaValidator")||this.deps.coreProtocols?.mapErrorToStatusCode(h.code)!==void 0))return mt(h,400);throw h}let p={status:o&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await Uy.deleteAllOlderMessagesButKeepInitialWrite(e,s,u,this.deps.messageStore,this.deps.dataStore,this.deps.stateIndex),t.descriptor.squash===!0&&await this.deps.resumableTaskManager.run({name:cf.RecordsSquash,data:{tenant:e,message:t}}),f?.postProcessWrite!==void 0&&await f.postProcessWrite(e,i,{messageStore:this.deps.messageStore,dataStore:this.deps.dataStore,stateIndex:this.deps.stateIndex}),p}async cloneAndAddEncodedData(e,t){let n={...e};return n.encodedData=Ie.bytesToBase64Url(t),n}async processMessageWithDataStream(e,t,n){let i=t;if(t.descriptor.dataSize<=co.maxDataSizeAllowedToBeEncoded){let a=await zt.toBytes(n),s=await ur.computeDagPbCidFromBytes(a);r.validateDataIntegrity(t.descriptor.dataCid,t.descriptor.dataSize,s,a.length);let o=t.descriptor.protocol===void 0?void 0:this.deps.coreProtocols?.get(t.descriptor.protocol);o?.validateRecord!==void 0&&o.validateRecord(t,a),i=await this.cloneAndAddEncodedData(t,a)}else{let[a,s]=zt.duplicateDataStream(n,2);try{let[o,c]=await Promise.all([ur.computeDagPbCidFromStream(a),this.deps.dataStore.put(e,t.recordId,t.descriptor.dataCid,s)]);r.validateDataIntegrity(t.descriptor.dataCid,t.descriptor.dataSize,o,c.dataSize)}catch(o){throw await this.deps.dataStore.delete(e,t.recordId,t.descriptor.dataCid),o}}return i}async processMessageWithoutDataStream(e,t,n){let i={...t},{dataCid:a,dataSize:s}=t.descriptor;if(r.validateDataIntegrity(a,s,n.descriptor.dataCid,n.descriptor.dataSize),s<=co.maxDataSizeAllowedToBeEncoded){if(n.encodedData===void 0)throw new ne(re.RecordsWriteMissingEncodedDataInPrevious,"No dataStream was provided and unable to get data from previous message");i.encodedData=n.encodedData}else if(await this.deps.dataStore.get(e,n.recordId,t.descriptor.dataCid)===void 0)throw new ne(re.RecordsWriteMissingDataInPrevious,"No dataStream was provided and unable to get data from previous message");return i}static validateDataIntegrity(e,t,n,i){if(e!==n)throw new ne(re.RecordsWriteDataCidMismatch,`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(t!==i)throw new ne(re.RecordsWriteDataSizeMismatch,`actual data size ${i} bytes does not match dataSize in descriptor: ${t}`)}async enforceSquashBackstop(e,t){if(t.descriptor.protocol===void 0||t.descriptor.protocolPath===void 0)return;let n;try{n=await ws.fetchProtocolDefinition(e,t.descriptor.protocol,this.deps.messageStore,void 0,this.deps.coreProtocols)}catch(d){console.warn(`enforceSquashBackstop: failed to fetch protocol definition for '${t.descriptor.protocol}':`,d);return}let i=t.descriptor.protocolPath.split("/"),a=n.structure[i[0]];for(let d=1;d<i.length&&a!==void 0;d++)a=a[i[d]];if(a?.$squash!==!0)return;let s={interface:ve.Records,method:me.Write,isLatestBaseState:!0,protocol:t.descriptor.protocol,protocolPath:t.descriptor.protocolPath,squash:!0},o=Ae.getParentContextFromOfContextId(t.contextId);if(o!==void 0&&o!==""){let d=Xt.constructPrefixFilterAsRangeFilter(o);s.contextId=d}let{messages:c}=await this.deps.messageStore.query(e,[s],{messageTimestamp:At.Descending},{limit:1});if(c.length===0)return;let l=c[0];if(t.descriptor.messageTimestamp<=l.descriptor.messageTimestamp)throw new ne(re.ProtocolAuthorizationSquashBackstop,`incoming message timestamp '${t.descriptor.messageTimestamp}' is not newer than the most recent squash record timestamp '${l.descriptor.messageTimestamp}' at protocol path '${t.descriptor.protocolPath}'.`)}async authorizeRecordsWrite(e,t,n){if(t.owner!==void 0&&t.owner!==e)throw new ne(re.RecordsWriteOwnerAndTenantMismatch,`Owner ${t.owner} must be the same as tenant ${e} when specified.`);if(t.isSignedByAuthorDelegate&&await t.authorizeAuthorDelegate(n),t.isSignedByOwnerDelegate&&await t.authorizeOwnerDelegate(n),t.owner===void 0){if(t.author===e)return;if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let i=await et.fetchGrant(e,n,t.signaturePayload.permissionGrantId);await Un.authorizeWrite({recordsWriteMessage:t.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:i,messageStore:n})}else await ws.authorizeWrite(e,t,n,this.deps.coreProtocols)}}}});function dle(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 i=0;i<r.length;i++){var a=r.charAt(i),s=a.charCodeAt(0);if(t[s]!==255)throw new TypeError(a+" is ambiguous");t[s]=i}var o=r.length,c=r.charAt(0),l=Math.log(o)/Math.log(256),d=Math.log(256)/Math.log(o);function u(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,y=0,v=0,w=h.length;v!==w&&h[v]===0;)v++,m++;for(var E=(w-v)*d+1>>>0,_=new Uint8Array(E);v!==w;){for(var A=h[v],D=0,M=E-1;(A!==0||D<y)&&M!==-1;M--,D++)A+=256*_[M]>>>0,_[M]=A%o>>>0,A=A/o>>>0;if(A!==0)throw new Error("Non-zero carry");y=D,v++}for(var C=E-y;C!==E&&_[C]===0;)C++;for(var z=c.repeat(m);C<E;++C)z+=r.charAt(_[C]);return z}function f(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var y=0,v=0;h[m]===c;)y++,m++;for(var w=(h.length-m)*l+1>>>0,E=new Uint8Array(w);h[m];){var _=t[h.charCodeAt(m)];if(_===255)return;for(var A=0,D=w-1;(_!==0||A<v)&&D!==-1;D--,A++)_+=o*E[D]>>>0,E[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");v=A,m++}if(h[m]!==" "){for(var M=w-v;M!==w&&E[M]===0;)M++;for(var C=new Uint8Array(y+(w-M)),z=y;M!==w;)C[z++]=E[M++];return C}}}function p(h){var m=f(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:p}}function ble(r){return r.byteOffset!==0||r.byteLength!==r.buffer.byteLength}function Ple(r){return typeof r!="object"||r===null?!1:typeof r[Symbol.asyncIterator]=="function"}function lC(r){let e=Object.prototype.toString.call(r).match(/\s([a-zA-Z0-9]+)/),[t,n]=e;return n}function $z(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Ale;)e[t++]=r&255|rq,r/=128;for(;r&_le;)e[t++]=r&255|rq,r>>>=7;return e[t]=r|0,$z.bytes=t-n+1,e}function uC(r,n){var t=0,n=n||0,i=0,a=n,s,o=r.length;do{if(a>=o)throw uC.bytes=0,new RangeError("Could not decode varint");s=r[a++],t+=i<28?(s&nq)<<i:(s&nq)*Math.pow(2,i),i+=7}while(s>=Ile);return uC.bytes=a-n,t}function Bz(r){Object.keys(r).forEach(e=>{let t=r[e];t===void 0?delete r[e]:t!==null&&typeof t=="object"&&Bz(t)})}function Xle(r){let e=r.trim().toLowerCase();e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1));let t=e.indexOf("%");if(t!==-1&&(e=e.slice(0,t)),e.endsWith(".")&&(e=e.slice(0,-1)),e==="localhost"||e.endsWith(".localhost"))return!0;let n=jz(e);return n!==void 0?Mz(n):e.includes(":")?rue(e):!1}function aq(r,e="URL",t){var n;let i=typeof r=="string"?new URL(r):new URL(r.toString()),a=(n=t?.allowedProtocols)!==null&&n!==void 0?n:Qle;if(!a.includes(i.protocol))throw new R2(`${e} must use one of the allowed schemes (${a.join(", ")}): ${i.protocol}`);if(i.hostname==="")throw new R2(`${e} must specify a hostname.`);if(Xle(i.hostname))throw new R2(`${e} must not target a private, loopback, or link-local host: ${i.hostname}`);return i}function Oz(r,e,t){return Yle(this,void 0,void 0,function*(){var n,i;let a=(n=t?.description)!==null&&n!==void 0?n:"URL",s=(i=t?.maxRedirects)!==null&&i!==void 0?i:eue,o=aq(r,a,{allowedProtocols:t?.allowedProtocols}).href;for(let c=0;c<=s;c++){let l=yield fetch(o,Object.assign(Object.assign({},e),{redirect:"manual"}));if(!tue.has(l.status))return l;let d=l.headers.get("location");if(d===null)return l;o=aq(new URL(d,o),a,{allowedProtocols:t?.allowedProtocols}).href}throw new Error(`${a} exceeded the maximum number of redirects (${s}).`)})}function jz(r){let e=r.split(".");if(e.length!==4)return;let t=e.map(n=>/^\d+$/.test(n)?Number(n):Number.NaN);if(t.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return t}function Mz([r,e]){return r===0||r===10||r===100&&e>=64&&e<=127||r===127||r===169&&e===254||r===172&&e>=16&&e<=31||r===192&&e===168||r>=224}function rue(r){let e=nue(r);if(e===void 0)return!1;let[t,n,i,a,s,o,c,l]=e,d=t===0&&n===0&&i===0&&a===0&&s===0&&o===0;return e.every(u=>u===0)||d&&c===0&&l===1||(t&65024)===64512||(t&65472)===65152||(t&65280)===65280?!0:t===100&&n===65435&&i===0&&a===0&&s===0&&o===0||t===0&&n===0&&i===0&&a===0&&s===0&&o===65535?Mz(sue(c,l)):!!d}function nue(r){let[e,t,n]=r.split("::");if(n!==void 0)return;let i=e===""?[]:e.split(":"),a=t===void 0||t===""?[]:t.split(":"),s=iue([...i,...a]);if(s===void 0||s.length>8||t===void 0&&s.length!==8||t!==void 0&&s.length>=8)return;let o=s.map(l=>/^[0-9a-f]{1,4}$/.test(l)?Number.parseInt(l,16):Number.NaN);if(!o.every(l=>Number.isInteger(l)&&l>=0&&l<=65535))return;if(t===void 0)return o;let c=new Array(8-o.length).fill(0);return[...o.slice(0,i.length),...c,...o.slice(i.length)]}function iue(r){let e=r.at(-1);if(!e?.includes("."))return r;let t=jz(e);if(t===void 0)return;let[n,i,a,s]=t;return[...r.slice(0,-1),((n<<8|i)&65535).toString(16),((a<<8|s)&65535).toString(16)]}function sue(r,e){return[r>>8&255,r&255,e>>8&255,e&255]}function Od(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function yh(r){if(!Od(r))throw new Error("Uint8Array expected");let e="";for(let t=0;t<r.length;t++)e+=aue[r[t]];return e}function Nz(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function jC(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}function cq(r){if(r>=jl._0&&r<=jl._9)return r-jl._0;if(r>=jl._A&&r<=jl._F)return r-(jl._A-10);if(r>=jl._a&&r<=jl._f)return r-(jl._a-10)}function Xy(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let i=0,a=0;i<t;i++,a+=2){let s=cq(r.charCodeAt(a)),o=cq(r.charCodeAt(a+1));if(s===void 0||o===void 0){let c=r[a]+r[a+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+a)}n[i]=s*16+o}return n}function ph(r){return jC(yh(r))}function Sf(r){if(!Od(r))throw new Error("Uint8Array expected");return jC(yh(Uint8Array.from(r).reverse()))}function jd(r,e){return Xy(r.toString(16).padStart(e*2,"0"))}function Qy(r,e){return jd(r,e).reverse()}function cue(r){return Xy(Nz(r))}function Hn(r,e,t){let n;if(typeof e=="string")try{n=Xy(e)}catch(a){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${a}`)}else if(Od(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let i=n.length;if(typeof t=="number"&&i!==t)throw new Error(`${r} expected ${t} bytes, got ${i}`);return n}function gh(...r){let e=0;for(let i=0;i<r.length;i++){let a=r[i];if(!Od(a))throw new Error("Uint8Array expected");e+=a.length}let t=new Uint8Array(e),n=0;for(let i=0;i<r.length;i++){let a=r[i];t.set(a,n),n+=a.length}return t}function due(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function lue(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function uue(r){let e;for(e=0;r>Uz;r>>=fE,e+=1);return e}function fue(r,e){return r>>BigInt(e)&fE}function Lz(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=eC(r),i=eC(r),a=0,s=()=>{n.fill(1),i.fill(0),a=0},o=(...d)=>t(i,n,...d),c=(d=eC())=>{i=o(dq([0]),d),n=o(),d.length!==0&&(i=o(dq([1]),d),n=o())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,u=[];for(;d<e;){n=o();let f=n.slice();u.push(f),d+=n.length}return gh(...u)};return(d,u)=>{s(),c(d);let f;for(;!(f=u(l()));)c();return s(),f}}function bh(r,e,t={}){let n=(i,a,s)=>{let o=hue[a];if(typeof o!="function")throw new Error(`Invalid validator "${a}", expected function`);let c=r[i];if(!(s&&c===void 0)&&!o(c,r))throw new Error(`Invalid param ${String(i)}=${c} (${typeof c}), expected ${a}`)};for(let[i,a]of Object.entries(e))n(i,a,!1);for(let[i,a]of Object.entries(t))n(i,a,!0);return r}function lq(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function mue(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function qz(r,...e){if(!mue(r))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(r.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${r.length}`)}function yue(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");lq(r.outputLen),lq(r.blockLen)}function Q2(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function gue(r,e){qz(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}function zz(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Fz(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function KC(r){if(typeof r=="string"&&(r=Fz(r)),!zz(r))throw new Error(`expected Uint8Array, got ${typeof r}`);return r}function Gz(...r){let e=0;for(let n=0;n<r.length;n++){let i=r[n];if(!zz(i))throw new Error("Uint8Array expected");e+=i.length}let t=new Uint8Array(e);for(let n=0,i=0;n<r.length;n++){let a=r[n];t.set(a,i),i+=a.length}return t}function Vz(r){let e=n=>r().update(KC(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function UC(r=32){if(tC&&typeof tC.getRandomValues=="function")return tC.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function vue(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),a=BigInt(4294967295),s=Number(t>>i&a),o=Number(t&a),c=n?4:0,l=n?0:4;r.setUint32(e+c,s,n),r.setUint32(e+l,o,n)}function Zr(r,e){let t=r%e;return t>=mi?t:e+t}function Zz(r,e,t){if(t<=mi||e<mi)throw new Error("Expected power/modulo > 0");if(t===yn)return mi;let n=yn;for(;e>mi;)e&yn&&(n=n*r%t),r=r*r%t,e>>=yn;return n}function En(r,e,t){let n=r;for(;e-- >mi;)n*=n,n%=t;return n}function hC(r,e){if(r===mi||e<=mi)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Zr(r,e),n=e,i=mi,a=yn,s=yn,o=mi;for(;t!==mi;){let c=n/t,l=n%t,d=i-s*c,u=a-o*c;n=t,t=l,i=s,a=o,s=d,o=u}if(n!==yn)throw new Error("invert: does not exist");return Zr(i,e)}function _ue(r){let e=(r-yn)/ch,t,n,i;for(t=r-yn,n=0;t%ch===mi;t/=ch,n++);for(i=ch;i<r&&Zz(i,e,r)!==r-yn;i++);if(n===1){let s=(r+yn)/pC;return function(o,c){let l=o.pow(c,s);if(!o.eql(o.sqr(l),c))throw new Error("Cannot find square root");return l}}let a=(t+yn)/ch;return function(s,o){if(s.pow(o,e)===s.neg(s.ONE))throw new Error("Cannot find square root");let c=n,l=s.pow(s.mul(s.ONE,i),t),d=s.pow(o,a),u=s.pow(o,t);for(;!s.eql(u,s.ONE);){if(s.eql(u,s.ZERO))return s.ZERO;let f=1;for(let h=s.sqr(u);f<c&&!s.eql(h,s.ONE);f++)h=s.sqr(h);let p=s.pow(l,yn<<BigInt(c-f-1));l=s.sqr(p),d=s.mul(d,p),u=s.mul(u,l),c=f}return d}}function Aue(r){if(r%pC===Sue){let e=(r+yn)/pC;return function(t,n){let i=t.pow(n,e);if(!t.eql(t.sqr(i),n))throw new Error("Cannot find square root");return i}}if(r%fq===uq){let e=(r-uq)/fq;return function(t,n){let i=t.mul(n,ch),a=t.pow(i,e),s=t.mul(n,a),o=t.mul(t.mul(s,ch),a),c=t.mul(s,t.sub(o,t.ONE));if(!t.eql(t.sqr(c),n))throw new Error("Cannot find square root");return c}}return r%kue,_ue(r)}function Due(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Iue.reduce((n,i)=>(n[i]="function",n),e);return bh(r,t)}function Rue(r,e,t){if(t<mi)throw new Error("Expected power > 0");if(t===mi)return r.ONE;if(t===yn)return e;let n=r.ONE,i=e;for(;t>mi;)t&yn&&(n=r.mul(n,i)),i=r.sqr(i),t>>=yn;return n}function Cue(r,e){let t=new Array(e.length),n=e.reduce((a,s,o)=>r.is0(s)?a:(t[o]=a,r.mul(a,s)),r.ONE),i=r.inv(n);return e.reduceRight((a,s,o)=>r.is0(s)?a:(t[o]=r.mul(a,t[o]),r.mul(a,s)),i),t}function Yz(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function NC(r,e,t=!1,n={}){if(r<=mi)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:i,nByteLength:a}=Yz(r,e);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=Aue(r),o=Object.freeze({ORDER:r,BITS:i,BYTES:a,MASK:MC(i),ZERO:mi,ONE:yn,create:c=>Zr(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return mi<=c&&c<r},is0:c=>c===mi,isOdd:c=>(c&yn)===yn,neg:c=>Zr(-c,r),eql:(c,l)=>c===l,sqr:c=>Zr(c*c,r),add:(c,l)=>Zr(c+l,r),sub:(c,l)=>Zr(c-l,r),mul:(c,l)=>Zr(c*l,r),pow:(c,l)=>Rue(o,c,l),div:(c,l)=>Zr(c*hC(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>hC(c,r),sqrt:n.sqrt||(c=>s(o,c)),invertBatch:c=>Cue(o,c),cmov:(c,l,d)=>d?l:c,toBytes:c=>t?Qy(c,a):jd(c,a),fromBytes:c=>{if(c.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${c.length}`);return t?Sf(c):ph(c)}});return Object.freeze(o)}function $ue(r,e){if(!r.isOdd)throw new Error("Field doesn't have isOdd");let t=r.sqrt(e);return r.isOdd(t)?r.neg(t):t}function Xz(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function Qz(r){let e=Xz(r);return e+Math.ceil(e/2)}function Bue(r,e,t=!1){let n=r.length,i=Xz(e),a=Qz(e);if(n<16||n<a||n>1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);let s=t?ph(r):Sf(r),o=Zr(s,e-yn)+yn;return t?Qy(o,i):jd(o,i)}function e7(r,e){let t=(i,a)=>{let s=a.negate();return i?s:a},n=i=>{let a=Math.ceil(e/i)+1,s=2**(i-1);return{windows:a,windowSize:s}};return{constTimeNegate:t,unsafeLadder(i,a){let s=r.ZERO,o=i;for(;a>Oue;)a&nC&&(s=s.add(o)),o=o.double(),a>>=nC;return s},precomputeWindow(i,a){let{windows:s,windowSize:o}=n(a),c=[],l=i,d=l;for(let u=0;u<s;u++){d=l,c.push(d);for(let f=1;f<o;f++)d=d.add(l),c.push(d);l=d.double()}return c},wNAF(i,a,s){let{windows:o,windowSize:c}=n(i),l=r.ZERO,d=r.BASE,u=BigInt(2**i-1),f=2**i,p=BigInt(i);for(let h=0;h<o;h++){let m=h*c,y=Number(s&u);s>>=p,y>c&&(y-=f,s+=nC);let v=m,w=m+Math.abs(y)-1,E=h%2!==0,_=y<0;y===0?d=d.add(t(E,a[v])):l=l.add(t(_,a[w]))}return{p:l,f:d}},wNAFCached(i,a,s,o){let c=i._WINDOW_SIZE||1,l=a.get(i);return l||(l=this.precomputeWindow(i,c),c!==1&&a.set(i,o(l))),this.wNAF(c,l,s)}}}function LC(r){return Due(r.Fp),bh(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Yz(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}function jue(r){let e=LC(r);bh(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:i}=e;if(t){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}function Uue(r){let e=jue(r),{Fp:t}=e,n=e.toBytes||((h,m,y)=>{let v=m.toAffine();return gh(Uint8Array.from([4]),t.toBytes(v.x),t.toBytes(v.y))}),i=e.fromBytes||(h=>{let m=h.subarray(1),y=t.fromBytes(m.subarray(0,t.BYTES)),v=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:y,y:v}});function a(h){let{a:m,b:y}=e,v=t.sqr(h),w=t.mul(v,h);return t.add(t.add(w,t.mul(h,m)),y)}if(!t.eql(t.sqr(e.Gy),a(e.Gx)))throw new Error("bad generator point: equation left != right");function s(h){return typeof h=="bigint"&&ql<h&&h<e.n}function o(h){if(!s(h))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(h){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:v,n:w}=e;if(m&&typeof h!="bigint"){if(Od(h)&&(h=yh(h)),typeof h!="string"||!m.includes(h.length))throw new Error("Invalid key");h=h.padStart(y*2,"0")}let E;try{E=typeof h=="bigint"?h:ph(Hn("private key",h,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof h}`)}return v&&(E=Zr(E,w)),o(E),E}let l=new Map;function d(h){if(!(h instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(m,y,v){if(this.px=m,this.py=y,this.pz=v,m==null||!t.isValid(m))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(v==null||!t.isValid(v))throw new Error("z required")}static fromAffine(m){let{x:y,y:v}=m||{};if(!m||!t.isValid(y)||!t.isValid(v))throw new Error("invalid affine point");if(m instanceof u)throw new Error("projective point not allowed");let w=E=>t.eql(E,t.ZERO);return w(y)&&w(v)?u.ZERO:new u(y,v,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=t.invertBatch(m.map(v=>v.pz));return m.map((v,w)=>v.toAffine(y[w])).map(u.fromAffine)}static fromHex(m){let y=u.fromAffine(i(Hn("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return u.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not FE");let v=t.sqr(y),w=a(m);if(!t.eql(v,w))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){d(m);let{px:y,py:v,pz:w}=this,{px:E,py:_,pz:A}=m,D=t.eql(t.mul(y,A),t.mul(E,w)),M=t.eql(t.mul(v,A),t.mul(_,w));return D&&M}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,v=t.mul(y,pq),{px:w,py:E,pz:_}=this,A=t.ZERO,D=t.ZERO,M=t.ZERO,C=t.mul(w,w),z=t.mul(E,E),L=t.mul(_,_),B=t.mul(w,E);return B=t.add(B,B),M=t.mul(w,_),M=t.add(M,M),A=t.mul(m,M),D=t.mul(v,L),D=t.add(A,D),A=t.sub(z,D),D=t.add(z,D),D=t.mul(A,D),A=t.mul(B,A),M=t.mul(v,M),L=t.mul(m,L),B=t.sub(C,L),B=t.mul(m,B),B=t.add(B,M),M=t.add(C,C),C=t.add(M,C),C=t.add(C,L),C=t.mul(C,B),D=t.add(D,C),L=t.mul(E,_),L=t.add(L,L),C=t.mul(L,B),A=t.sub(A,C),M=t.mul(L,z),M=t.add(M,M),M=t.add(M,M),new u(A,D,M)}add(m){d(m);let{px:y,py:v,pz:w}=this,{px:E,py:_,pz:A}=m,D=t.ZERO,M=t.ZERO,C=t.ZERO,z=e.a,L=t.mul(e.b,pq),B=t.mul(y,E),W=t.mul(v,_),ee=t.mul(w,A),R=t.add(y,v),$=t.add(E,_);R=t.mul(R,$),$=t.add(B,W),R=t.sub(R,$),$=t.add(y,w);let S=t.add(E,A);return $=t.mul($,S),S=t.add(B,ee),$=t.sub($,S),S=t.add(v,w),D=t.add(_,A),S=t.mul(S,D),D=t.add(W,ee),S=t.sub(S,D),C=t.mul(z,$),D=t.mul(L,ee),C=t.add(D,C),D=t.sub(W,C),C=t.add(W,C),M=t.mul(D,C),W=t.add(B,B),W=t.add(W,B),ee=t.mul(z,ee),$=t.mul(L,$),W=t.add(W,ee),ee=t.sub(B,ee),ee=t.mul(z,ee),$=t.add($,ee),B=t.mul(W,$),M=t.add(M,B),B=t.mul(S,$),D=t.mul(R,D),D=t.sub(D,B),B=t.mul(R,W),C=t.mul(S,C),C=t.add(C,B),new u(D,M,C)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return p.wNAFCached(this,l,m,y=>{let v=t.invertBatch(y.map(w=>w.pz));return y.map((w,E)=>w.toAffine(v[E])).map(u.fromAffine)})}multiplyUnsafe(m){let y=u.ZERO;if(m===ql)return y;if(o(m),m===$a)return this;let{endo:v}=e;if(!v)return p.unsafeLadder(this,m);let{k1neg:w,k1:E,k2neg:_,k2:A}=v.splitScalar(m),D=y,M=y,C=this;for(;E>ql||A>ql;)E&$a&&(D=D.add(C)),A&$a&&(M=M.add(C)),C=C.double(),E>>=$a,A>>=$a;return w&&(D=D.negate()),_&&(M=M.negate()),M=new u(t.mul(M.px,v.beta),M.py,M.pz),D.add(M)}multiply(m){o(m);let y=m,v,w,{endo:E}=e;if(E){let{k1neg:_,k1:A,k2neg:D,k2:M}=E.splitScalar(y),{p:C,f:z}=this.wNAF(A),{p:L,f:B}=this.wNAF(M);C=p.constTimeNegate(_,C),L=p.constTimeNegate(D,L),L=new u(t.mul(L.px,E.beta),L.py,L.pz),v=C.add(L),w=z.add(B)}else{let{p:_,f:A}=this.wNAF(y);v=_,w=A}return u.normalizeZ([v,w])[0]}multiplyAndAddUnsafe(m,y,v){let w=u.BASE,E=(A,D)=>D===ql||D===$a||!A.equals(w)?A.multiplyUnsafe(D):A.multiply(D),_=E(this,y).add(E(m,v));return _.is0()?void 0:_}toAffine(m){let{px:y,py:v,pz:w}=this,E=this.is0();m==null&&(m=E?t.ONE:t.inv(w));let _=t.mul(y,m),A=t.mul(v,m),D=t.mul(w,m);if(E)return{x:t.ZERO,y:t.ZERO};if(!t.eql(D,t.ONE))throw new Error("invZ was invalid");return{x:_,y:A}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===$a)return!0;if(y)return y(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===$a?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return yh(this.toRawBytes(m))}}u.BASE=new u(e.Gx,e.Gy,t.ONE),u.ZERO=new u(t.ZERO,t.ONE,t.ZERO);let f=e.nBitLength,p=e7(u,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:a,isWithinCurveOrder:s}}function Nue(r){let e=LC(r);return bh(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Lue(r){let e=Nue(r),{Fp:t,n}=e,i=t.BYTES+1,a=2*t.BYTES+1;function s($){return ql<$&&$<t.ORDER}function o($){return Zr($,n)}function c($){return hC($,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:d,weierstrassEquation:u,isWithinCurveOrder:f}=Uue({...e,toBytes($,S,x){let P=S.toAffine(),k=t.toBytes(P.x),I=gh;return x?I(Uint8Array.from([S.hasEvenY()?2:3]),k):I(Uint8Array.from([4]),k,t.toBytes(P.y))},fromBytes($){let S=$.length,x=$[0],P=$.subarray(1);if(S===i&&(x===2||x===3)){let k=ph(P);if(!s(k))throw new Error("Point is not on curve");let I=u(k),j=t.sqrt(I),q=(j&$a)===$a;return(x&1)===1!==q&&(j=t.neg(j)),{x:k,y:j}}else if(S===a&&x===4){let k=t.fromBytes(P.subarray(0,t.BYTES)),I=t.fromBytes(P.subarray(t.BYTES,2*t.BYTES));return{x:k,y:I}}else throw new Error(`Point of length ${S} was invalid. Expected ${i} compressed bytes or ${a} uncompressed bytes`)}}),p=$=>yh(jd($,e.nByteLength));function h($){let S=n>>$a;return $>S}function m($){return h($)?o(-$):$}let y=($,S,x)=>ph($.slice(S,x));class v{constructor(S,x,P){this.r=S,this.s=x,this.recovery=P,this.assertValidity()}static fromCompact(S){let x=e.nByteLength;return S=Hn("compactSignature",S,x*2),new v(y(S,0,x),y(S,x,2*x))}static fromDER(S){let{r:x,s:P}=uh.toSig(Hn("DER",S));return new v(x,P)}assertValidity(){if(!f(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!f(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(S){return new v(this.r,this.s,S)}recoverPublicKey(S){let{r:x,s:P,recovery:k}=this,I=M(Hn("msgHash",S));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let j=k===2||k===3?x+e.n:x;if(j>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let q=k&1?"03":"02",H=l.fromHex(q+p(j)),J=c(j),V=o(-I*J),Z=o(P*J),F=l.BASE.multiplyAndAddUnsafe(H,V,Z);if(!F)throw new Error("point at infinify");return F.assertValidity(),F}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Xy(this.toDERHex())}toDERHex(){return uh.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Xy(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let w={isValidPrivateKey($){try{return d($),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let $=Qz(e.n);return Bue(e.randomBytes($),e.n)},precompute($=8,S=l.BASE){return S._setWindowSize($),S.multiply(BigInt(3)),S}};function E($,S=!0){return l.fromPrivateKey($).toRawBytes(S)}function _($){let S=Od($),x=typeof $=="string",P=(S||x)&&$.length;return S?P===i||P===a:x?P===2*i||P===2*a:$ instanceof l}function A($,S,x=!0){if(_($))throw new Error("first arg must be private key");if(!_(S))throw new Error("second arg must be public key");return l.fromHex(S).multiply(d($)).toRawBytes(x)}let D=e.bits2int||function($){let S=ph($),x=$.length*8-e.nBitLength;return x>0?S>>BigInt(x):S},M=e.bits2int_modN||function($){return o(D($))},C=MC(e.nBitLength);function z($){if(typeof $!="bigint")throw new Error("bigint expected");if(!(ql<=$&&$<C))throw new Error(`bigint expected < 2^${e.nBitLength}`);return jd($,e.nByteLength)}function L($,S,x=B){if(["recovered","canonical"].some(ie=>ie in x))throw new Error("sign() legacy options not supported");let{hash:P,randomBytes:k}=e,{lowS:I,prehash:j,extraEntropy:q}=x;I==null&&(I=!0),$=Hn("msgHash",$),j&&($=Hn("prehashed msgHash",P($)));let H=M($),J=d(S),V=[z(J),z(H)];if(q!=null){let ie=q===!0?k(t.BYTES):q;V.push(Hn("extraEntropy",ie))}let Z=gh(...V),F=H;function X(ie){let se=D(ie);if(!f(se))return;let Y=c(se),de=l.BASE.multiply(se).toAffine(),pe=o(de.x);if(pe===ql)return;let le=o(Y*o(F+pe*J));if(le===ql)return;let Se=(de.x===pe?0:2)|Number(de.y&$a),he=le;return I&&h(le)&&(he=m(le),Se^=1),new v(pe,he,Se)}return{seed:Z,k2sig:X}}let B={lowS:e.lowS,prehash:!1},W={lowS:e.lowS,prehash:!1};function ee($,S,x=B){let{seed:P,k2sig:k}=L($,S,x),I=e;return Lz(I.hash.outputLen,I.nByteLength,I.hmac)(P,k)}l.BASE._setWindowSize(8);function R($,S,x,P=W){let k=$;if(S=Hn("msgHash",S),x=Hn("publicKey",x),"strict"in P)throw new Error("options.strict was renamed to lowS");let{lowS:I,prehash:j}=P,q,H;try{if(typeof k=="string"||Od(k))try{q=v.fromDER(k)}catch(Y){if(!(Y instanceof uh.Err))throw Y;q=v.fromCompact(k)}else if(typeof k=="object"&&typeof k.r=="bigint"&&typeof k.s=="bigint"){let{r:Y,s:de}=k;q=new v(Y,de)}else throw new Error("PARSE");H=l.fromHex(x)}catch(Y){if(Y.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(I&&q.hasHighS())return!1;j&&(S=e.hash(S));let{r:J,s:V}=q,Z=M(S),F=c(V),X=o(Z*F),ie=o(J*F),se=l.BASE.multiplyAndAddUnsafe(H,X,ie)?.toAffine();return se?o(se.x)===J:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:A,sign:ee,verify:R,ProjectivePoint:l,Signature:v,utils:w}}function que(r){return{hash:r,hmac:(e,...t)=>r7(r,e,Gz(...t)),randomBytes:UC}}function n7(r,e){let t=n=>Lue({...r,...que(n)});return Object.freeze({...t(e),create:t})}function Fue(r){let e=i7,t=BigInt(3),n=BigInt(6),i=BigInt(11),a=BigInt(22),s=BigInt(23),o=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,u=En(d,t,e)*d%e,f=En(u,t,e)*d%e,p=En(f,mC,e)*l%e,h=En(p,i,e)*p%e,m=En(h,a,e)*h%e,y=En(m,o,e)*m%e,v=En(y,c,e)*y%e,w=En(v,o,e)*m%e,E=En(w,t,e)*d%e,_=En(E,s,e)*h%e,A=En(_,n,e)*l%e,D=En(A,mC,e);if(!yC.eql(yC.sqr(D),r))throw new Error("Cannot find square root");return D}function Gue(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function s7(r,...e){if(!Gue(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function yq(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Hue(r,e){s7(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}function Vue(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function o7(r){return typeof r=="string"&&(r=Vue(r)),s7(r),r}function Jue(r){let e=n=>r().update(o7(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Zue(r=32){if(C2&&typeof C2.getRandomValues=="function")return C2.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Yue(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),a=BigInt(4294967295),s=Number(t>>i&a),o=Number(t&a),c=n?4:0,l=n?0:4;r.setUint32(e+c,s,n),r.setUint32(e+l,o,n)}function nfe(r){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let i=Object.keys(n).sort((s,o)=>s.localeCompare(o)),a={};for(let s of i)a[s]=e(n[s]);return a}return n},t=e(r);return JSON.stringify(t)}function xr(r){return sfe(this,arguments,void 0,function*({jwk:e}){let t=e.kty,n;if(t==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(t==="oct")n={k:e.k,kty:e.kty};else if(t==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(t==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${t}`);Bz(n);let i=nfe(n),a=rt.string(i).toUint8Array(),s=yield a7.digest({data:a});return rt.uint8Array(s).toBase64Url()})}function hh(r){return!(!r||typeof r!="object"||!("kty"in r&&"crv"in r&&"x"in r&&"d"in r)||r.kty!=="EC"||typeof r.d!="string"||typeof r.x!="string")}function qC(r){return!(!r||typeof r!="object"||!("kty"in r&&"crv"in r&&"x"in r)||"d"in r||r.kty!=="EC"||typeof r.x!="string")}function Gl(r){return!(!r||typeof r!="object"||!("kty"in r&&"crv"in r&&"x"in r&&"d"in r)||r.kty!=="OKP"||typeof r.d!="string"||typeof r.x!="string")}function zC(r){return!(!r||typeof r!="object"||"d"in r||!("kty"in r&&"crv"in r&&"x"in r)||r.kty!=="OKP"||typeof r.x!="string")}function ofe(r){if(!r||typeof r!="object")return!1;switch(r.kty){case"EC":case"OKP":case"RSA":return"d"in r;case"oct":return"k"in r;default:return!1}}function d7(r,e=!1){return e?{h:Number(r&E2),l:Number(r>>gC&E2)}:{h:Number(r>>gC&E2)|0,l:Number(r&E2)|0}}function ffe(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let i=0;i<r.length;i++){let{h:a,l:s}=d7(r[i],e);[t[i],n[i]]=[a,s]}return[t,n]}function _fe(r,e,t,n){let i=(e>>>0)+(n>>>0);return{h:r+t+(i/2**32|0)|0,l:i|0}}function Ufe(r){let e=LC(r);return bh(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function FC(r){let e=Ufe(r),{Fp:t,n,prehash:i,hash:a,randomBytes:s,nByteLength:o,h:c}=e,l=S2<<BigInt(o*8)-Go,d=t.create,u=e.uvRatio||((x,P)=>{try{return{isValid:!0,value:t.sqrt(x*t.inv(P))}}catch{return{isValid:!1,value:Ac}}}),f=e.adjustScalarBytes||(x=>x),p=e.domain||((x,P,k)=>{if(P.length||k)throw new Error("Contexts/pre-hash are not supported");return x}),h=x=>typeof x=="bigint"&&Ac<x,m=(x,P)=>h(x)&&h(P)&&x<P,y=x=>x===Ac||m(x,l);function v(x,P){if(m(x,P))return x;throw new Error(`Expected valid scalar < ${P}, got ${typeof x} ${x}`)}function w(x){return x===Ac?x:v(x,n)}let E=new Map;function _(x){if(!(x instanceof A))throw new Error("ExtendedPoint expected")}class A{constructor(P,k,I,j){if(this.ex=P,this.ey=k,this.ez=I,this.et=j,!y(P))throw new Error("x required");if(!y(k))throw new Error("y required");if(!y(I))throw new Error("z required");if(!y(j))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(P){if(P instanceof A)throw new Error("extended point not allowed");let{x:k,y:I}=P||{};if(!y(k)||!y(I))throw new Error("invalid affine point");return new A(k,I,Go,d(k*I))}static normalizeZ(P){let k=t.invertBatch(P.map(I=>I.ez));return P.map((I,j)=>I.toAffine(k[j])).map(A.fromAffine)}_setWindowSize(P){this._WINDOW_SIZE=P,E.delete(this)}assertValidity(){let{a:P,d:k}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:I,ey:j,ez:q,et:H}=this,J=d(I*I),V=d(j*j),Z=d(q*q),F=d(Z*Z),X=d(J*P),ie=d(Z*d(X+V)),se=d(F+d(k*d(J*V)));if(ie!==se)throw new Error("bad point: equation left != right (1)");let Y=d(I*j),de=d(q*H);if(Y!==de)throw new Error("bad point: equation left != right (2)")}equals(P){_(P);let{ex:k,ey:I,ez:j}=this,{ex:q,ey:H,ez:J}=P,V=d(k*J),Z=d(q*j),F=d(I*J),X=d(H*j);return V===Z&&F===X}is0(){return this.equals(A.ZERO)}negate(){return new A(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:P}=e,{ex:k,ey:I,ez:j}=this,q=d(k*k),H=d(I*I),J=d(S2*d(j*j)),V=d(P*q),Z=k+I,F=d(d(Z*Z)-q-H),X=V+H,ie=X-J,se=V-H,Y=d(F*ie),de=d(X*se),pe=d(F*se),le=d(ie*X);return new A(Y,de,le,pe)}add(P){_(P);let{a:k,d:I}=e,{ex:j,ey:q,ez:H,et:J}=this,{ex:V,ey:Z,ez:F,et:X}=P;if(k===BigInt(-1)){let Ys=d((q-j)*(Z+V)),We=d((q+j)*(Z-V)),nr=d(We-Ys);if(nr===Ac)return this.double();let Ur=d(H*S2*X),pr=d(J*S2*F),Lt=pr+Ur,T=We+Ys,U=pr-Ur,N=d(Lt*nr),te=d(T*U),ce=d(Lt*U),ge=d(nr*T);return new A(N,te,ge,ce)}let ie=d(j*V),se=d(q*Z),Y=d(J*I*X),de=d(H*F),pe=d((j+q)*(V+Z)-ie-se),le=de-Y,Se=de+Y,he=d(se-k*ie),Te=d(pe*le),Rt=d(Se*he),ti=d(pe*he),Kr=d(le*Se);return new A(Te,Rt,Kr,ti)}subtract(P){return this.add(P.negate())}wNAF(P){return C.wNAFCached(this,E,P,A.normalizeZ)}multiply(P){let{p:k,f:I}=this.wNAF(v(P,n));return A.normalizeZ([k,I])[0]}multiplyUnsafe(P){let k=w(P);return k===Ac?M:this.equals(M)||k===Go?this:this.equals(D)?this.wNAF(k).p:C.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return C.unsafeLadder(this,n).is0()}toAffine(P){let{ex:k,ey:I,ez:j}=this,q=this.is0();P==null&&(P=q?Mfe:t.inv(j));let H=d(k*P),J=d(I*P),V=d(j*P);if(q)return{x:Ac,y:Go};if(V!==Go)throw new Error("invZ was invalid");return{x:H,y:J}}clearCofactor(){let{h:P}=e;return P===Go?this:this.multiplyUnsafe(P)}static fromHex(P,k=!1){let{d:I,a:j}=e,q=t.BYTES;P=Hn("pointHex",P,q);let H=P.slice(),J=P[q-1];H[q-1]=J&-129;let V=Sf(H);V===Ac||(k?v(V,l):v(V,t.ORDER));let Z=d(V*V),F=d(Z-Go),X=d(I*Z-j),{isValid:ie,value:se}=u(F,X);if(!ie)throw new Error("Point.fromHex: invalid y coordinate");let Y=(se&Go)===Go,de=(J&128)!==0;if(!k&&se===Ac&&de)throw new Error("Point.fromHex: x=0 and x_0=1");return de!==Y&&(se=d(-se)),A.fromAffine({x:se,y:V})}static fromPrivateKey(P){return B(P).point}toRawBytes(){let{x:P,y:k}=this.toAffine(),I=Qy(k,t.BYTES);return I[I.length-1]|=P&Go?128:0,I}toHex(){return yh(this.toRawBytes())}}A.BASE=new A(e.Gx,e.Gy,Go,d(e.Gx*e.Gy)),A.ZERO=new A(Ac,Go,Go,Ac);let{BASE:D,ZERO:M}=A,C=e7(A,o*8);function z(x){return Zr(x,n)}function L(x){return z(Sf(x))}function B(x){let P=o;x=Hn("private key",x,P);let k=Hn("hashed private key",a(x),2*P),I=f(k.slice(0,P)),j=k.slice(P,2*P),q=L(I),H=D.multiply(q),J=H.toRawBytes();return{head:I,prefix:j,scalar:q,point:H,pointBytes:J}}function W(x){return B(x).pointBytes}function ee(x=new Uint8Array,...P){let k=gh(...P);return L(a(p(k,Hn("context",x),!!i)))}function R(x,P,k={}){x=Hn("message",x),i&&(x=i(x));let{prefix:I,scalar:j,pointBytes:q}=B(P),H=ee(k.context,I,x),J=D.multiply(H).toRawBytes(),V=ee(k.context,J,q,x),Z=z(H+V*j);w(Z);let F=gh(J,Qy(Z,t.BYTES));return Hn("result",F,o*2)}let $=Kfe;function S(x,P,k,I=$){let{context:j,zip215:q}=I,H=t.BYTES;x=Hn("signature",x,2*H),P=Hn("message",P),i&&(P=i(P));let J=Sf(x.slice(H,2*H)),V,Z,F;try{V=A.fromHex(k,q),Z=A.fromHex(x.slice(0,H),q),F=D.multiplyUnsafe(J)}catch{return!1}if(!q&&V.isSmallOrder())return!1;let X=ee(j,Z.toRawBytes(),V.toRawBytes(),P);return Z.add(V.multiplyUnsafe(X)).subtract(F).clearCofactor().equals(A.ZERO)}return D._setWindowSize(8),{CURVE:e,getPublicKey:W,sign:R,verify:S,ExtendedPoint:A,utils:{getExtendedPublicKey:B,randomPrivateKey:()=>s(t.BYTES),precompute(x=8,P=A.BASE){return P._setWindowSize(x),P.multiply(BigInt(3)),P}}}}function Nfe(r){return bh(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function Lfe(r){let e=Nfe(r),{P:t}=e,n=E=>Zr(E,t),i=e.montgomeryBits,a=Math.ceil(i/8),s=e.nByteLength,o=e.adjustScalarBytes||(E=>E),c=e.powPminus2||(E=>Zz(E,t-BigInt(2),t));function l(E,_,A){let D=n(E*(_-A));return _=n(_-D),A=n(A+D),[_,A]}function d(E){if(typeof E=="bigint"&&D0<=E&&E<t)return E;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let u=(e.a-BigInt(2))/BigInt(4);function f(E,_){let A=d(E),D=d(_),M=A,C=sC,z=D0,L=A,B=sC,W=D0,ee;for(let $=BigInt(i-1);$>=D0;$--){let S=D>>$&sC;W^=S,ee=l(W,C,L),C=ee[0],L=ee[1],ee=l(W,z,B),z=ee[0],B=ee[1],W=S;let x=C+z,P=n(x*x),k=C-z,I=n(k*k),j=P-I,q=L+B,H=L-B,J=n(H*x),V=n(q*k),Z=J+V,F=J-V;L=n(Z*Z),B=n(M*n(F*F)),C=n(P*I),z=n(j*(P+n(u*j)))}ee=l(W,C,L),C=ee[0],L=ee[1],ee=l(W,z,B),z=ee[0],B=ee[1];let R=c(z);return n(C*R)}function p(E){return Qy(n(E),a)}function h(E){let _=Hn("u coordinate",E,a);return s===32&&(_[31]&=127),Sf(_)}function m(E){let _=Hn("scalar",E),A=_.length;if(A!==a&&A!==s)throw new Error(`Expected ${a} or ${s} bytes, got ${A}`);return Sf(o(_))}function y(E,_){let A=h(_),D=m(E),M=f(A,D);if(M===D0)throw new Error("Invalid private or public key received");return p(M)}let v=p(e.Gu);function w(E){return y(E,v)}return{scalarMult:y,scalarMultBase:w,getSharedSecret:(E,_)=>y(E,_),getPublicKey:E=>w(E),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:v}}function u7(r){let e=tb,t=r*r%e*r%e,n=En(t,wC,e)*t%e,i=En(n,qfe,e)*r%e,a=En(i,zfe,e)*i%e,s=En(a,bq,e)*a%e,o=En(s,Ffe,e)*s%e,c=En(o,Gfe,e)*o%e,l=En(c,Pq,e)*c%e,d=En(l,Pq,e)*c%e,u=En(d,bq,e)*a%e;return{pow_p_5_8:En(u,wC,e)*r%e,b2:t}}function f7(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Hfe(r,e){let t=tb,n=Zr(e*e*e,t),i=Zr(n*n*e,t),a=u7(r*i).pow_p_5_8,s=Zr(r*n*a,t),o=Zr(e*s*s,t),c=s,l=Zr(s*vq,t),d=o===r,u=o===Zr(-r,t),f=o===Zr(-r*vq,t);return d&&(s=c),(u||f)&&(s=l),Tue(s,t)&&(s=Zr(-s,t)),{isValid:d||u,value:s}}function p7(r,e,t){if(e.length>255)throw new Error("Context is too big");return Gz(Fz("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}function Vfe(r){let{y:e}=oh.ExtendedPoint.fromHex(r),t=BigInt(1);return Ma.toBytes(Ma.create((t+e)*Ma.inv(t-e)))}function Wfe(r){let e=rb.hash(r.subarray(0,32));return rb.adjustScalarBytes(e).subarray(0,32)}function ipe(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;return e==="string"||e==="number"||e==="bigint"||e==="symbol"?e:e==="function"?"Function":Array.isArray(r)?"Array":r instanceof Uint8Array?"Uint8Array":r.constructor===Object?"Object":spe(r)||"Object"}function spe(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(npe.includes(e))return e}function eE(r){return cb&&globalThis.Buffer.isBuffer(r)}function m7(r){return r instanceof Uint8Array?eE(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}function y7(r,e){if(eE(r)&&eE(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 xq(r){let e=[],t=0;for(let n=0;n<r.length;n++){let i=r.charCodeAt(n);i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(i>=55296&&i<=57343&&(i=65533),e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e}function ig(r,e,t){if(r.length-e<t)throw new Error(`${Sn} not enough data for type`)}function Ph(r,e,t){ig(r,e,1);let n=r[e];if(t.strict===!0&&n<rs[0])throw new Error(`${Sn} integer encoded in more bytes than necessary (strict decode)`);return n}function xh(r,e,t){ig(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<rs[1])throw new Error(`${Sn} integer encoded in more bytes than necessary (strict decode)`);return n}function Eh(r,e,t){ig(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<rs[2])throw new Error(`${Sn} integer encoded in more bytes than necessary (strict decode)`);return n}function Sh(r,e,t){ig(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],a=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&a<rs[3])throw new Error(`${Sn} integer encoded in more bytes than necessary (strict decode)`);if(a<=Number.MAX_SAFE_INTEGER)return Number(a);if(t.allowBigInt===!0)return a;throw new Error(`${Sn} integers outside of the safe integer range are not supported`)}function mpe(r,e,t,n){return new Qe(xe.uint,Ph(r,e+1,n),2)}function ype(r,e,t,n){return new Qe(xe.uint,xh(r,e+1,n),3)}function gpe(r,e,t,n){return new Qe(xe.uint,Eh(r,e+1,n),5)}function wpe(r,e,t,n){return new Qe(xe.uint,Sh(r,e+1,n),9)}function kh(r,e){return Ua(r,0,e.value)}function Ua(r,e,t){if(t<rs[0]){let n=Number(t);r.push([e|n])}else if(t<rs[1]){let n=Number(t);r.push([e|24,n])}else if(t<rs[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<rs[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<rs[4]){let i=[e|27,0,0,0,0,0,0,0],a=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=a&255,a=a>>8,i[7]=a&255,a=a>>8,i[6]=a&255,a=a>>8,i[5]=a&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${Sn} encountered BigInt larger than allowable range`)}}function vpe(r,e,t,n){return new Qe(xe.negint,-1-Ph(r,e+1,n),2)}function bpe(r,e,t,n){return new Qe(xe.negint,-1-xh(r,e+1,n),3)}function Ppe(r,e,t,n){return new Qe(xe.negint,-1-Eh(r,e+1,n),5)}function xpe(r,e,t,n){let i=Sh(r,e+1,n);if(typeof i!="bigint"){let a=-1-i;if(a>=Number.MIN_SAFE_INTEGER)return new Qe(xe.negint,a,9)}if(n.allowBigInt!==!0)throw new Error(`${Sn} integers outside of the safe integer range are not supported`);return new Qe(xe.negint,GC-BigInt(i),9)}function HC(r,e){let t=e.value,n=typeof t=="bigint"?t*GC-v7:t*-1-1;Ua(r,e.type.majorEncoded,n)}function lb(r,e,t,n){ig(r,e,t+n);let i=r.slice(e+t,e+t+n);return new Qe(xe.bytes,i,t+n)}function Epe(r,e,t,n){return lb(r,e,1,t)}function Spe(r,e,t,n){return lb(r,e,2,Ph(r,e+1,n))}function kpe(r,e,t,n){return lb(r,e,3,xh(r,e+1,n))}function _pe(r,e,t,n){return lb(r,e,5,Eh(r,e+1,n))}function Ape(r,e,t,n){let i=Sh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Sn} 64-bit integer bytes lengths not supported`);return lb(r,e,9,i)}function tE(r){return r.encodedBytes===void 0&&(r.encodedBytes=xe.equals(r.type,xe.string)?dpe(r.value):r.value),r.encodedBytes}function pE(r,e){let t=tE(e);Ua(r,e.type.majorEncoded,t.length),r.push(t)}function Tpe(r,e){return r.length<e.length?-1:r.length>e.length?1:y7(r,e)}function Dpe(r,e,t){if(t-e<Ipe){let n="";for(let i=e;i<t;i++){let a=r[i];if(a&128)return Eq.decode(r.subarray(e,t));n+=String.fromCharCode(a)}return n}return Eq.decode(r.subarray(e,t))}function ub(r,e,t,n,i){let a=t+n;ig(r,e,a);let s=new Qe(xe.string,Dpe(r,e+t,e+a),a);return i.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+a)),s}function Rpe(r,e,t,n){return ub(r,e,1,t,n)}function Cpe(r,e,t,n){return ub(r,e,2,Ph(r,e+1,n),n)}function $pe(r,e,t,n){return ub(r,e,3,xh(r,e+1,n),n)}function Bpe(r,e,t,n){return ub(r,e,5,Eh(r,e+1,n),n)}function Ope(r,e,t,n){let i=Sh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Sn} 64-bit integer string lengths not supported`);return ub(r,e,9,i,n)}function sg(r,e,t,n){return new Qe(xe.array,n,t)}function Mpe(r,e,t,n){return sg(r,e,1,t)}function Kpe(r,e,t,n){return sg(r,e,2,Ph(r,e+1,n))}function Upe(r,e,t,n){return sg(r,e,3,xh(r,e+1,n))}function Npe(r,e,t,n){return sg(r,e,5,Eh(r,e+1,n))}function Lpe(r,e,t,n){let i=Sh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Sn} 64-bit integer array lengths not supported`);return sg(r,e,9,i)}function qpe(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Sn} indefinite length items not allowed`);return sg(r,e,1,1/0)}function VC(r,e){Ua(r,xe.array.majorEncoded,e.value)}function og(r,e,t,n){return new Qe(xe.map,n,t)}function zpe(r,e,t,n){return og(r,e,1,t)}function Fpe(r,e,t,n){return og(r,e,2,Ph(r,e+1,n))}function Gpe(r,e,t,n){return og(r,e,3,xh(r,e+1,n))}function Hpe(r,e,t,n){return og(r,e,5,Eh(r,e+1,n))}function Vpe(r,e,t,n){let i=Sh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Sn} 64-bit integer map lengths not supported`);return og(r,e,9,i)}function Wpe(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Sn} indefinite length items not allowed`);return og(r,e,1,1/0)}function WC(r,e){Ua(r,xe.map.majorEncoded,e.value)}function Jpe(r,e,t,n){return new Qe(xe.tag,t,1)}function Zpe(r,e,t,n){return new Qe(xe.tag,Ph(r,e+1,n),2)}function Ype(r,e,t,n){return new Qe(xe.tag,xh(r,e+1,n),3)}function Xpe(r,e,t,n){return new Qe(xe.tag,Eh(r,e+1,n),5)}function Qpe(r,e,t,n){return new Qe(xe.tag,Sh(r,e+1,n),9)}function JC(r,e){Ua(r,xe.tag.majorEncoded,e.value)}function ehe(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Sn} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Qe(xe.null,null,1):new Qe(xe.undefined,void 0,1)}function the(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Sn} indefinite length items not allowed`);return new Qe(xe.break,void 0,1)}function ZC(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Sn} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Sn} Infinity values are not supported`)}return new Qe(xe.float,r,e)}function rhe(r,e,t,n){return ZC(XC(r,e+1),3,n)}function nhe(r,e,t,n){return ZC(QC(r,e+1),5,n)}function ihe(r,e,t,n){return ZC(A7(r,e+1),9,n)}function YC(r,e,t){let n=e.value;if(n===!1)r.push([xe.float.majorEncoded|b7]);else if(n===!0)r.push([xe.float.majorEncoded|P7]);else if(n===null)r.push([xe.float.majorEncoded|x7]);else if(n===void 0)r.push([xe.float.majorEncoded|E7]);else{let i,a=!1;(!t||t.float64!==!0)&&(k7(n),i=XC(Tc,1),n===i||Number.isNaN(n)?(Tc[0]=249,r.push(Tc.slice(0,3)),a=!0):(_7(n),i=QC(Tc,1),n===i&&(Tc[0]=250,r.push(Tc.slice(0,5)),a=!0))),a||(she(n),i=A7(Tc,1),Tc[0]=251,r.push(Tc.slice(0,9)))}}function k7(r){if(r===1/0)Ra.setUint16(0,31744,!1);else if(r===-1/0)Ra.setUint16(0,64512,!1);else if(Number.isNaN(r))Ra.setUint16(0,32256,!1);else{Ra.setFloat32(0,r);let e=Ra.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Ra.setUint16(0,31744,!1);else if(t===0)Ra.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?Ra.setUint16(0,0):i<-14?Ra.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Ra.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function XC(r,e){if(r.length-e<2)throw new Error(`${Sn} 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,i=t&1023,a;return n===0?a=i*2**-24:n!==31?a=(i+1024)*2**(n-25):a=i===0?1/0:NaN,t&32768?-a:a}function _7(r){Ra.setFloat32(0,r,!1)}function QC(r,e){if(r.length-e<4)throw new Error(`${Sn} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function she(r){Ra.setFloat64(0,r,!1)}function A7(r,e){if(r.length-e<8)throw new Error(`${Sn} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}function fr(r,e,t){throw new Error(`${Sn} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function hE(r){return()=>{throw new Error(`${Sn} ${r}`)}}function ohe(r){switch(r.type){case xe.false:return Nl([244]);case xe.true:return Nl([245]);case xe.null:return Nl([246]);case xe.bytes:return r.value.length?void 0:Nl([64]);case xe.string:return r.value===""?Nl([96]):void 0;case xe.array:return r.value===0?Nl([128]):void 0;case xe.map:return r.value===0?Nl([160]):void 0;case xe.uint:return r.value<24?Nl([Number(r.value)]):void 0;case xe.negint:if(r.value>=-24)return Nl([31-Number(r.value)])}}function che(){let r=[];return r[xe.uint.major]=kh,r[xe.negint.major]=HC,r[xe.bytes.major]=pE,r[xe.string.major]=jpe,r[xe.array.major]=VC,r[xe.map.major]=WC,r[xe.tag.major]=JC,r[xe.float.major]=YC,r}function $2(r,e={},t){let n=ipe(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||_f[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let a=_f[n];if(!a)throw new Error(`${w7} unsupported type: ${n}`);return a(r,n,e,t)}function uhe(r,e){e.mapSorter&&r.sort(e.mapSorter)}function fhe(r,e){if(r[0]instanceof Qe&&e[0]instanceof Qe){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=kq(t.value)),n._keyBytes||(n._keyBytes=kq(n.value)),y7(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function kq(r){return phe(r,dhe,ahe)}function I7(r,e,t,n){if(Array.isArray(e))for(let i of e)I7(r,i,t,n);else t[e.type.major](r,e,n)}function phe(r,e,t,n){let i=n instanceof Uint8Array,a=i?new hpe(n):lhe,s=$2(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let o=t.quickEncodeToken(s);if(o)return i?(a.push(o),a.toBytes()):o;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(i||(a=new g7(l)),c(a,s,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return i?a.toBytes():m7(a.chunks[0])}}return a.reset(),I7(a,s,e,t),a.toBytes(!0)}function Ws(r){if(typeof r=="string"&&r.length!==0)return r.split("#").pop()}function hhe({didDocument:r,id:e,type:t}){return r?.service?.filter(n=>!(e&&n.id!==e||t&&n.type!==t))??[]}async function mhe({didDocument:r,publicKeyJwk:e,publicKeyMultibase:t}){let n=mE({didDocument:r});for(let i of n)if(e&&i.publicKeyJwk){if(await xr({jwk:e})===await xr({jwk:i.publicKeyJwk}))return i}else if(t&&i.publicKeyMultibase&&t===i.publicKeyMultibase)return i;return null}function mE({didDocument:r}){if(!r)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...r.verificationMethod?.filter(rE)??[]),Object.keys(lE).forEach(t=>{e.push(...r[t]?.filter(rE)??[])}),e}function D7({didDocument:r}){let e=mE({didDocument:r}).map(t=>t.type);return[...new Set(e)]}function R7({didDocument:r,methodId:e}){let t=[];return Object.keys(lE).forEach(n=>{if(Array.isArray(r[n])){let i=r[n],a=Ws(e);i.some(s=>{let o=Ws(s)===a,c=rE(s)&&Ws(s.id)===a;return o||c})&&t.push(n)}}),t}function C7(r){return!r||typeof r!="object"||r===null?!1:"id"in r&&"type"in r&&"serviceEndpoint"in r}function yhe(r){return!(!C7(r)||r.type!=="DecentralizedWebNode")}function rE(r){return!(!r||typeof r!="object"||r===null||!("id"in r&&"type"in r&&"controller"in r)||typeof r.id!="string"||typeof r.type!="string"||typeof r.controller!="string")}function _h(r){return!(!r||typeof r!="object"||r===null)&&"uri"in r&&"document"in r&&"metadata"in r&&(!("keyManager"in r)||r.keyManager===void 0)}function $7({keyBytes:r,multicodecCode:e,multicodecName:t}){let n=Ka.addPrefix({code:e,data:r,name:t}),i=rt.uint8Array(n).toBase58Btc();return rt.base58Btc(i).toMultibase()}function B7({multibaseKeyId:r}){try{let e=rt.multibase(r).toBase58Btc(),t=rt.base58Btc(e).toUint8Array(),{code:n,data:i,name:a}=Ka.removePrefix({prefixedData:t});return{keyBytes:i,multicodecCode:n,multicodecName:a}}catch{throw new Xe("invalidDid",`Invalid multibase identifier: ${r}`)}}function pb(r){let e=r<0?1:0;return r=Math.abs(Number(r||1)),Math.floor(Math.log10(r))+1+e}function N7(r){return ArrayBuffer.isView(r)?"arraybufferview":Array.isArray(r)?"array":r instanceof Number?"number":r instanceof Boolean?"boolean":r instanceof Set?"set":r instanceof Map?"map":r instanceof String?"string":r instanceof ArrayBuffer?"arraybuffer":typeof r}function gr(r,e,t){let n=[],i=null;return gr._encode(n,r),i=whe(n),gr.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,t),e):i}function z7(r,e,t){let n=0,i=1;for(let a=e;a<t;a++){let s=r[a];if(s<58&&s>=48){n=n*10+(s-48);continue}if(!(a===e&&s===43)){if(a===e&&s===45){i=-1;continue}if(s===46)break;throw new Error("not a number: buffer["+a+"] = "+s)}}return n*i}function gt(r,e,t,n){return r==null||r.length===0?null:(typeof e!="number"&&n==null&&(n=e,e=void 0),typeof t!="number"&&n==null&&(n=t,t=void 0),gt.position=0,gt.encoding=n||null,gt.data=ArrayBuffer.isView(r)?new Uint8Array(r.slice(e,t)):Hl(r),gt.bytes=gt.data.length,gt.next())}function The(r){let e=2;for(let t of r)e+=gE(t);return e}function Ihe(r){let e=2;for(let[t,n]of r){let i=Hl(t).byteLength;e+=pb(i)+1+i,e+=gE(n)}return e}function Dhe(r){let e=2,t=Object.keys(r);for(let n=0;n<t.length;n++){let i=Hl(t[n]).byteLength;e+=pb(i)+1+i,e+=gE(r[t[n]])}return e}function Rhe(r){let e=Hl(r).byteLength;return pb(e)+1+e}function Che(r){let e=r.byteLength-r.byteOffset;return pb(e)+1+e}function gE(r){if(r==null)return 0;let e=N7(r);switch(e){case"arraybufferview":return Che(r);case"string":return Rhe(r);case"array":case"set":return The(r);case"number":return 1+pb(Math.floor(r))+1;case"bigint":return 1+r.toString().length+1;case"object":return Dhe(r);case"map":return Ihe(r);default:throw new TypeError(`Unsupported value of type "${e}"`)}}function H7(r){if(Bd.isFormat(r))return Bd.size;if(kf.isFormat(r))return kf.size;throw Error(`Invalid ip address: ${r}`)}function jhe(r){return H7(r)===Bd.size?1:2}function Mhe(r,e,t){t=~~t;let n=H7(r);return typeof e=="function"&&(e=e(t+n)),n===Bd.size?Bd.encode(r,e,t):kf.encode(r,e,t)}function Khe(r,e,t){if(e=~~e,t=t||r.length-e,t===Bd.size)return Bd.decode(r,e,t);if(t===kf.size)return kf.decode(r,e,t);throw Error(`Invalid buffer size needs to be ${Bd.size} for v4 or ${kf.size} for v6.`)}function wE(r){switch(r){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+r}function nb(r){switch(r.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return r.toUpperCase().startsWith("UNKNOWN_")?parseInt(r.slice(8)):0}function Uhe(r){switch(r){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+r}function Nhe(r){switch(r){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+r}function V7(r){switch(r){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+r}function W7(r){switch(r.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}function Lhe(r){switch(r){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return r<0?null:`OPTION_${r}`}function Kq(r){if(typeof r=="number")return r;if(!r)return-1;switch(r.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=r.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}function J7(r){let e=0,t=r.length;for(let n=0;n<t;n+=1){let i=r.charCodeAt(n);if(i<=127)e+=1;else if(i<=2047)e+=2;else if((i&63488)!==55296)e+=3;else{let a=n+1;a===t||i>=56320||(r.charCodeAt(a)&64512)!==56320?e+=3:(n=a,e+=4)}}return e}function ib(r,e,t){let n=r.length;t==null&&(t=0),e===void 0&&(e=new Uint8Array(J7(r)+t));let i=t;for(let a=0;a<n;a+=1){let s=r.charCodeAt(a);if(s<=127)e[i++]=s;else if(s<=2047)e[i++]=192|(s&1984)>>6,e[i++]=128|s&63;else if((s&63488)!==55296)e[i++]=224|(s&61440)>>12,e[i++]=128|(s&4032)>>6,e[i++]=128|s&63;else{let o=a+1;if(o===n||s>=56320)e[i++]=239,e[i++]=191,e[i++]=189;else{let c=r.charCodeAt(o);(c&64512)!==56320?(e[i++]=239,e[i++]=191,e[i++]=189):(a=o,s=65536|(s&1023)<<10|c&1023,e[i++]=240|(s&1835008)>>18,e[i++]=128|(s&258048)>>12,e[i++]=128|(s&4032)>>6,e[i++]=128|s&63)}}}return ib.bytes=i-t,e}function hb(r,e,t){let n="";e==null&&(e=0),t==null&&(t=r.length);for(let i=e;i<t;){let a=r[i++],s;if(a<=128)s=a;else if(a>191&&a<224)s=(a&31)<<6|r[i++]&63;else if(a>239&&a<365){s=((a&7)<<18|(r[i++]&63)<<12|(r[i++]&63)<<6|r[i++]&63)-65536;let o=55296|s>>10&1023;n+=String.fromCharCode(o),s=56320|s&1023}else s=(a&15)<<12|(r[i++]&63)<<6|r[i++]&63;n+=String.fromCharCode(s)}return hb.bytes=t-e,n}function Af(r){return typeof r=="string"?J7(r):r.byteLength}function n6(r){return r instanceof Uint8Array?r:Array.isArray(r)?new Uint8Array(r):ib(r)}function i6(r,e,t){if(typeof e!="string")throw new Error("unknown input type");return ib(e,r,t),ib.bytes}function qhe(r,e,t){let n="";for(let i=e;i<t;){let a=r[i++];n+=Z7[a]}return n}function Uq(r){return r.length>>>1}function zhe(r,e,t,n){let i=0;for(;t<n;){let a=e.substr(i,2),s=K0[a];if(s===void 0)return;r[t++]=s,i+=2}return r}function Zo(r,e,t,n,i){return t<0&&(n-=t,t=0),n<0&&(n=0),i<0?new Uint8Array(0):t>=e.length||n>=i?0:Vhe(r,e,t,n,i)}function Vhe(r,e,t,n,i){i-n>e.length-t&&(i=n+e.length-t);let a=i-n,s=r.length-n;return a>s&&(a=s),(n!==0||i<r.length)&&(r=new Uint8Array(r.buffer,r.byteOffset+n,a)),e.set(r,t),a}function Fr({bytes:r=0,encode:e,decode:t,encodingLength:n}){return e.bytes=r,t.bytes=r,{encode:e,decode:t,encodingLength:n||(()=>r)}}function bC(r){if(r===1)return 20;if(r===2)return 32;throw new Error(`Invalid hashType=${r}, supported=1,2`)}function aC(r){switch(r.toUpperCase()){case"A":return X7;case"PTR":return Jy;case"CNAME":return Jy;case"DNAME":return Jy;case"TXT":return M2;case"NULL":return K2;case"AAAA":return q2;case"SRV":return N2;case"HINFO":return U2;case"CAA":return xf;case"NS":return O2;case"SOA":return j2;case"MX":return L2;case"OPT":return Ef;case"DNSKEY":return $d;case"RRSIG":return U0;case"RP":return N0;case"NSEC":return L0;case"NSEC3":return q0;case"SSHFP":return Hy;case"DS":return z0}return B2}function nE(r,e){if(r.questions)throw new Error("Only one .question object expected instead of a .questions array!");let t=Object.assign({type:e},r);return t.question&&(t.questions=[t.question],delete t.question),t}function Q7(r){let e=oE(r),t=new Uint8Array(2+e.byteLength);return nt(t,e.byteLength),Zo(e,t,2,0,e.length),Q7.bytes=t.byteLength,t}function eF(r){let e=Mt(r,0);if(r.byteLength<e+2)return null;let t=PC(r.slice(2));return eF.bytes=PC.bytes,t}function Vy(r,e){let t=0;for(let n=0;n<r.length;n++)t+=e.encodingLength(r[n]);return t}function F0(r,e,t,n){for(let i=0;i<r.length;i++)e.encode(r[i],t,n),n+=e.encode.bytes;return n}function k2(r,e,t,n){for(let i=0;i<r.length;i++)r[i]=e.decode(t,n),n+=e.decode.bytes;return n}function tF(r,e){let t=rt.uint8Array(r).toBase32Z();return new URL(t,e).href}async function rF(r,e,t){if(t)return fetch(r,e);try{return await Oz(r,e,{description:"Pkarr gateway URL"})}catch(n){throw n instanceof R2?new Xe("invalidGatewayUri",n.message):n}}async function Qhe({gatewayUri:r,publicKeyBytes:e,allowPrivateGatewayUri:t=!1}){let n=rt.uint8Array(e).toBase32Z(),i=tF(e,r),a;try{if(a=await rF(i,{method:"GET",signal:AbortSignal.timeout(3e4)},t),!a.ok)throw new Xe("notFound",`Pkarr record not found for: ${n}`)}catch(o){throw o instanceof Xe?o:new Xe("internalError",`Failed to fetch Pkarr record: ${o.message}`)}let s=await a.arrayBuffer();if(!s)throw new Xe("notFound",`Pkarr record not found for: ${n}`);if(s.byteLength<72)throw new Xe("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${s.byteLength}`);if(s.byteLength>1072)throw new Xe("invalidDidDocumentLength",`Pkarr response exceeds 1000 byte limit: ${s.byteLength}`);return{k:e,seq:Number(new DataView(s).getBigUint64(64)),sig:new Uint8Array(s,0,64),v:new Uint8Array(s,72)}}async function eme({gatewayUri:r,bep44Message:e,allowPrivateGatewayUri:t=!1}){let n=rt.uint8Array(e.k).toBase32Z(),i=tF(e.k,r),a=new Uint8Array(e.v.length+72);a.set(e.sig,0),new DataView(a.buffer).setBigUint64(e.sig.length,BigInt(e.seq)),a.set(e.v,e.sig.length+8);let s;try{s=await rF(i,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:a,signal:AbortSignal.timeout(3e4)},t)}catch(o){throw o instanceof Xe?o:new Xe("internalError",`Failed to put Pkarr record for identifier ${n}: ${o.message}`)}return s.ok}async function tme({dnsPacket:r,publicKeyBytes:e,signer:t}){let n=Math.ceil(Date.now()/1e3),i=oE(r),a=G7.encode({seq:n,v:i}).subarray(1,-1);if(a.length>1e3)throw new Xe("invalidDidDocumentLength",`DNS packet exceeds the 1000 byte maximum size: ${a.length} bytes`);let s=await t.sign({data:new Uint8Array(a)});return{k:e,seq:n,sig:s,v:i}}async function rme({bep44Message:r}){let e=await ts.bytesToPublicKey({publicKeyBytes:r.k}),t=G7.encode({seq:r.seq,v:r.v}).subarray(1,-1);if(!await ts.verify({key:e,signature:r.sig,data:new Uint8Array(t)}))throw new Xe("invalidSignature","Invalid signature for DHT BEP44 message");return PC(r.v)}async function iF({didUri:r}){let e=s6({didUri:r});return await ts.bytesToPublicKey({publicKeyBytes:e})}function s6({didUri:r}){let e=Vn.parse(r);if(!e)throw new Xe("invalidDid",`Invalid DID URI: ${r}`);if(e.method!==nF)throw new Xe("methodNotSupported",`Method not supported: ${e.method}`);let t;try{t=rt.base32Z(e.id).toUint8Array()}catch{throw new Xe("invalidPublicKey","Failed to decode method-specific identifier")}if(t.length!==32)throw new Xe("invalidPublicKeyLength",`Invalid public key length: ${t.length}`);return t}async function nme({identityKey:r}){let e=await ts.publicKeyToBytes({publicKey:r}),t=rt.uint8Array(e).toBase32Z();return`did:${nF}:${t}`}function o6(r){let e={Ed25519:ts,"P-256":{publicKeyToBytes:async({publicKey:t})=>{let n=await bs.publicKeyToBytes({publicKey:t});return await bs.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:bs.bytesToPublicKey,privateKeyToBytes:bs.privateKeyToBytes,bytesToPrivateKey:bs.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:t})=>{let n=await es.publicKeyToBytes({publicKey:t});return await es.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:es.bytesToPublicKey,privateKeyToBytes:es.privateKeyToBytes,bytesToPrivateKey:es.bytesToPrivateKey},X25519:Ly}[r];if(!e)throw new Xe("invalidPublicKeyType",`Unsupported curve: ${r}`);return e}async function sF({newDid:r,previousDidProof:e}){let t=await iF({didUri:e.previousDid}),n=s6({didUri:r}),i=rt.base64Url(e.signature).toUint8Array();if(!await ts.verify({key:t,data:n,signature:i}))throw new Xe("invalidPreviousDidProof","The previous DID proof is invalid.")}function sb(r){if(typeof r=="string")return r;if(r instanceof Uint8Array)return rt.uint8Array(r).toString();if(Array.isArray(r))return r.map(e=>sb(e)).join("");throw new Xe("internalError","Pkarr returned DNS TXT record with invalid data type")}function G0(r){return sb(r).split(z2).reduce((e,t)=>{let[n,i]=t.split("=");return e[n]=i,e},{})}function cF(r){if(r.length<=255)return r;let e=[];for(let t=0;t<r.length;t+=255)e.push(r.slice(t,t+255));return e}async function sme({didUri:r,dnsPacket:e}){let t={id:r},n={published:!0},i=new Map;for(let a of e?.answers??[]){if(a.type!=="TXT")continue;let s=a.name.split(".")[0].substring(1);switch(!0){case s.startsWith("aka"):{let o=sb(a.data);t.alsoKnownAs=o.split(Vs);break}case s.startsWith("cnt"):{let o=sb(a.data);t.controller=o.includes(Vs)?o.split(Vs):o;break}case s.startsWith("k"):{let{id:o,t:c,k:l,c:d,a:u}=G0(a.data),f=rt.base64Url(l).toUint8Array(),p=t6[Number(c)],h=await o6(p).bytesToPublicKey({publicKeyBytes:f});h.alg=u||aF[Number(c)];let m=s==="k0"?"0":o===void 0?await xr({jwk:h}):o;t.verificationMethod??=[];let y=`${r}#${m}`;t.verificationMethod.push({id:y,type:"JsonWebKey",controller:d??r,publicKeyJwk:h}),i.set(s,y);break}case s.startsWith("s"):{let{id:o,t:c,se:l,...d}=G0(a.data),u=l.includes(Vs)?l.split(Vs):[l],f=Object.fromEntries(Object.entries(d).map(([p,h])=>[p,h.includes(Vs)?h.split(Vs):h]));t.service??=[],t.service.push({...f,id:`${r}#${o}`,type:c,serviceEndpoint:u});break}case s.startsWith("typ"):{let{id:o}=G0(a.data);n.types=o.split(Vs).map(c=>Number(c));break}case s.startsWith("did"):{let o=p=>p.split(Vs).map(h=>i.get(h)).filter(h=>typeof h=="string"),{auth:c,asm:l,del:d,inv:u,agm:f}=G0(a.data);c&&(t.authentication=o(c)),l&&(t.assertionMethod=o(l)),d&&(t.capabilityDelegation=o(d)),u&&(t.capabilityInvocation=o(u)),f&&(t.keyAgreement=o(f));break}}}return{didDocument:t,didDocumentMetadata:n,didResolutionMetadata:{}}}async function ome({didDocument:r,didMetadata:e,authoritativeGatewayUris:t,previousDidProof:n}){let i=[],a=[],s=new Map,o=[],c=[];if(n!==void 0){let{signature:d,previousDid:u}=n;await sF({newDid:r.id,previousDidProof:n}),i.push({type:"TXT",name:"_prv._did.",ttl:wf,data:`id=${u};s=${d}`})}if(r.alsoKnownAs&&i.push({type:"TXT",name:"_aka._did.",ttl:wf,data:r.alsoKnownAs.join(Vs)}),r.controller){let d=Array.isArray(r.controller)?r.controller.join(Vs):r.controller;i.push({type:"TXT",name:"_cnt._did.",ttl:wf,data:d})}for(let[d,u]of r.verificationMethod?.entries()??[]){let f=`k${d}`;c.push(f);let p=u.id.split("#").pop();s.set(p,f);let h=u.publicKeyJwk;if(!(h?.crv&&h.crv in oF))throw new Xe("invalidPublicKeyType",`Verification method '${u.id}' contains an unsupported key type: ${h?.crv??"undefined"}`);let m=t6[h.crv],y=await o6(h.crv).publicKeyToBytes({publicKey:h}),v=rt.uint8Array(y).toBase64Url(),w=[`t=${m}`,`k=${v}`];p!=="0"&&await xr({jwk:h})!==p&&w.unshift(`id=${p}`),h.alg!==aF[m]&&w.push(`a=${h.alg}`),u.controller!==r.id&&w.push(`c=${u.controller}`),i.push({type:"TXT",name:`_${f}._did.`,ttl:wf,data:w.join(z2)})}r.service?.forEach((d,u)=>{let f=`s${u}`;o.push(f);let{id:p,type:h,serviceEndpoint:m,...y}=d;p=Ws(p),m=Array.isArray(m)?m.join(","):m;let v=Object.entries({id:p,t:h,se:m,...y}).map(([E,_])=>`${E}=${_}`).join(z2),w=cF(v);i.push({type:"TXT",name:`_${f}._did.`,ttl:wf,data:w})});let l=[`v=${ime}`];if(c.length&&l.push(`vm=${c.join(Vs)}`),Object.keys(lE).forEach(d=>{let u=r[d]?.map(f=>s.get(f.split("#").pop()));if(u){let f=M7[d];l.push(`${f}=${u.join(Vs)}`)}}),o.length&&l.push(`svc=${o.join(Vs)}`),e.types?.length){let d=e.types.map(u=>typeof u=="string"?j7[u]:u);i.push({type:"TXT",name:"_typ._did.",ttl:wf,data:`id=${d.join(Vs)}`})}i.push({type:"TXT",name:"_did."+qq(r.id)+".",ttl:wf,data:l.join(z2)});for(let d of t||[])a.push({type:"NS",name:"_did."+qq(r.id)+".",ttl:wf,data:d+"."});return{id:0,type:"response",flags:Yhe,answers:[...i,...a]}}function qq(r){return r.split(":")[2]}function cme(){return K.DID_DHT_GATEWAY_URI||ame}function dme(){return K.DID_DHT_ALLOW_PRIVATE_GATEWAY==="1"}function zq(r,e){return{gatewayUri:r??cme(),allowPrivateGatewayUri:e??dme()}}function uF(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Eme;)e[t++]=r&255|Hq,r/=128;for(;r&xme;)e[t++]=r&255|Hq,r>>>=7;return e[t]=r|0,uF.bytes=t-n+1,e}function kC(r,n){var t=0,n=n||0,i=0,a=n,s,o=r.length;do{if(a>=o)throw kC.bytes=0,new RangeError("Could not decode varint");s=r[a++],t+=i<28?(s&Vq)<<i:(s&Vq)*Math.pow(2,i),i+=7}while(s>=kme);return kC.bytes=a-n,t}function Yme(r){r=p6(r);let e=Yy+8;(r.length<e||r.length>1024)&&Ti("expected proper params");let t=Ye(xE(r),f6-1n)+1n;return m6(t)}var Bde,DC,Ode,jde,Mde,Kde,Zt,RC,Ude,vh,Nde,Lde,Md,qde,zde,CC,gz,wz,vz,Fde,Gde,Hde,Vde,dE,$C,fh,Wde,Jde,bz,Zde,Yde,Pz,Xde,Qde,ele,Q9,xz,tle,Ez,Sz,rle,nle,ile,kz,sle,ole,_z,lE,is,Xi,Vn,Xe,ale,ja,go,cle,lle,ule,fle,CNe,ple,BC,hle,mle,yle,Dz,gle,Rz,Cz,wle,vle,Yo,D2,$Ne,BNe,ONe,jNe,MNe,KNe,UNe,eq,Ba,NNe,LNe,qNe,Ol,zNe,T0,tq,x2,sh,rt,Z0,xle,Ele,O0,Sle,rq,kle,_le,Ale,Tle,Ile,nq,Dle,Rle,Cle,$le,Ble,Ole,jle,Mle,Kle,Ule,Nle,Lle,Y2,X2,X0,Q0,qle,zle,Fle,OC,iq,sq,fC,FNe,Gle,Hle,Vle,I0,Wle,oq,Jle,Ka,GNe,df,Zle,Yle,Qle,R2,eue,tue,uE,Kz,Uz,fE,oue,aue,jl,pue,MC,eC,dq,hue,tC,rC,Ad,wue,Hz,HNe,Wz,bue,Pue,xue,lf,uf,Eue,Jz,mi,yn,ch,Sue,pC,uq,fq,VNe,kue,Tue,Iue,Oue,nC,Mue,Kue,uh,ql,$a,WNe,pq,JNe,t7,r7,i7,hq,zue,mC,mq,yC,Vo,ZNe,YNe,C2,iC,Td,XNe,Wue,QNe,Xue,Que,efe,tfe,ff,pf,rfe,eb,ife,a7,sfe,gq,Zi,afe,es,c7,cfe,dfe,lfe,Ta,Yi,ufe,bs,Ml,wq,E2,gC,pfe,hfe,mfe,yfe,gfe,wfe,vfe,bfe,Pfe,xfe,Efe,Sfe,kfe,Afe,Tfe,Ife,Dfe,Rfe,Cfe,$fe,jt,Bfe,Ofe,hf,mf,jfe,l7,Ac,Go,S2,Mfe,Kfe,D0,sC,tb,vq,eLe,qfe,wC,zfe,bq,Ffe,Gfe,Pq,Ma,rb,oh,tLe,rLe,j0,Jfe,nLe,iLe,sLe,oLe,aLe,cLe,dLe,lLe,uLe,fLe,Ia,Zfe,ts,Kl,Yfe,Xfe,Qfe,yf,epe,Ly,R0,tpe,Ul,oC,Dc,rpe,npe,xe,Qe,cb,ope,ape,cpe,dpe,Nl,lpe,upe,fpe,ppe,g7,hpe,Sn,w7,db,rs,GC,v7,Eq,Ipe,jpe,b7,P7,x7,E7,S7,Ra,Tc,Oe,Vl,ahe,dhe,lhe,Sq,gf,_f,pLe,hLe,mLe,yLe,gLe,wLe,vLe,bLe,PLe,xLe,ELe,SLe,kLe,_q,Ps,Oa,Aq,Tq,_Le,ALe,TLe,ILe,Iq,Dq,Rq,Cq,e6,xs,fb,j7,t6,M7,$q,K7,Bq,ghe,whe,Oq,vhe,C0,bhe,U7,Phe,Hl,jq,Mq,DLe,yE,L7,q7,xhe,Ehe,She,khe,_he,r6,Ahe,F7,$he,G7,Bhe,Ohe,Bd,kf,wh,K0,Z7,Fhe,Ghe,Hhe,zl,Mt,Fl,nt,Whe,Nq,vC,Jhe,Y7,Zhe,He,hi,qy,B2,O2,j2,M2,K2,U2,Jy,N2,xf,L2,X7,q2,Lq,Ll,Ef,$d,U0,N0,Jo,L0,q0,z0,Hy,Ca,Zy,Yhe,ns,iE,sE,oE,PC,Xhe,nF,ime,wf,z2,Vs,oF,aF,ame,dF,wo,Fq,Wy,Fn,Gn,RLe,lme,ume,fme,pme,lF,hme,mme,yme,gme,vE,CLe,$Le,Gq,BLe,eg,wme,EC,Cd,Ho,a6,Ic,vme,ob,bme,Hq,Pme,xme,Eme,Sme,kme,Vq,_me,Ame,Tme,Ime,Dme,Rme,Cme,$me,Bme,Ome,jme,Mme,aE,Wq,Jq,Zq,Yq,Kme,fF,pF,Ume,hF,Xq,OLe,$0,Wo,_C,_2,AC,Ny,A2,mF,Qq,Nme,Qi,G2,TC,IC,T2,yo,gF,c6,tg,Lme,at,ez,tz,rg,cE,H2,wF,d6,l6,qme,zme,rz,vF,Id,Fme,nz,Gme,cC,iz,Hme,dh,Vme,Wme,u6,mh,f6,bF,PF,xF,Yy,sz,Ti,bE,EF,dC,SF,kF,ab,p6,Ye,oz,az,ng,Y0,V2,_F,h6,PE,xE,cz,m6,dz,lz,AF,Jme,Zme,uz,W2,Xme,lh,Qme,eye,fz,pz,B0,tye,rye,hz,nye,TF,Xo,iye,J2,I2,sye,mz,IF,mb,oye,DF,RF,aye,cye,EE,dye,SE,lye,ag,Qo=G(()=>{"use strict";g();Bde=Object.create,DC=Object.defineProperty,Ode=Object.getOwnPropertyDescriptor,jde=Object.getOwnPropertyNames,Mde=Object.getPrototypeOf,Kde=Object.prototype.hasOwnProperty,Zt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),RC=(r,e)=>{for(var t in e)DC(r,t,{get:e[t],enumerable:!0})},Ude=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of jde(e))!Kde.call(r,i)&&i!==t&&DC(r,i,{get:()=>e[i],enumerable:!(n=Ode(e,i))||n.enumerable});return r},vh=(r,e,t)=>(t=r!=null?Bde(Mde(r)):{},Ude(e||!r||!r.__esModule?DC(t,"default",{value:r,enumerable:!0}):t,r)),Nde=Zt((r,e)=>{var t=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,n=()=>t.now(),i=o=>o&&o===Math.floor(o)&&o>0&&isFinite(o),a=o=>o===1/0||i(o),s=class yz{constructor({max:c=1/0,ttl:l,updateAgeOnGet:d=!1,checkAgeOnGet:u=!1,noUpdateTTL:f=!1,dispose:p,noDisposeOnSet:h=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,l!==void 0&&!a(l))throw new TypeError("ttl must be positive integer or Infinity if set");if(!a(c))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=l,this.max=c,this.updateAgeOnGet=!!d,this.checkAgeOnGet=!!u,this.noUpdateTTL=!!f,this.noDisposeOnSet=!!h,p!==void 0){if(typeof p!="function")throw new TypeError("dispose must be function if set");this.dispose=p}this.timer=void 0,this.timerExpiration=void 0}setTimer(c,l){if(this.timerExpiration<c)return;this.timer&&clearTimeout(this.timer);let d=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let u in this.expirations){this.setTimer(u,u-n());break}},l);d.unref&&d.unref(),this.timerExpiration=c,this.timer=d}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return process.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){let c=this.dispose!==yz.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[l,d]of c)this.dispose(d,l,"delete")}setTTL(c,l=this.ttl){let d=this.expirationMap.get(c);if(d!==void 0){let u=this.expirations[d];!u||u.length<=1?delete this.expirations[d]:this.expirations[d]=u.filter(f=>f!==c)}if(l!==1/0){let u=Math.floor(n()+l);this.expirationMap.set(c,u),this.expirations[u]||(this.expirations[u]=[],this.setTimer(u,l)),this.expirations[u].push(c)}else this.expirationMap.set(c,1/0)}set(c,l,{ttl:d=this.ttl,noUpdateTTL:u=this.noUpdateTTL,noDisposeOnSet:f=this.noDisposeOnSet}={}){if(!a(d))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(c)){u||this.setTTL(c,d);let p=this.data.get(c);p!==l&&(this.data.set(c,l),f||this.dispose(p,c,"set"))}else this.setTTL(c,d),this.data.set(c,l);for(;this.size>this.max;)this.purgeToCapacity();return this}has(c){return this.data.has(c)}getRemainingTTL(c){let l=this.expirationMap.get(c);return l===1/0?l:l!==void 0?Math.max(0,Math.ceil(l-n())):0}get(c,{updateAgeOnGet:l=this.updateAgeOnGet,ttl:d=this.ttl,checkAgeOnGet:u=this.checkAgeOnGet}={}){let f=this.data.get(c);if(u&&this.getRemainingTTL(c)===0){this.delete(c);return}return l&&this.setTTL(c,d),f}dispose(c,l){}delete(c){let l=this.expirationMap.get(c);if(l!==void 0){let d=this.data.get(c);this.data.delete(c),this.expirationMap.delete(c);let u=this.expirations[l];return u&&(u.length<=1?delete this.expirations[l]:this.expirations[l]=u.filter(f=>f!==c)),this.dispose(d,c,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let c in this.expirations){let l=this.expirations[c];if(this.size-l.length>=this.max){delete this.expirations[c];let d=[];for(let u of l)d.push([u,this.data.get(u)]),this.data.delete(u),this.expirationMap.delete(u);for(let[u,f]of d)this.dispose(f,u,"evict")}else{let d=this.size-this.max,u=[];for(let f of l.splice(0,d))u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,p]of u)this.dispose(p,f,"evict");return}}}get size(){return this.data.size}purgeStale(){let c=Math.ceil(n());for(let l in this.expirations){if(l==="Infinity"||l>c)return;let d=[...this.expirations[l]||[]],u=[];delete this.expirations[l];for(let f of d)u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,p]of u)this.dispose(p,f,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let c in this.expirations)for(let l of this.expirations[c])yield[l,this.data.get(l)]}*keys(){for(let c in this.expirations)for(let l of this.expirations[c])yield l}*values(){for(let c in this.expirations)for(let l of this.expirations[c])yield this.data.get(l)}[Symbol.iterator](){return this.entries()}};e.exports=s}),Lde=Zt(r=>{"use strict";r.supports=function(...e){let t=e.reduce((n,i)=>Object.assign(n,i),{});return Object.assign(t,{snapshots:t.snapshots||!1,permanence:t.permanence||!1,seek:t.seek||!1,clear:t.clear||!1,getMany:t.getMany||!1,keyIterator:t.keyIterator||!1,valueIterator:t.valueIterator||!1,iteratorNextv:t.iteratorNextv||!1,iteratorAll:t.iteratorAll||!1,status:t.status||!1,createIfMissing:t.createIfMissing||!1,errorIfExists:t.errorIfExists||!1,deferredOpen:t.deferredOpen||!1,promises:t.promises||!1,streams:t.streams||!1,encodings:Object.assign({},t.encodings),events:Object.assign({},t.events),additionalMethods:Object.assign({},t.additionalMethods)})}}),Md=Zt((r,e)=>{"use strict";e.exports=class extends Error{constructor(t,n){super(t||""),typeof n=="object"&&n!==null&&(n.code&&(this.code=String(n.code)),n.expected&&(this.expected=!0),n.transient&&(this.transient=!0),n.cause&&(this.cause=n.cause)),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}}),qde=Zt(r=>{"use strict";r.byteLength=c,r.toByteArray=d,r.fromByteArray=p;var e=[],t=[],n=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(a=0,s=i.length;a<s;++a)e[a]=i[a],t[i.charCodeAt(a)]=a;var a,s;t[45]=62,t[95]=63;function o(h){var m=h.length;if(m%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var y=h.indexOf("=");y===-1&&(y=m);var v=y===m?0:4-y%4;return[y,v]}function c(h){var m=o(h),y=m[0],v=m[1];return(y+v)*3/4-v}function l(h,m,y){return(m+y)*3/4-y}function d(h){var m,y=o(h),v=y[0],w=y[1],E=new n(l(h,v,w)),_=0,A=w>0?v-4:v,D;for(D=0;D<A;D+=4)m=t[h.charCodeAt(D)]<<18|t[h.charCodeAt(D+1)]<<12|t[h.charCodeAt(D+2)]<<6|t[h.charCodeAt(D+3)],E[_++]=m>>16&255,E[_++]=m>>8&255,E[_++]=m&255;return w===2&&(m=t[h.charCodeAt(D)]<<2|t[h.charCodeAt(D+1)]>>4,E[_++]=m&255),w===1&&(m=t[h.charCodeAt(D)]<<10|t[h.charCodeAt(D+1)]<<4|t[h.charCodeAt(D+2)]>>2,E[_++]=m>>8&255,E[_++]=m&255),E}function u(h){return e[h>>18&63]+e[h>>12&63]+e[h>>6&63]+e[h&63]}function f(h,m,y){for(var v,w=[],E=m;E<y;E+=3)v=(h[E]<<16&16711680)+(h[E+1]<<8&65280)+(h[E+2]&255),w.push(u(v));return w.join("")}function p(h){for(var m,y=h.length,v=y%3,w=[],E=16383,_=0,A=y-v;_<A;_+=E)w.push(f(h,_,_+E>A?A:_+E));return v===1?(m=h[y-1],w.push(e[m>>2]+e[m<<4&63]+"==")):v===2&&(m=(h[y-2]<<8)+h[y-1],w.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),w.join("")}}),zde=Zt(r=>{r.read=function(e,t,n,i,a){var s,o,c=a*8-i-1,l=(1<<c)-1,d=l>>1,u=-7,f=n?a-1:0,p=n?-1:1,h=e[t+f];for(f+=p,s=h&(1<<-u)-1,h>>=-u,u+=c;u>0;s=s*256+e[t+f],f+=p,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=i;u>0;o=o*256+e[t+f],f+=p,u-=8);if(s===0)s=1-d;else{if(s===l)return o?NaN:(h?-1:1)*(1/0);o=o+Math.pow(2,i),s=s-d}return(h?-1:1)*o*Math.pow(2,s-i)},r.write=function(e,t,n,i,a,s){var o,c,l,d=s*8-a-1,u=(1<<d)-1,f=u>>1,p=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,h=i?0:s-1,m=i?1:-1,y=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+f>=1?t+=p/l:t+=p*Math.pow(2,1-f),t*l>=2&&(o++,l/=2),o+f>=u?(c=0,o=u):o+f>=1?(c=(t*l-1)*Math.pow(2,a),o=o+f):(c=t*Math.pow(2,f-1)*Math.pow(2,a),o=0));a>=8;e[n+h]=c&255,h+=m,c/=256,a-=8);for(o=o<<a|c,d+=a;d>0;e[n+h]=o&255,h+=m,o/=256,d-=8);e[n+h-m]|=y*128}}),CC=Zt(r=>{"use strict";var e=qde(),t=zde(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;r.Buffer=o,r.SlowBuffer=w,r.INSPECT_MAX_BYTES=50;var i=2147483647;r.kMaxLength=i,o.TYPED_ARRAY_SUPPORT=a(),!o.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let T=new Uint8Array(1),U={foo:function(){return 42}};return Object.setPrototypeOf(U,Uint8Array.prototype),Object.setPrototypeOf(T,U),T.foo()===42}catch{return!1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function s(T){if(T>i)throw new RangeError('The value "'+T+'" is invalid for option "size"');let U=new Uint8Array(T);return Object.setPrototypeOf(U,o.prototype),U}function o(T,U,N){if(typeof T=="number"){if(typeof U=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(T)}return c(T,U,N)}o.poolSize=8192;function c(T,U,N){if(typeof T=="string")return f(T,U);if(ArrayBuffer.isView(T))return h(T);if(T==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T);if(We(T,ArrayBuffer)||T&&We(T.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(We(T,SharedArrayBuffer)||T&&We(T.buffer,SharedArrayBuffer)))return m(T,U,N);if(typeof T=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let te=T.valueOf&&T.valueOf();if(te!=null&&te!==T)return o.from(te,U,N);let ce=y(T);if(ce)return ce;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof T[Symbol.toPrimitive]=="function")return o.from(T[Symbol.toPrimitive]("string"),U,N);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T)}o.from=function(T,U,N){return c(T,U,N)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function l(T){if(typeof T!="number")throw new TypeError('"size" argument must be of type number');if(T<0)throw new RangeError('The value "'+T+'" is invalid for option "size"')}function d(T,U,N){return l(T),T<=0?s(T):U!==void 0?typeof N=="string"?s(T).fill(U,N):s(T).fill(U):s(T)}o.alloc=function(T,U,N){return d(T,U,N)};function u(T){return l(T),s(T<0?0:v(T)|0)}o.allocUnsafe=function(T){return u(T)},o.allocUnsafeSlow=function(T){return u(T)};function f(T,U){if((typeof U!="string"||U==="")&&(U="utf8"),!o.isEncoding(U))throw new TypeError("Unknown encoding: "+U);let N=E(T,U)|0,te=s(N),ce=te.write(T,U);return ce!==N&&(te=te.slice(0,ce)),te}function p(T){let U=T.length<0?0:v(T.length)|0,N=s(U);for(let te=0;te<U;te+=1)N[te]=T[te]&255;return N}function h(T){if(We(T,Uint8Array)){let U=new Uint8Array(T);return m(U.buffer,U.byteOffset,U.byteLength)}return p(T)}function m(T,U,N){if(U<0||T.byteLength<U)throw new RangeError('"offset" is outside of buffer bounds');if(T.byteLength<U+(N||0))throw new RangeError('"length" is outside of buffer bounds');let te;return U===void 0&&N===void 0?te=new Uint8Array(T):N===void 0?te=new Uint8Array(T,U):te=new Uint8Array(T,U,N),Object.setPrototypeOf(te,o.prototype),te}function y(T){if(o.isBuffer(T)){let U=v(T.length)|0,N=s(U);return N.length===0||T.copy(N,0,0,U),N}if(T.length!==void 0)return typeof T.length!="number"||nr(T.length)?s(0):p(T);if(T.type==="Buffer"&&Array.isArray(T.data))return p(T.data)}function v(T){if(T>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return T|0}function w(T){return+T!=T&&(T=0),o.alloc(+T)}o.isBuffer=function(T){return T!=null&&T._isBuffer===!0&&T!==o.prototype},o.compare=function(T,U){if(We(T,Uint8Array)&&(T=o.from(T,T.offset,T.byteLength)),We(U,Uint8Array)&&(U=o.from(U,U.offset,U.byteLength)),!o.isBuffer(T)||!o.isBuffer(U))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(T===U)return 0;let N=T.length,te=U.length;for(let ce=0,ge=Math.min(N,te);ce<ge;++ce)if(T[ce]!==U[ce]){N=T[ce],te=U[ce];break}return N<te?-1:te<N?1:0},o.isEncoding=function(T){switch(String(T).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(T,U){if(!Array.isArray(T))throw new TypeError('"list" argument must be an Array of Buffers');if(T.length===0)return o.alloc(0);let N;if(U===void 0)for(U=0,N=0;N<T.length;++N)U+=T[N].length;let te=o.allocUnsafe(U),ce=0;for(N=0;N<T.length;++N){let ge=T[N];if(We(ge,Uint8Array))ce+ge.length>te.length?(o.isBuffer(ge)||(ge=o.from(ge)),ge.copy(te,ce)):Uint8Array.prototype.set.call(te,ge,ce);else if(o.isBuffer(ge))ge.copy(te,ce);else throw new TypeError('"list" argument must be an Array of Buffers');ce+=ge.length}return te};function E(T,U){if(o.isBuffer(T))return T.length;if(ArrayBuffer.isView(T)||We(T,ArrayBuffer))return T.byteLength;if(typeof T!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof T);let N=T.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&N===0)return 0;let ce=!1;for(;;)switch(U){case"ascii":case"latin1":case"binary":return N;case"utf8":case"utf-8":return Te(T).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N*2;case"hex":return N>>>1;case"base64":return Kr(T).length;default:if(ce)return te?-1:Te(T).length;U=(""+U).toLowerCase(),ce=!0}}o.byteLength=E;function _(T,U,N){let te=!1;if((U===void 0||U<0)&&(U=0),U>this.length||((N===void 0||N>this.length)&&(N=this.length),N<=0)||(N>>>=0,U>>>=0,N<=U))return"";for(T||(T="utf8");;)switch(T){case"hex":return k(this,U,N);case"utf8":case"utf-8":return R(this,U,N);case"ascii":return x(this,U,N);case"latin1":case"binary":return P(this,U,N);case"base64":return ee(this,U,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,U,N);default:if(te)throw new TypeError("Unknown encoding: "+T);T=(T+"").toLowerCase(),te=!0}}o.prototype._isBuffer=!0;function A(T,U,N){let te=T[U];T[U]=T[N],T[N]=te}o.prototype.swap16=function(){let T=this.length;if(T%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let U=0;U<T;U+=2)A(this,U,U+1);return this},o.prototype.swap32=function(){let T=this.length;if(T%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let U=0;U<T;U+=4)A(this,U,U+3),A(this,U+1,U+2);return this},o.prototype.swap64=function(){let T=this.length;if(T%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let U=0;U<T;U+=8)A(this,U,U+7),A(this,U+1,U+6),A(this,U+2,U+5),A(this,U+3,U+4);return this},o.prototype.toString=function(){let T=this.length;return T===0?"":arguments.length===0?R(this,0,T):_.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(T){if(!o.isBuffer(T))throw new TypeError("Argument must be a Buffer");return this===T?!0:o.compare(this,T)===0},o.prototype.inspect=function(){let T="",U=r.INSPECT_MAX_BYTES;return T=this.toString("hex",0,U).replace(/(.{2})/g,"$1 ").trim(),this.length>U&&(T+=" ... "),"<Buffer "+T+">"},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(T,U,N,te,ce){if(We(T,Uint8Array)&&(T=o.from(T,T.offset,T.byteLength)),!o.isBuffer(T))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof T);if(U===void 0&&(U=0),N===void 0&&(N=T?T.length:0),te===void 0&&(te=0),ce===void 0&&(ce=this.length),U<0||N>T.length||te<0||ce>this.length)throw new RangeError("out of range index");if(te>=ce&&U>=N)return 0;if(te>=ce)return-1;if(U>=N)return 1;if(U>>>=0,N>>>=0,te>>>=0,ce>>>=0,this===T)return 0;let ge=ce-te,Ee=N-U,qt=Math.min(ge,Ee),ri=this.slice(te,ce),Gr=T.slice(U,N);for(let Er=0;Er<qt;++Er)if(ri[Er]!==Gr[Er]){ge=ri[Er],Ee=Gr[Er];break}return ge<Ee?-1:Ee<ge?1:0};function D(T,U,N,te,ce){if(T.length===0)return-1;if(typeof N=="string"?(te=N,N=0):N>2147483647?N=2147483647:N<-2147483648&&(N=-2147483648),N=+N,nr(N)&&(N=ce?0:T.length-1),N<0&&(N=T.length+N),N>=T.length){if(ce)return-1;N=T.length-1}else if(N<0)if(ce)N=0;else return-1;if(typeof U=="string"&&(U=o.from(U,te)),o.isBuffer(U))return U.length===0?-1:M(T,U,N,te,ce);if(typeof U=="number")return U=U&255,typeof Uint8Array.prototype.indexOf=="function"?ce?Uint8Array.prototype.indexOf.call(T,U,N):Uint8Array.prototype.lastIndexOf.call(T,U,N):M(T,[U],N,te,ce);throw new TypeError("val must be string, number or Buffer")}function M(T,U,N,te,ce){let ge=1,Ee=T.length,qt=U.length;if(te!==void 0&&(te=String(te).toLowerCase(),te==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(T.length<2||U.length<2)return-1;ge=2,Ee/=2,qt/=2,N/=2}function ri(Er,hr){return ge===1?Er[hr]:Er.readUInt16BE(hr*ge)}let Gr;if(ce){let Er=-1;for(Gr=N;Gr<Ee;Gr++)if(ri(T,Gr)===ri(U,Er===-1?0:Gr-Er)){if(Er===-1&&(Er=Gr),Gr-Er+1===qt)return Er*ge}else Er!==-1&&(Gr-=Gr-Er),Er=-1}else for(N+qt>Ee&&(N=Ee-qt),Gr=N;Gr>=0;Gr--){let Er=!0;for(let hr=0;hr<qt;hr++)if(ri(T,Gr+hr)!==ri(U,hr)){Er=!1;break}if(Er)return Gr}return-1}o.prototype.includes=function(T,U,N){return this.indexOf(T,U,N)!==-1},o.prototype.indexOf=function(T,U,N){return D(this,T,U,N,!0)},o.prototype.lastIndexOf=function(T,U,N){return D(this,T,U,N,!1)};function C(T,U,N,te){N=Number(N)||0;let ce=T.length-N;te?(te=Number(te),te>ce&&(te=ce)):te=ce;let ge=U.length;te>ge/2&&(te=ge/2);let Ee;for(Ee=0;Ee<te;++Ee){let qt=parseInt(U.substr(Ee*2,2),16);if(nr(qt))return Ee;T[N+Ee]=qt}return Ee}function z(T,U,N,te){return Ys(Te(U,T.length-N),T,N,te)}function L(T,U,N,te){return Ys(Rt(U),T,N,te)}function B(T,U,N,te){return Ys(Kr(U),T,N,te)}function W(T,U,N,te){return Ys(ti(U,T.length-N),T,N,te)}o.prototype.write=function(T,U,N,te){if(U===void 0)te="utf8",N=this.length,U=0;else if(N===void 0&&typeof U=="string")te=U,N=this.length,U=0;else if(isFinite(U))U=U>>>0,isFinite(N)?(N=N>>>0,te===void 0&&(te="utf8")):(te=N,N=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let ce=this.length-U;if((N===void 0||N>ce)&&(N=ce),T.length>0&&(N<0||U<0)||U>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");let ge=!1;for(;;)switch(te){case"hex":return C(this,T,U,N);case"utf8":case"utf-8":return z(this,T,U,N);case"ascii":case"latin1":case"binary":return L(this,T,U,N);case"base64":return B(this,T,U,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return W(this,T,U,N);default:if(ge)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),ge=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ee(T,U,N){return U===0&&N===T.length?e.fromByteArray(T):e.fromByteArray(T.slice(U,N))}function R(T,U,N){N=Math.min(T.length,N);let te=[],ce=U;for(;ce<N;){let ge=T[ce],Ee=null,qt=ge>239?4:ge>223?3:ge>191?2:1;if(ce+qt<=N){let ri,Gr,Er,hr;switch(qt){case 1:ge<128&&(Ee=ge);break;case 2:ri=T[ce+1],(ri&192)===128&&(hr=(ge&31)<<6|ri&63,hr>127&&(Ee=hr));break;case 3:ri=T[ce+1],Gr=T[ce+2],(ri&192)===128&&(Gr&192)===128&&(hr=(ge&15)<<12|(ri&63)<<6|Gr&63,hr>2047&&(hr<55296||hr>57343)&&(Ee=hr));break;case 4:ri=T[ce+1],Gr=T[ce+2],Er=T[ce+3],(ri&192)===128&&(Gr&192)===128&&(Er&192)===128&&(hr=(ge&15)<<18|(ri&63)<<12|(Gr&63)<<6|Er&63,hr>65535&&hr<1114112&&(Ee=hr))}}Ee===null?(Ee=65533,qt=1):Ee>65535&&(Ee-=65536,te.push(Ee>>>10&1023|55296),Ee=56320|Ee&1023),te.push(Ee),ce+=qt}return S(te)}var $=4096;function S(T){let U=T.length;if(U<=$)return String.fromCharCode.apply(String,T);let N="",te=0;for(;te<U;)N+=String.fromCharCode.apply(String,T.slice(te,te+=$));return N}function x(T,U,N){let te="";N=Math.min(T.length,N);for(let ce=U;ce<N;++ce)te+=String.fromCharCode(T[ce]&127);return te}function P(T,U,N){let te="";N=Math.min(T.length,N);for(let ce=U;ce<N;++ce)te+=String.fromCharCode(T[ce]);return te}function k(T,U,N){let te=T.length;(!U||U<0)&&(U=0),(!N||N<0||N>te)&&(N=te);let ce="";for(let ge=U;ge<N;++ge)ce+=Ur[T[ge]];return ce}function I(T,U,N){let te=T.slice(U,N),ce="";for(let ge=0;ge<te.length-1;ge+=2)ce+=String.fromCharCode(te[ge]+te[ge+1]*256);return ce}o.prototype.slice=function(T,U){let N=this.length;T=~~T,U=U===void 0?N:~~U,T<0?(T+=N,T<0&&(T=0)):T>N&&(T=N),U<0?(U+=N,U<0&&(U=0)):U>N&&(U=N),U<T&&(U=T);let te=this.subarray(T,U);return Object.setPrototypeOf(te,o.prototype),te};function j(T,U,N){if(T%1!==0||T<0)throw new RangeError("offset is not uint");if(T+U>N)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(T,U,N){T=T>>>0,U=U>>>0,N||j(T,U,this.length);let te=this[T],ce=1,ge=0;for(;++ge<U&&(ce*=256);)te+=this[T+ge]*ce;return te},o.prototype.readUintBE=o.prototype.readUIntBE=function(T,U,N){T=T>>>0,U=U>>>0,N||j(T,U,this.length);let te=this[T+--U],ce=1;for(;U>0&&(ce*=256);)te+=this[T+--U]*ce;return te},o.prototype.readUint8=o.prototype.readUInt8=function(T,U){return T=T>>>0,U||j(T,1,this.length),this[T]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(T,U){return T=T>>>0,U||j(T,2,this.length),this[T]|this[T+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(T,U){return T=T>>>0,U||j(T,2,this.length),this[T]<<8|this[T+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(T,U){return T=T>>>0,U||j(T,4,this.length),(this[T]|this[T+1]<<8|this[T+2]<<16)+this[T+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(T,U){return T=T>>>0,U||j(T,4,this.length),this[T]*16777216+(this[T+1]<<16|this[T+2]<<8|this[T+3])},o.prototype.readBigUInt64LE=pr(function(T){T=T>>>0,pe(T,"offset");let U=this[T],N=this[T+7];(U===void 0||N===void 0)&&le(T,this.length-8);let te=U+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24,ce=this[++T]+this[++T]*2**8+this[++T]*2**16+N*2**24;return BigInt(te)+(BigInt(ce)<<BigInt(32))}),o.prototype.readBigUInt64BE=pr(function(T){T=T>>>0,pe(T,"offset");let U=this[T],N=this[T+7];(U===void 0||N===void 0)&&le(T,this.length-8);let te=U*2**24+this[++T]*2**16+this[++T]*2**8+this[++T],ce=this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+N;return(BigInt(te)<<BigInt(32))+BigInt(ce)}),o.prototype.readIntLE=function(T,U,N){T=T>>>0,U=U>>>0,N||j(T,U,this.length);let te=this[T],ce=1,ge=0;for(;++ge<U&&(ce*=256);)te+=this[T+ge]*ce;return ce*=128,te>=ce&&(te-=Math.pow(2,8*U)),te},o.prototype.readIntBE=function(T,U,N){T=T>>>0,U=U>>>0,N||j(T,U,this.length);let te=U,ce=1,ge=this[T+--te];for(;te>0&&(ce*=256);)ge+=this[T+--te]*ce;return ce*=128,ge>=ce&&(ge-=Math.pow(2,8*U)),ge},o.prototype.readInt8=function(T,U){return T=T>>>0,U||j(T,1,this.length),this[T]&128?(255-this[T]+1)*-1:this[T]},o.prototype.readInt16LE=function(T,U){T=T>>>0,U||j(T,2,this.length);let N=this[T]|this[T+1]<<8;return N&32768?N|4294901760:N},o.prototype.readInt16BE=function(T,U){T=T>>>0,U||j(T,2,this.length);let N=this[T+1]|this[T]<<8;return N&32768?N|4294901760:N},o.prototype.readInt32LE=function(T,U){return T=T>>>0,U||j(T,4,this.length),this[T]|this[T+1]<<8|this[T+2]<<16|this[T+3]<<24},o.prototype.readInt32BE=function(T,U){return T=T>>>0,U||j(T,4,this.length),this[T]<<24|this[T+1]<<16|this[T+2]<<8|this[T+3]},o.prototype.readBigInt64LE=pr(function(T){T=T>>>0,pe(T,"offset");let U=this[T],N=this[T+7];(U===void 0||N===void 0)&&le(T,this.length-8);let te=this[T+4]+this[T+5]*2**8+this[T+6]*2**16+(N<<24);return(BigInt(te)<<BigInt(32))+BigInt(U+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24)}),o.prototype.readBigInt64BE=pr(function(T){T=T>>>0,pe(T,"offset");let U=this[T],N=this[T+7];(U===void 0||N===void 0)&&le(T,this.length-8);let te=(U<<24)+this[++T]*2**16+this[++T]*2**8+this[++T];return(BigInt(te)<<BigInt(32))+BigInt(this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+N)}),o.prototype.readFloatLE=function(T,U){return T=T>>>0,U||j(T,4,this.length),t.read(this,T,!0,23,4)},o.prototype.readFloatBE=function(T,U){return T=T>>>0,U||j(T,4,this.length),t.read(this,T,!1,23,4)},o.prototype.readDoubleLE=function(T,U){return T=T>>>0,U||j(T,8,this.length),t.read(this,T,!0,52,8)},o.prototype.readDoubleBE=function(T,U){return T=T>>>0,U||j(T,8,this.length),t.read(this,T,!1,52,8)};function q(T,U,N,te,ce,ge){if(!o.isBuffer(T))throw new TypeError('"buffer" argument must be a Buffer instance');if(U>ce||U<ge)throw new RangeError('"value" argument is out of bounds');if(N+te>T.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(T,U,N,te){if(T=+T,U=U>>>0,N=N>>>0,!te){let Ee=Math.pow(2,8*N)-1;q(this,T,U,N,Ee,0)}let ce=1,ge=0;for(this[U]=T&255;++ge<N&&(ce*=256);)this[U+ge]=T/ce&255;return U+N},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(T,U,N,te){if(T=+T,U=U>>>0,N=N>>>0,!te){let Ee=Math.pow(2,8*N)-1;q(this,T,U,N,Ee,0)}let ce=N-1,ge=1;for(this[U+ce]=T&255;--ce>=0&&(ge*=256);)this[U+ce]=T/ge&255;return U+N},o.prototype.writeUint8=o.prototype.writeUInt8=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,1,255,0),this[U]=T&255,U+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,2,65535,0),this[U]=T&255,this[U+1]=T>>>8,U+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,2,65535,0),this[U]=T>>>8,this[U+1]=T&255,U+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,4,4294967295,0),this[U+3]=T>>>24,this[U+2]=T>>>16,this[U+1]=T>>>8,this[U]=T&255,U+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,4,4294967295,0),this[U]=T>>>24,this[U+1]=T>>>16,this[U+2]=T>>>8,this[U+3]=T&255,U+4};function H(T,U,N,te,ce){de(U,te,ce,T,N,7);let ge=Number(U&BigInt(4294967295));T[N++]=ge,ge=ge>>8,T[N++]=ge,ge=ge>>8,T[N++]=ge,ge=ge>>8,T[N++]=ge;let Ee=Number(U>>BigInt(32)&BigInt(4294967295));return T[N++]=Ee,Ee=Ee>>8,T[N++]=Ee,Ee=Ee>>8,T[N++]=Ee,Ee=Ee>>8,T[N++]=Ee,N}function J(T,U,N,te,ce){de(U,te,ce,T,N,7);let ge=Number(U&BigInt(4294967295));T[N+7]=ge,ge=ge>>8,T[N+6]=ge,ge=ge>>8,T[N+5]=ge,ge=ge>>8,T[N+4]=ge;let Ee=Number(U>>BigInt(32)&BigInt(4294967295));return T[N+3]=Ee,Ee=Ee>>8,T[N+2]=Ee,Ee=Ee>>8,T[N+1]=Ee,Ee=Ee>>8,T[N]=Ee,N+8}o.prototype.writeBigUInt64LE=pr(function(T,U=0){return H(this,T,U,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=pr(function(T,U=0){return J(this,T,U,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(T,U,N,te){if(T=+T,U=U>>>0,!te){let qt=Math.pow(2,8*N-1);q(this,T,U,N,qt-1,-qt)}let ce=0,ge=1,Ee=0;for(this[U]=T&255;++ce<N&&(ge*=256);)T<0&&Ee===0&&this[U+ce-1]!==0&&(Ee=1),this[U+ce]=(T/ge>>0)-Ee&255;return U+N},o.prototype.writeIntBE=function(T,U,N,te){if(T=+T,U=U>>>0,!te){let qt=Math.pow(2,8*N-1);q(this,T,U,N,qt-1,-qt)}let ce=N-1,ge=1,Ee=0;for(this[U+ce]=T&255;--ce>=0&&(ge*=256);)T<0&&Ee===0&&this[U+ce+1]!==0&&(Ee=1),this[U+ce]=(T/ge>>0)-Ee&255;return U+N},o.prototype.writeInt8=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,1,127,-128),T<0&&(T=255+T+1),this[U]=T&255,U+1},o.prototype.writeInt16LE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,2,32767,-32768),this[U]=T&255,this[U+1]=T>>>8,U+2},o.prototype.writeInt16BE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,2,32767,-32768),this[U]=T>>>8,this[U+1]=T&255,U+2},o.prototype.writeInt32LE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,4,2147483647,-2147483648),this[U]=T&255,this[U+1]=T>>>8,this[U+2]=T>>>16,this[U+3]=T>>>24,U+4},o.prototype.writeInt32BE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,4,2147483647,-2147483648),T<0&&(T=4294967295+T+1),this[U]=T>>>24,this[U+1]=T>>>16,this[U+2]=T>>>8,this[U+3]=T&255,U+4},o.prototype.writeBigInt64LE=pr(function(T,U=0){return H(this,T,U,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=pr(function(T,U=0){return J(this,T,U,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function V(T,U,N,te,ce,ge){if(N+te>T.length)throw new RangeError("Index out of range");if(N<0)throw new RangeError("Index out of range")}function Z(T,U,N,te,ce){return U=+U,N=N>>>0,ce||V(T,U,N,4,34028234663852886e22,-34028234663852886e22),t.write(T,U,N,te,23,4),N+4}o.prototype.writeFloatLE=function(T,U,N){return Z(this,T,U,!0,N)},o.prototype.writeFloatBE=function(T,U,N){return Z(this,T,U,!1,N)};function F(T,U,N,te,ce){return U=+U,N=N>>>0,ce||V(T,U,N,8,17976931348623157e292,-17976931348623157e292),t.write(T,U,N,te,52,8),N+8}o.prototype.writeDoubleLE=function(T,U,N){return F(this,T,U,!0,N)},o.prototype.writeDoubleBE=function(T,U,N){return F(this,T,U,!1,N)},o.prototype.copy=function(T,U,N,te){if(!o.isBuffer(T))throw new TypeError("argument should be a Buffer");if(N||(N=0),!te&&te!==0&&(te=this.length),U>=T.length&&(U=T.length),U||(U=0),te>0&&te<N&&(te=N),te===N||T.length===0||this.length===0)return 0;if(U<0)throw new RangeError("targetStart out of bounds");if(N<0||N>=this.length)throw new RangeError("Index out of range");if(te<0)throw new RangeError("sourceEnd out of bounds");te>this.length&&(te=this.length),T.length-U<te-N&&(te=T.length-U+N);let ce=te-N;return this===T&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(U,N,te):Uint8Array.prototype.set.call(T,this.subarray(N,te),U),ce},o.prototype.fill=function(T,U,N,te){if(typeof T=="string"){if(typeof U=="string"?(te=U,U=0,N=this.length):typeof N=="string"&&(te=N,N=this.length),te!==void 0&&typeof te!="string")throw new TypeError("encoding must be a string");if(typeof te=="string"&&!o.isEncoding(te))throw new TypeError("Unknown encoding: "+te);if(T.length===1){let ge=T.charCodeAt(0);(te==="utf8"&&ge<128||te==="latin1")&&(T=ge)}}else typeof T=="number"?T=T&255:typeof T=="boolean"&&(T=Number(T));if(U<0||this.length<U||this.length<N)throw new RangeError("Out of range index");if(N<=U)return this;U=U>>>0,N=N===void 0?this.length:N>>>0,T||(T=0);let ce;if(typeof T=="number")for(ce=U;ce<N;++ce)this[ce]=T;else{let ge=o.isBuffer(T)?T:o.from(T,te),Ee=ge.length;if(Ee===0)throw new TypeError('The value "'+T+'" is invalid for argument "value"');for(ce=0;ce<N-U;++ce)this[ce+U]=ge[ce%Ee]}return this};var X={};function ie(T,U,N){X[T]=class extends N{constructor(){super(),Object.defineProperty(this,"message",{value:U.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${T}]`,this.stack,delete this.name}get code(){return T}set code(te){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:te,writable:!0})}toString(){return`${this.name} [${T}]: ${this.message}`}}}ie("ERR_BUFFER_OUT_OF_BOUNDS",function(T){return T?`${T} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),ie("ERR_INVALID_ARG_TYPE",function(T,U){return`The "${T}" argument must be of type number. Received type ${typeof U}`},TypeError),ie("ERR_OUT_OF_RANGE",function(T,U,N){let te=`The value of "${T}" is out of range.`,ce=N;return Number.isInteger(N)&&Math.abs(N)>2**32?ce=se(String(N)):typeof N=="bigint"&&(ce=String(N),(N>BigInt(2)**BigInt(32)||N<-(BigInt(2)**BigInt(32)))&&(ce=se(ce)),ce+="n"),te+=` It must be ${U}. Received ${ce}`,te},RangeError);function se(T){let U="",N=T.length,te=T[0]==="-"?1:0;for(;N>=te+4;N-=3)U=`_${T.slice(N-3,N)}${U}`;return`${T.slice(0,N)}${U}`}function Y(T,U,N){pe(U,"offset"),(T[U]===void 0||T[U+N]===void 0)&&le(U,T.length-(N+1))}function de(T,U,N,te,ce,ge){if(T>N||T<U){let Ee=typeof U=="bigint"?"n":"",qt;throw ge>3?U===0||U===BigInt(0)?qt=`>= 0${Ee} and < 2${Ee} ** ${(ge+1)*8}${Ee}`:qt=`>= -(2${Ee} ** ${(ge+1)*8-1}${Ee}) and < 2 ** ${(ge+1)*8-1}${Ee}`:qt=`>= ${U}${Ee} and <= ${N}${Ee}`,new X.ERR_OUT_OF_RANGE("value",qt,T)}Y(te,ce,ge)}function pe(T,U){if(typeof T!="number")throw new X.ERR_INVALID_ARG_TYPE(U,"number",T)}function le(T,U,N){throw Math.floor(T)!==T?(pe(T,N),new X.ERR_OUT_OF_RANGE(N||"offset","an integer",T)):U<0?new X.ERR_BUFFER_OUT_OF_BOUNDS:new X.ERR_OUT_OF_RANGE(N||"offset",`>= ${N?1:0} and <= ${U}`,T)}var Se=/[^+/0-9A-Za-z-_]/g;function he(T){if(T=T.split("=")[0],T=T.trim().replace(Se,""),T.length<2)return"";for(;T.length%4!==0;)T=T+"=";return T}function Te(T,U){U=U||1/0;let N,te=T.length,ce=null,ge=[];for(let Ee=0;Ee<te;++Ee){if(N=T.charCodeAt(Ee),N>55295&&N<57344){if(!ce){if(N>56319){(U-=3)>-1&&ge.push(239,191,189);continue}else if(Ee+1===te){(U-=3)>-1&&ge.push(239,191,189);continue}ce=N;continue}if(N<56320){(U-=3)>-1&&ge.push(239,191,189),ce=N;continue}N=(ce-55296<<10|N-56320)+65536}else ce&&(U-=3)>-1&&ge.push(239,191,189);if(ce=null,N<128){if((U-=1)<0)break;ge.push(N)}else if(N<2048){if((U-=2)<0)break;ge.push(N>>6|192,N&63|128)}else if(N<65536){if((U-=3)<0)break;ge.push(N>>12|224,N>>6&63|128,N&63|128)}else if(N<1114112){if((U-=4)<0)break;ge.push(N>>18|240,N>>12&63|128,N>>6&63|128,N&63|128)}else throw new Error("Invalid code point")}return ge}function Rt(T){let U=[];for(let N=0;N<T.length;++N)U.push(T.charCodeAt(N)&255);return U}function ti(T,U){let N,te,ce,ge=[];for(let Ee=0;Ee<T.length&&!((U-=2)<0);++Ee)N=T.charCodeAt(Ee),te=N>>8,ce=N%256,ge.push(ce),ge.push(te);return ge}function Kr(T){return e.toByteArray(he(T))}function Ys(T,U,N,te){let ce;for(ce=0;ce<te&&!(ce+N>=U.length||ce>=T.length);++ce)U[ce+N]=T[ce];return ce}function We(T,U){return T instanceof U||T!=null&&T.constructor!=null&&T.constructor.name!=null&&T.constructor.name===U.name}function nr(T){return T!==T}var Ur=function(){let T="0123456789abcdef",U=new Array(256);for(let N=0;N<16;++N){let te=N*16;for(let ce=0;ce<16;++ce)U[te+ce]=T[N]+T[ce]}return U}();function pr(T){return typeof BigInt>"u"?Lt:T}function Lt(){throw new Error("BigInt not supported")}}),gz=Zt((r,e)=>{"use strict";var t=null;e.exports=function(){return t===null&&(t={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),t}}),wz=Zt(r=>{"use strict";var e=Md(),t=new Set(["buffer","view","utf8"]),n=class{constructor(i){if(this.encode=i.encode||this.encode,this.decode=i.decode||this.decode,this.name=i.name||this.name,this.format=i.format||this.format,typeof this.encode!="function")throw new TypeError("The 'encode' property must be a function");if(typeof this.decode!="function")throw new TypeError("The 'decode' property must be a function");if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),typeof this.name!="string"||this.name==="")throw new TypeError("The 'name' property must be a string");if(typeof this.format!="string"||!t.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");i.createViewTranscoder&&(this.createViewTranscoder=i.createViewTranscoder),i.createBufferTranscoder&&(this.createBufferTranscoder=i.createBufferTranscoder),i.createUTF8Transcoder&&(this.createUTF8Transcoder=i.createUTF8Transcoder)}get commonName(){return this.name.split("+")[0]}createBufferTranscoder(){throw new e(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new e(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new e(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};r.Encoding=n}),vz=Zt(r=>{"use strict";var{Buffer:e}=CC()||{},{Encoding:t}=wz(),n=gz(),i=class extends t{constructor(o){super({...o,format:"buffer"})}createViewTranscoder(){return new a({encode:this.encode,decode:o=>this.decode(e.from(o.buffer,o.byteOffset,o.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},a=class extends t{constructor(o){super({...o,format:"view"})}createBufferTranscoder(){return new i({encode:o=>{let c=this.encode(o);return e.from(c.buffer,c.byteOffset,c.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},s=class extends t{constructor(o){super({...o,format:"utf8"})}createBufferTranscoder(){return new i({encode:o=>e.from(this.encode(o),"utf8"),decode:o=>this.decode(o.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:o,textDecoder:c}=n();return new a({encode:l=>o.encode(this.encode(l)),decode:l=>this.decode(c.decode(l)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};r.BufferFormat=i,r.ViewFormat=a,r.UTF8Format=s}),Fde=Zt(r=>{"use strict";var{Buffer:e}=CC()||{Buffer:{isBuffer:()=>!1}},{textEncoder:t,textDecoder:n}=gz()(),{BufferFormat:i,ViewFormat:a,UTF8Format:s}=vz(),o=c=>c;r.utf8=new s({encode:function(c){return e.isBuffer(c)?c.toString("utf8"):ArrayBuffer.isView(c)?n.decode(c):String(c)},decode:o,name:"utf8",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:t.encode(c)},decode:function(c){return n.decode(c)},name:`${this.name}+view`})},createBufferTranscoder(){return new i({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:function(c){return c.toString("utf8")},name:`${this.name}+buffer`})}}),r.json=new s({encode:JSON.stringify,decode:JSON.parse,name:"json"}),r.buffer=new i({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:o,name:"buffer",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:e.from(String(c),"utf8")},decode:function(c){return e.from(c.buffer,c.byteOffset,c.byteLength)},name:`${this.name}+view`})}}),r.view=new a({encode:function(c){return ArrayBuffer.isView(c)?c:t.encode(c)},decode:o,name:"view",createBufferTranscoder(){return new i({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:o,name:`${this.name}+buffer`})}}),r.hex=new i({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"hex")},decode:function(c){return c.toString("hex")},name:"hex"}),r.base64=new i({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"base64")},decode:function(c){return c.toString("base64")},name:"base64"})}),Gde=Zt(r=>{"use strict";var e=Md(),t=Fde(),{Encoding:n}=wz(),{BufferFormat:i,ViewFormat:a,UTF8Format:s}=vz(),o=Symbol("formats"),c=Symbol("encodings"),l=new Set(["buffer","view","utf8"]),d=class{constructor(y){if(Array.isArray(y)){if(!y.every(v=>l.has(v)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[c]=new Map,this[o]=new Set(y);for(let v in t)try{this.encoding(v)}catch(w){if(w.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw w}}encodings(){return Array.from(new Set(this[c].values()))}encoding(y){let v=this[c].get(y);if(v===void 0){if(typeof y=="string"&&y!==""){if(v=h[y],!v)throw new e(`Encoding '${y}' is not found`,{code:"LEVEL_ENCODING_NOT_FOUND"})}else{if(typeof y!="object"||y===null)throw new TypeError("First argument 'encoding' must be a string or object");v=u(y)}let{name:w,format:E}=v;if(!this[o].has(E))if(this[o].has("view"))v=v.createViewTranscoder();else if(this[o].has("buffer"))v=v.createBufferTranscoder();else if(this[o].has("utf8"))v=v.createUTF8Transcoder();else throw new e(`Encoding '${w}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let _ of[y,w,v.name,v.commonName])this[c].set(_,v)}return v}};r.Transcoder=d;function u(y){if(y instanceof n)return y;let v="type"in y&&typeof y.type=="string"?y.type:void 0,w=y.name||v||`anonymous-${m++}`;switch(f(y)){case"view":return new a({...y,name:w});case"utf8":return new s({...y,name:w});case"buffer":return new i({...y,name:w});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function f(y){return"format"in y&&y.format!==void 0?y.format:"buffer"in y&&typeof y.buffer=="boolean"?y.buffer?"buffer":"utf8":"code"in y&&Number.isInteger(y.code)?"view":"buffer"}var p={binary:t.buffer,"utf-8":t.utf8},h={...t,...p},m=0}),Hde=Zt((r,e)=>{"use strict";var t=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function a(l,d,u){this.fn=l,this.context=d,this.once=u||!1}function s(l,d,u,f,p){if(typeof u!="function")throw new TypeError("The listener must be a function");var h=new a(u,f||l,p),m=n?n+d:d;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],h]:l._events[m].push(h):(l._events[m]=h,l._eventsCount++),l}function o(l,d){--l._eventsCount===0?l._events=new i:delete l._events[d]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var l=[],d,u;if(this._eventsCount===0)return l;for(u in d=this._events)t.call(d,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(d)):l},c.prototype.listeners=function(l){var d=n?n+l:l,u=this._events[d];if(!u)return[];if(u.fn)return[u.fn];for(var f=0,p=u.length,h=new Array(p);f<p;f++)h[f]=u[f].fn;return h},c.prototype.listenerCount=function(l){var d=n?n+l:l,u=this._events[d];return u?u.fn?1:u.length:0},c.prototype.emit=function(l,d,u,f,p,h){var m=n?n+l:l;if(!this._events[m])return!1;var y=this._events[m],v=arguments.length,w,E;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),v){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,d),!0;case 3:return y.fn.call(y.context,d,u),!0;case 4:return y.fn.call(y.context,d,u,f),!0;case 5:return y.fn.call(y.context,d,u,f,p),!0;case 6:return y.fn.call(y.context,d,u,f,p,h),!0}for(E=1,w=new Array(v-1);E<v;E++)w[E-1]=arguments[E];y.fn.apply(y.context,w)}else{var _=y.length,A;for(E=0;E<_;E++)switch(y[E].once&&this.removeListener(l,y[E].fn,void 0,!0),v){case 1:y[E].fn.call(y[E].context);break;case 2:y[E].fn.call(y[E].context,d);break;case 3:y[E].fn.call(y[E].context,d,u);break;case 4:y[E].fn.call(y[E].context,d,u,f);break;default:if(!w)for(A=1,w=new Array(v-1);A<v;A++)w[A-1]=arguments[A];y[E].fn.apply(y[E].context,w)}}return!0},c.prototype.on=function(l,d,u){return s(this,l,d,u,!1)},c.prototype.once=function(l,d,u){return s(this,l,d,u,!0)},c.prototype.removeListener=function(l,d,u,f){var p=n?n+l:l;if(!this._events[p])return this;if(!d)return o(this,p),this;var h=this._events[p];if(h.fn)h.fn===d&&(!f||h.once)&&(!u||h.context===u)&&o(this,p);else{for(var m=0,y=[],v=h.length;m<v;m++)(h[m].fn!==d||f&&!h[m].once||u&&h[m].context!==u)&&y.push(h[m]);y.length?this._events[p]=y.length===1?y[0]:y:o(this,p)}return this},c.prototype.removeAllListeners=function(l){var d;return l?(d=n?n+l:l,this._events[d]&&o(this,d)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,typeof e<"u"&&(e.exports=c)}),Vde=Zt((r,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)}),dE=Zt(r=>{"use strict";var e=Vde();r.fromCallback=function(t,n){if(t===void 0){var i=new Promise(function(a,s){t=function(o,c){o?s(o):a(c)}});t[n!==void 0?n:"promise"]=i}else if(typeof t!="function")throw new TypeError("Callback must be a function");return t},r.fromPromise=function(t,n){if(n===void 0)return t;t.then(function(i){e(()=>n(null,i))}).catch(function(i){e(()=>n(i))})}}),$C=Zt(r=>{"use strict";r.getCallback=function(e,t){return typeof e=="function"?e:t},r.getOptions=function(e,t){return typeof e=="object"&&e!==null?e:t!==void 0?t:{}}}),fh=Zt(r=>{"use strict";var{fromCallback:e}=dE(),t=Md(),{getOptions:n,getCallback:i}=$C(),a=Symbol("promise"),s=Symbol("callback"),o=Symbol("working"),c=Symbol("handleOne"),l=Symbol("handleMany"),d=Symbol("autoClose"),u=Symbol("finishWork"),f=Symbol("returnMany"),p=Symbol("closing"),h=Symbol("handleClose"),m=Symbol("closed"),y=Symbol("closeCallbacks"),v=Symbol("keyEncoding"),w=Symbol("valueEncoding"),E=Symbol("abortOnClose"),_=Symbol("legacy"),A=Symbol("keys"),D=Symbol("values"),M=Symbol("limit"),C=Symbol("count"),z=Object.freeze({}),L=()=>{},B=!1,W=class{constructor(x,P,k){if(typeof x!="object"||x===null){let I=x===null?"null":typeof x;throw new TypeError(`The first argument must be an abstract-level database, received ${I}`)}if(typeof P!="object"||P===null)throw new TypeError("The second argument must be an options object");this[m]=!1,this[y]=[],this[o]=!1,this[p]=!1,this[d]=!1,this[s]=null,this[c]=this[c].bind(this),this[l]=this[l].bind(this),this[h]=this[h].bind(this),this[v]=P[v],this[w]=P[w],this[_]=k,this[M]=Number.isInteger(P.limit)&&P.limit>=0?P.limit:1/0,this[C]=0,this[E]=!!P.abortOnClose,this.db=x,this.db.attachResource(this),this.nextTick=x.nextTick}get count(){return this[C]}get limit(){return this[M]}next(x){let P;if(x===void 0)P=new Promise((k,I)=>{x=(j,q,H)=>{j?I(j):this[_]?q===void 0&&H===void 0?k():k([q,H]):k(q)}});else if(typeof x!="function")throw new TypeError("Callback must be a function");return this[p]?this.nextTick(x,new t("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[o]?this.nextTick(x,new t("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[o]=!0,this[s]=x,this[C]>=this[M]?this.nextTick(this[c],null):this._next(this[c])),P}_next(x){this.nextTick(x)}nextv(x,P,k){return k=i(P,k),k=e(k,a),P=n(P,z),Number.isInteger(x)?(this[p]?this.nextTick(k,new t("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[o]?this.nextTick(k,new t("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(x<1&&(x=1),this[M]<1/0&&(x=Math.min(x,this[M]-this[C])),this[o]=!0,this[s]=k,x<=0?this.nextTick(this[l],null,[]):this._nextv(x,P,this[l])),k[a]):(this.nextTick(k,new TypeError("The first argument 'size' must be an integer")),k[a])}_nextv(x,P,k){let I=[],j=(q,H,J)=>{if(q)return k(q);if(this[_]?H===void 0&&J===void 0:H===void 0)return k(null,I);I.push(this[_]?[H,J]:H),I.length===x?k(null,I):this._next(j)};this._next(j)}all(x,P){return P=i(x,P),P=e(P,a),x=n(x,z),this[p]?this.nextTick(P,new t("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[o]?this.nextTick(P,new t("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[o]=!0,this[s]=P,this[d]=!0,this[C]>=this[M]?this.nextTick(this[l],null,[]):this._all(x,this[l])),P[a]}_all(x,P){let k=this[C],I=[],j=()=>{let H=this[M]<1/0?Math.min(1e3,this[M]-k):1e3;H<=0?this.nextTick(P,null,I):this._nextv(H,z,q)},q=(H,J)=>{H?P(H):J.length===0?P(null,I):(I.push.apply(I,J),k+=J.length,j())};j()}[u](){let x=this[s];return this[E]&&x===null?L:(this[o]=!1,this[s]=null,this[p]&&this._close(this[h]),x)}[f](x,P,k){this[d]?this.close(x.bind(null,P,k)):x(P,k)}seek(x,P){if(P=n(P,z),!this[p]){if(this[o])throw new t("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let k=this.db.keyEncoding(P.keyEncoding||this[v]),I=k.format;P.keyEncoding!==I&&(P={...P,keyEncoding:I});let j=this.db.prefixKey(k.encode(x),I);this._seek(j,P)}}}_seek(x,P){throw new t("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(x){return x=e(x,a),this[m]?this.nextTick(x):this[p]?this[y].push(x):(this[p]=!0,this[y].push(x),this[o]?this[E]&&this[u]()(new t("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[h])),x[a]}_close(x){this.nextTick(x)}[h](){this[m]=!0,this.db.detachResource(this);let x=this[y];this[y]=[];for(let P of x)P()}async*[Symbol.asyncIterator](){try{let x;for(;(x=await this.next())!==void 0;)yield x}finally{this[m]||await this.close()}}},ee=class extends W{constructor(x,P){super(x,P,!0),this[A]=P.keys!==!1,this[D]=P.values!==!1}[c](x,P,k){let I=this[u]();if(x)return I(x);try{P=this[A]&&P!==void 0?this[v].decode(P):void 0,k=this[D]&&k!==void 0?this[w].decode(k):void 0}catch(j){return I(new S("entry",j))}P===void 0&&k===void 0||this[C]++,I(null,P,k)}[l](x,P){let k=this[u]();if(x)return this[f](k,x);try{for(let I of P){let j=I[0],q=I[1];I[0]=this[A]&&j!==void 0?this[v].decode(j):void 0,I[1]=this[D]&&q!==void 0?this[w].decode(q):void 0}}catch(I){return this[f](k,new S("entries",I))}this[C]+=P.length,this[f](k,null,P)}end(x){return!B&&typeof console<"u"&&(B=!0,console.warn(new t("The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version",{code:"LEVEL_LEGACY"}))),this.close(x)}},R=class extends W{constructor(x,P){super(x,P,!1)}[c](x,P){let k=this[u]();if(x)return k(x);try{P=P!==void 0?this[v].decode(P):void 0}catch(I){return k(new S("key",I))}P!==void 0&&this[C]++,k(null,P)}[l](x,P){let k=this[u]();if(x)return this[f](k,x);try{for(let I=0;I<P.length;I++){let j=P[I];P[I]=j!==void 0?this[v].decode(j):void 0}}catch(I){return this[f](k,new S("keys",I))}this[C]+=P.length,this[f](k,null,P)}},$=class extends W{constructor(x,P){super(x,P,!1)}[c](x,P){let k=this[u]();if(x)return k(x);try{P=P!==void 0?this[w].decode(P):void 0}catch(I){return k(new S("value",I))}P!==void 0&&this[C]++,k(null,P)}[l](x,P){let k=this[u]();if(x)return this[f](k,x);try{for(let I=0;I<P.length;I++){let j=P[I];P[I]=j!==void 0?this[w].decode(j):void 0}}catch(I){return this[f](k,new S("values",I))}this[C]+=P.length,this[f](k,null,P)}},S=class extends t{constructor(x,P){super(`Iterator could not decode ${x}`,{code:"LEVEL_DECODE_ERROR",cause:P})}};for(let x of["_ended property","_nexting property","_end method"])Object.defineProperty(ee.prototype,x.split(" ")[0],{get(){throw new t(`The ${x} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new t(`The ${x} has been removed`,{code:"LEVEL_LEGACY"})}});ee.keyEncoding=v,ee.valueEncoding=w,r.AbstractIterator=ee,r.AbstractKeyIterator=R,r.AbstractValueIterator=$}),Wde=Zt(r=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:t}=fh(),n=Symbol("iterator"),i=Symbol("callback"),a=Symbol("handleOne"),s=Symbol("handleMany"),o=class extends e{constructor(l,d){super(l,d),this[n]=l.iterator({...d,keys:!0,values:!1}),this[a]=this[a].bind(this),this[s]=this[s].bind(this)}},c=class extends t{constructor(l,d){super(l,d),this[n]=l.iterator({...d,keys:!1,values:!0}),this[a]=this[a].bind(this),this[s]=this[s].bind(this)}};for(let l of[o,c]){let d=l===o,u=d?f=>f[0]:f=>f[1];l.prototype._next=function(f){this[i]=f,this[n].next(this[a])},l.prototype[a]=function(f,p,h){let m=this[i];f?m(f):m(null,d?p:h)},l.prototype._nextv=function(f,p,h){this[i]=h,this[n].nextv(f,p,this[s])},l.prototype._all=function(f,p){this[i]=p,this[n].all(f,this[s])},l.prototype[s]=function(f,p){let h=this[i];f?h(f):h(null,p.map(u))},l.prototype._seek=function(f,p){this[n].seek(f,p)},l.prototype._close=function(f){this[n].close(f)}}r.DefaultKeyIterator=o,r.DefaultValueIterator=c}),Jde=Zt(r=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:t,AbstractValueIterator:n}=fh(),i=Md(),a=Symbol("nut"),s=Symbol("undefer"),o=Symbol("factory"),c=class extends e{constructor(u,f){super(u,f),this[a]=null,this[o]=()=>u.iterator(f),this.db.defer(()=>this[s]())}},l=class extends t{constructor(u,f){super(u,f),this[a]=null,this[o]=()=>u.keys(f),this.db.defer(()=>this[s]())}},d=class extends n{constructor(u,f){super(u,f),this[a]=null,this[o]=()=>u.values(f),this.db.defer(()=>this[s]())}};for(let u of[c,l,d])u.prototype[s]=function(){this.db.status==="open"&&(this[a]=this[o]())},u.prototype._next=function(f){this[a]!==null?this[a].next(f):this.db.status==="opening"?this.db.defer(()=>this._next(f)):this.nextTick(f,new i("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._nextv=function(f,p,h){this[a]!==null?this[a].nextv(f,p,h):this.db.status==="opening"?this.db.defer(()=>this._nextv(f,p,h)):this.nextTick(h,new i("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._all=function(f,p){this[a]!==null?this[a].all(p):this.db.status==="opening"?this.db.defer(()=>this._all(f,p)):this.nextTick(p,new i("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._seek=function(f,p){this[a]!==null?this[a]._seek(f,p):this.db.status==="opening"&&this.db.defer(()=>this._seek(f,p))},u.prototype._close=function(f){this[a]!==null?this[a].close(f):this.db.status==="opening"?this.db.defer(()=>this._close(f)):this.nextTick(f)};r.DeferredIterator=c,r.DeferredKeyIterator=l,r.DeferredValueIterator=d}),bz=Zt(r=>{"use strict";var{fromCallback:e}=dE(),t=Md(),{getCallback:n,getOptions:i}=$C(),a=Symbol("promise"),s=Symbol("status"),o=Symbol("operations"),c=Symbol("finishClose"),l=Symbol("closeCallbacks"),d=class{constructor(u){if(typeof u!="object"||u===null){let f=u===null?"null":typeof u;throw new TypeError(`The first argument must be an abstract-level database, received ${f}`)}this[o]=[],this[l]=[],this[s]="open",this[c]=this[c].bind(this),this.db=u,this.db.attachResource(this),this.nextTick=u.nextTick}get length(){return this[o].length}put(u,f,p){if(this[s]!=="open")throw new t("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let h=this.db._checkKey(u)||this.db._checkValue(f);if(h)throw h;let m=p&&p.sublevel!=null?p.sublevel:this.db,y=p,v=m.keyEncoding(p&&p.keyEncoding),w=m.valueEncoding(p&&p.valueEncoding),E=v.format;p={...p,keyEncoding:E,valueEncoding:w.format},m!==this.db&&(p.sublevel=null);let _=m.prefixKey(v.encode(u),E),A=w.encode(f);return this._put(_,A,p),this[o].push({...y,type:"put",key:u,value:f}),this}_put(u,f,p){}del(u,f){if(this[s]!=="open")throw new t("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let p=this.db._checkKey(u);if(p)throw p;let h=f&&f.sublevel!=null?f.sublevel:this.db,m=f,y=h.keyEncoding(f&&f.keyEncoding),v=y.format;return f={...f,keyEncoding:v},h!==this.db&&(f.sublevel=null),this._del(h.prefixKey(y.encode(u),v),f),this[o].push({...m,type:"del",key:u}),this}_del(u,f){}clear(){if(this[s]!=="open")throw new t("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[o]=[],this}_clear(){}write(u,f){return f=n(u,f),f=e(f,a),u=i(u),this[s]!=="open"?this.nextTick(f,new t("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(f):(this[s]="writing",this._write(u,p=>{this[s]="closing",this[l].push(()=>f(p)),p||this.db.emit("batch",this[o]),this._close(this[c])})),f[a]}_write(u,f){}close(u){return u=e(u,a),this[s]==="closing"?this[l].push(u):this[s]==="closed"?this.nextTick(u):(this[l].push(u),this[s]!=="writing"&&(this[s]="closing",this._close(this[c]))),u[a]}_close(u){this.nextTick(u)}[c](){this[s]="closed",this.db.detachResource(this);let u=this[l];this[l]=[];for(let f of u)f()}};r.AbstractChainedBatch=d}),Zde=Zt(r=>{"use strict";var{AbstractChainedBatch:e}=bz(),t=Md(),n=Symbol("encoded"),i=class extends e{constructor(a){super(a),this[n]=[]}_put(a,s,o){this[n].push({...o,type:"put",key:a,value:s})}_del(a,s){this[n].push({...s,type:"del",key:a})}_clear(){this[n]=[]}_write(a,s){this.db.status==="opening"?this.db.defer(()=>this._write(a,s)):this.db.status==="open"?this[n].length===0?this.nextTick(s):this.db._batch(this[n],a,s):this.nextTick(s,new t("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};r.DefaultChainedBatch=i}),Yde=Zt((r,e)=>{"use strict";var t=Md(),n=Object.prototype.hasOwnProperty,i=new Set(["lt","lte","gt","gte"]);e.exports=function(a,s){let o={};for(let c in a)if(n.call(a,c)&&!(c==="keyEncoding"||c==="valueEncoding")){if(c==="start"||c==="end")throw new t(`The legacy range option '${c}' has been removed`,{code:"LEVEL_LEGACY"});if(c==="encoding")throw new t("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});i.has(c)?o[c]=s.encode(a[c]):o[c]=a[c]}return o.reverse=!!o.reverse,o.limit=Number.isInteger(o.limit)&&o.limit>=0?o.limit:-1,o}}),Pz=Zt((r,e)=>{var t;e.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):n=>(t||(t=Promise.resolve())).then(n).catch(i=>setTimeout(()=>{throw i},0))}),Xde=Zt((r,e)=>{"use strict";var t=Pz();e.exports=function(n,...i){i.length===0?t(n):t(()=>n(...i))}}),Qde=Zt(r=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:t,AbstractValueIterator:n}=fh(),i=Symbol("unfix"),a=Symbol("iterator"),s=Symbol("handleOne"),o=Symbol("handleMany"),c=Symbol("callback"),l=class extends e{constructor(f,p,h,m){super(f,p),this[a]=h,this[i]=m,this[s]=this[s].bind(this),this[o]=this[o].bind(this),this[c]=null}[s](f,p,h){let m=this[c];if(f)return m(f);p!==void 0&&(p=this[i](p)),m(f,p,h)}[o](f,p){let h=this[c];if(f)return h(f);for(let m of p){let y=m[0];y!==void 0&&(m[0]=this[i](y))}h(f,p)}},d=class extends t{constructor(f,p,h,m){super(f,p),this[a]=h,this[i]=m,this[s]=this[s].bind(this),this[o]=this[o].bind(this),this[c]=null}[s](f,p){let h=this[c];if(f)return h(f);p!==void 0&&(p=this[i](p)),h(f,p)}[o](f,p){let h=this[c];if(f)return h(f);for(let m=0;m<p.length;m++){let y=p[m];y!==void 0&&(p[m]=this[i](y))}h(f,p)}},u=class extends n{constructor(f,p,h){super(f,p),this[a]=h}};for(let f of[l,d])f.prototype._next=function(p){this[c]=p,this[a].next(this[s])},f.prototype._nextv=function(p,h,m){this[c]=m,this[a].nextv(p,h,this[o])},f.prototype._all=function(p,h){this[c]=h,this[a].all(p,this[o])};for(let f of[u])f.prototype._next=function(p){this[a].next(p)},f.prototype._nextv=function(p,h,m){this[a].nextv(p,h,m)},f.prototype._all=function(p,h){this[a].all(p,h)};for(let f of[l,d,u])f.prototype._seek=function(p,h){this[a].seek(p,h)},f.prototype._close=function(p){this[a].close(p)};r.AbstractSublevelIterator=l,r.AbstractSublevelKeyIterator=d,r.AbstractSublevelValueIterator=u}),ele=Zt((r,e)=>{"use strict";var t=Md(),{Buffer:n}=CC()||{},{AbstractSublevelIterator:i,AbstractSublevelKeyIterator:a,AbstractSublevelValueIterator:s}=Qde(),o=Symbol("prefix"),c=Symbol("upperBound"),l=Symbol("prefixRange"),d=Symbol("parent"),u=Symbol("unfix"),f=new TextEncoder,p={separator:"!"};e.exports=function({AbstractLevel:E}){class _ extends E{static defaults(D){if(typeof D=="string")throw new t("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(D&&D.open)throw new t("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return D==null?p:D.separator?D:{...D,separator:"!"}}constructor(D,M,C){let{separator:z,manifest:L,...B}=_.defaults(C);M=w(M,z);let W=z.charCodeAt(0)+1,ee=D[d]||D;if(!f.encode(M).every(S=>S>W&&S<127))throw new t(`Prefix must use bytes > ${W} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(h(ee,L),B);let R=(D.prefix||"")+z+M+z,$=R.slice(0,-1)+String.fromCharCode(W);this[d]=ee,this[o]=new y(R),this[c]=new y($),this[u]=new v,this.nextTick=ee.nextTick}prefixKey(D,M){if(M==="utf8")return this[o].utf8+D;if(D.byteLength===0)return this[o][M];if(M==="view"){let C=this[o].view,z=new Uint8Array(C.byteLength+D.byteLength);return z.set(C,0),z.set(D,C.byteLength),z}else{let C=this[o].buffer;return n.concat([C,D],C.byteLength+D.byteLength)}}[l](D,M){D.gte!==void 0?D.gte=this.prefixKey(D.gte,M):D.gt!==void 0?D.gt=this.prefixKey(D.gt,M):D.gte=this[o][M],D.lte!==void 0?D.lte=this.prefixKey(D.lte,M):D.lt!==void 0?D.lt=this.prefixKey(D.lt,M):D.lte=this[c][M]}get prefix(){return this[o].utf8}get db(){return this[d]}_open(D,M){this[d].open({passive:!0},M)}_put(D,M,C,z){this[d].put(D,M,C,z)}_get(D,M,C){this[d].get(D,M,C)}_getMany(D,M,C){this[d].getMany(D,M,C)}_del(D,M,C){this[d].del(D,M,C)}_batch(D,M,C){this[d].batch(D,M,C)}_clear(D,M){this[l](D,D.keyEncoding),this[d].clear(D,M)}_iterator(D){this[l](D,D.keyEncoding);let M=this[d].iterator(D),C=this[u].get(this[o].utf8.length,D.keyEncoding);return new i(this,D,M,C)}_keys(D){this[l](D,D.keyEncoding);let M=this[d].keys(D),C=this[u].get(this[o].utf8.length,D.keyEncoding);return new a(this,D,M,C)}_values(D){this[l](D,D.keyEncoding);let M=this[d].values(D);return new s(this,D,M)}}return{AbstractSublevel:_}};var h=function(E,_){return{...E.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},..._,encodings:{utf8:m(E,"utf8"),buffer:m(E,"buffer"),view:m(E,"view")}}},m=function(E,_){return E.supports.encodings[_]?E.keyEncoding(_).name===_:!1},y=class{constructor(E){this.utf8=E,this.view=f.encode(E),this.buffer=n?n.from(this.view.buffer,0,this.view.byteLength):{}}},v=class{constructor(){this.cache=new Map}get(E,_){let A=this.cache.get(_);return A===void 0&&(_==="view"?A=(function(D,M){return M.subarray(D)}).bind(null,E):A=(function(D,M){return M.slice(D)}).bind(null,E),this.cache.set(_,A)),A}},w=function(E,_){let A=0,D=E.length;for(;A<D&&E[A]===_;)A++;for(;D>A&&E[D-1]===_;)D--;return E.slice(A,D)}}),Q9=Zt(r=>{"use strict";var{supports:e}=Lde(),{Transcoder:t}=Gde(),{EventEmitter:n}=Hde(),{fromCallback:i}=dE(),a=Md(),{AbstractIterator:s}=fh(),{DefaultKeyIterator:o,DefaultValueIterator:c}=Wde(),{DeferredIterator:l,DeferredKeyIterator:d,DeferredValueIterator:u}=Jde(),{DefaultChainedBatch:f}=Zde(),{getCallback:p,getOptions:h}=$C(),m=Yde(),y=Symbol("promise"),v=Symbol("landed"),w=Symbol("resources"),E=Symbol("closeResources"),_=Symbol("operations"),A=Symbol("undefer"),D=Symbol("deferOpen"),M=Symbol("options"),C=Symbol("status"),z=Symbol("defaultOptions"),L=Symbol("transcoder"),B=Symbol("keyEncoding"),W=Symbol("valueEncoding"),ee=()=>{},R=class extends n{constructor(P,k){if(super(),typeof P!="object"||P===null)throw new TypeError("The first argument 'manifest' must be an object");k=h(k);let{keyEncoding:I,valueEncoding:j,passive:q,...H}=k;this[w]=new Set,this[_]=[],this[D]=!0,this[M]=H,this[C]="opening",this.supports=e(P,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:P.snapshots!==!1,permanence:P.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:P.encodings||{},events:Object.assign({},P.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[L]=new t(x(this)),this[B]=this[L].encoding(I||"utf8"),this[W]=this[L].encoding(j||"utf8");for(let J of this[L].encodings())this.supports.encodings[J.commonName]||(this.supports.encodings[J.commonName]=!0);this[z]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[B].commonName,valueEncoding:this[W].commonName}),key:Object.freeze({keyEncoding:this[B].commonName})},this.nextTick(()=>{this[D]&&this.open({passive:!1},ee)})}get status(){return this[C]}keyEncoding(P){return this[L].encoding(P??this[B])}valueEncoding(P){return this[L].encoding(P??this[W])}open(P,k){k=p(P,k),k=i(k,y),P={...this[M],...h(P)},P.createIfMissing=P.createIfMissing!==!1,P.errorIfExists=!!P.errorIfExists;let I=j=>{this[C]==="closing"||this[C]==="opening"?this.once(v,j?()=>I(j):I):this[C]!=="open"?k(new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:j})):k()};return P.passive?this[C]==="opening"?this.once(v,I):this.nextTick(I):this[C]==="closed"||this[D]?(this[D]=!1,this[C]="opening",this.emit("opening"),this._open(P,j=>{if(j){this[C]="closed",this[E](()=>{this.emit(v),I(j)}),this[A]();return}this[C]="open",this[A](),this.emit(v),this[C]==="open"&&this.emit("open"),this[C]==="open"&&this.emit("ready"),I()})):this[C]==="open"?this.nextTick(I):this.once(v,()=>this.open(P,k)),k[y]}_open(P,k){this.nextTick(k)}close(P){P=i(P,y);let k=I=>{this[C]==="opening"||this[C]==="closing"?this.once(v,I?k(I):k):this[C]!=="closed"?P(new a("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:I})):P()};if(this[C]==="open"){this[C]="closing",this.emit("closing");let I=j=>{this[C]="open",this[A](),this.emit(v),k(j)};this[E](()=>{this._close(j=>{if(j)return I(j);this[C]="closed",this[A](),this.emit(v),this[C]==="closed"&&this.emit("closed"),k()})})}else this[C]==="closed"?this.nextTick(k):this.once(v,()=>this.close(P));return P[y]}[E](P){if(this[w].size===0)return this.nextTick(P);let k=this[w].size,I=!0,j=()=>{--k===0&&(I?this.nextTick(P):P())};for(let q of this[w])q.close(j);I=!1,this[w].clear()}_close(P){this.nextTick(P)}get(P,k,I){if(I=p(k,I),I=i(I,y),k=h(k,this[z].entry),this[C]==="opening")return this.defer(()=>this.get(P,k,I)),I[y];if(S(this,I))return I[y];let j=this._checkKey(P);if(j)return this.nextTick(I,j),I[y];let q=this.keyEncoding(k.keyEncoding),H=this.valueEncoding(k.valueEncoding),J=q.format,V=H.format;return(k.keyEncoding!==J||k.valueEncoding!==V)&&(k=Object.assign({},k,{keyEncoding:J,valueEncoding:V})),this._get(this.prefixKey(q.encode(P),J),k,(Z,F)=>{if(Z)return(Z.code==="LEVEL_NOT_FOUND"||Z.notFound||/NotFound/i.test(Z))&&(Z.code||(Z.code="LEVEL_NOT_FOUND"),Z.notFound||(Z.notFound=!0),Z.status||(Z.status=404)),I(Z);try{F=H.decode(F)}catch(X){return I(new a("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:X}))}I(null,F)}),I[y]}_get(P,k,I){this.nextTick(I,new Error("NotFound"))}getMany(P,k,I){if(I=p(k,I),I=i(I,y),k=h(k,this[z].entry),this[C]==="opening")return this.defer(()=>this.getMany(P,k,I)),I[y];if(S(this,I))return I[y];if(!Array.isArray(P))return this.nextTick(I,new TypeError("The first argument 'keys' must be an array")),I[y];if(P.length===0)return this.nextTick(I,null,[]),I[y];let j=this.keyEncoding(k.keyEncoding),q=this.valueEncoding(k.valueEncoding),H=j.format,J=q.format;(k.keyEncoding!==H||k.valueEncoding!==J)&&(k=Object.assign({},k,{keyEncoding:H,valueEncoding:J}));let V=new Array(P.length);for(let Z=0;Z<P.length;Z++){let F=P[Z],X=this._checkKey(F);if(X)return this.nextTick(I,X),I[y];V[Z]=this.prefixKey(j.encode(F),H)}return this._getMany(V,k,(Z,F)=>{if(Z)return I(Z);try{for(let X=0;X<F.length;X++)F[X]!==void 0&&(F[X]=q.decode(F[X]))}catch(X){return I(new a(`Could not decode one or more of ${F.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:X}))}I(null,F)}),I[y]}_getMany(P,k,I){this.nextTick(I,null,new Array(P.length).fill(void 0))}put(P,k,I,j){if(j=p(I,j),j=i(j,y),I=h(I,this[z].entry),this[C]==="opening")return this.defer(()=>this.put(P,k,I,j)),j[y];if(S(this,j))return j[y];let q=this._checkKey(P)||this._checkValue(k);if(q)return this.nextTick(j,q),j[y];let H=this.keyEncoding(I.keyEncoding),J=this.valueEncoding(I.valueEncoding),V=H.format,Z=J.format;(I.keyEncoding!==V||I.valueEncoding!==Z)&&(I=Object.assign({},I,{keyEncoding:V,valueEncoding:Z}));let F=this.prefixKey(H.encode(P),V),X=J.encode(k);return this._put(F,X,I,ie=>{if(ie)return j(ie);this.emit("put",P,k),j()}),j[y]}_put(P,k,I,j){this.nextTick(j)}del(P,k,I){if(I=p(k,I),I=i(I,y),k=h(k,this[z].key),this[C]==="opening")return this.defer(()=>this.del(P,k,I)),I[y];if(S(this,I))return I[y];let j=this._checkKey(P);if(j)return this.nextTick(I,j),I[y];let q=this.keyEncoding(k.keyEncoding),H=q.format;return k.keyEncoding!==H&&(k=Object.assign({},k,{keyEncoding:H})),this._del(this.prefixKey(q.encode(P),H),k,J=>{if(J)return I(J);this.emit("del",P),I()}),I[y]}_del(P,k,I){this.nextTick(I)}batch(P,k,I){if(!arguments.length){if(this[C]==="opening")return new f(this);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof P=="function"?I=P:I=p(k,I),I=i(I,y),k=h(k,this[z].empty),this[C]==="opening")return this.defer(()=>this.batch(P,k,I)),I[y];if(S(this,I))return I[y];if(!Array.isArray(P))return this.nextTick(I,new TypeError("The first argument 'operations' must be an array")),I[y];if(P.length===0)return this.nextTick(I),I[y];let j=new Array(P.length),{keyEncoding:q,valueEncoding:H,...J}=k;for(let V=0;V<P.length;V++){if(typeof P[V]!="object"||P[V]===null)return this.nextTick(I,new TypeError("A batch operation must be an object")),I[y];let Z=Object.assign({},P[V]);if(Z.type!=="put"&&Z.type!=="del")return this.nextTick(I,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),I[y];let F=this._checkKey(Z.key);if(F)return this.nextTick(I,F),I[y];let X=Z.sublevel!=null?Z.sublevel:this,ie=X.keyEncoding(Z.keyEncoding||q),se=ie.format;if(Z.key=X.prefixKey(ie.encode(Z.key),se),Z.keyEncoding=se,Z.type==="put"){let Y=this._checkValue(Z.value);if(Y)return this.nextTick(I,Y),I[y];let de=X.valueEncoding(Z.valueEncoding||H);Z.value=de.encode(Z.value),Z.valueEncoding=de.format}X!==this&&(Z.sublevel=null),j[V]=Z}return this._batch(j,J,V=>{if(V)return I(V);this.emit("batch",P),I()}),I[y]}_batch(P,k,I){this.nextTick(I)}sublevel(P,k){return this._sublevel(P,$.defaults(k))}_sublevel(P,k){return new $(this,P,k)}prefixKey(P,k){return P}clear(P,k){if(k=p(P,k),k=i(k,y),P=h(P,this[z].empty),this[C]==="opening")return this.defer(()=>this.clear(P,k)),k[y];if(S(this,k))return k[y];let I=P,j=this.keyEncoding(P.keyEncoding);return P=m(P,j),P.keyEncoding=j.format,P.limit===0?this.nextTick(k):this._clear(P,q=>{if(q)return k(q);this.emit("clear",I),k()}),k[y]}_clear(P,k){this.nextTick(k)}iterator(P){let k=this.keyEncoding(P&&P.keyEncoding),I=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,k),P.keys=P.keys!==!1,P.values=P.values!==!1,P[s.keyEncoding]=k,P[s.valueEncoding]=I,P.keyEncoding=k.format,P.valueEncoding=I.format,this[C]==="opening")return new l(this,P);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(P)}_iterator(P){return new s(this,P)}keys(P){let k=this.keyEncoding(P&&P.keyEncoding),I=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,k),P[s.keyEncoding]=k,P[s.valueEncoding]=I,P.keyEncoding=k.format,P.valueEncoding=I.format,this[C]==="opening")return new d(this,P);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(P)}_keys(P){return new o(this,P)}values(P){let k=this.keyEncoding(P&&P.keyEncoding),I=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,k),P[s.keyEncoding]=k,P[s.valueEncoding]=I,P.keyEncoding=k.format,P.valueEncoding=I.format,this[C]==="opening")return new u(this,P);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(P)}_values(P){return new c(this,P)}defer(P){if(typeof P!="function")throw new TypeError("The first argument must be a function");this[_].push(P)}[A](){if(this[_].length===0)return;let P=this[_];this[_]=[];for(let k of P)k()}attachResource(P){if(typeof P!="object"||P===null||typeof P.close!="function")throw new TypeError("The first argument must be a resource object");this[w].add(P)}detachResource(P){this[w].delete(P)}_chainedBatch(){return new f(this)}_checkKey(P){if(P==null)return new a("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(P){if(P==null)return new a("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};R.prototype.nextTick=Xde();var{AbstractSublevel:$}=ele()({AbstractLevel:R});r.AbstractLevel=R,r.AbstractSublevel=$;var S=function(P,k){return P[C]!=="open"?(P.nextTick(k,new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},x=function(P){return Object.keys(P.supports.encodings).filter(k=>!!P.supports.encodings[k])}}),xz=Zt(r=>{"use strict";r.AbstractLevel=Q9().AbstractLevel,r.AbstractSublevel=Q9().AbstractSublevel,r.AbstractIterator=fh().AbstractIterator,r.AbstractKeyIterator=fh().AbstractKeyIterator,r.AbstractValueIterator=fh().AbstractValueIterator,r.AbstractChainedBatch=bz().AbstractChainedBatch}),tle=Zt((r,e)=>{e.exports=n;var t=Pz();function n(i,a,s){if(typeof a!="number")throw new Error("second argument must be a Number");let o,c,l,d,u,f=!0,p;Array.isArray(i)?(o=[],l=c=i.length):(d=Object.keys(i),o={},l=c=d.length);function h(y){function v(){s&&s(y,o),s=null}f?t(v):v()}function m(y,v,w){if(o[y]=w,v&&(u=!0),--l===0||v)h(v);else if(!u&&p<c){let E;d?(E=d[p],p+=1,i[E](function(_,A){m(E,_,A)})):(E=p,p+=1,i[E](function(_,A){m(E,_,A)}))}}p=a,l?d?d.some(function(y,v){return i[y](function(w,E){m(y,w,E)}),v===a-1}):i.some(function(y,v){return y(function(w,E){m(v,w,E)}),v===a-1}):h(null),f=!1}}),Ez=Zt((r,e)=>{"use strict";e.exports=function(t){let n=t.gte!==void 0?t.gte:t.gt!==void 0?t.gt:void 0,i=t.lte!==void 0?t.lte:t.lt!==void 0?t.lt:void 0,a=t.gte===void 0,s=t.lte===void 0;return n!==void 0&&i!==void 0?IDBKeyRange.bound(n,i,a,s):n!==void 0?IDBKeyRange.lowerBound(n,a):i!==void 0?IDBKeyRange.upperBound(i,s):null}}),Sz=Zt((r,e)=>{"use strict";var t=new TextEncoder;e.exports=function(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):t.encode(n)}}),rle=Zt(r=>{"use strict";var{AbstractIterator:e}=xz(),t=Ez(),n=Sz(),i=Symbol("cache"),a=Symbol("finished"),s=Symbol("options"),o=Symbol("currentOptions"),c=Symbol("position"),l=Symbol("location"),d=Symbol("first"),u={},f=class extends e{constructor(h,m,y){super(h,y),this[i]=[],this[a]=this.limit===0,this[s]=y,this[o]={...y},this[c]=void 0,this[l]=m,this[d]=!0}_nextv(h,m,y){if(this[d]=!1,this[a])return this.nextTick(y,null,[]);if(this[i].length>0)return h=Math.min(h,this[i].length),this.nextTick(y,null,this[i].splice(0,h));this[c]!==void 0&&(this[s].reverse?(this[o].lt=this[c],this[o].lte=void 0):(this[o].gt=this[c],this[o].gte=void 0));let v;try{v=t(this[o])}catch{return this[a]=!0,this.nextTick(y,null,[])}let w=this.db.db.transaction([this[l]],"readonly"),E=w.objectStore(this[l]),_=[];if(this[s].reverse){let A=!this[s].values&&E.openKeyCursor?"openKeyCursor":"openCursor";E[A](v,"prev").onsuccess=D=>{let M=D.target.result;if(M){let{key:C,value:z}=M;this[c]=C,_.push([this[s].keys&&C!==void 0?n(C):void 0,this[s].values&&z!==void 0?n(z):void 0]),_.length<h?M.continue():p(w)}else this[a]=!0}}else{let A,D,M=()=>{if(A===void 0||D===void 0)return;let C=Math.max(A.length,D.length);C===0||h===1/0?this[a]=!0:this[c]=A[C-1],_.length=C;for(let z=0;z<C;z++){let L=A[z],B=D[z];_[z]=[this[s].keys&&L!==void 0?n(L):void 0,this[s].values&&B!==void 0?n(B):void 0]}p(w)};this[s].keys||h<1/0?E.getAllKeys(v,h<1/0?h:void 0).onsuccess=C=>{A=C.target.result,M()}:(A=[],this.nextTick(M)),this[s].values?E.getAll(v,h<1/0?h:void 0).onsuccess=C=>{D=C.target.result,M()}:(D=[],this.nextTick(M))}w.onabort=()=>{y(w.error||new Error("aborted by user")),y=null},w.oncomplete=()=>{y(null,_),y=null}}_next(h){if(this[i].length>0){let[m,y]=this[i].shift();this.nextTick(h,null,m,y)}else if(this[a])this.nextTick(h);else{let m=Math.min(100,this.limit-this.count);this[d]&&(this[d]=!1,m=1),this._nextv(m,u,(y,v)=>{if(y)return h(y);this[i]=v,this._next(h)})}}_all(h,m){this[d]=!1;let y=this[i].splice(0,this[i].length),v=this.limit-this.count-y.length;if(v<=0)return this.nextTick(m,null,y);this._nextv(v,u,(w,E)=>{if(w)return m(w);y.length>0&&(E=y.concat(E)),m(null,E)})}_seek(h,m){this[d]=!0,this[i]=[],this[a]=!1,this[c]=void 0,this[o]={...this[s]};let y;try{y=t(this[s])}catch{this[a]=!0;return}y!==null&&!y.includes(h)?this[a]=!0:this[s].reverse?this[o].lte=h:this[o].gte=h}};r.Iterator=f;function p(h){typeof h.commit=="function"&&h.commit()}}),nle=Zt((r,e)=>{"use strict";e.exports=function(t,n,i,a,s){if(a.limit===0)return t.nextTick(s);let o=t.db.transaction([n],"readwrite"),c=o.objectStore(n),l=0;o.oncomplete=function(){s()},o.onabort=function(){s(o.error||new Error("aborted by user"))};let d=c.openKeyCursor?"openKeyCursor":"openCursor",u=a.reverse?"prev":"next";c[d](i,u).onsuccess=function(f){let p=f.target.result;p&&(c.delete(p.key).onsuccess=function(){(a.limit<=0||++l<a.limit)&&p.continue()})}}}),ile=Zt(r=>{"use strict";var{AbstractLevel:e}=xz(),t=Md(),n=tle(),{fromCallback:i}=dE(),{Iterator:a}=rle(),s=Sz(),o=nle(),c=Ez(),l="level-js-",d=Symbol("idb"),u=Symbol("namePrefix"),f=Symbol("location"),p=Symbol("version"),h=Symbol("store"),m=Symbol("onComplete"),y=Symbol("promise"),v=class extends e{constructor(w,E,_){if(typeof E=="function"||typeof _=="function")throw new t("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:A,version:D,...M}=E||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},M),typeof w!="string")throw new Error("constructor requires a location string argument");this[f]=w,this[u]=A??l,this[p]=parseInt(D||1,10),this[d]=null}get location(){return this[f]}get namePrefix(){return this[u]}get version(){return this[p]}get db(){return this[d]}get type(){return"browser-level"}_open(w,E){let _=indexedDB.open(this[u]+this[f],this[p]);_.onerror=function(){E(_.error||new Error("unknown error"))},_.onsuccess=()=>{this[d]=_.result,E()},_.onupgradeneeded=A=>{let D=A.target.result;D.objectStoreNames.contains(this[f])||D.createObjectStore(this[f])}}[h](w){return this[d].transaction([this[f]],w).objectStore(this[f])}[m](w,E){let _=w.transaction;_.onabort=function(){E(_.error||new Error("aborted by user"))},_.oncomplete=function(){E(null,w.result)}}_get(w,E,_){let A=this[h]("readonly"),D;try{D=A.get(w)}catch(M){return this.nextTick(_,M)}this[m](D,function(M,C){if(M)return _(M);if(C===void 0)return _(new t("Entry not found",{code:"LEVEL_NOT_FOUND"}));_(null,s(C))})}_getMany(w,E,_){let A=this[h]("readonly"),D=w.map(M=>C=>{let z;try{z=A.get(M)}catch(L){return C(L)}z.onsuccess=()=>{let L=z.result;C(null,L===void 0?L:s(L))},z.onerror=L=>{L.stopPropagation(),C(z.error)}});n(D,16,_)}_del(w,E,_){let A=this[h]("readwrite"),D;try{D=A.delete(w)}catch(M){return this.nextTick(_,M)}this[m](D,_)}_put(w,E,_,A){let D=this[h]("readwrite"),M;try{M=D.put(E,w)}catch(C){return this.nextTick(A,C)}this[m](M,A)}_iterator(w){return new a(this,this[f],w)}_batch(w,E,_){let A=this[h]("readwrite"),D=A.transaction,M=0,C;D.onabort=function(){_(C||D.error||new Error("aborted by user"))},D.oncomplete=function(){_()};function z(){let L=w[M++],B=L.key,W;try{W=L.type==="del"?A.delete(B):A.put(L.value,B)}catch(ee){C=ee,D.abort();return}M<w.length?W.onsuccess=z:typeof D.commit=="function"&&D.commit()}z()}_clear(w,E){let _,A;try{_=c(w)}catch{return this.nextTick(E)}if(w.limit>=0)return o(this,this[f],_,w,E);try{let D=this[h]("readwrite");A=_?D.delete(_):D.clear()}catch(D){return this.nextTick(E,D)}this[m](A,E)}_close(w){this[d].close(),this.nextTick(w)}};v.destroy=function(w,E,_){typeof E=="function"&&(_=E,E=l),_=i(_,y);let A=indexedDB.deleteDatabase(E+w);return A.onsuccess=function(){_()},A.onerror=function(D){_(D)},_[y]},r.BrowserLevel=v}),kz=Zt(r=>{r.Level=ile().BrowserLevel}),sle=Zt((r,e)=>{(function(t,n){typeof r=="object"&&typeof e<"u"?n(r):typeof define=="function"&&define.amd?define(["exports"],n):n(t.URI=t.URI||{})})(r,function(t){"use strict";function n(){for(var Q=arguments.length,oe=Array(Q),ae=0;ae<Q;ae++)oe[ae]=arguments[ae];if(oe.length>1){oe[0]=oe[0].slice(0,-1);for(var be=oe.length-1,Pe=1;Pe<be;++Pe)oe[Pe]=oe[Pe].slice(1,-1);return oe[be]=oe[be].slice(1),oe.join("")}else return oe[0]}function i(Q){return"(?:"+Q+")"}function a(Q){return Q===void 0?"undefined":Q===null?"null":Object.prototype.toString.call(Q).split(" ").pop().split("]").shift().toLowerCase()}function s(Q){return Q.toUpperCase()}function o(Q){return Q!=null?Q instanceof Array?Q:typeof Q.length!="number"||Q.split||Q.setInterval||Q.call?[Q]:Array.prototype.slice.call(Q):[]}function c(Q,oe){var ae=Q;if(oe)for(var be in oe)ae[be]=oe[be];return ae}function l(Q){var oe="[A-Za-z]",ae="[\\x0D]",be="[0-9]",Pe="[\\x22]",Ge=n(be,"[A-Fa-f]"),Bt="[\\x0A]",wr="[\\x20]",Xr=i(i("%[EFef]"+Ge+"%"+Ge+Ge+"%"+Ge+Ge)+"|"+i("%[89A-Fa-f]"+Ge+"%"+Ge+Ge)+"|"+i("%"+Ge+Ge)),Qr="[\\:\\/\\?\\#\\[\\]\\@]",dr="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",_n=n(Qr,dr),Yn=Q?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",gn=Q?"[\\uE000-\\uF8FF]":"[]",Tr=n(oe,be,"[\\-\\.\\_\\~]",Yn),Sr=i(oe+n(oe,be,"[\\+\\-\\.]")+"*"),os=i(i(Xr+"|"+n(Tr,dr,"[\\:]"))+"*"),jg=i(i("25[0-5]")+"|"+i("2[0-4]"+be)+"|"+i("1"+be+be)+"|"+i("[1-9]"+be)+"|"+be),Xs=i(i("25[0-5]")+"|"+i("2[0-4]"+be)+"|"+i("1"+be+be)+"|"+i("0?[1-9]"+be)+"|0?0?"+be),Ga=i(Xs+"\\."+Xs+"\\."+Xs+"\\."+Xs),Ir=i(Ge+"{1,4}"),Po=i(i(Ir+"\\:"+Ir)+"|"+Ga),ra=i(i(Ir+"\\:")+"{6}"+Po),Nd=i("\\:\\:"+i(Ir+"\\:")+"{5}"+Po),qf=i(i(Ir)+"?\\:\\:"+i(Ir+"\\:")+"{4}"+Po),$c=i(i(i(Ir+"\\:")+"{0,1}"+Ir)+"?\\:\\:"+i(Ir+"\\:")+"{3}"+Po),Ub=i(i(i(Ir+"\\:")+"{0,2}"+Ir)+"?\\:\\:"+i(Ir+"\\:")+"{2}"+Po),Nb=i(i(i(Ir+"\\:")+"{0,3}"+Ir)+"?\\:\\:"+Ir+"\\:"+Po),Fh=i(i(i(Ir+"\\:")+"{0,4}"+Ir)+"?\\:\\:"+Po),Gh=i(i(i(Ir+"\\:")+"{0,5}"+Ir)+"?\\:\\:"+Ir),Hh=i(i(i(Ir+"\\:")+"{0,6}"+Ir)+"?\\:\\:"),zf=i([ra,Nd,qf,$c,Ub,Nb,Fh,Gh,Hh].join("|")),Vh=i(i(Tr+"|"+Xr)+"+"),Wh=i(zf+"\\%25"+Vh),IV=i(zf+i("\\%25|\\%(?!"+Ge+"{2})")+Vh),DV=i("[vV]"+Ge+"+\\."+n(Tr,dr,"[\\:]")+"+"),RV=i("\\["+i(IV+"|"+zf+"|"+DV)+"\\]"),g5=i(i(Xr+"|"+n(Tr,dr))+"*"),Mg=i(RV+"|"+Ga+"(?!"+g5+")|"+g5),Kg=i(be+"*"),w5=i(i(os+"@")+"?"+Mg+i("\\:"+Kg)+"?"),Ug=i(Xr+"|"+n(Tr,dr,"[\\:\\@]")),CV=i(Ug+"*"),v5=i(Ug+"+"),$V=i(i(Xr+"|"+n(Tr,dr,"[\\@]"))+"+"),Ld=i(i("\\/"+CV)+"*"),Jh=i("\\/"+i(v5+Ld)+"?"),SS=i($V+Ld),Lb=i(v5+Ld),Zh="(?!"+Ug+")",Hwe=i(Ld+"|"+Jh+"|"+SS+"|"+Lb+"|"+Zh),Yh=i(i(Ug+"|"+n("[\\/\\?]",gn))+"*"),Ng=i(i(Ug+"|[\\/\\?]")+"*"),b5=i(i("\\/\\/"+w5+Ld)+"|"+Jh+"|"+Lb+"|"+Zh),BV=i(Sr+"\\:"+b5+i("\\?"+Yh)+"?"+i("\\#"+Ng)+"?"),OV=i(i("\\/\\/"+w5+Ld)+"|"+Jh+"|"+SS+"|"+Zh),jV=i(OV+i("\\?"+Yh)+"?"+i("\\#"+Ng)+"?"),Vwe=i(BV+"|"+jV),Wwe=i(Sr+"\\:"+b5+i("\\?"+Yh)+"?"),Jwe="^("+Sr+")\\:"+i(i("\\/\\/("+i("("+os+")@")+"?("+Mg+")"+i("\\:("+Kg+")")+"?)")+"?("+Ld+"|"+Jh+"|"+Lb+"|"+Zh+")")+i("\\?("+Yh+")")+"?"+i("\\#("+Ng+")")+"?$",Zwe="^(){0}"+i(i("\\/\\/("+i("("+os+")@")+"?("+Mg+")"+i("\\:("+Kg+")")+"?)")+"?("+Ld+"|"+Jh+"|"+SS+"|"+Zh+")")+i("\\?("+Yh+")")+"?"+i("\\#("+Ng+")")+"?$",Ywe="^("+Sr+")\\:"+i(i("\\/\\/("+i("("+os+")@")+"?("+Mg+")"+i("\\:("+Kg+")")+"?)")+"?("+Ld+"|"+Jh+"|"+Lb+"|"+Zh+")")+i("\\?("+Yh+")")+"?$",Xwe="^"+i("\\#("+Ng+")")+"?$",Qwe="^"+i("("+os+")@")+"?("+Mg+")"+i("\\:("+Kg+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",oe,be,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",Tr,dr),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",Tr,dr),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",Tr,dr),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",Tr,dr),"g"),NOT_QUERY:new RegExp(n("[^\\%]",Tr,dr,"[\\:\\@\\/\\?]",gn),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",Tr,dr,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",Tr,dr),"g"),UNRESERVED:new RegExp(Tr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",Tr,_n),"g"),PCT_ENCODED:new RegExp(Xr,"g"),IPV4ADDRESS:new RegExp("^("+Ga+")$"),IPV6ADDRESS:new RegExp("^\\[?("+zf+")"+i(i("\\%25|\\%(?!"+Ge+"{2})")+"("+Vh+")")+"?\\]?$")}}var d=l(!1),u=l(!0),f=function(){function Q(oe,ae){var be=[],Pe=!0,Ge=!1,Bt=void 0;try{for(var wr=oe[Symbol.iterator](),Xr;!(Pe=(Xr=wr.next()).done)&&(be.push(Xr.value),!(ae&&be.length===ae));Pe=!0);}catch(Qr){Ge=!0,Bt=Qr}finally{try{!Pe&&wr.return&&wr.return()}finally{if(Ge)throw Bt}}return be}return function(oe,ae){if(Array.isArray(oe))return oe;if(Symbol.iterator in Object(oe))return Q(oe,ae);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),p=function(Q){if(Array.isArray(Q)){for(var oe=0,ae=Array(Q.length);oe<Q.length;oe++)ae[oe]=Q[oe];return ae}else return Array.from(Q)},h=2147483647,m=36,y=1,v=26,w=38,E=700,_=72,A=128,D="-",M=/^xn--/,C=/[^\0-\x7E]/,z=/[\x2E\u3002\uFF0E\uFF61]/g,L={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},B=m-y,W=Math.floor,ee=String.fromCharCode;function R(Q){throw new RangeError(L[Q])}function $(Q,oe){for(var ae=[],be=Q.length;be--;)ae[be]=oe(Q[be]);return ae}function S(Q,oe){var ae=Q.split("@"),be="";ae.length>1&&(be=ae[0]+"@",Q=ae[1]),Q=Q.replace(z,".");var Pe=Q.split("."),Ge=$(Pe,oe).join(".");return be+Ge}function x(Q){for(var oe=[],ae=0,be=Q.length;ae<be;){var Pe=Q.charCodeAt(ae++);if(Pe>=55296&&Pe<=56319&&ae<be){var Ge=Q.charCodeAt(ae++);(Ge&64512)==56320?oe.push(((Pe&1023)<<10)+(Ge&1023)+65536):(oe.push(Pe),ae--)}else oe.push(Pe)}return oe}var P=function(Q){return String.fromCodePoint.apply(String,p(Q))},k=function(Q){return Q-48<10?Q-22:Q-65<26?Q-65:Q-97<26?Q-97:m},I=function(Q,oe){return Q+22+75*(Q<26)-((oe!=0)<<5)},j=function(Q,oe,ae){var be=0;for(Q=ae?W(Q/E):Q>>1,Q+=W(Q/oe);Q>B*v>>1;be+=m)Q=W(Q/B);return W(be+(B+1)*Q/(Q+w))},q=function(Q){var oe=[],ae=Q.length,be=0,Pe=A,Ge=_,Bt=Q.lastIndexOf(D);Bt<0&&(Bt=0);for(var wr=0;wr<Bt;++wr)Q.charCodeAt(wr)>=128&&R("not-basic"),oe.push(Q.charCodeAt(wr));for(var Xr=Bt>0?Bt+1:0;Xr<ae;){for(var Qr=be,dr=1,_n=m;;_n+=m){Xr>=ae&&R("invalid-input");var Yn=k(Q.charCodeAt(Xr++));(Yn>=m||Yn>W((h-be)/dr))&&R("overflow"),be+=Yn*dr;var gn=_n<=Ge?y:_n>=Ge+v?v:_n-Ge;if(Yn<gn)break;var Tr=m-gn;dr>W(h/Tr)&&R("overflow"),dr*=Tr}var Sr=oe.length+1;Ge=j(be-Qr,Sr,Qr==0),W(be/Sr)>h-Pe&&R("overflow"),Pe+=W(be/Sr),be%=Sr,oe.splice(be++,0,Pe)}return String.fromCodePoint.apply(String,oe)},H=function(Q){var oe=[];Q=x(Q);var ae=Q.length,be=A,Pe=0,Ge=_,Bt=!0,wr=!1,Xr=void 0;try{for(var Qr=Q[Symbol.iterator](),dr;!(Bt=(dr=Qr.next()).done);Bt=!0){var _n=dr.value;_n<128&&oe.push(ee(_n))}}catch(Wh){wr=!0,Xr=Wh}finally{try{!Bt&&Qr.return&&Qr.return()}finally{if(wr)throw Xr}}var Yn=oe.length,gn=Yn;for(Yn&&oe.push(D);gn<ae;){var Tr=h,Sr=!0,os=!1,jg=void 0;try{for(var Xs=Q[Symbol.iterator](),Ga;!(Sr=(Ga=Xs.next()).done);Sr=!0){var Ir=Ga.value;Ir>=be&&Ir<Tr&&(Tr=Ir)}}catch(Wh){os=!0,jg=Wh}finally{try{!Sr&&Xs.return&&Xs.return()}finally{if(os)throw jg}}var Po=gn+1;Tr-be>W((h-Pe)/Po)&&R("overflow"),Pe+=(Tr-be)*Po,be=Tr;var ra=!0,Nd=!1,qf=void 0;try{for(var $c=Q[Symbol.iterator](),Ub;!(ra=(Ub=$c.next()).done);ra=!0){var Nb=Ub.value;if(Nb<be&&++Pe>h&&R("overflow"),Nb==be){for(var Fh=Pe,Gh=m;;Gh+=m){var Hh=Gh<=Ge?y:Gh>=Ge+v?v:Gh-Ge;if(Fh<Hh)break;var zf=Fh-Hh,Vh=m-Hh;oe.push(ee(I(Hh+zf%Vh,0))),Fh=W(zf/Vh)}oe.push(ee(I(Fh,0))),Ge=j(Pe,Po,gn==Yn),Pe=0,++gn}}}catch(Wh){Nd=!0,qf=Wh}finally{try{!ra&&$c.return&&$c.return()}finally{if(Nd)throw qf}}++Pe,++be}return oe.join("")},J=function(Q){return S(Q,function(oe){return M.test(oe)?q(oe.slice(4).toLowerCase()):oe})},V=function(Q){return S(Q,function(oe){return C.test(oe)?"xn--"+H(oe):oe})},Z={version:"2.1.0",ucs2:{decode:x,encode:P},decode:q,encode:H,toASCII:V,toUnicode:J},F={};function X(Q){var oe=Q.charCodeAt(0),ae=void 0;return oe<16?ae="%0"+oe.toString(16).toUpperCase():oe<128?ae="%"+oe.toString(16).toUpperCase():oe<2048?ae="%"+(oe>>6|192).toString(16).toUpperCase()+"%"+(oe&63|128).toString(16).toUpperCase():ae="%"+(oe>>12|224).toString(16).toUpperCase()+"%"+(oe>>6&63|128).toString(16).toUpperCase()+"%"+(oe&63|128).toString(16).toUpperCase(),ae}function ie(Q){for(var oe="",ae=0,be=Q.length;ae<be;){var Pe=parseInt(Q.substr(ae+1,2),16);if(Pe<128)oe+=String.fromCharCode(Pe),ae+=3;else if(Pe>=194&&Pe<224){if(be-ae>=6){var Ge=parseInt(Q.substr(ae+4,2),16);oe+=String.fromCharCode((Pe&31)<<6|Ge&63)}else oe+=Q.substr(ae,6);ae+=6}else if(Pe>=224){if(be-ae>=9){var Bt=parseInt(Q.substr(ae+4,2),16),wr=parseInt(Q.substr(ae+7,2),16);oe+=String.fromCharCode((Pe&15)<<12|(Bt&63)<<6|wr&63)}else oe+=Q.substr(ae,9);ae+=9}else oe+=Q.substr(ae,3),ae+=3}return oe}function se(Q,oe){function ae(be){var Pe=ie(be);return Pe.match(oe.UNRESERVED)?Pe:be}return Q.scheme&&(Q.scheme=String(Q.scheme).replace(oe.PCT_ENCODED,ae).toLowerCase().replace(oe.NOT_SCHEME,"")),Q.userinfo!==void 0&&(Q.userinfo=String(Q.userinfo).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_USERINFO,X).replace(oe.PCT_ENCODED,s)),Q.host!==void 0&&(Q.host=String(Q.host).replace(oe.PCT_ENCODED,ae).toLowerCase().replace(oe.NOT_HOST,X).replace(oe.PCT_ENCODED,s)),Q.path!==void 0&&(Q.path=String(Q.path).replace(oe.PCT_ENCODED,ae).replace(Q.scheme?oe.NOT_PATH:oe.NOT_PATH_NOSCHEME,X).replace(oe.PCT_ENCODED,s)),Q.query!==void 0&&(Q.query=String(Q.query).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_QUERY,X).replace(oe.PCT_ENCODED,s)),Q.fragment!==void 0&&(Q.fragment=String(Q.fragment).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_FRAGMENT,X).replace(oe.PCT_ENCODED,s)),Q}function Y(Q){return Q.replace(/^0*(.*)/,"$1")||"0"}function de(Q,oe){var ae=Q.match(oe.IPV4ADDRESS)||[],be=f(ae,2),Pe=be[1];return Pe?Pe.split(".").map(Y).join("."):Q}function pe(Q,oe){var ae=Q.match(oe.IPV6ADDRESS)||[],be=f(ae,3),Pe=be[1],Ge=be[2];if(Pe){for(var Bt=Pe.toLowerCase().split("::").reverse(),wr=f(Bt,2),Xr=wr[0],Qr=wr[1],dr=Qr?Qr.split(":").map(Y):[],_n=Xr.split(":").map(Y),Yn=oe.IPV4ADDRESS.test(_n[_n.length-1]),gn=Yn?7:8,Tr=_n.length-gn,Sr=Array(gn),os=0;os<gn;++os)Sr[os]=dr[os]||_n[Tr+os]||"";Yn&&(Sr[gn-1]=de(Sr[gn-1],oe));var jg=Sr.reduce(function(ra,Nd,qf){if(!Nd||Nd==="0"){var $c=ra[ra.length-1];$c&&$c.index+$c.length===qf?$c.length++:ra.push({index:qf,length:1})}return ra},[]),Xs=jg.sort(function(ra,Nd){return Nd.length-ra.length})[0],Ga=void 0;if(Xs&&Xs.length>1){var Ir=Sr.slice(0,Xs.index),Po=Sr.slice(Xs.index+Xs.length);Ga=Ir.join(":")+"::"+Po.join(":")}else Ga=Sr.join(":");return Ge&&(Ga+="%"+Ge),Ga}else return Q}var le=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Se="".match(/(){0}/)[1]===void 0;function he(Q){var oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ae={},be=oe.iri!==!1?u:d;oe.reference==="suffix"&&(Q=(oe.scheme?oe.scheme+":":"")+"//"+Q);var Pe=Q.match(le);if(Pe){Se?(ae.scheme=Pe[1],ae.userinfo=Pe[3],ae.host=Pe[4],ae.port=parseInt(Pe[5],10),ae.path=Pe[6]||"",ae.query=Pe[7],ae.fragment=Pe[8],isNaN(ae.port)&&(ae.port=Pe[5])):(ae.scheme=Pe[1]||void 0,ae.userinfo=Q.indexOf("@")!==-1?Pe[3]:void 0,ae.host=Q.indexOf("//")!==-1?Pe[4]:void 0,ae.port=parseInt(Pe[5],10),ae.path=Pe[6]||"",ae.query=Q.indexOf("?")!==-1?Pe[7]:void 0,ae.fragment=Q.indexOf("#")!==-1?Pe[8]:void 0,isNaN(ae.port)&&(ae.port=Q.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?Pe[4]:void 0)),ae.host&&(ae.host=pe(de(ae.host,be),be)),ae.scheme===void 0&&ae.userinfo===void 0&&ae.host===void 0&&ae.port===void 0&&!ae.path&&ae.query===void 0?ae.reference="same-document":ae.scheme===void 0?ae.reference="relative":ae.fragment===void 0?ae.reference="absolute":ae.reference="uri",oe.reference&&oe.reference!=="suffix"&&oe.reference!==ae.reference&&(ae.error=ae.error||"URI is not a "+oe.reference+" reference.");var Ge=F[(oe.scheme||ae.scheme||"").toLowerCase()];if(!oe.unicodeSupport&&(!Ge||!Ge.unicodeSupport)){if(ae.host&&(oe.domainHost||Ge&&Ge.domainHost))try{ae.host=Z.toASCII(ae.host.replace(be.PCT_ENCODED,ie).toLowerCase())}catch(Bt){ae.error=ae.error||"Host's domain name can not be converted to ASCII via punycode: "+Bt}se(ae,d)}else se(ae,be);Ge&&Ge.parse&&Ge.parse(ae,oe)}else ae.error=ae.error||"URI can not be parsed.";return ae}function Te(Q,oe){var ae=oe.iri!==!1?u:d,be=[];return Q.userinfo!==void 0&&(be.push(Q.userinfo),be.push("@")),Q.host!==void 0&&be.push(pe(de(String(Q.host),ae),ae).replace(ae.IPV6ADDRESS,function(Pe,Ge,Bt){return"["+Ge+(Bt?"%25"+Bt:"")+"]"})),(typeof Q.port=="number"||typeof Q.port=="string")&&(be.push(":"),be.push(String(Q.port))),be.length?be.join(""):void 0}var Rt=/^\.\.?\//,ti=/^\/\.(\/|$)/,Kr=/^\/\.\.(\/|$)/,Ys=/^\/?(?:.|\n)*?(?=\/|$)/;function We(Q){for(var oe=[];Q.length;)if(Q.match(Rt))Q=Q.replace(Rt,"");else if(Q.match(ti))Q=Q.replace(ti,"/");else if(Q.match(Kr))Q=Q.replace(Kr,"/"),oe.pop();else if(Q==="."||Q==="..")Q="";else{var ae=Q.match(Ys);if(ae){var be=ae[0];Q=Q.slice(be.length),oe.push(be)}else throw new Error("Unexpected dot segment condition")}return oe.join("")}function nr(Q){var oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ae=oe.iri?u:d,be=[],Pe=F[(oe.scheme||Q.scheme||"").toLowerCase()];if(Pe&&Pe.serialize&&Pe.serialize(Q,oe),Q.host&&!ae.IPV6ADDRESS.test(Q.host)&&(oe.domainHost||Pe&&Pe.domainHost))try{Q.host=oe.iri?Z.toUnicode(Q.host):Z.toASCII(Q.host.replace(ae.PCT_ENCODED,ie).toLowerCase())}catch(wr){Q.error=Q.error||"Host's domain name can not be converted to "+(oe.iri?"Unicode":"ASCII")+" via punycode: "+wr}se(Q,ae),oe.reference!=="suffix"&&Q.scheme&&(be.push(Q.scheme),be.push(":"));var Ge=Te(Q,oe);if(Ge!==void 0&&(oe.reference!=="suffix"&&be.push("//"),be.push(Ge),Q.path&&Q.path.charAt(0)!=="/"&&be.push("/")),Q.path!==void 0){var Bt=Q.path;!oe.absolutePath&&(!Pe||!Pe.absolutePath)&&(Bt=We(Bt)),Ge===void 0&&(Bt=Bt.replace(/^\/\//,"/%2F")),be.push(Bt)}return Q.query!==void 0&&(be.push("?"),be.push(Q.query)),Q.fragment!==void 0&&(be.push("#"),be.push(Q.fragment)),be.join("")}function Ur(Q,oe){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},be=arguments[3],Pe={};return be||(Q=he(nr(Q,ae),ae),oe=he(nr(oe,ae),ae)),ae=ae||{},!ae.tolerant&&oe.scheme?(Pe.scheme=oe.scheme,Pe.userinfo=oe.userinfo,Pe.host=oe.host,Pe.port=oe.port,Pe.path=We(oe.path||""),Pe.query=oe.query):(oe.userinfo!==void 0||oe.host!==void 0||oe.port!==void 0?(Pe.userinfo=oe.userinfo,Pe.host=oe.host,Pe.port=oe.port,Pe.path=We(oe.path||""),Pe.query=oe.query):(oe.path?(oe.path.charAt(0)==="/"?Pe.path=We(oe.path):((Q.userinfo!==void 0||Q.host!==void 0||Q.port!==void 0)&&!Q.path?Pe.path="/"+oe.path:Q.path?Pe.path=Q.path.slice(0,Q.path.lastIndexOf("/")+1)+oe.path:Pe.path=oe.path,Pe.path=We(Pe.path)),Pe.query=oe.query):(Pe.path=Q.path,oe.query!==void 0?Pe.query=oe.query:Pe.query=Q.query),Pe.userinfo=Q.userinfo,Pe.host=Q.host,Pe.port=Q.port),Pe.scheme=Q.scheme),Pe.fragment=oe.fragment,Pe}function pr(Q,oe,ae){var be=c({scheme:"null"},ae);return nr(Ur(he(Q,be),he(oe,be),be,!0),be)}function Lt(Q,oe){return typeof Q=="string"?Q=nr(he(Q,oe),oe):a(Q)==="object"&&(Q=he(nr(Q,oe),oe)),Q}function T(Q,oe,ae){return typeof Q=="string"?Q=nr(he(Q,ae),ae):a(Q)==="object"&&(Q=nr(Q,ae)),typeof oe=="string"?oe=nr(he(oe,ae),ae):a(oe)==="object"&&(oe=nr(oe,ae)),Q===oe}function U(Q,oe){return Q&&Q.toString().replace(!oe||!oe.iri?d.ESCAPE:u.ESCAPE,X)}function N(Q,oe){return Q&&Q.toString().replace(!oe||!oe.iri?d.PCT_ENCODED:u.PCT_ENCODED,ie)}var te={scheme:"http",domainHost:!0,parse:function(Q,oe){return Q.host||(Q.error=Q.error||"HTTP URIs must have a host."),Q},serialize:function(Q,oe){var ae=String(Q.scheme).toLowerCase()==="https";return(Q.port===(ae?443:80)||Q.port==="")&&(Q.port=void 0),Q.path||(Q.path="/"),Q}},ce={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function ge(Q){return typeof Q.secure=="boolean"?Q.secure:String(Q.scheme).toLowerCase()==="wss"}var Ee={scheme:"ws",domainHost:!0,parse:function(Q,oe){var ae=Q;return ae.secure=ge(ae),ae.resourceName=(ae.path||"/")+(ae.query?"?"+ae.query:""),ae.path=void 0,ae.query=void 0,ae},serialize:function(Q,oe){if((Q.port===(ge(Q)?443:80)||Q.port==="")&&(Q.port=void 0),typeof Q.secure=="boolean"&&(Q.scheme=Q.secure?"wss":"ws",Q.secure=void 0),Q.resourceName){var ae=Q.resourceName.split("?"),be=f(ae,2),Pe=be[0],Ge=be[1];Q.path=Pe&&Pe!=="/"?Pe:void 0,Q.query=Ge,Q.resourceName=void 0}return Q.fragment=void 0,Q}},qt={scheme:"wss",domainHost:Ee.domainHost,parse:Ee.parse,serialize:Ee.serialize},ri={},Gr=!0,Er="[A-Za-z0-9\\-\\.\\_\\~"+(Gr?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",hr="[0-9A-Fa-f]",vV=i(i("%[EFef]"+hr+"%"+hr+hr+"%"+hr+hr)+"|"+i("%[89A-Fa-f]"+hr+"%"+hr+hr)+"|"+i("%"+hr+hr)),bV="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",PV="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",xV=n(PV,'[\\"\\\\]'),EV="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",SV=new RegExp(Er,"g"),zh=new RegExp(vV,"g"),kV=new RegExp(n("[^]",bV,"[\\.]",'[\\"]',xV),"g"),p5=new RegExp(n("[^]",Er,EV),"g"),_V=p5;function ES(Q){var oe=ie(Q);return oe.match(SV)?oe:Q}var h5={scheme:"mailto",parse:function(Q,oe){var ae=Q,be=ae.to=ae.path?ae.path.split(","):[];if(ae.path=void 0,ae.query){for(var Pe=!1,Ge={},Bt=ae.query.split("&"),wr=0,Xr=Bt.length;wr<Xr;++wr){var Qr=Bt[wr].split("=");switch(Qr[0]){case"to":for(var dr=Qr[1].split(","),_n=0,Yn=dr.length;_n<Yn;++_n)be.push(dr[_n]);break;case"subject":ae.subject=N(Qr[1],oe);break;case"body":ae.body=N(Qr[1],oe);break;default:Pe=!0,Ge[N(Qr[0],oe)]=N(Qr[1],oe);break}}Pe&&(ae.headers=Ge)}ae.query=void 0;for(var gn=0,Tr=be.length;gn<Tr;++gn){var Sr=be[gn].split("@");if(Sr[0]=N(Sr[0]),oe.unicodeSupport)Sr[1]=N(Sr[1],oe).toLowerCase();else try{Sr[1]=Z.toASCII(N(Sr[1],oe).toLowerCase())}catch(os){ae.error=ae.error||"Email address's domain name can not be converted to ASCII via punycode: "+os}be[gn]=Sr.join("@")}return ae},serialize:function(Q,oe){var ae=Q,be=o(Q.to);if(be){for(var Pe=0,Ge=be.length;Pe<Ge;++Pe){var Bt=String(be[Pe]),wr=Bt.lastIndexOf("@"),Xr=Bt.slice(0,wr).replace(zh,ES).replace(zh,s).replace(kV,X),Qr=Bt.slice(wr+1);try{Qr=oe.iri?Z.toUnicode(Qr):Z.toASCII(N(Qr,oe).toLowerCase())}catch(gn){ae.error=ae.error||"Email address's domain name can not be converted to "+(oe.iri?"Unicode":"ASCII")+" via punycode: "+gn}be[Pe]=Xr+"@"+Qr}ae.path=be.join(",")}var dr=Q.headers=Q.headers||{};Q.subject&&(dr.subject=Q.subject),Q.body&&(dr.body=Q.body);var _n=[];for(var Yn in dr)dr[Yn]!==ri[Yn]&&_n.push(Yn.replace(zh,ES).replace(zh,s).replace(p5,X)+"="+dr[Yn].replace(zh,ES).replace(zh,s).replace(_V,X));return _n.length&&(ae.query=_n.join("&")),ae}},AV=/^([^\:]+)\:(.*)/,m5={scheme:"urn",parse:function(Q,oe){var ae=Q.path&&Q.path.match(AV),be=Q;if(ae){var Pe=oe.scheme||be.scheme||"urn",Ge=ae[1].toLowerCase(),Bt=ae[2],wr=Pe+":"+(oe.nid||Ge),Xr=F[wr];be.nid=Ge,be.nss=Bt,be.path=void 0,Xr&&(be=Xr.parse(be,oe))}else be.error=be.error||"URN can not be parsed.";return be},serialize:function(Q,oe){var ae=oe.scheme||Q.scheme||"urn",be=Q.nid,Pe=ae+":"+(oe.nid||be),Ge=F[Pe];Ge&&(Q=Ge.serialize(Q,oe));var Bt=Q,wr=Q.nss;return Bt.path=(be||oe.nid)+":"+wr,Bt}},TV=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,y5={scheme:"urn:uuid",parse:function(Q,oe){var ae=Q;return ae.uuid=ae.nss,ae.nss=void 0,!oe.tolerant&&(!ae.uuid||!ae.uuid.match(TV))&&(ae.error=ae.error||"UUID is not valid."),ae},serialize:function(Q,oe){var ae=Q;return ae.nss=(Q.uuid||"").toLowerCase(),ae}};F[te.scheme]=te,F[ce.scheme]=ce,F[Ee.scheme]=Ee,F[qt.scheme]=qt,F[h5.scheme]=h5,F[m5.scheme]=m5,F[y5.scheme]=y5,t.SCHEMES=F,t.pctEncChar=X,t.pctDecChars=ie,t.parse=he,t.removeDotSegments=We,t.serialize=nr,t.resolveComponents=Ur,t.resolve=pr,t.normalize=Lt,t.equal=T,t.escapeComponent=U,t.unescapeComponent=N,Object.defineProperty(t,"__esModule",{value:!0})})}),ole=Zt((r,e)=>{"use strict";e.exports=function t(n){if(typeof n=="number"&&isNaN(n))throw new Error("NaN is not allowed");if(typeof n=="number"&&!isFinite(n))throw new Error("Infinity is not allowed");return n===null||typeof n!="object"?JSON.stringify(n):n.toJSON instanceof Function?t(n.toJSON()):Array.isArray(n)?`[${n.reduce((i,a,s)=>`${i}${s===0?"":","}${t(a===void 0||typeof a=="symbol"?null:a)}`,"")}]`:`{${Object.keys(n).sort().reduce((i,a)=>{if(n[a]===void 0||typeof n[a]=="symbol")return i;let s=i.length===0?"":",";return`${i}${s}${t(a)}:${t(n[a])}`},"")}}`}}),_z=Zt((r,e)=>{var t=1e3,n=t*60,i=n*60,a=i*24,s=a*7,o=a*365.25;e.exports=function(f,p){p=p||{};var h=typeof f;if(h==="string"&&f.length>0)return c(f);if(h==="number"&&isFinite(f))return p.long?d(f):l(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function c(f){if(f=String(f),!(f.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(p){var h=parseFloat(p[1]),m=(p[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return h*o;case"weeks":case"week":case"w":return h*s;case"days":case"day":case"d":return h*a;case"hours":case"hour":case"hrs":case"hr":case"h":return h*i;case"minutes":case"minute":case"mins":case"min":case"m":return h*n;case"seconds":case"second":case"secs":case"sec":case"s":return h*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return h;default:return}}}}function l(f){var p=Math.abs(f);return p>=a?Math.round(f/a)+"d":p>=i?Math.round(f/i)+"h":p>=n?Math.round(f/n)+"m":p>=t?Math.round(f/t)+"s":f+"ms"}function d(f){var p=Math.abs(f);return p>=a?u(f,p,a,"day"):p>=i?u(f,p,i,"hour"):p>=n?u(f,p,n,"minute"):p>=t?u(f,p,t,"second"):f+" ms"}function u(f,p,h,m){var y=p>=h*1.5;return Math.round(f/h)+" "+m+(y?"s":"")}}),lE=(r=>(r.authentication="authentication",r.assertionMethod="assertionMethod",r.keyAgreement="keyAgreement",r.capabilityInvocation="capabilityInvocation",r.capabilityDelegation="capabilityDelegation",r))(lE||{}),is={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},Xi=class Az{constructor({method:e,id:t,path:n,query:i,fragment:a,params:s}){this.uri=`did:${e}:${t}`,this.method=e,this.id=t,this.path=n,this.query=i,this.fragment=a,this.params=s}static parse(e){if(!e||e.length>2048)return null;let t=Az.DID_URI_PATTERN.exec(e);if(!t?.groups)return null;let{method:n,id:i,path:a,query:s,fragment:o}=t.groups,c={uri:`did:${n}:${i}`,method:n,id:i};if(a&&(c.path=a),s&&(c.query=s.slice(1)),o&&(c.fragment=o.slice(1)),s){let l={},d=s.slice(1).split("&");for(let u of d){let[f,p]=u.split("=");l[f]=p}c.params=l}return c}};Xi.METHOD_PATTERN="([a-z0-9]+)",Xi.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",Xi.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${Xi.PCT_ENCODED_PATTERN})`,Xi.METHOD_ID_PATTERN=`((?:${Xi.ID_CHAR_PATTERN}*:)*(${Xi.ID_CHAR_PATTERN}+))`,Xi.PATH_PATTERN="(/[^#?]*)?",Xi.QUERY_PATTERN="([?][^#]*)?",Xi.FRAGMENT_PATTERN="(#.*)?",Xi.DID_URI_PATTERN=new RegExp("^did:(?<method>"+Xi.METHOD_PATTERN+"):(?<id>"+Xi.METHOD_ID_PATTERN+")(?<path>"+Xi.PATH_PATTERN+")(?<query>"+Xi.QUERY_PATTERN+")(?<fragment>"+Xi.FRAGMENT_PATTERN+")$");Vn=Xi,Xe=class Tz extends Error{constructor(e,t){super(`${e}: ${t}`),this.code=e,this.name="DidError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Tz)}},ale=(r=>(r.InvalidDid="invalidDid",r.MethodNotSupported="methodNotSupported",r.InternalError="internalError",r.InvalidDidDocument="invalidDidDocument",r.InvalidDidDocumentLength="invalidDidDocumentLength",r.InvalidDidUrl="invalidDidUrl",r.InvalidGatewayUri="invalidGatewayUri",r.InvalidPreviousDidProof="invalidPreviousDidProof",r.InvalidPublicKey="invalidPublicKey",r.InvalidPublicKeyLength="invalidPublicKeyLength",r.InvalidPublicKeyType="invalidPublicKeyType",r.InvalidSignature="invalidSignature",r.NotFound="notFound",r.RepresentationNotSupported="representationNotSupported",r.UnsupportedPublicKeyType="unsupportedPublicKeyType",r))(ale||{}),ja=class Iz extends Error{constructor(e,t){super(t),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Iz)}};(function(r){r.AlgorithmNotSupported="algorithmNotSupported",r.EncodingError="encodingError",r.InvalidCoseSign1="invalidCoseSign1",r.InvalidEat="invalidEat",r.InvalidJwe="invalidJwe",r.InvalidJwk="invalidJwk",r.OperationNotSupported="operationNotSupported"})(go||(go={}));cle=vh(Nde(),1);lle=dle,ule=lle,fle=ule,CNe=new Uint8Array(0),ple=(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},BC=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")},hle=class{constructor(r,e,t){this.name=r,this.prefix=e,this.baseEncode=t}encode(r){if(r instanceof Uint8Array)return`${this.prefix}${this.baseEncode(r)}`;throw Error("Unknown type, must be binary type")}},mle=class{constructor(r,e,t){if(this.name=r,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=t}decode(r){if(typeof r=="string"){if(r.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(r)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(r.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(r){return Dz(this,r)}},yle=class{constructor(r){this.decoders=r}or(r){return Dz(this,r)}decode(r){let e=r[0],t=this.decoders[e];if(t)return t.decode(r);throw RangeError(`Unable to decode multibase string ${JSON.stringify(r)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Dz=(r,e)=>new yle({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),gle=class{constructor(r,e,t,n){this.name=r,this.prefix=e,this.baseEncode=t,this.baseDecode=n,this.encoder=new hle(r,e,t),this.decoder=new mle(r,e,n)}encode(r){return this.encoder.encode(r)}decode(r){return this.decoder.decode(r)}},Rz=({name:r,prefix:e,encode:t,decode:n})=>new gle(r,e,t,n),Cz=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=fle(t,e);return Rz({prefix:r,name:e,encode:n,decode:a=>BC(i(a))})},wle=(r,e,t,n)=>{let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let a=r.length;for(;r[a-1]==="=";)--a;let s=new Uint8Array(a*t/8|0),o=0,c=0,l=0;for(let d=0;d<a;++d){let u=i[r[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,o+=t,o>=8&&(o-=8,s[l++]=255&c>>o)}if(o>=t||255&c<<8-o)throw new SyntaxError("Unexpected end of data");return s},vle=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,a="",s=0,o=0;for(let c=0;c<r.length;++c)for(o=o<<8|r[c],s+=8;s>t;)s-=t,a+=e[i&o>>s];if(s&&(a+=e[i&o<<t-s]),n)for(;a.length*t&7;)a+="=";return a},Yo=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>Rz({prefix:e,name:r,encode(i){return vle(i,n,t)},decode(i){return wle(i,n,t,r)}}),D2=Yo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$Ne=Yo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),BNe=Yo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ONe=Yo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),jNe=Yo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),MNe=Yo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),KNe=Yo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),UNe=Yo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),eq=Yo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Ba=Cz({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),NNe=Cz({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),LNe=Yo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),qNe=Yo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ol=Yo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zNe=Yo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});T0=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},tq=function(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof __values=="function"?__values(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(a){t[a]=r[a]&&function(s){return new Promise(function(o,c){s=r[a](s),i(o,c,s.done,s.value)})}}function i(a,s,o,c){Promise.resolve(c).then(function(l){a({value:l,done:o})},s)}},x2=new TextEncoder,sh=new TextDecoder,rt=class mo{constructor(e,t){this.data=e,this.format=t}static arrayBuffer(e){return new mo(e,"ArrayBuffer")}static asyncIterable(e){if(!Ple(e))throw new TypeError("Input must be of type AsyncIterable.");return new mo(e,"AsyncIterable")}static base32Z(e){return new mo(e,"Base32Z")}static base58Btc(e){return new mo(e,"Base58Btc")}static base64Url(e){return new mo(e,"Base64Url")}static bufferSource(e){return new mo(e,"BufferSource")}static hex(e){if(typeof e!="string")throw new TypeError("Hex input must be a string.");if(e.length%2!==0)throw new TypeError("Hex input must have an even number of characters.");return new mo(e,"Hex")}static multibase(e){return new mo(e,"Multibase")}static object(e){return new mo(e,"Object")}static string(e){return new mo(e,"String")}static uint8Array(e){return new mo(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return Ba.baseDecode(this.data).buffer;case"Base64Url":return Ol.baseDecode(this.data).buffer;case"BufferSource":{if(lC(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return ble(this.data)?this.data.buffer.slice(this.data.byteOffset,this.data.byteOffset+this.data.byteLength):this.data.buffer;throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":return this.toUint8Array().buffer;case"String":return this.toUint8Array().buffer;case"Uint8Array":return this.data.buffer;default:throw new TypeError(`Conversion from ${this.format} to ArrayBuffer is not supported.`)}}toArrayBufferAsync(){return T0(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":return yield(yield this.toBlobAsync()).arrayBuffer();default:throw new TypeError(`Asynchronous conversion from ${this.format} to ArrayBuffer is not supported.`)}})}toBase32Z(){switch(this.format){case"Uint8Array":return eq.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Z is not supported.`)}}toBase58Btc(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return Ba.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return Ba.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base58Btc is not supported.`)}}toBase64Url(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return Ol.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return Ol.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),t=x2.encode(e);return Ol.baseEncode(t)}case"String":{let e=x2.encode(this.data);return Ol.baseEncode(e)}case"Uint8Array":return Ol.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return T0(this,void 0,void 0,function*(){var e,t,n,i;switch(this.format){case"AsyncIterable":{let c=[];try{for(var a=!0,s=tq(this.data),o;o=yield s.next(),e=o.done,!e;a=!0){i=o.value,a=!1;let l=i;c.push(l)}}catch(l){t={error:l}}finally{try{!a&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(t)throw t.error}}return new Blob(c)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let t=this.toUint8Array();return mo.uint8Array(t).toHex()}case"Base64Url":{let t=this.toUint8Array();return mo.uint8Array(t).toHex()}case"Uint8Array":{let t="";for(let n=0;n<this.data.length;n++)t+=e[this.data[n]];return t}default:throw new TypeError(`Conversion from ${this.format} to Hex is not supported.`)}}toMultibase(){switch(this.format){case"Base58Btc":return`z${this.data}`;default:throw new TypeError(`Conversion from ${this.format} to Multibase is not supported.`)}}toObject(){switch(this.format){case"Base64Url":{let e=Ol.baseDecode(this.data),t=sh.decode(e);return JSON.parse(t)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=sh.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return T0(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toStringAsync();return JSON.parse(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Object is not supported.`)}})}toString(){switch(this.format){case"ArrayBuffer":return sh.decode(this.data);case"Base64Url":{let e=Ol.baseDecode(this.data);return sh.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return sh.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return T0(this,void 0,void 0,function*(){var e,t,n,i;switch(this.format){case"AsyncIterable":{let c="";try{for(var a=!0,s=tq(this.data),o;o=yield s.next(),e=o.done,!e;a=!0){i=o.value,a=!1;let l=i;typeof l=="string"?c+=l:c+=sh.decode(l,{stream:!0})}}catch(l){t={error:l}}finally{try{!a&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(t)throw t.error}}return c+=sh.decode(void 0,{stream:!1}),c}default:throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`)}})}toUint8Array(){switch(this.format){case"ArrayBuffer":return new Uint8Array(this.data);case"Base32Z":return eq.baseDecode(this.data);case"Base58Btc":return Ba.baseDecode(this.data);case"Base64Url":return Ol.baseDecode(this.data);case"BufferSource":{let e=lC(this.data);if(e==="Uint8Array")return this.data;if(e==="ArrayBuffer")return new Uint8Array(this.data);if(ArrayBuffer.isView(this.data))return new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength);throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":{let e=new Uint8Array(this.data.length/2);for(let t=0;t<this.data.length;t+=2){let n=parseInt(this.data.substring(t,t+2),16);if(isNaN(n))throw new TypeError("Input is not a valid hexadecimal string.");e[t/2]=n}return e}case"Object":{let e=JSON.stringify(this.data);return x2.encode(e)}case"String":return x2.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return T0(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toArrayBufferAsync();return new Uint8Array(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Uint8Array is not supported.`)}})}};(function(r){r.Debug="debug",r.Silent="silent"})(Z0||(Z0={}));xle=class{constructor(){this.logLevel=Z0.Silent}setLogLevel(r){this.logLevel=r}log(r){this.info(r)}info(r){this.logLevel!==Z0.Silent&&console.info(r)}error(r){this.logLevel!==Z0.Silent&&console.error(r)}},Ele=new xle;typeof window<"u"&&(window.enboxLogger=Ele);O0={};RC(O0,{decode:()=>X2,encodeTo:()=>X0,encodingLength:()=>Q0});Sle=$z,rq=128,kle=127,_le=~kle,Ale=Math.pow(2,31);Tle=uC,Ile=128,nq=127;Dle=Math.pow(2,7),Rle=Math.pow(2,14),Cle=Math.pow(2,21),$le=Math.pow(2,28),Ble=Math.pow(2,35),Ole=Math.pow(2,42),jle=Math.pow(2,49),Mle=Math.pow(2,56),Kle=Math.pow(2,63),Ule=function(r){return r<Dle?1:r<Rle?2:r<Cle?3:r<$le?4:r<Ble?5:r<Ole?6:r<jle?7:r<Mle?8:r<Kle?9:10},Nle={encode:Sle,decode:Tle,encodingLength:Ule},Lle=Nle,Y2=Lle,X2=(r,e=0)=>[Y2.decode(r,e),Y2.decode.bytes],X0=(r,e,t=0)=>(Y2.encode(r,e,t),e),Q0=r=>Y2.encodingLength(r),qle=(r,e)=>{let t=e.byteLength,n=Q0(r),i=n+Q0(t),a=new Uint8Array(i+t);return X0(r,a,0),X0(t,a,n),a.set(e,i),new OC(r,t,e,a)},zle=r=>{let e=BC(r),[t,n]=X2(e),[i,a]=X2(e.subarray(n)),s=e.subarray(n+a);if(s.byteLength!==i)throw new Error("Incorrect length");return new OC(t,i,s,e)},Fle=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ple(r.bytes,t.bytes)}},OC=class{constructor(r,e,t,n){this.code=r,this.size=e,this.digest=t,this.bytes=n}},iq=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return Hle(t,fC(r),e||Ba.encoder);default:return Vle(t,fC(r),e||D2.encoder)}},sq=new WeakMap,fC=r=>{let e=sq.get(r);if(e==null){let t=new Map;return sq.set(r,t),t}return e},FNe=class vs{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==I0)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Wle)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return vs.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=qle(e,t);return vs.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 vs.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&Fle(e.multihash,n.multihash)}toString(e){return iq(this,e)}toJSON(){return{"/":iq(this)}}link(){return this}get[Symbol.toStringTag](){return"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 vs)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:a,bytes:s}=t;return new vs(n,i,a,s||oq(n,i,a.bytes))}else if(t[Jle]===!0){let{version:n,multihash:i,code:a}=t,s=zle(i);return vs.create(n,a,s)}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!==I0)throw new Error(`Version 0 CID must use dag-pb (code: ${I0}) block encoding`);return new vs(e,t,n,n.bytes)}case 1:{let i=oq(e,t,n.bytes);return new vs(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return vs.create(0,I0,e)}static createV1(e,t){return vs.create(1,e,t)}static decode(e){let[t,n]=vs.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=vs.inspectBytes(e),n=t.size-t.multihashSize,i=BC(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let a=i.subarray(t.multihashSize-t.digestSize),s=new OC(t.multihashCode,t.digestSize,a,i);return[t.version===0?vs.createV0(s):vs.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,f]=X2(e.subarray(t));return t+=f,u},i=n(),a=I0;if(i===18?(i=0,t=0):a=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,o=n(),c=n(),l=t+c,d=l-s;return{version:i,codec:a,multihashCode:o,digestSize:c,multihashSize:d,size:l}}static parse(e,t){let[n,i]=Gle(e,t),a=vs.decode(i);if(a.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return fC(a).set(n,e),a}},Gle=(r,e)=>{switch(r[0]){case"Q":{let t=e||Ba;return[Ba.prefix,t.decode(`${Ba.prefix}${r}`)]}case Ba.prefix:{let t=e||Ba;return[Ba.prefix,t.decode(r)]}case D2.prefix:{let t=e||D2;return[D2.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},Hle=(r,e,t)=>{let{prefix:n}=t;if(n!==Ba.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let a=t.encode(r).slice(1);return e.set(n,a),a}else return i},Vle=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let a=t.encode(r);return e.set(n,a),a}else return i},I0=112,Wle=18,oq=(r,e,t)=>{let n=Q0(r),i=n+Q0(e),a=new Uint8Array(i+t.byteLength);return X0(r,a,0),X0(e,a,n),a.set(t,i),a},Jle=Symbol.for("@ipld/js-cid/CID"),Ka=class vf{static addPrefix(e){var t;let{code:n,data:i,name:a}=e;if(!(a?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=vf.codeToName.has(n)?n:vf.nameToCode.get(a),n===void 0)throw new Error(`Unsupported multicodec: ${(t=e.name)!==null&&t!==void 0?t:e.code}`);let s=O0.encodingLength(n),o=new Uint8Array(s+i.byteLength);return o.set(i,s),O0.encodeTo(n,o),o}static getCodeFromData(e){let{prefixedData:t}=e,[n,i]=O0.decode(t);return n}static getCodeFromName(e){let{name:t}=e,n=vf.nameToCode.get(t);if(n===void 0)throw new Error(`Unsupported multicodec: ${t}`);return n}static getNameFromCode(e){let{code:t}=e,n=vf.codeToName.get(t);if(n===void 0)throw new Error(`Unsupported multicodec: ${t}`);return n}static registerCodec(e){vf.codeToName.set(e.code,e.name),vf.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:t}=e,[n,i]=O0.decode(t),a=vf.codeToName.get(n);if(a===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:t.slice(i),name:a}}};Ka.codeToName=new Map;Ka.nameToCode=new Map;Ka.registerCodec({code:237,name:"ed25519-pub"});Ka.registerCodec({code:4864,name:"ed25519-priv"});Ka.registerCodec({code:236,name:"x25519-pub"});Ka.registerCodec({code:4866,name:"x25519-priv"});Ka.registerCodec({code:231,name:"secp256k1-pub"});Ka.registerCodec({code:4865,name:"secp256k1-priv"});GNe=vh(kz(),1),df=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},Zle=class{constructor(){this.store=new Map}clear(){return df(this,void 0,void 0,function*(){this.store.clear()})}open(){return df(this,void 0,void 0,function*(){})}close(){return df(this,void 0,void 0,function*(){})}delete(r){return df(this,void 0,void 0,function*(){return this.store.delete(r)})}get(r){return df(this,void 0,void 0,function*(){return this.store.get(r)})}has(r){return df(this,void 0,void 0,function*(){return this.store.has(r)})}list(){return df(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(r,e){return df(this,void 0,void 0,function*(){this.store.set(r,e)})}},Yle=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})};Qle=["http:","https:"],R2=class extends Error{constructor(r){super(r),this.name="PublicUrlValidationError"}};eue=5,tue=new Set([301,302,303,307,308]);uE=class{},Kz={};RC(Kz,{bitGet:()=>fue,bitLen:()=>uue,bitMask:()=>MC,bitSet:()=>pue,bytesToHex:()=>yh,bytesToNumberBE:()=>ph,bytesToNumberLE:()=>Sf,concatBytes:()=>gh,createHmacDrbg:()=>Lz,ensureBytes:()=>Hn,equalBytes:()=>due,hexToBytes:()=>Xy,hexToNumber:()=>jC,isBytes:()=>Od,numberToBytesBE:()=>jd,numberToBytesLE:()=>Qy,numberToHexUnpadded:()=>Nz,numberToVarBytesBE:()=>cue,utf8ToBytes:()=>lue,validateObject:()=>bh});Uz=BigInt(0),fE=BigInt(1),oue=BigInt(2);aue=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));jl={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};pue=(r,e,t)=>r|(t?fE:Uz)<<BigInt(e),MC=r=>(oue<<BigInt(r-1))-fE,eC=r=>new Uint8Array(r),dq=r=>Uint8Array.from(r);hue={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Od(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};tC=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;rC=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Ad=(r,e)=>r<<32-e|r>>>e,wue=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!wue)throw new Error("Non little-endian hardware is not supported");Hz=class{clone(){return this._cloneInto()}},HNe={}.toString;Wz=class extends Hz{constructor(r,e,t,n){super(),this.blockLen=r,this.outputLen=e,this.padOffset=t,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(r),this.view=rC(this.buffer)}update(r){Q2(this);let{view:e,buffer:t,blockLen:n}=this;r=KC(r);let i=r.length;for(let a=0;a<i;){let s=Math.min(n-this.pos,i-a);if(s===n){let o=rC(r);for(;n<=i-a;a+=n)this.process(o,a);continue}t.set(r.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=r.length,this.roundClean(),this}digestInto(r){Q2(this),gue(r,this),this.finished=!0;let{buffer:e,view:t,blockLen:n,isLE:i}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(t,0),a=0);for(let d=a;d<n;d++)e[d]=0;vue(t,n-8,BigInt(this.length*8),i),this.process(t,0);let s=rC(r),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=o/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)s.setUint32(4*d,l[d],i)}digest(){let{buffer:r,outputLen:e}=this;this.digestInto(r);let t=r.slice(0,e);return this.destroy(),t}_cloneInto(r){r||(r=new this.constructor),r.set(...this.get());let{blockLen:e,buffer:t,length:n,finished:i,destroyed:a,pos:s}=this;return r.length=n,r.pos=s,r.finished=i,r.destroyed=a,n%e&&r.buffer.set(t),r}},bue=(r,e,t)=>r&e^~r&t,Pue=(r,e,t)=>r&e^r&t^e&t,xue=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),lf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),uf=new Uint32Array(64),Eue=class extends Wz{constructor(){super(64,32,8,!1),this.A=lf[0]|0,this.B=lf[1]|0,this.C=lf[2]|0,this.D=lf[3]|0,this.E=lf[4]|0,this.F=lf[5]|0,this.G=lf[6]|0,this.H=lf[7]|0}get(){let{A:r,B:e,C:t,D:n,E:i,F:a,G:s,H:o}=this;return[r,e,t,n,i,a,s,o]}set(r,e,t,n,i,a,s,o){this.A=r|0,this.B=e|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=s|0,this.H=o|0}process(r,e){for(let d=0;d<16;d++,e+=4)uf[d]=r.getUint32(e,!1);for(let d=16;d<64;d++){let u=uf[d-15],f=uf[d-2],p=Ad(u,7)^Ad(u,18)^u>>>3,h=Ad(f,17)^Ad(f,19)^f>>>10;uf[d]=h+uf[d-7]+p+uf[d-16]|0}let{A:t,B:n,C:i,D:a,E:s,F:o,G:c,H:l}=this;for(let d=0;d<64;d++){let u=Ad(s,6)^Ad(s,11)^Ad(s,25),f=l+u+bue(s,o,c)+xue[d]+uf[d]|0,p=(Ad(t,2)^Ad(t,13)^Ad(t,22))+Pue(t,n,i)|0;l=c,c=o,o=s,s=a+f|0,a=i,i=n,n=t,t=f+p|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,s=s+this.E|0,o=o+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(t,n,i,a,s,o,c,l)}roundClean(){uf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},Jz=Vz(()=>new Eue),mi=BigInt(0),yn=BigInt(1),ch=BigInt(2),Sue=BigInt(3),pC=BigInt(4),uq=BigInt(5),fq=BigInt(8),VNe=BigInt(9),kue=BigInt(16);Tue=(r,e)=>(Zr(r,e)&yn)===yn,Iue=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];Oue=BigInt(0),nC=BigInt(1);({bytesToNumberBE:Mue,hexToBytes:Kue}=Kz),uh={Err:class extends Error{constructor(r=""){super(r)}},_parseInt(r){let{Err:e}=uh;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:Mue(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=uh,t=typeof r=="string"?Kue(r):r;if(!Od(t))throw new Error("ui8a expected");let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:i,l:a}=uh._parseInt(t.subarray(2)),{d:s,l:o}=uh._parseInt(a);if(o.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(r){let e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{let d=l.toString(16);return d.length&1?`0${d}`:d},n=e(t(r.s)),i=e(t(r.r)),a=n.length/2,s=i.length/2,o=t(a),c=t(s);return`30${t(s+a+4)}02${c}${i}02${o}${n}`}},ql=BigInt(0),$a=BigInt(1),WNe=BigInt(2),pq=BigInt(3),JNe=BigInt(4);t7=class extends Hz{constructor(r,e){super(),this.finished=!1,this.destroyed=!1,yue(r);let t=KC(e);if(this.iHash=r.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(t.length>n?r.create().update(t).digest():t);for(let a=0;a<i.length;a++)i[a]^=54;this.iHash.update(i),this.oHash=r.create();for(let a=0;a<i.length;a++)i[a]^=106;this.oHash.update(i),i.fill(0)}update(r){return Q2(this),this.iHash.update(r),this}digestInto(r){Q2(this),qz(r,this.outputLen),this.finished=!0,this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let r=new Uint8Array(this.oHash.outputLen);return this.digestInto(r),r}_cloneInto(r){r||(r=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:t,finished:n,destroyed:i,blockLen:a,outputLen:s}=this;return r=r,r.finished=n,r.destroyed=i,r.blockLen=a,r.outputLen=s,r.oHash=e._cloneInto(r.oHash),r.iHash=t._cloneInto(r.iHash),r}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},r7=(r,e,t)=>new t7(r,e).update(t).digest();r7.create=(r,e)=>new t7(r,e);i7=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),hq=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),zue=BigInt(1),mC=BigInt(2),mq=(r,e)=>(r+e/mC)/e;yC=NC(i7,void 0,void 0,{sqrt:Fue}),Vo=n7({a:BigInt(0),b:BigInt(7),Fp:yC,n:hq,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=hq,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-zue*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=t,s=BigInt("0x100000000000000000000000000000000"),o=mq(a*r,e),c=mq(-n*r,e),l=Zr(r-o*t-c*i,e),d=Zr(-o*n-c*a,e),u=l>s,f=d>s;if(u&&(l=e-l),f&&(d=e-d),l>s||d>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:f,k2:d}}}},Jz),ZNe=BigInt(0),YNe=Vo.ProjectivePoint;C2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,iC=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Td=(r,e)=>r<<32-e|r>>>e,XNe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;Wue=class{clone(){return this._cloneInto()}},QNe={}.toString;Xue=(r,e,t)=>r&e^~r&t,Que=(r,e,t)=>r&e^r&t^e&t,efe=class extends Wue{constructor(r,e,t,n){super(),this.blockLen=r,this.outputLen=e,this.padOffset=t,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(r),this.view=iC(this.buffer)}update(r){yq(this);let{view:e,buffer:t,blockLen:n}=this;r=o7(r);let i=r.length;for(let a=0;a<i;){let s=Math.min(n-this.pos,i-a);if(s===n){let o=iC(r);for(;n<=i-a;a+=n)this.process(o,a);continue}t.set(r.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=r.length,this.roundClean(),this}digestInto(r){yq(this),Hue(r,this),this.finished=!0;let{buffer:e,view:t,blockLen:n,isLE:i}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(t,0),a=0);for(let d=a;d<n;d++)e[d]=0;Yue(t,n-8,BigInt(this.length*8),i),this.process(t,0);let s=iC(r),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=o/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)s.setUint32(4*d,l[d],i)}digest(){let{buffer:r,outputLen:e}=this;this.digestInto(r);let t=r.slice(0,e);return this.destroy(),t}_cloneInto(r){r||(r=new this.constructor),r.set(...this.get());let{blockLen:e,buffer:t,length:n,finished:i,destroyed:a,pos:s}=this;return r.length=n,r.pos=s,r.finished=i,r.destroyed=a,n%e&&r.buffer.set(t),r}},tfe=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ff=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),pf=new Uint32Array(64),rfe=class extends efe{constructor(){super(64,32,8,!1),this.A=ff[0]|0,this.B=ff[1]|0,this.C=ff[2]|0,this.D=ff[3]|0,this.E=ff[4]|0,this.F=ff[5]|0,this.G=ff[6]|0,this.H=ff[7]|0}get(){let{A:r,B:e,C:t,D:n,E:i,F:a,G:s,H:o}=this;return[r,e,t,n,i,a,s,o]}set(r,e,t,n,i,a,s,o){this.A=r|0,this.B=e|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=s|0,this.H=o|0}process(r,e){for(let d=0;d<16;d++,e+=4)pf[d]=r.getUint32(e,!1);for(let d=16;d<64;d++){let u=pf[d-15],f=pf[d-2],p=Td(u,7)^Td(u,18)^u>>>3,h=Td(f,17)^Td(f,19)^f>>>10;pf[d]=h+pf[d-7]+p+pf[d-16]|0}let{A:t,B:n,C:i,D:a,E:s,F:o,G:c,H:l}=this;for(let d=0;d<64;d++){let u=Td(s,6)^Td(s,11)^Td(s,25),f=l+u+Xue(s,o,c)+tfe[d]+pf[d]|0,p=(Td(t,2)^Td(t,13)^Td(t,22))+Que(t,n,i)|0;l=c,c=o,o=s,s=a+f|0,a=i,i=n,n=t,t=f+p|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,s=s+this.E|0,o=o+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(t,n,i,a,s,o,c,l)}roundClean(){pf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},eb=Jue(()=>new rfe);ife=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},a7=class{static digest(r){return ife(this,arguments,void 0,function*({data:e}){return eb(e)})}},sfe=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},gq="urn:jwk:";Zi=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},afe=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},es=class Dd{static adjustSignatureToLowS(e){return Zi(this,arguments,void 0,function*({signature:t}){let n=Vo.Signature.fromCompact(t);return n.hasHighS()?n.normalizeS().toCompactRawBytes():t})}static bytesToPrivateKey(e){return Zi(this,arguments,void 0,function*({privateKeyBytes:t}){let n=yield Dd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"secp256k1",d:rt.uint8Array(t).toBase64Url(),x:rt.uint8Array(n.x).toBase64Url(),y:rt.uint8Array(n.y).toBase64Url()};return i.kid=yield xr({jwk:i}),i})}static bytesToPublicKey(e){return Zi(this,arguments,void 0,function*({publicKeyBytes:t}){let n=yield Dd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"secp256k1",x:rt.uint8Array(n.x).toBase64Url(),y:rt.uint8Array(n.y).toBase64Url()};return i.kid=yield xr({jwk:i}),i})}static compressPublicKey(e){return Zi(this,arguments,void 0,function*({publicKeyBytes:t}){return Vo.ProjectivePoint.fromHex(t).toRawBytes(!0)})}static computePublicKey(e){return Zi(this,arguments,void 0,function*({key:t}){let n=yield Dd.privateKeyToBytes({privateKey:t}),i=yield Dd.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"secp256k1",x:rt.uint8Array(i.x).toBase64Url(),y:rt.uint8Array(i.y).toBase64Url()};return a.kid=yield xr({jwk:a}),a})}static convertDerToCompactSignature(e){return Zi(this,arguments,void 0,function*({derSignature:t}){return Vo.Signature.fromDER(t).toCompactRawBytes()})}static decompressPublicKey(e){return Zi(this,arguments,void 0,function*({publicKeyBytes:t}){return Vo.ProjectivePoint.fromHex(t).toRawBytes(!1)})}static generateKey(){return Zi(this,void 0,void 0,function*(){let e=Vo.utils.randomPrivateKey(),t=yield Dd.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield xr({jwk:t}),t})}static getPublicKey(e){return Zi(this,arguments,void 0,function*({key:t}){var n;if(!(hh(t)&&t.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=t,a=afe(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield xr({jwk:a})),a})}static privateKeyToBytes(e){return Zi(this,arguments,void 0,function*({privateKey:t}){if(!hh(t))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return rt.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Zi(this,arguments,void 0,function*({publicKey:t}){if(!(qC(t)&&t.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=rt.base64Url(t.x).toUint8Array(),a=rt.base64Url(t.y).toUint8Array();return new Uint8Array([...n,...i,...a])})}static sharedSecret(e){return Zi(this,arguments,void 0,function*({privateKeyA:t,publicKeyB:n}){if("x"in t&&"x"in n&&t.x===n.x)throw new Error("Secp256k1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield Dd.privateKeyToBytes({privateKey:t}),a=yield Dd.publicKeyToBytes({publicKey:n});return Vo.getSharedSecret(i,a,!0).slice(1)})}static sign(e){return Zi(this,arguments,void 0,function*({data:t,key:n}){let i=yield Dd.privateKeyToBytes({privateKey:n}),a=eb(t);return Vo.sign(a,i).toCompactRawBytes()})}static validatePrivateKey(e){return Zi(this,arguments,void 0,function*({privateKeyBytes:t}){return Vo.utils.isValidPrivateKey(t)})}static validatePublicKey(e){return Zi(this,arguments,void 0,function*({publicKeyBytes:t}){try{Vo.ProjectivePoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return Zi(this,arguments,void 0,function*({key:t,signature:n,data:i}){let a=yield Dd.publicKeyToBytes({publicKey:t}),s=eb(i);return Vo.verify(n,s,a,{lowS:!1})})}static getCurvePoint(e){return Zi(this,arguments,void 0,function*({keyBytes:t}){t.byteLength===32&&(t=Vo.getPublicKey(t));let n=Vo.ProjectivePoint.fromHex(t),i=jd(n.x,32),a=jd(n.y,32);return{x:i,y:a}})}},c7=NC(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),cfe=c7.create(BigInt("-3")),dfe=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),lfe=n7({a:cfe,b:dfe,Fp:c7,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Jz),Ta=lfe,Yi=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},ufe=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},bs=class Rd{static adjustSignatureToLowS(e){return Yi(this,arguments,void 0,function*({signature:t}){let n=Ta.Signature.fromCompact(t);return n.hasHighS()?n.normalizeS().toCompactRawBytes():t})}static bytesToPrivateKey(e){return Yi(this,arguments,void 0,function*({privateKeyBytes:t}){let n=yield Rd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"P-256",d:rt.uint8Array(t).toBase64Url(),x:rt.uint8Array(n.x).toBase64Url(),y:rt.uint8Array(n.y).toBase64Url()};return i.kid=yield xr({jwk:i}),i})}static bytesToPublicKey(e){return Yi(this,arguments,void 0,function*({publicKeyBytes:t}){let n=yield Rd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"P-256",x:rt.uint8Array(n.x).toBase64Url(),y:rt.uint8Array(n.y).toBase64Url()};return i.kid=yield xr({jwk:i}),i})}static compressPublicKey(e){return Yi(this,arguments,void 0,function*({publicKeyBytes:t}){return Ta.ProjectivePoint.fromHex(t).toRawBytes(!0)})}static computePublicKey(e){return Yi(this,arguments,void 0,function*({key:t}){let n=yield Rd.privateKeyToBytes({privateKey:t}),i=yield Rd.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"P-256",x:rt.uint8Array(i.x).toBase64Url(),y:rt.uint8Array(i.y).toBase64Url()};return a.kid=yield xr({jwk:a}),a})}static convertDerToCompactSignature(e){return Yi(this,arguments,void 0,function*({derSignature:t}){return Ta.Signature.fromDER(t).toCompactRawBytes()})}static decompressPublicKey(e){return Yi(this,arguments,void 0,function*({publicKeyBytes:t}){return Ta.ProjectivePoint.fromHex(t).toRawBytes(!1)})}static generateKey(){return Yi(this,void 0,void 0,function*(){let e=Ta.utils.randomPrivateKey(),t=yield Rd.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield xr({jwk:t}),t})}static getPublicKey(e){return Yi(this,arguments,void 0,function*({key:t}){var n;if(!(hh(t)&&t.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=t,a=ufe(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield xr({jwk:a})),a})}static privateKeyToBytes(e){return Yi(this,arguments,void 0,function*({privateKey:t}){if(!hh(t))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return rt.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Yi(this,arguments,void 0,function*({publicKey:t}){if(!(qC(t)&&t.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=rt.base64Url(t.x).toUint8Array(),a=rt.base64Url(t.y).toUint8Array();return new Uint8Array([...n,...i,...a])})}static sharedSecret(e){return Yi(this,arguments,void 0,function*({privateKeyA:t,publicKeyB:n}){if("x"in t&&"x"in n&&t.x===n.x)throw new Error("Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield Rd.privateKeyToBytes({privateKey:t}),a=yield Rd.publicKeyToBytes({publicKey:n});return Ta.getSharedSecret(i,a,!0).slice(1)})}static sign(e){return Yi(this,arguments,void 0,function*({data:t,key:n}){let i=yield Rd.privateKeyToBytes({privateKey:n}),a=eb(t);return Ta.sign(a,i).toCompactRawBytes()})}static validatePrivateKey(e){return Yi(this,arguments,void 0,function*({privateKeyBytes:t}){return Ta.utils.isValidPrivateKey(t)})}static validatePublicKey(e){return Yi(this,arguments,void 0,function*({publicKeyBytes:t}){try{Ta.ProjectivePoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return Yi(this,arguments,void 0,function*({key:t,signature:n,data:i}){let a=yield Rd.publicKeyToBytes({publicKey:t}),s=eb(i);return Ta.verify(n,s,a,{lowS:!1})})}static getCurvePoint(e){return Yi(this,arguments,void 0,function*({keyBytes:t}){t.byteLength===32&&(t=Ta.getPublicKey(t));let n=Ta.ProjectivePoint.fromHex(t),i=jd(n.x,32),a=jd(n.y,32);return{x:i,y:a}})}},Ml=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},wq=class extends uE{bytesToPrivateKey(r){return Ml(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"ES256K":case"secp256k1":{let n=yield es.bytesToPrivateKey({privateKeyBytes:t});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield bs.bytesToPrivateKey({privateKeyBytes:t});return n.alg="ES256",n}default:throw new ja(go.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(r){return Ml(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:t}){switch(e){case"ES256K":case"secp256k1":{let n=yield es.bytesToPublicKey({publicKeyBytes:t});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield bs.bytesToPublicKey({publicKeyBytes:t});return n.alg="ES256",n}default:throw new ja(go.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return Ml(this,arguments,void 0,function*({key:e}){if(!hh(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let t=yield es.computePublicKey({key:e});return t.alg="ES256K",t}case"P-256":{let t=yield bs.computePublicKey({key:e});return t.alg="ES256",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(r){return Ml(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let t=yield es.generateKey();return t.alg="ES256K",t}case"ES256":case"secp256r1":{let t=yield bs.generateKey();return t.alg="ES256",t}}})}getPublicKey(r){return Ml(this,arguments,void 0,function*({key:e}){if(!hh(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let t=yield es.getPublicKey({key:e});return t.alg="ES256K",t}case"P-256":{let t=yield bs.getPublicKey({key:e});return t.alg="ES256",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(r){return Ml(this,arguments,void 0,function*({key:e,data:t}){if(!hh(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield es.sign({key:e,data:t});case"P-256":return yield bs.sign({key:e,data:t});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(r){return Ml(this,arguments,void 0,function*({key:e,signature:t,data:n}){if(!qC(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(e.crv){case"secp256k1":return yield es.verify({key:e,signature:t,data:n});case"P-256":return yield bs.verify({key:e,signature:t,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return Ml(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield es.privateKeyToBytes({privateKey:e});case"P-256":return yield bs.privateKeyToBytes({privateKey:e});default:throw new ja(go.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(r){return Ml(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield es.publicKeyToBytes({publicKey:e});case"P-256":return yield bs.publicKeyToBytes({publicKey:e});default:throw new ja(go.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},E2=BigInt(4294967295),gC=BigInt(32);pfe=(r,e)=>BigInt(r>>>0)<<gC|BigInt(e>>>0),hfe=(r,e,t)=>r>>>t,mfe=(r,e,t)=>r<<32-t|e>>>t,yfe=(r,e,t)=>r>>>t|e<<32-t,gfe=(r,e,t)=>r<<32-t|e>>>t,wfe=(r,e,t)=>r<<64-t|e>>>t-32,vfe=(r,e,t)=>r>>>t-32|e<<64-t,bfe=(r,e)=>e,Pfe=(r,e)=>r,xfe=(r,e,t)=>r<<t|e>>>32-t,Efe=(r,e,t)=>e<<t|r>>>32-t,Sfe=(r,e,t)=>e<<t-32|r>>>64-t,kfe=(r,e,t)=>r<<t-32|e>>>64-t;Afe=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Tfe=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Ife=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Dfe=(r,e,t,n,i)=>e+t+n+i+(r/2**32|0)|0,Rfe=(r,e,t,n,i)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(i>>>0),Cfe=(r,e,t,n,i,a)=>e+t+n+i+a+(r/2**32|0)|0,$fe={fromBig:d7,split:ffe,toBig:pfe,shrSH:hfe,shrSL:mfe,rotrSH:yfe,rotrSL:gfe,rotrBH:wfe,rotrBL:vfe,rotr32H:bfe,rotr32L:Pfe,rotlSH:xfe,rotlSL:Efe,rotlBH:Sfe,rotlBL:kfe,add:_fe,add3L:Afe,add3H:Tfe,add4L:Ife,add4H:Dfe,add5H:Cfe,add5L:Rfe},jt=$fe,[Bfe,Ofe]=jt.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),hf=new Uint32Array(80),mf=new Uint32Array(80),jfe=class extends Wz{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:r,Al:e,Bh:t,Bl:n,Ch:i,Cl:a,Dh:s,Dl:o,Eh:c,El:l,Fh:d,Fl:u,Gh:f,Gl:p,Hh:h,Hl:m}=this;return[r,e,t,n,i,a,s,o,c,l,d,u,f,p,h,m]}set(r,e,t,n,i,a,s,o,c,l,d,u,f,p,h,m){this.Ah=r|0,this.Al=e|0,this.Bh=t|0,this.Bl=n|0,this.Ch=i|0,this.Cl=a|0,this.Dh=s|0,this.Dl=o|0,this.Eh=c|0,this.El=l|0,this.Fh=d|0,this.Fl=u|0,this.Gh=f|0,this.Gl=p|0,this.Hh=h|0,this.Hl=m|0}process(r,e){for(let w=0;w<16;w++,e+=4)hf[w]=r.getUint32(e),mf[w]=r.getUint32(e+=4);for(let w=16;w<80;w++){let E=hf[w-15]|0,_=mf[w-15]|0,A=jt.rotrSH(E,_,1)^jt.rotrSH(E,_,8)^jt.shrSH(E,_,7),D=jt.rotrSL(E,_,1)^jt.rotrSL(E,_,8)^jt.shrSL(E,_,7),M=hf[w-2]|0,C=mf[w-2]|0,z=jt.rotrSH(M,C,19)^jt.rotrBH(M,C,61)^jt.shrSH(M,C,6),L=jt.rotrSL(M,C,19)^jt.rotrBL(M,C,61)^jt.shrSL(M,C,6),B=jt.add4L(D,L,mf[w-7],mf[w-16]),W=jt.add4H(B,A,z,hf[w-7],hf[w-16]);hf[w]=W|0,mf[w]=B|0}let{Ah:t,Al:n,Bh:i,Bl:a,Ch:s,Cl:o,Dh:c,Dl:l,Eh:d,El:u,Fh:f,Fl:p,Gh:h,Gl:m,Hh:y,Hl:v}=this;for(let w=0;w<80;w++){let E=jt.rotrSH(d,u,14)^jt.rotrSH(d,u,18)^jt.rotrBH(d,u,41),_=jt.rotrSL(d,u,14)^jt.rotrSL(d,u,18)^jt.rotrBL(d,u,41),A=d&f^~d&h,D=u&p^~u&m,M=jt.add5L(v,_,D,Ofe[w],mf[w]),C=jt.add5H(M,y,E,A,Bfe[w],hf[w]),z=M|0,L=jt.rotrSH(t,n,28)^jt.rotrBH(t,n,34)^jt.rotrBH(t,n,39),B=jt.rotrSL(t,n,28)^jt.rotrBL(t,n,34)^jt.rotrBL(t,n,39),W=t&i^t&s^i&s,ee=n&a^n&o^a&o;y=h|0,v=m|0,h=f|0,m=p|0,f=d|0,p=u|0,{h:d,l:u}=jt.add(c|0,l|0,C|0,z|0),c=s|0,l=o|0,s=i|0,o=a|0,i=t|0,a=n|0;let R=jt.add3L(z,B,ee);t=jt.add3H(R,C,L,W),n=R|0}({h:t,l:n}=jt.add(this.Ah|0,this.Al|0,t|0,n|0)),{h:i,l:a}=jt.add(this.Bh|0,this.Bl|0,i|0,a|0),{h:s,l:o}=jt.add(this.Ch|0,this.Cl|0,s|0,o|0),{h:c,l}=jt.add(this.Dh|0,this.Dl|0,c|0,l|0),{h:d,l:u}=jt.add(this.Eh|0,this.El|0,d|0,u|0),{h:f,l:p}=jt.add(this.Fh|0,this.Fl|0,f|0,p|0),{h,l:m}=jt.add(this.Gh|0,this.Gl|0,h|0,m|0),{h:y,l:v}=jt.add(this.Hh|0,this.Hl|0,y|0,v|0),this.set(t,n,i,a,s,o,c,l,d,u,f,p,h,m,y,v)}roundClean(){hf.fill(0),mf.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},l7=Vz(()=>new jfe),Ac=BigInt(0),Go=BigInt(1),S2=BigInt(2),Mfe=BigInt(8),Kfe={zip215:!0};D0=BigInt(0),sC=BigInt(1);tb=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),vq=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),eLe=BigInt(0),qfe=BigInt(1),wC=BigInt(2),zfe=BigInt(5),bq=BigInt(10),Ffe=BigInt(20),Gfe=BigInt(40),Pq=BigInt(80);Ma=NC(tb,void 0,!0),rb={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ma,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:l7,randomBytes:UC,adjustScalarBytes:f7,uvRatio:Hfe},oh=FC(rb);tLe=FC({...rb,domain:p7}),rLe=FC({...rb,domain:p7,prehash:l7}),j0=Lfe({P:tb,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let e=tb,{pow_p_5_8:t,b2:n}=u7(r);return Zr(En(t,BigInt(3),e)*n,e)},adjustScalarBytes:f7,randomBytes:UC});Jfe=(Ma.ORDER+BigInt(3))/BigInt(8),nLe=Ma.pow(wC,Jfe),iLe=Ma.sqrt(Ma.neg(Ma.ONE)),sLe=(Ma.ORDER-BigInt(5))/BigInt(8),oLe=BigInt(486662),aLe=$ue(Ma,Ma.neg(BigInt(486664))),cLe=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),dLe=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),lLe=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),uLe=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),fLe=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ia=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},Zfe=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},ts=class bf{static bytesToPrivateKey(e){return Ia(this,arguments,void 0,function*({privateKeyBytes:t}){let n=oh.getPublicKey(t),i={crv:"Ed25519",d:rt.uint8Array(t).toBase64Url(),kty:"OKP",x:rt.uint8Array(n).toBase64Url()};return i.kid=yield xr({jwk:i}),i})}static bytesToPublicKey(e){return Ia(this,arguments,void 0,function*({publicKeyBytes:t}){let n={kty:"OKP",crv:"Ed25519",x:rt.uint8Array(t).toBase64Url()};return n.kid=yield xr({jwk:n}),n})}static computePublicKey(e){return Ia(this,arguments,void 0,function*({key:t}){let n=yield bf.privateKeyToBytes({privateKey:t}),i=oh.getPublicKey(n),a={kty:"OKP",crv:"Ed25519",x:rt.uint8Array(i).toBase64Url()};return a.kid=yield xr({jwk:a}),a})}static convertPrivateKeyToX25519(e){return Ia(this,arguments,void 0,function*({privateKey:t}){let n=yield bf.privateKeyToBytes({privateKey:t}),i=Wfe(n),a=j0.getPublicKey(i),s={kty:"OKP",crv:"X25519",d:rt.uint8Array(i).toBase64Url(),x:rt.uint8Array(a).toBase64Url()};return s.kid=yield xr({jwk:s}),s})}static convertPublicKeyToX25519(e){return Ia(this,arguments,void 0,function*({publicKey:t}){let n=yield bf.publicKeyToBytes({publicKey:t});if(!(yield bf.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let i=Vfe(n),a={kty:"OKP",crv:"X25519",x:rt.uint8Array(i).toBase64Url()};return a.kid=yield xr({jwk:a}),a})}static generateKey(){return Ia(this,void 0,void 0,function*(){let e=oh.utils.randomPrivateKey(),t=yield bf.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield xr({jwk:t}),t})}static getPublicKey(e){return Ia(this,arguments,void 0,function*({key:t}){var n;if(!(Gl(t)&&t.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=t,a=Zfe(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield xr({jwk:a})),a})}static privateKeyToBytes(e){return Ia(this,arguments,void 0,function*({privateKey:t}){if(!Gl(t))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return rt.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Ia(this,arguments,void 0,function*({publicKey:t}){if(!zC(t))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return rt.base64Url(t.x).toUint8Array()})}static sign(e){return Ia(this,arguments,void 0,function*({key:t,data:n}){let i=yield bf.privateKeyToBytes({privateKey:t});return oh.sign(n,i)})}static validatePublicKey(e){return Ia(this,arguments,void 0,function*({publicKeyBytes:t}){try{oh.ExtendedPoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return Ia(this,arguments,void 0,function*({key:t,signature:n,data:i}){let a=yield bf.publicKeyToBytes({publicKey:t});return oh.verify(n,i,a)})}},Kl=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},Yfe=class extends uE{bytesToPrivateKey(r){return Kl(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"Ed25519":{let n=yield ts.bytesToPrivateKey({privateKeyBytes:t});return n.alg="EdDSA",n}default:throw new ja(go.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(r){return Kl(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:t}){switch(e){case"Ed25519":{let n=yield ts.bytesToPublicKey({publicKeyBytes:t});return n.alg="EdDSA",n}default:throw new ja(go.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return Kl(this,arguments,void 0,function*({key:e}){if(!Gl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let t=yield ts.computePublicKey({key:e});return t.alg="EdDSA",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(r){return Kl(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let t=yield ts.generateKey();return t.alg="EdDSA",t}}})}getPublicKey(r){return Kl(this,arguments,void 0,function*({key:e}){if(!Gl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let t=yield ts.getPublicKey({key:e});return t.alg="EdDSA",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(r){return Kl(this,arguments,void 0,function*({key:e,data:t}){if(!Gl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield ts.sign({key:e,data:t});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(r){return Kl(this,arguments,void 0,function*({key:e,signature:t,data:n}){if(!zC(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield ts.verify({key:e,signature:t,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return Kl(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"Ed25519":return yield ts.privateKeyToBytes({privateKey:e});default:throw new ja(go.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(r){return Kl(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield ts.publicKeyToBytes({publicKey:e});default:throw new ja(go.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},Xfe=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},Qfe=class extends uE{digest(r){return Xfe(this,arguments,void 0,function*({algorithm:e,data:t}){switch(e){case"SHA-256":return yield a7.digest({data:t})}})}},yf=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},epe=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},Ly=class M0{static bytesToPrivateKey(e){return yf(this,arguments,void 0,function*({privateKeyBytes:t}){let n=j0.getPublicKey(t),i={kty:"OKP",crv:"X25519",d:rt.uint8Array(t).toBase64Url(),x:rt.uint8Array(n).toBase64Url()};return i.kid=yield xr({jwk:i}),i})}static bytesToPublicKey(e){return yf(this,arguments,void 0,function*({publicKeyBytes:t}){let n={kty:"OKP",crv:"X25519",x:rt.uint8Array(t).toBase64Url()};return n.kid=yield xr({jwk:n}),n})}static computePublicKey(e){return yf(this,arguments,void 0,function*({key:t}){let n=yield M0.privateKeyToBytes({privateKey:t}),i=j0.getPublicKey(n),a={kty:"OKP",crv:"X25519",x:rt.uint8Array(i).toBase64Url()};return a.kid=yield xr({jwk:a}),a})}static generateKey(){return yf(this,void 0,void 0,function*(){let e=j0.utils.randomPrivateKey(),t=yield M0.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield xr({jwk:t}),t})}static getPublicKey(e){return yf(this,arguments,void 0,function*({key:t}){var n;if(!(Gl(t)&&t.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=t,a=epe(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield xr({jwk:a})),a})}static privateKeyToBytes(e){return yf(this,arguments,void 0,function*({privateKey:t}){if(!Gl(t))throw new Error("X25519: The provided key is not a valid OKP private key.");return rt.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return yf(this,arguments,void 0,function*({publicKey:t}){if(!zC(t))throw new Error("X25519: The provided key is not a valid OKP public key.");return rt.base64Url(t.x).toUint8Array()})}static sharedSecret(e){return yf(this,arguments,void 0,function*({privateKeyA:t,publicKeyB:n}){if("x"in t&&"x"in n&&t.x===n.x)throw new Error("X25519: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield M0.privateKeyToBytes({privateKey:t}),a=yield M0.publicKeyToBytes({publicKey:n});return j0.getSharedSecret(i,a)})}},R0=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},tpe=class extends uE{bytesToPrivateKey(r){return R0(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"X25519":return Ly.bytesToPrivateKey({privateKeyBytes:t});default:throw new ja(go.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return R0(this,arguments,void 0,function*({key:e}){if(!Gl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Ly.computePublicKey({key:e});default:throw new ja(go.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(r){return R0(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return Ly.generateKey();default:throw new ja(go.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(r){return R0(this,arguments,void 0,function*({key:e}){if(!Gl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Ly.getPublicKey({key:e});default:throw new ja(go.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return R0(this,arguments,void 0,function*({privateKey:e}){return Ly.privateKeyToBytes({privateKey:e})})}},Ul=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},oC={Ed25519:{implementation:Yfe,names:["Ed25519"]},secp256k1:{implementation:wq,names:["ES256K","secp256k1"]},secp256r1:{implementation:wq,names:["ES256","secp256r1"]},"SHA-256":{implementation:Qfe,names:["SHA-256"]},X25519:{implementation:tpe,names:["X25519"]}},Dc=class{constructor(r){var e;this._algorithmInstances=new Map,this._keyStore=(e=r?.keyStore)!==null&&e!==void 0?e:new Zle}digest(r){return Ul(this,arguments,void 0,function*({algorithm:e,data:t}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:t})})}exportKey(r){return Ul(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(r){return Ul(this,arguments,void 0,function*({algorithm:e}){let t=yield this.getAlgorithm({algorithm:e}).generateKey({algorithm:e});if(t?.kid===void 0)throw new Error("Generated key is missing a required property: kid");let n=`${gq}${t.kid}`;return yield this._keyStore.set(n,t),n})}getKeyUri(r){return Ul(this,arguments,void 0,function*({key:e}){let t=yield xr({jwk:e});return`${gq}${t}`})}getPublicKey(r){return Ul(this,arguments,void 0,function*({keyUri:e}){let t=yield this.getPrivateKey({keyUri:e}),n=this.getAlgorithmName({key:t});return yield this.getAlgorithm({algorithm:n}).getPublicKey({key:t})})}importKey(r){return Ul(this,arguments,void 0,function*({key:e}){var t;if(!ofe(e))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let n=structuredClone(e);(t=n.kid)!==null&&t!==void 0||(n.kid=yield xr({jwk:n}));let i=yield this.getKeyUri({key:n});return yield this._keyStore.set(i,n),i})}sign(r){return Ul(this,arguments,void 0,function*({keyUri:e,data:t}){let n=yield this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:i}).sign({data:t,key:n})})}verify(r){return Ul(this,arguments,void 0,function*({key:e,signature:t,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:t,data:n})})}getAlgorithm({algorithm:r}){var e;let t=(e=oC[r])===null||e===void 0?void 0:e.implementation;if(!t)throw new Error(`Algorithm not supported: ${r}`);return this._algorithmInstances.has(t)||this._algorithmInstances.set(t,new t),this._algorithmInstances.get(t)}getAlgorithmName({key:r}){let e=r.alg,t=r.crv;for(let n in oC){let i=oC[n];if(e&&i.names.includes(e)||t&&i.names.includes(t))return n}throw new Error(`Unable to determine algorithm based on provided input: alg=${e}, crv=${t}`)}getPrivateKey(r){return Ul(this,arguments,void 0,function*({keyUri:e}){let t=yield this._keyStore.get(e);if(!t)throw new Error(`Key not found: ${e}`);return t})}},rpe=class h7{static getJoseSignatureAlgorithmFromPublicKey(e){let t={Ed25519:"EdDSA","P-256":"ES256","P-384":"ES384","P-521":"ES512",secp256k1:"ES256K"};if(e.alg&&Object.values(t).includes(e.alg))return e.alg;if(e.crv&&Object.keys(t).includes(e.crv))return t[e.crv];throw new Error(`Unable to determine algorithm based on provided input: alg=${e.alg}, crv=${e.crv}. Supported 'alg' values: ${Object.values(t).join(", ")}. Supported 'crv' values: ${Object.keys(t).join(", ")}.`)}static randomBytes(e){return Zue(e)}static randomUuid(){return C2.randomUUID()}static randomPin({length:e}){if(3>e||e>10)throw new Error("randomPin() can securely generate a PIN between 3 to 10 digits.");let t=Math.pow(10,e),n=Math.ceil(Math.log2(t)/8),i=Math.pow(2,n*8),a=i-i%t,s;do{s=0;let o=h7.randomBytes(n);for(let c of o)s=s*256+c}while(s>=a);return(s%t).toString().padStart(e,"0")}},npe=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];xe=class{constructor(r,e,t){this.major=r,this.majorEncoded=r<<5,this.name=e,this.terminal=t}toString(){return`Type[${this.major}].${this.name}`}compare(r){return this.major<r.major?-1:this.major>r.major?1:0}static equals(r,e){return r===e||r.major===e.major&&r.name===e.name}};xe.uint=new xe(0,"uint",!0);xe.negint=new xe(1,"negint",!0);xe.bytes=new xe(2,"bytes",!0);xe.string=new xe(3,"string",!0);xe.array=new xe(4,"array",!1);xe.map=new xe(5,"map",!1);xe.tag=new xe(6,"tag",!1);xe.float=new xe(7,"float",!0);xe.false=new xe(7,"false",!0);xe.true=new xe(7,"true",!0);xe.null=new xe(7,"null",!0);xe.undefined=new xe(7,"undefined",!0);xe.break=new xe(7,"break",!0);Qe=class{constructor(r,e,t){this.type=r,this.value=e,this.encodedLength=t,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}},cb=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ope=new TextEncoder;ape=24,cpe=200,dpe=cb?r=>r.length>=ape?globalThis.Buffer.from(r):xq(r):r=>r.length>=cpe?ope.encode(r):xq(r),Nl=r=>Uint8Array.from(r),lpe=cb?(r,e,t)=>eE(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),upe=cb?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),m7(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},fpe=cb?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);ppe=256,g7=class{constructor(r=ppe){this.chunkSize=r,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(r){let e=this.chunks[this.chunks.length-1];if(this.cursor+r.length<=this.maxCursor+1){let t=e.length-(this.maxCursor-this.cursor)-1;e.set(r,t)}else{if(e){let t=e.length-(this.maxCursor-this.cursor)-1;t<e.length&&(this.chunks[this.chunks.length-1]=e.subarray(0,t),this.maxCursor=this.cursor-1)}r.length<64&&r.length<this.chunkSize?(e=fpe(this.chunkSize),this.chunks.push(e),this.maxCursor+=e.length,this._initReuseChunk===null&&(this._initReuseChunk=e),e.set(r,0)):(this.chunks.push(r),this.maxCursor+=r.length)}this.cursor+=r.length}toBytes(r=!1){let e;if(this.chunks.length===1){let t=this.chunks[0];r&&this.cursor>t.length/2?(e=this.cursor===t.length?t:t.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):e=lpe(t,0,this.cursor)}else e=upe(this.chunks,this.cursor);return r&&this.reset(),e}},hpe=class{constructor(r){this.dest=r,this.cursor=0,this.chunks=[r]}reset(){this.cursor=0}push(r){if(this.cursor+r.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(r,this.cursor),this.cursor+=r.length}toBytes(r=!1){let e=this.dest.subarray(0,this.cursor);return r&&this.reset(),e}},Sn="CBOR decode error:",w7="CBOR encode error:",db=[];db[23]=1;db[24]=2;db[25]=3;db[26]=5;db[27]=9;rs=[24,256,65536,4294967296,BigInt("18446744073709551616")];kh.encodedSize=function(r){return Ua.encodedSize(r.value)};Ua.encodedSize=function(r){return r<rs[0]?1:r<rs[1]?2:r<rs[2]?3:r<rs[3]?5:9};kh.compareTokens=function(r,e){return r.value<e.value?-1:r.value>e.value?1:0};GC=BigInt(-1),v7=BigInt(1);HC.encodedSize=function(r){let e=r.value,t=typeof e=="bigint"?e*GC-v7:e*-1-1;return t<rs[0]?1:t<rs[1]?2:t<rs[2]?3:t<rs[3]?5:9};HC.compareTokens=function(r,e){return r.value<e.value?1:r.value>e.value?-1:0};pE.encodedSize=function(r){let e=tE(r);return Ua.encodedSize(e.length)+e.length};pE.compareTokens=function(r,e){return Tpe(tE(r),tE(e))};Eq=new TextDecoder,Ipe=32;jpe=pE;VC.compareTokens=kh.compareTokens;VC.encodedSize=function(r){return Ua.encodedSize(r.value)};WC.compareTokens=kh.compareTokens;WC.encodedSize=function(r){return Ua.encodedSize(r.value)};JC.compareTokens=kh.compareTokens;JC.encodedSize=function(r){return Ua.encodedSize(r.value)};b7=20,P7=21,x7=22,E7=23;YC.encodedSize=function(r,e){let t=r.value;if(t===!1||t===!0||t===null||t===void 0)return 1;if(!e||e.float64!==!0){k7(t);let n=XC(Tc,1);if(t===n||Number.isNaN(t))return 3;if(_7(t),n=QC(Tc,1),t===n)return 5}return 9};S7=new ArrayBuffer(9),Ra=new DataView(S7,1),Tc=new Uint8Array(S7,0);YC.compareTokens=kh.compareTokens;Oe=[];for(let r=0;r<=23;r++)Oe[r]=fr;Oe[24]=mpe;Oe[25]=ype;Oe[26]=gpe;Oe[27]=wpe;Oe[28]=fr;Oe[29]=fr;Oe[30]=fr;Oe[31]=fr;for(let r=32;r<=55;r++)Oe[r]=fr;Oe[56]=vpe;Oe[57]=bpe;Oe[58]=Ppe;Oe[59]=xpe;Oe[60]=fr;Oe[61]=fr;Oe[62]=fr;Oe[63]=fr;for(let r=64;r<=87;r++)Oe[r]=Epe;Oe[88]=Spe;Oe[89]=kpe;Oe[90]=_pe;Oe[91]=Ape;Oe[92]=fr;Oe[93]=fr;Oe[94]=fr;Oe[95]=hE("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)Oe[r]=Rpe;Oe[120]=Cpe;Oe[121]=$pe;Oe[122]=Bpe;Oe[123]=Ope;Oe[124]=fr;Oe[125]=fr;Oe[126]=fr;Oe[127]=hE("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)Oe[r]=Mpe;Oe[152]=Kpe;Oe[153]=Upe;Oe[154]=Npe;Oe[155]=Lpe;Oe[156]=fr;Oe[157]=fr;Oe[158]=fr;Oe[159]=qpe;for(let r=160;r<=183;r++)Oe[r]=zpe;Oe[184]=Fpe;Oe[185]=Gpe;Oe[186]=Hpe;Oe[187]=Vpe;Oe[188]=fr;Oe[189]=fr;Oe[190]=fr;Oe[191]=Wpe;for(let r=192;r<=215;r++)Oe[r]=Jpe;Oe[216]=Zpe;Oe[217]=Ype;Oe[218]=Xpe;Oe[219]=Qpe;Oe[220]=fr;Oe[221]=fr;Oe[222]=fr;Oe[223]=fr;for(let r=224;r<=243;r++)Oe[r]=hE("simple values are not supported");Oe[244]=fr;Oe[245]=fr;Oe[246]=fr;Oe[247]=ehe;Oe[248]=hE("simple values are not supported");Oe[249]=rhe;Oe[250]=nhe;Oe[251]=ihe;Oe[252]=fr;Oe[253]=fr;Oe[254]=fr;Oe[255]=the;Vl=[];for(let r=0;r<24;r++)Vl[r]=new Qe(xe.uint,r,1);for(let r=-1;r>=-24;r--)Vl[31-r]=new Qe(xe.negint,r,1);Vl[64]=new Qe(xe.bytes,new Uint8Array(0),1);Vl[96]=new Qe(xe.string,"",1);Vl[128]=new Qe(xe.array,0,1);Vl[160]=new Qe(xe.map,0,1);Vl[244]=new Qe(xe.false,!1,1);Vl[245]=new Qe(xe.true,!0,1);Vl[246]=new Qe(xe.null,null,1);ahe=Object.freeze({float64:!0,mapSorter:fhe,quickEncodeToken:ohe});dhe=che(),lhe=new g7,Sq=class T7{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(`${w7} object contains circular references`);return new T7(t,e)}},gf={null:new Qe(xe.null,null),undefined:new Qe(xe.undefined,void 0),true:new Qe(xe.true,!0),false:new Qe(xe.false,!1),emptyArray:new Qe(xe.array,0),emptyMap:new Qe(xe.map,0)},_f={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new Qe(xe.float,r):r>=0?new Qe(xe.uint,r):new Qe(xe.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new Qe(xe.uint,r):new Qe(xe.negint,r)},Uint8Array(r,e,t,n){return new Qe(xe.bytes,r)},string(r,e,t,n){return new Qe(xe.string,r)},boolean(r,e,t,n){return r?gf.true:gf.false},null(r,e,t,n){return gf.null},undefined(r,e,t,n){return gf.undefined},ArrayBuffer(r,e,t,n){return new Qe(xe.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new Qe(xe.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[gf.emptyArray,new Qe(xe.break)]:gf.emptyArray;n=Sq.createCheck(n,r);let i=[],a=0;for(let s of r)i[a++]=$2(s,t,n);return t.addBreakTokens?[new Qe(xe.array,r.length),i,new Qe(xe.break)]:[new Qe(xe.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",a=i?r.keys():Object.keys(r),s=i?r.size:a.length,o;if(s){o=new Array(s),n=Sq.createCheck(n,r);let c=!i&&t.ignoreUndefinedProperties,l=0;for(let d of a){let u=i?r.get(d):r[d];c&&u===void 0||(o[l++]=[$2(d,t,n),$2(u,t,n)])}l<s&&(o.length=l)}return o?.length?(uhe(o,t),t.addBreakTokens?[new Qe(xe.map,o.length),o,new Qe(xe.break)]:[new Qe(xe.map,o.length),o]):t.addBreakTokens===!0?[gf.emptyMap,new Qe(xe.break)]:gf.emptyMap}};_f.Map=_f.Object;_f.Buffer=_f.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))_f[`${r}Array`]=_f.DataView;pLe=xe.uint.majorEncoded,hLe=xe.negint.majorEncoded,mLe=xe.bytes.majorEncoded,yLe=xe.string.majorEncoded,gLe=xe.array.majorEncoded,wLe=xe.float.majorEncoded|b7,vLe=xe.float.majorEncoded|P7,bLe=xe.float.majorEncoded|x7,PLe=xe.float.majorEncoded|E7,xLe=BigInt(-1),ELe=BigInt(1);SLe=Symbol.for("DONE"),kLe=Symbol.for("BREAK");(function(r){r[r.OKP=1]="OKP",r[r.EC2=2]="EC2",r[r.Symmetric=4]="Symmetric"})(_q||(_q={}));(function(r){r[r.P256=1]="P256",r[r.P384=2]="P384",r[r.P521=3]="P521",r[r.X25519=4]="X25519",r[r.X448=5]="X448",r[r.Ed25519=6]="Ed25519",r[r.Ed448=7]="Ed448",r[r.Secp256k1=8]="Secp256k1"})(Ps||(Ps={}));(function(r){r[r.EdDSA=-8]="EdDSA",r[r.ES256=-7]="ES256",r[r.ES384=-35]="ES384",r[r.ES512=-36]="ES512",r[r.ES256K=-47]="ES256K"})(Oa||(Oa={}));(function(r){r[r.Kty=1]="Kty",r[r.Kid=2]="Kid",r[r.Alg=3]="Alg",r[r.KeyOps=4]="KeyOps",r[r.BaseIv=5]="BaseIv"})(Aq||(Aq={}));(function(r){r[r.Crv=-1]="Crv",r[r.X=-2]="X",r[r.Y=-3]="Y",r[r.D=-4]="D"})(Tq||(Tq={}));_Le={"P-256":Ps.P256,"P-384":Ps.P384,"P-521":Ps.P521,X25519:Ps.X25519,Ed25519:Ps.Ed25519,Ed448:Ps.Ed448,secp256k1:Ps.Secp256k1},ALe={[Ps.P256]:"P-256",[Ps.P384]:"P-384",[Ps.P521]:"P-521",[Ps.X25519]:"X25519",[Ps.Ed25519]:"Ed25519",[Ps.Ed448]:"Ed448",[Ps.Secp256k1]:"secp256k1"},TLe={EdDSA:Oa.EdDSA,ES256:Oa.ES256,ES384:Oa.ES384,ES512:Oa.ES512,ES256K:Oa.ES256K},ILe={[Oa.EdDSA]:"EdDSA",[Oa.ES256]:"ES256",[Oa.ES384]:"ES384",[Oa.ES512]:"ES512",[Oa.ES256K]:"ES256K"};(function(r){r[r.Alg=1]="Alg",r[r.Crit=2]="Crit",r[r.ContentType=3]="ContentType",r[r.Kid=4]="Kid"})(Iq||(Iq={}));(function(r){r[r.Iss=1]="Iss",r[r.Sub=2]="Sub",r[r.Aud=3]="Aud",r[r.Exp=4]="Exp",r[r.Nbf=5]="Nbf",r[r.Iat=6]="Iat",r[r.Cti=7]="Cti",r[r.Nonce=10]="Nonce",r[r.Ueid=256]="Ueid",r[r.Sueids=257]="Sueids",r[r.Oemid=258]="Oemid",r[r.Hwmodel=259]="Hwmodel",r[r.Hwversion=260]="Hwversion",r[r.Secboot=262]="Secboot",r[r.Dbgstat=263]="Dbgstat",r[r.Location=264]="Location",r[r.Profile=265]="Profile",r[r.Submods=266]="Submods",r[r.Measres=272]="Measres",r[r.Intuse=268]="Intuse"})(Dq||(Dq={}));(function(r){r[r.Enabled=0]="Enabled",r[r.Disabled=1]="Disabled",r[r.DisabledSinceBoot=2]="DisabledSinceBoot",r[r.DisabledPermanently=3]="DisabledPermanently",r[r.DisabledFullyAndPermanently=4]="DisabledFullyAndPermanently"})(Rq||(Rq={}));(function(r){r[r.Unrestricted=1]="Unrestricted",r[r.Restricted=2]="Restricted",r[r.SecureRestricted=3]="SecureRestricted",r[r.Hardware=4]="Hardware"})(Cq||(Cq={}));e6={};RC(e6,{extractDidFragment:()=>Ws,getServices:()=>hhe,getVerificationMethodByKey:()=>mhe,getVerificationMethodTypes:()=>D7,getVerificationMethods:()=>mE,getVerificationRelationshipsById:()=>R7,isDidService:()=>C7,isDidVerificationMethod:()=>rE,isDwnDidService:()=>yhe,isPortableDid:()=>_h,keyBytesToMultibaseId:()=>$7,multibaseIdToKeyBytes:()=>B7});xs=class O7{constructor({uri:e,document:t,metadata:n,keyManager:i}){this.uri=e,this.document=t,this.metadata=n,this.keyManager=i}async export(){if(!(Array.isArray(this.document.verificationMethod)&&this.document.verificationMethod.length>0))throw new Error(`DID document for '${this.uri}' is missing verification methods`);let e=JSON.parse(JSON.stringify({uri:this.uri,document:this.document,metadata:this.metadata}));if("exportKey"in this.keyManager&&typeof this.keyManager.exportKey=="function"){let t=[];for(let n of this.document.verificationMethod){if(!n.publicKeyJwk)throw new Error(`Verification method '${n.id}' does not contain a public key in JWK format`);let i=await this.keyManager.getKeyUri({key:n.publicKeyJwk}),a=await this.keyManager.exportKey({keyUri:i});t.push({...a})}e.privateKeys=t}return e}async getSigner(e){let t=this.document.verificationMethod?.find(s=>Ws(s.id)===(Ws(e?.methodId)??Ws(this.document.assertionMethod?.[0])));if(!t?.publicKeyJwk)throw new Xe("internalError","A verification method intended for signing could not be determined from the DID Document");let n=await this.keyManager.getKeyUri({key:t.publicKeyJwk}),i=await this.keyManager.getPublicKey({keyUri:n}),a=this.keyManager;return{algorithm:rpe.getJoseSignatureAlgorithmFromPublicKey(i),keyId:t.id,async sign({data:s}){return await a.sign({data:s,keyUri:n})},async verify({data:s,signature:o}){return await a.verify({data:s,key:i,signature:o})}}}static async import({portableDid:e,keyManager:t=new Dc}){let n=mE({didDocument:e.document});if(n.length===0)throw new Xe("invalidDidDocument","At least one verification method is required but 0 were given");for(let i of e.privateKeys??[]){let a=await t.getKeyUri({key:i});await t.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1)||await t.importKey({key:i})}for(let i of n){if(!i.publicKeyJwk)throw new Error(`Verification method '${i.id}' does not contain a public key in JWK format`);let a=await t.getKeyUri({key:i.publicKeyJwk});await t.getPublicKey({keyUri:a})}return new O7({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:t})}},fb=class{static async getSigningMethod(r){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")}static async resolve(r,e){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")}},j7=(r=>(r[r.Discoverable=0]="Discoverable",r[r.Organization=1]="Organization",r[r.Government=2]="Government",r[r.Corporation=3]="Corporation",r[r.LocalBusiness=4]="LocalBusiness",r[r.SoftwarePackage=5]="SoftwarePackage",r[r.WebApp=6]="WebApp",r[r.FinancialInstitution=7]="FinancialInstitution",r))(j7||{}),t6=(r=>(r[r.Ed25519=0]="Ed25519",r[r.secp256k1=1]="secp256k1",r[r.secp256r1=2]="secp256r1",r[r.X25519=3]="X25519",r))(t6||{}),M7=(r=>(r.authentication="auth",r.assertionMethod="asm",r.capabilityDelegation="del",r.capabilityInvocation="inv",r.keyAgreement="agm",r))(M7||{}),$q="0123456789abcdef",K7=[],Bq=[];for(let r=0;r<256;r++)K7[r]=$q[r>>4&15]+$q[r&15],r<16&&(r<10?Bq[48+r]=r:Bq[87+r]=r);ghe=r=>{let e=r.length,t="",n=0;for(;n<e;)t+=K7[r[n++]];return t},whe=(r,e=0)=>{let t=r.length||0;if(!e){let s=t;for(;s--;)e+=r[s].length}let n=new Uint8Array(e),i=e,a=t;for(;a--;)i-=r[a].length,n.set(r[a],i);return n},Oq="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",vhe=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(C0=0;C0<Oq.length;C0++)vhe[Oq.charCodeAt(C0)]=C0;bhe=new TextDecoder,U7=(r,e)=>e?new TextDecoder(e).decode(r):bhe.decode(r),Phe=new TextEncoder,Hl=r=>Phe.encode(r),jq=typeof window<"u"?window:self,Mq=jq.crypto||jq.msCrypto||{},DLe=Mq.subtle||Mq.webkitSubtle;gr.bytes=-1;gr._floatConversionDetected=!1;gr._encode=function(r,e){if(e!=null)switch(N7(e)){case"object":gr.dict(r,e);break;case"map":gr.dictMap(r,e);break;case"array":gr.list(r,e);break;case"set":gr.listSet(r,e);break;case"string":gr.string(r,e);break;case"number":gr.number(r,e);break;case"boolean":gr.number(r,e);break;case"arraybufferview":gr.buffer(r,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":gr.buffer(r,new Uint8Array(e));break}};yE=new Uint8Array([101]),L7=new Uint8Array([100]),q7=new Uint8Array([108]);gr.buffer=function(r,e){r.push(Hl(e.length+":"),e)};gr.string=function(r,e){r.push(Hl(Hl(e).byteLength+":"+e))};gr.number=function(r,e){if(Number.isInteger(e))return r.push(Hl("i"+BigInt(e)+"e"));let t=2147483648,n=e/t<<0,i=e%t<<0,a=n*t+i;r.push(Hl("i"+a+"e")),a!==e&&!gr._floatConversionDetected&&(gr._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+e+'":','Bencoding only defines support for integers, value was converted to "'+a+'"'),console.trace())};gr.dict=function(r,e){r.push(L7);let t=0,n,i=Object.keys(e).sort(),a=i.length;for(;t<a;t++)n=i[t],e[n]!=null&&(gr.string(r,n),gr._encode(r,e[n]));r.push(yE)};gr.dictMap=function(r,e){r.push(L7);let t=Array.from(e.keys()).sort();for(let n of t)e.get(n)!=null&&(ArrayBuffer.isView(n)?gr._encode(r,n):gr.string(r,String(n)),gr._encode(r,e.get(n)));r.push(yE)};gr.list=function(r,e){let t=0,n=e.length;for(r.push(q7);t<n;t++)e[t]!=null&&gr._encode(r,e[t]);r.push(yE)};gr.listSet=function(r,e){r.push(q7);for(let t of e)t!=null&&gr._encode(r,t);r.push(yE)};xhe=gr,Ehe=105,She=58,khe=100,_he=108,r6=101;gt.bytes=0;gt.position=0;gt.data=null;gt.encoding=null;gt.next=function(){switch(gt.data[gt.position]){case khe:return gt.dictionary();case _he:return gt.list();case Ehe:return gt.integer();default:return gt.buffer()}};gt.find=function(r){let e=gt.position,t=gt.data.length,n=gt.data;for(;e<t;){if(n[e]===r)return e;e++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(r)+'" [0x'+r.toString(16)+"]")};gt.dictionary=function(){gt.position++;let r={};for(;gt.data[gt.position]!==r6;){let e=gt.buffer(),t=U7(e);t.includes("\uFFFD")&&(t=ghe(e)),r[t]=gt.next()}return gt.position++,r};gt.list=function(){gt.position++;let r=[];for(;gt.data[gt.position]!==r6;)r.push(gt.next());return gt.position++,r};gt.integer=function(){let r=gt.find(r6),e=z7(gt.data,gt.position+1,r);return gt.position+=r+1-gt.position,e};gt.buffer=function(){let r=gt.find(She),e=z7(gt.data,gt.position,r),t=++r+e;return gt.position=t,gt.encoding?U7(gt.data.slice(r,t)):gt.data.slice(r,t)};Ahe=gt;F7=gE,$he=F7,G7={encode:xhe,decode:Ahe,byteLength:F7,encodingLength:$he},Bhe=/^(\d{1,3}\.){3,3}\d{1,3}$/,Ohe=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,Bd={name:"v4",size:4,isFormat:r=>Bhe.test(r),encode(r,e,t){t=~~t,e=e||new Uint8Array(t+4);let n=r.length,i=0;for(let a=0;a<n;){let s=r.charCodeAt(a++);s===46?(e[t++]=i,i=0):i=i*10+(s-48)}return e[t]=i,e},decode(r,e){return e=~~e,`${r[e++]}.${r[e++]}.${r[e++]}.${r[e]}`}},kf={name:"v6",size:16,isFormat:r=>r.length>0&&Ohe.test(r),encode(r,e,t){t=~~t;let n=t+16,i=-1,a=0,s=0,o=!0,c=!1;e=e||new Uint8Array(t+16);for(let l=0;l<r.length;l++){let d=r.charCodeAt(l);d===58?(o?i!==-1?(t<n&&(e[t]=0),t<n-1&&(e[t+1]=0),t+=2):t<n&&(i=t):(c===!0?(t<n&&(e[t]=s),t++):(t<n&&(e[t]=a>>8),t<n-1&&(e[t+1]=a&255),t+=2),a=0,s=0),o=!0,c=!1):d===46?(t<n&&(e[t]=s),t++,s=0,a=0,o=!1,c=!0):(o=!1,d>=97?d-=87:d>=65?d-=55:(d-=48,s=s*10+d),a=(a<<4)+d)}if(o===!1)c===!0?(t<n&&(e[t]=s),t++):(t<n&&(e[t]=a>>8),t<n-1&&(e[t+1]=a&255),t+=2);else if(i===0)t<n&&(e[t]=0),t<n-1&&(e[t+1]=0),t+=2;else if(i!==-1){t+=2;for(let l=Math.min(t-1,n-1);l>=i+2;l--)e[l]=e[l-2];e[i]=0,e[i+1]=0,i=t}if(i!==t&&i!==-1)for(t>n-2&&(t=n-2);n>i;)e[--n]=t<n&&t>i?e[--t]:0;else for(;t<n;)e[t++]=0;return e},decode(r,e){e=~~e;let t="";for(let n=0;n<16;n+=2)n!==0&&(t+=":"),t+=(r[e+n]<<8|r[e+n+1]).toString(16);return t.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};ib.bytes=0;hb.bytes=0;wh=r=>r instanceof Uint8Array;K0={},Z7=new Array(255);for(let r=0;r<=15;r+=1){let e=r.toString(16),t=e.toUpperCase();for(let n=0;n<=15;n+=1){let i=n.toString(16),a=i.toUpperCase(),s=r<<4|n,o=`${e}${i}`;Z7[s]=o,K0[o]=s,K0[`${t}${i}`]=s,K0[`${e}${a}`]=s,K0[`${t}${a}`]=s}}Fhe=Math.pow(2,24),Ghe=Math.pow(2,16),Hhe=Math.pow(2,8),zl=(r,e)=>r[e]*Fhe+r[e+1]*Ghe+r[e+2]*Hhe+r[e+3],Mt=(r,e)=>r[e]<<8|r[e+1],Fl=(r,e,t)=>(e=+e,r[t+3]=e,e=e>>>8,r[t+2]=e,e=e>>>8,r[t+1]=e,e=e>>>8,r[t]=e,t+4),nt=(r,e,t)=>(r[t]=e>>8,r[t+1]=e&255,t+2);Whe=0,Nq=32768,vC=32768,Jhe=~vC,Y7=32768,Zhe=~Y7;He=Fr({encode(r,e,t){e||(e=new Uint8Array(He.encodingLength(r))),t||(t=0);let n=t,i=r.replace(/^\.|\.$/gm,"");if(i.length){let a=i.split(".");for(let s=0;s<a.length;s++){let o=i6(e,a[s],t+1);e[t]=o,t+=o+1}}return e[t++]=0,He.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=[],n=e,i=0,a=0,s=!1;for(;;){if(e>=r.length)throw new Error("Cannot decode name (buffer overflow)");let o=r[e++];if(a+=s?0:1,o===0)break;if(o&192)if((o&192)===192){if(e+1>r.length)throw new Error("Cannot decode name (buffer overflow)");let c=Mt(r,e-1)-49152;if(c>=n)throw new Error("Cannot decode name (bad pointer)");e=c,n=c,a+=s?0:1,s=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+o>r.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=o+1,i>254)throw new Error("Cannot decode name (name too long)");t.push(hb(r,e,e+o)),e+=o,a+=s?0:o}}return He.decode.bytes=a,t.length===0?".":t.join(".")},encodingLength(r){return r==="."||r===".."?1:Af(r.replace(/^\.|\.$/gm,""))+2}}),hi=Fr({encode(r,e,t){e||(e=new Uint8Array(hi.encodingLength(r))),t||(t=0);let n=i6(e,r,t+1);return e[t]=n,hi.encode.bytes=n+1,e},decode(r,e){e||(e=0);let t=r[e],n=hb(r,e+1,e+1+t);return hi.decode.bytes=t+1,n},encodingLength(r){return Af(r)+1}}),qy=Fr({bytes:12,encode(r,e,t){e||(e=new Uint8Array(qy.encodingLength(r))),t||(t=0);let n=(r.flags||0)&32767,i=r.type==="response"?Nq:Whe;return nt(e,r.id||0,t),nt(e,n|i,t+2),nt(e,r.questions.length,t+4),nt(e,r.answers.length,t+6),nt(e,r.authorities.length,t+8),nt(e,r.additionals.length,t+10),e},decode(r,e){if(e||(e=0),r.length<12)throw new Error("Header must be 12 bytes");let t=Mt(r,e+2);return{id:Mt(r,e),type:t&Nq?"response":"query",flags:t&32767,flag_qr:(t>>15&1)===1,opcode:Nhe(t>>11&15),flag_aa:(t>>10&1)===1,flag_tc:(t>>9&1)===1,flag_rd:(t>>8&1)===1,flag_ra:(t>>7&1)===1,flag_z:(t>>6&1)===1,flag_ad:(t>>5&1)===1,flag_cd:(t>>4&1)===1,rcode:Uhe(t&15),questions:new Array(Mt(r,e+4)),answers:new Array(Mt(r,e+6)),authorities:new Array(Mt(r,e+8)),additionals:new Array(Mt(r,e+10))}},encodingLength(){return 12}}),B2=Fr({encode(r,e,t){e||(e=new Uint8Array(B2.encodingLength(r))),t||(t=0);let n=r.length;return nt(e,n,t),Zo(r,e,t+2,0,n),B2.encode.bytes=n+2,e},decode(r,e){e||(e=0);let t=Mt(r,e),n=r.slice(e+2,e+2+t);return B2.decode.bytes=t+2,n},encodingLength(r){return r.length+2}}),O2=Fr({encode(r,e,t){return e||(e=new Uint8Array(O2.encodingLength(r))),t||(t=0),He.encode(r,e,t+2),nt(e,He.encode.bytes,t),O2.encode.bytes=He.encode.bytes+2,e},decode(r,e){e||(e=0);let t=Mt(r,e),n=He.decode(r,e+2);return O2.decode.bytes=t+2,n},encodingLength(r){return He.encodingLength(r)+2}}),j2=Fr({encode(r,e,t){e||(e=new Uint8Array(j2.encodingLength(r))),t||(t=0);let n=t;return t+=2,He.encode(r.mname,e,t),t+=He.encode.bytes,He.encode(r.rname,e,t),t+=He.encode.bytes,Fl(e,r.serial||0,t),t+=4,Fl(e,r.refresh||0,t),t+=4,Fl(e,r.retry||0,t),t+=4,Fl(e,r.expire||0,t),t+=4,Fl(e,r.minimum||0,t),t+=4,nt(e,t-n-2,n),j2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.mname=He.decode(r,e),e+=He.decode.bytes,n.rname=He.decode(r,e),e+=He.decode.bytes,n.serial=zl(r,e),e+=4,n.refresh=zl(r,e),e+=4,n.retry=zl(r,e),e+=4,n.expire=zl(r,e),e+=4,n.minimum=zl(r,e),e+=4,j2.decode.bytes=e-t,n},encodingLength(r){return 22+He.encodingLength(r.mname)+He.encodingLength(r.rname)}}),M2=Fr({encode(r,e,t){Array.isArray(r)||(r=[r]);for(let i=0;i<r.length;i++)if(typeof r[i]=="string"&&(r[i]=n6(r[i])),!wh(r[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(M2.encodingLength(r))),t||(t=0);let n=t;return t+=2,r.forEach(function(i){e[t++]=i.length,Zo(i,e,t,0,i.length),t+=i.length}),nt(e,t-n-2,n),M2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=Mt(r,e);e+=2;let i=[];for(;n>0;){let a=r[e++];if(--n,n<a)throw new Error("Buffer overflow");i.push(r.slice(e,e+a)),e+=a,n-=a}return M2.decode.bytes=e-t,i},encodingLength(r){Array.isArray(r)||(r=[r]);let e=2;return r.forEach(function(t){typeof t=="string"?e+=Af(t)+1:e+=t.length+1}),e}}),K2=Fr({encode(r,e,t){e||(e=new Uint8Array(K2.encodingLength(r))),t||(t=0),typeof r=="string"&&(r=n6(r)),r||(r=new Uint8Array(0));let n=t;t+=2;let i=r.length;return Zo(r,e,t,0,i),t+=i,nt(e,t-n-2,n),K2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=Mt(r,e);e+=2;let i=r.slice(e,e+n);return e+=n,K2.decode.bytes=e-t,i},encodingLength(r){return r?(wh(r)?r.length:Af(r))+2:2}}),U2=Fr({encode(r,e,t){e||(e=new Uint8Array(U2.encodingLength(r))),t||(t=0);let n=t;return t+=2,hi.encode(r.cpu,e,t),t+=hi.encode.bytes,hi.encode(r.os,e,t),t+=hi.encode.bytes,nt(e,t-n-2,n),U2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.cpu=hi.decode(r,e),e+=hi.decode.bytes,n.os=hi.decode(r,e),e+=hi.decode.bytes,U2.decode.bytes=e-t,n},encodingLength(r){return hi.encodingLength(r.cpu)+hi.encodingLength(r.os)+2}}),Jy=Fr({encode(r,e,t){return e||(e=new Uint8Array(Jy.encodingLength(r))),t||(t=0),He.encode(r,e,t+2),nt(e,He.encode.bytes,t),Jy.encode.bytes=He.encode.bytes+2,e},decode(r,e){e||(e=0);let t=He.decode(r,e+2);return Jy.decode.bytes=He.decode.bytes+2,t},encodingLength(r){return He.encodingLength(r)+2}}),N2=Fr({encode(r,e,t){e||(e=new Uint8Array(N2.encodingLength(r))),t||(t=0),nt(e,r.priority||0,t+2),nt(e,r.weight||0,t+4),nt(e,r.port||0,t+6),He.encode(r.target,e,t+8);let n=He.encode.bytes+6;return nt(e,n,t),N2.encode.bytes=n+2,e},decode(r,e){e||(e=0);let t=Mt(r,e),n={};return n.priority=Mt(r,e+2),n.weight=Mt(r,e+4),n.port=Mt(r,e+6),n.target=He.decode(r,e+8),N2.decode.bytes=t+2,n},encodingLength(r){return 8+He.encodingLength(r.target)}}),xf=Fr({encode(r,e,t){let n=xf.encodingLength(r);return e||(e=new Uint8Array(xf.encodingLength(r))),t||(t=0),r.issuerCritical&&(r.flags=xf.ISSUER_CRITICAL),nt(e,n-2,t),t+=2,e[t]=r.flags||0,t+=1,hi.encode(r.tag,e,t),t+=hi.encode.bytes,i6(e,r.value,t),t+=Af(r.value),xf.encode.bytes=n,e},decode(r,e){e||(e=0);let t=Mt(r,e);e+=2;let n=e,i={};return i.flags=r[e],e+=1,i.tag=hi.decode(r,e),e+=hi.decode.bytes,i.value=hb(r,e,n+t),i.issuerCritical=!!(i.flags&xf.ISSUER_CRITICAL),xf.decode.bytes=t+2,i},encodingLength(r){return hi.encodingLength(r.tag)+hi.encodingLength(r.value)+2}});xf.ISSUER_CRITICAL=128;L2=Fr({encode(r,e,t){e||(e=new Uint8Array(L2.encodingLength(r))),t||(t=0);let n=t;return t+=2,nt(e,r.preference||0,t),t+=2,He.encode(r.exchange,e,t),t+=He.encode.bytes,nt(e,t-n-2,n),L2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.preference=Mt(r,e),e+=2,n.exchange=He.decode(r,e),e+=He.decode.bytes,L2.decode.bytes=e-t,n},encodingLength(r){return 4+He.encodingLength(r.exchange)}}),X7=Fr({encode(r,e,t){return e||(e=new Uint8Array(X7.encodingLength(r))),t||(t=0),nt(e,4,t),t+=2,Bd.encode(r,e,t),e},decode(r,e){return e||(e=0),e+=2,Bd.decode(r,e)},bytes:6}),q2=Fr({encode(r,e,t){return e||(e=new Uint8Array(q2.encodingLength(r))),t||(t=0),nt(e,16,t),t+=2,kf.encode(r,e,t),q2.encode.bytes=18,e},decode(r,e){e||(e=0),e+=2;let t=kf.decode(r,e);return q2.decode.bytes=18,t},bytes:18}),Lq=r=>new Uint8Array(r),Ll=Fr({encode(r,e,t){e||(e=new Uint8Array(Ll.encodingLength(r))),t||(t=0);let n=t,i=Kq(r.code);if(nt(e,i,t),t+=2,r.data)nt(e,r.data.length,t),t+=2,Zo(r.data,e,t),t+=r.data.length;else switch(i){case 8:{let a=r.sourcePrefixLength||0,s=r.family||jhe(r.ip,Lq),o=Mhe(r.ip,Lq),c=Math.ceil(a/8);nt(e,c+4,t),t+=2,nt(e,s,t),t+=2,e[t++]=a,e[t++]=r.scopePrefixLength||0,Zo(o,e,t,0,c),t+=c}break;case 11:r.timeout?(nt(e,2,t),t+=2,nt(e,r.timeout,t),t+=2):(nt(e,0,t),t+=2);break;case 12:{let a=r.length||0;nt(e,a,t),t+=2,e.fill(0,t,t+a),t+=a}break;case 14:{let a=r.tags.length*2;nt(e,a,t),t+=2;for(let s of r.tags)nt(e,s,t),t+=2}break;default:throw new Error(`Unknown roption code: ${r.code}`)}return Ll.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t={};t.code=Mt(r,e),t.type=Lhe(t.code),e+=2;let n=Mt(r,e);switch(e+=2,t.data=r.slice(e,e+n),t.code){case 8:t.family=Mt(r,e),e+=2,t.sourcePrefixLength=r[e++],t.scopePrefixLength=r[e++];{let i=new Uint8Array(t.family===1?4:16);Zo(r,i,0,e,e+n-4),t.ip=Khe(i)}break;case 11:n>0&&(t.timeout=Mt(r,e),e+=2);break;case 14:t.tags=[];for(let i=0;i<n;i+=2)t.tags.push(Mt(r,e)),e+=2}return Ll.decode.bytes=n+4,t},encodingLength(r){if(r.data)return r.data.length+4;switch(Kq(r.code)){case 8:{let e=r.sourcePrefixLength||0;return Math.ceil(e/8)+8}case 11:return typeof r.timeout=="number"?6:4;case 12:return r.length+4;case 14:return 4+r.tags.length*2}throw new Error(`Unknown roption code: ${r.code}`)}}),Ef=Fr({encode(r,e,t){e||(e=new Uint8Array(Ef.encodingLength(r))),t||(t=0);let n=t,i=Vy(r,Ll);return nt(e,i,t),t=F0(r,Ll,e,t+2),Ef.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=[],i=Mt(r,e);e+=2;let a=0;for(;i>0;)n[a++]=Ll.decode(r,e),e+=Ll.decode.bytes,i-=Ll.decode.bytes;return Ef.decode.bytes=e-t,n},encodingLength(r){return 2+Vy(r||[],Ll)}}),$d=Fr({encode(r,e,t){e||(e=new Uint8Array($d.encodingLength(r))),t||(t=0);let n=t,i=r.key;if(!wh(i))throw new Error("Key must be a Buffer");return t+=2,nt(e,r.flags,t),t+=2,e[t]=$d.PROTOCOL_DNSSEC,t+=1,e[t]=r.algorithm,t+=1,Zo(i,e,t,0,i.length),t+=i.length,$d.encode.bytes=t-n,nt(e,$d.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Mt(r,e);if(e+=2,n.flags=Mt(r,e),e+=2,r[e]!==$d.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=r[e],e+=1,n.key=r.slice(e,t+i+2),e+=n.key.length,$d.decode.bytes=e-t,n},encodingLength(r){return 6+Af(r.key)}});$d.PROTOCOL_DNSSEC=3;$d.ZONE_KEY=128;$d.SECURE_ENTRYPOINT=32768;U0=Fr({encode(r,e,t){e||(e=new Uint8Array(U0.encodingLength(r))),t||(t=0);let n=t,i=r.signature;if(!wh(i))throw new Error("Signature must be a Buffer");return t+=2,nt(e,nb(r.typeCovered),t),t+=2,e[t]=r.algorithm,t+=1,e[t]=r.labels,t+=1,Fl(e,r.originalTTL,t),t+=4,Fl(e,r.expiration,t),t+=4,Fl(e,r.inception,t),t+=4,nt(e,r.keyTag,t),t+=2,He.encode(r.signersName,e,t),t+=He.encode.bytes,Zo(i,e,t,0,i.length),t+=i.length,U0.encode.bytes=t-n,nt(e,U0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Mt(r,e);return e+=2,n.typeCovered=wE(Mt(r,e)),e+=2,n.algorithm=r[e],e+=1,n.labels=r[e],e+=1,n.originalTTL=zl(r,e),e+=4,n.expiration=zl(r,e),e+=4,n.inception=zl(r,e),e+=4,n.keyTag=Mt(r,e),e+=2,n.signersName=He.decode(r,e),e+=He.decode.bytes,n.signature=r.slice(e,t+i+2),e+=n.signature.length,U0.decode.bytes=e-t,n},encodingLength(r){return 20+He.encodingLength(r.signersName)+Af(r.signature)}}),N0=Fr({encode(r,e,t){e||(e=new Uint8Array(N0.encodingLength(r))),t||(t=0);let n=t;return t+=2,He.encode(r.mbox||".",e,t),t+=He.encode.bytes,He.encode(r.txt||".",e,t),t+=He.encode.bytes,N0.encode.bytes=t-n,nt(e,N0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.mbox=He.decode(r,e)||".",e+=He.decode.bytes,n.txt=He.decode(r,e)||".",e+=He.decode.bytes,N0.decode.bytes=e-t,n},encodingLength(r){return 2+He.encodingLength(r.mbox||".")+He.encodingLength(r.txt||".")}}),Jo=Fr({encode(r,e,t){e||(e=new Uint8Array(Jo.encodingLength(r))),t||(t=0);let n=t,i=[];for(let a=0;a<r.length;a++){let s=nb(r[a]);i[s>>8]===void 0&&(i[s>>8]=[]),i[s>>8][s>>3&31]|=1<<7-(s&7)}for(let a=0;a<i.length;a++)if(i[a]!==void 0){let s=n6(i[a]);e[t]=a,t+=1,e[t]=s.length,t+=1,Zo(s,e,t,0,s.length),t+=s.length}return Jo.encode.bytes=t-n,e},decode(r,e,t){e||(e=0);let n=e,i=[];for(;e-n<t;){let a=r[e];e+=1;let s=r[e];e+=1;for(let o=0;o<s;o++){let c=r[e+o];for(let l=0;l<8;l++)if(c&1<<7-l){let d=wE(a<<8|o<<3|l);i.push(d)}}e+=s}return Jo.decode.bytes=e-n,i},encodingLength(r){let e=[];for(let n=0;n<r.length;n++){let i=nb(r[n]);e[i>>8]=Math.max(e[i>>8]||0,i&255)}let t=0;for(let n=0;n<e.length;n++)e[n]!==void 0&&(t+=2+Math.ceil((e[n]+1)/8));return t}}),L0=Fr({encode(r,e,t){e||(e=new Uint8Array(L0.encodingLength(r))),t||(t=0);let n=t;return t+=2,He.encode(r.nextDomain,e,t),t+=He.encode.bytes,Jo.encode(r.rrtypes,e,t),t+=Jo.encode.bytes,L0.encode.bytes=t-n,nt(e,L0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Mt(r,e);return e+=2,n.nextDomain=He.decode(r,e),e+=He.decode.bytes,n.rrtypes=Jo.decode(r,e,i-(e-t)),e+=Jo.decode.bytes,L0.decode.bytes=e-t,n},encodingLength(r){return 2+He.encodingLength(r.nextDomain)+Jo.encodingLength(r.rrtypes)}}),q0=Fr({encode(r,e,t){e||(e=new Uint8Array(q0.encodingLength(r))),t||(t=0);let n=t,i=r.salt;if(!wh(i))throw new Error("salt must be a Buffer");let a=r.nextDomain;if(!wh(a))throw new Error("nextDomain must be a Buffer");return t+=2,e[t]=r.algorithm,t+=1,e[t]=r.flags,t+=1,nt(e,r.iterations,t),t+=2,e[t]=i.length,t+=1,Zo(i,e,t,0,i.length),t+=i.length,e[t]=a.length,t+=1,Zo(a,e,t,0,a.length),t+=a.length,Jo.encode(r.rrtypes,e,t),t+=Jo.encode.bytes,q0.encode.bytes=t-n,nt(e,q0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Mt(r,e);e+=2,n.algorithm=r[e],e+=1,n.flags=r[e],e+=1,n.iterations=Mt(r,e),e+=2;let a=r[e];e+=1,n.salt=r.slice(e,e+a),e+=a;let s=r[e];return e+=1,n.nextDomain=r.slice(e,e+s),e+=s,n.rrtypes=Jo.decode(r,e,i-(e-t)),e+=Jo.decode.bytes,q0.decode.bytes=e-t,n},encodingLength(r){return 8+r.salt.length+r.nextDomain.length+Jo.encodingLength(r.rrtypes)}}),z0=Fr({encode(r,e,t){e||(e=new Uint8Array(z0.encodingLength(r))),t||(t=0);let n=t,i=r.digest;if(!wh(i))throw new Error("Digest must be a Buffer");return t+=2,nt(e,r.keyTag,t),t+=2,e[t]=r.algorithm,t+=1,e[t]=r.digestType,t+=1,Zo(i,e,t,0,i.length),t+=i.length,z0.encode.bytes=t-n,nt(e,z0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Mt(r,e);return e+=2,n.keyTag=Mt(r,e),e+=2,n.algorithm=r[e],e+=1,n.digestType=r[e],e+=1,n.digest=r.slice(e,t+i+2),e+=n.digest.length,z0.decode.bytes=e-t,n},encodingLength(r){return 6+Af(r.digest)}}),Hy=Fr({encode(r,e,t){e||(e=new Uint8Array(Hy.encodingLength(r))),t||(t=0);let n=t;t+=2,e[t]=r.algorithm,t+=1,e[t]=r.hash,t+=1;let i=Uq(r.fingerprint),a=bC(r.hash);if(i!==a)throw new Error(`Invalid length of fingerprint "${r.fingerprint}" for hashType=${r.hash}: ${i} != ${a}`);return zhe(e,r.fingerprint,t,t+=i),Hy.encode.bytes=t-n,nt(e,Hy.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={};e+=2,n.algorithm=r[e],e+=1,n.hash=r[e],e+=1;let i=bC(n.hash);return n.fingerprint=qhe(r,e,e+i),e+=i,Hy.decode.bytes=e-t,n},encodingLength(r){return 4+Uq(r.fingerprint)}});Hy.getFingerprintLengthForHashType=bC;Ca=Fr({encode(r,e,t){e||(e=new Uint8Array(Ca.encodingLength(r))),t||(t=0);let n=t;if(He.encode(r.name,e,t),t+=He.encode.bytes,nt(e,nb(r.type),t),r.type.toUpperCase()==="OPT"){if(r.name!==".")throw new Error("OPT name must be root.");nt(e,r.udpPayloadSize||4096,t+2),e[t+4]=r.extendedRcode||0,e[t+5]=r.ednsVersion||0,nt(e,r.flags||0,t+6),t+=8,Ef.encode(r.options||[],e,t),t+=Ef.encode.bytes}else{let i=W7(r.class===void 0?"IN":r.class);r.flush&&(i|=vC),nt(e,i,t+2),Fl(e,r.ttl||0,t+4),t+=8;let a=aC(r.type);a.encode(r.data,e,t),t+=a.encode.bytes}return Ca.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t={},n=e;if(t.name=He.decode(r,e),e+=He.decode.bytes,t.type=wE(Mt(r,e)),t.type==="OPT")t.udpPayloadSize=Mt(r,e+2),t.extendedRcode=r[e+4],t.ednsVersion=r[e+5],t.flags=Mt(r,e+6),t.flag_do=(t.flags>>15&1)===1,t.options=Ef.decode(r,e+8),e+=8+Ef.decode.bytes;else{let i=Mt(r,e+2);t.ttl=zl(r,e+4),t.class=V7(i&Jhe),t.flush=!!(i&vC);let a=aC(t.type);t.data=a.decode(r,e+8),e+=8+a.decode.bytes}return Ca.decode.bytes=e-n,t},encodingLength(r){let e=r.data!==null&&r.data!==void 0?r.data:r.options;return He.encodingLength(r.name)+8+aC(r.type).encodingLength(e)}}),Zy=Fr({encode(r,e,t){e||(e=new Uint8Array(Zy.encodingLength(r))),t||(t=0);let n=t;return He.encode(r.name,e,t),t+=He.encode.bytes,nt(e,nb(r.type),t),t+=2,nt(e,W7(r.class===void 0?"IN":r.class),t),t+=2,Zy.encode.bytes=t-n,r},decode(r,e){e||(e=0);let t=e,n={};return n.name=He.decode(r,e),e+=He.decode.bytes,n.type=wE(Mt(r,e)),e+=2,n.class=V7(Mt(r,e)),e+=2,n.class&Y7&&(n.class&=Zhe),Zy.decode.bytes=e-t,n},encodingLength(r){return He.encodingLength(r.name)+4}}),Yhe=1024,ns={encode:function(r,e,t){let n=!e;n&&(e=new Uint8Array(Xhe(r))),t||(t=0);let i=t;return r.questions||(r.questions=[]),r.answers||(r.answers=[]),r.authorities||(r.authorities=[]),r.additionals||(r.additionals=[]),qy.encode(r,e,t),t+=qy.encode.bytes,t=F0(r.questions,Zy,e,t),t=F0(r.answers,Ca,e,t),t=F0(r.authorities,Ca,e,t),t=F0(r.additionals,Ca,e,t),ns.encode.bytes=t-i,n&&oE.bytes!==e.length?e.slice(0,oE.bytes):e},decode:function(r,e){e||(e=0);let t=e,n=qy.decode(r,e);return e+=qy.decode.bytes,e=k2(n.questions,Zy,r,e),e=k2(n.answers,Ca,r,e),e=k2(n.authorities,Ca,r,e),e=k2(n.additionals,Ca,r,e),ns.decode.bytes=e-t,n},encodingLength:function(r){return qy.encodingLength(r)+Vy(r.questions||[],Zy)+Vy(r.answers||[],Ca)+Vy(r.authorities||[],Ca)+Vy(r.additionals||[],Ca)}};ns.encode.bytes=0;ns.decode.bytes=0;iE={encode:function(r,e,t){return e=ns.encode(nE(r,"query"),e,t),iE.encode.bytes=ns.encode.bytes,e},decode:function(r,e){let t=ns.decode(r,e);return iE.decode.bytes=ns.decode.bytes,t.questions&&(t.question=t.questions[0],delete t.questions),t},encodingLength:function(r){return ns.encodingLength(nE(r,"query"))}};iE.encode.bytes=0;iE.decode.bytes=0;sE={encode:function(r,e,t){return e=ns.encode(nE(r,"response"),e,t),sE.encode.bytes=ns.encode.bytes,e},decode:function(r,e){let t=ns.decode(r,e);return sE.decode.bytes=ns.decode.bytes,t.questions&&(t.question=t.questions[0],delete t.questions),t},encodingLength:function(r){return ns.encodingLength(nE(r,"response"))}};sE.encode.bytes=0;sE.decode.bytes=0;oE=ns.encode,PC=ns.decode,Xhe=ns.encodingLength;Q7.bytes=0;eF.bytes=0;nF="dht";ime=0,wf=7200,z2=";",Vs=",",oF={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},aF={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};ame="https://enbox-did-dht.fly.dev";dF=class xC extends fb{static async create({keyManager:e=new Dc,options:t={}}={}){if(t.verificationMethods?.some(d=>!(d.algorithm in oF)))throw new Error("One or more verification method algorithms are not supported");let n=t.verificationMethods?.filter(d=>"id"in d).map(d=>d.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(t.services?.some(d=>!d.id||!d.type||!d.serviceEndpoint))throw new Error("One or more services are missing required properties");let i=await e.generateKey({algorithm:"Ed25519"}),a=await e.getPublicKey({keyUri:i}),s=await Wy.identityKeyToIdentifier({identityKey:a}),o={id:s,...t.alsoKnownAs&&{alsoKnownAs:t.alsoKnownAs},...t.controllers&&{controller:t.controllers}},c=[...t.verificationMethods??[]];c?.some(d=>d.id?.split("#").pop()==="0")||c.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let d of c){let u=d.id?.split("#").pop()==="0"?i:await e.generateKey({algorithm:d.algorithm}),f=await e.getPublicKey({keyUri:u}),p=d.id??f.kid??await xr({jwk:f});p=`${s}#${Ws(p)}`,o.verificationMethod??=[],o.verificationMethod.push({id:p,type:"JsonWebKey",controller:d.controller??s,publicKeyJwk:f});for(let h of d.purposes??[])o[h]??=[],o[h].push(p)}t.services?.forEach(d=>{o.service??=[],d.id=`${s}#${d.id.split("#").pop()}`,o.service.push(d)});let l=new xs({uri:s,document:o,metadata:{published:!1,...t.types&&{types:t.types}},keyManager:e});if(t.publish??!0){let d=await xC.publish({did:l,gatewayUri:t.gatewayUri,allowPrivateGatewayUri:t.allowPrivateGatewayUri});l.metadata=d.didDocumentMetadata}return l}static async import({portableDid:e,keyManager:t=new Dc}){if(Vn.parse(e.uri)?.method!==xC.methodName)throw new Xe("methodNotSupported","Method not supported");let n=await xs.import({portableDid:e,keyManager:t});if(!n.document.verificationMethod?.some(i=>i.id?.split("#").pop()==="0"))throw new Xe("invalidDidDocument","DID document must contain an Identity Key");return n}static async getSigningMethod({didDocument:e,methodId:t="#0"}){let n=Vn.parse(e.id);if(n&&n.method!==this.methodName)throw new Xe("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(a=>Ws(a.id)===(Ws(t)??Ws(e.assertionMethod?.[0])));if(!i?.publicKeyJwk)throw new Xe("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async publish({did:e,gatewayUri:t,allowPrivateGatewayUri:n}){let i=zq(t,n);return Fq.put({did:e,...i})}static async resolve(e,t={}){let{gatewayUri:n,allowPrivateGatewayUri:i}=zq(t.gatewayUri,t.allowPrivateGatewayUri);try{await Wy.identifierToIdentityKey({didUri:e});let{didDocument:a,didDocumentMetadata:s}=await Fq.get({didUri:e,gatewayUri:n,allowPrivateGatewayUri:i});return{...is,didDocument:a,didDocumentMetadata:s}}catch(a){if(!(a instanceof Xe))throw new Error(a);return{...is,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};dF.methodName="dht";wo=dF,Fq=class H0{static async get({didUri:e,gatewayUri:t,allowPrivateGatewayUri:n=!1}){let i=Wy.identifierToIdentityKeyBytes({didUri:e}),a=await H0.pkarrGet({gatewayUri:t,publicKeyBytes:i,allowPrivateGatewayUri:n}),s=await Wy.parseBep44GetMessage({bep44Message:a}),o=await H0.fromDnsPacket({didUri:e,dnsPacket:s});return o.didDocumentMetadata.versionId=a.seq.toString(),o}static async put({did:e,gatewayUri:t,allowPrivateGatewayUri:n=!1}){let i=await H0.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[t]}),a=await Wy.createBep44PutMessage({dnsPacket:i,publicKeyBytes:Wy.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),s=await H0.pkarrPut({gatewayUri:t,bep44Message:a,allowPrivateGatewayUri:n});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:s,versionId:a.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return Qhe(e)}static async pkarrPut(e){return eme(e)}static async fromDnsPacket(e){return sme(e)}static async toDnsPacket(e){return ome(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},Wy=class{static async createBep44PutMessage(r){return tme(r)}static async identifierToIdentityKey(r){return iF(r)}static identifierToIdentityKeyBytes(r){return s6(r)}static async identityKeyToIdentifier(r){return nme(r)}static keyConverter(r){return o6(r)}static async parseBep44GetMessage(r){return rme(r)}static parseTxtDataToObject(r){return G0(r)}static parseTxtDataToString(r){return sb(r)}static async validatePreviousDidProof(r){return sF(r)}static chunkDataIfNeeded(r){return cF(r)}},Fn={DeltaExceedsMaximumSize:"DeltaExceedsMaximumSize",DidDocumentPublicKeyIdDuplicated:"DidDocumentPublicKeyIdDuplicated",DidDocumentPublicKeyMissingOrIncorrectType:"DidDocumentPublicKeyMissingOrIncorrectType",DidDocumentServiceIdDuplicated:"DidDocumentServiceIdDuplicated",DidSuffixIncorrectLength:"DidSuffixIncorrectLength",EncodedStringIncorrectEncoding:"EncodedStringIncorrectEncoding",IdNotUsingBase64UrlCharacterSet:"IdNotUsingBase64UrlCharacterSet",IdTooLong:"IdTooLong",JwkEs256kMissingOrInvalidCrv:"JwkEs256kMissingOrInvalidCrv",JwkEs256kMissingOrInvalidKty:"JwkEs256kMissingOrInvalidKty",JwkEs256kHasIncorrectLengthOfX:"JwkEs256kHasIncorrectLengthOfX",JwkEs256kHasIncorrectLengthOfY:"JwkEs256kHasIncorrectLengthOfY",JwkEs256kHasIncorrectLengthOfD:"JwkEs256kHasIncorrectLengthOfD",MultihashStringNotAMultihash:"MultihashStringNotAMultihash",MultihashUnsupportedHashAlgorithm:"MultihashUnsupportedHashAlgorithm",PublicKeyJwkEs256kHasUnexpectedProperty:"PublicKeyJwkEs256kHasUnexpectedProperty",PublicKeyPurposeDuplicated:"PublicKeyPurposeDuplicated",ServiceEndpointCannotBeAnArray:"ServiceEndpointCannotBeAnArray",ServiceEndpointStringNotValidUri:"ServiceEndpointStringNotValidUri",ServiceTypeTooLong:"ServiceTypeTooLong"},Gn=class extends Error{constructor(r,e){super(`${r}: ${e}`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}},RLe=new Uint8Array(0),lme=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")},ume=class{constructor(r,e,t){this.name=r,this.prefix=e,this.baseEncode=t}encode(r){if(r instanceof Uint8Array)return`${this.prefix}${this.baseEncode(r)}`;throw Error("Unknown type, must be binary type")}},fme=class{constructor(r,e,t){if(this.name=r,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=t}decode(r){if(typeof r=="string"){if(r.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(r)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(r.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(r){return lF(this,r)}},pme=class{constructor(r){this.decoders=r}or(r){return lF(this,r)}decode(r){let e=r[0],t=this.decoders[e];if(t)return t.decode(r);throw RangeError(`Unable to decode multibase string ${JSON.stringify(r)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},lF=(r,e)=>new pme({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),hme=class{constructor(r,e,t,n){this.name=r,this.prefix=e,this.baseEncode=t,this.baseDecode=n,this.encoder=new ume(r,e,t),this.decoder=new fme(r,e,n)}encode(r){return this.encoder.encode(r)}decode(r){return this.decoder.decode(r)}},mme=({name:r,prefix:e,encode:t,decode:n})=>new hme(r,e,t,n),yme=(r,e,t,n)=>{let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let a=r.length;for(;r[a-1]==="=";)--a;let s=new Uint8Array(a*t/8|0),o=0,c=0,l=0;for(let d=0;d<a;++d){let u=i[r[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,o+=t,o>=8&&(o-=8,s[l++]=255&c>>o)}if(o>=t||255&c<<8-o)throw new SyntaxError("Unexpected end of data");return s},gme=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,a="",s=0,o=0;for(let c=0;c<r.length;++c)for(o=o<<8|r[c],s+=8;s>t;)s-=t,a+=e[i&o>>s];if(s&&(a+=e[i&o<<t-s]),n)for(;a.length*t&7;)a+="=";return a},vE=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>mme({prefix:e,name:r,encode(i){return gme(i,n,t)},decode(i){return yme(i,n,t,r)}}),CLe=vE({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$Le=vE({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Gq=vE({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),BLe=vE({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),eg=class F2{static encode(e){return Gq.baseEncode(e)}static decodeAsBytes(e,t){if(!F2.isBase64UrlString(e))throw new Gn(Fn.EncodedStringIncorrectEncoding,`Given ${t} must be base64url string.`);return Gq.baseDecode(e)}static decodeAsString(e,t){let n=F2.decodeAsBytes(e,t);return F2.bytesToString(n)}static isBase64UrlString(e){return/^[A-Za-z0-9_-]+$/.test(e)}static stringToBytes(e){return new TextEncoder().encode(e)}static bytesToString(e){return new TextDecoder().decode(e)}},wme=vh(sle(),1);(function(r){r.Public="public",r.Private="private"})(EC||(EC={}));Cd=EC,Ho=class{static validateEs256kOperationKey(r,e){let t=new Set(["kty","crv","x","y"]);e===Cd.Private&&t.add("d");for(let n in r)if(!t.has(n))throw new Gn(Fn.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${n}'.`);if(r.crv!=="secp256k1")throw new Gn(Fn.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${r.crv}.'`);if(r.kty!=="EC")throw new Gn(Fn.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${r.kty}.'`);if(r.x.length!==43)throw new Gn(Fn.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(r.y.length!==43)throw new Gn(Fn.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(e===Cd.Private&&(r.d===void 0||r.d.length!==43))throw new Gn(Fn.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(r){if(r.length>50)throw new Gn(Fn.IdTooLong,`Key ID length ${r.length} exceed max allowed length of 50.`);if(!eg.isBase64UrlString(r))throw new Gn(Fn.IdNotUsingBase64UrlCharacterSet,`Key ID '${r}' is not a Base64URL string.`)}static validatePublicKeyPurposes(r){if(r===void 0)return;let e=new Set;for(let t of r){if(e.has(t))throw new Gn(Fn.PublicKeyPurposeDuplicated,`Public key purpose '${t}' already specified.`);e.add(t)}}},a6=class{};a6.hashAlgorithmInMultihashCode=18;a6.maxCanonicalizedDeltaSizeInBytes=1e3;Ic=a6,vme=vh(ole(),1),ob=class SC{static canonicalizeAsBytes(e){let t=SC.removeAllUndefinedProperties(e),n=vme.default(t);return eg.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let t in e)typeof e[t]=="object"?SC.removeAllUndefinedProperties(e[t]):e[t]===void 0&&delete e[t];return e}},bme=uF,Hq=128,Pme=127,xme=~Pme,Eme=Math.pow(2,31);Sme=kC,kme=128,Vq=127;_me=Math.pow(2,7),Ame=Math.pow(2,14),Tme=Math.pow(2,21),Ime=Math.pow(2,28),Dme=Math.pow(2,35),Rme=Math.pow(2,42),Cme=Math.pow(2,49),$me=Math.pow(2,56),Bme=Math.pow(2,63),Ome=function(r){return r<_me?1:r<Ame?2:r<Tme?3:r<Ime?4:r<Dme?5:r<Rme?6:r<Cme?7:r<$me?8:r<Bme?9:10},jme={encode:bme,decode:Sme,encodingLength:Ome},Mme=jme,aE=Mme,Wq=(r,e=0)=>[aE.decode(r,e),aE.decode.bytes],Jq=(r,e,t=0)=>(aE.encode(r,e,t),e),Zq=r=>aE.encodingLength(r),Yq=(r,e)=>{let t=e.byteLength,n=Zq(r),i=n+Zq(t),a=new Uint8Array(i+t);return Jq(r,a,0),Jq(t,a,n),a.set(e,i),new fF(r,t,e,a)},Kme=r=>{let e=lme(r),[t,n]=Wq(e),[i,a]=Wq(e.subarray(n)),s=e.subarray(n+a);if(s.byteLength!==i)throw new Error("Incorrect length");return new fF(t,i,s,e)},fF=class{constructor(r,e,t,n){this.code=r,this.size=e,this.digest=t,this.bytes=n}},pF=({name:r,code:e,encode:t})=>new Ume(r,e,t),Ume=class{constructor(r,e,t){this.name=r,this.code=e,this.encode=t}digest(r){if(r instanceof Uint8Array){let e=this.encode(r);return e instanceof Uint8Array?Yq(this.code,e):e.then(t=>Yq(this.code,t))}else throw Error("Unknown type, must be binary type")}},hF=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Xq=pF({name:"sha2-256",code:18,encode:hF("SHA-256")}),OLe=pF({name:"sha2-512",code:19,encode:hF("SHA-512")}),$0=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},Wo=class V0{static hash(e,t){return $0(this,void 0,void 0,function*(){let n;switch(t){case 18:n=(yield Xq.digest(e)).bytes;break;default:throw new Gn(Fn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${t} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,t){return $0(this,void 0,void 0,function*(){let n;switch(t){case 18:n=yield Xq.encode(e);break;default:throw new Gn(Fn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${t} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,t){return $0(this,void 0,void 0,function*(){let n=ob.canonicalizeAsBytes(e);return yield V0.hashThenEncode(n,t)})}static canonicalizeThenDoubleHashThenEncode(e,t){return $0(this,void 0,void 0,function*(){let n=ob.canonicalizeAsBytes(e),i=yield V0.hashAsNonMultihashBytes(n,t);return yield V0.hashThenEncode(i,t)})}static hashThenEncode(e,t){return $0(this,void 0,void 0,function*(){let n=yield V0.hash(e,t);return eg.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,t){let n,i=eg.decodeAsBytes(e,t);try{n=Kme(i)}catch{throw new Gn(Fn.MultihashStringNotAMultihash,`Given ${t} string '${e}' is not a multihash after decoding.`)}let a=Ic.hashAlgorithmInMultihashCode;if(a!==n.code)throw new Gn(Fn.MultihashUnsupportedHashAlgorithm,`Given ${t} uses unsupported multihash algorithm with code ${n.code}, should use ${a} or change IonSdkConfig to desired hashing algorithm.`)}};(function(r){r.Create="create",r.Update="update",r.Deactivate="deactivate",r.Recover="recover"})(_C||(_C={}));_2=_C;(function(r){r.Replace="replace",r.AddPublicKeys="add-public-keys",r.RemovePublicKeys="remove-public-keys",r.AddServices="add-services",r.RemoveServices="remove-services"})(AC||(AC={}));Ny=AC,A2=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},mF=class Da{static createCreateRequest(e){return A2(this,void 0,void 0,function*(){let t=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,a=e.document.services;Ho.validateEs256kOperationKey(t,Cd.Public),Ho.validateEs256kOperationKey(n,Cd.Public),Da.validateDidDocumentKeys(i),Da.validateServices(a);let s=Ic.hashAlgorithmInMultihashCode,o=[{action:Ny.Replace,document:e.document}],c={updateCommitment:yield Wo.canonicalizeThenDoubleHashThenEncode(n,s),patches:o};Da.validateDeltaSize(c);let l={deltaHash:yield Wo.canonicalizeThenHashThenEncode(c,s),recoveryCommitment:yield Wo.canonicalizeThenDoubleHashThenEncode(t,s)};return{type:_2.Create,suffixData:l,delta:c}})}static createDeactivateRequest(e){return A2(this,void 0,void 0,function*(){Da.validateDidSuffix(e.didSuffix),Ho.validateEs256kOperationKey(e.recoveryPublicKey,Cd.Public);let t=Ic.hashAlgorithmInMultihashCode,n=yield Wo.canonicalizeThenHashThenEncode(e.recoveryPublicKey,t),i={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},a=yield e.signer.sign({alg:"ES256K"},i);return{type:_2.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:a}})}static createRecoverRequest(e){return A2(this,void 0,void 0,function*(){Da.validateDidSuffix(e.didSuffix),Ho.validateEs256kOperationKey(e.recoveryPublicKey,Cd.Public),Ho.validateEs256kOperationKey(e.nextRecoveryPublicKey,Cd.Public),Ho.validateEs256kOperationKey(e.nextUpdatePublicKey,Cd.Public),Da.validateDidDocumentKeys(e.document.publicKeys),Da.validateServices(e.document.services);let t=Ic.hashAlgorithmInMultihashCode,n=yield Wo.canonicalizeThenHashThenEncode(e.recoveryPublicKey,t),i=[{action:Ny.Replace,document:e.document}],a=yield Wo.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,t),s={patches:i,updateCommitment:a},o=yield Wo.canonicalizeThenHashThenEncode(s,t),c={recoveryCommitment:yield Wo.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,t),recoveryKey:e.recoveryPublicKey,deltaHash:o},l=yield e.signer.sign({alg:"ES256K"},c);return{type:_2.Recover,didSuffix:e.didSuffix,revealValue:n,delta:s,signedData:l}})}static createUpdateRequest(e){return A2(this,void 0,void 0,function*(){if(Da.validateDidSuffix(e.didSuffix),Ho.validateEs256kOperationKey(e.updatePublicKey,Cd.Public),Ho.validateEs256kOperationKey(e.nextUpdatePublicKey,Cd.Public),Da.validateServices(e.servicesToAdd),Da.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let h of e.idsOfServicesToRemove)Ho.validateId(h);if(e.idsOfPublicKeysToRemove!==void 0)for(let h of e.idsOfPublicKeysToRemove)Ho.validateId(h);let t=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let h={action:Ny.AddServices,services:n};t.push(h)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let h={action:Ny.RemoveServices,ids:i};t.push(h)}let a=e.publicKeysToAdd;if(a!==void 0&&a.length>0){let h={action:Ny.AddPublicKeys,publicKeys:a};t.push(h)}let s=e.idsOfPublicKeysToRemove;if(s!==void 0&&s.length>0){let h={action:Ny.RemovePublicKeys,ids:s};t.push(h)}let o=Ic.hashAlgorithmInMultihashCode,c=yield Wo.canonicalizeThenHashThenEncode(e.updatePublicKey,o),l=yield Wo.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,o),d={patches:t,updateCommitment:l},u=yield Wo.canonicalizeThenHashThenEncode(d,o),f={updateKey:e.updatePublicKey,deltaHash:u},p=yield e.signer.sign({alg:"ES256K"},f);return{type:_2.Update,didSuffix:e.didSuffix,revealValue:c,delta:d,signedData:p}})}static validateDidSuffix(e){Wo.validateEncodedHashComputedUsingSupportedHashAlgorithm(e,"didSuffix")}static validateDidDocumentKeys(e){if(e===void 0)return;let t=new Set;for(let n of e){if(Array.isArray(n.publicKeyJwk))throw new Gn(Fn.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(Ho.validateId(n.id),t.has(n.id))throw new Gn(Fn.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);t.add(n.id),Ho.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let t=new Set;for(let n of e){if(Da.validateService(n),t.has(n.id))throw new Gn(Fn.DidDocumentServiceIdDuplicated,"Service id has to be unique");t.add(n.id)}}}static validateService(e){Ho.validateId(e.id);let t=30;if(e.type.length>t){let n=`Service endpoint type length ${e.type.length} exceeds max allowed length of ${t}.`;throw new Gn(Fn.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Gn(Fn.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&wme.parse(e.serviceEndpoint).error!==void 0)throw new Gn(Fn.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let t=ob.canonicalizeAsBytes(e);if(t.length>Ic.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${t.length} bytes exceeded limit of ${Ic.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Gn(Fn.DeltaExceedsMaximumSize,n)}}},Qq=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},Nme=class yF{static createLongFormDid(e){return Qq(this,void 0,void 0,function*(){let t=yield mF.createCreateRequest(e),n=yield yF.computeDidUniqueSuffix(t.suffixData),i;Ic.network===void 0||Ic.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${Ic.network}:${n}`;let a={suffixData:t.suffixData,delta:t.delta},s=ob.canonicalizeAsBytes(a),o=eg.encode(s);return`${i}:${o}`})}static computeDidUniqueSuffix(e){return Qq(this,void 0,void 0,function*(){let t=ob.canonicalizeAsBytes(e),n=yield Wo.hash(t,Ic.hashAlgorithmInMultihashCode);return eg.encode(n)})}},Qi=2n**255n-19n,G2=2n**252n+27742317777372353535851937790883648493n,TC=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,IC=0x6666666666666666666666666666666666666666666666666666666666666658n,T2={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Qi,n:G2,h:8,Gx:TC,Gy:IC},yo=(r="")=>{throw new Error(r)},gF=r=>typeof r=="string",c6=(r,e)=>!(r instanceof Uint8Array)||typeof e=="number"&&e>0&&r.length!==e?yo("Uint8Array expected"):r,tg=r=>new Uint8Array(r),Lme=(r,e)=>c6(gF(r)?l6(r):tg(r),e),at=(r,e=Qi)=>{let t=r%e;return t>=0n?t:e+t},ez=r=>r instanceof rg?r:yo("Point expected"),rg=class zy{constructor(e,t,n,i){this.ex=e,this.ey=t,this.ez=n,this.et=i}static fromAffine(e){return new zy(e.x,e.y,1n,at(e.x*e.y))}static fromHex(e,t=!0){let{d:n}=T2;e=Lme(e,32);let i=e.slice();i[31]=e[31]&-129;let a=zme(i);a===0n||(t&&!(0n<a&&a<Qi)&&yo("bad y coord 1"),!t&&!(0n<a&&a<2n**256n)&&yo("bad y coord 2"));let s=at(a*a),o=at(s-1n),c=at(n*s+1n),{isValid:l,value:d}=Gme(o,c);l||yo("bad y coordinate 3");let u=(d&1n)===1n;return(e[31]&128)!==0!==u&&(d=at(-d)),new zy(d,a,1n,at(d*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){let{ex:t,ey:n,ez:i}=this,{ex:a,ey:s,ez:o}=ez(e),c=at(t*o),l=at(a*i),d=at(n*o),u=at(s*i);return c===l&&d===u}is0(){return this.equals(H2)}negate(){return new zy(at(-this.ex),this.ey,this.ez,at(-this.et))}double(){let{ex:e,ey:t,ez:n}=this,{a:i}=T2,a=at(e*e),s=at(t*t),o=at(2n*at(n*n)),c=at(i*a),l=e+t,d=at(at(l*l)-a-s),u=c+s,f=u-o,p=c-s,h=at(d*f),m=at(u*p),y=at(d*p),v=at(f*u);return new zy(h,m,v,y)}add(e){let{ex:t,ey:n,ez:i,et:a}=this,{ex:s,ey:o,ez:c,et:l}=ez(e),{a:d,d:u}=T2,f=at(t*s),p=at(n*o),h=at(a*u*l),m=at(i*c),y=at((t+n)*(s+o)-f-p),v=at(m-h),w=at(m+h),E=at(p-d*f),_=at(y*v),A=at(w*E),D=at(y*E),M=at(v*w);return new zy(_,A,M,D)}mul(e,t=!0){if(e===0n)return t===!0?yo("cannot multiply by 0"):H2;if(typeof e=="bigint"&&0n<e&&e<G2||yo("invalid scalar, must be < L"),!t&&this.is0()||e===1n)return this;if(this.equals(cE))return Wme(e).p;let n=H2,i=cE;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):t&&(i=i.add(a));return n}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(T2.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(G2/2n,!1).double();return G2%2n&&(e=e.add(this)),e.is0()}toAffine(){let{ex:e,ey:t,ez:n}=this;if(this.is0())return{x:0n,y:0n};let i=vF(n);return at(n*i)!==1n&&yo("invalid inverse"),{x:at(e*i),y:at(t*i)}}toRawBytes(){let{x:e,y:t}=this.toAffine(),n=qme(t);return n[31]|=e&1n?128:0,n}toHex(){return d6(this.toRawBytes())}};rg.BASE=new rg(TC,IC,1n,at(TC*IC));rg.ZERO=new rg(0n,1n,1n,0n);({BASE:cE,ZERO:H2}=rg),wF=(r,e)=>r.toString(16).padStart(e,"0"),d6=r=>Array.from(r).map(e=>wF(e,2)).join(""),l6=r=>{let e=r.length;(!gF(r)||e%2)&&yo("hex invalid 1");let t=tg(e/2);for(let n=0;n<t.length;n++){let i=n*2,a=r.slice(i,i+2),s=Number.parseInt(a,16);(Number.isNaN(s)||s<0)&&yo("hex invalid 2"),t[n]=s}return t},qme=r=>l6(wF(r,32*2)).reverse(),zme=r=>BigInt("0x"+d6(tg(c6(r)).reverse())),rz=(...r)=>{let e=tg(r.reduce((n,i)=>n+c6(i).length,0)),t=0;return r.forEach(n=>{e.set(n,t),t+=n.length}),e},vF=(r,e=Qi)=>{(r===0n||e<=0n)&&yo("no inverse n="+r+" mod="+e);let t=at(r,e),n=e,i=0n,a=1n,s=1n,o=0n;for(;t!==0n;){let c=n/t,l=n%t,d=i-s*c,u=a-o*c;n=t,t=l,i=s,a=o,s=d,o=u}return n===1n?at(i,e):yo("no inverse")},Id=(r,e)=>{let t=r;for(;e-- >0n;)t*=t,t%=Qi;return t},Fme=r=>{let e=r*r%Qi*r%Qi,t=Id(e,2n)*e%Qi,n=Id(t,1n)*r%Qi,i=Id(n,5n)*n%Qi,a=Id(i,10n)*i%Qi,s=Id(a,20n)*a%Qi,o=Id(s,40n)*s%Qi,c=Id(o,80n)*o%Qi,l=Id(c,80n)*o%Qi,d=Id(l,10n)*i%Qi;return{pow_p_5_8:Id(d,2n)*r%Qi,b2:e}},nz=19681161376707505956807079304988542015446066515923890162744021073123829784752n,Gme=(r,e)=>{let t=at(e*e*e),n=at(t*t*e),i=Fme(r*n).pow_p_5_8,a=at(r*t*i),s=at(e*a*a),o=a,c=at(a*nz),l=s===r,d=s===at(-r),u=s===at(-r*nz);return l&&(a=o),(d||u)&&(a=c),(at(a)&1n)===1n&&(a=at(-a)),{isValid:l||d,value:a}},iz=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,Hme={bytesToHex:d6,hexToBytes:l6,concatBytes:rz,mod:at,invert:vF,randomBytes:r=>{let e=iz();return e||yo("crypto.getRandomValues must be defined"),e.getRandomValues(tg(r))},sha512Async:async(...r)=>{let e=iz();e||yo("crypto.subtle or etc.sha512Async must be defined");let t=rz(...r);return tg(await e.subtle.digest("SHA-512",t.buffer))},sha512Sync:void 0};Object.defineProperties(Hme,{sha512Sync:{configurable:!1,get(){return cC},set(r){cC||(cC=r)}}});dh=8,Vme=()=>{let r=[],e=256/dh+1,t=cE,n=t;for(let i=0;i<e;i++){n=t,r.push(n);for(let a=1;a<2**(dh-1);a++)n=n.add(t),r.push(n);t=n.double()}return r},Wme=r=>{let e=tz||(tz=Vme()),t=(d,u)=>{let f=u.negate();return d?f:u},n=H2,i=cE,a=1+256/dh,s=2**(dh-1),o=BigInt(2**dh-1),c=2**dh,l=BigInt(dh);for(let d=0;d<a;d++){let u=d*s,f=Number(r&o);r>>=l,f>s&&(f-=c,r+=1n);let p=u,h=u+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?i=i.add(t(m,e[p])):n=n.add(t(y,e[h]))}return{p:n,f:i}},u6=2n**256n,mh=u6-0x1000003d1n,f6=u6-0x14551231950b75fc4402da1732fc9bebfn,bF=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,PF=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,xF={p:mh,n:f6,a:0n,b:7n,Gx:bF,Gy:PF},Yy=32,sz=r=>Ye(Ye(r*r)*r+xF.b),Ti=(r="")=>{throw new Error(r)},bE=r=>typeof r=="bigint",EF=r=>typeof r=="string",dC=r=>bE(r)&&0n<r&&r<mh,SF=r=>bE(r)&&0n<r&&r<f6,kF=(r,e)=>!(r instanceof Uint8Array)||typeof e=="number"&&e>0&&r.length!==e?Ti("Uint8Array expected"):r,ab=r=>new Uint8Array(r),p6=(r,e)=>kF(EF(r)?PE(r):ab(r),e),Ye=(r,e=mh)=>{let t=r%e;return t>=0n?t:e+t},oz=r=>r instanceof ng?r:Ti("Point expected"),ng=class Fy{constructor(e,t,n){this.px=e,this.py=t,this.pz=n}static fromAffine(e){return new Fy(e.x,e.y,1n)}static fromHex(e){e=p6(e);let t,n=e[0],i=e.subarray(1),a=cz(i,0,Yy),s=e.length;if(s===33&&[2,3].includes(n)){dC(a)||Ti("Point hex invalid: x not FE");let o=Jme(sz(a)),c=(o&1n)===1n;(n&1)===1!==c&&(o=Ye(-o)),t=new Fy(a,o,1n)}return s===65&&n===4&&(t=new Fy(a,cz(i,Yy,2*Yy),1n)),t?t.ok():Ti("Point is not on curve")}static fromPrivateKey(e){return Y0.mul(Zme(e))}get x(){return this.aff().x}get y(){return this.aff().y}equals(e){let{px:t,py:n,pz:i}=this,{px:a,py:s,pz:o}=oz(e),c=Ye(t*o),l=Ye(a*i),d=Ye(n*o),u=Ye(s*i);return c===l&&d===u}negate(){return new Fy(this.px,Ye(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:t,py:n,pz:i}=this,{px:a,py:s,pz:o}=oz(e),{a:c,b:l}=xF,d=0n,u=0n,f=0n,p=Ye(l*3n),h=Ye(t*a),m=Ye(n*s),y=Ye(i*o),v=Ye(t+n),w=Ye(a+s);v=Ye(v*w),w=Ye(h+m),v=Ye(v-w),w=Ye(t+i);let E=Ye(a+o);return w=Ye(w*E),E=Ye(h+y),w=Ye(w-E),E=Ye(n+i),d=Ye(s+o),E=Ye(E*d),d=Ye(m+y),E=Ye(E-d),f=Ye(c*w),d=Ye(p*y),f=Ye(d+f),d=Ye(m-f),f=Ye(m+f),u=Ye(d*f),m=Ye(h+h),m=Ye(m+h),y=Ye(c*y),w=Ye(p*w),m=Ye(m+y),y=Ye(h-y),y=Ye(c*y),w=Ye(w+y),h=Ye(m*w),u=Ye(u+h),h=Ye(E*w),d=Ye(v*d),d=Ye(d-h),h=Ye(v*m),f=Ye(E*f),f=Ye(f+h),new Fy(d,u,f)}mul(e,t=!0){if(!t&&e===0n)return V2;if(SF(e)||Ti("invalid scalar"),this.equals(Y0))return eye(e).p;let n=V2,i=Y0;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):t&&(i=i.add(a));return n}mulAddQUns(e,t,n){return this.mul(t,!1).add(e.mul(n,!1)).ok()}toAffine(){let{px:e,py:t,pz:n}=this;if(this.equals(V2))return{x:0n,y:0n};if(n===1n)return{x:e,y:t};let i=AF(n);return Ye(n*i)!==1n&&Ti("invalid inverse"),{x:Ye(e*i),y:Ye(t*i)}}assertValidity(){let{x:e,y:t}=this.aff();return(!dC(e)||!dC(t))&&Ti("Point invalid: x or y"),Ye(t*t)===sz(e)?this:Ti("Point invalid: not on curve")}multiply(e){return this.mul(e)}aff(){return this.toAffine()}ok(){return this.assertValidity()}toHex(e=!0){let{x:t,y:n}=this.aff();return(e?(n&1n)===0n?"02":"03":"04")+dz(t)+(e?"":dz(n))}toRawBytes(e=!0){return PE(this.toHex(e))}};ng.BASE=new ng(bF,PF,1n);ng.ZERO=new ng(0n,1n,0n);({BASE:Y0,ZERO:V2}=ng),_F=(r,e)=>r.toString(16).padStart(e,"0"),h6=r=>Array.from(r).map(e=>_F(e,2)).join(""),PE=r=>{let e=r.length;(!EF(r)||e%2)&&Ti("hex invalid 1");let t=ab(e/2);for(let n=0;n<t.length;n++){let i=n*2,a=r.slice(i,i+2),s=Number.parseInt(a,16);(Number.isNaN(s)||s<0)&&Ti("hex invalid 2"),t[n]=s}return t},xE=r=>BigInt("0x"+(h6(r)||"0")),cz=(r,e,t)=>xE(r.slice(e,t)),m6=r=>bE(r)&&r>=0n&&r<u6?PE(_F(r,2*Yy)):Ti("bigint expected"),dz=r=>h6(m6(r)),lz=(...r)=>{let e=ab(r.reduce((n,i)=>n+kF(i).length,0)),t=0;return r.forEach(n=>{e.set(n,t),t+=n.length}),e},AF=(r,e=mh)=>{(r===0n||e<=0n)&&Ti("no inverse n="+r+" mod="+e);let t=Ye(r,e),n=e,i=0n,a=1n,s=1n,o=0n;for(;t!==0n;){let c=n/t,l=n%t,d=i-s*c,u=a-o*c;n=t,t=l,i=s,a=o,s=d,o=u}return n===1n?Ye(i,e):Ti("no inverse")},Jme=r=>{let e=1n;for(let t=r,n=(mh+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*t%mh),t=t*t%mh;return Ye(e*e)===r?e:Ti("sqrt invalid")},Zme=r=>(bE(r)||(r=xE(p6(r,Yy))),SF(r)?r:Ti("private key out of range")),uz=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;Xme={hexToBytes:PE,bytesToHex:h6,concatBytes:lz,bytesToNumberBE:xE,numberToBytesBE:m6,mod:Ye,invert:AF,hmacSha256Async:async(r,...e)=>{let t=uz();if(!t)return Ti("etc.hmacSha256Async not set");let n=t.subtle,i=await n.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return ab(await n.sign("HMAC",i,lz(...e)))},hmacSha256Sync:W2,hashToPrivateKey:Yme,randomBytes:r=>{let e=uz();return e||Ti("crypto.getRandomValues must be defined"),e.getRandomValues(ab(r))}};Object.defineProperties(Xme,{hmacSha256Sync:{configurable:!1,get(){return W2},set(r){W2||(W2=r)}}});lh=8,Qme=()=>{let r=[],e=256/lh+1,t=Y0,n=t;for(let i=0;i<e;i++){n=t,r.push(n);for(let a=1;a<2**(lh-1);a++)n=n.add(t),r.push(n);t=n.double()}return r},eye=r=>{let e=az||(az=Qme()),t=(d,u)=>{let f=u.negate();return d?f:u},n=V2,i=Y0,a=1+256/lh,s=2**(lh-1),o=BigInt(2**lh-1),c=2**lh,l=BigInt(lh);for(let d=0;d<a;d++){let u=d*s,f=Number(r&o);r>>=l,f>s&&(f-=c,r+=1n);let p=u,h=u+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?i=i.add(t(m,e[p])):n=n.add(t(y,e[h]))}return{p:n,f:i}};(function(r){r.Mainnet="mainnet",r.Testnet="test"})(fz||(fz={}));(function(r){r.Authentication="authentication",r.AssertionMethod="assertionMethod",r.CapabilityInvocation="capabilityInvocation",r.CapabilityDelegation="capabilityDelegation",r.KeyAgreement="keyAgreement"})(pz||(pz={}));B0=class ah{static appendPathToUrl({baseUrl:e,path:t}){let n=new URL(e);return n.pathname=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",n.pathname+=t.startsWith("/")?t.substring(1):t,n.toString()}static async computeLongFormDidUri({recoveryKey:e,updateKey:t,services:n,verificationMethods:i}){let a=await ah.createIonDocument({services:n,verificationMethods:i}),s=ah.normalizeJwk(e),o=ah.normalizeJwk(t);return await Nme.createLongFormDid({document:a,recoveryKey:s,updateKey:o})}static async constructCreateRequest({ionDocument:e,recoveryKey:t,updateKey:n}){return await mF.createCreateRequest({document:e,recoveryKey:ah.normalizeJwk(t),updateKey:ah.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:t}){let n=[];for(let a of t){let s=a.id??a.publicKeyJwk.kid??await xr({jwk:a.publicKeyJwk});s=`${s.split("#").pop()}`;let o={id:s,publicKeyJwk:ah.normalizeJwk(a.publicKeyJwk),purposes:a.purposes,type:"JsonWebKey2020"};n.push(o)}let i=e.map(a=>({...a,id:`${a.id.split("#").pop()}`}));return{publicKeys:n,services:i}}static normalizeJwk(e){let t=e.kty,n;if(t==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(t==="oct")n={k:e.k,kty:e.kty};else if(t==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(t==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${t}`);return n}},tye=(r=>(r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.secp256r1="secp256r1",r.X25519="X25519",r))(tye||{}),rye={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},hz="https://ion.tbd.engineering",nye=class W0 extends fb{static async create({keyManager:e=new Dc,options:t={}}={}){if(t.verificationMethods?.some(h=>!(h.algorithm in rye)))throw new Error("One or more verification method algorithms are not supported");let n=t.verificationMethods?.filter(h=>"id"in h).map(h=>h.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(t.services?.some(h=>!h.id||!h.type||!h.serviceEndpoint))throw new Error("One or more services are missing required properties");let i={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},a=[];for(let h of t.verificationMethods??[i]){let m=await e.generateKey({algorithm:h.algorithm}),y=await e.getPublicKey({keyUri:m});a.push({id:h.id,publicKeyJwk:y,purposes:h.purposes??["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let s=await e.generateKey({algorithm:"secp256k1"}),o=await e.getPublicKey({keyUri:s}),c=await e.generateKey({algorithm:"secp256k1"}),l=await e.getPublicKey({keyUri:c}),d=await B0.computeLongFormDidUri({recoveryKey:o,updateKey:l,services:t.services??[],verificationMethods:a}),{didDocument:u,didResolutionMetadata:f}=await W0.resolve(d,{gatewayUri:t.gatewayUri});if(u===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let p=new xs({uri:d,document:u,metadata:{published:!1,canonicalId:d.split(":",3).join(":"),recoveryKey:o,updateKey:l},keyManager:e});if(t.publish??!0){let h=await W0.publish({did:p,gatewayUri:t.gatewayUri});p.metadata=h.didDocumentMetadata}return p}static async getSigningMethod({didDocument:e,methodId:t}){let n=Vn.parse(e.id);if(n&&n.method!==this.methodName)throw new Xe("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(a=>a.id===(t??e.assertionMethod?.[0]));if(!i?.publicKeyJwk)throw new Xe("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async import({portableDid:e,keyManager:t=new Dc}){if(Vn.parse(e.uri)?.method!==W0.methodName)throw new Xe("methodNotSupported","Method not supported");return await xs.import({portableDid:e,keyManager:t})}static async publish({did:e,gatewayUri:t=hz}){let n=e.document.verificationMethod?.map(s=>({id:s.id,publicKeyJwk:s.publicKeyJwk,purposes:R7({didDocument:e.document,methodId:s.id})}))??[],i=await B0.createIonDocument({services:e.document.service??[],verificationMethods:n}),a=await B0.constructCreateRequest({ionDocument:i,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let s=B0.appendPathToUrl({baseUrl:t,path:"/operations"}),o=await fetch(s,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(3e4)});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:o.ok},didRegistrationMetadata:{}}}catch{return{didDocument:null,didDocumentMetadata:{published:!1},didRegistrationMetadata:{error:"internalError",errorMessage:`Failed to publish DID document for: ${e.uri}`}}}}static async resolve(e,t={}){let n=Vn.parse(e);if(!n)return{...is,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==W0.methodName)return{...is,didResolutionMetadata:{error:"methodNotSupported"}};let i=t?.gatewayUri??hz;try{let a=B0.appendPathToUrl({baseUrl:i,path:`/identifiers/${e}`}),s=await fetch(a,{signal:AbortSignal.timeout(3e4)});if(!s.ok)throw new Xe("notFound",`Unable to find DID document for: ${e}`);let{didDocument:o,didDocumentMetadata:c}=await s.json();return{...is,...o&&{didDocument:o},didDocumentMetadata:{published:c?.method?.published,...c}}}catch(a){if(!(a instanceof Xe))throw new Error(a);return{...is,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};nye.methodName="ion";TF=class J0 extends fb{static async create({keyManager:e=new Dc,options:t={}}={}){if(t.algorithm&&t.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(t.verificationMethods&&t.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=t.algorithm??t.verificationMethods?.[0]?.algorithm??"Ed25519",i=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:i}),s=rt.object(a).toBase64Url(),o=`did:${J0.methodName}:${s}`,c=(await J0.resolve(o)).didDocument;return new xs({uri:o,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let t=Vn.parse(e.id);if(t&&t.method!==this.methodName)throw new Xe("methodNotSupported",`Method not supported: ${t.method}`);let[n]=e.verificationMethod??[];if(!n?.publicKeyJwk)throw new Xe("internalError","A verification method intended for signing could not be determined from the DID Document");return n}static async import({portableDid:e,keyManager:t=new Dc}){if(Vn.parse(e.uri)?.method!==J0.methodName)throw new Xe("methodNotSupported","Method not supported");let n=await xs.import({portableDid:e,keyManager:t});if(n.document.verificationMethod.length!==1)throw new Xe("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,t){let n=Vn.parse(e),i;try{i=n?rt.base64Url(n.id).toObject():void 0}catch{}if(!n||!i)return{...is,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==J0.methodName)return{...is,didResolutionMetadata:{error:"methodNotSupported"}};let a={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},s=`${a.id}#0`;switch(a.verificationMethod=[{id:s,type:"JsonWebKey",controller:a.id,publicKeyJwk:i}],a.authentication=[s],a.assertionMethod=[s],a.capabilityInvocation=[s],a.capabilityDelegation=[s],a.keyAgreement=[s],i.use){case"sig":{delete a.keyAgreement;break}case"enc":{delete a.authentication,delete a.assertionMethod,delete a.capabilityInvocation,delete a.capabilityDelegation;break}}return{...is,didDocument:a}}};TF.methodName="jwk";Xo=TF,iye={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},J2=class Gy{static async jwkToMulticodec({jwk:e}){let t=[];e.crv&&(t.push(e.crv),e.d?t.push("private"):t.push("public"));let n=t.join(":"),i=Gy.JWK_TO_MULTICODEC[n];if(i===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:Ka.getCodeFromName({name:i}),name:i}}static keyCompressor(e){let t={"P-256":bs.compressPublicKey,secp256k1:es.compressPublicKey}[e];if(!t)throw new Xe("invalidPublicKeyType",`Unsupported curve: ${e}`);return t}static keyConverter(e){let t={Ed25519:ts,"P-256":bs,secp256k1:es}[e];if(!t)throw new Xe("invalidPublicKeyType",`Unsupported curve: ${e}`);return t}static async multicodecToJwk({code:e,name:t}){if(!(t?!e:e))throw new Error("Either 'name' or 'code' must be defined, but not both.");t=t===void 0?Ka.getNameFromCode({code:e}):t;let n=t,i=Gy.MULTICODEC_TO_JWK[n];if(i===void 0)throw new Error("Unsupported Multicodec to JWK conversion");return{...i}}static async publicKeyToMultibaseId({publicKey:e}){if(!(e?.crv&&e.crv in iye))throw new Xe("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let t=await Gy.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(t=await Gy.keyCompressor(e.crv)({publicKeyBytes:t}));let{name:n}=await Gy.jwkToMulticodec({jwk:e});return $7({keyBytes:t,multicodecName:n})}};J2.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},J2.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},J2.MULTICODEC_TO_JWK={"ed25519-pub":{crv:"Ed25519",kty:"OKP",x:""},"ed25519-priv":{crv:"Ed25519",kty:"OKP",x:"",d:""},"secp256k1-pub":{crv:"secp256k1",kty:"EC",x:"",y:""},"secp256k1-priv":{crv:"secp256k1",kty:"EC",x:"",y:"",d:""}};I2=J2,sye=(r=>(r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.secp256r1="secp256r1",r))(sye||{}),mz={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},IF=class Pf extends fb{static async create({keyManager:e=new Dc,options:t={}}={}){if(t.algorithm&&t.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(t.verificationMethods&&t.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=t.algorithm??t.verificationMethods?.[0]?.algorithm??"Ed25519",i=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:i}),s=await I2.publicKeyToMultibaseId({publicKey:a}),o=`did:${Pf.methodName}:${s}`,c=(await Pf.resolve(o,t)).didDocument;return new xs({uri:o,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let t=Vn.parse(e.id);if(t&&t.method!==this.methodName)throw new Xe("methodNotSupported",`Method not supported: ${t.method}`);let[n]=e.assertionMethod||[],i=e.verificationMethod?.find(a=>a.id===n);if(!i?.publicKeyJwk)throw new Xe("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async import({portableDid:e,keyManager:t=new Dc}){if(Vn.parse(e.uri)?.method!==Pf.methodName)throw new Xe("methodNotSupported","Method not supported");let n=await xs.import({portableDid:e,keyManager:t});if(n.document.verificationMethod.length!==1)throw new Xe("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,t){try{let n=await Pf.createDocument({didUri:e,options:t});return{...is,didDocument:n}}catch(n){if(!(n instanceof Xe))throw new Error(n);return{...is,didResolutionMetadata:{error:n.code,...n.message&&{errorMessage:n.message}}}}}static async createDocument({didUri:e,options:t={}}){let{defaultContext:n="https://www.w3.org/ns/did/v1",enableExperimentalPublicKeyTypes:i=!1,publicKeyFormat:a="JsonWebKey2020"}=t,s={id:""},o=Vn.parse(e);if(!o)throw new Xe("invalidDid",`Invalid DID URI: ${e}`);let c=o.id;if(o.method!==Pf.methodName)throw new Xe("methodNotSupported",`Method not supported: ${o.method}`);if(!Pf.validateIdentifier(o))throw new Xe("invalidDid",`Invalid DID URI: ${e}`);let l=await Pf.createSignatureMethod({didUri:e,multibaseValue:c,options:{enableExperimentalPublicKeyTypes:i,publicKeyFormat:a}});s.id=o.uri,s.verificationMethod=[l],s.authentication=[l.id],s.assertionMethod=[l.id],s.capabilityInvocation=[l.id],s.capabilityDelegation=[l.id];let d=[n];return D7({didDocument:s}).forEach(u=>{let f=mz[u];d.push(f)}),s["@context"]=d,s}static async createSignatureMethod({didUri:e,multibaseValue:t,options:n}){let{enableExperimentalPublicKeyTypes:i,publicKeyFormat:a}=n,s={id:"",type:"",controller:""},{keyBytes:o,multicodecCode:c,multicodecName:l}=B7({multibaseKeyId:t}),d=o.byteLength,u=I2.MULTICODEC_PUBLIC_KEY_LENGTH[c];if(d!==u)throw new Xe("invalidPublicKeyLength",`Expected ${d} bytes. Actual: ${u}`);let f=!1;switch(l){case"secp256k1-pub":f=await es.validatePublicKey({publicKeyBytes:o});break;case"ed25519-pub":f=await ts.validatePublicKey({publicKeyBytes:o});break}if(!f)throw new Xe("invalidPublicKey","Invalid public key detected.");s.id=`${e}#${t}`;try{new URL(s.id)}catch{throw new Xe("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(a in mz))throw new Xe("unsupportedPublicKeyType",`Unsupported format: ${a}`);if(i===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(a))throw new Xe("invalidPublicKeyType",`Specified '${a}' without setting enableExperimentalPublicKeyTypes to true.`);if(s.type=a,s.controller=e,a==="Ed25519VerificationKey2020"&&(s.publicKeyMultibase=t),a==="JsonWebKey2020"){let{crv:p}=await I2.multicodecToJwk({code:c});s.publicKeyJwk=await I2.keyConverter(p).bytesToPublicKey({publicKeyBytes:o})}return s}static validateIdentifier(e){let{method:t,id:n}=e,[i]=e.uri.split(":",1);return i==="did"&&t==="key"&&!0&&lC(n)==="String"&&n.startsWith("z")}};IF.methodName="key";mb=IF,oye=3e4,DF=class Z2 extends fb{static async create({keyManager:e=new Dc,options:t}){if(!t.domain)throw new Xe("invalidDid","The 'domain' option is required for did:web creation");if(t.algorithm&&t.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");let n=t.path?`${t.domain}:${t.path}`:t.domain,i=`did:${Z2.methodName}:${n}`;if(!Vn.parse(i))throw new Xe("invalidDid",`The constructed DID URI is invalid: ${i}`);let a=t.verificationMethods??[{algorithm:t.algorithm??"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]}],s={"@context":["https://www.w3.org/ns/did/v1"],id:i};for(let o=0;o<a.length;o++){let c=a[o],l=await e.generateKey({algorithm:c.algorithm}),d=await e.getPublicKey({keyUri:l}),u=c.id?.split("#").pop()??`key-${o}`,f=`${i}#${u}`;s.verificationMethod??=[],s.verificationMethod.push({id:f,type:"JsonWebKey",controller:c.controller??i,publicKeyJwk:d});for(let p of c.purposes??[])s[p]??=[],s[p].push(f)}return t.services&&(s.service=t.services.map(o=>({...o,id:`${i}#${o.id.split("#").pop()}`}))),new xs({uri:i,document:s,metadata:{published:!1},keyManager:e})}static async getSigningMethod({didDocument:e,methodId:t}){let n=Vn.parse(e.id);if(n&&n.method!==this.methodName)throw new Xe("methodNotSupported",`Method not supported: ${n.method}`);let i=Ws(t)??Ws(e.assertionMethod?.[0]),a=i?e.verificationMethod?.find(s=>Ws(s.id)===i):e.verificationMethod?.[0];if(!a?.publicKeyJwk)throw new Xe("internalError","A verification method intended for signing could not be determined from the DID Document");return a}static async import({portableDid:e,keyManager:t=new Dc}){if(Vn.parse(e.uri)?.method!==Z2.methodName)throw new Xe("methodNotSupported","Method not supported");return await xs.import({portableDid:e,keyManager:t})}static async resolve(e,t){let n=Vn.parse(e);if(!n)return{...is,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==Z2.methodName)return{...is,didResolutionMetadata:{error:"methodNotSupported"}};let i=`https://${n.id.replace(/:/g,"/")}`;i=decodeURIComponent(i);let a=n.id.includes(":")?`${i}/did.json`:`${i}/.well-known/did.json`;try{let s=await Oz(a,{signal:AbortSignal.timeout(oye)},{description:"did:web document URL"});if(!s.ok)throw new Error("HTTP error status code returned");let o=await s.json();return{...is,didDocument:o}}catch{return{...is,didResolutionMetadata:{error:"notFound"}}}}};DF.methodName="web";RF=DF,aye=vh(kz(),1),cye=vh(_z(),1),EE=class{constructor({db:r,location:e="DATA/DID_RESOLVERCACHE",ttl:t="15m"}={}){this.cache=r??new aye.Level(e),this.ttl=(0,cye.default)(t)}open(){return this.cache.open()}async get(r){try{let e=await this.cache.get(r),t=JSON.parse(e);if(Date.now()>=t.ttlMillis){this.cache.nextTick(()=>this.cache.del(r));return}else return t.value}catch(e){if(e.notFound)return;throw e}}set(r,e){let t={ttlMillis:Date.now()+this.ttl,value:e},n=JSON.stringify(t);return this.cache.put(r,n)}delete(r){return this.cache.del(r)}clear(){return this.cache.clear()}close(){return this.cache.close()}},dye=vh(_z(),1),SE=class{constructor({ttl:r="15m"}={}){this.cache=new cle.default({ttl:(0,dye.default)(r)})}async open(){}async get(r){if(!r)throw new Error("Key cannot be null or undefined");return this.cache.get(r)}async set(r,e){this.cache.set(r,e)}async delete(r){this.cache.delete(r)}async clear(){this.cache.clear()}async close(){}},lye={open(){return Promise.resolve()},get(r){return Promise.resolve(void 0)},set(r,e){return Promise.resolve()},delete(r){return Promise.resolve()},clear(){return Promise.resolve()},close(){return Promise.resolve()}},ag=class{constructor({cache:r,didResolvers:e}){this.didResolvers=new Map,this._inFlight=new Map,this.cache=r||lye;for(let t of e)this.didResolvers.set(t.methodName,t)}async open(){await this.cache.open()}async close(){await this.cache.close()}async resolve(r,e){let t=Vn.parse(r);if(!t)return{...is,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${r}`}};let n=this.didResolvers.get(t.method);if(!n)return{...is,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${t.method}`}};if(e!==void 0)return n.resolve(t.uri,e);let i=await this.cache.get(t.uri);if(i)return i;let a=this._inFlight.get(t.uri);if(a)return a;let s=(async()=>{let o=await n.resolve(t.uri,e);if(!o.didResolutionMetadata.error)try{await this.cache.set(t.uri,o)}catch{}return o})();this._inFlight.set(t.uri,s);try{return await s}finally{this._inFlight.delete(t.uri)}}async dereference(r,e){let t=Vn.parse(r);if(!t)return{dereferencingMetadata:{error:"invalidDidUrl"},contentStream:null,contentMetadata:{}};let{didDocument:n,didResolutionMetadata:i,didDocumentMetadata:a}=await this.resolve(t.uri);if(!n)return{dereferencingMetadata:{error:i.error},contentStream:null,contentMetadata:{}};if(!t.fragment||t.query)return{dereferencingMetadata:{contentType:"application/did+json"},contentStream:n,contentMetadata:a};let{service:s=[],verificationMethod:o=[]}=n,c=new Set([r,t.fragment,`#${t.fragment}`]),l;for(let d of o)if(c.has(d.id)){l=d;break}for(let d of s)if(c.has(d.id)){l=d;break}return l?{dereferencingMetadata:{contentType:"application/did+json"},contentStream:l,contentMetadata:i}:{dereferencingMetadata:{error:"notFound"},contentStream:null,contentMetadata:{}}}};});var cg,CF=G(()=>{"use strict";g();WI();VI();yr();zo();BU();jU();KU();Fo();$9();B9();V9();W9();J9();Z9();Y9();X9();m2();QR();Qo();ar();cg=class r{methodHandlers;didResolver;messageStore;dataStore;resumableTaskStore;stateIndex;tenantGate;eventLog;storageController;resumableTaskManager;_coreProtocols;ownsResolver;constructor(e){this.didResolver=e.didResolver,this.ownsResolver=e.ownsResolver??!1,this.tenantGate=e.tenantGate,this.messageStore=e.messageStore,this.dataStore=e.dataStore,this.resumableTaskStore=e.resumableTaskStore,this.stateIndex=e.stateIndex,this.eventLog=e.eventLog,this.storageController=new Uy({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new h2(e.resumableTaskStore,this.storageController),this._coreProtocols=new vy,this._coreProtocols.register(new et);let t={didResolver:this.didResolver,messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,resumableTaskManager:this.resumableTaskManager,coreProtocols:this._coreProtocols,eventLog:this.eventLog};this.methodHandlers={[ve.Messages+me.Read]:new Px(t),[ve.Messages+me.Subscribe]:new Sx(t),[ve.Messages+me.Sync]:new _x(t),[ve.Protocols+me.Configure]:new l2(t),[ve.Protocols+me.Query]:new f2(t),[ve.Records+me.Count]:new p2(t),[ve.Records+me.Delete]:new y2(t),[ve.Records+me.Query]:new g2(t),[ve.Records+me.Read]:new w2(t),[ve.Records+me.Subscribe]:new b2(t),[ve.Records+me.Write]:new P2(t)}}static async create(e){e.didResolver||(e.didResolver=new ag({didResolvers:[wo,Xo,mb,RF],cache:new SE}),e.ownsResolver=!0),e.tenantGate??=new by;let t=new r(e);return await t.open(),t}async open(){let e=this.didResolver;this.ownsResolver&&typeof e.open=="function"&&await e.open(),await this.messageStore.open(),await this.dataStore.open(),await this.resumableTaskStore.open(),await this.stateIndex.open(),await this.eventLog?.open(),await this.resumableTaskManager.resumeTasksAndWaitForCompletion()}async close(){await this.eventLog?.close(),await this.messageStore.close(),await this.dataStore.close(),await this.resumableTaskStore.close(),await this.stateIndex.close();let e=this.didResolver;this.ownsResolver&&typeof e.close=="function"&&await e.close()}get coreProtocols(){return this._coreProtocols}get storage(){return{messageStore:this.messageStore,stateIndex:this.stateIndex,eventLog:this.eventLog}}async processMessage(e,t,n={}){let i=await this.validateTenant(e)??await this.validateMessageIntegrity(t);if(i!==void 0)return i;let{dataStream:a,subscriptionHandler:s}=n,o=t.descriptor.interface+t.descriptor.method;return await this.methodHandlers[o].handle({tenant:e,message:t,dataStream:a,subscriptionHandler:s})}async validateTenant(e){let t=await this.tenantGate.isActiveTenant(e);if(!t.isActiveTenant)return{status:{code:401,detail:t.detail??`DID ${e} is not an active tenant.`}}}async validateMessageIntegrity(e){let t=e?.descriptor?.interface,n=e?.descriptor?.method;if(t===void 0||n===void 0)return{status:{code:400,detail:`Both interface and method must be present, interface: ${t}, method: ${n}`}};try{ye.validateJsonSchema(e)}catch(i){return mt(i,400)}}}});function uye(r){return new Promise((e,t)=>{if(r.aborted){t(r.reason);return}r.addEventListener("abort",()=>{t(r.reason)})})}async function Wn(r,e){return e?Promise.race([r,uye(e)]):r}var kE=G(()=>{"use strict";g()});import{Level as fye}from"level";async function Js(r,e){return new fye(r,{...e,keyEncoding:"utf8"})}var Na,Tf=G(()=>{"use strict";g();kE();Na=class r{config;db;constructor(e,t){this.config={createLevelDatabase:Js,...e},this.db=t}async open(){switch(await this.createLevelDatabase(),this.db.status){case"open":return;case"opening":return new Promise(e=>{this.db.once("open",e)});case"closing":return new Promise((e,t)=>{let n=()=>{this.db.open().then(e).catch(t)};this.db.once("closed",n)});case"closed":return this.db.open()}}async close(){if(this.db)switch(this.db.status){case"open":return this.db.close();case"opening":return new Promise((e,t)=>{let n=()=>{this.db.close().then(e).catch(t)};this.db.once("open",n)});case"closing":return new Promise(e=>{this.db.once("closed",e)});case"closed":return}}async partition(e){return await this.createLevelDatabase(),new r(this.config,this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding}))}async get(e,t){t?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),t?.signal);try{return await Wn(this.db.get(String(e)),t?.signal)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async has(e,t){return!!await this.get(e,t)}async*keys(e){e?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),e?.signal);for await(let t of this.db.keys())e?.signal?.throwIfAborted(),yield t}async*iterator(e,t){t?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),t?.signal);for await(let n of this.db.iterator(e))t?.signal?.throwIfAborted(),yield n}async put(e,t,n){return n?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),n?.signal),Wn(this.db.put(String(e),t),n?.signal)}async delete(e,t){return t?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),t?.signal),Wn(this.db.del(String(e)),t?.signal)}async isEmpty(e){for await(let t of this.keys(e))return!1;return!0}async clear(){await this.createLevelDatabase(),await this.db.clear(),await this.compactUnderlyingStorage()}async batch(e,t){return t?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),t?.signal),Wn(this.db.batch(e),t?.signal)}createPartitionOperation(e,t){return{...t,sublevel:this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}async compactUnderlyingStorage(e){e?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),e?.signal);let t=this.sublevelRange;if(!t)return;let n=this.root;if(n.db.supports.additionalMethods.compactRange)return Wn(n.db.compactRange?.(...t),e?.signal)}get sublevelRange(){let e=this.db.prefix;if(!e)return;let t=e.slice(0,-1)+String.fromCharCode(e.charCodeAt(e.length-1)+1);return[e,t]}get root(){let e=this.db;for(let t=e.db;t&&t!==e;)e=t;return new r(this.config,e)}async createLevelDatabase(){this.db??=await this.config.createLevelDatabase(this.config.location,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}});var If,_E=G(()=>{"use strict";g();Cw();Tf();If=class r{config;db;constructor(e,t){this.config={createLevelDatabase:Js,...e},this.db=t??new Na({...this.config,valueEncoding:"binary"})}async open(){return this.db.open()}async close(){return this.db.close()}async partition(e){let t=await this.db.partition(e);return new r({...this.config,location:""},t)}async put(e,t,n){return await this.db.put(String(e),t,n),Yt.parse(e.toString())}async get(e,t){return await this.db.get(String(e),t)}async has(e,t){return this.db.has(String(e),t)}async delete(e,t){return this.db.delete(String(e),t)}async isEmpty(e){return this.db.isEmpty(e)}async*putMany(e,t){for await(let n of e)await this.put(n.cid,n.block,t),yield n.cid}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}async*getAll(e){let t=this.db.iterator({keys:!0,keyEncoding:"buffer"},e);for await(let[n,i]of t)yield{cid:Yt.decode(n),block:i}}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async clear(){return this.db.clear()}}});function pye(r){return r[Symbol.asyncIterator]!=null}function hye(r){if(pye(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 $F,BF=G(()=>{g();$F=hye});var OF,mye,jF,yye,MF,KF=G(()=>{g();Ff();nm();OF=0,mye="identity",jF=Ha,yye=r=>Zf(OF,jF(r)),MF={code:OF,name:mye,encode:jF,digest:yye}});var UF,gye,NF,LF=G(()=>{g();Dm();UF=An(ca(),1);dl();gye=async(r,e,t,n,i,a,s,o)=>{let c=await s.get(r,o),l=O_(c),d=l,u=t;for(;n.length>0;){let f=n[0];if(f in d){n.shift(),u=`${u}/${f}`;let p=Yt.asCID(d[f]);if(p!=null)return{entry:{type:"object",name:e,path:t,cid:r,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield l}},next:{cid:p,name:f,path:u,toResolve:n}};d=d[f]}else throw(0,UF.default)(new Error(`No property named ${f} found in cbor node ${r}`),"ERR_NO_PROP")}return{entry:{type:"object",name:e,path:t,cid:r,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield l}}}},NF=gye});function wye(r,e,t,n){let i=BigInt(r.length),a=BigInt(e+i);return t>=a||n<e?new Uint8Array(0):(n>=e&&n<a&&(r=r.subarray(0,Number(n-e))),t>=e&&t<a&&(r=r.subarray(Number(t-e))),r)}var Ah,AE=G(()=>{g();Ah=wye});var yb,vye,dg,TE=G(()=>{g();yb=An(ca(),1),vye=(r,e=0,t=r)=>{let n=BigInt(r),i=BigInt(e??0),a=BigInt(t);if(a!==n&&(a=i+a),a>n&&(a=n),i<0n)throw(0,yb.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,yb.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(a<0n)throw(0,yb.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(a>n)throw(0,yb.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:i,end:a}},dg=vye});var qF,bye,Pye,zF,FF=G(()=>{g();qF=An(ca(),1);nm();ul();AE();TE();bye=r=>{async function*e(t={}){let{start:n,end:i}=dg(r.length,t.offset,t.length),a=Ah(r,0n,n,i);t.onProgress?.(new Rn("unixfs:exporter:progress:identity",{bytesRead:BigInt(a.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield a}return e},Pye=async(r,e,t,n,i,a,s,o)=>{if(n.length>0)throw(0,qF.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=e1(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:bye(c.digest),depth:a,size:BigInt(c.digest.length),node:c.digest}}},zF=Pye});var GF,xye,Eye,HF,VF=G(()=>{g();GF=An(ca(),1);ul();AE();TE();xye=r=>{async function*e(t={}){let{start:n,end:i}=dg(r.length,t.offset,t.length),a=Ah(r,0n,n,i);t.onProgress?.(new Rn("unixfs:exporter:progress:raw",{bytesRead:BigInt(a.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield a}return e},Eye=async(r,e,t,n,i,a,s,o)=>{if(n.length>0)throw(0,GF.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=await s.get(r,o);return{entry:{type:"raw",name:e,path:t,cid:r,content:xye(c),depth:a,size:BigInt(c.length),node:c}}},HF=Eye});var Sye,kye,WF,_ye,JF,ZF,YF=G(()=>{g();da();OA();jA();Sye=async function(r){return(await rP.encode(r)).slice(0,8).reverse()},kye=async(r,e,t)=>{await Promise.all(r.map(async n=>{if(n.Name==null)throw new Error("Unexpected Link without a Name");if(n.Name.length===2){let i=parseInt(n.Name,16);e._putObjectAt(i,new Vc({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(n.Name.substring(2),!0)}))},WF=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),_ye=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},JF=async(r,e,t,n,i)=>{if(n==null){let d=sP({hashFn:Sye});n={rootBucket:d,hamtDepth:1,lastBucket:d}}await kye(r.Links,n.lastBucket,n.rootBucket);let a=await n.rootBucket._findNewBucketAndPos(e),s=WF(a.pos),o=_ye(a);o.length>n.hamtDepth&&(n.lastBucket=o[n.hamtDepth],s=WF(n.lastBucket._posAtParent));let c=r.Links.find(d=>{if(d.Name==null)return!1;let u=d.Name.substring(0,2),f=d.Name.substring(2);return!(u!==s||f!==""&&f!==e)});if(c==null)return;if(c.Name!=null&&c.Name.substring(2)===e)return c.Hash;n.hamtDepth++;let l=await t.get(c.Hash,i);return r=ll(l),JF(r,e,t,n,i)},ZF=JF});function Aye(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var IE,y6=G(()=>{g();IE=Aye});function Tye(r){return r[Symbol.asyncIterator]!=null}function Iye(r,e){let t=0;if(Tye(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=IE(r),{value:i,done:a}=n.next();if(a===!0)return function*(){}();let s=e(i,t++);if(typeof s.then=="function")return async function*(){await s&&(yield i);for(let c of n)await e(c,t++)&&(yield c)}();let o=e;return function*(){s===!0&&(yield i);for(let c of n)o(c,t++)&&(yield c)}()}var XF,QF=G(()=>{g();y6();XF=Iye});function Dye(r){return r[Symbol.asyncIterator]!=null}function Rye(r,e){let t=0;if(Dye(r))return async function*(){for await(let c of r)yield e(c,t++)}();let n=IE(r),{value:i,done:a}=n.next();if(a===!0)return function*(){}();let s=e(i,t++);if(typeof s.then=="function")return async function*(){yield await s;for(let c of n)yield e(c,t++)}();let o=e;return function*(){yield s;for(let c of n)yield o(c,t++)}()}var lg,DE=G(()=>{g();y6();lg=Rye});function vo(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var RE=G(()=>{g()});async function*Th(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,i=new EventTarget,a=[],s=vo(),o=vo(),c=!1,l,d=!1;i.addEventListener("task-complete",()=>{o.resolve()}),Promise.resolve().then(async()=>{try{for await(let h of r){if(a.length===t&&(s=vo(),await s.promise),d)break;let m={done:!1};a.push(m),h().then(y=>{m.done=!0,m.ok=!0,m.value=y,i.dispatchEvent(new CE("task-complete"))},y=>{m.done=!0,m.err=y,i.dispatchEvent(new CE("task-complete"))})}c=!0,i.dispatchEvent(new CE("task-complete"))}catch(h){l=h,i.dispatchEvent(new CE("task-complete"))}});function u(){return n?a[0]?.done:!!a.find(h=>h.done)}function*f(){for(;a.length>0&&a[0].done;){let h=a[0];if(a.shift(),h.ok)yield h.value;else throw d=!0,s.resolve(),h.err;s.resolve()}}function*p(){for(;u();)for(let h=0;h<a.length;h++)if(a[h].done){let m=a[h];if(a.splice(h,1),h--,m.ok)yield m.value;else throw d=!0,s.resolve(),m.err;s.resolve()}}for(;;){if(u()||(o=vo(),await o.promise),l!=null||(n?yield*f():yield*p(),l!=null))throw l;if(c&&a.length===0)break}}var CE,$E=G(()=>{g();RE();CE=globalThis.CustomEvent??Event});var BE,ug,eG=G(()=>{g();BE=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}},ug=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new BE(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 BE(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()}}});function OE(r={}){return Cye(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 Cye(r,e){e=e??{};let t=e.onEnd,n=new ug,i,a,s,o=vo(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,v)=>{a=w=>{a=null,n.push(w);try{y(r(n))}catch(E){v(E)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{o.resolve(),o=vo()})}},l=y=>a!=null?a(y):(n.push(y),i),d=y=>(n=new ug,a!=null?a({error:y}):(n.push({error:y}),i)),u=y=>{if(s)return i;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})},f=y=>s?i:(s=!0,y!=null?d(y):l({done:!0})),p=()=>(n=new ug,f(),{done:!0}),h=y=>(f(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:h,push:u,end:f,get readableLength(){return n.size},onEmpty:async y=>{let v=y?.signal;if(v?.throwIfAborted(),n.isEmpty())return;let w,E;v!=null&&(w=new Promise((_,A)=>{E=()=>{A(new g6)},v.addEventListener("abort",E)}));try{await Promise.race([o.promise,w])}finally{E!=null&&v!=null&&v?.removeEventListener("abort",E)}}},t==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(y){return m.end(y),t!=null&&(t(y),t=void 0),i},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},i}var g6,w6=G(()=>{g();RE();eG();g6=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}});function $ye(r){return r.reason}async function tG(r,e,t){if(e==null)return r;let n=t?.translateError??$ye;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([r,new Promise((a,s)=>{i=()=>{s(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var rG=G(()=>{g()});function nG(){return new v6}var v6,iG=G(()=>{g();RE();rG();v6=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=vo(),this.haveNext=vo()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=vo(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=vo(),await tG(this.readNext.promise,t?.signal,t)}}});function Bye(r){return r[Symbol.asyncIterator]!=null}async function Oye(r,e,t){try{await Promise.all(r.map(async n=>{for await(let i of n)await e.push(i,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*jye(r){let e=new AbortController,t=nG();Oye(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Mye(r){for(let e of r)yield*e}function Kye(...r){let e=[];for(let t of r)Bye(t)||e.push(t);return e.length===r.length?Mye(e):jye(r)}var sG,oG=G(()=>{g();iG();sG=Kye});function fg(r,...e){if(r==null)throw new Error("Empty pipeline");if(b6(r)){let n=r;r=()=>n.source}else if(cG(r)||aG(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&b6(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++)b6(t[n])&&(t[n]=Nye(t[n]));return Uye(...t)}var Uye,aG,cG,b6,Nye,jE=G(()=>{g();w6();oG();Uye=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},aG=r=>r?.[Symbol.asyncIterator]!=null,cG=r=>r?.[Symbol.iterator]!=null,b6=r=>r==null?!1:r.sink!=null&&r.source!=null,Nye=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=OE({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let i,a=r.source;if(aG(a))i=async function*(){yield*a,n.end()};else if(cG(a))i=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return sG(n,i())}return r.source}});var Lye,dG,lG=G(()=>{g();QF();DE();$E();jE();ul();Lye=(r,e,t,n,i,a,s)=>{async function*o(c={}){let l=c.offset??0,d=c.length??e.Links.length,u=e.Links.slice(l,d);c.onProgress?.(new Rn("unixfs:exporter:walk:directory",{cid:r})),yield*fg(u,f=>lg(f,p=>async()=>{let h=p.Name??"",m=`${n}/${h}`;return(await i(p.Hash,h,m,[],a+1,s,c)).entry}),f=>Th(f,{ordered:!0}),f=>XF(f,p=>p!=null))}return o},dG=Lye});var fG=ke((zze,P6)=>{"use strict";g();var qye=Object.prototype.hasOwnProperty,Zs="~";function gb(){}Object.create&&(gb.prototype=Object.create(null),new gb().__proto__||(Zs=!1));function zye(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function uG(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var a=new zye(t,n||r,i),s=Zs?Zs+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],a]:r._events[s].push(a):(r._events[s]=a,r._eventsCount++),r}function ME(r,e){--r._eventsCount===0?r._events=new gb:delete r._events[e]}function Es(){this._events=new gb,this._eventsCount=0}Es.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)qye.call(t,n)&&e.push(Zs?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Es.prototype.listeners=function(e){var t=Zs?Zs+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,s=new Array(a);i<a;i++)s[i]=n[i].fn;return s};Es.prototype.listenerCount=function(e){var t=Zs?Zs+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Es.prototype.emit=function(e,t,n,i,a,s){var o=Zs?Zs+e:e;if(!this._events[o])return!1;var c=this._events[o],l=arguments.length,d,u;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,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,s),!0}for(u=1,d=new Array(l-1);u<l;u++)d[u-1]=arguments[u];c.fn.apply(c.context,d)}else{var f=c.length,p;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,i);break;default:if(!d)for(p=1,d=new Array(l-1);p<l;p++)d[p-1]=arguments[p];c[u].fn.apply(c[u].context,d)}}return!0};Es.prototype.on=function(e,t,n){return uG(this,e,t,n,!1)};Es.prototype.once=function(e,t,n){return uG(this,e,t,n,!0)};Es.prototype.removeListener=function(e,t,n,i){var a=Zs?Zs+e:e;if(!this._events[a])return this;if(!t)return ME(this,a),this;var s=this._events[a];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&ME(this,a);else{for(var o=0,c=[],l=s.length;o<l;o++)(s[o].fn!==t||i&&!s[o].once||n&&s[o].context!==n)&&c.push(s[o]);c.length?this._events[a]=c.length===1?c[0]:c:ME(this,a)}return this};Es.prototype.removeAllListeners=function(e){var t;return e?(t=Zs?Zs+e:e,this._events[t]&&ME(this,t)):(this._events=new gb,this._eventsCount=0),this};Es.prototype.off=Es.prototype.removeListener;Es.prototype.addListener=Es.prototype.on;Es.prefixed=Zs;Es.EventEmitter=Es;typeof P6<"u"&&(P6.exports=Es)});var x6,pG=G(()=>{g();x6=An(fG(),1)});function S6(r,e,t,n){let i,a=new Promise((s,o)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){s(r);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&o(mG(c)),c.addEventListener("abort",()=>{o(mG(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{s(t())}catch(d){o(d)}return}let c=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,l=t instanceof Error?t:new wb(c);typeof r.cancel=="function"&&r.cancel(),o(l)},e),(async()=>{try{s(await r)}catch(c){o(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return a.clear=()=>{clearTimeout(i),i=void 0},a}var wb,E6,hG,mG,yG=G(()=>{g();wb=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},E6=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},hG=r=>globalThis.DOMException===void 0?new E6(r):new DOMException(r),mG=r=>{let e=r.reason===void 0?hG("This operation was aborted."):r.reason;return e instanceof Error?e:hG(e)}});function k6(r,e,t){let n=0,i=r.length;for(;i>0;){let a=Math.trunc(i/2),s=n+a;t(r[s],e)<=0?(n=++s,i-=a+1):i=a}return n}var gG=G(()=>{g()});var Ih,Wl,_6,wG,vG=G(()=>{g();gG();Ih=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},_6=class{constructor(){Wl.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&Ih(this,Wl,"f")[this.size-1].priority>=t.priority){Ih(this,Wl,"f").push(n);return}let i=k6(Ih(this,Wl,"f"),n,(a,s)=>s.priority-a.priority);Ih(this,Wl,"f").splice(i,0,n)}dequeue(){let e=Ih(this,Wl,"f").shift();return e?.run}filter(e){return Ih(this,Wl,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return Ih(this,Wl,"f").length}};Wl=new WeakMap;wG=_6});var kn,Ve,Jn,bb,Pb,Rf,zE,xb,KE,Rc,vb,ea,UE,ta,Eb,Df,NE,bG,PG,SG,xG,EG,LE,A6,T6,FE,kG,qE,GE,I6,_G,AG=G(()=>{g();pG();yG();vG();kn=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Ve=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},GE=class extends Error{},I6=class extends x6.default{constructor(e){var t,n,i,a;if(super(),Jn.add(this),bb.set(this,void 0),Pb.set(this,void 0),Rf.set(this,0),zE.set(this,void 0),xb.set(this,void 0),KE.set(this,0),Rc.set(this,void 0),vb.set(this,void 0),ea.set(this,void 0),UE.set(this,void 0),ta.set(this,0),Eb.set(this,void 0),Df.set(this,void 0),NE.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:wG,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${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 \`${(a=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""}\` (${typeof e.interval})`);kn(this,bb,e.carryoverConcurrencyCount,"f"),kn(this,Pb,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),kn(this,zE,e.intervalCap,"f"),kn(this,xb,e.interval,"f"),kn(this,ea,new e.queueClass,"f"),kn(this,UE,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,kn(this,NE,e.throwOnTimeout===!0,"f"),kn(this,Df,e.autoStart===!1,"f")}get concurrency(){return Ve(this,Eb,"f")}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})`);kn(this,Eb,e,"f"),Ve(this,Jn,"m",FE).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:Ve(this,NE,"f"),...t},new Promise((n,i)=>{Ve(this,ea,"f").enqueue(async()=>{var a,s,o;kn(this,ta,(s=Ve(this,ta,"f"),s++,s),"f"),kn(this,Rf,(o=Ve(this,Rf,"f"),o++,o),"f");try{if(!((a=t.signal)===null||a===void 0)&&a.aborted)throw new GE("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=S6(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,Ve(this,Jn,"m",kG).call(this,t.signal)]));let l=await c;n(l),this.emit("completed",l)}catch(c){if(c instanceof wb&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{Ve(this,Jn,"m",SG).call(this)}},t),this.emit("add"),Ve(this,Jn,"m",LE).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return Ve(this,Df,"f")?(kn(this,Df,!1,"f"),Ve(this,Jn,"m",FE).call(this),this):this}pause(){kn(this,Df,!0,"f")}clear(){kn(this,ea,new(Ve(this,UE,"f")),"f")}async onEmpty(){Ve(this,ea,"f").size!==0&&await Ve(this,Jn,"m",qE).call(this,"empty")}async onSizeLessThan(e){Ve(this,ea,"f").size<e||await Ve(this,Jn,"m",qE).call(this,"next",()=>Ve(this,ea,"f").size<e)}async onIdle(){Ve(this,ta,"f")===0&&Ve(this,ea,"f").size===0||await Ve(this,Jn,"m",qE).call(this,"idle")}get size(){return Ve(this,ea,"f").size}sizeBy(e){return Ve(this,ea,"f").filter(e).length}get pending(){return Ve(this,ta,"f")}get isPaused(){return Ve(this,Df,"f")}};bb=new WeakMap,Pb=new WeakMap,Rf=new WeakMap,zE=new WeakMap,xb=new WeakMap,KE=new WeakMap,Rc=new WeakMap,vb=new WeakMap,ea=new WeakMap,UE=new WeakMap,ta=new WeakMap,Eb=new WeakMap,Df=new WeakMap,NE=new WeakMap,Jn=new WeakSet,bG=function(){return Ve(this,Pb,"f")||Ve(this,Rf,"f")<Ve(this,zE,"f")},PG=function(){return Ve(this,ta,"f")<Ve(this,Eb,"f")},SG=function(){var e;kn(this,ta,(e=Ve(this,ta,"f"),e--,e),"f"),Ve(this,Jn,"m",LE).call(this),this.emit("next")},xG=function(){Ve(this,Jn,"m",T6).call(this),Ve(this,Jn,"m",A6).call(this),kn(this,vb,void 0,"f")},EG=function(){let e=Date.now();if(Ve(this,Rc,"f")===void 0){let t=Ve(this,KE,"f")-e;if(t<0)kn(this,Rf,Ve(this,bb,"f")?Ve(this,ta,"f"):0,"f");else return Ve(this,vb,"f")===void 0&&kn(this,vb,setTimeout(()=>{Ve(this,Jn,"m",xG).call(this)},t),"f"),!0}return!1},LE=function(){if(Ve(this,ea,"f").size===0)return Ve(this,Rc,"f")&&clearInterval(Ve(this,Rc,"f")),kn(this,Rc,void 0,"f"),this.emit("empty"),Ve(this,ta,"f")===0&&this.emit("idle"),!1;if(!Ve(this,Df,"f")){let e=!Ve(this,Jn,"a",EG);if(Ve(this,Jn,"a",bG)&&Ve(this,Jn,"a",PG)){let t=Ve(this,ea,"f").dequeue();return t?(this.emit("active"),t(),e&&Ve(this,Jn,"m",A6).call(this),!0):!1}}return!1},A6=function(){Ve(this,Pb,"f")||Ve(this,Rc,"f")!==void 0||(kn(this,Rc,setInterval(()=>{Ve(this,Jn,"m",T6).call(this)},Ve(this,xb,"f")),"f"),kn(this,KE,Date.now()+Ve(this,xb,"f"),"f"))},T6=function(){Ve(this,Rf,"f")===0&&Ve(this,ta,"f")===0&&Ve(this,Rc,"f")&&(clearInterval(Ve(this,Rc,"f")),kn(this,Rc,void 0,"f")),kn(this,Rf,Ve(this,bb,"f")?Ve(this,ta,"f"):0,"f"),Ve(this,Jn,"m",FE).call(this)},FE=function(){for(;Ve(this,Jn,"m",LE).call(this););},kG=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new GE("The task was aborted."))},{once:!0})})},qE=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};_G=I6});async function TG(r,e,t,n,i,a,s){if(e instanceof Uint8Array){let l=Ah(e,n,i,a);t.push(l);return}if(e.Data==null)throw(0,Dh.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let o;try{o=bi.unmarshal(e.Data)}catch(l){throw(0,Dh.default)(l,"ERR_NOT_UNIXFS")}if(o.data!=null){let l=o.data,d=Ah(l,n,i,a);t.push(d),n+=BigInt(d.byteLength)}let c=[];if(e.Links.length!==o.blockSizes.length)throw(0,Dh.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let l=0;l<e.Links.length;l++){let d=e.Links[l],u=n,f=u+o.blockSizes[l];if((i>=u&&i<f||a>=u&&a<=f||i<u&&a>f)&&c.push({link:d,blockStart:n}),n=f,n>a)break}await fg(c,l=>lg(l,d=>async()=>{let u=await r.get(d.link.Hash,s);return{...d,block:u}}),l=>Th(l,{ordered:!0}),async l=>{for await(let{link:d,block:u,blockStart:f}of l){let p;switch(d.Hash.code){case Mw:p=ll(u);break;case xu:p=u;break;default:t.end((0,Dh.default)(new Error(`Unsupported codec: ${d.Hash.code}`),"ERR_NOT_UNIXFS"));return}let h=new _G({concurrency:1});h.on("error",m=>{t.end(m)}),h.add(async()=>{s.onProgress?.(new Rn("unixfs:exporter:walk:file",{cid:d.Hash})),await TG(r,p,t,f,i,a,s)}),await h.onIdle()}}),n>=a&&t.end()}var Dh,Fye,D6,IG=G(()=>{g();da();Dh=An(ca(),1);Pu();DE();$E();jE();w6();Gw();AG();ul();AE();TE();Fye=(r,e,t,n,i,a,s)=>{async function*o(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:d,end:u}=dg(l,c.offset,c.length);if(u===0n)return;let f=0n,p=u-d,h=OE();c.onProgress?.(new Rn("unixfs:exporter:walk:file",{cid:r})),TG(s,e,h,0n,d,u,c).catch(m=>{h.end(m)});for await(let m of h)if(m!=null){if(f+=BigInt(m.byteLength),f>p)throw h.end(),(0,Dh.default)(new Error("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect"),"ERR_OVER_READ");f===p&&h.end(),c.onProgress?.(new Rn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:p,fileSize:l})),yield m}if(f<p)throw(0,Dh.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return o},D6=Fye});async function*DG(r,e,t,n,i,a){let s=r.Links,o=fg(s,c=>lg(c,l=>async()=>{let d=l.Name!=null?l.Name.substring(2):null;if(d!=null&&d!==""){let u=await t(l.Hash,d,`${e}/${d}`,[],n+1,i,a);return{entries:u.entry==null?[]:[u.entry]}}else{let u=await i.get(l.Hash,a);return r=ll(u),a.onProgress?.(new Rn("unixfs:exporter:walk:hamt-sharded-directory",{cid:l.Hash})),{entries:DG(r,e,t,n,i,a)}}}),c=>Th(c,{ordered:!0}));for await(let{entries:c}of o)yield*c}var Gye,RG,CG=G(()=>{g();da();DE();$E();jE();ul();Gye=(r,e,t,n,i,a,s)=>{function o(c={}){return c.onProgress?.(new Rn("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),DG(e,n,i,a,s,c)}return o};RG=Gye});var Sb,Hye,Vye,Wye,$G,BG=G(()=>{g();da();Sb=An(ca(),1);Pu();YF();lG();IG();CG();Hye=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,Vye={raw:D6,file:D6,directory:dG,"hamt-sharded-directory":RG,metadata:(r,e,t,n,i,a,s)=>()=>[],symlink:(r,e,t,n,i,a,s)=>()=>[]},Wye=async(r,e,t,n,i,a,s,o)=>{let c=await s.get(r,o),l=ll(c),d,u;if(e==null&&(e=r.toString()),l.Data==null)throw(0,Sb.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{d=bi.unmarshal(l.Data)}catch(p){throw(0,Sb.default)(p,"ERR_NOT_UNIXFS")}if(t==null&&(t=e),n.length>0){let p;if(d?.type==="hamt-sharded-directory"?p=await ZF(l,n[0],s):p=Hye(l,n[0]),p==null)throw(0,Sb.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let h=n.shift(),m=`${t}/${h}`;u={cid:p,toResolve:n,name:h??"",path:m}}let f=Vye[d.type](r,l,d,t,i,a,s);if(f==null)throw(0,Sb.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return d.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:f,unixfs:d,depth:a,node:l,size:d.fileSize()},next:u}:{entry:{type:"file",name:e,path:t,cid:r,content:f,unixfs:d,depth:a,node:l,size:d.fileSize()},next:u}},$G=Wye});var OG,Jye,jG,MG,KG=G(()=>{g();Dm();da();OG=An(ca(),1);Gw();KF();LF();FF();VF();BG();Jye={[Mw]:$G,[xu]:HF,[gu]:NF,[MF.code]:zF},jG=async(r,e,t,n,i,a,s)=>{let o=Jye[r.code];if(o==null)throw(0,OG.default)(new Error(`No resolver for code ${r.code}`),"ERR_NO_RESOLVER");return o(r,e,t,n,jG,i,a,s)},MG=jG});async function*Xye(r,e,t={}){let{cid:n,toResolve:i}=Yye(r),a=n.toString(),s=a,o=i.length;for(;;){let c=await MG(n,a,s,i,o,e,t);if(c.entry==null&&c.next==null)throw(0,HE.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");if(c.entry!=null&&(yield c.entry),c.next==null)return;i=c.next.toResolve,n=c.next.cid,a=c.next.name,s=c.next.path}}async function UG(r,e,t={}){let n=await $F(Xye(r,e,t));if(n==null)throw(0,HE.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");return n}var HE,Zye,Yye,NG=G(()=>{g();HE=An(ca(),1);BF();dl();KG();Zye=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),Yye=r=>{if(r instanceof Uint8Array)return{cid:Yt.decode(r),toResolve:[]};let e=Yt.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=Zye(r);return{cid:Yt.parse(t[0]),toResolve:t.slice(1)}}throw(0,HE.default)(new Error(`Unknown path type ${r}`),"ERR_BAD_PATH")}});var R6,VE,Cf,LG=G(()=>{"use strict";g();_E();Tf();wu();NG();UA();R6=new TextEncoder,VE=new TextDecoder,Cf=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:Js,...e},this.blockstore=new If({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase})}async open(){await this.blockstore.open()}async close(){await this.blockstore.close()}async put(e,t,n,i){let a=await this.getRefsPartition(e,t),s=await a.get(n);if(s){await i.cancel();let{dataSize:u}=JSON.parse(VE.decode(s));return{dataSize:u}}let o=await this.getRefcountsPartition(),c=await o.get(n),l=c?JSON.parse(VE.decode(c)):{count:0,dataSize:0},d;if(l.count>0)await i.cancel(),d=l.dataSize;else{let u=await this.getBlocksPartition(n),f=Ww([{content:zt.asAsyncIterable(i)}],u,{cidVersion:1}),p;for await(p of f);d=Number(p.unixfs?.fileSize()??p.size)}return await a.put(n,R6.encode(JSON.stringify({dataSize:d}))),await o.put(n,R6.encode(JSON.stringify({count:l.count+1,dataSize:d}))),{dataSize:d}}async get(e,t,n){let a=await(await this.getRefsPartition(e,t)).get(n);if(!a)return;let{dataSize:s}=JSON.parse(VE.decode(a)),o=await this.getBlocksPartition(n);if(!await o.has(n))return;let d=(await UG(n,o)).content(),u=new ReadableStream({async pull(f){let p=await d.next();p.done?f.close():f.enqueue(p.value)}});return{dataSize:s,dataStream:u}}async delete(e,t,n){let i=await this.getRefsPartition(e,t);if(!await i.get(n))return;await i.delete(n);let s=await this.getRefcountsPartition(),o=await s.get(n);if(!o)return;let c=JSON.parse(VE.decode(o)),l=c.count-1;l<=0?(await(await this.getBlocksPartition(n)).clear(),await s.delete(n)):await s.put(n,R6.encode(JSON.stringify({count:l,dataSize:c.dataSize})))}async clear(){await this.blockstore.clear()}async getRefsPartition(e,t){return(await(await this.blockstore.db.partition("refs")).partition(e)).partition(t)}async getBlocksPartition(e){return(await this.blockstore.partition("blocks")).partition(e)}async getRefcountsPartition(){return this.blockstore.db.partition("refcounts")}}});async function qG(r,e,t){let n=`__compound:${t.name}__`;return(await r.partition(e)).partition(n)}function zG(r,e,t,n,i){let a=[];for(let l of t.properties){let d=e[l];if(d===void 0||Array.isArray(d))return;a.push(n(d))}let s=e[t.sortProperty];if(s===void 0||Array.isArray(s))return;let o=a.join(WE),c=n(s);return o+WE+c+i+r}function FG(r,e,t){let n=[];for(let i of e.properties){let a=r[i];if(a===void 0||typeof a=="object")return;n.push(t(a))}return n.join(WE)+WE}function GG(r,e,t,n,i,a){let s=zG(t.messageCid,t.indexes,n,i,a);if(s!==void 0)return VG(r,e,`__compound:${n.name}__`,{type:"put",key:s,value:JSON.stringify(t)})}function HG(r,e,t,n,i,a,s){let o=zG(t,n,i,a,s);if(o!==void 0)return VG(r,e,`__compound:${i.name}__`,{type:"del",key:o})}async function VG(r,e,t,n){return(await r.partition(e)).createPartitionOperation(t,n)}function C6(r,e,t){let n,i=0;for(let a of t){if(a.sortProperty!==e.sortProperty)continue;let s=!0;for(let o of a.properties){let c=r[o];if(c===void 0||typeof c=="object"){s=!1;break}}s&&a.properties.length>i&&(n=a,i=a.properties.length)}return n}async function WG(r,e,t,n,i,a,s,o,c){let{sortDirection:l=At.Ascending,cursor:d,limit:u}=n,f=FG(t,i,a);if(f===void 0)return o(e,[t],n,c);let p=await qG(r,e,i),h={};if(d===void 0)l===At.Ascending?(h.gt=f,h.lt=f+"\xFF"):(h.gt=f,h.lt=f+"\xFF",h.reverse=!0);else{let E=a(d.value),_=f+E+s+d.messageCid;l===At.Ascending?(h.gt=_,h.lt=f+"\xFF"):(h.lt=_,h.gt=f,h.reverse=!0)}let m=new Set(i.properties),y={},v=!1;for(let E in t)m.has(E)||(y[E]=t[E],v=!0);let w=[];for await(let[E,_]of p.iterator(h,c)){if(u!==void 0&&w.length===u)break;let A=JSON.parse(_);v&&!Xt.matchFilter(A.indexes,y)||w.push(A)}return w}async function JG(r,e,t,n,i,a,s){let o=FG(t,n,i);if(o===void 0)return(await a(e,[t],{sortProperty:n.sortProperty},s)).length;let c=await qG(r,e,n),l=new Set(n.properties),d=!1,u={};for(let h in t)l.has(h)||(u[h]=t[h],d=!0);let f={gt:o,lt:o+"\xFF"},p=0;if(d)for await(let[h,m]of c.iterator(f,s)){let y=JSON.parse(m);Xt.matchFilter(y.indexes,u)&&p++}else for await(let[h,m]of c.iterator(f,s))p++;return p}var WE,ZG=G(()=>{"use strict";g();gc();rd();WE=""});var YG,Rh,$6=G(()=>{"use strict";g();st();LA();rd();ZG();Tf();vt();gc();YG="index",Rh=class r{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:Js,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new Na({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"})}async open(){await this.db.open()}async close(){await this.db.close()}async clear(){await this.db.clear()}async put(e,t,n,i){if(bp(n))throw new ne(re.IndexMissingIndexableProperty,"Index must include at least one valid indexable property");let a={messageCid:t,indexes:n},s=[];for(let d in n){let u=n[d];if(Array.isArray(u))for(let f of u){let p=this.createPutIndexedItemOperation(e,a,d,f);s.push(p)}else{let f=this.createPutIndexedItemOperation(e,a,d,u);s.push(f)}}for(let d of this._compoundIndexes){let u=GG(this.db,e,a,d,r.encodeValue,r.delimiter);u!==void 0&&s.push(u)}let o=this.createOperationForIndexesLookupPartition(e,{type:"put",key:t,value:JSON.stringify(n)});s.push(o);let c=await Promise.all(s);await(await this.db.partition(e)).batch(c,i)}async delete(e,t,n){let i=[],a=await this.getIndexes(e,t);if(a===void 0)return;let s=this.createOperationForIndexesLookupPartition(e,{type:"del",key:t});i.push(s);for(let l in a){let d=a[l];if(Array.isArray(d))for(let u of d){let f=this.createDeleteIndexedItemOperation(e,t,l,u);i.push(f)}else{let u=this.createDeleteIndexedItemOperation(e,t,l,d);i.push(u)}}for(let l of this._compoundIndexes){let d=HG(this.db,e,t,a,l,r.encodeValue,r.delimiter);d!==void 0&&i.push(d)}let o=await Promise.all(i);await(await this.db.partition(e)).batch(o,n)}async createPutIndexedItemOperation(e,t,n,i){let{messageCid:a}=t,s=r.keySegmentJoin(r.encodeValue(i),a);return this.createOperationForIndexPartition(e,n,{type:"put",key:s,value:JSON.stringify(t)})}async createDeleteIndexedItemOperation(e,t,n,i){let a=r.keySegmentJoin(r.encodeValue(i),t);return this.createOperationForIndexPartition(e,n,{type:"del",key:a})}async createOperationForIndexPartition(e,t,n){let i=await this.db.partition(e),a=r.getIndexPartitionName(t);return i.createPartitionOperation(a,n)}async createOperationForIndexesLookupPartition(e,t){return(await this.db.partition(e)).createPartitionOperation(YG,t)}static getIndexPartitionName(e){return`__${e}__`}async getIndexPartition(e,t){let n=r.getIndexPartitionName(t);return(await this.db.partition(e)).partition(n)}async getIndexesLookupPartition(e){return(await this.db.partition(e)).partition(YG)}async query(e,t,n,i){if(t.length===1&&!bp(t[0])){let a=C6(t[0],n,this._compoundIndexes);if(a!==void 0)return WG(this.db,e,t[0],n,a,r.encodeValue,r.delimiter,this.queryWithIteratorPaging.bind(this),i)}return r.shouldQueryWithInMemoryPaging(t,n)?this.queryWithInMemoryPaging(e,t,n,i):this.queryWithIteratorPaging(e,t,n,i)}async count(e,t,n,i){if(t.length===1&&!bp(t[0])){let s=C6(t[0],{...n},this._compoundIndexes);if(s!==void 0)return JG(this.db,e,t[0],s,r.encodeValue,this.query.bind(this),i)}return(await this.query(e,t,{...n},i)).length}async queryWithIteratorPaging(e,t,n,i){let{cursor:a,limit:s}=n,o=a?this.createStartingKeyFromCursor(a):"",c=[];for await(let l of this.getIndexIterator(e,o,n,i)){if(s!==void 0&&s===c.length)break;let{indexes:d}=l;Xt.matchAnyFilter(d,t)&&c.push(l)}return c}async*getIndexIterator(e,t,n,i){let{sortProperty:a,sortDirection:s=At.Ascending,cursor:o}=n,c={gt:t};s===At.Descending&&(c.reverse=!0,o!==void 0&&(c.lt=t,delete c.gt));let l=await this.getIndexPartition(e,a);for await(let[d,u]of l.iterator(c,i)){let{indexes:f,messageCid:p}=JSON.parse(u);yield{indexes:f,messageCid:p}}}createStartingKeyFromCursor(e){let{messageCid:t,value:n}=e;return r.keySegmentJoin(r.encodeValue(n),t)}static createCursorFromLastArrayItem(e,t){if(e.length>0)return this.createCursorFromItem(e.at(-1),t)}static createCursorFromItem(e,t){let{messageCid:n,indexes:i}=e,a=i[t];if(a===void 0)throw new ne(re.IndexInvalidCursorSortProperty,`the sort property '${t}' is not defined within the given item.`);if(typeof a=="boolean"||Array.isArray(a))throw new ne(re.IndexInvalidCursorValueType,`only string or number values are supported for cursors, a(n) ${typeof a} was given.`);return{messageCid:n,value:a}}async queryWithInMemoryPaging(e,t,n,i){let{sortProperty:a,sortDirection:s=At.Ascending,cursor:o,limit:c}=n,l=o?this.createStartingKeyFromCursor(o):void 0,d=new Map;t.length===0&&(t=[{}]);try{for(let h of t)await this.executeSingleFilterQuery(e,h,a,d,i)}catch(h){if(h.code===re.IndexInvalidSortPropertyInMemory)return[]}let u=[...d.values()].sort((h,m)=>this.sortItems(h,m,a,s)),f=l===void 0?0:this.findCursorStartingIndex(u,s,a,l);if(f<0)return[];let p=c===void 0?void 0:f+c;return u.slice(f,p)}async executeSingleFilterQuery(e,t,n,i,a){let s=c=>{for(let l of c)if(!(i.has(l.messageCid)||!Xt.matchFilter(l.indexes,t))){if(l.indexes[n]===void 0)throw new ne(re.IndexInvalidSortPropertyInMemory,`invalid sort property ${n}`);i.set(l.messageCid,l)}};if(bp(t)){let c=await this.getAllItems(e,n);s(c);return}let o=DP.reduceFilter(t);for(let c in o){let l=o[c];if(Xt.isEqualFilter(l)){let d=await this.filterExactMatches(e,c,l,a);s(d)}else if(Xt.isOneOfFilter(l))for(let d of new Set(l)){let u=await this.filterExactMatches(e,c,d,a);s(u)}else if(Xt.isRangeFilter(l)){let d=await this.filterRangeMatches(e,c,l,a);s(d)}}}async getAllItems(e,t){let n=await this.getIndexPartition(e,t),i=[];for await(let[a,s]of n.iterator())i.push(JSON.parse(s));return i}async filterExactMatches(e,t,n,i){let a=r.keySegmentJoin(r.encodeValue(n)),s={gt:a},o=await this.getIndexPartition(e,t),c=[];for await(let[l,d]of o.iterator(s,i)){if(!l.startsWith(a))break;c.push(JSON.parse(d))}return c}async filterRangeMatches(e,t,n,i){let a={};for(let c in n){let l=c,d=r.encodeValue(n[l]);l==="lte"?a[l]=d+"\xFF":a[l]=d}a.gt===void 0&&a.gte===void 0&&(a.reverse=!0);let s=[],o=await this.getIndexPartition(e,t);for await(let[c,l]of o.iterator(a,i))"gt"in n&&this.extractIndexValueFromKey(c)===r.encodeValue(n.gt)||s.push(JSON.parse(l));return s}sortItems(e,t,n,i){let a=e.indexes[n],s=t.indexes[n],o=r.encodeValue(a)+e.messageCid,c=r.encodeValue(s)+t.messageCid;return i===At.Ascending?Jw(o,c):Jw(c,o)}findCursorStartingIndex(e,t,n,i){let a=c=>{let{messageCid:l,indexes:d}=c,u=d[n],f=r.keySegmentJoin(r.encodeValue(u),l);return t===At.Ascending?f>i:f<i},s=0,o=e.length;for(;s<o;){let c=s+o>>>1;a(e[c])?o=c:s=c+1}return s<e.length?s:-1}async getIndexes(e,t){let i=await(await this.getIndexesLookupPartition(e)).get(t);if(i!==void 0)return JSON.parse(i)}extractIndexValueFromKey(e){let[t]=e.split(r.delimiter);return t}static delimiter="\0";static keySegmentJoin(...e){return e.join(r.delimiter)}static encodeNumberValue(e){let t=Number.MAX_SAFE_INTEGER,n="!",i=String(Number.MAX_SAFE_INTEGER).length,a=e<0?n:"",s=e<0?t:0;return a+String(e+s).padStart(i,"0")}static encodeValue(e){switch(typeof e){case"number":return this.encodeNumberValue(e);default:return JSON.stringify(e)}}static shouldQueryWithInMemoryPaging(e,t){for(let n of e)if(!r.isFilterConcise(n,t))return!1;return!0}static isFilterConcise(e,t){return e.recordId!==void 0?!0:t.cursor!==void 0?!1:e.protocolPath!==void 0||e.contextId!==void 0||e.parentId!==void 0||e.schema!==void 0}}});function JE({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*Qye(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],a=Yt.asCID(n);a?yield[i.join("/"),a]:typeof n=="object"&&(yield*B6(n,i))}else{let t=Yt.asCID(e);t?yield[r.join("/"),t]:yield*B6(e,r)}}function*B6(r,e){if(r==null||r instanceof Uint8Array)return;let t=Yt.asCID(r);t&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let a=[...e,n];yield*Qye(a,i)}}function*ege(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&!Yt.asCID(n)&&(yield*O6(n,i))}else yield*O6(e,r)}function*O6(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!Yt.asCID(n)&&(yield*ege(i,n))}}function tge(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let a=Yt.asCID(t);if(a)return{value:a,remaining:e.slice(n+1).join("/")}}return{value:t}}async function XG({value:r,codec:e,hasher:t}){if(typeof r>"u")throw new Error('Missing required argument "value"');if(!e||!t)throw new Error("Missing required argument: codec or hasher");let n=e.encode(r),i=await t.digest(n),a=Yt.create(1,e.code,i);return new ZE({value:r,bytes:n,cid:a})}async function QG({bytes:r,codec:e,hasher:t}){if(!r)throw new Error('Missing required argument "bytes"');if(!e||!t)throw new Error("Missing required argument: codec or hasher");let n=e.decode(r),i=await t.digest(r),a=Yt.create(1,e.code,i);return new ZE({value:n,bytes:r,cid:a})}var ZE,eH=G(()=>{g();Cw();L_();ZE=class{constructor({cid:e,bytes:t,value:n}){if(!e||!t||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:JE(),bytes:JE(),value:JE(),asBlock:JE()})}links(){return B6(this.value,[])}tree(){return O6(this.value,[])}get(e="/"){return tge(this.value,e.split("/").filter(Boolean))}}});var nge,$f,tH=G(()=>{"use strict";g();eH();Dm();_E();fl();dl();Tf();kE();$6();yr();Ql();rd();nge=[{name:"protocol-protocolPath-messageTimestamp",properties:["protocol","protocolPath"],sortProperty:"messageTimestamp"},{name:"protocol-protocolPath-dateCreated",properties:["protocol","protocolPath"],sortProperty:"dateCreated"},{name:"schema-messageTimestamp",properties:["schema"],sortProperty:"messageTimestamp"},{name:"schema-dateCreated",properties:["schema"],sortProperty:"dateCreated"},{name:"protocol-contextId-messageTimestamp",properties:["protocol","contextId"],sortProperty:"messageTimestamp"}],$f=class r{config;blockstore;index;constructor(e={}){this.config={blockstoreLocation:"MESSAGESTORE",indexLocation:"INDEX",createLevelDatabase:Js,...e},this.blockstore=new If({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new Rh({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??nge})}async open(){await this.blockstore.open(),await this.index.open()}async close(){await this.blockstore.close(),await this.index.close()}async get(e,t,n){n?.signal?.throwIfAborted();let i=await Wn(this.blockstore.partition(e),n?.signal),a=Yt.parse(t),s=await i.get(a,n);return s?(await Wn(QG({bytes:s,codec:cl,hasher:On}),n?.signal)).value:void 0}async query(e,t,n,i,a){a?.signal?.throwIfAborted();let s=r.buildQueryOptions(n,i),o=await this.index.query(e,t,s,a),c;i?.limit!==void 0&&i.limit<o.length&&(o.splice(-1),c=Rh.createCursorFromLastArrayItem(o,s.sortProperty));let l=[];for(let d=0;d<o.length;d++){let{messageCid:u}=o[d],f=await this.get(e,u,a);f&&l.push(f)}return{messages:l,cursor:c}}async count(e,t,n,i){i?.signal?.throwIfAborted();let a=r.buildQueryOptions(n);return this.index.count(e,t,a,i)}static buildQueryOptions(e={},t={}){let{limit:n,cursor:i}=t,{dateCreated:a,datePublished:s,messageTimestamp:o}=e,c=At.Ascending,l="messageTimestamp";return a!==void 0?l="dateCreated":s!==void 0?l="datePublished":o!==void 0&&(l="messageTimestamp"),e[l]!==void 0&&(c=e[l]),n!==void 0&&n>0&&(n=n+1),{sortDirection:c,sortProperty:l,limit:n,cursor:i}}async delete(e,t,n){n?.signal?.throwIfAborted();let i=await Wn(this.blockstore.partition(e),n?.signal),a=Yt.parse(t);await i.delete(a,n),await this.index.delete(e,t,n)}async put(e,t,n,i){i?.signal?.throwIfAborted();let a=await Wn(this.blockstore.partition(e),i?.signal),s=await Wn(XG({value:t,codec:cl,hasher:On}),i?.signal),o=ur.parseCid(await ye.getCid(t));await a.put(o,s.bytes,i);let c=o.toString();await this.index.put(e,c,n,i)}async clear(){await this.blockstore.clear(),await this.index.clear()}}});var Bf,rH=G(()=>{"use strict";g();fl();Tf();Bf=class r{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:Js,...e},this.db=new Na({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"})}async open(){await this.db.open()}async close(){await this.db.close()}async register(e,t){let n=await ur.computeCid(e),i={id:n,timeout:Date.now()+t*1e3,retryCount:0,task:e};return await this.db.put(n,JSON.stringify(i)),i}async grab(e){let t=[];for await(let[n,i]of this.db.iterator()){let a=JSON.parse(i);if(Date.now()>=a.timeout&&(a.timeout=Date.now()+r.taskTimeoutInSeconds*1e3,a.retryCount++,await this.db.put(a.id,JSON.stringify(a)),t.push(a)),t.length>=e)break}return t}async read(e){let t=await this.db.get(e);if(t)return JSON.parse(t)}async extend(e,t){let n=await this.db.get(e);if(n){let i=JSON.parse(n);i.timeout=Date.now()+t*1e3,await this.db.put(i.id,JSON.stringify(i))}}async delete(e){return this.db.delete(e)}async clear(){await this.db.clear()}}});function nH(r){return{all:r=r||new Map,on:function(e,t){var n=r.get(e);n?n.push(t):r.set(e,[t])},off:function(e,t){var n=r.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):r.set(e,[]))},emit:function(e,t){var n=r.get(e);n&&n.slice().map(function(i){i(t)}),(n=r.get("*"))&&n.slice().map(function(i){i(e,t)})}}}var iH=G(()=>{g()});var sH,Of,oH=G(()=>{"use strict";g();iH();gc();vt();sH="events",Of=class r{emitter=nH();isOpen=!1;errorHandler=e=>{console.error("event log error",e)};maxEventsPerTenant;tenantLogs=new Map;tenantSeqs=new Map;epoch;constructor(e={}){this.maxEventsPerTenant=e.maxEventsPerTenant??1e4,this.epoch=crypto.randomUUID(),e.errorHandler&&(this.errorHandler=e.errorHandler)}async getStreamId(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(n);return Array.from(i.slice(0,8),a=>a.toString(16).padStart(2,"0")).join("")}async buildToken(e,t,n){return{streamId:await this.getStreamId(e),epoch:this.epoch,position:String(t),messageCid:n}}async validateCursor(e,t){let n=await this.getStreamId(e),i;if(t.streamId!==n)i="stream_mismatch";else if(t.epoch===this.epoch){let c=this.tenantLogs.get(e);if(c!==void 0&&c.size>0){let l=c.keys().next().value;if(r.parsePosition(t.position)<l-1)i="token_too_old";else return}else return}else i="epoch_mismatch";let a=await this.getReplayBounds(e),s={requested:t,oldestAvailable:a?.oldest??t,latestAvailable:a?.latest??t,reason:i},o=new ne(re.EventLogProgressGap,`progress token gap: ${i}`);throw o.gapInfo=s,o}async open(){this.isOpen=!0}async close(){this.isOpen=!1,this.emitter.all.clear(),this.tenantLogs.clear(),this.tenantSeqs.clear()}async emit(e,t,n,i){if(!this.isOpen){this.errorHandler(new ne(re.EventLogNotOpenError,"a message emitted when EventLog is closed"));return}let s=(this.tenantSeqs.get(e)??0)+1;this.tenantSeqs.set(e,s);let o=this.tenantLogs.get(e);if(o===void 0&&(o=new Map,this.tenantLogs.set(e,o)),o.set(s,{event:t,indexes:n,messageCid:i}),o.size>this.maxEventsPerTenant){let l=o.size-this.maxEventsPerTenant,d=0;for(let u of o.keys()){if(d>=l)break;o.delete(u),d++}}let c=`${e}_${sH}`;return this.emitter.emit(c,{tenant:e,event:t,indexes:n,seq:s,messageCid:i}),this.buildToken(e,s,i)}async read(e,t={}){let{cursor:n,limit:i,filters:a}=t;n!==void 0&&await this.validateCursor(e,n);let s=n===void 0?void 0:r.parsePosition(n.position),o=this.tenantLogs.get(e);if(o===void 0||o.size===0)return{events:[],cursor:n};let c=[],l=i??Number.MAX_SAFE_INTEGER;for(let[d,u]of o)if(!(s!==void 0&&d<=s)&&!(a!==void 0&&a.length>0&&!Xt.matchAnyFilter(u.indexes,a))&&(c.push({seq:d,event:u.event,indexes:u.indexes,messageCid:u.messageCid}),c.length>=l))break;if(c.length>0){let d=c[c.length-1],u=await this.buildToken(e,d.seq,d.messageCid);return{events:c,cursor:u}}return{events:c,cursor:n}}static parsePosition(e){try{let t=BigInt(e);if(t<0n)throw new ne(re.EventLogNotOpenError,`invalid cursor position: '${e}'`);return Number(t)}catch(t){throw t instanceof ne?t:new ne(re.EventLogNotOpenError,`invalid cursor position: '${e}'`)}}async subscribe(e,t,n,i){let a=`${e}_${sH}`,{cursor:s,filters:o}=i??{},c=async d=>this.buildToken(e,d.seq,d.messageCid);if(s!==void 0){await this.validateCursor(e,s);let d=r.parsePosition(s.position),u=[],f=!1,p=v=>{o!==void 0&&o.length>0&&!Xt.matchAnyFilter(v.indexes,o)||(f?c(v).then(w=>{n({type:"event",cursor:w,event:v.event})}):u.push({event:v.event,seq:v.seq,messageCid:v.messageCid}))};this.emitter.on(a,p);let h=await this.read(e,{cursor:s,filters:o}),m=h.cursor??s,y=h.cursor===void 0?d:r.parsePosition(h.cursor.position);for(let v of h.events){let w=await this.buildToken(e,v.seq,v.messageCid??"");n({type:"event",cursor:w,event:v.event})}f=!0;for(let v of u)if(v.seq>y){let w=await this.buildToken(e,v.seq,v.messageCid);n({type:"event",cursor:w,event:v.event})}return n({type:"eose",cursor:m}),{id:t,close:async()=>{this.emitter.off(a,p)}}}let l=d=>{o!==void 0&&o.length>0&&!Xt.matchAnyFilter(d.indexes,o)||c(d).then(u=>{n({type:"event",cursor:u,event:d.event})})};return this.emitter.on(a,l),{id:t,close:async()=>{this.emitter.off(a,l)}}}async getReplayBounds(e){let t=this.tenantLogs.get(e);if(t===void 0||t.size===0)return;let n=[...t.keys()],i=n[0],a=n[n.length-1],s=t.get(i),o=t.get(a),c=await this.buildToken(e,i,s.messageCid),l=await this.buildToken(e,a,o.messageCid);return{oldest:c,latest:l}}async trim(e,t){let n=this.tenantLogs.get(e);if(n!==void 0)if(typeof t=="number")for(let i of n.keys())if(i<t)n.delete(i);else break;else for(let[i,a]of n)(a.indexes.messageTimestamp??"")<t&&n.delete(i)}}});var pg,j6=G(()=>{"use strict";g();Ju();pg=class{db;nodesPartition;metaPartition;initialized=!1;constructor(e){this.db=e}async open(){this.nodesPartition=await this.db.partition("nodes"),this.metaPartition=await this.db.partition("meta"),this.initialized=!0}async close(){this.initialized=!1}async clear(){await this.db.clear(),this.nodesPartition=await this.db.partition("nodes"),this.metaPartition=await this.db.partition("meta")}async getNode(e){this.ensureInitialized();let t=on(e),n=await this.nodesPartition.get(t);if(n!==void 0)return this.deserializeNode(JSON.parse(n))}async putNode(e,t){this.ensureInitialized();let n=on(e),i=this.serializeNode(t);await this.nodesPartition.put(n,JSON.stringify(i))}async deleteNode(e){this.ensureInitialized();let t=on(e);await this.nodesPartition.delete(t)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return Wu(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",on(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:on(e.leftHash),rightHash:on(e.rightHash)}:{type:"leaf",keyHash:on(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:Wu(e.leftHash),rightHash:Wu(e.rightHash)}:{type:"leaf",keyHash:Wu(e.keyHash),valueCid:e.valueCid}}}});var hg,M6=G(()=>{"use strict";g();Ju();hg=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await Il()}async close(){await this.store.close()}async clear(){await this.store.clear()}async getRoot(){let e=await this.store.getRoot();return e===void 0?this.defaultHashes[0]:e}async insert(e){let t=await Vu(e),n=await xy(t,e),i={type:"leaf",keyHash:t,valueCid:e};await this.store.putNode(n,i);let a=await this.getRoot(),s=await this.insertAtNode(a,t,n,i,0);return await this.store.setRoot(s),s}async delete(e){let t=await Vu(e),n=await this.getRoot(),i=await this.deleteAtNode(n,t,0);return await this.store.setRoot(i),i}async has(e){let t=await Vu(e),n=await this.getRoot();return this.existsAtNode(n,t,0)}async getProof(e){let t=await Vu(e),n=await this.getRoot();return this.generateProof(n,t,0)}async getSubtreeHash(e){let t=await this.getRoot();for(let n=0;n<e.length;n++){if(sn(t,this.defaultHashes[n]))return this.defaultHashes[e.length];let i=await this.store.getNode(t);if(i===void 0||i.type==="leaf")return i?.type==="leaf"?this.computeSubtreeHashForLeaf(i,n,e):this.defaultHashes[e.length];let a=i;e[n]?t=a.rightHash:t=a.leftHash}return t}async getLeaves(e){let t=await this.getRoot();for(let n=0;n<e.length;n++){if(sn(t,this.defaultHashes[n]))return[];let i=await this.store.getNode(t);if(i===void 0)return[];if(i.type==="leaf")return this.leafMatchesPrefix(i.keyHash,e)?[i.valueCid]:[];let a=i;e[n]?t=a.rightHash:t=a.leftHash}return this.collectLeaves(t,e.length)}async diff(e){let t=await this.getRoot(),n=await e.getRoot();if(sn(t,n))return{onlyLocal:[],onlyRemote:[]};let i=[],a=[];return await this.diffAtNode(t,n,0,this,e,i,a),{onlyLocal:i,onlyRemote:a}}async insertAtNode(e,t,n,i,a){if(a>=hs||sn(e,this.defaultHashes[a]))return n;let s=await this.store.getNode(e);if(s===void 0)return n;if(s.type==="leaf")return sn(s.keyHash,t)?(await this.store.deleteNode(e),n):this.splitLeaves(s,e,i,n,a);let o=s,c=lo(t,a),l,d;c?(l=o.leftHash,d=await this.insertAtNode(o.rightHash,t,n,i,a+1)):(l=await this.insertAtNode(o.leftHash,t,n,i,a+1),d=o.rightHash);let u=await Dl(l,d);if(!sn(u,e)){let f={type:"internal",leftHash:l,rightHash:d};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async splitLeaves(e,t,n,i,a){let s=a;for(;s<hs&&lo(e.keyHash,s)===lo(n.keyHash,s);)s++;if(s>=hs)return i;let o=lo(e.keyHash,s),c,l;o?(c=i,l=t):(c=t,l=i);let d=await Dl(c,l);await this.store.putNode(d,{type:"internal",leftHash:c,rightHash:l});for(let u=s-1;u>=a;u--){let f=lo(e.keyHash,u),p=this.defaultHashes[u+1],h,m;f?(h=p,m=d):(h=d,m=p),d=await Dl(h,m),await this.store.putNode(d,{type:"internal",leftHash:h,rightHash:m})}return d}async deleteAtNode(e,t,n){if(n>=hs)return this.defaultHashes[hs];if(sn(e,this.defaultHashes[n]))return e;let i=await this.store.getNode(e);if(i===void 0)return this.defaultHashes[n];if(i.type==="leaf")return sn(i.keyHash,t)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let a=i,s=lo(t,n),o,c;if(s?(o=a.leftHash,c=await this.deleteAtNode(a.rightHash,t,n+1)):(o=await this.deleteAtNode(a.leftHash,t,n+1),c=a.rightHash),sn(o,this.defaultHashes[n+1])&&sn(c,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let l=sn(o,this.defaultHashes[n+1]),d=sn(c,this.defaultHashes[n+1]);if(l||d){let f=l?c:o;if((await this.store.getNode(f))?.type==="leaf")return await this.store.deleteNode(e),f}let u=await Dl(o,c);if(!sn(u,e)){let f={type:"internal",leftHash:o,rightHash:c};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async existsAtNode(e,t,n){if(n>=hs||sn(e,this.defaultHashes[n]))return!1;let i=await this.store.getNode(e);if(i===void 0)return!1;if(i.type==="leaf")return sn(i.keyHash,t);let a=i;return lo(t,n)?this.existsAtNode(a.rightHash,t,n+1):this.existsAtNode(a.leftHash,t,n+1)}async generateProof(e,t,n){if(n>=hs)return{siblings:[],leafNode:void 0,depth:n};if(sn(e,this.defaultHashes[n]))return{siblings:[],leafNode:void 0,depth:n};let i=await this.store.getNode(e);if(i===void 0)return{siblings:[],leafNode:void 0,depth:n};if(i.type==="leaf")return{siblings:[],leafNode:i,depth:n};let a=i,s=lo(t,n),o,c;s?(o=a.rightHash,c=a.leftHash):(o=a.leftHash,c=a.rightHash);let l=await this.generateProof(o,t,n+1);return l.siblings.unshift(c),l}async computeSubtreeHashForLeaf(e,t,n){for(let i=t;i<n.length;i++)if(lo(e.keyHash,i)!==n[i])return this.defaultHashes[n.length];return await xy(e.keyHash,e.valueCid)}leafMatchesPrefix(e,t){for(let n=0;n<t.length;n++)if(lo(e,n)!==t[n])return!1;return!0}async collectLeaves(e,t){if(t>=hs||sn(e,this.defaultHashes[t]))return[];let n=await this.store.getNode(e);if(n===void 0)return[];if(n.type==="leaf")return[n.valueCid];let i=n,a=await this.collectLeaves(i.leftHash,t+1),s=await this.collectLeaves(i.rightHash,t+1);return[...a,...s]}async diffAtNode(e,t,n,i,a,s,o){if(sn(e,t)||n>=hs)return;let c=sn(e,this.defaultHashes[n]),l=sn(t,this.defaultHashes[n]);if(c&&!l){let f=await a.collectLeaves(t,n);o.push(...f);return}if(!c&&l){let f=await i.collectLeaves(e,n);s.push(...f);return}let d=await i.store.getNode(e),u=await a.store.getNode(t);if(d?.type==="leaf"&&u?.type==="leaf"){sn(d.keyHash,u.keyHash)?d.valueCid!==u.valueCid&&(s.push(d.valueCid),o.push(u.valueCid)):(s.push(d.valueCid),o.push(u.valueCid));return}if(d?.type==="leaf"){let f=await a.collectLeaves(t,n),p=d.valueCid;new Set(f).has(p)||s.push(p);for(let m of f)m!==p&&o.push(m);return}if(u?.type==="leaf"){let f=await i.collectLeaves(e,n),p=u.valueCid;new Set(f).has(p)||o.push(p);for(let m of f)m!==p&&s.push(m);return}if(d?.type==="internal"&&u?.type==="internal"){await this.diffAtNode(d.leftHash,u.leftHash,n+1,i,a,s,o),await this.diffAtNode(d.rightHash,u.rightHash,n+1,i,a,s,o);return}if(d===void 0){let f=await a.collectLeaves(t,n);o.push(...f)}if(u===void 0){let f=await i.collectLeaves(e,n);s.push(...f)}}}});var jf,aH=G(()=>{"use strict";g();Ju();j6();M6();Tf();jf=class{config;db;globalTrees=new Map;protocolTrees=new Map;constructor(e){this.config={location:"STATEINDEX",createLevelDatabase:Js,...e}}async open(){this.db=new Na({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await Il()}async close(){this.globalTrees.clear(),this.protocolTrees.clear(),await this.db.close()}async clear(){this.globalTrees.clear(),this.protocolTrees.clear(),await this.db.clear()}async insert(e,t,n){await(await this.getGlobalTree(e)).insert(t);let a=n.protocol;a!==void 0&&await(await this.getProtocolTree(e,a)).insert(t),await this.storeIndexes(e,t,n)}async delete(e,t){let n=await this.getGlobalTree(e);for(let i of t){let a=await this.getStoredIndexes(e,i);if(await n.delete(i),a!==void 0){let s=a.protocol;s!==void 0&&await(await this.getProtocolTree(e,s)).delete(i)}await this.deleteStoredIndexes(e,i)}}async getRoot(e){return(await this.getGlobalTree(e)).getRoot()}async getProtocolRoot(e,t){return(await this.getProtocolTree(e,t)).getRoot()}async getSubtreeHash(e,t){return(await this.getGlobalTree(e)).getSubtreeHash(t)}async getProtocolSubtreeHash(e,t,n){return(await this.getProtocolTree(e,t)).getSubtreeHash(n)}async getLeaves(e,t){return(await this.getGlobalTree(e)).getLeaves(t)}async getProtocolLeaves(e,t,n){return(await this.getProtocolTree(e,t)).getLeaves(n)}getGlobalTree(e){let t=this.globalTrees.get(e);return t!==void 0||(t=this.createTree(this.db,[e,"global"]),this.globalTrees.set(e,t)),t}getProtocolTree(e,t){let n=`${e}\0${t}`,i=this.protocolTrees.get(n);return i!==void 0||(i=this.createTree(this.db,[e,"proto",t]),this.protocolTrees.set(n,i)),i}async createTree(e,t){let n=e;for(let s of t)n=await n.partition(s);let i=new pg(n),a=new hg(i);return await a.initialize(),a}async storeIndexes(e,t,n){let i=await this.getMetaPartition(e),a={protocol:n.protocol};await i.put(t,JSON.stringify(a))}async getStoredIndexes(e,t){let i=await(await this.getMetaPartition(e)).get(t);if(i!==void 0)return JSON.parse(i)}async deleteStoredIndexes(e,t){await(await this.getMetaPartition(e)).delete(t)}async getMetaPartition(e){return(await this.db.partition(e)).partition("meta")}}});var YE,cH=G(()=>{"use strict";g();Ju();YE=class{nodes=new Map;root;async open(){}async close(){}async clear(){this.nodes.clear(),this.root=void 0}async getNode(e){return this.nodes.get(on(e))}async putNode(e,t){this.nodes.set(on(e),t)}async deleteNode(e){this.nodes.delete(on(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}}});var ige,XE,dH=G(()=>{"use strict";g();Dm();dl();wu();Qo();zS();Tn();Uc();bx();Ex();Fo();v1();d2();u2();Qn();gx();A0();wx();v2();zs();st();t1();Ql();qs();bn();gv();ar();Hm();ige={protocol:"http://test-protocol.xyz",published:!1,types:{testRecord:{}},structure:{testRecord:{}}},XE=class r{static async generatePersona(e){let t=e?.did;t||(t=`did:example:${r.randomString(32)}`);let n=r.randomString(10),i=e?.keyId??`${t}#${n}`,a=e?.keyPair??await Va.generateKeyPair(),s=e?.encryptionKeyPair;if(!s){let c=await kt.generateKey();s={publicJwk:await kt.getPublicKey({key:c}),privateJwk:c}}return{did:t,keyId:i,keyPair:a,encryptionKeyPair:s,signer:new il({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:`${t}#${i}`})}}static async installDefaultTestProtocol(e,t){let n=await Sa.create({definition:ige,signer:ct.createSigner(t)}),i=await e.processMessage(t.did,n.message);if(i.status.code!==202)throw new Error(`Failed to install default test protocol: ${i.status.code} ${i.status.detail}`)}static async generateProtocolsConfigure(e){let t=e?.author??await r.generatePersona(),n=e?.protocolDefinition;if(!n){let o="record"+r.randomString(10);n={protocol:r.randomString(20),published:e?.published??!1,types:{},structure:{}},n.types[o]={schema:"test-object",dataFormats:["text/plain"]},n.structure[o]={}}let i=ct.createSigner(t),a={messageTimestamp:e?.messageTimestamp,definition:n,signer:i,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},s=await Sa.create(a);return{author:t,message:s.message,protocolsConfigure:s}}static async generateProtocolsQuery(e){let t=e?.author??await r.generatePersona(),n=ct.createSigner(t),i={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};Wt(i);let a=await ka.create(i);return{author:t,message:a.message,protocolsQuery:a}}static async generateGrantCreate(e){let t=e?.author??await r.generatePersona(),n=e?.grantedTo??await r.generatePersona(),i=e?.dateExpires??_t.createOffsetTimestamp({seconds:10}),a=e?.scope??{interface:ve.Messages,method:me.Read},s=ct.createSigner(t),o=n.did,c={signer:s,grantedTo:o,dateExpires:i,scope:a,description:e?.description??r.randomString(10),delegated:e?.delegated??!1,requestId:e?.requestId,conditions:e?.conditions},l=await et.createGrant(c);return{dataStream:zt.fromBytes(l.permissionGrantBytes),recordsWrite:l.recordsWrite,dataBytes:l.permissionGrantBytes,message:l.recordsWrite.message,dataEncodedMessage:l.dataEncodedMessage}}static async generateRecordsWrite(e){let t=e?.author??await r.generatePersona(),n=ct.createSigner(t),i=ct.createSigners(e?.attesters??[]),a=e?.dataCid,s=e?.dataSize,o,c;a===void 0&&s===void 0&&(o=e?.data??r.randomBytes(32),c=zt.fromBytes(o));let l={recipient:e?.recipient,protocol:e?.protocol??"http://test-protocol.xyz",protocolPath:e?.protocolPath??"testRecord",protocolRole:e?.protocolRole,schema:e?.schema??`http://${r.randomString(20)}`,tags:e?.tags,recordId:e?.recordId,parentContextId:e?.parentContextId,published:e?.published,dataFormat:e?.dataFormat??"application/json",dateCreated:e?.dateCreated,messageTimestamp:e?.messageTimestamp,datePublished:e?.datePublished,data:o,dataCid:a,dataSize:s,signer:n,attestationSigners:i,encryptionInput:e?.encryptionInput,permissionGrantId:e?.permissionGrantId,squash:e?.squash},d=await Pt.create(l),u=d.message;return{author:t,message:u,dataCid:a,dataSize:s,dataBytes:o,dataStream:c,recordsWrite:d}}static async generateProtocolEncryptedRecordsWrite(e){let{plaintextBytes:t,author:n,recipient:i,protocolDefinition:a,protocolPath:s,protocolParentContextId:o,protocolContextDerivingRootKeyId:c,protocolContextDerivedPublicKeyJwk:l}=e,d=r.randomBytes(12),u=r.randomBytes(32),{ciphertext:f,tag:p}=await xi.aeadEncrypt(ci.A256GCM,u,d,t),h=s.split("/"),m=h[h.length-1],{message:y,dataStream:v,recordsWrite:w}=await r.generateRecordsWrite({author:n,recipient:i,protocol:a.protocol,protocolPath:s,parentContextId:o,schema:a.types[m].schema,dataFormat:a.types[m].dataFormats?.[0],data:f}),E={initializationVector:d,key:u,authenticationTag:p,keyEncryptionInputs:[]};if(e.encryptSymmetricKeyWithProtocolPathDerivedKey){let _=a.structure;for(let C of h)_=_[C];let A=_.$encryption?.publicKeyJwk,M={publicKeyId:_.$encryption?.rootKeyId,publicKey:A,derivationScheme:xt.ProtocolPath};E.keyEncryptionInputs.push(M)}if(e.encryptSymmetricKeyWithProtocolContextDerivedKey){let _;if(o===void 0){let A={rootKeyId:n.keyId,derivationScheme:xt.ProtocolContext,derivedPrivateKey:n.encryptionKeyPair.privateJwk},D=await Pt.getEntryId(n.did,y.descriptor),M=Ae.constructKeyDerivationPathUsingProtocolContextScheme(D),C=await ji.derivePublicKey(A,M);_={publicKeyId:n.keyId,publicKey:C,derivationScheme:xt.ProtocolContext}}else{if(c===void 0||l===void 0)throw new Error("`protocolContextDerivingRootKeyId` and `protocolContextDerivedPublicKeyJwk` must both be defined if `protocolContextId` is given");_={publicKeyId:c,publicKey:l,derivationScheme:xt.ProtocolContext}}E.keyEncryptionInputs.push(_)}return await w.encryptSymmetricEncryptionKey(E),await w.sign({signer:ct.createSigner(n)}),{message:y,dataStream:v,recordsWrite:w,encryptedDataBytes:f,encryptionInput:E}}static async generateFromRecordsWrite(e){let t=e.existingWrite.message,n=_t.getCurrentTimestamp(),i=!(e.published??t.descriptor.published),a=e.datePublished??(i?n:void 0),s=e.data??r.randomBytes(32),o=zt.fromBytes(s),c={recordsWriteMessage:e.existingWrite.message,data:s,published:i,datePublished:a,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:ct.createSigner(e.author)},l=await Pt.createFrom(c);return{message:l.message,recordsWrite:l,dataBytes:s,dataStream:o}}static async generateRecordsQuery(e){let t=e?.author,n=e?.anonymous??!1;if(n&&t)throw new Error("Cannot have `author` and be anonymous at the same time.");t===void 0&&!n&&(t=await r.generatePersona());let i;t!==void 0&&(i=ct.createSigner(t));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole};Wt(a);let o=(await wa.create(a)).message;return{author:t,message:o}}static async generateRecordsSubscribe(e){let t=e?.author,n=e?.anonymous??!1;if(n&&t)throw new Error("Cannot have `author` and be anonymous at the same time.");t===void 0&&!n&&(t=await r.generatePersona());let i;t!==void 0&&(i=ct.createSigner(t));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole,cursor:e?.cursor};Wt(a);let o=(await Aa.create(a)).message;return{author:t,message:o}}static async generateRecordsCount(e){let t=e?.author,n=e?.anonymous??!1;if(n&&t)throw new Error("Cannot have `author` and be anonymous at the same time.");t===void 0&&!n&&(t=await r.generatePersona());let i;t!==void 0&&(i=ct.createSigner(t));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},protocolRole:e?.protocolRole};Wt(a);let o=(await yd.create(a)).message;return{author:t,message:o}}static async generateRecordsDelete(e){let t=e?.author??await r.generateDidKeyPersona(),n=await _a.create({recordId:e?.recordId??await r.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:ct.createSigner(t)});return{author:t,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let t=e?.author??await r.generatePersona(),n=ct.createSigner(t),i={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};Wt(i);let a=await vd.create(i),s=a.message;return{author:t,messagesSubscribe:a,message:s}}static async generateMessagesRead(e){let t=e?.author??await r.generatePersona(),i={signer:ct.createSigner(t),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},a=await wd.create(i);return{author:t,messagesRead:a,message:a.message}}static generateAuthorization(){return{signature:r.generateAuthorizationSignature()}}static generateAuthorizationSignature(){return{payload:"anyPayload",signatures:[{protected:"anyProtectedHeader",signature:"anySignature"}]}}static async randomSignatureString(){let e=await Gg.generateKeyPair(),t=await Gg.sign(r.randomBytes(32),e.privateJwk);return Ie.bytesToBase64Url(t)}static randomString(e){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="";for(let i=0;i<e;i++)n+=t.charAt(Math.floor(Math.random()*t.length));return n}static randomBytes(e){let t=new Uint8Array(e);for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return t}static async randomCborSha256Cid(){let e=r.randomBytes(32),t=await On.digest(e);return(await Yt.createV1(gu,t)).toString()}static randomInt(e,t){return Math.floor(Math.random()*(t-e)+e)}static randomTimestamp(e){let{year:t,month:n,day:i,hour:a,minute:s,second:o,millisecond:c,microsecond:l}=e||{};return _t.createTimestamp({year:t||this.randomInt(2e3,2022),month:n||this.randomInt(1,12),day:i||this.randomInt(1,28),hour:a||this.randomInt(0,23),minute:s||this.randomInt(0,59),second:o||this.randomInt(0,59),millisecond:c||this.randomInt(0,1e3),microsecond:l||this.randomInt(0,1e3)})}static createDidResolutionResult(e){return{didResolutionMetadata:{},didDocument:{id:e.did,verificationMethod:[{controller:e.did,id:e.keyId,type:"JsonWebKey2020",publicKeyJwk:e.keyPair.publicJwk}]},didDocumentMetadata:{}}}static async generateDidKeyPersona(){let e=await mb.create(),t=await mb.getSigningMethod({didDocument:e.document}),n=t.id,i=await e.export(),a={publicJwk:t.publicKeyJwk,privateJwk:i.privateKeys[0]},s=await kt.generateKey(),c={publicJwk:await kt.getPublicKey({key:s}),privateJwk:s};return{did:e.uri,keyId:n,keyPair:a,encryptionKeyPair:c,signer:new il({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:n})}}}});var QE,lH=G(()=>{"use strict";g();st();QE=class r{static pollRetrySleep=20;static pollTimeout=2e3;static async pollUntilSuccessOrTimeout(e,t=r.pollRetrySleep,n=r.pollTimeout){let i=Date.now();for(;;)try{return await e()}catch{if(Date.now()-i>=n)throw new Error("Operation timed out");await Jc(t)}}}});var uH={};ir(uH,{AllowAllTenantGate:()=>by,BlockstoreLevel:()=>If,Cid:()=>ur,ContentEncryptionAlgorithm:()=>ci,CoreProtocolRegistry:()=>vy,DataStoreLevel:()=>Cf,DataStream:()=>zt,DateSort:()=>Ot,Dwn:()=>cg,DwnConstant:()=>co,DwnError:()=>ne,DwnErrorCode:()=>re,DwnInterfaceName:()=>ve,DwnMethodName:()=>me,Encoder:()=>Ie,Encryption:()=>xi,EventEmitterEventLog:()=>Of,HdKey:()=>ji,IndexLevel:()=>Rh,Jws:()=>ct,KeyAgreementAlgorithm:()=>yv,KeyDerivationScheme:()=>xt,LevelWrapper:()=>Na,Message:()=>ye,MessageStoreLevel:()=>$f,MessagesRead:()=>wd,MessagesSubscribe:()=>vd,MessagesSync:()=>Zu,PERMISSIONS_REVOCATION_PATH:()=>RP,PermissionConditionPublication:()=>Vm,PermissionGrant:()=>kr,PermissionRequest:()=>gd,PermissionsProtocol:()=>et,Poller:()=>QE,PrivateKeySigner:()=>il,ProtocolRecordLimitStrategy:()=>Zl,Protocols:()=>Sd,ProtocolsConfigure:()=>Sa,ProtocolsQuery:()=>ka,Records:()=>Ae,RecordsCount:()=>yd,RecordsDelete:()=>_a,RecordsQuery:()=>wa,RecordsRead:()=>_d,RecordsSubscribe:()=>Aa,RecordsWrite:()=>Pt,ResumableTaskStoreLevel:()=>Bf,SMTStoreLevel:()=>pg,SMTStoreMemory:()=>YE,SMT_DEPTH:()=>hs,Secp256k1:()=>Va,Secp256r1:()=>nl,SortDirection:()=>At,SparseMerkleTree:()=>hg,StateIndexLevel:()=>jf,TestDataGenerator:()=>XE,Time:()=>_t,ZERO_HASH:()=>kx,authenticate:()=>mn,createLevelDatabase:()=>Js,executeUnlessAborted:()=>Wn,getBit:()=>lo,getDefaultHashes:()=>ZI,getRuleSetAtPath:()=>kd,hashChildren:()=>Dl,hashEquals:()=>sn,hashKey:()=>Vu,hashLeaf:()=>xy,hashToHex:()=>on,hexToHash:()=>Wu,initDefaultHashes:()=>Il,isCrossProtocolRef:()=>af,parseCrossProtocolRef:()=>Hs});var Zn=G(()=>{"use strict";g();Lg();qo();VI();RT();WI();fl();gx();wx();wu();Hm();CF();Py();vt();ar();Tn();Ex();gv();zs();kE();Uc();yr();bx();YI();lc();JI();Fo();v1();nh();d2();u2();Qn();A0();XR();v2();t1();Hk();rd();qs();CT();Pp();_E();LG();$6();Tf();tH();rH();oH();aH();M6();j6();cH();Ju();dH();lH()});var iS=ke((bVe,wH)=>{g();var gg=1e3,wg=gg*60,vg=wg*60,Bh=vg*24,hge=Bh*7,mge=Bh*365.25;wH.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return yge(r);if(t==="number"&&isFinite(r))return e.long?wge(r):gge(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function yge(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*mge;case"weeks":case"week":case"w":return t*hge;case"days":case"day":case"d":return t*Bh;case"hours":case"hour":case"hrs":case"hr":case"h":return t*vg;case"minutes":case"minute":case"mins":case"min":case"m":return t*wg;case"seconds":case"second":case"secs":case"sec":case"s":return t*gg;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function gge(r){var e=Math.abs(r);return e>=Bh?Math.round(r/Bh)+"d":e>=vg?Math.round(r/vg)+"h":e>=wg?Math.round(r/wg)+"m":e>=gg?Math.round(r/gg)+"s":r+"ms"}function wge(r){var e=Math.abs(r);return e>=Bh?nS(r,e,Bh,"day"):e>=vg?nS(r,e,vg,"hour"):e>=wg?nS(r,e,wg,"minute"):e>=gg?nS(r,e,gg,"second"):r+" ms"}function nS(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});g();g();Zn();Zn();var De=(d=>(d[d.MessagesRead=ve.Messages+me.Read]="MessagesRead",d[d.MessagesSubscribe=ve.Messages+me.Subscribe]="MessagesSubscribe",d[d.MessagesSync=ve.Messages+me.Sync]="MessagesSync",d[d.ProtocolsConfigure=ve.Protocols+me.Configure]="ProtocolsConfigure",d[d.ProtocolsQuery=ve.Protocols+me.Query]="ProtocolsQuery",d[d.RecordsDelete=ve.Records+me.Delete]="RecordsDelete",d[d.RecordsQuery=ve.Records+me.Query]="RecordsQuery",d[d.RecordsRead=ve.Records+me.Read]="RecordsRead",d[d.RecordsSubscribe=ve.Records+me.Subscribe]="RecordsSubscribe",d[d.RecordsWrite=ve.Records+me.Write]="RecordsWrite",d))(De||{}),Ch={[De.MessagesRead]:wd,[De.MessagesSubscribe]:vd,[De.MessagesSync]:Zu,[De.ProtocolsConfigure]:Sa,[De.ProtocolsQuery]:ka,[De.RecordsDelete]:_a,[De.RecordsQuery]:wa,[De.RecordsRead]:_d,[De.RecordsSubscribe]:Aa,[De.RecordsWrite]:Pt};g();async function K6(r){let e={kind:r.kind};r.kind==="protocol"&&(e.protocol=r.protocol,r.protocolPathPrefixes!==void 0&&(e.protocolPathPrefixes=[...new Set(r.protocolPathPrefixes)].sort((l,d)=>l.localeCompare(d))),r.contextIdPrefixes!==void 0&&(e.contextIdPrefixes=[...new Set(r.contextIdPrefixes)].sort((l,d)=>l.localeCompare(d))));let t=JSON.stringify(e),n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-256",n),a=new Uint8Array(i),s="";for(let l of a)s+=String.fromCharCode(l);let o=btoa(s).replaceAll("+","-").replaceAll("/","_"),c=o.length;for(;c>0&&o.codePointAt(c-1)===61;)c--;return c===o.length?o:o.slice(0,c)}var U6=100;g();var N6="^",ss=class r{constructor(e){this.db=e,this.sublevel=this.db.sublevel("replicationLinks")}static buildKey(e,t,n){return`${e}${N6}${t}${N6}${n}`}async getOrCreateLink(e){let t=await K6(e.scope),n=r.buildKey(e.tenantDid,e.remoteEndpoint,t);try{let a=await this.sublevel.get(n),s=JSON.parse(a);return delete s.push,s.connectivity="unknown",s}catch(a){if(a.code!=="LEVEL_NOT_FOUND")throw a}let i={tenantDid:e.tenantDid,remoteEndpoint:e.remoteEndpoint,scopeId:t,scope:e.scope,status:"initializing",connectivity:"unknown",pull:{},needsReconcile:!1,delegateDid:e.delegateDid,protocol:e.protocol};return await this.sublevel.put(n,JSON.stringify(i)),i}async saveLink(e){let t=r.buildKey(e.tenantDid,e.remoteEndpoint,e.scopeId);e.lastActivityAt=new Date().toISOString(),await this.sublevel.put(t,JSON.stringify(e))}async deleteLink(e,t,n){let i=r.buildKey(e,t,n);await this.sublevel.del(i)}async getLinksForTenant(e){let t=`${e}${N6}`,n=[];for await(let[i,a]of this.sublevel.iterator())i.startsWith(t)&&n.push(JSON.parse(a));return n}async getAllLinks(){let e=[];for await(let[,t]of this.sublevel.iterator())e.push(JSON.parse(t));return e}async updateDelegateDid(e,t){let n=await this.getLinksForTenant(e),i=[];for(let a of n)a.delegateDid!==t&&(a.delegateDid=t,await this.saveLink(a),i.push(a));return i}async setStatus(e,t){e.status=t,await this.saveLink(e)}static comparePosition(e,t){let n=BigInt(e.position)-BigInt(t.position);return n<BigInt(0)?-1:n>BigInt(0)?1:0}static validateTokenDomain(e,t){return e.contiguousAppliedToken===void 0?!0:t.streamId===e.contiguousAppliedToken.streamId&&t.epoch===e.contiguousAppliedToken.epoch}static setReceivedToken(e,t){(e.receivedToken===void 0||r.comparePosition(t,e.receivedToken)>0)&&(e.receivedToken=t)}static commitContiguousToken(e,t){e.contiguousAppliedToken=t}static resetCheckpoint(e,t){e.contiguousAppliedToken=t,e.receivedToken=t}async markNeedsReconcile(e,t){e.needsReconcile||(e.needsReconcile=!0,await this.saveLink(e))}async clearNeedsReconcile(e){e.needsReconcile&&(e.needsReconcile=!1,await this.saveLink(e))}};g();var L6=(p=>(p.ProtocolMetadataMissing="ClosureProtocolMetadataMissing",p.InitialWriteMissing="ClosureInitialWriteMissing",p.ParentChainMissing="ClosureParentChainMissing",p.ContextChainMissing="ClosureContextChainMissing",p.GrantMissing="ClosureGrantMissing",p.GrantNotYetActive="ClosureGrantNotYetActive",p.GrantExpired="ClosureGrantExpired",p.GrantRevocationMissing="ClosureGrantRevocationMissing",p.VisibilityFloorMissing="ClosureVisibilityFloorMissing",p.EncryptionDependencyMissing="ClosureEncryptionDependencyMissing",p.CrossProtocolReferenceMissing="ClosureCrossProtocolReferenceMissing",p.DependencyForbidden="ClosureDependencyForbidden",p.DepthExceeded="ClosureDepthExceeded",p))(L6||{});function kb(r,e,t){return{tenantDid:r,protocolCache:new Map,grantCache:new Map,satisfiedDeps:new Set,missingDeps:new Set,maxDepth:e??32,isDelegateSession:t?.isDelegateSession}}function fH(r,e){let t=e.descriptor;if(t.interface==="Protocols"&&t.method==="Configure"){let n=t.definition?t.definition.protocol:void 0;n&&r.protocolCache.delete(n)}if(t.protocol==="https://identity.foundation/dwn/permissions"){let n=e.recordId,i=t.protocolPath;if(i==="grant"&&n&&(r.grantCache.delete(n),r.satisfiedDeps.delete(`permissionGrant:grantId:${n}`),r.missingDeps.delete(`permissionGrant:grantId:${n}`)),i==="grant/revocation"){let a=t.parentId;a&&(r.grantCache.delete(`revocation:${a}`),r.satisfiedDeps.delete(`grantRevocation:grantId:${a}`),r.missingDeps.delete(`grantRevocation:grantId:${a}`),r.satisfiedDeps.delete(`permissionGrant:grantId:${a}`),r.missingDeps.delete(`permissionGrant:grantId:${a}`))}}if(t.interface==="Records"){let n=e.recordId,i=t.protocol,a=t.protocolPath;if(n){let s=o=>{let c=o.indexOf(n);if(c===-1)return!1;let l=c>0?o[c-1]:":",d=c+n.length<o.length?o[c+n.length]:"|",u=l===":"||l==="|",f=d==="|"||d===void 0;return u&&(c+n.length===o.length||f)};for(let o of r.satisfiedDeps)s(o)&&r.satisfiedDeps.delete(o);for(let o of r.missingDeps)s(o)&&r.missingDeps.delete(o)}if(i&&a){let s=`filter:${i}|${a}`;for(let o of r.satisfiedDeps)o.includes(s)&&r.satisfiedDeps.delete(o);for(let o of r.missingDeps)o.includes(s)&&r.missingDeps.delete(o)}if(i==="https://identity.foundation/protocols/key-delivery"){let o=e.descriptor?.tags?.protocol;if(o){let c=`messageCid:${o}|`;for(let l of r.satisfiedDeps)l.includes(c)&&r.satisfiedDeps.delete(l);for(let l of r.missingDeps)l.includes(c)&&r.missingDeps.delete(l)}}else if(i){let s=`messageCid:${i}|`;for(let o of r.satisfiedDeps)o.includes(s)&&r.satisfiedDeps.delete(o);for(let o of r.missingDeps)o.includes(s)&&r.missingDeps.delete(o)}}}g();Zn();g();function pH(r,e){let[t,...n]=e.split("/"),i=r.structure[t];for(let a of n){if(!i)return;i=i[a]}return i}function KHe(r){return r.split("/")[0]||r}function $h(r,e){let t=pH(r,e);if(!t)return!1;function n(i){for(let a in i)if(!a.startsWith("$")){let s=i[a];if(s.$role===!0||n(s))return!0}return!1}return n(t)?!0:q6(void 0,e,r)}function q6(r,e,t){function n(i){if(i.$actions){for(let a of i.$actions)if(a.who&&a.who!=="anyone"&&(r===void 0||a.who===r)&&a.of===e&&a.can?.includes("read"))return!0}for(let a in i)if(!a.startsWith("$")&&n(i[a]))return!0;return!1}for(let i in t.structure)if(n(t.structure[i]))return!0;return!1}function z6({protocolDefinition:r,protocolPath:e,recipient:t,tenantDid:n,authorDid:i}){let a=new Set,s=pH(r,e);return s&&(s.$role===!0&&t&&a.add(t),t&&t!==n&&q6("recipient",e,r)&&a.add(t),i&&i!==n&&q6("author",e,r)&&a.add(i),a.delete(n)),a}function sge(r){let t=r.descriptor.protocol;return t?t===et.uri?[]:[{dependencyClass:1,label:"protocolsConfigure",identifier:t,identifierType:"protocol"}]:[]}function oge(r){let e=r.descriptor,t=[];if(e.interface!=="Records")return[];let n=r.recordId,i=e.parentId;i&&t.push({dependencyClass:2,label:"parentRecord",identifier:i,identifierType:"recordId"});let a=r.contextId;if(a&&n&&a!==n){let s=a.split("/")[0];t.push({dependencyClass:2,label:"contextRoot",identifier:s,identifierType:"recordId"})}if(n&&e.method==="Write"){let s=e.dateCreated,o=e.messageTimestamp;s&&o&&s!==o&&t.push({dependencyClass:2,label:"initialWrite",identifier:n,identifierType:"recordId"})}return n&&e.method==="Delete"&&t.push({dependencyClass:2,label:"initialWrite",identifier:n,identifierType:"recordId"}),t}function age(r){let e=[],t=r.authorization;if(!t)return[];let n=t.signature?.payload;if(n)try{let i=JSON.parse(Buffer.from(n,"base64url").toString("utf-8"));i.permissionGrantId&&(e.push({dependencyClass:3,label:"permissionGrant",identifier:i.permissionGrantId,identifierType:"grantId"}),e.push({dependencyClass:3,label:"grantRevocation",identifier:i.permissionGrantId,identifierType:"grantId"}))}catch{}return e}function cge(r,e){if(!r||!e)return;let t=e.split("/"),n=r,i;for(let a of t){if(!Object.hasOwn(n,a))return;i=n[a],n=i}return i}function dge(r,e,t){let n=r.descriptor;if(n.interface!=="Records")return[];let i=n.protocolPath;if(!i)return[];let a=[];if(cge(e?.structure,i)?.$encryption){let d=i.split("/").pop();if(e?.types?.[d??""]?.encryptionRequired===!0){a.push({dependencyClass:5,label:"encryptionKeyMaterial",identifier:n.protocol,identifierType:"protocol"});let f=r.contextId,p=!1;if(f){let m=i.split("/")[0];p=$h(e,m)}if(t&&!p||a.push({dependencyClass:5,label:"keyDeliveryProtocol",identifier:"https://identity.foundation/protocols/key-delivery",identifierType:"protocol"}),p&&f){let m=f.split("/")[0];a.push({dependencyClass:5,label:"contextKeyRecord",identifier:`${n.protocol}|${m}`,identifierType:"messageCid"})}}}let o=i.split("/")[0],c=e?.structure?.[o];if(c?.$ref){let d=c.$ref.indexOf(":");if(d>0){let u=c.$ref.substring(0,d),p=e?.uses?.[u];if(p){a.push({dependencyClass:6,label:"crossProtocolConfig",identifier:p,identifierType:"protocol"});let h=i.split("/"),m=n.parentId;h.length===2&&m&&a.push({dependencyClass:6,label:"crossProtocolParent",identifier:`${p}|${m}`,identifierType:"recordId"})}}}let l=r.authorization;if(l&&e?.uses){let d=l.signature?.payload;if(d)try{let f=JSON.parse(Buffer.from(d,"base64url").toString("utf-8")).protocolRole;if(f?.includes(":")){let p=f.indexOf(":"),h=f.substring(0,p),m=e.uses[h];if(m){a.push({dependencyClass:6,label:"crossProtocolRoleConfig",identifier:m,identifierType:"protocol"});let y=f.substring(p+1),v=ye.getAuthor(r),w=r.contextId;if(v){let E={interface:"Records",method:"Write",protocol:m,protocolPath:y,recipient:v,isLatestBaseState:!0};if(w){let A=y.split("/").length-1;if(A>0){let M=w.split("/").slice(0,A).join("/");M&&(E.contextId={gte:M,lt:M+"\uFFFF"})}}let _=E.contextId?JSON.stringify(E.contextId):"no-context";a.push({dependencyClass:6,label:"crossProtocolRoleRecord",identifier:`${m}|${y}|${v}|${_}`,identifierType:"filter",filter:E})}}}}catch{}}return a}async function eS(r,e,t,n){if(t.kind==="full")return{complete:!0,rootMessageCid:await ye.getCid(r),edges:[],depth:0};let i=await ye.getCid(r),a=[],s=new Set,o=0,c=[r];for(s.add(i);c.length>0;){if(o>=n.maxDepth)return{complete:!1,rootMessageCid:i,edges:a,failure:{code:"ClosureDepthExceeded",edge:{dependencyClass:1,label:"depth",identifier:String(o),identifierType:"messageCid"},detail:`closure traversal exceeded max depth of ${n.maxDepth}`},depth:o};let l=c.length;for(let d=0;d<l;d++){let u=c.shift(),f=[...sge(u),...oge(u),...age(u)],p=await hH(f,a,e,n,s,c,i,o);if(p)return p;let m=u.descriptor.protocol;if(m){let v=n.protocolCache.get(m)?.descriptor?.definition;if(v){let w=dge(u,v,n.isDelegateSession),E=await hH(w,a,e,n,s,c,i,o);if(E)return E}}if(o===0){let y=uge(u,a,n,i,o);if(y)return y}}o++}return{complete:!0,rootMessageCid:i,edges:a,depth:o}}async function lge(r,e,t,n,i){let a=kb(n,i),s=[];for(let o of r){let c=await eS(o,e,t,a);s.push(c)}return s}function uge(r,e,t,n,i){let a=e.find(p=>p.label==="permissionGrant");if(!a)return null;let s=r.descriptor.messageTimestamp;if(!s)return null;let o=t.grantCache.get(a.identifier);if(!o)return null;let c=o.descriptor.dateCreated,l,d=o.encodedData;if(d)try{l=JSON.parse(Buffer.from(d,"base64url").toString("utf-8")).dateExpires}catch{}if(c&&s<c)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:"ClosureGrantNotYetActive",edge:a,detail:`grant '${a.identifier}' is not yet active at message timestamp ${s} (dateGranted: ${c})`},depth:i};if(l&&s>=l)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:"ClosureGrantExpired",edge:a,detail:`grant '${a.identifier}' expired at ${l}, message timestamp is ${s}`},depth:i};let u=`revocation:${a.identifier}`,f=t.grantCache.get(u);if(f&&f.descriptor.interface!=="Synthetic"){let p=f.descriptor.messageTimestamp;if(p&&p<=s)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:"ClosureGrantRevocationMissing",edge:e.find(h=>h.label==="grantRevocation")??a,detail:`grant '${a.identifier}' was revoked at ${p}, before message timestamp ${s}`},depth:i}}return null}async function hH(r,e,t,n,i,a,s,o){for(let c of r){e.push(c);let l=`${c.label}:${c.identifierType}:${c.identifier}`;if(n.satisfiedDeps.has(l))continue;if(n.missingDeps.has(l))return{complete:!1,rootMessageCid:s,edges:e,failure:{code:mH(c),edge:c,detail:`dependency '${c.label}' (${c.identifier}) is missing`},depth:o};let d=await fge(c,t,n);if(!d)return n.missingDeps.add(l),{complete:!1,rootMessageCid:s,edges:e,failure:{code:mH(c),edge:c,detail:`dependency '${c.label}' (${c.identifier}) not found locally`},depth:o};if(n.satisfiedDeps.add(l),!(c.identifierType==="grantId"||c.identifierType==="filter"||c.label==="contextKeyRecord")){let f=await ye.getCid(d);i.has(f)||(i.add(f),a.push(d))}}return null}async function fge(r,e,t){switch(r.identifierType){case"protocol":{if(t.protocolCache.has(r.identifier))return t.protocolCache.get(r.identifier)??null;let{messages:n}=await e.query(t.tenantDid,[{interface:"Protocols",method:"Configure",protocol:r.identifier,isLatestBaseState:!0}]),i=n.length>0?n[0]:null;return t.protocolCache.set(r.identifier,i),i}case"recordId":{if(r.label==="initialWrite"){let{messages:i}=await e.query(t.tenantDid,[{entryId:r.identifier}]);if(i.length>0)return i[0];let{messages:a}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",recordId:r.identifier,isLatestBaseState:!1}]);return a.length>0?a[0]:null}if(r.label==="crossProtocolParent"){let i=r.identifier.indexOf("|");if(i>0){let a=r.identifier.substring(0,i),s=r.identifier.substring(i+1),{messages:o}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:a,recordId:s,isLatestBaseState:!0}]);return o.length>0?o[0]:null}}let{messages:n}=await e.query(t.tenantDid,[{interface:"Records",recordId:r.identifier,isLatestBaseState:!0}]);return n.length>0?n[0]:null}case"grantId":{if(r.label==="grantRevocation"){let a=`revocation:${r.identifier}`;if(t.grantCache.has(a))return t.grantCache.get(a)??null;let{messages:s}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/dwn/permissions",parentId:r.identifier,protocolPath:"grant/revocation",isLatestBaseState:!0}]),o;for(let d of s){let u=d.descriptor.messageTimestamp;(!o||u<o.descriptor.messageTimestamp)&&(o=d)}let l=o??{descriptor:{interface:"Synthetic",method:"NoRevocation"}};return t.grantCache.set(a,l),l}if(t.grantCache.has(r.identifier))return t.grantCache.get(r.identifier)??null;let{messages:n}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/dwn/permissions",protocolPath:"grant",recordId:r.identifier,isLatestBaseState:!0}]),i=n.length>0?n[0]:null;return t.grantCache.set(r.identifier,i),i}case"messageCid":{if(r.label==="contextKeyRecord"){let n=r.identifier.indexOf("|");if(n>0){let i=r.identifier.substring(0,n),a=r.identifier.substring(n+1),{messages:s}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/protocols/key-delivery",protocolPath:"contextKey","tag.protocol":i,"tag.contextId":a}]);return s.length>0?s[0]:null}}return await e.get(t.tenantDid,r.identifier)??null}case"filter":{if(!r.filter)return null;let{messages:n}=await e.query(t.tenantDid,[r.filter]);return n.length>0?n[0]:null}default:return null}}function mH(r){switch(r.dependencyClass){case 1:return"ClosureProtocolMetadataMissing";case 2:return r.label==="initialWrite"?"ClosureInitialWriteMissing":r.label==="parentRecord"?"ClosureParentChainMissing":r.label==="contextRoot"?"ClosureContextChainMissing":"ClosureParentChainMissing";case 3:return r.label==="permissionGrant"?"ClosureGrantMissing":"ClosureGrantRevocationMissing";case 4:return r.label==="squashContextRoot"?"ClosureVisibilityFloorMissing":"ClosureVisibilityFloorMissing";case 5:return"ClosureEncryptionDependencyMissing";case 6:return"ClosureCrossProtocolReferenceMissing";default:return"ClosureDependencyForbidden"}}g();Qo();st();var Mf=class extends EE{constructor({agent:t,db:n,location:i,ttl:a}){super({db:n,location:i,ttl:a});this._resolving=new Map;this._agent=t}get agent(){if(!this._agent)throw new Error("Agent not initialized");return this._agent}set agent(t){this._agent=t}async get(t){try{let n=await this.cache.get(t),i=JSON.parse(n);if(!this._resolving.has(t)&&Date.now()>=i.ttlMillis){this._resolving.set(t,!0);let a=await this.agent.did.get({didUri:t,tenant:this.agent.agentDid.uri});if(typeof a>"u")this._resolving.delete(t),this.cache.nextTick(()=>this.cache.del(t));else try{let s=await this.agent.did.resolve(t);if(!s.didResolutionMetadata.error&&s.didDocument){let o={...a,document:s.didDocument,metadata:s.didDocumentMetadata};try{await this.agent.did.update({portableDid:o,tenant:this.agent.agentDid.uri,publish:!1})}catch(c){c.message&&!c.message.includes("No changes detected, update aborted")&&us.error(`Error updating DID: ${c.message}`)}}}finally{this._resolving.delete(t)}}return i.value}catch(n){if(n.notFound)return;throw n}}};g();var yH=class{constructor(e){this.agent=e.agent,this.did=e.did,this.delegateDid=e.delegateDid,this.recoveryPhrase=e.recoveryPhrase,this.identity=e.identity}};g();Zn();g();Qo();Zn();async function mg(r,e){let t=await e.dereference(`${r}#dwn`);if(t.dereferencingMetadata.error)throw new Error(`Failed to dereference '${r}#dwn': ${t.dereferencingMetadata.error}`);if(e6.isDwnDidService(t.contentStream)){let{serviceEndpoint:n}=t.contentStream,i=typeof n=="string"?[n]:Array.isArray(n)&&n.every(a=>typeof a=="string")?n:[];if(i.length>0)return i}return[]}function eVe(r){return ye.getAuthor(r)}function tVe(r){return ct.decodePlainObjectPayload(r.authorization.signature)?.protocolRole}function Kd(r){return!r||typeof r!="object"||r===null?!1:"message"in r&&typeof r.message=="object"&&r.message!==null&&"descriptor"in r.message&&typeof r.message.descriptor=="object"&&r.message.descriptor!==null&&"interface"in r.message.descriptor&&r.message.descriptor.interface===ve.Records&&"method"in r.message.descriptor&&r.message.descriptor.method===me.Write}function pge(r){return ye.getCid(r)}async function rVe(r,e){let t=e===Ot.CreatedAscending||e===Ot.CreatedDescending?r.descriptor.dateCreated:r.descriptor.datePublished;if(t===void 0)throw new Error("The dateCreated or datePublished property is missing from the record descriptor.");return{messageCid:await pge(r),value:t}}function nVe(r,e=3e3,t=3e5,n){let i=Date.now()+t,a=null,s=!0;return new Promise((o,c)=>{n&&n.addEventListener("abort",()=>{s=!1,a!==null&&clearTimeout(a),console.log("Polling aborted by user"),o(null)});async function l(){if(!s)return;let d=i-Date.now();if(d<=0){s=!1,console.log("Polling stopped: TTL reached"),o(null);return}console.log(`Polling... (Remaining time: ${Math.ceil(d/1e3)}s)`);try{let u=await r();if(u.ok){s=!1,a!==null&&clearTimeout(a),console.log("Polling stopped: Success condition met"),o(u);return}}catch(u){console.error("Error fetching data:",u),c(u)}s&&(a=setTimeout(l,e))}l()})}async function F6(r,e,t){if(!Number.isInteger(e)||e<1)throw new Error(`mapConcurrent: concurrency must be a positive integer, got ${e}`);if(r.length===0)return[];let n=new Array(r.length),i=0,a=async()=>{for(;;){let c=i++;if(c>=r.length)return;n[c]=await t(r[c],c)}},s=Math.min(e,r.length),o=[];for(let c=0;c<s;c++)o.push(a());return await Promise.all(o),n}async function tS(r,e,t){return F6(r,e,async(n,i)=>{try{return{status:"fulfilled",value:await t(n,i)}}catch(a){return{status:"rejected",reason:a}}})}var gH=class{constructor({didResolver:e,rpcClient:t}){this._didResolver=e,this._rpcClient=t}async recordsQuery(e,t){let n=await wa.create({filter:t.filter,dateSort:t.dateSort,pagination:t.pagination,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,n.message)}async recordsRead(e,t){let n=await _d.create({filter:t.filter,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,n.message)}async recordsSubscribe(e,t,n){let i=await Aa.create({filter:t.filter,dateSort:t.dateSort,pagination:t.pagination,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,i.message,void 0,n)}async recordsCount(e,t){let n=await yd.create({filter:t.filter,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,n.message)}async protocolsQuery(e,t){let n=await ka.create({filter:t?.filter,messageTimestamp:t?.messageTimestamp});return await this.sendRequest(e,n.message)}async sendRequest(e,t,n,i){let a=await mg(e,this._didResolver),s=[];for(let o of a)try{if(i!==void 0){if(!(await this._rpcClient.getServerInfo(o)).webSocketSupport){s.push({url:o,message:"WebSocket support is not enabled on the server."});continue}let d=new URL(o);d.protocol=d.protocol==="http:"?"ws:":"wss:",o=d.toString()}return await this._rpcClient.sendDwnRequest({dwnUrl:o,targetDid:e,message:t,data:n,subscriptionHandler:i})}catch(c){s.push({url:o,message:c instanceof Error?c.message:"Unknown error"})}throw new Error(`AnonymousDwnApi: Failed to send request to '${e}': ${JSON.stringify(s)}`)}};g();var yg=class{constructor({did:e,metadata:t}){this.did=e,this.metadata=t}async export(){return{portableDid:await this.did.export(),metadata:{...this.metadata}}}};g();bn();var G6={"AES-GCM":{implementation:zm,names:["A128GCM","A192GCM","A256GCM"],operations:["bytesToPrivateKey","decrypt","encrypt","generateKey"]},"AES-KW":{implementation:Fm,names:["A128KW","A192KW","A256KW"],operations:["bytesToPrivateKey","generateKey","privateKeyToBytes","wrapKey","unwrapKey"]},Ed25519:{implementation:Qc,names:["Ed25519"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},HKDF:{implementation:_P,names:["HKDF-256","HKDF-384","HKDF-512"],operations:["deriveKey","deriveKeyBytes"]},PBKDF2:{implementation:TP,names:["PBES2-HS256+A128KW","PBES2-HS384+A192KW","PBES2-HS512+A256KW"],operations:["deriveKey","deriveKeyBytes"]},secp256k1:{implementation:pc,names:["ES256K","secp256k1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},secp256r1:{implementation:pc,names:["ES256","secp256r1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},"SHA-256":{implementation:Cu,names:["SHA-256"],operations:["digest"]},X25519:{implementation:Bu,names:["X25519"],operations:["bytesToPrivateKey","generateKey"]}},bo=class{constructor(){this._algorithmInstances=new Map}async bytesToPrivateKey({algorithm:e,privateKeyBytes:t}){let n=this.getAlgorithmName({algorithm:e});return await this.getAlgorithm({algorithm:n}).bytesToPrivateKey({algorithm:e,privateKeyBytes:t})}async bytesToPublicKey({algorithm:e,publicKeyBytes:t}){let n=this.getAlgorithmName({algorithm:e});return await this.getAlgorithm({algorithm:n}).bytesToPublicKey({algorithm:e,publicKeyBytes:t})}async decrypt(e){let t=this.getAlgorithmName({key:e.key});return await this.getAlgorithm({algorithm:t}).decrypt(e)}async deriveKey(e){let t=this.getAlgorithmName({algorithm:e.algorithm}),n=this.getAlgorithm({algorithm:t}),i;switch(e.algorithm){case"HKDF-256":case"HKDF-384":case"HKDF-512":{i=e.derivedKeyAlgorithm;break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{i=e.algorithm.split(/[-+]/)[2];break}default:throw new qe(Ue.AlgorithmNotSupported,`The specified "algorithm" is not supported: ${e.algorithm}`)}let a=+(i.match(/\d+/)?.[0]??-1);if(a===-1)throw new qe(Ue.AlgorithmNotSupported,`The derived key algorithm" is not supported: ${i}`);let s=await n.deriveKeyBytes({...e,length:a});return await this.bytesToPrivateKey({algorithm:i,privateKeyBytes:s})}async deriveKeyBytes(e){let t=this.getAlgorithmName({algorithm:e.algorithm});return await this.getAlgorithm({algorithm:t}).deriveKeyBytes(e)}async digest({algorithm:e,data:t}){return await this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:t})}async encrypt(e){let t=this.getAlgorithmName({key:e.key});return await this.getAlgorithm({algorithm:t}).encrypt(e)}async generateKey(e){let t=this.getAlgorithmName({algorithm:e.algorithm}),i=await this.getAlgorithm({algorithm:t}).generateKey({algorithm:e.algorithm});return i.kid??=await yt({jwk:i}),i}async getPublicKey({key:e}){let t=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:t}).getPublicKey({key:e})}async privateKeyToBytes({privateKey:e}){let t=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:t}).privateKeyToBytes({privateKey:e})}async publicKeyToBytes({publicKey:e}){let t=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:t}).publicKeyToBytes({publicKey:e})}async sign({key:e,data:t}){let n=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:n}).sign({data:t,key:e})}async unwrapKey(e){let t=this.getAlgorithmName({key:e.decryptionKey});return await this.getAlgorithm({algorithm:t}).unwrapKey(e)}async verify({key:e,signature:t,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:t,data:n})}async wrapKey(e){let t=this.getAlgorithmName({key:e.encryptionKey});return await this.getAlgorithm({algorithm:t}).wrapKey(e)}getAlgorithm({algorithm:e}){let t=G6[e]?.implementation;if(!t)throw new qe(Ue.AlgorithmNotSupported,`Algorithm not supported: ${e}`);return this._algorithmInstances.has(t)||this._algorithmInstances.set(t,new t),this._algorithmInstances.get(t)}getAlgorithmName({algorithm:e,key:t}){let n=t?.alg??e,i=t?.crv;for(let a of Object.keys(G6)){let s=G6[a].names;if(n&&s.includes(n))return a;if(i&&s.includes(i))return a}throw new qe(Ue.AlgorithmNotSupported,`Algorithm not supported based on provided input: alg=${n}, crv=${i}. Please check the documentation for the list of supported algorithms.`)}};g();Qo();bn();g();st();Qo();g();var _b={protocol:"https://identity.foundation/protocols/web5/identity-store",published:!1,types:{portableDid:{schema:"https://identity.foundation/schemas/web5/portable-did",dataFormats:["application/json"]},identityMetadata:{schema:"https://identity.foundation/schemas/web5/identity-metadata",dataFormats:["application/json"]}},structure:{portableDid:{},identityMetadata:{}}},La={protocol:"https://identity.foundation/protocols/key-delivery",published:!1,types:{contextKey:{dataFormats:["application/json"]}},structure:{contextKey:{$actions:[{who:"recipient",of:"contextKey",can:["read"]}],$tags:{$requiredTags:["protocol","contextId"],$allowUndefinedTags:!1,protocol:{type:"string"},contextId:{type:"string"}}}}},H6={protocol:"https://identity.foundation/protocols/web5/jwk-store",published:!1,types:{privateJwk:{schema:"https://identity.foundation/schemas/web5/private-jwk",dataFormats:["application/json"],encryptionRequired:!0}},structure:{privateJwk:{}}};g();bn();var Ii="^",rS=class extends ed{constructor(){super(),this._predefinedKeys=new Map,this._keyGenerator=this._predefinedKeys.keys()}async addPredefinedKeys({privateKeys:e}){let t={};for(let n of e){n.kid??=await yt({jwk:n});let i=await this.getKeyUri({key:n});t[i]=n}this._predefinedKeys=new Map(Object.entries(t)),this._keyGenerator=this._predefinedKeys.keys()}async exportKey({keyUri:e}){let t=this._predefinedKeys.get(e);if(!t)throw new Error(`DeterministicKeyGenerator.exportKey: Key not found: ${e}`);return t}async generateKey(e){let{value:t,done:n}=this._keyGenerator.next();if(n)throw new Error("Ran out of predefined keys");return t}async getPublicKey({keyUri:e}){let t=this._predefinedKeys.get(e);if(!t)throw new Error(`DeterministicKeyGenerator.getPublicKey: Key not found: ${e}`);let{d:n,...i}=t;return i}async sign({keyUri:e,data:t}){let n=this._predefinedKeys.get(e);if(!n)throw new Error(`DeterministicKeyGenerator.sign: Key not found: ${e}`);return await Kn.sign({data:t,key:n})}};async function Ud({agent:r,tenant:e,didUri:t}){if(e)return e;if(r.agentDid)return r.agentDid.uri;if(!t)throw new Error("Failed to determine tenant DID: 'agent.agentDid', 'tenant', and 'didUri' are undefined");return t}g();var Ab=An(iS(),1);st();Zn();var Kf=class{constructor(){this.name="DwnDataStore";this._cache=new Pi.default({ttl:(0,Ab.default)("15 minutes"),max:100});this._index=new Pi.default({ttl:(0,Ab.default)("21 days"),max:1e3});this._protocolInitializedCache=new Pi.default({ttl:(0,Ab.default)("1 hour"),max:1e3});this._tenantEncryptionActive=new Pi.default({ttl:(0,Ab.default)("1 hour"),max:1e3});this._recordProperties={dataFormat:"application/json",protocol:"",protocolPath:""}}async delete({id:e,agent:t,tenant:n}){let i=await Ud({agent:t,tenant:n,didUri:e}),a=await this.lookupRecordId({id:e,tenantDid:i,agent:t});if(!a)return!1;let{reply:{status:s}}=await t.dwn.processRequest({author:i,target:i,messageType:De.RecordsDelete,messageParams:{recordId:a}});if(s.code===202)return this._index.delete(`${i}${Ii}${e}`),this._cache.delete(a),!0;throw new Error(`${this.name}: Failed to delete '${e}' from store: (${s.code}) ${s.detail}`)}async get({id:e,agent:t,tenant:n,useCache:i=!1}){let a=await Ud({agent:t,tenant:n,didUri:e}),s=await this.lookupRecordId({id:e,tenantDid:a,agent:t});if(s)return await this.getRecord({recordId:s,tenantDid:a,agent:t,useCache:i})}async list({agent:e,tenant:t}){let n=await Ud({tenant:t,agent:e});return await this.getAllRecords({agent:e,tenantDid:n})}async set({id:e,data:t,tenant:n,agent:i,preventDuplicates:a=!0,updateExisting:s=!1,useCache:o=!1}){let c=await Ud({agent:i,tenant:n,didUri:e});await this.initialize({tenant:c,agent:i});let l={...this._recordProperties};if(s){let h=await this.getExistingRecordEntry({id:e,tenantDid:c,agent:i});if(!h)throw new Error(`${this.name}: Update failed due to missing entry for: ${e}`);l.recordId=h.recordsWrite.recordId,l.dateCreated=h.recordsWrite.descriptor.dateCreated}else if(a&&await this.lookupRecordId({id:e,tenantDid:c,agent:i}))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${e}`);let d=fe.object(t).toUint8Array(),u=this.isEncryptionActive(c),{message:f,reply:{status:p}}=await i.dwn.processRequest({author:c,target:c,messageType:De.RecordsWrite,messageParams:{...this._recordProperties,...l},dataStream:new Blob([d],{type:"application/json"}),...u?{encryption:!0}:{}});if(!(f&&p.code===202))throw new Error(`${this.name}: Failed to write data to store for ${e}: ${p.detail}`);this._index.set(`${c}${Ii}${e}`,f.recordId),o&&this._cache.set(f.recordId,t)}async initialize({tenant:e,agent:t}){let n=await Ud({agent:t,tenant:e});if(this._protocolInitializedCache.has(n)&&(!this.encryptionRequired||this._tenantEncryptionActive.has(n)))return;let{reply:{status:i,entries:a}}=await t.dwn.processRequest({author:n,target:n,messageType:De.ProtocolsQuery,messageParams:{filter:{protocol:this._recordProtocolDefinition.protocol}}});if(i.code!==200)throw new Error(`Failed to query for protocols: ${i.code} - ${i.detail}`);let s=!1;if(a?.length===0)s=(await this.installProtocol(n,t)).encryptionActive;else if(this.encryptionRequired){let o=a[0].descriptor?.definition,c=Object.keys(o?.structure??{})[0];s=!!(c&&o?.structure[c]?.$encryption)}this._tenantEncryptionActive.set(n,s),this._protocolInitializedCache.set(n,!0)}get encryptionRequired(){return this._encryptionRequired===void 0&&(this._encryptionRequired=Object.values(this._recordProtocolDefinition.types).some(e=>e.encryptionRequired===!0)),this._encryptionRequired}isEncryptionActive(e){return this._tenantEncryptionActive.get(e)===!0}async getAllRecords(e){throw new Error("Not implemented: Classes extending DwnDataStore must implement getAllRecords()")}async getRecord({recordId:e,tenantDid:t,agent:n,useCache:i}){if(i){let c=this._cache.get(e);if(c)return c}let a=this.encryptionRequired||this.isEncryptionActive(t),{reply:s}=await n.dwn.processRequest({author:t,target:t,messageType:De.RecordsRead,messageParams:{filter:{recordId:e}},...a?{encryption:!0}:{}});if(!s.entry?.data)throw new Error(`${this.name}: Failed to read data from DWN for: ${e}`);let o=await Mm.consumeToJson({readableStream:s.entry.data});return i&&this._cache.set(e,o),o}async installProtocol(e,t){let n=this._recordProtocolDefinition,i=!1;if(this.encryptionRequired){let s=await t.dwn.getEncryptionKeyDeriver(e);n=await Sd.deriveAndInjectPublicEncryptionKeys(n,s),i=!0}let{reply:{status:a}}=await t.dwn.processRequest({author:e,target:e,messageType:De.ProtocolsConfigure,messageParams:{definition:n}});if(a.code!==202)throw new Error(`Failed to install protocol: ${a.code} - ${a.detail}`);return{encryptionActive:i}}async lookupRecordId({id:e,tenantDid:t,agent:n}){let i=this._index.get(`${t}${Ii}${e}`,{updateAgeOnGet:!0});return i||(await this.getAllRecords({agent:n,tenantDid:t}),i=this._index.get(`${t}${Ii}${e}`)),i}async getExistingRecordEntry({id:e,tenantDid:t,agent:n}){let i=await this.lookupRecordId({id:e,tenantDid:t,agent:n});if(i){let{reply:a}=await n.dwn.processRequest({author:t,target:t,messageType:De.RecordsRead,messageParams:{filter:{recordId:i}}});return a.entry}}},Uf=class{constructor(){this.name="InMemoryDataStore";this.store=new Map}async delete({id:e,agent:t,tenant:n}){let i=await Ud({agent:t,tenant:n,didUri:e});return this.store.has(`${i}${Ii}${e}`)?(this.store.delete(`${i}${Ii}${e}`),!0):!1}async get({id:e,agent:t,tenant:n}){let i=await Ud({agent:t,tenant:n,didUri:e});return this.store.get(`${i}${Ii}${e}`)}async list({agent:e,tenant:t}){let n=await Ud({tenant:t,agent:e}),i=[];for(let[a,s]of this.store.entries())a.startsWith(`${n}${Ii}`)&&i.push(s);return i}async set({id:e,data:t,tenant:n,agent:i,preventDuplicates:a,updateExisting:s}){let o=await Ud({agent:i,tenant:n,didUri:e});if(s){if(!this.store.has(`${o}${Ii}${e}`))throw new Error(`${this.name}: Update failed due to missing entry for: ${e}`)}else if(a&&this.store.has(`${o}${Ii}${e}`))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${e}`);let c=structuredClone(t);this.store.set(`${o}${Ii}${e}`,c)}};var bg=class extends Kf{constructor(){super(...arguments);this.name="DwnDidStore";this._recordProtocolDefinition=_b;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"portableDid",schema:this._recordProtocolDefinition.types.portableDid.schema}}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async list(t){return await super.list(t)}async set(t){return await super.set(t)}async getAllRecords({agent:t,tenantDid:n}){this._index.clear();let{reply:i}=await t.dwn.processRequest({author:n,target:n,messageType:De.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let s of i.entries??[]){if(!s.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);let o=fe.base64Url(s.encodedData).toObject();if(_h(o)){let c=`${n}${Ii}${o.uri}`;this._index.set(c,s.recordId),this._cache.set(s.recordId,o),a.push(o)}}return a}},Pg=class extends Uf{constructor(){super(...arguments);this.name="InMemoryDidStore"}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async list(t){return await super.list(t)}async set(t){return await super.set(t)}};var vge=(t=>(t.Create="Create",t.Resolve="Resolve",t))(vge||{});function vH(r,e){return r.messageType===e}var Oh=class extends ag{constructor({agent:t,didMethods:n,resolverCache:i,store:a}){if(!n)throw new TypeError("AgentDidApi: Required parameter missing: 'didMethods'");super({didResolvers:n,cache:i??new Mf({agent:t,location:"DATA/AGENT/DID_CACHE"})});this._didMethods=new Map;this._agent=t,this._store=a??new Pg;for(let s of n)this._didMethods.set(s.methodName,s)}get agent(){if(this._agent===void 0)throw new Error("AgentDidApi: Unable to determine agent execution context.");return this._agent}set agent(t){this._agent=t,"agent"in this.cache&&(this.cache.agent=t)}async create({method:t,tenant:n,options:i,store:a}){let o=await this.getMethod(t).create({keyManager:this.agent.keyManager,options:i});if(await this.cache.set(o.uri,{didDocument:o.document,didResolutionMetadata:{},didDocumentMetadata:o.metadata}),a??!0){let{uri:c,document:l,metadata:d}=o,u={uri:c,document:l,metadata:d};await this._store.set({id:u.uri,data:u,agent:this.agent,tenant:n??u.uri,preventDuplicates:!1,useCache:!0})}return o}async export({didUri:t,tenant:n}){let i=await this.get({didUri:t,tenant:n});if(!i)throw new Error(`AgentDidApi: Failed to export due to DID not found: ${t}`);return await i.export()}async get({didUri:t,tenant:n}){let i=await this._store.get({id:t,agent:this.agent,tenant:n,useCache:!0});return i?await xs.import({portableDid:i,keyManager:this.agent.keyManager}):void 0}async getSigningMethod({didUri:t,methodId:n}){let i=Vn.parse(t);if(!i)throw new Error(`Invalid DID URI: ${t}`);let a=this.getMethod(i.method),{didDocument:s,didResolutionMetadata:o}=await this.resolve(t);if(!s)throw new Error(`DID resolution failed for '${t}': ${JSON.stringify(o)}`);return await a.getSigningMethod({didDocument:s,methodId:n})}async update({tenant:t,portableDid:n,publish:i=!0}){let a=await this.get({didUri:n.uri,tenant:t??n.uri});if(!a)throw new Error(`AgentDidApi: Could not update, DID not found: ${n.uri}`);if(sv(n.document)===sv(a.document))throw new Error("AgentDidApi: No changes detected, update aborted");let s=await xs.import({keyManager:this.agent.keyManager,portableDid:n}),{uri:o,document:c,metadata:l}=s,d={uri:o,document:c,metadata:l};return await this.cache.set(o,{didDocument:c,didResolutionMetadata:{},didDocumentMetadata:l}),await this._store.set({id:o,data:d,agent:this.agent,tenant:t??o,updateExisting:!0,useCache:!0}),i&&Vn.parse(o)?.method==="dht"&&await wo.publish({did:s}),s}async import({portableDid:t,tenant:n}){let i=await xs.import({keyManager:this.agent.keyManager,portableDid:t}),{uri:a,document:s,metadata:o}=i,c={uri:a,document:s,metadata:o};return await this.cache.set(a,{didDocument:s,didResolutionMetadata:{},didDocumentMetadata:o}),await this._store.set({id:c.uri,data:c,agent:this.agent,tenant:n??c.uri,preventDuplicates:!0,useCache:!0}),i}async delete({didUri:t,tenant:n,deleteKey:i=!0}){let a=await this._store.get({id:t,agent:this.agent,tenant:n,useCache:!1});if(!a)throw new Error("AgentDidApi: Could not delete, DID not found");await this.cache.delete(t),await this._store.delete({id:t,agent:this.agent,tenant:n}),i&&await this.deleteKeys({portableDid:a})}async deleteKeys({portableDid:t}){for(let n of t.document.verificationMethod||[]){if(!n.publicKeyJwk)continue;let i=await this.agent.keyManager.getKeyUri({key:n.publicKeyJwk});await this.agent.keyManager.deleteKey({keyUri:i})}}async processRequest(t){if(vH(t,"Create"))try{let n=await this.create({...t.messageParams});return{result:{uri:n.uri,document:n.document,metadata:n.metadata},ok:!0,status:{code:201,message:"Created"}}}catch(n){return{ok:!1,status:{code:500,message:n.message??"Unknown error occurred"}}}if(vH(t,"Resolve")){let{didUri:n,options:i}=t.messageParams;return{result:await this.resolve(n,i),ok:!0,status:{code:200,message:"OK"}}}throw new Error(`AgentDidApi: Unsupported request type: ${t.messageType}`)}getMethod(t){let n=this._didMethods.get(t);if(n===void 0)throw new Error(`DID Method not supported: ${t}`);return n}};g();Zn();st();bn();Qo();g();Zn();st();var Ss=class r{constructor({agent:e}={}){this._cachedPermissions=new Pi.default({ttl:60*1e3});this._agent=e}get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}async getPermissionForRequest({connectedDid:e,delegateDid:t,delegate:n,messageType:i,protocol:a,cached:s=!1}){let o=[e,t,i,a].join("~"),c=s?this._cachedPermissions.get(o):void 0;if(c)return c;let l=await this.fetchGrants({author:t,target:t,grantor:e,grantee:t}),d=await r.matchGrantFromArray(e,t,{messageType:i,protocol:a},l,n);if(!d)throw new Error(`CachedPermissions: No permissions found for ${i}: ${a}`);return this._cachedPermissions.set(o,d),d}async fetchGrants({author:e,target:t,grantee:n,grantor:i,protocol:a,remote:s=!1,checkRevoked:o=!0}){let c=a?{protocol:a}:void 0,l={author:e,target:t,messageType:De.RecordsQuery,messageParams:{filter:{author:i,recipient:n,protocol:et.uri,protocolPath:et.grantPath,tags:c}}},{reply:d}=s?await this.agent.sendDwnRequest(l):await this.agent.processDwnRequest(l);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${d.status.detail}`);let u=o?await this.fetchRevokedGrantIds({author:e,target:t,grantor:i,remote:s,tags:c}):new Set,f=[];for(let p of d.entries){if(u.has(p.recordId))continue;let h=kr.parse(p);f.push({grant:h,message:p})}return f}async fetchRevokedGrantIds({author:e,target:t,grantor:n,remote:i,tags:a}){let s={author:e,target:t,messageType:De.RecordsQuery,messageParams:{filter:{author:n,protocol:et.uri,protocolPath:et.revocationPath,tags:a}}},{reply:o}=i?await this.agent.sendDwnRequest(s):await this.agent.processDwnRequest(s);if(o.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${o.status.detail}`);let c=new Set;for(let l of o.entries)l.descriptor.parentId!==void 0&&c.add(l.descriptor.parentId);return c}async fetchRequests({author:e,target:t,protocol:n,remote:i=!1}){let a=n?{protocol:n}:void 0,s={author:e,target:t,messageType:De.RecordsQuery,messageParams:{filter:{protocol:et.uri,protocolPath:et.requestPath,tags:a}}},{reply:o}=i?await this.agent.sendDwnRequest(s):await this.agent.processDwnRequest(s);if(o.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${o.status.detail}`);let c=[];for(let l of o.entries){let d=gd.parse(l);c.push({request:d,message:l})}return c}async isGrantRevoked({author:e,target:t,grantRecordId:n,remote:i=!1}){let a={author:e,target:t,messageType:De.RecordsRead,messageParams:{filter:{parentId:n,protocol:et.uri,protocolPath:et.revocationPath}}},{reply:s}=i?await this.agent.sendDwnRequest(a):await this.agent.processDwnRequest(a);if(s.status.code===404)return!1;if(s.status.code===200)return!0;throw new Error(`PermissionsApi: Failed to check if grant is revoked: ${s.status.detail}`)}async createGrant(e){let{author:t,store:n=!1,delegated:i=!1,...a}=e,s;et.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope};a.delegateKeyDelivery&&(o.delegateKeyDelivery=a.delegateKeyDelivery);let c=fe.object(o).toUint8Array(),l={recipient:a.grantedTo,protocol:et.uri,protocolPath:et.grantPath,dataFormat:"application/json",tags:s},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:t,target:t,messageType:De.RecordsWrite,messageParams:l,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${d.status.detail}`);let f={...u,encodedData:fe.uint8Array(c).toBase64Url()};return{grant:kr.parse(f),message:f}}async createRequest(e){let{author:t,store:n=!1,delegated:i=!1,...a}=e,s;et.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={description:a.description,delegated:i,scope:a.scope},c=fe.object(o).toUint8Array(),l={protocol:et.uri,protocolPath:et.requestPath,dataFormat:"application/json",tags:s},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:t,target:t,messageType:De.RecordsWrite,messageParams:l,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${d.status.detail}`);let f={...u,encodedData:fe.uint8Array(c).toBase64Url()};return{request:gd.parse(f),message:f}}async createRevocation(e){let{author:t,store:n=!1,grant:i,description:a}=e,s={description:a},o=fe.object(s).toUint8Array(),c;et.hasProtocolScope(i.scope)&&(c={protocol:i.scope.protocol});let l={parentContextId:i.id,protocol:et.uri,protocolPath:et.revocationPath,dataFormat:"application/json",tags:c};e.permissionGrantId&&(l.permissionGrantId=e.permissionGrantId);let{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:t,target:t,messageType:De.RecordsWrite,messageParams:l,granteeDid:e.granteeDid,dataStream:new Blob([o])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${d.status.detail}`);return{message:{...u,encodedData:fe.uint8Array(o).toBase64Url()}}}async clear(){this._cachedPermissions.clear()}static async matchGrantFromArray(e,t,n,i,a=!1){let s;for(let o of i){let{grant:c,message:l}=o;if(a===!0&&c.delegated!==!0)continue;let{messageType:d,protocol:u,protocolPath:f,contextId:p}=n;if(this.matchScopeFromGrant(e,t,d,c,u,f,p)){if(c.scope.interface+c.scope.method===d)return{grant:c,message:l};s||(s={grant:c,message:l})}}return s}static matchScopeFromGrant(e,t,n,i,a,s,o){if(i.grantee!==t||i.grantor!==e)return!1;let c=i.scope,l=c.interface+c.method;if(c.interface==="Messages"?c.method==="Read"&&(n===De.MessagesRead||n===De.MessagesSync||n===De.MessagesSubscribe):l===n)if(V6(n)){let u=c;if(u.protocol!==a)return!1;if(this.isUnrestrictedProtocolScope(u)||u.protocolPath!==void 0&&u.protocolPath===s||u.contextId!==void 0&&o?.startsWith(u.contextId))return!0}else{let u=c;return u.protocol===void 0?!0:u.protocol!==a?!1:this.isUnrestrictedProtocolScope(u)}return!1}static isUnrestrictedProtocolScope(e){return e.contextId===void 0&&e.protocolPath===void 0}};g();g();var bge="@enbox/dwn-server";function sS(r){return r.endsWith("/")?r.slice(0,-1):r}var jh=class{constructor(e,t=1e4,n){this._rpcClient=e;this._cacheTtlMs=t;this._discoveryFile=n;this._cacheExpiry=0}async getEndpoint(){let e=Date.now();if(e<this._cacheExpiry)return this._cachedEndpoint;let t=await this._tryDiscoveryFile();if(t!==void 0)return this._setCacheEntry(t,e),t;this._setCacheEntry(void 0,e)}async setCachedEndpoint(e){let t=sS(e),n=await this._validateEndpoint(t);return n&&this._setCacheEntry(t,Date.now()),n}clearCache(){this._cachedEndpoint=void 0,this._cacheExpiry=0}async _tryDiscoveryFile(){if(this._discoveryFile)try{let e=await this._discoveryFile.read();return e&&await this._validateEndpoint(e.endpoint)?e.endpoint:void 0}catch{return}}async _validateEndpoint(e){try{return(await this._rpcClient.getServerInfo(e)).server===bge}catch{return!1}}_setCacheEntry(e,t){this._cachedEndpoint=e,this._cacheExpiry=t+this._cacheTtlMs}};function Pge(){try{let r=_S,e=r("node:fs/promises"),t=r("node:path"),n=r("node:os");return{async readFile(i){try{return await e.readFile(i,"utf-8")}catch{return null}},async writeFile(i,a){await e.mkdir(t.dirname(i),{recursive:!0}),await e.writeFile(i,a,{encoding:"utf-8",mode:384})},async removeFile(i){try{await e.unlink(i)}catch{}},isProcessAlive(i){try{return process.kill(i,0),!0}catch{return!1}},homedir(){return n.homedir()}}}catch{return}}var xge=".enbox",Ege="dwn.json",oS=class{constructor(e,t){let n=e??Pge();if(!n)throw new Error("DwnDiscoveryFile: No filesystem adapter available. Provide a DiscoveryFileFs implementation or run in Node.js / Bun.");if(this._fs=n,t)this._filePath=t;else{let a=_S("node:path");this._filePath=a.join(n.homedir(),xge,Ege)}}get path(){return this._filePath}async read(){let e=await this._fs.readFile(this._filePath);if(e===null)return;let t;try{t=JSON.parse(e)}catch{await this._fs.removeFile(this._filePath);return}if(!Sge(t)){await this._fs.removeFile(this._filePath);return}if(!this._fs.isProcessAlive(t.pid)){await this._fs.removeFile(this._filePath);return}let n={endpoint:sS(t.endpoint),pid:t.pid};return t.capabilities!==void 0&&(n.capabilities=t.capabilities),n}async write(e){let t={endpoint:sS(e.endpoint),pid:e.pid};e.capabilities!==void 0&&e.capabilities.length>0&&(t.capabilities=e.capabilities);let n=JSON.stringify(t,null,2);await this._fs.writeFile(this._filePath,n)}async remove(){await this._fs.removeFile(this._filePath)}};function Sge(r){if(typeof r!="object"||r===null)return!1;let e=r;return!(typeof e.endpoint!="string"||e.endpoint.length===0||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||e.capabilities!==void 0&&(!Array.isArray(e.capabilities)||!e.capabilities.every(t=>typeof t=="string")))}g();Zn();function qa(r,e){return r.messageType===e}function kge(r,e){return e.descriptor.interface+e.descriptor.method===r}function V6(r){return r===De.RecordsDelete||r===De.RecordsQuery||r===De.RecordsRead||r===De.RecordsSubscribe||r===De.RecordsWrite}function Mh(r){return r.interface===ve.Records}function _ge(r){return r.interface===ve.Messages}g();Zn();bn();function aS(r){return r===ci.XC20P?24:12}function Kh(r,e,t,n,i){return{initializationVector:e,key:r,keyEncryptionInputs:[{publicKeyId:t,publicKey:n,derivationScheme:i}]}}async function cS(r,e,t,n=ci.A256GCM){let{ciphertextStream:i,tag:a}=await xi.aeadEncryptStream(n,e,t,zt.fromBytes(r)),s=await zt.toBytes(i),o=zt.fromBytes(s),c=await ur.computeDagPbCidFromStream(o);return{encryptedBytes:s,dataCid:c,dataSize:s.length,authenticationTag:a}}async function za(r,e){let{didDocument:t,didResolutionMetadata:n}=await r.did.resolve(e);if(!t)throw new Error(`AgentDwnApi: Failed to resolve DID '${e}': ${JSON.stringify(n)}`);let i=t.keyAgreement;if(!i||i.length===0)throw new Error(`AgentDwnApi: DID '${e}' does not have a keyAgreement verification method. Create the identity with an X25519 key with keyAgreement purpose to use protocol encryption.`);let a=i[0],s;if(typeof a=="string"){let l=a.includes("#")?a.split("#").pop():a;s=t.verificationMethod?.find(d=>d.id.endsWith(`#${l}`))}else s=a;if(!s?.publicKeyJwk)throw new Error(`AgentDwnApi: keyAgreement verification method for '${e}' does not contain a public key in JWK format.`);let o=s.publicKeyJwk;if(o.crv==="Ed25519")o=await Kn.convertPublicKeyToX25519({publicKey:o});else if(o.crv!=="X25519")throw new Error(`AgentDwnApi: keyAgreement key for '${e}' uses curve '${o.crv}', but DWN encryption requires 'X25519' (or 'Ed25519' which is auto-converted).`);let c=await r.keyManager.getKeyUri({key:o});return{keyId:s.id,keyUri:c,publicKeyJwk:o}}async function PH(r,e,t,n,i){let{keyId:a,keyUri:s}=await za(r,e),o=Ae.constructKeyDerivationPathUsingProtocolContextScheme(t),c=await r.keyManager.derivePublicKey({keyUri:s,derivationPath:o});return{encryptionInput:Kh(n,i,a,c,xt.ProtocolContext),keyId:a,keyUri:s,contextDerivationPath:o}}function xH(r,e,t,n){let i=r.keyManager;return{rootKeyId:e,derivationScheme:n,decrypt:async(a,s)=>i.jweKeyUnwrap({keyUri:t,derivationPath:a,encryptedKey:s.encryptedKey,ephemeralPublicKey:s.ephemeralPublicKey})}}async function Ib(r,e){let{keyId:t,keyUri:n}=await za(r,e),i=r.keyManager;return{rootKeyId:t,derivationScheme:xt.ProtocolPath,derivePublicKey:async a=>i.derivePublicKey({keyUri:n,derivationPath:a})}}async function W6(r,e){let{keyId:t,keyUri:n}=await za(r,e);return xH(r,t,n,xt.ProtocolPath)}function Tb(r){return{rootKeyId:r.rootKeyId,derivationScheme:r.derivationScheme,decrypt:async(e,t)=>{let n=await Ae.derivePrivateKey(r,e),i=await kt.bytesToPrivateKey({privateKeyBytes:n});return xi.ecdhEsUnwrapKey(i,t.ephemeralPublicKey,t.encryptedKey)}}}function Age(r){return{rootKeyId:r.rootKeyId,derivationScheme:r.derivationScheme,decrypt:async(e,t)=>{let n=r.derivationPath??[];if(n.length!==e.length||!n.every((s,o)=>s===e[o]))throw new Error(`Delegate decryption key is out of scope for this protocol path. Key path: [${n.join(", ")}], record path: [${e.join(", ")}].`);let i=await Ae.derivePrivateKey(r,e),a=await kt.bytesToPrivateKey({privateKeyBytes:i});return xi.ecdhEsUnwrapKey(a,t.ephemeralPublicKey,t.encryptedKey)}}}async function bH(r,e,t,n,i,a,s,o,c){let{encryption:l}=t;if(!l?.recipients.some(E=>E.header.derivationScheme===xt.ProtocolContext)||!t.contextId){if(s&&o){let E=t.descriptor.protocol,_=t.descriptor.protocolPath;if(E){let A=`ddk~${o}`,D=s.get(A);if(D){let M=D.filter(z=>z.protocol===E);if(_){let z=M.find(L=>L.scope.kind==="protocolPath"&&L.scope.protocolPath===_);if(z)return Age(z.derivedPrivateKey)}let C=M.find(z=>z.scope.kind==="protocol");if(C)return Tb(C.derivedPrivateKey)}}}return W6(r,e)}let u=l.recipients.find(E=>E.header.derivationScheme===xt.ProtocolContext),f=t.contextId.split("/")[0];if(c&&o){let E=t.descriptor.protocol;if(E){let _=`dctx~${o}~${E}~${f}`,A=c.get(_);if(A)return Tb(A);try{let D=await a({ownerDid:e,requesterDid:o,sourceProtocol:E,sourceContextId:f});if(D)return c.set(_,D),Tb(D)}catch{}}throw new Error(`AgentDwnApi: Delegate '${o}' does not have a context key for context '${f}'. No delivered contextKey record was found via the key-delivery protocol. The delegate may need to reconnect or wait for sync.`)}let{keyId:p,keyUri:h}=await za(r,e);if(u.header.kid===p)return xH(r,p,h,xt.ProtocolContext);let m=`ctx~${e}~${f}`,y=i.get(m);if(y)return Tb(y);let v=t.descriptor.protocol,w=await a({ownerDid:e,requesterDid:e,sourceProtocol:v,sourceContextId:f});if(!w){let{Jws:E}=await Promise.resolve().then(()=>(Zn(),uH)),_=n??E.getSignerDid(t.authorization.signature.signatures[0]);w=await a({ownerDid:_,requesterDid:e,sourceProtocol:v,sourceContextId:f})}if(!w)throw new Error(`AgentDwnApi: Failed to decrypt record '${t.recordId}'. Record uses context-derived encryption but no contextKey record could be found via the key-delivery protocol.`);return i.set(m,w),Tb(w)}async function EH(r,e,t,n,i,a,s){if(!("encryption"in r)||!r.encryption)return;let o=r,c=o.granteeDid;if(qa(o,De.RecordsRead)){let l=e;if(l.status.code===200&&l.entry?.recordsWrite?.encryption&&l.entry?.data){let d=await bH(t,o.author,l.entry.recordsWrite,o.target,n,i,a,c,s);try{l.entry.data=await Ae.decrypt(l.entry.recordsWrite,d,l.entry.data)}catch(u){throw new Error(`AgentDwnApi: Failed to decrypt record '${l.entry.recordsWrite.recordId}'. Original error: ${u.message}`)}}}if(qa(o,De.RecordsQuery)){let l=e;if(l.status.code===200&&l.entries){for(let d of l.entries)if(d.encryption&&d.encodedData){let u=await bH(t,o.author,d,o.target,n,i,a,c,s);try{let f=Ie.base64UrlToBytes(d.encodedData),p=zt.fromBytes(f),h=await Ae.decrypt(d,u,p),m=await zt.toBytes(h);d.encodedData=Ie.bytesToBase64Url(m)}catch(f){throw new Error(`AgentDwnApi: Failed to decrypt record '${d.recordId}'. Original error: ${f.message}`)}}}}}g();Zn();async function SH(r,e,t,n,i,a){if(i.get(e))return;let s=La.protocol;if(!await n(e,s)){let c=await Ib(r,e),l=await Sd.deriveAndInjectPublicEncryptionKeys(La,c),{reply:{status:d}}=await t({author:e,target:e,messageType:De.ProtocolsConfigure,messageParams:{definition:l}});if(d.code!==202)throw new Error(`AgentDwnApi: Failed to install key delivery protocol: ${d.code} - ${d.detail}`);a.delete(`${e}~${s}`)}i.set(e,!0)}async function kH(r,e,t,n,i,a){let{tenantDid:s,recipientDid:o,contextKeyData:c,sourceProtocol:l,sourceContextId:d,recipientKeyDeliveryPublicKey:u}=e;await n(s);let f=La.protocol,p=new TextEncoder().encode(JSON.stringify(c)),h={protocol:f,protocolPath:"contextKey",dataFormat:"application/json",recipient:o,tags:{protocol:l,contextId:d}},m,y;if(u){let v=ci.A256GCM,w=crypto.getRandomValues(new Uint8Array(32)),E=crypto.getRandomValues(new Uint8Array(aS(v))),{encryptedBytes:_,dataCid:A,dataSize:D,authenticationTag:M}=await cS(p,w,E,v),C={...Kh(w,E,u.rootKeyId,u.publicKeyJwk,xt.ProtocolPath),authenticationTag:M};({message:m,reply:{status:y}}=await t({author:s,target:s,messageType:De.RecordsWrite,messageParams:{...h,dataCid:A,dataSize:D,encryptionInput:C},dataStream:new Blob([_])}))}else({message:m,reply:{status:y}}=await t({author:s,target:s,messageType:De.RecordsWrite,messageParams:h,dataStream:new Blob([p],{type:"application/json"}),encryption:!0}));if(!(m&&y.code===202))throw new Error(`AgentDwnApi: Failed to write contextKey record for ${o}: ${y.code} - ${y.detail}`);return a(i(s,m).catch(v=>{console.warn(`AgentDwnApi: Eager send of contextKey record '${m.recordId}' to remote DWN failed: ${v.message}. Sync will deliver it later.`)})),m.recordId}async function _H(r,e,t,n,i,a){let s;try{s=await a(e)}catch{return}if(s.length===0)return;let{data:o}=await n({author:e,messageType:De.RecordsWrite,messageCid:await ye.getCid(t)});await i({targetDid:e,dwnEndpointUrls:s,message:t,data:o})}async function Tge(r,e,t,n,i){try{let{reply:a}=await r({author:e,target:t,messageType:De.RecordsQuery,messageParams:{filter:n}});if(a.status.code!==200||!a.entries?.length)return;let s=a.entries[0].recordId,{reply:o}=await r({author:e,target:t,messageType:De.RecordsRead,messageParams:{filter:{recordId:s}},encryption:!0}),c=o;return c.entry?.data?i(await zt.toBytes(c.entry.data)):void 0}catch{return}}async function AH(r,e,t){let{ownerDid:n,requesterDid:i,sourceProtocol:a,sourceContextId:s}=e,o=La.protocol,c=n===i,l={protocol:o,protocolPath:"contextKey",recipient:i,tags:{protocol:a,contextId:s}},d=u=>JSON.parse(new TextDecoder().decode(u));if(c){let{reply:u}=await t({author:i,target:n,messageType:De.RecordsQuery,messageParams:{filter:l}});if(u.status.code!==200||!u.entries?.length)return;let f=u.entries[0].recordId,{reply:p}=await t({author:i,target:n,messageType:De.RecordsRead,messageParams:{filter:{recordId:f}},encryption:!0}),h=p;return h.entry?.data?d(await zt.toBytes(h.entry.data)):void 0}return Tge(t,i,n,l,d)}g();Zn();async function TH(r,e,t,n,i,a,s){let o=`${r}~${e}`,c=i.get(o);if(c)return c;let d=await n(a??r),u=await Ch[De.ProtocolsQuery].create({filter:{protocol:e},signer:d,...s?{permissionGrantId:s}:{}}),f=await t.processMessage(r,u.message);if(f.status.code!==200||!f.entries?.length)return;let p=f.entries[0].descriptor.definition;return i.set(o,p),p}async function IH(r,e,t,n,i){let a=`remote~${r}~${e}`,s=i.get(a);if(s)return s;let o=await Ch[De.ProtocolsQuery].create({filter:{protocol:e}}),c=await n({targetDid:r,dwnEndpointUrls:await t(r),message:o.message});if(c.status.code!==200||!c.entries?.length)throw new Error(`AgentDwnApi: Failed to fetch protocol '${e}' from '${r}'. The recipient may not have the protocol installed.`);let l=c.entries[0].descriptor.definition;return i.set(a,l),l}async function DH(r,e,t,n,i,a,s){let o=await a(n),c=await Ch[De.RecordsQuery].create({signer:o,filter:{protocol:e,contextId:t}}),l=await i(r),d=await s({targetDid:r,dwnEndpointUrls:l,message:c.message});if(!(d.status.code!==200||!d.entries?.length)){for(let u of d.entries)if(u.encryption?.recipients){let f=u.encryption.recipients.find(p=>p.header.derivationScheme===xt.ProtocolContext&&p.header.derivedPublicKey);if(f?.header.derivedPublicKey)return{rootKeyId:f.header.kid,derivedPublicKey:f.header.derivedPublicKey}}}}var Jl=class r{constructor(e){this._protocolDefinitionCache=new Pi.default({ttl:30*60*1e3});this._contextKeyCache=new Pi.default({ttl:30*60*1e3});this._contextDerivedKeyCache=new Pi.default({ttl:30*60*1e3});this._delegateDecryptionKeyCache=new Pi.default({ttl:24*60*60*1e3});this._delegateContextKeyCache=new Pi.default({ttl:24*60*60*1e3});this._delegateContextKeyCacheIndex=new Map;this._delegateMultiPartyProtocols=new Map;this._localManagedDidCache=new Pi.default({ttl:30*60*1e3});this._pendingEagerSends=new Set;this._keyDeliveryProtocolInstalledCache=new Pi.default({ttl:21*24*60*60*1e3,max:1e3});let{agent:t,localDwnStrategy:n="prefer"}=e;this._agent=t,this._dwn="dwn"in e?e.dwn:void 0,this._localDwnEndpoint="localDwnEndpoint"in e?e.localDwnEndpoint:void 0,this._localDwnStrategy=n,t&&(this._localDwnDiscovery=new jh(t.rpc,1e4,r._tryCreateDiscoveryFile()))}get isRemoteMode(){return this._dwn===void 0}get agent(){if(this._agent===void 0)throw new Error("AgentDwnApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._localDwnDiscovery=new jh(e.rpc,1e4,r._tryCreateDiscoveryFile()),this._localManagedDidCache.clear()}get localDwnStrategy(){return this._localDwnStrategy}setLocalDwnStrategy(e){this._localDwnStrategy=e}async setCachedLocalDwnEndpoint(e){return this._localDwnDiscovery??=new jh(this.agent.rpc,1e4,r._tryCreateDiscoveryFile()),this._localDwnDiscovery.setCachedEndpoint(e)}async getDwnEndpointUrlsForTarget(e){if(!await this.shouldUseLocalDwnForTarget(e))return mg(e,this.agent.did);let n=await this.getLocalDwnEndpoint();if(this._localDwnStrategy==="only"){if(!n)throw new Error("AgentDwnApi: Local DWN strategy is 'only' but no local DWN endpoint was discovered. Ensure the local DWN server is running and discoverable via the discovery file (~/.enbox/dwn.json) or dwn://connect.");return[n]}let i=[];try{i=await mg(e,this.agent.did)}catch(s){if(!n)throw s}return n?[...new Set([n,...i])]:i}async getRemoteDwnEndpointUrls(e){return mg(e,this.agent.did)}async getLocalDwnEndpoint(){return this._localDwnEndpoint?this._localDwnEndpoint:(this._localDwnDiscovery??=new jh(this.agent.rpc,1e4,r._tryCreateDiscoveryFile()),this._localDwnDiscovery.getEndpoint())}static _tryCreateDiscoveryFile(){try{return new oS}catch{return}}async shouldUseLocalDwnForTarget(e){if(this._localDwnStrategy==="off")return!1;let t=this._localManagedDidCache.get(e);if(t!==void 0)return t;if(e===this.agent.agentDid.uri)return this._localManagedDidCache.set(e,!0),!0;let n=await this.agent.identity.list(),i=new Set;for(let s of n)i.add(s.did.uri),s.metadata.connectedDid&&i.add(s.metadata.connectedDid);for(let s of i)this._localManagedDidCache.set(s,!0);let a=i.has(e);return a||this._localManagedDidCache.set(e,!1),a}get node(){if(!this._dwn)throw new Error(`AgentDwnApi: The in-process DWN instance is not available. The agent is operating in remote mode (local DWN server at '${this._localDwnEndpoint}'). Use processRequest() instead of accessing the DWN node directly.`);return this._dwn}static async createDwn({dataPath:e,dataStore:t,didResolver:n,stateIndex:i,eventLog:a,messageStore:s,tenantGate:o,resumableTaskStore:c}){return t??=new Cf({blockstoreLocation:`${e}/DWN_DATASTORE`}),n??=new ag({didResolvers:[wo,Xo],cache:new EE({location:`${e}/DID_RESOLVERCACHE`})}),i??=new jf({location:`${e}/DWN_STATEINDEX`}),s??=new $f({blockstoreLocation:`${e}/DWN_MESSAGESTORE`,indexLocation:`${e}/DWN_MESSAGEINDEX`}),c??=new Bf({location:`${e}/DWN_RESUMABLETASKSTORE`}),a??=new Of,await cg.create({dataStore:t,didResolver:n,stateIndex:i,eventLog:a,messageStore:s,tenantGate:o,resumableTaskStore:c})}async processRequest(e){let{message:t,dataStream:n}=await this.constructDwnMessage({request:e}),{subscriptionHandler:i}=e,a;if(e.store===!1)a={status:{code:202,detail:"Accepted"}};else if(this._dwn)a=await this._dwn.processMessage(e.target,t,{dataStream:n,subscriptionHandler:i});else{let s;if(n){let o=await zt.toBytes(n);s=new Blob([o])}a=await this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:[this._localDwnEndpoint],message:t,data:s,subscriptionHandler:i})}return await Promise.all([this.postWriteKeyDelivery(e,t,a),this.maybeDecryptReply(e,a)]),{reply:a,message:t,messageCid:await ye.getCid(t)}}async processRawMessage(e,t,n){if(this._dwn)return this._dwn.processMessage(e,t,{dataStream:n?.dataStream});let i;if(n?.dataStream){let a=await zt.toBytes(n.dataStream);i=new Blob([a])}return this.sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:[this._localDwnEndpoint],message:t,data:i})}async sendRequest(e){let t=await this.getDwnEndpointUrlsForTarget(e.target);if(t.length===0)throw new Error(`AgentDwnApi: DID Service is missing or malformed: ${e.target}#dwn`);let n,i,a,s;if("messageCid"in e)({message:i,data:a}=await this.getDwnMessage({author:e.author,messageCid:e.messageCid,messageType:e.messageType})),n=e.messageCid;else{if({message:i}=await this.constructDwnMessage({request:e}),e.dataStream&&!(e.dataStream instanceof Blob))throw new Error("AgentDwnApi: DataStream must be provided as a Blob");a=e.dataStream,s=e.subscriptionHandler}let o;s!==void 0&&!("messageCid"in e)&&(o=async l=>{let d=l===void 0?e.messageParams:{...e.messageParams,cursor:l},u={...e,messageParams:d},{message:f}=await this.constructDwnMessage({request:u});return f});let c=await this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:t,message:i,data:a,subscriptionHandler:s,resubscribeFactory:o});return await this.maybeDecryptReply(e,c),n??=await ye.getCid(i),{reply:c,message:i,messageCid:n}}async postWriteKeyDelivery(e,t,n){if(!qa(e,De.RecordsWrite)||!e.encryption||n.status.code!==202)return;let i=e.messageParams;if(i.protocol!==La.protocol)try{let a=await this.getProtocolDefinition(e.target,i.protocol);if(!a)return;let s=t,o=ct.getSignerDid(s.authorization.signature.signatures[0]),c=o!==e.target,l=!i.parentContextId,d=i.protocolPath.split("/")[0],u=$h(a,d),f=z6({protocolDefinition:a,protocolPath:i.protocolPath,recipient:i.recipient,tenantDid:e.target,authorDid:c?o:void 0}),p=s.contextId?.split("/")[0]||s.contextId||s.recordId,h=u&&l&&!c&&this.hasEligibleDelegatesForProtocol(i.protocol),m=u&&l&&!c;if(f.size>0||h||m){let{keyId:y,keyUri:v}=await za(this.agent,e.target),w=[xt.ProtocolContext,p],E=await this.agent.keyManager.derivePrivateKeyBytes({keyUri:v,derivationPath:w}),_=await kt.bytesToPrivateKey({privateKeyBytes:E}),A={rootKeyId:y,derivationScheme:xt.ProtocolContext,derivationPath:w,derivedPrivateKey:_};if(f.size>0){let D=s.authorization?.authorKeyDeliveryPublicKey;for(let M of f)try{let C=M===o&&D?D:void 0;await this.writeContextKeyRecord({tenantDid:e.target,recipientDid:M,contextKeyData:A,sourceProtocol:i.protocol,sourceContextId:p,recipientKeyDeliveryPublicKey:C})}catch(C){console.warn(`AgentDwnApi: Key delivery to '${M}' for context '${p}' failed: ${C.message}. The participant may not be able to decrypt records in this context.`)}}h&&this.deliverContextKeyToDelegates(i.protocol,p,A),m&&await this.deliverContextKeyToDelegatesViaDwn(e.target,i.protocol,p,A)}}catch(a){console.warn(`AgentDwnApi: Post-write participant detection failed: ${a.message}`)}}async sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:t,message:n,data:i,subscriptionHandler:a,resubscribeFactory:s}){let o=[];if(n.descriptor.method===me.Subscribe&&a===void 0)throw new Error("AgentDwnApi: Subscription handler is required for subscription requests.");for(let c of t)try{if(a!==void 0){if(!(await this.agent.rpc.getServerInfo(c)).webSocketSupport){o.push({url:c,message:"WebSocket support is not enabled on the server."});continue}let u=new URL(c);u.protocol=u.protocol==="http:"?"ws:":"wss:",c=u.toString()}return await this.agent.rpc.sendDwnRequest({dwnUrl:c,targetDid:e,message:n,data:i,subscription:a?{handler:a,resubscribeFactory:s}:void 0})}catch(l){o.push({url:c,message:l instanceof Error?l.message:"Unknown error"})}throw new Error(`Failed to send DWN RPC request: ${JSON.stringify(o)}`)}async constructDwnMessage({request:e}){if(e.granteeDid&&!this.hasGrantParams(e.messageParams))throw new Error("AgentDwnApi: Requested to sign with a permission but no grant messageParams were provided in the request");let t=e.rawMessage,n;if(qa(e,De.RecordsWrite)){let o=e.messageParams;if(e.dataStream&&!o?.data){let{dataStream:c}=e,l;if(c instanceof Blob){let[d,u]=c.stream().tee();l=d,n=u}else if(c instanceof ReadableStream){let[d,u]=c.tee();l=d,n=u}!t&&o&&(o.dataCid=await ur.computeDagPbCidFromStream(l),o.dataSize===void 0&&c instanceof Blob&&(o.dataSize=c.size))}}if(qa(e,De.ProtocolsConfigure)&&e.encryption&&!t){let o=e.messageParams,c=await Ib(this.agent,e.author);o.definition=await Sd.deriveAndInjectPublicEncryptionKeys(o.definition,c),this._protocolDefinitionCache.delete(`${e.target}~${o.definition.protocol}`)}if(qa(e,De.ProtocolsConfigure)&&!e.encryption&&!t){let o=e.messageParams?.definition;o?.protocol&&this._protocolDefinitionCache.set(`${e.target}~${o.protocol}`,o)}let i;if(qa(e,De.RecordsWrite)&&e.encryption&&!t){let o=e.messageParams;if(o?.protocol&&o.protocolPath){let c=e.target!==e.author,l;if(c?l=await this.fetchRemoteProtocolDefinition(e.target,o.protocol):l=await this.getProtocolDefinition(e.target,o.protocol,e.granteeDid),!l)throw new Error(`AgentDwnApi: Protocol '${o.protocol}' is not installed for '${e.target}'. Install the protocol before writing encrypted records.`);let d=o.protocolPath.split("/"),u=l.structure;for(let L of d)u=u[L];if(!u?.$encryption)throw new Error(`AgentDwnApi: Protocol '${o.protocol}' at path '${o.protocolPath}' does not have encryption configured. Configure the protocol with encryption: true.`);let f=o.protocolPath.split("/")[0],h=o.protocol===La.protocol?!1:$h(l,f),m=!o.parentContextId,y;if(o.data)y=o.data instanceof Uint8Array?o.data:new TextEncoder().encode(String(o.data));else if(e.dataStream instanceof Blob)y=new Uint8Array(await e.dataStream.arrayBuffer());else if(e.dataStream instanceof ReadableStream)y=await zt.toBytes(e.dataStream);else throw new Error("AgentDwnApi: Data must be provided for encrypted records.");let v=ci.A256GCM,w=crypto.getRandomValues(new Uint8Array(32)),E=crypto.getRandomValues(new Uint8Array(aS(v))),_,A=()=>Kh(w,E,u.$encryption.rootKeyId,u.$encryption.publicKeyJwk,xt.ProtocolPath);if(c&&h&&m)_=A();else if(c&&h&&!m){let L=o.parentContextId.split("/")[0]||o.parentContextId,B=await this.extractDerivedPublicKey(e.target,o.protocol,L,e.author);B?_=Kh(w,E,B.rootKeyId,B.derivedPublicKey,xt.ProtocolContext):_=A()}else if(c)_=A();else if(h&&!m){let L=o.parentContextId.split("/")[0]||o.parentContextId,B=this._contextKeyCache.get(L);if(!B){let{keyId:ee,keyUri:R}=await za(this.agent,e.author),$=Ae.constructKeyDerivationPathUsingProtocolContextScheme(L);B={keyId:ee,keyUri:R,contextDerivationPath:$},this._contextKeyCache.set(L,B)}let W=await this.agent.keyManager.derivePublicKey({keyUri:B.keyUri,derivationPath:B.contextDerivationPath});_=Kh(w,E,B.keyId,W,xt.ProtocolContext)}else h&&m?_=void 0:_=A();let{encryptedBytes:D,dataCid:M,dataSize:C,authenticationTag:z}=await cS(y,w,E,v);if(o.dataCid=M,o.dataSize=C,delete o.data,n=zt.fromBytes(D),e.dataStream=void 0,_?(_.authenticationTag=z,o.encryptionInput=_):i={dataEncryptionKey:w,dataEncryptionIV:E,encryptedBytes:D,authenticationTag:z},c&&h){let{keyId:L,keyUri:B}=await za(this.agent,e.author),W=[xt.ProtocolPath,La.protocol,"contextKey"],ee=await this.agent.keyManager.derivePublicKey({keyUri:B,derivationPath:W});o.authorKeyDeliveryPublicKey={rootKeyId:L,publicKeyJwk:ee}}}}let a,s=Ch[e.messageType];if(t){if(a=await s.parse(t),Kd(a)&&e.signAsOwner){let o=await this.getSigner(e.author);await a.signAsOwner(o)}else if(e.granteeDid&&Kd(a)&&e.signAsOwnerDelegate){let o=await this.getSigner(e.granteeDid),c=e.messageParams;await a.signAsOwnerDelegate(o,c.delegatedGrant)}}else{if(e.messageParams===void 0)throw new Error("AgentDwnApi: messageParams must be provided when rawMessage is not given.");let o=e.granteeDid?await this.getSigner(e.granteeDid):await this.getSigner(e.author),c={...e.messageParams};if(e.granteeDid&&c.permissionGrantId&&!c.delegatedGrant&&qa(e,De.RecordsWrite)){let{reply:l}=await this.processRequest({author:e.granteeDid,target:e.author,messageType:De.RecordsRead,messageParams:{filter:{recordId:c.permissionGrantId}}});if(l.status.code===200&&l.entry?.recordsWrite&&l.entry?.data){let d=await zt.toBytes(l.entry.data);c.delegatedGrant={...l.entry.recordsWrite,encodedData:fe.uint8Array(d).toBase64Url()}}}if(a=await s.create({...c,signer:o}),i&&qa(e,De.RecordsWrite)){let l=a,d=l.message.recordId,{encryptionInput:u,keyId:f,keyUri:p,contextDerivationPath:h}=await PH(this.agent,e.author,d,i.dataEncryptionKey,i.dataEncryptionIV),m={...u,authenticationTag:i.authenticationTag};await l.encryptSymmetricEncryptionKey(m),await l.sign({signer:o}),this._contextKeyCache.set(d,{keyId:f,keyUri:p,contextDerivationPath:h})}}return{message:a.message,dataStream:n}}hasGrantParams(e){return e!==void 0&&("permissionGrantId"in e&&e.permissionGrantId!==void 0||"delegatedGrant"in e&&e.delegatedGrant!==void 0)}async getSigner(e){if(e===this.agent.agentDid.uri){let t=await this.agent.agentDid.getSigner();return{algorithm:t.algorithm,keyId:t.keyId,sign:async n=>await t.sign({data:n})}}else try{let t=await this.agent.did.get({didUri:e});if(t){let o=await t.getSigner();return{algorithm:o.algorithm,keyId:o.keyId,sign:async c=>await o.sign({data:c})}}let n=await this.agent.did.getSigningMethod({didUri:e});if(!n.publicKeyJwk)throw new Error(`Verification method '${n.id}' does not contain a public key in JWK format`);let i=await this.agent.keyManager.getKeyUri({key:n.publicKeyJwk}),a=await this.agent.keyManager.getPublicKey({keyUri:i}),s=this.agent.keyManager;return{algorithm:vn.getJoseSignatureAlgorithmFromPublicKey(a),keyId:n.id,sign:async o=>await s.sign({data:o,keyUri:i})}}catch(t){throw new Error(`AgentDwnApi: Unable to get signer for author '${e}': ${t.message}`)}}async getEncryptionKeyDeriver(e){return Ib(this.agent,e)}async getEncryptionKeyInfo(e){return za(this.agent,e)}async getKeyDecrypter(e){return W6(this.agent,e)}detectNewParticipants(e){return z6(e)}async getProtocolDefinition(e,t,n){if(!this._dwn)try{return await this.fetchRemoteProtocolDefinition(e,t)}catch(a){let s=a instanceof Error?a.message:"";if(s.includes("not found")||s.includes("404")||s.includes("No protocol"))return;throw a}let i;if(n)try{let a=new Ss({agent:this.agent}),{grant:s}=await a.getPermissionForRequest({connectedDid:e,delegateDid:n,protocol:t,cached:!0,messageType:De.ProtocolsQuery});i=s.id}catch{}return TH(e,t,this._dwn,this.getSigner.bind(this),this._protocolDefinitionCache,n,i)}async fetchRemoteProtocolDefinition(e,t){return IH(e,t,this.getDwnEndpointUrlsForTarget.bind(this),this.sendDwnRpcRequest.bind(this),this._protocolDefinitionCache)}async extractDerivedPublicKey(e,t,n,i){return DH(e,t,n,i,this.getDwnEndpointUrlsForTarget.bind(this),this.getSigner.bind(this),this.sendDwnRpcRequest.bind(this))}async maybeDecryptReply(e,t){return EH(e,t,this.agent,this._contextDerivedKeyCache,this.fetchContextKeyRecord.bind(this),this._delegateDecryptionKeyCache,this._delegateContextKeyCache)}async getDwnMessage({author:e,messageCid:t}){let n=await this.getSigner(e),i=await Ch[De.MessagesRead].create({messageCid:t,signer:n}),a;if(this._dwn?a=await this._dwn.processMessage(e,i.message):a=await this.sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:[this._localDwnEndpoint],message:i.message}),a.status.code!==200)throw new Error(`AgentDwnApi: Failed to read message, response status: ${a.status.code} - ${a.status.detail}`);let s=a.entry,c={message:s.message};if(Kd(s)){let l=s.data;if(l){let d=await zt.toBytes(l);c.data=new Blob([d],{type:s.message.descriptor.dataFormat})}}return c}async ensureKeyDeliveryProtocol(e){return SH(this.agent,e,this.processRequest.bind(this),this.getProtocolDefinition.bind(this),this._keyDeliveryProtocolInstalledCache,this._protocolDefinitionCache)}set onDelegateContextKeysChanged(e){this._onDelegateContextKeysChanged=e}importDelegateDecryptionKeys(e,t){let n=`ddk~${e}`;this._delegateDecryptionKeyCache.set(n,t)}importDelegateContextKeys(e,t,n){let i=this._delegateContextKeyCacheIndex.get(e);if(i)for(let o of i)this._delegateContextKeyCache.delete(o);let a=[];for(let o of t){let c=`dctx~${e}~${o.protocol}~${o.contextId}`;this._delegateContextKeyCache.set(c,o.derivedPrivateKey),a.push(c)}this._delegateContextKeyCacheIndex.set(e,a);let s=new Set(n??[]);for(let o of t)s.add(o.protocol);s.size>0?this._delegateMultiPartyProtocols.set(e,s):this._delegateMultiPartyProtocols.delete(e)}clearDelegateDecryptionKeys(e){if(e){this._delegateDecryptionKeyCache.delete(`ddk~${e}`);let t=this._delegateContextKeyCacheIndex.get(e);if(t){for(let n of t)this._delegateContextKeyCache.delete(n);this._delegateContextKeyCacheIndex.delete(e)}this._delegateMultiPartyProtocols.delete(e)}else this._delegateDecryptionKeyCache.clear(),this._delegateContextKeyCache.clear(),this._delegateContextKeyCacheIndex.clear(),this._delegateMultiPartyProtocols.clear()}exportDelegateContextKeys(e){let t=this._delegateContextKeyCacheIndex.get(e);if(!t)return[];let n=[],i=`dctx~${e}~`;for(let a of t){let s=this._delegateContextKeyCache.get(a);if(!s||!a.startsWith(i))continue;let o=a.slice(i.length),c=o.lastIndexOf("~");c!==-1&&n.push({protocol:o.slice(0,c),contextId:o.slice(c+1),derivedPrivateKey:s})}return n}exportDelegateMultiPartyProtocols(e){let t=this._delegateMultiPartyProtocols.get(e);return t?[...t]:[]}hasEligibleDelegatesForProtocol(e){for(let[,t]of this._delegateMultiPartyProtocols)if(t.has(e))return!0;return!1}deliverContextKeyToDelegates(e,t,n){for(let[i,a]of this._delegateMultiPartyProtocols){if(!a.has(e))continue;let s=`dctx~${i}~${e}~${t}`;if(this._delegateContextKeyCache.get(s))continue;this._delegateContextKeyCache.set(s,n);let o=this._delegateContextKeyCacheIndex.get(i)??[];o.push(s),this._delegateContextKeyCacheIndex.set(i,o),this._onDelegateContextKeysChanged?.(i)}}async deliverContextKeyToDelegatesViaDwn(e,t,n,i){try{let s=await new Ss({agent:this.agent}).fetchGrants({author:e,target:e,grantor:e,protocol:t,checkRevoked:!0}),o=new Set(["Read","Query","Subscribe"]),c=Date.now(),l=new Set;for(let d of s){if(!d.grant.delegated||new Date(d.grant.dateExpires).getTime()<=c)continue;let u=d.grant.scope;if(u.interface!=="Records"||!o.has(u.method)||u.protocolPath||u.contextId)continue;let f=d.grant.grantee,p=d.grant.delegateKeyDelivery;if(!p?.rootKeyId||!p?.publicKeyJwk||l.has(f))continue;let h=p.publicKeyJwk;try{await this.writeContextKeyRecord({tenantDid:e,recipientDid:f,contextKeyData:i,sourceProtocol:t,sourceContextId:n,recipientKeyDeliveryPublicKey:{rootKeyId:p.rootKeyId,publicKeyJwk:h}}),l.add(f)}catch(m){console.warn(`AgentDwnApi: Cross-device key delivery to delegate '${f}' for context '${n}' failed: ${m.message}. The delegate may need to reconnect.`)}}}catch(a){console.warn(`AgentDwnApi: Delegate grant discovery for protocol '${t}' failed: ${a.message}`)}}trackEagerSend(e){return this._pendingEagerSends.add(e),e.finally(()=>{this._pendingEagerSends.delete(e)}),e}async drainPendingEagerSends(){if(this._pendingEagerSends.size===0)return;let e=[...this._pendingEagerSends];await Promise.allSettled(e)}async writeContextKeyRecord(e){return kH(this.agent,e,this.processRequest.bind(this),this.ensureKeyDeliveryProtocol.bind(this),this.eagerSendContextKeyRecord.bind(this),this.trackEagerSend.bind(this))}async eagerSendContextKeyRecord(e,t){return _H(this.agent,e,t,this.getDwnMessage.bind(this),this.sendDwnRpcRequest.bind(this),this.getDwnEndpointUrlsForTarget.bind(this))}async fetchContextKeyRecord(e){return AH(this.agent,e,this.processRequest.bind(this))}};g();var CH="dwn",$H="connect";function KWe(r){return`${CH}://${$H}?callback=${encodeURIComponent(r)}`}function Ige(r){let e=JSON.stringify(r);return Cge(e)}function RH(r){try{let e=$ge(r),t=JSON.parse(e);return Dge(t)?t:void 0}catch{return}}function UWe(r){try{let e=`${CH}://`;if(!r.startsWith(e))return;let t=r.slice(e.length),n=t.indexOf("?");if(n===-1||t.slice(0,n)!==$H)return;let a=t.slice(n+1),o=new URLSearchParams(a).get("callback");return!o||o.length===0?void 0:{callback:o}}catch{return}}function NWe(r,e){let t=Ige(e);return`${r.split("#")[0]}#${t}`}function LWe(r){let e=r.indexOf("#");if(e===-1)return RH(r);let t=r.slice(e+1);if(t.length!==0)return RH(t)}function Dge(r){if(typeof r!="object"||r===null)return!1;let e=r;return!(typeof e.endpoint!="string"||e.endpoint.length===0||!Rge(e.endpoint))}function Rge(r){try{let t=new URL(r).hostname.toLowerCase();return!!(t==="127.0.0.1"||t==="::1"||t==="[::1]"||t==="localhost"||t.endsWith(".localhost"))}catch{return!1}}function Cge(r){let e=new TextEncoder().encode(r),t="";for(let a=0;a<e.length;a++)t+=String.fromCharCode(e[a]);let n=btoa(t).replaceAll("+","-").replaceAll("/","_"),i=n.length;for(;i>0&&n.codePointAt(i-1)===61;)i--;return i===n.length?n:n.slice(0,i)}function $ge(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=e.length%4;t===2?e+="==":t===3&&(e+="=");let n=atob(e),i=new Uint8Array(n.length);for(let a=0;a<n.length;a++)i[a]=n.charCodeAt(a);return new TextDecoder().decode(i)}g();g();PP();s1();g();u1();Ja();var Bge=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),OH=Uint8Array.from({length:16},(r,e)=>e),Oge=OH.map(r=>(9*r+5)%16),Z6=[OH],Y6=[Oge];for(let r=0;r<4;r++)for(let e of[Z6,Y6])e.push(e[r].map(t=>Bge[t]));var jH=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(r=>new Uint8Array(r)),jge=Z6.map((r,e)=>r.map(t=>jH[e][t])),Mge=Y6.map((r,e)=>r.map(t=>jH[e][t])),Kge=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Uge=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),dS=(r,e)=>r<<e|r>>>32-e;function BH(r,e,t,n){return r===0?e^t^n:r===1?e&t|~e&n:r===2?(e|~t)^n:r===3?e&n|t&~n:e^(t|~n)}var lS=new Uint32Array(16),J6=class extends iu{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){let{h0:e,h1:t,h2:n,h3:i,h4:a}=this;return[e,t,n,i,a]}set(e,t,n,i,a){this.h0=e|0,this.h1=t|0,this.h2=n|0,this.h3=i|0,this.h4=a|0}process(e,t){for(let p=0;p<16;p++,t+=4)lS[p]=e.getUint32(t,!0);let n=this.h0|0,i=n,a=this.h1|0,s=a,o=this.h2|0,c=o,l=this.h3|0,d=l,u=this.h4|0,f=u;for(let p=0;p<5;p++){let h=4-p,m=Kge[p],y=Uge[p],v=Z6[p],w=Y6[p],E=jge[p],_=Mge[p];for(let A=0;A<16;A++){let D=dS(n+BH(p,a,o,l)+lS[v[A]]+m,E[A])+u|0;n=u,u=l,l=dS(o,10)|0,o=a,a=D}for(let A=0;A<16;A++){let D=dS(i+BH(h,s,c,d)+lS[w[A]]+y,_[A])+f|0;i=f,f=d,d=dS(c,10)|0,c=s,s=D}}this.set(this.h1+o+d|0,this.h2+l+f|0,this.h3+u+i|0,this.h4+n+s|0,this.h0+a+c|0)}roundClean(){lS.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}},MH=am(()=>new J6);iw();wP();Ja();sm();var Nge=tw("ed25519 seed"),X6=2147483648,KH=new Uint8Array([0]);function UH(r,...e){return typeof r=="string"&&(r=q$(r)),Gd(r,...e),r}var Lge=r=>MH(au(r)),qge=r=>Vd(r).getUint32(0,!1),Q6=r=>{if(!Number.isSafeInteger(r)||r<0||r>2**32-1)throw new Error(`Invalid number=${r}. Should be from 0 to 2 ** 32 - 1`);let e=new Uint8Array(4);return Vd(e).setUint32(0,r,!1),e},uS=class r{get publicKeyRaw(){return pa.getPublicKey(this.privateKey)}get publicKey(){return Yf(KH,this.publicKeyRaw)}get pubHash(){return Lge(this.publicKey)}get fingerprint(){return qge(this.pubHash)}get fingerprintHex(){return rk(Q6(this.fingerprint))}get parentFingerprintHex(){return rk(Q6(this.parentFingerprint))}static fromMasterSeed(e){if(e=UH(e),8*e.length<128||8*e.length>512)throw new Error(`HDKey: wrong seed length=${e.length}. Should be between 128 and 512 bits; 256 bits is advised)`);let t=ru(Ru,Nge,e);return new r({privateKey:t.slice(0,32),chainCode:t.slice(32)})}constructor(e){if(this.depth=0,this.index=0,this.parentFingerprint=0,!e||typeof e!="object")throw new Error("HDKey.constructor must not be called directly");if(Gd(e.privateKey,32),Gd(e.chainCode,32),this.depth=e.depth||0,this.index=e.index||0,this.parentFingerprint=e.parentFingerprint||0,!this.depth&&(this.parentFingerprint||this.index))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");this.chainCode=e.chainCode,this.privateKey=e.privateKey}derive(e,t=!1){if(!/^[mM]'?/.test(e))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(e))return this;let n=e.replace(/^[mM]'?\//,"").split("/"),i=this;for(let a of n){let s=/^(\d+)('?)$/.exec(a);if(!s||s.length!==3)throw new Error(`Invalid child index: ${a}`);let o=+s[1];if(!Number.isSafeInteger(o)||o>=X6)throw new Error("Invalid index");(t||s[2]==="'")&&(o+=X6),i=i.deriveChild(o)}return i}deriveChild(e){if(e<X6)throw new Error(`Non-hardened child derivation not possible for Ed25519 (index=${e})`);let t=Yf(KH,this.privateKey,Q6(e)),n=ru(Ru,this.chainCode,t);return new r({chainCode:n.slice(32),depth:this.depth+1,parentFingerprint:this.fingerprint,index:e,privateKey:n.slice(0,32)})}sign(e){return pa.sign(e,this.privateKey)}verify(e,t){return t=UH(t,64),pa.verify(t,e,this.publicKeyRaw)}};g();var e5=`abandon
10
+ deps: ${t}}`};var xae={keyword:"dependencies",type:"object",schemaType:"object",error:Ed.error,code(r){let[e,t]=Eae(r);DL(r,e),RL(r,t)}};function Eae({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let i=Array.isArray(r[n])?e:t;i[n]=r[n]}return[e,t]}function DL(r,e=r.schema){let{gen:t,data:n,it:i}=r;if(Object.keys(e).length===0)return;let a=t.let("missing");for(let s in e){let o=e[s];if(o.length===0)continue;let c=(0,P0.propertyInData)(t,n,s,i.opts.ownProperties);r.setParams({property:s,depsCount:o.length,deps:o.join(", ")}),i.allErrors?t.if(c,()=>{for(let l of o)(0,P0.checkReportMissingProp)(r,l)}):(t.if((0,mR._)`${c} && (${(0,P0.checkMissingProp)(r,o,a)})`),(0,P0.reportMissingProp)(r,a),t.else())}}Ed.validatePropertyDeps=DL;function RL(r,e=r.schema){let{gen:t,data:n,keyword:i,it:a}=r,s=t.name("valid");for(let o in e)(0,Pae.alwaysValidSchema)(a,e[o])||(t.if((0,P0.propertyInData)(t,n,o,a.opts.ownProperties),()=>{let c=r.subschema({keyword:i,schemaProp:o},s);r.mergeValidEvaluated(c,s)},()=>t.var(s,!0)),r.ok(s))}Ed.validateSchemaDeps=RL;Ed.default=xae});var $L=ke(yR=>{"use strict";g();Object.defineProperty(yR,"__esModule",{value:!0});var CL=Dt(),Sae=Vt(),kae={message:"property name must be valid",params:({params:r})=>(0,CL._)`{propertyName: ${r.propertyName}}`},_ae={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:kae,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,Sae.alwaysValidSchema)(i,t))return;let a=e.name("valid");e.forIn("key",n,s=>{r.setParams({propertyName:s}),r.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},a),e.if((0,CL.not)(a),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(a)}};yR.default=_ae});var wR=ke(gR=>{"use strict";g();Object.defineProperty(gR,"__esModule",{value:!0});var t2=Pa(),_c=Dt(),Aae=ba(),r2=Vt(),Tae={message:"must NOT have additional properties",params:({params:r})=>(0,_c._)`{additionalProperty: ${r.additionalProperty}}`},Iae={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Tae,code(r){let{gen:e,schema:t,parentSchema:n,data:i,errsCount:a,it:s}=r;if(!a)throw new Error("ajv implementation error");let{allErrors:o,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,r2.alwaysValidSchema)(s,t))return;let l=(0,t2.allSchemaProperties)(n.properties),d=(0,t2.allSchemaProperties)(n.patternProperties);u(),r.ok((0,_c._)`${a} === ${Aae.default.errors}`);function u(){e.forIn("key",i,y=>{!l.length&&!d.length?h(y):e.if(f(y),()=>h(y))})}function f(y){let v;if(l.length>8){let w=(0,r2.schemaRefOrVal)(s,n.properties,"properties");v=(0,t2.isOwnProperty)(e,w,y)}else l.length?v=(0,_c.or)(...l.map(w=>(0,_c._)`${y} === ${w}`)):v=_c.nil;return d.length&&(v=(0,_c.or)(v,...d.map(w=>(0,_c._)`${(0,t2.usePattern)(r,w)}.test(${y})`))),(0,_c.not)(v)}function p(y){e.code((0,_c._)`delete ${i}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),o||e.break();return}if(typeof t=="object"&&!(0,r2.alwaysValidSchema)(s,t)){let v=e.name("valid");c.removeAdditional==="failing"?(m(y,v,!1),e.if((0,_c.not)(v),()=>{r.reset(),p(y)})):(m(y,v),o||e.if((0,_c.not)(v),()=>e.break()))}}function m(y,v,w){let E={keyword:"additionalProperties",dataProp:y,dataPropType:r2.Type.Str};w===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(E,v)}}};gR.default=Iae});var jL=ke(bR=>{"use strict";g();Object.defineProperty(bR,"__esModule",{value:!0});var Dae=o0(),BL=Pa(),vR=Vt(),OL=wR(),Rae={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:a}=r;a.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&OL.default.code(new Dae.KeywordCxt(a,OL.default,"additionalProperties"));let s=(0,BL.allSchemaProperties)(t);for(let u of s)a.definedProperties.add(u);a.opts.unevaluated&&s.length&&a.props!==!0&&(a.props=vR.mergeEvaluated.props(e,(0,vR.toHash)(s),a.props));let o=s.filter(u=>!(0,vR.alwaysValidSchema)(a,t[u]));if(o.length===0)return;let c=e.name("valid");for(let u of o)l(u)?d(u):(e.if((0,BL.propertyInData)(e,i,u,a.opts.ownProperties)),d(u),a.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(u),r.ok(c);function l(u){return a.opts.useDefaults&&!a.compositeRule&&t[u].default!==void 0}function d(u){r.subschema({keyword:"properties",schemaProp:u,dataProp:u},c)}}};bR.default=Rae});var NL=ke(PR=>{"use strict";g();Object.defineProperty(PR,"__esModule",{value:!0});var ML=Pa(),n2=Dt(),KL=Vt(),UL=Vt(),Cae={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:i,it:a}=r,{opts:s}=a,o=(0,ML.allSchemaProperties)(t),c=o.filter(m=>(0,KL.alwaysValidSchema)(a,t[m]));if(o.length===0||c.length===o.length&&(!a.opts.unevaluated||a.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&i.properties,d=e.name("valid");a.props!==!0&&!(a.props instanceof n2.Name)&&(a.props=(0,UL.evaluatedPropsToName)(e,a.props));let{props:u}=a;f();function f(){for(let m of o)l&&p(m),a.allErrors?h(m):(e.var(d,!0),h(m),e.if(d))}function p(m){for(let y in l)new RegExp(m).test(y)&&(0,KL.checkStrictMode)(a,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,n2._)`${(0,ML.usePattern)(r,m)}.test(${y})`,()=>{let v=c.includes(m);v||r.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:UL.Type.Str},d),a.opts.unevaluated&&u!==!0?e.assign((0,n2._)`${u}[${y}]`,!0):!v&&!a.allErrors&&e.if((0,n2.not)(d),()=>e.break())})})}}};PR.default=Cae});var LL=ke(xR=>{"use strict";g();Object.defineProperty(xR,"__esModule",{value:!0});var $ae=Vt(),Bae={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,$ae.alwaysValidSchema)(n,t)){r.fail();return}let i=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};xR.default=Bae});var qL=ke(ER=>{"use strict";g();Object.defineProperty(ER,"__esModule",{value:!0});var Oae=Pa(),jae={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Oae.validateUnion,error:{message:"must match a schema in anyOf"}};ER.default=jae});var zL=ke(SR=>{"use strict";g();Object.defineProperty(SR,"__esModule",{value:!0});var i2=Dt(),Mae=Vt(),Kae={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,i2._)`{passingSchemas: ${r.passing}}`},Uae={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Kae,code(r){let{gen:e,schema:t,parentSchema:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let a=t,s=e.let("valid",!1),o=e.let("passing",null),c=e.name("_valid");r.setParams({passing:o}),e.block(l),r.result(s,()=>r.reset(),()=>r.error(!0));function l(){a.forEach((d,u)=>{let f;(0,Mae.alwaysValidSchema)(i,d)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},c),u>0&&e.if((0,i2._)`${c} && ${s}`).assign(s,!1).assign(o,(0,i2._)`[${o}, ${u}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(o,u),f&&r.mergeEvaluated(f,i2.Name)})})}}};SR.default=Uae});var FL=ke(kR=>{"use strict";g();Object.defineProperty(kR,"__esModule",{value:!0});var Nae=Vt(),Lae={keyword:"allOf",schemaType:"array",code(r){let{gen:e,schema:t,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");let i=e.name("valid");t.forEach((a,s)=>{if((0,Nae.alwaysValidSchema)(n,a))return;let o=r.subschema({keyword:"allOf",schemaProp:s},i);r.ok(i),r.mergeEvaluated(o)})}};kR.default=Lae});var VL=ke(_R=>{"use strict";g();Object.defineProperty(_R,"__esModule",{value:!0});var s2=Dt(),HL=Vt(),qae={message:({params:r})=>(0,s2.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,s2._)`{failingKeyword: ${r.ifClause}}`},zae={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:qae,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,HL.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=GL(n,"then"),a=GL(n,"else");if(!i&&!a)return;let s=e.let("valid",!0),o=e.name("_valid");if(c(),r.reset(),i&&a){let d=e.let("ifClause");r.setParams({ifClause:d}),e.if(o,l("then",d),l("else",d))}else i?e.if(o,l("then")):e.if((0,s2.not)(o),l("else"));r.pass(s,()=>r.error(!0));function c(){let d=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},o);r.mergeEvaluated(d)}function l(d,u){return()=>{let f=r.subschema({keyword:d},o);e.assign(s,o),r.mergeValidEvaluated(f,s),u?e.assign(u,(0,s2._)`${d}`):r.setParams({ifClause:d})}}}};function GL(r,e){let t=r.schema[e];return t!==void 0&&!(0,HL.alwaysValidSchema)(r,t)}_R.default=zae});var WL=ke(AR=>{"use strict";g();Object.defineProperty(AR,"__esModule",{value:!0});var Fae=Vt(),Gae={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,Fae.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};AR.default=Gae});var JL=ke(TR=>{"use strict";g();Object.defineProperty(TR,"__esModule",{value:!0});var Hae=lR(),Vae=_L(),Wae=uR(),Jae=TL(),Zae=IL(),Yae=e2(),Xae=$L(),Qae=wR(),ece=jL(),tce=NL(),rce=LL(),nce=qL(),ice=zL(),sce=FL(),oce=VL(),ace=WL();function cce(r=!1){let e=[rce.default,nce.default,ice.default,sce.default,oce.default,ace.default,Xae.default,Qae.default,Yae.default,ece.default,tce.default];return r?e.push(Vae.default,Jae.default):e.push(Hae.default,Wae.default),e.push(Zae.default),e}TR.default=cce});var DR=ke(x0=>{"use strict";g();Object.defineProperty(x0,"__esModule",{value:!0});x0.dynamicAnchor=void 0;var IR=Dt(),dce=ba(),ZL=c0(),lce=Wx(),uce={keyword:"$dynamicAnchor",schemaType:"string",code:r=>YL(r,r.schema)};function YL(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,IR._)`${dce.default.dynamicAnchors}${(0,IR.getProperty)(e)}`,a=n.errSchemaPath==="#"?n.validateName:fce(r);t.if((0,IR._)`!${i}`,()=>t.assign(i,a))}x0.dynamicAnchor=YL;function fce(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:i,baseId:a,localRefs:s,meta:o}=e.root,{schemaId:c}=n.opts,l=new ZL.SchemaEnv({schema:t,schemaId:c,root:i,baseId:a,localRefs:s,meta:o});return ZL.compileSchema.call(n,l),(0,lce.getValidate)(r,l)}x0.default=uce});var RR=ke(E0=>{"use strict";g();Object.defineProperty(E0,"__esModule",{value:!0});E0.dynamicRef=void 0;var XL=Dt(),pce=ba(),QL=Wx(),hce={keyword:"$dynamicRef",schemaType:"string",code:r=>e9(r,r.schema)};function e9(r,e){let{gen:t,keyword:n,it:i}=r;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let a=e.slice(1);if(i.allErrors)s();else{let c=t.let("valid",!1);s(c),r.ok(c)}function s(c){if(i.schemaEnv.root.dynamicAnchors[a]){let l=t.let("_v",(0,XL._)`${pce.default.dynamicAnchors}${(0,XL.getProperty)(a)}`);t.if(l,o(l,c),o(i.validateName,c))}else o(i.validateName,c)()}function o(c,l){return l?()=>t.block(()=>{(0,QL.callRef)(r,c),t.let(l,!0)}):()=>(0,QL.callRef)(r,c)}}E0.dynamicRef=e9;E0.default=hce});var t9=ke(CR=>{"use strict";g();Object.defineProperty(CR,"__esModule",{value:!0});var mce=DR(),yce=Vt(),gce={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,mce.dynamicAnchor)(r,""):(0,yce.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};CR.default=gce});var r9=ke($R=>{"use strict";g();Object.defineProperty($R,"__esModule",{value:!0});var wce=RR(),vce={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,wce.dynamicRef)(r,r.schema)};$R.default=vce});var n9=ke(BR=>{"use strict";g();Object.defineProperty(BR,"__esModule",{value:!0});var bce=DR(),Pce=RR(),xce=t9(),Ece=r9(),Sce=[bce.default,Pce.default,xce.default,Ece.default];BR.default=Sce});var s9=ke(OR=>{"use strict";g();Object.defineProperty(OR,"__esModule",{value:!0});var i9=e2(),kce={keyword:"dependentRequired",type:"object",schemaType:"object",error:i9.error,code:r=>(0,i9.validatePropertyDeps)(r)};OR.default=kce});var o9=ke(jR=>{"use strict";g();Object.defineProperty(jR,"__esModule",{value:!0});var _ce=e2(),Ace={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,_ce.validateSchemaDeps)(r)};jR.default=Ace});var a9=ke(MR=>{"use strict";g();Object.defineProperty(MR,"__esModule",{value:!0});var Tce=Vt(),Ice={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,Tce.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};MR.default=Ice});var c9=ke(KR=>{"use strict";g();Object.defineProperty(KR,"__esModule",{value:!0});var Dce=s9(),Rce=o9(),Cce=a9(),$ce=[Dce.default,Rce.default,Cce.default];KR.default=$ce});var l9=ke(UR=>{"use strict";g();Object.defineProperty(UR,"__esModule",{value:!0});var sf=Dt(),d9=Vt(),Bce=ba(),Oce={message:"must NOT have unevaluated properties",params:({params:r})=>(0,sf._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},jce={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Oce,code(r){let{gen:e,schema:t,data:n,errsCount:i,it:a}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:s,props:o}=a;o instanceof sf.Name?e.if((0,sf._)`${o} !== true`,()=>e.forIn("key",n,u=>e.if(l(o,u),()=>c(u)))):o!==!0&&e.forIn("key",n,u=>o===void 0?c(u):e.if(d(o,u),()=>c(u))),a.props=!0,r.ok((0,sf._)`${i} === ${Bce.default.errors}`);function c(u){if(t===!1){r.setParams({unevaluatedProperty:u}),r.error(),s||e.break();return}if(!(0,d9.alwaysValidSchema)(a,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:d9.Type.Str},f),s||e.if((0,sf.not)(f),()=>e.break())}}function l(u,f){return(0,sf._)`!${u} || !${u}[${f}]`}function d(u,f){let p=[];for(let h in u)u[h]===!0&&p.push((0,sf._)`${f} !== ${h}`);return(0,sf.and)(...p)}}};UR.default=jce});var f9=ke(NR=>{"use strict";g();Object.defineProperty(NR,"__esModule",{value:!0});var rh=Dt(),u9=Vt(),Mce={message:({params:{len:r}})=>(0,rh.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,rh._)`{limit: ${r}}`},Kce={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Mce,code(r){let{gen:e,schema:t,data:n,it:i}=r,a=i.items||0;if(a===!0)return;let s=e.const("len",(0,rh._)`${n}.length`);if(t===!1)r.setParams({len:a}),r.fail((0,rh._)`${s} > ${a}`);else if(typeof t=="object"&&!(0,u9.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,rh._)`${s} <= ${a}`);e.if((0,rh.not)(c),()=>o(c,a)),r.ok(c)}i.items=!0;function o(c,l){e.forRange("i",l,s,d=>{r.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:u9.Type.Num},c),i.allErrors||e.if((0,rh.not)(c),()=>e.break())})}}};NR.default=Kce});var p9=ke(LR=>{"use strict";g();Object.defineProperty(LR,"__esModule",{value:!0});var Uce=l9(),Nce=f9(),Lce=[Uce.default,Nce.default];LR.default=Lce});var h9=ke(qR=>{"use strict";g();Object.defineProperty(qR,"__esModule",{value:!0});var zn=Dt(),qce={message:({schemaCode:r})=>(0,zn.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,zn._)`{format: ${r}}`},zce={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:qce,code(r,e){let{gen:t,data:n,$data:i,schema:a,schemaCode:s,it:o}=r,{opts:c,errSchemaPath:l,schemaEnv:d,self:u}=o;if(!c.validateFormats)return;i?f():p();function f(){let h=t.scopeValue("formats",{ref:u.formats,code:c.code.formats}),m=t.const("fDef",(0,zn._)`${h}[${s}]`),y=t.let("fType"),v=t.let("format");t.if((0,zn._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(y,(0,zn._)`${m}.type || "string"`).assign(v,(0,zn._)`${m}.validate`),()=>t.assign(y,(0,zn._)`"string"`).assign(v,m)),r.fail$data((0,zn.or)(w(),E()));function w(){return c.strictSchema===!1?zn.nil:(0,zn._)`${s} && !${v}`}function E(){let _=d.$async?(0,zn._)`(${m}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,zn._)`${v}(${n})`,A=(0,zn._)`(typeof ${v} == "function" ? ${_} : ${v}.test(${n}))`;return(0,zn._)`${v} && ${v} !== true && ${y} === ${e} && !${A}`}}function p(){let h=u.formats[a];if(!h){w();return}if(h===!0)return;let[m,y,v]=E(h);m===e&&r.pass(_());function w(){if(c.strictSchema===!1){u.logger.warn(A());return}throw new Error(A());function A(){return`unknown format "${a}" ignored in schema at path "${l}"`}}function E(A){let D=A instanceof RegExp?(0,zn.regexpCode)(A):c.code.formats?(0,zn._)`${c.code.formats}${(0,zn.getProperty)(a)}`:void 0,M=t.scopeValue("formats",{key:a,ref:A,code:D});return typeof A=="object"&&!(A instanceof RegExp)?[A.type||"string",A.validate,(0,zn._)`${M}.validate`]:["string",A,M]}function _(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,zn._)`await ${v}(${n})`}return typeof y=="function"?(0,zn._)`${v}(${n})`:(0,zn._)`${v}.test(${n})`}}}};qR.default=zce});var m9=ke(zR=>{"use strict";g();Object.defineProperty(zR,"__esModule",{value:!0});var Fce=h9(),Gce=[Fce.default];zR.default=Gce});var y9=ke(By=>{"use strict";g();Object.defineProperty(By,"__esModule",{value:!0});By.contentVocabulary=By.metadataVocabulary=void 0;By.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];By.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var w9=ke(FR=>{"use strict";g();Object.defineProperty(FR,"__esModule",{value:!0});var Hce=lL(),Vce=xL(),Wce=JL(),Jce=n9(),Zce=c9(),Yce=p9(),Xce=m9(),g9=y9(),Qce=[Jce.default,Hce.default,Vce.default,(0,Wce.default)(!0),Xce.default,g9.metadataVocabulary,g9.contentVocabulary,Zce.default,Yce.default];FR.default=Qce});var b9=ke(o2=>{"use strict";g();Object.defineProperty(o2,"__esModule",{value:!0});o2.DiscrError=void 0;var v9;(function(r){r.Tag="tag",r.Mapping="mapping"})(v9||(o2.DiscrError=v9={}))});var x9=ke(HR=>{"use strict";g();Object.defineProperty(HR,"__esModule",{value:!0});var Oy=Dt(),GR=b9(),P9=c0(),ede=a0(),tde=Vt(),rde={message:({params:{discrError:r,tagName:e}})=>r===GR.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Oy._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},nde={keyword:"discriminator",type:"object",schemaType:"object",error:rde,code(r){let{gen:e,data:t,schema:n,parentSchema:i,it:a}=r,{oneOf:s}=i;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let o=n.propertyName;if(typeof o!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Oy._)`${t}${(0,Oy.getProperty)(o)}`);e.if((0,Oy._)`typeof ${l} == "string"`,()=>d(),()=>r.error(!1,{discrError:GR.DiscrError.Tag,tag:l,tagName:o})),r.ok(c);function d(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,Oy._)`${l} === ${h}`),e.assign(c,u(p[h]));e.else(),r.error(!1,{discrError:GR.DiscrError.Mapping,tag:l,tagName:o}),e.endIf()}function u(p){let h=e.name("valid"),m=r.subschema({keyword:"oneOf",schemaProp:p},h);return r.mergeEvaluated(m,Oy.Name),h}function f(){var p;let h={},m=v(i),y=!0;for(let _=0;_<s.length;_++){let A=s[_];if(A?.$ref&&!(0,tde.schemaHasRulesButRef)(A,a.self.RULES)){let M=A.$ref;if(A=P9.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,M),A instanceof P9.SchemaEnv&&(A=A.schema),A===void 0)throw new ede.default(a.opts.uriResolver,a.baseId,M)}let D=(p=A?.properties)===null||p===void 0?void 0:p[o];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${o}"`);y=y&&(m||v(A)),w(D,_)}if(!y)throw new Error(`discriminator: "${o}" must be required`);return h;function v({required:_}){return Array.isArray(_)&&_.includes(o)}function w(_,A){if(_.const)E(_.const,A);else if(_.enum)for(let D of _.enum)E(D,A);else throw new Error(`discriminator: "properties/${o}" must have "const" or "enum"`)}function E(_,A){if(typeof _!="string"||_ in h)throw new Error(`discriminator: "${o}" values must be unique strings`);h[_]=A}}}};HR.default=nde});var E9=ke((Dje,ide)=>{ide.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var S9=ke((Rje,sde)=>{sde.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var k9=ke((Cje,ode)=>{ode.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var _9=ke(($je,ade)=>{ade.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var A9=ke((Bje,cde)=>{cde.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var T9=ke((Oje,dde)=>{dde.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var I9=ke((jje,lde)=>{lde.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var D9=ke((Mje,ude)=>{ude.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var R9=ke(VR=>{"use strict";g();Object.defineProperty(VR,"__esModule",{value:!0});var fde=E9(),pde=S9(),hde=k9(),mde=_9(),yde=A9(),gde=T9(),wde=I9(),vde=D9(),bde=["/properties"];function Pde(r){return[fde,pde,hde,mde,yde,e(this,gde),wde,e(this,vde)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,bde):n}}VR.default=Pde});var ZR=ke((cn,JR)=>{"use strict";g();Object.defineProperty(cn,"__esModule",{value:!0});cn.MissingRefError=cn.ValidationError=cn.CodeGen=cn.Name=cn.nil=cn.stringify=cn.str=cn._=cn.KeywordCxt=cn.Ajv2020=void 0;var xde=sL(),Ede=w9(),Sde=x9(),kde=R9(),WR="https://json-schema.org/draft/2020-12/schema",jy=class extends xde.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Ede.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Sde.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(kde.default.call(this,e),this.refs["http://json-schema.org/schema"]=WR)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(WR)?WR:void 0)}};cn.Ajv2020=jy;JR.exports=cn=jy;JR.exports.Ajv2020=jy;Object.defineProperty(cn,"__esModule",{value:!0});cn.default=jy;var _de=o0();Object.defineProperty(cn,"KeywordCxt",{enumerable:!0,get:function(){return _de.KeywordCxt}});var My=Dt();Object.defineProperty(cn,"_",{enumerable:!0,get:function(){return My._}});Object.defineProperty(cn,"str",{enumerable:!0,get:function(){return My.str}});Object.defineProperty(cn,"stringify",{enumerable:!0,get:function(){return My.stringify}});Object.defineProperty(cn,"nil",{enumerable:!0,get:function(){return My.nil}});Object.defineProperty(cn,"Name",{enumerable:!0,get:function(){return My.Name}});Object.defineProperty(cn,"CodeGen",{enumerable:!0,get:function(){return My.CodeGen}});var Ade=Ux();Object.defineProperty(cn,"ValidationError",{enumerable:!0,get:function(){return Ade.default}});var Tde=a0();Object.defineProperty(cn,"MissingRefError",{enumerable:!0,get:function(){return Tde.default}})});var of,a2=G(()=>{"use strict";g();CP();vt();of=class r{static async authorizeConfigure(e){let{protocolsConfigureMessage:t,expectedGrantor:n,expectedGrantee:i,permissionGrant:a,messageStore:s}=e;await jo.performBaseValidation({incomingMessage:t,expectedGrantor:n,expectedGrantee:i,permissionGrant:a,messageStore:s}),r.verifyScope(t,a.scope)}static async authorizeQuery(e){let{expectedGrantee:t,expectedGrantor:n,incomingMessage:i,permissionGrant:a,messageStore:s}=e;await jo.performBaseValidation({incomingMessage:i,expectedGrantor:n,expectedGrantee:t,permissionGrant:a,messageStore:s});let c=a.scope.protocol,l=i.descriptor.filter?.protocol;if(c!==void 0&&l!==c)throw new ne(re.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch,`Grant protocol scope ${c} does not match protocol in message ${l}`)}static verifyScope(e,t){if(t.protocol!==void 0&&t.protocol!==e.descriptor.definition.protocol)throw new ne(re.ProtocolsGrantAuthorizationScopeProtocolMismatch,"Grant scope specifies different protocol than what appears in the configure message.")}}});function Hs(r){let e=r.indexOf(":");if(e===-1)return;let t=r.substring(0,e),n=r.substring(e+1);return{alias:t,protocolPath:n}}function af(r){return r.includes(":")}function c2(r){return r.split("/").slice(-1)[0]}function kd(r,e){let t=r.split("/"),n,i=e;for(let a of t){if(!Object.hasOwn(i,a))return;n=i[a],i=n}return n}var Sd,nh=G(()=>{"use strict";g();bn();Hm();Sd=class{static async deriveAndInjectPublicEncryptionKeys(e,t,n){let i=JSON.parse(JSON.stringify(e));if(typeof t!="string"){let l=t,d=[xt.ProtocolPath,e.protocol];async function u(f,p){for(let h in f)if(!h.startsWith("$")){let m=[...p,h],y=f[h];if(y.$ref!==void 0){await u(y,m);continue}let v=await l.derivePublicKey(m);y.$encryption={rootKeyId:l.rootKeyId,publicKeyJwk:v},await u(y,m)}}return await u(i.structure,d),i}let a=t;async function s(l,d){for(let u in l)if(!u.startsWith("$")){let f=await ji.derivePrivateKey(d,[u]),p=l[u];if(p.$ref!==void 0){await s(p,f);continue}let h=await kt.getPublicKey({key:f.derivedPrivateKey});p.$encryption={rootKeyId:a,publicKeyJwk:h},await s(p,f)}}let o={derivationScheme:xt.ProtocolPath,derivedPrivateKey:n,rootKeyId:a},c=await ji.derivePrivateKey(o,[xt.ProtocolPath,e.protocol]);return await s(i.structure,c),i}}});var C9,Sa,d2=G(()=>{"use strict";g();xc();C9=An(ZR(),1);yr();lc();a2();qs();vt();ar();nh();ma();Lg();Sa=class r extends Bn{static async parse(e){return ye.validateJsonSchema(e),r.validateProtocolDefinition(e.descriptor.definition),await ye.validateSignatureStructure(e.authorization.signature,e.descriptor),_t.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:ve.Protocols,method:me.Configure,messageTimestamp:e.messageTimestamp??_t.getCurrentTimestamp(),definition:r.normalizeDefinition(e.definition),...e.permissionGrantId!==void 0&&{permissionGrantId:e.permissionGrantId}},n=await ye.createAuthorization({descriptor:t,signer:e.signer,delegatedGrant:e.delegatedGrant,permissionGrantId:e.permissionGrantId}),i={descriptor:t,authorization:n};return ye.validateJsonSchema(i),r.validateProtocolDefinition(i.descriptor.definition),new r(i)}async authorizeAuthorDelegate(e){let t=kr.parse(this.message.authorization.authorDelegatedGrant);await of.authorizeConfigure({protocolsConfigureMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:t,messageStore:e})}static validateProtocolDefinition(e){let{protocol:t,types:n,uses:i}=e;di(t);for(let a in n){let s=n[a].schema;s!==void 0&&nd(s)}i!==void 0&&r.validateUses(i,t),r.validateStructure(e)}static validateUses(e,t){let n=/^[a-zA-Z][a-zA-Z0-9_-]*$/;for(let i in e){if(!n.test(i))throw new ne(re.ProtocolsConfigureInvalidUsesAlias,`invalid 'uses' alias '${i}': must match pattern ${n.toString()}.`);try{di(e[i])}catch{throw new ne(re.ProtocolsConfigureInvalidUsesProtocolUrl,`invalid 'uses' protocol URL for alias '${i}': '${e[i]}' is not a valid normalized protocol URL.`)}if(e[i]===t)throw new ne(re.ProtocolsConfigureInvalidUsesSelfReference,`'uses' alias '${i}' references the protocol's own URI '${t}'. a protocol cannot compose itself.`)}}static validateStructure(e){let{uses:t}=e,n=Object.keys(e.types),i=r.fetchAllRolePathsRecursively("",e.structure,[]);r.validateRuleSetRecursively({ruleSet:e.structure,ruleSetProtocolPath:"",recordTypes:n,roles:i,uses:t,types:e.types})}static fetchAllRolePathsRecursively(e,t,n){if(e.split("/").length>10)throw new ne(re.ProtocolsConfigureRecordNestingDepthExceeded,"Record nesting depth exceeded 10 levels.");for(let i in t){if(i.startsWith("$"))continue;let a=t[i],s;e===""?s=i:s=`${e}/${i}`,a.$role?n.push(s):r.fetchAllRolePathsRecursively(s,a,n)}return n}static validateRuleSetRecursively(e){let{ruleSet:t,ruleSetProtocolPath:n,recordTypes:i,roles:a,uses:s,types:o}=e;if(t.$ref!==void 0){if(n.includes("/"))throw new ne(re.ProtocolsConfigureInvalidRefNotAtRoot,`'$ref' at protocol path '${n}' is not allowed: '$ref' nodes are only supported at the root level of the structure.`);r.validateRefNode(t,n,s)}if(t.$size!==void 0){let{min:l=0,max:d}=t.$size;if(d!==void 0&&d<l)throw new ne(re.ProtocolsConfigureInvalidSize,`Invalid size range found: max limit ${d} less than min limit ${l} at protocol path '${n}'`)}if(t.$recordLimit!==void 0){let{max:l,strategy:d}=t.$recordLimit;if(!Number.isInteger(l)||l<1)throw new ne(re.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.max value ${l} at protocol path '${n}': must be an integer >= 1.`);let u=Object.values(Zl);if(!u.includes(d))throw new ne(re.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.strategy '${d}' at protocol path '${n}': must be one of ${u.join(", ")}.`)}if(t.$tags){let l=new C9.default.default,{$allowUndefinedTags:d,$requiredTags:u,...f}=t.$tags;for(let p in f){let h=f[p];if(!l.validateSchema(h)){let m=l.errorsText(l.errors,{dataVar:`${n}/$tags/${p}`});throw new ne(re.ProtocolsConfigureInvalidTagSchema,`tags schema validation error: ${m}`)}}}let c=t.$actions??[];for(let l=0;l<c.length;l++){let d=c[l];if(d.role!==void 0){if(af(d.role))r.validateCrossProtocolAlias(d.role,s,n,"role");else if(!a.includes(d.role))throw new ne(re.ProtocolsConfigureRoleDoesNotExistAtGivenPath,`Role in action ${JSON.stringify(d)} for rule set ${n} does not exist.`)}if(d.who==="anyone"&&d.of)throw new ne(re.ProtocolsConfigureInvalidActionOfNotAllowed,`'of' is not allowed at rule set protocol path (${n})`);if(d.who===Bc.Recipient&&d.of===void 0&&d.can.some(f=>![vr.CoUpdate,vr.CoDelete,vr.CoPrune].includes(f)))throw new ne(re.ProtocolsConfigureInvalidRecipientOfAction,"Rules for `recipient` without `of` property must have `can` containing only `co-update`, `co-delete`, and `co-prune`.");if(d.who===Bc.Author&&!d.of)throw new ne(re.ProtocolsConfigureInvalidActionMissingOf,"'of' is required when 'author' is specified as 'who'");if(d.of!==void 0&&n!==""){if(af(d.of))r.validateCrossProtocolAlias(d.of,s,n,"of");else if(!(n===d.of||n.startsWith(d.of+"/")))throw new ne(re.ProtocolsConfigureInvalidActionOfNotAnAncestor,`'of' value '${d.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(d)}.`)}if(d.can!==void 0){if(d.can.includes(vr.Update)&&!d.can.includes(vr.Create))throw new ne(re.ProtocolsConfigureInvalidActionUpdateWithoutCreate,`Action rule ${JSON.stringify(d)} contains 'update' action but missing the required 'create' action.`);if(d.can.includes(vr.Delete)&&!d.can.includes(vr.Create))throw new ne(re.ProtocolsConfigureInvalidActionDeleteWithoutCreate,`Action rule ${JSON.stringify(d)} contains 'delete' action but missing the required 'create' action.`);if(d.can.includes(vr.Prune)&&!d.can.includes(vr.Create))throw new ne(re.ProtocolsConfigureInvalidActionPruneWithoutCreate,`Action rule ${JSON.stringify(d)} contains 'prune' action but missing the required 'create' action.`)}for(let u=l+1;u<c.length;u++){let f=c[u];if(d.who===void 0){if(d.role===f.role)throw new ne(re.ProtocolsConfigureDuplicateRoleInRuleSet,`More than one action rule per role ${d.role} not allowed within a rule set: ${JSON.stringify(d)}`)}else if(d.who===f.who&&d.of===f.of)throw new ne(re.ProtocolsConfigureDuplicateActorInRuleSet,`More than one action rule per actor ${d.who} of ${d.of} not allowed within a rule set: ${JSON.stringify(d)}`)}}if(n!==""){let l=n.split("/").pop();o[l]?.encryptionRequired===!0&&c.some(f=>f.who===Bc.Anyone&&f.can.includes(vr.Read))&&console.warn(`ProtocolsConfigure: type '${l}' at path '${n}' has encryptionRequired: true but allows { who: 'anyone', can: ['read'] }. Anyone can read the record but no one outside the key holders can decrypt it.`)}t.$delivery!==void 0&&(t.$actions===void 0||t.$actions.length===0)&&console.warn(`ProtocolsConfigure: protocol path '${n}' has $delivery: '${t.$delivery}' but no $actions rules. The server uses $actions to determine delivery targets \u2014 without $actions, no participants can be resolved for delivery.`),t.$immutable===!0&&c.length>0&&c.some(d=>d.can.includes(vr.Update)||d.can.includes(vr.CoUpdate))&&console.warn(`ProtocolsConfigure: protocol path '${n}' has $immutable: true but $actions include 'update' or 'co-update'. The $immutable directive takes precedence \u2014 updates will always be rejected regardless of action rules.`);for(let l in t){if(l.startsWith("$"))continue;let d=t[l];if(d.$ref===void 0&&!i.includes(l))throw new ne(re.ProtocolsConfigureInvalidRuleSetRecordType,`Rule set ${l} is not declared as an allowed type in the protocol definition.`);let u;n===""?u=l:u=`${n}/${l}`,r.validateRuleSetRecursively({ruleSet:d,ruleSetProtocolPath:u,recordTypes:i,roles:a,uses:s,types:o})}}static validateRefNode(e,t,n){let i=e.$ref,a=Hs(i);if(a===void 0)throw new ne(re.ProtocolsConfigureInvalidRefAlias,`'$ref' value '${i}' at protocol path '${t}' must be in 'alias:typePath' format.`);if(n?.[a.alias]===void 0)throw new ne(re.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${a.alias}' at protocol path '${t}' does not exist in the 'uses' map.`);let s=["$actions","$role","$size","$tags","$encryption","$recordLimit","$immutable","$delivery","$squash"];for(let o of s)if(e[o]!==void 0)throw new ne(re.ProtocolsConfigureInvalidRefNodeHasDirectives,`'$ref' node at protocol path '${t}' must not have '${o}'. $ref nodes are pure attachment points \u2014 directives belong on child rule sets.`)}static validateCrossProtocolAlias(e,t,n,i){let a=Hs(e);if(a===void 0){let s=i==="role"?re.ProtocolsConfigureInvalidCrossProtocolRole:re.ProtocolsConfigureInvalidCrossProtocolOf;throw new ne(s,`cross-protocol '${i}' reference '${e}' at protocol path '${n}' could not be parsed as a valid 'alias:path' format.`)}if(t?.[a.alias]===void 0){let s=i==="role"?re.ProtocolsConfigureInvalidCrossProtocolRole:re.ProtocolsConfigureInvalidCrossProtocolOf;throw new ne(s,`cross-protocol '${i}' alias '${a.alias}' in '${e}' at protocol path '${n}' does not exist in the 'uses' map.`)}}static normalizeDefinition(e){let t={};for(let i in e.types)t[i]={...e.types[i]};for(let i in t){let a=t[i].schema;a!==void 0&&(t[i].schema=Tp(a))}let n;if(e.uses!==void 0){n={};for(let i in e.uses)try{n[i]=js(e.uses[i])}catch{n[i]=e.uses[i]}}return{...e,protocol:js(e.protocol),types:t,...n!==void 0&&{uses:n}}}}});var l2,$9=G(()=>{"use strict";g();qo();yr();zo();Fo();d2();a2();vt();ar();nh();l2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await Sa.parse(t)}catch(d){return mt(d,400)}try{await mn(t.authorization,this.deps.didResolver),await r.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(d){return mt(d,401)}try{await r.validateCompositionDependencies(e,t.descriptor.definition,this.deps.messageStore)}catch(d){return mt(d,400)}let i={interface:ve.Protocols,method:me.Configure,protocol:t.descriptor.definition.protocol},{messages:a}=await this.deps.messageStore.query(e,[i]),s=await ye.getCid(t);for(let d of a)if(await ye.getCid(d)===s)return{status:{code:409,detail:"Conflict"}};let o=await ye.getNewestMessage(a),c=!1;(o===void 0||await ye.isNewer(t,o))&&(c=!0,o=t);let l;if(c){let d=r.constructIndexes(n,!0);await this.deps.messageStore.put(e,t,d);let u=await ye.getCid(t);await this.deps.stateIndex.insert(e,u,d),this.deps.eventLog!==void 0&&await this.deps.eventLog.emit(e,{message:t},d,u),l={status:{code:202,detail:"Accepted"}}}else{let d=r.constructIndexes(n,!1);await this.deps.messageStore.put(e,t,d);let u=await ye.getCid(t);await this.deps.stateIndex.insert(e,u,d),l={status:{code:202,detail:"Accepted"}}}for(let d of a)if(d!==o){let u=await Sa.parse(d),f=r.constructIndexes(u,!1),p=await ye.getCid(d);await this.deps.messageStore.delete(e,p),await this.deps.messageStore.put(e,d,f)}return l}static constructIndexes(e,t){let{definition:n,...i}=e.message.descriptor,{author:a}=e;return{...i,author:a,protocol:n.protocol,published:n.published,isLatestBaseState:t}}static async authorizeProtocolsConfigure(e,t,n){if(t.isSignedByAuthorDelegate&&await t.authorizeAuthorDelegate(n),t.author!==e)if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let i=await et.fetchGrant(e,n,t.signaturePayload.permissionGrantId);await of.authorizeConfigure({protocolsConfigureMessage:t.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:i,messageStore:n})}else throw new ne(re.ProtocolsConfigureAuthorizationFailed,"message failed authorization")}static async validateCompositionDependencies(e,t,n){let{uses:i}=t;if(i===void 0)return;let a=new Map;for(let s in i){let o=i[s],c=await r.fetchInstalledProtocolDefinition(e,o,n);if(c===void 0)throw new ne(re.ProtocolsConfigureComposedProtocolNotInstalled,`composed protocol '${o}' (alias '${s}') is not installed for tenant '${e}'.`);a.set(s,c)}r.validateRefsAndRolesRecursively(t.structure,"",a)}static async fetchInstalledProtocolDefinition(e,t,n){let i={interface:ve.Protocols,method:me.Configure,protocol:t,isLatestBaseState:!0},{messages:a}=await n.query(e,[i]);if(a.length!==0)return a[0].descriptor.definition}static validateRefsAndRolesRecursively(e,t,n){for(let i in e){if(i.startsWith("$"))continue;let a=e[i],s=t===""?i:`${t}/${i}`;if(a.$ref!==void 0){let c=Hs(a.$ref);if(c!==void 0){let l=n.get(c.alias);if(l===void 0)throw new ne(re.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${c.alias}' at protocol path '${s}' was not found in the referenced definitions map.`);let d=c.protocolPath.split("/"),u=l.structure;for(let f=0;f<d.length;f++){let p=d[f],h=u[p];if(h===void 0)throw new ne(re.ProtocolsConfigureInvalidRefProtocolPath,`'$ref' at protocol path '${s}' references type path '${c.protocolPath}' which does not exist in protocol '${l.protocol}'.`);if(h.$ref!==void 0){let m=d.slice(0,f+1).join("/");throw new ne(re.ProtocolsConfigureInvalidRefTargetThroughRef,`'$ref' at protocol path '${s}' references type path '${c.protocolPath}' in protocol '${l.protocol}', but the node '${m}' is itself a '$ref' composition point. multi-level composition (chaining through '$ref' nodes) is not supported.`)}u=h}}}let o=a.$actions??[];for(let c of o){if(c.role!==void 0){let l=Hs(c.role);if(l!==void 0){let d=n.get(l.alias);if(d===void 0)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role alias '${l.alias}' in '${c.role}' at protocol path '${s}' was not found in the referenced definitions map.`);if(!kd(l.protocolPath,d.structure)?.$role)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role '${c.role}' at protocol path '${s}' does not point to a valid role ($role: true) in protocol '${d.protocol}'.`)}}if(c.of!==void 0){let l=Hs(c.of);if(l!==void 0){let d=n.get(l.alias);if(d===void 0)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' alias '${l.alias}' in '${c.of}' at protocol path '${s}' was not found in the referenced definitions map.`);if(kd(l.protocolPath,d.structure)===void 0)throw new ne(re.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' reference '${c.of}' at protocol path '${s}' does not point to a valid type path in protocol '${d.protocol}'.`)}}}r.validateRefsAndRolesRecursively(a,s,n)}}}});var ka,u2=G(()=>{"use strict";g();xc();yr();Fo();a2();st();qs();vt();ar();ma();ka=class r extends Bn{static async parse(e){return e.authorization!==void 0&&await ye.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&di(e.descriptor.filter.protocol),_t.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:ve.Protocols,method:me.Query,messageTimestamp:e.messageTimestamp??_t.getCurrentTimestamp(),filter:e.filter?r.normalizeFilter(e.filter):void 0,permissionGrantId:e.permissionGrantId};Wt(t);let n;e.signer!==void 0&&(n=await ye.createAuthorization({descriptor:t,signer:e.signer,permissionGrantId:e.permissionGrantId}));let i={descriptor:t,authorization:n};return ye.validateJsonSchema(i),new r(i)}static normalizeFilter(e){return{...e,protocol:js(e.protocol)}}async authorize(e,t){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await et.fetchGrant(e,t,this.signaturePayload.permissionGrantId);await of.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:t})}else throw new ne(re.ProtocolsQueryUnauthorized,"The ProtocolsQuery failed authorization")}}});var f2,B9=G(()=>{"use strict";g();qo();vt();zo();u2();st();ar();f2=class{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await ka.parse(t)}catch(s){return mt(s,400)}try{await mn(t.authorization,this.deps.didResolver),await n.authorize(e,this.deps.messageStore)}catch(s){if(s.code===re.AuthenticateJwsMissing||s.code===re.ProtocolsQueryUnauthorized||s.code===re.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch){let o=await this.fetchPublishedProtocolsConfigure(e,n);return{status:{code:200,detail:"OK"},entries:o}}else return mt(s,401)}let i={...t.descriptor.filter,interface:ve.Protocols,method:me.Configure,isLatestBaseState:!0};Wt(i);let{messages:a}=await this.deps.messageStore.query(e,[i]);return{status:{code:200,detail:"OK"},entries:a}}async fetchPublishedProtocolsConfigure(e,t){let n={...t.message.descriptor.filter,interface:ve.Protocols,method:me.Configure,published:!0,isLatestBaseState:!0},{messages:i}=await this.deps.messageStore.query(e,[n]);return i}}});async function S0(r,e,t,n,i,a,s,o){let c=e.signaturePayload?.protocolRole;if(c===void 0)return;let l=t,d=c;if(af(c)){let h=Hs(c);if(h===void 0)throw new ne(re.ProtocolAuthorizationNotARole,`Cross-protocol role '${c}' could not be parsed as a valid 'alias:path' format.`);if(i.uses?.[h.alias]===void 0)throw new ne(re.ProtocolAuthorizationNotARole,`Cross-protocol role alias '${h.alias}' in '${c}' does not exist in the protocol's 'uses' map.`);l=i.uses[h.alias],d=h.protocolPath;let m=await s(r,l,a,o);if(!kd(d,m.structure)?.$role)throw new ne(re.ProtocolAuthorizationNotARole,`Cross-protocol role path ${c} does not match role record type.`)}else if(!kd(c,i.structure)?.$role)throw new ne(re.ProtocolAuthorizationNotARole,`Protocol path ${c} does not match role record type.`);let u={interface:ve.Records,method:me.Write,protocol:l,protocolPath:d,recipient:e.author,isLatestBaseState:!0},f=d.split("/").length-1;if(n===void 0&&f>0)throw new ne(re.ProtocolAuthorizationMissingContextId,"Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=Xt.constructPrefixFilterAsRangeFilter(m);u.contextId=y}let{messages:p}=await a.query(r,[u]);if(p.length===0)throw new ne(re.ProtocolAuthorizationMatchingRoleRecordNotFound,`No matching role record found for protocol path ${d}`)}async function Ide(r,e,t){switch(e.message.descriptor.method){case me.Delete:let n=e,i=n.message.descriptor.recordId,a=await Pt.fetchInitialRecordsWrite(t,r,i);if(a===void 0)return[];let s=[];return n.message.descriptor.prune?(s.push(vr.CoPrune),e.author===a.author&&s.push(vr.Prune)):(s.push(vr.CoDelete),e.author===a.author&&s.push(vr.Delete)),s;case me.Count:return[vr.Read];case me.Query:return[vr.Read];case me.Read:return[vr.Read];case me.Subscribe:return[vr.Read];case me.Write:let c=e;if(await c.isInitialWrite())return c.message.descriptor.squash===!0?[vr.Squash,vr.Create]:[vr.Create];{let l=e.message.recordId,d=await Pt.fetchInitialRecordsWrite(t,r,l);return d===void 0?[]:e.author===d.author?[vr.CoUpdate,vr.Update]:[vr.CoUpdate]}}return[]}async function k0(r,e,t,n,i,a){let s=e.message.descriptor.method,o=await Ide(r,e,i),c=e.author,l=t.$actions;if(l===void 0)throw new ne(re.ProtocolAuthorizationActionRulesNotFound,`no action rule defined for Records${s}, ${c} is unauthorized`);let d=e.signaturePayload?.protocolRole;for(let u of l){if(!u.can.some(h=>o.includes(h)))continue;if(u.who===Bc.Anyone)return;if(c===void 0)continue;if(d!==void 0){if(u.role===d)return;continue}if(u.who===Bc.Recipient&&u.of===void 0){let h;if(e.message.descriptor.method===me.Write?h=e.message:h=n[n.length-1],h.descriptor.recipient===c)return;continue}if(await Dde(c,u,n,a))return}throw new ne(re.ProtocolAuthorizationActionNotAllowed,`Inbound message action Records${s} by author ${e.author} not allowed.`)}async function Dde(r,e,t,n){let i=e.of;if(i===void 0)return!1;let a;if(af(i)&&n?.uses!==void 0){let s=Hs(i);if(s!==void 0){let o=n.uses[s.alias];o!==void 0&&(a=t.find(c=>c.descriptor.protocol===o&&c.descriptor.protocolPath===s.protocolPath))}}else a=t.find(s=>s.descriptor.protocolPath===i);if(a===void 0)return!1;if(e.who===Bc.Recipient)return r===a.descriptor.recipient;{let s=(await Pt.parse(a)).author;return r===s}}var O9=G(()=>{"use strict";g();gc();zs();vt();ar();nh();Lg()});async function Ky(r,e,t){let n={interface:ve.Records,method:me.Write,recordId:e},{messages:i}=await t.query(r,[n]);return i.length===0?void 0:await Pt.getInitialWrite(i)}async function _0(r,e,t){if(e===void 0)return[];let n=[],i=e;for(;i!==void 0;){let a=await Ky(r,i,t);if(a===void 0)throw new ne(re.ProtocolAuthorizationParentNotFoundConstructingRecordChain,`Unexpected error that should never trigger: no parent found with ID ${i} when constructing record chain.`);n.push(a),i=a.descriptor.parentId}return n.reverse()}async function YR(r,e,t){let n=await Ky(r,e.message.recordId,t);if(n!==void 0)return n.descriptor.messageTimestamp}var j9=G(()=>{"use strict";g();zs();vt();ar()});async function K9(r,e,t,n,i){let a=e.message.descriptor.protocolPath,s=c2(a),o=e.message.descriptor.parentId;if(o===void 0){if(a!==s)throw new ne(re.ProtocolAuthorizationParentlessIncorrectProtocolPath,`Declared protocol path '${a}' is not valid for records with no parent'.`);return}let c=e.message.descriptor.protocol,l=await Rde(r,c,a,t,n,i),d={isLatestBaseState:!0,interface:ve.Records,method:me.Write,protocol:l,recordId:o},{messages:u}=await t.query(r,[d]),f=u[0];if(f===void 0)throw l!==c?new ne(re.ProtocolAuthorizationCrossProtocolParentNotFound,`Could not find parent record '${o}' in protocol '${l}' for cross-protocol child at path '${a}'.`):new ne(re.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${a}'.`);if(`${f.descriptor.protocolPath}/${s}`!==a)throw new ne(re.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${a}'.`);let m=`${f.contextId}/${e.message.recordId}`,y=e.message.contextId;if(y!==m)throw new ne(re.ProtocolAuthorizationIncorrectContextId,`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function Rde(r,e,t,n,i,a){let s=t.split("/");if(s.length<=1)return e;let o=await i(r,e,n,a),c=o.structure[s[0]];if(c?.$ref!==void 0){let l=Hs(c.$ref);if(l!==void 0&&o.uses!==void 0){let d=o.uses[l.alias];if(d!==void 0)return s.length===2?d:e}}return e}async function U9(r,e,t,n,i,a){let s=e.descriptor.protocolPath,o=c2(s),c=await Cde(r,s,t,n,i,a);$de(e,c,o)}async function Cde(r,e,t,n,i,a){let s=e.split("/"),o=t.structure[s[0]];if(o?.$ref!==void 0&&s.length===1){let c=Hs(o.$ref);if(c!==void 0&&t.uses!==void 0){let l=t.uses[c.alias];if(l!==void 0)return(await i(r,l,n,a)).types}}return t.types}function $de(r,e,t){let n=t??c2(r.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new ne(re.ProtocolAuthorizationInvalidType,`record with type ${n} not allowed in protocol`);let a=e[n],{schema:s}=r.descriptor;if(a.schema!==void 0&&a.schema!==s)throw new ne(re.ProtocolAuthorizationInvalidSchema,`type '${n}' must have schema '${a.schema}', instead has '${s}'`);let{dataFormat:o}=r.descriptor;if(a.dataFormats!==void 0&&!a.dataFormats.includes(o))throw new ne(re.ProtocolAuthorizationIncorrectDataFormat,`type '${n}' must have data format in (${a.dataFormats}), instead has '${o}'`);if(a.encryptionRequired===!0&&r.encryption===void 0)throw new ne(re.ProtocolAuthorizationEncryptionRequired,`type '${n}' requires encryption but message has no encryption metadata`)}function N9(r,e){let{min:t=0,max:n}=e.$size||{},i=r.message.descriptor.dataSize;if(i<t)throw new ne(re.ProtocolAuthorizationMinSizeInvalid,`data size ${i} is less than allowed ${t}`);if(n!==void 0&&i>n)throw new ne(re.ProtocolAuthorizationMaxSizeInvalid,`data size ${i} is more than allowed ${n}`)}function L9(r,e){if(e.$tags!==void 0){let{tags:t={},protocol:n,protocolPath:i}=r.message.descriptor,{$allowUndefinedTags:a,$requiredTags:s,...o}=e.$tags,c=a||!1,l=s||[],d=new M9.default.default,u=d.compile({type:"object",properties:o,required:l,additionalProperties:c});if(!u(t)){let p=d.errorsText(u.errors,{dataVar:`${n}/${i}/$tags`});throw new ne(re.ProtocolAuthorizationTagsInvalidSchema,`tags schema validation error: ${p}`)}}}async function q9(r,e,t,n){if(!t.$role)return;let i=e,a=i.message.descriptor.recipient;if(a===void 0)throw new ne(re.ProtocolAuthorizationRoleMissingRecipient,"Role records must have a recipient");let s=i.message.descriptor.protocolPath,o={interface:ve.Records,method:me.Write,isLatestBaseState:!0,protocol:i.message.descriptor.protocol,protocolPath:s,recipient:a},c=Ae.getParentContextFromOfContextId(i.message.contextId);if(c!==""){let f=Xt.constructPrefixFilterAsRangeFilter(c);o.contextId=f}let{messages:l}=await n.query(r,[o]);if(l.filter(f=>f.recordId!==i.message.recordId).length>0)throw new ne(re.ProtocolAuthorizationDuplicateRoleRecipient,`DID '${a}' is already recipient of a role record at protocol path '${s} under the parent context ${c}.`)}async function z9(r,e,t,n){if(t.$recordLimit===void 0||!await e.isInitialWrite())return;let{max:a,strategy:s}=t.$recordLimit,o=e.message.descriptor.protocolPath,c={interface:ve.Records,method:me.Write,isLatestBaseState:!0,protocol:e.message.descriptor.protocol,protocolPath:o},l=Ae.getParentContextFromOfContextId(e.message.contextId);if(l!==""){let u=Xt.constructPrefixFilterAsRangeFilter(l);c.contextId=u}if(await n.count(r,[c])>=a)throw s===Zl.Reject?new ne(re.ProtocolAuthorizationRecordLimitExceeded,`record limit of ${a} reached at protocol path '${o}'${l===""?"":` under parent context '${l}'`}: new records are rejected until existing records are deleted.`):new ne(re.ProtocolAuthorizationRecordLimitStrategyNotImplemented,`record limit strategy '${s}' is not yet implemented.`)}async function F9(r,e){if(r.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new ne(re.ProtocolAuthorizationSquashNotEnabled,`squash writes are not enabled at protocol path '${r.message.descriptor.protocolPath}': rule set must have $squash: true.`);if(!await r.isInitialWrite())throw new ne(re.ProtocolAuthorizationSquashNotInitialWrite,"squash write must be an initial write (a new record): updates cannot be squash writes.")}async function G9(r,e){if(!(e.$immutable!==!0||await r.isInitialWrite()))throw new ne(re.ProtocolAuthorizationImmutableRecord,`record at protocol path '${r.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var M9,H9=G(()=>{"use strict";g();Lg();M9=An(ZR(),1);gc();Qn();vt();ar();nh()});var ws,ih=G(()=>{"use strict";g();nh();rd();vt();ar();O9();j9();H9();ws=class r{static async validateReferentialIntegrity(e,t,n,i){let a=await YR(e,t,n),s=await r.fetchProtocolDefinition(e,t.message.descriptor.protocol,n,a,i),o=r.createBoundFetchDefinition(i);await U9(e,t.message,s,n,o,a),await K9(e,t,n,o,a);let c=r.getRuleSet(t.message.descriptor.protocolPath,s);await q9(e,t,c,n),N9(t,c),L9(t,c),await G9(t,c),await F9(t,c),await z9(e,t,c,n)}static async authorizeWrite(e,t,n,i){let a=await Ky(e,t.message.recordId,n),s;a===void 0?s=await _0(e,t.message.descriptor.parentId,n):s=await _0(e,t.message.recordId,n);let o=await YR(e,t,n),c=await r.fetchProtocolDefinition(e,t.message.descriptor.protocol,n,o,i),l=r.getRuleSet(t.message.descriptor.protocolPath,c),d=r.createBoundFetchDefinition(i);await S0(e,t,t.message.descriptor.protocol,t.message.contextId,c,n,d,o),await k0(e,t,l,s,n,c)}static async authorizeRead(e,t,n,i,a){let s=await _0(e,n.message.recordId,i),o=await Ky(e,n.message.recordId,i),c=o===void 0?n.message.descriptor.messageTimestamp:o.descriptor.messageTimestamp,l=await r.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,c,a),d=r.getRuleSet(n.message.descriptor.protocolPath,l),u=r.createBoundFetchDefinition(a);await S0(e,t,n.message.descriptor.protocol,n.message.contextId,l,i,u,c),await k0(e,t,d,s,i,l)}static async authorizeQueryOrSubscribe(e,t,n,i){let{protocol:a,protocolPath:s,contextId:o}=t.message.descriptor.filter,c=await r.fetchProtocolDefinition(e,a,n,void 0,i),l=r.getRuleSet(s,c),d=r.createBoundFetchDefinition(i);await S0(e,t,a,o,c,n,d),await k0(e,t,l,[],n,c)}static async authorizeDelete(e,t,n,i,a){let s=await _0(e,t.message.descriptor.recordId,i),o=await Ky(e,t.message.descriptor.recordId,i),c=o===void 0?n.message.descriptor.messageTimestamp:o.descriptor.messageTimestamp,l=await r.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,c,a),d=r.getRuleSet(n.message.descriptor.protocolPath,l),u=r.createBoundFetchDefinition(a);await S0(e,t,n.message.descriptor.protocol,n.message.contextId,l,i,u,c),await k0(e,t,d,s,i,l)}static async fetchProtocolDefinition(e,t,n,i,a){if(a!==void 0){let l=a.getDefinition(t);if(l!==void 0)return l}let s={interface:ve.Protocols,method:me.Configure,protocol:t};i===void 0?s.isLatestBaseState=!0:s.messageTimestamp={lte:i};let{messages:o}=await n.query(e,[s],{messageTimestamp:At.Descending},{limit:1});if(o.length===0)throw new ne(re.ProtocolAuthorizationProtocolNotFound,`unable to find protocol definition for ${t}`);return o[0].descriptor.definition}static createBoundFetchDefinition(e){return(t,n,i,a)=>r.fetchProtocolDefinition(t,n,i,a,e)}static getRuleSet(e,t){let n=kd(e,t.structure);if(n===void 0)throw new ne(re.ProtocolAuthorizationMissingRuleSet,`No rule set defined for protocolPath ${e}`);return n}}});var p2,V9=G(()=>{"use strict";g();qo();yr();zo();ih();Qn();gx();ar();p2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await yd.parse(t)}catch(a){return mt(a,400)}let i;if(Ae.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)i=await this.countPublishedRecords(e,n);else{try{await mn(t.authorization,this.deps.didResolver),await r.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(a){return mt(a,401)}n.author===e?i=await this.countRecordsAsOwner(e,n):i=await this.countRecordsAsNonOwner(e,n)}return{status:{code:200,detail:"OK"},count:i}}async countRecordsAsOwner(e,t){let{filter:n}=t.message.descriptor,i={...Ae.convertFilter(n),interface:ve.Records,method:me.Write,isLatestBaseState:!0};return this.deps.messageStore.count(e,[i])}async countRecordsAsNonOwner(e,t){let{filter:n}=t.message.descriptor,i=[];return Ae.filterIncludesPublishedRecords(n)&&i.push(r.buildPublishedRecordsFilter(t)),Ae.filterIncludesUnpublishedRecords(n)&&(Ae.shouldBuildUnpublishedAuthorFilter(n,t.author)&&i.push(r.buildUnpublishedRecordsByCountAuthorFilter(t)),Ae.shouldProtocolAuthorize(t.signaturePayload)&&i.push(r.buildUnpublishedProtocolAuthorizedRecordsFilter(t)),Ae.shouldBuildUnpublishedRecipientFilter(n,t.author)&&i.push(r.buildUnpublishedRecordsForCountAuthorFilter(t))),this.deps.messageStore.count(e,i)}async countPublishedRecords(e,t){let n=r.buildPublishedRecordsFilter(t);return this.deps.messageStore.count(e,[n])}static buildPublishedRecordsFilter(e){let{filter:t}=e.message.descriptor;return{...Ae.convertFilter(t),interface:ve.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:t}=e.message.descriptor;return{...Ae.convertFilter(t),interface:ve.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:t}=e.message.descriptor;return{...Ae.convertFilter(t),interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:t}=e.message.descriptor;return{...Ae.convertFilter(t),author:e.author,interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),Ae.shouldProtocolAuthorize(t.signaturePayload)&&await ws.authorizeQueryOrSubscribe(e,t,n,i)}}});var _a,A0=G(()=>{"use strict";g();xc();yr();lc();Qn();id();st();qs();ar();_a=class r extends Bn{static async parse(e){let t;return e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Ae.validateDelegatedGrantReferentialIntegrity(e,t),_t.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t=e.recordId,n=_t.getCurrentTimestamp(),i={interface:ve.Records,method:me.Delete,messageTimestamp:e.messageTimestamp??n,recordId:t,prune:e.prune??!1},a=await ye.createAuthorization({descriptor:i,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),s={descriptor:i,authorization:a};return ye.validateJsonSchema(s),new r(s)}constructIndexes(e){let n={...this.message.descriptor},{protocol:i,protocolPath:a,recipient:s,schema:o,parentId:c,dateCreated:l}=e.descriptor,d={isLatestBaseState:!0,protocol:i,protocolPath:a,recipient:s,schema:o,parentId:c,dateCreated:l,contextId:e.contextId,author:this.author,...n};return Wt(d),d}async authorizeDelegate(e,t){let n=kr.parse(this.message.authorization.authorDelegatedGrant);await Un.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:t})}}});var cf,h2,m2=G(()=>{"use strict";g();(function(r){r.RecordsDelete="RecordsDelete",r.RecordsSquash="RecordsSquash"})(cf||(cf={}));h2=class r{resumableTaskStore;static timeoutExtensionFrequencyInSeconds=30;resumableTaskBatchSize=100;resumableTaskHandlers;constructor(e,t){this.resumableTaskStore=e,this.resumableTaskHandlers={[cf.RecordsDelete]:async n=>await t.performRecordsDelete(n),[cf.RecordsSquash]:async n=>await t.performRecordsSquash(n)}}async run(e){let t=r.timeoutExtensionFrequencyInSeconds*2,n=await this.resumableTaskStore.register(e,t);await this.runWithAutomaticTimeoutExtension(n)}async runWithAutomaticTimeoutExtension(e){let t=r.timeoutExtensionFrequencyInSeconds*2,n;try{n=setInterval(()=>{this.resumableTaskStore.extend(e.id,t)},r.timeoutExtensionFrequencyInSeconds*1e3);let i=this.resumableTaskHandlers[e.task.name];await i(e.task.data),await this.resumableTaskStore.delete(e.id)}finally{r.clearTimeoutExtensionTimer(n)}}static clearTimeoutExtensionTimer(e){clearInterval(e)}async resumeTasksAndWaitForCompletion(){for(;;){let e=await this.resumableTaskStore.grab(this.resumableTaskBatchSize);if(e===void 0||e.length===0)break;await this.retryTasksUntilCompletion(e)}}async retryTasksUntilCompletion(e){let t=e;for(;t.length>0;){let n=t;t=[];for(let i of n)try{await this.runWithAutomaticTimeoutExtension(i)}catch(a){console.error("Error while running resumable task:",a),console.error("Resumable task:",i),t.push(i)}}}}});var y2,W9=G(()=>{"use strict";g();qo();ar();yr();zo();Fo();ih();Qn();A0();id();zs();m2();y2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await _a.parse(t)}catch(l){return mt(l,400)}try{await mn(t.authorization,this.deps.didResolver)}catch(l){return mt(l,401)}let i={interface:ve.Records,recordId:t.descriptor.recordId},{messages:a}=await this.deps.messageStore.query(e,[i]),s=await ye.getNewestMessage(a);if(!Ae.canPerformDeleteAgainstRecord(t,s))return{status:{code:404,detail:"Not Found"}};if(!await ye.isNewer(t,s))return{status:{code:409,detail:"Conflict"}};try{let l=await Pt.fetchInitialRecordsWrite(this.deps.messageStore,e,t.descriptor.recordId);await r.authorizeRecordsDelete(e,n,l,this.deps.messageStore,this.deps.coreProtocols)}catch(l){return mt(l,401)}return await this.deps.resumableTaskManager.run({name:cf.RecordsDelete,data:{tenant:e,message:t}}),{status:{code:202,detail:"Accepted"}}}static async authorizeRecordsDelete(e,t,n,i,a){if(ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n.message,i),t.author!==e)if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let s=await et.fetchGrant(e,i,t.signaturePayload.permissionGrantId);await Un.authorizeDelete({recordsDeleteMessage:t.message,recordsWriteToDelete:n.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:s,messageStore:i})}else await ws.authorizeDelete(e,t,n,i,a)}}});var g2,J9=G(()=>{"use strict";g();qo();Pp();yr();zo();ih();Qn();wx();zs();rd();ar();g2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await wa.parse(t)}catch(s){return mt(s,400)}let i,a;if(Ae.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0){let s=await this.fetchPublishedRecords(e,n);i=s.messages,a=s.cursor}else{try{await mn(t.authorization,this.deps.didResolver),await r.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(s){return mt(s,401)}if(n.author===e){let s=await this.fetchRecordsAsOwner(e,n);i=s.messages,a=s.cursor}else{let s=await this.fetchRecordsAsNonOwner(e,n);i=s.messages,a=s.cursor}}for(let s of i)if(!await Pt.isInitialWrite(s)){let c=(await this.deps.messageStore.query(e,[{recordId:s.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete c.encodedData,s.initialWrite=c}return{status:{code:200,detail:"OK"},entries:i,cursor:a}}convertDateSort(e){switch(e){case Ot.CreatedAscending:return{dateCreated:At.Ascending};case Ot.CreatedDescending:return{dateCreated:At.Descending};case Ot.PublishedAscending:return{datePublished:At.Ascending};case Ot.PublishedDescending:return{datePublished:At.Descending};case Ot.UpdatedAscending:return{messageTimestamp:At.Ascending};case Ot.UpdatedDescending:return{messageTimestamp:At.Descending};default:return{dateCreated:At.Ascending}}}async fetchRecordsAsOwner(e,t){let{dateSort:n,filter:i,pagination:a}=t.message.descriptor,s={...Ae.convertFilter(i,n),interface:ve.Records,method:me.Write,isLatestBaseState:!0},o=this.convertDateSort(n);return this.deps.messageStore.query(e,[s],o,a)}async fetchRecordsAsNonOwner(e,t){let{dateSort:n,pagination:i,filter:a}=t.message.descriptor,s=[];Ae.filterIncludesPublishedRecords(a)&&s.push(r.buildPublishedRecordsFilter(t)),Ae.filterIncludesUnpublishedRecords(a)&&(Ae.shouldBuildUnpublishedAuthorFilter(a,t.author)&&s.push(r.buildUnpublishedRecordsByQueryAuthorFilter(t)),Ae.shouldProtocolAuthorize(t.signaturePayload)&&s.push(r.buildUnpublishedProtocolAuthorizedRecordsFilter(t)),Ae.shouldBuildUnpublishedRecipientFilter(a,t.author)&&s.push(r.buildUnpublishedRecordsForQueryAuthorFilter(t)));let o=this.convertDateSort(n);return this.deps.messageStore.query(e,s,o,i)}async fetchPublishedRecords(e,t){let{dateSort:n,pagination:i}=t.message.descriptor,a=r.buildPublishedRecordsFilter(t),s=this.convertDateSort(n);return this.deps.messageStore.query(e,[a],s,i)}static buildPublishedRecordsFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ae.convertFilter(n,t),interface:ve.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ae.convertFilter(n,t),interface:ve.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ae.convertFilter(n,t),interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ae.convertFilter(n,t),author:e.author,interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),Ae.shouldProtocolAuthorize(t.signaturePayload)&&await ws.authorizeQueryOrSubscribe(e,t,n,i)}}});var _d,XR=G(()=>{"use strict";g();xc();Pp();yr();lc();Qn();id();st();qs();vt();ar();_d=class r extends Bn{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort===Ot.PublishedAscending||e.descriptor.dateSort===Ot.PublishedDescending))throw new ne(re.RecordsReadParseFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let t;return e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Ae.validateDelegatedGrantReferentialIntegrity(e,t),_t.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let{filter:t,signer:n,permissionGrantId:i,protocolRole:a,dateSort:s}=e,o=_t.getCurrentTimestamp();if(e.filter.published===!1&&(s===Ot.PublishedAscending||s===Ot.PublishedDescending))throw new ne(re.RecordsReadCreateFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${s}`);let c={interface:ve.Records,method:me.Read,filter:Ae.normalizeFilter(t),messageTimestamp:e.messageTimestamp??o,permissionGrantId:i,dateSort:s};Wt(c);let l;n!==void 0&&(l=await ye.createAuthorization({descriptor:c,signer:n,permissionGrantId:i,protocolRole:a,delegatedGrant:e.delegatedGrant}));let d={descriptor:c,authorization:l};return ye.validateJsonSchema(d),new r(d)}async authorizeDelegate(e,t){let n=kr.parse(this.message.authorization.authorDelegatedGrant);await Un.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:t})}}});var w2,Z9=G(()=>{"use strict";g();qo();wu();Tn();yr();zo();Fo();ih();Qn();id();XR();zs();vt();ar();w2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t}){let n;try{n=await _d.parse(t)}catch(u){return mt(u,400)}try{n.author!==void 0&&await mn(t.authorization,this.deps.didResolver)}catch(u){return mt(u,401)}let i={interface:ve.Records,isLatestBaseState:!0,...Ae.convertFilter(t.descriptor.filter)},a=Ae.convertDateSort(t.descriptor.dateSort),{messages:s}=await this.deps.messageStore.query(e,[i],a,{limit:1});if(s.length===0)return{status:{code:404,detail:"Not Found"}};let o=s[0];if(o.descriptor.method===me.Delete){let u=o,f=u.descriptor.recordId,p=await Pt.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(p===void 0)return mt(new ne(re.RecordsReadInitialWriteNotFound,"initial write for deleted record not found"),400);let h;try{h=await Pt.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{h=p}let m=await Pt.parse(h);try{await r.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return mt(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:u,initialWrite:p}}}let c=o;try{let u=await Pt.parse(c);await r.authorizeRecordsRead(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return mt(u,401)}let l;if(c.encodedData===void 0){let u=await this.deps.dataStore.get(e,c.recordId,c.descriptor.dataCid);if(u?.dataStream===void 0)return{status:{code:410,detail:"Record data not available"},entry:{recordsWrite:c}};l=u.dataStream}else{let u=Ie.base64UrlToBytes(c.encodedData);l=zt.fromBytes(u),delete c.encodedData}let d={status:{code:200,detail:"OK"},entry:{recordsWrite:c,data:l}};if(!await Pt.isInitialWrite(c)){let f=(await this.deps.messageStore.query(e,[{recordId:c.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete f.encodedData,d.entry.initialWrite=f}return d}static async authorizeRecordsRead(e,t,n,i,a){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n.message,i);let{descriptor:s}=n.message;if(t.author!==e){if(s.published===!0)return;if(t.author!==void 0&&(t.author===s.recipient||t.author===n.author))return;if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let o=await et.fetchGrant(e,i,t.signaturePayload.permissionGrantId);await Un.authorizeRead({recordsReadMessage:t.message,recordsWriteMessageToBeRead:n.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:o,messageStore:i})}else await ws.authorizeRead(e,t,n,i,a)}}}});var Aa,v2=G(()=>{"use strict";g();xc();yr();lc();Qn();id();st();qs();vt();ar();ma();Aa=class r extends Bn{static async parse(e){let t;if(e.authorization!==void 0&&(t=await ye.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Ae.validateDelegatedGrantReferentialIntegrity(e,t),t?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ne(re.RecordsSubscribeFilterMissingRequiredProperties,"Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&di(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&nd(e.descriptor.filter.schema),_t.validateTimestamp(e.descriptor.messageTimestamp),new r(e)}static async create(e){let t={interface:ve.Records,method:me.Subscribe,messageTimestamp:e.messageTimestamp??_t.getCurrentTimestamp(),filter:Ae.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};Wt(t);let n=e.signer,i;n&&(i=await ye.createAuthorization({descriptor:t,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:t,authorization:i};return ye.validateJsonSchema(a),new r(a)}async authorizeDelegate(e){let t=kr.parse(this.message.authorization.authorDelegatedGrant);await Un.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:t,messageStore:e})}}});var b2,Y9=G(()=>{"use strict";g();qo();Pp();yr();zo();ih();Qn();v2();zs();rd();vt();ar();b2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return mt(new ne(re.RecordsSubscribeEventLogUnimplemented,"Subscriptions are not supported"),501);let i;try{i=await Aa.parse(t)}catch(f){return mt(f,400)}let a=[],s=[];if(Ae.filterIncludesPublishedRecords(i.message.descriptor.filter)&&i.author===void 0)a=[r.buildPublishedEventFilter(i)],s=[r.buildPublishedQueryFilter(i)],delete t.authorization;else{try{await mn(t.authorization,this.deps.didResolver),await r.authorizeRecordsSubscribe(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return mt(f,401)}i.author===e?(a=r.buildOwnerEventFilters(i),s=r.buildOwnerQueryFilters(i)):(a=r.buildNonOwnerEventFilters(i),s=r.buildNonOwnerQueryFilters(i))}let o=await ye.getCid(t),{cursor:c}=i.message.descriptor;if(c!==void 0)try{let f=await this.deps.eventLog.subscribe(e,o,n,{cursor:c,filters:a});return{status:{code:200,detail:"OK"},subscription:f}}catch(f){if(f instanceof ne&&f.code===re.EventLogProgressGap){let p=f.gapInfo;return{status:{code:410,detail:"Progress token gap"},error:p===void 0?void 0:{code:"ProgressGap",...p}}}return mt(f,500)}let l=await this.deps.eventLog.subscribe(e,o,n,{filters:a}),d,u;try{let{dateSort:f,pagination:p}=i.message.descriptor,h=r.convertDateSort(f),m=await this.deps.messageStore.query(e,s,h,p);d=m.messages,u=m.cursor;for(let y of d)if(!await Pt.isInitialWrite(y)){let w=(await this.deps.messageStore.query(e,[{recordId:y.recordId,isLatestBaseState:!1,method:me.Write}])).messages[0];delete w.encodedData,y.initialWrite=w}}catch(f){return await l.close(),mt(f,500)}return{status:{code:200,detail:"OK"},subscription:l,entries:d,cursor:u}}static convertDateSort(e){switch(e){case Ot.CreatedAscending:return{dateCreated:At.Ascending};case Ot.CreatedDescending:return{dateCreated:At.Descending};case Ot.PublishedAscending:return{datePublished:At.Ascending};case Ot.PublishedDescending:return{datePublished:At.Descending};case Ot.UpdatedAscending:return{messageTimestamp:At.Ascending};case Ot.UpdatedDescending:return{messageTimestamp:At.Descending};default:return{dateCreated:At.Ascending}}}static buildOwnerEventFilters(e){let{filter:t}=e.message.descriptor;return[{...Ae.convertFilter(t),interface:ve.Records,method:[me.Write,me.Delete]}]}static buildNonOwnerEventFilters(e){let t=[],{filter:n}=e.message.descriptor;return Ae.filterIncludesPublishedRecords(n)&&t.push(r.buildPublishedEventFilter(e)),Ae.filterIncludesUnpublishedRecords(n)&&(Ae.shouldBuildUnpublishedAuthorFilter(n,e.author)&&t.push({...Ae.convertFilter(n),author:e.author,interface:ve.Records,method:[me.Write,me.Delete],published:!1}),Ae.shouldProtocolAuthorize(e.signaturePayload)&&t.push({...Ae.convertFilter(n),interface:ve.Records,method:[me.Write,me.Delete],published:!1}),Ae.shouldBuildUnpublishedRecipientFilter(n,e.author)&&t.push({...Ae.convertFilter(n),interface:ve.Records,method:[me.Write,me.Delete],recipient:e.author,published:!1})),t}static buildPublishedEventFilter(e){return{...Ae.convertFilter(e.message.descriptor.filter),interface:ve.Records,method:[me.Write,me.Delete],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:t,filter:n}=e.message.descriptor;return[{...Ae.convertFilter(n,t),interface:ve.Records,method:me.Write,isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let t=[],{dateSort:n,filter:i}=e.message.descriptor;return Ae.filterIncludesPublishedRecords(i)&&t.push(r.buildPublishedQueryFilter(e)),Ae.filterIncludesUnpublishedRecords(i)&&(Ae.shouldBuildUnpublishedAuthorFilter(i,e.author)&&t.push({...Ae.convertFilter(i,n),author:e.author,interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}),Ae.shouldProtocolAuthorize(e.signaturePayload)&&t.push({...Ae.convertFilter(i,n),interface:ve.Records,method:me.Write,isLatestBaseState:!0,published:!1}),Ae.shouldBuildUnpublishedRecipientFilter(i,e.author)&&t.push({...Ae.convertFilter(i,n),interface:ve.Records,method:me.Write,recipient:e.author,isLatestBaseState:!0,published:!1})),t}static buildPublishedQueryFilter(e){let{dateSort:t,filter:n}=e.message.descriptor;return{...Ae.convertFilter(n,t),interface:ve.Records,method:me.Write,published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,t,n,i){ye.isSignedByAuthorDelegate(t.message)&&await t.authorizeDelegate(n),Ae.shouldProtocolAuthorize(t.signaturePayload)&&await ws.authorizeQueryOrSubscribe(e,t,n,i)}}});var Uy,QR=G(()=>{"use strict";g();Py();gc();yr();Qn();A0();zs();ar();Uy=class r{messageStore;dataStore;stateIndex;eventLog;constructor({messageStore:e,dataStore:t,stateIndex:n,eventLog:i}){this.messageStore=e,this.dataStore=t,this.stateIndex=n,this.eventLog=i}async performRecordsDelete({tenant:e,message:t}){let n={interface:ve.Records,recordId:t.descriptor.recordId},{messages:i}=await this.messageStore.query(e,[n]),a=await ye.getNewestMessage(i);if(!Ae.canPerformDeleteAgainstRecord(t,a))return;let s=await _a.parse(t),o=await Pt.getInitialWrite(i),c=s.constructIndexes(o),l=await ye.getCid(t);await this.messageStore.put(e,t,c),await this.stateIndex.insert(e,l,c),this.eventLog!==void 0&&await this.eventLog.emit(e,{message:t,initialWrite:o},c,l),t.descriptor.prune&&await r.purgeRecordDescendants(e,t.descriptor.recordId,this.messageStore,this.dataStore,this.stateIndex),await r.deleteAllOlderMessagesButKeepInitialWrite(e,i,t,this.messageStore,this.dataStore,this.stateIndex)}async performRecordsSquash({tenant:e,message:t}){let{protocol:n,protocolPath:i,messageTimestamp:a}=t.descriptor,s={interface:ve.Records,protocol:n,protocolPath:i},o=Ae.getParentContextFromOfContextId(t.contextId);if(o!==void 0&&o!==""){let d=Xt.constructPrefixFilterAsRangeFilter(o);s.contextId=d}let{messages:c}=await this.messageStore.query(e,[s]),l=new Map;for(let d of c){let u;Ae.isRecordsWrite(d)?u=d.recordId:u=d.descriptor.recordId;let f=l.get(u);f===void 0?l.set(u,[d]):f.push(d)}for(let[d,u]of l){if(d===t.recordId)continue;let f=await ye.getNewestMessage(u);if(f===void 0)continue;f.descriptor.messageTimestamp<a&&await r.purgeRecordMessages(e,u,this.messageStore,this.dataStore,this.stateIndex)}}static async deleteFromDataStoreIfNeeded(e,t,n,i){if(n.descriptor.method!==me.Write)return;let a=n;a.descriptor.dataSize<=co.maxDataSizeAllowedToBeEncoded||a.descriptor.dataCid!==i.descriptor.dataCid&&await e.delete(t,a.recordId,a.descriptor.dataCid)}static async purgeRecordDescendants(e,t,n,i,a){let s={interface:ve.Records,parentId:t},{messages:o}=await n.query(e,[s]),c=new Map;for(let l of o){let d;Ae.isRecordsWrite(l)?d=l.recordId:d=l.descriptor.recordId;let u=c.get(d);u?u.push(l):c.set(d,[l])}for(let l of c.keys())await r.purgeRecordDescendants(e,l,n,i,a);for(let l of c.keys())await r.purgeRecordMessages(e,c.get(l),n,i,a)}static async purgeRecordMessages(e,t,n,i,a){let s=t.filter(l=>l.descriptor.method===me.Write),o=await ye.getNewestMessage(s);await i.delete(e,o.recordId,o.descriptor.dataCid);let c=await Promise.all(t.map(l=>ye.getCid(l)));await a.delete(e,c),await Promise.all(c.map(l=>n.delete(e,l)))}static async deleteAllOlderMessagesButKeepInitialWrite(e,t,n,i,a,s){let o=[];for(let c of t){if(await ye.isOlder(c,n)){await r.deleteFromDataStoreIfNeeded(a,e,c,n);let d=await ye.getCid(c);if(await i.delete(e,d),await Pt.isInitialWrite(c)){let h=await(await Pt.parse(c)).constructIndexes(!1),m=c;delete m.encodedData,await i.put(e,m,h)}else{let f=await ye.getCid(c);o.push(f)}}await s.delete(e,o)}}}});var P2,X9=G(()=>{"use strict";g();qo();fl();wu();Py();Tn();gc();yr();zo();Fo();ih();Qn();id();zs();m2();rd();QR();vt();ar();P2=class r{deps;constructor(e){this.deps=e}async handle({tenant:e,message:t,dataStream:n}){let i;try{i=await Pt.parse(t),await ws.validateReferentialIntegrity(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(h){return mt(h,400)}try{await mn(t.authorization,this.deps.didResolver,t.attestation),await this.authorizeRecordsWrite(e,i,this.deps.messageStore)}catch(h){return mt(h,401)}let a={interface:ve.Records,recordId:t.recordId},{messages:s}=await this.deps.messageStore.query(e,[a]),o=await i.isInitialWrite(),c;if(!o)try{c=await Pt.getInitialWrite(s),Pt.verifyEqualityOfImmutableProperties(c,t)}catch(h){return mt(h,400)}try{await this.enforceSquashBackstop(e,t)}catch(h){return mt(h,409)}let l=await ye.getNewestMessage(s),d=!1,u;if(l===void 0||await ye.isNewer(t,l)?(d=!0,u=t):u=l,!d){let h=!1;if(l!==void 0&&n!==void 0&&await Pt.isInitialWrite(l)){let y=!!l.encodedData,v=this.deps.dataStore?!!await this.deps.dataStore.get(e,i.message.recordId,t.descriptor.dataCid):!1;h=!y&&!v}if(!h)return{status:{code:409,detail:"Conflict"}}}let f=t.descriptor.protocol===void 0?void 0:this.deps.coreProtocols?.get(t.descriptor.protocol);try{if(l?.descriptor.method===me.Delete)throw new ne(re.RecordsWriteNotAllowedAfterDelete,"RecordsWrite is not allowed after a RecordsDelete.");f?.preProcessWrite!==void 0&&await f.preProcessWrite(e,t,this.deps.messageStore);let h=!1,m=t;if(n===void 0){if(!o){let w=l;m=await this.processMessageWithoutDataStream(e,t,w),h=!0}}else m=await this.processMessageWithDataStream(e,t,n),h=!0;let y=await i.constructIndexes(h);await this.deps.messageStore.put(e,m,y);let v=await ye.getCid(t);await this.deps.stateIndex.insert(e,v,y),this.deps.eventLog!==void 0&&h&&await this.deps.eventLog.emit(e,{message:m,initialWrite:c},y,v)}catch(h){if(h instanceof ne&&(h.code===re.RecordsWriteMissingEncodedDataInPrevious||h.code===re.RecordsWriteMissingDataInPrevious||h.code===re.RecordsWriteNotAllowedAfterDelete||h.code===re.RecordsWriteDataCidMismatch||h.code===re.RecordsWriteDataSizeMismatch||h.code.startsWith("SchemaValidator")||this.deps.coreProtocols?.mapErrorToStatusCode(h.code)!==void 0))return mt(h,400);throw h}let p={status:o&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await Uy.deleteAllOlderMessagesButKeepInitialWrite(e,s,u,this.deps.messageStore,this.deps.dataStore,this.deps.stateIndex),t.descriptor.squash===!0&&await this.deps.resumableTaskManager.run({name:cf.RecordsSquash,data:{tenant:e,message:t}}),f?.postProcessWrite!==void 0&&await f.postProcessWrite(e,i,{messageStore:this.deps.messageStore,dataStore:this.deps.dataStore,stateIndex:this.deps.stateIndex}),p}async cloneAndAddEncodedData(e,t){let n={...e};return n.encodedData=Ie.bytesToBase64Url(t),n}async processMessageWithDataStream(e,t,n){let i=t;if(t.descriptor.dataSize<=co.maxDataSizeAllowedToBeEncoded){let a=await zt.toBytes(n),s=await ur.computeDagPbCidFromBytes(a);r.validateDataIntegrity(t.descriptor.dataCid,t.descriptor.dataSize,s,a.length);let o=t.descriptor.protocol===void 0?void 0:this.deps.coreProtocols?.get(t.descriptor.protocol);o?.validateRecord!==void 0&&o.validateRecord(t,a),i=await this.cloneAndAddEncodedData(t,a)}else{let[a,s]=zt.duplicateDataStream(n,2);try{let[o,c]=await Promise.all([ur.computeDagPbCidFromStream(a),this.deps.dataStore.put(e,t.recordId,t.descriptor.dataCid,s)]);r.validateDataIntegrity(t.descriptor.dataCid,t.descriptor.dataSize,o,c.dataSize)}catch(o){throw await this.deps.dataStore.delete(e,t.recordId,t.descriptor.dataCid),o}}return i}async processMessageWithoutDataStream(e,t,n){let i={...t},{dataCid:a,dataSize:s}=t.descriptor;if(r.validateDataIntegrity(a,s,n.descriptor.dataCid,n.descriptor.dataSize),s<=co.maxDataSizeAllowedToBeEncoded){if(n.encodedData===void 0)throw new ne(re.RecordsWriteMissingEncodedDataInPrevious,"No dataStream was provided and unable to get data from previous message");i.encodedData=n.encodedData}else if(await this.deps.dataStore.get(e,n.recordId,t.descriptor.dataCid)===void 0)throw new ne(re.RecordsWriteMissingDataInPrevious,"No dataStream was provided and unable to get data from previous message");return i}static validateDataIntegrity(e,t,n,i){if(e!==n)throw new ne(re.RecordsWriteDataCidMismatch,`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(t!==i)throw new ne(re.RecordsWriteDataSizeMismatch,`actual data size ${i} bytes does not match dataSize in descriptor: ${t}`)}async enforceSquashBackstop(e,t){if(t.descriptor.protocol===void 0||t.descriptor.protocolPath===void 0)return;let n;try{n=await ws.fetchProtocolDefinition(e,t.descriptor.protocol,this.deps.messageStore,void 0,this.deps.coreProtocols)}catch(d){console.warn(`enforceSquashBackstop: failed to fetch protocol definition for '${t.descriptor.protocol}':`,d);return}let i=t.descriptor.protocolPath.split("/"),a=n.structure[i[0]];for(let d=1;d<i.length&&a!==void 0;d++)a=a[i[d]];if(a?.$squash!==!0)return;let s={interface:ve.Records,method:me.Write,isLatestBaseState:!0,protocol:t.descriptor.protocol,protocolPath:t.descriptor.protocolPath,squash:!0},o=Ae.getParentContextFromOfContextId(t.contextId);if(o!==void 0&&o!==""){let d=Xt.constructPrefixFilterAsRangeFilter(o);s.contextId=d}let{messages:c}=await this.deps.messageStore.query(e,[s],{messageTimestamp:At.Descending},{limit:1});if(c.length===0)return;let l=c[0];if(t.descriptor.messageTimestamp<=l.descriptor.messageTimestamp)throw new ne(re.ProtocolAuthorizationSquashBackstop,`incoming message timestamp '${t.descriptor.messageTimestamp}' is not newer than the most recent squash record timestamp '${l.descriptor.messageTimestamp}' at protocol path '${t.descriptor.protocolPath}'.`)}async authorizeRecordsWrite(e,t,n){if(t.owner!==void 0&&t.owner!==e)throw new ne(re.RecordsWriteOwnerAndTenantMismatch,`Owner ${t.owner} must be the same as tenant ${e} when specified.`);if(t.isSignedByAuthorDelegate&&await t.authorizeAuthorDelegate(n),t.isSignedByOwnerDelegate&&await t.authorizeOwnerDelegate(n),t.owner===void 0){if(t.author===e)return;if(t.author!==void 0&&t.signaturePayload.permissionGrantId!==void 0){let i=await et.fetchGrant(e,n,t.signaturePayload.permissionGrantId);await Un.authorizeWrite({recordsWriteMessage:t.message,expectedGrantor:e,expectedGrantee:t.author,permissionGrant:i,messageStore:n})}else await ws.authorizeWrite(e,t,n,this.deps.coreProtocols)}}}});function dle(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 i=0;i<r.length;i++){var a=r.charAt(i),s=a.charCodeAt(0);if(t[s]!==255)throw new TypeError(a+" is ambiguous");t[s]=i}var o=r.length,c=r.charAt(0),l=Math.log(o)/Math.log(256),d=Math.log(256)/Math.log(o);function u(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,y=0,v=0,w=h.length;v!==w&&h[v]===0;)v++,m++;for(var E=(w-v)*d+1>>>0,_=new Uint8Array(E);v!==w;){for(var A=h[v],D=0,M=E-1;(A!==0||D<y)&&M!==-1;M--,D++)A+=256*_[M]>>>0,_[M]=A%o>>>0,A=A/o>>>0;if(A!==0)throw new Error("Non-zero carry");y=D,v++}for(var C=E-y;C!==E&&_[C]===0;)C++;for(var z=c.repeat(m);C<E;++C)z+=r.charAt(_[C]);return z}function f(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var y=0,v=0;h[m]===c;)y++,m++;for(var w=(h.length-m)*l+1>>>0,E=new Uint8Array(w);h[m];){var _=t[h.charCodeAt(m)];if(_===255)return;for(var A=0,D=w-1;(_!==0||A<v)&&D!==-1;D--,A++)_+=o*E[D]>>>0,E[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");v=A,m++}if(h[m]!==" "){for(var M=w-v;M!==w&&E[M]===0;)M++;for(var C=new Uint8Array(y+(w-M)),z=y;M!==w;)C[z++]=E[M++];return C}}}function p(h){var m=f(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:p}}function ble(r){return r.byteOffset!==0||r.byteLength!==r.buffer.byteLength}function Ple(r){return typeof r!="object"||r===null?!1:typeof r[Symbol.asyncIterator]=="function"}function lC(r){let e=Object.prototype.toString.call(r).match(/\s([a-zA-Z0-9]+)/),[t,n]=e;return n}function $z(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Ale;)e[t++]=r&255|rq,r/=128;for(;r&_le;)e[t++]=r&255|rq,r>>>=7;return e[t]=r|0,$z.bytes=t-n+1,e}function uC(r,n){var t=0,n=n||0,i=0,a=n,s,o=r.length;do{if(a>=o)throw uC.bytes=0,new RangeError("Could not decode varint");s=r[a++],t+=i<28?(s&nq)<<i:(s&nq)*Math.pow(2,i),i+=7}while(s>=Ile);return uC.bytes=a-n,t}function Bz(r){Object.keys(r).forEach(e=>{let t=r[e];t===void 0?delete r[e]:t!==null&&typeof t=="object"&&Bz(t)})}function Xle(r){let e=r.trim().toLowerCase();e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1));let t=e.indexOf("%");if(t!==-1&&(e=e.slice(0,t)),e.endsWith(".")&&(e=e.slice(0,-1)),e==="localhost"||e.endsWith(".localhost"))return!0;let n=jz(e);return n!==void 0?Mz(n):e.includes(":")?rue(e):!1}function aq(r,e="URL",t){var n;let i=typeof r=="string"?new URL(r):new URL(r.toString()),a=(n=t?.allowedProtocols)!==null&&n!==void 0?n:Qle;if(!a.includes(i.protocol))throw new R2(`${e} must use one of the allowed schemes (${a.join(", ")}): ${i.protocol}`);if(i.hostname==="")throw new R2(`${e} must specify a hostname.`);if(Xle(i.hostname))throw new R2(`${e} must not target a private, loopback, or link-local host: ${i.hostname}`);return i}function Oz(r,e,t){return Yle(this,void 0,void 0,function*(){var n,i;let a=(n=t?.description)!==null&&n!==void 0?n:"URL",s=(i=t?.maxRedirects)!==null&&i!==void 0?i:eue,o=aq(r,a,{allowedProtocols:t?.allowedProtocols}).href;for(let c=0;c<=s;c++){let l=yield fetch(o,Object.assign(Object.assign({},e),{redirect:"manual"}));if(!tue.has(l.status))return l;let d=l.headers.get("location");if(d===null)return l;o=aq(new URL(d,o),a,{allowedProtocols:t?.allowedProtocols}).href}throw new Error(`${a} exceeded the maximum number of redirects (${s}).`)})}function jz(r){let e=r.split(".");if(e.length!==4)return;let t=e.map(n=>/^\d+$/.test(n)?Number(n):Number.NaN);if(t.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return t}function Mz([r,e]){return r===0||r===10||r===100&&e>=64&&e<=127||r===127||r===169&&e===254||r===172&&e>=16&&e<=31||r===192&&e===168||r>=224}function rue(r){let e=nue(r);if(e===void 0)return!1;let[t,n,i,a,s,o,c,l]=e,d=t===0&&n===0&&i===0&&a===0&&s===0&&o===0;return e.every(u=>u===0)||d&&c===0&&l===1||(t&65024)===64512||(t&65472)===65152||(t&65280)===65280?!0:t===100&&n===65435&&i===0&&a===0&&s===0&&o===0||t===0&&n===0&&i===0&&a===0&&s===0&&o===65535?Mz(sue(c,l)):!!d}function nue(r){let[e,t,n]=r.split("::");if(n!==void 0)return;let i=e===""?[]:e.split(":"),a=t===void 0||t===""?[]:t.split(":"),s=iue([...i,...a]);if(s===void 0||s.length>8||t===void 0&&s.length!==8||t!==void 0&&s.length>=8)return;let o=s.map(l=>/^[0-9a-f]{1,4}$/.test(l)?Number.parseInt(l,16):Number.NaN);if(!o.every(l=>Number.isInteger(l)&&l>=0&&l<=65535))return;if(t===void 0)return o;let c=new Array(8-o.length).fill(0);return[...o.slice(0,i.length),...c,...o.slice(i.length)]}function iue(r){let e=r.at(-1);if(!e?.includes("."))return r;let t=jz(e);if(t===void 0)return;let[n,i,a,s]=t;return[...r.slice(0,-1),((n<<8|i)&65535).toString(16),((a<<8|s)&65535).toString(16)]}function sue(r,e){return[r>>8&255,r&255,e>>8&255,e&255]}function Od(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function yh(r){if(!Od(r))throw new Error("Uint8Array expected");let e="";for(let t=0;t<r.length;t++)e+=aue[r[t]];return e}function Nz(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function jC(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}function cq(r){if(r>=jl._0&&r<=jl._9)return r-jl._0;if(r>=jl._A&&r<=jl._F)return r-(jl._A-10);if(r>=jl._a&&r<=jl._f)return r-(jl._a-10)}function Xy(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let i=0,a=0;i<t;i++,a+=2){let s=cq(r.charCodeAt(a)),o=cq(r.charCodeAt(a+1));if(s===void 0||o===void 0){let c=r[a]+r[a+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+a)}n[i]=s*16+o}return n}function ph(r){return jC(yh(r))}function Sf(r){if(!Od(r))throw new Error("Uint8Array expected");return jC(yh(Uint8Array.from(r).reverse()))}function jd(r,e){return Xy(r.toString(16).padStart(e*2,"0"))}function Qy(r,e){return jd(r,e).reverse()}function cue(r){return Xy(Nz(r))}function Hn(r,e,t){let n;if(typeof e=="string")try{n=Xy(e)}catch(a){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${a}`)}else if(Od(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let i=n.length;if(typeof t=="number"&&i!==t)throw new Error(`${r} expected ${t} bytes, got ${i}`);return n}function gh(...r){let e=0;for(let i=0;i<r.length;i++){let a=r[i];if(!Od(a))throw new Error("Uint8Array expected");e+=a.length}let t=new Uint8Array(e),n=0;for(let i=0;i<r.length;i++){let a=r[i];t.set(a,n),n+=a.length}return t}function due(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function lue(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function uue(r){let e;for(e=0;r>Uz;r>>=fE,e+=1);return e}function fue(r,e){return r>>BigInt(e)&fE}function Lz(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=eC(r),i=eC(r),a=0,s=()=>{n.fill(1),i.fill(0),a=0},o=(...d)=>t(i,n,...d),c=(d=eC())=>{i=o(dq([0]),d),n=o(),d.length!==0&&(i=o(dq([1]),d),n=o())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0,u=[];for(;d<e;){n=o();let f=n.slice();u.push(f),d+=n.length}return gh(...u)};return(d,u)=>{s(),c(d);let f;for(;!(f=u(l()));)c();return s(),f}}function bh(r,e,t={}){let n=(i,a,s)=>{let o=hue[a];if(typeof o!="function")throw new Error(`Invalid validator "${a}", expected function`);let c=r[i];if(!(s&&c===void 0)&&!o(c,r))throw new Error(`Invalid param ${String(i)}=${c} (${typeof c}), expected ${a}`)};for(let[i,a]of Object.entries(e))n(i,a,!1);for(let[i,a]of Object.entries(t))n(i,a,!0);return r}function lq(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`Wrong positive integer: ${r}`)}function mue(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function qz(r,...e){if(!mue(r))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(r.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${r.length}`)}function yue(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");lq(r.outputLen),lq(r.blockLen)}function Q2(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function gue(r,e){qz(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}function zz(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Fz(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function KC(r){if(typeof r=="string"&&(r=Fz(r)),!zz(r))throw new Error(`expected Uint8Array, got ${typeof r}`);return r}function Gz(...r){let e=0;for(let n=0;n<r.length;n++){let i=r[n];if(!zz(i))throw new Error("Uint8Array expected");e+=i.length}let t=new Uint8Array(e);for(let n=0,i=0;n<r.length;n++){let a=r[n];t.set(a,i),i+=a.length}return t}function Vz(r){let e=n=>r().update(KC(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function UC(r=32){if(tC&&typeof tC.getRandomValues=="function")return tC.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function vue(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),a=BigInt(4294967295),s=Number(t>>i&a),o=Number(t&a),c=n?4:0,l=n?0:4;r.setUint32(e+c,s,n),r.setUint32(e+l,o,n)}function Zr(r,e){let t=r%e;return t>=mi?t:e+t}function Zz(r,e,t){if(t<=mi||e<mi)throw new Error("Expected power/modulo > 0");if(t===yn)return mi;let n=yn;for(;e>mi;)e&yn&&(n=n*r%t),r=r*r%t,e>>=yn;return n}function En(r,e,t){let n=r;for(;e-- >mi;)n*=n,n%=t;return n}function hC(r,e){if(r===mi||e<=mi)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=Zr(r,e),n=e,i=mi,a=yn,s=yn,o=mi;for(;t!==mi;){let c=n/t,l=n%t,d=i-s*c,u=a-o*c;n=t,t=l,i=s,a=o,s=d,o=u}if(n!==yn)throw new Error("invert: does not exist");return Zr(i,e)}function _ue(r){let e=(r-yn)/ch,t,n,i;for(t=r-yn,n=0;t%ch===mi;t/=ch,n++);for(i=ch;i<r&&Zz(i,e,r)!==r-yn;i++);if(n===1){let s=(r+yn)/pC;return function(o,c){let l=o.pow(c,s);if(!o.eql(o.sqr(l),c))throw new Error("Cannot find square root");return l}}let a=(t+yn)/ch;return function(s,o){if(s.pow(o,e)===s.neg(s.ONE))throw new Error("Cannot find square root");let c=n,l=s.pow(s.mul(s.ONE,i),t),d=s.pow(o,a),u=s.pow(o,t);for(;!s.eql(u,s.ONE);){if(s.eql(u,s.ZERO))return s.ZERO;let f=1;for(let h=s.sqr(u);f<c&&!s.eql(h,s.ONE);f++)h=s.sqr(h);let p=s.pow(l,yn<<BigInt(c-f-1));l=s.sqr(p),d=s.mul(d,p),u=s.mul(u,l),c=f}return d}}function Aue(r){if(r%pC===Sue){let e=(r+yn)/pC;return function(t,n){let i=t.pow(n,e);if(!t.eql(t.sqr(i),n))throw new Error("Cannot find square root");return i}}if(r%fq===uq){let e=(r-uq)/fq;return function(t,n){let i=t.mul(n,ch),a=t.pow(i,e),s=t.mul(n,a),o=t.mul(t.mul(s,ch),a),c=t.mul(s,t.sub(o,t.ONE));if(!t.eql(t.sqr(c),n))throw new Error("Cannot find square root");return c}}return r%kue,_ue(r)}function Due(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Iue.reduce((n,i)=>(n[i]="function",n),e);return bh(r,t)}function Rue(r,e,t){if(t<mi)throw new Error("Expected power > 0");if(t===mi)return r.ONE;if(t===yn)return e;let n=r.ONE,i=e;for(;t>mi;)t&yn&&(n=r.mul(n,i)),i=r.sqr(i),t>>=yn;return n}function Cue(r,e){let t=new Array(e.length),n=e.reduce((a,s,o)=>r.is0(s)?a:(t[o]=a,r.mul(a,s)),r.ONE),i=r.inv(n);return e.reduceRight((a,s,o)=>r.is0(s)?a:(t[o]=r.mul(a,t[o]),r.mul(a,s)),i),t}function Yz(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function NC(r,e,t=!1,n={}){if(r<=mi)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:i,nByteLength:a}=Yz(r,e);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=Aue(r),o=Object.freeze({ORDER:r,BITS:i,BYTES:a,MASK:MC(i),ZERO:mi,ONE:yn,create:c=>Zr(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return mi<=c&&c<r},is0:c=>c===mi,isOdd:c=>(c&yn)===yn,neg:c=>Zr(-c,r),eql:(c,l)=>c===l,sqr:c=>Zr(c*c,r),add:(c,l)=>Zr(c+l,r),sub:(c,l)=>Zr(c-l,r),mul:(c,l)=>Zr(c*l,r),pow:(c,l)=>Rue(o,c,l),div:(c,l)=>Zr(c*hC(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>hC(c,r),sqrt:n.sqrt||(c=>s(o,c)),invertBatch:c=>Cue(o,c),cmov:(c,l,d)=>d?l:c,toBytes:c=>t?Qy(c,a):jd(c,a),fromBytes:c=>{if(c.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${c.length}`);return t?Sf(c):ph(c)}});return Object.freeze(o)}function $ue(r,e){if(!r.isOdd)throw new Error("Field doesn't have isOdd");let t=r.sqrt(e);return r.isOdd(t)?r.neg(t):t}function Xz(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function Qz(r){let e=Xz(r);return e+Math.ceil(e/2)}function Bue(r,e,t=!1){let n=r.length,i=Xz(e),a=Qz(e);if(n<16||n<a||n>1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);let s=t?ph(r):Sf(r),o=Zr(s,e-yn)+yn;return t?Qy(o,i):jd(o,i)}function e7(r,e){let t=(i,a)=>{let s=a.negate();return i?s:a},n=i=>{let a=Math.ceil(e/i)+1,s=2**(i-1);return{windows:a,windowSize:s}};return{constTimeNegate:t,unsafeLadder(i,a){let s=r.ZERO,o=i;for(;a>Oue;)a&nC&&(s=s.add(o)),o=o.double(),a>>=nC;return s},precomputeWindow(i,a){let{windows:s,windowSize:o}=n(a),c=[],l=i,d=l;for(let u=0;u<s;u++){d=l,c.push(d);for(let f=1;f<o;f++)d=d.add(l),c.push(d);l=d.double()}return c},wNAF(i,a,s){let{windows:o,windowSize:c}=n(i),l=r.ZERO,d=r.BASE,u=BigInt(2**i-1),f=2**i,p=BigInt(i);for(let h=0;h<o;h++){let m=h*c,y=Number(s&u);s>>=p,y>c&&(y-=f,s+=nC);let v=m,w=m+Math.abs(y)-1,E=h%2!==0,_=y<0;y===0?d=d.add(t(E,a[v])):l=l.add(t(_,a[w]))}return{p:l,f:d}},wNAFCached(i,a,s,o){let c=i._WINDOW_SIZE||1,l=a.get(i);return l||(l=this.precomputeWindow(i,c),c!==1&&a.set(i,o(l))),this.wNAF(c,l,s)}}}function LC(r){return Due(r.Fp),bh(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Yz(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}function jue(r){let e=LC(r);bh(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:i}=e;if(t){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}function Uue(r){let e=jue(r),{Fp:t}=e,n=e.toBytes||((h,m,y)=>{let v=m.toAffine();return gh(Uint8Array.from([4]),t.toBytes(v.x),t.toBytes(v.y))}),i=e.fromBytes||(h=>{let m=h.subarray(1),y=t.fromBytes(m.subarray(0,t.BYTES)),v=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:y,y:v}});function a(h){let{a:m,b:y}=e,v=t.sqr(h),w=t.mul(v,h);return t.add(t.add(w,t.mul(h,m)),y)}if(!t.eql(t.sqr(e.Gy),a(e.Gx)))throw new Error("bad generator point: equation left != right");function s(h){return typeof h=="bigint"&&ql<h&&h<e.n}function o(h){if(!s(h))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(h){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:v,n:w}=e;if(m&&typeof h!="bigint"){if(Od(h)&&(h=yh(h)),typeof h!="string"||!m.includes(h.length))throw new Error("Invalid key");h=h.padStart(y*2,"0")}let E;try{E=typeof h=="bigint"?h:ph(Hn("private key",h,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof h}`)}return v&&(E=Zr(E,w)),o(E),E}let l=new Map;function d(h){if(!(h instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(m,y,v){if(this.px=m,this.py=y,this.pz=v,m==null||!t.isValid(m))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(v==null||!t.isValid(v))throw new Error("z required")}static fromAffine(m){let{x:y,y:v}=m||{};if(!m||!t.isValid(y)||!t.isValid(v))throw new Error("invalid affine point");if(m instanceof u)throw new Error("projective point not allowed");let w=E=>t.eql(E,t.ZERO);return w(y)&&w(v)?u.ZERO:new u(y,v,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=t.invertBatch(m.map(v=>v.pz));return m.map((v,w)=>v.toAffine(y[w])).map(u.fromAffine)}static fromHex(m){let y=u.fromAffine(i(Hn("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return u.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not FE");let v=t.sqr(y),w=a(m);if(!t.eql(v,w))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){d(m);let{px:y,py:v,pz:w}=this,{px:E,py:_,pz:A}=m,D=t.eql(t.mul(y,A),t.mul(E,w)),M=t.eql(t.mul(v,A),t.mul(_,w));return D&&M}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,v=t.mul(y,pq),{px:w,py:E,pz:_}=this,A=t.ZERO,D=t.ZERO,M=t.ZERO,C=t.mul(w,w),z=t.mul(E,E),L=t.mul(_,_),B=t.mul(w,E);return B=t.add(B,B),M=t.mul(w,_),M=t.add(M,M),A=t.mul(m,M),D=t.mul(v,L),D=t.add(A,D),A=t.sub(z,D),D=t.add(z,D),D=t.mul(A,D),A=t.mul(B,A),M=t.mul(v,M),L=t.mul(m,L),B=t.sub(C,L),B=t.mul(m,B),B=t.add(B,M),M=t.add(C,C),C=t.add(M,C),C=t.add(C,L),C=t.mul(C,B),D=t.add(D,C),L=t.mul(E,_),L=t.add(L,L),C=t.mul(L,B),A=t.sub(A,C),M=t.mul(L,z),M=t.add(M,M),M=t.add(M,M),new u(A,D,M)}add(m){d(m);let{px:y,py:v,pz:w}=this,{px:E,py:_,pz:A}=m,D=t.ZERO,M=t.ZERO,C=t.ZERO,z=e.a,L=t.mul(e.b,pq),B=t.mul(y,E),W=t.mul(v,_),ee=t.mul(w,A),R=t.add(y,v),$=t.add(E,_);R=t.mul(R,$),$=t.add(B,W),R=t.sub(R,$),$=t.add(y,w);let S=t.add(E,A);return $=t.mul($,S),S=t.add(B,ee),$=t.sub($,S),S=t.add(v,w),D=t.add(_,A),S=t.mul(S,D),D=t.add(W,ee),S=t.sub(S,D),C=t.mul(z,$),D=t.mul(L,ee),C=t.add(D,C),D=t.sub(W,C),C=t.add(W,C),M=t.mul(D,C),W=t.add(B,B),W=t.add(W,B),ee=t.mul(z,ee),$=t.mul(L,$),W=t.add(W,ee),ee=t.sub(B,ee),ee=t.mul(z,ee),$=t.add($,ee),B=t.mul(W,$),M=t.add(M,B),B=t.mul(S,$),D=t.mul(R,D),D=t.sub(D,B),B=t.mul(R,W),C=t.mul(S,C),C=t.add(C,B),new u(D,M,C)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return p.wNAFCached(this,l,m,y=>{let v=t.invertBatch(y.map(w=>w.pz));return y.map((w,E)=>w.toAffine(v[E])).map(u.fromAffine)})}multiplyUnsafe(m){let y=u.ZERO;if(m===ql)return y;if(o(m),m===$a)return this;let{endo:v}=e;if(!v)return p.unsafeLadder(this,m);let{k1neg:w,k1:E,k2neg:_,k2:A}=v.splitScalar(m),D=y,M=y,C=this;for(;E>ql||A>ql;)E&$a&&(D=D.add(C)),A&$a&&(M=M.add(C)),C=C.double(),E>>=$a,A>>=$a;return w&&(D=D.negate()),_&&(M=M.negate()),M=new u(t.mul(M.px,v.beta),M.py,M.pz),D.add(M)}multiply(m){o(m);let y=m,v,w,{endo:E}=e;if(E){let{k1neg:_,k1:A,k2neg:D,k2:M}=E.splitScalar(y),{p:C,f:z}=this.wNAF(A),{p:L,f:B}=this.wNAF(M);C=p.constTimeNegate(_,C),L=p.constTimeNegate(D,L),L=new u(t.mul(L.px,E.beta),L.py,L.pz),v=C.add(L),w=z.add(B)}else{let{p:_,f:A}=this.wNAF(y);v=_,w=A}return u.normalizeZ([v,w])[0]}multiplyAndAddUnsafe(m,y,v){let w=u.BASE,E=(A,D)=>D===ql||D===$a||!A.equals(w)?A.multiplyUnsafe(D):A.multiply(D),_=E(this,y).add(E(m,v));return _.is0()?void 0:_}toAffine(m){let{px:y,py:v,pz:w}=this,E=this.is0();m==null&&(m=E?t.ONE:t.inv(w));let _=t.mul(y,m),A=t.mul(v,m),D=t.mul(w,m);if(E)return{x:t.ZERO,y:t.ZERO};if(!t.eql(D,t.ONE))throw new Error("invZ was invalid");return{x:_,y:A}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===$a)return!0;if(y)return y(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===$a?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return yh(this.toRawBytes(m))}}u.BASE=new u(e.Gx,e.Gy,t.ONE),u.ZERO=new u(t.ZERO,t.ONE,t.ZERO);let f=e.nBitLength,p=e7(u,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:a,isWithinCurveOrder:s}}function Nue(r){let e=LC(r);return bh(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Lue(r){let e=Nue(r),{Fp:t,n}=e,i=t.BYTES+1,a=2*t.BYTES+1;function s($){return ql<$&&$<t.ORDER}function o($){return Zr($,n)}function c($){return hC($,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:d,weierstrassEquation:u,isWithinCurveOrder:f}=Uue({...e,toBytes($,S,x){let P=S.toAffine(),k=t.toBytes(P.x),I=gh;return x?I(Uint8Array.from([S.hasEvenY()?2:3]),k):I(Uint8Array.from([4]),k,t.toBytes(P.y))},fromBytes($){let S=$.length,x=$[0],P=$.subarray(1);if(S===i&&(x===2||x===3)){let k=ph(P);if(!s(k))throw new Error("Point is not on curve");let I=u(k),j=t.sqrt(I),q=(j&$a)===$a;return(x&1)===1!==q&&(j=t.neg(j)),{x:k,y:j}}else if(S===a&&x===4){let k=t.fromBytes(P.subarray(0,t.BYTES)),I=t.fromBytes(P.subarray(t.BYTES,2*t.BYTES));return{x:k,y:I}}else throw new Error(`Point of length ${S} was invalid. Expected ${i} compressed bytes or ${a} uncompressed bytes`)}}),p=$=>yh(jd($,e.nByteLength));function h($){let S=n>>$a;return $>S}function m($){return h($)?o(-$):$}let y=($,S,x)=>ph($.slice(S,x));class v{constructor(S,x,P){this.r=S,this.s=x,this.recovery=P,this.assertValidity()}static fromCompact(S){let x=e.nByteLength;return S=Hn("compactSignature",S,x*2),new v(y(S,0,x),y(S,x,2*x))}static fromDER(S){let{r:x,s:P}=uh.toSig(Hn("DER",S));return new v(x,P)}assertValidity(){if(!f(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!f(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(S){return new v(this.r,this.s,S)}recoverPublicKey(S){let{r:x,s:P,recovery:k}=this,I=M(Hn("msgHash",S));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let j=k===2||k===3?x+e.n:x;if(j>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let q=k&1?"03":"02",H=l.fromHex(q+p(j)),J=c(j),V=o(-I*J),Z=o(P*J),F=l.BASE.multiplyAndAddUnsafe(H,V,Z);if(!F)throw new Error("point at infinify");return F.assertValidity(),F}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Xy(this.toDERHex())}toDERHex(){return uh.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Xy(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let w={isValidPrivateKey($){try{return d($),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let $=Qz(e.n);return Bue(e.randomBytes($),e.n)},precompute($=8,S=l.BASE){return S._setWindowSize($),S.multiply(BigInt(3)),S}};function E($,S=!0){return l.fromPrivateKey($).toRawBytes(S)}function _($){let S=Od($),x=typeof $=="string",P=(S||x)&&$.length;return S?P===i||P===a:x?P===2*i||P===2*a:$ instanceof l}function A($,S,x=!0){if(_($))throw new Error("first arg must be private key");if(!_(S))throw new Error("second arg must be public key");return l.fromHex(S).multiply(d($)).toRawBytes(x)}let D=e.bits2int||function($){let S=ph($),x=$.length*8-e.nBitLength;return x>0?S>>BigInt(x):S},M=e.bits2int_modN||function($){return o(D($))},C=MC(e.nBitLength);function z($){if(typeof $!="bigint")throw new Error("bigint expected");if(!(ql<=$&&$<C))throw new Error(`bigint expected < 2^${e.nBitLength}`);return jd($,e.nByteLength)}function L($,S,x=B){if(["recovered","canonical"].some(ie=>ie in x))throw new Error("sign() legacy options not supported");let{hash:P,randomBytes:k}=e,{lowS:I,prehash:j,extraEntropy:q}=x;I==null&&(I=!0),$=Hn("msgHash",$),j&&($=Hn("prehashed msgHash",P($)));let H=M($),J=d(S),V=[z(J),z(H)];if(q!=null){let ie=q===!0?k(t.BYTES):q;V.push(Hn("extraEntropy",ie))}let Z=gh(...V),F=H;function X(ie){let se=D(ie);if(!f(se))return;let Y=c(se),de=l.BASE.multiply(se).toAffine(),pe=o(de.x);if(pe===ql)return;let le=o(Y*o(F+pe*J));if(le===ql)return;let Se=(de.x===pe?0:2)|Number(de.y&$a),he=le;return I&&h(le)&&(he=m(le),Se^=1),new v(pe,he,Se)}return{seed:Z,k2sig:X}}let B={lowS:e.lowS,prehash:!1},W={lowS:e.lowS,prehash:!1};function ee($,S,x=B){let{seed:P,k2sig:k}=L($,S,x),I=e;return Lz(I.hash.outputLen,I.nByteLength,I.hmac)(P,k)}l.BASE._setWindowSize(8);function R($,S,x,P=W){let k=$;if(S=Hn("msgHash",S),x=Hn("publicKey",x),"strict"in P)throw new Error("options.strict was renamed to lowS");let{lowS:I,prehash:j}=P,q,H;try{if(typeof k=="string"||Od(k))try{q=v.fromDER(k)}catch(Y){if(!(Y instanceof uh.Err))throw Y;q=v.fromCompact(k)}else if(typeof k=="object"&&typeof k.r=="bigint"&&typeof k.s=="bigint"){let{r:Y,s:de}=k;q=new v(Y,de)}else throw new Error("PARSE");H=l.fromHex(x)}catch(Y){if(Y.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(I&&q.hasHighS())return!1;j&&(S=e.hash(S));let{r:J,s:V}=q,Z=M(S),F=c(V),X=o(Z*F),ie=o(J*F),se=l.BASE.multiplyAndAddUnsafe(H,X,ie)?.toAffine();return se?o(se.x)===J:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:A,sign:ee,verify:R,ProjectivePoint:l,Signature:v,utils:w}}function que(r){return{hash:r,hmac:(e,...t)=>r7(r,e,Gz(...t)),randomBytes:UC}}function n7(r,e){let t=n=>Lue({...r,...que(n)});return Object.freeze({...t(e),create:t})}function Fue(r){let e=i7,t=BigInt(3),n=BigInt(6),i=BigInt(11),a=BigInt(22),s=BigInt(23),o=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,u=En(d,t,e)*d%e,f=En(u,t,e)*d%e,p=En(f,mC,e)*l%e,h=En(p,i,e)*p%e,m=En(h,a,e)*h%e,y=En(m,o,e)*m%e,v=En(y,c,e)*y%e,w=En(v,o,e)*m%e,E=En(w,t,e)*d%e,_=En(E,s,e)*h%e,A=En(_,n,e)*l%e,D=En(A,mC,e);if(!yC.eql(yC.sqr(D),r))throw new Error("Cannot find square root");return D}function Gue(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function s7(r,...e){if(!Gue(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function yq(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Hue(r,e){s7(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}function Vue(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function o7(r){return typeof r=="string"&&(r=Vue(r)),s7(r),r}function Jue(r){let e=n=>r().update(o7(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Zue(r=32){if(C2&&typeof C2.getRandomValues=="function")return C2.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Yue(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),a=BigInt(4294967295),s=Number(t>>i&a),o=Number(t&a),c=n?4:0,l=n?0:4;r.setUint32(e+c,s,n),r.setUint32(e+l,o,n)}function nfe(r){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let i=Object.keys(n).sort((s,o)=>s.localeCompare(o)),a={};for(let s of i)a[s]=e(n[s]);return a}return n},t=e(r);return JSON.stringify(t)}function xr(r){return sfe(this,arguments,void 0,function*({jwk:e}){let t=e.kty,n;if(t==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(t==="oct")n={k:e.k,kty:e.kty};else if(t==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(t==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${t}`);Bz(n);let i=nfe(n),a=rt.string(i).toUint8Array(),s=yield a7.digest({data:a});return rt.uint8Array(s).toBase64Url()})}function hh(r){return!(!r||typeof r!="object"||!("kty"in r&&"crv"in r&&"x"in r&&"d"in r)||r.kty!=="EC"||typeof r.d!="string"||typeof r.x!="string")}function qC(r){return!(!r||typeof r!="object"||!("kty"in r&&"crv"in r&&"x"in r)||"d"in r||r.kty!=="EC"||typeof r.x!="string")}function Gl(r){return!(!r||typeof r!="object"||!("kty"in r&&"crv"in r&&"x"in r&&"d"in r)||r.kty!=="OKP"||typeof r.d!="string"||typeof r.x!="string")}function zC(r){return!(!r||typeof r!="object"||"d"in r||!("kty"in r&&"crv"in r&&"x"in r)||r.kty!=="OKP"||typeof r.x!="string")}function ofe(r){if(!r||typeof r!="object")return!1;switch(r.kty){case"EC":case"OKP":case"RSA":return"d"in r;case"oct":return"k"in r;default:return!1}}function d7(r,e=!1){return e?{h:Number(r&E2),l:Number(r>>gC&E2)}:{h:Number(r>>gC&E2)|0,l:Number(r&E2)|0}}function ffe(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let i=0;i<r.length;i++){let{h:a,l:s}=d7(r[i],e);[t[i],n[i]]=[a,s]}return[t,n]}function _fe(r,e,t,n){let i=(e>>>0)+(n>>>0);return{h:r+t+(i/2**32|0)|0,l:i|0}}function Ufe(r){let e=LC(r);return bh(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function FC(r){let e=Ufe(r),{Fp:t,n,prehash:i,hash:a,randomBytes:s,nByteLength:o,h:c}=e,l=S2<<BigInt(o*8)-Go,d=t.create,u=e.uvRatio||((x,P)=>{try{return{isValid:!0,value:t.sqrt(x*t.inv(P))}}catch{return{isValid:!1,value:Ac}}}),f=e.adjustScalarBytes||(x=>x),p=e.domain||((x,P,k)=>{if(P.length||k)throw new Error("Contexts/pre-hash are not supported");return x}),h=x=>typeof x=="bigint"&&Ac<x,m=(x,P)=>h(x)&&h(P)&&x<P,y=x=>x===Ac||m(x,l);function v(x,P){if(m(x,P))return x;throw new Error(`Expected valid scalar < ${P}, got ${typeof x} ${x}`)}function w(x){return x===Ac?x:v(x,n)}let E=new Map;function _(x){if(!(x instanceof A))throw new Error("ExtendedPoint expected")}class A{constructor(P,k,I,j){if(this.ex=P,this.ey=k,this.ez=I,this.et=j,!y(P))throw new Error("x required");if(!y(k))throw new Error("y required");if(!y(I))throw new Error("z required");if(!y(j))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(P){if(P instanceof A)throw new Error("extended point not allowed");let{x:k,y:I}=P||{};if(!y(k)||!y(I))throw new Error("invalid affine point");return new A(k,I,Go,d(k*I))}static normalizeZ(P){let k=t.invertBatch(P.map(I=>I.ez));return P.map((I,j)=>I.toAffine(k[j])).map(A.fromAffine)}_setWindowSize(P){this._WINDOW_SIZE=P,E.delete(this)}assertValidity(){let{a:P,d:k}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:I,ey:j,ez:q,et:H}=this,J=d(I*I),V=d(j*j),Z=d(q*q),F=d(Z*Z),X=d(J*P),ie=d(Z*d(X+V)),se=d(F+d(k*d(J*V)));if(ie!==se)throw new Error("bad point: equation left != right (1)");let Y=d(I*j),de=d(q*H);if(Y!==de)throw new Error("bad point: equation left != right (2)")}equals(P){_(P);let{ex:k,ey:I,ez:j}=this,{ex:q,ey:H,ez:J}=P,V=d(k*J),Z=d(q*j),F=d(I*J),X=d(H*j);return V===Z&&F===X}is0(){return this.equals(A.ZERO)}negate(){return new A(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:P}=e,{ex:k,ey:I,ez:j}=this,q=d(k*k),H=d(I*I),J=d(S2*d(j*j)),V=d(P*q),Z=k+I,F=d(d(Z*Z)-q-H),X=V+H,ie=X-J,se=V-H,Y=d(F*ie),de=d(X*se),pe=d(F*se),le=d(ie*X);return new A(Y,de,le,pe)}add(P){_(P);let{a:k,d:I}=e,{ex:j,ey:q,ez:H,et:J}=this,{ex:V,ey:Z,ez:F,et:X}=P;if(k===BigInt(-1)){let Ys=d((q-j)*(Z+V)),We=d((q+j)*(Z-V)),nr=d(We-Ys);if(nr===Ac)return this.double();let Ur=d(H*S2*X),pr=d(J*S2*F),Lt=pr+Ur,T=We+Ys,U=pr-Ur,N=d(Lt*nr),te=d(T*U),ce=d(Lt*U),ge=d(nr*T);return new A(N,te,ge,ce)}let ie=d(j*V),se=d(q*Z),Y=d(J*I*X),de=d(H*F),pe=d((j+q)*(V+Z)-ie-se),le=de-Y,Se=de+Y,he=d(se-k*ie),Te=d(pe*le),Rt=d(Se*he),ti=d(pe*he),Kr=d(le*Se);return new A(Te,Rt,Kr,ti)}subtract(P){return this.add(P.negate())}wNAF(P){return C.wNAFCached(this,E,P,A.normalizeZ)}multiply(P){let{p:k,f:I}=this.wNAF(v(P,n));return A.normalizeZ([k,I])[0]}multiplyUnsafe(P){let k=w(P);return k===Ac?M:this.equals(M)||k===Go?this:this.equals(D)?this.wNAF(k).p:C.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return C.unsafeLadder(this,n).is0()}toAffine(P){let{ex:k,ey:I,ez:j}=this,q=this.is0();P==null&&(P=q?Mfe:t.inv(j));let H=d(k*P),J=d(I*P),V=d(j*P);if(q)return{x:Ac,y:Go};if(V!==Go)throw new Error("invZ was invalid");return{x:H,y:J}}clearCofactor(){let{h:P}=e;return P===Go?this:this.multiplyUnsafe(P)}static fromHex(P,k=!1){let{d:I,a:j}=e,q=t.BYTES;P=Hn("pointHex",P,q);let H=P.slice(),J=P[q-1];H[q-1]=J&-129;let V=Sf(H);V===Ac||(k?v(V,l):v(V,t.ORDER));let Z=d(V*V),F=d(Z-Go),X=d(I*Z-j),{isValid:ie,value:se}=u(F,X);if(!ie)throw new Error("Point.fromHex: invalid y coordinate");let Y=(se&Go)===Go,de=(J&128)!==0;if(!k&&se===Ac&&de)throw new Error("Point.fromHex: x=0 and x_0=1");return de!==Y&&(se=d(-se)),A.fromAffine({x:se,y:V})}static fromPrivateKey(P){return B(P).point}toRawBytes(){let{x:P,y:k}=this.toAffine(),I=Qy(k,t.BYTES);return I[I.length-1]|=P&Go?128:0,I}toHex(){return yh(this.toRawBytes())}}A.BASE=new A(e.Gx,e.Gy,Go,d(e.Gx*e.Gy)),A.ZERO=new A(Ac,Go,Go,Ac);let{BASE:D,ZERO:M}=A,C=e7(A,o*8);function z(x){return Zr(x,n)}function L(x){return z(Sf(x))}function B(x){let P=o;x=Hn("private key",x,P);let k=Hn("hashed private key",a(x),2*P),I=f(k.slice(0,P)),j=k.slice(P,2*P),q=L(I),H=D.multiply(q),J=H.toRawBytes();return{head:I,prefix:j,scalar:q,point:H,pointBytes:J}}function W(x){return B(x).pointBytes}function ee(x=new Uint8Array,...P){let k=gh(...P);return L(a(p(k,Hn("context",x),!!i)))}function R(x,P,k={}){x=Hn("message",x),i&&(x=i(x));let{prefix:I,scalar:j,pointBytes:q}=B(P),H=ee(k.context,I,x),J=D.multiply(H).toRawBytes(),V=ee(k.context,J,q,x),Z=z(H+V*j);w(Z);let F=gh(J,Qy(Z,t.BYTES));return Hn("result",F,o*2)}let $=Kfe;function S(x,P,k,I=$){let{context:j,zip215:q}=I,H=t.BYTES;x=Hn("signature",x,2*H),P=Hn("message",P),i&&(P=i(P));let J=Sf(x.slice(H,2*H)),V,Z,F;try{V=A.fromHex(k,q),Z=A.fromHex(x.slice(0,H),q),F=D.multiplyUnsafe(J)}catch{return!1}if(!q&&V.isSmallOrder())return!1;let X=ee(j,Z.toRawBytes(),V.toRawBytes(),P);return Z.add(V.multiplyUnsafe(X)).subtract(F).clearCofactor().equals(A.ZERO)}return D._setWindowSize(8),{CURVE:e,getPublicKey:W,sign:R,verify:S,ExtendedPoint:A,utils:{getExtendedPublicKey:B,randomPrivateKey:()=>s(t.BYTES),precompute(x=8,P=A.BASE){return P._setWindowSize(x),P.multiply(BigInt(3)),P}}}}function Nfe(r){return bh(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function Lfe(r){let e=Nfe(r),{P:t}=e,n=E=>Zr(E,t),i=e.montgomeryBits,a=Math.ceil(i/8),s=e.nByteLength,o=e.adjustScalarBytes||(E=>E),c=e.powPminus2||(E=>Zz(E,t-BigInt(2),t));function l(E,_,A){let D=n(E*(_-A));return _=n(_-D),A=n(A+D),[_,A]}function d(E){if(typeof E=="bigint"&&D0<=E&&E<t)return E;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let u=(e.a-BigInt(2))/BigInt(4);function f(E,_){let A=d(E),D=d(_),M=A,C=sC,z=D0,L=A,B=sC,W=D0,ee;for(let $=BigInt(i-1);$>=D0;$--){let S=D>>$&sC;W^=S,ee=l(W,C,L),C=ee[0],L=ee[1],ee=l(W,z,B),z=ee[0],B=ee[1],W=S;let x=C+z,P=n(x*x),k=C-z,I=n(k*k),j=P-I,q=L+B,H=L-B,J=n(H*x),V=n(q*k),Z=J+V,F=J-V;L=n(Z*Z),B=n(M*n(F*F)),C=n(P*I),z=n(j*(P+n(u*j)))}ee=l(W,C,L),C=ee[0],L=ee[1],ee=l(W,z,B),z=ee[0],B=ee[1];let R=c(z);return n(C*R)}function p(E){return Qy(n(E),a)}function h(E){let _=Hn("u coordinate",E,a);return s===32&&(_[31]&=127),Sf(_)}function m(E){let _=Hn("scalar",E),A=_.length;if(A!==a&&A!==s)throw new Error(`Expected ${a} or ${s} bytes, got ${A}`);return Sf(o(_))}function y(E,_){let A=h(_),D=m(E),M=f(A,D);if(M===D0)throw new Error("Invalid private or public key received");return p(M)}let v=p(e.Gu);function w(E){return y(E,v)}return{scalarMult:y,scalarMultBase:w,getSharedSecret:(E,_)=>y(E,_),getPublicKey:E=>w(E),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:v}}function u7(r){let e=tb,t=r*r%e*r%e,n=En(t,wC,e)*t%e,i=En(n,qfe,e)*r%e,a=En(i,zfe,e)*i%e,s=En(a,bq,e)*a%e,o=En(s,Ffe,e)*s%e,c=En(o,Gfe,e)*o%e,l=En(c,Pq,e)*c%e,d=En(l,Pq,e)*c%e,u=En(d,bq,e)*a%e;return{pow_p_5_8:En(u,wC,e)*r%e,b2:t}}function f7(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Hfe(r,e){let t=tb,n=Zr(e*e*e,t),i=Zr(n*n*e,t),a=u7(r*i).pow_p_5_8,s=Zr(r*n*a,t),o=Zr(e*s*s,t),c=s,l=Zr(s*vq,t),d=o===r,u=o===Zr(-r,t),f=o===Zr(-r*vq,t);return d&&(s=c),(u||f)&&(s=l),Tue(s,t)&&(s=Zr(-s,t)),{isValid:d||u,value:s}}function p7(r,e,t){if(e.length>255)throw new Error("Context is too big");return Gz(Fz("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}function Vfe(r){let{y:e}=oh.ExtendedPoint.fromHex(r),t=BigInt(1);return Ma.toBytes(Ma.create((t+e)*Ma.inv(t-e)))}function Wfe(r){let e=rb.hash(r.subarray(0,32));return rb.adjustScalarBytes(e).subarray(0,32)}function ipe(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;return e==="string"||e==="number"||e==="bigint"||e==="symbol"?e:e==="function"?"Function":Array.isArray(r)?"Array":r instanceof Uint8Array?"Uint8Array":r.constructor===Object?"Object":spe(r)||"Object"}function spe(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(npe.includes(e))return e}function eE(r){return cb&&globalThis.Buffer.isBuffer(r)}function m7(r){return r instanceof Uint8Array?eE(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}function y7(r,e){if(eE(r)&&eE(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 xq(r){let e=[],t=0;for(let n=0;n<r.length;n++){let i=r.charCodeAt(n);i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(i>=55296&&i<=57343&&(i=65533),e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e}function ig(r,e,t){if(r.length-e<t)throw new Error(`${Sn} not enough data for type`)}function Ph(r,e,t){ig(r,e,1);let n=r[e];if(t.strict===!0&&n<rs[0])throw new Error(`${Sn} integer encoded in more bytes than necessary (strict decode)`);return n}function xh(r,e,t){ig(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<rs[1])throw new Error(`${Sn} integer encoded in more bytes than necessary (strict decode)`);return n}function Eh(r,e,t){ig(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<rs[2])throw new Error(`${Sn} integer encoded in more bytes than necessary (strict decode)`);return n}function Sh(r,e,t){ig(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],a=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&a<rs[3])throw new Error(`${Sn} integer encoded in more bytes than necessary (strict decode)`);if(a<=Number.MAX_SAFE_INTEGER)return Number(a);if(t.allowBigInt===!0)return a;throw new Error(`${Sn} integers outside of the safe integer range are not supported`)}function mpe(r,e,t,n){return new Qe(xe.uint,Ph(r,e+1,n),2)}function ype(r,e,t,n){return new Qe(xe.uint,xh(r,e+1,n),3)}function gpe(r,e,t,n){return new Qe(xe.uint,Eh(r,e+1,n),5)}function wpe(r,e,t,n){return new Qe(xe.uint,Sh(r,e+1,n),9)}function kh(r,e){return Ua(r,0,e.value)}function Ua(r,e,t){if(t<rs[0]){let n=Number(t);r.push([e|n])}else if(t<rs[1]){let n=Number(t);r.push([e|24,n])}else if(t<rs[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<rs[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<rs[4]){let i=[e|27,0,0,0,0,0,0,0],a=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=a&255,a=a>>8,i[7]=a&255,a=a>>8,i[6]=a&255,a=a>>8,i[5]=a&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${Sn} encountered BigInt larger than allowable range`)}}function vpe(r,e,t,n){return new Qe(xe.negint,-1-Ph(r,e+1,n),2)}function bpe(r,e,t,n){return new Qe(xe.negint,-1-xh(r,e+1,n),3)}function Ppe(r,e,t,n){return new Qe(xe.negint,-1-Eh(r,e+1,n),5)}function xpe(r,e,t,n){let i=Sh(r,e+1,n);if(typeof i!="bigint"){let a=-1-i;if(a>=Number.MIN_SAFE_INTEGER)return new Qe(xe.negint,a,9)}if(n.allowBigInt!==!0)throw new Error(`${Sn} integers outside of the safe integer range are not supported`);return new Qe(xe.negint,GC-BigInt(i),9)}function HC(r,e){let t=e.value,n=typeof t=="bigint"?t*GC-v7:t*-1-1;Ua(r,e.type.majorEncoded,n)}function lb(r,e,t,n){ig(r,e,t+n);let i=r.slice(e+t,e+t+n);return new Qe(xe.bytes,i,t+n)}function Epe(r,e,t,n){return lb(r,e,1,t)}function Spe(r,e,t,n){return lb(r,e,2,Ph(r,e+1,n))}function kpe(r,e,t,n){return lb(r,e,3,xh(r,e+1,n))}function _pe(r,e,t,n){return lb(r,e,5,Eh(r,e+1,n))}function Ape(r,e,t,n){let i=Sh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Sn} 64-bit integer bytes lengths not supported`);return lb(r,e,9,i)}function tE(r){return r.encodedBytes===void 0&&(r.encodedBytes=xe.equals(r.type,xe.string)?dpe(r.value):r.value),r.encodedBytes}function pE(r,e){let t=tE(e);Ua(r,e.type.majorEncoded,t.length),r.push(t)}function Tpe(r,e){return r.length<e.length?-1:r.length>e.length?1:y7(r,e)}function Dpe(r,e,t){if(t-e<Ipe){let n="";for(let i=e;i<t;i++){let a=r[i];if(a&128)return Eq.decode(r.subarray(e,t));n+=String.fromCharCode(a)}return n}return Eq.decode(r.subarray(e,t))}function ub(r,e,t,n,i){let a=t+n;ig(r,e,a);let s=new Qe(xe.string,Dpe(r,e+t,e+a),a);return i.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+a)),s}function Rpe(r,e,t,n){return ub(r,e,1,t,n)}function Cpe(r,e,t,n){return ub(r,e,2,Ph(r,e+1,n),n)}function $pe(r,e,t,n){return ub(r,e,3,xh(r,e+1,n),n)}function Bpe(r,e,t,n){return ub(r,e,5,Eh(r,e+1,n),n)}function Ope(r,e,t,n){let i=Sh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Sn} 64-bit integer string lengths not supported`);return ub(r,e,9,i,n)}function sg(r,e,t,n){return new Qe(xe.array,n,t)}function Mpe(r,e,t,n){return sg(r,e,1,t)}function Kpe(r,e,t,n){return sg(r,e,2,Ph(r,e+1,n))}function Upe(r,e,t,n){return sg(r,e,3,xh(r,e+1,n))}function Npe(r,e,t,n){return sg(r,e,5,Eh(r,e+1,n))}function Lpe(r,e,t,n){let i=Sh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Sn} 64-bit integer array lengths not supported`);return sg(r,e,9,i)}function qpe(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Sn} indefinite length items not allowed`);return sg(r,e,1,1/0)}function VC(r,e){Ua(r,xe.array.majorEncoded,e.value)}function og(r,e,t,n){return new Qe(xe.map,n,t)}function zpe(r,e,t,n){return og(r,e,1,t)}function Fpe(r,e,t,n){return og(r,e,2,Ph(r,e+1,n))}function Gpe(r,e,t,n){return og(r,e,3,xh(r,e+1,n))}function Hpe(r,e,t,n){return og(r,e,5,Eh(r,e+1,n))}function Vpe(r,e,t,n){let i=Sh(r,e+1,n);if(typeof i=="bigint")throw new Error(`${Sn} 64-bit integer map lengths not supported`);return og(r,e,9,i)}function Wpe(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Sn} indefinite length items not allowed`);return og(r,e,1,1/0)}function WC(r,e){Ua(r,xe.map.majorEncoded,e.value)}function Jpe(r,e,t,n){return new Qe(xe.tag,t,1)}function Zpe(r,e,t,n){return new Qe(xe.tag,Ph(r,e+1,n),2)}function Ype(r,e,t,n){return new Qe(xe.tag,xh(r,e+1,n),3)}function Xpe(r,e,t,n){return new Qe(xe.tag,Eh(r,e+1,n),5)}function Qpe(r,e,t,n){return new Qe(xe.tag,Sh(r,e+1,n),9)}function JC(r,e){Ua(r,xe.tag.majorEncoded,e.value)}function ehe(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Sn} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Qe(xe.null,null,1):new Qe(xe.undefined,void 0,1)}function the(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Sn} indefinite length items not allowed`);return new Qe(xe.break,void 0,1)}function ZC(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Sn} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Sn} Infinity values are not supported`)}return new Qe(xe.float,r,e)}function rhe(r,e,t,n){return ZC(XC(r,e+1),3,n)}function nhe(r,e,t,n){return ZC(QC(r,e+1),5,n)}function ihe(r,e,t,n){return ZC(A7(r,e+1),9,n)}function YC(r,e,t){let n=e.value;if(n===!1)r.push([xe.float.majorEncoded|b7]);else if(n===!0)r.push([xe.float.majorEncoded|P7]);else if(n===null)r.push([xe.float.majorEncoded|x7]);else if(n===void 0)r.push([xe.float.majorEncoded|E7]);else{let i,a=!1;(!t||t.float64!==!0)&&(k7(n),i=XC(Tc,1),n===i||Number.isNaN(n)?(Tc[0]=249,r.push(Tc.slice(0,3)),a=!0):(_7(n),i=QC(Tc,1),n===i&&(Tc[0]=250,r.push(Tc.slice(0,5)),a=!0))),a||(she(n),i=A7(Tc,1),Tc[0]=251,r.push(Tc.slice(0,9)))}}function k7(r){if(r===1/0)Ra.setUint16(0,31744,!1);else if(r===-1/0)Ra.setUint16(0,64512,!1);else if(Number.isNaN(r))Ra.setUint16(0,32256,!1);else{Ra.setFloat32(0,r);let e=Ra.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Ra.setUint16(0,31744,!1);else if(t===0)Ra.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?Ra.setUint16(0,0):i<-14?Ra.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Ra.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function XC(r,e){if(r.length-e<2)throw new Error(`${Sn} 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,i=t&1023,a;return n===0?a=i*2**-24:n!==31?a=(i+1024)*2**(n-25):a=i===0?1/0:NaN,t&32768?-a:a}function _7(r){Ra.setFloat32(0,r,!1)}function QC(r,e){if(r.length-e<4)throw new Error(`${Sn} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function she(r){Ra.setFloat64(0,r,!1)}function A7(r,e){if(r.length-e<8)throw new Error(`${Sn} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}function fr(r,e,t){throw new Error(`${Sn} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function hE(r){return()=>{throw new Error(`${Sn} ${r}`)}}function ohe(r){switch(r.type){case xe.false:return Nl([244]);case xe.true:return Nl([245]);case xe.null:return Nl([246]);case xe.bytes:return r.value.length?void 0:Nl([64]);case xe.string:return r.value===""?Nl([96]):void 0;case xe.array:return r.value===0?Nl([128]):void 0;case xe.map:return r.value===0?Nl([160]):void 0;case xe.uint:return r.value<24?Nl([Number(r.value)]):void 0;case xe.negint:if(r.value>=-24)return Nl([31-Number(r.value)])}}function che(){let r=[];return r[xe.uint.major]=kh,r[xe.negint.major]=HC,r[xe.bytes.major]=pE,r[xe.string.major]=jpe,r[xe.array.major]=VC,r[xe.map.major]=WC,r[xe.tag.major]=JC,r[xe.float.major]=YC,r}function $2(r,e={},t){let n=ipe(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||_f[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let a=_f[n];if(!a)throw new Error(`${w7} unsupported type: ${n}`);return a(r,n,e,t)}function uhe(r,e){e.mapSorter&&r.sort(e.mapSorter)}function fhe(r,e){if(r[0]instanceof Qe&&e[0]instanceof Qe){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=kq(t.value)),n._keyBytes||(n._keyBytes=kq(n.value)),y7(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function kq(r){return phe(r,dhe,ahe)}function I7(r,e,t,n){if(Array.isArray(e))for(let i of e)I7(r,i,t,n);else t[e.type.major](r,e,n)}function phe(r,e,t,n){let i=n instanceof Uint8Array,a=i?new hpe(n):lhe,s=$2(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let o=t.quickEncodeToken(s);if(o)return i?(a.push(o),a.toBytes()):o;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(i||(a=new g7(l)),c(a,s,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return i?a.toBytes():m7(a.chunks[0])}}return a.reset(),I7(a,s,e,t),a.toBytes(!0)}function Ws(r){if(typeof r=="string"&&r.length!==0)return r.split("#").pop()}function hhe({didDocument:r,id:e,type:t}){return r?.service?.filter(n=>!(e&&n.id!==e||t&&n.type!==t))??[]}async function mhe({didDocument:r,publicKeyJwk:e,publicKeyMultibase:t}){let n=mE({didDocument:r});for(let i of n)if(e&&i.publicKeyJwk){if(await xr({jwk:e})===await xr({jwk:i.publicKeyJwk}))return i}else if(t&&i.publicKeyMultibase&&t===i.publicKeyMultibase)return i;return null}function mE({didDocument:r}){if(!r)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...r.verificationMethod?.filter(rE)??[]),Object.keys(lE).forEach(t=>{e.push(...r[t]?.filter(rE)??[])}),e}function D7({didDocument:r}){let e=mE({didDocument:r}).map(t=>t.type);return[...new Set(e)]}function R7({didDocument:r,methodId:e}){let t=[];return Object.keys(lE).forEach(n=>{if(Array.isArray(r[n])){let i=r[n],a=Ws(e);i.some(s=>{let o=Ws(s)===a,c=rE(s)&&Ws(s.id)===a;return o||c})&&t.push(n)}}),t}function C7(r){return!r||typeof r!="object"||r===null?!1:"id"in r&&"type"in r&&"serviceEndpoint"in r}function yhe(r){return!(!C7(r)||r.type!=="DecentralizedWebNode")}function rE(r){return!(!r||typeof r!="object"||r===null||!("id"in r&&"type"in r&&"controller"in r)||typeof r.id!="string"||typeof r.type!="string"||typeof r.controller!="string")}function _h(r){return!(!r||typeof r!="object"||r===null)&&"uri"in r&&"document"in r&&"metadata"in r&&(!("keyManager"in r)||r.keyManager===void 0)}function $7({keyBytes:r,multicodecCode:e,multicodecName:t}){let n=Ka.addPrefix({code:e,data:r,name:t}),i=rt.uint8Array(n).toBase58Btc();return rt.base58Btc(i).toMultibase()}function B7({multibaseKeyId:r}){try{let e=rt.multibase(r).toBase58Btc(),t=rt.base58Btc(e).toUint8Array(),{code:n,data:i,name:a}=Ka.removePrefix({prefixedData:t});return{keyBytes:i,multicodecCode:n,multicodecName:a}}catch{throw new Xe("invalidDid",`Invalid multibase identifier: ${r}`)}}function pb(r){let e=r<0?1:0;return r=Math.abs(Number(r||1)),Math.floor(Math.log10(r))+1+e}function N7(r){return ArrayBuffer.isView(r)?"arraybufferview":Array.isArray(r)?"array":r instanceof Number?"number":r instanceof Boolean?"boolean":r instanceof Set?"set":r instanceof Map?"map":r instanceof String?"string":r instanceof ArrayBuffer?"arraybuffer":typeof r}function gr(r,e,t){let n=[],i=null;return gr._encode(n,r),i=whe(n),gr.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,t),e):i}function z7(r,e,t){let n=0,i=1;for(let a=e;a<t;a++){let s=r[a];if(s<58&&s>=48){n=n*10+(s-48);continue}if(!(a===e&&s===43)){if(a===e&&s===45){i=-1;continue}if(s===46)break;throw new Error("not a number: buffer["+a+"] = "+s)}}return n*i}function gt(r,e,t,n){return r==null||r.length===0?null:(typeof e!="number"&&n==null&&(n=e,e=void 0),typeof t!="number"&&n==null&&(n=t,t=void 0),gt.position=0,gt.encoding=n||null,gt.data=ArrayBuffer.isView(r)?new Uint8Array(r.slice(e,t)):Hl(r),gt.bytes=gt.data.length,gt.next())}function The(r){let e=2;for(let t of r)e+=gE(t);return e}function Ihe(r){let e=2;for(let[t,n]of r){let i=Hl(t).byteLength;e+=pb(i)+1+i,e+=gE(n)}return e}function Dhe(r){let e=2,t=Object.keys(r);for(let n=0;n<t.length;n++){let i=Hl(t[n]).byteLength;e+=pb(i)+1+i,e+=gE(r[t[n]])}return e}function Rhe(r){let e=Hl(r).byteLength;return pb(e)+1+e}function Che(r){let e=r.byteLength-r.byteOffset;return pb(e)+1+e}function gE(r){if(r==null)return 0;let e=N7(r);switch(e){case"arraybufferview":return Che(r);case"string":return Rhe(r);case"array":case"set":return The(r);case"number":return 1+pb(Math.floor(r))+1;case"bigint":return 1+r.toString().length+1;case"object":return Dhe(r);case"map":return Ihe(r);default:throw new TypeError(`Unsupported value of type "${e}"`)}}function H7(r){if(Bd.isFormat(r))return Bd.size;if(kf.isFormat(r))return kf.size;throw Error(`Invalid ip address: ${r}`)}function jhe(r){return H7(r)===Bd.size?1:2}function Mhe(r,e,t){t=~~t;let n=H7(r);return typeof e=="function"&&(e=e(t+n)),n===Bd.size?Bd.encode(r,e,t):kf.encode(r,e,t)}function Khe(r,e,t){if(e=~~e,t=t||r.length-e,t===Bd.size)return Bd.decode(r,e,t);if(t===kf.size)return kf.decode(r,e,t);throw Error(`Invalid buffer size needs to be ${Bd.size} for v4 or ${kf.size} for v6.`)}function wE(r){switch(r){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+r}function nb(r){switch(r.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return r.toUpperCase().startsWith("UNKNOWN_")?parseInt(r.slice(8)):0}function Uhe(r){switch(r){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+r}function Nhe(r){switch(r){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+r}function V7(r){switch(r){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+r}function W7(r){switch(r.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}function Lhe(r){switch(r){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return r<0?null:`OPTION_${r}`}function Kq(r){if(typeof r=="number")return r;if(!r)return-1;switch(r.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=r.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}function J7(r){let e=0,t=r.length;for(let n=0;n<t;n+=1){let i=r.charCodeAt(n);if(i<=127)e+=1;else if(i<=2047)e+=2;else if((i&63488)!==55296)e+=3;else{let a=n+1;a===t||i>=56320||(r.charCodeAt(a)&64512)!==56320?e+=3:(n=a,e+=4)}}return e}function ib(r,e,t){let n=r.length;t==null&&(t=0),e===void 0&&(e=new Uint8Array(J7(r)+t));let i=t;for(let a=0;a<n;a+=1){let s=r.charCodeAt(a);if(s<=127)e[i++]=s;else if(s<=2047)e[i++]=192|(s&1984)>>6,e[i++]=128|s&63;else if((s&63488)!==55296)e[i++]=224|(s&61440)>>12,e[i++]=128|(s&4032)>>6,e[i++]=128|s&63;else{let o=a+1;if(o===n||s>=56320)e[i++]=239,e[i++]=191,e[i++]=189;else{let c=r.charCodeAt(o);(c&64512)!==56320?(e[i++]=239,e[i++]=191,e[i++]=189):(a=o,s=65536|(s&1023)<<10|c&1023,e[i++]=240|(s&1835008)>>18,e[i++]=128|(s&258048)>>12,e[i++]=128|(s&4032)>>6,e[i++]=128|s&63)}}}return ib.bytes=i-t,e}function hb(r,e,t){let n="";e==null&&(e=0),t==null&&(t=r.length);for(let i=e;i<t;){let a=r[i++],s;if(a<=128)s=a;else if(a>191&&a<224)s=(a&31)<<6|r[i++]&63;else if(a>239&&a<365){s=((a&7)<<18|(r[i++]&63)<<12|(r[i++]&63)<<6|r[i++]&63)-65536;let o=55296|s>>10&1023;n+=String.fromCharCode(o),s=56320|s&1023}else s=(a&15)<<12|(r[i++]&63)<<6|r[i++]&63;n+=String.fromCharCode(s)}return hb.bytes=t-e,n}function Af(r){return typeof r=="string"?J7(r):r.byteLength}function n6(r){return r instanceof Uint8Array?r:Array.isArray(r)?new Uint8Array(r):ib(r)}function i6(r,e,t){if(typeof e!="string")throw new Error("unknown input type");return ib(e,r,t),ib.bytes}function qhe(r,e,t){let n="";for(let i=e;i<t;){let a=r[i++];n+=Z7[a]}return n}function Uq(r){return r.length>>>1}function zhe(r,e,t,n){let i=0;for(;t<n;){let a=e.substr(i,2),s=K0[a];if(s===void 0)return;r[t++]=s,i+=2}return r}function Zo(r,e,t,n,i){return t<0&&(n-=t,t=0),n<0&&(n=0),i<0?new Uint8Array(0):t>=e.length||n>=i?0:Vhe(r,e,t,n,i)}function Vhe(r,e,t,n,i){i-n>e.length-t&&(i=n+e.length-t);let a=i-n,s=r.length-n;return a>s&&(a=s),(n!==0||i<r.length)&&(r=new Uint8Array(r.buffer,r.byteOffset+n,a)),e.set(r,t),a}function Fr({bytes:r=0,encode:e,decode:t,encodingLength:n}){return e.bytes=r,t.bytes=r,{encode:e,decode:t,encodingLength:n||(()=>r)}}function bC(r){if(r===1)return 20;if(r===2)return 32;throw new Error(`Invalid hashType=${r}, supported=1,2`)}function aC(r){switch(r.toUpperCase()){case"A":return X7;case"PTR":return Jy;case"CNAME":return Jy;case"DNAME":return Jy;case"TXT":return M2;case"NULL":return K2;case"AAAA":return q2;case"SRV":return N2;case"HINFO":return U2;case"CAA":return xf;case"NS":return O2;case"SOA":return j2;case"MX":return L2;case"OPT":return Ef;case"DNSKEY":return $d;case"RRSIG":return U0;case"RP":return N0;case"NSEC":return L0;case"NSEC3":return q0;case"SSHFP":return Hy;case"DS":return z0}return B2}function nE(r,e){if(r.questions)throw new Error("Only one .question object expected instead of a .questions array!");let t=Object.assign({type:e},r);return t.question&&(t.questions=[t.question],delete t.question),t}function Q7(r){let e=oE(r),t=new Uint8Array(2+e.byteLength);return nt(t,e.byteLength),Zo(e,t,2,0,e.length),Q7.bytes=t.byteLength,t}function eF(r){let e=Mt(r,0);if(r.byteLength<e+2)return null;let t=PC(r.slice(2));return eF.bytes=PC.bytes,t}function Vy(r,e){let t=0;for(let n=0;n<r.length;n++)t+=e.encodingLength(r[n]);return t}function F0(r,e,t,n){for(let i=0;i<r.length;i++)e.encode(r[i],t,n),n+=e.encode.bytes;return n}function k2(r,e,t,n){for(let i=0;i<r.length;i++)r[i]=e.decode(t,n),n+=e.decode.bytes;return n}function tF(r,e){let t=rt.uint8Array(r).toBase32Z();return new URL(t,e).href}async function rF(r,e,t){if(t)return fetch(r,e);try{return await Oz(r,e,{description:"Pkarr gateway URL"})}catch(n){throw n instanceof R2?new Xe("invalidGatewayUri",n.message):n}}async function Qhe({gatewayUri:r,publicKeyBytes:e,allowPrivateGatewayUri:t=!1}){let n=rt.uint8Array(e).toBase32Z(),i=tF(e,r),a;try{if(a=await rF(i,{method:"GET",signal:AbortSignal.timeout(3e4)},t),!a.ok)throw new Xe("notFound",`Pkarr record not found for: ${n}`)}catch(o){throw o instanceof Xe?o:new Xe("internalError",`Failed to fetch Pkarr record: ${o.message}`)}let s=await a.arrayBuffer();if(!s)throw new Xe("notFound",`Pkarr record not found for: ${n}`);if(s.byteLength<72)throw new Xe("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${s.byteLength}`);if(s.byteLength>1072)throw new Xe("invalidDidDocumentLength",`Pkarr response exceeds 1000 byte limit: ${s.byteLength}`);return{k:e,seq:Number(new DataView(s).getBigUint64(64)),sig:new Uint8Array(s,0,64),v:new Uint8Array(s,72)}}async function eme({gatewayUri:r,bep44Message:e,allowPrivateGatewayUri:t=!1}){let n=rt.uint8Array(e.k).toBase32Z(),i=tF(e.k,r),a=new Uint8Array(e.v.length+72);a.set(e.sig,0),new DataView(a.buffer).setBigUint64(e.sig.length,BigInt(e.seq)),a.set(e.v,e.sig.length+8);let s;try{s=await rF(i,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:a,signal:AbortSignal.timeout(3e4)},t)}catch(o){throw o instanceof Xe?o:new Xe("internalError",`Failed to put Pkarr record for identifier ${n}: ${o.message}`)}return s.ok}async function tme({dnsPacket:r,publicKeyBytes:e,signer:t}){let n=Math.ceil(Date.now()/1e3),i=oE(r),a=G7.encode({seq:n,v:i}).subarray(1,-1);if(a.length>1e3)throw new Xe("invalidDidDocumentLength",`DNS packet exceeds the 1000 byte maximum size: ${a.length} bytes`);let s=await t.sign({data:new Uint8Array(a)});return{k:e,seq:n,sig:s,v:i}}async function rme({bep44Message:r}){let e=await ts.bytesToPublicKey({publicKeyBytes:r.k}),t=G7.encode({seq:r.seq,v:r.v}).subarray(1,-1);if(!await ts.verify({key:e,signature:r.sig,data:new Uint8Array(t)}))throw new Xe("invalidSignature","Invalid signature for DHT BEP44 message");return PC(r.v)}async function iF({didUri:r}){let e=s6({didUri:r});return await ts.bytesToPublicKey({publicKeyBytes:e})}function s6({didUri:r}){let e=Vn.parse(r);if(!e)throw new Xe("invalidDid",`Invalid DID URI: ${r}`);if(e.method!==nF)throw new Xe("methodNotSupported",`Method not supported: ${e.method}`);let t;try{t=rt.base32Z(e.id).toUint8Array()}catch{throw new Xe("invalidPublicKey","Failed to decode method-specific identifier")}if(t.length!==32)throw new Xe("invalidPublicKeyLength",`Invalid public key length: ${t.length}`);return t}async function nme({identityKey:r}){let e=await ts.publicKeyToBytes({publicKey:r}),t=rt.uint8Array(e).toBase32Z();return`did:${nF}:${t}`}function o6(r){let e={Ed25519:ts,"P-256":{publicKeyToBytes:async({publicKey:t})=>{let n=await bs.publicKeyToBytes({publicKey:t});return await bs.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:bs.bytesToPublicKey,privateKeyToBytes:bs.privateKeyToBytes,bytesToPrivateKey:bs.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:t})=>{let n=await es.publicKeyToBytes({publicKey:t});return await es.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:es.bytesToPublicKey,privateKeyToBytes:es.privateKeyToBytes,bytesToPrivateKey:es.bytesToPrivateKey},X25519:Ly}[r];if(!e)throw new Xe("invalidPublicKeyType",`Unsupported curve: ${r}`);return e}async function sF({newDid:r,previousDidProof:e}){let t=await iF({didUri:e.previousDid}),n=s6({didUri:r}),i=rt.base64Url(e.signature).toUint8Array();if(!await ts.verify({key:t,data:n,signature:i}))throw new Xe("invalidPreviousDidProof","The previous DID proof is invalid.")}function sb(r){if(typeof r=="string")return r;if(r instanceof Uint8Array)return rt.uint8Array(r).toString();if(Array.isArray(r))return r.map(e=>sb(e)).join("");throw new Xe("internalError","Pkarr returned DNS TXT record with invalid data type")}function G0(r){return sb(r).split(z2).reduce((e,t)=>{let[n,i]=t.split("=");return e[n]=i,e},{})}function cF(r){if(r.length<=255)return r;let e=[];for(let t=0;t<r.length;t+=255)e.push(r.slice(t,t+255));return e}async function sme({didUri:r,dnsPacket:e}){let t={id:r},n={published:!0},i=new Map;for(let a of e?.answers??[]){if(a.type!=="TXT")continue;let s=a.name.split(".")[0].substring(1);switch(!0){case s.startsWith("aka"):{let o=sb(a.data);t.alsoKnownAs=o.split(Vs);break}case s.startsWith("cnt"):{let o=sb(a.data);t.controller=o.includes(Vs)?o.split(Vs):o;break}case s.startsWith("k"):{let{id:o,t:c,k:l,c:d,a:u}=G0(a.data),f=rt.base64Url(l).toUint8Array(),p=t6[Number(c)],h=await o6(p).bytesToPublicKey({publicKeyBytes:f});h.alg=u||aF[Number(c)];let m=s==="k0"?"0":o===void 0?await xr({jwk:h}):o;t.verificationMethod??=[];let y=`${r}#${m}`;t.verificationMethod.push({id:y,type:"JsonWebKey",controller:d??r,publicKeyJwk:h}),i.set(s,y);break}case s.startsWith("s"):{let{id:o,t:c,se:l,...d}=G0(a.data),u=l.includes(Vs)?l.split(Vs):[l],f=Object.fromEntries(Object.entries(d).map(([p,h])=>[p,h.includes(Vs)?h.split(Vs):h]));t.service??=[],t.service.push({...f,id:`${r}#${o}`,type:c,serviceEndpoint:u});break}case s.startsWith("typ"):{let{id:o}=G0(a.data);n.types=o.split(Vs).map(c=>Number(c));break}case s.startsWith("did"):{let o=p=>p.split(Vs).map(h=>i.get(h)).filter(h=>typeof h=="string"),{auth:c,asm:l,del:d,inv:u,agm:f}=G0(a.data);c&&(t.authentication=o(c)),l&&(t.assertionMethod=o(l)),d&&(t.capabilityDelegation=o(d)),u&&(t.capabilityInvocation=o(u)),f&&(t.keyAgreement=o(f));break}}}return{didDocument:t,didDocumentMetadata:n,didResolutionMetadata:{}}}async function ome({didDocument:r,didMetadata:e,authoritativeGatewayUris:t,previousDidProof:n}){let i=[],a=[],s=new Map,o=[],c=[];if(n!==void 0){let{signature:d,previousDid:u}=n;await sF({newDid:r.id,previousDidProof:n}),i.push({type:"TXT",name:"_prv._did.",ttl:wf,data:`id=${u};s=${d}`})}if(r.alsoKnownAs&&i.push({type:"TXT",name:"_aka._did.",ttl:wf,data:r.alsoKnownAs.join(Vs)}),r.controller){let d=Array.isArray(r.controller)?r.controller.join(Vs):r.controller;i.push({type:"TXT",name:"_cnt._did.",ttl:wf,data:d})}for(let[d,u]of r.verificationMethod?.entries()??[]){let f=`k${d}`;c.push(f);let p=u.id.split("#").pop();s.set(p,f);let h=u.publicKeyJwk;if(!(h?.crv&&h.crv in oF))throw new Xe("invalidPublicKeyType",`Verification method '${u.id}' contains an unsupported key type: ${h?.crv??"undefined"}`);let m=t6[h.crv],y=await o6(h.crv).publicKeyToBytes({publicKey:h}),v=rt.uint8Array(y).toBase64Url(),w=[`t=${m}`,`k=${v}`];p!=="0"&&await xr({jwk:h})!==p&&w.unshift(`id=${p}`),h.alg!==aF[m]&&w.push(`a=${h.alg}`),u.controller!==r.id&&w.push(`c=${u.controller}`),i.push({type:"TXT",name:`_${f}._did.`,ttl:wf,data:w.join(z2)})}r.service?.forEach((d,u)=>{let f=`s${u}`;o.push(f);let{id:p,type:h,serviceEndpoint:m,...y}=d;p=Ws(p),m=Array.isArray(m)?m.join(","):m;let v=Object.entries({id:p,t:h,se:m,...y}).map(([E,_])=>`${E}=${_}`).join(z2),w=cF(v);i.push({type:"TXT",name:`_${f}._did.`,ttl:wf,data:w})});let l=[`v=${ime}`];if(c.length&&l.push(`vm=${c.join(Vs)}`),Object.keys(lE).forEach(d=>{let u=r[d]?.map(f=>s.get(f.split("#").pop()));if(u){let f=M7[d];l.push(`${f}=${u.join(Vs)}`)}}),o.length&&l.push(`svc=${o.join(Vs)}`),e.types?.length){let d=e.types.map(u=>typeof u=="string"?j7[u]:u);i.push({type:"TXT",name:"_typ._did.",ttl:wf,data:`id=${d.join(Vs)}`})}i.push({type:"TXT",name:"_did."+qq(r.id)+".",ttl:wf,data:l.join(z2)});for(let d of t||[])a.push({type:"NS",name:"_did."+qq(r.id)+".",ttl:wf,data:d+"."});return{id:0,type:"response",flags:Yhe,answers:[...i,...a]}}function qq(r){return r.split(":")[2]}function cme(){return K.DID_DHT_GATEWAY_URI||ame}function dme(){return K.DID_DHT_ALLOW_PRIVATE_GATEWAY==="1"}function zq(r,e){return{gatewayUri:r??cme(),allowPrivateGatewayUri:e??dme()}}function uF(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Eme;)e[t++]=r&255|Hq,r/=128;for(;r&xme;)e[t++]=r&255|Hq,r>>>=7;return e[t]=r|0,uF.bytes=t-n+1,e}function kC(r,n){var t=0,n=n||0,i=0,a=n,s,o=r.length;do{if(a>=o)throw kC.bytes=0,new RangeError("Could not decode varint");s=r[a++],t+=i<28?(s&Vq)<<i:(s&Vq)*Math.pow(2,i),i+=7}while(s>=kme);return kC.bytes=a-n,t}function Yme(r){r=p6(r);let e=Yy+8;(r.length<e||r.length>1024)&&Ti("expected proper params");let t=Ye(xE(r),f6-1n)+1n;return m6(t)}var Bde,DC,Ode,jde,Mde,Kde,Zt,RC,Ude,vh,Nde,Lde,Md,qde,zde,CC,gz,wz,vz,Fde,Gde,Hde,Vde,dE,$C,fh,Wde,Jde,bz,Zde,Yde,Pz,Xde,Qde,ele,Q9,xz,tle,Ez,Sz,rle,nle,ile,kz,sle,ole,_z,lE,is,Xi,Vn,Xe,ale,ja,go,cle,lle,ule,fle,CNe,ple,BC,hle,mle,yle,Dz,gle,Rz,Cz,wle,vle,Yo,D2,$Ne,BNe,ONe,jNe,MNe,KNe,UNe,eq,Ba,NNe,LNe,qNe,Ol,zNe,T0,tq,x2,sh,rt,Z0,xle,Ele,O0,Sle,rq,kle,_le,Ale,Tle,Ile,nq,Dle,Rle,Cle,$le,Ble,Ole,jle,Mle,Kle,Ule,Nle,Lle,Y2,X2,X0,Q0,qle,zle,Fle,OC,iq,sq,fC,FNe,Gle,Hle,Vle,I0,Wle,oq,Jle,Ka,GNe,df,Zle,Yle,Qle,R2,eue,tue,uE,Kz,Uz,fE,oue,aue,jl,pue,MC,eC,dq,hue,tC,rC,Ad,wue,Hz,HNe,Wz,bue,Pue,xue,lf,uf,Eue,Jz,mi,yn,ch,Sue,pC,uq,fq,VNe,kue,Tue,Iue,Oue,nC,Mue,Kue,uh,ql,$a,WNe,pq,JNe,t7,r7,i7,hq,zue,mC,mq,yC,Vo,ZNe,YNe,C2,iC,Td,XNe,Wue,QNe,Xue,Que,efe,tfe,ff,pf,rfe,eb,ife,a7,sfe,gq,Zi,afe,es,c7,cfe,dfe,lfe,Ta,Yi,ufe,bs,Ml,wq,E2,gC,pfe,hfe,mfe,yfe,gfe,wfe,vfe,bfe,Pfe,xfe,Efe,Sfe,kfe,Afe,Tfe,Ife,Dfe,Rfe,Cfe,$fe,jt,Bfe,Ofe,hf,mf,jfe,l7,Ac,Go,S2,Mfe,Kfe,D0,sC,tb,vq,eLe,qfe,wC,zfe,bq,Ffe,Gfe,Pq,Ma,rb,oh,tLe,rLe,j0,Jfe,nLe,iLe,sLe,oLe,aLe,cLe,dLe,lLe,uLe,fLe,Ia,Zfe,ts,Kl,Yfe,Xfe,Qfe,yf,epe,Ly,R0,tpe,Ul,oC,Dc,rpe,npe,xe,Qe,cb,ope,ape,cpe,dpe,Nl,lpe,upe,fpe,ppe,g7,hpe,Sn,w7,db,rs,GC,v7,Eq,Ipe,jpe,b7,P7,x7,E7,S7,Ra,Tc,Oe,Vl,ahe,dhe,lhe,Sq,gf,_f,pLe,hLe,mLe,yLe,gLe,wLe,vLe,bLe,PLe,xLe,ELe,SLe,kLe,_q,Ps,Oa,Aq,Tq,_Le,ALe,TLe,ILe,Iq,Dq,Rq,Cq,e6,xs,fb,j7,t6,M7,$q,K7,Bq,ghe,whe,Oq,vhe,C0,bhe,U7,Phe,Hl,jq,Mq,DLe,yE,L7,q7,xhe,Ehe,She,khe,_he,r6,Ahe,F7,$he,G7,Bhe,Ohe,Bd,kf,wh,K0,Z7,Fhe,Ghe,Hhe,zl,Mt,Fl,nt,Whe,Nq,vC,Jhe,Y7,Zhe,He,hi,qy,B2,O2,j2,M2,K2,U2,Jy,N2,xf,L2,X7,q2,Lq,Ll,Ef,$d,U0,N0,Jo,L0,q0,z0,Hy,Ca,Zy,Yhe,ns,iE,sE,oE,PC,Xhe,nF,ime,wf,z2,Vs,oF,aF,ame,dF,wo,Fq,Wy,Fn,Gn,RLe,lme,ume,fme,pme,lF,hme,mme,yme,gme,vE,CLe,$Le,Gq,BLe,eg,wme,EC,Cd,Ho,a6,Ic,vme,ob,bme,Hq,Pme,xme,Eme,Sme,kme,Vq,_me,Ame,Tme,Ime,Dme,Rme,Cme,$me,Bme,Ome,jme,Mme,aE,Wq,Jq,Zq,Yq,Kme,fF,pF,Ume,hF,Xq,OLe,$0,Wo,_C,_2,AC,Ny,A2,mF,Qq,Nme,Qi,G2,TC,IC,T2,yo,gF,c6,tg,Lme,at,ez,tz,rg,cE,H2,wF,d6,l6,qme,zme,rz,vF,Id,Fme,nz,Gme,cC,iz,Hme,dh,Vme,Wme,u6,mh,f6,bF,PF,xF,Yy,sz,Ti,bE,EF,dC,SF,kF,ab,p6,Ye,oz,az,ng,Y0,V2,_F,h6,PE,xE,cz,m6,dz,lz,AF,Jme,Zme,uz,W2,Xme,lh,Qme,eye,fz,pz,B0,tye,rye,hz,nye,TF,Xo,iye,J2,I2,sye,mz,IF,mb,oye,DF,RF,aye,cye,EE,dye,SE,lye,ag,Qo=G(()=>{"use strict";g();Bde=Object.create,DC=Object.defineProperty,Ode=Object.getOwnPropertyDescriptor,jde=Object.getOwnPropertyNames,Mde=Object.getPrototypeOf,Kde=Object.prototype.hasOwnProperty,Zt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),RC=(r,e)=>{for(var t in e)DC(r,t,{get:e[t],enumerable:!0})},Ude=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of jde(e))!Kde.call(r,i)&&i!==t&&DC(r,i,{get:()=>e[i],enumerable:!(n=Ode(e,i))||n.enumerable});return r},vh=(r,e,t)=>(t=r!=null?Bde(Mde(r)):{},Ude(e||!r||!r.__esModule?DC(t,"default",{value:r,enumerable:!0}):t,r)),Nde=Zt((r,e)=>{var t=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,n=()=>t.now(),i=o=>o&&o===Math.floor(o)&&o>0&&isFinite(o),a=o=>o===1/0||i(o),s=class yz{constructor({max:c=1/0,ttl:l,updateAgeOnGet:d=!1,checkAgeOnGet:u=!1,noUpdateTTL:f=!1,dispose:p,noDisposeOnSet:h=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,l!==void 0&&!a(l))throw new TypeError("ttl must be positive integer or Infinity if set");if(!a(c))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=l,this.max=c,this.updateAgeOnGet=!!d,this.checkAgeOnGet=!!u,this.noUpdateTTL=!!f,this.noDisposeOnSet=!!h,p!==void 0){if(typeof p!="function")throw new TypeError("dispose must be function if set");this.dispose=p}this.timer=void 0,this.timerExpiration=void 0}setTimer(c,l){if(this.timerExpiration<c)return;this.timer&&clearTimeout(this.timer);let d=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let u in this.expirations){this.setTimer(u,u-n());break}},l);d.unref&&d.unref(),this.timerExpiration=c,this.timer=d}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return process.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){let c=this.dispose!==yz.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[l,d]of c)this.dispose(d,l,"delete")}setTTL(c,l=this.ttl){let d=this.expirationMap.get(c);if(d!==void 0){let u=this.expirations[d];!u||u.length<=1?delete this.expirations[d]:this.expirations[d]=u.filter(f=>f!==c)}if(l!==1/0){let u=Math.floor(n()+l);this.expirationMap.set(c,u),this.expirations[u]||(this.expirations[u]=[],this.setTimer(u,l)),this.expirations[u].push(c)}else this.expirationMap.set(c,1/0)}set(c,l,{ttl:d=this.ttl,noUpdateTTL:u=this.noUpdateTTL,noDisposeOnSet:f=this.noDisposeOnSet}={}){if(!a(d))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(c)){u||this.setTTL(c,d);let p=this.data.get(c);p!==l&&(this.data.set(c,l),f||this.dispose(p,c,"set"))}else this.setTTL(c,d),this.data.set(c,l);for(;this.size>this.max;)this.purgeToCapacity();return this}has(c){return this.data.has(c)}getRemainingTTL(c){let l=this.expirationMap.get(c);return l===1/0?l:l!==void 0?Math.max(0,Math.ceil(l-n())):0}get(c,{updateAgeOnGet:l=this.updateAgeOnGet,ttl:d=this.ttl,checkAgeOnGet:u=this.checkAgeOnGet}={}){let f=this.data.get(c);if(u&&this.getRemainingTTL(c)===0){this.delete(c);return}return l&&this.setTTL(c,d),f}dispose(c,l){}delete(c){let l=this.expirationMap.get(c);if(l!==void 0){let d=this.data.get(c);this.data.delete(c),this.expirationMap.delete(c);let u=this.expirations[l];return u&&(u.length<=1?delete this.expirations[l]:this.expirations[l]=u.filter(f=>f!==c)),this.dispose(d,c,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let c in this.expirations){let l=this.expirations[c];if(this.size-l.length>=this.max){delete this.expirations[c];let d=[];for(let u of l)d.push([u,this.data.get(u)]),this.data.delete(u),this.expirationMap.delete(u);for(let[u,f]of d)this.dispose(f,u,"evict")}else{let d=this.size-this.max,u=[];for(let f of l.splice(0,d))u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,p]of u)this.dispose(p,f,"evict");return}}}get size(){return this.data.size}purgeStale(){let c=Math.ceil(n());for(let l in this.expirations){if(l==="Infinity"||l>c)return;let d=[...this.expirations[l]||[]],u=[];delete this.expirations[l];for(let f of d)u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,p]of u)this.dispose(p,f,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let c in this.expirations)for(let l of this.expirations[c])yield[l,this.data.get(l)]}*keys(){for(let c in this.expirations)for(let l of this.expirations[c])yield l}*values(){for(let c in this.expirations)for(let l of this.expirations[c])yield this.data.get(l)}[Symbol.iterator](){return this.entries()}};e.exports=s}),Lde=Zt(r=>{"use strict";r.supports=function(...e){let t=e.reduce((n,i)=>Object.assign(n,i),{});return Object.assign(t,{snapshots:t.snapshots||!1,permanence:t.permanence||!1,seek:t.seek||!1,clear:t.clear||!1,getMany:t.getMany||!1,keyIterator:t.keyIterator||!1,valueIterator:t.valueIterator||!1,iteratorNextv:t.iteratorNextv||!1,iteratorAll:t.iteratorAll||!1,status:t.status||!1,createIfMissing:t.createIfMissing||!1,errorIfExists:t.errorIfExists||!1,deferredOpen:t.deferredOpen||!1,promises:t.promises||!1,streams:t.streams||!1,encodings:Object.assign({},t.encodings),events:Object.assign({},t.events),additionalMethods:Object.assign({},t.additionalMethods)})}}),Md=Zt((r,e)=>{"use strict";e.exports=class extends Error{constructor(t,n){super(t||""),typeof n=="object"&&n!==null&&(n.code&&(this.code=String(n.code)),n.expected&&(this.expected=!0),n.transient&&(this.transient=!0),n.cause&&(this.cause=n.cause)),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}}),qde=Zt(r=>{"use strict";r.byteLength=c,r.toByteArray=d,r.fromByteArray=p;var e=[],t=[],n=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(a=0,s=i.length;a<s;++a)e[a]=i[a],t[i.charCodeAt(a)]=a;var a,s;t[45]=62,t[95]=63;function o(h){var m=h.length;if(m%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var y=h.indexOf("=");y===-1&&(y=m);var v=y===m?0:4-y%4;return[y,v]}function c(h){var m=o(h),y=m[0],v=m[1];return(y+v)*3/4-v}function l(h,m,y){return(m+y)*3/4-y}function d(h){var m,y=o(h),v=y[0],w=y[1],E=new n(l(h,v,w)),_=0,A=w>0?v-4:v,D;for(D=0;D<A;D+=4)m=t[h.charCodeAt(D)]<<18|t[h.charCodeAt(D+1)]<<12|t[h.charCodeAt(D+2)]<<6|t[h.charCodeAt(D+3)],E[_++]=m>>16&255,E[_++]=m>>8&255,E[_++]=m&255;return w===2&&(m=t[h.charCodeAt(D)]<<2|t[h.charCodeAt(D+1)]>>4,E[_++]=m&255),w===1&&(m=t[h.charCodeAt(D)]<<10|t[h.charCodeAt(D+1)]<<4|t[h.charCodeAt(D+2)]>>2,E[_++]=m>>8&255,E[_++]=m&255),E}function u(h){return e[h>>18&63]+e[h>>12&63]+e[h>>6&63]+e[h&63]}function f(h,m,y){for(var v,w=[],E=m;E<y;E+=3)v=(h[E]<<16&16711680)+(h[E+1]<<8&65280)+(h[E+2]&255),w.push(u(v));return w.join("")}function p(h){for(var m,y=h.length,v=y%3,w=[],E=16383,_=0,A=y-v;_<A;_+=E)w.push(f(h,_,_+E>A?A:_+E));return v===1?(m=h[y-1],w.push(e[m>>2]+e[m<<4&63]+"==")):v===2&&(m=(h[y-2]<<8)+h[y-1],w.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),w.join("")}}),zde=Zt(r=>{r.read=function(e,t,n,i,a){var s,o,c=a*8-i-1,l=(1<<c)-1,d=l>>1,u=-7,f=n?a-1:0,p=n?-1:1,h=e[t+f];for(f+=p,s=h&(1<<-u)-1,h>>=-u,u+=c;u>0;s=s*256+e[t+f],f+=p,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=i;u>0;o=o*256+e[t+f],f+=p,u-=8);if(s===0)s=1-d;else{if(s===l)return o?NaN:(h?-1:1)*(1/0);o=o+Math.pow(2,i),s=s-d}return(h?-1:1)*o*Math.pow(2,s-i)},r.write=function(e,t,n,i,a,s){var o,c,l,d=s*8-a-1,u=(1<<d)-1,f=u>>1,p=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,h=i?0:s-1,m=i?1:-1,y=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+f>=1?t+=p/l:t+=p*Math.pow(2,1-f),t*l>=2&&(o++,l/=2),o+f>=u?(c=0,o=u):o+f>=1?(c=(t*l-1)*Math.pow(2,a),o=o+f):(c=t*Math.pow(2,f-1)*Math.pow(2,a),o=0));a>=8;e[n+h]=c&255,h+=m,c/=256,a-=8);for(o=o<<a|c,d+=a;d>0;e[n+h]=o&255,h+=m,o/=256,d-=8);e[n+h-m]|=y*128}}),CC=Zt(r=>{"use strict";var e=qde(),t=zde(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;r.Buffer=o,r.SlowBuffer=w,r.INSPECT_MAX_BYTES=50;var i=2147483647;r.kMaxLength=i,o.TYPED_ARRAY_SUPPORT=a(),!o.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{let T=new Uint8Array(1),U={foo:function(){return 42}};return Object.setPrototypeOf(U,Uint8Array.prototype),Object.setPrototypeOf(T,U),T.foo()===42}catch{return!1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function s(T){if(T>i)throw new RangeError('The value "'+T+'" is invalid for option "size"');let U=new Uint8Array(T);return Object.setPrototypeOf(U,o.prototype),U}function o(T,U,N){if(typeof T=="number"){if(typeof U=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(T)}return c(T,U,N)}o.poolSize=8192;function c(T,U,N){if(typeof T=="string")return f(T,U);if(ArrayBuffer.isView(T))return h(T);if(T==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T);if(We(T,ArrayBuffer)||T&&We(T.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(We(T,SharedArrayBuffer)||T&&We(T.buffer,SharedArrayBuffer)))return m(T,U,N);if(typeof T=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let te=T.valueOf&&T.valueOf();if(te!=null&&te!==T)return o.from(te,U,N);let ce=y(T);if(ce)return ce;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof T[Symbol.toPrimitive]=="function")return o.from(T[Symbol.toPrimitive]("string"),U,N);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T)}o.from=function(T,U,N){return c(T,U,N)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function l(T){if(typeof T!="number")throw new TypeError('"size" argument must be of type number');if(T<0)throw new RangeError('The value "'+T+'" is invalid for option "size"')}function d(T,U,N){return l(T),T<=0?s(T):U!==void 0?typeof N=="string"?s(T).fill(U,N):s(T).fill(U):s(T)}o.alloc=function(T,U,N){return d(T,U,N)};function u(T){return l(T),s(T<0?0:v(T)|0)}o.allocUnsafe=function(T){return u(T)},o.allocUnsafeSlow=function(T){return u(T)};function f(T,U){if((typeof U!="string"||U==="")&&(U="utf8"),!o.isEncoding(U))throw new TypeError("Unknown encoding: "+U);let N=E(T,U)|0,te=s(N),ce=te.write(T,U);return ce!==N&&(te=te.slice(0,ce)),te}function p(T){let U=T.length<0?0:v(T.length)|0,N=s(U);for(let te=0;te<U;te+=1)N[te]=T[te]&255;return N}function h(T){if(We(T,Uint8Array)){let U=new Uint8Array(T);return m(U.buffer,U.byteOffset,U.byteLength)}return p(T)}function m(T,U,N){if(U<0||T.byteLength<U)throw new RangeError('"offset" is outside of buffer bounds');if(T.byteLength<U+(N||0))throw new RangeError('"length" is outside of buffer bounds');let te;return U===void 0&&N===void 0?te=new Uint8Array(T):N===void 0?te=new Uint8Array(T,U):te=new Uint8Array(T,U,N),Object.setPrototypeOf(te,o.prototype),te}function y(T){if(o.isBuffer(T)){let U=v(T.length)|0,N=s(U);return N.length===0||T.copy(N,0,0,U),N}if(T.length!==void 0)return typeof T.length!="number"||nr(T.length)?s(0):p(T);if(T.type==="Buffer"&&Array.isArray(T.data))return p(T.data)}function v(T){if(T>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return T|0}function w(T){return+T!=T&&(T=0),o.alloc(+T)}o.isBuffer=function(T){return T!=null&&T._isBuffer===!0&&T!==o.prototype},o.compare=function(T,U){if(We(T,Uint8Array)&&(T=o.from(T,T.offset,T.byteLength)),We(U,Uint8Array)&&(U=o.from(U,U.offset,U.byteLength)),!o.isBuffer(T)||!o.isBuffer(U))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(T===U)return 0;let N=T.length,te=U.length;for(let ce=0,ge=Math.min(N,te);ce<ge;++ce)if(T[ce]!==U[ce]){N=T[ce],te=U[ce];break}return N<te?-1:te<N?1:0},o.isEncoding=function(T){switch(String(T).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(T,U){if(!Array.isArray(T))throw new TypeError('"list" argument must be an Array of Buffers');if(T.length===0)return o.alloc(0);let N;if(U===void 0)for(U=0,N=0;N<T.length;++N)U+=T[N].length;let te=o.allocUnsafe(U),ce=0;for(N=0;N<T.length;++N){let ge=T[N];if(We(ge,Uint8Array))ce+ge.length>te.length?(o.isBuffer(ge)||(ge=o.from(ge)),ge.copy(te,ce)):Uint8Array.prototype.set.call(te,ge,ce);else if(o.isBuffer(ge))ge.copy(te,ce);else throw new TypeError('"list" argument must be an Array of Buffers');ce+=ge.length}return te};function E(T,U){if(o.isBuffer(T))return T.length;if(ArrayBuffer.isView(T)||We(T,ArrayBuffer))return T.byteLength;if(typeof T!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof T);let N=T.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&N===0)return 0;let ce=!1;for(;;)switch(U){case"ascii":case"latin1":case"binary":return N;case"utf8":case"utf-8":return Te(T).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N*2;case"hex":return N>>>1;case"base64":return Kr(T).length;default:if(ce)return te?-1:Te(T).length;U=(""+U).toLowerCase(),ce=!0}}o.byteLength=E;function _(T,U,N){let te=!1;if((U===void 0||U<0)&&(U=0),U>this.length||((N===void 0||N>this.length)&&(N=this.length),N<=0)||(N>>>=0,U>>>=0,N<=U))return"";for(T||(T="utf8");;)switch(T){case"hex":return k(this,U,N);case"utf8":case"utf-8":return R(this,U,N);case"ascii":return x(this,U,N);case"latin1":case"binary":return P(this,U,N);case"base64":return ee(this,U,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,U,N);default:if(te)throw new TypeError("Unknown encoding: "+T);T=(T+"").toLowerCase(),te=!0}}o.prototype._isBuffer=!0;function A(T,U,N){let te=T[U];T[U]=T[N],T[N]=te}o.prototype.swap16=function(){let T=this.length;if(T%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let U=0;U<T;U+=2)A(this,U,U+1);return this},o.prototype.swap32=function(){let T=this.length;if(T%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let U=0;U<T;U+=4)A(this,U,U+3),A(this,U+1,U+2);return this},o.prototype.swap64=function(){let T=this.length;if(T%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let U=0;U<T;U+=8)A(this,U,U+7),A(this,U+1,U+6),A(this,U+2,U+5),A(this,U+3,U+4);return this},o.prototype.toString=function(){let T=this.length;return T===0?"":arguments.length===0?R(this,0,T):_.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(T){if(!o.isBuffer(T))throw new TypeError("Argument must be a Buffer");return this===T?!0:o.compare(this,T)===0},o.prototype.inspect=function(){let T="",U=r.INSPECT_MAX_BYTES;return T=this.toString("hex",0,U).replace(/(.{2})/g,"$1 ").trim(),this.length>U&&(T+=" ... "),"<Buffer "+T+">"},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(T,U,N,te,ce){if(We(T,Uint8Array)&&(T=o.from(T,T.offset,T.byteLength)),!o.isBuffer(T))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof T);if(U===void 0&&(U=0),N===void 0&&(N=T?T.length:0),te===void 0&&(te=0),ce===void 0&&(ce=this.length),U<0||N>T.length||te<0||ce>this.length)throw new RangeError("out of range index");if(te>=ce&&U>=N)return 0;if(te>=ce)return-1;if(U>=N)return 1;if(U>>>=0,N>>>=0,te>>>=0,ce>>>=0,this===T)return 0;let ge=ce-te,Ee=N-U,qt=Math.min(ge,Ee),ri=this.slice(te,ce),Gr=T.slice(U,N);for(let Er=0;Er<qt;++Er)if(ri[Er]!==Gr[Er]){ge=ri[Er],Ee=Gr[Er];break}return ge<Ee?-1:Ee<ge?1:0};function D(T,U,N,te,ce){if(T.length===0)return-1;if(typeof N=="string"?(te=N,N=0):N>2147483647?N=2147483647:N<-2147483648&&(N=-2147483648),N=+N,nr(N)&&(N=ce?0:T.length-1),N<0&&(N=T.length+N),N>=T.length){if(ce)return-1;N=T.length-1}else if(N<0)if(ce)N=0;else return-1;if(typeof U=="string"&&(U=o.from(U,te)),o.isBuffer(U))return U.length===0?-1:M(T,U,N,te,ce);if(typeof U=="number")return U=U&255,typeof Uint8Array.prototype.indexOf=="function"?ce?Uint8Array.prototype.indexOf.call(T,U,N):Uint8Array.prototype.lastIndexOf.call(T,U,N):M(T,[U],N,te,ce);throw new TypeError("val must be string, number or Buffer")}function M(T,U,N,te,ce){let ge=1,Ee=T.length,qt=U.length;if(te!==void 0&&(te=String(te).toLowerCase(),te==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(T.length<2||U.length<2)return-1;ge=2,Ee/=2,qt/=2,N/=2}function ri(Er,hr){return ge===1?Er[hr]:Er.readUInt16BE(hr*ge)}let Gr;if(ce){let Er=-1;for(Gr=N;Gr<Ee;Gr++)if(ri(T,Gr)===ri(U,Er===-1?0:Gr-Er)){if(Er===-1&&(Er=Gr),Gr-Er+1===qt)return Er*ge}else Er!==-1&&(Gr-=Gr-Er),Er=-1}else for(N+qt>Ee&&(N=Ee-qt),Gr=N;Gr>=0;Gr--){let Er=!0;for(let hr=0;hr<qt;hr++)if(ri(T,Gr+hr)!==ri(U,hr)){Er=!1;break}if(Er)return Gr}return-1}o.prototype.includes=function(T,U,N){return this.indexOf(T,U,N)!==-1},o.prototype.indexOf=function(T,U,N){return D(this,T,U,N,!0)},o.prototype.lastIndexOf=function(T,U,N){return D(this,T,U,N,!1)};function C(T,U,N,te){N=Number(N)||0;let ce=T.length-N;te?(te=Number(te),te>ce&&(te=ce)):te=ce;let ge=U.length;te>ge/2&&(te=ge/2);let Ee;for(Ee=0;Ee<te;++Ee){let qt=parseInt(U.substr(Ee*2,2),16);if(nr(qt))return Ee;T[N+Ee]=qt}return Ee}function z(T,U,N,te){return Ys(Te(U,T.length-N),T,N,te)}function L(T,U,N,te){return Ys(Rt(U),T,N,te)}function B(T,U,N,te){return Ys(Kr(U),T,N,te)}function W(T,U,N,te){return Ys(ti(U,T.length-N),T,N,te)}o.prototype.write=function(T,U,N,te){if(U===void 0)te="utf8",N=this.length,U=0;else if(N===void 0&&typeof U=="string")te=U,N=this.length,U=0;else if(isFinite(U))U=U>>>0,isFinite(N)?(N=N>>>0,te===void 0&&(te="utf8")):(te=N,N=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let ce=this.length-U;if((N===void 0||N>ce)&&(N=ce),T.length>0&&(N<0||U<0)||U>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");let ge=!1;for(;;)switch(te){case"hex":return C(this,T,U,N);case"utf8":case"utf-8":return z(this,T,U,N);case"ascii":case"latin1":case"binary":return L(this,T,U,N);case"base64":return B(this,T,U,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return W(this,T,U,N);default:if(ge)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),ge=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ee(T,U,N){return U===0&&N===T.length?e.fromByteArray(T):e.fromByteArray(T.slice(U,N))}function R(T,U,N){N=Math.min(T.length,N);let te=[],ce=U;for(;ce<N;){let ge=T[ce],Ee=null,qt=ge>239?4:ge>223?3:ge>191?2:1;if(ce+qt<=N){let ri,Gr,Er,hr;switch(qt){case 1:ge<128&&(Ee=ge);break;case 2:ri=T[ce+1],(ri&192)===128&&(hr=(ge&31)<<6|ri&63,hr>127&&(Ee=hr));break;case 3:ri=T[ce+1],Gr=T[ce+2],(ri&192)===128&&(Gr&192)===128&&(hr=(ge&15)<<12|(ri&63)<<6|Gr&63,hr>2047&&(hr<55296||hr>57343)&&(Ee=hr));break;case 4:ri=T[ce+1],Gr=T[ce+2],Er=T[ce+3],(ri&192)===128&&(Gr&192)===128&&(Er&192)===128&&(hr=(ge&15)<<18|(ri&63)<<12|(Gr&63)<<6|Er&63,hr>65535&&hr<1114112&&(Ee=hr))}}Ee===null?(Ee=65533,qt=1):Ee>65535&&(Ee-=65536,te.push(Ee>>>10&1023|55296),Ee=56320|Ee&1023),te.push(Ee),ce+=qt}return S(te)}var $=4096;function S(T){let U=T.length;if(U<=$)return String.fromCharCode.apply(String,T);let N="",te=0;for(;te<U;)N+=String.fromCharCode.apply(String,T.slice(te,te+=$));return N}function x(T,U,N){let te="";N=Math.min(T.length,N);for(let ce=U;ce<N;++ce)te+=String.fromCharCode(T[ce]&127);return te}function P(T,U,N){let te="";N=Math.min(T.length,N);for(let ce=U;ce<N;++ce)te+=String.fromCharCode(T[ce]);return te}function k(T,U,N){let te=T.length;(!U||U<0)&&(U=0),(!N||N<0||N>te)&&(N=te);let ce="";for(let ge=U;ge<N;++ge)ce+=Ur[T[ge]];return ce}function I(T,U,N){let te=T.slice(U,N),ce="";for(let ge=0;ge<te.length-1;ge+=2)ce+=String.fromCharCode(te[ge]+te[ge+1]*256);return ce}o.prototype.slice=function(T,U){let N=this.length;T=~~T,U=U===void 0?N:~~U,T<0?(T+=N,T<0&&(T=0)):T>N&&(T=N),U<0?(U+=N,U<0&&(U=0)):U>N&&(U=N),U<T&&(U=T);let te=this.subarray(T,U);return Object.setPrototypeOf(te,o.prototype),te};function j(T,U,N){if(T%1!==0||T<0)throw new RangeError("offset is not uint");if(T+U>N)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(T,U,N){T=T>>>0,U=U>>>0,N||j(T,U,this.length);let te=this[T],ce=1,ge=0;for(;++ge<U&&(ce*=256);)te+=this[T+ge]*ce;return te},o.prototype.readUintBE=o.prototype.readUIntBE=function(T,U,N){T=T>>>0,U=U>>>0,N||j(T,U,this.length);let te=this[T+--U],ce=1;for(;U>0&&(ce*=256);)te+=this[T+--U]*ce;return te},o.prototype.readUint8=o.prototype.readUInt8=function(T,U){return T=T>>>0,U||j(T,1,this.length),this[T]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(T,U){return T=T>>>0,U||j(T,2,this.length),this[T]|this[T+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(T,U){return T=T>>>0,U||j(T,2,this.length),this[T]<<8|this[T+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(T,U){return T=T>>>0,U||j(T,4,this.length),(this[T]|this[T+1]<<8|this[T+2]<<16)+this[T+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(T,U){return T=T>>>0,U||j(T,4,this.length),this[T]*16777216+(this[T+1]<<16|this[T+2]<<8|this[T+3])},o.prototype.readBigUInt64LE=pr(function(T){T=T>>>0,pe(T,"offset");let U=this[T],N=this[T+7];(U===void 0||N===void 0)&&le(T,this.length-8);let te=U+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24,ce=this[++T]+this[++T]*2**8+this[++T]*2**16+N*2**24;return BigInt(te)+(BigInt(ce)<<BigInt(32))}),o.prototype.readBigUInt64BE=pr(function(T){T=T>>>0,pe(T,"offset");let U=this[T],N=this[T+7];(U===void 0||N===void 0)&&le(T,this.length-8);let te=U*2**24+this[++T]*2**16+this[++T]*2**8+this[++T],ce=this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+N;return(BigInt(te)<<BigInt(32))+BigInt(ce)}),o.prototype.readIntLE=function(T,U,N){T=T>>>0,U=U>>>0,N||j(T,U,this.length);let te=this[T],ce=1,ge=0;for(;++ge<U&&(ce*=256);)te+=this[T+ge]*ce;return ce*=128,te>=ce&&(te-=Math.pow(2,8*U)),te},o.prototype.readIntBE=function(T,U,N){T=T>>>0,U=U>>>0,N||j(T,U,this.length);let te=U,ce=1,ge=this[T+--te];for(;te>0&&(ce*=256);)ge+=this[T+--te]*ce;return ce*=128,ge>=ce&&(ge-=Math.pow(2,8*U)),ge},o.prototype.readInt8=function(T,U){return T=T>>>0,U||j(T,1,this.length),this[T]&128?(255-this[T]+1)*-1:this[T]},o.prototype.readInt16LE=function(T,U){T=T>>>0,U||j(T,2,this.length);let N=this[T]|this[T+1]<<8;return N&32768?N|4294901760:N},o.prototype.readInt16BE=function(T,U){T=T>>>0,U||j(T,2,this.length);let N=this[T+1]|this[T]<<8;return N&32768?N|4294901760:N},o.prototype.readInt32LE=function(T,U){return T=T>>>0,U||j(T,4,this.length),this[T]|this[T+1]<<8|this[T+2]<<16|this[T+3]<<24},o.prototype.readInt32BE=function(T,U){return T=T>>>0,U||j(T,4,this.length),this[T]<<24|this[T+1]<<16|this[T+2]<<8|this[T+3]},o.prototype.readBigInt64LE=pr(function(T){T=T>>>0,pe(T,"offset");let U=this[T],N=this[T+7];(U===void 0||N===void 0)&&le(T,this.length-8);let te=this[T+4]+this[T+5]*2**8+this[T+6]*2**16+(N<<24);return(BigInt(te)<<BigInt(32))+BigInt(U+this[++T]*2**8+this[++T]*2**16+this[++T]*2**24)}),o.prototype.readBigInt64BE=pr(function(T){T=T>>>0,pe(T,"offset");let U=this[T],N=this[T+7];(U===void 0||N===void 0)&&le(T,this.length-8);let te=(U<<24)+this[++T]*2**16+this[++T]*2**8+this[++T];return(BigInt(te)<<BigInt(32))+BigInt(this[++T]*2**24+this[++T]*2**16+this[++T]*2**8+N)}),o.prototype.readFloatLE=function(T,U){return T=T>>>0,U||j(T,4,this.length),t.read(this,T,!0,23,4)},o.prototype.readFloatBE=function(T,U){return T=T>>>0,U||j(T,4,this.length),t.read(this,T,!1,23,4)},o.prototype.readDoubleLE=function(T,U){return T=T>>>0,U||j(T,8,this.length),t.read(this,T,!0,52,8)},o.prototype.readDoubleBE=function(T,U){return T=T>>>0,U||j(T,8,this.length),t.read(this,T,!1,52,8)};function q(T,U,N,te,ce,ge){if(!o.isBuffer(T))throw new TypeError('"buffer" argument must be a Buffer instance');if(U>ce||U<ge)throw new RangeError('"value" argument is out of bounds');if(N+te>T.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(T,U,N,te){if(T=+T,U=U>>>0,N=N>>>0,!te){let Ee=Math.pow(2,8*N)-1;q(this,T,U,N,Ee,0)}let ce=1,ge=0;for(this[U]=T&255;++ge<N&&(ce*=256);)this[U+ge]=T/ce&255;return U+N},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(T,U,N,te){if(T=+T,U=U>>>0,N=N>>>0,!te){let Ee=Math.pow(2,8*N)-1;q(this,T,U,N,Ee,0)}let ce=N-1,ge=1;for(this[U+ce]=T&255;--ce>=0&&(ge*=256);)this[U+ce]=T/ge&255;return U+N},o.prototype.writeUint8=o.prototype.writeUInt8=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,1,255,0),this[U]=T&255,U+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,2,65535,0),this[U]=T&255,this[U+1]=T>>>8,U+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,2,65535,0),this[U]=T>>>8,this[U+1]=T&255,U+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,4,4294967295,0),this[U+3]=T>>>24,this[U+2]=T>>>16,this[U+1]=T>>>8,this[U]=T&255,U+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,4,4294967295,0),this[U]=T>>>24,this[U+1]=T>>>16,this[U+2]=T>>>8,this[U+3]=T&255,U+4};function H(T,U,N,te,ce){de(U,te,ce,T,N,7);let ge=Number(U&BigInt(4294967295));T[N++]=ge,ge=ge>>8,T[N++]=ge,ge=ge>>8,T[N++]=ge,ge=ge>>8,T[N++]=ge;let Ee=Number(U>>BigInt(32)&BigInt(4294967295));return T[N++]=Ee,Ee=Ee>>8,T[N++]=Ee,Ee=Ee>>8,T[N++]=Ee,Ee=Ee>>8,T[N++]=Ee,N}function J(T,U,N,te,ce){de(U,te,ce,T,N,7);let ge=Number(U&BigInt(4294967295));T[N+7]=ge,ge=ge>>8,T[N+6]=ge,ge=ge>>8,T[N+5]=ge,ge=ge>>8,T[N+4]=ge;let Ee=Number(U>>BigInt(32)&BigInt(4294967295));return T[N+3]=Ee,Ee=Ee>>8,T[N+2]=Ee,Ee=Ee>>8,T[N+1]=Ee,Ee=Ee>>8,T[N]=Ee,N+8}o.prototype.writeBigUInt64LE=pr(function(T,U=0){return H(this,T,U,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=pr(function(T,U=0){return J(this,T,U,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(T,U,N,te){if(T=+T,U=U>>>0,!te){let qt=Math.pow(2,8*N-1);q(this,T,U,N,qt-1,-qt)}let ce=0,ge=1,Ee=0;for(this[U]=T&255;++ce<N&&(ge*=256);)T<0&&Ee===0&&this[U+ce-1]!==0&&(Ee=1),this[U+ce]=(T/ge>>0)-Ee&255;return U+N},o.prototype.writeIntBE=function(T,U,N,te){if(T=+T,U=U>>>0,!te){let qt=Math.pow(2,8*N-1);q(this,T,U,N,qt-1,-qt)}let ce=N-1,ge=1,Ee=0;for(this[U+ce]=T&255;--ce>=0&&(ge*=256);)T<0&&Ee===0&&this[U+ce+1]!==0&&(Ee=1),this[U+ce]=(T/ge>>0)-Ee&255;return U+N},o.prototype.writeInt8=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,1,127,-128),T<0&&(T=255+T+1),this[U]=T&255,U+1},o.prototype.writeInt16LE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,2,32767,-32768),this[U]=T&255,this[U+1]=T>>>8,U+2},o.prototype.writeInt16BE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,2,32767,-32768),this[U]=T>>>8,this[U+1]=T&255,U+2},o.prototype.writeInt32LE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,4,2147483647,-2147483648),this[U]=T&255,this[U+1]=T>>>8,this[U+2]=T>>>16,this[U+3]=T>>>24,U+4},o.prototype.writeInt32BE=function(T,U,N){return T=+T,U=U>>>0,N||q(this,T,U,4,2147483647,-2147483648),T<0&&(T=4294967295+T+1),this[U]=T>>>24,this[U+1]=T>>>16,this[U+2]=T>>>8,this[U+3]=T&255,U+4},o.prototype.writeBigInt64LE=pr(function(T,U=0){return H(this,T,U,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=pr(function(T,U=0){return J(this,T,U,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function V(T,U,N,te,ce,ge){if(N+te>T.length)throw new RangeError("Index out of range");if(N<0)throw new RangeError("Index out of range")}function Z(T,U,N,te,ce){return U=+U,N=N>>>0,ce||V(T,U,N,4,34028234663852886e22,-34028234663852886e22),t.write(T,U,N,te,23,4),N+4}o.prototype.writeFloatLE=function(T,U,N){return Z(this,T,U,!0,N)},o.prototype.writeFloatBE=function(T,U,N){return Z(this,T,U,!1,N)};function F(T,U,N,te,ce){return U=+U,N=N>>>0,ce||V(T,U,N,8,17976931348623157e292,-17976931348623157e292),t.write(T,U,N,te,52,8),N+8}o.prototype.writeDoubleLE=function(T,U,N){return F(this,T,U,!0,N)},o.prototype.writeDoubleBE=function(T,U,N){return F(this,T,U,!1,N)},o.prototype.copy=function(T,U,N,te){if(!o.isBuffer(T))throw new TypeError("argument should be a Buffer");if(N||(N=0),!te&&te!==0&&(te=this.length),U>=T.length&&(U=T.length),U||(U=0),te>0&&te<N&&(te=N),te===N||T.length===0||this.length===0)return 0;if(U<0)throw new RangeError("targetStart out of bounds");if(N<0||N>=this.length)throw new RangeError("Index out of range");if(te<0)throw new RangeError("sourceEnd out of bounds");te>this.length&&(te=this.length),T.length-U<te-N&&(te=T.length-U+N);let ce=te-N;return this===T&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(U,N,te):Uint8Array.prototype.set.call(T,this.subarray(N,te),U),ce},o.prototype.fill=function(T,U,N,te){if(typeof T=="string"){if(typeof U=="string"?(te=U,U=0,N=this.length):typeof N=="string"&&(te=N,N=this.length),te!==void 0&&typeof te!="string")throw new TypeError("encoding must be a string");if(typeof te=="string"&&!o.isEncoding(te))throw new TypeError("Unknown encoding: "+te);if(T.length===1){let ge=T.charCodeAt(0);(te==="utf8"&&ge<128||te==="latin1")&&(T=ge)}}else typeof T=="number"?T=T&255:typeof T=="boolean"&&(T=Number(T));if(U<0||this.length<U||this.length<N)throw new RangeError("Out of range index");if(N<=U)return this;U=U>>>0,N=N===void 0?this.length:N>>>0,T||(T=0);let ce;if(typeof T=="number")for(ce=U;ce<N;++ce)this[ce]=T;else{let ge=o.isBuffer(T)?T:o.from(T,te),Ee=ge.length;if(Ee===0)throw new TypeError('The value "'+T+'" is invalid for argument "value"');for(ce=0;ce<N-U;++ce)this[ce+U]=ge[ce%Ee]}return this};var X={};function ie(T,U,N){X[T]=class extends N{constructor(){super(),Object.defineProperty(this,"message",{value:U.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${T}]`,this.stack,delete this.name}get code(){return T}set code(te){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:te,writable:!0})}toString(){return`${this.name} [${T}]: ${this.message}`}}}ie("ERR_BUFFER_OUT_OF_BOUNDS",function(T){return T?`${T} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),ie("ERR_INVALID_ARG_TYPE",function(T,U){return`The "${T}" argument must be of type number. Received type ${typeof U}`},TypeError),ie("ERR_OUT_OF_RANGE",function(T,U,N){let te=`The value of "${T}" is out of range.`,ce=N;return Number.isInteger(N)&&Math.abs(N)>2**32?ce=se(String(N)):typeof N=="bigint"&&(ce=String(N),(N>BigInt(2)**BigInt(32)||N<-(BigInt(2)**BigInt(32)))&&(ce=se(ce)),ce+="n"),te+=` It must be ${U}. Received ${ce}`,te},RangeError);function se(T){let U="",N=T.length,te=T[0]==="-"?1:0;for(;N>=te+4;N-=3)U=`_${T.slice(N-3,N)}${U}`;return`${T.slice(0,N)}${U}`}function Y(T,U,N){pe(U,"offset"),(T[U]===void 0||T[U+N]===void 0)&&le(U,T.length-(N+1))}function de(T,U,N,te,ce,ge){if(T>N||T<U){let Ee=typeof U=="bigint"?"n":"",qt;throw ge>3?U===0||U===BigInt(0)?qt=`>= 0${Ee} and < 2${Ee} ** ${(ge+1)*8}${Ee}`:qt=`>= -(2${Ee} ** ${(ge+1)*8-1}${Ee}) and < 2 ** ${(ge+1)*8-1}${Ee}`:qt=`>= ${U}${Ee} and <= ${N}${Ee}`,new X.ERR_OUT_OF_RANGE("value",qt,T)}Y(te,ce,ge)}function pe(T,U){if(typeof T!="number")throw new X.ERR_INVALID_ARG_TYPE(U,"number",T)}function le(T,U,N){throw Math.floor(T)!==T?(pe(T,N),new X.ERR_OUT_OF_RANGE(N||"offset","an integer",T)):U<0?new X.ERR_BUFFER_OUT_OF_BOUNDS:new X.ERR_OUT_OF_RANGE(N||"offset",`>= ${N?1:0} and <= ${U}`,T)}var Se=/[^+/0-9A-Za-z-_]/g;function he(T){if(T=T.split("=")[0],T=T.trim().replace(Se,""),T.length<2)return"";for(;T.length%4!==0;)T=T+"=";return T}function Te(T,U){U=U||1/0;let N,te=T.length,ce=null,ge=[];for(let Ee=0;Ee<te;++Ee){if(N=T.charCodeAt(Ee),N>55295&&N<57344){if(!ce){if(N>56319){(U-=3)>-1&&ge.push(239,191,189);continue}else if(Ee+1===te){(U-=3)>-1&&ge.push(239,191,189);continue}ce=N;continue}if(N<56320){(U-=3)>-1&&ge.push(239,191,189),ce=N;continue}N=(ce-55296<<10|N-56320)+65536}else ce&&(U-=3)>-1&&ge.push(239,191,189);if(ce=null,N<128){if((U-=1)<0)break;ge.push(N)}else if(N<2048){if((U-=2)<0)break;ge.push(N>>6|192,N&63|128)}else if(N<65536){if((U-=3)<0)break;ge.push(N>>12|224,N>>6&63|128,N&63|128)}else if(N<1114112){if((U-=4)<0)break;ge.push(N>>18|240,N>>12&63|128,N>>6&63|128,N&63|128)}else throw new Error("Invalid code point")}return ge}function Rt(T){let U=[];for(let N=0;N<T.length;++N)U.push(T.charCodeAt(N)&255);return U}function ti(T,U){let N,te,ce,ge=[];for(let Ee=0;Ee<T.length&&!((U-=2)<0);++Ee)N=T.charCodeAt(Ee),te=N>>8,ce=N%256,ge.push(ce),ge.push(te);return ge}function Kr(T){return e.toByteArray(he(T))}function Ys(T,U,N,te){let ce;for(ce=0;ce<te&&!(ce+N>=U.length||ce>=T.length);++ce)U[ce+N]=T[ce];return ce}function We(T,U){return T instanceof U||T!=null&&T.constructor!=null&&T.constructor.name!=null&&T.constructor.name===U.name}function nr(T){return T!==T}var Ur=function(){let T="0123456789abcdef",U=new Array(256);for(let N=0;N<16;++N){let te=N*16;for(let ce=0;ce<16;++ce)U[te+ce]=T[N]+T[ce]}return U}();function pr(T){return typeof BigInt>"u"?Lt:T}function Lt(){throw new Error("BigInt not supported")}}),gz=Zt((r,e)=>{"use strict";var t=null;e.exports=function(){return t===null&&(t={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),t}}),wz=Zt(r=>{"use strict";var e=Md(),t=new Set(["buffer","view","utf8"]),n=class{constructor(i){if(this.encode=i.encode||this.encode,this.decode=i.decode||this.decode,this.name=i.name||this.name,this.format=i.format||this.format,typeof this.encode!="function")throw new TypeError("The 'encode' property must be a function");if(typeof this.decode!="function")throw new TypeError("The 'decode' property must be a function");if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),typeof this.name!="string"||this.name==="")throw new TypeError("The 'name' property must be a string");if(typeof this.format!="string"||!t.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");i.createViewTranscoder&&(this.createViewTranscoder=i.createViewTranscoder),i.createBufferTranscoder&&(this.createBufferTranscoder=i.createBufferTranscoder),i.createUTF8Transcoder&&(this.createUTF8Transcoder=i.createUTF8Transcoder)}get commonName(){return this.name.split("+")[0]}createBufferTranscoder(){throw new e(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new e(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new e(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};r.Encoding=n}),vz=Zt(r=>{"use strict";var{Buffer:e}=CC()||{},{Encoding:t}=wz(),n=gz(),i=class extends t{constructor(o){super({...o,format:"buffer"})}createViewTranscoder(){return new a({encode:this.encode,decode:o=>this.decode(e.from(o.buffer,o.byteOffset,o.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},a=class extends t{constructor(o){super({...o,format:"view"})}createBufferTranscoder(){return new i({encode:o=>{let c=this.encode(o);return e.from(c.buffer,c.byteOffset,c.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},s=class extends t{constructor(o){super({...o,format:"utf8"})}createBufferTranscoder(){return new i({encode:o=>e.from(this.encode(o),"utf8"),decode:o=>this.decode(o.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:o,textDecoder:c}=n();return new a({encode:l=>o.encode(this.encode(l)),decode:l=>this.decode(c.decode(l)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};r.BufferFormat=i,r.ViewFormat=a,r.UTF8Format=s}),Fde=Zt(r=>{"use strict";var{Buffer:e}=CC()||{Buffer:{isBuffer:()=>!1}},{textEncoder:t,textDecoder:n}=gz()(),{BufferFormat:i,ViewFormat:a,UTF8Format:s}=vz(),o=c=>c;r.utf8=new s({encode:function(c){return e.isBuffer(c)?c.toString("utf8"):ArrayBuffer.isView(c)?n.decode(c):String(c)},decode:o,name:"utf8",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:t.encode(c)},decode:function(c){return n.decode(c)},name:`${this.name}+view`})},createBufferTranscoder(){return new i({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:function(c){return c.toString("utf8")},name:`${this.name}+buffer`})}}),r.json=new s({encode:JSON.stringify,decode:JSON.parse,name:"json"}),r.buffer=new i({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:o,name:"buffer",createViewTranscoder(){return new a({encode:function(c){return ArrayBuffer.isView(c)?c:e.from(String(c),"utf8")},decode:function(c){return e.from(c.buffer,c.byteOffset,c.byteLength)},name:`${this.name}+view`})}}),r.view=new a({encode:function(c){return ArrayBuffer.isView(c)?c:t.encode(c)},decode:o,name:"view",createBufferTranscoder(){return new i({encode:function(c){return e.isBuffer(c)?c:ArrayBuffer.isView(c)?e.from(c.buffer,c.byteOffset,c.byteLength):e.from(String(c),"utf8")},decode:o,name:`${this.name}+buffer`})}}),r.hex=new i({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"hex")},decode:function(c){return c.toString("hex")},name:"hex"}),r.base64=new i({encode:function(c){return e.isBuffer(c)?c:e.from(String(c),"base64")},decode:function(c){return c.toString("base64")},name:"base64"})}),Gde=Zt(r=>{"use strict";var e=Md(),t=Fde(),{Encoding:n}=wz(),{BufferFormat:i,ViewFormat:a,UTF8Format:s}=vz(),o=Symbol("formats"),c=Symbol("encodings"),l=new Set(["buffer","view","utf8"]),d=class{constructor(y){if(Array.isArray(y)){if(!y.every(v=>l.has(v)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[c]=new Map,this[o]=new Set(y);for(let v in t)try{this.encoding(v)}catch(w){if(w.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw w}}encodings(){return Array.from(new Set(this[c].values()))}encoding(y){let v=this[c].get(y);if(v===void 0){if(typeof y=="string"&&y!==""){if(v=h[y],!v)throw new e(`Encoding '${y}' is not found`,{code:"LEVEL_ENCODING_NOT_FOUND"})}else{if(typeof y!="object"||y===null)throw new TypeError("First argument 'encoding' must be a string or object");v=u(y)}let{name:w,format:E}=v;if(!this[o].has(E))if(this[o].has("view"))v=v.createViewTranscoder();else if(this[o].has("buffer"))v=v.createBufferTranscoder();else if(this[o].has("utf8"))v=v.createUTF8Transcoder();else throw new e(`Encoding '${w}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let _ of[y,w,v.name,v.commonName])this[c].set(_,v)}return v}};r.Transcoder=d;function u(y){if(y instanceof n)return y;let v="type"in y&&typeof y.type=="string"?y.type:void 0,w=y.name||v||`anonymous-${m++}`;switch(f(y)){case"view":return new a({...y,name:w});case"utf8":return new s({...y,name:w});case"buffer":return new i({...y,name:w});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function f(y){return"format"in y&&y.format!==void 0?y.format:"buffer"in y&&typeof y.buffer=="boolean"?y.buffer?"buffer":"utf8":"code"in y&&Number.isInteger(y.code)?"view":"buffer"}var p={binary:t.buffer,"utf-8":t.utf8},h={...t,...p},m=0}),Hde=Zt((r,e)=>{"use strict";var t=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function a(l,d,u){this.fn=l,this.context=d,this.once=u||!1}function s(l,d,u,f,p){if(typeof u!="function")throw new TypeError("The listener must be a function");var h=new a(u,f||l,p),m=n?n+d:d;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],h]:l._events[m].push(h):(l._events[m]=h,l._eventsCount++),l}function o(l,d){--l._eventsCount===0?l._events=new i:delete l._events[d]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var l=[],d,u;if(this._eventsCount===0)return l;for(u in d=this._events)t.call(d,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(d)):l},c.prototype.listeners=function(l){var d=n?n+l:l,u=this._events[d];if(!u)return[];if(u.fn)return[u.fn];for(var f=0,p=u.length,h=new Array(p);f<p;f++)h[f]=u[f].fn;return h},c.prototype.listenerCount=function(l){var d=n?n+l:l,u=this._events[d];return u?u.fn?1:u.length:0},c.prototype.emit=function(l,d,u,f,p,h){var m=n?n+l:l;if(!this._events[m])return!1;var y=this._events[m],v=arguments.length,w,E;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),v){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,d),!0;case 3:return y.fn.call(y.context,d,u),!0;case 4:return y.fn.call(y.context,d,u,f),!0;case 5:return y.fn.call(y.context,d,u,f,p),!0;case 6:return y.fn.call(y.context,d,u,f,p,h),!0}for(E=1,w=new Array(v-1);E<v;E++)w[E-1]=arguments[E];y.fn.apply(y.context,w)}else{var _=y.length,A;for(E=0;E<_;E++)switch(y[E].once&&this.removeListener(l,y[E].fn,void 0,!0),v){case 1:y[E].fn.call(y[E].context);break;case 2:y[E].fn.call(y[E].context,d);break;case 3:y[E].fn.call(y[E].context,d,u);break;case 4:y[E].fn.call(y[E].context,d,u,f);break;default:if(!w)for(A=1,w=new Array(v-1);A<v;A++)w[A-1]=arguments[A];y[E].fn.apply(y[E].context,w)}}return!0},c.prototype.on=function(l,d,u){return s(this,l,d,u,!1)},c.prototype.once=function(l,d,u){return s(this,l,d,u,!0)},c.prototype.removeListener=function(l,d,u,f){var p=n?n+l:l;if(!this._events[p])return this;if(!d)return o(this,p),this;var h=this._events[p];if(h.fn)h.fn===d&&(!f||h.once)&&(!u||h.context===u)&&o(this,p);else{for(var m=0,y=[],v=h.length;m<v;m++)(h[m].fn!==d||f&&!h[m].once||u&&h[m].context!==u)&&y.push(h[m]);y.length?this._events[p]=y.length===1?y[0]:y:o(this,p)}return this},c.prototype.removeAllListeners=function(l){var d;return l?(d=n?n+l:l,this._events[d]&&o(this,d)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,typeof e<"u"&&(e.exports=c)}),Vde=Zt((r,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)}),dE=Zt(r=>{"use strict";var e=Vde();r.fromCallback=function(t,n){if(t===void 0){var i=new Promise(function(a,s){t=function(o,c){o?s(o):a(c)}});t[n!==void 0?n:"promise"]=i}else if(typeof t!="function")throw new TypeError("Callback must be a function");return t},r.fromPromise=function(t,n){if(n===void 0)return t;t.then(function(i){e(()=>n(null,i))}).catch(function(i){e(()=>n(i))})}}),$C=Zt(r=>{"use strict";r.getCallback=function(e,t){return typeof e=="function"?e:t},r.getOptions=function(e,t){return typeof e=="object"&&e!==null?e:t!==void 0?t:{}}}),fh=Zt(r=>{"use strict";var{fromCallback:e}=dE(),t=Md(),{getOptions:n,getCallback:i}=$C(),a=Symbol("promise"),s=Symbol("callback"),o=Symbol("working"),c=Symbol("handleOne"),l=Symbol("handleMany"),d=Symbol("autoClose"),u=Symbol("finishWork"),f=Symbol("returnMany"),p=Symbol("closing"),h=Symbol("handleClose"),m=Symbol("closed"),y=Symbol("closeCallbacks"),v=Symbol("keyEncoding"),w=Symbol("valueEncoding"),E=Symbol("abortOnClose"),_=Symbol("legacy"),A=Symbol("keys"),D=Symbol("values"),M=Symbol("limit"),C=Symbol("count"),z=Object.freeze({}),L=()=>{},B=!1,W=class{constructor(x,P,k){if(typeof x!="object"||x===null){let I=x===null?"null":typeof x;throw new TypeError(`The first argument must be an abstract-level database, received ${I}`)}if(typeof P!="object"||P===null)throw new TypeError("The second argument must be an options object");this[m]=!1,this[y]=[],this[o]=!1,this[p]=!1,this[d]=!1,this[s]=null,this[c]=this[c].bind(this),this[l]=this[l].bind(this),this[h]=this[h].bind(this),this[v]=P[v],this[w]=P[w],this[_]=k,this[M]=Number.isInteger(P.limit)&&P.limit>=0?P.limit:1/0,this[C]=0,this[E]=!!P.abortOnClose,this.db=x,this.db.attachResource(this),this.nextTick=x.nextTick}get count(){return this[C]}get limit(){return this[M]}next(x){let P;if(x===void 0)P=new Promise((k,I)=>{x=(j,q,H)=>{j?I(j):this[_]?q===void 0&&H===void 0?k():k([q,H]):k(q)}});else if(typeof x!="function")throw new TypeError("Callback must be a function");return this[p]?this.nextTick(x,new t("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[o]?this.nextTick(x,new t("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[o]=!0,this[s]=x,this[C]>=this[M]?this.nextTick(this[c],null):this._next(this[c])),P}_next(x){this.nextTick(x)}nextv(x,P,k){return k=i(P,k),k=e(k,a),P=n(P,z),Number.isInteger(x)?(this[p]?this.nextTick(k,new t("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[o]?this.nextTick(k,new t("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(x<1&&(x=1),this[M]<1/0&&(x=Math.min(x,this[M]-this[C])),this[o]=!0,this[s]=k,x<=0?this.nextTick(this[l],null,[]):this._nextv(x,P,this[l])),k[a]):(this.nextTick(k,new TypeError("The first argument 'size' must be an integer")),k[a])}_nextv(x,P,k){let I=[],j=(q,H,J)=>{if(q)return k(q);if(this[_]?H===void 0&&J===void 0:H===void 0)return k(null,I);I.push(this[_]?[H,J]:H),I.length===x?k(null,I):this._next(j)};this._next(j)}all(x,P){return P=i(x,P),P=e(P,a),x=n(x,z),this[p]?this.nextTick(P,new t("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[o]?this.nextTick(P,new t("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[o]=!0,this[s]=P,this[d]=!0,this[C]>=this[M]?this.nextTick(this[l],null,[]):this._all(x,this[l])),P[a]}_all(x,P){let k=this[C],I=[],j=()=>{let H=this[M]<1/0?Math.min(1e3,this[M]-k):1e3;H<=0?this.nextTick(P,null,I):this._nextv(H,z,q)},q=(H,J)=>{H?P(H):J.length===0?P(null,I):(I.push.apply(I,J),k+=J.length,j())};j()}[u](){let x=this[s];return this[E]&&x===null?L:(this[o]=!1,this[s]=null,this[p]&&this._close(this[h]),x)}[f](x,P,k){this[d]?this.close(x.bind(null,P,k)):x(P,k)}seek(x,P){if(P=n(P,z),!this[p]){if(this[o])throw new t("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let k=this.db.keyEncoding(P.keyEncoding||this[v]),I=k.format;P.keyEncoding!==I&&(P={...P,keyEncoding:I});let j=this.db.prefixKey(k.encode(x),I);this._seek(j,P)}}}_seek(x,P){throw new t("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(x){return x=e(x,a),this[m]?this.nextTick(x):this[p]?this[y].push(x):(this[p]=!0,this[y].push(x),this[o]?this[E]&&this[u]()(new t("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[h])),x[a]}_close(x){this.nextTick(x)}[h](){this[m]=!0,this.db.detachResource(this);let x=this[y];this[y]=[];for(let P of x)P()}async*[Symbol.asyncIterator](){try{let x;for(;(x=await this.next())!==void 0;)yield x}finally{this[m]||await this.close()}}},ee=class extends W{constructor(x,P){super(x,P,!0),this[A]=P.keys!==!1,this[D]=P.values!==!1}[c](x,P,k){let I=this[u]();if(x)return I(x);try{P=this[A]&&P!==void 0?this[v].decode(P):void 0,k=this[D]&&k!==void 0?this[w].decode(k):void 0}catch(j){return I(new S("entry",j))}P===void 0&&k===void 0||this[C]++,I(null,P,k)}[l](x,P){let k=this[u]();if(x)return this[f](k,x);try{for(let I of P){let j=I[0],q=I[1];I[0]=this[A]&&j!==void 0?this[v].decode(j):void 0,I[1]=this[D]&&q!==void 0?this[w].decode(q):void 0}}catch(I){return this[f](k,new S("entries",I))}this[C]+=P.length,this[f](k,null,P)}end(x){return!B&&typeof console<"u"&&(B=!0,console.warn(new t("The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version",{code:"LEVEL_LEGACY"}))),this.close(x)}},R=class extends W{constructor(x,P){super(x,P,!1)}[c](x,P){let k=this[u]();if(x)return k(x);try{P=P!==void 0?this[v].decode(P):void 0}catch(I){return k(new S("key",I))}P!==void 0&&this[C]++,k(null,P)}[l](x,P){let k=this[u]();if(x)return this[f](k,x);try{for(let I=0;I<P.length;I++){let j=P[I];P[I]=j!==void 0?this[v].decode(j):void 0}}catch(I){return this[f](k,new S("keys",I))}this[C]+=P.length,this[f](k,null,P)}},$=class extends W{constructor(x,P){super(x,P,!1)}[c](x,P){let k=this[u]();if(x)return k(x);try{P=P!==void 0?this[w].decode(P):void 0}catch(I){return k(new S("value",I))}P!==void 0&&this[C]++,k(null,P)}[l](x,P){let k=this[u]();if(x)return this[f](k,x);try{for(let I=0;I<P.length;I++){let j=P[I];P[I]=j!==void 0?this[w].decode(j):void 0}}catch(I){return this[f](k,new S("values",I))}this[C]+=P.length,this[f](k,null,P)}},S=class extends t{constructor(x,P){super(`Iterator could not decode ${x}`,{code:"LEVEL_DECODE_ERROR",cause:P})}};for(let x of["_ended property","_nexting property","_end method"])Object.defineProperty(ee.prototype,x.split(" ")[0],{get(){throw new t(`The ${x} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new t(`The ${x} has been removed`,{code:"LEVEL_LEGACY"})}});ee.keyEncoding=v,ee.valueEncoding=w,r.AbstractIterator=ee,r.AbstractKeyIterator=R,r.AbstractValueIterator=$}),Wde=Zt(r=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:t}=fh(),n=Symbol("iterator"),i=Symbol("callback"),a=Symbol("handleOne"),s=Symbol("handleMany"),o=class extends e{constructor(l,d){super(l,d),this[n]=l.iterator({...d,keys:!0,values:!1}),this[a]=this[a].bind(this),this[s]=this[s].bind(this)}},c=class extends t{constructor(l,d){super(l,d),this[n]=l.iterator({...d,keys:!1,values:!0}),this[a]=this[a].bind(this),this[s]=this[s].bind(this)}};for(let l of[o,c]){let d=l===o,u=d?f=>f[0]:f=>f[1];l.prototype._next=function(f){this[i]=f,this[n].next(this[a])},l.prototype[a]=function(f,p,h){let m=this[i];f?m(f):m(null,d?p:h)},l.prototype._nextv=function(f,p,h){this[i]=h,this[n].nextv(f,p,this[s])},l.prototype._all=function(f,p){this[i]=p,this[n].all(f,this[s])},l.prototype[s]=function(f,p){let h=this[i];f?h(f):h(null,p.map(u))},l.prototype._seek=function(f,p){this[n].seek(f,p)},l.prototype._close=function(f){this[n].close(f)}}r.DefaultKeyIterator=o,r.DefaultValueIterator=c}),Jde=Zt(r=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:t,AbstractValueIterator:n}=fh(),i=Md(),a=Symbol("nut"),s=Symbol("undefer"),o=Symbol("factory"),c=class extends e{constructor(u,f){super(u,f),this[a]=null,this[o]=()=>u.iterator(f),this.db.defer(()=>this[s]())}},l=class extends t{constructor(u,f){super(u,f),this[a]=null,this[o]=()=>u.keys(f),this.db.defer(()=>this[s]())}},d=class extends n{constructor(u,f){super(u,f),this[a]=null,this[o]=()=>u.values(f),this.db.defer(()=>this[s]())}};for(let u of[c,l,d])u.prototype[s]=function(){this.db.status==="open"&&(this[a]=this[o]())},u.prototype._next=function(f){this[a]!==null?this[a].next(f):this.db.status==="opening"?this.db.defer(()=>this._next(f)):this.nextTick(f,new i("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._nextv=function(f,p,h){this[a]!==null?this[a].nextv(f,p,h):this.db.status==="opening"?this.db.defer(()=>this._nextv(f,p,h)):this.nextTick(h,new i("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._all=function(f,p){this[a]!==null?this[a].all(p):this.db.status==="opening"?this.db.defer(()=>this._all(f,p)):this.nextTick(p,new i("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._seek=function(f,p){this[a]!==null?this[a]._seek(f,p):this.db.status==="opening"&&this.db.defer(()=>this._seek(f,p))},u.prototype._close=function(f){this[a]!==null?this[a].close(f):this.db.status==="opening"?this.db.defer(()=>this._close(f)):this.nextTick(f)};r.DeferredIterator=c,r.DeferredKeyIterator=l,r.DeferredValueIterator=d}),bz=Zt(r=>{"use strict";var{fromCallback:e}=dE(),t=Md(),{getCallback:n,getOptions:i}=$C(),a=Symbol("promise"),s=Symbol("status"),o=Symbol("operations"),c=Symbol("finishClose"),l=Symbol("closeCallbacks"),d=class{constructor(u){if(typeof u!="object"||u===null){let f=u===null?"null":typeof u;throw new TypeError(`The first argument must be an abstract-level database, received ${f}`)}this[o]=[],this[l]=[],this[s]="open",this[c]=this[c].bind(this),this.db=u,this.db.attachResource(this),this.nextTick=u.nextTick}get length(){return this[o].length}put(u,f,p){if(this[s]!=="open")throw new t("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let h=this.db._checkKey(u)||this.db._checkValue(f);if(h)throw h;let m=p&&p.sublevel!=null?p.sublevel:this.db,y=p,v=m.keyEncoding(p&&p.keyEncoding),w=m.valueEncoding(p&&p.valueEncoding),E=v.format;p={...p,keyEncoding:E,valueEncoding:w.format},m!==this.db&&(p.sublevel=null);let _=m.prefixKey(v.encode(u),E),A=w.encode(f);return this._put(_,A,p),this[o].push({...y,type:"put",key:u,value:f}),this}_put(u,f,p){}del(u,f){if(this[s]!=="open")throw new t("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let p=this.db._checkKey(u);if(p)throw p;let h=f&&f.sublevel!=null?f.sublevel:this.db,m=f,y=h.keyEncoding(f&&f.keyEncoding),v=y.format;return f={...f,keyEncoding:v},h!==this.db&&(f.sublevel=null),this._del(h.prefixKey(y.encode(u),v),f),this[o].push({...m,type:"del",key:u}),this}_del(u,f){}clear(){if(this[s]!=="open")throw new t("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[o]=[],this}_clear(){}write(u,f){return f=n(u,f),f=e(f,a),u=i(u),this[s]!=="open"?this.nextTick(f,new t("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(f):(this[s]="writing",this._write(u,p=>{this[s]="closing",this[l].push(()=>f(p)),p||this.db.emit("batch",this[o]),this._close(this[c])})),f[a]}_write(u,f){}close(u){return u=e(u,a),this[s]==="closing"?this[l].push(u):this[s]==="closed"?this.nextTick(u):(this[l].push(u),this[s]!=="writing"&&(this[s]="closing",this._close(this[c]))),u[a]}_close(u){this.nextTick(u)}[c](){this[s]="closed",this.db.detachResource(this);let u=this[l];this[l]=[];for(let f of u)f()}};r.AbstractChainedBatch=d}),Zde=Zt(r=>{"use strict";var{AbstractChainedBatch:e}=bz(),t=Md(),n=Symbol("encoded"),i=class extends e{constructor(a){super(a),this[n]=[]}_put(a,s,o){this[n].push({...o,type:"put",key:a,value:s})}_del(a,s){this[n].push({...s,type:"del",key:a})}_clear(){this[n]=[]}_write(a,s){this.db.status==="opening"?this.db.defer(()=>this._write(a,s)):this.db.status==="open"?this[n].length===0?this.nextTick(s):this.db._batch(this[n],a,s):this.nextTick(s,new t("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};r.DefaultChainedBatch=i}),Yde=Zt((r,e)=>{"use strict";var t=Md(),n=Object.prototype.hasOwnProperty,i=new Set(["lt","lte","gt","gte"]);e.exports=function(a,s){let o={};for(let c in a)if(n.call(a,c)&&!(c==="keyEncoding"||c==="valueEncoding")){if(c==="start"||c==="end")throw new t(`The legacy range option '${c}' has been removed`,{code:"LEVEL_LEGACY"});if(c==="encoding")throw new t("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});i.has(c)?o[c]=s.encode(a[c]):o[c]=a[c]}return o.reverse=!!o.reverse,o.limit=Number.isInteger(o.limit)&&o.limit>=0?o.limit:-1,o}}),Pz=Zt((r,e)=>{var t;e.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):n=>(t||(t=Promise.resolve())).then(n).catch(i=>setTimeout(()=>{throw i},0))}),Xde=Zt((r,e)=>{"use strict";var t=Pz();e.exports=function(n,...i){i.length===0?t(n):t(()=>n(...i))}}),Qde=Zt(r=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:t,AbstractValueIterator:n}=fh(),i=Symbol("unfix"),a=Symbol("iterator"),s=Symbol("handleOne"),o=Symbol("handleMany"),c=Symbol("callback"),l=class extends e{constructor(f,p,h,m){super(f,p),this[a]=h,this[i]=m,this[s]=this[s].bind(this),this[o]=this[o].bind(this),this[c]=null}[s](f,p,h){let m=this[c];if(f)return m(f);p!==void 0&&(p=this[i](p)),m(f,p,h)}[o](f,p){let h=this[c];if(f)return h(f);for(let m of p){let y=m[0];y!==void 0&&(m[0]=this[i](y))}h(f,p)}},d=class extends t{constructor(f,p,h,m){super(f,p),this[a]=h,this[i]=m,this[s]=this[s].bind(this),this[o]=this[o].bind(this),this[c]=null}[s](f,p){let h=this[c];if(f)return h(f);p!==void 0&&(p=this[i](p)),h(f,p)}[o](f,p){let h=this[c];if(f)return h(f);for(let m=0;m<p.length;m++){let y=p[m];y!==void 0&&(p[m]=this[i](y))}h(f,p)}},u=class extends n{constructor(f,p,h){super(f,p),this[a]=h}};for(let f of[l,d])f.prototype._next=function(p){this[c]=p,this[a].next(this[s])},f.prototype._nextv=function(p,h,m){this[c]=m,this[a].nextv(p,h,this[o])},f.prototype._all=function(p,h){this[c]=h,this[a].all(p,this[o])};for(let f of[u])f.prototype._next=function(p){this[a].next(p)},f.prototype._nextv=function(p,h,m){this[a].nextv(p,h,m)},f.prototype._all=function(p,h){this[a].all(p,h)};for(let f of[l,d,u])f.prototype._seek=function(p,h){this[a].seek(p,h)},f.prototype._close=function(p){this[a].close(p)};r.AbstractSublevelIterator=l,r.AbstractSublevelKeyIterator=d,r.AbstractSublevelValueIterator=u}),ele=Zt((r,e)=>{"use strict";var t=Md(),{Buffer:n}=CC()||{},{AbstractSublevelIterator:i,AbstractSublevelKeyIterator:a,AbstractSublevelValueIterator:s}=Qde(),o=Symbol("prefix"),c=Symbol("upperBound"),l=Symbol("prefixRange"),d=Symbol("parent"),u=Symbol("unfix"),f=new TextEncoder,p={separator:"!"};e.exports=function({AbstractLevel:E}){class _ extends E{static defaults(D){if(typeof D=="string")throw new t("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(D&&D.open)throw new t("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return D==null?p:D.separator?D:{...D,separator:"!"}}constructor(D,M,C){let{separator:z,manifest:L,...B}=_.defaults(C);M=w(M,z);let W=z.charCodeAt(0)+1,ee=D[d]||D;if(!f.encode(M).every(S=>S>W&&S<127))throw new t(`Prefix must use bytes > ${W} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(h(ee,L),B);let R=(D.prefix||"")+z+M+z,$=R.slice(0,-1)+String.fromCharCode(W);this[d]=ee,this[o]=new y(R),this[c]=new y($),this[u]=new v,this.nextTick=ee.nextTick}prefixKey(D,M){if(M==="utf8")return this[o].utf8+D;if(D.byteLength===0)return this[o][M];if(M==="view"){let C=this[o].view,z=new Uint8Array(C.byteLength+D.byteLength);return z.set(C,0),z.set(D,C.byteLength),z}else{let C=this[o].buffer;return n.concat([C,D],C.byteLength+D.byteLength)}}[l](D,M){D.gte!==void 0?D.gte=this.prefixKey(D.gte,M):D.gt!==void 0?D.gt=this.prefixKey(D.gt,M):D.gte=this[o][M],D.lte!==void 0?D.lte=this.prefixKey(D.lte,M):D.lt!==void 0?D.lt=this.prefixKey(D.lt,M):D.lte=this[c][M]}get prefix(){return this[o].utf8}get db(){return this[d]}_open(D,M){this[d].open({passive:!0},M)}_put(D,M,C,z){this[d].put(D,M,C,z)}_get(D,M,C){this[d].get(D,M,C)}_getMany(D,M,C){this[d].getMany(D,M,C)}_del(D,M,C){this[d].del(D,M,C)}_batch(D,M,C){this[d].batch(D,M,C)}_clear(D,M){this[l](D,D.keyEncoding),this[d].clear(D,M)}_iterator(D){this[l](D,D.keyEncoding);let M=this[d].iterator(D),C=this[u].get(this[o].utf8.length,D.keyEncoding);return new i(this,D,M,C)}_keys(D){this[l](D,D.keyEncoding);let M=this[d].keys(D),C=this[u].get(this[o].utf8.length,D.keyEncoding);return new a(this,D,M,C)}_values(D){this[l](D,D.keyEncoding);let M=this[d].values(D);return new s(this,D,M)}}return{AbstractSublevel:_}};var h=function(E,_){return{...E.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},..._,encodings:{utf8:m(E,"utf8"),buffer:m(E,"buffer"),view:m(E,"view")}}},m=function(E,_){return E.supports.encodings[_]?E.keyEncoding(_).name===_:!1},y=class{constructor(E){this.utf8=E,this.view=f.encode(E),this.buffer=n?n.from(this.view.buffer,0,this.view.byteLength):{}}},v=class{constructor(){this.cache=new Map}get(E,_){let A=this.cache.get(_);return A===void 0&&(_==="view"?A=(function(D,M){return M.subarray(D)}).bind(null,E):A=(function(D,M){return M.slice(D)}).bind(null,E),this.cache.set(_,A)),A}},w=function(E,_){let A=0,D=E.length;for(;A<D&&E[A]===_;)A++;for(;D>A&&E[D-1]===_;)D--;return E.slice(A,D)}}),Q9=Zt(r=>{"use strict";var{supports:e}=Lde(),{Transcoder:t}=Gde(),{EventEmitter:n}=Hde(),{fromCallback:i}=dE(),a=Md(),{AbstractIterator:s}=fh(),{DefaultKeyIterator:o,DefaultValueIterator:c}=Wde(),{DeferredIterator:l,DeferredKeyIterator:d,DeferredValueIterator:u}=Jde(),{DefaultChainedBatch:f}=Zde(),{getCallback:p,getOptions:h}=$C(),m=Yde(),y=Symbol("promise"),v=Symbol("landed"),w=Symbol("resources"),E=Symbol("closeResources"),_=Symbol("operations"),A=Symbol("undefer"),D=Symbol("deferOpen"),M=Symbol("options"),C=Symbol("status"),z=Symbol("defaultOptions"),L=Symbol("transcoder"),B=Symbol("keyEncoding"),W=Symbol("valueEncoding"),ee=()=>{},R=class extends n{constructor(P,k){if(super(),typeof P!="object"||P===null)throw new TypeError("The first argument 'manifest' must be an object");k=h(k);let{keyEncoding:I,valueEncoding:j,passive:q,...H}=k;this[w]=new Set,this[_]=[],this[D]=!0,this[M]=H,this[C]="opening",this.supports=e(P,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:P.snapshots!==!1,permanence:P.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:P.encodings||{},events:Object.assign({},P.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[L]=new t(x(this)),this[B]=this[L].encoding(I||"utf8"),this[W]=this[L].encoding(j||"utf8");for(let J of this[L].encodings())this.supports.encodings[J.commonName]||(this.supports.encodings[J.commonName]=!0);this[z]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[B].commonName,valueEncoding:this[W].commonName}),key:Object.freeze({keyEncoding:this[B].commonName})},this.nextTick(()=>{this[D]&&this.open({passive:!1},ee)})}get status(){return this[C]}keyEncoding(P){return this[L].encoding(P??this[B])}valueEncoding(P){return this[L].encoding(P??this[W])}open(P,k){k=p(P,k),k=i(k,y),P={...this[M],...h(P)},P.createIfMissing=P.createIfMissing!==!1,P.errorIfExists=!!P.errorIfExists;let I=j=>{this[C]==="closing"||this[C]==="opening"?this.once(v,j?()=>I(j):I):this[C]!=="open"?k(new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:j})):k()};return P.passive?this[C]==="opening"?this.once(v,I):this.nextTick(I):this[C]==="closed"||this[D]?(this[D]=!1,this[C]="opening",this.emit("opening"),this._open(P,j=>{if(j){this[C]="closed",this[E](()=>{this.emit(v),I(j)}),this[A]();return}this[C]="open",this[A](),this.emit(v),this[C]==="open"&&this.emit("open"),this[C]==="open"&&this.emit("ready"),I()})):this[C]==="open"?this.nextTick(I):this.once(v,()=>this.open(P,k)),k[y]}_open(P,k){this.nextTick(k)}close(P){P=i(P,y);let k=I=>{this[C]==="opening"||this[C]==="closing"?this.once(v,I?k(I):k):this[C]!=="closed"?P(new a("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:I})):P()};if(this[C]==="open"){this[C]="closing",this.emit("closing");let I=j=>{this[C]="open",this[A](),this.emit(v),k(j)};this[E](()=>{this._close(j=>{if(j)return I(j);this[C]="closed",this[A](),this.emit(v),this[C]==="closed"&&this.emit("closed"),k()})})}else this[C]==="closed"?this.nextTick(k):this.once(v,()=>this.close(P));return P[y]}[E](P){if(this[w].size===0)return this.nextTick(P);let k=this[w].size,I=!0,j=()=>{--k===0&&(I?this.nextTick(P):P())};for(let q of this[w])q.close(j);I=!1,this[w].clear()}_close(P){this.nextTick(P)}get(P,k,I){if(I=p(k,I),I=i(I,y),k=h(k,this[z].entry),this[C]==="opening")return this.defer(()=>this.get(P,k,I)),I[y];if(S(this,I))return I[y];let j=this._checkKey(P);if(j)return this.nextTick(I,j),I[y];let q=this.keyEncoding(k.keyEncoding),H=this.valueEncoding(k.valueEncoding),J=q.format,V=H.format;return(k.keyEncoding!==J||k.valueEncoding!==V)&&(k=Object.assign({},k,{keyEncoding:J,valueEncoding:V})),this._get(this.prefixKey(q.encode(P),J),k,(Z,F)=>{if(Z)return(Z.code==="LEVEL_NOT_FOUND"||Z.notFound||/NotFound/i.test(Z))&&(Z.code||(Z.code="LEVEL_NOT_FOUND"),Z.notFound||(Z.notFound=!0),Z.status||(Z.status=404)),I(Z);try{F=H.decode(F)}catch(X){return I(new a("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:X}))}I(null,F)}),I[y]}_get(P,k,I){this.nextTick(I,new Error("NotFound"))}getMany(P,k,I){if(I=p(k,I),I=i(I,y),k=h(k,this[z].entry),this[C]==="opening")return this.defer(()=>this.getMany(P,k,I)),I[y];if(S(this,I))return I[y];if(!Array.isArray(P))return this.nextTick(I,new TypeError("The first argument 'keys' must be an array")),I[y];if(P.length===0)return this.nextTick(I,null,[]),I[y];let j=this.keyEncoding(k.keyEncoding),q=this.valueEncoding(k.valueEncoding),H=j.format,J=q.format;(k.keyEncoding!==H||k.valueEncoding!==J)&&(k=Object.assign({},k,{keyEncoding:H,valueEncoding:J}));let V=new Array(P.length);for(let Z=0;Z<P.length;Z++){let F=P[Z],X=this._checkKey(F);if(X)return this.nextTick(I,X),I[y];V[Z]=this.prefixKey(j.encode(F),H)}return this._getMany(V,k,(Z,F)=>{if(Z)return I(Z);try{for(let X=0;X<F.length;X++)F[X]!==void 0&&(F[X]=q.decode(F[X]))}catch(X){return I(new a(`Could not decode one or more of ${F.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:X}))}I(null,F)}),I[y]}_getMany(P,k,I){this.nextTick(I,null,new Array(P.length).fill(void 0))}put(P,k,I,j){if(j=p(I,j),j=i(j,y),I=h(I,this[z].entry),this[C]==="opening")return this.defer(()=>this.put(P,k,I,j)),j[y];if(S(this,j))return j[y];let q=this._checkKey(P)||this._checkValue(k);if(q)return this.nextTick(j,q),j[y];let H=this.keyEncoding(I.keyEncoding),J=this.valueEncoding(I.valueEncoding),V=H.format,Z=J.format;(I.keyEncoding!==V||I.valueEncoding!==Z)&&(I=Object.assign({},I,{keyEncoding:V,valueEncoding:Z}));let F=this.prefixKey(H.encode(P),V),X=J.encode(k);return this._put(F,X,I,ie=>{if(ie)return j(ie);this.emit("put",P,k),j()}),j[y]}_put(P,k,I,j){this.nextTick(j)}del(P,k,I){if(I=p(k,I),I=i(I,y),k=h(k,this[z].key),this[C]==="opening")return this.defer(()=>this.del(P,k,I)),I[y];if(S(this,I))return I[y];let j=this._checkKey(P);if(j)return this.nextTick(I,j),I[y];let q=this.keyEncoding(k.keyEncoding),H=q.format;return k.keyEncoding!==H&&(k=Object.assign({},k,{keyEncoding:H})),this._del(this.prefixKey(q.encode(P),H),k,J=>{if(J)return I(J);this.emit("del",P),I()}),I[y]}_del(P,k,I){this.nextTick(I)}batch(P,k,I){if(!arguments.length){if(this[C]==="opening")return new f(this);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof P=="function"?I=P:I=p(k,I),I=i(I,y),k=h(k,this[z].empty),this[C]==="opening")return this.defer(()=>this.batch(P,k,I)),I[y];if(S(this,I))return I[y];if(!Array.isArray(P))return this.nextTick(I,new TypeError("The first argument 'operations' must be an array")),I[y];if(P.length===0)return this.nextTick(I),I[y];let j=new Array(P.length),{keyEncoding:q,valueEncoding:H,...J}=k;for(let V=0;V<P.length;V++){if(typeof P[V]!="object"||P[V]===null)return this.nextTick(I,new TypeError("A batch operation must be an object")),I[y];let Z=Object.assign({},P[V]);if(Z.type!=="put"&&Z.type!=="del")return this.nextTick(I,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),I[y];let F=this._checkKey(Z.key);if(F)return this.nextTick(I,F),I[y];let X=Z.sublevel!=null?Z.sublevel:this,ie=X.keyEncoding(Z.keyEncoding||q),se=ie.format;if(Z.key=X.prefixKey(ie.encode(Z.key),se),Z.keyEncoding=se,Z.type==="put"){let Y=this._checkValue(Z.value);if(Y)return this.nextTick(I,Y),I[y];let de=X.valueEncoding(Z.valueEncoding||H);Z.value=de.encode(Z.value),Z.valueEncoding=de.format}X!==this&&(Z.sublevel=null),j[V]=Z}return this._batch(j,J,V=>{if(V)return I(V);this.emit("batch",P),I()}),I[y]}_batch(P,k,I){this.nextTick(I)}sublevel(P,k){return this._sublevel(P,$.defaults(k))}_sublevel(P,k){return new $(this,P,k)}prefixKey(P,k){return P}clear(P,k){if(k=p(P,k),k=i(k,y),P=h(P,this[z].empty),this[C]==="opening")return this.defer(()=>this.clear(P,k)),k[y];if(S(this,k))return k[y];let I=P,j=this.keyEncoding(P.keyEncoding);return P=m(P,j),P.keyEncoding=j.format,P.limit===0?this.nextTick(k):this._clear(P,q=>{if(q)return k(q);this.emit("clear",I),k()}),k[y]}_clear(P,k){this.nextTick(k)}iterator(P){let k=this.keyEncoding(P&&P.keyEncoding),I=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,k),P.keys=P.keys!==!1,P.values=P.values!==!1,P[s.keyEncoding]=k,P[s.valueEncoding]=I,P.keyEncoding=k.format,P.valueEncoding=I.format,this[C]==="opening")return new l(this,P);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(P)}_iterator(P){return new s(this,P)}keys(P){let k=this.keyEncoding(P&&P.keyEncoding),I=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,k),P[s.keyEncoding]=k,P[s.valueEncoding]=I,P.keyEncoding=k.format,P.valueEncoding=I.format,this[C]==="opening")return new d(this,P);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(P)}_keys(P){return new o(this,P)}values(P){let k=this.keyEncoding(P&&P.keyEncoding),I=this.valueEncoding(P&&P.valueEncoding);if(P=m(P,k),P[s.keyEncoding]=k,P[s.valueEncoding]=I,P.keyEncoding=k.format,P.valueEncoding=I.format,this[C]==="opening")return new u(this,P);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(P)}_values(P){return new c(this,P)}defer(P){if(typeof P!="function")throw new TypeError("The first argument must be a function");this[_].push(P)}[A](){if(this[_].length===0)return;let P=this[_];this[_]=[];for(let k of P)k()}attachResource(P){if(typeof P!="object"||P===null||typeof P.close!="function")throw new TypeError("The first argument must be a resource object");this[w].add(P)}detachResource(P){this[w].delete(P)}_chainedBatch(){return new f(this)}_checkKey(P){if(P==null)return new a("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(P){if(P==null)return new a("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};R.prototype.nextTick=Xde();var{AbstractSublevel:$}=ele()({AbstractLevel:R});r.AbstractLevel=R,r.AbstractSublevel=$;var S=function(P,k){return P[C]!=="open"?(P.nextTick(k,new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},x=function(P){return Object.keys(P.supports.encodings).filter(k=>!!P.supports.encodings[k])}}),xz=Zt(r=>{"use strict";r.AbstractLevel=Q9().AbstractLevel,r.AbstractSublevel=Q9().AbstractSublevel,r.AbstractIterator=fh().AbstractIterator,r.AbstractKeyIterator=fh().AbstractKeyIterator,r.AbstractValueIterator=fh().AbstractValueIterator,r.AbstractChainedBatch=bz().AbstractChainedBatch}),tle=Zt((r,e)=>{e.exports=n;var t=Pz();function n(i,a,s){if(typeof a!="number")throw new Error("second argument must be a Number");let o,c,l,d,u,f=!0,p;Array.isArray(i)?(o=[],l=c=i.length):(d=Object.keys(i),o={},l=c=d.length);function h(y){function v(){s&&s(y,o),s=null}f?t(v):v()}function m(y,v,w){if(o[y]=w,v&&(u=!0),--l===0||v)h(v);else if(!u&&p<c){let E;d?(E=d[p],p+=1,i[E](function(_,A){m(E,_,A)})):(E=p,p+=1,i[E](function(_,A){m(E,_,A)}))}}p=a,l?d?d.some(function(y,v){return i[y](function(w,E){m(y,w,E)}),v===a-1}):i.some(function(y,v){return y(function(w,E){m(v,w,E)}),v===a-1}):h(null),f=!1}}),Ez=Zt((r,e)=>{"use strict";e.exports=function(t){let n=t.gte!==void 0?t.gte:t.gt!==void 0?t.gt:void 0,i=t.lte!==void 0?t.lte:t.lt!==void 0?t.lt:void 0,a=t.gte===void 0,s=t.lte===void 0;return n!==void 0&&i!==void 0?IDBKeyRange.bound(n,i,a,s):n!==void 0?IDBKeyRange.lowerBound(n,a):i!==void 0?IDBKeyRange.upperBound(i,s):null}}),Sz=Zt((r,e)=>{"use strict";var t=new TextEncoder;e.exports=function(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):t.encode(n)}}),rle=Zt(r=>{"use strict";var{AbstractIterator:e}=xz(),t=Ez(),n=Sz(),i=Symbol("cache"),a=Symbol("finished"),s=Symbol("options"),o=Symbol("currentOptions"),c=Symbol("position"),l=Symbol("location"),d=Symbol("first"),u={},f=class extends e{constructor(h,m,y){super(h,y),this[i]=[],this[a]=this.limit===0,this[s]=y,this[o]={...y},this[c]=void 0,this[l]=m,this[d]=!0}_nextv(h,m,y){if(this[d]=!1,this[a])return this.nextTick(y,null,[]);if(this[i].length>0)return h=Math.min(h,this[i].length),this.nextTick(y,null,this[i].splice(0,h));this[c]!==void 0&&(this[s].reverse?(this[o].lt=this[c],this[o].lte=void 0):(this[o].gt=this[c],this[o].gte=void 0));let v;try{v=t(this[o])}catch{return this[a]=!0,this.nextTick(y,null,[])}let w=this.db.db.transaction([this[l]],"readonly"),E=w.objectStore(this[l]),_=[];if(this[s].reverse){let A=!this[s].values&&E.openKeyCursor?"openKeyCursor":"openCursor";E[A](v,"prev").onsuccess=D=>{let M=D.target.result;if(M){let{key:C,value:z}=M;this[c]=C,_.push([this[s].keys&&C!==void 0?n(C):void 0,this[s].values&&z!==void 0?n(z):void 0]),_.length<h?M.continue():p(w)}else this[a]=!0}}else{let A,D,M=()=>{if(A===void 0||D===void 0)return;let C=Math.max(A.length,D.length);C===0||h===1/0?this[a]=!0:this[c]=A[C-1],_.length=C;for(let z=0;z<C;z++){let L=A[z],B=D[z];_[z]=[this[s].keys&&L!==void 0?n(L):void 0,this[s].values&&B!==void 0?n(B):void 0]}p(w)};this[s].keys||h<1/0?E.getAllKeys(v,h<1/0?h:void 0).onsuccess=C=>{A=C.target.result,M()}:(A=[],this.nextTick(M)),this[s].values?E.getAll(v,h<1/0?h:void 0).onsuccess=C=>{D=C.target.result,M()}:(D=[],this.nextTick(M))}w.onabort=()=>{y(w.error||new Error("aborted by user")),y=null},w.oncomplete=()=>{y(null,_),y=null}}_next(h){if(this[i].length>0){let[m,y]=this[i].shift();this.nextTick(h,null,m,y)}else if(this[a])this.nextTick(h);else{let m=Math.min(100,this.limit-this.count);this[d]&&(this[d]=!1,m=1),this._nextv(m,u,(y,v)=>{if(y)return h(y);this[i]=v,this._next(h)})}}_all(h,m){this[d]=!1;let y=this[i].splice(0,this[i].length),v=this.limit-this.count-y.length;if(v<=0)return this.nextTick(m,null,y);this._nextv(v,u,(w,E)=>{if(w)return m(w);y.length>0&&(E=y.concat(E)),m(null,E)})}_seek(h,m){this[d]=!0,this[i]=[],this[a]=!1,this[c]=void 0,this[o]={...this[s]};let y;try{y=t(this[s])}catch{this[a]=!0;return}y!==null&&!y.includes(h)?this[a]=!0:this[s].reverse?this[o].lte=h:this[o].gte=h}};r.Iterator=f;function p(h){typeof h.commit=="function"&&h.commit()}}),nle=Zt((r,e)=>{"use strict";e.exports=function(t,n,i,a,s){if(a.limit===0)return t.nextTick(s);let o=t.db.transaction([n],"readwrite"),c=o.objectStore(n),l=0;o.oncomplete=function(){s()},o.onabort=function(){s(o.error||new Error("aborted by user"))};let d=c.openKeyCursor?"openKeyCursor":"openCursor",u=a.reverse?"prev":"next";c[d](i,u).onsuccess=function(f){let p=f.target.result;p&&(c.delete(p.key).onsuccess=function(){(a.limit<=0||++l<a.limit)&&p.continue()})}}}),ile=Zt(r=>{"use strict";var{AbstractLevel:e}=xz(),t=Md(),n=tle(),{fromCallback:i}=dE(),{Iterator:a}=rle(),s=Sz(),o=nle(),c=Ez(),l="level-js-",d=Symbol("idb"),u=Symbol("namePrefix"),f=Symbol("location"),p=Symbol("version"),h=Symbol("store"),m=Symbol("onComplete"),y=Symbol("promise"),v=class extends e{constructor(w,E,_){if(typeof E=="function"||typeof _=="function")throw new t("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:A,version:D,...M}=E||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},M),typeof w!="string")throw new Error("constructor requires a location string argument");this[f]=w,this[u]=A??l,this[p]=parseInt(D||1,10),this[d]=null}get location(){return this[f]}get namePrefix(){return this[u]}get version(){return this[p]}get db(){return this[d]}get type(){return"browser-level"}_open(w,E){let _=indexedDB.open(this[u]+this[f],this[p]);_.onerror=function(){E(_.error||new Error("unknown error"))},_.onsuccess=()=>{this[d]=_.result,E()},_.onupgradeneeded=A=>{let D=A.target.result;D.objectStoreNames.contains(this[f])||D.createObjectStore(this[f])}}[h](w){return this[d].transaction([this[f]],w).objectStore(this[f])}[m](w,E){let _=w.transaction;_.onabort=function(){E(_.error||new Error("aborted by user"))},_.oncomplete=function(){E(null,w.result)}}_get(w,E,_){let A=this[h]("readonly"),D;try{D=A.get(w)}catch(M){return this.nextTick(_,M)}this[m](D,function(M,C){if(M)return _(M);if(C===void 0)return _(new t("Entry not found",{code:"LEVEL_NOT_FOUND"}));_(null,s(C))})}_getMany(w,E,_){let A=this[h]("readonly"),D=w.map(M=>C=>{let z;try{z=A.get(M)}catch(L){return C(L)}z.onsuccess=()=>{let L=z.result;C(null,L===void 0?L:s(L))},z.onerror=L=>{L.stopPropagation(),C(z.error)}});n(D,16,_)}_del(w,E,_){let A=this[h]("readwrite"),D;try{D=A.delete(w)}catch(M){return this.nextTick(_,M)}this[m](D,_)}_put(w,E,_,A){let D=this[h]("readwrite"),M;try{M=D.put(E,w)}catch(C){return this.nextTick(A,C)}this[m](M,A)}_iterator(w){return new a(this,this[f],w)}_batch(w,E,_){let A=this[h]("readwrite"),D=A.transaction,M=0,C;D.onabort=function(){_(C||D.error||new Error("aborted by user"))},D.oncomplete=function(){_()};function z(){let L=w[M++],B=L.key,W;try{W=L.type==="del"?A.delete(B):A.put(L.value,B)}catch(ee){C=ee,D.abort();return}M<w.length?W.onsuccess=z:typeof D.commit=="function"&&D.commit()}z()}_clear(w,E){let _,A;try{_=c(w)}catch{return this.nextTick(E)}if(w.limit>=0)return o(this,this[f],_,w,E);try{let D=this[h]("readwrite");A=_?D.delete(_):D.clear()}catch(D){return this.nextTick(E,D)}this[m](A,E)}_close(w){this[d].close(),this.nextTick(w)}};v.destroy=function(w,E,_){typeof E=="function"&&(_=E,E=l),_=i(_,y);let A=indexedDB.deleteDatabase(E+w);return A.onsuccess=function(){_()},A.onerror=function(D){_(D)},_[y]},r.BrowserLevel=v}),kz=Zt(r=>{r.Level=ile().BrowserLevel}),sle=Zt((r,e)=>{(function(t,n){typeof r=="object"&&typeof e<"u"?n(r):typeof define=="function"&&define.amd?define(["exports"],n):n(t.URI=t.URI||{})})(r,function(t){"use strict";function n(){for(var Q=arguments.length,oe=Array(Q),ae=0;ae<Q;ae++)oe[ae]=arguments[ae];if(oe.length>1){oe[0]=oe[0].slice(0,-1);for(var be=oe.length-1,Pe=1;Pe<be;++Pe)oe[Pe]=oe[Pe].slice(1,-1);return oe[be]=oe[be].slice(1),oe.join("")}else return oe[0]}function i(Q){return"(?:"+Q+")"}function a(Q){return Q===void 0?"undefined":Q===null?"null":Object.prototype.toString.call(Q).split(" ").pop().split("]").shift().toLowerCase()}function s(Q){return Q.toUpperCase()}function o(Q){return Q!=null?Q instanceof Array?Q:typeof Q.length!="number"||Q.split||Q.setInterval||Q.call?[Q]:Array.prototype.slice.call(Q):[]}function c(Q,oe){var ae=Q;if(oe)for(var be in oe)ae[be]=oe[be];return ae}function l(Q){var oe="[A-Za-z]",ae="[\\x0D]",be="[0-9]",Pe="[\\x22]",Ge=n(be,"[A-Fa-f]"),Bt="[\\x0A]",wr="[\\x20]",Xr=i(i("%[EFef]"+Ge+"%"+Ge+Ge+"%"+Ge+Ge)+"|"+i("%[89A-Fa-f]"+Ge+"%"+Ge+Ge)+"|"+i("%"+Ge+Ge)),Qr="[\\:\\/\\?\\#\\[\\]\\@]",dr="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",_n=n(Qr,dr),Yn=Q?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",gn=Q?"[\\uE000-\\uF8FF]":"[]",Tr=n(oe,be,"[\\-\\.\\_\\~]",Yn),Sr=i(oe+n(oe,be,"[\\+\\-\\.]")+"*"),os=i(i(Xr+"|"+n(Tr,dr,"[\\:]"))+"*"),jg=i(i("25[0-5]")+"|"+i("2[0-4]"+be)+"|"+i("1"+be+be)+"|"+i("[1-9]"+be)+"|"+be),Xs=i(i("25[0-5]")+"|"+i("2[0-4]"+be)+"|"+i("1"+be+be)+"|"+i("0?[1-9]"+be)+"|0?0?"+be),Ga=i(Xs+"\\."+Xs+"\\."+Xs+"\\."+Xs),Ir=i(Ge+"{1,4}"),Po=i(i(Ir+"\\:"+Ir)+"|"+Ga),ra=i(i(Ir+"\\:")+"{6}"+Po),Nd=i("\\:\\:"+i(Ir+"\\:")+"{5}"+Po),qf=i(i(Ir)+"?\\:\\:"+i(Ir+"\\:")+"{4}"+Po),$c=i(i(i(Ir+"\\:")+"{0,1}"+Ir)+"?\\:\\:"+i(Ir+"\\:")+"{3}"+Po),Ub=i(i(i(Ir+"\\:")+"{0,2}"+Ir)+"?\\:\\:"+i(Ir+"\\:")+"{2}"+Po),Nb=i(i(i(Ir+"\\:")+"{0,3}"+Ir)+"?\\:\\:"+Ir+"\\:"+Po),Fh=i(i(i(Ir+"\\:")+"{0,4}"+Ir)+"?\\:\\:"+Po),Gh=i(i(i(Ir+"\\:")+"{0,5}"+Ir)+"?\\:\\:"+Ir),Hh=i(i(i(Ir+"\\:")+"{0,6}"+Ir)+"?\\:\\:"),zf=i([ra,Nd,qf,$c,Ub,Nb,Fh,Gh,Hh].join("|")),Vh=i(i(Tr+"|"+Xr)+"+"),Wh=i(zf+"\\%25"+Vh),IV=i(zf+i("\\%25|\\%(?!"+Ge+"{2})")+Vh),DV=i("[vV]"+Ge+"+\\."+n(Tr,dr,"[\\:]")+"+"),RV=i("\\["+i(IV+"|"+zf+"|"+DV)+"\\]"),g5=i(i(Xr+"|"+n(Tr,dr))+"*"),Mg=i(RV+"|"+Ga+"(?!"+g5+")|"+g5),Kg=i(be+"*"),w5=i(i(os+"@")+"?"+Mg+i("\\:"+Kg)+"?"),Ug=i(Xr+"|"+n(Tr,dr,"[\\:\\@]")),CV=i(Ug+"*"),v5=i(Ug+"+"),$V=i(i(Xr+"|"+n(Tr,dr,"[\\@]"))+"+"),Ld=i(i("\\/"+CV)+"*"),Jh=i("\\/"+i(v5+Ld)+"?"),SS=i($V+Ld),Lb=i(v5+Ld),Zh="(?!"+Ug+")",Hwe=i(Ld+"|"+Jh+"|"+SS+"|"+Lb+"|"+Zh),Yh=i(i(Ug+"|"+n("[\\/\\?]",gn))+"*"),Ng=i(i(Ug+"|[\\/\\?]")+"*"),b5=i(i("\\/\\/"+w5+Ld)+"|"+Jh+"|"+Lb+"|"+Zh),BV=i(Sr+"\\:"+b5+i("\\?"+Yh)+"?"+i("\\#"+Ng)+"?"),OV=i(i("\\/\\/"+w5+Ld)+"|"+Jh+"|"+SS+"|"+Zh),jV=i(OV+i("\\?"+Yh)+"?"+i("\\#"+Ng)+"?"),Vwe=i(BV+"|"+jV),Wwe=i(Sr+"\\:"+b5+i("\\?"+Yh)+"?"),Jwe="^("+Sr+")\\:"+i(i("\\/\\/("+i("("+os+")@")+"?("+Mg+")"+i("\\:("+Kg+")")+"?)")+"?("+Ld+"|"+Jh+"|"+Lb+"|"+Zh+")")+i("\\?("+Yh+")")+"?"+i("\\#("+Ng+")")+"?$",Zwe="^(){0}"+i(i("\\/\\/("+i("("+os+")@")+"?("+Mg+")"+i("\\:("+Kg+")")+"?)")+"?("+Ld+"|"+Jh+"|"+SS+"|"+Zh+")")+i("\\?("+Yh+")")+"?"+i("\\#("+Ng+")")+"?$",Ywe="^("+Sr+")\\:"+i(i("\\/\\/("+i("("+os+")@")+"?("+Mg+")"+i("\\:("+Kg+")")+"?)")+"?("+Ld+"|"+Jh+"|"+Lb+"|"+Zh+")")+i("\\?("+Yh+")")+"?$",Xwe="^"+i("\\#("+Ng+")")+"?$",Qwe="^"+i("("+os+")@")+"?("+Mg+")"+i("\\:("+Kg+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",oe,be,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",Tr,dr),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",Tr,dr),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",Tr,dr),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",Tr,dr),"g"),NOT_QUERY:new RegExp(n("[^\\%]",Tr,dr,"[\\:\\@\\/\\?]",gn),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",Tr,dr,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",Tr,dr),"g"),UNRESERVED:new RegExp(Tr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",Tr,_n),"g"),PCT_ENCODED:new RegExp(Xr,"g"),IPV4ADDRESS:new RegExp("^("+Ga+")$"),IPV6ADDRESS:new RegExp("^\\[?("+zf+")"+i(i("\\%25|\\%(?!"+Ge+"{2})")+"("+Vh+")")+"?\\]?$")}}var d=l(!1),u=l(!0),f=function(){function Q(oe,ae){var be=[],Pe=!0,Ge=!1,Bt=void 0;try{for(var wr=oe[Symbol.iterator](),Xr;!(Pe=(Xr=wr.next()).done)&&(be.push(Xr.value),!(ae&&be.length===ae));Pe=!0);}catch(Qr){Ge=!0,Bt=Qr}finally{try{!Pe&&wr.return&&wr.return()}finally{if(Ge)throw Bt}}return be}return function(oe,ae){if(Array.isArray(oe))return oe;if(Symbol.iterator in Object(oe))return Q(oe,ae);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),p=function(Q){if(Array.isArray(Q)){for(var oe=0,ae=Array(Q.length);oe<Q.length;oe++)ae[oe]=Q[oe];return ae}else return Array.from(Q)},h=2147483647,m=36,y=1,v=26,w=38,E=700,_=72,A=128,D="-",M=/^xn--/,C=/[^\0-\x7E]/,z=/[\x2E\u3002\uFF0E\uFF61]/g,L={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},B=m-y,W=Math.floor,ee=String.fromCharCode;function R(Q){throw new RangeError(L[Q])}function $(Q,oe){for(var ae=[],be=Q.length;be--;)ae[be]=oe(Q[be]);return ae}function S(Q,oe){var ae=Q.split("@"),be="";ae.length>1&&(be=ae[0]+"@",Q=ae[1]),Q=Q.replace(z,".");var Pe=Q.split("."),Ge=$(Pe,oe).join(".");return be+Ge}function x(Q){for(var oe=[],ae=0,be=Q.length;ae<be;){var Pe=Q.charCodeAt(ae++);if(Pe>=55296&&Pe<=56319&&ae<be){var Ge=Q.charCodeAt(ae++);(Ge&64512)==56320?oe.push(((Pe&1023)<<10)+(Ge&1023)+65536):(oe.push(Pe),ae--)}else oe.push(Pe)}return oe}var P=function(Q){return String.fromCodePoint.apply(String,p(Q))},k=function(Q){return Q-48<10?Q-22:Q-65<26?Q-65:Q-97<26?Q-97:m},I=function(Q,oe){return Q+22+75*(Q<26)-((oe!=0)<<5)},j=function(Q,oe,ae){var be=0;for(Q=ae?W(Q/E):Q>>1,Q+=W(Q/oe);Q>B*v>>1;be+=m)Q=W(Q/B);return W(be+(B+1)*Q/(Q+w))},q=function(Q){var oe=[],ae=Q.length,be=0,Pe=A,Ge=_,Bt=Q.lastIndexOf(D);Bt<0&&(Bt=0);for(var wr=0;wr<Bt;++wr)Q.charCodeAt(wr)>=128&&R("not-basic"),oe.push(Q.charCodeAt(wr));for(var Xr=Bt>0?Bt+1:0;Xr<ae;){for(var Qr=be,dr=1,_n=m;;_n+=m){Xr>=ae&&R("invalid-input");var Yn=k(Q.charCodeAt(Xr++));(Yn>=m||Yn>W((h-be)/dr))&&R("overflow"),be+=Yn*dr;var gn=_n<=Ge?y:_n>=Ge+v?v:_n-Ge;if(Yn<gn)break;var Tr=m-gn;dr>W(h/Tr)&&R("overflow"),dr*=Tr}var Sr=oe.length+1;Ge=j(be-Qr,Sr,Qr==0),W(be/Sr)>h-Pe&&R("overflow"),Pe+=W(be/Sr),be%=Sr,oe.splice(be++,0,Pe)}return String.fromCodePoint.apply(String,oe)},H=function(Q){var oe=[];Q=x(Q);var ae=Q.length,be=A,Pe=0,Ge=_,Bt=!0,wr=!1,Xr=void 0;try{for(var Qr=Q[Symbol.iterator](),dr;!(Bt=(dr=Qr.next()).done);Bt=!0){var _n=dr.value;_n<128&&oe.push(ee(_n))}}catch(Wh){wr=!0,Xr=Wh}finally{try{!Bt&&Qr.return&&Qr.return()}finally{if(wr)throw Xr}}var Yn=oe.length,gn=Yn;for(Yn&&oe.push(D);gn<ae;){var Tr=h,Sr=!0,os=!1,jg=void 0;try{for(var Xs=Q[Symbol.iterator](),Ga;!(Sr=(Ga=Xs.next()).done);Sr=!0){var Ir=Ga.value;Ir>=be&&Ir<Tr&&(Tr=Ir)}}catch(Wh){os=!0,jg=Wh}finally{try{!Sr&&Xs.return&&Xs.return()}finally{if(os)throw jg}}var Po=gn+1;Tr-be>W((h-Pe)/Po)&&R("overflow"),Pe+=(Tr-be)*Po,be=Tr;var ra=!0,Nd=!1,qf=void 0;try{for(var $c=Q[Symbol.iterator](),Ub;!(ra=(Ub=$c.next()).done);ra=!0){var Nb=Ub.value;if(Nb<be&&++Pe>h&&R("overflow"),Nb==be){for(var Fh=Pe,Gh=m;;Gh+=m){var Hh=Gh<=Ge?y:Gh>=Ge+v?v:Gh-Ge;if(Fh<Hh)break;var zf=Fh-Hh,Vh=m-Hh;oe.push(ee(I(Hh+zf%Vh,0))),Fh=W(zf/Vh)}oe.push(ee(I(Fh,0))),Ge=j(Pe,Po,gn==Yn),Pe=0,++gn}}}catch(Wh){Nd=!0,qf=Wh}finally{try{!ra&&$c.return&&$c.return()}finally{if(Nd)throw qf}}++Pe,++be}return oe.join("")},J=function(Q){return S(Q,function(oe){return M.test(oe)?q(oe.slice(4).toLowerCase()):oe})},V=function(Q){return S(Q,function(oe){return C.test(oe)?"xn--"+H(oe):oe})},Z={version:"2.1.0",ucs2:{decode:x,encode:P},decode:q,encode:H,toASCII:V,toUnicode:J},F={};function X(Q){var oe=Q.charCodeAt(0),ae=void 0;return oe<16?ae="%0"+oe.toString(16).toUpperCase():oe<128?ae="%"+oe.toString(16).toUpperCase():oe<2048?ae="%"+(oe>>6|192).toString(16).toUpperCase()+"%"+(oe&63|128).toString(16).toUpperCase():ae="%"+(oe>>12|224).toString(16).toUpperCase()+"%"+(oe>>6&63|128).toString(16).toUpperCase()+"%"+(oe&63|128).toString(16).toUpperCase(),ae}function ie(Q){for(var oe="",ae=0,be=Q.length;ae<be;){var Pe=parseInt(Q.substr(ae+1,2),16);if(Pe<128)oe+=String.fromCharCode(Pe),ae+=3;else if(Pe>=194&&Pe<224){if(be-ae>=6){var Ge=parseInt(Q.substr(ae+4,2),16);oe+=String.fromCharCode((Pe&31)<<6|Ge&63)}else oe+=Q.substr(ae,6);ae+=6}else if(Pe>=224){if(be-ae>=9){var Bt=parseInt(Q.substr(ae+4,2),16),wr=parseInt(Q.substr(ae+7,2),16);oe+=String.fromCharCode((Pe&15)<<12|(Bt&63)<<6|wr&63)}else oe+=Q.substr(ae,9);ae+=9}else oe+=Q.substr(ae,3),ae+=3}return oe}function se(Q,oe){function ae(be){var Pe=ie(be);return Pe.match(oe.UNRESERVED)?Pe:be}return Q.scheme&&(Q.scheme=String(Q.scheme).replace(oe.PCT_ENCODED,ae).toLowerCase().replace(oe.NOT_SCHEME,"")),Q.userinfo!==void 0&&(Q.userinfo=String(Q.userinfo).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_USERINFO,X).replace(oe.PCT_ENCODED,s)),Q.host!==void 0&&(Q.host=String(Q.host).replace(oe.PCT_ENCODED,ae).toLowerCase().replace(oe.NOT_HOST,X).replace(oe.PCT_ENCODED,s)),Q.path!==void 0&&(Q.path=String(Q.path).replace(oe.PCT_ENCODED,ae).replace(Q.scheme?oe.NOT_PATH:oe.NOT_PATH_NOSCHEME,X).replace(oe.PCT_ENCODED,s)),Q.query!==void 0&&(Q.query=String(Q.query).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_QUERY,X).replace(oe.PCT_ENCODED,s)),Q.fragment!==void 0&&(Q.fragment=String(Q.fragment).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_FRAGMENT,X).replace(oe.PCT_ENCODED,s)),Q}function Y(Q){return Q.replace(/^0*(.*)/,"$1")||"0"}function de(Q,oe){var ae=Q.match(oe.IPV4ADDRESS)||[],be=f(ae,2),Pe=be[1];return Pe?Pe.split(".").map(Y).join("."):Q}function pe(Q,oe){var ae=Q.match(oe.IPV6ADDRESS)||[],be=f(ae,3),Pe=be[1],Ge=be[2];if(Pe){for(var Bt=Pe.toLowerCase().split("::").reverse(),wr=f(Bt,2),Xr=wr[0],Qr=wr[1],dr=Qr?Qr.split(":").map(Y):[],_n=Xr.split(":").map(Y),Yn=oe.IPV4ADDRESS.test(_n[_n.length-1]),gn=Yn?7:8,Tr=_n.length-gn,Sr=Array(gn),os=0;os<gn;++os)Sr[os]=dr[os]||_n[Tr+os]||"";Yn&&(Sr[gn-1]=de(Sr[gn-1],oe));var jg=Sr.reduce(function(ra,Nd,qf){if(!Nd||Nd==="0"){var $c=ra[ra.length-1];$c&&$c.index+$c.length===qf?$c.length++:ra.push({index:qf,length:1})}return ra},[]),Xs=jg.sort(function(ra,Nd){return Nd.length-ra.length})[0],Ga=void 0;if(Xs&&Xs.length>1){var Ir=Sr.slice(0,Xs.index),Po=Sr.slice(Xs.index+Xs.length);Ga=Ir.join(":")+"::"+Po.join(":")}else Ga=Sr.join(":");return Ge&&(Ga+="%"+Ge),Ga}else return Q}var le=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Se="".match(/(){0}/)[1]===void 0;function he(Q){var oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ae={},be=oe.iri!==!1?u:d;oe.reference==="suffix"&&(Q=(oe.scheme?oe.scheme+":":"")+"//"+Q);var Pe=Q.match(le);if(Pe){Se?(ae.scheme=Pe[1],ae.userinfo=Pe[3],ae.host=Pe[4],ae.port=parseInt(Pe[5],10),ae.path=Pe[6]||"",ae.query=Pe[7],ae.fragment=Pe[8],isNaN(ae.port)&&(ae.port=Pe[5])):(ae.scheme=Pe[1]||void 0,ae.userinfo=Q.indexOf("@")!==-1?Pe[3]:void 0,ae.host=Q.indexOf("//")!==-1?Pe[4]:void 0,ae.port=parseInt(Pe[5],10),ae.path=Pe[6]||"",ae.query=Q.indexOf("?")!==-1?Pe[7]:void 0,ae.fragment=Q.indexOf("#")!==-1?Pe[8]:void 0,isNaN(ae.port)&&(ae.port=Q.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?Pe[4]:void 0)),ae.host&&(ae.host=pe(de(ae.host,be),be)),ae.scheme===void 0&&ae.userinfo===void 0&&ae.host===void 0&&ae.port===void 0&&!ae.path&&ae.query===void 0?ae.reference="same-document":ae.scheme===void 0?ae.reference="relative":ae.fragment===void 0?ae.reference="absolute":ae.reference="uri",oe.reference&&oe.reference!=="suffix"&&oe.reference!==ae.reference&&(ae.error=ae.error||"URI is not a "+oe.reference+" reference.");var Ge=F[(oe.scheme||ae.scheme||"").toLowerCase()];if(!oe.unicodeSupport&&(!Ge||!Ge.unicodeSupport)){if(ae.host&&(oe.domainHost||Ge&&Ge.domainHost))try{ae.host=Z.toASCII(ae.host.replace(be.PCT_ENCODED,ie).toLowerCase())}catch(Bt){ae.error=ae.error||"Host's domain name can not be converted to ASCII via punycode: "+Bt}se(ae,d)}else se(ae,be);Ge&&Ge.parse&&Ge.parse(ae,oe)}else ae.error=ae.error||"URI can not be parsed.";return ae}function Te(Q,oe){var ae=oe.iri!==!1?u:d,be=[];return Q.userinfo!==void 0&&(be.push(Q.userinfo),be.push("@")),Q.host!==void 0&&be.push(pe(de(String(Q.host),ae),ae).replace(ae.IPV6ADDRESS,function(Pe,Ge,Bt){return"["+Ge+(Bt?"%25"+Bt:"")+"]"})),(typeof Q.port=="number"||typeof Q.port=="string")&&(be.push(":"),be.push(String(Q.port))),be.length?be.join(""):void 0}var Rt=/^\.\.?\//,ti=/^\/\.(\/|$)/,Kr=/^\/\.\.(\/|$)/,Ys=/^\/?(?:.|\n)*?(?=\/|$)/;function We(Q){for(var oe=[];Q.length;)if(Q.match(Rt))Q=Q.replace(Rt,"");else if(Q.match(ti))Q=Q.replace(ti,"/");else if(Q.match(Kr))Q=Q.replace(Kr,"/"),oe.pop();else if(Q==="."||Q==="..")Q="";else{var ae=Q.match(Ys);if(ae){var be=ae[0];Q=Q.slice(be.length),oe.push(be)}else throw new Error("Unexpected dot segment condition")}return oe.join("")}function nr(Q){var oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ae=oe.iri?u:d,be=[],Pe=F[(oe.scheme||Q.scheme||"").toLowerCase()];if(Pe&&Pe.serialize&&Pe.serialize(Q,oe),Q.host&&!ae.IPV6ADDRESS.test(Q.host)&&(oe.domainHost||Pe&&Pe.domainHost))try{Q.host=oe.iri?Z.toUnicode(Q.host):Z.toASCII(Q.host.replace(ae.PCT_ENCODED,ie).toLowerCase())}catch(wr){Q.error=Q.error||"Host's domain name can not be converted to "+(oe.iri?"Unicode":"ASCII")+" via punycode: "+wr}se(Q,ae),oe.reference!=="suffix"&&Q.scheme&&(be.push(Q.scheme),be.push(":"));var Ge=Te(Q,oe);if(Ge!==void 0&&(oe.reference!=="suffix"&&be.push("//"),be.push(Ge),Q.path&&Q.path.charAt(0)!=="/"&&be.push("/")),Q.path!==void 0){var Bt=Q.path;!oe.absolutePath&&(!Pe||!Pe.absolutePath)&&(Bt=We(Bt)),Ge===void 0&&(Bt=Bt.replace(/^\/\//,"/%2F")),be.push(Bt)}return Q.query!==void 0&&(be.push("?"),be.push(Q.query)),Q.fragment!==void 0&&(be.push("#"),be.push(Q.fragment)),be.join("")}function Ur(Q,oe){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},be=arguments[3],Pe={};return be||(Q=he(nr(Q,ae),ae),oe=he(nr(oe,ae),ae)),ae=ae||{},!ae.tolerant&&oe.scheme?(Pe.scheme=oe.scheme,Pe.userinfo=oe.userinfo,Pe.host=oe.host,Pe.port=oe.port,Pe.path=We(oe.path||""),Pe.query=oe.query):(oe.userinfo!==void 0||oe.host!==void 0||oe.port!==void 0?(Pe.userinfo=oe.userinfo,Pe.host=oe.host,Pe.port=oe.port,Pe.path=We(oe.path||""),Pe.query=oe.query):(oe.path?(oe.path.charAt(0)==="/"?Pe.path=We(oe.path):((Q.userinfo!==void 0||Q.host!==void 0||Q.port!==void 0)&&!Q.path?Pe.path="/"+oe.path:Q.path?Pe.path=Q.path.slice(0,Q.path.lastIndexOf("/")+1)+oe.path:Pe.path=oe.path,Pe.path=We(Pe.path)),Pe.query=oe.query):(Pe.path=Q.path,oe.query!==void 0?Pe.query=oe.query:Pe.query=Q.query),Pe.userinfo=Q.userinfo,Pe.host=Q.host,Pe.port=Q.port),Pe.scheme=Q.scheme),Pe.fragment=oe.fragment,Pe}function pr(Q,oe,ae){var be=c({scheme:"null"},ae);return nr(Ur(he(Q,be),he(oe,be),be,!0),be)}function Lt(Q,oe){return typeof Q=="string"?Q=nr(he(Q,oe),oe):a(Q)==="object"&&(Q=he(nr(Q,oe),oe)),Q}function T(Q,oe,ae){return typeof Q=="string"?Q=nr(he(Q,ae),ae):a(Q)==="object"&&(Q=nr(Q,ae)),typeof oe=="string"?oe=nr(he(oe,ae),ae):a(oe)==="object"&&(oe=nr(oe,ae)),Q===oe}function U(Q,oe){return Q&&Q.toString().replace(!oe||!oe.iri?d.ESCAPE:u.ESCAPE,X)}function N(Q,oe){return Q&&Q.toString().replace(!oe||!oe.iri?d.PCT_ENCODED:u.PCT_ENCODED,ie)}var te={scheme:"http",domainHost:!0,parse:function(Q,oe){return Q.host||(Q.error=Q.error||"HTTP URIs must have a host."),Q},serialize:function(Q,oe){var ae=String(Q.scheme).toLowerCase()==="https";return(Q.port===(ae?443:80)||Q.port==="")&&(Q.port=void 0),Q.path||(Q.path="/"),Q}},ce={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function ge(Q){return typeof Q.secure=="boolean"?Q.secure:String(Q.scheme).toLowerCase()==="wss"}var Ee={scheme:"ws",domainHost:!0,parse:function(Q,oe){var ae=Q;return ae.secure=ge(ae),ae.resourceName=(ae.path||"/")+(ae.query?"?"+ae.query:""),ae.path=void 0,ae.query=void 0,ae},serialize:function(Q,oe){if((Q.port===(ge(Q)?443:80)||Q.port==="")&&(Q.port=void 0),typeof Q.secure=="boolean"&&(Q.scheme=Q.secure?"wss":"ws",Q.secure=void 0),Q.resourceName){var ae=Q.resourceName.split("?"),be=f(ae,2),Pe=be[0],Ge=be[1];Q.path=Pe&&Pe!=="/"?Pe:void 0,Q.query=Ge,Q.resourceName=void 0}return Q.fragment=void 0,Q}},qt={scheme:"wss",domainHost:Ee.domainHost,parse:Ee.parse,serialize:Ee.serialize},ri={},Gr=!0,Er="[A-Za-z0-9\\-\\.\\_\\~"+(Gr?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",hr="[0-9A-Fa-f]",vV=i(i("%[EFef]"+hr+"%"+hr+hr+"%"+hr+hr)+"|"+i("%[89A-Fa-f]"+hr+"%"+hr+hr)+"|"+i("%"+hr+hr)),bV="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",PV="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",xV=n(PV,'[\\"\\\\]'),EV="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",SV=new RegExp(Er,"g"),zh=new RegExp(vV,"g"),kV=new RegExp(n("[^]",bV,"[\\.]",'[\\"]',xV),"g"),p5=new RegExp(n("[^]",Er,EV),"g"),_V=p5;function ES(Q){var oe=ie(Q);return oe.match(SV)?oe:Q}var h5={scheme:"mailto",parse:function(Q,oe){var ae=Q,be=ae.to=ae.path?ae.path.split(","):[];if(ae.path=void 0,ae.query){for(var Pe=!1,Ge={},Bt=ae.query.split("&"),wr=0,Xr=Bt.length;wr<Xr;++wr){var Qr=Bt[wr].split("=");switch(Qr[0]){case"to":for(var dr=Qr[1].split(","),_n=0,Yn=dr.length;_n<Yn;++_n)be.push(dr[_n]);break;case"subject":ae.subject=N(Qr[1],oe);break;case"body":ae.body=N(Qr[1],oe);break;default:Pe=!0,Ge[N(Qr[0],oe)]=N(Qr[1],oe);break}}Pe&&(ae.headers=Ge)}ae.query=void 0;for(var gn=0,Tr=be.length;gn<Tr;++gn){var Sr=be[gn].split("@");if(Sr[0]=N(Sr[0]),oe.unicodeSupport)Sr[1]=N(Sr[1],oe).toLowerCase();else try{Sr[1]=Z.toASCII(N(Sr[1],oe).toLowerCase())}catch(os){ae.error=ae.error||"Email address's domain name can not be converted to ASCII via punycode: "+os}be[gn]=Sr.join("@")}return ae},serialize:function(Q,oe){var ae=Q,be=o(Q.to);if(be){for(var Pe=0,Ge=be.length;Pe<Ge;++Pe){var Bt=String(be[Pe]),wr=Bt.lastIndexOf("@"),Xr=Bt.slice(0,wr).replace(zh,ES).replace(zh,s).replace(kV,X),Qr=Bt.slice(wr+1);try{Qr=oe.iri?Z.toUnicode(Qr):Z.toASCII(N(Qr,oe).toLowerCase())}catch(gn){ae.error=ae.error||"Email address's domain name can not be converted to "+(oe.iri?"Unicode":"ASCII")+" via punycode: "+gn}be[Pe]=Xr+"@"+Qr}ae.path=be.join(",")}var dr=Q.headers=Q.headers||{};Q.subject&&(dr.subject=Q.subject),Q.body&&(dr.body=Q.body);var _n=[];for(var Yn in dr)dr[Yn]!==ri[Yn]&&_n.push(Yn.replace(zh,ES).replace(zh,s).replace(p5,X)+"="+dr[Yn].replace(zh,ES).replace(zh,s).replace(_V,X));return _n.length&&(ae.query=_n.join("&")),ae}},AV=/^([^\:]+)\:(.*)/,m5={scheme:"urn",parse:function(Q,oe){var ae=Q.path&&Q.path.match(AV),be=Q;if(ae){var Pe=oe.scheme||be.scheme||"urn",Ge=ae[1].toLowerCase(),Bt=ae[2],wr=Pe+":"+(oe.nid||Ge),Xr=F[wr];be.nid=Ge,be.nss=Bt,be.path=void 0,Xr&&(be=Xr.parse(be,oe))}else be.error=be.error||"URN can not be parsed.";return be},serialize:function(Q,oe){var ae=oe.scheme||Q.scheme||"urn",be=Q.nid,Pe=ae+":"+(oe.nid||be),Ge=F[Pe];Ge&&(Q=Ge.serialize(Q,oe));var Bt=Q,wr=Q.nss;return Bt.path=(be||oe.nid)+":"+wr,Bt}},TV=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,y5={scheme:"urn:uuid",parse:function(Q,oe){var ae=Q;return ae.uuid=ae.nss,ae.nss=void 0,!oe.tolerant&&(!ae.uuid||!ae.uuid.match(TV))&&(ae.error=ae.error||"UUID is not valid."),ae},serialize:function(Q,oe){var ae=Q;return ae.nss=(Q.uuid||"").toLowerCase(),ae}};F[te.scheme]=te,F[ce.scheme]=ce,F[Ee.scheme]=Ee,F[qt.scheme]=qt,F[h5.scheme]=h5,F[m5.scheme]=m5,F[y5.scheme]=y5,t.SCHEMES=F,t.pctEncChar=X,t.pctDecChars=ie,t.parse=he,t.removeDotSegments=We,t.serialize=nr,t.resolveComponents=Ur,t.resolve=pr,t.normalize=Lt,t.equal=T,t.escapeComponent=U,t.unescapeComponent=N,Object.defineProperty(t,"__esModule",{value:!0})})}),ole=Zt((r,e)=>{"use strict";e.exports=function t(n){if(typeof n=="number"&&isNaN(n))throw new Error("NaN is not allowed");if(typeof n=="number"&&!isFinite(n))throw new Error("Infinity is not allowed");return n===null||typeof n!="object"?JSON.stringify(n):n.toJSON instanceof Function?t(n.toJSON()):Array.isArray(n)?`[${n.reduce((i,a,s)=>`${i}${s===0?"":","}${t(a===void 0||typeof a=="symbol"?null:a)}`,"")}]`:`{${Object.keys(n).sort().reduce((i,a)=>{if(n[a]===void 0||typeof n[a]=="symbol")return i;let s=i.length===0?"":",";return`${i}${s}${t(a)}:${t(n[a])}`},"")}}`}}),_z=Zt((r,e)=>{var t=1e3,n=t*60,i=n*60,a=i*24,s=a*7,o=a*365.25;e.exports=function(f,p){p=p||{};var h=typeof f;if(h==="string"&&f.length>0)return c(f);if(h==="number"&&isFinite(f))return p.long?d(f):l(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function c(f){if(f=String(f),!(f.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(p){var h=parseFloat(p[1]),m=(p[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return h*o;case"weeks":case"week":case"w":return h*s;case"days":case"day":case"d":return h*a;case"hours":case"hour":case"hrs":case"hr":case"h":return h*i;case"minutes":case"minute":case"mins":case"min":case"m":return h*n;case"seconds":case"second":case"secs":case"sec":case"s":return h*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return h;default:return}}}}function l(f){var p=Math.abs(f);return p>=a?Math.round(f/a)+"d":p>=i?Math.round(f/i)+"h":p>=n?Math.round(f/n)+"m":p>=t?Math.round(f/t)+"s":f+"ms"}function d(f){var p=Math.abs(f);return p>=a?u(f,p,a,"day"):p>=i?u(f,p,i,"hour"):p>=n?u(f,p,n,"minute"):p>=t?u(f,p,t,"second"):f+" ms"}function u(f,p,h,m){var y=p>=h*1.5;return Math.round(f/h)+" "+m+(y?"s":"")}}),lE=(r=>(r.authentication="authentication",r.assertionMethod="assertionMethod",r.keyAgreement="keyAgreement",r.capabilityInvocation="capabilityInvocation",r.capabilityDelegation="capabilityDelegation",r))(lE||{}),is={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},Xi=class Az{constructor({method:e,id:t,path:n,query:i,fragment:a,params:s}){this.uri=`did:${e}:${t}`,this.method=e,this.id=t,this.path=n,this.query=i,this.fragment=a,this.params=s}static parse(e){if(!e||e.length>2048)return null;let t=Az.DID_URI_PATTERN.exec(e);if(!t?.groups)return null;let{method:n,id:i,path:a,query:s,fragment:o}=t.groups,c={uri:`did:${n}:${i}`,method:n,id:i};if(a&&(c.path=a),s&&(c.query=s.slice(1)),o&&(c.fragment=o.slice(1)),s){let l={},d=s.slice(1).split("&");for(let u of d){let[f,p]=u.split("=");l[f]=p}c.params=l}return c}};Xi.METHOD_PATTERN="([a-z0-9]+)",Xi.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",Xi.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${Xi.PCT_ENCODED_PATTERN})`,Xi.METHOD_ID_PATTERN=`((?:${Xi.ID_CHAR_PATTERN}*:)*(${Xi.ID_CHAR_PATTERN}+))`,Xi.PATH_PATTERN="(/[^#?]*)?",Xi.QUERY_PATTERN="([?][^#]*)?",Xi.FRAGMENT_PATTERN="(#.*)?",Xi.DID_URI_PATTERN=new RegExp("^did:(?<method>"+Xi.METHOD_PATTERN+"):(?<id>"+Xi.METHOD_ID_PATTERN+")(?<path>"+Xi.PATH_PATTERN+")(?<query>"+Xi.QUERY_PATTERN+")(?<fragment>"+Xi.FRAGMENT_PATTERN+")$");Vn=Xi,Xe=class Tz extends Error{constructor(e,t){super(`${e}: ${t}`),this.code=e,this.name="DidError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Tz)}},ale=(r=>(r.InvalidDid="invalidDid",r.MethodNotSupported="methodNotSupported",r.InternalError="internalError",r.InvalidDidDocument="invalidDidDocument",r.InvalidDidDocumentLength="invalidDidDocumentLength",r.InvalidDidUrl="invalidDidUrl",r.InvalidGatewayUri="invalidGatewayUri",r.InvalidPreviousDidProof="invalidPreviousDidProof",r.InvalidPublicKey="invalidPublicKey",r.InvalidPublicKeyLength="invalidPublicKeyLength",r.InvalidPublicKeyType="invalidPublicKeyType",r.InvalidSignature="invalidSignature",r.NotFound="notFound",r.RepresentationNotSupported="representationNotSupported",r.UnsupportedPublicKeyType="unsupportedPublicKeyType",r))(ale||{}),ja=class Iz extends Error{constructor(e,t){super(t),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Iz)}};(function(r){r.AlgorithmNotSupported="algorithmNotSupported",r.EncodingError="encodingError",r.InvalidCoseSign1="invalidCoseSign1",r.InvalidEat="invalidEat",r.InvalidJwe="invalidJwe",r.InvalidJwk="invalidJwk",r.OperationNotSupported="operationNotSupported"})(go||(go={}));cle=vh(Nde(),1);lle=dle,ule=lle,fle=ule,CNe=new Uint8Array(0),ple=(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},BC=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")},hle=class{constructor(r,e,t){this.name=r,this.prefix=e,this.baseEncode=t}encode(r){if(r instanceof Uint8Array)return`${this.prefix}${this.baseEncode(r)}`;throw Error("Unknown type, must be binary type")}},mle=class{constructor(r,e,t){if(this.name=r,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=t}decode(r){if(typeof r=="string"){if(r.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(r)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(r.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(r){return Dz(this,r)}},yle=class{constructor(r){this.decoders=r}or(r){return Dz(this,r)}decode(r){let e=r[0],t=this.decoders[e];if(t)return t.decode(r);throw RangeError(`Unable to decode multibase string ${JSON.stringify(r)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Dz=(r,e)=>new yle({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),gle=class{constructor(r,e,t,n){this.name=r,this.prefix=e,this.baseEncode=t,this.baseDecode=n,this.encoder=new hle(r,e,t),this.decoder=new mle(r,e,n)}encode(r){return this.encoder.encode(r)}decode(r){return this.decoder.decode(r)}},Rz=({name:r,prefix:e,encode:t,decode:n})=>new gle(r,e,t,n),Cz=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:i}=fle(t,e);return Rz({prefix:r,name:e,encode:n,decode:a=>BC(i(a))})},wle=(r,e,t,n)=>{let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let a=r.length;for(;r[a-1]==="=";)--a;let s=new Uint8Array(a*t/8|0),o=0,c=0,l=0;for(let d=0;d<a;++d){let u=i[r[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,o+=t,o>=8&&(o-=8,s[l++]=255&c>>o)}if(o>=t||255&c<<8-o)throw new SyntaxError("Unexpected end of data");return s},vle=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,a="",s=0,o=0;for(let c=0;c<r.length;++c)for(o=o<<8|r[c],s+=8;s>t;)s-=t,a+=e[i&o>>s];if(s&&(a+=e[i&o<<t-s]),n)for(;a.length*t&7;)a+="=";return a},Yo=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>Rz({prefix:e,name:r,encode(i){return vle(i,n,t)},decode(i){return wle(i,n,t,r)}}),D2=Yo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$Ne=Yo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),BNe=Yo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ONe=Yo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),jNe=Yo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),MNe=Yo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),KNe=Yo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),UNe=Yo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),eq=Yo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Ba=Cz({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),NNe=Cz({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),LNe=Yo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),qNe=Yo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ol=Yo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zNe=Yo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});T0=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},tq=function(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof __values=="function"?__values(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(a){t[a]=r[a]&&function(s){return new Promise(function(o,c){s=r[a](s),i(o,c,s.done,s.value)})}}function i(a,s,o,c){Promise.resolve(c).then(function(l){a({value:l,done:o})},s)}},x2=new TextEncoder,sh=new TextDecoder,rt=class mo{constructor(e,t){this.data=e,this.format=t}static arrayBuffer(e){return new mo(e,"ArrayBuffer")}static asyncIterable(e){if(!Ple(e))throw new TypeError("Input must be of type AsyncIterable.");return new mo(e,"AsyncIterable")}static base32Z(e){return new mo(e,"Base32Z")}static base58Btc(e){return new mo(e,"Base58Btc")}static base64Url(e){return new mo(e,"Base64Url")}static bufferSource(e){return new mo(e,"BufferSource")}static hex(e){if(typeof e!="string")throw new TypeError("Hex input must be a string.");if(e.length%2!==0)throw new TypeError("Hex input must have an even number of characters.");return new mo(e,"Hex")}static multibase(e){return new mo(e,"Multibase")}static object(e){return new mo(e,"Object")}static string(e){return new mo(e,"String")}static uint8Array(e){return new mo(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return Ba.baseDecode(this.data).buffer;case"Base64Url":return Ol.baseDecode(this.data).buffer;case"BufferSource":{if(lC(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return ble(this.data)?this.data.buffer.slice(this.data.byteOffset,this.data.byteOffset+this.data.byteLength):this.data.buffer;throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":return this.toUint8Array().buffer;case"String":return this.toUint8Array().buffer;case"Uint8Array":return this.data.buffer;default:throw new TypeError(`Conversion from ${this.format} to ArrayBuffer is not supported.`)}}toArrayBufferAsync(){return T0(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":return yield(yield this.toBlobAsync()).arrayBuffer();default:throw new TypeError(`Asynchronous conversion from ${this.format} to ArrayBuffer is not supported.`)}})}toBase32Z(){switch(this.format){case"Uint8Array":return eq.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Z is not supported.`)}}toBase58Btc(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return Ba.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return Ba.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base58Btc is not supported.`)}}toBase64Url(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return Ol.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return Ol.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),t=x2.encode(e);return Ol.baseEncode(t)}case"String":{let e=x2.encode(this.data);return Ol.baseEncode(e)}case"Uint8Array":return Ol.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return T0(this,void 0,void 0,function*(){var e,t,n,i;switch(this.format){case"AsyncIterable":{let c=[];try{for(var a=!0,s=tq(this.data),o;o=yield s.next(),e=o.done,!e;a=!0){i=o.value,a=!1;let l=i;c.push(l)}}catch(l){t={error:l}}finally{try{!a&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(t)throw t.error}}return new Blob(c)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let t=this.toUint8Array();return mo.uint8Array(t).toHex()}case"Base64Url":{let t=this.toUint8Array();return mo.uint8Array(t).toHex()}case"Uint8Array":{let t="";for(let n=0;n<this.data.length;n++)t+=e[this.data[n]];return t}default:throw new TypeError(`Conversion from ${this.format} to Hex is not supported.`)}}toMultibase(){switch(this.format){case"Base58Btc":return`z${this.data}`;default:throw new TypeError(`Conversion from ${this.format} to Multibase is not supported.`)}}toObject(){switch(this.format){case"Base64Url":{let e=Ol.baseDecode(this.data),t=sh.decode(e);return JSON.parse(t)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=sh.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return T0(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toStringAsync();return JSON.parse(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Object is not supported.`)}})}toString(){switch(this.format){case"ArrayBuffer":return sh.decode(this.data);case"Base64Url":{let e=Ol.baseDecode(this.data);return sh.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return sh.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return T0(this,void 0,void 0,function*(){var e,t,n,i;switch(this.format){case"AsyncIterable":{let c="";try{for(var a=!0,s=tq(this.data),o;o=yield s.next(),e=o.done,!e;a=!0){i=o.value,a=!1;let l=i;typeof l=="string"?c+=l:c+=sh.decode(l,{stream:!0})}}catch(l){t={error:l}}finally{try{!a&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(t)throw t.error}}return c+=sh.decode(void 0,{stream:!1}),c}default:throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`)}})}toUint8Array(){switch(this.format){case"ArrayBuffer":return new Uint8Array(this.data);case"Base32Z":return eq.baseDecode(this.data);case"Base58Btc":return Ba.baseDecode(this.data);case"Base64Url":return Ol.baseDecode(this.data);case"BufferSource":{let e=lC(this.data);if(e==="Uint8Array")return this.data;if(e==="ArrayBuffer")return new Uint8Array(this.data);if(ArrayBuffer.isView(this.data))return new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength);throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":{let e=new Uint8Array(this.data.length/2);for(let t=0;t<this.data.length;t+=2){let n=parseInt(this.data.substring(t,t+2),16);if(isNaN(n))throw new TypeError("Input is not a valid hexadecimal string.");e[t/2]=n}return e}case"Object":{let e=JSON.stringify(this.data);return x2.encode(e)}case"String":return x2.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return T0(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toArrayBufferAsync();return new Uint8Array(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Uint8Array is not supported.`)}})}};(function(r){r.Debug="debug",r.Silent="silent"})(Z0||(Z0={}));xle=class{constructor(){this.logLevel=Z0.Silent}setLogLevel(r){this.logLevel=r}log(r){this.info(r)}info(r){this.logLevel!==Z0.Silent&&console.info(r)}error(r){this.logLevel!==Z0.Silent&&console.error(r)}},Ele=new xle;typeof window<"u"&&(window.enboxLogger=Ele);O0={};RC(O0,{decode:()=>X2,encodeTo:()=>X0,encodingLength:()=>Q0});Sle=$z,rq=128,kle=127,_le=~kle,Ale=Math.pow(2,31);Tle=uC,Ile=128,nq=127;Dle=Math.pow(2,7),Rle=Math.pow(2,14),Cle=Math.pow(2,21),$le=Math.pow(2,28),Ble=Math.pow(2,35),Ole=Math.pow(2,42),jle=Math.pow(2,49),Mle=Math.pow(2,56),Kle=Math.pow(2,63),Ule=function(r){return r<Dle?1:r<Rle?2:r<Cle?3:r<$le?4:r<Ble?5:r<Ole?6:r<jle?7:r<Mle?8:r<Kle?9:10},Nle={encode:Sle,decode:Tle,encodingLength:Ule},Lle=Nle,Y2=Lle,X2=(r,e=0)=>[Y2.decode(r,e),Y2.decode.bytes],X0=(r,e,t=0)=>(Y2.encode(r,e,t),e),Q0=r=>Y2.encodingLength(r),qle=(r,e)=>{let t=e.byteLength,n=Q0(r),i=n+Q0(t),a=new Uint8Array(i+t);return X0(r,a,0),X0(t,a,n),a.set(e,i),new OC(r,t,e,a)},zle=r=>{let e=BC(r),[t,n]=X2(e),[i,a]=X2(e.subarray(n)),s=e.subarray(n+a);if(s.byteLength!==i)throw new Error("Incorrect length");return new OC(t,i,s,e)},Fle=(r,e)=>{if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ple(r.bytes,t.bytes)}},OC=class{constructor(r,e,t,n){this.code=r,this.size=e,this.digest=t,this.bytes=n}},iq=(r,e)=>{let{bytes:t,version:n}=r;switch(n){case 0:return Hle(t,fC(r),e||Ba.encoder);default:return Vle(t,fC(r),e||D2.encoder)}},sq=new WeakMap,fC=r=>{let e=sq.get(r);if(e==null){let t=new Map;return sq.set(r,t),t}return e},FNe=class vs{constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==I0)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Wle)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return vs.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=qle(e,t);return vs.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 vs.equals(this,e)}static equals(e,t){let n=t;return n&&e.code===n.code&&e.version===n.version&&Fle(e.multihash,n.multihash)}toString(e){return iq(this,e)}toJSON(){return{"/":iq(this)}}link(){return this}get[Symbol.toStringTag](){return"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 vs)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:a,bytes:s}=t;return new vs(n,i,a,s||oq(n,i,a.bytes))}else if(t[Jle]===!0){let{version:n,multihash:i,code:a}=t,s=zle(i);return vs.create(n,a,s)}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!==I0)throw new Error(`Version 0 CID must use dag-pb (code: ${I0}) block encoding`);return new vs(e,t,n,n.bytes)}case 1:{let i=oq(e,t,n.bytes);return new vs(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return vs.create(0,I0,e)}static createV1(e,t){return vs.create(1,e,t)}static decode(e){let[t,n]=vs.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=vs.inspectBytes(e),n=t.size-t.multihashSize,i=BC(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let a=i.subarray(t.multihashSize-t.digestSize),s=new OC(t.multihashCode,t.digestSize,a,i);return[t.version===0?vs.createV0(s):vs.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,f]=X2(e.subarray(t));return t+=f,u},i=n(),a=I0;if(i===18?(i=0,t=0):a=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,o=n(),c=n(),l=t+c,d=l-s;return{version:i,codec:a,multihashCode:o,digestSize:c,multihashSize:d,size:l}}static parse(e,t){let[n,i]=Gle(e,t),a=vs.decode(i);if(a.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return fC(a).set(n,e),a}},Gle=(r,e)=>{switch(r[0]){case"Q":{let t=e||Ba;return[Ba.prefix,t.decode(`${Ba.prefix}${r}`)]}case Ba.prefix:{let t=e||Ba;return[Ba.prefix,t.decode(r)]}case D2.prefix:{let t=e||D2;return[D2.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},Hle=(r,e,t)=>{let{prefix:n}=t;if(n!==Ba.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let a=t.encode(r).slice(1);return e.set(n,a),a}else return i},Vle=(r,e,t)=>{let{prefix:n}=t,i=e.get(n);if(i==null){let a=t.encode(r);return e.set(n,a),a}else return i},I0=112,Wle=18,oq=(r,e,t)=>{let n=Q0(r),i=n+Q0(e),a=new Uint8Array(i+t.byteLength);return X0(r,a,0),X0(e,a,n),a.set(t,i),a},Jle=Symbol.for("@ipld/js-cid/CID"),Ka=class vf{static addPrefix(e){var t;let{code:n,data:i,name:a}=e;if(!(a?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=vf.codeToName.has(n)?n:vf.nameToCode.get(a),n===void 0)throw new Error(`Unsupported multicodec: ${(t=e.name)!==null&&t!==void 0?t:e.code}`);let s=O0.encodingLength(n),o=new Uint8Array(s+i.byteLength);return o.set(i,s),O0.encodeTo(n,o),o}static getCodeFromData(e){let{prefixedData:t}=e,[n,i]=O0.decode(t);return n}static getCodeFromName(e){let{name:t}=e,n=vf.nameToCode.get(t);if(n===void 0)throw new Error(`Unsupported multicodec: ${t}`);return n}static getNameFromCode(e){let{code:t}=e,n=vf.codeToName.get(t);if(n===void 0)throw new Error(`Unsupported multicodec: ${t}`);return n}static registerCodec(e){vf.codeToName.set(e.code,e.name),vf.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:t}=e,[n,i]=O0.decode(t),a=vf.codeToName.get(n);if(a===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:t.slice(i),name:a}}};Ka.codeToName=new Map;Ka.nameToCode=new Map;Ka.registerCodec({code:237,name:"ed25519-pub"});Ka.registerCodec({code:4864,name:"ed25519-priv"});Ka.registerCodec({code:236,name:"x25519-pub"});Ka.registerCodec({code:4866,name:"x25519-priv"});Ka.registerCodec({code:231,name:"secp256k1-pub"});Ka.registerCodec({code:4865,name:"secp256k1-priv"});GNe=vh(kz(),1),df=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},Zle=class{constructor(){this.store=new Map}clear(){return df(this,void 0,void 0,function*(){this.store.clear()})}open(){return df(this,void 0,void 0,function*(){})}close(){return df(this,void 0,void 0,function*(){})}delete(r){return df(this,void 0,void 0,function*(){return this.store.delete(r)})}get(r){return df(this,void 0,void 0,function*(){return this.store.get(r)})}has(r){return df(this,void 0,void 0,function*(){return this.store.has(r)})}list(){return df(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(r,e){return df(this,void 0,void 0,function*(){this.store.set(r,e)})}},Yle=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})};Qle=["http:","https:"],R2=class extends Error{constructor(r){super(r),this.name="PublicUrlValidationError"}};eue=5,tue=new Set([301,302,303,307,308]);uE=class{},Kz={};RC(Kz,{bitGet:()=>fue,bitLen:()=>uue,bitMask:()=>MC,bitSet:()=>pue,bytesToHex:()=>yh,bytesToNumberBE:()=>ph,bytesToNumberLE:()=>Sf,concatBytes:()=>gh,createHmacDrbg:()=>Lz,ensureBytes:()=>Hn,equalBytes:()=>due,hexToBytes:()=>Xy,hexToNumber:()=>jC,isBytes:()=>Od,numberToBytesBE:()=>jd,numberToBytesLE:()=>Qy,numberToHexUnpadded:()=>Nz,numberToVarBytesBE:()=>cue,utf8ToBytes:()=>lue,validateObject:()=>bh});Uz=BigInt(0),fE=BigInt(1),oue=BigInt(2);aue=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));jl={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};pue=(r,e,t)=>r|(t?fE:Uz)<<BigInt(e),MC=r=>(oue<<BigInt(r-1))-fE,eC=r=>new Uint8Array(r),dq=r=>Uint8Array.from(r);hue={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Od(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};tC=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;rC=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Ad=(r,e)=>r<<32-e|r>>>e,wue=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!wue)throw new Error("Non little-endian hardware is not supported");Hz=class{clone(){return this._cloneInto()}},HNe={}.toString;Wz=class extends Hz{constructor(r,e,t,n){super(),this.blockLen=r,this.outputLen=e,this.padOffset=t,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(r),this.view=rC(this.buffer)}update(r){Q2(this);let{view:e,buffer:t,blockLen:n}=this;r=KC(r);let i=r.length;for(let a=0;a<i;){let s=Math.min(n-this.pos,i-a);if(s===n){let o=rC(r);for(;n<=i-a;a+=n)this.process(o,a);continue}t.set(r.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=r.length,this.roundClean(),this}digestInto(r){Q2(this),gue(r,this),this.finished=!0;let{buffer:e,view:t,blockLen:n,isLE:i}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(t,0),a=0);for(let d=a;d<n;d++)e[d]=0;vue(t,n-8,BigInt(this.length*8),i),this.process(t,0);let s=rC(r),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=o/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)s.setUint32(4*d,l[d],i)}digest(){let{buffer:r,outputLen:e}=this;this.digestInto(r);let t=r.slice(0,e);return this.destroy(),t}_cloneInto(r){r||(r=new this.constructor),r.set(...this.get());let{blockLen:e,buffer:t,length:n,finished:i,destroyed:a,pos:s}=this;return r.length=n,r.pos=s,r.finished=i,r.destroyed=a,n%e&&r.buffer.set(t),r}},bue=(r,e,t)=>r&e^~r&t,Pue=(r,e,t)=>r&e^r&t^e&t,xue=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),lf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),uf=new Uint32Array(64),Eue=class extends Wz{constructor(){super(64,32,8,!1),this.A=lf[0]|0,this.B=lf[1]|0,this.C=lf[2]|0,this.D=lf[3]|0,this.E=lf[4]|0,this.F=lf[5]|0,this.G=lf[6]|0,this.H=lf[7]|0}get(){let{A:r,B:e,C:t,D:n,E:i,F:a,G:s,H:o}=this;return[r,e,t,n,i,a,s,o]}set(r,e,t,n,i,a,s,o){this.A=r|0,this.B=e|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=s|0,this.H=o|0}process(r,e){for(let d=0;d<16;d++,e+=4)uf[d]=r.getUint32(e,!1);for(let d=16;d<64;d++){let u=uf[d-15],f=uf[d-2],p=Ad(u,7)^Ad(u,18)^u>>>3,h=Ad(f,17)^Ad(f,19)^f>>>10;uf[d]=h+uf[d-7]+p+uf[d-16]|0}let{A:t,B:n,C:i,D:a,E:s,F:o,G:c,H:l}=this;for(let d=0;d<64;d++){let u=Ad(s,6)^Ad(s,11)^Ad(s,25),f=l+u+bue(s,o,c)+xue[d]+uf[d]|0,p=(Ad(t,2)^Ad(t,13)^Ad(t,22))+Pue(t,n,i)|0;l=c,c=o,o=s,s=a+f|0,a=i,i=n,n=t,t=f+p|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,s=s+this.E|0,o=o+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(t,n,i,a,s,o,c,l)}roundClean(){uf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},Jz=Vz(()=>new Eue),mi=BigInt(0),yn=BigInt(1),ch=BigInt(2),Sue=BigInt(3),pC=BigInt(4),uq=BigInt(5),fq=BigInt(8),VNe=BigInt(9),kue=BigInt(16);Tue=(r,e)=>(Zr(r,e)&yn)===yn,Iue=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];Oue=BigInt(0),nC=BigInt(1);({bytesToNumberBE:Mue,hexToBytes:Kue}=Kz),uh={Err:class extends Error{constructor(r=""){super(r)}},_parseInt(r){let{Err:e}=uh;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:Mue(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=uh,t=typeof r=="string"?Kue(r):r;if(!Od(t))throw new Error("ui8a expected");let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:i,l:a}=uh._parseInt(t.subarray(2)),{d:s,l:o}=uh._parseInt(a);if(o.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(r){let e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{let d=l.toString(16);return d.length&1?`0${d}`:d},n=e(t(r.s)),i=e(t(r.r)),a=n.length/2,s=i.length/2,o=t(a),c=t(s);return`30${t(s+a+4)}02${c}${i}02${o}${n}`}},ql=BigInt(0),$a=BigInt(1),WNe=BigInt(2),pq=BigInt(3),JNe=BigInt(4);t7=class extends Hz{constructor(r,e){super(),this.finished=!1,this.destroyed=!1,yue(r);let t=KC(e);if(this.iHash=r.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(t.length>n?r.create().update(t).digest():t);for(let a=0;a<i.length;a++)i[a]^=54;this.iHash.update(i),this.oHash=r.create();for(let a=0;a<i.length;a++)i[a]^=106;this.oHash.update(i),i.fill(0)}update(r){return Q2(this),this.iHash.update(r),this}digestInto(r){Q2(this),qz(r,this.outputLen),this.finished=!0,this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let r=new Uint8Array(this.oHash.outputLen);return this.digestInto(r),r}_cloneInto(r){r||(r=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:t,finished:n,destroyed:i,blockLen:a,outputLen:s}=this;return r=r,r.finished=n,r.destroyed=i,r.blockLen=a,r.outputLen=s,r.oHash=e._cloneInto(r.oHash),r.iHash=t._cloneInto(r.iHash),r}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},r7=(r,e,t)=>new t7(r,e).update(t).digest();r7.create=(r,e)=>new t7(r,e);i7=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),hq=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),zue=BigInt(1),mC=BigInt(2),mq=(r,e)=>(r+e/mC)/e;yC=NC(i7,void 0,void 0,{sqrt:Fue}),Vo=n7({a:BigInt(0),b:BigInt(7),Fp:yC,n:hq,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=hq,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-zue*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=t,s=BigInt("0x100000000000000000000000000000000"),o=mq(a*r,e),c=mq(-n*r,e),l=Zr(r-o*t-c*i,e),d=Zr(-o*n-c*a,e),u=l>s,f=d>s;if(u&&(l=e-l),f&&(d=e-d),l>s||d>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:f,k2:d}}}},Jz),ZNe=BigInt(0),YNe=Vo.ProjectivePoint;C2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,iC=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Td=(r,e)=>r<<32-e|r>>>e,XNe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;Wue=class{clone(){return this._cloneInto()}},QNe={}.toString;Xue=(r,e,t)=>r&e^~r&t,Que=(r,e,t)=>r&e^r&t^e&t,efe=class extends Wue{constructor(r,e,t,n){super(),this.blockLen=r,this.outputLen=e,this.padOffset=t,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(r),this.view=iC(this.buffer)}update(r){yq(this);let{view:e,buffer:t,blockLen:n}=this;r=o7(r);let i=r.length;for(let a=0;a<i;){let s=Math.min(n-this.pos,i-a);if(s===n){let o=iC(r);for(;n<=i-a;a+=n)this.process(o,a);continue}t.set(r.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=r.length,this.roundClean(),this}digestInto(r){yq(this),Hue(r,this),this.finished=!0;let{buffer:e,view:t,blockLen:n,isLE:i}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(t,0),a=0);for(let d=a;d<n;d++)e[d]=0;Yue(t,n-8,BigInt(this.length*8),i),this.process(t,0);let s=iC(r),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=o/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)s.setUint32(4*d,l[d],i)}digest(){let{buffer:r,outputLen:e}=this;this.digestInto(r);let t=r.slice(0,e);return this.destroy(),t}_cloneInto(r){r||(r=new this.constructor),r.set(...this.get());let{blockLen:e,buffer:t,length:n,finished:i,destroyed:a,pos:s}=this;return r.length=n,r.pos=s,r.finished=i,r.destroyed=a,n%e&&r.buffer.set(t),r}},tfe=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ff=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),pf=new Uint32Array(64),rfe=class extends efe{constructor(){super(64,32,8,!1),this.A=ff[0]|0,this.B=ff[1]|0,this.C=ff[2]|0,this.D=ff[3]|0,this.E=ff[4]|0,this.F=ff[5]|0,this.G=ff[6]|0,this.H=ff[7]|0}get(){let{A:r,B:e,C:t,D:n,E:i,F:a,G:s,H:o}=this;return[r,e,t,n,i,a,s,o]}set(r,e,t,n,i,a,s,o){this.A=r|0,this.B=e|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=s|0,this.H=o|0}process(r,e){for(let d=0;d<16;d++,e+=4)pf[d]=r.getUint32(e,!1);for(let d=16;d<64;d++){let u=pf[d-15],f=pf[d-2],p=Td(u,7)^Td(u,18)^u>>>3,h=Td(f,17)^Td(f,19)^f>>>10;pf[d]=h+pf[d-7]+p+pf[d-16]|0}let{A:t,B:n,C:i,D:a,E:s,F:o,G:c,H:l}=this;for(let d=0;d<64;d++){let u=Td(s,6)^Td(s,11)^Td(s,25),f=l+u+Xue(s,o,c)+tfe[d]+pf[d]|0,p=(Td(t,2)^Td(t,13)^Td(t,22))+Que(t,n,i)|0;l=c,c=o,o=s,s=a+f|0,a=i,i=n,n=t,t=f+p|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,s=s+this.E|0,o=o+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(t,n,i,a,s,o,c,l)}roundClean(){pf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},eb=Jue(()=>new rfe);ife=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},a7=class{static digest(r){return ife(this,arguments,void 0,function*({data:e}){return eb(e)})}},sfe=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},gq="urn:jwk:";Zi=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},afe=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},es=class Dd{static adjustSignatureToLowS(e){return Zi(this,arguments,void 0,function*({signature:t}){let n=Vo.Signature.fromCompact(t);return n.hasHighS()?n.normalizeS().toCompactRawBytes():t})}static bytesToPrivateKey(e){return Zi(this,arguments,void 0,function*({privateKeyBytes:t}){let n=yield Dd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"secp256k1",d:rt.uint8Array(t).toBase64Url(),x:rt.uint8Array(n.x).toBase64Url(),y:rt.uint8Array(n.y).toBase64Url()};return i.kid=yield xr({jwk:i}),i})}static bytesToPublicKey(e){return Zi(this,arguments,void 0,function*({publicKeyBytes:t}){let n=yield Dd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"secp256k1",x:rt.uint8Array(n.x).toBase64Url(),y:rt.uint8Array(n.y).toBase64Url()};return i.kid=yield xr({jwk:i}),i})}static compressPublicKey(e){return Zi(this,arguments,void 0,function*({publicKeyBytes:t}){return Vo.ProjectivePoint.fromHex(t).toRawBytes(!0)})}static computePublicKey(e){return Zi(this,arguments,void 0,function*({key:t}){let n=yield Dd.privateKeyToBytes({privateKey:t}),i=yield Dd.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"secp256k1",x:rt.uint8Array(i.x).toBase64Url(),y:rt.uint8Array(i.y).toBase64Url()};return a.kid=yield xr({jwk:a}),a})}static convertDerToCompactSignature(e){return Zi(this,arguments,void 0,function*({derSignature:t}){return Vo.Signature.fromDER(t).toCompactRawBytes()})}static decompressPublicKey(e){return Zi(this,arguments,void 0,function*({publicKeyBytes:t}){return Vo.ProjectivePoint.fromHex(t).toRawBytes(!1)})}static generateKey(){return Zi(this,void 0,void 0,function*(){let e=Vo.utils.randomPrivateKey(),t=yield Dd.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield xr({jwk:t}),t})}static getPublicKey(e){return Zi(this,arguments,void 0,function*({key:t}){var n;if(!(hh(t)&&t.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=t,a=afe(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield xr({jwk:a})),a})}static privateKeyToBytes(e){return Zi(this,arguments,void 0,function*({privateKey:t}){if(!hh(t))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return rt.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Zi(this,arguments,void 0,function*({publicKey:t}){if(!(qC(t)&&t.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=rt.base64Url(t.x).toUint8Array(),a=rt.base64Url(t.y).toUint8Array();return new Uint8Array([...n,...i,...a])})}static sharedSecret(e){return Zi(this,arguments,void 0,function*({privateKeyA:t,publicKeyB:n}){if("x"in t&&"x"in n&&t.x===n.x)throw new Error("Secp256k1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield Dd.privateKeyToBytes({privateKey:t}),a=yield Dd.publicKeyToBytes({publicKey:n});return Vo.getSharedSecret(i,a,!0).slice(1)})}static sign(e){return Zi(this,arguments,void 0,function*({data:t,key:n}){let i=yield Dd.privateKeyToBytes({privateKey:n}),a=eb(t);return Vo.sign(a,i).toCompactRawBytes()})}static validatePrivateKey(e){return Zi(this,arguments,void 0,function*({privateKeyBytes:t}){return Vo.utils.isValidPrivateKey(t)})}static validatePublicKey(e){return Zi(this,arguments,void 0,function*({publicKeyBytes:t}){try{Vo.ProjectivePoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return Zi(this,arguments,void 0,function*({key:t,signature:n,data:i}){let a=yield Dd.publicKeyToBytes({publicKey:t}),s=eb(i);return Vo.verify(n,s,a,{lowS:!1})})}static getCurvePoint(e){return Zi(this,arguments,void 0,function*({keyBytes:t}){t.byteLength===32&&(t=Vo.getPublicKey(t));let n=Vo.ProjectivePoint.fromHex(t),i=jd(n.x,32),a=jd(n.y,32);return{x:i,y:a}})}},c7=NC(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),cfe=c7.create(BigInt("-3")),dfe=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),lfe=n7({a:cfe,b:dfe,Fp:c7,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Jz),Ta=lfe,Yi=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},ufe=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},bs=class Rd{static adjustSignatureToLowS(e){return Yi(this,arguments,void 0,function*({signature:t}){let n=Ta.Signature.fromCompact(t);return n.hasHighS()?n.normalizeS().toCompactRawBytes():t})}static bytesToPrivateKey(e){return Yi(this,arguments,void 0,function*({privateKeyBytes:t}){let n=yield Rd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"P-256",d:rt.uint8Array(t).toBase64Url(),x:rt.uint8Array(n.x).toBase64Url(),y:rt.uint8Array(n.y).toBase64Url()};return i.kid=yield xr({jwk:i}),i})}static bytesToPublicKey(e){return Yi(this,arguments,void 0,function*({publicKeyBytes:t}){let n=yield Rd.getCurvePoint({keyBytes:t}),i={kty:"EC",crv:"P-256",x:rt.uint8Array(n.x).toBase64Url(),y:rt.uint8Array(n.y).toBase64Url()};return i.kid=yield xr({jwk:i}),i})}static compressPublicKey(e){return Yi(this,arguments,void 0,function*({publicKeyBytes:t}){return Ta.ProjectivePoint.fromHex(t).toRawBytes(!0)})}static computePublicKey(e){return Yi(this,arguments,void 0,function*({key:t}){let n=yield Rd.privateKeyToBytes({privateKey:t}),i=yield Rd.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"P-256",x:rt.uint8Array(i.x).toBase64Url(),y:rt.uint8Array(i.y).toBase64Url()};return a.kid=yield xr({jwk:a}),a})}static convertDerToCompactSignature(e){return Yi(this,arguments,void 0,function*({derSignature:t}){return Ta.Signature.fromDER(t).toCompactRawBytes()})}static decompressPublicKey(e){return Yi(this,arguments,void 0,function*({publicKeyBytes:t}){return Ta.ProjectivePoint.fromHex(t).toRawBytes(!1)})}static generateKey(){return Yi(this,void 0,void 0,function*(){let e=Ta.utils.randomPrivateKey(),t=yield Rd.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield xr({jwk:t}),t})}static getPublicKey(e){return Yi(this,arguments,void 0,function*({key:t}){var n;if(!(hh(t)&&t.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=t,a=ufe(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield xr({jwk:a})),a})}static privateKeyToBytes(e){return Yi(this,arguments,void 0,function*({privateKey:t}){if(!hh(t))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return rt.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Yi(this,arguments,void 0,function*({publicKey:t}){if(!(qC(t)&&t.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=rt.base64Url(t.x).toUint8Array(),a=rt.base64Url(t.y).toUint8Array();return new Uint8Array([...n,...i,...a])})}static sharedSecret(e){return Yi(this,arguments,void 0,function*({privateKeyA:t,publicKeyB:n}){if("x"in t&&"x"in n&&t.x===n.x)throw new Error("Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield Rd.privateKeyToBytes({privateKey:t}),a=yield Rd.publicKeyToBytes({publicKey:n});return Ta.getSharedSecret(i,a,!0).slice(1)})}static sign(e){return Yi(this,arguments,void 0,function*({data:t,key:n}){let i=yield Rd.privateKeyToBytes({privateKey:n}),a=eb(t);return Ta.sign(a,i).toCompactRawBytes()})}static validatePrivateKey(e){return Yi(this,arguments,void 0,function*({privateKeyBytes:t}){return Ta.utils.isValidPrivateKey(t)})}static validatePublicKey(e){return Yi(this,arguments,void 0,function*({publicKeyBytes:t}){try{Ta.ProjectivePoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return Yi(this,arguments,void 0,function*({key:t,signature:n,data:i}){let a=yield Rd.publicKeyToBytes({publicKey:t}),s=eb(i);return Ta.verify(n,s,a,{lowS:!1})})}static getCurvePoint(e){return Yi(this,arguments,void 0,function*({keyBytes:t}){t.byteLength===32&&(t=Ta.getPublicKey(t));let n=Ta.ProjectivePoint.fromHex(t),i=jd(n.x,32),a=jd(n.y,32);return{x:i,y:a}})}},Ml=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},wq=class extends uE{bytesToPrivateKey(r){return Ml(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"ES256K":case"secp256k1":{let n=yield es.bytesToPrivateKey({privateKeyBytes:t});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield bs.bytesToPrivateKey({privateKeyBytes:t});return n.alg="ES256",n}default:throw new ja(go.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(r){return Ml(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:t}){switch(e){case"ES256K":case"secp256k1":{let n=yield es.bytesToPublicKey({publicKeyBytes:t});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield bs.bytesToPublicKey({publicKeyBytes:t});return n.alg="ES256",n}default:throw new ja(go.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return Ml(this,arguments,void 0,function*({key:e}){if(!hh(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let t=yield es.computePublicKey({key:e});return t.alg="ES256K",t}case"P-256":{let t=yield bs.computePublicKey({key:e});return t.alg="ES256",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(r){return Ml(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let t=yield es.generateKey();return t.alg="ES256K",t}case"ES256":case"secp256r1":{let t=yield bs.generateKey();return t.alg="ES256",t}}})}getPublicKey(r){return Ml(this,arguments,void 0,function*({key:e}){if(!hh(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let t=yield es.getPublicKey({key:e});return t.alg="ES256K",t}case"P-256":{let t=yield bs.getPublicKey({key:e});return t.alg="ES256",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(r){return Ml(this,arguments,void 0,function*({key:e,data:t}){if(!hh(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield es.sign({key:e,data:t});case"P-256":return yield bs.sign({key:e,data:t});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(r){return Ml(this,arguments,void 0,function*({key:e,signature:t,data:n}){if(!qC(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(e.crv){case"secp256k1":return yield es.verify({key:e,signature:t,data:n});case"P-256":return yield bs.verify({key:e,signature:t,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return Ml(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield es.privateKeyToBytes({privateKey:e});case"P-256":return yield bs.privateKeyToBytes({privateKey:e});default:throw new ja(go.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(r){return Ml(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield es.publicKeyToBytes({publicKey:e});case"P-256":return yield bs.publicKeyToBytes({publicKey:e});default:throw new ja(go.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},E2=BigInt(4294967295),gC=BigInt(32);pfe=(r,e)=>BigInt(r>>>0)<<gC|BigInt(e>>>0),hfe=(r,e,t)=>r>>>t,mfe=(r,e,t)=>r<<32-t|e>>>t,yfe=(r,e,t)=>r>>>t|e<<32-t,gfe=(r,e,t)=>r<<32-t|e>>>t,wfe=(r,e,t)=>r<<64-t|e>>>t-32,vfe=(r,e,t)=>r>>>t-32|e<<64-t,bfe=(r,e)=>e,Pfe=(r,e)=>r,xfe=(r,e,t)=>r<<t|e>>>32-t,Efe=(r,e,t)=>e<<t|r>>>32-t,Sfe=(r,e,t)=>e<<t-32|r>>>64-t,kfe=(r,e,t)=>r<<t-32|e>>>64-t;Afe=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Tfe=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Ife=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Dfe=(r,e,t,n,i)=>e+t+n+i+(r/2**32|0)|0,Rfe=(r,e,t,n,i)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(i>>>0),Cfe=(r,e,t,n,i,a)=>e+t+n+i+a+(r/2**32|0)|0,$fe={fromBig:d7,split:ffe,toBig:pfe,shrSH:hfe,shrSL:mfe,rotrSH:yfe,rotrSL:gfe,rotrBH:wfe,rotrBL:vfe,rotr32H:bfe,rotr32L:Pfe,rotlSH:xfe,rotlSL:Efe,rotlBH:Sfe,rotlBL:kfe,add:_fe,add3L:Afe,add3H:Tfe,add4L:Ife,add4H:Dfe,add5H:Cfe,add5L:Rfe},jt=$fe,[Bfe,Ofe]=jt.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),hf=new Uint32Array(80),mf=new Uint32Array(80),jfe=class extends Wz{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:r,Al:e,Bh:t,Bl:n,Ch:i,Cl:a,Dh:s,Dl:o,Eh:c,El:l,Fh:d,Fl:u,Gh:f,Gl:p,Hh:h,Hl:m}=this;return[r,e,t,n,i,a,s,o,c,l,d,u,f,p,h,m]}set(r,e,t,n,i,a,s,o,c,l,d,u,f,p,h,m){this.Ah=r|0,this.Al=e|0,this.Bh=t|0,this.Bl=n|0,this.Ch=i|0,this.Cl=a|0,this.Dh=s|0,this.Dl=o|0,this.Eh=c|0,this.El=l|0,this.Fh=d|0,this.Fl=u|0,this.Gh=f|0,this.Gl=p|0,this.Hh=h|0,this.Hl=m|0}process(r,e){for(let w=0;w<16;w++,e+=4)hf[w]=r.getUint32(e),mf[w]=r.getUint32(e+=4);for(let w=16;w<80;w++){let E=hf[w-15]|0,_=mf[w-15]|0,A=jt.rotrSH(E,_,1)^jt.rotrSH(E,_,8)^jt.shrSH(E,_,7),D=jt.rotrSL(E,_,1)^jt.rotrSL(E,_,8)^jt.shrSL(E,_,7),M=hf[w-2]|0,C=mf[w-2]|0,z=jt.rotrSH(M,C,19)^jt.rotrBH(M,C,61)^jt.shrSH(M,C,6),L=jt.rotrSL(M,C,19)^jt.rotrBL(M,C,61)^jt.shrSL(M,C,6),B=jt.add4L(D,L,mf[w-7],mf[w-16]),W=jt.add4H(B,A,z,hf[w-7],hf[w-16]);hf[w]=W|0,mf[w]=B|0}let{Ah:t,Al:n,Bh:i,Bl:a,Ch:s,Cl:o,Dh:c,Dl:l,Eh:d,El:u,Fh:f,Fl:p,Gh:h,Gl:m,Hh:y,Hl:v}=this;for(let w=0;w<80;w++){let E=jt.rotrSH(d,u,14)^jt.rotrSH(d,u,18)^jt.rotrBH(d,u,41),_=jt.rotrSL(d,u,14)^jt.rotrSL(d,u,18)^jt.rotrBL(d,u,41),A=d&f^~d&h,D=u&p^~u&m,M=jt.add5L(v,_,D,Ofe[w],mf[w]),C=jt.add5H(M,y,E,A,Bfe[w],hf[w]),z=M|0,L=jt.rotrSH(t,n,28)^jt.rotrBH(t,n,34)^jt.rotrBH(t,n,39),B=jt.rotrSL(t,n,28)^jt.rotrBL(t,n,34)^jt.rotrBL(t,n,39),W=t&i^t&s^i&s,ee=n&a^n&o^a&o;y=h|0,v=m|0,h=f|0,m=p|0,f=d|0,p=u|0,{h:d,l:u}=jt.add(c|0,l|0,C|0,z|0),c=s|0,l=o|0,s=i|0,o=a|0,i=t|0,a=n|0;let R=jt.add3L(z,B,ee);t=jt.add3H(R,C,L,W),n=R|0}({h:t,l:n}=jt.add(this.Ah|0,this.Al|0,t|0,n|0)),{h:i,l:a}=jt.add(this.Bh|0,this.Bl|0,i|0,a|0),{h:s,l:o}=jt.add(this.Ch|0,this.Cl|0,s|0,o|0),{h:c,l}=jt.add(this.Dh|0,this.Dl|0,c|0,l|0),{h:d,l:u}=jt.add(this.Eh|0,this.El|0,d|0,u|0),{h:f,l:p}=jt.add(this.Fh|0,this.Fl|0,f|0,p|0),{h,l:m}=jt.add(this.Gh|0,this.Gl|0,h|0,m|0),{h:y,l:v}=jt.add(this.Hh|0,this.Hl|0,y|0,v|0),this.set(t,n,i,a,s,o,c,l,d,u,f,p,h,m,y,v)}roundClean(){hf.fill(0),mf.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},l7=Vz(()=>new jfe),Ac=BigInt(0),Go=BigInt(1),S2=BigInt(2),Mfe=BigInt(8),Kfe={zip215:!0};D0=BigInt(0),sC=BigInt(1);tb=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),vq=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),eLe=BigInt(0),qfe=BigInt(1),wC=BigInt(2),zfe=BigInt(5),bq=BigInt(10),Ffe=BigInt(20),Gfe=BigInt(40),Pq=BigInt(80);Ma=NC(tb,void 0,!0),rb={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ma,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:l7,randomBytes:UC,adjustScalarBytes:f7,uvRatio:Hfe},oh=FC(rb);tLe=FC({...rb,domain:p7}),rLe=FC({...rb,domain:p7,prehash:l7}),j0=Lfe({P:tb,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let e=tb,{pow_p_5_8:t,b2:n}=u7(r);return Zr(En(t,BigInt(3),e)*n,e)},adjustScalarBytes:f7,randomBytes:UC});Jfe=(Ma.ORDER+BigInt(3))/BigInt(8),nLe=Ma.pow(wC,Jfe),iLe=Ma.sqrt(Ma.neg(Ma.ONE)),sLe=(Ma.ORDER-BigInt(5))/BigInt(8),oLe=BigInt(486662),aLe=$ue(Ma,Ma.neg(BigInt(486664))),cLe=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),dLe=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),lLe=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),uLe=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),fLe=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ia=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},Zfe=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},ts=class bf{static bytesToPrivateKey(e){return Ia(this,arguments,void 0,function*({privateKeyBytes:t}){let n=oh.getPublicKey(t),i={crv:"Ed25519",d:rt.uint8Array(t).toBase64Url(),kty:"OKP",x:rt.uint8Array(n).toBase64Url()};return i.kid=yield xr({jwk:i}),i})}static bytesToPublicKey(e){return Ia(this,arguments,void 0,function*({publicKeyBytes:t}){let n={kty:"OKP",crv:"Ed25519",x:rt.uint8Array(t).toBase64Url()};return n.kid=yield xr({jwk:n}),n})}static computePublicKey(e){return Ia(this,arguments,void 0,function*({key:t}){let n=yield bf.privateKeyToBytes({privateKey:t}),i=oh.getPublicKey(n),a={kty:"OKP",crv:"Ed25519",x:rt.uint8Array(i).toBase64Url()};return a.kid=yield xr({jwk:a}),a})}static convertPrivateKeyToX25519(e){return Ia(this,arguments,void 0,function*({privateKey:t}){let n=yield bf.privateKeyToBytes({privateKey:t}),i=Wfe(n),a=j0.getPublicKey(i),s={kty:"OKP",crv:"X25519",d:rt.uint8Array(i).toBase64Url(),x:rt.uint8Array(a).toBase64Url()};return s.kid=yield xr({jwk:s}),s})}static convertPublicKeyToX25519(e){return Ia(this,arguments,void 0,function*({publicKey:t}){let n=yield bf.publicKeyToBytes({publicKey:t});if(!(yield bf.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let i=Vfe(n),a={kty:"OKP",crv:"X25519",x:rt.uint8Array(i).toBase64Url()};return a.kid=yield xr({jwk:a}),a})}static generateKey(){return Ia(this,void 0,void 0,function*(){let e=oh.utils.randomPrivateKey(),t=yield bf.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield xr({jwk:t}),t})}static getPublicKey(e){return Ia(this,arguments,void 0,function*({key:t}){var n;if(!(Gl(t)&&t.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=t,a=Zfe(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield xr({jwk:a})),a})}static privateKeyToBytes(e){return Ia(this,arguments,void 0,function*({privateKey:t}){if(!Gl(t))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return rt.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return Ia(this,arguments,void 0,function*({publicKey:t}){if(!zC(t))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return rt.base64Url(t.x).toUint8Array()})}static sign(e){return Ia(this,arguments,void 0,function*({key:t,data:n}){let i=yield bf.privateKeyToBytes({privateKey:t});return oh.sign(n,i)})}static validatePublicKey(e){return Ia(this,arguments,void 0,function*({publicKeyBytes:t}){try{oh.ExtendedPoint.fromHex(t).assertValidity()}catch{return!1}return!0})}static verify(e){return Ia(this,arguments,void 0,function*({key:t,signature:n,data:i}){let a=yield bf.publicKeyToBytes({publicKey:t});return oh.verify(n,i,a)})}},Kl=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},Yfe=class extends uE{bytesToPrivateKey(r){return Kl(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"Ed25519":{let n=yield ts.bytesToPrivateKey({privateKeyBytes:t});return n.alg="EdDSA",n}default:throw new ja(go.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(r){return Kl(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:t}){switch(e){case"Ed25519":{let n=yield ts.bytesToPublicKey({publicKeyBytes:t});return n.alg="EdDSA",n}default:throw new ja(go.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return Kl(this,arguments,void 0,function*({key:e}){if(!Gl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let t=yield ts.computePublicKey({key:e});return t.alg="EdDSA",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(r){return Kl(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let t=yield ts.generateKey();return t.alg="EdDSA",t}}})}getPublicKey(r){return Kl(this,arguments,void 0,function*({key:e}){if(!Gl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let t=yield ts.getPublicKey({key:e});return t.alg="EdDSA",t}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(r){return Kl(this,arguments,void 0,function*({key:e,data:t}){if(!Gl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield ts.sign({key:e,data:t});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(r){return Kl(this,arguments,void 0,function*({key:e,signature:t,data:n}){if(!zC(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield ts.verify({key:e,signature:t,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return Kl(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"Ed25519":return yield ts.privateKeyToBytes({privateKey:e});default:throw new ja(go.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(r){return Kl(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield ts.publicKeyToBytes({publicKey:e});default:throw new ja(go.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},Xfe=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},Qfe=class extends uE{digest(r){return Xfe(this,arguments,void 0,function*({algorithm:e,data:t}){switch(e){case"SHA-256":return yield a7.digest({data:t})}})}},yf=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},epe=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},Ly=class M0{static bytesToPrivateKey(e){return yf(this,arguments,void 0,function*({privateKeyBytes:t}){let n=j0.getPublicKey(t),i={kty:"OKP",crv:"X25519",d:rt.uint8Array(t).toBase64Url(),x:rt.uint8Array(n).toBase64Url()};return i.kid=yield xr({jwk:i}),i})}static bytesToPublicKey(e){return yf(this,arguments,void 0,function*({publicKeyBytes:t}){let n={kty:"OKP",crv:"X25519",x:rt.uint8Array(t).toBase64Url()};return n.kid=yield xr({jwk:n}),n})}static computePublicKey(e){return yf(this,arguments,void 0,function*({key:t}){let n=yield M0.privateKeyToBytes({privateKey:t}),i=j0.getPublicKey(n),a={kty:"OKP",crv:"X25519",x:rt.uint8Array(i).toBase64Url()};return a.kid=yield xr({jwk:a}),a})}static generateKey(){return yf(this,void 0,void 0,function*(){let e=j0.utils.randomPrivateKey(),t=yield M0.bytesToPrivateKey({privateKeyBytes:e});return t.kid=yield xr({jwk:t}),t})}static getPublicKey(e){return yf(this,arguments,void 0,function*({key:t}){var n;if(!(Gl(t)&&t.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=t,a=epe(t,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield xr({jwk:a})),a})}static privateKeyToBytes(e){return yf(this,arguments,void 0,function*({privateKey:t}){if(!Gl(t))throw new Error("X25519: The provided key is not a valid OKP private key.");return rt.base64Url(t.d).toUint8Array()})}static publicKeyToBytes(e){return yf(this,arguments,void 0,function*({publicKey:t}){if(!zC(t))throw new Error("X25519: The provided key is not a valid OKP public key.");return rt.base64Url(t.x).toUint8Array()})}static sharedSecret(e){return yf(this,arguments,void 0,function*({privateKeyA:t,publicKeyB:n}){if("x"in t&&"x"in n&&t.x===n.x)throw new Error("X25519: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield M0.privateKeyToBytes({privateKey:t}),a=yield M0.publicKeyToBytes({publicKey:n});return j0.getSharedSecret(i,a)})}},R0=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},tpe=class extends uE{bytesToPrivateKey(r){return R0(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:t}){switch(e){case"X25519":return Ly.bytesToPrivateKey({privateKeyBytes:t});default:throw new ja(go.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(r){return R0(this,arguments,void 0,function*({key:e}){if(!Gl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Ly.computePublicKey({key:e});default:throw new ja(go.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(r){return R0(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return Ly.generateKey();default:throw new ja(go.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(r){return R0(this,arguments,void 0,function*({key:e}){if(!Gl(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Ly.getPublicKey({key:e});default:throw new ja(go.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(r){return R0(this,arguments,void 0,function*({privateKey:e}){return Ly.privateKeyToBytes({privateKey:e})})}},Ul=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},oC={Ed25519:{implementation:Yfe,names:["Ed25519"]},secp256k1:{implementation:wq,names:["ES256K","secp256k1"]},secp256r1:{implementation:wq,names:["ES256","secp256r1"]},"SHA-256":{implementation:Qfe,names:["SHA-256"]},X25519:{implementation:tpe,names:["X25519"]}},Dc=class{constructor(r){var e;this._algorithmInstances=new Map,this._keyStore=(e=r?.keyStore)!==null&&e!==void 0?e:new Zle}digest(r){return Ul(this,arguments,void 0,function*({algorithm:e,data:t}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:t})})}exportKey(r){return Ul(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(r){return Ul(this,arguments,void 0,function*({algorithm:e}){let t=yield this.getAlgorithm({algorithm:e}).generateKey({algorithm:e});if(t?.kid===void 0)throw new Error("Generated key is missing a required property: kid");let n=`${gq}${t.kid}`;return yield this._keyStore.set(n,t),n})}getKeyUri(r){return Ul(this,arguments,void 0,function*({key:e}){let t=yield xr({jwk:e});return`${gq}${t}`})}getPublicKey(r){return Ul(this,arguments,void 0,function*({keyUri:e}){let t=yield this.getPrivateKey({keyUri:e}),n=this.getAlgorithmName({key:t});return yield this.getAlgorithm({algorithm:n}).getPublicKey({key:t})})}importKey(r){return Ul(this,arguments,void 0,function*({key:e}){var t;if(!ofe(e))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let n=structuredClone(e);(t=n.kid)!==null&&t!==void 0||(n.kid=yield xr({jwk:n}));let i=yield this.getKeyUri({key:n});return yield this._keyStore.set(i,n),i})}sign(r){return Ul(this,arguments,void 0,function*({keyUri:e,data:t}){let n=yield this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:i}).sign({data:t,key:n})})}verify(r){return Ul(this,arguments,void 0,function*({key:e,signature:t,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:t,data:n})})}getAlgorithm({algorithm:r}){var e;let t=(e=oC[r])===null||e===void 0?void 0:e.implementation;if(!t)throw new Error(`Algorithm not supported: ${r}`);return this._algorithmInstances.has(t)||this._algorithmInstances.set(t,new t),this._algorithmInstances.get(t)}getAlgorithmName({key:r}){let e=r.alg,t=r.crv;for(let n in oC){let i=oC[n];if(e&&i.names.includes(e)||t&&i.names.includes(t))return n}throw new Error(`Unable to determine algorithm based on provided input: alg=${e}, crv=${t}`)}getPrivateKey(r){return Ul(this,arguments,void 0,function*({keyUri:e}){let t=yield this._keyStore.get(e);if(!t)throw new Error(`Key not found: ${e}`);return t})}},rpe=class h7{static getJoseSignatureAlgorithmFromPublicKey(e){let t={Ed25519:"EdDSA","P-256":"ES256","P-384":"ES384","P-521":"ES512",secp256k1:"ES256K"};if(e.alg&&Object.values(t).includes(e.alg))return e.alg;if(e.crv&&Object.keys(t).includes(e.crv))return t[e.crv];throw new Error(`Unable to determine algorithm based on provided input: alg=${e.alg}, crv=${e.crv}. Supported 'alg' values: ${Object.values(t).join(", ")}. Supported 'crv' values: ${Object.keys(t).join(", ")}.`)}static randomBytes(e){return Zue(e)}static randomUuid(){return C2.randomUUID()}static randomPin({length:e}){if(3>e||e>10)throw new Error("randomPin() can securely generate a PIN between 3 to 10 digits.");let t=Math.pow(10,e),n=Math.ceil(Math.log2(t)/8),i=Math.pow(2,n*8),a=i-i%t,s;do{s=0;let o=h7.randomBytes(n);for(let c of o)s=s*256+c}while(s>=a);return(s%t).toString().padStart(e,"0")}},npe=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];xe=class{constructor(r,e,t){this.major=r,this.majorEncoded=r<<5,this.name=e,this.terminal=t}toString(){return`Type[${this.major}].${this.name}`}compare(r){return this.major<r.major?-1:this.major>r.major?1:0}static equals(r,e){return r===e||r.major===e.major&&r.name===e.name}};xe.uint=new xe(0,"uint",!0);xe.negint=new xe(1,"negint",!0);xe.bytes=new xe(2,"bytes",!0);xe.string=new xe(3,"string",!0);xe.array=new xe(4,"array",!1);xe.map=new xe(5,"map",!1);xe.tag=new xe(6,"tag",!1);xe.float=new xe(7,"float",!0);xe.false=new xe(7,"false",!0);xe.true=new xe(7,"true",!0);xe.null=new xe(7,"null",!0);xe.undefined=new xe(7,"undefined",!0);xe.break=new xe(7,"break",!0);Qe=class{constructor(r,e,t){this.type=r,this.value=e,this.encodedLength=t,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}},cb=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ope=new TextEncoder;ape=24,cpe=200,dpe=cb?r=>r.length>=ape?globalThis.Buffer.from(r):xq(r):r=>r.length>=cpe?ope.encode(r):xq(r),Nl=r=>Uint8Array.from(r),lpe=cb?(r,e,t)=>eE(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),upe=cb?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),m7(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},fpe=cb?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);ppe=256,g7=class{constructor(r=ppe){this.chunkSize=r,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(r){let e=this.chunks[this.chunks.length-1];if(this.cursor+r.length<=this.maxCursor+1){let t=e.length-(this.maxCursor-this.cursor)-1;e.set(r,t)}else{if(e){let t=e.length-(this.maxCursor-this.cursor)-1;t<e.length&&(this.chunks[this.chunks.length-1]=e.subarray(0,t),this.maxCursor=this.cursor-1)}r.length<64&&r.length<this.chunkSize?(e=fpe(this.chunkSize),this.chunks.push(e),this.maxCursor+=e.length,this._initReuseChunk===null&&(this._initReuseChunk=e),e.set(r,0)):(this.chunks.push(r),this.maxCursor+=r.length)}this.cursor+=r.length}toBytes(r=!1){let e;if(this.chunks.length===1){let t=this.chunks[0];r&&this.cursor>t.length/2?(e=this.cursor===t.length?t:t.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):e=lpe(t,0,this.cursor)}else e=upe(this.chunks,this.cursor);return r&&this.reset(),e}},hpe=class{constructor(r){this.dest=r,this.cursor=0,this.chunks=[r]}reset(){this.cursor=0}push(r){if(this.cursor+r.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(r,this.cursor),this.cursor+=r.length}toBytes(r=!1){let e=this.dest.subarray(0,this.cursor);return r&&this.reset(),e}},Sn="CBOR decode error:",w7="CBOR encode error:",db=[];db[23]=1;db[24]=2;db[25]=3;db[26]=5;db[27]=9;rs=[24,256,65536,4294967296,BigInt("18446744073709551616")];kh.encodedSize=function(r){return Ua.encodedSize(r.value)};Ua.encodedSize=function(r){return r<rs[0]?1:r<rs[1]?2:r<rs[2]?3:r<rs[3]?5:9};kh.compareTokens=function(r,e){return r.value<e.value?-1:r.value>e.value?1:0};GC=BigInt(-1),v7=BigInt(1);HC.encodedSize=function(r){let e=r.value,t=typeof e=="bigint"?e*GC-v7:e*-1-1;return t<rs[0]?1:t<rs[1]?2:t<rs[2]?3:t<rs[3]?5:9};HC.compareTokens=function(r,e){return r.value<e.value?1:r.value>e.value?-1:0};pE.encodedSize=function(r){let e=tE(r);return Ua.encodedSize(e.length)+e.length};pE.compareTokens=function(r,e){return Tpe(tE(r),tE(e))};Eq=new TextDecoder,Ipe=32;jpe=pE;VC.compareTokens=kh.compareTokens;VC.encodedSize=function(r){return Ua.encodedSize(r.value)};WC.compareTokens=kh.compareTokens;WC.encodedSize=function(r){return Ua.encodedSize(r.value)};JC.compareTokens=kh.compareTokens;JC.encodedSize=function(r){return Ua.encodedSize(r.value)};b7=20,P7=21,x7=22,E7=23;YC.encodedSize=function(r,e){let t=r.value;if(t===!1||t===!0||t===null||t===void 0)return 1;if(!e||e.float64!==!0){k7(t);let n=XC(Tc,1);if(t===n||Number.isNaN(t))return 3;if(_7(t),n=QC(Tc,1),t===n)return 5}return 9};S7=new ArrayBuffer(9),Ra=new DataView(S7,1),Tc=new Uint8Array(S7,0);YC.compareTokens=kh.compareTokens;Oe=[];for(let r=0;r<=23;r++)Oe[r]=fr;Oe[24]=mpe;Oe[25]=ype;Oe[26]=gpe;Oe[27]=wpe;Oe[28]=fr;Oe[29]=fr;Oe[30]=fr;Oe[31]=fr;for(let r=32;r<=55;r++)Oe[r]=fr;Oe[56]=vpe;Oe[57]=bpe;Oe[58]=Ppe;Oe[59]=xpe;Oe[60]=fr;Oe[61]=fr;Oe[62]=fr;Oe[63]=fr;for(let r=64;r<=87;r++)Oe[r]=Epe;Oe[88]=Spe;Oe[89]=kpe;Oe[90]=_pe;Oe[91]=Ape;Oe[92]=fr;Oe[93]=fr;Oe[94]=fr;Oe[95]=hE("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)Oe[r]=Rpe;Oe[120]=Cpe;Oe[121]=$pe;Oe[122]=Bpe;Oe[123]=Ope;Oe[124]=fr;Oe[125]=fr;Oe[126]=fr;Oe[127]=hE("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)Oe[r]=Mpe;Oe[152]=Kpe;Oe[153]=Upe;Oe[154]=Npe;Oe[155]=Lpe;Oe[156]=fr;Oe[157]=fr;Oe[158]=fr;Oe[159]=qpe;for(let r=160;r<=183;r++)Oe[r]=zpe;Oe[184]=Fpe;Oe[185]=Gpe;Oe[186]=Hpe;Oe[187]=Vpe;Oe[188]=fr;Oe[189]=fr;Oe[190]=fr;Oe[191]=Wpe;for(let r=192;r<=215;r++)Oe[r]=Jpe;Oe[216]=Zpe;Oe[217]=Ype;Oe[218]=Xpe;Oe[219]=Qpe;Oe[220]=fr;Oe[221]=fr;Oe[222]=fr;Oe[223]=fr;for(let r=224;r<=243;r++)Oe[r]=hE("simple values are not supported");Oe[244]=fr;Oe[245]=fr;Oe[246]=fr;Oe[247]=ehe;Oe[248]=hE("simple values are not supported");Oe[249]=rhe;Oe[250]=nhe;Oe[251]=ihe;Oe[252]=fr;Oe[253]=fr;Oe[254]=fr;Oe[255]=the;Vl=[];for(let r=0;r<24;r++)Vl[r]=new Qe(xe.uint,r,1);for(let r=-1;r>=-24;r--)Vl[31-r]=new Qe(xe.negint,r,1);Vl[64]=new Qe(xe.bytes,new Uint8Array(0),1);Vl[96]=new Qe(xe.string,"",1);Vl[128]=new Qe(xe.array,0,1);Vl[160]=new Qe(xe.map,0,1);Vl[244]=new Qe(xe.false,!1,1);Vl[245]=new Qe(xe.true,!0,1);Vl[246]=new Qe(xe.null,null,1);ahe=Object.freeze({float64:!0,mapSorter:fhe,quickEncodeToken:ohe});dhe=che(),lhe=new g7,Sq=class T7{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(`${w7} object contains circular references`);return new T7(t,e)}},gf={null:new Qe(xe.null,null),undefined:new Qe(xe.undefined,void 0),true:new Qe(xe.true,!0),false:new Qe(xe.false,!1),emptyArray:new Qe(xe.array,0),emptyMap:new Qe(xe.map,0)},_f={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new Qe(xe.float,r):r>=0?new Qe(xe.uint,r):new Qe(xe.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new Qe(xe.uint,r):new Qe(xe.negint,r)},Uint8Array(r,e,t,n){return new Qe(xe.bytes,r)},string(r,e,t,n){return new Qe(xe.string,r)},boolean(r,e,t,n){return r?gf.true:gf.false},null(r,e,t,n){return gf.null},undefined(r,e,t,n){return gf.undefined},ArrayBuffer(r,e,t,n){return new Qe(xe.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new Qe(xe.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[gf.emptyArray,new Qe(xe.break)]:gf.emptyArray;n=Sq.createCheck(n,r);let i=[],a=0;for(let s of r)i[a++]=$2(s,t,n);return t.addBreakTokens?[new Qe(xe.array,r.length),i,new Qe(xe.break)]:[new Qe(xe.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",a=i?r.keys():Object.keys(r),s=i?r.size:a.length,o;if(s){o=new Array(s),n=Sq.createCheck(n,r);let c=!i&&t.ignoreUndefinedProperties,l=0;for(let d of a){let u=i?r.get(d):r[d];c&&u===void 0||(o[l++]=[$2(d,t,n),$2(u,t,n)])}l<s&&(o.length=l)}return o?.length?(uhe(o,t),t.addBreakTokens?[new Qe(xe.map,o.length),o,new Qe(xe.break)]:[new Qe(xe.map,o.length),o]):t.addBreakTokens===!0?[gf.emptyMap,new Qe(xe.break)]:gf.emptyMap}};_f.Map=_f.Object;_f.Buffer=_f.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))_f[`${r}Array`]=_f.DataView;pLe=xe.uint.majorEncoded,hLe=xe.negint.majorEncoded,mLe=xe.bytes.majorEncoded,yLe=xe.string.majorEncoded,gLe=xe.array.majorEncoded,wLe=xe.float.majorEncoded|b7,vLe=xe.float.majorEncoded|P7,bLe=xe.float.majorEncoded|x7,PLe=xe.float.majorEncoded|E7,xLe=BigInt(-1),ELe=BigInt(1);SLe=Symbol.for("DONE"),kLe=Symbol.for("BREAK");(function(r){r[r.OKP=1]="OKP",r[r.EC2=2]="EC2",r[r.Symmetric=4]="Symmetric"})(_q||(_q={}));(function(r){r[r.P256=1]="P256",r[r.P384=2]="P384",r[r.P521=3]="P521",r[r.X25519=4]="X25519",r[r.X448=5]="X448",r[r.Ed25519=6]="Ed25519",r[r.Ed448=7]="Ed448",r[r.Secp256k1=8]="Secp256k1"})(Ps||(Ps={}));(function(r){r[r.EdDSA=-8]="EdDSA",r[r.ES256=-7]="ES256",r[r.ES384=-35]="ES384",r[r.ES512=-36]="ES512",r[r.ES256K=-47]="ES256K"})(Oa||(Oa={}));(function(r){r[r.Kty=1]="Kty",r[r.Kid=2]="Kid",r[r.Alg=3]="Alg",r[r.KeyOps=4]="KeyOps",r[r.BaseIv=5]="BaseIv"})(Aq||(Aq={}));(function(r){r[r.Crv=-1]="Crv",r[r.X=-2]="X",r[r.Y=-3]="Y",r[r.D=-4]="D"})(Tq||(Tq={}));_Le={"P-256":Ps.P256,"P-384":Ps.P384,"P-521":Ps.P521,X25519:Ps.X25519,Ed25519:Ps.Ed25519,Ed448:Ps.Ed448,secp256k1:Ps.Secp256k1},ALe={[Ps.P256]:"P-256",[Ps.P384]:"P-384",[Ps.P521]:"P-521",[Ps.X25519]:"X25519",[Ps.Ed25519]:"Ed25519",[Ps.Ed448]:"Ed448",[Ps.Secp256k1]:"secp256k1"},TLe={EdDSA:Oa.EdDSA,ES256:Oa.ES256,ES384:Oa.ES384,ES512:Oa.ES512,ES256K:Oa.ES256K},ILe={[Oa.EdDSA]:"EdDSA",[Oa.ES256]:"ES256",[Oa.ES384]:"ES384",[Oa.ES512]:"ES512",[Oa.ES256K]:"ES256K"};(function(r){r[r.Alg=1]="Alg",r[r.Crit=2]="Crit",r[r.ContentType=3]="ContentType",r[r.Kid=4]="Kid"})(Iq||(Iq={}));(function(r){r[r.Iss=1]="Iss",r[r.Sub=2]="Sub",r[r.Aud=3]="Aud",r[r.Exp=4]="Exp",r[r.Nbf=5]="Nbf",r[r.Iat=6]="Iat",r[r.Cti=7]="Cti",r[r.Nonce=10]="Nonce",r[r.Ueid=256]="Ueid",r[r.Sueids=257]="Sueids",r[r.Oemid=258]="Oemid",r[r.Hwmodel=259]="Hwmodel",r[r.Hwversion=260]="Hwversion",r[r.Secboot=262]="Secboot",r[r.Dbgstat=263]="Dbgstat",r[r.Location=264]="Location",r[r.Profile=265]="Profile",r[r.Submods=266]="Submods",r[r.Measres=272]="Measres",r[r.Intuse=268]="Intuse"})(Dq||(Dq={}));(function(r){r[r.Enabled=0]="Enabled",r[r.Disabled=1]="Disabled",r[r.DisabledSinceBoot=2]="DisabledSinceBoot",r[r.DisabledPermanently=3]="DisabledPermanently",r[r.DisabledFullyAndPermanently=4]="DisabledFullyAndPermanently"})(Rq||(Rq={}));(function(r){r[r.Unrestricted=1]="Unrestricted",r[r.Restricted=2]="Restricted",r[r.SecureRestricted=3]="SecureRestricted",r[r.Hardware=4]="Hardware"})(Cq||(Cq={}));e6={};RC(e6,{extractDidFragment:()=>Ws,getServices:()=>hhe,getVerificationMethodByKey:()=>mhe,getVerificationMethodTypes:()=>D7,getVerificationMethods:()=>mE,getVerificationRelationshipsById:()=>R7,isDidService:()=>C7,isDidVerificationMethod:()=>rE,isDwnDidService:()=>yhe,isPortableDid:()=>_h,keyBytesToMultibaseId:()=>$7,multibaseIdToKeyBytes:()=>B7});xs=class O7{constructor({uri:e,document:t,metadata:n,keyManager:i}){this.uri=e,this.document=t,this.metadata=n,this.keyManager=i}async export(){if(!(Array.isArray(this.document.verificationMethod)&&this.document.verificationMethod.length>0))throw new Error(`DID document for '${this.uri}' is missing verification methods`);let e=JSON.parse(JSON.stringify({uri:this.uri,document:this.document,metadata:this.metadata}));if("exportKey"in this.keyManager&&typeof this.keyManager.exportKey=="function"){let t=[];for(let n of this.document.verificationMethod){if(!n.publicKeyJwk)throw new Error(`Verification method '${n.id}' does not contain a public key in JWK format`);let i=await this.keyManager.getKeyUri({key:n.publicKeyJwk}),a=await this.keyManager.exportKey({keyUri:i});t.push({...a})}e.privateKeys=t}return e}async getSigner(e){let t=this.document.verificationMethod?.find(s=>Ws(s.id)===(Ws(e?.methodId)??Ws(this.document.assertionMethod?.[0])));if(!t?.publicKeyJwk)throw new Xe("internalError","A verification method intended for signing could not be determined from the DID Document");let n=await this.keyManager.getKeyUri({key:t.publicKeyJwk}),i=await this.keyManager.getPublicKey({keyUri:n}),a=this.keyManager;return{algorithm:rpe.getJoseSignatureAlgorithmFromPublicKey(i),keyId:t.id,async sign({data:s}){return await a.sign({data:s,keyUri:n})},async verify({data:s,signature:o}){return await a.verify({data:s,key:i,signature:o})}}}static async import({portableDid:e,keyManager:t=new Dc}){let n=mE({didDocument:e.document});if(n.length===0)throw new Xe("invalidDidDocument","At least one verification method is required but 0 were given");for(let i of e.privateKeys??[]){let a=await t.getKeyUri({key:i});await t.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1)||await t.importKey({key:i})}for(let i of n){if(!i.publicKeyJwk)throw new Error(`Verification method '${i.id}' does not contain a public key in JWK format`);let a=await t.getKeyUri({key:i.publicKeyJwk});await t.getPublicKey({keyUri:a})}return new O7({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:t})}},fb=class{static async getSigningMethod(r){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")}static async resolve(r,e){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")}},j7=(r=>(r[r.Discoverable=0]="Discoverable",r[r.Organization=1]="Organization",r[r.Government=2]="Government",r[r.Corporation=3]="Corporation",r[r.LocalBusiness=4]="LocalBusiness",r[r.SoftwarePackage=5]="SoftwarePackage",r[r.WebApp=6]="WebApp",r[r.FinancialInstitution=7]="FinancialInstitution",r))(j7||{}),t6=(r=>(r[r.Ed25519=0]="Ed25519",r[r.secp256k1=1]="secp256k1",r[r.secp256r1=2]="secp256r1",r[r.X25519=3]="X25519",r))(t6||{}),M7=(r=>(r.authentication="auth",r.assertionMethod="asm",r.capabilityDelegation="del",r.capabilityInvocation="inv",r.keyAgreement="agm",r))(M7||{}),$q="0123456789abcdef",K7=[],Bq=[];for(let r=0;r<256;r++)K7[r]=$q[r>>4&15]+$q[r&15],r<16&&(r<10?Bq[48+r]=r:Bq[87+r]=r);ghe=r=>{let e=r.length,t="",n=0;for(;n<e;)t+=K7[r[n++]];return t},whe=(r,e=0)=>{let t=r.length||0;if(!e){let s=t;for(;s--;)e+=r[s].length}let n=new Uint8Array(e),i=e,a=t;for(;a--;)i-=r[a].length,n.set(r[a],i);return n},Oq="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",vhe=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(C0=0;C0<Oq.length;C0++)vhe[Oq.charCodeAt(C0)]=C0;bhe=new TextDecoder,U7=(r,e)=>e?new TextDecoder(e).decode(r):bhe.decode(r),Phe=new TextEncoder,Hl=r=>Phe.encode(r),jq=typeof window<"u"?window:self,Mq=jq.crypto||jq.msCrypto||{},DLe=Mq.subtle||Mq.webkitSubtle;gr.bytes=-1;gr._floatConversionDetected=!1;gr._encode=function(r,e){if(e!=null)switch(N7(e)){case"object":gr.dict(r,e);break;case"map":gr.dictMap(r,e);break;case"array":gr.list(r,e);break;case"set":gr.listSet(r,e);break;case"string":gr.string(r,e);break;case"number":gr.number(r,e);break;case"boolean":gr.number(r,e);break;case"arraybufferview":gr.buffer(r,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":gr.buffer(r,new Uint8Array(e));break}};yE=new Uint8Array([101]),L7=new Uint8Array([100]),q7=new Uint8Array([108]);gr.buffer=function(r,e){r.push(Hl(e.length+":"),e)};gr.string=function(r,e){r.push(Hl(Hl(e).byteLength+":"+e))};gr.number=function(r,e){if(Number.isInteger(e))return r.push(Hl("i"+BigInt(e)+"e"));let t=2147483648,n=e/t<<0,i=e%t<<0,a=n*t+i;r.push(Hl("i"+a+"e")),a!==e&&!gr._floatConversionDetected&&(gr._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+e+'":','Bencoding only defines support for integers, value was converted to "'+a+'"'),console.trace())};gr.dict=function(r,e){r.push(L7);let t=0,n,i=Object.keys(e).sort(),a=i.length;for(;t<a;t++)n=i[t],e[n]!=null&&(gr.string(r,n),gr._encode(r,e[n]));r.push(yE)};gr.dictMap=function(r,e){r.push(L7);let t=Array.from(e.keys()).sort();for(let n of t)e.get(n)!=null&&(ArrayBuffer.isView(n)?gr._encode(r,n):gr.string(r,String(n)),gr._encode(r,e.get(n)));r.push(yE)};gr.list=function(r,e){let t=0,n=e.length;for(r.push(q7);t<n;t++)e[t]!=null&&gr._encode(r,e[t]);r.push(yE)};gr.listSet=function(r,e){r.push(q7);for(let t of e)t!=null&&gr._encode(r,t);r.push(yE)};xhe=gr,Ehe=105,She=58,khe=100,_he=108,r6=101;gt.bytes=0;gt.position=0;gt.data=null;gt.encoding=null;gt.next=function(){switch(gt.data[gt.position]){case khe:return gt.dictionary();case _he:return gt.list();case Ehe:return gt.integer();default:return gt.buffer()}};gt.find=function(r){let e=gt.position,t=gt.data.length,n=gt.data;for(;e<t;){if(n[e]===r)return e;e++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(r)+'" [0x'+r.toString(16)+"]")};gt.dictionary=function(){gt.position++;let r={};for(;gt.data[gt.position]!==r6;){let e=gt.buffer(),t=U7(e);t.includes("\uFFFD")&&(t=ghe(e)),r[t]=gt.next()}return gt.position++,r};gt.list=function(){gt.position++;let r=[];for(;gt.data[gt.position]!==r6;)r.push(gt.next());return gt.position++,r};gt.integer=function(){let r=gt.find(r6),e=z7(gt.data,gt.position+1,r);return gt.position+=r+1-gt.position,e};gt.buffer=function(){let r=gt.find(She),e=z7(gt.data,gt.position,r),t=++r+e;return gt.position=t,gt.encoding?U7(gt.data.slice(r,t)):gt.data.slice(r,t)};Ahe=gt;F7=gE,$he=F7,G7={encode:xhe,decode:Ahe,byteLength:F7,encodingLength:$he},Bhe=/^(\d{1,3}\.){3,3}\d{1,3}$/,Ohe=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,Bd={name:"v4",size:4,isFormat:r=>Bhe.test(r),encode(r,e,t){t=~~t,e=e||new Uint8Array(t+4);let n=r.length,i=0;for(let a=0;a<n;){let s=r.charCodeAt(a++);s===46?(e[t++]=i,i=0):i=i*10+(s-48)}return e[t]=i,e},decode(r,e){return e=~~e,`${r[e++]}.${r[e++]}.${r[e++]}.${r[e]}`}},kf={name:"v6",size:16,isFormat:r=>r.length>0&&Ohe.test(r),encode(r,e,t){t=~~t;let n=t+16,i=-1,a=0,s=0,o=!0,c=!1;e=e||new Uint8Array(t+16);for(let l=0;l<r.length;l++){let d=r.charCodeAt(l);d===58?(o?i!==-1?(t<n&&(e[t]=0),t<n-1&&(e[t+1]=0),t+=2):t<n&&(i=t):(c===!0?(t<n&&(e[t]=s),t++):(t<n&&(e[t]=a>>8),t<n-1&&(e[t+1]=a&255),t+=2),a=0,s=0),o=!0,c=!1):d===46?(t<n&&(e[t]=s),t++,s=0,a=0,o=!1,c=!0):(o=!1,d>=97?d-=87:d>=65?d-=55:(d-=48,s=s*10+d),a=(a<<4)+d)}if(o===!1)c===!0?(t<n&&(e[t]=s),t++):(t<n&&(e[t]=a>>8),t<n-1&&(e[t+1]=a&255),t+=2);else if(i===0)t<n&&(e[t]=0),t<n-1&&(e[t+1]=0),t+=2;else if(i!==-1){t+=2;for(let l=Math.min(t-1,n-1);l>=i+2;l--)e[l]=e[l-2];e[i]=0,e[i+1]=0,i=t}if(i!==t&&i!==-1)for(t>n-2&&(t=n-2);n>i;)e[--n]=t<n&&t>i?e[--t]:0;else for(;t<n;)e[t++]=0;return e},decode(r,e){e=~~e;let t="";for(let n=0;n<16;n+=2)n!==0&&(t+=":"),t+=(r[e+n]<<8|r[e+n+1]).toString(16);return t.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};ib.bytes=0;hb.bytes=0;wh=r=>r instanceof Uint8Array;K0={},Z7=new Array(255);for(let r=0;r<=15;r+=1){let e=r.toString(16),t=e.toUpperCase();for(let n=0;n<=15;n+=1){let i=n.toString(16),a=i.toUpperCase(),s=r<<4|n,o=`${e}${i}`;Z7[s]=o,K0[o]=s,K0[`${t}${i}`]=s,K0[`${e}${a}`]=s,K0[`${t}${a}`]=s}}Fhe=Math.pow(2,24),Ghe=Math.pow(2,16),Hhe=Math.pow(2,8),zl=(r,e)=>r[e]*Fhe+r[e+1]*Ghe+r[e+2]*Hhe+r[e+3],Mt=(r,e)=>r[e]<<8|r[e+1],Fl=(r,e,t)=>(e=+e,r[t+3]=e,e=e>>>8,r[t+2]=e,e=e>>>8,r[t+1]=e,e=e>>>8,r[t]=e,t+4),nt=(r,e,t)=>(r[t]=e>>8,r[t+1]=e&255,t+2);Whe=0,Nq=32768,vC=32768,Jhe=~vC,Y7=32768,Zhe=~Y7;He=Fr({encode(r,e,t){e||(e=new Uint8Array(He.encodingLength(r))),t||(t=0);let n=t,i=r.replace(/^\.|\.$/gm,"");if(i.length){let a=i.split(".");for(let s=0;s<a.length;s++){let o=i6(e,a[s],t+1);e[t]=o,t+=o+1}}return e[t++]=0,He.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=[],n=e,i=0,a=0,s=!1;for(;;){if(e>=r.length)throw new Error("Cannot decode name (buffer overflow)");let o=r[e++];if(a+=s?0:1,o===0)break;if(o&192)if((o&192)===192){if(e+1>r.length)throw new Error("Cannot decode name (buffer overflow)");let c=Mt(r,e-1)-49152;if(c>=n)throw new Error("Cannot decode name (bad pointer)");e=c,n=c,a+=s?0:1,s=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+o>r.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=o+1,i>254)throw new Error("Cannot decode name (name too long)");t.push(hb(r,e,e+o)),e+=o,a+=s?0:o}}return He.decode.bytes=a,t.length===0?".":t.join(".")},encodingLength(r){return r==="."||r===".."?1:Af(r.replace(/^\.|\.$/gm,""))+2}}),hi=Fr({encode(r,e,t){e||(e=new Uint8Array(hi.encodingLength(r))),t||(t=0);let n=i6(e,r,t+1);return e[t]=n,hi.encode.bytes=n+1,e},decode(r,e){e||(e=0);let t=r[e],n=hb(r,e+1,e+1+t);return hi.decode.bytes=t+1,n},encodingLength(r){return Af(r)+1}}),qy=Fr({bytes:12,encode(r,e,t){e||(e=new Uint8Array(qy.encodingLength(r))),t||(t=0);let n=(r.flags||0)&32767,i=r.type==="response"?Nq:Whe;return nt(e,r.id||0,t),nt(e,n|i,t+2),nt(e,r.questions.length,t+4),nt(e,r.answers.length,t+6),nt(e,r.authorities.length,t+8),nt(e,r.additionals.length,t+10),e},decode(r,e){if(e||(e=0),r.length<12)throw new Error("Header must be 12 bytes");let t=Mt(r,e+2);return{id:Mt(r,e),type:t&Nq?"response":"query",flags:t&32767,flag_qr:(t>>15&1)===1,opcode:Nhe(t>>11&15),flag_aa:(t>>10&1)===1,flag_tc:(t>>9&1)===1,flag_rd:(t>>8&1)===1,flag_ra:(t>>7&1)===1,flag_z:(t>>6&1)===1,flag_ad:(t>>5&1)===1,flag_cd:(t>>4&1)===1,rcode:Uhe(t&15),questions:new Array(Mt(r,e+4)),answers:new Array(Mt(r,e+6)),authorities:new Array(Mt(r,e+8)),additionals:new Array(Mt(r,e+10))}},encodingLength(){return 12}}),B2=Fr({encode(r,e,t){e||(e=new Uint8Array(B2.encodingLength(r))),t||(t=0);let n=r.length;return nt(e,n,t),Zo(r,e,t+2,0,n),B2.encode.bytes=n+2,e},decode(r,e){e||(e=0);let t=Mt(r,e),n=r.slice(e+2,e+2+t);return B2.decode.bytes=t+2,n},encodingLength(r){return r.length+2}}),O2=Fr({encode(r,e,t){return e||(e=new Uint8Array(O2.encodingLength(r))),t||(t=0),He.encode(r,e,t+2),nt(e,He.encode.bytes,t),O2.encode.bytes=He.encode.bytes+2,e},decode(r,e){e||(e=0);let t=Mt(r,e),n=He.decode(r,e+2);return O2.decode.bytes=t+2,n},encodingLength(r){return He.encodingLength(r)+2}}),j2=Fr({encode(r,e,t){e||(e=new Uint8Array(j2.encodingLength(r))),t||(t=0);let n=t;return t+=2,He.encode(r.mname,e,t),t+=He.encode.bytes,He.encode(r.rname,e,t),t+=He.encode.bytes,Fl(e,r.serial||0,t),t+=4,Fl(e,r.refresh||0,t),t+=4,Fl(e,r.retry||0,t),t+=4,Fl(e,r.expire||0,t),t+=4,Fl(e,r.minimum||0,t),t+=4,nt(e,t-n-2,n),j2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.mname=He.decode(r,e),e+=He.decode.bytes,n.rname=He.decode(r,e),e+=He.decode.bytes,n.serial=zl(r,e),e+=4,n.refresh=zl(r,e),e+=4,n.retry=zl(r,e),e+=4,n.expire=zl(r,e),e+=4,n.minimum=zl(r,e),e+=4,j2.decode.bytes=e-t,n},encodingLength(r){return 22+He.encodingLength(r.mname)+He.encodingLength(r.rname)}}),M2=Fr({encode(r,e,t){Array.isArray(r)||(r=[r]);for(let i=0;i<r.length;i++)if(typeof r[i]=="string"&&(r[i]=n6(r[i])),!wh(r[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(M2.encodingLength(r))),t||(t=0);let n=t;return t+=2,r.forEach(function(i){e[t++]=i.length,Zo(i,e,t,0,i.length),t+=i.length}),nt(e,t-n-2,n),M2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=Mt(r,e);e+=2;let i=[];for(;n>0;){let a=r[e++];if(--n,n<a)throw new Error("Buffer overflow");i.push(r.slice(e,e+a)),e+=a,n-=a}return M2.decode.bytes=e-t,i},encodingLength(r){Array.isArray(r)||(r=[r]);let e=2;return r.forEach(function(t){typeof t=="string"?e+=Af(t)+1:e+=t.length+1}),e}}),K2=Fr({encode(r,e,t){e||(e=new Uint8Array(K2.encodingLength(r))),t||(t=0),typeof r=="string"&&(r=n6(r)),r||(r=new Uint8Array(0));let n=t;t+=2;let i=r.length;return Zo(r,e,t,0,i),t+=i,nt(e,t-n-2,n),K2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=Mt(r,e);e+=2;let i=r.slice(e,e+n);return e+=n,K2.decode.bytes=e-t,i},encodingLength(r){return r?(wh(r)?r.length:Af(r))+2:2}}),U2=Fr({encode(r,e,t){e||(e=new Uint8Array(U2.encodingLength(r))),t||(t=0);let n=t;return t+=2,hi.encode(r.cpu,e,t),t+=hi.encode.bytes,hi.encode(r.os,e,t),t+=hi.encode.bytes,nt(e,t-n-2,n),U2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.cpu=hi.decode(r,e),e+=hi.decode.bytes,n.os=hi.decode(r,e),e+=hi.decode.bytes,U2.decode.bytes=e-t,n},encodingLength(r){return hi.encodingLength(r.cpu)+hi.encodingLength(r.os)+2}}),Jy=Fr({encode(r,e,t){return e||(e=new Uint8Array(Jy.encodingLength(r))),t||(t=0),He.encode(r,e,t+2),nt(e,He.encode.bytes,t),Jy.encode.bytes=He.encode.bytes+2,e},decode(r,e){e||(e=0);let t=He.decode(r,e+2);return Jy.decode.bytes=He.decode.bytes+2,t},encodingLength(r){return He.encodingLength(r)+2}}),N2=Fr({encode(r,e,t){e||(e=new Uint8Array(N2.encodingLength(r))),t||(t=0),nt(e,r.priority||0,t+2),nt(e,r.weight||0,t+4),nt(e,r.port||0,t+6),He.encode(r.target,e,t+8);let n=He.encode.bytes+6;return nt(e,n,t),N2.encode.bytes=n+2,e},decode(r,e){e||(e=0);let t=Mt(r,e),n={};return n.priority=Mt(r,e+2),n.weight=Mt(r,e+4),n.port=Mt(r,e+6),n.target=He.decode(r,e+8),N2.decode.bytes=t+2,n},encodingLength(r){return 8+He.encodingLength(r.target)}}),xf=Fr({encode(r,e,t){let n=xf.encodingLength(r);return e||(e=new Uint8Array(xf.encodingLength(r))),t||(t=0),r.issuerCritical&&(r.flags=xf.ISSUER_CRITICAL),nt(e,n-2,t),t+=2,e[t]=r.flags||0,t+=1,hi.encode(r.tag,e,t),t+=hi.encode.bytes,i6(e,r.value,t),t+=Af(r.value),xf.encode.bytes=n,e},decode(r,e){e||(e=0);let t=Mt(r,e);e+=2;let n=e,i={};return i.flags=r[e],e+=1,i.tag=hi.decode(r,e),e+=hi.decode.bytes,i.value=hb(r,e,n+t),i.issuerCritical=!!(i.flags&xf.ISSUER_CRITICAL),xf.decode.bytes=t+2,i},encodingLength(r){return hi.encodingLength(r.tag)+hi.encodingLength(r.value)+2}});xf.ISSUER_CRITICAL=128;L2=Fr({encode(r,e,t){e||(e=new Uint8Array(L2.encodingLength(r))),t||(t=0);let n=t;return t+=2,nt(e,r.preference||0,t),t+=2,He.encode(r.exchange,e,t),t+=He.encode.bytes,nt(e,t-n-2,n),L2.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.preference=Mt(r,e),e+=2,n.exchange=He.decode(r,e),e+=He.decode.bytes,L2.decode.bytes=e-t,n},encodingLength(r){return 4+He.encodingLength(r.exchange)}}),X7=Fr({encode(r,e,t){return e||(e=new Uint8Array(X7.encodingLength(r))),t||(t=0),nt(e,4,t),t+=2,Bd.encode(r,e,t),e},decode(r,e){return e||(e=0),e+=2,Bd.decode(r,e)},bytes:6}),q2=Fr({encode(r,e,t){return e||(e=new Uint8Array(q2.encodingLength(r))),t||(t=0),nt(e,16,t),t+=2,kf.encode(r,e,t),q2.encode.bytes=18,e},decode(r,e){e||(e=0),e+=2;let t=kf.decode(r,e);return q2.decode.bytes=18,t},bytes:18}),Lq=r=>new Uint8Array(r),Ll=Fr({encode(r,e,t){e||(e=new Uint8Array(Ll.encodingLength(r))),t||(t=0);let n=t,i=Kq(r.code);if(nt(e,i,t),t+=2,r.data)nt(e,r.data.length,t),t+=2,Zo(r.data,e,t),t+=r.data.length;else switch(i){case 8:{let a=r.sourcePrefixLength||0,s=r.family||jhe(r.ip,Lq),o=Mhe(r.ip,Lq),c=Math.ceil(a/8);nt(e,c+4,t),t+=2,nt(e,s,t),t+=2,e[t++]=a,e[t++]=r.scopePrefixLength||0,Zo(o,e,t,0,c),t+=c}break;case 11:r.timeout?(nt(e,2,t),t+=2,nt(e,r.timeout,t),t+=2):(nt(e,0,t),t+=2);break;case 12:{let a=r.length||0;nt(e,a,t),t+=2,e.fill(0,t,t+a),t+=a}break;case 14:{let a=r.tags.length*2;nt(e,a,t),t+=2;for(let s of r.tags)nt(e,s,t),t+=2}break;default:throw new Error(`Unknown roption code: ${r.code}`)}return Ll.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t={};t.code=Mt(r,e),t.type=Lhe(t.code),e+=2;let n=Mt(r,e);switch(e+=2,t.data=r.slice(e,e+n),t.code){case 8:t.family=Mt(r,e),e+=2,t.sourcePrefixLength=r[e++],t.scopePrefixLength=r[e++];{let i=new Uint8Array(t.family===1?4:16);Zo(r,i,0,e,e+n-4),t.ip=Khe(i)}break;case 11:n>0&&(t.timeout=Mt(r,e),e+=2);break;case 14:t.tags=[];for(let i=0;i<n;i+=2)t.tags.push(Mt(r,e)),e+=2}return Ll.decode.bytes=n+4,t},encodingLength(r){if(r.data)return r.data.length+4;switch(Kq(r.code)){case 8:{let e=r.sourcePrefixLength||0;return Math.ceil(e/8)+8}case 11:return typeof r.timeout=="number"?6:4;case 12:return r.length+4;case 14:return 4+r.tags.length*2}throw new Error(`Unknown roption code: ${r.code}`)}}),Ef=Fr({encode(r,e,t){e||(e=new Uint8Array(Ef.encodingLength(r))),t||(t=0);let n=t,i=Vy(r,Ll);return nt(e,i,t),t=F0(r,Ll,e,t+2),Ef.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t=e,n=[],i=Mt(r,e);e+=2;let a=0;for(;i>0;)n[a++]=Ll.decode(r,e),e+=Ll.decode.bytes,i-=Ll.decode.bytes;return Ef.decode.bytes=e-t,n},encodingLength(r){return 2+Vy(r||[],Ll)}}),$d=Fr({encode(r,e,t){e||(e=new Uint8Array($d.encodingLength(r))),t||(t=0);let n=t,i=r.key;if(!wh(i))throw new Error("Key must be a Buffer");return t+=2,nt(e,r.flags,t),t+=2,e[t]=$d.PROTOCOL_DNSSEC,t+=1,e[t]=r.algorithm,t+=1,Zo(i,e,t,0,i.length),t+=i.length,$d.encode.bytes=t-n,nt(e,$d.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Mt(r,e);if(e+=2,n.flags=Mt(r,e),e+=2,r[e]!==$d.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=r[e],e+=1,n.key=r.slice(e,t+i+2),e+=n.key.length,$d.decode.bytes=e-t,n},encodingLength(r){return 6+Af(r.key)}});$d.PROTOCOL_DNSSEC=3;$d.ZONE_KEY=128;$d.SECURE_ENTRYPOINT=32768;U0=Fr({encode(r,e,t){e||(e=new Uint8Array(U0.encodingLength(r))),t||(t=0);let n=t,i=r.signature;if(!wh(i))throw new Error("Signature must be a Buffer");return t+=2,nt(e,nb(r.typeCovered),t),t+=2,e[t]=r.algorithm,t+=1,e[t]=r.labels,t+=1,Fl(e,r.originalTTL,t),t+=4,Fl(e,r.expiration,t),t+=4,Fl(e,r.inception,t),t+=4,nt(e,r.keyTag,t),t+=2,He.encode(r.signersName,e,t),t+=He.encode.bytes,Zo(i,e,t,0,i.length),t+=i.length,U0.encode.bytes=t-n,nt(e,U0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Mt(r,e);return e+=2,n.typeCovered=wE(Mt(r,e)),e+=2,n.algorithm=r[e],e+=1,n.labels=r[e],e+=1,n.originalTTL=zl(r,e),e+=4,n.expiration=zl(r,e),e+=4,n.inception=zl(r,e),e+=4,n.keyTag=Mt(r,e),e+=2,n.signersName=He.decode(r,e),e+=He.decode.bytes,n.signature=r.slice(e,t+i+2),e+=n.signature.length,U0.decode.bytes=e-t,n},encodingLength(r){return 20+He.encodingLength(r.signersName)+Af(r.signature)}}),N0=Fr({encode(r,e,t){e||(e=new Uint8Array(N0.encodingLength(r))),t||(t=0);let n=t;return t+=2,He.encode(r.mbox||".",e,t),t+=He.encode.bytes,He.encode(r.txt||".",e,t),t+=He.encode.bytes,N0.encode.bytes=t-n,nt(e,N0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={};return e+=2,n.mbox=He.decode(r,e)||".",e+=He.decode.bytes,n.txt=He.decode(r,e)||".",e+=He.decode.bytes,N0.decode.bytes=e-t,n},encodingLength(r){return 2+He.encodingLength(r.mbox||".")+He.encodingLength(r.txt||".")}}),Jo=Fr({encode(r,e,t){e||(e=new Uint8Array(Jo.encodingLength(r))),t||(t=0);let n=t,i=[];for(let a=0;a<r.length;a++){let s=nb(r[a]);i[s>>8]===void 0&&(i[s>>8]=[]),i[s>>8][s>>3&31]|=1<<7-(s&7)}for(let a=0;a<i.length;a++)if(i[a]!==void 0){let s=n6(i[a]);e[t]=a,t+=1,e[t]=s.length,t+=1,Zo(s,e,t,0,s.length),t+=s.length}return Jo.encode.bytes=t-n,e},decode(r,e,t){e||(e=0);let n=e,i=[];for(;e-n<t;){let a=r[e];e+=1;let s=r[e];e+=1;for(let o=0;o<s;o++){let c=r[e+o];for(let l=0;l<8;l++)if(c&1<<7-l){let d=wE(a<<8|o<<3|l);i.push(d)}}e+=s}return Jo.decode.bytes=e-n,i},encodingLength(r){let e=[];for(let n=0;n<r.length;n++){let i=nb(r[n]);e[i>>8]=Math.max(e[i>>8]||0,i&255)}let t=0;for(let n=0;n<e.length;n++)e[n]!==void 0&&(t+=2+Math.ceil((e[n]+1)/8));return t}}),L0=Fr({encode(r,e,t){e||(e=new Uint8Array(L0.encodingLength(r))),t||(t=0);let n=t;return t+=2,He.encode(r.nextDomain,e,t),t+=He.encode.bytes,Jo.encode(r.rrtypes,e,t),t+=Jo.encode.bytes,L0.encode.bytes=t-n,nt(e,L0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Mt(r,e);return e+=2,n.nextDomain=He.decode(r,e),e+=He.decode.bytes,n.rrtypes=Jo.decode(r,e,i-(e-t)),e+=Jo.decode.bytes,L0.decode.bytes=e-t,n},encodingLength(r){return 2+He.encodingLength(r.nextDomain)+Jo.encodingLength(r.rrtypes)}}),q0=Fr({encode(r,e,t){e||(e=new Uint8Array(q0.encodingLength(r))),t||(t=0);let n=t,i=r.salt;if(!wh(i))throw new Error("salt must be a Buffer");let a=r.nextDomain;if(!wh(a))throw new Error("nextDomain must be a Buffer");return t+=2,e[t]=r.algorithm,t+=1,e[t]=r.flags,t+=1,nt(e,r.iterations,t),t+=2,e[t]=i.length,t+=1,Zo(i,e,t,0,i.length),t+=i.length,e[t]=a.length,t+=1,Zo(a,e,t,0,a.length),t+=a.length,Jo.encode(r.rrtypes,e,t),t+=Jo.encode.bytes,q0.encode.bytes=t-n,nt(e,q0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Mt(r,e);e+=2,n.algorithm=r[e],e+=1,n.flags=r[e],e+=1,n.iterations=Mt(r,e),e+=2;let a=r[e];e+=1,n.salt=r.slice(e,e+a),e+=a;let s=r[e];return e+=1,n.nextDomain=r.slice(e,e+s),e+=s,n.rrtypes=Jo.decode(r,e,i-(e-t)),e+=Jo.decode.bytes,q0.decode.bytes=e-t,n},encodingLength(r){return 8+r.salt.length+r.nextDomain.length+Jo.encodingLength(r.rrtypes)}}),z0=Fr({encode(r,e,t){e||(e=new Uint8Array(z0.encodingLength(r))),t||(t=0);let n=t,i=r.digest;if(!wh(i))throw new Error("Digest must be a Buffer");return t+=2,nt(e,r.keyTag,t),t+=2,e[t]=r.algorithm,t+=1,e[t]=r.digestType,t+=1,Zo(i,e,t,0,i.length),t+=i.length,z0.encode.bytes=t-n,nt(e,z0.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={},i=Mt(r,e);return e+=2,n.keyTag=Mt(r,e),e+=2,n.algorithm=r[e],e+=1,n.digestType=r[e],e+=1,n.digest=r.slice(e,t+i+2),e+=n.digest.length,z0.decode.bytes=e-t,n},encodingLength(r){return 6+Af(r.digest)}}),Hy=Fr({encode(r,e,t){e||(e=new Uint8Array(Hy.encodingLength(r))),t||(t=0);let n=t;t+=2,e[t]=r.algorithm,t+=1,e[t]=r.hash,t+=1;let i=Uq(r.fingerprint),a=bC(r.hash);if(i!==a)throw new Error(`Invalid length of fingerprint "${r.fingerprint}" for hashType=${r.hash}: ${i} != ${a}`);return zhe(e,r.fingerprint,t,t+=i),Hy.encode.bytes=t-n,nt(e,Hy.encode.bytes-2,n),e},decode(r,e){e||(e=0);let t=e,n={};e+=2,n.algorithm=r[e],e+=1,n.hash=r[e],e+=1;let i=bC(n.hash);return n.fingerprint=qhe(r,e,e+i),e+=i,Hy.decode.bytes=e-t,n},encodingLength(r){return 4+Uq(r.fingerprint)}});Hy.getFingerprintLengthForHashType=bC;Ca=Fr({encode(r,e,t){e||(e=new Uint8Array(Ca.encodingLength(r))),t||(t=0);let n=t;if(He.encode(r.name,e,t),t+=He.encode.bytes,nt(e,nb(r.type),t),r.type.toUpperCase()==="OPT"){if(r.name!==".")throw new Error("OPT name must be root.");nt(e,r.udpPayloadSize||4096,t+2),e[t+4]=r.extendedRcode||0,e[t+5]=r.ednsVersion||0,nt(e,r.flags||0,t+6),t+=8,Ef.encode(r.options||[],e,t),t+=Ef.encode.bytes}else{let i=W7(r.class===void 0?"IN":r.class);r.flush&&(i|=vC),nt(e,i,t+2),Fl(e,r.ttl||0,t+4),t+=8;let a=aC(r.type);a.encode(r.data,e,t),t+=a.encode.bytes}return Ca.encode.bytes=t-n,e},decode(r,e){e||(e=0);let t={},n=e;if(t.name=He.decode(r,e),e+=He.decode.bytes,t.type=wE(Mt(r,e)),t.type==="OPT")t.udpPayloadSize=Mt(r,e+2),t.extendedRcode=r[e+4],t.ednsVersion=r[e+5],t.flags=Mt(r,e+6),t.flag_do=(t.flags>>15&1)===1,t.options=Ef.decode(r,e+8),e+=8+Ef.decode.bytes;else{let i=Mt(r,e+2);t.ttl=zl(r,e+4),t.class=V7(i&Jhe),t.flush=!!(i&vC);let a=aC(t.type);t.data=a.decode(r,e+8),e+=8+a.decode.bytes}return Ca.decode.bytes=e-n,t},encodingLength(r){let e=r.data!==null&&r.data!==void 0?r.data:r.options;return He.encodingLength(r.name)+8+aC(r.type).encodingLength(e)}}),Zy=Fr({encode(r,e,t){e||(e=new Uint8Array(Zy.encodingLength(r))),t||(t=0);let n=t;return He.encode(r.name,e,t),t+=He.encode.bytes,nt(e,nb(r.type),t),t+=2,nt(e,W7(r.class===void 0?"IN":r.class),t),t+=2,Zy.encode.bytes=t-n,r},decode(r,e){e||(e=0);let t=e,n={};return n.name=He.decode(r,e),e+=He.decode.bytes,n.type=wE(Mt(r,e)),e+=2,n.class=V7(Mt(r,e)),e+=2,n.class&Y7&&(n.class&=Zhe),Zy.decode.bytes=e-t,n},encodingLength(r){return He.encodingLength(r.name)+4}}),Yhe=1024,ns={encode:function(r,e,t){let n=!e;n&&(e=new Uint8Array(Xhe(r))),t||(t=0);let i=t;return r.questions||(r.questions=[]),r.answers||(r.answers=[]),r.authorities||(r.authorities=[]),r.additionals||(r.additionals=[]),qy.encode(r,e,t),t+=qy.encode.bytes,t=F0(r.questions,Zy,e,t),t=F0(r.answers,Ca,e,t),t=F0(r.authorities,Ca,e,t),t=F0(r.additionals,Ca,e,t),ns.encode.bytes=t-i,n&&oE.bytes!==e.length?e.slice(0,oE.bytes):e},decode:function(r,e){e||(e=0);let t=e,n=qy.decode(r,e);return e+=qy.decode.bytes,e=k2(n.questions,Zy,r,e),e=k2(n.answers,Ca,r,e),e=k2(n.authorities,Ca,r,e),e=k2(n.additionals,Ca,r,e),ns.decode.bytes=e-t,n},encodingLength:function(r){return qy.encodingLength(r)+Vy(r.questions||[],Zy)+Vy(r.answers||[],Ca)+Vy(r.authorities||[],Ca)+Vy(r.additionals||[],Ca)}};ns.encode.bytes=0;ns.decode.bytes=0;iE={encode:function(r,e,t){return e=ns.encode(nE(r,"query"),e,t),iE.encode.bytes=ns.encode.bytes,e},decode:function(r,e){let t=ns.decode(r,e);return iE.decode.bytes=ns.decode.bytes,t.questions&&(t.question=t.questions[0],delete t.questions),t},encodingLength:function(r){return ns.encodingLength(nE(r,"query"))}};iE.encode.bytes=0;iE.decode.bytes=0;sE={encode:function(r,e,t){return e=ns.encode(nE(r,"response"),e,t),sE.encode.bytes=ns.encode.bytes,e},decode:function(r,e){let t=ns.decode(r,e);return sE.decode.bytes=ns.decode.bytes,t.questions&&(t.question=t.questions[0],delete t.questions),t},encodingLength:function(r){return ns.encodingLength(nE(r,"response"))}};sE.encode.bytes=0;sE.decode.bytes=0;oE=ns.encode,PC=ns.decode,Xhe=ns.encodingLength;Q7.bytes=0;eF.bytes=0;nF="dht";ime=0,wf=7200,z2=";",Vs=",",oF={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},aF={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};ame="https://enbox-did-dht.fly.dev";dF=class xC extends fb{static async create({keyManager:e=new Dc,options:t={}}={}){if(t.verificationMethods?.some(d=>!(d.algorithm in oF)))throw new Error("One or more verification method algorithms are not supported");let n=t.verificationMethods?.filter(d=>"id"in d).map(d=>d.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(t.services?.some(d=>!d.id||!d.type||!d.serviceEndpoint))throw new Error("One or more services are missing required properties");let i=await e.generateKey({algorithm:"Ed25519"}),a=await e.getPublicKey({keyUri:i}),s=await Wy.identityKeyToIdentifier({identityKey:a}),o={id:s,...t.alsoKnownAs&&{alsoKnownAs:t.alsoKnownAs},...t.controllers&&{controller:t.controllers}},c=[...t.verificationMethods??[]];c?.some(d=>d.id?.split("#").pop()==="0")||c.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let d of c){let u=d.id?.split("#").pop()==="0"?i:await e.generateKey({algorithm:d.algorithm}),f=await e.getPublicKey({keyUri:u}),p=d.id??f.kid??await xr({jwk:f});p=`${s}#${Ws(p)}`,o.verificationMethod??=[],o.verificationMethod.push({id:p,type:"JsonWebKey",controller:d.controller??s,publicKeyJwk:f});for(let h of d.purposes??[])o[h]??=[],o[h].push(p)}t.services?.forEach(d=>{o.service??=[],d.id=`${s}#${d.id.split("#").pop()}`,o.service.push(d)});let l=new xs({uri:s,document:o,metadata:{published:!1,...t.types&&{types:t.types}},keyManager:e});if(t.publish??!0){let d=await xC.publish({did:l,gatewayUri:t.gatewayUri,allowPrivateGatewayUri:t.allowPrivateGatewayUri});l.metadata=d.didDocumentMetadata}return l}static async import({portableDid:e,keyManager:t=new Dc}){if(Vn.parse(e.uri)?.method!==xC.methodName)throw new Xe("methodNotSupported","Method not supported");let n=await xs.import({portableDid:e,keyManager:t});if(!n.document.verificationMethod?.some(i=>i.id?.split("#").pop()==="0"))throw new Xe("invalidDidDocument","DID document must contain an Identity Key");return n}static async getSigningMethod({didDocument:e,methodId:t="#0"}){let n=Vn.parse(e.id);if(n&&n.method!==this.methodName)throw new Xe("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(a=>Ws(a.id)===(Ws(t)??Ws(e.assertionMethod?.[0])));if(!i?.publicKeyJwk)throw new Xe("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async publish({did:e,gatewayUri:t,allowPrivateGatewayUri:n}){let i=zq(t,n);return Fq.put({did:e,...i})}static async resolve(e,t={}){let{gatewayUri:n,allowPrivateGatewayUri:i}=zq(t.gatewayUri,t.allowPrivateGatewayUri);try{await Wy.identifierToIdentityKey({didUri:e});let{didDocument:a,didDocumentMetadata:s}=await Fq.get({didUri:e,gatewayUri:n,allowPrivateGatewayUri:i});return{...is,didDocument:a,didDocumentMetadata:s}}catch(a){if(!(a instanceof Xe))throw new Error(a);return{...is,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};dF.methodName="dht";wo=dF,Fq=class H0{static async get({didUri:e,gatewayUri:t,allowPrivateGatewayUri:n=!1}){let i=Wy.identifierToIdentityKeyBytes({didUri:e}),a=await H0.pkarrGet({gatewayUri:t,publicKeyBytes:i,allowPrivateGatewayUri:n}),s=await Wy.parseBep44GetMessage({bep44Message:a}),o=await H0.fromDnsPacket({didUri:e,dnsPacket:s});return o.didDocumentMetadata.versionId=a.seq.toString(),o}static async put({did:e,gatewayUri:t,allowPrivateGatewayUri:n=!1}){let i=await H0.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[t]}),a=await Wy.createBep44PutMessage({dnsPacket:i,publicKeyBytes:Wy.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),s=await H0.pkarrPut({gatewayUri:t,bep44Message:a,allowPrivateGatewayUri:n});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:s,versionId:a.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return Qhe(e)}static async pkarrPut(e){return eme(e)}static async fromDnsPacket(e){return sme(e)}static async toDnsPacket(e){return ome(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},Wy=class{static async createBep44PutMessage(r){return tme(r)}static async identifierToIdentityKey(r){return iF(r)}static identifierToIdentityKeyBytes(r){return s6(r)}static async identityKeyToIdentifier(r){return nme(r)}static keyConverter(r){return o6(r)}static async parseBep44GetMessage(r){return rme(r)}static parseTxtDataToObject(r){return G0(r)}static parseTxtDataToString(r){return sb(r)}static async validatePreviousDidProof(r){return sF(r)}static chunkDataIfNeeded(r){return cF(r)}},Fn={DeltaExceedsMaximumSize:"DeltaExceedsMaximumSize",DidDocumentPublicKeyIdDuplicated:"DidDocumentPublicKeyIdDuplicated",DidDocumentPublicKeyMissingOrIncorrectType:"DidDocumentPublicKeyMissingOrIncorrectType",DidDocumentServiceIdDuplicated:"DidDocumentServiceIdDuplicated",DidSuffixIncorrectLength:"DidSuffixIncorrectLength",EncodedStringIncorrectEncoding:"EncodedStringIncorrectEncoding",IdNotUsingBase64UrlCharacterSet:"IdNotUsingBase64UrlCharacterSet",IdTooLong:"IdTooLong",JwkEs256kMissingOrInvalidCrv:"JwkEs256kMissingOrInvalidCrv",JwkEs256kMissingOrInvalidKty:"JwkEs256kMissingOrInvalidKty",JwkEs256kHasIncorrectLengthOfX:"JwkEs256kHasIncorrectLengthOfX",JwkEs256kHasIncorrectLengthOfY:"JwkEs256kHasIncorrectLengthOfY",JwkEs256kHasIncorrectLengthOfD:"JwkEs256kHasIncorrectLengthOfD",MultihashStringNotAMultihash:"MultihashStringNotAMultihash",MultihashUnsupportedHashAlgorithm:"MultihashUnsupportedHashAlgorithm",PublicKeyJwkEs256kHasUnexpectedProperty:"PublicKeyJwkEs256kHasUnexpectedProperty",PublicKeyPurposeDuplicated:"PublicKeyPurposeDuplicated",ServiceEndpointCannotBeAnArray:"ServiceEndpointCannotBeAnArray",ServiceEndpointStringNotValidUri:"ServiceEndpointStringNotValidUri",ServiceTypeTooLong:"ServiceTypeTooLong"},Gn=class extends Error{constructor(r,e){super(`${r}: ${e}`),this.code=r,Object.setPrototypeOf(this,new.target.prototype)}},RLe=new Uint8Array(0),lme=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")},ume=class{constructor(r,e,t){this.name=r,this.prefix=e,this.baseEncode=t}encode(r){if(r instanceof Uint8Array)return`${this.prefix}${this.baseEncode(r)}`;throw Error("Unknown type, must be binary type")}},fme=class{constructor(r,e,t){if(this.name=r,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=t}decode(r){if(typeof r=="string"){if(r.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(r)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(r.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(r){return lF(this,r)}},pme=class{constructor(r){this.decoders=r}or(r){return lF(this,r)}decode(r){let e=r[0],t=this.decoders[e];if(t)return t.decode(r);throw RangeError(`Unable to decode multibase string ${JSON.stringify(r)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},lF=(r,e)=>new pme({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),hme=class{constructor(r,e,t,n){this.name=r,this.prefix=e,this.baseEncode=t,this.baseDecode=n,this.encoder=new ume(r,e,t),this.decoder=new fme(r,e,n)}encode(r){return this.encoder.encode(r)}decode(r){return this.decoder.decode(r)}},mme=({name:r,prefix:e,encode:t,decode:n})=>new hme(r,e,t,n),yme=(r,e,t,n)=>{let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let a=r.length;for(;r[a-1]==="=";)--a;let s=new Uint8Array(a*t/8|0),o=0,c=0,l=0;for(let d=0;d<a;++d){let u=i[r[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,o+=t,o>=8&&(o-=8,s[l++]=255&c>>o)}if(o>=t||255&c<<8-o)throw new SyntaxError("Unexpected end of data");return s},gme=(r,e,t)=>{let n=e[e.length-1]==="=",i=(1<<t)-1,a="",s=0,o=0;for(let c=0;c<r.length;++c)for(o=o<<8|r[c],s+=8;s>t;)s-=t,a+=e[i&o>>s];if(s&&(a+=e[i&o<<t-s]),n)for(;a.length*t&7;)a+="=";return a},vE=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>mme({prefix:e,name:r,encode(i){return gme(i,n,t)},decode(i){return yme(i,n,t,r)}}),CLe=vE({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$Le=vE({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Gq=vE({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),BLe=vE({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),eg=class F2{static encode(e){return Gq.baseEncode(e)}static decodeAsBytes(e,t){if(!F2.isBase64UrlString(e))throw new Gn(Fn.EncodedStringIncorrectEncoding,`Given ${t} must be base64url string.`);return Gq.baseDecode(e)}static decodeAsString(e,t){let n=F2.decodeAsBytes(e,t);return F2.bytesToString(n)}static isBase64UrlString(e){return/^[A-Za-z0-9_-]+$/.test(e)}static stringToBytes(e){return new TextEncoder().encode(e)}static bytesToString(e){return new TextDecoder().decode(e)}},wme=vh(sle(),1);(function(r){r.Public="public",r.Private="private"})(EC||(EC={}));Cd=EC,Ho=class{static validateEs256kOperationKey(r,e){let t=new Set(["kty","crv","x","y"]);e===Cd.Private&&t.add("d");for(let n in r)if(!t.has(n))throw new Gn(Fn.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${n}'.`);if(r.crv!=="secp256k1")throw new Gn(Fn.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${r.crv}.'`);if(r.kty!=="EC")throw new Gn(Fn.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${r.kty}.'`);if(r.x.length!==43)throw new Gn(Fn.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(r.y.length!==43)throw new Gn(Fn.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(e===Cd.Private&&(r.d===void 0||r.d.length!==43))throw new Gn(Fn.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(r){if(r.length>50)throw new Gn(Fn.IdTooLong,`Key ID length ${r.length} exceed max allowed length of 50.`);if(!eg.isBase64UrlString(r))throw new Gn(Fn.IdNotUsingBase64UrlCharacterSet,`Key ID '${r}' is not a Base64URL string.`)}static validatePublicKeyPurposes(r){if(r===void 0)return;let e=new Set;for(let t of r){if(e.has(t))throw new Gn(Fn.PublicKeyPurposeDuplicated,`Public key purpose '${t}' already specified.`);e.add(t)}}},a6=class{};a6.hashAlgorithmInMultihashCode=18;a6.maxCanonicalizedDeltaSizeInBytes=1e3;Ic=a6,vme=vh(ole(),1),ob=class SC{static canonicalizeAsBytes(e){let t=SC.removeAllUndefinedProperties(e),n=vme.default(t);return eg.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let t in e)typeof e[t]=="object"?SC.removeAllUndefinedProperties(e[t]):e[t]===void 0&&delete e[t];return e}},bme=uF,Hq=128,Pme=127,xme=~Pme,Eme=Math.pow(2,31);Sme=kC,kme=128,Vq=127;_me=Math.pow(2,7),Ame=Math.pow(2,14),Tme=Math.pow(2,21),Ime=Math.pow(2,28),Dme=Math.pow(2,35),Rme=Math.pow(2,42),Cme=Math.pow(2,49),$me=Math.pow(2,56),Bme=Math.pow(2,63),Ome=function(r){return r<_me?1:r<Ame?2:r<Tme?3:r<Ime?4:r<Dme?5:r<Rme?6:r<Cme?7:r<$me?8:r<Bme?9:10},jme={encode:bme,decode:Sme,encodingLength:Ome},Mme=jme,aE=Mme,Wq=(r,e=0)=>[aE.decode(r,e),aE.decode.bytes],Jq=(r,e,t=0)=>(aE.encode(r,e,t),e),Zq=r=>aE.encodingLength(r),Yq=(r,e)=>{let t=e.byteLength,n=Zq(r),i=n+Zq(t),a=new Uint8Array(i+t);return Jq(r,a,0),Jq(t,a,n),a.set(e,i),new fF(r,t,e,a)},Kme=r=>{let e=lme(r),[t,n]=Wq(e),[i,a]=Wq(e.subarray(n)),s=e.subarray(n+a);if(s.byteLength!==i)throw new Error("Incorrect length");return new fF(t,i,s,e)},fF=class{constructor(r,e,t,n){this.code=r,this.size=e,this.digest=t,this.bytes=n}},pF=({name:r,code:e,encode:t})=>new Ume(r,e,t),Ume=class{constructor(r,e,t){this.name=r,this.code=e,this.encode=t}digest(r){if(r instanceof Uint8Array){let e=this.encode(r);return e instanceof Uint8Array?Yq(this.code,e):e.then(t=>Yq(this.code,t))}else throw Error("Unknown type, must be binary type")}},hF=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Xq=pF({name:"sha2-256",code:18,encode:hF("SHA-256")}),OLe=pF({name:"sha2-512",code:19,encode:hF("SHA-512")}),$0=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},Wo=class V0{static hash(e,t){return $0(this,void 0,void 0,function*(){let n;switch(t){case 18:n=(yield Xq.digest(e)).bytes;break;default:throw new Gn(Fn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${t} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,t){return $0(this,void 0,void 0,function*(){let n;switch(t){case 18:n=yield Xq.encode(e);break;default:throw new Gn(Fn.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${t} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,t){return $0(this,void 0,void 0,function*(){let n=ob.canonicalizeAsBytes(e);return yield V0.hashThenEncode(n,t)})}static canonicalizeThenDoubleHashThenEncode(e,t){return $0(this,void 0,void 0,function*(){let n=ob.canonicalizeAsBytes(e),i=yield V0.hashAsNonMultihashBytes(n,t);return yield V0.hashThenEncode(i,t)})}static hashThenEncode(e,t){return $0(this,void 0,void 0,function*(){let n=yield V0.hash(e,t);return eg.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,t){let n,i=eg.decodeAsBytes(e,t);try{n=Kme(i)}catch{throw new Gn(Fn.MultihashStringNotAMultihash,`Given ${t} string '${e}' is not a multihash after decoding.`)}let a=Ic.hashAlgorithmInMultihashCode;if(a!==n.code)throw new Gn(Fn.MultihashUnsupportedHashAlgorithm,`Given ${t} uses unsupported multihash algorithm with code ${n.code}, should use ${a} or change IonSdkConfig to desired hashing algorithm.`)}};(function(r){r.Create="create",r.Update="update",r.Deactivate="deactivate",r.Recover="recover"})(_C||(_C={}));_2=_C;(function(r){r.Replace="replace",r.AddPublicKeys="add-public-keys",r.RemovePublicKeys="remove-public-keys",r.AddServices="add-services",r.RemoveServices="remove-services"})(AC||(AC={}));Ny=AC,A2=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},mF=class Da{static createCreateRequest(e){return A2(this,void 0,void 0,function*(){let t=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,a=e.document.services;Ho.validateEs256kOperationKey(t,Cd.Public),Ho.validateEs256kOperationKey(n,Cd.Public),Da.validateDidDocumentKeys(i),Da.validateServices(a);let s=Ic.hashAlgorithmInMultihashCode,o=[{action:Ny.Replace,document:e.document}],c={updateCommitment:yield Wo.canonicalizeThenDoubleHashThenEncode(n,s),patches:o};Da.validateDeltaSize(c);let l={deltaHash:yield Wo.canonicalizeThenHashThenEncode(c,s),recoveryCommitment:yield Wo.canonicalizeThenDoubleHashThenEncode(t,s)};return{type:_2.Create,suffixData:l,delta:c}})}static createDeactivateRequest(e){return A2(this,void 0,void 0,function*(){Da.validateDidSuffix(e.didSuffix),Ho.validateEs256kOperationKey(e.recoveryPublicKey,Cd.Public);let t=Ic.hashAlgorithmInMultihashCode,n=yield Wo.canonicalizeThenHashThenEncode(e.recoveryPublicKey,t),i={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},a=yield e.signer.sign({alg:"ES256K"},i);return{type:_2.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:a}})}static createRecoverRequest(e){return A2(this,void 0,void 0,function*(){Da.validateDidSuffix(e.didSuffix),Ho.validateEs256kOperationKey(e.recoveryPublicKey,Cd.Public),Ho.validateEs256kOperationKey(e.nextRecoveryPublicKey,Cd.Public),Ho.validateEs256kOperationKey(e.nextUpdatePublicKey,Cd.Public),Da.validateDidDocumentKeys(e.document.publicKeys),Da.validateServices(e.document.services);let t=Ic.hashAlgorithmInMultihashCode,n=yield Wo.canonicalizeThenHashThenEncode(e.recoveryPublicKey,t),i=[{action:Ny.Replace,document:e.document}],a=yield Wo.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,t),s={patches:i,updateCommitment:a},o=yield Wo.canonicalizeThenHashThenEncode(s,t),c={recoveryCommitment:yield Wo.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,t),recoveryKey:e.recoveryPublicKey,deltaHash:o},l=yield e.signer.sign({alg:"ES256K"},c);return{type:_2.Recover,didSuffix:e.didSuffix,revealValue:n,delta:s,signedData:l}})}static createUpdateRequest(e){return A2(this,void 0,void 0,function*(){if(Da.validateDidSuffix(e.didSuffix),Ho.validateEs256kOperationKey(e.updatePublicKey,Cd.Public),Ho.validateEs256kOperationKey(e.nextUpdatePublicKey,Cd.Public),Da.validateServices(e.servicesToAdd),Da.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let h of e.idsOfServicesToRemove)Ho.validateId(h);if(e.idsOfPublicKeysToRemove!==void 0)for(let h of e.idsOfPublicKeysToRemove)Ho.validateId(h);let t=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let h={action:Ny.AddServices,services:n};t.push(h)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let h={action:Ny.RemoveServices,ids:i};t.push(h)}let a=e.publicKeysToAdd;if(a!==void 0&&a.length>0){let h={action:Ny.AddPublicKeys,publicKeys:a};t.push(h)}let s=e.idsOfPublicKeysToRemove;if(s!==void 0&&s.length>0){let h={action:Ny.RemovePublicKeys,ids:s};t.push(h)}let o=Ic.hashAlgorithmInMultihashCode,c=yield Wo.canonicalizeThenHashThenEncode(e.updatePublicKey,o),l=yield Wo.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,o),d={patches:t,updateCommitment:l},u=yield Wo.canonicalizeThenHashThenEncode(d,o),f={updateKey:e.updatePublicKey,deltaHash:u},p=yield e.signer.sign({alg:"ES256K"},f);return{type:_2.Update,didSuffix:e.didSuffix,revealValue:c,delta:d,signedData:p}})}static validateDidSuffix(e){Wo.validateEncodedHashComputedUsingSupportedHashAlgorithm(e,"didSuffix")}static validateDidDocumentKeys(e){if(e===void 0)return;let t=new Set;for(let n of e){if(Array.isArray(n.publicKeyJwk))throw new Gn(Fn.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(Ho.validateId(n.id),t.has(n.id))throw new Gn(Fn.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);t.add(n.id),Ho.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let t=new Set;for(let n of e){if(Da.validateService(n),t.has(n.id))throw new Gn(Fn.DidDocumentServiceIdDuplicated,"Service id has to be unique");t.add(n.id)}}}static validateService(e){Ho.validateId(e.id);let t=30;if(e.type.length>t){let n=`Service endpoint type length ${e.type.length} exceeds max allowed length of ${t}.`;throw new Gn(Fn.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Gn(Fn.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&wme.parse(e.serviceEndpoint).error!==void 0)throw new Gn(Fn.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let t=ob.canonicalizeAsBytes(e);if(t.length>Ic.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${t.length} bytes exceeded limit of ${Ic.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Gn(Fn.DeltaExceedsMaximumSize,n)}}},Qq=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(r,e||[])).next())})},Nme=class yF{static createLongFormDid(e){return Qq(this,void 0,void 0,function*(){let t=yield mF.createCreateRequest(e),n=yield yF.computeDidUniqueSuffix(t.suffixData),i;Ic.network===void 0||Ic.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${Ic.network}:${n}`;let a={suffixData:t.suffixData,delta:t.delta},s=ob.canonicalizeAsBytes(a),o=eg.encode(s);return`${i}:${o}`})}static computeDidUniqueSuffix(e){return Qq(this,void 0,void 0,function*(){let t=ob.canonicalizeAsBytes(e),n=yield Wo.hash(t,Ic.hashAlgorithmInMultihashCode);return eg.encode(n)})}},Qi=2n**255n-19n,G2=2n**252n+27742317777372353535851937790883648493n,TC=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,IC=0x6666666666666666666666666666666666666666666666666666666666666658n,T2={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Qi,n:G2,h:8,Gx:TC,Gy:IC},yo=(r="")=>{throw new Error(r)},gF=r=>typeof r=="string",c6=(r,e)=>!(r instanceof Uint8Array)||typeof e=="number"&&e>0&&r.length!==e?yo("Uint8Array expected"):r,tg=r=>new Uint8Array(r),Lme=(r,e)=>c6(gF(r)?l6(r):tg(r),e),at=(r,e=Qi)=>{let t=r%e;return t>=0n?t:e+t},ez=r=>r instanceof rg?r:yo("Point expected"),rg=class zy{constructor(e,t,n,i){this.ex=e,this.ey=t,this.ez=n,this.et=i}static fromAffine(e){return new zy(e.x,e.y,1n,at(e.x*e.y))}static fromHex(e,t=!0){let{d:n}=T2;e=Lme(e,32);let i=e.slice();i[31]=e[31]&-129;let a=zme(i);a===0n||(t&&!(0n<a&&a<Qi)&&yo("bad y coord 1"),!t&&!(0n<a&&a<2n**256n)&&yo("bad y coord 2"));let s=at(a*a),o=at(s-1n),c=at(n*s+1n),{isValid:l,value:d}=Gme(o,c);l||yo("bad y coordinate 3");let u=(d&1n)===1n;return(e[31]&128)!==0!==u&&(d=at(-d)),new zy(d,a,1n,at(d*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){let{ex:t,ey:n,ez:i}=this,{ex:a,ey:s,ez:o}=ez(e),c=at(t*o),l=at(a*i),d=at(n*o),u=at(s*i);return c===l&&d===u}is0(){return this.equals(H2)}negate(){return new zy(at(-this.ex),this.ey,this.ez,at(-this.et))}double(){let{ex:e,ey:t,ez:n}=this,{a:i}=T2,a=at(e*e),s=at(t*t),o=at(2n*at(n*n)),c=at(i*a),l=e+t,d=at(at(l*l)-a-s),u=c+s,f=u-o,p=c-s,h=at(d*f),m=at(u*p),y=at(d*p),v=at(f*u);return new zy(h,m,v,y)}add(e){let{ex:t,ey:n,ez:i,et:a}=this,{ex:s,ey:o,ez:c,et:l}=ez(e),{a:d,d:u}=T2,f=at(t*s),p=at(n*o),h=at(a*u*l),m=at(i*c),y=at((t+n)*(s+o)-f-p),v=at(m-h),w=at(m+h),E=at(p-d*f),_=at(y*v),A=at(w*E),D=at(y*E),M=at(v*w);return new zy(_,A,M,D)}mul(e,t=!0){if(e===0n)return t===!0?yo("cannot multiply by 0"):H2;if(typeof e=="bigint"&&0n<e&&e<G2||yo("invalid scalar, must be < L"),!t&&this.is0()||e===1n)return this;if(this.equals(cE))return Wme(e).p;let n=H2,i=cE;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):t&&(i=i.add(a));return n}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(T2.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(G2/2n,!1).double();return G2%2n&&(e=e.add(this)),e.is0()}toAffine(){let{ex:e,ey:t,ez:n}=this;if(this.is0())return{x:0n,y:0n};let i=vF(n);return at(n*i)!==1n&&yo("invalid inverse"),{x:at(e*i),y:at(t*i)}}toRawBytes(){let{x:e,y:t}=this.toAffine(),n=qme(t);return n[31]|=e&1n?128:0,n}toHex(){return d6(this.toRawBytes())}};rg.BASE=new rg(TC,IC,1n,at(TC*IC));rg.ZERO=new rg(0n,1n,1n,0n);({BASE:cE,ZERO:H2}=rg),wF=(r,e)=>r.toString(16).padStart(e,"0"),d6=r=>Array.from(r).map(e=>wF(e,2)).join(""),l6=r=>{let e=r.length;(!gF(r)||e%2)&&yo("hex invalid 1");let t=tg(e/2);for(let n=0;n<t.length;n++){let i=n*2,a=r.slice(i,i+2),s=Number.parseInt(a,16);(Number.isNaN(s)||s<0)&&yo("hex invalid 2"),t[n]=s}return t},qme=r=>l6(wF(r,32*2)).reverse(),zme=r=>BigInt("0x"+d6(tg(c6(r)).reverse())),rz=(...r)=>{let e=tg(r.reduce((n,i)=>n+c6(i).length,0)),t=0;return r.forEach(n=>{e.set(n,t),t+=n.length}),e},vF=(r,e=Qi)=>{(r===0n||e<=0n)&&yo("no inverse n="+r+" mod="+e);let t=at(r,e),n=e,i=0n,a=1n,s=1n,o=0n;for(;t!==0n;){let c=n/t,l=n%t,d=i-s*c,u=a-o*c;n=t,t=l,i=s,a=o,s=d,o=u}return n===1n?at(i,e):yo("no inverse")},Id=(r,e)=>{let t=r;for(;e-- >0n;)t*=t,t%=Qi;return t},Fme=r=>{let e=r*r%Qi*r%Qi,t=Id(e,2n)*e%Qi,n=Id(t,1n)*r%Qi,i=Id(n,5n)*n%Qi,a=Id(i,10n)*i%Qi,s=Id(a,20n)*a%Qi,o=Id(s,40n)*s%Qi,c=Id(o,80n)*o%Qi,l=Id(c,80n)*o%Qi,d=Id(l,10n)*i%Qi;return{pow_p_5_8:Id(d,2n)*r%Qi,b2:e}},nz=19681161376707505956807079304988542015446066515923890162744021073123829784752n,Gme=(r,e)=>{let t=at(e*e*e),n=at(t*t*e),i=Fme(r*n).pow_p_5_8,a=at(r*t*i),s=at(e*a*a),o=a,c=at(a*nz),l=s===r,d=s===at(-r),u=s===at(-r*nz);return l&&(a=o),(d||u)&&(a=c),(at(a)&1n)===1n&&(a=at(-a)),{isValid:l||d,value:a}},iz=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,Hme={bytesToHex:d6,hexToBytes:l6,concatBytes:rz,mod:at,invert:vF,randomBytes:r=>{let e=iz();return e||yo("crypto.getRandomValues must be defined"),e.getRandomValues(tg(r))},sha512Async:async(...r)=>{let e=iz();e||yo("crypto.subtle or etc.sha512Async must be defined");let t=rz(...r);return tg(await e.subtle.digest("SHA-512",t.buffer))},sha512Sync:void 0};Object.defineProperties(Hme,{sha512Sync:{configurable:!1,get(){return cC},set(r){cC||(cC=r)}}});dh=8,Vme=()=>{let r=[],e=256/dh+1,t=cE,n=t;for(let i=0;i<e;i++){n=t,r.push(n);for(let a=1;a<2**(dh-1);a++)n=n.add(t),r.push(n);t=n.double()}return r},Wme=r=>{let e=tz||(tz=Vme()),t=(d,u)=>{let f=u.negate();return d?f:u},n=H2,i=cE,a=1+256/dh,s=2**(dh-1),o=BigInt(2**dh-1),c=2**dh,l=BigInt(dh);for(let d=0;d<a;d++){let u=d*s,f=Number(r&o);r>>=l,f>s&&(f-=c,r+=1n);let p=u,h=u+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?i=i.add(t(m,e[p])):n=n.add(t(y,e[h]))}return{p:n,f:i}},u6=2n**256n,mh=u6-0x1000003d1n,f6=u6-0x14551231950b75fc4402da1732fc9bebfn,bF=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,PF=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,xF={p:mh,n:f6,a:0n,b:7n,Gx:bF,Gy:PF},Yy=32,sz=r=>Ye(Ye(r*r)*r+xF.b),Ti=(r="")=>{throw new Error(r)},bE=r=>typeof r=="bigint",EF=r=>typeof r=="string",dC=r=>bE(r)&&0n<r&&r<mh,SF=r=>bE(r)&&0n<r&&r<f6,kF=(r,e)=>!(r instanceof Uint8Array)||typeof e=="number"&&e>0&&r.length!==e?Ti("Uint8Array expected"):r,ab=r=>new Uint8Array(r),p6=(r,e)=>kF(EF(r)?PE(r):ab(r),e),Ye=(r,e=mh)=>{let t=r%e;return t>=0n?t:e+t},oz=r=>r instanceof ng?r:Ti("Point expected"),ng=class Fy{constructor(e,t,n){this.px=e,this.py=t,this.pz=n}static fromAffine(e){return new Fy(e.x,e.y,1n)}static fromHex(e){e=p6(e);let t,n=e[0],i=e.subarray(1),a=cz(i,0,Yy),s=e.length;if(s===33&&[2,3].includes(n)){dC(a)||Ti("Point hex invalid: x not FE");let o=Jme(sz(a)),c=(o&1n)===1n;(n&1)===1!==c&&(o=Ye(-o)),t=new Fy(a,o,1n)}return s===65&&n===4&&(t=new Fy(a,cz(i,Yy,2*Yy),1n)),t?t.ok():Ti("Point is not on curve")}static fromPrivateKey(e){return Y0.mul(Zme(e))}get x(){return this.aff().x}get y(){return this.aff().y}equals(e){let{px:t,py:n,pz:i}=this,{px:a,py:s,pz:o}=oz(e),c=Ye(t*o),l=Ye(a*i),d=Ye(n*o),u=Ye(s*i);return c===l&&d===u}negate(){return new Fy(this.px,Ye(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:t,py:n,pz:i}=this,{px:a,py:s,pz:o}=oz(e),{a:c,b:l}=xF,d=0n,u=0n,f=0n,p=Ye(l*3n),h=Ye(t*a),m=Ye(n*s),y=Ye(i*o),v=Ye(t+n),w=Ye(a+s);v=Ye(v*w),w=Ye(h+m),v=Ye(v-w),w=Ye(t+i);let E=Ye(a+o);return w=Ye(w*E),E=Ye(h+y),w=Ye(w-E),E=Ye(n+i),d=Ye(s+o),E=Ye(E*d),d=Ye(m+y),E=Ye(E-d),f=Ye(c*w),d=Ye(p*y),f=Ye(d+f),d=Ye(m-f),f=Ye(m+f),u=Ye(d*f),m=Ye(h+h),m=Ye(m+h),y=Ye(c*y),w=Ye(p*w),m=Ye(m+y),y=Ye(h-y),y=Ye(c*y),w=Ye(w+y),h=Ye(m*w),u=Ye(u+h),h=Ye(E*w),d=Ye(v*d),d=Ye(d-h),h=Ye(v*m),f=Ye(E*f),f=Ye(f+h),new Fy(d,u,f)}mul(e,t=!0){if(!t&&e===0n)return V2;if(SF(e)||Ti("invalid scalar"),this.equals(Y0))return eye(e).p;let n=V2,i=Y0;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):t&&(i=i.add(a));return n}mulAddQUns(e,t,n){return this.mul(t,!1).add(e.mul(n,!1)).ok()}toAffine(){let{px:e,py:t,pz:n}=this;if(this.equals(V2))return{x:0n,y:0n};if(n===1n)return{x:e,y:t};let i=AF(n);return Ye(n*i)!==1n&&Ti("invalid inverse"),{x:Ye(e*i),y:Ye(t*i)}}assertValidity(){let{x:e,y:t}=this.aff();return(!dC(e)||!dC(t))&&Ti("Point invalid: x or y"),Ye(t*t)===sz(e)?this:Ti("Point invalid: not on curve")}multiply(e){return this.mul(e)}aff(){return this.toAffine()}ok(){return this.assertValidity()}toHex(e=!0){let{x:t,y:n}=this.aff();return(e?(n&1n)===0n?"02":"03":"04")+dz(t)+(e?"":dz(n))}toRawBytes(e=!0){return PE(this.toHex(e))}};ng.BASE=new ng(bF,PF,1n);ng.ZERO=new ng(0n,1n,0n);({BASE:Y0,ZERO:V2}=ng),_F=(r,e)=>r.toString(16).padStart(e,"0"),h6=r=>Array.from(r).map(e=>_F(e,2)).join(""),PE=r=>{let e=r.length;(!EF(r)||e%2)&&Ti("hex invalid 1");let t=ab(e/2);for(let n=0;n<t.length;n++){let i=n*2,a=r.slice(i,i+2),s=Number.parseInt(a,16);(Number.isNaN(s)||s<0)&&Ti("hex invalid 2"),t[n]=s}return t},xE=r=>BigInt("0x"+(h6(r)||"0")),cz=(r,e,t)=>xE(r.slice(e,t)),m6=r=>bE(r)&&r>=0n&&r<u6?PE(_F(r,2*Yy)):Ti("bigint expected"),dz=r=>h6(m6(r)),lz=(...r)=>{let e=ab(r.reduce((n,i)=>n+kF(i).length,0)),t=0;return r.forEach(n=>{e.set(n,t),t+=n.length}),e},AF=(r,e=mh)=>{(r===0n||e<=0n)&&Ti("no inverse n="+r+" mod="+e);let t=Ye(r,e),n=e,i=0n,a=1n,s=1n,o=0n;for(;t!==0n;){let c=n/t,l=n%t,d=i-s*c,u=a-o*c;n=t,t=l,i=s,a=o,s=d,o=u}return n===1n?Ye(i,e):Ti("no inverse")},Jme=r=>{let e=1n;for(let t=r,n=(mh+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*t%mh),t=t*t%mh;return Ye(e*e)===r?e:Ti("sqrt invalid")},Zme=r=>(bE(r)||(r=xE(p6(r,Yy))),SF(r)?r:Ti("private key out of range")),uz=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;Xme={hexToBytes:PE,bytesToHex:h6,concatBytes:lz,bytesToNumberBE:xE,numberToBytesBE:m6,mod:Ye,invert:AF,hmacSha256Async:async(r,...e)=>{let t=uz();if(!t)return Ti("etc.hmacSha256Async not set");let n=t.subtle,i=await n.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return ab(await n.sign("HMAC",i,lz(...e)))},hmacSha256Sync:W2,hashToPrivateKey:Yme,randomBytes:r=>{let e=uz();return e||Ti("crypto.getRandomValues must be defined"),e.getRandomValues(ab(r))}};Object.defineProperties(Xme,{hmacSha256Sync:{configurable:!1,get(){return W2},set(r){W2||(W2=r)}}});lh=8,Qme=()=>{let r=[],e=256/lh+1,t=Y0,n=t;for(let i=0;i<e;i++){n=t,r.push(n);for(let a=1;a<2**(lh-1);a++)n=n.add(t),r.push(n);t=n.double()}return r},eye=r=>{let e=az||(az=Qme()),t=(d,u)=>{let f=u.negate();return d?f:u},n=V2,i=Y0,a=1+256/lh,s=2**(lh-1),o=BigInt(2**lh-1),c=2**lh,l=BigInt(lh);for(let d=0;d<a;d++){let u=d*s,f=Number(r&o);r>>=l,f>s&&(f-=c,r+=1n);let p=u,h=u+Math.abs(f)-1,m=d%2!==0,y=f<0;f===0?i=i.add(t(m,e[p])):n=n.add(t(y,e[h]))}return{p:n,f:i}};(function(r){r.Mainnet="mainnet",r.Testnet="test"})(fz||(fz={}));(function(r){r.Authentication="authentication",r.AssertionMethod="assertionMethod",r.CapabilityInvocation="capabilityInvocation",r.CapabilityDelegation="capabilityDelegation",r.KeyAgreement="keyAgreement"})(pz||(pz={}));B0=class ah{static appendPathToUrl({baseUrl:e,path:t}){let n=new URL(e);return n.pathname=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",n.pathname+=t.startsWith("/")?t.substring(1):t,n.toString()}static async computeLongFormDidUri({recoveryKey:e,updateKey:t,services:n,verificationMethods:i}){let a=await ah.createIonDocument({services:n,verificationMethods:i}),s=ah.normalizeJwk(e),o=ah.normalizeJwk(t);return await Nme.createLongFormDid({document:a,recoveryKey:s,updateKey:o})}static async constructCreateRequest({ionDocument:e,recoveryKey:t,updateKey:n}){return await mF.createCreateRequest({document:e,recoveryKey:ah.normalizeJwk(t),updateKey:ah.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:t}){let n=[];for(let a of t){let s=a.id??a.publicKeyJwk.kid??await xr({jwk:a.publicKeyJwk});s=`${s.split("#").pop()}`;let o={id:s,publicKeyJwk:ah.normalizeJwk(a.publicKeyJwk),purposes:a.purposes,type:"JsonWebKey2020"};n.push(o)}let i=e.map(a=>({...a,id:`${a.id.split("#").pop()}`}));return{publicKeys:n,services:i}}static normalizeJwk(e){let t=e.kty,n;if(t==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(t==="oct")n={k:e.k,kty:e.kty};else if(t==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(t==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${t}`);return n}},tye=(r=>(r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.secp256r1="secp256r1",r.X25519="X25519",r))(tye||{}),rye={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},hz="https://ion.tbd.engineering",nye=class W0 extends fb{static async create({keyManager:e=new Dc,options:t={}}={}){if(t.verificationMethods?.some(h=>!(h.algorithm in rye)))throw new Error("One or more verification method algorithms are not supported");let n=t.verificationMethods?.filter(h=>"id"in h).map(h=>h.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(t.services?.some(h=>!h.id||!h.type||!h.serviceEndpoint))throw new Error("One or more services are missing required properties");let i={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},a=[];for(let h of t.verificationMethods??[i]){let m=await e.generateKey({algorithm:h.algorithm}),y=await e.getPublicKey({keyUri:m});a.push({id:h.id,publicKeyJwk:y,purposes:h.purposes??["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let s=await e.generateKey({algorithm:"secp256k1"}),o=await e.getPublicKey({keyUri:s}),c=await e.generateKey({algorithm:"secp256k1"}),l=await e.getPublicKey({keyUri:c}),d=await B0.computeLongFormDidUri({recoveryKey:o,updateKey:l,services:t.services??[],verificationMethods:a}),{didDocument:u,didResolutionMetadata:f}=await W0.resolve(d,{gatewayUri:t.gatewayUri});if(u===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let p=new xs({uri:d,document:u,metadata:{published:!1,canonicalId:d.split(":",3).join(":"),recoveryKey:o,updateKey:l},keyManager:e});if(t.publish??!0){let h=await W0.publish({did:p,gatewayUri:t.gatewayUri});p.metadata=h.didDocumentMetadata}return p}static async getSigningMethod({didDocument:e,methodId:t}){let n=Vn.parse(e.id);if(n&&n.method!==this.methodName)throw new Xe("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(a=>a.id===(t??e.assertionMethod?.[0]));if(!i?.publicKeyJwk)throw new Xe("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async import({portableDid:e,keyManager:t=new Dc}){if(Vn.parse(e.uri)?.method!==W0.methodName)throw new Xe("methodNotSupported","Method not supported");return await xs.import({portableDid:e,keyManager:t})}static async publish({did:e,gatewayUri:t=hz}){let n=e.document.verificationMethod?.map(s=>({id:s.id,publicKeyJwk:s.publicKeyJwk,purposes:R7({didDocument:e.document,methodId:s.id})}))??[],i=await B0.createIonDocument({services:e.document.service??[],verificationMethods:n}),a=await B0.constructCreateRequest({ionDocument:i,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let s=B0.appendPathToUrl({baseUrl:t,path:"/operations"}),o=await fetch(s,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(3e4)});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:o.ok},didRegistrationMetadata:{}}}catch{return{didDocument:null,didDocumentMetadata:{published:!1},didRegistrationMetadata:{error:"internalError",errorMessage:`Failed to publish DID document for: ${e.uri}`}}}}static async resolve(e,t={}){let n=Vn.parse(e);if(!n)return{...is,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==W0.methodName)return{...is,didResolutionMetadata:{error:"methodNotSupported"}};let i=t?.gatewayUri??hz;try{let a=B0.appendPathToUrl({baseUrl:i,path:`/identifiers/${e}`}),s=await fetch(a,{signal:AbortSignal.timeout(3e4)});if(!s.ok)throw new Xe("notFound",`Unable to find DID document for: ${e}`);let{didDocument:o,didDocumentMetadata:c}=await s.json();return{...is,...o&&{didDocument:o},didDocumentMetadata:{published:c?.method?.published,...c}}}catch(a){if(!(a instanceof Xe))throw new Error(a);return{...is,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};nye.methodName="ion";TF=class J0 extends fb{static async create({keyManager:e=new Dc,options:t={}}={}){if(t.algorithm&&t.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(t.verificationMethods&&t.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=t.algorithm??t.verificationMethods?.[0]?.algorithm??"Ed25519",i=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:i}),s=rt.object(a).toBase64Url(),o=`did:${J0.methodName}:${s}`,c=(await J0.resolve(o)).didDocument;return new xs({uri:o,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let t=Vn.parse(e.id);if(t&&t.method!==this.methodName)throw new Xe("methodNotSupported",`Method not supported: ${t.method}`);let[n]=e.verificationMethod??[];if(!n?.publicKeyJwk)throw new Xe("internalError","A verification method intended for signing could not be determined from the DID Document");return n}static async import({portableDid:e,keyManager:t=new Dc}){if(Vn.parse(e.uri)?.method!==J0.methodName)throw new Xe("methodNotSupported","Method not supported");let n=await xs.import({portableDid:e,keyManager:t});if(n.document.verificationMethod.length!==1)throw new Xe("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,t){let n=Vn.parse(e),i;try{i=n?rt.base64Url(n.id).toObject():void 0}catch{}if(!n||!i)return{...is,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==J0.methodName)return{...is,didResolutionMetadata:{error:"methodNotSupported"}};let a={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},s=`${a.id}#0`;switch(a.verificationMethod=[{id:s,type:"JsonWebKey",controller:a.id,publicKeyJwk:i}],a.authentication=[s],a.assertionMethod=[s],a.capabilityInvocation=[s],a.capabilityDelegation=[s],a.keyAgreement=[s],i.use){case"sig":{delete a.keyAgreement;break}case"enc":{delete a.authentication,delete a.assertionMethod,delete a.capabilityInvocation,delete a.capabilityDelegation;break}}return{...is,didDocument:a}}};TF.methodName="jwk";Xo=TF,iye={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},J2=class Gy{static async jwkToMulticodec({jwk:e}){let t=[];e.crv&&(t.push(e.crv),e.d?t.push("private"):t.push("public"));let n=t.join(":"),i=Gy.JWK_TO_MULTICODEC[n];if(i===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:Ka.getCodeFromName({name:i}),name:i}}static keyCompressor(e){let t={"P-256":bs.compressPublicKey,secp256k1:es.compressPublicKey}[e];if(!t)throw new Xe("invalidPublicKeyType",`Unsupported curve: ${e}`);return t}static keyConverter(e){let t={Ed25519:ts,"P-256":bs,secp256k1:es}[e];if(!t)throw new Xe("invalidPublicKeyType",`Unsupported curve: ${e}`);return t}static async multicodecToJwk({code:e,name:t}){if(!(t?!e:e))throw new Error("Either 'name' or 'code' must be defined, but not both.");t=t===void 0?Ka.getNameFromCode({code:e}):t;let n=t,i=Gy.MULTICODEC_TO_JWK[n];if(i===void 0)throw new Error("Unsupported Multicodec to JWK conversion");return{...i}}static async publicKeyToMultibaseId({publicKey:e}){if(!(e?.crv&&e.crv in iye))throw new Xe("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let t=await Gy.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(t=await Gy.keyCompressor(e.crv)({publicKeyBytes:t}));let{name:n}=await Gy.jwkToMulticodec({jwk:e});return $7({keyBytes:t,multicodecName:n})}};J2.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},J2.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},J2.MULTICODEC_TO_JWK={"ed25519-pub":{crv:"Ed25519",kty:"OKP",x:""},"ed25519-priv":{crv:"Ed25519",kty:"OKP",x:"",d:""},"secp256k1-pub":{crv:"secp256k1",kty:"EC",x:"",y:""},"secp256k1-priv":{crv:"secp256k1",kty:"EC",x:"",y:"",d:""}};I2=J2,sye=(r=>(r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.secp256r1="secp256r1",r))(sye||{}),mz={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},IF=class Pf extends fb{static async create({keyManager:e=new Dc,options:t={}}={}){if(t.algorithm&&t.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(t.verificationMethods&&t.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=t.algorithm??t.verificationMethods?.[0]?.algorithm??"Ed25519",i=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:i}),s=await I2.publicKeyToMultibaseId({publicKey:a}),o=`did:${Pf.methodName}:${s}`,c=(await Pf.resolve(o,t)).didDocument;return new xs({uri:o,document:c,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let t=Vn.parse(e.id);if(t&&t.method!==this.methodName)throw new Xe("methodNotSupported",`Method not supported: ${t.method}`);let[n]=e.assertionMethod||[],i=e.verificationMethod?.find(a=>a.id===n);if(!i?.publicKeyJwk)throw new Xe("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async import({portableDid:e,keyManager:t=new Dc}){if(Vn.parse(e.uri)?.method!==Pf.methodName)throw new Xe("methodNotSupported","Method not supported");let n=await xs.import({portableDid:e,keyManager:t});if(n.document.verificationMethod.length!==1)throw new Xe("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,t){try{let n=await Pf.createDocument({didUri:e,options:t});return{...is,didDocument:n}}catch(n){if(!(n instanceof Xe))throw new Error(n);return{...is,didResolutionMetadata:{error:n.code,...n.message&&{errorMessage:n.message}}}}}static async createDocument({didUri:e,options:t={}}){let{defaultContext:n="https://www.w3.org/ns/did/v1",enableExperimentalPublicKeyTypes:i=!1,publicKeyFormat:a="JsonWebKey2020"}=t,s={id:""},o=Vn.parse(e);if(!o)throw new Xe("invalidDid",`Invalid DID URI: ${e}`);let c=o.id;if(o.method!==Pf.methodName)throw new Xe("methodNotSupported",`Method not supported: ${o.method}`);if(!Pf.validateIdentifier(o))throw new Xe("invalidDid",`Invalid DID URI: ${e}`);let l=await Pf.createSignatureMethod({didUri:e,multibaseValue:c,options:{enableExperimentalPublicKeyTypes:i,publicKeyFormat:a}});s.id=o.uri,s.verificationMethod=[l],s.authentication=[l.id],s.assertionMethod=[l.id],s.capabilityInvocation=[l.id],s.capabilityDelegation=[l.id];let d=[n];return D7({didDocument:s}).forEach(u=>{let f=mz[u];d.push(f)}),s["@context"]=d,s}static async createSignatureMethod({didUri:e,multibaseValue:t,options:n}){let{enableExperimentalPublicKeyTypes:i,publicKeyFormat:a}=n,s={id:"",type:"",controller:""},{keyBytes:o,multicodecCode:c,multicodecName:l}=B7({multibaseKeyId:t}),d=o.byteLength,u=I2.MULTICODEC_PUBLIC_KEY_LENGTH[c];if(d!==u)throw new Xe("invalidPublicKeyLength",`Expected ${d} bytes. Actual: ${u}`);let f=!1;switch(l){case"secp256k1-pub":f=await es.validatePublicKey({publicKeyBytes:o});break;case"ed25519-pub":f=await ts.validatePublicKey({publicKeyBytes:o});break}if(!f)throw new Xe("invalidPublicKey","Invalid public key detected.");s.id=`${e}#${t}`;try{new URL(s.id)}catch{throw new Xe("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(a in mz))throw new Xe("unsupportedPublicKeyType",`Unsupported format: ${a}`);if(i===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(a))throw new Xe("invalidPublicKeyType",`Specified '${a}' without setting enableExperimentalPublicKeyTypes to true.`);if(s.type=a,s.controller=e,a==="Ed25519VerificationKey2020"&&(s.publicKeyMultibase=t),a==="JsonWebKey2020"){let{crv:p}=await I2.multicodecToJwk({code:c});s.publicKeyJwk=await I2.keyConverter(p).bytesToPublicKey({publicKeyBytes:o})}return s}static validateIdentifier(e){let{method:t,id:n}=e,[i]=e.uri.split(":",1);return i==="did"&&t==="key"&&!0&&lC(n)==="String"&&n.startsWith("z")}};IF.methodName="key";mb=IF,oye=3e4,DF=class Z2 extends fb{static async create({keyManager:e=new Dc,options:t}){if(!t.domain)throw new Xe("invalidDid","The 'domain' option is required for did:web creation");if(t.algorithm&&t.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");let n=t.path?`${t.domain}:${t.path}`:t.domain,i=`did:${Z2.methodName}:${n}`;if(!Vn.parse(i))throw new Xe("invalidDid",`The constructed DID URI is invalid: ${i}`);let a=t.verificationMethods??[{algorithm:t.algorithm??"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]}],s={"@context":["https://www.w3.org/ns/did/v1"],id:i};for(let o=0;o<a.length;o++){let c=a[o],l=await e.generateKey({algorithm:c.algorithm}),d=await e.getPublicKey({keyUri:l}),u=c.id?.split("#").pop()??`key-${o}`,f=`${i}#${u}`;s.verificationMethod??=[],s.verificationMethod.push({id:f,type:"JsonWebKey",controller:c.controller??i,publicKeyJwk:d});for(let p of c.purposes??[])s[p]??=[],s[p].push(f)}return t.services&&(s.service=t.services.map(o=>({...o,id:`${i}#${o.id.split("#").pop()}`}))),new xs({uri:i,document:s,metadata:{published:!1},keyManager:e})}static async getSigningMethod({didDocument:e,methodId:t}){let n=Vn.parse(e.id);if(n&&n.method!==this.methodName)throw new Xe("methodNotSupported",`Method not supported: ${n.method}`);let i=Ws(t)??Ws(e.assertionMethod?.[0]),a=i?e.verificationMethod?.find(s=>Ws(s.id)===i):e.verificationMethod?.[0];if(!a?.publicKeyJwk)throw new Xe("internalError","A verification method intended for signing could not be determined from the DID Document");return a}static async import({portableDid:e,keyManager:t=new Dc}){if(Vn.parse(e.uri)?.method!==Z2.methodName)throw new Xe("methodNotSupported","Method not supported");return await xs.import({portableDid:e,keyManager:t})}static async resolve(e,t){let n=Vn.parse(e);if(!n)return{...is,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==Z2.methodName)return{...is,didResolutionMetadata:{error:"methodNotSupported"}};let i=`https://${n.id.replace(/:/g,"/")}`;i=decodeURIComponent(i);let a=n.id.includes(":")?`${i}/did.json`:`${i}/.well-known/did.json`;try{let s=await Oz(a,{signal:AbortSignal.timeout(oye)},{description:"did:web document URL"});if(!s.ok)throw new Error("HTTP error status code returned");let o=await s.json();return{...is,didDocument:o}}catch{return{...is,didResolutionMetadata:{error:"notFound"}}}}};DF.methodName="web";RF=DF,aye=vh(kz(),1),cye=vh(_z(),1),EE=class{constructor({db:r,location:e="DATA/DID_RESOLVERCACHE",ttl:t="15m"}={}){this.cache=r??new aye.Level(e),this.ttl=(0,cye.default)(t)}open(){return this.cache.open()}async get(r){try{let e=await this.cache.get(r),t=JSON.parse(e);if(Date.now()>=t.ttlMillis){this.cache.nextTick(()=>this.cache.del(r));return}else return t.value}catch(e){if(e.notFound)return;throw e}}set(r,e){let t={ttlMillis:Date.now()+this.ttl,value:e},n=JSON.stringify(t);return this.cache.put(r,n)}delete(r){return this.cache.del(r)}clear(){return this.cache.clear()}close(){return this.cache.close()}},dye=vh(_z(),1),SE=class{constructor({ttl:r="15m"}={}){this.cache=new cle.default({ttl:(0,dye.default)(r)})}async open(){}async get(r){if(!r)throw new Error("Key cannot be null or undefined");return this.cache.get(r)}async set(r,e){this.cache.set(r,e)}async delete(r){this.cache.delete(r)}async clear(){this.cache.clear()}async close(){}},lye={open(){return Promise.resolve()},get(r){return Promise.resolve(void 0)},set(r,e){return Promise.resolve()},delete(r){return Promise.resolve()},clear(){return Promise.resolve()},close(){return Promise.resolve()}},ag=class{constructor({cache:r,didResolvers:e}){this.didResolvers=new Map,this._inFlight=new Map,this.cache=r||lye;for(let t of e)this.didResolvers.set(t.methodName,t)}async open(){await this.cache.open()}async close(){await this.cache.close()}async resolve(r,e){let t=Vn.parse(r);if(!t)return{...is,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${r}`}};let n=this.didResolvers.get(t.method);if(!n)return{...is,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${t.method}`}};if(e!==void 0)return n.resolve(t.uri,e);let i=await this.cache.get(t.uri);if(i)return i;let a=this._inFlight.get(t.uri);if(a)return a;let s=(async()=>{let o=await n.resolve(t.uri,e);if(!o.didResolutionMetadata.error)try{await this.cache.set(t.uri,o)}catch{}return o})();this._inFlight.set(t.uri,s);try{return await s}finally{this._inFlight.delete(t.uri)}}async dereference(r,e){let t=Vn.parse(r);if(!t)return{dereferencingMetadata:{error:"invalidDidUrl"},contentStream:null,contentMetadata:{}};let{didDocument:n,didResolutionMetadata:i,didDocumentMetadata:a}=await this.resolve(t.uri);if(!n)return{dereferencingMetadata:{error:i.error},contentStream:null,contentMetadata:{}};if(!t.fragment||t.query)return{dereferencingMetadata:{contentType:"application/did+json"},contentStream:n,contentMetadata:a};let{service:s=[],verificationMethod:o=[]}=n,c=new Set([r,t.fragment,`#${t.fragment}`]),l;for(let d of o)if(c.has(d.id)){l=d;break}for(let d of s)if(c.has(d.id)){l=d;break}return l?{dereferencingMetadata:{contentType:"application/did+json"},contentStream:l,contentMetadata:i}:{dereferencingMetadata:{error:"notFound"},contentStream:null,contentMetadata:{}}}};});var cg,CF=G(()=>{"use strict";g();WI();VI();yr();zo();BU();jU();KU();Fo();$9();B9();V9();W9();J9();Z9();Y9();X9();m2();QR();Qo();ar();cg=class r{methodHandlers;didResolver;messageStore;dataStore;resumableTaskStore;stateIndex;tenantGate;eventLog;storageController;resumableTaskManager;_coreProtocols;ownsResolver;constructor(e){this.didResolver=e.didResolver,this.ownsResolver=e.ownsResolver??!1,this.tenantGate=e.tenantGate,this.messageStore=e.messageStore,this.dataStore=e.dataStore,this.resumableTaskStore=e.resumableTaskStore,this.stateIndex=e.stateIndex,this.eventLog=e.eventLog,this.storageController=new Uy({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new h2(e.resumableTaskStore,this.storageController),this._coreProtocols=new vy,this._coreProtocols.register(new et);let t={didResolver:this.didResolver,messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,resumableTaskManager:this.resumableTaskManager,coreProtocols:this._coreProtocols,eventLog:this.eventLog};this.methodHandlers={[ve.Messages+me.Read]:new Px(t),[ve.Messages+me.Subscribe]:new Sx(t),[ve.Messages+me.Sync]:new _x(t),[ve.Protocols+me.Configure]:new l2(t),[ve.Protocols+me.Query]:new f2(t),[ve.Records+me.Count]:new p2(t),[ve.Records+me.Delete]:new y2(t),[ve.Records+me.Query]:new g2(t),[ve.Records+me.Read]:new w2(t),[ve.Records+me.Subscribe]:new b2(t),[ve.Records+me.Write]:new P2(t)}}static async create(e){e.didResolver||(e.didResolver=new ag({didResolvers:[wo,Xo,mb,RF],cache:new SE}),e.ownsResolver=!0),e.tenantGate??=new by;let t=new r(e);return await t.open(),t}async open(){let e=this.didResolver;this.ownsResolver&&typeof e.open=="function"&&await e.open(),await this.messageStore.open(),await this.dataStore.open(),await this.resumableTaskStore.open(),await this.stateIndex.open(),await this.eventLog?.open(),await this.resumableTaskManager.resumeTasksAndWaitForCompletion()}async close(){await this.eventLog?.close(),await this.messageStore.close(),await this.dataStore.close(),await this.resumableTaskStore.close(),await this.stateIndex.close();let e=this.didResolver;this.ownsResolver&&typeof e.close=="function"&&await e.close()}get coreProtocols(){return this._coreProtocols}get storage(){return{messageStore:this.messageStore,stateIndex:this.stateIndex,eventLog:this.eventLog}}async processMessage(e,t,n={}){let i=await this.validateTenant(e)??await this.validateMessageIntegrity(t);if(i!==void 0)return i;let{dataStream:a,subscriptionHandler:s}=n,o=t.descriptor.interface+t.descriptor.method;return await this.methodHandlers[o].handle({tenant:e,message:t,dataStream:a,subscriptionHandler:s})}async validateTenant(e){let t=await this.tenantGate.isActiveTenant(e);if(!t.isActiveTenant)return{status:{code:401,detail:t.detail??`DID ${e} is not an active tenant.`}}}async validateMessageIntegrity(e){let t=e?.descriptor?.interface,n=e?.descriptor?.method;if(t===void 0||n===void 0)return{status:{code:400,detail:`Both interface and method must be present, interface: ${t}, method: ${n}`}};try{ye.validateJsonSchema(e)}catch(i){return mt(i,400)}}}});function uye(r){return new Promise((e,t)=>{if(r.aborted){t(r.reason);return}r.addEventListener("abort",()=>{t(r.reason)})})}async function Wn(r,e){return e?Promise.race([r,uye(e)]):r}var kE=G(()=>{"use strict";g()});import{Level as fye}from"level";async function Js(r,e){return new fye(r,{...e,keyEncoding:"utf8"})}var Na,Tf=G(()=>{"use strict";g();kE();Na=class r{config;db;constructor(e,t){this.config={createLevelDatabase:Js,...e},this.db=t}async open(){switch(await this.createLevelDatabase(),this.db.status){case"open":return;case"opening":return new Promise(e=>{this.db.once("open",e)});case"closing":return new Promise((e,t)=>{let n=()=>{this.db.open().then(e).catch(t)};this.db.once("closed",n)});case"closed":return this.db.open()}}async close(){if(this.db)switch(this.db.status){case"open":return this.db.close();case"opening":return new Promise((e,t)=>{let n=()=>{this.db.close().then(e).catch(t)};this.db.once("open",n)});case"closing":return new Promise(e=>{this.db.once("closed",e)});case"closed":return}}async partition(e){return await this.createLevelDatabase(),new r(this.config,this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding}))}async get(e,t){t?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),t?.signal);try{return await Wn(this.db.get(String(e)),t?.signal)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async has(e,t){return!!await this.get(e,t)}async*keys(e){e?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),e?.signal);for await(let t of this.db.keys())e?.signal?.throwIfAborted(),yield t}async*iterator(e,t){t?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),t?.signal);for await(let n of this.db.iterator(e))t?.signal?.throwIfAborted(),yield n}async put(e,t,n){return n?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),n?.signal),Wn(this.db.put(String(e),t),n?.signal)}async delete(e,t){return t?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),t?.signal),Wn(this.db.del(String(e)),t?.signal)}async isEmpty(e){for await(let t of this.keys(e))return!1;return!0}async clear(){await this.createLevelDatabase(),await this.db.clear(),await this.compactUnderlyingStorage()}async batch(e,t){return t?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),t?.signal),Wn(this.db.batch(e),t?.signal)}createPartitionOperation(e,t){return{...t,sublevel:this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}async compactUnderlyingStorage(e){e?.signal?.throwIfAborted(),await Wn(this.createLevelDatabase(),e?.signal);let t=this.sublevelRange;if(!t)return;let n=this.root;if(n.db.supports.additionalMethods.compactRange)return Wn(n.db.compactRange?.(...t),e?.signal)}get sublevelRange(){let e=this.db.prefix;if(!e)return;let t=e.slice(0,-1)+String.fromCharCode(e.charCodeAt(e.length-1)+1);return[e,t]}get root(){let e=this.db;for(let t=e.db;t&&t!==e;)e=t;return new r(this.config,e)}async createLevelDatabase(){this.db??=await this.config.createLevelDatabase(this.config.location,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}});var If,_E=G(()=>{"use strict";g();Cw();Tf();If=class r{config;db;constructor(e,t){this.config={createLevelDatabase:Js,...e},this.db=t??new Na({...this.config,valueEncoding:"binary"})}async open(){return this.db.open()}async close(){return this.db.close()}async partition(e){let t=await this.db.partition(e);return new r({...this.config,location:""},t)}async put(e,t,n){return await this.db.put(String(e),t,n),Yt.parse(e.toString())}async get(e,t){return await this.db.get(String(e),t)}async has(e,t){return this.db.has(String(e),t)}async delete(e,t){return this.db.delete(String(e),t)}async isEmpty(e){return this.db.isEmpty(e)}async*putMany(e,t){for await(let n of e)await this.put(n.cid,n.block,t),yield n.cid}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}async*getAll(e){let t=this.db.iterator({keys:!0,keyEncoding:"buffer"},e);for await(let[n,i]of t)yield{cid:Yt.decode(n),block:i}}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async clear(){return this.db.clear()}}});function pye(r){return r[Symbol.asyncIterator]!=null}function hye(r){if(pye(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 $F,BF=G(()=>{g();$F=hye});var OF,mye,jF,yye,MF,KF=G(()=>{g();Ff();nm();OF=0,mye="identity",jF=Ha,yye=r=>Zf(OF,jF(r)),MF={code:OF,name:mye,encode:jF,digest:yye}});var UF,gye,NF,LF=G(()=>{g();Dm();UF=An(ca(),1);dl();gye=async(r,e,t,n,i,a,s,o)=>{let c=await s.get(r,o),l=O_(c),d=l,u=t;for(;n.length>0;){let f=n[0];if(f in d){n.shift(),u=`${u}/${f}`;let p=Yt.asCID(d[f]);if(p!=null)return{entry:{type:"object",name:e,path:t,cid:r,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield l}},next:{cid:p,name:f,path:u,toResolve:n}};d=d[f]}else throw(0,UF.default)(new Error(`No property named ${f} found in cbor node ${r}`),"ERR_NO_PROP")}return{entry:{type:"object",name:e,path:t,cid:r,node:c,depth:a,size:BigInt(c.length),content:async function*(){yield l}}}},NF=gye});function wye(r,e,t,n){let i=BigInt(r.length),a=BigInt(e+i);return t>=a||n<e?new Uint8Array(0):(n>=e&&n<a&&(r=r.subarray(0,Number(n-e))),t>=e&&t<a&&(r=r.subarray(Number(t-e))),r)}var Ah,AE=G(()=>{g();Ah=wye});var yb,vye,dg,TE=G(()=>{g();yb=An(ca(),1),vye=(r,e=0,t=r)=>{let n=BigInt(r),i=BigInt(e??0),a=BigInt(t);if(a!==n&&(a=i+a),a>n&&(a=n),i<0n)throw(0,yb.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,yb.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(a<0n)throw(0,yb.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(a>n)throw(0,yb.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:i,end:a}},dg=vye});var qF,bye,Pye,zF,FF=G(()=>{g();qF=An(ca(),1);nm();ul();AE();TE();bye=r=>{async function*e(t={}){let{start:n,end:i}=dg(r.length,t.offset,t.length),a=Ah(r,0n,n,i);t.onProgress?.(new Rn("unixfs:exporter:progress:identity",{bytesRead:BigInt(a.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield a}return e},Pye=async(r,e,t,n,i,a,s,o)=>{if(n.length>0)throw(0,qF.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=e1(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:bye(c.digest),depth:a,size:BigInt(c.digest.length),node:c.digest}}},zF=Pye});var GF,xye,Eye,HF,VF=G(()=>{g();GF=An(ca(),1);ul();AE();TE();xye=r=>{async function*e(t={}){let{start:n,end:i}=dg(r.length,t.offset,t.length),a=Ah(r,0n,n,i);t.onProgress?.(new Rn("unixfs:exporter:progress:raw",{bytesRead:BigInt(a.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield a}return e},Eye=async(r,e,t,n,i,a,s,o)=>{if(n.length>0)throw(0,GF.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=await s.get(r,o);return{entry:{type:"raw",name:e,path:t,cid:r,content:xye(c),depth:a,size:BigInt(c.length),node:c}}},HF=Eye});var Sye,kye,WF,_ye,JF,ZF,YF=G(()=>{g();da();OA();jA();Sye=async function(r){return(await rP.encode(r)).slice(0,8).reverse()},kye=async(r,e,t)=>{await Promise.all(r.map(async n=>{if(n.Name==null)throw new Error("Unexpected Link without a Name");if(n.Name.length===2){let i=parseInt(n.Name,16);e._putObjectAt(i,new Vc({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(n.Name.substring(2),!0)}))},WF=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),_ye=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},JF=async(r,e,t,n,i)=>{if(n==null){let d=sP({hashFn:Sye});n={rootBucket:d,hamtDepth:1,lastBucket:d}}await kye(r.Links,n.lastBucket,n.rootBucket);let a=await n.rootBucket._findNewBucketAndPos(e),s=WF(a.pos),o=_ye(a);o.length>n.hamtDepth&&(n.lastBucket=o[n.hamtDepth],s=WF(n.lastBucket._posAtParent));let c=r.Links.find(d=>{if(d.Name==null)return!1;let u=d.Name.substring(0,2),f=d.Name.substring(2);return!(u!==s||f!==""&&f!==e)});if(c==null)return;if(c.Name!=null&&c.Name.substring(2)===e)return c.Hash;n.hamtDepth++;let l=await t.get(c.Hash,i);return r=ll(l),JF(r,e,t,n,i)},ZF=JF});function Aye(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var IE,y6=G(()=>{g();IE=Aye});function Tye(r){return r[Symbol.asyncIterator]!=null}function Iye(r,e){let t=0;if(Tye(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=IE(r),{value:i,done:a}=n.next();if(a===!0)return function*(){}();let s=e(i,t++);if(typeof s.then=="function")return async function*(){await s&&(yield i);for(let c of n)await e(c,t++)&&(yield c)}();let o=e;return function*(){s===!0&&(yield i);for(let c of n)o(c,t++)&&(yield c)}()}var XF,QF=G(()=>{g();y6();XF=Iye});function Dye(r){return r[Symbol.asyncIterator]!=null}function Rye(r,e){let t=0;if(Dye(r))return async function*(){for await(let c of r)yield e(c,t++)}();let n=IE(r),{value:i,done:a}=n.next();if(a===!0)return function*(){}();let s=e(i,t++);if(typeof s.then=="function")return async function*(){yield await s;for(let c of n)yield e(c,t++)}();let o=e;return function*(){yield s;for(let c of n)yield o(c,t++)}()}var lg,DE=G(()=>{g();y6();lg=Rye});function vo(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var RE=G(()=>{g()});async function*Th(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,i=new EventTarget,a=[],s=vo(),o=vo(),c=!1,l,d=!1;i.addEventListener("task-complete",()=>{o.resolve()}),Promise.resolve().then(async()=>{try{for await(let h of r){if(a.length===t&&(s=vo(),await s.promise),d)break;let m={done:!1};a.push(m),h().then(y=>{m.done=!0,m.ok=!0,m.value=y,i.dispatchEvent(new CE("task-complete"))},y=>{m.done=!0,m.err=y,i.dispatchEvent(new CE("task-complete"))})}c=!0,i.dispatchEvent(new CE("task-complete"))}catch(h){l=h,i.dispatchEvent(new CE("task-complete"))}});function u(){return n?a[0]?.done:!!a.find(h=>h.done)}function*f(){for(;a.length>0&&a[0].done;){let h=a[0];if(a.shift(),h.ok)yield h.value;else throw d=!0,s.resolve(),h.err;s.resolve()}}function*p(){for(;u();)for(let h=0;h<a.length;h++)if(a[h].done){let m=a[h];if(a.splice(h,1),h--,m.ok)yield m.value;else throw d=!0,s.resolve(),m.err;s.resolve()}}for(;;){if(u()||(o=vo(),await o.promise),l!=null||(n?yield*f():yield*p(),l!=null))throw l;if(c&&a.length===0)break}}var CE,$E=G(()=>{g();RE();CE=globalThis.CustomEvent??Event});var BE,ug,eG=G(()=>{g();BE=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}},ug=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new BE(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 BE(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()}}});function OE(r={}){return Cye(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 Cye(r,e){e=e??{};let t=e.onEnd,n=new ug,i,a,s,o=vo(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,v)=>{a=w=>{a=null,n.push(w);try{y(r(n))}catch(E){v(E)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{o.resolve(),o=vo()})}},l=y=>a!=null?a(y):(n.push(y),i),d=y=>(n=new ug,a!=null?a({error:y}):(n.push({error:y}),i)),u=y=>{if(s)return i;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})},f=y=>s?i:(s=!0,y!=null?d(y):l({done:!0})),p=()=>(n=new ug,f(),{done:!0}),h=y=>(f(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:h,push:u,end:f,get readableLength(){return n.size},onEmpty:async y=>{let v=y?.signal;if(v?.throwIfAborted(),n.isEmpty())return;let w,E;v!=null&&(w=new Promise((_,A)=>{E=()=>{A(new g6)},v.addEventListener("abort",E)}));try{await Promise.race([o.promise,w])}finally{E!=null&&v!=null&&v?.removeEventListener("abort",E)}}},t==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(y){return m.end(y),t!=null&&(t(y),t=void 0),i},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},i}var g6,w6=G(()=>{g();RE();eG();g6=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}});function $ye(r){return r.reason}async function tG(r,e,t){if(e==null)return r;let n=t?.translateError??$ye;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([r,new Promise((a,s)=>{i=()=>{s(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var rG=G(()=>{g()});function nG(){return new v6}var v6,iG=G(()=>{g();RE();rG();v6=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=vo(),this.haveNext=vo()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=vo(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=vo(),await tG(this.readNext.promise,t?.signal,t)}}});function Bye(r){return r[Symbol.asyncIterator]!=null}async function Oye(r,e,t){try{await Promise.all(r.map(async n=>{for await(let i of n)await e.push(i,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*jye(r){let e=new AbortController,t=nG();Oye(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Mye(r){for(let e of r)yield*e}function Kye(...r){let e=[];for(let t of r)Bye(t)||e.push(t);return e.length===r.length?Mye(e):jye(r)}var sG,oG=G(()=>{g();iG();sG=Kye});function fg(r,...e){if(r==null)throw new Error("Empty pipeline");if(b6(r)){let n=r;r=()=>n.source}else if(cG(r)||aG(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&b6(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++)b6(t[n])&&(t[n]=Nye(t[n]));return Uye(...t)}var Uye,aG,cG,b6,Nye,jE=G(()=>{g();w6();oG();Uye=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},aG=r=>r?.[Symbol.asyncIterator]!=null,cG=r=>r?.[Symbol.iterator]!=null,b6=r=>r==null?!1:r.sink!=null&&r.source!=null,Nye=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=OE({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let i,a=r.source;if(aG(a))i=async function*(){yield*a,n.end()};else if(cG(a))i=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return sG(n,i())}return r.source}});var Lye,dG,lG=G(()=>{g();QF();DE();$E();jE();ul();Lye=(r,e,t,n,i,a,s)=>{async function*o(c={}){let l=c.offset??0,d=c.length??e.Links.length,u=e.Links.slice(l,d);c.onProgress?.(new Rn("unixfs:exporter:walk:directory",{cid:r})),yield*fg(u,f=>lg(f,p=>async()=>{let h=p.Name??"",m=`${n}/${h}`;return(await i(p.Hash,h,m,[],a+1,s,c)).entry}),f=>Th(f,{ordered:!0}),f=>XF(f,p=>p!=null))}return o},dG=Lye});var fG=ke((zze,P6)=>{"use strict";g();var qye=Object.prototype.hasOwnProperty,Zs="~";function gb(){}Object.create&&(gb.prototype=Object.create(null),new gb().__proto__||(Zs=!1));function zye(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function uG(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var a=new zye(t,n||r,i),s=Zs?Zs+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],a]:r._events[s].push(a):(r._events[s]=a,r._eventsCount++),r}function ME(r,e){--r._eventsCount===0?r._events=new gb:delete r._events[e]}function Es(){this._events=new gb,this._eventsCount=0}Es.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)qye.call(t,n)&&e.push(Zs?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Es.prototype.listeners=function(e){var t=Zs?Zs+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,s=new Array(a);i<a;i++)s[i]=n[i].fn;return s};Es.prototype.listenerCount=function(e){var t=Zs?Zs+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Es.prototype.emit=function(e,t,n,i,a,s){var o=Zs?Zs+e:e;if(!this._events[o])return!1;var c=this._events[o],l=arguments.length,d,u;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,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,s),!0}for(u=1,d=new Array(l-1);u<l;u++)d[u-1]=arguments[u];c.fn.apply(c.context,d)}else{var f=c.length,p;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,i);break;default:if(!d)for(p=1,d=new Array(l-1);p<l;p++)d[p-1]=arguments[p];c[u].fn.apply(c[u].context,d)}}return!0};Es.prototype.on=function(e,t,n){return uG(this,e,t,n,!1)};Es.prototype.once=function(e,t,n){return uG(this,e,t,n,!0)};Es.prototype.removeListener=function(e,t,n,i){var a=Zs?Zs+e:e;if(!this._events[a])return this;if(!t)return ME(this,a),this;var s=this._events[a];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&ME(this,a);else{for(var o=0,c=[],l=s.length;o<l;o++)(s[o].fn!==t||i&&!s[o].once||n&&s[o].context!==n)&&c.push(s[o]);c.length?this._events[a]=c.length===1?c[0]:c:ME(this,a)}return this};Es.prototype.removeAllListeners=function(e){var t;return e?(t=Zs?Zs+e:e,this._events[t]&&ME(this,t)):(this._events=new gb,this._eventsCount=0),this};Es.prototype.off=Es.prototype.removeListener;Es.prototype.addListener=Es.prototype.on;Es.prefixed=Zs;Es.EventEmitter=Es;typeof P6<"u"&&(P6.exports=Es)});var x6,pG=G(()=>{g();x6=An(fG(),1)});function S6(r,e,t,n){let i,a=new Promise((s,o)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){s(r);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&o(mG(c)),c.addEventListener("abort",()=>{o(mG(c))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof t=="function"){try{s(t())}catch(d){o(d)}return}let c=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,l=t instanceof Error?t:new wb(c);typeof r.cancel=="function"&&r.cancel(),o(l)},e),(async()=>{try{s(await r)}catch(c){o(c)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return a.clear=()=>{clearTimeout(i),i=void 0},a}var wb,E6,hG,mG,yG=G(()=>{g();wb=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},E6=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},hG=r=>globalThis.DOMException===void 0?new E6(r):new DOMException(r),mG=r=>{let e=r.reason===void 0?hG("This operation was aborted."):r.reason;return e instanceof Error?e:hG(e)}});function k6(r,e,t){let n=0,i=r.length;for(;i>0;){let a=Math.trunc(i/2),s=n+a;t(r[s],e)<=0?(n=++s,i-=a+1):i=a}return n}var gG=G(()=>{g()});var Ih,Wl,_6,wG,vG=G(()=>{g();gG();Ih=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},_6=class{constructor(){Wl.set(this,[])}enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&Ih(this,Wl,"f")[this.size-1].priority>=t.priority){Ih(this,Wl,"f").push(n);return}let i=k6(Ih(this,Wl,"f"),n,(a,s)=>s.priority-a.priority);Ih(this,Wl,"f").splice(i,0,n)}dequeue(){let e=Ih(this,Wl,"f").shift();return e?.run}filter(e){return Ih(this,Wl,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return Ih(this,Wl,"f").length}};Wl=new WeakMap;wG=_6});var kn,Ve,Jn,bb,Pb,Rf,zE,xb,KE,Rc,vb,ea,UE,ta,Eb,Df,NE,bG,PG,SG,xG,EG,LE,A6,T6,FE,kG,qE,GE,I6,_G,AG=G(()=>{g();pG();yG();vG();kn=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Ve=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},GE=class extends Error{},I6=class extends x6.default{constructor(e){var t,n,i,a;if(super(),Jn.add(this),bb.set(this,void 0),Pb.set(this,void 0),Rf.set(this,0),zE.set(this,void 0),xb.set(this,void 0),KE.set(this,0),Rc.set(this,void 0),vb.set(this,void 0),ea.set(this,void 0),UE.set(this,void 0),ta.set(this,0),Eb.set(this,void 0),Df.set(this,void 0),NE.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:wG,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${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 \`${(a=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""}\` (${typeof e.interval})`);kn(this,bb,e.carryoverConcurrencyCount,"f"),kn(this,Pb,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),kn(this,zE,e.intervalCap,"f"),kn(this,xb,e.interval,"f"),kn(this,ea,new e.queueClass,"f"),kn(this,UE,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,kn(this,NE,e.throwOnTimeout===!0,"f"),kn(this,Df,e.autoStart===!1,"f")}get concurrency(){return Ve(this,Eb,"f")}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})`);kn(this,Eb,e,"f"),Ve(this,Jn,"m",FE).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:Ve(this,NE,"f"),...t},new Promise((n,i)=>{Ve(this,ea,"f").enqueue(async()=>{var a,s,o;kn(this,ta,(s=Ve(this,ta,"f"),s++,s),"f"),kn(this,Rf,(o=Ve(this,Rf,"f"),o++,o),"f");try{if(!((a=t.signal)===null||a===void 0)&&a.aborted)throw new GE("The task was aborted.");let c=e({signal:t.signal});t.timeout&&(c=S6(Promise.resolve(c),t.timeout)),t.signal&&(c=Promise.race([c,Ve(this,Jn,"m",kG).call(this,t.signal)]));let l=await c;n(l),this.emit("completed",l)}catch(c){if(c instanceof wb&&!t.throwOnTimeout){n();return}i(c),this.emit("error",c)}finally{Ve(this,Jn,"m",SG).call(this)}},t),this.emit("add"),Ve(this,Jn,"m",LE).call(this)})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return Ve(this,Df,"f")?(kn(this,Df,!1,"f"),Ve(this,Jn,"m",FE).call(this),this):this}pause(){kn(this,Df,!0,"f")}clear(){kn(this,ea,new(Ve(this,UE,"f")),"f")}async onEmpty(){Ve(this,ea,"f").size!==0&&await Ve(this,Jn,"m",qE).call(this,"empty")}async onSizeLessThan(e){Ve(this,ea,"f").size<e||await Ve(this,Jn,"m",qE).call(this,"next",()=>Ve(this,ea,"f").size<e)}async onIdle(){Ve(this,ta,"f")===0&&Ve(this,ea,"f").size===0||await Ve(this,Jn,"m",qE).call(this,"idle")}get size(){return Ve(this,ea,"f").size}sizeBy(e){return Ve(this,ea,"f").filter(e).length}get pending(){return Ve(this,ta,"f")}get isPaused(){return Ve(this,Df,"f")}};bb=new WeakMap,Pb=new WeakMap,Rf=new WeakMap,zE=new WeakMap,xb=new WeakMap,KE=new WeakMap,Rc=new WeakMap,vb=new WeakMap,ea=new WeakMap,UE=new WeakMap,ta=new WeakMap,Eb=new WeakMap,Df=new WeakMap,NE=new WeakMap,Jn=new WeakSet,bG=function(){return Ve(this,Pb,"f")||Ve(this,Rf,"f")<Ve(this,zE,"f")},PG=function(){return Ve(this,ta,"f")<Ve(this,Eb,"f")},SG=function(){var e;kn(this,ta,(e=Ve(this,ta,"f"),e--,e),"f"),Ve(this,Jn,"m",LE).call(this),this.emit("next")},xG=function(){Ve(this,Jn,"m",T6).call(this),Ve(this,Jn,"m",A6).call(this),kn(this,vb,void 0,"f")},EG=function(){let e=Date.now();if(Ve(this,Rc,"f")===void 0){let t=Ve(this,KE,"f")-e;if(t<0)kn(this,Rf,Ve(this,bb,"f")?Ve(this,ta,"f"):0,"f");else return Ve(this,vb,"f")===void 0&&kn(this,vb,setTimeout(()=>{Ve(this,Jn,"m",xG).call(this)},t),"f"),!0}return!1},LE=function(){if(Ve(this,ea,"f").size===0)return Ve(this,Rc,"f")&&clearInterval(Ve(this,Rc,"f")),kn(this,Rc,void 0,"f"),this.emit("empty"),Ve(this,ta,"f")===0&&this.emit("idle"),!1;if(!Ve(this,Df,"f")){let e=!Ve(this,Jn,"a",EG);if(Ve(this,Jn,"a",bG)&&Ve(this,Jn,"a",PG)){let t=Ve(this,ea,"f").dequeue();return t?(this.emit("active"),t(),e&&Ve(this,Jn,"m",A6).call(this),!0):!1}}return!1},A6=function(){Ve(this,Pb,"f")||Ve(this,Rc,"f")!==void 0||(kn(this,Rc,setInterval(()=>{Ve(this,Jn,"m",T6).call(this)},Ve(this,xb,"f")),"f"),kn(this,KE,Date.now()+Ve(this,xb,"f"),"f"))},T6=function(){Ve(this,Rf,"f")===0&&Ve(this,ta,"f")===0&&Ve(this,Rc,"f")&&(clearInterval(Ve(this,Rc,"f")),kn(this,Rc,void 0,"f")),kn(this,Rf,Ve(this,bb,"f")?Ve(this,ta,"f"):0,"f"),Ve(this,Jn,"m",FE).call(this)},FE=function(){for(;Ve(this,Jn,"m",LE).call(this););},kG=async function(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(new GE("The task was aborted."))},{once:!0})})},qE=async function(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})};_G=I6});async function TG(r,e,t,n,i,a,s){if(e instanceof Uint8Array){let l=Ah(e,n,i,a);t.push(l);return}if(e.Data==null)throw(0,Dh.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let o;try{o=bi.unmarshal(e.Data)}catch(l){throw(0,Dh.default)(l,"ERR_NOT_UNIXFS")}if(o.data!=null){let l=o.data,d=Ah(l,n,i,a);t.push(d),n+=BigInt(d.byteLength)}let c=[];if(e.Links.length!==o.blockSizes.length)throw(0,Dh.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let l=0;l<e.Links.length;l++){let d=e.Links[l],u=n,f=u+o.blockSizes[l];if((i>=u&&i<f||a>=u&&a<=f||i<u&&a>f)&&c.push({link:d,blockStart:n}),n=f,n>a)break}await fg(c,l=>lg(l,d=>async()=>{let u=await r.get(d.link.Hash,s);return{...d,block:u}}),l=>Th(l,{ordered:!0}),async l=>{for await(let{link:d,block:u,blockStart:f}of l){let p;switch(d.Hash.code){case Mw:p=ll(u);break;case xu:p=u;break;default:t.end((0,Dh.default)(new Error(`Unsupported codec: ${d.Hash.code}`),"ERR_NOT_UNIXFS"));return}let h=new _G({concurrency:1});h.on("error",m=>{t.end(m)}),h.add(async()=>{s.onProgress?.(new Rn("unixfs:exporter:walk:file",{cid:d.Hash})),await TG(r,p,t,f,i,a,s)}),await h.onIdle()}}),n>=a&&t.end()}var Dh,Fye,D6,IG=G(()=>{g();da();Dh=An(ca(),1);Pu();DE();$E();jE();w6();Gw();AG();ul();AE();TE();Fye=(r,e,t,n,i,a,s)=>{async function*o(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:d,end:u}=dg(l,c.offset,c.length);if(u===0n)return;let f=0n,p=u-d,h=OE();c.onProgress?.(new Rn("unixfs:exporter:walk:file",{cid:r})),TG(s,e,h,0n,d,u,c).catch(m=>{h.end(m)});for await(let m of h)if(m!=null){if(f+=BigInt(m.byteLength),f>p)throw h.end(),(0,Dh.default)(new Error("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect"),"ERR_OVER_READ");f===p&&h.end(),c.onProgress?.(new Rn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:p,fileSize:l})),yield m}if(f<p)throw(0,Dh.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return o},D6=Fye});async function*DG(r,e,t,n,i,a){let s=r.Links,o=fg(s,c=>lg(c,l=>async()=>{let d=l.Name!=null?l.Name.substring(2):null;if(d!=null&&d!==""){let u=await t(l.Hash,d,`${e}/${d}`,[],n+1,i,a);return{entries:u.entry==null?[]:[u.entry]}}else{let u=await i.get(l.Hash,a);return r=ll(u),a.onProgress?.(new Rn("unixfs:exporter:walk:hamt-sharded-directory",{cid:l.Hash})),{entries:DG(r,e,t,n,i,a)}}}),c=>Th(c,{ordered:!0}));for await(let{entries:c}of o)yield*c}var Gye,RG,CG=G(()=>{g();da();DE();$E();jE();ul();Gye=(r,e,t,n,i,a,s)=>{function o(c={}){return c.onProgress?.(new Rn("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),DG(e,n,i,a,s,c)}return o};RG=Gye});var Sb,Hye,Vye,Wye,$G,BG=G(()=>{g();da();Sb=An(ca(),1);Pu();YF();lG();IG();CG();Hye=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,Vye={raw:D6,file:D6,directory:dG,"hamt-sharded-directory":RG,metadata:(r,e,t,n,i,a,s)=>()=>[],symlink:(r,e,t,n,i,a,s)=>()=>[]},Wye=async(r,e,t,n,i,a,s,o)=>{let c=await s.get(r,o),l=ll(c),d,u;if(e==null&&(e=r.toString()),l.Data==null)throw(0,Sb.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{d=bi.unmarshal(l.Data)}catch(p){throw(0,Sb.default)(p,"ERR_NOT_UNIXFS")}if(t==null&&(t=e),n.length>0){let p;if(d?.type==="hamt-sharded-directory"?p=await ZF(l,n[0],s):p=Hye(l,n[0]),p==null)throw(0,Sb.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let h=n.shift(),m=`${t}/${h}`;u={cid:p,toResolve:n,name:h??"",path:m}}let f=Vye[d.type](r,l,d,t,i,a,s);if(f==null)throw(0,Sb.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return d.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:f,unixfs:d,depth:a,node:l,size:d.fileSize()},next:u}:{entry:{type:"file",name:e,path:t,cid:r,content:f,unixfs:d,depth:a,node:l,size:d.fileSize()},next:u}},$G=Wye});var OG,Jye,jG,MG,KG=G(()=>{g();Dm();da();OG=An(ca(),1);Gw();KF();LF();FF();VF();BG();Jye={[Mw]:$G,[xu]:HF,[gu]:NF,[MF.code]:zF},jG=async(r,e,t,n,i,a,s)=>{let o=Jye[r.code];if(o==null)throw(0,OG.default)(new Error(`No resolver for code ${r.code}`),"ERR_NO_RESOLVER");return o(r,e,t,n,jG,i,a,s)},MG=jG});async function*Xye(r,e,t={}){let{cid:n,toResolve:i}=Yye(r),a=n.toString(),s=a,o=i.length;for(;;){let c=await MG(n,a,s,i,o,e,t);if(c.entry==null&&c.next==null)throw(0,HE.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");if(c.entry!=null&&(yield c.entry),c.next==null)return;i=c.next.toResolve,n=c.next.cid,a=c.next.name,s=c.next.path}}async function UG(r,e,t={}){let n=await $F(Xye(r,e,t));if(n==null)throw(0,HE.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");return n}var HE,Zye,Yye,NG=G(()=>{g();HE=An(ca(),1);BF();dl();KG();Zye=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),Yye=r=>{if(r instanceof Uint8Array)return{cid:Yt.decode(r),toResolve:[]};let e=Yt.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=Zye(r);return{cid:Yt.parse(t[0]),toResolve:t.slice(1)}}throw(0,HE.default)(new Error(`Unknown path type ${r}`),"ERR_BAD_PATH")}});var R6,VE,Cf,LG=G(()=>{"use strict";g();_E();Tf();wu();NG();UA();R6=new TextEncoder,VE=new TextDecoder,Cf=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:Js,...e},this.blockstore=new If({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase})}async open(){await this.blockstore.open()}async close(){await this.blockstore.close()}async put(e,t,n,i){let a=await this.getRefsPartition(e,t),s=await a.get(n);if(s){await i.cancel();let{dataSize:u}=JSON.parse(VE.decode(s));return{dataSize:u}}let o=await this.getRefcountsPartition(),c=await o.get(n),l=c?JSON.parse(VE.decode(c)):{count:0,dataSize:0},d;if(l.count>0)await i.cancel(),d=l.dataSize;else{let u=await this.getBlocksPartition(n),f=Ww([{content:zt.asAsyncIterable(i)}],u,{cidVersion:1}),p;for await(p of f);d=Number(p.unixfs?.fileSize()??p.size)}return await a.put(n,R6.encode(JSON.stringify({dataSize:d}))),await o.put(n,R6.encode(JSON.stringify({count:l.count+1,dataSize:d}))),{dataSize:d}}async get(e,t,n){let a=await(await this.getRefsPartition(e,t)).get(n);if(!a)return;let{dataSize:s}=JSON.parse(VE.decode(a)),o=await this.getBlocksPartition(n);if(!await o.has(n))return;let d=(await UG(n,o)).content(),u=new ReadableStream({async pull(f){let p=await d.next();p.done?f.close():f.enqueue(p.value)}});return{dataSize:s,dataStream:u}}async delete(e,t,n){let i=await this.getRefsPartition(e,t);if(!await i.get(n))return;await i.delete(n);let s=await this.getRefcountsPartition(),o=await s.get(n);if(!o)return;let c=JSON.parse(VE.decode(o)),l=c.count-1;l<=0?(await(await this.getBlocksPartition(n)).clear(),await s.delete(n)):await s.put(n,R6.encode(JSON.stringify({count:l,dataSize:c.dataSize})))}async clear(){await this.blockstore.clear()}async getRefsPartition(e,t){return(await(await this.blockstore.db.partition("refs")).partition(e)).partition(t)}async getBlocksPartition(e){return(await this.blockstore.partition("blocks")).partition(e)}async getRefcountsPartition(){return this.blockstore.db.partition("refcounts")}}});async function qG(r,e,t){let n=`__compound:${t.name}__`;return(await r.partition(e)).partition(n)}function zG(r,e,t,n,i){let a=[];for(let l of t.properties){let d=e[l];if(d===void 0||Array.isArray(d))return;a.push(n(d))}let s=e[t.sortProperty];if(s===void 0||Array.isArray(s))return;let o=a.join(WE),c=n(s);return o+WE+c+i+r}function FG(r,e,t){let n=[];for(let i of e.properties){let a=r[i];if(a===void 0||typeof a=="object")return;n.push(t(a))}return n.join(WE)+WE}function GG(r,e,t,n,i,a){let s=zG(t.messageCid,t.indexes,n,i,a);if(s!==void 0)return VG(r,e,`__compound:${n.name}__`,{type:"put",key:s,value:JSON.stringify(t)})}function HG(r,e,t,n,i,a,s){let o=zG(t,n,i,a,s);if(o!==void 0)return VG(r,e,`__compound:${i.name}__`,{type:"del",key:o})}async function VG(r,e,t,n){return(await r.partition(e)).createPartitionOperation(t,n)}function C6(r,e,t){let n,i=0;for(let a of t){if(a.sortProperty!==e.sortProperty)continue;let s=!0;for(let o of a.properties){let c=r[o];if(c===void 0||typeof c=="object"){s=!1;break}}s&&a.properties.length>i&&(n=a,i=a.properties.length)}return n}async function WG(r,e,t,n,i,a,s,o,c){let{sortDirection:l=At.Ascending,cursor:d,limit:u}=n,f=FG(t,i,a);if(f===void 0)return o(e,[t],n,c);let p=await qG(r,e,i),h={};if(d===void 0)l===At.Ascending?(h.gt=f,h.lt=f+"\xFF"):(h.gt=f,h.lt=f+"\xFF",h.reverse=!0);else{let E=a(d.value),_=f+E+s+d.messageCid;l===At.Ascending?(h.gt=_,h.lt=f+"\xFF"):(h.lt=_,h.gt=f,h.reverse=!0)}let m=new Set(i.properties),y={},v=!1;for(let E in t)m.has(E)||(y[E]=t[E],v=!0);let w=[];for await(let[E,_]of p.iterator(h,c)){if(u!==void 0&&w.length===u)break;let A=JSON.parse(_);v&&!Xt.matchFilter(A.indexes,y)||w.push(A)}return w}async function JG(r,e,t,n,i,a,s){let o=FG(t,n,i);if(o===void 0)return(await a(e,[t],{sortProperty:n.sortProperty},s)).length;let c=await qG(r,e,n),l=new Set(n.properties),d=!1,u={};for(let h in t)l.has(h)||(u[h]=t[h],d=!0);let f={gt:o,lt:o+"\xFF"},p=0;if(d)for await(let[h,m]of c.iterator(f,s)){let y=JSON.parse(m);Xt.matchFilter(y.indexes,u)&&p++}else for await(let[h,m]of c.iterator(f,s))p++;return p}var WE,ZG=G(()=>{"use strict";g();gc();rd();WE=""});var YG,Rh,$6=G(()=>{"use strict";g();st();LA();rd();ZG();Tf();vt();gc();YG="index",Rh=class r{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:Js,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new Na({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"})}async open(){await this.db.open()}async close(){await this.db.close()}async clear(){await this.db.clear()}async put(e,t,n,i){if(bp(n))throw new ne(re.IndexMissingIndexableProperty,"Index must include at least one valid indexable property");let a={messageCid:t,indexes:n},s=[];for(let d in n){let u=n[d];if(Array.isArray(u))for(let f of u){let p=this.createPutIndexedItemOperation(e,a,d,f);s.push(p)}else{let f=this.createPutIndexedItemOperation(e,a,d,u);s.push(f)}}for(let d of this._compoundIndexes){let u=GG(this.db,e,a,d,r.encodeValue,r.delimiter);u!==void 0&&s.push(u)}let o=this.createOperationForIndexesLookupPartition(e,{type:"put",key:t,value:JSON.stringify(n)});s.push(o);let c=await Promise.all(s);await(await this.db.partition(e)).batch(c,i)}async delete(e,t,n){let i=[],a=await this.getIndexes(e,t);if(a===void 0)return;let s=this.createOperationForIndexesLookupPartition(e,{type:"del",key:t});i.push(s);for(let l in a){let d=a[l];if(Array.isArray(d))for(let u of d){let f=this.createDeleteIndexedItemOperation(e,t,l,u);i.push(f)}else{let u=this.createDeleteIndexedItemOperation(e,t,l,d);i.push(u)}}for(let l of this._compoundIndexes){let d=HG(this.db,e,t,a,l,r.encodeValue,r.delimiter);d!==void 0&&i.push(d)}let o=await Promise.all(i);await(await this.db.partition(e)).batch(o,n)}async createPutIndexedItemOperation(e,t,n,i){let{messageCid:a}=t,s=r.keySegmentJoin(r.encodeValue(i),a);return this.createOperationForIndexPartition(e,n,{type:"put",key:s,value:JSON.stringify(t)})}async createDeleteIndexedItemOperation(e,t,n,i){let a=r.keySegmentJoin(r.encodeValue(i),t);return this.createOperationForIndexPartition(e,n,{type:"del",key:a})}async createOperationForIndexPartition(e,t,n){let i=await this.db.partition(e),a=r.getIndexPartitionName(t);return i.createPartitionOperation(a,n)}async createOperationForIndexesLookupPartition(e,t){return(await this.db.partition(e)).createPartitionOperation(YG,t)}static getIndexPartitionName(e){return`__${e}__`}async getIndexPartition(e,t){let n=r.getIndexPartitionName(t);return(await this.db.partition(e)).partition(n)}async getIndexesLookupPartition(e){return(await this.db.partition(e)).partition(YG)}async query(e,t,n,i){if(t.length===1&&!bp(t[0])){let a=C6(t[0],n,this._compoundIndexes);if(a!==void 0)return WG(this.db,e,t[0],n,a,r.encodeValue,r.delimiter,this.queryWithIteratorPaging.bind(this),i)}return r.shouldQueryWithInMemoryPaging(t,n)?this.queryWithInMemoryPaging(e,t,n,i):this.queryWithIteratorPaging(e,t,n,i)}async count(e,t,n,i){if(t.length===1&&!bp(t[0])){let s=C6(t[0],{...n},this._compoundIndexes);if(s!==void 0)return JG(this.db,e,t[0],s,r.encodeValue,this.query.bind(this),i)}return(await this.query(e,t,{...n},i)).length}async queryWithIteratorPaging(e,t,n,i){let{cursor:a,limit:s}=n,o=a?this.createStartingKeyFromCursor(a):"",c=[];for await(let l of this.getIndexIterator(e,o,n,i)){if(s!==void 0&&s===c.length)break;let{indexes:d}=l;Xt.matchAnyFilter(d,t)&&c.push(l)}return c}async*getIndexIterator(e,t,n,i){let{sortProperty:a,sortDirection:s=At.Ascending,cursor:o}=n,c={gt:t};s===At.Descending&&(c.reverse=!0,o!==void 0&&(c.lt=t,delete c.gt));let l=await this.getIndexPartition(e,a);for await(let[d,u]of l.iterator(c,i)){let{indexes:f,messageCid:p}=JSON.parse(u);yield{indexes:f,messageCid:p}}}createStartingKeyFromCursor(e){let{messageCid:t,value:n}=e;return r.keySegmentJoin(r.encodeValue(n),t)}static createCursorFromLastArrayItem(e,t){if(e.length>0)return this.createCursorFromItem(e.at(-1),t)}static createCursorFromItem(e,t){let{messageCid:n,indexes:i}=e,a=i[t];if(a===void 0)throw new ne(re.IndexInvalidCursorSortProperty,`the sort property '${t}' is not defined within the given item.`);if(typeof a=="boolean"||Array.isArray(a))throw new ne(re.IndexInvalidCursorValueType,`only string or number values are supported for cursors, a(n) ${typeof a} was given.`);return{messageCid:n,value:a}}async queryWithInMemoryPaging(e,t,n,i){let{sortProperty:a,sortDirection:s=At.Ascending,cursor:o,limit:c}=n,l=o?this.createStartingKeyFromCursor(o):void 0,d=new Map;t.length===0&&(t=[{}]);try{for(let h of t)await this.executeSingleFilterQuery(e,h,a,d,i)}catch(h){if(h.code===re.IndexInvalidSortPropertyInMemory)return[]}let u=[...d.values()].sort((h,m)=>this.sortItems(h,m,a,s)),f=l===void 0?0:this.findCursorStartingIndex(u,s,a,l);if(f<0)return[];let p=c===void 0?void 0:f+c;return u.slice(f,p)}async executeSingleFilterQuery(e,t,n,i,a){let s=c=>{for(let l of c)if(!(i.has(l.messageCid)||!Xt.matchFilter(l.indexes,t))){if(l.indexes[n]===void 0)throw new ne(re.IndexInvalidSortPropertyInMemory,`invalid sort property ${n}`);i.set(l.messageCid,l)}};if(bp(t)){let c=await this.getAllItems(e,n);s(c);return}let o=DP.reduceFilter(t);for(let c in o){let l=o[c];if(Xt.isEqualFilter(l)){let d=await this.filterExactMatches(e,c,l,a);s(d)}else if(Xt.isOneOfFilter(l))for(let d of new Set(l)){let u=await this.filterExactMatches(e,c,d,a);s(u)}else if(Xt.isRangeFilter(l)){let d=await this.filterRangeMatches(e,c,l,a);s(d)}}}async getAllItems(e,t){let n=await this.getIndexPartition(e,t),i=[];for await(let[a,s]of n.iterator())i.push(JSON.parse(s));return i}async filterExactMatches(e,t,n,i){let a=r.keySegmentJoin(r.encodeValue(n)),s={gt:a},o=await this.getIndexPartition(e,t),c=[];for await(let[l,d]of o.iterator(s,i)){if(!l.startsWith(a))break;c.push(JSON.parse(d))}return c}async filterRangeMatches(e,t,n,i){let a={};for(let c in n){let l=c,d=r.encodeValue(n[l]);l==="lte"?a[l]=d+"\xFF":a[l]=d}a.gt===void 0&&a.gte===void 0&&(a.reverse=!0);let s=[],o=await this.getIndexPartition(e,t);for await(let[c,l]of o.iterator(a,i))"gt"in n&&this.extractIndexValueFromKey(c)===r.encodeValue(n.gt)||s.push(JSON.parse(l));return s}sortItems(e,t,n,i){let a=e.indexes[n],s=t.indexes[n],o=r.encodeValue(a)+e.messageCid,c=r.encodeValue(s)+t.messageCid;return i===At.Ascending?Jw(o,c):Jw(c,o)}findCursorStartingIndex(e,t,n,i){let a=c=>{let{messageCid:l,indexes:d}=c,u=d[n],f=r.keySegmentJoin(r.encodeValue(u),l);return t===At.Ascending?f>i:f<i},s=0,o=e.length;for(;s<o;){let c=s+o>>>1;a(e[c])?o=c:s=c+1}return s<e.length?s:-1}async getIndexes(e,t){let i=await(await this.getIndexesLookupPartition(e)).get(t);if(i!==void 0)return JSON.parse(i)}extractIndexValueFromKey(e){let[t]=e.split(r.delimiter);return t}static delimiter="\0";static keySegmentJoin(...e){return e.join(r.delimiter)}static encodeNumberValue(e){let t=Number.MAX_SAFE_INTEGER,n="!",i=String(Number.MAX_SAFE_INTEGER).length,a=e<0?n:"",s=e<0?t:0;return a+String(e+s).padStart(i,"0")}static encodeValue(e){switch(typeof e){case"number":return this.encodeNumberValue(e);default:return JSON.stringify(e)}}static shouldQueryWithInMemoryPaging(e,t){for(let n of e)if(!r.isFilterConcise(n,t))return!1;return!0}static isFilterConcise(e,t){return e.recordId!==void 0?!0:t.cursor!==void 0?!1:e.protocolPath!==void 0||e.contextId!==void 0||e.parentId!==void 0||e.schema!==void 0}}});function JE({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*Qye(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],a=Yt.asCID(n);a?yield[i.join("/"),a]:typeof n=="object"&&(yield*B6(n,i))}else{let t=Yt.asCID(e);t?yield[r.join("/"),t]:yield*B6(e,r)}}function*B6(r,e){if(r==null||r instanceof Uint8Array)return;let t=Yt.asCID(r);t&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let a=[...e,n];yield*Qye(a,i)}}function*ege(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&!Yt.asCID(n)&&(yield*O6(n,i))}else yield*O6(e,r)}function*O6(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!Yt.asCID(n)&&(yield*ege(i,n))}}function tge(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let a=Yt.asCID(t);if(a)return{value:a,remaining:e.slice(n+1).join("/")}}return{value:t}}async function XG({value:r,codec:e,hasher:t}){if(typeof r>"u")throw new Error('Missing required argument "value"');if(!e||!t)throw new Error("Missing required argument: codec or hasher");let n=e.encode(r),i=await t.digest(n),a=Yt.create(1,e.code,i);return new ZE({value:r,bytes:n,cid:a})}async function QG({bytes:r,codec:e,hasher:t}){if(!r)throw new Error('Missing required argument "bytes"');if(!e||!t)throw new Error("Missing required argument: codec or hasher");let n=e.decode(r),i=await t.digest(r),a=Yt.create(1,e.code,i);return new ZE({value:n,bytes:r,cid:a})}var ZE,eH=G(()=>{g();Cw();L_();ZE=class{constructor({cid:e,bytes:t,value:n}){if(!e||!t||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:JE(),bytes:JE(),value:JE(),asBlock:JE()})}links(){return B6(this.value,[])}tree(){return O6(this.value,[])}get(e="/"){return tge(this.value,e.split("/").filter(Boolean))}}});var nge,$f,tH=G(()=>{"use strict";g();eH();Dm();_E();fl();dl();Tf();kE();$6();yr();Ql();rd();nge=[{name:"protocol-protocolPath-messageTimestamp",properties:["protocol","protocolPath"],sortProperty:"messageTimestamp"},{name:"protocol-protocolPath-dateCreated",properties:["protocol","protocolPath"],sortProperty:"dateCreated"},{name:"schema-messageTimestamp",properties:["schema"],sortProperty:"messageTimestamp"},{name:"schema-dateCreated",properties:["schema"],sortProperty:"dateCreated"},{name:"protocol-contextId-messageTimestamp",properties:["protocol","contextId"],sortProperty:"messageTimestamp"}],$f=class r{config;blockstore;index;constructor(e={}){this.config={blockstoreLocation:"MESSAGESTORE",indexLocation:"INDEX",createLevelDatabase:Js,...e},this.blockstore=new If({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new Rh({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??nge})}async open(){await this.blockstore.open(),await this.index.open()}async close(){await this.blockstore.close(),await this.index.close()}async get(e,t,n){n?.signal?.throwIfAborted();let i=await Wn(this.blockstore.partition(e),n?.signal),a=Yt.parse(t),s=await i.get(a,n);return s?(await Wn(QG({bytes:s,codec:cl,hasher:On}),n?.signal)).value:void 0}async query(e,t,n,i,a){a?.signal?.throwIfAborted();let s=r.buildQueryOptions(n,i),o=await this.index.query(e,t,s,a),c;i?.limit!==void 0&&i.limit<o.length&&(o.splice(-1),c=Rh.createCursorFromLastArrayItem(o,s.sortProperty));let l=[];for(let d=0;d<o.length;d++){let{messageCid:u}=o[d],f=await this.get(e,u,a);f&&l.push(f)}return{messages:l,cursor:c}}async count(e,t,n,i){i?.signal?.throwIfAborted();let a=r.buildQueryOptions(n);return this.index.count(e,t,a,i)}static buildQueryOptions(e={},t={}){let{limit:n,cursor:i}=t,{dateCreated:a,datePublished:s,messageTimestamp:o}=e,c=At.Ascending,l="messageTimestamp";return a!==void 0?l="dateCreated":s!==void 0?l="datePublished":o!==void 0&&(l="messageTimestamp"),e[l]!==void 0&&(c=e[l]),n!==void 0&&n>0&&(n=n+1),{sortDirection:c,sortProperty:l,limit:n,cursor:i}}async delete(e,t,n){n?.signal?.throwIfAborted();let i=await Wn(this.blockstore.partition(e),n?.signal),a=Yt.parse(t);await i.delete(a,n),await this.index.delete(e,t,n)}async put(e,t,n,i){i?.signal?.throwIfAborted();let a=await Wn(this.blockstore.partition(e),i?.signal),s=await Wn(XG({value:t,codec:cl,hasher:On}),i?.signal),o=ur.parseCid(await ye.getCid(t));await a.put(o,s.bytes,i);let c=o.toString();await this.index.put(e,c,n,i)}async clear(){await this.blockstore.clear(),await this.index.clear()}}});var Bf,rH=G(()=>{"use strict";g();fl();Tf();Bf=class r{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:Js,...e},this.db=new Na({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"})}async open(){await this.db.open()}async close(){await this.db.close()}async register(e,t){let n=await ur.computeCid(e),i={id:n,timeout:Date.now()+t*1e3,retryCount:0,task:e};return await this.db.put(n,JSON.stringify(i)),i}async grab(e){let t=[];for await(let[n,i]of this.db.iterator()){let a=JSON.parse(i);if(Date.now()>=a.timeout&&(a.timeout=Date.now()+r.taskTimeoutInSeconds*1e3,a.retryCount++,await this.db.put(a.id,JSON.stringify(a)),t.push(a)),t.length>=e)break}return t}async read(e){let t=await this.db.get(e);if(t)return JSON.parse(t)}async extend(e,t){let n=await this.db.get(e);if(n){let i=JSON.parse(n);i.timeout=Date.now()+t*1e3,await this.db.put(i.id,JSON.stringify(i))}}async delete(e){return this.db.delete(e)}async clear(){await this.db.clear()}}});function nH(r){return{all:r=r||new Map,on:function(e,t){var n=r.get(e);n?n.push(t):r.set(e,[t])},off:function(e,t){var n=r.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):r.set(e,[]))},emit:function(e,t){var n=r.get(e);n&&n.slice().map(function(i){i(t)}),(n=r.get("*"))&&n.slice().map(function(i){i(e,t)})}}}var iH=G(()=>{g()});var sH,Of,oH=G(()=>{"use strict";g();iH();gc();vt();sH="events",Of=class r{emitter=nH();isOpen=!1;errorHandler=e=>{console.error("event log error",e)};maxEventsPerTenant;tenantLogs=new Map;tenantSeqs=new Map;epoch;constructor(e={}){this.maxEventsPerTenant=e.maxEventsPerTenant??1e4,this.epoch=crypto.randomUUID(),e.errorHandler&&(this.errorHandler=e.errorHandler)}async getStreamId(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(n);return Array.from(i.slice(0,8),a=>a.toString(16).padStart(2,"0")).join("")}async buildToken(e,t,n){return{streamId:await this.getStreamId(e),epoch:this.epoch,position:String(t),messageCid:n}}async validateCursor(e,t){let n=await this.getStreamId(e),i;if(t.streamId!==n)i="stream_mismatch";else if(t.epoch===this.epoch){let c=this.tenantLogs.get(e);if(c!==void 0&&c.size>0){let l=c.keys().next().value;if(r.parsePosition(t.position)<l-1)i="token_too_old";else return}else return}else i="epoch_mismatch";let a=await this.getReplayBounds(e),s={requested:t,oldestAvailable:a?.oldest??t,latestAvailable:a?.latest??t,reason:i},o=new ne(re.EventLogProgressGap,`progress token gap: ${i}`);throw o.gapInfo=s,o}async open(){this.isOpen=!0}async close(){this.isOpen=!1,this.emitter.all.clear(),this.tenantLogs.clear(),this.tenantSeqs.clear()}async emit(e,t,n,i){if(!this.isOpen){this.errorHandler(new ne(re.EventLogNotOpenError,"a message emitted when EventLog is closed"));return}let s=(this.tenantSeqs.get(e)??0)+1;this.tenantSeqs.set(e,s);let o=this.tenantLogs.get(e);if(o===void 0&&(o=new Map,this.tenantLogs.set(e,o)),o.set(s,{event:t,indexes:n,messageCid:i}),o.size>this.maxEventsPerTenant){let l=o.size-this.maxEventsPerTenant,d=0;for(let u of o.keys()){if(d>=l)break;o.delete(u),d++}}let c=`${e}_${sH}`;return this.emitter.emit(c,{tenant:e,event:t,indexes:n,seq:s,messageCid:i}),this.buildToken(e,s,i)}async read(e,t={}){let{cursor:n,limit:i,filters:a}=t;n!==void 0&&await this.validateCursor(e,n);let s=n===void 0?void 0:r.parsePosition(n.position),o=this.tenantLogs.get(e);if(o===void 0||o.size===0)return{events:[],cursor:n};let c=[],l=i??Number.MAX_SAFE_INTEGER;for(let[d,u]of o)if(!(s!==void 0&&d<=s)&&!(a!==void 0&&a.length>0&&!Xt.matchAnyFilter(u.indexes,a))&&(c.push({seq:d,event:u.event,indexes:u.indexes,messageCid:u.messageCid}),c.length>=l))break;if(c.length>0){let d=c[c.length-1],u=await this.buildToken(e,d.seq,d.messageCid);return{events:c,cursor:u}}return{events:c,cursor:n}}static parsePosition(e){try{let t=BigInt(e);if(t<0n)throw new ne(re.EventLogNotOpenError,`invalid cursor position: '${e}'`);return Number(t)}catch(t){throw t instanceof ne?t:new ne(re.EventLogNotOpenError,`invalid cursor position: '${e}'`)}}async subscribe(e,t,n,i){let a=`${e}_${sH}`,{cursor:s,filters:o}=i??{},c=async d=>this.buildToken(e,d.seq,d.messageCid);if(s!==void 0){await this.validateCursor(e,s);let d=r.parsePosition(s.position),u=[],f=!1,p=v=>{o!==void 0&&o.length>0&&!Xt.matchAnyFilter(v.indexes,o)||(f?c(v).then(w=>{n({type:"event",cursor:w,event:v.event})}):u.push({event:v.event,seq:v.seq,messageCid:v.messageCid}))};this.emitter.on(a,p);let h=await this.read(e,{cursor:s,filters:o}),m=h.cursor??s,y=h.cursor===void 0?d:r.parsePosition(h.cursor.position);for(let v of h.events){let w=await this.buildToken(e,v.seq,v.messageCid??"");n({type:"event",cursor:w,event:v.event})}f=!0;for(let v of u)if(v.seq>y){let w=await this.buildToken(e,v.seq,v.messageCid);n({type:"event",cursor:w,event:v.event})}return n({type:"eose",cursor:m}),{id:t,close:async()=>{this.emitter.off(a,p)}}}let l=d=>{o!==void 0&&o.length>0&&!Xt.matchAnyFilter(d.indexes,o)||c(d).then(u=>{n({type:"event",cursor:u,event:d.event})})};return this.emitter.on(a,l),{id:t,close:async()=>{this.emitter.off(a,l)}}}async getReplayBounds(e){let t=this.tenantLogs.get(e);if(t===void 0||t.size===0)return;let n=[...t.keys()],i=n[0],a=n[n.length-1],s=t.get(i),o=t.get(a),c=await this.buildToken(e,i,s.messageCid),l=await this.buildToken(e,a,o.messageCid);return{oldest:c,latest:l}}async trim(e,t){let n=this.tenantLogs.get(e);if(n!==void 0)if(typeof t=="number")for(let i of n.keys())if(i<t)n.delete(i);else break;else for(let[i,a]of n)(a.indexes.messageTimestamp??"")<t&&n.delete(i)}}});var pg,j6=G(()=>{"use strict";g();Ju();pg=class{db;nodesPartition;metaPartition;initialized=!1;constructor(e){this.db=e}async open(){this.nodesPartition=await this.db.partition("nodes"),this.metaPartition=await this.db.partition("meta"),this.initialized=!0}async close(){this.initialized=!1}async clear(){await this.db.clear(),this.nodesPartition=await this.db.partition("nodes"),this.metaPartition=await this.db.partition("meta")}async getNode(e){this.ensureInitialized();let t=on(e),n=await this.nodesPartition.get(t);if(n!==void 0)return this.deserializeNode(JSON.parse(n))}async putNode(e,t){this.ensureInitialized();let n=on(e),i=this.serializeNode(t);await this.nodesPartition.put(n,JSON.stringify(i))}async deleteNode(e){this.ensureInitialized();let t=on(e);await this.nodesPartition.delete(t)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return Wu(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",on(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:on(e.leftHash),rightHash:on(e.rightHash)}:{type:"leaf",keyHash:on(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:Wu(e.leftHash),rightHash:Wu(e.rightHash)}:{type:"leaf",keyHash:Wu(e.keyHash),valueCid:e.valueCid}}}});var hg,M6=G(()=>{"use strict";g();Ju();hg=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await Il()}async close(){await this.store.close()}async clear(){await this.store.clear()}async getRoot(){let e=await this.store.getRoot();return e===void 0?this.defaultHashes[0]:e}async insert(e){let t=await Vu(e),n=await xy(t,e),i={type:"leaf",keyHash:t,valueCid:e};await this.store.putNode(n,i);let a=await this.getRoot(),s=await this.insertAtNode(a,t,n,i,0);return await this.store.setRoot(s),s}async delete(e){let t=await Vu(e),n=await this.getRoot(),i=await this.deleteAtNode(n,t,0);return await this.store.setRoot(i),i}async has(e){let t=await Vu(e),n=await this.getRoot();return this.existsAtNode(n,t,0)}async getProof(e){let t=await Vu(e),n=await this.getRoot();return this.generateProof(n,t,0)}async getSubtreeHash(e){let t=await this.getRoot();for(let n=0;n<e.length;n++){if(sn(t,this.defaultHashes[n]))return this.defaultHashes[e.length];let i=await this.store.getNode(t);if(i===void 0||i.type==="leaf")return i?.type==="leaf"?this.computeSubtreeHashForLeaf(i,n,e):this.defaultHashes[e.length];let a=i;e[n]?t=a.rightHash:t=a.leftHash}return t}async getLeaves(e){let t=await this.getRoot();for(let n=0;n<e.length;n++){if(sn(t,this.defaultHashes[n]))return[];let i=await this.store.getNode(t);if(i===void 0)return[];if(i.type==="leaf")return this.leafMatchesPrefix(i.keyHash,e)?[i.valueCid]:[];let a=i;e[n]?t=a.rightHash:t=a.leftHash}return this.collectLeaves(t,e.length)}async diff(e){let t=await this.getRoot(),n=await e.getRoot();if(sn(t,n))return{onlyLocal:[],onlyRemote:[]};let i=[],a=[];return await this.diffAtNode(t,n,0,this,e,i,a),{onlyLocal:i,onlyRemote:a}}async insertAtNode(e,t,n,i,a){if(a>=hs||sn(e,this.defaultHashes[a]))return n;let s=await this.store.getNode(e);if(s===void 0)return n;if(s.type==="leaf")return sn(s.keyHash,t)?(await this.store.deleteNode(e),n):this.splitLeaves(s,e,i,n,a);let o=s,c=lo(t,a),l,d;c?(l=o.leftHash,d=await this.insertAtNode(o.rightHash,t,n,i,a+1)):(l=await this.insertAtNode(o.leftHash,t,n,i,a+1),d=o.rightHash);let u=await Dl(l,d);if(!sn(u,e)){let f={type:"internal",leftHash:l,rightHash:d};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async splitLeaves(e,t,n,i,a){let s=a;for(;s<hs&&lo(e.keyHash,s)===lo(n.keyHash,s);)s++;if(s>=hs)return i;let o=lo(e.keyHash,s),c,l;o?(c=i,l=t):(c=t,l=i);let d=await Dl(c,l);await this.store.putNode(d,{type:"internal",leftHash:c,rightHash:l});for(let u=s-1;u>=a;u--){let f=lo(e.keyHash,u),p=this.defaultHashes[u+1],h,m;f?(h=p,m=d):(h=d,m=p),d=await Dl(h,m),await this.store.putNode(d,{type:"internal",leftHash:h,rightHash:m})}return d}async deleteAtNode(e,t,n){if(n>=hs)return this.defaultHashes[hs];if(sn(e,this.defaultHashes[n]))return e;let i=await this.store.getNode(e);if(i===void 0)return this.defaultHashes[n];if(i.type==="leaf")return sn(i.keyHash,t)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let a=i,s=lo(t,n),o,c;if(s?(o=a.leftHash,c=await this.deleteAtNode(a.rightHash,t,n+1)):(o=await this.deleteAtNode(a.leftHash,t,n+1),c=a.rightHash),sn(o,this.defaultHashes[n+1])&&sn(c,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let l=sn(o,this.defaultHashes[n+1]),d=sn(c,this.defaultHashes[n+1]);if(l||d){let f=l?c:o;if((await this.store.getNode(f))?.type==="leaf")return await this.store.deleteNode(e),f}let u=await Dl(o,c);if(!sn(u,e)){let f={type:"internal",leftHash:o,rightHash:c};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async existsAtNode(e,t,n){if(n>=hs||sn(e,this.defaultHashes[n]))return!1;let i=await this.store.getNode(e);if(i===void 0)return!1;if(i.type==="leaf")return sn(i.keyHash,t);let a=i;return lo(t,n)?this.existsAtNode(a.rightHash,t,n+1):this.existsAtNode(a.leftHash,t,n+1)}async generateProof(e,t,n){if(n>=hs)return{siblings:[],leafNode:void 0,depth:n};if(sn(e,this.defaultHashes[n]))return{siblings:[],leafNode:void 0,depth:n};let i=await this.store.getNode(e);if(i===void 0)return{siblings:[],leafNode:void 0,depth:n};if(i.type==="leaf")return{siblings:[],leafNode:i,depth:n};let a=i,s=lo(t,n),o,c;s?(o=a.rightHash,c=a.leftHash):(o=a.leftHash,c=a.rightHash);let l=await this.generateProof(o,t,n+1);return l.siblings.unshift(c),l}async computeSubtreeHashForLeaf(e,t,n){for(let i=t;i<n.length;i++)if(lo(e.keyHash,i)!==n[i])return this.defaultHashes[n.length];return await xy(e.keyHash,e.valueCid)}leafMatchesPrefix(e,t){for(let n=0;n<t.length;n++)if(lo(e,n)!==t[n])return!1;return!0}async collectLeaves(e,t){if(t>=hs||sn(e,this.defaultHashes[t]))return[];let n=await this.store.getNode(e);if(n===void 0)return[];if(n.type==="leaf")return[n.valueCid];let i=n,a=await this.collectLeaves(i.leftHash,t+1),s=await this.collectLeaves(i.rightHash,t+1);return[...a,...s]}async diffAtNode(e,t,n,i,a,s,o){if(sn(e,t)||n>=hs)return;let c=sn(e,this.defaultHashes[n]),l=sn(t,this.defaultHashes[n]);if(c&&!l){let f=await a.collectLeaves(t,n);o.push(...f);return}if(!c&&l){let f=await i.collectLeaves(e,n);s.push(...f);return}let d=await i.store.getNode(e),u=await a.store.getNode(t);if(d?.type==="leaf"&&u?.type==="leaf"){sn(d.keyHash,u.keyHash)?d.valueCid!==u.valueCid&&(s.push(d.valueCid),o.push(u.valueCid)):(s.push(d.valueCid),o.push(u.valueCid));return}if(d?.type==="leaf"){let f=await a.collectLeaves(t,n),p=d.valueCid;new Set(f).has(p)||s.push(p);for(let m of f)m!==p&&o.push(m);return}if(u?.type==="leaf"){let f=await i.collectLeaves(e,n),p=u.valueCid;new Set(f).has(p)||o.push(p);for(let m of f)m!==p&&s.push(m);return}if(d?.type==="internal"&&u?.type==="internal"){await this.diffAtNode(d.leftHash,u.leftHash,n+1,i,a,s,o),await this.diffAtNode(d.rightHash,u.rightHash,n+1,i,a,s,o);return}if(d===void 0){let f=await a.collectLeaves(t,n);o.push(...f)}if(u===void 0){let f=await i.collectLeaves(e,n);s.push(...f)}}}});var jf,aH=G(()=>{"use strict";g();Ju();j6();M6();Tf();jf=class{config;db;globalTrees=new Map;protocolTrees=new Map;constructor(e){this.config={location:"STATEINDEX",createLevelDatabase:Js,...e}}async open(){this.db=new Na({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await Il()}async close(){this.globalTrees.clear(),this.protocolTrees.clear(),await this.db.close()}async clear(){this.globalTrees.clear(),this.protocolTrees.clear(),await this.db.clear()}async insert(e,t,n){await(await this.getGlobalTree(e)).insert(t);let a=n.protocol;a!==void 0&&await(await this.getProtocolTree(e,a)).insert(t),await this.storeIndexes(e,t,n)}async delete(e,t){let n=await this.getGlobalTree(e);for(let i of t){let a=await this.getStoredIndexes(e,i);if(await n.delete(i),a!==void 0){let s=a.protocol;s!==void 0&&await(await this.getProtocolTree(e,s)).delete(i)}await this.deleteStoredIndexes(e,i)}}async getRoot(e){return(await this.getGlobalTree(e)).getRoot()}async getProtocolRoot(e,t){return(await this.getProtocolTree(e,t)).getRoot()}async getSubtreeHash(e,t){return(await this.getGlobalTree(e)).getSubtreeHash(t)}async getProtocolSubtreeHash(e,t,n){return(await this.getProtocolTree(e,t)).getSubtreeHash(n)}async getLeaves(e,t){return(await this.getGlobalTree(e)).getLeaves(t)}async getProtocolLeaves(e,t,n){return(await this.getProtocolTree(e,t)).getLeaves(n)}getGlobalTree(e){let t=this.globalTrees.get(e);return t!==void 0||(t=this.createTree(this.db,[e,"global"]),this.globalTrees.set(e,t)),t}getProtocolTree(e,t){let n=`${e}\0${t}`,i=this.protocolTrees.get(n);return i!==void 0||(i=this.createTree(this.db,[e,"proto",t]),this.protocolTrees.set(n,i)),i}async createTree(e,t){let n=e;for(let s of t)n=await n.partition(s);let i=new pg(n),a=new hg(i);return await a.initialize(),a}async storeIndexes(e,t,n){let i=await this.getMetaPartition(e),a={protocol:n.protocol};await i.put(t,JSON.stringify(a))}async getStoredIndexes(e,t){let i=await(await this.getMetaPartition(e)).get(t);if(i!==void 0)return JSON.parse(i)}async deleteStoredIndexes(e,t){await(await this.getMetaPartition(e)).delete(t)}async getMetaPartition(e){return(await this.db.partition(e)).partition("meta")}}});var YE,cH=G(()=>{"use strict";g();Ju();YE=class{nodes=new Map;root;async open(){}async close(){}async clear(){this.nodes.clear(),this.root=void 0}async getNode(e){return this.nodes.get(on(e))}async putNode(e,t){this.nodes.set(on(e),t)}async deleteNode(e){this.nodes.delete(on(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}}});var ige,XE,dH=G(()=>{"use strict";g();Dm();dl();wu();Qo();zS();Tn();Uc();bx();Ex();Fo();v1();d2();u2();Qn();gx();A0();wx();v2();zs();st();t1();Ql();qs();bn();gv();ar();Hm();ige={protocol:"http://test-protocol.xyz",published:!1,types:{testRecord:{}},structure:{testRecord:{}}},XE=class r{static async generatePersona(e){let t=e?.did;t||(t=`did:example:${r.randomString(32)}`);let n=r.randomString(10),i=e?.keyId??`${t}#${n}`,a=e?.keyPair??await Va.generateKeyPair(),s=e?.encryptionKeyPair;if(!s){let c=await kt.generateKey();s={publicJwk:await kt.getPublicKey({key:c}),privateJwk:c}}return{did:t,keyId:i,keyPair:a,encryptionKeyPair:s,signer:new il({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:`${t}#${i}`})}}static async installDefaultTestProtocol(e,t){let n=await Sa.create({definition:ige,signer:ct.createSigner(t)}),i=await e.processMessage(t.did,n.message);if(i.status.code!==202)throw new Error(`Failed to install default test protocol: ${i.status.code} ${i.status.detail}`)}static async generateProtocolsConfigure(e){let t=e?.author??await r.generatePersona(),n=e?.protocolDefinition;if(!n){let o="record"+r.randomString(10);n={protocol:r.randomString(20),published:e?.published??!1,types:{},structure:{}},n.types[o]={schema:"test-object",dataFormats:["text/plain"]},n.structure[o]={}}let i=ct.createSigner(t),a={messageTimestamp:e?.messageTimestamp,definition:n,signer:i,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},s=await Sa.create(a);return{author:t,message:s.message,protocolsConfigure:s}}static async generateProtocolsQuery(e){let t=e?.author??await r.generatePersona(),n=ct.createSigner(t),i={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};Wt(i);let a=await ka.create(i);return{author:t,message:a.message,protocolsQuery:a}}static async generateGrantCreate(e){let t=e?.author??await r.generatePersona(),n=e?.grantedTo??await r.generatePersona(),i=e?.dateExpires??_t.createOffsetTimestamp({seconds:10}),a=e?.scope??{interface:ve.Messages,method:me.Read},s=ct.createSigner(t),o=n.did,c={signer:s,grantedTo:o,dateExpires:i,scope:a,description:e?.description??r.randomString(10),delegated:e?.delegated??!1,requestId:e?.requestId,conditions:e?.conditions},l=await et.createGrant(c);return{dataStream:zt.fromBytes(l.permissionGrantBytes),recordsWrite:l.recordsWrite,dataBytes:l.permissionGrantBytes,message:l.recordsWrite.message,dataEncodedMessage:l.dataEncodedMessage}}static async generateRecordsWrite(e){let t=e?.author??await r.generatePersona(),n=ct.createSigner(t),i=ct.createSigners(e?.attesters??[]),a=e?.dataCid,s=e?.dataSize,o,c;a===void 0&&s===void 0&&(o=e?.data??r.randomBytes(32),c=zt.fromBytes(o));let l={recipient:e?.recipient,protocol:e?.protocol??"http://test-protocol.xyz",protocolPath:e?.protocolPath??"testRecord",protocolRole:e?.protocolRole,schema:e?.schema??`http://${r.randomString(20)}`,tags:e?.tags,recordId:e?.recordId,parentContextId:e?.parentContextId,published:e?.published,dataFormat:e?.dataFormat??"application/json",dateCreated:e?.dateCreated,messageTimestamp:e?.messageTimestamp,datePublished:e?.datePublished,data:o,dataCid:a,dataSize:s,signer:n,attestationSigners:i,encryptionInput:e?.encryptionInput,permissionGrantId:e?.permissionGrantId,squash:e?.squash},d=await Pt.create(l),u=d.message;return{author:t,message:u,dataCid:a,dataSize:s,dataBytes:o,dataStream:c,recordsWrite:d}}static async generateProtocolEncryptedRecordsWrite(e){let{plaintextBytes:t,author:n,recipient:i,protocolDefinition:a,protocolPath:s,protocolParentContextId:o,protocolContextDerivingRootKeyId:c,protocolContextDerivedPublicKeyJwk:l}=e,d=r.randomBytes(12),u=r.randomBytes(32),{ciphertext:f,tag:p}=await xi.aeadEncrypt(ci.A256GCM,u,d,t),h=s.split("/"),m=h[h.length-1],{message:y,dataStream:v,recordsWrite:w}=await r.generateRecordsWrite({author:n,recipient:i,protocol:a.protocol,protocolPath:s,parentContextId:o,schema:a.types[m].schema,dataFormat:a.types[m].dataFormats?.[0],data:f}),E={initializationVector:d,key:u,authenticationTag:p,keyEncryptionInputs:[]};if(e.encryptSymmetricKeyWithProtocolPathDerivedKey){let _=a.structure;for(let C of h)_=_[C];let A=_.$encryption?.publicKeyJwk,M={publicKeyId:_.$encryption?.rootKeyId,publicKey:A,derivationScheme:xt.ProtocolPath};E.keyEncryptionInputs.push(M)}if(e.encryptSymmetricKeyWithProtocolContextDerivedKey){let _;if(o===void 0){let A={rootKeyId:n.keyId,derivationScheme:xt.ProtocolContext,derivedPrivateKey:n.encryptionKeyPair.privateJwk},D=await Pt.getEntryId(n.did,y.descriptor),M=Ae.constructKeyDerivationPathUsingProtocolContextScheme(D),C=await ji.derivePublicKey(A,M);_={publicKeyId:n.keyId,publicKey:C,derivationScheme:xt.ProtocolContext}}else{if(c===void 0||l===void 0)throw new Error("`protocolContextDerivingRootKeyId` and `protocolContextDerivedPublicKeyJwk` must both be defined if `protocolContextId` is given");_={publicKeyId:c,publicKey:l,derivationScheme:xt.ProtocolContext}}E.keyEncryptionInputs.push(_)}return await w.encryptSymmetricEncryptionKey(E),await w.sign({signer:ct.createSigner(n)}),{message:y,dataStream:v,recordsWrite:w,encryptedDataBytes:f,encryptionInput:E}}static async generateFromRecordsWrite(e){let t=e.existingWrite.message,n=_t.getCurrentTimestamp(),i=!(e.published??t.descriptor.published),a=e.datePublished??(i?n:void 0),s=e.data??r.randomBytes(32),o=zt.fromBytes(s),c={recordsWriteMessage:e.existingWrite.message,data:s,published:i,datePublished:a,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:ct.createSigner(e.author)},l=await Pt.createFrom(c);return{message:l.message,recordsWrite:l,dataBytes:s,dataStream:o}}static async generateRecordsQuery(e){let t=e?.author,n=e?.anonymous??!1;if(n&&t)throw new Error("Cannot have `author` and be anonymous at the same time.");t===void 0&&!n&&(t=await r.generatePersona());let i;t!==void 0&&(i=ct.createSigner(t));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole};Wt(a);let o=(await wa.create(a)).message;return{author:t,message:o}}static async generateRecordsSubscribe(e){let t=e?.author,n=e?.anonymous??!1;if(n&&t)throw new Error("Cannot have `author` and be anonymous at the same time.");t===void 0&&!n&&(t=await r.generatePersona());let i;t!==void 0&&(i=ct.createSigner(t));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole,cursor:e?.cursor};Wt(a);let o=(await Aa.create(a)).message;return{author:t,message:o}}static async generateRecordsCount(e){let t=e?.author,n=e?.anonymous??!1;if(n&&t)throw new Error("Cannot have `author` and be anonymous at the same time.");t===void 0&&!n&&(t=await r.generatePersona());let i;t!==void 0&&(i=ct.createSigner(t));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:r.randomString(10)},protocolRole:e?.protocolRole};Wt(a);let o=(await yd.create(a)).message;return{author:t,message:o}}static async generateRecordsDelete(e){let t=e?.author??await r.generateDidKeyPersona(),n=await _a.create({recordId:e?.recordId??await r.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:ct.createSigner(t)});return{author:t,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let t=e?.author??await r.generatePersona(),n=ct.createSigner(t),i={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};Wt(i);let a=await vd.create(i),s=a.message;return{author:t,messagesSubscribe:a,message:s}}static async generateMessagesRead(e){let t=e?.author??await r.generatePersona(),i={signer:ct.createSigner(t),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},a=await wd.create(i);return{author:t,messagesRead:a,message:a.message}}static generateAuthorization(){return{signature:r.generateAuthorizationSignature()}}static generateAuthorizationSignature(){return{payload:"anyPayload",signatures:[{protected:"anyProtectedHeader",signature:"anySignature"}]}}static async randomSignatureString(){let e=await Gg.generateKeyPair(),t=await Gg.sign(r.randomBytes(32),e.privateJwk);return Ie.bytesToBase64Url(t)}static randomString(e){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="";for(let i=0;i<e;i++)n+=t.charAt(Math.floor(Math.random()*t.length));return n}static randomBytes(e){let t=new Uint8Array(e);for(let n=0;n<e;n++)t[n]=Math.floor(Math.random()*256);return t}static async randomCborSha256Cid(){let e=r.randomBytes(32),t=await On.digest(e);return(await Yt.createV1(gu,t)).toString()}static randomInt(e,t){return Math.floor(Math.random()*(t-e)+e)}static randomTimestamp(e){let{year:t,month:n,day:i,hour:a,minute:s,second:o,millisecond:c,microsecond:l}=e||{};return _t.createTimestamp({year:t||this.randomInt(2e3,2022),month:n||this.randomInt(1,12),day:i||this.randomInt(1,28),hour:a||this.randomInt(0,23),minute:s||this.randomInt(0,59),second:o||this.randomInt(0,59),millisecond:c||this.randomInt(0,1e3),microsecond:l||this.randomInt(0,1e3)})}static createDidResolutionResult(e){return{didResolutionMetadata:{},didDocument:{id:e.did,verificationMethod:[{controller:e.did,id:e.keyId,type:"JsonWebKey2020",publicKeyJwk:e.keyPair.publicJwk}]},didDocumentMetadata:{}}}static async generateDidKeyPersona(){let e=await mb.create(),t=await mb.getSigningMethod({didDocument:e.document}),n=t.id,i=await e.export(),a={publicJwk:t.publicKeyJwk,privateJwk:i.privateKeys[0]},s=await kt.generateKey(),c={publicJwk:await kt.getPublicKey({key:s}),privateJwk:s};return{did:e.uri,keyId:n,keyPair:a,encryptionKeyPair:c,signer:new il({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:n})}}}});var QE,lH=G(()=>{"use strict";g();st();QE=class r{static pollRetrySleep=20;static pollTimeout=2e3;static async pollUntilSuccessOrTimeout(e,t=r.pollRetrySleep,n=r.pollTimeout){let i=Date.now();for(;;)try{return await e()}catch{if(Date.now()-i>=n)throw new Error("Operation timed out");await Jc(t)}}}});var uH={};ir(uH,{AllowAllTenantGate:()=>by,BlockstoreLevel:()=>If,Cid:()=>ur,ContentEncryptionAlgorithm:()=>ci,CoreProtocolRegistry:()=>vy,DataStoreLevel:()=>Cf,DataStream:()=>zt,DateSort:()=>Ot,Dwn:()=>cg,DwnConstant:()=>co,DwnError:()=>ne,DwnErrorCode:()=>re,DwnInterfaceName:()=>ve,DwnMethodName:()=>me,Encoder:()=>Ie,Encryption:()=>xi,EventEmitterEventLog:()=>Of,HdKey:()=>ji,IndexLevel:()=>Rh,Jws:()=>ct,KeyAgreementAlgorithm:()=>yv,KeyDerivationScheme:()=>xt,LevelWrapper:()=>Na,Message:()=>ye,MessageStoreLevel:()=>$f,MessagesRead:()=>wd,MessagesSubscribe:()=>vd,MessagesSync:()=>Zu,PERMISSIONS_REVOCATION_PATH:()=>RP,PermissionConditionPublication:()=>Vm,PermissionGrant:()=>kr,PermissionRequest:()=>gd,PermissionsProtocol:()=>et,Poller:()=>QE,PrivateKeySigner:()=>il,ProtocolRecordLimitStrategy:()=>Zl,Protocols:()=>Sd,ProtocolsConfigure:()=>Sa,ProtocolsQuery:()=>ka,Records:()=>Ae,RecordsCount:()=>yd,RecordsDelete:()=>_a,RecordsQuery:()=>wa,RecordsRead:()=>_d,RecordsSubscribe:()=>Aa,RecordsWrite:()=>Pt,ResumableTaskStoreLevel:()=>Bf,SMTStoreLevel:()=>pg,SMTStoreMemory:()=>YE,SMT_DEPTH:()=>hs,Secp256k1:()=>Va,Secp256r1:()=>nl,SortDirection:()=>At,SparseMerkleTree:()=>hg,StateIndexLevel:()=>jf,TestDataGenerator:()=>XE,Time:()=>_t,ZERO_HASH:()=>kx,authenticate:()=>mn,createLevelDatabase:()=>Js,executeUnlessAborted:()=>Wn,getBit:()=>lo,getDefaultHashes:()=>ZI,getRuleSetAtPath:()=>kd,hashChildren:()=>Dl,hashEquals:()=>sn,hashKey:()=>Vu,hashLeaf:()=>xy,hashToHex:()=>on,hexToHash:()=>Wu,initDefaultHashes:()=>Il,isCrossProtocolRef:()=>af,parseCrossProtocolRef:()=>Hs});var Zn=G(()=>{"use strict";g();Lg();qo();VI();RT();WI();fl();gx();wx();wu();Hm();CF();Py();vt();ar();Tn();Ex();gv();zs();kE();Uc();yr();bx();YI();lc();JI();Fo();v1();nh();d2();u2();Qn();A0();XR();v2();t1();Hk();rd();qs();CT();Pp();_E();LG();$6();Tf();tH();rH();oH();aH();M6();j6();cH();Ju();dH();lH()});var iS=ke((bVe,wH)=>{g();var gg=1e3,wg=gg*60,vg=wg*60,Bh=vg*24,hge=Bh*7,mge=Bh*365.25;wH.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return yge(r);if(t==="number"&&isFinite(r))return e.long?wge(r):gge(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function yge(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*mge;case"weeks":case"week":case"w":return t*hge;case"days":case"day":case"d":return t*Bh;case"hours":case"hour":case"hrs":case"hr":case"h":return t*vg;case"minutes":case"minute":case"mins":case"min":case"m":return t*wg;case"seconds":case"second":case"secs":case"sec":case"s":return t*gg;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function gge(r){var e=Math.abs(r);return e>=Bh?Math.round(r/Bh)+"d":e>=vg?Math.round(r/vg)+"h":e>=wg?Math.round(r/wg)+"m":e>=gg?Math.round(r/gg)+"s":r+"ms"}function wge(r){var e=Math.abs(r);return e>=Bh?nS(r,e,Bh,"day"):e>=vg?nS(r,e,vg,"hour"):e>=wg?nS(r,e,wg,"minute"):e>=gg?nS(r,e,gg,"second"):r+" ms"}function nS(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});g();g();Zn();Zn();var De=(d=>(d[d.MessagesRead=ve.Messages+me.Read]="MessagesRead",d[d.MessagesSubscribe=ve.Messages+me.Subscribe]="MessagesSubscribe",d[d.MessagesSync=ve.Messages+me.Sync]="MessagesSync",d[d.ProtocolsConfigure=ve.Protocols+me.Configure]="ProtocolsConfigure",d[d.ProtocolsQuery=ve.Protocols+me.Query]="ProtocolsQuery",d[d.RecordsDelete=ve.Records+me.Delete]="RecordsDelete",d[d.RecordsQuery=ve.Records+me.Query]="RecordsQuery",d[d.RecordsRead=ve.Records+me.Read]="RecordsRead",d[d.RecordsSubscribe=ve.Records+me.Subscribe]="RecordsSubscribe",d[d.RecordsWrite=ve.Records+me.Write]="RecordsWrite",d))(De||{}),Ch={[De.MessagesRead]:wd,[De.MessagesSubscribe]:vd,[De.MessagesSync]:Zu,[De.ProtocolsConfigure]:Sa,[De.ProtocolsQuery]:ka,[De.RecordsDelete]:_a,[De.RecordsQuery]:wa,[De.RecordsRead]:_d,[De.RecordsSubscribe]:Aa,[De.RecordsWrite]:Pt};g();async function K6(r){let e={kind:r.kind};r.kind==="protocol"&&(e.protocol=r.protocol,r.protocolPathPrefixes!==void 0&&(e.protocolPathPrefixes=[...new Set(r.protocolPathPrefixes)].sort((l,d)=>l.localeCompare(d))),r.contextIdPrefixes!==void 0&&(e.contextIdPrefixes=[...new Set(r.contextIdPrefixes)].sort((l,d)=>l.localeCompare(d))));let t=JSON.stringify(e),n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-256",n),a=new Uint8Array(i),s="";for(let l of a)s+=String.fromCharCode(l);let o=btoa(s).replaceAll("+","-").replaceAll("/","_"),c=o.length;for(;c>0&&o.codePointAt(c-1)===61;)c--;return c===o.length?o:o.slice(0,c)}var U6=100;g();var N6="^",ss=class r{constructor(e){this.db=e,this.sublevel=this.db.sublevel("replicationLinks")}static buildKey(e,t,n){return`${e}${N6}${t}${N6}${n}`}async getOrCreateLink(e){let t=await K6(e.scope),n=r.buildKey(e.tenantDid,e.remoteEndpoint,t);try{let a=await this.sublevel.get(n),s=JSON.parse(a);return delete s.push,s.connectivity="unknown",s}catch(a){if(a.code!=="LEVEL_NOT_FOUND")throw a}let i={tenantDid:e.tenantDid,remoteEndpoint:e.remoteEndpoint,scopeId:t,scope:e.scope,status:"initializing",connectivity:"unknown",pull:{},needsReconcile:!1,delegateDid:e.delegateDid,protocol:e.protocol};return await this.sublevel.put(n,JSON.stringify(i)),i}async saveLink(e){let t=r.buildKey(e.tenantDid,e.remoteEndpoint,e.scopeId);e.lastActivityAt=new Date().toISOString(),await this.sublevel.put(t,JSON.stringify(e))}async deleteLink(e,t,n){let i=r.buildKey(e,t,n);await this.sublevel.del(i)}async getLinksForTenant(e){let t=`${e}${N6}`,n=[];for await(let[i,a]of this.sublevel.iterator())i.startsWith(t)&&n.push(JSON.parse(a));return n}async getAllLinks(){let e=[];for await(let[,t]of this.sublevel.iterator())e.push(JSON.parse(t));return e}async updateDelegateDid(e,t){let n=await this.getLinksForTenant(e),i=[];for(let a of n)a.delegateDid!==t&&(a.delegateDid=t,await this.saveLink(a),i.push(a));return i}async setStatus(e,t){e.status=t,await this.saveLink(e)}static comparePosition(e,t){let n=BigInt(e.position)-BigInt(t.position);return n<BigInt(0)?-1:n>BigInt(0)?1:0}static validateTokenDomain(e,t){return e.contiguousAppliedToken===void 0?!0:t.streamId===e.contiguousAppliedToken.streamId&&t.epoch===e.contiguousAppliedToken.epoch}static setReceivedToken(e,t){(e.receivedToken===void 0||r.comparePosition(t,e.receivedToken)>0)&&(e.receivedToken=t)}static commitContiguousToken(e,t){e.contiguousAppliedToken=t}static resetCheckpoint(e,t){e.contiguousAppliedToken=t,e.receivedToken=t}async markNeedsReconcile(e,t){e.needsReconcile||(e.needsReconcile=!0,await this.saveLink(e))}async clearNeedsReconcile(e){e.needsReconcile&&(e.needsReconcile=!1,await this.saveLink(e))}};g();var L6=(p=>(p.ProtocolMetadataMissing="ClosureProtocolMetadataMissing",p.InitialWriteMissing="ClosureInitialWriteMissing",p.ParentChainMissing="ClosureParentChainMissing",p.ContextChainMissing="ClosureContextChainMissing",p.GrantMissing="ClosureGrantMissing",p.GrantNotYetActive="ClosureGrantNotYetActive",p.GrantExpired="ClosureGrantExpired",p.GrantRevocationMissing="ClosureGrantRevocationMissing",p.VisibilityFloorMissing="ClosureVisibilityFloorMissing",p.EncryptionDependencyMissing="ClosureEncryptionDependencyMissing",p.CrossProtocolReferenceMissing="ClosureCrossProtocolReferenceMissing",p.DependencyForbidden="ClosureDependencyForbidden",p.DepthExceeded="ClosureDepthExceeded",p))(L6||{});function kb(r,e,t){return{tenantDid:r,protocolCache:new Map,grantCache:new Map,satisfiedDeps:new Set,missingDeps:new Set,maxDepth:e??32,isDelegateSession:t?.isDelegateSession}}function fH(r,e){let t=e.descriptor;if(t.interface==="Protocols"&&t.method==="Configure"){let n=t.definition?t.definition.protocol:void 0;n&&r.protocolCache.delete(n)}if(t.protocol==="https://identity.foundation/dwn/permissions"){let n=e.recordId,i=t.protocolPath;if(i==="grant"&&n&&(r.grantCache.delete(n),r.satisfiedDeps.delete(`permissionGrant:grantId:${n}`),r.missingDeps.delete(`permissionGrant:grantId:${n}`)),i==="grant/revocation"){let a=t.parentId;a&&(r.grantCache.delete(`revocation:${a}`),r.satisfiedDeps.delete(`grantRevocation:grantId:${a}`),r.missingDeps.delete(`grantRevocation:grantId:${a}`),r.satisfiedDeps.delete(`permissionGrant:grantId:${a}`),r.missingDeps.delete(`permissionGrant:grantId:${a}`))}}if(t.interface==="Records"){let n=e.recordId,i=t.protocol,a=t.protocolPath;if(n){let s=o=>{let c=o.indexOf(n);if(c===-1)return!1;let l=c>0?o[c-1]:":",d=c+n.length<o.length?o[c+n.length]:"|",u=l===":"||l==="|",f=d==="|"||d===void 0;return u&&(c+n.length===o.length||f)};for(let o of r.satisfiedDeps)s(o)&&r.satisfiedDeps.delete(o);for(let o of r.missingDeps)s(o)&&r.missingDeps.delete(o)}if(i&&a){let s=`filter:${i}|${a}`;for(let o of r.satisfiedDeps)o.includes(s)&&r.satisfiedDeps.delete(o);for(let o of r.missingDeps)o.includes(s)&&r.missingDeps.delete(o)}if(i==="https://identity.foundation/protocols/key-delivery"){let o=e.descriptor?.tags?.protocol;if(o){let c=`messageCid:${o}|`;for(let l of r.satisfiedDeps)l.includes(c)&&r.satisfiedDeps.delete(l);for(let l of r.missingDeps)l.includes(c)&&r.missingDeps.delete(l)}}else if(i){let s=`messageCid:${i}|`;for(let o of r.satisfiedDeps)o.includes(s)&&r.satisfiedDeps.delete(o);for(let o of r.missingDeps)o.includes(s)&&r.missingDeps.delete(o)}}}g();Zn();g();function pH(r,e){let[t,...n]=e.split("/"),i=r.structure[t];for(let a of n){if(!i)return;i=i[a]}return i}function KHe(r){return r.split("/")[0]||r}function $h(r,e){let t=pH(r,e);if(!t)return!1;function n(i){for(let a in i)if(!a.startsWith("$")){let s=i[a];if(s.$role===!0||n(s))return!0}return!1}return n(t)?!0:q6(void 0,e,r)}function q6(r,e,t){function n(i){if(i.$actions){for(let a of i.$actions)if(a.who&&a.who!=="anyone"&&(r===void 0||a.who===r)&&a.of===e&&a.can?.includes("read"))return!0}for(let a in i)if(!a.startsWith("$")&&n(i[a]))return!0;return!1}for(let i in t.structure)if(n(t.structure[i]))return!0;return!1}function z6({protocolDefinition:r,protocolPath:e,recipient:t,tenantDid:n,authorDid:i}){let a=new Set,s=pH(r,e);return s&&(s.$role===!0&&t&&a.add(t),t&&t!==n&&q6("recipient",e,r)&&a.add(t),i&&i!==n&&q6("author",e,r)&&a.add(i),a.delete(n)),a}function sge(r){let t=r.descriptor.protocol;return t?t===et.uri?[]:[{dependencyClass:1,label:"protocolsConfigure",identifier:t,identifierType:"protocol"}]:[]}function oge(r){let e=r.descriptor,t=[];if(e.interface!=="Records")return[];let n=r.recordId,i=e.parentId;i&&t.push({dependencyClass:2,label:"parentRecord",identifier:i,identifierType:"recordId"});let a=r.contextId;if(a&&n&&a!==n){let s=a.split("/")[0];t.push({dependencyClass:2,label:"contextRoot",identifier:s,identifierType:"recordId"})}if(n&&e.method==="Write"){let s=e.dateCreated,o=e.messageTimestamp;s&&o&&s!==o&&t.push({dependencyClass:2,label:"initialWrite",identifier:n,identifierType:"recordId"})}return n&&e.method==="Delete"&&t.push({dependencyClass:2,label:"initialWrite",identifier:n,identifierType:"recordId"}),t}function age(r){let e=[],t=r.authorization;if(!t)return[];let n=t.signature?.payload;if(n)try{let i=JSON.parse(Buffer.from(n,"base64url").toString("utf-8"));i.permissionGrantId&&(e.push({dependencyClass:3,label:"permissionGrant",identifier:i.permissionGrantId,identifierType:"grantId"}),e.push({dependencyClass:3,label:"grantRevocation",identifier:i.permissionGrantId,identifierType:"grantId"}))}catch{}return e}function cge(r,e){if(!r||!e)return;let t=e.split("/"),n=r,i;for(let a of t){if(!Object.hasOwn(n,a))return;i=n[a],n=i}return i}function dge(r,e,t){let n=r.descriptor;if(n.interface!=="Records")return[];let i=n.protocolPath;if(!i)return[];let a=[];if(cge(e?.structure,i)?.$encryption){let d=i.split("/").pop();if(e?.types?.[d??""]?.encryptionRequired===!0){a.push({dependencyClass:5,label:"encryptionKeyMaterial",identifier:n.protocol,identifierType:"protocol"});let f=r.contextId,p=!1;if(f){let m=i.split("/")[0];p=$h(e,m)}if(t&&!p||a.push({dependencyClass:5,label:"keyDeliveryProtocol",identifier:"https://identity.foundation/protocols/key-delivery",identifierType:"protocol"}),p&&f){let m=f.split("/")[0];a.push({dependencyClass:5,label:"contextKeyRecord",identifier:`${n.protocol}|${m}`,identifierType:"messageCid"})}}}let o=i.split("/")[0],c=e?.structure?.[o];if(c?.$ref){let d=c.$ref.indexOf(":");if(d>0){let u=c.$ref.substring(0,d),p=e?.uses?.[u];if(p){a.push({dependencyClass:6,label:"crossProtocolConfig",identifier:p,identifierType:"protocol"});let h=i.split("/"),m=n.parentId;h.length===2&&m&&a.push({dependencyClass:6,label:"crossProtocolParent",identifier:`${p}|${m}`,identifierType:"recordId"})}}}let l=r.authorization;if(l&&e?.uses){let d=l.signature?.payload;if(d)try{let f=JSON.parse(Buffer.from(d,"base64url").toString("utf-8")).protocolRole;if(f?.includes(":")){let p=f.indexOf(":"),h=f.substring(0,p),m=e.uses[h];if(m){a.push({dependencyClass:6,label:"crossProtocolRoleConfig",identifier:m,identifierType:"protocol"});let y=f.substring(p+1),v=ye.getAuthor(r),w=r.contextId;if(v){let E={interface:"Records",method:"Write",protocol:m,protocolPath:y,recipient:v,isLatestBaseState:!0};if(w){let A=y.split("/").length-1;if(A>0){let M=w.split("/").slice(0,A).join("/");M&&(E.contextId={gte:M,lt:M+"\uFFFF"})}}let _=E.contextId?JSON.stringify(E.contextId):"no-context";a.push({dependencyClass:6,label:"crossProtocolRoleRecord",identifier:`${m}|${y}|${v}|${_}`,identifierType:"filter",filter:E})}}}}catch{}}return a}async function eS(r,e,t,n){if(t.kind==="full")return{complete:!0,rootMessageCid:await ye.getCid(r),edges:[],depth:0};let i=await ye.getCid(r),a=[],s=new Set,o=0,c=[r];for(s.add(i);c.length>0;){if(o>=n.maxDepth)return{complete:!1,rootMessageCid:i,edges:a,failure:{code:"ClosureDepthExceeded",edge:{dependencyClass:1,label:"depth",identifier:String(o),identifierType:"messageCid"},detail:`closure traversal exceeded max depth of ${n.maxDepth}`},depth:o};let l=c.length;for(let d=0;d<l;d++){let u=c.shift(),f=[...sge(u),...oge(u),...age(u)],p=await hH(f,a,e,n,s,c,i,o);if(p)return p;let m=u.descriptor.protocol;if(m){let v=n.protocolCache.get(m)?.descriptor?.definition;if(v){let w=dge(u,v,n.isDelegateSession),E=await hH(w,a,e,n,s,c,i,o);if(E)return E}}if(o===0){let y=uge(u,a,n,i,o);if(y)return y}}o++}return{complete:!0,rootMessageCid:i,edges:a,depth:o}}async function lge(r,e,t,n,i){let a=kb(n,i),s=[];for(let o of r){let c=await eS(o,e,t,a);s.push(c)}return s}function uge(r,e,t,n,i){let a=e.find(p=>p.label==="permissionGrant");if(!a)return null;let s=r.descriptor.messageTimestamp;if(!s)return null;let o=t.grantCache.get(a.identifier);if(!o)return null;let c=o.descriptor.dateCreated,l,d=o.encodedData;if(d)try{l=JSON.parse(Buffer.from(d,"base64url").toString("utf-8")).dateExpires}catch{}if(c&&s<c)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:"ClosureGrantNotYetActive",edge:a,detail:`grant '${a.identifier}' is not yet active at message timestamp ${s} (dateGranted: ${c})`},depth:i};if(l&&s>=l)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:"ClosureGrantExpired",edge:a,detail:`grant '${a.identifier}' expired at ${l}, message timestamp is ${s}`},depth:i};let u=`revocation:${a.identifier}`,f=t.grantCache.get(u);if(f&&f.descriptor.interface!=="Synthetic"){let p=f.descriptor.messageTimestamp;if(p&&p<=s)return{complete:!1,rootMessageCid:n,edges:e,failure:{code:"ClosureGrantRevocationMissing",edge:e.find(h=>h.label==="grantRevocation")??a,detail:`grant '${a.identifier}' was revoked at ${p}, before message timestamp ${s}`},depth:i}}return null}async function hH(r,e,t,n,i,a,s,o){for(let c of r){e.push(c);let l=`${c.label}:${c.identifierType}:${c.identifier}`;if(n.satisfiedDeps.has(l))continue;if(n.missingDeps.has(l))return{complete:!1,rootMessageCid:s,edges:e,failure:{code:mH(c),edge:c,detail:`dependency '${c.label}' (${c.identifier}) is missing`},depth:o};let d=await fge(c,t,n);if(!d)return n.missingDeps.add(l),{complete:!1,rootMessageCid:s,edges:e,failure:{code:mH(c),edge:c,detail:`dependency '${c.label}' (${c.identifier}) not found locally`},depth:o};if(n.satisfiedDeps.add(l),!(c.identifierType==="grantId"||c.identifierType==="filter"||c.label==="contextKeyRecord")){let f=await ye.getCid(d);i.has(f)||(i.add(f),a.push(d))}}return null}async function fge(r,e,t){switch(r.identifierType){case"protocol":{if(t.protocolCache.has(r.identifier))return t.protocolCache.get(r.identifier)??null;let{messages:n}=await e.query(t.tenantDid,[{interface:"Protocols",method:"Configure",protocol:r.identifier,isLatestBaseState:!0}]),i=n.length>0?n[0]:null;return t.protocolCache.set(r.identifier,i),i}case"recordId":{if(r.label==="initialWrite"){let{messages:i}=await e.query(t.tenantDid,[{entryId:r.identifier}]);if(i.length>0)return i[0];let{messages:a}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",recordId:r.identifier,isLatestBaseState:!1}]);return a.length>0?a[0]:null}if(r.label==="crossProtocolParent"){let i=r.identifier.indexOf("|");if(i>0){let a=r.identifier.substring(0,i),s=r.identifier.substring(i+1),{messages:o}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:a,recordId:s,isLatestBaseState:!0}]);return o.length>0?o[0]:null}}let{messages:n}=await e.query(t.tenantDid,[{interface:"Records",recordId:r.identifier,isLatestBaseState:!0}]);return n.length>0?n[0]:null}case"grantId":{if(r.label==="grantRevocation"){let a=`revocation:${r.identifier}`;if(t.grantCache.has(a))return t.grantCache.get(a)??null;let{messages:s}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/dwn/permissions",parentId:r.identifier,protocolPath:"grant/revocation",isLatestBaseState:!0}]),o;for(let d of s){let u=d.descriptor.messageTimestamp;(!o||u<o.descriptor.messageTimestamp)&&(o=d)}let l=o??{descriptor:{interface:"Synthetic",method:"NoRevocation"}};return t.grantCache.set(a,l),l}if(t.grantCache.has(r.identifier))return t.grantCache.get(r.identifier)??null;let{messages:n}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/dwn/permissions",protocolPath:"grant",recordId:r.identifier,isLatestBaseState:!0}]),i=n.length>0?n[0]:null;return t.grantCache.set(r.identifier,i),i}case"messageCid":{if(r.label==="contextKeyRecord"){let n=r.identifier.indexOf("|");if(n>0){let i=r.identifier.substring(0,n),a=r.identifier.substring(n+1),{messages:s}=await e.query(t.tenantDid,[{interface:"Records",method:"Write",protocol:"https://identity.foundation/protocols/key-delivery",protocolPath:"contextKey","tag.protocol":i,"tag.contextId":a}]);return s.length>0?s[0]:null}}return await e.get(t.tenantDid,r.identifier)??null}case"filter":{if(!r.filter)return null;let{messages:n}=await e.query(t.tenantDid,[r.filter]);return n.length>0?n[0]:null}default:return null}}function mH(r){switch(r.dependencyClass){case 1:return"ClosureProtocolMetadataMissing";case 2:return r.label==="initialWrite"?"ClosureInitialWriteMissing":r.label==="parentRecord"?"ClosureParentChainMissing":r.label==="contextRoot"?"ClosureContextChainMissing":"ClosureParentChainMissing";case 3:return r.label==="permissionGrant"?"ClosureGrantMissing":"ClosureGrantRevocationMissing";case 4:return r.label==="squashContextRoot"?"ClosureVisibilityFloorMissing":"ClosureVisibilityFloorMissing";case 5:return"ClosureEncryptionDependencyMissing";case 6:return"ClosureCrossProtocolReferenceMissing";default:return"ClosureDependencyForbidden"}}g();Qo();st();var Mf=class extends EE{constructor({agent:t,db:n,location:i,ttl:a}){super({db:n,location:i,ttl:a});this._resolving=new Map;this._agent=t}get agent(){if(!this._agent)throw new Error("Agent not initialized");return this._agent}set agent(t){this._agent=t}async get(t){try{let n=await this.cache.get(t),i=JSON.parse(n);if(!this._resolving.has(t)&&Date.now()>=i.ttlMillis){this._resolving.set(t,!0);let a=await this.agent.did.get({didUri:t,tenant:this.agent.agentDid.uri});if(typeof a>"u")this._resolving.delete(t),this.cache.nextTick(()=>this.cache.del(t));else try{let s=await this.agent.did.resolve(t);if(!s.didResolutionMetadata.error&&s.didDocument){let o={...a,document:s.didDocument,metadata:s.didDocumentMetadata};try{await this.agent.did.update({portableDid:o,tenant:this.agent.agentDid.uri,publish:!1})}catch(c){c.message&&!c.message.includes("No changes detected, update aborted")&&us.error(`Error updating DID: ${c.message}`)}}}finally{this._resolving.delete(t)}}return i.value}catch(n){if(n.notFound)return;throw n}}};g();var yH=class{constructor(e){this.agent=e.agent,this.did=e.did,this.delegateDid=e.delegateDid,this.recoveryPhrase=e.recoveryPhrase,this.identity=e.identity}};g();Zn();g();Qo();Zn();async function mg(r,e){let t=await e.dereference(`${r}#dwn`);if(t.dereferencingMetadata.error)throw new Error(`Failed to dereference '${r}#dwn': ${t.dereferencingMetadata.error}`);if(e6.isDwnDidService(t.contentStream)){let{serviceEndpoint:n}=t.contentStream,i=typeof n=="string"?[n]:Array.isArray(n)&&n.every(a=>typeof a=="string")?n:[];if(i.length>0)return i}return[]}function eVe(r){return ye.getAuthor(r)}function tVe(r){return ct.decodePlainObjectPayload(r.authorization.signature)?.protocolRole}function Kd(r){return!r||typeof r!="object"||r===null?!1:"message"in r&&typeof r.message=="object"&&r.message!==null&&"descriptor"in r.message&&typeof r.message.descriptor=="object"&&r.message.descriptor!==null&&"interface"in r.message.descriptor&&r.message.descriptor.interface===ve.Records&&"method"in r.message.descriptor&&r.message.descriptor.method===me.Write}function pge(r){return ye.getCid(r)}async function rVe(r,e){let t=e===Ot.CreatedAscending||e===Ot.CreatedDescending?r.descriptor.dateCreated:r.descriptor.datePublished;if(t===void 0)throw new Error("The dateCreated or datePublished property is missing from the record descriptor.");return{messageCid:await pge(r),value:t}}function nVe(r,e=3e3,t=3e5,n){let i=Date.now()+t,a=null,s=!0;return new Promise((o,c)=>{n&&n.addEventListener("abort",()=>{s=!1,a!==null&&clearTimeout(a),console.log("Polling aborted by user"),o(null)});async function l(){if(!s)return;let d=i-Date.now();if(d<=0){s=!1,console.log("Polling stopped: TTL reached"),o(null);return}console.log(`Polling... (Remaining time: ${Math.ceil(d/1e3)}s)`);try{let u=await r();if(u.ok){s=!1,a!==null&&clearTimeout(a),console.log("Polling stopped: Success condition met"),o(u);return}}catch(u){console.error("Error fetching data:",u),c(u)}s&&(a=setTimeout(l,e))}l()})}async function F6(r,e,t){if(!Number.isInteger(e)||e<1)throw new Error(`mapConcurrent: concurrency must be a positive integer, got ${e}`);if(r.length===0)return[];let n=new Array(r.length),i=0,a=async()=>{for(;;){let c=i++;if(c>=r.length)return;n[c]=await t(r[c],c)}},s=Math.min(e,r.length),o=[];for(let c=0;c<s;c++)o.push(a());return await Promise.all(o),n}async function tS(r,e,t){return F6(r,e,async(n,i)=>{try{return{status:"fulfilled",value:await t(n,i)}}catch(a){return{status:"rejected",reason:a}}})}var gH=class{constructor({didResolver:e,rpcClient:t}){this._didResolver=e,this._rpcClient=t}async recordsQuery(e,t){let n=await wa.create({filter:t.filter,dateSort:t.dateSort,pagination:t.pagination,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,n.message)}async recordsRead(e,t){let n=await _d.create({filter:t.filter,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,n.message)}async recordsSubscribe(e,t,n){let i=await Aa.create({filter:t.filter,dateSort:t.dateSort,pagination:t.pagination,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,i.message,void 0,n)}async recordsCount(e,t){let n=await yd.create({filter:t.filter,messageTimestamp:t.messageTimestamp});return await this.sendRequest(e,n.message)}async protocolsQuery(e,t){let n=await ka.create({filter:t?.filter,messageTimestamp:t?.messageTimestamp});return await this.sendRequest(e,n.message)}async sendRequest(e,t,n,i){let a=await mg(e,this._didResolver),s=[];for(let o of a)try{if(i!==void 0){if(!(await this._rpcClient.getServerInfo(o)).webSocketSupport){s.push({url:o,message:"WebSocket support is not enabled on the server."});continue}let d=new URL(o);d.protocol=d.protocol==="http:"?"ws:":"wss:",o=d.toString()}return await this._rpcClient.sendDwnRequest({dwnUrl:o,targetDid:e,message:t,data:n,subscriptionHandler:i})}catch(c){s.push({url:o,message:c instanceof Error?c.message:"Unknown error"})}throw new Error(`AnonymousDwnApi: Failed to send request to '${e}': ${JSON.stringify(s)}`)}};g();var yg=class{constructor({did:e,metadata:t}){this.did=e,this.metadata=t}async export(){return{portableDid:await this.did.export(),metadata:{...this.metadata}}}};g();bn();var G6={"AES-GCM":{implementation:zm,names:["A128GCM","A192GCM","A256GCM"],operations:["bytesToPrivateKey","decrypt","encrypt","generateKey"]},"AES-KW":{implementation:Fm,names:["A128KW","A192KW","A256KW"],operations:["bytesToPrivateKey","generateKey","privateKeyToBytes","wrapKey","unwrapKey"]},Ed25519:{implementation:Qc,names:["Ed25519"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},HKDF:{implementation:_P,names:["HKDF-256","HKDF-384","HKDF-512"],operations:["deriveKey","deriveKeyBytes"]},PBKDF2:{implementation:TP,names:["PBES2-HS256+A128KW","PBES2-HS384+A192KW","PBES2-HS512+A256KW"],operations:["deriveKey","deriveKeyBytes"]},secp256k1:{implementation:pc,names:["ES256K","secp256k1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},secp256r1:{implementation:pc,names:["ES256","secp256r1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},"SHA-256":{implementation:Cu,names:["SHA-256"],operations:["digest"]},X25519:{implementation:Bu,names:["X25519"],operations:["bytesToPrivateKey","generateKey"]}},bo=class{constructor(){this._algorithmInstances=new Map}async bytesToPrivateKey({algorithm:e,privateKeyBytes:t}){let n=this.getAlgorithmName({algorithm:e});return await this.getAlgorithm({algorithm:n}).bytesToPrivateKey({algorithm:e,privateKeyBytes:t})}async bytesToPublicKey({algorithm:e,publicKeyBytes:t}){let n=this.getAlgorithmName({algorithm:e});return await this.getAlgorithm({algorithm:n}).bytesToPublicKey({algorithm:e,publicKeyBytes:t})}async decrypt(e){let t=this.getAlgorithmName({key:e.key});return await this.getAlgorithm({algorithm:t}).decrypt(e)}async deriveKey(e){let t=this.getAlgorithmName({algorithm:e.algorithm}),n=this.getAlgorithm({algorithm:t}),i;switch(e.algorithm){case"HKDF-256":case"HKDF-384":case"HKDF-512":{i=e.derivedKeyAlgorithm;break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{i=e.algorithm.split(/[-+]/)[2];break}default:throw new qe(Ue.AlgorithmNotSupported,`The specified "algorithm" is not supported: ${e.algorithm}`)}let a=+(i.match(/\d+/)?.[0]??-1);if(a===-1)throw new qe(Ue.AlgorithmNotSupported,`The derived key algorithm" is not supported: ${i}`);let s=await n.deriveKeyBytes({...e,length:a});return await this.bytesToPrivateKey({algorithm:i,privateKeyBytes:s})}async deriveKeyBytes(e){let t=this.getAlgorithmName({algorithm:e.algorithm});return await this.getAlgorithm({algorithm:t}).deriveKeyBytes(e)}async digest({algorithm:e,data:t}){return await this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:t})}async encrypt(e){let t=this.getAlgorithmName({key:e.key});return await this.getAlgorithm({algorithm:t}).encrypt(e)}async generateKey(e){let t=this.getAlgorithmName({algorithm:e.algorithm}),i=await this.getAlgorithm({algorithm:t}).generateKey({algorithm:e.algorithm});return i.kid??=await yt({jwk:i}),i}async getPublicKey({key:e}){let t=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:t}).getPublicKey({key:e})}async privateKeyToBytes({privateKey:e}){let t=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:t}).privateKeyToBytes({privateKey:e})}async publicKeyToBytes({publicKey:e}){let t=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:t}).publicKeyToBytes({publicKey:e})}async sign({key:e,data:t}){let n=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:n}).sign({data:t,key:e})}async unwrapKey(e){let t=this.getAlgorithmName({key:e.decryptionKey});return await this.getAlgorithm({algorithm:t}).unwrapKey(e)}async verify({key:e,signature:t,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:t,data:n})}async wrapKey(e){let t=this.getAlgorithmName({key:e.encryptionKey});return await this.getAlgorithm({algorithm:t}).wrapKey(e)}getAlgorithm({algorithm:e}){let t=G6[e]?.implementation;if(!t)throw new qe(Ue.AlgorithmNotSupported,`Algorithm not supported: ${e}`);return this._algorithmInstances.has(t)||this._algorithmInstances.set(t,new t),this._algorithmInstances.get(t)}getAlgorithmName({algorithm:e,key:t}){let n=t?.alg??e,i=t?.crv;for(let a of Object.keys(G6)){let s=G6[a].names;if(n&&s.includes(n))return a;if(i&&s.includes(i))return a}throw new qe(Ue.AlgorithmNotSupported,`Algorithm not supported based on provided input: alg=${n}, crv=${i}. Please check the documentation for the list of supported algorithms.`)}};g();Qo();bn();g();st();Qo();g();var _b={protocol:"https://identity.foundation/protocols/web5/identity-store",published:!1,types:{portableDid:{schema:"https://identity.foundation/schemas/web5/portable-did",dataFormats:["application/json"]},identityMetadata:{schema:"https://identity.foundation/schemas/web5/identity-metadata",dataFormats:["application/json"]}},structure:{portableDid:{},identityMetadata:{}}},La={protocol:"https://identity.foundation/protocols/key-delivery",published:!1,types:{contextKey:{dataFormats:["application/json"]}},structure:{contextKey:{$actions:[{who:"recipient",of:"contextKey",can:["read"]}],$tags:{$requiredTags:["protocol","contextId"],$allowUndefinedTags:!1,protocol:{type:"string"},contextId:{type:"string"}}}}},H6={protocol:"https://identity.foundation/protocols/web5/jwk-store",published:!1,types:{privateJwk:{schema:"https://identity.foundation/schemas/web5/private-jwk",dataFormats:["application/json"],encryptionRequired:!0}},structure:{privateJwk:{}}};g();bn();var Ii="^",rS=class extends ed{constructor(){super(),this._predefinedKeys=new Map,this._keyGenerator=this._predefinedKeys.keys()}async addPredefinedKeys({privateKeys:e}){let t={};for(let n of e){n.kid??=await yt({jwk:n});let i=await this.getKeyUri({key:n});t[i]=n}this._predefinedKeys=new Map(Object.entries(t)),this._keyGenerator=this._predefinedKeys.keys()}async exportKey({keyUri:e}){let t=this._predefinedKeys.get(e);if(!t)throw new Error(`DeterministicKeyGenerator.exportKey: Key not found: ${e}`);return t}async generateKey(e){let{value:t,done:n}=this._keyGenerator.next();if(n)throw new Error("Ran out of predefined keys");return t}async getPublicKey({keyUri:e}){let t=this._predefinedKeys.get(e);if(!t)throw new Error(`DeterministicKeyGenerator.getPublicKey: Key not found: ${e}`);let{d:n,...i}=t;return i}async sign({keyUri:e,data:t}){let n=this._predefinedKeys.get(e);if(!n)throw new Error(`DeterministicKeyGenerator.sign: Key not found: ${e}`);return await Kn.sign({data:t,key:n})}};async function Ud({agent:r,tenant:e,didUri:t}){if(e)return e;if(r.agentDid)return r.agentDid.uri;if(!t)throw new Error("Failed to determine tenant DID: 'agent.agentDid', 'tenant', and 'didUri' are undefined");return t}g();var Ab=An(iS(),1);st();Zn();var Kf=class{constructor(){this.name="DwnDataStore";this._cache=new Pi.default({ttl:(0,Ab.default)("15 minutes"),max:100});this._index=new Pi.default({ttl:(0,Ab.default)("21 days"),max:1e3});this._protocolInitializedCache=new Pi.default({ttl:(0,Ab.default)("1 hour"),max:1e3});this._tenantEncryptionActive=new Pi.default({ttl:(0,Ab.default)("1 hour"),max:1e3});this._recordProperties={dataFormat:"application/json",protocol:"",protocolPath:""}}async delete({id:e,agent:t,tenant:n}){let i=await Ud({agent:t,tenant:n,didUri:e}),a=await this.lookupRecordId({id:e,tenantDid:i,agent:t});if(!a)return!1;let{reply:{status:s}}=await t.dwn.processRequest({author:i,target:i,messageType:De.RecordsDelete,messageParams:{recordId:a}});if(s.code===202)return this._index.delete(`${i}${Ii}${e}`),this._cache.delete(a),!0;throw new Error(`${this.name}: Failed to delete '${e}' from store: (${s.code}) ${s.detail}`)}async get({id:e,agent:t,tenant:n,useCache:i=!1}){let a=await Ud({agent:t,tenant:n,didUri:e}),s=await this.lookupRecordId({id:e,tenantDid:a,agent:t});if(s)return await this.getRecord({recordId:s,tenantDid:a,agent:t,useCache:i})}async list({agent:e,tenant:t}){let n=await Ud({tenant:t,agent:e});return await this.getAllRecords({agent:e,tenantDid:n})}async set({id:e,data:t,tenant:n,agent:i,preventDuplicates:a=!0,updateExisting:s=!1,useCache:o=!1}){let c=await Ud({agent:i,tenant:n,didUri:e});await this.initialize({tenant:c,agent:i});let l={...this._recordProperties};if(s){let h=await this.getExistingRecordEntry({id:e,tenantDid:c,agent:i});if(!h)throw new Error(`${this.name}: Update failed due to missing entry for: ${e}`);l.recordId=h.recordsWrite.recordId,l.dateCreated=h.recordsWrite.descriptor.dateCreated}else if(a&&await this.lookupRecordId({id:e,tenantDid:c,agent:i}))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${e}`);let d=fe.object(t).toUint8Array(),u=this.isEncryptionActive(c),{message:f,reply:{status:p}}=await i.dwn.processRequest({author:c,target:c,messageType:De.RecordsWrite,messageParams:{...this._recordProperties,...l},dataStream:new Blob([d],{type:"application/json"}),...u?{encryption:!0}:{}});if(!(f&&p.code===202))throw new Error(`${this.name}: Failed to write data to store for ${e}: ${p.detail}`);this._index.set(`${c}${Ii}${e}`,f.recordId),o&&this._cache.set(f.recordId,t)}async initialize({tenant:e,agent:t}){let n=await Ud({agent:t,tenant:e});if(this._protocolInitializedCache.has(n)&&(!this.encryptionRequired||this._tenantEncryptionActive.has(n)))return;let{reply:{status:i,entries:a}}=await t.dwn.processRequest({author:n,target:n,messageType:De.ProtocolsQuery,messageParams:{filter:{protocol:this._recordProtocolDefinition.protocol}}});if(i.code!==200)throw new Error(`Failed to query for protocols: ${i.code} - ${i.detail}`);let s=!1;if(a?.length===0)s=(await this.installProtocol(n,t)).encryptionActive;else if(this.encryptionRequired){let o=a[0].descriptor?.definition,c=Object.keys(o?.structure??{})[0];s=!!(c&&o?.structure[c]?.$encryption)}this._tenantEncryptionActive.set(n,s),this._protocolInitializedCache.set(n,!0)}get encryptionRequired(){return this._encryptionRequired===void 0&&(this._encryptionRequired=Object.values(this._recordProtocolDefinition.types).some(e=>e.encryptionRequired===!0)),this._encryptionRequired}isEncryptionActive(e){return this._tenantEncryptionActive.get(e)===!0}async getAllRecords(e){throw new Error("Not implemented: Classes extending DwnDataStore must implement getAllRecords()")}async getRecord({recordId:e,tenantDid:t,agent:n,useCache:i}){if(i){let c=this._cache.get(e);if(c)return c}let a=this.encryptionRequired||this.isEncryptionActive(t),{reply:s}=await n.dwn.processRequest({author:t,target:t,messageType:De.RecordsRead,messageParams:{filter:{recordId:e}},...a?{encryption:!0}:{}});if(!s.entry?.data)throw new Error(`${this.name}: Failed to read data from DWN for: ${e}`);let o=await Mm.consumeToJson({readableStream:s.entry.data});return i&&this._cache.set(e,o),o}async installProtocol(e,t){let n=this._recordProtocolDefinition,i=!1;if(this.encryptionRequired){let s=await t.dwn.getEncryptionKeyDeriver(e);n=await Sd.deriveAndInjectPublicEncryptionKeys(n,s),i=!0}let{reply:{status:a}}=await t.dwn.processRequest({author:e,target:e,messageType:De.ProtocolsConfigure,messageParams:{definition:n}});if(a.code!==202)throw new Error(`Failed to install protocol: ${a.code} - ${a.detail}`);return i&&await t.dwn.ensureKeyDeliveryProtocol(e),{encryptionActive:i}}async lookupRecordId({id:e,tenantDid:t,agent:n}){let i=this._index.get(`${t}${Ii}${e}`,{updateAgeOnGet:!0});return i||(await this.getAllRecords({agent:n,tenantDid:t}),i=this._index.get(`${t}${Ii}${e}`)),i}async getExistingRecordEntry({id:e,tenantDid:t,agent:n}){let i=await this.lookupRecordId({id:e,tenantDid:t,agent:n});if(i){let{reply:a}=await n.dwn.processRequest({author:t,target:t,messageType:De.RecordsRead,messageParams:{filter:{recordId:i}}});return a.entry}}},Uf=class{constructor(){this.name="InMemoryDataStore";this.store=new Map}async delete({id:e,agent:t,tenant:n}){let i=await Ud({agent:t,tenant:n,didUri:e});return this.store.has(`${i}${Ii}${e}`)?(this.store.delete(`${i}${Ii}${e}`),!0):!1}async get({id:e,agent:t,tenant:n}){let i=await Ud({agent:t,tenant:n,didUri:e});return this.store.get(`${i}${Ii}${e}`)}async list({agent:e,tenant:t}){let n=await Ud({tenant:t,agent:e}),i=[];for(let[a,s]of this.store.entries())a.startsWith(`${n}${Ii}`)&&i.push(s);return i}async set({id:e,data:t,tenant:n,agent:i,preventDuplicates:a,updateExisting:s}){let o=await Ud({agent:i,tenant:n,didUri:e});if(s){if(!this.store.has(`${o}${Ii}${e}`))throw new Error(`${this.name}: Update failed due to missing entry for: ${e}`)}else if(a&&this.store.has(`${o}${Ii}${e}`))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${e}`);let c=structuredClone(t);this.store.set(`${o}${Ii}${e}`,c)}};var bg=class extends Kf{constructor(){super(...arguments);this.name="DwnDidStore";this._recordProtocolDefinition=_b;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"portableDid",schema:this._recordProtocolDefinition.types.portableDid.schema}}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async list(t){return await super.list(t)}async set(t){return await super.set(t)}async getAllRecords({agent:t,tenantDid:n}){this._index.clear();let{reply:i}=await t.dwn.processRequest({author:n,target:n,messageType:De.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let s of i.entries??[]){if(!s.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);let o=fe.base64Url(s.encodedData).toObject();if(_h(o)){let c=`${n}${Ii}${o.uri}`;this._index.set(c,s.recordId),this._cache.set(s.recordId,o),a.push(o)}}return a}},Pg=class extends Uf{constructor(){super(...arguments);this.name="InMemoryDidStore"}async delete(t){return await super.delete(t)}async get(t){return await super.get(t)}async list(t){return await super.list(t)}async set(t){return await super.set(t)}};var vge=(t=>(t.Create="Create",t.Resolve="Resolve",t))(vge||{});function vH(r,e){return r.messageType===e}var Oh=class extends ag{constructor({agent:t,didMethods:n,resolverCache:i,store:a}){if(!n)throw new TypeError("AgentDidApi: Required parameter missing: 'didMethods'");super({didResolvers:n,cache:i??new Mf({agent:t,location:"DATA/AGENT/DID_CACHE"})});this._didMethods=new Map;this._agent=t,this._store=a??new Pg;for(let s of n)this._didMethods.set(s.methodName,s)}get agent(){if(this._agent===void 0)throw new Error("AgentDidApi: Unable to determine agent execution context.");return this._agent}set agent(t){this._agent=t,"agent"in this.cache&&(this.cache.agent=t)}async create({method:t,tenant:n,options:i,store:a}){let o=await this.getMethod(t).create({keyManager:this.agent.keyManager,options:i});if(await this.cache.set(o.uri,{didDocument:o.document,didResolutionMetadata:{},didDocumentMetadata:o.metadata}),a??!0){let{uri:c,document:l,metadata:d}=o,u={uri:c,document:l,metadata:d};await this._store.set({id:u.uri,data:u,agent:this.agent,tenant:n??u.uri,preventDuplicates:!1,useCache:!0})}return o}async export({didUri:t,tenant:n}){let i=await this.get({didUri:t,tenant:n});if(!i)throw new Error(`AgentDidApi: Failed to export due to DID not found: ${t}`);return await i.export()}async get({didUri:t,tenant:n}){let i=await this._store.get({id:t,agent:this.agent,tenant:n,useCache:!0});return i?await xs.import({portableDid:i,keyManager:this.agent.keyManager}):void 0}async getSigningMethod({didUri:t,methodId:n}){let i=Vn.parse(t);if(!i)throw new Error(`Invalid DID URI: ${t}`);let a=this.getMethod(i.method),{didDocument:s,didResolutionMetadata:o}=await this.resolve(t);if(!s)throw new Error(`DID resolution failed for '${t}': ${JSON.stringify(o)}`);return await a.getSigningMethod({didDocument:s,methodId:n})}async update({tenant:t,portableDid:n,publish:i=!0}){let a=await this.get({didUri:n.uri,tenant:t??n.uri});if(!a)throw new Error(`AgentDidApi: Could not update, DID not found: ${n.uri}`);if(sv(n.document)===sv(a.document))throw new Error("AgentDidApi: No changes detected, update aborted");let s=await xs.import({keyManager:this.agent.keyManager,portableDid:n}),{uri:o,document:c,metadata:l}=s,d={uri:o,document:c,metadata:l};return await this.cache.set(o,{didDocument:c,didResolutionMetadata:{},didDocumentMetadata:l}),await this._store.set({id:o,data:d,agent:this.agent,tenant:t??o,updateExisting:!0,useCache:!0}),i&&Vn.parse(o)?.method==="dht"&&await wo.publish({did:s}),s}async import({portableDid:t,tenant:n}){let i=await xs.import({keyManager:this.agent.keyManager,portableDid:t}),{uri:a,document:s,metadata:o}=i,c={uri:a,document:s,metadata:o};return await this.cache.set(a,{didDocument:s,didResolutionMetadata:{},didDocumentMetadata:o}),await this._store.set({id:c.uri,data:c,agent:this.agent,tenant:n??c.uri,preventDuplicates:!0,useCache:!0}),i}async delete({didUri:t,tenant:n,deleteKey:i=!0}){let a=await this._store.get({id:t,agent:this.agent,tenant:n,useCache:!1});if(!a)throw new Error("AgentDidApi: Could not delete, DID not found");await this.cache.delete(t),await this._store.delete({id:t,agent:this.agent,tenant:n}),i&&await this.deleteKeys({portableDid:a})}async deleteKeys({portableDid:t}){for(let n of t.document.verificationMethod||[]){if(!n.publicKeyJwk)continue;let i=await this.agent.keyManager.getKeyUri({key:n.publicKeyJwk});await this.agent.keyManager.deleteKey({keyUri:i})}}async processRequest(t){if(vH(t,"Create"))try{let n=await this.create({...t.messageParams});return{result:{uri:n.uri,document:n.document,metadata:n.metadata},ok:!0,status:{code:201,message:"Created"}}}catch(n){return{ok:!1,status:{code:500,message:n.message??"Unknown error occurred"}}}if(vH(t,"Resolve")){let{didUri:n,options:i}=t.messageParams;return{result:await this.resolve(n,i),ok:!0,status:{code:200,message:"OK"}}}throw new Error(`AgentDidApi: Unsupported request type: ${t.messageType}`)}getMethod(t){let n=this._didMethods.get(t);if(n===void 0)throw new Error(`DID Method not supported: ${t}`);return n}};g();Zn();st();bn();Qo();g();Zn();st();var Ss=class r{constructor({agent:e}={}){this._cachedPermissions=new Pi.default({ttl:60*1e3});this._agent=e}get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}async getPermissionForRequest({connectedDid:e,delegateDid:t,delegate:n,messageType:i,protocol:a,cached:s=!1}){let o=[e,t,i,a].join("~"),c=s?this._cachedPermissions.get(o):void 0;if(c)return c;let l=await this.fetchGrants({author:t,target:t,grantor:e,grantee:t}),d=await r.matchGrantFromArray(e,t,{messageType:i,protocol:a},l,n);if(!d)throw new Error(`CachedPermissions: No permissions found for ${i}: ${a}`);return this._cachedPermissions.set(o,d),d}async fetchGrants({author:e,target:t,grantee:n,grantor:i,protocol:a,remote:s=!1,checkRevoked:o=!0}){let c=a?{protocol:a}:void 0,l={author:e,target:t,messageType:De.RecordsQuery,messageParams:{filter:{author:i,recipient:n,protocol:et.uri,protocolPath:et.grantPath,tags:c}}},{reply:d}=s?await this.agent.sendDwnRequest(l):await this.agent.processDwnRequest(l);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${d.status.detail}`);let u=o?await this.fetchRevokedGrantIds({author:e,target:t,grantor:i,remote:s,tags:c}):new Set,f=[];for(let p of d.entries){if(u.has(p.recordId))continue;let h=kr.parse(p);f.push({grant:h,message:p})}return f}async fetchRevokedGrantIds({author:e,target:t,grantor:n,remote:i,tags:a}){let s={author:e,target:t,messageType:De.RecordsQuery,messageParams:{filter:{author:n,protocol:et.uri,protocolPath:et.revocationPath,tags:a}}},{reply:o}=i?await this.agent.sendDwnRequest(s):await this.agent.processDwnRequest(s);if(o.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${o.status.detail}`);let c=new Set;for(let l of o.entries)l.descriptor.parentId!==void 0&&c.add(l.descriptor.parentId);return c}async fetchRequests({author:e,target:t,protocol:n,remote:i=!1}){let a=n?{protocol:n}:void 0,s={author:e,target:t,messageType:De.RecordsQuery,messageParams:{filter:{protocol:et.uri,protocolPath:et.requestPath,tags:a}}},{reply:o}=i?await this.agent.sendDwnRequest(s):await this.agent.processDwnRequest(s);if(o.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${o.status.detail}`);let c=[];for(let l of o.entries){let d=gd.parse(l);c.push({request:d,message:l})}return c}async isGrantRevoked({author:e,target:t,grantRecordId:n,remote:i=!1}){let a={author:e,target:t,messageType:De.RecordsRead,messageParams:{filter:{parentId:n,protocol:et.uri,protocolPath:et.revocationPath}}},{reply:s}=i?await this.agent.sendDwnRequest(a):await this.agent.processDwnRequest(a);if(s.status.code===404)return!1;if(s.status.code===200)return!0;throw new Error(`PermissionsApi: Failed to check if grant is revoked: ${s.status.detail}`)}async createGrant(e){let{author:t,store:n=!1,delegated:i=!1,...a}=e,s;et.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope};a.delegateKeyDelivery&&(o.delegateKeyDelivery=a.delegateKeyDelivery);let c=fe.object(o).toUint8Array(),l={recipient:a.grantedTo,protocol:et.uri,protocolPath:et.grantPath,dataFormat:"application/json",tags:s},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:t,target:t,messageType:De.RecordsWrite,messageParams:l,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${d.status.detail}`);let f={...u,encodedData:fe.uint8Array(c).toBase64Url()};return{grant:kr.parse(f),message:f}}async createRequest(e){let{author:t,store:n=!1,delegated:i=!1,...a}=e,s;et.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={description:a.description,delegated:i,scope:a.scope},c=fe.object(o).toUint8Array(),l={protocol:et.uri,protocolPath:et.requestPath,dataFormat:"application/json",tags:s},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:t,target:t,messageType:De.RecordsWrite,messageParams:l,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${d.status.detail}`);let f={...u,encodedData:fe.uint8Array(c).toBase64Url()};return{request:gd.parse(f),message:f}}async createRevocation(e){let{author:t,store:n=!1,grant:i,description:a}=e,s={description:a},o=fe.object(s).toUint8Array(),c;et.hasProtocolScope(i.scope)&&(c={protocol:i.scope.protocol});let l={parentContextId:i.id,protocol:et.uri,protocolPath:et.revocationPath,dataFormat:"application/json",tags:c};e.permissionGrantId&&(l.permissionGrantId=e.permissionGrantId);let{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:t,target:t,messageType:De.RecordsWrite,messageParams:l,granteeDid:e.granteeDid,dataStream:new Blob([o])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${d.status.detail}`);return{message:{...u,encodedData:fe.uint8Array(o).toBase64Url()}}}async clear(){this._cachedPermissions.clear()}static async matchGrantFromArray(e,t,n,i,a=!1){let s;for(let o of i){let{grant:c,message:l}=o;if(a===!0&&c.delegated!==!0)continue;let{messageType:d,protocol:u,protocolPath:f,contextId:p}=n;if(this.matchScopeFromGrant(e,t,d,c,u,f,p)){if(c.scope.interface+c.scope.method===d)return{grant:c,message:l};s||(s={grant:c,message:l})}}return s}static matchScopeFromGrant(e,t,n,i,a,s,o){if(i.grantee!==t||i.grantor!==e)return!1;let c=i.scope,l=c.interface+c.method;if(c.interface==="Messages"?c.method==="Read"&&(n===De.MessagesRead||n===De.MessagesSync||n===De.MessagesSubscribe):l===n)if(V6(n)){let u=c;if(u.protocol!==a)return!1;if(this.isUnrestrictedProtocolScope(u)||u.protocolPath!==void 0&&u.protocolPath===s||u.contextId!==void 0&&o?.startsWith(u.contextId))return!0}else{let u=c;return u.protocol===void 0?!0:u.protocol!==a?!1:this.isUnrestrictedProtocolScope(u)}return!1}static isUnrestrictedProtocolScope(e){return e.contextId===void 0&&e.protocolPath===void 0}};g();g();var bge="@enbox/dwn-server";function sS(r){return r.endsWith("/")?r.slice(0,-1):r}var jh=class{constructor(e,t=1e4,n){this._rpcClient=e;this._cacheTtlMs=t;this._discoveryFile=n;this._cacheExpiry=0}async getEndpoint(){let e=Date.now();if(e<this._cacheExpiry)return this._cachedEndpoint;let t=await this._tryDiscoveryFile();if(t!==void 0)return this._setCacheEntry(t,e),t;this._setCacheEntry(void 0,e)}async setCachedEndpoint(e){let t=sS(e),n=await this._validateEndpoint(t);return n&&this._setCacheEntry(t,Date.now()),n}clearCache(){this._cachedEndpoint=void 0,this._cacheExpiry=0}async _tryDiscoveryFile(){if(this._discoveryFile)try{let e=await this._discoveryFile.read();return e&&await this._validateEndpoint(e.endpoint)?e.endpoint:void 0}catch{return}}async _validateEndpoint(e){try{return(await this._rpcClient.getServerInfo(e)).server===bge}catch{return!1}}_setCacheEntry(e,t){this._cachedEndpoint=e,this._cacheExpiry=t+this._cacheTtlMs}};function Pge(){try{let r=_S,e=r("node:fs/promises"),t=r("node:path"),n=r("node:os");return{async readFile(i){try{return await e.readFile(i,"utf-8")}catch{return null}},async writeFile(i,a){await e.mkdir(t.dirname(i),{recursive:!0}),await e.writeFile(i,a,{encoding:"utf-8",mode:384})},async removeFile(i){try{await e.unlink(i)}catch{}},isProcessAlive(i){try{return process.kill(i,0),!0}catch{return!1}},homedir(){return n.homedir()}}}catch{return}}var xge=".enbox",Ege="dwn.json",oS=class{constructor(e,t){let n=e??Pge();if(!n)throw new Error("DwnDiscoveryFile: No filesystem adapter available. Provide a DiscoveryFileFs implementation or run in Node.js / Bun.");if(this._fs=n,t)this._filePath=t;else{let a=_S("node:path");this._filePath=a.join(n.homedir(),xge,Ege)}}get path(){return this._filePath}async read(){let e=await this._fs.readFile(this._filePath);if(e===null)return;let t;try{t=JSON.parse(e)}catch{await this._fs.removeFile(this._filePath);return}if(!Sge(t)){await this._fs.removeFile(this._filePath);return}if(!this._fs.isProcessAlive(t.pid)){await this._fs.removeFile(this._filePath);return}let n={endpoint:sS(t.endpoint),pid:t.pid};return t.capabilities!==void 0&&(n.capabilities=t.capabilities),n}async write(e){let t={endpoint:sS(e.endpoint),pid:e.pid};e.capabilities!==void 0&&e.capabilities.length>0&&(t.capabilities=e.capabilities);let n=JSON.stringify(t,null,2);await this._fs.writeFile(this._filePath,n)}async remove(){await this._fs.removeFile(this._filePath)}};function Sge(r){if(typeof r!="object"||r===null)return!1;let e=r;return!(typeof e.endpoint!="string"||e.endpoint.length===0||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||e.capabilities!==void 0&&(!Array.isArray(e.capabilities)||!e.capabilities.every(t=>typeof t=="string")))}g();Zn();function qa(r,e){return r.messageType===e}function kge(r,e){return e.descriptor.interface+e.descriptor.method===r}function V6(r){return r===De.RecordsDelete||r===De.RecordsQuery||r===De.RecordsRead||r===De.RecordsSubscribe||r===De.RecordsWrite}function Mh(r){return r.interface===ve.Records}function _ge(r){return r.interface===ve.Messages}g();Zn();bn();function aS(r){return r===ci.XC20P?24:12}function Kh(r,e,t,n,i){return{initializationVector:e,key:r,keyEncryptionInputs:[{publicKeyId:t,publicKey:n,derivationScheme:i}]}}async function cS(r,e,t,n=ci.A256GCM){let{ciphertextStream:i,tag:a}=await xi.aeadEncryptStream(n,e,t,zt.fromBytes(r)),s=await zt.toBytes(i),o=zt.fromBytes(s),c=await ur.computeDagPbCidFromStream(o);return{encryptedBytes:s,dataCid:c,dataSize:s.length,authenticationTag:a}}async function za(r,e){let{didDocument:t,didResolutionMetadata:n}=await r.did.resolve(e);if(!t)throw new Error(`AgentDwnApi: Failed to resolve DID '${e}': ${JSON.stringify(n)}`);let i=t.keyAgreement;if(!i||i.length===0)throw new Error(`AgentDwnApi: DID '${e}' does not have a keyAgreement verification method. Create the identity with an X25519 key with keyAgreement purpose to use protocol encryption.`);let a=i[0],s;if(typeof a=="string"){let l=a.includes("#")?a.split("#").pop():a;s=t.verificationMethod?.find(d=>d.id.endsWith(`#${l}`))}else s=a;if(!s?.publicKeyJwk)throw new Error(`AgentDwnApi: keyAgreement verification method for '${e}' does not contain a public key in JWK format.`);let o=s.publicKeyJwk;if(o.crv==="Ed25519")o=await Kn.convertPublicKeyToX25519({publicKey:o});else if(o.crv!=="X25519")throw new Error(`AgentDwnApi: keyAgreement key for '${e}' uses curve '${o.crv}', but DWN encryption requires 'X25519' (or 'Ed25519' which is auto-converted).`);let c=await r.keyManager.getKeyUri({key:o});return{keyId:s.id,keyUri:c,publicKeyJwk:o}}async function PH(r,e,t,n,i){let{keyId:a,keyUri:s}=await za(r,e),o=Ae.constructKeyDerivationPathUsingProtocolContextScheme(t),c=await r.keyManager.derivePublicKey({keyUri:s,derivationPath:o});return{encryptionInput:Kh(n,i,a,c,xt.ProtocolContext),keyId:a,keyUri:s,contextDerivationPath:o}}function xH(r,e,t,n){let i=r.keyManager;return{rootKeyId:e,derivationScheme:n,decrypt:async(a,s)=>i.jweKeyUnwrap({keyUri:t,derivationPath:a,encryptedKey:s.encryptedKey,ephemeralPublicKey:s.ephemeralPublicKey})}}async function Ib(r,e){let{keyId:t,keyUri:n}=await za(r,e),i=r.keyManager;return{rootKeyId:t,derivationScheme:xt.ProtocolPath,derivePublicKey:async a=>i.derivePublicKey({keyUri:n,derivationPath:a})}}async function W6(r,e){let{keyId:t,keyUri:n}=await za(r,e);return xH(r,t,n,xt.ProtocolPath)}function Tb(r){return{rootKeyId:r.rootKeyId,derivationScheme:r.derivationScheme,decrypt:async(e,t)=>{let n=await Ae.derivePrivateKey(r,e),i=await kt.bytesToPrivateKey({privateKeyBytes:n});return xi.ecdhEsUnwrapKey(i,t.ephemeralPublicKey,t.encryptedKey)}}}function Age(r){return{rootKeyId:r.rootKeyId,derivationScheme:r.derivationScheme,decrypt:async(e,t)=>{let n=r.derivationPath??[];if(n.length!==e.length||!n.every((s,o)=>s===e[o]))throw new Error(`Delegate decryption key is out of scope for this protocol path. Key path: [${n.join(", ")}], record path: [${e.join(", ")}].`);let i=await Ae.derivePrivateKey(r,e),a=await kt.bytesToPrivateKey({privateKeyBytes:i});return xi.ecdhEsUnwrapKey(a,t.ephemeralPublicKey,t.encryptedKey)}}}async function bH(r,e,t,n,i,a,s,o,c){let{encryption:l}=t;if(!l?.recipients.some(E=>E.header.derivationScheme===xt.ProtocolContext)||!t.contextId){if(s&&o){let E=t.descriptor.protocol,_=t.descriptor.protocolPath;if(E){let A=`ddk~${o}`,D=s.get(A);if(D){let M=D.filter(z=>z.protocol===E);if(_){let z=M.find(L=>L.scope.kind==="protocolPath"&&L.scope.protocolPath===_);if(z)return Age(z.derivedPrivateKey)}let C=M.find(z=>z.scope.kind==="protocol");if(C)return Tb(C.derivedPrivateKey)}}}return W6(r,e)}let u=l.recipients.find(E=>E.header.derivationScheme===xt.ProtocolContext),f=t.contextId.split("/")[0];if(c&&o){let E=t.descriptor.protocol;if(E){let _=`dctx~${o}~${E}~${f}`,A=c.get(_);if(A)return Tb(A);try{let D=await a({ownerDid:e,requesterDid:o,sourceProtocol:E,sourceContextId:f});if(D)return c.set(_,D),Tb(D)}catch{}}throw new Error(`AgentDwnApi: Delegate '${o}' does not have a context key for context '${f}'. No delivered contextKey record was found via the key-delivery protocol. The delegate may need to reconnect or wait for sync.`)}let{keyId:p,keyUri:h}=await za(r,e);if(u.header.kid===p)return xH(r,p,h,xt.ProtocolContext);let m=`ctx~${e}~${f}`,y=i.get(m);if(y)return Tb(y);let v=t.descriptor.protocol,w=await a({ownerDid:e,requesterDid:e,sourceProtocol:v,sourceContextId:f});if(!w){let{Jws:E}=await Promise.resolve().then(()=>(Zn(),uH)),_=n??E.getSignerDid(t.authorization.signature.signatures[0]);w=await a({ownerDid:_,requesterDid:e,sourceProtocol:v,sourceContextId:f})}if(!w)throw new Error(`AgentDwnApi: Failed to decrypt record '${t.recordId}'. Record uses context-derived encryption but no contextKey record could be found via the key-delivery protocol.`);return i.set(m,w),Tb(w)}async function EH(r,e,t,n,i,a,s){if(!("encryption"in r)||!r.encryption)return;let o=r,c=o.granteeDid;if(qa(o,De.RecordsRead)){let l=e;if(l.status.code===200&&l.entry?.recordsWrite?.encryption&&l.entry?.data){let d=await bH(t,o.author,l.entry.recordsWrite,o.target,n,i,a,c,s);try{l.entry.data=await Ae.decrypt(l.entry.recordsWrite,d,l.entry.data)}catch(u){throw new Error(`AgentDwnApi: Failed to decrypt record '${l.entry.recordsWrite.recordId}'. Original error: ${u.message}`)}}}if(qa(o,De.RecordsQuery)){let l=e;if(l.status.code===200&&l.entries){for(let d of l.entries)if(d.encryption&&d.encodedData){let u=await bH(t,o.author,d,o.target,n,i,a,c,s);try{let f=Ie.base64UrlToBytes(d.encodedData),p=zt.fromBytes(f),h=await Ae.decrypt(d,u,p),m=await zt.toBytes(h);d.encodedData=Ie.bytesToBase64Url(m)}catch(f){throw new Error(`AgentDwnApi: Failed to decrypt record '${d.recordId}'. Original error: ${f.message}`)}}}}}g();Zn();async function SH(r,e,t,n,i,a){if(i.get(e))return;let s=La.protocol;if(!await n(e,s)){let c=await Ib(r,e),l=await Sd.deriveAndInjectPublicEncryptionKeys(La,c),{reply:{status:d}}=await t({author:e,target:e,messageType:De.ProtocolsConfigure,messageParams:{definition:l}});if(d.code!==202)throw new Error(`AgentDwnApi: Failed to install key delivery protocol: ${d.code} - ${d.detail}`);a.delete(`${e}~${s}`)}i.set(e,!0)}async function kH(r,e,t,n,i,a){let{tenantDid:s,recipientDid:o,contextKeyData:c,sourceProtocol:l,sourceContextId:d,recipientKeyDeliveryPublicKey:u}=e;await n(s);let f=La.protocol,p=new TextEncoder().encode(JSON.stringify(c)),h={protocol:f,protocolPath:"contextKey",dataFormat:"application/json",recipient:o,tags:{protocol:l,contextId:d}},m,y;if(u){let v=ci.A256GCM,w=crypto.getRandomValues(new Uint8Array(32)),E=crypto.getRandomValues(new Uint8Array(aS(v))),{encryptedBytes:_,dataCid:A,dataSize:D,authenticationTag:M}=await cS(p,w,E,v),C={...Kh(w,E,u.rootKeyId,u.publicKeyJwk,xt.ProtocolPath),authenticationTag:M};({message:m,reply:{status:y}}=await t({author:s,target:s,messageType:De.RecordsWrite,messageParams:{...h,dataCid:A,dataSize:D,encryptionInput:C},dataStream:new Blob([_])}))}else({message:m,reply:{status:y}}=await t({author:s,target:s,messageType:De.RecordsWrite,messageParams:h,dataStream:new Blob([p],{type:"application/json"}),encryption:!0}));if(!(m&&y.code===202))throw new Error(`AgentDwnApi: Failed to write contextKey record for ${o}: ${y.code} - ${y.detail}`);return a(i(s,m).catch(v=>{console.warn(`AgentDwnApi: Eager send of contextKey record '${m.recordId}' to remote DWN failed: ${v.message}. Sync will deliver it later.`)})),m.recordId}async function _H(r,e,t,n,i,a){let s;try{s=await a(e)}catch{return}if(s.length===0)return;let{data:o}=await n({author:e,messageType:De.RecordsWrite,messageCid:await ye.getCid(t)});await i({targetDid:e,dwnEndpointUrls:s,message:t,data:o})}async function Tge(r,e,t,n,i){try{let{reply:a}=await r({author:e,target:t,messageType:De.RecordsQuery,messageParams:{filter:n}});if(a.status.code!==200||!a.entries?.length)return;let s=a.entries[0].recordId,{reply:o}=await r({author:e,target:t,messageType:De.RecordsRead,messageParams:{filter:{recordId:s}},encryption:!0}),c=o;return c.entry?.data?i(await zt.toBytes(c.entry.data)):void 0}catch{return}}async function AH(r,e,t){let{ownerDid:n,requesterDid:i,sourceProtocol:a,sourceContextId:s}=e,o=La.protocol,c=n===i,l={protocol:o,protocolPath:"contextKey",recipient:i,tags:{protocol:a,contextId:s}},d=u=>JSON.parse(new TextDecoder().decode(u));if(c){let{reply:u}=await t({author:i,target:n,messageType:De.RecordsQuery,messageParams:{filter:l}});if(u.status.code!==200||!u.entries?.length)return;let f=u.entries[0].recordId,{reply:p}=await t({author:i,target:n,messageType:De.RecordsRead,messageParams:{filter:{recordId:f}},encryption:!0}),h=p;return h.entry?.data?d(await zt.toBytes(h.entry.data)):void 0}return Tge(t,i,n,l,d)}g();Zn();async function TH(r,e,t,n,i,a,s){let o=`${r}~${e}`,c=i.get(o);if(c)return c;let d=await n(a??r),u=await Ch[De.ProtocolsQuery].create({filter:{protocol:e},signer:d,...s?{permissionGrantId:s}:{}}),f=await t.processMessage(r,u.message);if(f.status.code!==200||!f.entries?.length)return;let p=f.entries[0].descriptor.definition;return i.set(o,p),p}async function IH(r,e,t,n,i){let a=`remote~${r}~${e}`,s=i.get(a);if(s)return s;let o=await Ch[De.ProtocolsQuery].create({filter:{protocol:e}}),c=await n({targetDid:r,dwnEndpointUrls:await t(r),message:o.message});if(c.status.code!==200||!c.entries?.length)throw new Error(`AgentDwnApi: Failed to fetch protocol '${e}' from '${r}'. The recipient may not have the protocol installed.`);let l=c.entries[0].descriptor.definition;return i.set(a,l),l}async function DH(r,e,t,n,i,a,s){let o=await a(n),c=await Ch[De.RecordsQuery].create({signer:o,filter:{protocol:e,contextId:t}}),l=await i(r),d=await s({targetDid:r,dwnEndpointUrls:l,message:c.message});if(!(d.status.code!==200||!d.entries?.length)){for(let u of d.entries)if(u.encryption?.recipients){let f=u.encryption.recipients.find(p=>p.header.derivationScheme===xt.ProtocolContext&&p.header.derivedPublicKey);if(f?.header.derivedPublicKey)return{rootKeyId:f.header.kid,derivedPublicKey:f.header.derivedPublicKey}}}}var Jl=class r{constructor(e){this._protocolDefinitionCache=new Pi.default({ttl:30*60*1e3});this._contextKeyCache=new Pi.default({ttl:30*60*1e3});this._contextDerivedKeyCache=new Pi.default({ttl:30*60*1e3});this._delegateDecryptionKeyCache=new Pi.default({ttl:24*60*60*1e3});this._delegateContextKeyCache=new Pi.default({ttl:24*60*60*1e3});this._delegateContextKeyCacheIndex=new Map;this._delegateMultiPartyProtocols=new Map;this._localManagedDidCache=new Pi.default({ttl:30*60*1e3});this._pendingEagerSends=new Set;this._keyDeliveryProtocolInstalledCache=new Pi.default({ttl:21*24*60*60*1e3,max:1e3});let{agent:t,localDwnStrategy:n="prefer"}=e;this._agent=t,this._dwn="dwn"in e?e.dwn:void 0,this._localDwnEndpoint="localDwnEndpoint"in e?e.localDwnEndpoint:void 0,this._localDwnStrategy=n,t&&(this._localDwnDiscovery=new jh(t.rpc,1e4,r._tryCreateDiscoveryFile()))}get isRemoteMode(){return this._dwn===void 0}get agent(){if(this._agent===void 0)throw new Error("AgentDwnApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._localDwnDiscovery=new jh(e.rpc,1e4,r._tryCreateDiscoveryFile()),this._localManagedDidCache.clear()}get localDwnStrategy(){return this._localDwnStrategy}setLocalDwnStrategy(e){this._localDwnStrategy=e}async setCachedLocalDwnEndpoint(e){return this._localDwnDiscovery??=new jh(this.agent.rpc,1e4,r._tryCreateDiscoveryFile()),this._localDwnDiscovery.setCachedEndpoint(e)}async getDwnEndpointUrlsForTarget(e){if(!await this.shouldUseLocalDwnForTarget(e))return mg(e,this.agent.did);let n=await this.getLocalDwnEndpoint();if(this._localDwnStrategy==="only"){if(!n)throw new Error("AgentDwnApi: Local DWN strategy is 'only' but no local DWN endpoint was discovered. Ensure the local DWN server is running and discoverable via the discovery file (~/.enbox/dwn.json) or dwn://connect.");return[n]}let i=[];try{i=await mg(e,this.agent.did)}catch(s){if(!n)throw s}return n?[...new Set([n,...i])]:i}async getRemoteDwnEndpointUrls(e){return mg(e,this.agent.did)}async getLocalDwnEndpoint(){return this._localDwnEndpoint?this._localDwnEndpoint:(this._localDwnDiscovery??=new jh(this.agent.rpc,1e4,r._tryCreateDiscoveryFile()),this._localDwnDiscovery.getEndpoint())}static _tryCreateDiscoveryFile(){try{return new oS}catch{return}}async shouldUseLocalDwnForTarget(e){if(this._localDwnStrategy==="off")return!1;let t=this._localManagedDidCache.get(e);if(t!==void 0)return t;if(e===this.agent.agentDid.uri)return this._localManagedDidCache.set(e,!0),!0;let n=await this.agent.identity.list(),i=new Set;for(let s of n)i.add(s.did.uri),s.metadata.connectedDid&&i.add(s.metadata.connectedDid);for(let s of i)this._localManagedDidCache.set(s,!0);let a=i.has(e);return a||this._localManagedDidCache.set(e,!1),a}get node(){if(!this._dwn)throw new Error(`AgentDwnApi: The in-process DWN instance is not available. The agent is operating in remote mode (local DWN server at '${this._localDwnEndpoint}'). Use processRequest() instead of accessing the DWN node directly.`);return this._dwn}static async createDwn({dataPath:e,dataStore:t,didResolver:n,stateIndex:i,eventLog:a,messageStore:s,tenantGate:o,resumableTaskStore:c}){return t??=new Cf({blockstoreLocation:`${e}/DWN_DATASTORE`}),n??=new ag({didResolvers:[wo,Xo],cache:new EE({location:`${e}/DID_RESOLVERCACHE`})}),i??=new jf({location:`${e}/DWN_STATEINDEX`}),s??=new $f({blockstoreLocation:`${e}/DWN_MESSAGESTORE`,indexLocation:`${e}/DWN_MESSAGEINDEX`}),c??=new Bf({location:`${e}/DWN_RESUMABLETASKSTORE`}),a??=new Of,await cg.create({dataStore:t,didResolver:n,stateIndex:i,eventLog:a,messageStore:s,tenantGate:o,resumableTaskStore:c})}async processRequest(e){let{message:t,dataStream:n}=await this.constructDwnMessage({request:e}),{subscriptionHandler:i}=e,a;if(e.store===!1)a={status:{code:202,detail:"Accepted"}};else if(this._dwn)a=await this._dwn.processMessage(e.target,t,{dataStream:n,subscriptionHandler:i});else{let s;if(n){let o=await zt.toBytes(n);s=new Blob([o])}a=await this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:[this._localDwnEndpoint],message:t,data:s,subscriptionHandler:i})}return await Promise.all([this.postWriteKeyDelivery(e,t,a),this.maybeDecryptReply(e,a)]),{reply:a,message:t,messageCid:await ye.getCid(t)}}async processRawMessage(e,t,n){if(this._dwn)return this._dwn.processMessage(e,t,{dataStream:n?.dataStream});let i;if(n?.dataStream){let a=await zt.toBytes(n.dataStream);i=new Blob([a])}return this.sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:[this._localDwnEndpoint],message:t,data:i})}async sendRequest(e){let t=await this.getDwnEndpointUrlsForTarget(e.target);if(t.length===0)throw new Error(`AgentDwnApi: DID Service is missing or malformed: ${e.target}#dwn`);let n,i,a,s;if("messageCid"in e)({message:i,data:a}=await this.getDwnMessage({author:e.author,messageCid:e.messageCid,messageType:e.messageType})),n=e.messageCid;else{if({message:i}=await this.constructDwnMessage({request:e}),e.dataStream&&!(e.dataStream instanceof Blob))throw new Error("AgentDwnApi: DataStream must be provided as a Blob");a=e.dataStream,s=e.subscriptionHandler}let o;s!==void 0&&!("messageCid"in e)&&(o=async l=>{let d=l===void 0?e.messageParams:{...e.messageParams,cursor:l},u={...e,messageParams:d},{message:f}=await this.constructDwnMessage({request:u});return f});let c=await this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:t,message:i,data:a,subscriptionHandler:s,resubscribeFactory:o});return await this.maybeDecryptReply(e,c),n??=await ye.getCid(i),{reply:c,message:i,messageCid:n}}async postWriteKeyDelivery(e,t,n){if(!qa(e,De.RecordsWrite)||!e.encryption||n.status.code!==202)return;let i=e.messageParams;if(i.protocol!==La.protocol)try{let a=await this.getProtocolDefinition(e.target,i.protocol);if(!a)return;let s=t,o=ct.getSignerDid(s.authorization.signature.signatures[0]),c=o!==e.target,l=!i.parentContextId,d=i.protocolPath.split("/")[0],u=$h(a,d),f=z6({protocolDefinition:a,protocolPath:i.protocolPath,recipient:i.recipient,tenantDid:e.target,authorDid:c?o:void 0}),p=s.contextId?.split("/")[0]||s.contextId||s.recordId,h=u&&l&&!c&&this.hasEligibleDelegatesForProtocol(i.protocol),m=u&&l&&!c;if(f.size>0||h||m){let{keyId:y,keyUri:v}=await za(this.agent,e.target),w=[xt.ProtocolContext,p],E=await this.agent.keyManager.derivePrivateKeyBytes({keyUri:v,derivationPath:w}),_=await kt.bytesToPrivateKey({privateKeyBytes:E}),A={rootKeyId:y,derivationScheme:xt.ProtocolContext,derivationPath:w,derivedPrivateKey:_};if(f.size>0){let D=s.authorization?.authorKeyDeliveryPublicKey;for(let M of f)try{let C=M===o&&D?D:void 0;await this.writeContextKeyRecord({tenantDid:e.target,recipientDid:M,contextKeyData:A,sourceProtocol:i.protocol,sourceContextId:p,recipientKeyDeliveryPublicKey:C})}catch(C){console.warn(`AgentDwnApi: Key delivery to '${M}' for context '${p}' failed: ${C.message}. The participant may not be able to decrypt records in this context.`)}}h&&this.deliverContextKeyToDelegates(i.protocol,p,A),m&&await this.deliverContextKeyToDelegatesViaDwn(e.target,i.protocol,p,A)}}catch(a){console.warn(`AgentDwnApi: Post-write participant detection failed: ${a.message}`)}}async sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:t,message:n,data:i,subscriptionHandler:a,resubscribeFactory:s}){let o=[];if(n.descriptor.method===me.Subscribe&&a===void 0)throw new Error("AgentDwnApi: Subscription handler is required for subscription requests.");for(let c of t)try{if(a!==void 0){if(!(await this.agent.rpc.getServerInfo(c)).webSocketSupport){o.push({url:c,message:"WebSocket support is not enabled on the server."});continue}let u=new URL(c);u.protocol=u.protocol==="http:"?"ws:":"wss:",c=u.toString()}return await this.agent.rpc.sendDwnRequest({dwnUrl:c,targetDid:e,message:n,data:i,subscription:a?{handler:a,resubscribeFactory:s}:void 0})}catch(l){o.push({url:c,message:l instanceof Error?l.message:"Unknown error"})}throw new Error(`Failed to send DWN RPC request: ${JSON.stringify(o)}`)}async constructDwnMessage({request:e}){if(e.granteeDid&&!this.hasGrantParams(e.messageParams))throw new Error("AgentDwnApi: Requested to sign with a permission but no grant messageParams were provided in the request");let t=e.rawMessage,n;if(qa(e,De.RecordsWrite)){let o=e.messageParams;if(e.dataStream&&!o?.data){let{dataStream:c}=e,l;if(c instanceof Blob){let[d,u]=c.stream().tee();l=d,n=u}else if(c instanceof ReadableStream){let[d,u]=c.tee();l=d,n=u}!t&&o&&(o.dataCid=await ur.computeDagPbCidFromStream(l),o.dataSize===void 0&&c instanceof Blob&&(o.dataSize=c.size))}}if(qa(e,De.ProtocolsConfigure)&&e.encryption&&!t){let o=e.messageParams,c=await Ib(this.agent,e.author);o.definition=await Sd.deriveAndInjectPublicEncryptionKeys(o.definition,c),this._protocolDefinitionCache.delete(`${e.target}~${o.definition.protocol}`)}if(qa(e,De.ProtocolsConfigure)&&!e.encryption&&!t){let o=e.messageParams?.definition;o?.protocol&&this._protocolDefinitionCache.set(`${e.target}~${o.protocol}`,o)}let i;if(qa(e,De.RecordsWrite)&&e.encryption&&!t){let o=e.messageParams;if(o?.protocol&&o.protocolPath){let c=e.target!==e.author,l;if(c?l=await this.fetchRemoteProtocolDefinition(e.target,o.protocol):l=await this.getProtocolDefinition(e.target,o.protocol,e.granteeDid),!l)throw new Error(`AgentDwnApi: Protocol '${o.protocol}' is not installed for '${e.target}'. Install the protocol before writing encrypted records.`);let d=o.protocolPath.split("/"),u=l.structure;for(let L of d)u=u[L];if(!u?.$encryption)throw new Error(`AgentDwnApi: Protocol '${o.protocol}' at path '${o.protocolPath}' does not have encryption configured. Configure the protocol with encryption: true.`);let f=o.protocolPath.split("/")[0],h=o.protocol===La.protocol?!1:$h(l,f),m=!o.parentContextId,y;if(o.data)y=o.data instanceof Uint8Array?o.data:new TextEncoder().encode(String(o.data));else if(e.dataStream instanceof Blob)y=new Uint8Array(await e.dataStream.arrayBuffer());else if(e.dataStream instanceof ReadableStream)y=await zt.toBytes(e.dataStream);else throw new Error("AgentDwnApi: Data must be provided for encrypted records.");let v=ci.A256GCM,w=crypto.getRandomValues(new Uint8Array(32)),E=crypto.getRandomValues(new Uint8Array(aS(v))),_,A=()=>Kh(w,E,u.$encryption.rootKeyId,u.$encryption.publicKeyJwk,xt.ProtocolPath);if(c&&h&&m)_=A();else if(c&&h&&!m){let L=o.parentContextId.split("/")[0]||o.parentContextId,B=await this.extractDerivedPublicKey(e.target,o.protocol,L,e.author);B?_=Kh(w,E,B.rootKeyId,B.derivedPublicKey,xt.ProtocolContext):_=A()}else if(c)_=A();else if(h&&!m){let L=o.parentContextId.split("/")[0]||o.parentContextId,B=this._contextKeyCache.get(L);if(!B){let{keyId:ee,keyUri:R}=await za(this.agent,e.author),$=Ae.constructKeyDerivationPathUsingProtocolContextScheme(L);B={keyId:ee,keyUri:R,contextDerivationPath:$},this._contextKeyCache.set(L,B)}let W=await this.agent.keyManager.derivePublicKey({keyUri:B.keyUri,derivationPath:B.contextDerivationPath});_=Kh(w,E,B.keyId,W,xt.ProtocolContext)}else h&&m?_=void 0:_=A();let{encryptedBytes:D,dataCid:M,dataSize:C,authenticationTag:z}=await cS(y,w,E,v);if(o.dataCid=M,o.dataSize=C,delete o.data,n=zt.fromBytes(D),e.dataStream=void 0,_?(_.authenticationTag=z,o.encryptionInput=_):i={dataEncryptionKey:w,dataEncryptionIV:E,encryptedBytes:D,authenticationTag:z},c&&h){let{keyId:L,keyUri:B}=await za(this.agent,e.author),W=[xt.ProtocolPath,La.protocol,"contextKey"],ee=await this.agent.keyManager.derivePublicKey({keyUri:B,derivationPath:W});o.authorKeyDeliveryPublicKey={rootKeyId:L,publicKeyJwk:ee}}}}let a,s=Ch[e.messageType];if(t){if(a=await s.parse(t),Kd(a)&&e.signAsOwner){let o=await this.getSigner(e.author);await a.signAsOwner(o)}else if(e.granteeDid&&Kd(a)&&e.signAsOwnerDelegate){let o=await this.getSigner(e.granteeDid),c=e.messageParams;await a.signAsOwnerDelegate(o,c.delegatedGrant)}}else{if(e.messageParams===void 0)throw new Error("AgentDwnApi: messageParams must be provided when rawMessage is not given.");let o=e.granteeDid?await this.getSigner(e.granteeDid):await this.getSigner(e.author),c={...e.messageParams};if(e.granteeDid&&c.permissionGrantId&&!c.delegatedGrant&&qa(e,De.RecordsWrite)){let{reply:l}=await this.processRequest({author:e.granteeDid,target:e.author,messageType:De.RecordsRead,messageParams:{filter:{recordId:c.permissionGrantId}}});if(l.status.code===200&&l.entry?.recordsWrite&&l.entry?.data){let d=await zt.toBytes(l.entry.data);c.delegatedGrant={...l.entry.recordsWrite,encodedData:fe.uint8Array(d).toBase64Url()}}}if(a=await s.create({...c,signer:o}),i&&qa(e,De.RecordsWrite)){let l=a,d=l.message.recordId,{encryptionInput:u,keyId:f,keyUri:p,contextDerivationPath:h}=await PH(this.agent,e.author,d,i.dataEncryptionKey,i.dataEncryptionIV),m={...u,authenticationTag:i.authenticationTag};await l.encryptSymmetricEncryptionKey(m),await l.sign({signer:o}),this._contextKeyCache.set(d,{keyId:f,keyUri:p,contextDerivationPath:h})}}return{message:a.message,dataStream:n}}hasGrantParams(e){return e!==void 0&&("permissionGrantId"in e&&e.permissionGrantId!==void 0||"delegatedGrant"in e&&e.delegatedGrant!==void 0)}async getSigner(e){if(e===this.agent.agentDid.uri){let t=await this.agent.agentDid.getSigner();return{algorithm:t.algorithm,keyId:t.keyId,sign:async n=>await t.sign({data:n})}}else try{let t=await this.agent.did.get({didUri:e});if(t){let o=await t.getSigner();return{algorithm:o.algorithm,keyId:o.keyId,sign:async c=>await o.sign({data:c})}}let n=await this.agent.did.getSigningMethod({didUri:e});if(!n.publicKeyJwk)throw new Error(`Verification method '${n.id}' does not contain a public key in JWK format`);let i=await this.agent.keyManager.getKeyUri({key:n.publicKeyJwk}),a=await this.agent.keyManager.getPublicKey({keyUri:i}),s=this.agent.keyManager;return{algorithm:vn.getJoseSignatureAlgorithmFromPublicKey(a),keyId:n.id,sign:async o=>await s.sign({data:o,keyUri:i})}}catch(t){throw new Error(`AgentDwnApi: Unable to get signer for author '${e}': ${t.message}`)}}async getEncryptionKeyDeriver(e){return Ib(this.agent,e)}async getEncryptionKeyInfo(e){return za(this.agent,e)}async getKeyDecrypter(e){return W6(this.agent,e)}detectNewParticipants(e){return z6(e)}async getProtocolDefinition(e,t,n){if(!this._dwn)try{return await this.fetchRemoteProtocolDefinition(e,t)}catch(a){let s=a instanceof Error?a.message:"";if(s.includes("not found")||s.includes("404")||s.includes("No protocol"))return;throw a}let i;if(n)try{let a=new Ss({agent:this.agent}),{grant:s}=await a.getPermissionForRequest({connectedDid:e,delegateDid:n,protocol:t,cached:!0,messageType:De.ProtocolsQuery});i=s.id}catch{}return TH(e,t,this._dwn,this.getSigner.bind(this),this._protocolDefinitionCache,n,i)}async fetchRemoteProtocolDefinition(e,t){return IH(e,t,this.getDwnEndpointUrlsForTarget.bind(this),this.sendDwnRpcRequest.bind(this),this._protocolDefinitionCache)}async extractDerivedPublicKey(e,t,n,i){return DH(e,t,n,i,this.getDwnEndpointUrlsForTarget.bind(this),this.getSigner.bind(this),this.sendDwnRpcRequest.bind(this))}async maybeDecryptReply(e,t){return EH(e,t,this.agent,this._contextDerivedKeyCache,this.fetchContextKeyRecord.bind(this),this._delegateDecryptionKeyCache,this._delegateContextKeyCache)}async getDwnMessage({author:e,messageCid:t}){let n=await this.getSigner(e),i=await Ch[De.MessagesRead].create({messageCid:t,signer:n}),a;if(this._dwn?a=await this._dwn.processMessage(e,i.message):a=await this.sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:[this._localDwnEndpoint],message:i.message}),a.status.code!==200)throw new Error(`AgentDwnApi: Failed to read message, response status: ${a.status.code} - ${a.status.detail}`);let s=a.entry,c={message:s.message};if(Kd(s)){let l=s.data;if(l){let d=await zt.toBytes(l);c.data=new Blob([d],{type:s.message.descriptor.dataFormat})}}return c}async ensureKeyDeliveryProtocol(e){return SH(this.agent,e,this.processRequest.bind(this),this.getProtocolDefinition.bind(this),this._keyDeliveryProtocolInstalledCache,this._protocolDefinitionCache)}set onDelegateContextKeysChanged(e){this._onDelegateContextKeysChanged=e}importDelegateDecryptionKeys(e,t){let n=`ddk~${e}`;this._delegateDecryptionKeyCache.set(n,t)}importDelegateContextKeys(e,t,n){let i=this._delegateContextKeyCacheIndex.get(e);if(i)for(let o of i)this._delegateContextKeyCache.delete(o);let a=[];for(let o of t){let c=`dctx~${e}~${o.protocol}~${o.contextId}`;this._delegateContextKeyCache.set(c,o.derivedPrivateKey),a.push(c)}this._delegateContextKeyCacheIndex.set(e,a);let s=new Set(n??[]);for(let o of t)s.add(o.protocol);s.size>0?this._delegateMultiPartyProtocols.set(e,s):this._delegateMultiPartyProtocols.delete(e)}clearDelegateDecryptionKeys(e){if(e){this._delegateDecryptionKeyCache.delete(`ddk~${e}`);let t=this._delegateContextKeyCacheIndex.get(e);if(t){for(let n of t)this._delegateContextKeyCache.delete(n);this._delegateContextKeyCacheIndex.delete(e)}this._delegateMultiPartyProtocols.delete(e)}else this._delegateDecryptionKeyCache.clear(),this._delegateContextKeyCache.clear(),this._delegateContextKeyCacheIndex.clear(),this._delegateMultiPartyProtocols.clear()}exportDelegateContextKeys(e){let t=this._delegateContextKeyCacheIndex.get(e);if(!t)return[];let n=[],i=`dctx~${e}~`;for(let a of t){let s=this._delegateContextKeyCache.get(a);if(!s||!a.startsWith(i))continue;let o=a.slice(i.length),c=o.lastIndexOf("~");c!==-1&&n.push({protocol:o.slice(0,c),contextId:o.slice(c+1),derivedPrivateKey:s})}return n}exportDelegateMultiPartyProtocols(e){let t=this._delegateMultiPartyProtocols.get(e);return t?[...t]:[]}hasEligibleDelegatesForProtocol(e){for(let[,t]of this._delegateMultiPartyProtocols)if(t.has(e))return!0;return!1}deliverContextKeyToDelegates(e,t,n){for(let[i,a]of this._delegateMultiPartyProtocols){if(!a.has(e))continue;let s=`dctx~${i}~${e}~${t}`;if(this._delegateContextKeyCache.get(s))continue;this._delegateContextKeyCache.set(s,n);let o=this._delegateContextKeyCacheIndex.get(i)??[];o.push(s),this._delegateContextKeyCacheIndex.set(i,o),this._onDelegateContextKeysChanged?.(i)}}async deliverContextKeyToDelegatesViaDwn(e,t,n,i){try{let s=await new Ss({agent:this.agent}).fetchGrants({author:e,target:e,grantor:e,protocol:t,checkRevoked:!0}),o=new Set(["Read","Query","Subscribe"]),c=Date.now(),l=new Set;for(let d of s){if(!d.grant.delegated||new Date(d.grant.dateExpires).getTime()<=c)continue;let u=d.grant.scope;if(u.interface!=="Records"||!o.has(u.method)||u.protocolPath||u.contextId)continue;let f=d.grant.grantee,p=d.grant.delegateKeyDelivery;if(!p?.rootKeyId||!p?.publicKeyJwk||l.has(f))continue;let h=p.publicKeyJwk;try{await this.writeContextKeyRecord({tenantDid:e,recipientDid:f,contextKeyData:i,sourceProtocol:t,sourceContextId:n,recipientKeyDeliveryPublicKey:{rootKeyId:p.rootKeyId,publicKeyJwk:h}}),l.add(f)}catch(m){console.warn(`AgentDwnApi: Cross-device key delivery to delegate '${f}' for context '${n}' failed: ${m.message}. The delegate may need to reconnect.`)}}}catch(a){console.warn(`AgentDwnApi: Delegate grant discovery for protocol '${t}' failed: ${a.message}`)}}trackEagerSend(e){return this._pendingEagerSends.add(e),e.finally(()=>{this._pendingEagerSends.delete(e)}),e}async drainPendingEagerSends(){if(this._pendingEagerSends.size===0)return;let e=[...this._pendingEagerSends];await Promise.allSettled(e)}async writeContextKeyRecord(e){return kH(this.agent,e,this.processRequest.bind(this),this.ensureKeyDeliveryProtocol.bind(this),this.eagerSendContextKeyRecord.bind(this),this.trackEagerSend.bind(this))}async eagerSendContextKeyRecord(e,t){return _H(this.agent,e,t,this.getDwnMessage.bind(this),this.sendDwnRpcRequest.bind(this),this.getDwnEndpointUrlsForTarget.bind(this))}async fetchContextKeyRecord(e){return AH(this.agent,e,this.processRequest.bind(this))}};g();var CH="dwn",$H="connect";function KWe(r){return`${CH}://${$H}?callback=${encodeURIComponent(r)}`}function Ige(r){let e=JSON.stringify(r);return Cge(e)}function RH(r){try{let e=$ge(r),t=JSON.parse(e);return Dge(t)?t:void 0}catch{return}}function UWe(r){try{let e=`${CH}://`;if(!r.startsWith(e))return;let t=r.slice(e.length),n=t.indexOf("?");if(n===-1||t.slice(0,n)!==$H)return;let a=t.slice(n+1),o=new URLSearchParams(a).get("callback");return!o||o.length===0?void 0:{callback:o}}catch{return}}function NWe(r,e){let t=Ige(e);return`${r.split("#")[0]}#${t}`}function LWe(r){let e=r.indexOf("#");if(e===-1)return RH(r);let t=r.slice(e+1);if(t.length!==0)return RH(t)}function Dge(r){if(typeof r!="object"||r===null)return!1;let e=r;return!(typeof e.endpoint!="string"||e.endpoint.length===0||!Rge(e.endpoint))}function Rge(r){try{let t=new URL(r).hostname.toLowerCase();return!!(t==="127.0.0.1"||t==="::1"||t==="[::1]"||t==="localhost"||t.endsWith(".localhost"))}catch{return!1}}function Cge(r){let e=new TextEncoder().encode(r),t="";for(let a=0;a<e.length;a++)t+=String.fromCharCode(e[a]);let n=btoa(t).replaceAll("+","-").replaceAll("/","_"),i=n.length;for(;i>0&&n.codePointAt(i-1)===61;)i--;return i===n.length?n:n.slice(0,i)}function $ge(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=e.length%4;t===2?e+="==":t===3&&(e+="=");let n=atob(e),i=new Uint8Array(n.length);for(let a=0;a<n.length;a++)i[a]=n.charCodeAt(a);return new TextDecoder().decode(i)}g();g();PP();s1();g();u1();Ja();var Bge=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),OH=Uint8Array.from({length:16},(r,e)=>e),Oge=OH.map(r=>(9*r+5)%16),Z6=[OH],Y6=[Oge];for(let r=0;r<4;r++)for(let e of[Z6,Y6])e.push(e[r].map(t=>Bge[t]));var jH=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(r=>new Uint8Array(r)),jge=Z6.map((r,e)=>r.map(t=>jH[e][t])),Mge=Y6.map((r,e)=>r.map(t=>jH[e][t])),Kge=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Uge=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),dS=(r,e)=>r<<e|r>>>32-e;function BH(r,e,t,n){return r===0?e^t^n:r===1?e&t|~e&n:r===2?(e|~t)^n:r===3?e&n|t&~n:e^(t|~n)}var lS=new Uint32Array(16),J6=class extends iu{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){let{h0:e,h1:t,h2:n,h3:i,h4:a}=this;return[e,t,n,i,a]}set(e,t,n,i,a){this.h0=e|0,this.h1=t|0,this.h2=n|0,this.h3=i|0,this.h4=a|0}process(e,t){for(let p=0;p<16;p++,t+=4)lS[p]=e.getUint32(t,!0);let n=this.h0|0,i=n,a=this.h1|0,s=a,o=this.h2|0,c=o,l=this.h3|0,d=l,u=this.h4|0,f=u;for(let p=0;p<5;p++){let h=4-p,m=Kge[p],y=Uge[p],v=Z6[p],w=Y6[p],E=jge[p],_=Mge[p];for(let A=0;A<16;A++){let D=dS(n+BH(p,a,o,l)+lS[v[A]]+m,E[A])+u|0;n=u,u=l,l=dS(o,10)|0,o=a,a=D}for(let A=0;A<16;A++){let D=dS(i+BH(h,s,c,d)+lS[w[A]]+y,_[A])+f|0;i=f,f=d,d=dS(c,10)|0,c=s,s=D}}this.set(this.h1+o+d|0,this.h2+l+f|0,this.h3+u+i|0,this.h4+n+s|0,this.h0+a+c|0)}roundClean(){lS.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}},MH=am(()=>new J6);iw();wP();Ja();sm();var Nge=tw("ed25519 seed"),X6=2147483648,KH=new Uint8Array([0]);function UH(r,...e){return typeof r=="string"&&(r=q$(r)),Gd(r,...e),r}var Lge=r=>MH(au(r)),qge=r=>Vd(r).getUint32(0,!1),Q6=r=>{if(!Number.isSafeInteger(r)||r<0||r>2**32-1)throw new Error(`Invalid number=${r}. Should be from 0 to 2 ** 32 - 1`);let e=new Uint8Array(4);return Vd(e).setUint32(0,r,!1),e},uS=class r{get publicKeyRaw(){return pa.getPublicKey(this.privateKey)}get publicKey(){return Yf(KH,this.publicKeyRaw)}get pubHash(){return Lge(this.publicKey)}get fingerprint(){return qge(this.pubHash)}get fingerprintHex(){return rk(Q6(this.fingerprint))}get parentFingerprintHex(){return rk(Q6(this.parentFingerprint))}static fromMasterSeed(e){if(e=UH(e),8*e.length<128||8*e.length>512)throw new Error(`HDKey: wrong seed length=${e.length}. Should be between 128 and 512 bits; 256 bits is advised)`);let t=ru(Ru,Nge,e);return new r({privateKey:t.slice(0,32),chainCode:t.slice(32)})}constructor(e){if(this.depth=0,this.index=0,this.parentFingerprint=0,!e||typeof e!="object")throw new Error("HDKey.constructor must not be called directly");if(Gd(e.privateKey,32),Gd(e.chainCode,32),this.depth=e.depth||0,this.index=e.index||0,this.parentFingerprint=e.parentFingerprint||0,!this.depth&&(this.parentFingerprint||this.index))throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");this.chainCode=e.chainCode,this.privateKey=e.privateKey}derive(e,t=!1){if(!/^[mM]'?/.test(e))throw new Error('Path must start with "m" or "M"');if(/^[mM]'?$/.test(e))return this;let n=e.replace(/^[mM]'?\//,"").split("/"),i=this;for(let a of n){let s=/^(\d+)('?)$/.exec(a);if(!s||s.length!==3)throw new Error(`Invalid child index: ${a}`);let o=+s[1];if(!Number.isSafeInteger(o)||o>=X6)throw new Error("Invalid index");(t||s[2]==="'")&&(o+=X6),i=i.deriveChild(o)}return i}deriveChild(e){if(e<X6)throw new Error(`Non-hardened child derivation not possible for Ed25519 (index=${e})`);let t=Yf(KH,this.privateKey,Q6(e)),n=ru(Ru,this.chainCode,t);return new r({chainCode:n.slice(32),depth:this.depth+1,parentFingerprint:this.fingerprint,index:e,privateKey:n.slice(0,32)})}sign(e){return pa.sign(e,this.privateKey)}verify(e,t){return t=UH(t,64),pa.verify(t,e,this.publicKeyRaw)}};g();var e5=`abandon
11
11
  ability
12
12
  able
13
13
  about