@enbox/agent 0.5.4 → 0.5.6

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,jt._)`[${i}]`)}}}function fne({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,jt._)`${e} !== undefined`,()=>t.assign((0,jt._)`${e}[${r}]`,n))}function eD(t,e,r,n=yy.Correct){let i=n===yy.Correct?jt.operators.EQ:jt.operators.NEQ,a;switch(t){case"null":return(0,jt._)`${e} ${i} null`;case"array":a=(0,jt._)`Array.isArray(${e})`;break;case"object":a=(0,jt._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":a=s((0,jt._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":a=s();break;default:return(0,jt._)`typeof ${e} ${i} ${t}`}return n===yy.Correct?a:(0,jt.not)(a);function s(o=jt.nil){return(0,jt.and)((0,jt._)`typeof ${e} == "number"`,o,r?(0,jt._)`isFinite(${e})`:jt.nil)}}ms.checkDataType=eD;function tD(t,e,r,n){if(t.length===1)return eD(t[0],e,r,n);let i,a=(0,IN.toHash)(t);if(a.array&&a.object){let s=(0,jt._)`typeof ${e} != "object"`;i=a.null?s:(0,jt._)`!${e} || ${s}`,delete a.null,delete a.array,delete a.object}else i=jt.nil;a.number&&delete a.integer;for(let s in a)i=(0,jt.and)(i,eD(s,e,r,n));return i}ms.checkDataTypes=tD;var pne={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,jt._)`{type: ${t}}`:(0,jt._)`{type: ${e}}`};function rD(t){let e=hne(t);(0,ane.reportError)(e,pne)}ms.reportTypeError=rD;function hne(t){let{gen:e,data:r,schema:n}=t,i=(0,IN.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:t}}});var $N=_e(Px=>{"use strict";g();Object.defineProperty(Px,"__esModule",{value:!0});Px.assignDefaults=void 0;var gy=Bt(),mne=Zt();function yne(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let i in r)CN(t,i,r[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,a)=>CN(t,a,i.default))}Px.assignDefaults=yne;function CN(t,e,r){let{gen:n,compositeRule:i,data:a,opts:s}=t;if(r===void 0)return;let o=(0,gy._)`${a}${(0,gy.getProperty)(e)}`;if(i){(0,mne.checkStrictMode)(t,`default is ignored for: ${o}`);return}let d=(0,gy._)`${o} === undefined`;s.useDefaults==="empty"&&(d=(0,gy._)`${d} || ${o} === null || ${o} === ""`),n.if(d,(0,gy._)`${o} = ${(0,gy.stringify)(r)}`)}});var wa=_e(Ur=>{"use strict";g();Object.defineProperty(Ur,"__esModule",{value:!0});Ur.validateUnion=Ur.validateArray=Ur.usePattern=Ur.callValidateCode=Ur.schemaProperties=Ur.allSchemaProperties=Ur.noPropertyInData=Ur.propertyInData=Ur.isOwnProperty=Ur.hasPropFunc=Ur.reportMissingProp=Ur.checkMissingProp=Ur.checkReportMissingProp=void 0;var on=Bt(),nD=Zt(),Wu=ga(),gne=Zt();function wne(t,e){let{gen:r,data:n,it:i}=t;r.if(sD(r,n,e,i.opts.ownProperties),()=>{t.setParams({missingProperty:(0,on._)`${e}`},!0),t.error()})}Ur.checkReportMissingProp=wne;function vne({gen:t,data:e,it:{opts:r}},n,i){return(0,on.or)(...n.map(a=>(0,on.and)(sD(t,e,a,r.ownProperties),(0,on._)`${i} = ${a}`)))}Ur.checkMissingProp=vne;function bne(t,e){t.setParams({missingProperty:e},!0),t.error()}Ur.reportMissingProp=bne;function BN(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,on._)`Object.prototype.hasOwnProperty`})}Ur.hasPropFunc=BN;function iD(t,e,r){return(0,on._)`${BN(t)}.call(${e}, ${r})`}Ur.isOwnProperty=iD;function Pne(t,e,r,n){let i=(0,on._)`${e}${(0,on.getProperty)(r)} !== undefined`;return n?(0,on._)`${i} && ${iD(t,e,r)}`:i}Ur.propertyInData=Pne;function sD(t,e,r,n){let i=(0,on._)`${e}${(0,on.getProperty)(r)} === undefined`;return n?(0,on.or)(i,(0,on.not)(iD(t,e,r))):i}Ur.noPropertyInData=sD;function ON(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ur.allSchemaProperties=ON;function xne(t,e){return ON(e).filter(r=>!(0,nD.alwaysValidSchema)(t,e[r]))}Ur.schemaProperties=xne;function Ene({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:a},it:s},o,d,l){let c=l?(0,on._)`${t}, ${e}, ${n}${i}`:e,u=[[Wu.default.instancePath,(0,on.strConcat)(Wu.default.instancePath,a)],[Wu.default.parentData,s.parentData],[Wu.default.parentDataProperty,s.parentDataProperty],[Wu.default.rootData,Wu.default.rootData]];s.opts.dynamicRef&&u.push([Wu.default.dynamicAnchors,Wu.default.dynamicAnchors]);let f=(0,on._)`${c}, ${r.object(...u)}`;return d!==on.nil?(0,on._)`${o}.call(${d}, ${f})`:(0,on._)`${o}(${f})`}Ur.callValidateCode=Ene;var Sne=(0,on._)`new RegExp`;function Ane({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,a=i(r,n);return t.scopeValue("pattern",{key:a.toString(),ref:a,code:(0,on._)`${i.code==="new RegExp"?Sne:(0,gne.useFunc)(t,i)}(${r}, ${n})`})}Ur.usePattern=Ane;function kne(t){let{gen:e,data:r,keyword:n,it:i}=t,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 d=e.const("len",(0,on._)`${r}.length`);e.forRange("i",0,d,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:nD.Type.Num},a),e.if((0,on.not)(a),o)})}}Ur.validateArray=kne;function _ne(t){let{gen:e,schema:r,keyword:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(d=>(0,nD.alwaysValidSchema)(i,d))&&!i.opts.unevaluated)return;let s=e.let("valid",!1),o=e.name("_valid");e.block(()=>r.forEach((d,l)=>{let c=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},o);e.assign(s,(0,on._)`${s} || ${o}`),t.mergeValidEvaluated(c,o)||e.if((0,on.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}Ur.validateUnion=_ne});var KN=_e(ud=>{"use strict";g();Object.defineProperty(ud,"__esModule",{value:!0});ud.validateKeywordUsage=ud.validSchemaType=ud.funcKeywordCode=ud.macroKeywordCode=void 0;var qs=Bt(),Gp=ga(),Tne=wa(),Ine=z0();function Dne(t,e){let{gen:r,keyword:n,schema:i,parentSchema:a,it:s}=t,o=e.macro.call(s.self,i,a,s),d=MN(r,n,o);s.opts.validateSchema!==!1&&s.self.validateSchema(o,!0);let l=r.name("valid");t.subschema({schema:o,schemaPath:qs.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:d,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}ud.macroKeywordCode=Dne;function Rne(t,e){var r;let{gen:n,keyword:i,schema:a,parentSchema:s,$data:o,it:d}=t;$ne(d,e);let l=!o&&e.compile?e.compile.call(d.self,a,s,d):e.validate,c=MN(n,i,l),u=n.let("valid");t.block$data(u,f),t.ok((r=e.valid)!==null&&r!==void 0?r:u);function f(){if(e.errors===!1)m(),e.modifying&&jN(t),y(()=>t.error());else{let b=e.async?h():p();e.modifying&&jN(t),y(()=>Cne(t,b))}}function h(){let b=n.let("ruleErrs",null);return n.try(()=>m((0,qs._)`await `),w=>n.assign(u,!1).if((0,qs._)`${w} instanceof ${d.ValidationError}`,()=>n.assign(b,(0,qs._)`${w}.errors`),()=>n.throw(w))),b}function p(){let b=(0,qs._)`${c}.errors`;return n.assign(b,null),m(qs.nil),b}function m(b=e.async?(0,qs._)`await `:qs.nil){let w=d.opts.passContext?Gp.default.this:Gp.default.self,S=!("compile"in e&&!o||e.schema===!1);n.assign(u,(0,qs._)`${b}${(0,Tne.callValidateCode)(t,c,w,S)}`,e.modifying)}function y(b){var w;n.if((0,qs.not)((w=e.valid)!==null&&w!==void 0?w:u),b)}}ud.funcKeywordCode=Rne;function jN(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,qs._)`${n.parentData}[${n.parentDataProperty}]`))}function Cne(t,e){let{gen:r}=t;r.if((0,qs._)`Array.isArray(${e})`,()=>{r.assign(Gp.default.vErrors,(0,qs._)`${Gp.default.vErrors} === null ? ${e} : ${Gp.default.vErrors}.concat(${e})`).assign(Gp.default.errors,(0,qs._)`${Gp.default.vErrors}.length`),(0,Ine.extendErrors)(t)},()=>t.error())}function $ne({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function MN(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,qs.stringify)(r)})}function Bne(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}ud.validSchemaType=Bne;function One({schema:t,opts:e,self:r,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(t,o)))throw new Error(`parent schema must have dependencies of ${a}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(t[a])){let d=`keyword "${a}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(d);else throw new Error(d)}}ud.validateKeywordUsage=One});var UN=_e(Ju=>{"use strict";g();Object.defineProperty(Ju,"__esModule",{value:!0});Ju.extendSubschemaMode=Ju.extendSubschemaData=Ju.getSubschema=void 0;var fd=Bt(),NN=Zt();function jne(t,{keyword:e,schemaProp:r,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=t.schema[e];return r===void 0?{schema:o,schemaPath:(0,fd._)`${t.schemaPath}${(0,fd.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:o[r],schemaPath:(0,fd._)`${t.schemaPath}${(0,fd.getProperty)(e)}${(0,fd.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,NN.escapeFragment)(r)}`}}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')}Ju.getSubschema=jne;function Mne(t,e,{dataProp:r,dataPropType:n,data:i,dataTypes:a,propertyName:s}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:o}=e;if(r!==void 0){let{errorPath:l,dataPathArr:c,opts:u}=e,f=o.let("data",(0,fd._)`${e.data}${(0,fd.getProperty)(r)}`,!0);d(f),t.errorPath=(0,fd.str)`${l}${(0,NN.getErrorPath)(r,n,u.jsPropertySyntax)}`,t.parentDataProperty=(0,fd._)`${r}`,t.dataPathArr=[...c,t.parentDataProperty]}if(i!==void 0){let l=i instanceof fd.Name?i:o.let("data",i,!0);d(l),s!==void 0&&(t.propertyName=s)}a&&(t.dataTypes=a);function d(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}Ju.extendSubschemaData=Mne;function Kne(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:a}){n!==void 0&&(t.compositeRule=n),i!==void 0&&(t.createErrors=i),a!==void 0&&(t.allErrors=a),t.jtdDiscriminator=e,t.jtdMetadata=r}Ju.extendSubschemaMode=Kne});var oD=_e((L3e,LN)=>{"use strict";g();LN.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,i,a;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!t(e[i],r[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(a=Object.keys(e),n=a.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,a[i]))return!1;for(i=n;i--!==0;){var s=a[i];if(!t(e[s],r[s]))return!1}return!0}return e!==e&&r!==r}});var zN=_e((z3e,qN)=>{"use strict";g();var Zu=qN.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};xx(e,n,i,t,"",t)};Zu.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Zu.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Zu.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Zu.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 xx(t,e,r,n,i,a,s,o,d,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,a,s,o,d,l);for(var c in n){var u=n[c];if(Array.isArray(u)){if(c in Zu.arrayKeywords)for(var f=0;f<u.length;f++)xx(t,e,r,u[f],i+"/"+c+"/"+f,a,i,c,n,f)}else if(c in Zu.propsKeywords){if(u&&typeof u=="object")for(var h in u)xx(t,e,r,u[h],i+"/"+c+"/"+Nne(h),a,i,c,n,h)}else(c in Zu.keywords||t.allKeys&&!(c in Zu.skipKeywords))&&xx(t,e,r,u,i+"/"+c,a,i,c,n)}r(n,i,a,s,o,d,l)}}function Nne(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var G0=_e(ao=>{"use strict";g();Object.defineProperty(ao,"__esModule",{value:!0});ao.getSchemaRefs=ao.resolveUrl=ao.normalizeId=ao._getFullPath=ao.getFullPath=ao.inlineRef=void 0;var Une=Zt(),Lne=oD(),qne=zN(),zne=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Fne(t,e=!0){return typeof t=="boolean"?!0:e===!0?!aD(t):e?FN(t)<=e:!1}ao.inlineRef=Fne;var Gne=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function aD(t){for(let e in t){if(Gne.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(aD)||typeof r=="object"&&aD(r))return!0}return!1}function FN(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!zne.has(r)&&(typeof t[r]=="object"&&(0,Une.eachItem)(t[r],n=>e+=FN(n)),e===1/0))return 1/0}return e}function GN(t,e="",r){r!==!1&&(e=wy(e));let n=t.parse(e);return HN(t,n)}ao.getFullPath=GN;function HN(t,e){return t.serialize(e).split("#")[0]+"#"}ao._getFullPath=HN;var Hne=/#\/?$/;function wy(t){return t?t.replace(Hne,""):""}ao.normalizeId=wy;function Vne(t,e,r){return r=wy(r),t.resolve(e,r)}ao.resolveUrl=Vne;var Wne=/^[a-z_][-a-z0-9._]*$/i;function Jne(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=wy(t[r]||e),a={"":i},s=GN(n,i,!1),o={},d=new Set;return qne(t,{allKeys:!0},(u,f,h,p)=>{if(p===void 0)return;let m=s+f,y=a[p];typeof u[r]=="string"&&(y=b.call(this,u[r])),w.call(this,u.$anchor),w.call(this,u.$dynamicAnchor),a[f]=y;function b(S){let k=this.opts.uriResolver.resolve;if(S=wy(y?k(y,S):S),d.has(S))throw c(S);d.add(S);let T=this.refs[S];return typeof T=="string"&&(T=this.refs[T]),typeof T=="object"?l(u,T.schema,S):S!==wy(m)&&(S[0]==="#"?(l(u,o[S],S),o[S]=u):this.refs[S]=m),S}function w(S){if(typeof S=="string"){if(!Wne.test(S))throw new Error(`invalid anchor "${S}"`);b.call(this,`#${S}`)}}}),o;function l(u,f,h){if(f!==void 0&&!Lne(u,f))throw c(h)}function c(u){return new Error(`reference "${u}" resolves to more than one schema`)}}ao.getSchemaRefs=Jne});var W0=_e(Yu=>{"use strict";g();Object.defineProperty(Yu,"__esModule",{value:!0});Yu.getData=Yu.KeywordCxt=Yu.validateFunctionCode=void 0;var YN=kN(),VN=F0(),dD=QI(),Ex=F0(),Zne=$N(),V0=KN(),cD=UN(),Qe=Bt(),kt=ga(),Yne=G0(),Al=Zt(),H0=z0();function Xne(t){if(eU(t)&&(tU(t),QN(t))){tie(t);return}XN(t,()=>(0,YN.topBoolOrEmptySchema)(t))}Yu.validateFunctionCode=Xne;function XN({gen:t,validateName:e,schema:r,schemaEnv:n,opts:i},a){i.code.es5?t.func(e,(0,Qe._)`${kt.default.data}, ${kt.default.valCxt}`,n.$async,()=>{t.code((0,Qe._)`"use strict"; ${WN(r,i)}`),eie(t,i),t.code(a)}):t.func(e,(0,Qe._)`${kt.default.data}, ${Qne(i)}`,n.$async,()=>t.code(WN(r,i)).code(a))}function Qne(t){return(0,Qe._)`{${kt.default.instancePath}="", ${kt.default.parentData}, ${kt.default.parentDataProperty}, ${kt.default.rootData}=${kt.default.data}${t.dynamicRef?(0,Qe._)`, ${kt.default.dynamicAnchors}={}`:Qe.nil}}={}`}function eie(t,e){t.if(kt.default.valCxt,()=>{t.var(kt.default.instancePath,(0,Qe._)`${kt.default.valCxt}.${kt.default.instancePath}`),t.var(kt.default.parentData,(0,Qe._)`${kt.default.valCxt}.${kt.default.parentData}`),t.var(kt.default.parentDataProperty,(0,Qe._)`${kt.default.valCxt}.${kt.default.parentDataProperty}`),t.var(kt.default.rootData,(0,Qe._)`${kt.default.valCxt}.${kt.default.rootData}`),e.dynamicRef&&t.var(kt.default.dynamicAnchors,(0,Qe._)`${kt.default.valCxt}.${kt.default.dynamicAnchors}`)},()=>{t.var(kt.default.instancePath,(0,Qe._)`""`),t.var(kt.default.parentData,(0,Qe._)`undefined`),t.var(kt.default.parentDataProperty,(0,Qe._)`undefined`),t.var(kt.default.rootData,kt.default.data),e.dynamicRef&&t.var(kt.default.dynamicAnchors,(0,Qe._)`{}`)})}function tie(t){let{schema:e,opts:r,gen:n}=t;XN(t,()=>{r.$comment&&e.$comment&&nU(t),oie(t),n.let(kt.default.vErrors,null),n.let(kt.default.errors,0),r.unevaluated&&rie(t),rU(t),die(t)})}function rie(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Qe._)`${r}.evaluated`),e.if((0,Qe._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Qe._)`${t.evaluated}.props`,(0,Qe._)`undefined`)),e.if((0,Qe._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Qe._)`${t.evaluated}.items`,(0,Qe._)`undefined`))}function WN(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Qe._)`/*# sourceURL=${r} */`:Qe.nil}function nie(t,e){if(eU(t)&&(tU(t),QN(t))){iie(t,e);return}(0,YN.boolOrEmptySchema)(t,e)}function QN({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function eU(t){return typeof t.schema!="boolean"}function iie(t,e){let{schema:r,gen:n,opts:i}=t;i.$comment&&r.$comment&&nU(t),aie(t),cie(t);let a=n.const("_errs",kt.default.errors);rU(t,a),n.var(e,(0,Qe._)`${a} === ${kt.default.errors}`)}function tU(t){(0,Al.checkUnknownRules)(t),sie(t)}function rU(t,e){if(t.opts.jtd)return JN(t,[],!1,e);let r=(0,VN.getSchemaTypes)(t.schema),n=(0,VN.coerceAndCheckDataType)(t,r);JN(t,r,!n,e)}function sie(t){let{schema:e,errSchemaPath:r,opts:n,self:i}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Al.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function oie(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Al.checkStrictMode)(t,"default is ignored in the schema root")}function aie(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Yne.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function cie(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function nU({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:i}){let a=r.$comment;if(i.$comment===!0)t.code((0,Qe._)`${kt.default.self}.logger.log(${a})`);else if(typeof i.$comment=="function"){let s=(0,Qe.str)`${n}/$comment`,o=t.scopeValue("root",{ref:e.root});t.code((0,Qe._)`${kt.default.self}.opts.$comment(${a}, ${s}, ${o}.schema)`)}}function die(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:i,opts:a}=t;r.$async?e.if((0,Qe._)`${kt.default.errors} === 0`,()=>e.return(kt.default.data),()=>e.throw((0,Qe._)`new ${i}(${kt.default.vErrors})`)):(e.assign((0,Qe._)`${n}.errors`,kt.default.vErrors),a.unevaluated&&lie(t),e.return((0,Qe._)`${kt.default.errors} === 0`))}function lie({gen:t,evaluated:e,props:r,items:n}){r instanceof Qe.Name&&t.assign((0,Qe._)`${e}.props`,r),n instanceof Qe.Name&&t.assign((0,Qe._)`${e}.items`,n)}function JN(t,e,r,n){let{gen:i,schema:a,data:s,allErrors:o,opts:d,self:l}=t,{RULES:c}=l;if(a.$ref&&(d.ignoreKeywordsWithRef||!(0,Al.schemaHasRulesButRef)(a,c))){i.block(()=>sU(t,"$ref",c.all.$ref.definition));return}d.jtd||uie(t,e),i.block(()=>{for(let f of c.rules)u(f);u(c.post)});function u(f){(0,dD.shouldUseGroup)(a,f)&&(f.type?(i.if((0,Ex.checkDataType)(f.type,s,d.strictNumbers)),ZN(t,f),e.length===1&&e[0]===f.type&&r&&(i.else(),(0,Ex.reportTypeError)(t)),i.endIf()):ZN(t,f),o||i.if((0,Qe._)`${kt.default.errors} === ${n||0}`))}}function ZN(t,e){let{gen:r,schema:n,opts:{useDefaults:i}}=t;i&&(0,Zne.assignDefaults)(t,e.type),r.block(()=>{for(let a of e.rules)(0,dD.shouldUseRule)(n,a)&&sU(t,a.keyword,a.definition,e.type)})}function uie(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(fie(t,e),t.opts.allowUnionTypes||pie(t,e),hie(t,t.dataTypes))}function fie(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{iU(t.dataTypes,r)||lD(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),yie(t,e)}}function pie(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&lD(t,"use allowUnionTypes to allow union type keyword")}function hie(t,e){let r=t.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,dD.shouldUseRule)(t.schema,i)){let{type:a}=i.definition;a.length&&!a.some(s=>mie(e,s))&&lD(t,`missing type "${a.join(",")}" for keyword "${n}"`)}}}function mie(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function iU(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function yie(t,e){let r=[];for(let n of t.dataTypes)iU(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function lD(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Al.checkStrictMode)(t,e,t.opts.strictTypes)}var Sx=class{constructor(e,r,n){if((0,V0.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Al.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",oU(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,V0.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",kt.default.errors))}result(e,r,n){this.failResult((0,Qe.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,Qe.not)(e),void 0,r)}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:r}=this;this.fail((0,Qe._)`${r} !== undefined && (${(0,Qe.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?H0.reportExtraError:H0.reportError)(this,this.def.error,r)}$dataError(){(0,H0.reportError)(this,this.def.$dataError||H0.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,H0.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=Qe.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Qe.nil,r=Qe.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:a,def:s}=this;n.if((0,Qe.or)((0,Qe._)`${i} === undefined`,r)),e!==Qe.nil&&n.assign(e,!0),(a.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Qe.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:i,it:a}=this;return(0,Qe.or)(s(),o());function s(){if(n.length){if(!(r instanceof Qe.Name))throw new Error("ajv implementation error");let d=Array.isArray(n)?n:[n];return(0,Qe._)`${(0,Ex.checkDataTypes)(d,r,a.opts.strictNumbers,Ex.DataType.Wrong)}`}return Qe.nil}function o(){if(i.validateSchema){let d=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,Qe._)`!${d}(${r})`}return Qe.nil}}subschema(e,r){let n=(0,cD.getSubschema)(this.it,e);(0,cD.extendSubschemaData)(n,this.it,e),(0,cD.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return nie(i,r),i}mergeEvaluated(e,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Al.mergeEvaluated.props(i,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Al.mergeEvaluated.items(i,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(e,Qe.Name)),!0}};Yu.KeywordCxt=Sx;function sU(t,e,r,n){let i=new Sx(t,r,e);"code"in r?r.code(i,n):i.$data&&r.validate?(0,V0.funcKeywordCode)(i,r):"macro"in r?(0,V0.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,V0.funcKeywordCode)(i,r)}var gie=/^\/(?:[^~]|~0|~1)*$/,wie=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function oU(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let i,a;if(t==="")return kt.default.rootData;if(t[0]==="/"){if(!gie.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);i=t,a=kt.default.rootData}else{let l=wie.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let c=+l[1];if(i=l[2],i==="#"){if(c>=e)throw new Error(d("property/index",c));return n[e-c]}if(c>e)throw new Error(d("data",c));if(a=r[e-c],!i)return a}let s=a,o=i.split("/");for(let l of o)l&&(a=(0,Qe._)`${a}${(0,Qe.getProperty)((0,Al.unescapeJsonPointer)(l))}`,s=(0,Qe._)`${s} && ${a}`);return s;function d(l,c){return`Cannot access ${l} ${c} levels up, current level is ${e}`}}Yu.getData=oU});var Ax=_e(fD=>{"use strict";g();Object.defineProperty(fD,"__esModule",{value:!0});var uD=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};fD.default=uD});var J0=_e(mD=>{"use strict";g();Object.defineProperty(mD,"__esModule",{value:!0});var pD=G0(),hD=class extends Error{constructor(e,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,pD.resolveUrl)(e,r,n),this.missingSchema=(0,pD.normalizeId)((0,pD.getFullPath)(e,this.missingRef))}};mD.default=hD});var Z0=_e(va=>{"use strict";g();Object.defineProperty(va,"__esModule",{value:!0});va.resolveSchema=va.getCompilingSchema=va.resolveRef=va.compileSchema=va.SchemaEnv=void 0;var gc=Bt(),vie=Ax(),Hp=ga(),wc=G0(),aU=Zt(),bie=W0(),vy=class{constructor(e){var r;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=(r=e.baseId)!==null&&r!==void 0?r:(0,wc.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};va.SchemaEnv=vy;function gD(t){let e=cU.call(this,t);if(e)return e;let r=(0,wc.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:a}=this.opts,s=new gc.CodeGen(this.scope,{es5:n,lines:i,ownProperties:a}),o;t.$async&&(o=s.scopeValue("Error",{ref:vie.default,code:(0,gc._)`require("ajv/dist/runtime/validation_error").default`}));let d=s.scopeName("validate");t.validateName=d;let l={gen:s,allErrors:this.opts.allErrors,data:Hp.default.data,parentData:Hp.default.parentData,parentDataProperty:Hp.default.parentDataProperty,dataNames:[Hp.default.data],dataPathArr:[gc.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,gc.stringify)(t.schema)}:{ref:t.schema}),validateName:d,ValidationError:o,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:gc.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,gc._)`""`,opts:this.opts,self:this},c;try{this._compilations.add(t),(0,bie.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let u=s.toString();c=`${s.scopeRefs(Hp.default.scope)}return ${u}`,this.opts.code.process&&(c=this.opts.code.process(c,t));let h=new Function(`${Hp.default.self}`,`${Hp.default.scope}`,c)(this,this.scope.get());if(this.scope.value(d,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:d,validateCode:u,scopeValues:s._values}),this.opts.unevaluated){let{props:p,items:m}=l;h.evaluated={props:p instanceof gc.Name?void 0:p,items:m instanceof gc.Name?void 0:m,dynamicProps:p instanceof gc.Name,dynamicItems:m instanceof gc.Name},h.source&&(h.source.evaluated=(0,gc.stringify)(h.evaluated))}return t.validate=h,t}catch(u){throw delete t.validate,delete t.validateName,c&&this.logger.error("Error compiling schema, function code:",c),u}finally{this._compilations.delete(t)}}va.compileSchema=gD;function Pie(t,e,r){var n;r=(0,wc.resolveUrl)(this.opts.uriResolver,e,r);let i=t.refs[r];if(i)return i;let a=Sie.call(this,t,r);if(a===void 0){let s=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:o}=this.opts;s&&(a=new vy({schema:s,schemaId:o,root:t,baseId:e}))}if(a!==void 0)return t.refs[r]=xie.call(this,a)}va.resolveRef=Pie;function xie(t){return(0,wc.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:gD.call(this,t)}function cU(t){for(let e of this._compilations)if(Eie(e,t))return e}va.getCompilingSchema=cU;function Eie(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Sie(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||kx.call(this,t,e)}function kx(t,e){let r=this.opts.uriResolver.parse(e),n=(0,wc._getFullPath)(this.opts.uriResolver,r),i=(0,wc.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===i)return yD.call(this,r,t);let a=(0,wc.normalizeId)(n),s=this.refs[a]||this.schemas[a];if(typeof s=="string"){let o=kx.call(this,t,s);return typeof o?.schema!="object"?void 0:yD.call(this,r,o)}if(typeof s?.schema=="object"){if(s.validate||gD.call(this,s),a===(0,wc.normalizeId)(e)){let{schema:o}=s,{schemaId:d}=this.opts,l=o[d];return l&&(i=(0,wc.resolveUrl)(this.opts.uriResolver,i,l)),new vy({schema:o,schemaId:d,root:t,baseId:i})}return yD.call(this,r,s)}}va.resolveSchema=kx;var Aie=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function yD(t,{baseId:e,schema:r,root:n}){var i;if(((i=t.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let o of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let d=r[(0,aU.unescapeFragment)(o)];if(d===void 0)return;r=d;let l=typeof r=="object"&&r[this.opts.schemaId];!Aie.has(o)&&l&&(e=(0,wc.resolveUrl)(this.opts.uriResolver,e,l))}let a;if(typeof r!="boolean"&&r.$ref&&!(0,aU.schemaHasRulesButRef)(r,this.RULES)){let o=(0,wc.resolveUrl)(this.opts.uriResolver,e,r.$ref);a=kx.call(this,n,o)}let{schemaId:s}=this.opts;if(a=a||new vy({schema:r,schemaId:s,root:n,baseId:e}),a.schema!==a.root.schema)return a}});var dU=_e((tBe,kie)=>{kie.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 vD=_e((rBe,pU)=>{"use strict";g();var _ie=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),uU=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 wD(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var Tie=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function lU(t){return t.length=0,!0}function Iie(t,e,r){if(t.length){let n=wD(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Die(t){let e=0,r={error:!1,address:"",zone:""},n=[],i=[],a=!1,s=!1,o=Iie;for(let d=0;d<t.length;d++){let l=t[d];if(!(l==="["||l==="]"))if(l===":"){if(a===!0&&(s=!0),!o(i,n,r))break;if(++e>7){r.error=!0;break}d>0&&t[d-1]===":"&&(a=!0),n.push(":");continue}else if(l==="%"){if(!o(i,n,r))break;o=lU}else{i.push(l);continue}}return i.length&&(o===lU?r.zone=i.join(""):s?n.push(i.join("")):n.push(wD(i))),r.address=n.join(""),r}function fU(t){if(Rie(t,":")<2)return{host:t,isIPV6:!1};let e=Die(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function Rie(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function Cie(t){let e=t,r=[],n=-1,i=0;for(;i=e.length;){if(i===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.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]==="/")){r.push("/");break}}else if(i===3&&e==="/.."){r.length!==0&&r.pop(),r.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),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function $ie(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function Bie(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!uU(r)){let n=fU(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}pU.exports={nonSimpleDomain:Tie,recomposeAuthority:Bie,normalizeComponentEncoding:$ie,removeDotSegments:Cie,isIPv4:uU,isUUID:_ie,normalizeIPv6:fU,stringArrayToHexStripped:wD}});var wU=_e((iBe,gU)=>{"use strict";g();var{isUUID:Oie}=vD(),jie=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Mie=["http","https","ws","wss","urn","urn:uuid"];function Kie(t){return Mie.indexOf(t)!==-1}function bD(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function hU(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function mU(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function Nie(t){return t.secure=bD(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Uie(t){if((t.port===(bD(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function Lie(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(jie);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let i=`${n}:${e.nid||t.nid}`,a=PD(i);t.path=void 0,a&&(t=a.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function qie(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),i=`${r}:${e.nid||n}`,a=PD(i);a&&(t=a.serialize(t,e));let s=t,o=t.nss;return s.path=`${n||e.nid}:${o}`,e.skipEscape=!0,s}function zie(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Oie(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Fie(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var yU={scheme:"http",domainHost:!0,parse:hU,serialize:mU},Gie={scheme:"https",domainHost:yU.domainHost,parse:hU,serialize:mU},_x={scheme:"ws",domainHost:!0,parse:Nie,serialize:Uie},Hie={scheme:"wss",domainHost:_x.domainHost,parse:_x.parse,serialize:_x.serialize},Vie={scheme:"urn",parse:Lie,serialize:qie,skipNormalize:!0},Wie={scheme:"urn:uuid",parse:zie,serialize:Fie,skipNormalize:!0},Tx={http:yU,https:Gie,ws:_x,wss:Hie,urn:Vie,"urn:uuid":Wie};Object.setPrototypeOf(Tx,null);function PD(t){return t&&(Tx[t]||Tx[t.toLowerCase()])||void 0}gU.exports={wsIsSecure:bD,SCHEMES:Tx,isValidSchemeName:Kie,getSchemeHandler:PD}});var PU=_e((oBe,Dx)=>{"use strict";g();var{normalizeIPv6:Jie,removeDotSegments:Y0,recomposeAuthority:Zie,normalizeComponentEncoding:Ix,isIPv4:Yie,nonSimpleDomain:Xie}=vD(),{SCHEMES:Qie,getSchemeHandler:vU}=wU();function ese(t,e){return typeof t=="string"?t=pd(kl(t,e),e):typeof t=="object"&&(t=kl(pd(t,e),e)),t}function tse(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},i=bU(kl(t,n),kl(e,n),n,!0);return n.skipEscape=!0,pd(i,n)}function bU(t,e,r,n){let i={};return n||(t=kl(pd(t,r),r),e=kl(pd(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=Y0(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=Y0(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=Y0(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?i.path="/"+e.path:t.path?i.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=Y0(i.path)),i.query=e.query):(i.path=t.path,e.query!==void 0?i.query=e.query:i.query=t.query),i.userinfo=t.userinfo,i.host=t.host,i.port=t.port),i.scheme=t.scheme),i.fragment=e.fragment,i}function rse(t,e,r){return typeof t=="string"?(t=unescape(t),t=pd(Ix(kl(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=pd(Ix(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=pd(Ix(kl(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=pd(Ix(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function pd(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),i=[],a=vU(n.scheme||r.scheme);a&&a.serialize&&a.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&i.push(r.scheme,":");let s=Zie(r);if(s!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(s),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let o=r.path;!n.absolutePath&&(!a||!a.absolutePath)&&(o=Y0(o)),s===void 0&&o[0]==="/"&&o[1]==="/"&&(o="/%2F"+o.slice(2)),i.push(o)}return r.query!==void 0&&i.push("?",r.query),r.fragment!==void 0&&i.push("#",r.fragment),i.join("")}var nse=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function kl(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let a=t.match(nse);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(Yie(n.host)===!1){let d=Jie(n.host);n.host=d.host.toLowerCase(),i=d.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",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let s=vU(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&i===!1&&Xie(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)&&(t.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,r)}else n.error=n.error||"URI can not be parsed.";return n}var xD={SCHEMES:Qie,normalize:ese,resolve:tse,resolveComponent:bU,equal:rse,serialize:pd,parse:kl};Dx.exports=xD;Dx.exports.default=xD;Dx.exports.fastUri=xD});var EU=_e(ED=>{"use strict";g();Object.defineProperty(ED,"__esModule",{value:!0});var xU=PU();xU.code='require("ajv/dist/runtime/uri").default';ED.default=xU});var RU=_e(Hi=>{"use strict";g();Object.defineProperty(Hi,"__esModule",{value:!0});Hi.CodeGen=Hi.Name=Hi.nil=Hi.stringify=Hi.str=Hi._=Hi.KeywordCxt=void 0;var ise=W0();Object.defineProperty(Hi,"KeywordCxt",{enumerable:!0,get:function(){return ise.KeywordCxt}});var by=Bt();Object.defineProperty(Hi,"_",{enumerable:!0,get:function(){return by._}});Object.defineProperty(Hi,"str",{enumerable:!0,get:function(){return by.str}});Object.defineProperty(Hi,"stringify",{enumerable:!0,get:function(){return by.stringify}});Object.defineProperty(Hi,"nil",{enumerable:!0,get:function(){return by.nil}});Object.defineProperty(Hi,"Name",{enumerable:!0,get:function(){return by.Name}});Object.defineProperty(Hi,"CodeGen",{enumerable:!0,get:function(){return by.CodeGen}});var sse=Ax(),TU=J0(),ose=XI(),X0=Z0(),ase=Bt(),Q0=G0(),Rx=F0(),AD=Zt(),SU=dU(),cse=EU(),IU=(t,e)=>new RegExp(t,e);IU.code="new RegExp";var dse=["removeAdditional","useDefaults","coerceTypes"],lse=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),use={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."},fse={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},AU=200;function pse(t){var e,r,n,i,a,s,o,d,l,c,u,f,h,p,m,y,b,w,S,k,T,D,K,C,G;let z=t.strict,N=(e=t.code)===null||e===void 0?void 0:e.optimize,V=N===!0||N===void 0?1:N||0,ee=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:IU,R=(i=t.uriResolver)!==null&&i!==void 0?i:cse.default;return{strictSchema:(s=(a=t.strictSchema)!==null&&a!==void 0?a:z)!==null&&s!==void 0?s:!0,strictNumbers:(d=(o=t.strictNumbers)!==null&&o!==void 0?o:z)!==null&&d!==void 0?d:!0,strictTypes:(c=(l=t.strictTypes)!==null&&l!==void 0?l:z)!==null&&c!==void 0?c:"log",strictTuples:(f=(u=t.strictTuples)!==null&&u!==void 0?u:z)!==null&&f!==void 0?f:"log",strictRequired:(p=(h=t.strictRequired)!==null&&h!==void 0?h:z)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:V,regExp:ee}:{optimize:V,regExp:ee},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:AU,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:AU,meta:(b=t.meta)!==null&&b!==void 0?b:!0,messages:(w=t.messages)!==null&&w!==void 0?w:!0,inlineRefs:(S=t.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(T=t.addUsedSchema)!==null&&T!==void 0?T:!0,validateSchema:(D=t.validateSchema)!==null&&D!==void 0?D:!0,validateFormats:(K=t.validateFormats)!==null&&K!==void 0?K:!0,unicodeRegExp:(C=t.unicodeRegExp)!==null&&C!==void 0?C:!0,int32range:(G=t.int32range)!==null&&G!==void 0?G:!0,uriResolver:R}}var ev=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...pse(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new ase.ValueScope({scope:{},prefixes:lse,es5:r,lines:n}),this.logger=vse(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,ose.getRules)(),kU.call(this,use,e,"NOT SUPPORTED"),kU.call(this,fse,e,"DEPRECATED","warn"),this._metaOpts=gse.call(this),e.formats&&mse.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&yse.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),hse.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,i=SU;n==="id"&&(i={...SU},i.id=i.$id,delete i.$id),r&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){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(r);return"$async"in n||(this.errors=n.errors),i}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){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,r);async function i(c,u){await a.call(this,c.$schema);let f=this._addSchema(c,u);return f.validate||s.call(this,f)}async function a(c){c&&!this.getSchema(c)&&await i.call(this,{$ref:c},!0)}async function s(c){try{return this._compileSchemaEnv(c)}catch(u){if(!(u instanceof TU.default))throw u;return o.call(this,u),await d.call(this,u.missingSchema),s.call(this,c)}}function o({missingSchema:c,missingRef:u}){if(this.refs[c])throw new Error(`AnySchema ${c} is loaded but ${u} cannot be resolved`)}async function d(c){let u=await l.call(this,c);this.refs[c]||await a.call(this,u.$schema),this.refs[c]||this.addSchema(u,c,r)}async function l(c){let u=this._loading[c];if(u)return u;try{return await(this._loading[c]=n(c))}finally{delete this._loading[c]}}}addSchema(e,r,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 r=(0,Q0.normalizeId)(r||a),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,i,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){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&&r){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 r;for(;typeof(r=_U.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,i=new X0.SchemaEnv({schema:{},schemaId:n});if(r=X0.resolveSchema.call(this,i,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}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 r=_U.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Q0.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.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(Pse.call(this,n,r),!r)return(0,AD.eachItem)(n,a=>SD.call(this,a)),this;Ese.call(this,r);let i={...r,type:(0,Rx.getJSONTypes)(r.type),schemaType:(0,Rx.getJSONTypes)(r.schemaType)};return(0,AD.eachItem)(n,i.type.length===0?a=>SD.call(this,a,i):a=>i.type.forEach(s=>SD.call(this,a,i,s))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let i=n.rules.findIndex(a=>a.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,a)=>i+r+a)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of r){let a=i.split("/").slice(1),s=e;for(let o of a)s=s[o];for(let o in n){let d=n[o];if(typeof d!="object")continue;let{$data:l}=d.definition,c=s[o];l&&c&&(s[o]=DU(c))}}return e}_removeAllSchemas(e,r){for(let n in e){let i=e[n];(!r||r.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,r,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 d=this._cache.get(e);if(d!==void 0)return d;n=(0,Q0.normalizeId)(s||n);let l=Q0.getSchemaRefs.call(this,e,n);return d=new X0.SchemaEnv({schema:e,schemaId:o,meta:r,baseId:n,localRefs:l}),this._cache.set(d.schema,d),a&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=d),i&&this.validateSchema(e,!0),d}_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):X0.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{X0.compileSchema.call(this,e)}finally{this.opts=r}}};ev.ValidationError=sse.default;ev.MissingRefError=TU.default;Hi.default=ev;function kU(t,e,r,n="error"){for(let i in t){let a=i;a in e&&this.logger[n](`${r}: option ${i}. ${t[a]}`)}}function _U(t){return t=(0,Q0.normalizeId)(t),this.schemas[t]||this.refs[t]}function hse(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function mse(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function yse(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function gse(){let t={...this.opts};for(let e of dse)delete t[e];return t}var wse={log(){},warn(){},error(){}};function vse(t){if(t===!1)return wse;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var bse=/^[a-z_$][a-z0-9_$:-]*$/i;function Pse(t,e){let{RULES:r}=this;if((0,AD.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!bse.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 SD(t,e,r){var n;let i=e?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,s=i?a.post:a.rules.find(({type:d})=>d===r);if(s||(s={type:r,rules:[]},a.rules.push(s)),a.keywords[t]=!0,!e)return;let o={keyword:t,definition:{...e,type:(0,Rx.getJSONTypes)(e.type),schemaType:(0,Rx.getJSONTypes)(e.schemaType)}};e.before?xse.call(this,s,o,e.before):s.rules.push(o),a.all[t]=o,(n=e.implements)===null||n===void 0||n.forEach(d=>this.addKeyword(d))}function xse(t,e,r){let n=t.rules.findIndex(i=>i.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function Ese(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=DU(e)),t.validateSchema=this.compile(e,!0))}var Sse={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function DU(t){return{anyOf:[t,Sse]}}});var CU=_e(kD=>{"use strict";g();Object.defineProperty(kD,"__esModule",{value:!0});var Ase={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};kD.default=Ase});var Bx=_e(Vp=>{"use strict";g();Object.defineProperty(Vp,"__esModule",{value:!0});Vp.callRef=Vp.getValidate=void 0;var kse=J0(),$U=wa(),co=Bt(),Py=ga(),BU=Z0(),Cx=Zt(),_se={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:i,schemaEnv:a,validateName:s,opts:o,self:d}=n,{root:l}=a;if((r==="#"||r==="#/")&&i===l.baseId)return u();let c=BU.resolveRef.call(d,l,i,r);if(c===void 0)throw new kse.default(n.opts.uriResolver,i,r);if(c instanceof BU.SchemaEnv)return f(c);return h(c);function u(){if(a===l)return $x(t,s,a,a.$async);let p=e.scopeValue("root",{ref:l});return $x(t,(0,co._)`${p}.validate`,l,l.$async)}function f(p){let m=OU(t,p);$x(t,m,p,p.$async)}function h(p){let m=e.scopeValue("schema",o.code.source===!0?{ref:p,code:(0,co.stringify)(p)}:{ref:p}),y=e.name("valid"),b=t.subschema({schema:p,dataTypes:[],schemaPath:co.nil,topSchemaRef:m,errSchemaPath:r},y);t.mergeEvaluated(b),t.ok(y)}}};function OU(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,co._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Vp.getValidate=OU;function $x(t,e,r,n){let{gen:i,it:a}=t,{allErrors:s,schemaEnv:o,opts:d}=a,l=d.passContext?Py.default.this:co.nil;n?c():u();function c(){if(!o.$async)throw new Error("async schema referenced by sync schema");let p=i.let("valid");i.try(()=>{i.code((0,co._)`await ${(0,$U.callValidateCode)(t,e,l)}`),h(e),s||i.assign(p,!0)},m=>{i.if((0,co._)`!(${m} instanceof ${a.ValidationError})`,()=>i.throw(m)),f(m),s||i.assign(p,!1)}),t.ok(p)}function u(){t.result((0,$U.callValidateCode)(t,e,l),()=>h(e),()=>f(e))}function f(p){let m=(0,co._)`${p}.errors`;i.assign(Py.default.vErrors,(0,co._)`${Py.default.vErrors} === null ? ${m} : ${Py.default.vErrors}.concat(${m})`),i.assign(Py.default.errors,(0,co._)`${Py.default.vErrors}.length`)}function h(p){var m;if(!a.opts.unevaluated)return;let y=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(a.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(a.props=Cx.mergeEvaluated.props(i,y.props,a.props));else{let b=i.var("props",(0,co._)`${p}.evaluated.props`);a.props=Cx.mergeEvaluated.props(i,b,a.props,co.Name)}if(a.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(a.items=Cx.mergeEvaluated.items(i,y.items,a.items));else{let b=i.var("items",(0,co._)`${p}.evaluated.items`);a.items=Cx.mergeEvaluated.items(i,b,a.items,co.Name)}}}Vp.callRef=$x;Vp.default=_se});var jU=_e(_D=>{"use strict";g();Object.defineProperty(_D,"__esModule",{value:!0});var Tse=CU(),Ise=Bx(),Dse=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Tse.default,Ise.default];_D.default=Dse});var MU=_e(TD=>{"use strict";g();Object.defineProperty(TD,"__esModule",{value:!0});var Ox=Bt(),Xu=Ox.operators,jx={maximum:{okStr:"<=",ok:Xu.LTE,fail:Xu.GT},minimum:{okStr:">=",ok:Xu.GTE,fail:Xu.LT},exclusiveMaximum:{okStr:"<",ok:Xu.LT,fail:Xu.GTE},exclusiveMinimum:{okStr:">",ok:Xu.GT,fail:Xu.LTE}},Rse={message:({keyword:t,schemaCode:e})=>(0,Ox.str)`must be ${jx[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ox._)`{comparison: ${jx[t].okStr}, limit: ${e}}`},Cse={keyword:Object.keys(jx),type:"number",schemaType:"number",$data:!0,error:Rse,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Ox._)`${r} ${jx[e].fail} ${n} || isNaN(${r})`)}};TD.default=Cse});var KU=_e(ID=>{"use strict";g();Object.defineProperty(ID,"__esModule",{value:!0});var tv=Bt(),$se={message:({schemaCode:t})=>(0,tv.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,tv._)`{multipleOf: ${t}}`},Bse={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:$se,code(t){let{gen:e,data:r,schemaCode:n,it:i}=t,a=i.opts.multipleOfPrecision,s=e.let("res"),o=a?(0,tv._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${a}`:(0,tv._)`${s} !== parseInt(${s})`;t.fail$data((0,tv._)`(${n} === 0 || (${s} = ${r}/${n}, ${o}))`)}};ID.default=Bse});var NU=_e(DD=>{"use strict";g();Object.defineProperty(DD,"__esModule",{value:!0});var Wp=Bt(),Ose=Zt(),jse=DA(),Mse={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Wp.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Wp._)`{limit: ${t}}`},Kse={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Mse,code(t){let{keyword:e,data:r,schemaCode:n,it:i}=t,a=e==="maxLength"?Wp.operators.GT:Wp.operators.LT,s=i.opts.unicode===!1?(0,Wp._)`${r}.length`:(0,Wp._)`${(0,Ose.useFunc)(t.gen,jse.default)}(${r})`;t.fail$data((0,Wp._)`${s} ${a} ${n}`)}};DD.default=Kse});var UU=_e(RD=>{"use strict";g();Object.defineProperty(RD,"__esModule",{value:!0});var Nse=wa(),Use=Zt(),xy=Bt(),Lse={message:({schemaCode:t})=>(0,xy.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,xy._)`{pattern: ${t}}`},qse={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Lse,code(t){let{gen:e,data:r,$data:n,schema:i,schemaCode:a,it:s}=t,o=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:d}=s.opts.code,l=d.code==="new RegExp"?(0,xy._)`new RegExp`:(0,Use.useFunc)(e,d),c=e.let("valid");e.try(()=>e.assign(c,(0,xy._)`${l}(${a}, ${o}).test(${r})`),()=>e.assign(c,!1)),t.fail$data((0,xy._)`!${c}`)}else{let d=(0,Nse.usePattern)(t,i);t.fail$data((0,xy._)`!${d}.test(${r})`)}}};RD.default=qse});var LU=_e(CD=>{"use strict";g();Object.defineProperty(CD,"__esModule",{value:!0});var rv=Bt(),zse={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,rv.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,rv._)`{limit: ${t}}`},Fse={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:zse,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxProperties"?rv.operators.GT:rv.operators.LT;t.fail$data((0,rv._)`Object.keys(${r}).length ${i} ${n}`)}};CD.default=Fse});var qU=_e($D=>{"use strict";g();Object.defineProperty($D,"__esModule",{value:!0});var nv=wa(),iv=Bt(),Gse=Zt(),Hse={message:({params:{missingProperty:t}})=>(0,iv.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,iv._)`{missingProperty: ${t}}`},Vse={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Hse,code(t){let{gen:e,schema:r,schemaCode:n,data:i,$data:a,it:s}=t,{opts:o}=s;if(!a&&r.length===0)return;let d=r.length>=o.loopRequired;if(s.allErrors?l():c(),o.strictRequired){let h=t.parentSchema.properties,{definedProperties:p}=t.it;for(let m of r)if(h?.[m]===void 0&&!p.has(m)){let y=s.schemaEnv.baseId+s.errSchemaPath,b=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,Gse.checkStrictMode)(s,b,s.opts.strictRequired)}}function l(){if(d||a)t.block$data(iv.nil,u);else for(let h of r)(0,nv.checkReportMissingProp)(t,h)}function c(){let h=e.let("missing");if(d||a){let p=e.let("valid",!0);t.block$data(p,()=>f(h,p)),t.ok(p)}else e.if((0,nv.checkMissingProp)(t,r,h)),(0,nv.reportMissingProp)(t,h),e.else()}function u(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,nv.noPropertyInData)(e,i,h,o.ownProperties),()=>t.error())})}function f(h,p){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(p,(0,nv.propertyInData)(e,i,h,o.ownProperties)),e.if((0,iv.not)(p),()=>{t.error(),e.break()})},iv.nil)}}};$D.default=Vse});var zU=_e(BD=>{"use strict";g();Object.defineProperty(BD,"__esModule",{value:!0});var sv=Bt(),Wse={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,sv.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,sv._)`{limit: ${t}}`},Jse={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Wse,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxItems"?sv.operators.GT:sv.operators.LT;t.fail$data((0,sv._)`${r}.length ${i} ${n}`)}};BD.default=Jse});var Mx=_e(OD=>{"use strict";g();Object.defineProperty(OD,"__esModule",{value:!0});var FU=oD();FU.code='require("ajv/dist/runtime/equal").default';OD.default=FU});var GU=_e(MD=>{"use strict";g();Object.defineProperty(MD,"__esModule",{value:!0});var jD=F0(),Vi=Bt(),Zse=Zt(),Yse=Mx(),Xse={message:({params:{i:t,j:e}})=>(0,Vi.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Vi._)`{i: ${t}, j: ${e}}`},Qse={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Xse,code(t){let{gen:e,data:r,$data:n,schema:i,parentSchema:a,schemaCode:s,it:o}=t;if(!n&&!i)return;let d=e.let("valid"),l=a.items?(0,jD.getSchemaTypes)(a.items):[];t.block$data(d,c,(0,Vi._)`${s} === false`),t.ok(d);function c(){let p=e.let("i",(0,Vi._)`${r}.length`),m=e.let("j");t.setParams({i:p,j:m}),e.assign(d,!0),e.if((0,Vi._)`${p} > 1`,()=>(u()?f:h)(p,m))}function u(){return l.length>0&&!l.some(p=>p==="object"||p==="array")}function f(p,m){let y=e.name("item"),b=(0,jD.checkDataTypes)(l,y,o.opts.strictNumbers,jD.DataType.Wrong),w=e.const("indices",(0,Vi._)`{}`);e.for((0,Vi._)`;${p}--;`,()=>{e.let(y,(0,Vi._)`${r}[${p}]`),e.if(b,(0,Vi._)`continue`),l.length>1&&e.if((0,Vi._)`typeof ${y} == "string"`,(0,Vi._)`${y} += "_"`),e.if((0,Vi._)`typeof ${w}[${y}] == "number"`,()=>{e.assign(m,(0,Vi._)`${w}[${y}]`),t.error(),e.assign(d,!1).break()}).code((0,Vi._)`${w}[${y}] = ${p}`)})}function h(p,m){let y=(0,Zse.useFunc)(e,Yse.default),b=e.name("outer");e.label(b).for((0,Vi._)`;${p}--;`,()=>e.for((0,Vi._)`${m} = ${p}; ${m}--;`,()=>e.if((0,Vi._)`${y}(${r}[${p}], ${r}[${m}])`,()=>{t.error(),e.assign(d,!1).break(b)})))}}};MD.default=Qse});var HU=_e(ND=>{"use strict";g();Object.defineProperty(ND,"__esModule",{value:!0});var KD=Bt(),eoe=Zt(),toe=Mx(),roe={message:"must be equal to constant",params:({schemaCode:t})=>(0,KD._)`{allowedValue: ${t}}`},noe={keyword:"const",$data:!0,error:roe,code(t){let{gen:e,data:r,$data:n,schemaCode:i,schema:a}=t;n||a&&typeof a=="object"?t.fail$data((0,KD._)`!${(0,eoe.useFunc)(e,toe.default)}(${r}, ${i})`):t.fail((0,KD._)`${a} !== ${r}`)}};ND.default=noe});var VU=_e(UD=>{"use strict";g();Object.defineProperty(UD,"__esModule",{value:!0});var ov=Bt(),ioe=Zt(),soe=Mx(),ooe={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ov._)`{allowedValues: ${t}}`},aoe={keyword:"enum",schemaType:"array",$data:!0,error:ooe,code(t){let{gen:e,data:r,$data:n,schema:i,schemaCode:a,it:s}=t;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let o=i.length>=s.opts.loopEnum,d,l=()=>d??(d=(0,ioe.useFunc)(e,soe.default)),c;if(o||n)c=e.let("valid"),t.block$data(c,u);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let h=e.const("vSchema",a);c=(0,ov.or)(...i.map((p,m)=>f(h,m)))}t.pass(c);function u(){e.assign(c,!1),e.forOf("v",a,h=>e.if((0,ov._)`${l()}(${r}, ${h})`,()=>e.assign(c,!0).break()))}function f(h,p){let m=i[p];return typeof m=="object"&&m!==null?(0,ov._)`${l()}(${r}, ${h}[${p}])`:(0,ov._)`${r} === ${m}`}}};UD.default=aoe});var WU=_e(LD=>{"use strict";g();Object.defineProperty(LD,"__esModule",{value:!0});var coe=MU(),doe=KU(),loe=NU(),uoe=UU(),foe=LU(),poe=qU(),hoe=zU(),moe=GU(),yoe=HU(),goe=VU(),woe=[coe.default,doe.default,loe.default,uoe.default,foe.default,poe.default,hoe.default,moe.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},yoe.default,goe.default];LD.default=woe});var zD=_e(av=>{"use strict";g();Object.defineProperty(av,"__esModule",{value:!0});av.validateAdditionalItems=void 0;var Jp=Bt(),qD=Zt(),voe={message:({params:{len:t}})=>(0,Jp.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Jp._)`{limit: ${t}}`},boe={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:voe,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,qD.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}JU(t,n)}};function JU(t,e){let{gen:r,schema:n,data:i,keyword:a,it:s}=t;s.items=!0;let o=r.const("len",(0,Jp._)`${i}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Jp._)`${o} <= ${e.length}`);else if(typeof n=="object"&&!(0,qD.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,Jp._)`${o} <= ${e.length}`);r.if((0,Jp.not)(l),()=>d(l)),t.ok(l)}function d(l){r.forRange("i",e.length,o,c=>{t.subschema({keyword:a,dataProp:c,dataPropType:qD.Type.Num},l),s.allErrors||r.if((0,Jp.not)(l),()=>r.break())})}}av.validateAdditionalItems=JU;av.default=boe});var FD=_e(cv=>{"use strict";g();Object.defineProperty(cv,"__esModule",{value:!0});cv.validateTuple=void 0;var ZU=Bt(),Kx=Zt(),Poe=wa(),xoe={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return YU(t,"additionalItems",e);r.items=!0,!(0,Kx.alwaysValidSchema)(r,e)&&t.ok((0,Poe.validateArray)(t))}};function YU(t,e,r=t.schema){let{gen:n,parentSchema:i,data:a,keyword:s,it:o}=t;c(i),o.opts.unevaluated&&r.length&&o.items!==!0&&(o.items=Kx.mergeEvaluated.items(n,r.length,o.items));let d=n.name("valid"),l=n.const("len",(0,ZU._)`${a}.length`);r.forEach((u,f)=>{(0,Kx.alwaysValidSchema)(o,u)||(n.if((0,ZU._)`${l} > ${f}`,()=>t.subschema({keyword:s,schemaProp:f,dataProp:f},d)),t.ok(d))});function c(u){let{opts:f,errSchemaPath:h}=o,p=r.length,m=p===u.minItems&&(p===u.maxItems||u[e]===!1);if(f.strictTuples&&!m){let y=`"${s}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,Kx.checkStrictMode)(o,y,f.strictTuples)}}}cv.validateTuple=YU;cv.default=xoe});var XU=_e(GD=>{"use strict";g();Object.defineProperty(GD,"__esModule",{value:!0});var Eoe=FD(),Soe={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Eoe.validateTuple)(t,"items")};GD.default=Soe});var eL=_e(HD=>{"use strict";g();Object.defineProperty(HD,"__esModule",{value:!0});var QU=Bt(),Aoe=Zt(),koe=wa(),_oe=zD(),Toe={message:({params:{len:t}})=>(0,QU.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,QU._)`{limit: ${t}}`},Ioe={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Toe,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:i}=r;n.items=!0,!(0,Aoe.alwaysValidSchema)(n,e)&&(i?(0,_oe.validateAdditionalItems)(t,i):t.ok((0,koe.validateArray)(t)))}};HD.default=Ioe});var tL=_e(VD=>{"use strict";g();Object.defineProperty(VD,"__esModule",{value:!0});var ba=Bt(),Nx=Zt(),Doe={message:({params:{min:t,max:e}})=>e===void 0?(0,ba.str)`must contain at least ${t} valid item(s)`:(0,ba.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ba._)`{minContains: ${t}}`:(0,ba._)`{minContains: ${t}, maxContains: ${e}}`},Roe={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Doe,code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:a}=t,s,o,{minContains:d,maxContains:l}=n;a.opts.next?(s=d===void 0?1:d,o=l):s=1;let c=e.const("len",(0,ba._)`${i}.length`);if(t.setParams({min:s,max:o}),o===void 0&&s===0){(0,Nx.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(o!==void 0&&s>o){(0,Nx.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Nx.alwaysValidSchema)(a,r)){let m=(0,ba._)`${c} >= ${s}`;o!==void 0&&(m=(0,ba._)`${m} && ${c} <= ${o}`),t.pass(m);return}a.items=!0;let u=e.name("valid");o===void 0&&s===1?h(u,()=>e.if(u,()=>e.break())):s===0?(e.let(u,!0),o!==void 0&&e.if((0,ba._)`${i}.length > 0`,f)):(e.let(u,!1),f()),t.result(u,()=>t.reset());function f(){let m=e.name("_valid"),y=e.let("count",0);h(m,()=>e.if(m,()=>p(y)))}function h(m,y){e.forRange("i",0,c,b=>{t.subschema({keyword:"contains",dataProp:b,dataPropType:Nx.Type.Num,compositeRule:!0},m),y()})}function p(m){e.code((0,ba._)`${m}++`),o===void 0?e.if((0,ba._)`${m} >= ${s}`,()=>e.assign(u,!0).break()):(e.if((0,ba._)`${m} > ${o}`,()=>e.assign(u,!1).break()),s===1?e.assign(u,!0):e.if((0,ba._)`${m} >= ${s}`,()=>e.assign(u,!0)))}}};VD.default=Roe});var Ux=_e(hd=>{"use strict";g();Object.defineProperty(hd,"__esModule",{value:!0});hd.validateSchemaDeps=hd.validatePropertyDeps=hd.error=void 0;var WD=Bt(),Coe=Zt(),dv=wa();hd.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,WD.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,WD._)`{property: ${t},
8
8
  missingProperty: ${n},
9
9
  depsCount: ${e},
10
- deps: ${r}}`};var $oe={keyword:"dependencies",type:"object",schemaType:"object",error:hd.error,code(t){let[e,r]=Boe(t);rL(t,e),nL(t,r)}};function Boe({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let i=Array.isArray(t[n])?e:r;i[n]=t[n]}return[e,r]}function rL(t,e=t.schema){let{gen:r,data:n,it:i}=t;if(Object.keys(e).length===0)return;let a=r.let("missing");for(let s in e){let o=e[s];if(o.length===0)continue;let d=(0,dv.propertyInData)(r,n,s,i.opts.ownProperties);t.setParams({property:s,depsCount:o.length,deps:o.join(", ")}),i.allErrors?r.if(d,()=>{for(let l of o)(0,dv.checkReportMissingProp)(t,l)}):(r.if((0,WD._)`${d} && (${(0,dv.checkMissingProp)(t,o,a)})`),(0,dv.reportMissingProp)(t,a),r.else())}}hd.validatePropertyDeps=rL;function nL(t,e=t.schema){let{gen:r,data:n,keyword:i,it:a}=t,s=r.name("valid");for(let o in e)(0,Coe.alwaysValidSchema)(a,e[o])||(r.if((0,dv.propertyInData)(r,n,o,a.opts.ownProperties),()=>{let d=t.subschema({keyword:i,schemaProp:o},s);t.mergeValidEvaluated(d,s)},()=>r.var(s,!0)),t.ok(s))}hd.validateSchemaDeps=nL;hd.default=$oe});var sL=_e(JD=>{"use strict";g();Object.defineProperty(JD,"__esModule",{value:!0});var iL=Bt(),Ooe=Zt(),joe={message:"property name must be valid",params:({params:t})=>(0,iL._)`{propertyName: ${t.propertyName}}`},Moe={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:joe,code(t){let{gen:e,schema:r,data:n,it:i}=t;if((0,Ooe.alwaysValidSchema)(i,r))return;let a=e.name("valid");e.forIn("key",n,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},a),e.if((0,iL.not)(a),()=>{t.error(!0),i.allErrors||e.break()})}),t.ok(a)}};JD.default=Moe});var YD=_e(ZD=>{"use strict";g();Object.defineProperty(ZD,"__esModule",{value:!0});var Lx=wa(),vc=Bt(),Koe=ga(),qx=Zt(),Noe={message:"must NOT have additional properties",params:({params:t})=>(0,vc._)`{additionalProperty: ${t.additionalProperty}}`},Uoe={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Noe,code(t){let{gen:e,schema:r,parentSchema:n,data:i,errsCount:a,it:s}=t;if(!a)throw new Error("ajv implementation error");let{allErrors:o,opts:d}=s;if(s.props=!0,d.removeAdditional!=="all"&&(0,qx.alwaysValidSchema)(s,r))return;let l=(0,Lx.allSchemaProperties)(n.properties),c=(0,Lx.allSchemaProperties)(n.patternProperties);u(),t.ok((0,vc._)`${a} === ${Koe.default.errors}`);function u(){e.forIn("key",i,y=>{!l.length&&!c.length?p(y):e.if(f(y),()=>p(y))})}function f(y){let b;if(l.length>8){let w=(0,qx.schemaRefOrVal)(s,n.properties,"properties");b=(0,Lx.isOwnProperty)(e,w,y)}else l.length?b=(0,vc.or)(...l.map(w=>(0,vc._)`${y} === ${w}`)):b=vc.nil;return c.length&&(b=(0,vc.or)(b,...c.map(w=>(0,vc._)`${(0,Lx.usePattern)(t,w)}.test(${y})`))),(0,vc.not)(b)}function h(y){e.code((0,vc._)`delete ${i}[${y}]`)}function p(y){if(d.removeAdditional==="all"||d.removeAdditional&&r===!1){h(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),o||e.break();return}if(typeof r=="object"&&!(0,qx.alwaysValidSchema)(s,r)){let b=e.name("valid");d.removeAdditional==="failing"?(m(y,b,!1),e.if((0,vc.not)(b),()=>{t.reset(),h(y)})):(m(y,b),o||e.if((0,vc.not)(b),()=>e.break()))}}function m(y,b,w){let S={keyword:"additionalProperties",dataProp:y,dataPropType:qx.Type.Str};w===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(S,b)}}};ZD.default=Uoe});var cL=_e(QD=>{"use strict";g();Object.defineProperty(QD,"__esModule",{value:!0});var Loe=W0(),oL=wa(),XD=Zt(),aL=YD(),qoe={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:a}=t;a.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&aL.default.code(new Loe.KeywordCxt(a,aL.default,"additionalProperties"));let s=(0,oL.allSchemaProperties)(r);for(let u of s)a.definedProperties.add(u);a.opts.unevaluated&&s.length&&a.props!==!0&&(a.props=XD.mergeEvaluated.props(e,(0,XD.toHash)(s),a.props));let o=s.filter(u=>!(0,XD.alwaysValidSchema)(a,r[u]));if(o.length===0)return;let d=e.name("valid");for(let u of o)l(u)?c(u):(e.if((0,oL.propertyInData)(e,i,u,a.opts.ownProperties)),c(u),a.allErrors||e.else().var(d,!0),e.endIf()),t.it.definedProperties.add(u),t.ok(d);function l(u){return a.opts.useDefaults&&!a.compositeRule&&r[u].default!==void 0}function c(u){t.subschema({keyword:"properties",schemaProp:u,dataProp:u},d)}}};QD.default=qoe});var fL=_e(eR=>{"use strict";g();Object.defineProperty(eR,"__esModule",{value:!0});var dL=wa(),zx=Bt(),lL=Zt(),uL=Zt(),zoe={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:i,it:a}=t,{opts:s}=a,o=(0,dL.allSchemaProperties)(r),d=o.filter(m=>(0,lL.alwaysValidSchema)(a,r[m]));if(o.length===0||d.length===o.length&&(!a.opts.unevaluated||a.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&i.properties,c=e.name("valid");a.props!==!0&&!(a.props instanceof zx.Name)&&(a.props=(0,uL.evaluatedPropsToName)(e,a.props));let{props:u}=a;f();function f(){for(let m of o)l&&h(m),a.allErrors?p(m):(e.var(c,!0),p(m),e.if(c))}function h(m){for(let y in l)new RegExp(m).test(y)&&(0,lL.checkStrictMode)(a,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function p(m){e.forIn("key",n,y=>{e.if((0,zx._)`${(0,dL.usePattern)(t,m)}.test(${y})`,()=>{let b=d.includes(m);b||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:uL.Type.Str},c),a.opts.unevaluated&&u!==!0?e.assign((0,zx._)`${u}[${y}]`,!0):!b&&!a.allErrors&&e.if((0,zx.not)(c),()=>e.break())})})}}};eR.default=zoe});var pL=_e(tR=>{"use strict";g();Object.defineProperty(tR,"__esModule",{value:!0});var Foe=Zt(),Goe={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Foe.alwaysValidSchema)(n,r)){t.fail();return}let i=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),t.failResult(i,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};tR.default=Goe});var hL=_e(rR=>{"use strict";g();Object.defineProperty(rR,"__esModule",{value:!0});var Hoe=wa(),Voe={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Hoe.validateUnion,error:{message:"must match a schema in anyOf"}};rR.default=Voe});var mL=_e(nR=>{"use strict";g();Object.defineProperty(nR,"__esModule",{value:!0});var Fx=Bt(),Woe=Zt(),Joe={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Fx._)`{passingSchemas: ${t.passing}}`},Zoe={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Joe,code(t){let{gen:e,schema:r,parentSchema:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let a=r,s=e.let("valid",!1),o=e.let("passing",null),d=e.name("_valid");t.setParams({passing:o}),e.block(l),t.result(s,()=>t.reset(),()=>t.error(!0));function l(){a.forEach((c,u)=>{let f;(0,Woe.alwaysValidSchema)(i,c)?e.var(d,!0):f=t.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},d),u>0&&e.if((0,Fx._)`${d} && ${s}`).assign(s,!1).assign(o,(0,Fx._)`[${o}, ${u}]`).else(),e.if(d,()=>{e.assign(s,!0),e.assign(o,u),f&&t.mergeEvaluated(f,Fx.Name)})})}}};nR.default=Zoe});var yL=_e(iR=>{"use strict";g();Object.defineProperty(iR,"__esModule",{value:!0});var Yoe=Zt(),Xoe={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=e.name("valid");r.forEach((a,s)=>{if((0,Yoe.alwaysValidSchema)(n,a))return;let o=t.subschema({keyword:"allOf",schemaProp:s},i);t.ok(i),t.mergeEvaluated(o)})}};iR.default=Xoe});var vL=_e(sR=>{"use strict";g();Object.defineProperty(sR,"__esModule",{value:!0});var Gx=Bt(),wL=Zt(),Qoe={message:({params:t})=>(0,Gx.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Gx._)`{failingKeyword: ${t.ifClause}}`},eae={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Qoe,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,wL.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(d(),t.reset(),i&&a){let c=e.let("ifClause");t.setParams({ifClause:c}),e.if(o,l("then",c),l("else",c))}else i?e.if(o,l("then")):e.if((0,Gx.not)(o),l("else"));t.pass(s,()=>t.error(!0));function d(){let c=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},o);t.mergeEvaluated(c)}function l(c,u){return()=>{let f=t.subschema({keyword:c},o);e.assign(s,o),t.mergeValidEvaluated(f,s),u?e.assign(u,(0,Gx._)`${c}`):t.setParams({ifClause:c})}}}};function gL(t,e){let r=t.schema[e];return r!==void 0&&!(0,wL.alwaysValidSchema)(t,r)}sR.default=eae});var bL=_e(oR=>{"use strict";g();Object.defineProperty(oR,"__esModule",{value:!0});var tae=Zt(),rae={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,tae.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};oR.default=rae});var PL=_e(aR=>{"use strict";g();Object.defineProperty(aR,"__esModule",{value:!0});var nae=zD(),iae=XU(),sae=FD(),oae=eL(),aae=tL(),cae=Ux(),dae=sL(),lae=YD(),uae=cL(),fae=fL(),pae=pL(),hae=hL(),mae=mL(),yae=yL(),gae=vL(),wae=bL();function vae(t=!1){let e=[pae.default,hae.default,mae.default,yae.default,gae.default,wae.default,dae.default,lae.default,cae.default,uae.default,fae.default];return t?e.push(iae.default,oae.default):e.push(nae.default,sae.default),e.push(aae.default),e}aR.default=vae});var dR=_e(lv=>{"use strict";g();Object.defineProperty(lv,"__esModule",{value:!0});lv.dynamicAnchor=void 0;var cR=Bt(),bae=ga(),xL=Z0(),Pae=Bx(),xae={keyword:"$dynamicAnchor",schemaType:"string",code:t=>EL(t,t.schema)};function EL(t,e){let{gen:r,it:n}=t;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,cR._)`${bae.default.dynamicAnchors}${(0,cR.getProperty)(e)}`,a=n.errSchemaPath==="#"?n.validateName:Eae(t);r.if((0,cR._)`!${i}`,()=>r.assign(i,a))}lv.dynamicAnchor=EL;function Eae(t){let{schemaEnv:e,schema:r,self:n}=t.it,{root:i,baseId:a,localRefs:s,meta:o}=e.root,{schemaId:d}=n.opts,l=new xL.SchemaEnv({schema:r,schemaId:d,root:i,baseId:a,localRefs:s,meta:o});return xL.compileSchema.call(n,l),(0,Pae.getValidate)(t,l)}lv.default=xae});var lR=_e(uv=>{"use strict";g();Object.defineProperty(uv,"__esModule",{value:!0});uv.dynamicRef=void 0;var SL=Bt(),Sae=ga(),AL=Bx(),Aae={keyword:"$dynamicRef",schemaType:"string",code:t=>kL(t,t.schema)};function kL(t,e){let{gen:r,keyword:n,it:i}=t;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let a=e.slice(1);if(i.allErrors)s();else{let d=r.let("valid",!1);s(d),t.ok(d)}function s(d){if(i.schemaEnv.root.dynamicAnchors[a]){let l=r.let("_v",(0,SL._)`${Sae.default.dynamicAnchors}${(0,SL.getProperty)(a)}`);r.if(l,o(l,d),o(i.validateName,d))}else o(i.validateName,d)()}function o(d,l){return l?()=>r.block(()=>{(0,AL.callRef)(t,d),r.let(l,!0)}):()=>(0,AL.callRef)(t,d)}}uv.dynamicRef=kL;uv.default=Aae});var _L=_e(uR=>{"use strict";g();Object.defineProperty(uR,"__esModule",{value:!0});var kae=dR(),_ae=Zt(),Tae={keyword:"$recursiveAnchor",schemaType:"boolean",code(t){t.schema?(0,kae.dynamicAnchor)(t,""):(0,_ae.checkStrictMode)(t.it,"$recursiveAnchor: false is ignored")}};uR.default=Tae});var TL=_e(fR=>{"use strict";g();Object.defineProperty(fR,"__esModule",{value:!0});var Iae=lR(),Dae={keyword:"$recursiveRef",schemaType:"string",code:t=>(0,Iae.dynamicRef)(t,t.schema)};fR.default=Dae});var IL=_e(pR=>{"use strict";g();Object.defineProperty(pR,"__esModule",{value:!0});var Rae=dR(),Cae=lR(),$ae=_L(),Bae=TL(),Oae=[Rae.default,Cae.default,$ae.default,Bae.default];pR.default=Oae});var RL=_e(hR=>{"use strict";g();Object.defineProperty(hR,"__esModule",{value:!0});var DL=Ux(),jae={keyword:"dependentRequired",type:"object",schemaType:"object",error:DL.error,code:t=>(0,DL.validatePropertyDeps)(t)};hR.default=jae});var CL=_e(mR=>{"use strict";g();Object.defineProperty(mR,"__esModule",{value:!0});var Mae=Ux(),Kae={keyword:"dependentSchemas",type:"object",schemaType:"object",code:t=>(0,Mae.validateSchemaDeps)(t)};mR.default=Kae});var $L=_e(yR=>{"use strict";g();Object.defineProperty(yR,"__esModule",{value:!0});var Nae=Zt(),Uae={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:t,parentSchema:e,it:r}){e.contains===void 0&&(0,Nae.checkStrictMode)(r,`"${t}" without "contains" is ignored`)}};yR.default=Uae});var BL=_e(gR=>{"use strict";g();Object.defineProperty(gR,"__esModule",{value:!0});var Lae=RL(),qae=CL(),zae=$L(),Fae=[Lae.default,qae.default,zae.default];gR.default=Fae});var jL=_e(wR=>{"use strict";g();Object.defineProperty(wR,"__esModule",{value:!0});var Qu=Bt(),OL=Zt(),Gae=ga(),Hae={message:"must NOT have unevaluated properties",params:({params:t})=>(0,Qu._)`{unevaluatedProperty: ${t.unevaluatedProperty}}`},Vae={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Hae,code(t){let{gen:e,schema:r,data:n,errsCount:i,it:a}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:s,props:o}=a;o instanceof Qu.Name?e.if((0,Qu._)`${o} !== true`,()=>e.forIn("key",n,u=>e.if(l(o,u),()=>d(u)))):o!==!0&&e.forIn("key",n,u=>o===void 0?d(u):e.if(c(o,u),()=>d(u))),a.props=!0,t.ok((0,Qu._)`${i} === ${Gae.default.errors}`);function d(u){if(r===!1){t.setParams({unevaluatedProperty:u}),t.error(),s||e.break();return}if(!(0,OL.alwaysValidSchema)(a,r)){let f=e.name("valid");t.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:OL.Type.Str},f),s||e.if((0,Qu.not)(f),()=>e.break())}}function l(u,f){return(0,Qu._)`!${u} || !${u}[${f}]`}function c(u,f){let h=[];for(let p in u)u[p]===!0&&h.push((0,Qu._)`${f} !== ${p}`);return(0,Qu.and)(...h)}}};wR.default=Vae});var KL=_e(vR=>{"use strict";g();Object.defineProperty(vR,"__esModule",{value:!0});var Zp=Bt(),ML=Zt(),Wae={message:({params:{len:t}})=>(0,Zp.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Zp._)`{limit: ${t}}`},Jae={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Wae,code(t){let{gen:e,schema:r,data:n,it:i}=t,a=i.items||0;if(a===!0)return;let s=e.const("len",(0,Zp._)`${n}.length`);if(r===!1)t.setParams({len:a}),t.fail((0,Zp._)`${s} > ${a}`);else if(typeof r=="object"&&!(0,ML.alwaysValidSchema)(i,r)){let d=e.var("valid",(0,Zp._)`${s} <= ${a}`);e.if((0,Zp.not)(d),()=>o(d,a)),t.ok(d)}i.items=!0;function o(d,l){e.forRange("i",l,s,c=>{t.subschema({keyword:"unevaluatedItems",dataProp:c,dataPropType:ML.Type.Num},d),i.allErrors||e.if((0,Zp.not)(d),()=>e.break())})}}};vR.default=Jae});var NL=_e(bR=>{"use strict";g();Object.defineProperty(bR,"__esModule",{value:!0});var Zae=jL(),Yae=KL(),Xae=[Zae.default,Yae.default];bR.default=Xae});var UL=_e(PR=>{"use strict";g();Object.defineProperty(PR,"__esModule",{value:!0});var Un=Bt(),Qae={message:({schemaCode:t})=>(0,Un.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Un._)`{format: ${t}}`},ece={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Qae,code(t,e){let{gen:r,data:n,$data:i,schema:a,schemaCode:s,it:o}=t,{opts:d,errSchemaPath:l,schemaEnv:c,self:u}=o;if(!d.validateFormats)return;i?f():h();function f(){let p=r.scopeValue("formats",{ref:u.formats,code:d.code.formats}),m=r.const("fDef",(0,Un._)`${p}[${s}]`),y=r.let("fType"),b=r.let("format");r.if((0,Un._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,Un._)`${m}.type || "string"`).assign(b,(0,Un._)`${m}.validate`),()=>r.assign(y,(0,Un._)`"string"`).assign(b,m)),t.fail$data((0,Un.or)(w(),S()));function w(){return d.strictSchema===!1?Un.nil:(0,Un._)`${s} && !${b}`}function S(){let k=c.$async?(0,Un._)`(${m}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,Un._)`${b}(${n})`,T=(0,Un._)`(typeof ${b} == "function" ? ${k} : ${b}.test(${n}))`;return(0,Un._)`${b} && ${b} !== true && ${y} === ${e} && !${T}`}}function h(){let p=u.formats[a];if(!p){w();return}if(p===!0)return;let[m,y,b]=S(p);m===e&&t.pass(k());function w(){if(d.strictSchema===!1){u.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${a}" ignored in schema at path "${l}"`}}function S(T){let D=T instanceof RegExp?(0,Un.regexpCode)(T):d.code.formats?(0,Un._)`${d.code.formats}${(0,Un.getProperty)(a)}`:void 0,K=r.scopeValue("formats",{key:a,ref:T,code:D});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,Un._)`${K}.validate`]:["string",T,K]}function k(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!c.$async)throw new Error("async format in sync schema");return(0,Un._)`await ${b}(${n})`}return typeof y=="function"?(0,Un._)`${b}(${n})`:(0,Un._)`${b}.test(${n})`}}}};PR.default=ece});var LL=_e(xR=>{"use strict";g();Object.defineProperty(xR,"__esModule",{value:!0});var tce=UL(),rce=[tce.default];xR.default=rce});var qL=_e(Ey=>{"use strict";g();Object.defineProperty(Ey,"__esModule",{value:!0});Ey.contentVocabulary=Ey.metadataVocabulary=void 0;Ey.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ey.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var FL=_e(ER=>{"use strict";g();Object.defineProperty(ER,"__esModule",{value:!0});var nce=jU(),ice=WU(),sce=PL(),oce=IL(),ace=BL(),cce=NL(),dce=LL(),zL=qL(),lce=[oce.default,nce.default,ice.default,(0,sce.default)(!0),dce.default,zL.metadataVocabulary,zL.contentVocabulary,ace.default,cce.default];ER.default=lce});var HL=_e(Hx=>{"use strict";g();Object.defineProperty(Hx,"__esModule",{value:!0});Hx.DiscrError=void 0;var GL;(function(t){t.Tag="tag",t.Mapping="mapping"})(GL||(Hx.DiscrError=GL={}))});var WL=_e(AR=>{"use strict";g();Object.defineProperty(AR,"__esModule",{value:!0});var Sy=Bt(),SR=HL(),VL=Z0(),uce=J0(),fce=Zt(),pce={message:({params:{discrError:t,tagName:e}})=>t===SR.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Sy._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},hce={keyword:"discriminator",type:"object",schemaType:"object",error:pce,code(t){let{gen:e,data:r,schema:n,parentSchema:i,it:a}=t,{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 d=e.let("valid",!1),l=e.const("tag",(0,Sy._)`${r}${(0,Sy.getProperty)(o)}`);e.if((0,Sy._)`typeof ${l} == "string"`,()=>c(),()=>t.error(!1,{discrError:SR.DiscrError.Tag,tag:l,tagName:o})),t.ok(d);function c(){let h=f();e.if(!1);for(let p in h)e.elseIf((0,Sy._)`${l} === ${p}`),e.assign(d,u(h[p]));e.else(),t.error(!1,{discrError:SR.DiscrError.Mapping,tag:l,tagName:o}),e.endIf()}function u(h){let p=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:h},p);return t.mergeEvaluated(m,Sy.Name),p}function f(){var h;let p={},m=b(i),y=!0;for(let k=0;k<s.length;k++){let T=s[k];if(T?.$ref&&!(0,fce.schemaHasRulesButRef)(T,a.self.RULES)){let K=T.$ref;if(T=VL.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,K),T instanceof VL.SchemaEnv&&(T=T.schema),T===void 0)throw new uce.default(a.opts.uriResolver,a.baseId,K)}let D=(h=T?.properties)===null||h===void 0?void 0:h[o];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${o}"`);y=y&&(m||b(T)),w(D,k)}if(!y)throw new Error(`discriminator: "${o}" must be required`);return p;function b({required:k}){return Array.isArray(k)&&k.includes(o)}function w(k,T){if(k.const)S(k.const,T);else if(k.enum)for(let D of k.enum)S(D,T);else throw new Error(`discriminator: "properties/${o}" must have "const" or "enum"`)}function S(k,T){if(typeof k!="string"||k in p)throw new Error(`discriminator: "${o}" values must be unique strings`);p[k]=T}}}};AR.default=hce});var JL=_e((iOe,mce)=>{mce.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 ZL=_e((sOe,yce)=>{yce.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 YL=_e((oOe,gce)=>{gce.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 XL=_e((aOe,wce)=>{wce.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 QL=_e((cOe,vce)=>{vce.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 e9=_e((dOe,bce)=>{bce.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 t9=_e((lOe,Pce)=>{Pce.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 r9=_e((uOe,xce)=>{xce.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 n9=_e(kR=>{"use strict";g();Object.defineProperty(kR,"__esModule",{value:!0});var Ece=JL(),Sce=ZL(),Ace=YL(),kce=XL(),_ce=QL(),Tce=e9(),Ice=t9(),Dce=r9(),Rce=["/properties"];function Cce(t){return[Ece,Sce,Ace,kce,_ce,e(this,Tce),Ice,e(this,Dce)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function e(r,n){return t?r.$dataMetaSchema(n,Rce):n}}kR.default=Cce});var IR=_e((an,TR)=>{"use strict";g();Object.defineProperty(an,"__esModule",{value:!0});an.MissingRefError=an.ValidationError=an.CodeGen=an.Name=an.nil=an.stringify=an.str=an._=an.KeywordCxt=an.Ajv2020=void 0;var $ce=RU(),Bce=FL(),Oce=WL(),jce=n9(),_R="https://json-schema.org/draft/2020-12/schema",Ay=class extends $ce.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Bce.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Oce.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:r}=this.opts;r&&(jce.default.call(this,e),this.refs["http://json-schema.org/schema"]=_R)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_R)?_R:void 0)}};an.Ajv2020=Ay;TR.exports=an=Ay;TR.exports.Ajv2020=Ay;Object.defineProperty(an,"__esModule",{value:!0});an.default=Ay;var Mce=W0();Object.defineProperty(an,"KeywordCxt",{enumerable:!0,get:function(){return Mce.KeywordCxt}});var ky=Bt();Object.defineProperty(an,"_",{enumerable:!0,get:function(){return ky._}});Object.defineProperty(an,"str",{enumerable:!0,get:function(){return ky.str}});Object.defineProperty(an,"stringify",{enumerable:!0,get:function(){return ky.stringify}});Object.defineProperty(an,"nil",{enumerable:!0,get:function(){return ky.nil}});Object.defineProperty(an,"Name",{enumerable:!0,get:function(){return ky.Name}});Object.defineProperty(an,"CodeGen",{enumerable:!0,get:function(){return ky.CodeGen}});var Kce=Ax();Object.defineProperty(an,"ValidationError",{enumerable:!0,get:function(){return Kce.default}});var Nce=J0();Object.defineProperty(an,"MissingRefError",{enumerable:!0,get:function(){return Nce.default}})});var ef,Vx=F(()=>{"use strict";g();wP();xt();ef=class t{static async authorizeConfigure(e){let{protocolsConfigureMessage:r,expectedGrantor:n,expectedGrantee:i,permissionGrant:a,messageStore:s}=e;await $o.performBaseValidation({incomingMessage:r,expectedGrantor:n,expectedGrantee:i,permissionGrant:a,messageStore:s}),t.verifyScope(r,a.scope)}static async authorizeQuery(e){let{expectedGrantee:r,expectedGrantor:n,incomingMessage:i,permissionGrant:a,messageStore:s}=e;await $o.performBaseValidation({incomingMessage:i,expectedGrantor:n,expectedGrantee:r,permissionGrant:a,messageStore:s});let d=a.scope.protocol,l=i.descriptor.filter?.protocol;if(d!==void 0&&l!==d)throw new ie(ne.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch,`Grant protocol scope ${d} does not match protocol in message ${l}`)}static verifyScope(e,r){if(r.protocol!==void 0&&r.protocol!==e.descriptor.definition.protocol)throw new ie(ne.ProtocolsGrantAuthorizationScopeProtocolMismatch,"Grant scope specifies different protocol than what appears in the configure message.")}}});function zs(t){let e=t.indexOf(":");if(e===-1)return;let r=t.substring(0,e),n=t.substring(e+1);return{alias:r,protocolPath:n}}function tf(t){return t.includes(":")}function Wx(t){return t.split("/").slice(-1)[0]}function yd(t,e){let r=t.split("/"),n,i=e;for(let a of r){if(!Object.hasOwn(i,a))return;n=i[a],i=n}return n}var md,Yp=F(()=>{"use strict";g();wn();jm();md=class{static async deriveAndInjectPublicEncryptionKeys(e,r,n){let i=JSON.parse(JSON.stringify(e));if(typeof r!="string"){let l=r,c=[Ht.ProtocolPath,e.protocol];async function u(f,h){for(let p in f)if(!p.startsWith("$")){let m=[...h,p],y=f[p];if(y.$ref!==void 0){await u(y,m);continue}let b=await l.derivePublicKey(m);y.$encryption={rootKeyId:l.rootKeyId,publicKeyJwk:b},await u(y,m)}}return await u(i.structure,c),i}let a=r;async function s(l,c){for(let u in l)if(!u.startsWith("$")){let f=await $s.derivePrivateKey(c,[u]),h=l[u];if(h.$ref!==void 0){await s(h,f);continue}let p=await Gt.getPublicKey({key:f.derivedPrivateKey});h.$encryption={rootKeyId:a,publicKeyJwk:p},await s(h,f)}}let o={derivationScheme:Ht.ProtocolPath,derivedPrivateKey:n,rootKeyId:a},d=await $s.derivePrivateKey(o,[Ht.ProtocolPath,e.protocol]);return await s(i.structure,d),i}}});var i9,Pa,Jx=F(()=>{"use strict";g();mc();i9=An(IR(),1);wr();nc();Vx();us();xt();lr();Yp();ua();Tg();Pa=class t extends $n{static async parse(e){return we.validateJsonSchema(e),t.validateProtocolDefinition(e.descriptor.definition),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),St.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:be.Protocols,method:ge.Configure,messageTimestamp:e.messageTimestamp??St.getCurrentTimestamp(),definition:t.normalizeDefinition(e.definition),...e.permissionGrantId!==void 0&&{permissionGrantId:e.permissionGrantId}},n=await we.createAuthorization({descriptor:r,signer:e.signer,delegatedGrant:e.delegatedGrant,permissionGrantId:e.permissionGrantId}),i={descriptor:r,authorization:n};return we.validateJsonSchema(i),t.validateProtocolDefinition(i.descriptor.definition),new t(i)}async authorizeAuthorDelegate(e){let r=Ir.parse(this.message.authorization.authorDelegatedGrant);await ef.authorizeConfigure({protocolsConfigureMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}static validateProtocolDefinition(e){let{protocol:r,types:n,uses:i}=e;si(r);for(let a in n){let s=n[a].schema;s!==void 0&&Wc(s)}i!==void 0&&t.validateUses(i,r),t.validateStructure(e)}static validateUses(e,r){let n=/^[a-zA-Z][a-zA-Z0-9_-]*$/;for(let i in e){if(!n.test(i))throw new ie(ne.ProtocolsConfigureInvalidUsesAlias,`invalid 'uses' alias '${i}': must match pattern ${n.toString()}.`);try{si(e[i])}catch{throw new ie(ne.ProtocolsConfigureInvalidUsesProtocolUrl,`invalid 'uses' protocol URL for alias '${i}': '${e[i]}' is not a valid normalized protocol URL.`)}if(e[i]===r)throw new ie(ne.ProtocolsConfigureInvalidUsesSelfReference,`'uses' alias '${i}' references the protocol's own URI '${r}'. a protocol cannot compose itself.`)}}static validateStructure(e){let{uses:r}=e,n=Object.keys(e.types),i=t.fetchAllRolePathsRecursively("",e.structure,[]);t.validateRuleSetRecursively({ruleSet:e.structure,ruleSetProtocolPath:"",recordTypes:n,roles:i,uses:r,types:e.types})}static fetchAllRolePathsRecursively(e,r,n){if(e.split("/").length>10)throw new ie(ne.ProtocolsConfigureRecordNestingDepthExceeded,"Record nesting depth exceeded 10 levels.");for(let i in r){if(i.startsWith("$"))continue;let a=r[i],s;e===""?s=i:s=`${e}/${i}`,a.$role?n.push(s):t.fetchAllRolePathsRecursively(s,a,n)}return n}static validateRuleSetRecursively(e){let{ruleSet:r,ruleSetProtocolPath:n,recordTypes:i,roles:a,uses:s,types:o}=e;if(r.$ref!==void 0){if(n.includes("/"))throw new ie(ne.ProtocolsConfigureInvalidRefNotAtRoot,`'$ref' at protocol path '${n}' is not allowed: '$ref' nodes are only supported at the root level of the structure.`);t.validateRefNode(r,n,s)}if(r.$size!==void 0){let{min:l=0,max:c}=r.$size;if(c!==void 0&&c<l)throw new ie(ne.ProtocolsConfigureInvalidSize,`Invalid size range found: max limit ${c} less than min limit ${l} at protocol path '${n}'`)}if(r.$recordLimit!==void 0){let{max:l,strategy:c}=r.$recordLimit;if(!Number.isInteger(l)||l<1)throw new ie(ne.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.max value ${l} at protocol path '${n}': must be an integer >= 1.`);let u=Object.values(Hl);if(!u.includes(c))throw new ie(ne.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.strategy '${c}' at protocol path '${n}': must be one of ${u.join(", ")}.`)}if(r.$tags){let l=new i9.default.default,{$allowUndefinedTags:c,$requiredTags:u,...f}=r.$tags;for(let h in f){let p=f[h];if(!l.validateSchema(p)){let m=l.errorsText(l.errors,{dataVar:`${n}/$tags/${h}`});throw new ie(ne.ProtocolsConfigureInvalidTagSchema,`tags schema validation error: ${m}`)}}}let d=r.$actions??[];for(let l=0;l<d.length;l++){let c=d[l];if(c.role!==void 0){if(tf(c.role))t.validateCrossProtocolAlias(c.role,s,n,"role");else if(!a.includes(c.role))throw new ie(ne.ProtocolsConfigureRoleDoesNotExistAtGivenPath,`Role in action ${JSON.stringify(c)} for rule set ${n} does not exist.`)}if(c.who==="anyone"&&c.of)throw new ie(ne.ProtocolsConfigureInvalidActionOfNotAllowed,`'of' is not allowed at rule set protocol path (${n})`);if(c.who===kc.Recipient&&c.of===void 0&&c.can.some(f=>![Pr.CoUpdate,Pr.CoDelete,Pr.CoPrune].includes(f)))throw new ie(ne.ProtocolsConfigureInvalidRecipientOfAction,"Rules for `recipient` without `of` property must have `can` containing only `co-update`, `co-delete`, and `co-prune`.");if(c.who===kc.Author&&!c.of)throw new ie(ne.ProtocolsConfigureInvalidActionMissingOf,"'of' is required when 'author' is specified as 'who'");if(c.of!==void 0&&n!==""){if(tf(c.of))t.validateCrossProtocolAlias(c.of,s,n,"of");else if(!(n===c.of||n.startsWith(c.of+"/")))throw new ie(ne.ProtocolsConfigureInvalidActionOfNotAnAncestor,`'of' value '${c.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(c)}.`)}if(c.can!==void 0){if(c.can.includes(Pr.Update)&&!c.can.includes(Pr.Create))throw new ie(ne.ProtocolsConfigureInvalidActionUpdateWithoutCreate,`Action rule ${JSON.stringify(c)} contains 'update' action but missing the required 'create' action.`);if(c.can.includes(Pr.Delete)&&!c.can.includes(Pr.Create))throw new ie(ne.ProtocolsConfigureInvalidActionDeleteWithoutCreate,`Action rule ${JSON.stringify(c)} contains 'delete' action but missing the required 'create' action.`);if(c.can.includes(Pr.Prune)&&!c.can.includes(Pr.Create))throw new ie(ne.ProtocolsConfigureInvalidActionPruneWithoutCreate,`Action rule ${JSON.stringify(c)} contains 'prune' action but missing the required 'create' action.`)}for(let u=l+1;u<d.length;u++){let f=d[u];if(c.who!==void 0){if(c.who===f.who&&c.of===f.of)throw new ie(ne.ProtocolsConfigureDuplicateActorInRuleSet,`More than one action rule per actor ${c.who} of ${c.of} not allowed within a rule set: ${JSON.stringify(c)}`)}else if(c.role===f.role)throw new ie(ne.ProtocolsConfigureDuplicateRoleInRuleSet,`More than one action rule per role ${c.role} not allowed within a rule set: ${JSON.stringify(c)}`)}}if(n!==""){let l=n.split("/").pop();o[l]?.encryptionRequired===!0&&d.some(f=>f.who===kc.Anyone&&f.can.includes(Pr.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.`)}r.$delivery!==void 0&&(r.$actions===void 0||r.$actions.length===0)&&console.warn(`ProtocolsConfigure: protocol path '${n}' has $delivery: '${r.$delivery}' but no $actions rules. The server uses $actions to determine delivery targets \u2014 without $actions, no participants can be resolved for delivery.`),r.$immutable===!0&&d.length>0&&d.some(c=>c.can.includes(Pr.Update)||c.can.includes(Pr.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 r){if(l.startsWith("$"))continue;let c=r[l];if(c.$ref===void 0&&!i.includes(l))throw new ie(ne.ProtocolsConfigureInvalidRuleSetRecordType,`Rule set ${l} is not declared as an allowed type in the protocol definition.`);let u;n===""?u=l:u=`${n}/${l}`,t.validateRuleSetRecursively({ruleSet:c,ruleSetProtocolPath:u,recordTypes:i,roles:a,uses:s,types:o})}}static validateRefNode(e,r,n){let i=e.$ref,a=zs(i);if(a===void 0)throw new ie(ne.ProtocolsConfigureInvalidRefAlias,`'$ref' value '${i}' at protocol path '${r}' must be in 'alias:typePath' format.`);if(n===void 0||n[a.alias]===void 0)throw new ie(ne.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${a.alias}' at protocol path '${r}' 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 ie(ne.ProtocolsConfigureInvalidRefNodeHasDirectives,`'$ref' node at protocol path '${r}' must not have '${o}'. $ref nodes are pure attachment points \u2014 directives belong on child rule sets.`)}static validateCrossProtocolAlias(e,r,n,i){let a=zs(e);if(a===void 0){let s=i==="role"?ne.ProtocolsConfigureInvalidCrossProtocolRole:ne.ProtocolsConfigureInvalidCrossProtocolOf;throw new ie(s,`cross-protocol '${i}' reference '${e}' at protocol path '${n}' could not be parsed as a valid 'alias:path' format.`)}if(r===void 0||r[a.alias]===void 0){let s=i==="role"?ne.ProtocolsConfigureInvalidCrossProtocolRole:ne.ProtocolsConfigureInvalidCrossProtocolOf;throw new ie(s,`cross-protocol '${i}' alias '${a.alias}' in '${e}' at protocol path '${n}' does not exist in the 'uses' map.`)}}static normalizeDefinition(e){let r={};for(let i in e.types)r[i]={...e.types[i]};for(let i in r){let a=r[i].schema;a!==void 0&&(r[i].schema=xp(a))}let n;if(e.uses!==void 0){n={};for(let i in e.uses)try{n[i]=Bs(e.uses[i])}catch{n[i]=e.uses[i]}}return{...e,protocol:Bs(e.protocol),types:r,...n!==void 0&&{uses:n}}}}});var Zx,s9=F(()=>{"use strict";g();No();wr();Uo();Lo();Jx();Vx();xt();lr();Yp();Zx=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Pa.parse(r)}catch(c){return wt(c,400)}try{await pn(r.authorization,this.deps.didResolver),await t.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(c){return wt(c,401)}try{await t.validateCompositionDependencies(e,r.descriptor.definition,this.deps.messageStore)}catch(c){return wt(c,400)}let i={interface:be.Protocols,method:ge.Configure,protocol:r.descriptor.definition.protocol},{messages:a}=await this.deps.messageStore.query(e,[i]),s=await we.getCid(r);for(let c of a)if(await we.getCid(c)===s)return{status:{code:409,detail:"Conflict"}};let o=await we.getNewestMessage(a),d=!1;(o===void 0||await we.isNewer(r,o))&&(d=!0,o=r);let l;if(d){let c=t.constructIndexes(n,!0);await this.deps.messageStore.put(e,r,c);let u=await we.getCid(r);await this.deps.stateIndex.insert(e,u,c),this.deps.eventLog!==void 0&&await this.deps.eventLog.emit(e,{message:r},c),l={status:{code:202,detail:"Accepted"}}}else{let c=t.constructIndexes(n,!1);await this.deps.messageStore.put(e,r,c);let u=await we.getCid(r);await this.deps.stateIndex.insert(e,u,c),l={status:{code:202,detail:"Accepted"}}}for(let c of a)if(c!==o){let u=await Pa.parse(c),f=t.constructIndexes(u,!1),h=await we.getCid(c);await this.deps.messageStore.delete(e,h),await this.deps.messageStore.put(e,c,f)}return l}static constructIndexes(e,r){let{definition:n,...i}=e.message.descriptor,{author:a}=e;return{...i,author:a,protocol:n.protocol,published:n.published,isLatestBaseState:r}}static async authorizeProtocolsConfigure(e,r,n){if(r.isSignedByAuthorDelegate&&await r.authorizeAuthorDelegate(n),r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let i=await dt.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await ef.authorizeConfigure({protocolsConfigureMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:i,messageStore:n})}else throw new ie(ne.ProtocolsConfigureAuthorizationFailed,"message failed authorization")}static async validateCompositionDependencies(e,r,n){let{uses:i}=r;if(i===void 0)return;let a=new Map;for(let s in i){let o=i[s],d=await t.fetchInstalledProtocolDefinition(e,o,n);if(d===void 0)throw new ie(ne.ProtocolsConfigureComposedProtocolNotInstalled,`composed protocol '${o}' (alias '${s}') is not installed for tenant '${e}'.`);a.set(s,d)}t.validateRefsAndRolesRecursively(r.structure,"",a)}static async fetchInstalledProtocolDefinition(e,r,n){let i={interface:be.Protocols,method:ge.Configure,protocol:r,isLatestBaseState:!0},{messages:a}=await n.query(e,[i]);if(a.length!==0)return a[0].descriptor.definition}static validateRefsAndRolesRecursively(e,r,n){for(let i in e){if(i.startsWith("$"))continue;let a=e[i],s=r===""?i:`${r}/${i}`;if(a.$ref!==void 0){let d=zs(a.$ref);if(d!==void 0){let l=n.get(d.alias);if(l===void 0)throw new ie(ne.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${d.alias}' at protocol path '${s}' was not found in the referenced definitions map.`);let c=d.protocolPath.split("/"),u=l.structure;for(let f=0;f<c.length;f++){let h=c[f],p=u[h];if(p===void 0)throw new ie(ne.ProtocolsConfigureInvalidRefProtocolPath,`'$ref' at protocol path '${s}' references type path '${d.protocolPath}' which does not exist in protocol '${l.protocol}'.`);if(p.$ref!==void 0){let m=c.slice(0,f+1).join("/");throw new ie(ne.ProtocolsConfigureInvalidRefTargetThroughRef,`'$ref' at protocol path '${s}' references type path '${d.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=p}}}let o=a.$actions??[];for(let d of o){if(d.role!==void 0){let l=zs(d.role);if(l!==void 0){let c=n.get(l.alias);if(c===void 0)throw new ie(ne.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role alias '${l.alias}' in '${d.role}' at protocol path '${s}' was not found in the referenced definitions map.`);let u=yd(l.protocolPath,c.structure);if(u===void 0||!u.$role)throw new ie(ne.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role '${d.role}' at protocol path '${s}' does not point to a valid role ($role: true) in protocol '${c.protocol}'.`)}}if(d.of!==void 0){let l=zs(d.of);if(l!==void 0){let c=n.get(l.alias);if(c===void 0)throw new ie(ne.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' alias '${l.alias}' in '${d.of}' at protocol path '${s}' was not found in the referenced definitions map.`);if(yd(l.protocolPath,c.structure)===void 0)throw new ie(ne.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' reference '${d.of}' at protocol path '${s}' does not point to a valid type path in protocol '${c.protocol}'.`)}}}t.validateRefsAndRolesRecursively(a,s,n)}}}});var xa,Yx=F(()=>{"use strict";g();mc();wr();Lo();Vx();Di();us();xt();lr();ua();xa=class t extends $n{static async parse(e){return e.authorization!==void 0&&await we.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&si(e.descriptor.filter.protocol),St.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:be.Protocols,method:ge.Query,messageTimestamp:e.messageTimestamp??St.getCurrentTimestamp(),filter:e.filter?t.normalizeFilter(e.filter):void 0,permissionGrantId:e.permissionGrantId};tr(r);let n;e.signer!==void 0&&(n=await we.createAuthorization({descriptor:r,signer:e.signer,permissionGrantId:e.permissionGrantId}));let i={descriptor:r,authorization:n};return we.validateJsonSchema(i),new t(i)}static normalizeFilter(e){return{...e,protocol:Bs(e.protocol)}}async authorize(e,r){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await dt.fetchGrant(e,r,this.signaturePayload.permissionGrantId);await ef.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:r})}else throw new ie(ne.ProtocolsQueryUnauthorized,"The ProtocolsQuery failed authorization")}}});var Xx,o9=F(()=>{"use strict";g();No();xt();Uo();Yx();Di();lr();Xx=class{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await xa.parse(r)}catch(s){return wt(s,400)}try{await pn(r.authorization,this.deps.didResolver),await n.authorize(e,this.deps.messageStore)}catch(s){if(s.code===ne.AuthenticateJwsMissing||s.code===ne.ProtocolsQueryUnauthorized||s.code===ne.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch){let o=await this.fetchPublishedProtocolsConfigure(e,n);return{status:{code:200,detail:"OK"},entries:o}}else return wt(s,401)}let i={...r.descriptor.filter,interface:be.Protocols,method:ge.Configure,isLatestBaseState:!0};tr(i);let{messages:a}=await this.deps.messageStore.query(e,[i]);return{status:{code:200,detail:"OK"},entries:a}}async fetchPublishedProtocolsConfigure(e,r){let n={...r.message.descriptor.filter,interface:be.Protocols,method:ge.Configure,published:!0,isLatestBaseState:!0},{messages:i}=await this.deps.messageStore.query(e,[n]);return i}}});async function fv(t,e,r,n,i,a,s,o){let d=e.signaturePayload?.protocolRole;if(d===void 0)return;let l=r,c=d;if(tf(d)){let p=zs(d);if(p===void 0)throw new ie(ne.ProtocolAuthorizationNotARole,`Cross-protocol role '${d}' could not be parsed as a valid 'alias:path' format.`);if(i.uses===void 0||i.uses[p.alias]===void 0)throw new ie(ne.ProtocolAuthorizationNotARole,`Cross-protocol role alias '${p.alias}' in '${d}' does not exist in the protocol's 'uses' map.`);l=i.uses[p.alias],c=p.protocolPath;let m=await s(t,l,a,o),y=yd(c,m.structure);if(y===void 0||!y.$role)throw new ie(ne.ProtocolAuthorizationNotARole,`Cross-protocol role path ${d} does not match role record type.`)}else{let p=yd(d,i.structure);if(p===void 0||!p.$role)throw new ie(ne.ProtocolAuthorizationNotARole,`Protocol path ${d} does not match role record type.`)}let u={interface:be.Records,method:ge.Write,protocol:l,protocolPath:c,recipient:e.author,isLatestBaseState:!0},f=c.split("/").length-1;if(n===void 0&&f>0)throw new ie(ne.ProtocolAuthorizationMissingContextId,"Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=ir.constructPrefixFilterAsRangeFilter(m);u.contextId=y}let{messages:h}=await a.query(t,[u]);if(h.length===0)throw new ie(ne.ProtocolAuthorizationMatchingRoleRecordNotFound,`No matching role record found for protocol path ${c}`)}async function Uce(t,e,r){switch(e.message.descriptor.method){case ge.Delete:let n=e,i=n.message.descriptor.recordId,a=await At.fetchInitialRecordsWrite(r,t,i);if(a===void 0)return[];let s=[];return n.message.descriptor.prune?(s.push(Pr.CoPrune),e.author===a.author&&s.push(Pr.Prune)):(s.push(Pr.CoDelete),e.author===a.author&&s.push(Pr.Delete)),s;case ge.Count:return[Pr.Read];case ge.Query:return[Pr.Read];case ge.Read:return[Pr.Read];case ge.Subscribe:return[Pr.Read];case ge.Write:let d=e;if(await d.isInitialWrite())return d.message.descriptor.squash===!0?[Pr.Squash,Pr.Create]:[Pr.Create];{let l=e.message.recordId,c=await At.fetchInitialRecordsWrite(r,t,l);return c===void 0?[]:e.author===c.author?[Pr.CoUpdate,Pr.Update]:[Pr.CoUpdate]}}return[]}async function pv(t,e,r,n,i,a){let s=e.message.descriptor.method,o=await Uce(t,e,i),d=e.author,l=r.$actions;if(l===void 0)throw new ie(ne.ProtocolAuthorizationActionRulesNotFound,`no action rule defined for Records${s}, ${d} is unauthorized`);let c=e.signaturePayload?.protocolRole;for(let u of l){if(!u.can.some(p=>o.includes(p)))continue;if(u.who===kc.Anyone)return;if(d===void 0)continue;if(c!==void 0){if(u.role===c)return;continue}if(u.who===kc.Recipient&&u.of===void 0){let p;if(e.message.descriptor.method===ge.Write?p=e.message:p=n[n.length-1],p.descriptor.recipient===d)return;continue}if(await Lce(d,u,n,a))return}throw new ie(ne.ProtocolAuthorizationActionNotAllowed,`Inbound message action Records${s} by author ${e.author} not allowed.`)}async function Lce(t,e,r,n){let i=e.of;if(i===void 0)return!1;let a;if(tf(i)&&n?.uses!==void 0){let s=zs(i);if(s!==void 0){let o=n.uses[s.alias];o!==void 0&&(a=r.find(d=>d.descriptor.protocol===o&&d.descriptor.protocolPath===s.protocolPath))}}else a=r.find(s=>s.descriptor.protocolPath===i);if(a===void 0)return!1;if(e.who===kc.Recipient)return t===a.descriptor.recipient;{let s=(await At.parse(a)).author;return t===s}}var a9=F(()=>{"use strict";g();lc();Us();xt();lr();Yp();Tg()});async function _y(t,e,r){let n={interface:be.Records,method:ge.Write,recordId:e},{messages:i}=await r.query(t,[n]);return i.length===0?void 0:await At.getInitialWrite(i)}async function hv(t,e,r){if(e===void 0)return[];let n=[],i=e;for(;i!==void 0;){let a=await _y(t,i,r);if(a===void 0)throw new ie(ne.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 DR(t,e,r){let n=await _y(t,e.message.recordId,r);if(n!==void 0)return n.descriptor.messageTimestamp}var c9=F(()=>{"use strict";g();Us();xt();lr()});async function l9(t,e,r,n,i){let a=e.message.descriptor.protocolPath,s=Wx(a),o=e.message.descriptor.parentId;if(o===void 0){if(a!==s)throw new ie(ne.ProtocolAuthorizationParentlessIncorrectProtocolPath,`Declared protocol path '${a}' is not valid for records with no parent'.`);return}let d=e.message.descriptor.protocol,l=await qce(t,d,a,r,n,i),c={isLatestBaseState:!0,interface:be.Records,method:ge.Write,protocol:l,recordId:o},{messages:u}=await r.query(t,[c]),f=u[0];if(f===void 0)throw l!==d?new ie(ne.ProtocolAuthorizationCrossProtocolParentNotFound,`Could not find parent record '${o}' in protocol '${l}' for cross-protocol child at path '${a}'.`):new ie(ne.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${a}'.`);if(`${f.descriptor.protocolPath}/${s}`!==a)throw new ie(ne.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 ie(ne.ProtocolAuthorizationIncorrectContextId,`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function qce(t,e,r,n,i,a){let s=r.split("/");if(s.length<=1)return e;let o=await i(t,e,n,a),d=o.structure[s[0]];if(d?.$ref!==void 0){let l=zs(d.$ref);if(l!==void 0&&o.uses!==void 0){let c=o.uses[l.alias];if(c!==void 0)return s.length===2?c:e}}return e}async function u9(t,e,r,n,i,a){let s=e.descriptor.protocolPath,o=Wx(s),d=await zce(t,s,r,n,i,a);Fce(e,d,o)}async function zce(t,e,r,n,i,a){let s=e.split("/"),o=r.structure[s[0]];if(o?.$ref!==void 0&&s.length===1){let d=zs(o.$ref);if(d!==void 0&&r.uses!==void 0){let l=r.uses[d.alias];if(l!==void 0)return(await i(t,l,n,a)).types}}return r.types}function Fce(t,e,r){let n=r??Wx(t.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new ie(ne.ProtocolAuthorizationInvalidType,`record with type ${n} not allowed in protocol`);let a=e[n],{schema:s}=t.descriptor;if(a.schema!==void 0&&a.schema!==s)throw new ie(ne.ProtocolAuthorizationInvalidSchema,`type '${n}' must have schema '${a.schema}', instead has '${s}'`);let{dataFormat:o}=t.descriptor;if(a.dataFormats!==void 0&&!a.dataFormats.includes(o))throw new ie(ne.ProtocolAuthorizationIncorrectDataFormat,`type '${n}' must have data format in (${a.dataFormats}), instead has '${o}'`);if(a.encryptionRequired===!0&&t.encryption===void 0)throw new ie(ne.ProtocolAuthorizationEncryptionRequired,`type '${n}' requires encryption but message has no encryption metadata`)}function f9(t,e){let{min:r=0,max:n}=e.$size||{},i=t.message.descriptor.dataSize;if(i<r)throw new ie(ne.ProtocolAuthorizationMinSizeInvalid,`data size ${i} is less than allowed ${r}`);if(n!==void 0&&i>n)throw new ie(ne.ProtocolAuthorizationMaxSizeInvalid,`data size ${i} is more than allowed ${n}`)}function p9(t,e){if(e.$tags!==void 0){let{tags:r={},protocol:n,protocolPath:i}=t.message.descriptor,{$allowUndefinedTags:a,$requiredTags:s,...o}=e.$tags,d=a||!1,l=s||[],c=new d9.default.default,u=c.compile({type:"object",properties:o,required:l,additionalProperties:d});if(!u(r)){let h=c.errorsText(u.errors,{dataVar:`${n}/${i}/$tags`});throw new ie(ne.ProtocolAuthorizationTagsInvalidSchema,`tags schema validation error: ${h}`)}}}async function h9(t,e,r,n){if(!r.$role)return;let i=e,a=i.message.descriptor.recipient;if(a===void 0)throw new ie(ne.ProtocolAuthorizationRoleMissingRecipient,"Role records must have a recipient");let s=i.message.descriptor.protocolPath,o={interface:be.Records,method:ge.Write,isLatestBaseState:!0,protocol:i.message.descriptor.protocol,protocolPath:s,recipient:a},d=Te.getParentContextFromOfContextId(i.message.contextId);if(d!==""){let f=ir.constructPrefixFilterAsRangeFilter(d);o.contextId=f}let{messages:l}=await n.query(t,[o]);if(l.filter(f=>f.recordId!==i.message.recordId).length>0)throw new ie(ne.ProtocolAuthorizationDuplicateRoleRecipient,`DID '${a}' is already recipient of a role record at protocol path '${s} under the parent context ${d}.`)}async function m9(t,e,r,n){if(r.$recordLimit===void 0||!await e.isInitialWrite())return;let{max:a,strategy:s}=r.$recordLimit,o=e.message.descriptor.protocolPath,d={interface:be.Records,method:ge.Write,isLatestBaseState:!0,protocol:e.message.descriptor.protocol,protocolPath:o},l=Te.getParentContextFromOfContextId(e.message.contextId);if(l!==""){let u=ir.constructPrefixFilterAsRangeFilter(l);d.contextId=u}if(await n.count(t,[d])>=a)throw s===Hl.Reject?new ie(ne.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 ie(ne.ProtocolAuthorizationRecordLimitStrategyNotImplemented,`record limit strategy '${s}' is not yet implemented.`)}async function y9(t,e){if(t.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new ie(ne.ProtocolAuthorizationSquashNotEnabled,`squash writes are not enabled at protocol path '${t.message.descriptor.protocolPath}': rule set must have $squash: true.`);if(!await t.isInitialWrite())throw new ie(ne.ProtocolAuthorizationSquashNotInitialWrite,"squash write must be an initial write (a new record): updates cannot be squash writes.")}async function g9(t,e){if(!(e.$immutable!==!0||await t.isInitialWrite()))throw new ie(ne.ProtocolAuthorizationImmutableRecord,`record at protocol path '${t.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var d9,w9=F(()=>{"use strict";g();Tg();d9=An(IR(),1);lc();Jn();xt();lr();Yp()});var ys,Xp=F(()=>{"use strict";g();Yp();Vc();xt();lr();a9();c9();w9();ys=class t{static async validateReferentialIntegrity(e,r,n,i){let a=await DR(e,r,n),s=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,a,i),o=t.createBoundFetchDefinition(i);await u9(e,r.message,s,n,o,a),await l9(e,r,n,o,a);let d=t.getRuleSet(r.message.descriptor.protocolPath,s);await h9(e,r,d,n),f9(r,d),p9(r,d),await g9(r,d),await y9(r,d),await m9(e,r,d,n)}static async authorizeWrite(e,r,n,i){let a=await _y(e,r.message.recordId,n),s;a===void 0?s=await hv(e,r.message.descriptor.parentId,n):s=await hv(e,r.message.recordId,n);let o=await DR(e,r,n),d=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,o,i),l=t.getRuleSet(r.message.descriptor.protocolPath,d),c=t.createBoundFetchDefinition(i);await fv(e,r,r.message.descriptor.protocol,r.message.contextId,d,n,c,o),await pv(e,r,l,s,n,d)}static async authorizeRead(e,r,n,i,a){let s=await hv(e,n.message.recordId,i),o=await _y(e,n.message.recordId,i),d=o!==void 0?o.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,l=await t.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,d,a),c=t.getRuleSet(n.message.descriptor.protocolPath,l),u=t.createBoundFetchDefinition(a);await fv(e,r,n.message.descriptor.protocol,n.message.contextId,l,i,u,d),await pv(e,r,c,s,i,l)}static async authorizeQueryOrSubscribe(e,r,n,i){let{protocol:a,protocolPath:s,contextId:o}=r.message.descriptor.filter,d=await t.fetchProtocolDefinition(e,a,n,void 0,i),l=t.getRuleSet(s,d),c=t.createBoundFetchDefinition(i);await fv(e,r,a,o,d,n,c),await pv(e,r,l,[],n,d)}static async authorizeDelete(e,r,n,i,a){let s=await hv(e,r.message.descriptor.recordId,i),o=await _y(e,r.message.descriptor.recordId,i),d=o!==void 0?o.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,l=await t.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,d,a),c=t.getRuleSet(n.message.descriptor.protocolPath,l),u=t.createBoundFetchDefinition(a);await fv(e,r,n.message.descriptor.protocol,n.message.contextId,l,i,u,d),await pv(e,r,c,s,i,l)}static async fetchProtocolDefinition(e,r,n,i,a){if(a!==void 0){let l=a.getDefinition(r);if(l!==void 0)return l}let s={interface:be.Protocols,method:ge.Configure,protocol:r};i!==void 0?s.messageTimestamp={lte:i}:s.isLatestBaseState=!0;let{messages:o}=await n.query(e,[s],{messageTimestamp:It.Descending},{limit:1});if(o.length===0)throw new ie(ne.ProtocolAuthorizationProtocolNotFound,`unable to find protocol definition for ${r}`);return o[0].descriptor.definition}static createBoundFetchDefinition(e){return(r,n,i,a)=>t.fetchProtocolDefinition(r,n,i,a,e)}static getRuleSet(e,r){let n=yd(e,r.structure);if(n===void 0)throw new ie(ne.ProtocolAuthorizationMissingRuleSet,`No rule set defined for protocolPath ${e}`);return n}}});var Qx,v9=F(()=>{"use strict";g();No();wr();Uo();Xp();Jn();nx();lr();Qx=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await ad.parse(r)}catch(a){return wt(a,400)}let i;if(Te.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)i=await this.countPublishedRecords(e,n);else{try{await pn(r.authorization,this.deps.didResolver),await t.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(a){return wt(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,r){let{filter:n}=r.message.descriptor,i={...Te.convertFilter(n),interface:be.Records,method:ge.Write,isLatestBaseState:!0};return this.deps.messageStore.count(e,[i])}async countRecordsAsNonOwner(e,r){let{filter:n}=r.message.descriptor,i=[];return Te.filterIncludesPublishedRecords(n)&&i.push(t.buildPublishedRecordsFilter(r)),Te.filterIncludesUnpublishedRecords(n)&&(Te.shouldBuildUnpublishedAuthorFilter(n,r.author)&&i.push(t.buildUnpublishedRecordsByCountAuthorFilter(r)),Te.shouldProtocolAuthorize(r.signaturePayload)&&i.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),Te.shouldBuildUnpublishedRecipientFilter(n,r.author)&&i.push(t.buildUnpublishedRecordsForCountAuthorFilter(r))),this.deps.messageStore.count(e,i)}async countPublishedRecords(e,r){let n=t.buildPublishedRecordsFilter(r);return this.deps.messageStore.count(e,[n])}static buildPublishedRecordsFilter(e){let{filter:r}=e.message.descriptor;return{...Te.convertFilter(r),interface:be.Records,method:ge.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{...Te.convertFilter(r),interface:be.Records,method:ge.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:r}=e.message.descriptor;return{...Te.convertFilter(r),interface:be.Records,method:ge.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{...Te.convertFilter(r),author:e.author,interface:be.Records,method:ge.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,r,n,i){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),Te.shouldProtocolAuthorize(r.signaturePayload)&&await ys.authorizeQueryOrSubscribe(e,r,n,i)}}});var Ea,mv=F(()=>{"use strict";g();mc();wr();nc();Jn();Jc();Di();us();lr();Ea=class t extends $n{static async parse(e){let r;return e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Te.validateDelegatedGrantReferentialIntegrity(e,r),St.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r=e.recordId,n=St.getCurrentTimestamp(),i={interface:be.Records,method:ge.Delete,messageTimestamp:e.messageTimestamp??n,recordId:r,prune:e.prune??!1},a=await we.createAuthorization({descriptor:i,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),s={descriptor:i,authorization:a};return we.validateJsonSchema(s),new t(s)}constructIndexes(e){let n={...this.message.descriptor},{protocol:i,protocolPath:a,recipient:s,schema:o,parentId:d,dateCreated:l}=e.descriptor,c={isLatestBaseState:!0,protocol:i,protocolPath:a,recipient:s,schema:o,parentId:d,dateCreated:l,contextId:e.contextId,author:this.author,...n};return tr(c),c}async authorizeDelegate(e,r){let n=Ir.parse(this.message.authorization.authorDelegatedGrant);await jn.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}}});var rf,e2,t2=F(()=>{"use strict";g();(function(t){t.RecordsDelete="RecordsDelete",t.RecordsSquash="RecordsSquash"})(rf||(rf={}));e2=class t{resumableTaskStore;static timeoutExtensionFrequencyInSeconds=30;resumableTaskBatchSize=100;resumableTaskHandlers;constructor(e,r){this.resumableTaskStore=e,this.resumableTaskHandlers={[rf.RecordsDelete]:async n=>await r.performRecordsDelete(n),[rf.RecordsSquash]:async n=>await r.performRecordsSquash(n)}}async run(e){let r=t.timeoutExtensionFrequencyInSeconds*2,n=await this.resumableTaskStore.register(e,r);await this.runWithAutomaticTimeoutExtension(n)}async runWithAutomaticTimeoutExtension(e){let r=t.timeoutExtensionFrequencyInSeconds*2,n;try{n=setInterval(()=>{this.resumableTaskStore.extend(e.id,r)},t.timeoutExtensionFrequencyInSeconds*1e3);let i=this.resumableTaskHandlers[e.task.name];await i(e.task.data),await this.resumableTaskStore.delete(e.id)}finally{t.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 r=e;for(;r.length>0;){let n=r;r=[];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),r.push(i)}}}}});var r2,b9=F(()=>{"use strict";g();No();lr();wr();Uo();Lo();Xp();Jn();mv();Jc();Us();t2();r2=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Ea.parse(r)}catch(l){return wt(l,400)}try{await pn(r.authorization,this.deps.didResolver)}catch(l){return wt(l,401)}let i={interface:be.Records,recordId:r.descriptor.recordId},{messages:a}=await this.deps.messageStore.query(e,[i]),s=await we.getNewestMessage(a);if(!Te.canPerformDeleteAgainstRecord(r,s))return{status:{code:404,detail:"Not Found"}};if(!await we.isNewer(r,s))return{status:{code:409,detail:"Conflict"}};try{let l=await At.fetchInitialRecordsWrite(this.deps.messageStore,e,r.descriptor.recordId);await t.authorizeRecordsDelete(e,n,l,this.deps.messageStore,this.deps.coreProtocols)}catch(l){return wt(l,401)}return await this.deps.resumableTaskManager.run({name:rf.RecordsDelete,data:{tenant:e,message:r}}),{status:{code:202,detail:"Accepted"}}}static async authorizeRecordsDelete(e,r,n,i,a){if(we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n.message,i),r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await dt.fetchGrant(e,i,r.signaturePayload.permissionGrantId);await jn.authorizeDelete({recordsDeleteMessage:r.message,recordsWriteToDelete:n.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:i})}else await ys.authorizeDelete(e,r,n,i,a)}}});var n2,P9=F(()=>{"use strict";g();No();hp();wr();Uo();Xp();Jn();ix();Us();Vc();lr();n2=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await ha.parse(r)}catch(s){return wt(s,400)}let i,a;if(Te.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 pn(r.authorization,this.deps.didResolver),await t.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(s){return wt(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 At.isInitialWrite(s)){let d=(await this.deps.messageStore.query(e,[{recordId:s.recordId,isLatestBaseState:!1,method:ge.Write}])).messages[0];delete d.encodedData,s.initialWrite=d}return{status:{code:200,detail:"OK"},entries:i,cursor:a}}convertDateSort(e){switch(e){case Kt.CreatedAscending:return{dateCreated:It.Ascending};case Kt.CreatedDescending:return{dateCreated:It.Descending};case Kt.PublishedAscending:return{datePublished:It.Ascending};case Kt.PublishedDescending:return{datePublished:It.Descending};case Kt.UpdatedAscending:return{messageTimestamp:It.Ascending};case Kt.UpdatedDescending:return{messageTimestamp:It.Descending};default:return{dateCreated:It.Ascending}}}async fetchRecordsAsOwner(e,r){let{dateSort:n,filter:i,pagination:a}=r.message.descriptor,s={...Te.convertFilter(i,n),interface:be.Records,method:ge.Write,isLatestBaseState:!0},o=this.convertDateSort(n);return this.deps.messageStore.query(e,[s],o,a)}async fetchRecordsAsNonOwner(e,r){let{dateSort:n,pagination:i,filter:a}=r.message.descriptor,s=[];Te.filterIncludesPublishedRecords(a)&&s.push(t.buildPublishedRecordsFilter(r)),Te.filterIncludesUnpublishedRecords(a)&&(Te.shouldBuildUnpublishedAuthorFilter(a,r.author)&&s.push(t.buildUnpublishedRecordsByQueryAuthorFilter(r)),Te.shouldProtocolAuthorize(r.signaturePayload)&&s.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),Te.shouldBuildUnpublishedRecipientFilter(a,r.author)&&s.push(t.buildUnpublishedRecordsForQueryAuthorFilter(r)));let o=this.convertDateSort(n);return this.deps.messageStore.query(e,s,o,i)}async fetchPublishedRecords(e,r){let{dateSort:n,pagination:i}=r.message.descriptor,a=t.buildPublishedRecordsFilter(r),s=this.convertDateSort(n);return this.deps.messageStore.query(e,[a],s,i)}static buildPublishedRecordsFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...Te.convertFilter(n,r),interface:be.Records,method:ge.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...Te.convertFilter(n,r),interface:be.Records,method:ge.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...Te.convertFilter(n,r),interface:be.Records,method:ge.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...Te.convertFilter(n,r),author:e.author,interface:be.Records,method:ge.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,r,n,i){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),Te.shouldProtocolAuthorize(r.signaturePayload)&&await ys.authorizeQueryOrSubscribe(e,r,n,i)}}});var gd,RR=F(()=>{"use strict";g();mc();hp();wr();nc();Jn();Jc();Di();us();xt();lr();gd=class t extends $n{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort===Kt.PublishedAscending||e.descriptor.dateSort===Kt.PublishedDescending))throw new ie(ne.RecordsReadParseFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let r;return e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Te.validateDelegatedGrantReferentialIntegrity(e,r),St.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let{filter:r,signer:n,permissionGrantId:i,protocolRole:a,dateSort:s}=e,o=St.getCurrentTimestamp();if(e.filter.published===!1&&(s===Kt.PublishedAscending||s===Kt.PublishedDescending))throw new ie(ne.RecordsReadCreateFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${s}`);let d={interface:be.Records,method:ge.Read,filter:Te.normalizeFilter(r),messageTimestamp:e.messageTimestamp??o,permissionGrantId:i,dateSort:s};tr(d);let l;n!==void 0&&(l=await we.createAuthorization({descriptor:d,signer:n,permissionGrantId:i,protocolRole:a,delegatedGrant:e.delegatedGrant}));let c={descriptor:d,authorization:l};return we.validateJsonSchema(c),new t(c)}async authorizeDelegate(e,r){let n=Ir.parse(this.message.authorization.authorDelegatedGrant);await jn.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}}});var i2,x9=F(()=>{"use strict";g();No();hu();kn();wr();Uo();Lo();Xp();Jn();Jc();RR();Us();xt();lr();i2=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await gd.parse(r)}catch(u){return wt(u,400)}try{n.author!==void 0&&await pn(r.authorization,this.deps.didResolver)}catch(u){return wt(u,401)}let i={interface:be.Records,isLatestBaseState:!0,...Te.convertFilter(r.descriptor.filter)},a=Te.convertDateSort(r.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===ge.Delete){let u=o,f=u.descriptor.recordId,h=await At.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(h===void 0)return wt(new ie(ne.RecordsReadInitialWriteNotFound,"initial write for deleted record not found"),400);let p;try{p=await At.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{p=h}let m=await At.parse(p);try{await t.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return wt(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:u,initialWrite:h}}}let d=o;try{let u=await At.parse(d);await t.authorizeRecordsRead(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return wt(u,401)}let l;if(d.encodedData!==void 0){let u=De.base64UrlToBytes(d.encodedData);l=Yt.fromBytes(u),delete d.encodedData}else{let u=await this.deps.dataStore.get(e,d.recordId,d.descriptor.dataCid);if(u?.dataStream===void 0)return{status:{code:410,detail:"Record data not available"},entry:{recordsWrite:d}};l=u.dataStream}let c={status:{code:200,detail:"OK"},entry:{recordsWrite:d,data:l}};if(!await At.isInitialWrite(d)){let f=(await this.deps.messageStore.query(e,[{recordId:d.recordId,isLatestBaseState:!1,method:ge.Write}])).messages[0];delete f.encodedData,c.entry.initialWrite=f}return c}static async authorizeRecordsRead(e,r,n,i,a){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n.message,i);let{descriptor:s}=n.message;if(r.author!==e){if(s.published===!0)return;if(r.author!==void 0&&(r.author===s.recipient||r.author===n.author))return;if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let o=await dt.fetchGrant(e,i,r.signaturePayload.permissionGrantId);await jn.authorizeRead({recordsReadMessage:r.message,recordsWriteMessageToBeRead:n.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:o,messageStore:i})}else await ys.authorizeRead(e,r,n,i,a)}}}});var Sa,s2=F(()=>{"use strict";g();mc();wr();nc();Jn();Jc();Di();us();xt();lr();ua();Sa=class t extends $n{static async parse(e){let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Te.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ie(ne.RecordsSubscribeFilterMissingRequiredProperties,"Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&si(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Wc(e.descriptor.filter.schema),St.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:be.Records,method:ge.Subscribe,messageTimestamp:e.messageTimestamp??St.getCurrentTimestamp(),filter:Te.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};tr(r);let n=e.signer,i;n&&(i=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:i};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Ir.parse(this.message.authorization.authorDelegatedGrant);await jn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}}});var o2,E9=F(()=>{"use strict";g();No();hp();wr();Uo();Xp();Jn();s2();Us();Vc();xt();lr();o2=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return wt(new ie(ne.RecordsSubscribeEventLogUnimplemented,"Subscriptions are not supported"),501);let i;try{i=await Sa.parse(r)}catch(f){return wt(f,400)}let a=[],s=[];if(Te.filterIncludesPublishedRecords(i.message.descriptor.filter)&&i.author===void 0)a=[t.buildPublishedEventFilter(i)],s=[t.buildPublishedQueryFilter(i)],delete r.authorization;else{try{await pn(r.authorization,this.deps.didResolver),await t.authorizeRecordsSubscribe(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return wt(f,401)}i.author===e?(a=t.buildOwnerEventFilters(i),s=t.buildOwnerQueryFilters(i)):(a=t.buildNonOwnerEventFilters(i),s=t.buildNonOwnerQueryFilters(i))}let o=await we.getCid(r),{cursor:d}=i.message.descriptor;if(d!==void 0)try{let f=await this.deps.eventLog.subscribe(e,o,n,{cursor:d,filters:a});return{status:{code:200,detail:"OK"},subscription:f}}catch(f){return wt(f,500)}let l=await this.deps.eventLog.subscribe(e,o,n,{filters:a}),c,u;try{let{dateSort:f,pagination:h}=i.message.descriptor,p=t.convertDateSort(f),m=await this.deps.messageStore.query(e,s,p,h);c=m.messages,u=m.cursor;for(let y of c)if(!await At.isInitialWrite(y)){let w=(await this.deps.messageStore.query(e,[{recordId:y.recordId,isLatestBaseState:!1,method:ge.Write}])).messages[0];delete w.encodedData,y.initialWrite=w}}catch(f){return await l.close(),wt(f,500)}return{status:{code:200,detail:"OK"},subscription:l,entries:c,cursor:u}}static convertDateSort(e){switch(e){case Kt.CreatedAscending:return{dateCreated:It.Ascending};case Kt.CreatedDescending:return{dateCreated:It.Descending};case Kt.PublishedAscending:return{datePublished:It.Ascending};case Kt.PublishedDescending:return{datePublished:It.Descending};case Kt.UpdatedAscending:return{messageTimestamp:It.Ascending};case Kt.UpdatedDescending:return{messageTimestamp:It.Descending};default:return{dateCreated:It.Ascending}}}static buildOwnerEventFilters(e){let{filter:r}=e.message.descriptor;return[{...Te.convertFilter(r),interface:be.Records,method:[ge.Write,ge.Delete]}]}static buildNonOwnerEventFilters(e){let r=[],{filter:n}=e.message.descriptor;return Te.filterIncludesPublishedRecords(n)&&r.push(t.buildPublishedEventFilter(e)),Te.filterIncludesUnpublishedRecords(n)&&(Te.shouldBuildUnpublishedAuthorFilter(n,e.author)&&r.push({...Te.convertFilter(n),author:e.author,interface:be.Records,method:[ge.Write,ge.Delete],published:!1}),Te.shouldProtocolAuthorize(e.signaturePayload)&&r.push({...Te.convertFilter(n),interface:be.Records,method:[ge.Write,ge.Delete],published:!1}),Te.shouldBuildUnpublishedRecipientFilter(n,e.author)&&r.push({...Te.convertFilter(n),interface:be.Records,method:[ge.Write,ge.Delete],recipient:e.author,published:!1})),r}static buildPublishedEventFilter(e){return{...Te.convertFilter(e.message.descriptor.filter),interface:be.Records,method:[ge.Write,ge.Delete],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:r,filter:n}=e.message.descriptor;return[{...Te.convertFilter(n,r),interface:be.Records,method:ge.Write,isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let r=[],{dateSort:n,filter:i}=e.message.descriptor;return Te.filterIncludesPublishedRecords(i)&&r.push(t.buildPublishedQueryFilter(e)),Te.filterIncludesUnpublishedRecords(i)&&(Te.shouldBuildUnpublishedAuthorFilter(i,e.author)&&r.push({...Te.convertFilter(i,n),author:e.author,interface:be.Records,method:ge.Write,isLatestBaseState:!0,published:!1}),Te.shouldProtocolAuthorize(e.signaturePayload)&&r.push({...Te.convertFilter(i,n),interface:be.Records,method:ge.Write,isLatestBaseState:!0,published:!1}),Te.shouldBuildUnpublishedRecipientFilter(i,e.author)&&r.push({...Te.convertFilter(i,n),interface:be.Records,method:ge.Write,recipient:e.author,isLatestBaseState:!0,published:!1})),r}static buildPublishedQueryFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...Te.convertFilter(n,r),interface:be.Records,method:ge.Write,published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,r,n,i){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),Te.shouldProtocolAuthorize(r.signaturePayload)&&await ys.authorizeQueryOrSubscribe(e,r,n,i)}}});var Ty,CR=F(()=>{"use strict";g();B0();lc();wr();Jn();mv();Us();lr();Ty=class t{messageStore;dataStore;stateIndex;eventLog;constructor({messageStore:e,dataStore:r,stateIndex:n,eventLog:i}){this.messageStore=e,this.dataStore=r,this.stateIndex=n,this.eventLog=i}async performRecordsDelete({tenant:e,message:r}){let n={interface:be.Records,recordId:r.descriptor.recordId},{messages:i}=await this.messageStore.query(e,[n]),a=await we.getNewestMessage(i);if(!Te.canPerformDeleteAgainstRecord(r,a))return;let s=await Ea.parse(r),o=await At.getInitialWrite(i),d=s.constructIndexes(o),l=await we.getCid(r);await this.messageStore.put(e,r,d),await this.stateIndex.insert(e,l,d),this.eventLog!==void 0&&await this.eventLog.emit(e,{message:r,initialWrite:o},d),r.descriptor.prune&&await t.purgeRecordDescendants(e,r.descriptor.recordId,this.messageStore,this.dataStore,this.stateIndex),await t.deleteAllOlderMessagesButKeepInitialWrite(e,i,r,this.messageStore,this.dataStore,this.stateIndex)}async performRecordsSquash({tenant:e,message:r}){let{protocol:n,protocolPath:i,messageTimestamp:a}=r.descriptor,s={interface:be.Records,protocol:n,protocolPath:i},o=Te.getParentContextFromOfContextId(r.contextId);if(o!==void 0&&o!==""){let c=ir.constructPrefixFilterAsRangeFilter(o);s.contextId=c}let{messages:d}=await this.messageStore.query(e,[s]),l=new Map;for(let c of d){let u;Te.isRecordsWrite(c)?u=c.recordId:u=c.descriptor.recordId;let f=l.get(u);f!==void 0?f.push(c):l.set(u,[c])}for(let[c,u]of l){if(c===r.recordId)continue;let f=await we.getNewestMessage(u);if(f===void 0)continue;f.descriptor.messageTimestamp<a&&await t.purgeRecordMessages(e,u,this.messageStore,this.dataStore,this.stateIndex)}}static async deleteFromDataStoreIfNeeded(e,r,n,i){if(n.descriptor.method!==ge.Write)return;let a=n;a.descriptor.dataSize<=ma.maxDataSizeAllowedToBeEncoded||a.descriptor.dataCid!==i.descriptor.dataCid&&await e.delete(r,a.recordId,a.descriptor.dataCid)}static async purgeRecordDescendants(e,r,n,i,a){let s={interface:be.Records,parentId:r},{messages:o}=await n.query(e,[s]),d=new Map;for(let l of o){let c;Te.isRecordsWrite(l)?c=l.recordId:c=l.descriptor.recordId;let u=d.get(c);u?u.push(l):d.set(c,[l])}for(let l of d.keys())await t.purgeRecordDescendants(e,l,n,i,a);for(let l of d.keys())await t.purgeRecordMessages(e,d.get(l),n,i,a)}static async purgeRecordMessages(e,r,n,i,a){let s=r.filter(l=>l.descriptor.method===ge.Write),o=await we.getNewestMessage(s);await i.delete(e,o.recordId,o.descriptor.dataCid);let d=await Promise.all(r.map(l=>we.getCid(l)));await a.delete(e,d),await Promise.all(d.map(l=>n.delete(e,l)))}static async deleteAllOlderMessagesButKeepInitialWrite(e,r,n,i,a,s){let o=[];for(let d of r){if(await we.isOlder(d,n)){await t.deleteFromDataStoreIfNeeded(a,e,d,n);let c=await we.getCid(d);if(await i.delete(e,c),await At.isInitialWrite(d)){let p=await(await At.parse(d)).constructIndexes(!1),m=d;delete m.encodedData,await i.put(e,m,p)}else{let f=await we.getCid(d);o.push(f)}}await s.delete(e,o)}}}});var a2,S9=F(()=>{"use strict";g();No();il();hu();B0();kn();lc();wr();Uo();Lo();Xp();Jn();Jc();Us();t2();Vc();CR();xt();lr();a2=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r,dataStream:n}){let i;try{i=await At.parse(r),await ys.validateReferentialIntegrity(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(p){return wt(p,400)}try{await pn(r.authorization,this.deps.didResolver,r.attestation),await this.authorizeRecordsWrite(e,i,this.deps.messageStore)}catch(p){return wt(p,401)}let a={interface:be.Records,recordId:r.recordId},{messages:s}=await this.deps.messageStore.query(e,[a]),o=await i.isInitialWrite(),d;if(!o)try{d=await At.getInitialWrite(s),At.verifyEqualityOfImmutableProperties(d,r)}catch(p){return wt(p,400)}try{await this.enforceSquashBackstop(e,r)}catch(p){return wt(p,409)}let l=await we.getNewestMessage(s),c=!1,u;if(l===void 0||await we.isNewer(r,l)?(c=!0,u=r):u=l,!c)return{status:{code:409,detail:"Conflict"}};let f=r.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(r.descriptor.protocol):void 0;try{if(l?.descriptor.method===ge.Delete)throw new ie(ne.RecordsWriteNotAllowedAfterDelete,"RecordsWrite is not allowed after a RecordsDelete.");f?.preProcessWrite!==void 0&&await f.preProcessWrite(e,r,this.deps.messageStore);let p=!1,m=r;if(n!==void 0)m=await this.processMessageWithDataStream(e,r,n),p=!0;else if(!o){let b=l;m=await this.processMessageWithoutDataStream(e,r,b),p=!0}let y=await i.constructIndexes(p);await this.deps.messageStore.put(e,m,y),await this.deps.stateIndex.insert(e,await we.getCid(r),y),this.deps.eventLog!==void 0&&p&&await this.deps.eventLog.emit(e,{message:r,initialWrite:d},y)}catch(p){if(p instanceof ie&&(p.code===ne.RecordsWriteMissingEncodedDataInPrevious||p.code===ne.RecordsWriteMissingDataInPrevious||p.code===ne.RecordsWriteNotAllowedAfterDelete||p.code===ne.RecordsWriteDataCidMismatch||p.code===ne.RecordsWriteDataSizeMismatch||p.code.startsWith("SchemaValidator")||this.deps.coreProtocols?.mapErrorToStatusCode(p.code)!==void 0))return wt(p,400);throw p}let h={status:o&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await Ty.deleteAllOlderMessagesButKeepInitialWrite(e,s,u,this.deps.messageStore,this.deps.dataStore,this.deps.stateIndex),r.descriptor.squash===!0&&await this.deps.resumableTaskManager.run({name:rf.RecordsSquash,data:{tenant:e,message:r}}),f?.postProcessWrite!==void 0&&await f.postProcessWrite(e,i,{messageStore:this.deps.messageStore,dataStore:this.deps.dataStore,stateIndex:this.deps.stateIndex}),h}async cloneAndAddEncodedData(e,r){let n={...e};return n.encodedData=De.bytesToBase64Url(r),n}async processMessageWithDataStream(e,r,n){let i=r;if(r.descriptor.dataSize<=ma.maxDataSizeAllowedToBeEncoded){let a=await Yt.toBytes(n),s=await hr.computeDagPbCidFromBytes(a);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,s,a.length);let o=r.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(r.descriptor.protocol):void 0;o?.validateRecord!==void 0&&o.validateRecord(r,a),i=await this.cloneAndAddEncodedData(r,a)}else{let[a,s]=Yt.duplicateDataStream(n,2);try{let[o,d]=await Promise.all([hr.computeDagPbCidFromStream(a),this.deps.dataStore.put(e,r.recordId,r.descriptor.dataCid,s)]);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,o,d.dataSize)}catch(o){throw await this.deps.dataStore.delete(e,r.recordId,r.descriptor.dataCid),o}}return i}async processMessageWithoutDataStream(e,r,n){let i={...r},{dataCid:a,dataSize:s}=r.descriptor;if(t.validateDataIntegrity(a,s,n.descriptor.dataCid,n.descriptor.dataSize),s<=ma.maxDataSizeAllowedToBeEncoded)if(n.encodedData!==void 0)i.encodedData=n.encodedData;else throw new ie(ne.RecordsWriteMissingEncodedDataInPrevious,"No dataStream was provided and unable to get data from previous message");else if(await this.deps.dataStore.get(e,n.recordId,r.descriptor.dataCid)===void 0)throw new ie(ne.RecordsWriteMissingDataInPrevious,"No dataStream was provided and unable to get data from previous message");return i}static validateDataIntegrity(e,r,n,i){if(e!==n)throw new ie(ne.RecordsWriteDataCidMismatch,`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(r!==i)throw new ie(ne.RecordsWriteDataSizeMismatch,`actual data size ${i} bytes does not match dataSize in descriptor: ${r}`)}async enforceSquashBackstop(e,r){if(r.descriptor.protocol===void 0||r.descriptor.protocolPath===void 0)return;let n;try{n=await ys.fetchProtocolDefinition(e,r.descriptor.protocol,this.deps.messageStore,void 0,this.deps.coreProtocols)}catch(c){console.warn(`enforceSquashBackstop: failed to fetch protocol definition for '${r.descriptor.protocol}':`,c);return}let i=r.descriptor.protocolPath.split("/"),a=n.structure[i[0]];for(let c=1;c<i.length&&a!==void 0;c++)a=a[i[c]];if(a===void 0||a.$squash!==!0)return;let s={interface:be.Records,method:ge.Write,isLatestBaseState:!0,protocol:r.descriptor.protocol,protocolPath:r.descriptor.protocolPath,squash:!0},o=Te.getParentContextFromOfContextId(r.contextId);if(o!==void 0&&o!==""){let c=ir.constructPrefixFilterAsRangeFilter(o);s.contextId=c}let{messages:d}=await this.deps.messageStore.query(e,[s],{messageTimestamp:It.Descending},{limit:1});if(d.length===0)return;let l=d[0];if(r.descriptor.messageTimestamp<=l.descriptor.messageTimestamp)throw new ie(ne.ProtocolAuthorizationSquashBackstop,`incoming message timestamp '${r.descriptor.messageTimestamp}' is not newer than the most recent squash record timestamp '${l.descriptor.messageTimestamp}' at protocol path '${r.descriptor.protocolPath}'.`)}async authorizeRecordsWrite(e,r,n){if(r.owner!==void 0&&r.owner!==e)throw new ie(ne.RecordsWriteOwnerAndTenantMismatch,`Owner ${r.owner} must be the same as tenant ${e} when specified.`);if(r.isSignedByAuthorDelegate&&await r.authorizeAuthorDelegate(n),r.isSignedByOwnerDelegate&&await r.authorizeOwnerDelegate(n),r.owner===void 0){if(r.author===e)return;if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let i=await dt.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await jn.authorizeWrite({recordsWriteMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:i,messageStore:n})}else await ys.authorizeWrite(e,r,n,this.deps.coreProtocols)}}}});function bde(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var a=t.charAt(i),s=a.charCodeAt(0);if(r[s]!==255)throw new TypeError(a+" is ambiguous");r[s]=i}var o=t.length,d=t.charAt(0),l=Math.log(o)/Math.log(256),c=Math.log(256)/Math.log(o);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,y=0,b=0,w=p.length;b!==w&&p[b]===0;)b++,m++;for(var S=(w-b)*c+1>>>0,k=new Uint8Array(S);b!==w;){for(var T=p[b],D=0,K=S-1;(T!==0||D<y)&&K!==-1;K--,D++)T+=256*k[K]>>>0,k[K]=T%o>>>0,T=T/o>>>0;if(T!==0)throw new Error("Non-zero carry");y=D,b++}for(var C=S-y;C!==S&&k[C]===0;)C++;for(var G=d.repeat(m);C<S;++C)G+=t.charAt(k[C]);return G}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var y=0,b=0;p[m]===d;)y++,m++;for(var w=(p.length-m)*l+1>>>0,S=new Uint8Array(w);p[m];){var k=r[p.charCodeAt(m)];if(k===255)return;for(var T=0,D=w-1;(k!==0||T<b)&&D!==-1;D--,T++)k+=o*S[D]>>>0,S[D]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");b=T,m++}if(p[m]!==" "){for(var K=w-b;K!==w&&S[K]===0;)K++;for(var C=new Uint8Array(y+(w-K)),G=y;K!==w;)C[G++]=S[K++];return C}}}function h(p){var m=f(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:h}}function Rde(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function Cde(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function zR(t){let e=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[r,n]=e;return n}function i7(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Kde;)e[r++]=t&255|T9,t/=128;for(;t&Mde;)e[r++]=t&255|T9,t>>>=7;return e[r]=t|0,i7.bytes=r-n+1,e}function FR(t,n){var r=0,n=n||0,i=0,a=n,s,o=t.length;do{if(a>=o)throw FR.bytes=0,new RangeError("Could not decode varint");s=t[a++],r+=i<28?(s&I9)<<i:(s&I9)*Math.pow(2,i),i+=7}while(s>=Ude);return FR.bytes=a-n,r}function s7(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&s7(t[e])})}function kd(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function lh(t){if(!kd(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=dle[t[r]];return e}function c7(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function y6(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}function $9(t){if(t>=Tl._0&&t<=Tl._9)return t-Tl._0;if(t>=Tl._A&&t<=Tl._F)return t-(Tl._A-10);if(t>=Tl._a&&t<=Tl._f)return t-(Tl._a-10)}function Ly(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,r=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,a=0;i<r;i++,a+=2){let s=$9(t.charCodeAt(a)),o=$9(t.charCodeAt(a+1));if(s===void 0||o===void 0){let d=t[a]+t[a+1];throw new Error('hex string expected, got non-hex character "'+d+'" at index '+a)}n[i]=s*16+o}return n}function ah(t){return y6(lh(t))}function vf(t){if(!kd(t))throw new Error("Uint8Array expected");return y6(lh(Uint8Array.from(t).reverse()))}function _d(t,e){return Ly(t.toString(16).padStart(e*2,"0"))}function qy(t,e){return _d(t,e).reverse()}function lle(t){return Ly(c7(t))}function zn(t,e,r){let n;if(typeof e=="string")try{n=Ly(e)}catch(a){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${a}`)}else if(kd(e))n=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(`${t} expected ${r} bytes, got ${i}`);return n}function uh(...t){let e=0;for(let i=0;i<t.length;i++){let a=t[i];if(!kd(a))throw new Error("Uint8Array expected");e+=a.length}let r=new Uint8Array(e),n=0;for(let i=0;i<t.length;i++){let a=t[i];r.set(a,n),n+=a.length}return r}function ule(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function fle(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function ple(t){let e;for(e=0;t>a7;t>>=Y2,e+=1);return e}function hle(t,e){return t>>BigInt(e)&Y2}function d7(t,e,r){if(typeof t!="number"||t<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 r!="function")throw new Error("hmacFn must be a function");let n=$R(t),i=$R(t),a=0,s=()=>{n.fill(1),i.fill(0),a=0},o=(...c)=>r(i,n,...c),d=(c=$R())=>{i=o(B9([0]),c),n=o(),c.length!==0&&(i=o(B9([1]),c),n=o())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let c=0,u=[];for(;c<e;){n=o();let f=n.slice();u.push(f),c+=n.length}return uh(...u)};return(c,u)=>{s(),d(c);let f;for(;!(f=u(l()));)d();return s(),f}}function hh(t,e,r={}){let n=(i,a,s)=>{let o=yle[a];if(typeof o!="function")throw new Error(`Invalid validator "${a}", expected function`);let d=t[i];if(!(s&&d===void 0)&&!o(d,t))throw new Error(`Invalid param ${String(i)}=${d} (${typeof d}), expected ${a}`)};for(let[i,a]of Object.entries(e))n(i,a,!1);for(let[i,a]of Object.entries(r))n(i,a,!0);return t}function O9(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function gle(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function l7(t,...e){if(!gle(t))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function wle(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");O9(t.outputLen),O9(t.blockLen)}function K2(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function vle(t,e){l7(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}function u7(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function f7(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function w6(t){if(typeof t=="string"&&(t=f7(t)),!u7(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function p7(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!u7(i))throw new Error("Uint8Array expected");e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let a=t[n];r.set(a,i),i+=a.length}return r}function m7(t){let e=n=>t().update(w6(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function v6(t=32){if(BR&&typeof BR.getRandomValues=="function")return BR.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Ple(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),a=BigInt(4294967295),s=Number(r>>i&a),o=Number(r&a),d=n?4:0,l=n?0:4;t.setUint32(e+d,s,n),t.setUint32(e+l,o,n)}function Zr(t,e){let r=t%e;return r>=ui?r:e+r}function w7(t,e,r){if(r<=ui||e<ui)throw new Error("Expected power/modulo > 0");if(r===hn)return ui;let n=hn;for(;e>ui;)e&hn&&(n=n*t%r),t=t*t%r,e>>=hn;return n}function Pn(t,e,r){let n=t;for(;e-- >ui;)n*=n,n%=r;return n}function VR(t,e){if(t===ui||e<=ui)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Zr(t,e),n=e,i=ui,a=hn,s=hn,o=ui;for(;r!==ui;){let d=n/r,l=n%r,c=i-s*d,u=a-o*d;n=r,r=l,i=s,a=o,s=c,o=u}if(n!==hn)throw new Error("invert: does not exist");return Zr(i,e)}function Tle(t){let e=(t-hn)/rh,r,n,i;for(r=t-hn,n=0;r%rh===ui;r/=rh,n++);for(i=rh;i<t&&w7(i,e,t)!==t-hn;i++);if(n===1){let s=(t+hn)/HR;return function(o,d){let l=o.pow(d,s);if(!o.eql(o.sqr(l),d))throw new Error("Cannot find square root");return l}}let a=(r+hn)/rh;return function(s,o){if(s.pow(o,e)===s.neg(s.ONE))throw new Error("Cannot find square root");let d=n,l=s.pow(s.mul(s.ONE,i),r),c=s.pow(o,a),u=s.pow(o,r);for(;!s.eql(u,s.ONE);){if(s.eql(u,s.ZERO))return s.ZERO;let f=1;for(let p=s.sqr(u);f<d&&!s.eql(p,s.ONE);f++)p=s.sqr(p);let h=s.pow(l,hn<<BigInt(d-f-1));l=s.sqr(h),c=s.mul(c,h),u=s.mul(u,l),d=f}return c}}function Ile(t){if(t%HR===kle){let e=(t+hn)/HR;return function(r,n){let i=r.pow(n,e);if(!r.eql(r.sqr(i),n))throw new Error("Cannot find square root");return i}}if(t%M9===j9){let e=(t-j9)/M9;return function(r,n){let i=r.mul(n,rh),a=r.pow(i,e),s=r.mul(n,a),o=r.mul(r.mul(s,rh),a),d=r.mul(s,r.sub(o,r.ONE));if(!r.eql(r.sqr(d),n))throw new Error("Cannot find square root");return d}}return t%_le,Tle(t)}function Cle(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Rle.reduce((n,i)=>(n[i]="function",n),e);return hh(t,r)}function $le(t,e,r){if(r<ui)throw new Error("Expected power > 0");if(r===ui)return t.ONE;if(r===hn)return e;let n=t.ONE,i=e;for(;r>ui;)r&hn&&(n=t.mul(n,i)),i=t.sqr(i),r>>=hn;return n}function Ble(t,e){let r=new Array(e.length),n=e.reduce((a,s,o)=>t.is0(s)?a:(r[o]=a,t.mul(a,s)),t.ONE),i=t.inv(n);return e.reduceRight((a,s,o)=>t.is0(s)?a:(r[o]=t.mul(a,r[o]),t.mul(a,s)),i),r}function v7(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function b6(t,e,r=!1,n={}){if(t<=ui)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:i,nByteLength:a}=v7(t,e);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=Ile(t),o=Object.freeze({ORDER:t,BITS:i,BYTES:a,MASK:g6(i),ZERO:ui,ONE:hn,create:d=>Zr(d,t),isValid:d=>{if(typeof d!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof d}`);return ui<=d&&d<t},is0:d=>d===ui,isOdd:d=>(d&hn)===hn,neg:d=>Zr(-d,t),eql:(d,l)=>d===l,sqr:d=>Zr(d*d,t),add:(d,l)=>Zr(d+l,t),sub:(d,l)=>Zr(d-l,t),mul:(d,l)=>Zr(d*l,t),pow:(d,l)=>$le(o,d,l),div:(d,l)=>Zr(d*VR(l,t),t),sqrN:d=>d*d,addN:(d,l)=>d+l,subN:(d,l)=>d-l,mulN:(d,l)=>d*l,inv:d=>VR(d,t),sqrt:n.sqrt||(d=>s(o,d)),invertBatch:d=>Ble(o,d),cmov:(d,l,c)=>c?l:d,toBytes:d=>r?qy(d,a):_d(d,a),fromBytes:d=>{if(d.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${d.length}`);return r?vf(d):ah(d)}});return Object.freeze(o)}function Ole(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");let r=t.sqrt(e);return t.isOdd(r)?t.neg(r):r}function b7(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function P7(t){let e=b7(t);return e+Math.ceil(e/2)}function jle(t,e,r=!1){let n=t.length,i=b7(e),a=P7(e);if(n<16||n<a||n>1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);let s=r?ah(t):vf(t),o=Zr(s,e-hn)+hn;return r?qy(o,i):_d(o,i)}function x7(t,e){let r=(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:r,unsafeLadder(i,a){let s=t.ZERO,o=i;for(;a>Mle;)a&jR&&(s=s.add(o)),o=o.double(),a>>=jR;return s},precomputeWindow(i,a){let{windows:s,windowSize:o}=n(a),d=[],l=i,c=l;for(let u=0;u<s;u++){c=l,d.push(c);for(let f=1;f<o;f++)c=c.add(l),d.push(c);l=c.double()}return d},wNAF(i,a,s){let{windows:o,windowSize:d}=n(i),l=t.ZERO,c=t.BASE,u=BigInt(2**i-1),f=2**i,h=BigInt(i);for(let p=0;p<o;p++){let m=p*d,y=Number(s&u);s>>=h,y>d&&(y-=f,s+=jR);let b=m,w=m+Math.abs(y)-1,S=p%2!==0,k=y<0;y===0?c=c.add(r(S,a[b])):l=l.add(r(k,a[w]))}return{p:l,f:c}},wNAFCached(i,a,s,o){let d=i._WINDOW_SIZE||1,l=a.get(i);return l||(l=this.precomputeWindow(i,d),d!==1&&a.set(i,o(l))),this.wNAF(d,l,s)}}}function P6(t){return Cle(t.Fp),hh(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...v7(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Kle(t){let e=P6(t);hh(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}function Lle(t){let e=Kle(t),{Fp:r}=e,n=e.toBytes||((p,m,y)=>{let b=m.toAffine();return uh(Uint8Array.from([4]),r.toBytes(b.x),r.toBytes(b.y))}),i=e.fromBytes||(p=>{let m=p.subarray(1),y=r.fromBytes(m.subarray(0,r.BYTES)),b=r.fromBytes(m.subarray(r.BYTES,2*r.BYTES));return{x:y,y:b}});function a(p){let{a:m,b:y}=e,b=r.sqr(p),w=r.mul(b,p);return r.add(r.add(w,r.mul(p,m)),y)}if(!r.eql(r.sqr(e.Gy),a(e.Gx)))throw new Error("bad generator point: equation left != right");function s(p){return typeof p=="bigint"&&Bl<p&&p<e.n}function o(p){if(!s(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function d(p){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:b,n:w}=e;if(m&&typeof p!="bigint"){if(kd(p)&&(p=lh(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let S;try{S=typeof p=="bigint"?p:ah(zn("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return b&&(S=Zr(S,w)),o(S),S}let l=new Map;function c(p){if(!(p instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(m,y,b){if(this.px=m,this.py=y,this.pz=b,m==null||!r.isValid(m))throw new Error("x required");if(y==null||!r.isValid(y))throw new Error("y required");if(b==null||!r.isValid(b))throw new Error("z required")}static fromAffine(m){let{x:y,y:b}=m||{};if(!m||!r.isValid(y)||!r.isValid(b))throw new Error("invalid affine point");if(m instanceof u)throw new Error("projective point not allowed");let w=S=>r.eql(S,r.ZERO);return w(y)&&w(b)?u.ZERO:new u(y,b,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=r.invertBatch(m.map(b=>b.pz));return m.map((b,w)=>b.toAffine(y[w])).map(u.fromAffine)}static fromHex(m){let y=u.fromAffine(i(zn("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return u.BASE.multiply(d(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!r.isValid(m)||!r.isValid(y))throw new Error("bad point: x or y not FE");let b=r.sqr(y),w=a(m);if(!r.eql(b,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(r.isOdd)return!r.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){c(m);let{px:y,py:b,pz:w}=this,{px:S,py:k,pz:T}=m,D=r.eql(r.mul(y,T),r.mul(S,w)),K=r.eql(r.mul(b,T),r.mul(k,w));return D&&K}negate(){return new u(this.px,r.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,b=r.mul(y,K9),{px:w,py:S,pz:k}=this,T=r.ZERO,D=r.ZERO,K=r.ZERO,C=r.mul(w,w),G=r.mul(S,S),z=r.mul(k,k),N=r.mul(w,S);return N=r.add(N,N),K=r.mul(w,k),K=r.add(K,K),T=r.mul(m,K),D=r.mul(b,z),D=r.add(T,D),T=r.sub(G,D),D=r.add(G,D),D=r.mul(T,D),T=r.mul(N,T),K=r.mul(b,K),z=r.mul(m,z),N=r.sub(C,z),N=r.mul(m,N),N=r.add(N,K),K=r.add(C,C),C=r.add(K,C),C=r.add(C,z),C=r.mul(C,N),D=r.add(D,C),z=r.mul(S,k),z=r.add(z,z),C=r.mul(z,N),T=r.sub(T,C),K=r.mul(z,G),K=r.add(K,K),K=r.add(K,K),new u(T,D,K)}add(m){c(m);let{px:y,py:b,pz:w}=this,{px:S,py:k,pz:T}=m,D=r.ZERO,K=r.ZERO,C=r.ZERO,G=e.a,z=r.mul(e.b,K9),N=r.mul(y,S),V=r.mul(b,k),ee=r.mul(w,T),R=r.add(y,b),B=r.add(S,k);R=r.mul(R,B),B=r.add(N,V),R=r.sub(R,B),B=r.add(y,w);let P=r.add(S,T);return B=r.mul(B,P),P=r.add(N,ee),B=r.sub(B,P),P=r.add(b,w),D=r.add(k,T),P=r.mul(P,D),D=r.add(V,ee),P=r.sub(P,D),C=r.mul(G,B),D=r.mul(z,ee),C=r.add(D,C),D=r.sub(V,C),C=r.add(V,C),K=r.mul(D,C),V=r.add(N,N),V=r.add(V,N),ee=r.mul(G,ee),B=r.mul(z,B),V=r.add(V,ee),ee=r.sub(N,ee),ee=r.mul(G,ee),B=r.add(B,ee),N=r.mul(V,B),K=r.add(K,N),N=r.mul(P,B),D=r.mul(R,D),D=r.sub(D,N),N=r.mul(R,V),C=r.mul(P,C),C=r.add(C,N),new u(D,K,C)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return h.wNAFCached(this,l,m,y=>{let b=r.invertBatch(y.map(w=>w.pz));return y.map((w,S)=>w.toAffine(b[S])).map(u.fromAffine)})}multiplyUnsafe(m){let y=u.ZERO;if(m===Bl)return y;if(o(m),m===Da)return this;let{endo:b}=e;if(!b)return h.unsafeLadder(this,m);let{k1neg:w,k1:S,k2neg:k,k2:T}=b.splitScalar(m),D=y,K=y,C=this;for(;S>Bl||T>Bl;)S&Da&&(D=D.add(C)),T&Da&&(K=K.add(C)),C=C.double(),S>>=Da,T>>=Da;return w&&(D=D.negate()),k&&(K=K.negate()),K=new u(r.mul(K.px,b.beta),K.py,K.pz),D.add(K)}multiply(m){o(m);let y=m,b,w,{endo:S}=e;if(S){let{k1neg:k,k1:T,k2neg:D,k2:K}=S.splitScalar(y),{p:C,f:G}=this.wNAF(T),{p:z,f:N}=this.wNAF(K);C=h.constTimeNegate(k,C),z=h.constTimeNegate(D,z),z=new u(r.mul(z.px,S.beta),z.py,z.pz),b=C.add(z),w=G.add(N)}else{let{p:k,f:T}=this.wNAF(y);b=k,w=T}return u.normalizeZ([b,w])[0]}multiplyAndAddUnsafe(m,y,b){let w=u.BASE,S=(T,D)=>D===Bl||D===Da||!T.equals(w)?T.multiplyUnsafe(D):T.multiply(D),k=S(this,y).add(S(m,b));return k.is0()?void 0:k}toAffine(m){let{px:y,py:b,pz:w}=this,S=this.is0();m==null&&(m=S?r.ONE:r.inv(w));let k=r.mul(y,m),T=r.mul(b,m),D=r.mul(w,m);if(S)return{x:r.ZERO,y:r.ZERO};if(!r.eql(D,r.ONE))throw new Error("invZ was invalid");return{x:k,y:T}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===Da)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===Da?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return lh(this.toRawBytes(m))}}u.BASE=new u(e.Gx,e.Gy,r.ONE),u.ZERO=new u(r.ZERO,r.ONE,r.ZERO);let f=e.nBitLength,h=x7(u,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:a,isWithinCurveOrder:s}}function qle(t){let e=P6(t);return hh(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function zle(t){let e=qle(t),{Fp:r,n}=e,i=r.BYTES+1,a=2*r.BYTES+1;function s(B){return Bl<B&&B<r.ORDER}function o(B){return Zr(B,n)}function d(B){return VR(B,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:u,isWithinCurveOrder:f}=Lle({...e,toBytes(B,P,E){let x=P.toAffine(),A=r.toBytes(x.x),I=uh;return E?I(Uint8Array.from([P.hasEvenY()?2:3]),A):I(Uint8Array.from([4]),A,r.toBytes(x.y))},fromBytes(B){let P=B.length,E=B[0],x=B.subarray(1);if(P===i&&(E===2||E===3)){let A=ah(x);if(!s(A))throw new Error("Point is not on curve");let I=u(A),M=r.sqrt(I),q=(M&Da)===Da;return(E&1)===1!==q&&(M=r.neg(M)),{x:A,y:M}}else if(P===a&&E===4){let A=r.fromBytes(x.subarray(0,r.BYTES)),I=r.fromBytes(x.subarray(r.BYTES,2*r.BYTES));return{x:A,y:I}}else throw new Error(`Point of length ${P} was invalid. Expected ${i} compressed bytes or ${a} uncompressed bytes`)}}),h=B=>lh(_d(B,e.nByteLength));function p(B){let P=n>>Da;return B>P}function m(B){return p(B)?o(-B):B}let y=(B,P,E)=>ah(B.slice(P,E));class b{constructor(P,E,x){this.r=P,this.s=E,this.recovery=x,this.assertValidity()}static fromCompact(P){let E=e.nByteLength;return P=zn("compactSignature",P,E*2),new b(y(P,0,E),y(P,E,2*E))}static fromDER(P){let{r:E,s:x}=sh.toSig(zn("DER",P));return new b(E,x)}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(P){return new b(this.r,this.s,P)}recoverPublicKey(P){let{r:E,s:x,recovery:A}=this,I=K(zn("msgHash",P));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let M=A===2||A===3?E+e.n:E;if(M>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let q=A&1?"03":"02",H=l.fromHex(q+h(M)),W=d(M),J=o(-I*W),X=o(x*W),L=l.BASE.multiplyAndAddUnsafe(H,J,X);if(!L)throw new Error("point at infinify");return L.assertValidity(),L}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new b(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Ly(this.toDERHex())}toDERHex(){return sh.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ly(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let w={isValidPrivateKey(B){try{return c(B),!0}catch{return!1}},normPrivateKeyToScalar:c,randomPrivateKey:()=>{let B=P7(e.n);return jle(e.randomBytes(B),e.n)},precompute(B=8,P=l.BASE){return P._setWindowSize(B),P.multiply(BigInt(3)),P}};function S(B,P=!0){return l.fromPrivateKey(B).toRawBytes(P)}function k(B){let P=kd(B),E=typeof B=="string",x=(P||E)&&B.length;return P?x===i||x===a:E?x===2*i||x===2*a:B instanceof l}function T(B,P,E=!0){if(k(B))throw new Error("first arg must be private key");if(!k(P))throw new Error("second arg must be public key");return l.fromHex(P).multiply(c(B)).toRawBytes(E)}let D=e.bits2int||function(B){let P=ah(B),E=B.length*8-e.nBitLength;return E>0?P>>BigInt(E):P},K=e.bits2int_modN||function(B){return o(D(B))},C=g6(e.nBitLength);function G(B){if(typeof B!="bigint")throw new Error("bigint expected");if(!(Bl<=B&&B<C))throw new Error(`bigint expected < 2^${e.nBitLength}`);return _d(B,e.nByteLength)}function z(B,P,E=N){if(["recovered","canonical"].some(se=>se in E))throw new Error("sign() legacy options not supported");let{hash:x,randomBytes:A}=e,{lowS:I,prehash:M,extraEntropy:q}=E;I==null&&(I=!0),B=zn("msgHash",B),M&&(B=zn("prehashed msgHash",x(B)));let H=K(B),W=c(P),J=[G(W),G(H)];if(q!=null){let se=q===!0?A(r.BYTES):q;J.push(zn("extraEntropy",se))}let X=uh(...J),L=H;function Q(se){let re=D(se);if(!f(re))return;let Y=d(re),le=l.BASE.multiply(re).toAffine(),ue=o(le.x);if(ue===Bl)return;let pe=o(Y*o(L+ue*W));if(pe===Bl)return;let xe=(le.x===ue?0:2)|Number(le.y&Da),de=pe;return I&&p(pe)&&(de=m(pe),xe^=1),new b(ue,de,xe)}return{seed:X,k2sig:Q}}let N={lowS:e.lowS,prehash:!1},V={lowS:e.lowS,prehash:!1};function ee(B,P,E=N){let{seed:x,k2sig:A}=z(B,P,E),I=e;return d7(I.hash.outputLen,I.nByteLength,I.hmac)(x,A)}l.BASE._setWindowSize(8);function R(B,P,E,x=V){let A=B;if(P=zn("msgHash",P),E=zn("publicKey",E),"strict"in x)throw new Error("options.strict was renamed to lowS");let{lowS:I,prehash:M}=x,q,H;try{if(typeof A=="string"||kd(A))try{q=b.fromDER(A)}catch(Y){if(!(Y instanceof sh.Err))throw Y;q=b.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:Y,s:le}=A;q=new b(Y,le)}else throw new Error("PARSE");H=l.fromHex(E)}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;M&&(P=e.hash(P));let{r:W,s:J}=q,X=K(P),L=d(J),Q=o(X*L),se=o(W*L),re=l.BASE.multiplyAndAddUnsafe(H,Q,se)?.toAffine();return re?o(re.x)===W:!1}return{CURVE:e,getPublicKey:S,getSharedSecret:T,sign:ee,verify:R,ProjectivePoint:l,Signature:b,utils:w}}function Fle(t){return{hash:t,hmac:(e,...r)=>S7(t,e,p7(...r)),randomBytes:v6}}function A7(t,e){let r=n=>zle({...t,...Fle(n)});return Object.freeze({...r(e),create:r})}function Hle(t){let e=k7,r=BigInt(3),n=BigInt(6),i=BigInt(11),a=BigInt(22),s=BigInt(23),o=BigInt(44),d=BigInt(88),l=t*t*t%e,c=l*l*t%e,u=Pn(c,r,e)*c%e,f=Pn(u,r,e)*c%e,h=Pn(f,WR,e)*l%e,p=Pn(h,i,e)*h%e,m=Pn(p,a,e)*p%e,y=Pn(m,o,e)*m%e,b=Pn(y,d,e)*y%e,w=Pn(b,o,e)*m%e,S=Pn(w,r,e)*c%e,k=Pn(S,s,e)*p%e,T=Pn(k,n,e)*l%e,D=Pn(T,WR,e);if(!JR.eql(JR.sqr(D),t))throw new Error("Cannot find square root");return D}function Vle(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function _7(t,...e){if(!Vle(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function L9(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Wle(t,e){_7(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}function Jle(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function T7(t){return typeof t=="string"&&(t=Jle(t)),_7(t),t}function Yle(t){let e=n=>t().update(T7(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Xle(t=32){if(g2&&typeof g2.getRandomValues=="function")return g2.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Qle(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),a=BigInt(4294967295),s=Number(r>>i&a),o=Number(r&a),d=n?4:0,l=n?0:4;t.setUint32(e+d,s,n),t.setUint32(e+l,o,n)}function sue(t){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let i=Object.keys(n).sort(),a={};for(let s of i)a[s]=e(n[s]);return a}return n},r=e(t);return JSON.stringify(r)}function Ar(t){return aue(this,arguments,void 0,function*({jwk:e}){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);s7(n);let i=sue(n),a=it.string(i).toUint8Array(),s=yield I7.digest({data:a});return it.uint8Array(s).toBase64Url()})}function ch(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="EC"||typeof t.d!="string"||typeof t.x!="string")}function x6(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t)||"d"in t||t.kty!=="EC"||typeof t.x!="string")}function Ml(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="OKP"||typeof t.d!="string"||typeof t.x!="string")}function E6(t){return!(!t||typeof t!="object"||"d"in t||!("kty"in t&&"crv"in t&&"x"in t)||t.kty!=="OKP"||typeof t.x!="string")}function cue(t){if(!t||typeof t!="object")return!1;switch(t.kty){case"EC":case"OKP":case"RSA":return"d"in t;case"oct":return"k"in t;default:return!1}}function R7(t,e=!1){return e?{h:Number(t&d2),l:Number(t>>ZR&d2)}:{h:Number(t>>ZR&d2)|0,l:Number(t&d2)|0}}function hue(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){let{h:a,l:s}=R7(t[i],e);[r[i],n[i]]=[a,s]}return[r,n]}function Tue(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}function Lue(t){let e=P6(t);return hh(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function S6(t){let e=Lue(t),{Fp:r,n,prehash:i,hash:a,randomBytes:s,nByteLength:o,h:d}=e,l=l2<<BigInt(o*8)-qo,c=r.create,u=e.uvRatio||((E,x)=>{try{return{isValid:!0,value:r.sqrt(E*r.inv(x))}}catch{return{isValid:!1,value:bc}}}),f=e.adjustScalarBytes||(E=>E),h=e.domain||((E,x,A)=>{if(x.length||A)throw new Error("Contexts/pre-hash are not supported");return E}),p=E=>typeof E=="bigint"&&bc<E,m=(E,x)=>p(E)&&p(x)&&E<x,y=E=>E===bc||m(E,l);function b(E,x){if(m(E,x))return E;throw new Error(`Expected valid scalar < ${x}, got ${typeof E} ${E}`)}function w(E){return E===bc?E:b(E,n)}let S=new Map;function k(E){if(!(E instanceof T))throw new Error("ExtendedPoint expected")}class T{constructor(x,A,I,M){if(this.ex=x,this.ey=A,this.ez=I,this.et=M,!y(x))throw new Error("x required");if(!y(A))throw new Error("y required");if(!y(I))throw new Error("z required");if(!y(M))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(x){if(x instanceof T)throw new Error("extended point not allowed");let{x:A,y:I}=x||{};if(!y(A)||!y(I))throw new Error("invalid affine point");return new T(A,I,qo,c(A*I))}static normalizeZ(x){let A=r.invertBatch(x.map(I=>I.ez));return x.map((I,M)=>I.toAffine(A[M])).map(T.fromAffine)}_setWindowSize(x){this._WINDOW_SIZE=x,S.delete(this)}assertValidity(){let{a:x,d:A}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:I,ey:M,ez:q,et:H}=this,W=c(I*I),J=c(M*M),X=c(q*q),L=c(X*X),Q=c(W*x),se=c(X*c(Q+J)),re=c(L+c(A*c(W*J)));if(se!==re)throw new Error("bad point: equation left != right (1)");let Y=c(I*M),le=c(q*H);if(Y!==le)throw new Error("bad point: equation left != right (2)")}equals(x){k(x);let{ex:A,ey:I,ez:M}=this,{ex:q,ey:H,ez:W}=x,J=c(A*W),X=c(q*M),L=c(I*W),Q=c(H*M);return J===X&&L===Q}is0(){return this.equals(T.ZERO)}negate(){return new T(c(-this.ex),this.ey,this.ez,c(-this.et))}double(){let{a:x}=e,{ex:A,ey:I,ez:M}=this,q=c(A*A),H=c(I*I),W=c(l2*c(M*M)),J=c(x*q),X=A+I,L=c(c(X*X)-q-H),Q=J+H,se=Q-W,re=J-H,Y=c(L*se),le=c(Q*re),ue=c(L*re),pe=c(se*Q);return new T(Y,le,pe,ue)}add(x){k(x);let{a:A,d:I}=e,{ex:M,ey:q,ez:H,et:W}=this,{ex:J,ey:X,ez:L,et:Q}=x;if(A===BigInt(-1)){let Ct=c((q-M)*(X+J)),ke=c((q+M)*(X-J)),ot=c(ke-Ct);if(ot===bc)return this.double();let _t=c(H*l2*Q),Rt=c(W*l2*L),zt=Rt+_t,_=ke+Ct,O=Rt-_t,U=c(zt*ot),te=c(_*O),ce=c(zt*O),me=c(ot*_);return new T(U,te,me,ce)}let se=c(M*J),re=c(q*X),Y=c(W*I*Q),le=c(H*L),ue=c((M+q)*(J+X)-se-re),pe=le-Y,xe=le+Y,de=c(re-A*se),Pe=c(ue*pe),Ne=c(xe*de),He=c(ue*de),Je=c(pe*xe);return new T(Pe,Ne,Je,He)}subtract(x){return this.add(x.negate())}wNAF(x){return C.wNAFCached(this,S,x,T.normalizeZ)}multiply(x){let{p:A,f:I}=this.wNAF(b(x,n));return T.normalizeZ([A,I])[0]}multiplyUnsafe(x){let A=w(x);return A===bc?K:this.equals(K)||A===qo?this:this.equals(D)?this.wNAF(A).p:C.unsafeLadder(this,A)}isSmallOrder(){return this.multiplyUnsafe(d).is0()}isTorsionFree(){return C.unsafeLadder(this,n).is0()}toAffine(x){let{ex:A,ey:I,ez:M}=this,q=this.is0();x==null&&(x=q?Nue:r.inv(M));let H=c(A*x),W=c(I*x),J=c(M*x);if(q)return{x:bc,y:qo};if(J!==qo)throw new Error("invZ was invalid");return{x:H,y:W}}clearCofactor(){let{h:x}=e;return x===qo?this:this.multiplyUnsafe(x)}static fromHex(x,A=!1){let{d:I,a:M}=e,q=r.BYTES;x=zn("pointHex",x,q);let H=x.slice(),W=x[q-1];H[q-1]=W&-129;let J=vf(H);J===bc||(A?b(J,l):b(J,r.ORDER));let X=c(J*J),L=c(X-qo),Q=c(I*X-M),{isValid:se,value:re}=u(L,Q);if(!se)throw new Error("Point.fromHex: invalid y coordinate");let Y=(re&qo)===qo,le=(W&128)!==0;if(!A&&re===bc&&le)throw new Error("Point.fromHex: x=0 and x_0=1");return le!==Y&&(re=c(-re)),T.fromAffine({x:re,y:J})}static fromPrivateKey(x){return N(x).point}toRawBytes(){let{x,y:A}=this.toAffine(),I=qy(A,r.BYTES);return I[I.length-1]|=x&qo?128:0,I}toHex(){return lh(this.toRawBytes())}}T.BASE=new T(e.Gx,e.Gy,qo,c(e.Gx*e.Gy)),T.ZERO=new T(bc,qo,qo,bc);let{BASE:D,ZERO:K}=T,C=x7(T,o*8);function G(E){return Zr(E,n)}function z(E){return G(vf(E))}function N(E){let x=o;E=zn("private key",E,x);let A=zn("hashed private key",a(E),2*x),I=f(A.slice(0,x)),M=A.slice(x,2*x),q=z(I),H=D.multiply(q),W=H.toRawBytes();return{head:I,prefix:M,scalar:q,point:H,pointBytes:W}}function V(E){return N(E).pointBytes}function ee(E=new Uint8Array,...x){let A=uh(...x);return z(a(h(A,zn("context",E),!!i)))}function R(E,x,A={}){E=zn("message",E),i&&(E=i(E));let{prefix:I,scalar:M,pointBytes:q}=N(x),H=ee(A.context,I,E),W=D.multiply(H).toRawBytes(),J=ee(A.context,W,q,E),X=G(H+J*M);w(X);let L=uh(W,qy(X,r.BYTES));return zn("result",L,o*2)}let B=Uue;function P(E,x,A,I=B){let{context:M,zip215:q}=I,H=r.BYTES;E=zn("signature",E,2*H),x=zn("message",x),i&&(x=i(x));let W=vf(E.slice(H,2*H)),J,X,L;try{J=T.fromHex(A,q),X=T.fromHex(E.slice(0,H),q),L=D.multiplyUnsafe(W)}catch{return!1}if(!q&&J.isSmallOrder())return!1;let Q=ee(M,X.toRawBytes(),J.toRawBytes(),x);return X.add(J.multiplyUnsafe(Q)).subtract(L).clearCofactor().equals(T.ZERO)}return D._setWindowSize(8),{CURVE:e,getPublicKey:V,sign:R,verify:P,ExtendedPoint:T,utils:{getExtendedPublicKey:N,randomPrivateKey:()=>s(r.BYTES),precompute(E=8,x=T.BASE){return x._setWindowSize(E),x.multiply(BigInt(3)),x}}}}function que(t){return hh(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function zue(t){let e=que(t),{P:r}=e,n=S=>Zr(S,r),i=e.montgomeryBits,a=Math.ceil(i/8),s=e.nByteLength,o=e.adjustScalarBytes||(S=>S),d=e.powPminus2||(S=>w7(S,r-BigInt(2),r));function l(S,k,T){let D=n(S*(k-T));return k=n(k-D),T=n(T+D),[k,T]}function c(S){if(typeof S=="bigint"&&wv<=S&&S<r)return S;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let u=(e.a-BigInt(2))/BigInt(4);function f(S,k){let T=c(S),D=c(k),K=T,C=KR,G=wv,z=T,N=KR,V=wv,ee;for(let B=BigInt(i-1);B>=wv;B--){let P=D>>B&KR;V^=P,ee=l(V,C,z),C=ee[0],z=ee[1],ee=l(V,G,N),G=ee[0],N=ee[1],V=P;let E=C+G,x=n(E*E),A=C-G,I=n(A*A),M=x-I,q=z+N,H=z-N,W=n(H*E),J=n(q*A),X=W+J,L=W-J;z=n(X*X),N=n(K*n(L*L)),C=n(x*I),G=n(M*(x+n(u*M)))}ee=l(V,C,z),C=ee[0],z=ee[1],ee=l(V,G,N),G=ee[0],N=ee[1];let R=d(G);return n(C*R)}function h(S){return qy(n(S),a)}function p(S){let k=zn("u coordinate",S,a);return s===32&&(k[31]&=127),vf(k)}function m(S){let k=zn("scalar",S),T=k.length;if(T!==a&&T!==s)throw new Error(`Expected ${a} or ${s} bytes, got ${T}`);return vf(o(k))}function y(S,k){let T=p(k),D=m(S),K=f(T,D);if(K===wv)throw new Error("Invalid private or public key received");return h(K)}let b=h(e.Gu);function w(S){return y(S,b)}return{scalarMult:y,scalarMultBase:w,getSharedSecret:(S,k)=>y(S,k),getPublicKey:S=>w(S),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:b}}function $7(t){let e=zv,r=t*t%e*t%e,n=Pn(r,YR,e)*r%e,i=Pn(n,Fue,e)*t%e,a=Pn(i,Gue,e)*i%e,s=Pn(a,G9,e)*a%e,o=Pn(s,Hue,e)*s%e,d=Pn(o,Vue,e)*o%e,l=Pn(d,H9,e)*d%e,c=Pn(l,H9,e)*d%e,u=Pn(c,G9,e)*a%e;return{pow_p_5_8:Pn(u,YR,e)*t%e,b2:r}}function B7(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Wue(t,e){let r=zv,n=Zr(e*e*e,r),i=Zr(n*n*e,r),a=$7(t*i).pow_p_5_8,s=Zr(t*n*a,r),o=Zr(e*s*s,r),d=s,l=Zr(s*F9,r),c=o===t,u=o===Zr(-t,r),f=o===Zr(-t*F9,r);return c&&(s=d),(u||f)&&(s=l),Dle(s,r)&&(s=Zr(-s,r)),{isValid:c||u,value:s}}function O7(t,e,r){if(e.length>255)throw new Error("Context is too big");return p7(f7("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}function Jue(t){let{y:e}=eh.ExtendedPoint.fromHex(t),r=BigInt(1);return Ba.toBytes(Ba.create((r+e)*Ba.inv(r-e)))}function Zue(t){let e=Fv.hash(t.subarray(0,32));return Fv.adjustScalarBytes(e).subarray(0,32)}function ofe(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;return e==="string"||e==="number"||e==="bigint"||e==="symbol"?e:e==="function"?"Function":Array.isArray(t)?"Array":t instanceof Uint8Array?"Uint8Array":t.constructor===Object?"Object":afe(t)||"Object"}function afe(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(sfe.includes(e))return e}function N2(t){return Zv&&globalThis.Buffer.isBuffer(t)}function j7(t){return t instanceof Uint8Array?N2(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}function M7(t,e){if(N2(t)&&N2(e))return t.compare(e);for(let r=0;r<t.length;r++)if(t[r]!==e[r])return t[r]<e[r]?-1:1;return 0}function V9(t){let e=[],r=0;for(let n=0;n<t.length;n++){let i=t.charCodeAt(n);i<128?e[r++]=i:i<2048?(e[r++]=i>>6|192,e[r++]=i&63|128):(i&64512)===55296&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++n)&1023),e[r++]=i>>18|240,e[r++]=i>>12&63|128,e[r++]=i>>6&63|128,e[r++]=i&63|128):(i>=55296&&i<=57343&&(i=65533),e[r++]=i>>12|224,e[r++]=i>>6&63|128,e[r++]=i&63|128)}return e}function Vy(t,e,r){if(t.length-e<r)throw new Error(`${xn} not enough data for type`)}function mh(t,e,r){Vy(t,e,1);let n=t[e];if(r.strict===!0&&n<es[0])throw new Error(`${xn} integer encoded in more bytes than necessary (strict decode)`);return n}function yh(t,e,r){Vy(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<es[1])throw new Error(`${xn} integer encoded in more bytes than necessary (strict decode)`);return n}function gh(t,e,r){Vy(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<es[2])throw new Error(`${xn} integer encoded in more bytes than necessary (strict decode)`);return n}function wh(t,e,r){Vy(t,e,8);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],i=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],a=(BigInt(n)<<BigInt(32))+BigInt(i);if(r.strict===!0&&a<es[3])throw new Error(`${xn} integer encoded in more bytes than necessary (strict decode)`);if(a<=Number.MAX_SAFE_INTEGER)return Number(a);if(r.allowBigInt===!0)return a;throw new Error(`${xn} integers outside of the safe integer range are not supported`)}function gfe(t,e,r,n){return new tt(Se.uint,mh(t,e+1,n),2)}function wfe(t,e,r,n){return new tt(Se.uint,yh(t,e+1,n),3)}function vfe(t,e,r,n){return new tt(Se.uint,gh(t,e+1,n),5)}function bfe(t,e,r,n){return new tt(Se.uint,wh(t,e+1,n),9)}function vh(t,e){return ja(t,0,e.value)}function ja(t,e,r){if(r<es[0]){let n=Number(r);t.push([e|n])}else if(r<es[1]){let n=Number(r);t.push([e|24,n])}else if(r<es[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<es[3]){let n=Number(r);t.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(r);if(n<es[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,t.push(i)}else throw new Error(`${xn} encountered BigInt larger than allowable range`)}}function Pfe(t,e,r,n){return new tt(Se.negint,-1-mh(t,e+1,n),2)}function xfe(t,e,r,n){return new tt(Se.negint,-1-yh(t,e+1,n),3)}function Efe(t,e,r,n){return new tt(Se.negint,-1-gh(t,e+1,n),5)}function Sfe(t,e,r,n){let i=wh(t,e+1,n);if(typeof i!="bigint"){let a=-1-i;if(a>=Number.MIN_SAFE_INTEGER)return new tt(Se.negint,a,9)}if(n.allowBigInt!==!0)throw new Error(`${xn} integers outside of the safe integer range are not supported`);return new tt(Se.negint,A6-BigInt(i),9)}function k6(t,e){let r=e.value,n=typeof r=="bigint"?r*A6-U7:r*-1-1;ja(t,e.type.majorEncoded,n)}function Xv(t,e,r,n){Vy(t,e,r+n);let i=t.slice(e+r,e+r+n);return new tt(Se.bytes,i,r+n)}function Afe(t,e,r,n){return Xv(t,e,1,r)}function kfe(t,e,r,n){return Xv(t,e,2,mh(t,e+1,n))}function _fe(t,e,r,n){return Xv(t,e,3,yh(t,e+1,n))}function Tfe(t,e,r,n){return Xv(t,e,5,gh(t,e+1,n))}function Ife(t,e,r,n){let i=wh(t,e+1,n);if(typeof i=="bigint")throw new Error(`${xn} 64-bit integer bytes lengths not supported`);return Xv(t,e,9,i)}function U2(t){return t.encodedBytes===void 0&&(t.encodedBytes=Se.equals(t.type,Se.string)?ufe(t.value):t.value),t.encodedBytes}function X2(t,e){let r=U2(e);ja(t,e.type.majorEncoded,r.length),t.push(r)}function Dfe(t,e){return t.length<e.length?-1:t.length>e.length?1:M7(t,e)}function Cfe(t,e,r){if(r-e<Rfe){let n="";for(let i=e;i<r;i++){let a=t[i];if(a&128)return W9.decode(t.subarray(e,r));n+=String.fromCharCode(a)}return n}return W9.decode(t.subarray(e,r))}function Qv(t,e,r,n,i){let a=r+n;Vy(t,e,a);let s=new tt(Se.string,Cfe(t,e+r,e+a),a);return i.retainStringBytes===!0&&(s.byteValue=t.slice(e+r,e+a)),s}function $fe(t,e,r,n){return Qv(t,e,1,r,n)}function Bfe(t,e,r,n){return Qv(t,e,2,mh(t,e+1,n),n)}function Ofe(t,e,r,n){return Qv(t,e,3,yh(t,e+1,n),n)}function jfe(t,e,r,n){return Qv(t,e,5,gh(t,e+1,n),n)}function Mfe(t,e,r,n){let i=wh(t,e+1,n);if(typeof i=="bigint")throw new Error(`${xn} 64-bit integer string lengths not supported`);return Qv(t,e,9,i,n)}function Wy(t,e,r,n){return new tt(Se.array,n,r)}function Nfe(t,e,r,n){return Wy(t,e,1,r)}function Ufe(t,e,r,n){return Wy(t,e,2,mh(t,e+1,n))}function Lfe(t,e,r,n){return Wy(t,e,3,yh(t,e+1,n))}function qfe(t,e,r,n){return Wy(t,e,5,gh(t,e+1,n))}function zfe(t,e,r,n){let i=wh(t,e+1,n);if(typeof i=="bigint")throw new Error(`${xn} 64-bit integer array lengths not supported`);return Wy(t,e,9,i)}function Ffe(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${xn} indefinite length items not allowed`);return Wy(t,e,1,1/0)}function _6(t,e){ja(t,Se.array.majorEncoded,e.value)}function Jy(t,e,r,n){return new tt(Se.map,n,r)}function Gfe(t,e,r,n){return Jy(t,e,1,r)}function Hfe(t,e,r,n){return Jy(t,e,2,mh(t,e+1,n))}function Vfe(t,e,r,n){return Jy(t,e,3,yh(t,e+1,n))}function Wfe(t,e,r,n){return Jy(t,e,5,gh(t,e+1,n))}function Jfe(t,e,r,n){let i=wh(t,e+1,n);if(typeof i=="bigint")throw new Error(`${xn} 64-bit integer map lengths not supported`);return Jy(t,e,9,i)}function Zfe(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${xn} indefinite length items not allowed`);return Jy(t,e,1,1/0)}function T6(t,e){ja(t,Se.map.majorEncoded,e.value)}function Yfe(t,e,r,n){return new tt(Se.tag,r,1)}function Xfe(t,e,r,n){return new tt(Se.tag,mh(t,e+1,n),2)}function Qfe(t,e,r,n){return new tt(Se.tag,yh(t,e+1,n),3)}function epe(t,e,r,n){return new tt(Se.tag,gh(t,e+1,n),5)}function tpe(t,e,r,n){return new tt(Se.tag,wh(t,e+1,n),9)}function I6(t,e){ja(t,Se.tag.majorEncoded,e.value)}function rpe(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${xn} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new tt(Se.null,null,1):new tt(Se.undefined,void 0,1)}function npe(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${xn} indefinite length items not allowed`);return new tt(Se.break,void 0,1)}function D6(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${xn} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${xn} Infinity values are not supported`)}return new tt(Se.float,t,e)}function ipe(t,e,r,n){return D6(C6(t,e+1),3,n)}function spe(t,e,r,n){return D6($6(t,e+1),5,n)}function ope(t,e,r,n){return D6(W7(t,e+1),9,n)}function R6(t,e,r){let n=e.value;if(n===!1)t.push([Se.float.majorEncoded|L7]);else if(n===!0)t.push([Se.float.majorEncoded|q7]);else if(n===null)t.push([Se.float.majorEncoded|z7]);else if(n===void 0)t.push([Se.float.majorEncoded|F7]);else{let i,a=!1;(!r||r.float64!==!0)&&(H7(n),i=C6(Pc,1),n===i||Number.isNaN(n)?(Pc[0]=249,t.push(Pc.slice(0,3)),a=!0):(V7(n),i=$6(Pc,1),n===i&&(Pc[0]=250,t.push(Pc.slice(0,5)),a=!0))),a||(ape(n),i=W7(Pc,1),Pc[0]=251,t.push(Pc.slice(0,9)))}}function H7(t){if(t===1/0)Ta.setUint16(0,31744,!1);else if(t===-1/0)Ta.setUint16(0,64512,!1);else if(Number.isNaN(t))Ta.setUint16(0,32256,!1);else{Ta.setFloat32(0,t);let e=Ta.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)Ta.setUint16(0,31744,!1);else if(r===0)Ta.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let i=r-127;i<-24?Ta.setUint16(0,0):i<-14?Ta.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Ta.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function C6(t,e){if(t.length-e<2)throw new Error(`${xn} not enough data for float16`);let r=(t[e]<<8)+t[e+1];if(r===31744)return 1/0;if(r===64512)return-1/0;if(r===32256)return NaN;let n=r>>10&31,i=r&1023,a;return n===0?a=i*2**-24:n!==31?a=(i+1024)*2**(n-25):a=i===0?1/0:NaN,r&32768?-a:a}function V7(t){Ta.setFloat32(0,t,!1)}function $6(t,e){if(t.length-e<4)throw new Error(`${xn} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function ape(t){Ta.setFloat64(0,t,!1)}function W7(t,e){if(t.length-e<8)throw new Error(`${xn} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}function mr(t,e,r){throw new Error(`${xn} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function Q2(t){return()=>{throw new Error(`${xn} ${t}`)}}function cpe(t){switch(t.type){case Se.false:return Cl([244]);case Se.true:return Cl([245]);case Se.null:return Cl([246]);case Se.bytes:return t.value.length?void 0:Cl([64]);case Se.string:return t.value===""?Cl([96]):void 0;case Se.array:return t.value===0?Cl([128]):void 0;case Se.map:return t.value===0?Cl([160]):void 0;case Se.uint:return t.value<24?Cl([Number(t.value)]):void 0;case Se.negint:if(t.value>=-24)return Cl([31-Number(t.value)])}}function lpe(){let t=[];return t[Se.uint.major]=vh,t[Se.negint.major]=k6,t[Se.bytes.major]=X2,t[Se.string.major]=Kfe,t[Se.array.major]=_6,t[Se.map.major]=T6,t[Se.tag.major]=I6,t[Se.float.major]=R6,t}function w2(t,e={},r){let n=ofe(t),i=e&&e.typeEncoders&&e.typeEncoders[n]||Pf[n];if(typeof i=="function"){let s=i(t,n,e,r);if(s!=null)return s}let a=Pf[n];if(!a)throw new Error(`${N7} unsupported type: ${n}`);return a(t,n,e,r)}function ppe(t,e){e.mapSorter&&t.sort(e.mapSorter)}function hpe(t,e){if(t[0]instanceof tt&&e[0]instanceof tt){let r=t[0],n=e[0];return r._keyBytes||(r._keyBytes=Z9(r.value)),n._keyBytes||(n._keyBytes=Z9(n.value)),M7(r._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Z9(t){return mpe(t,upe,dpe)}function Z7(t,e,r,n){if(Array.isArray(e))for(let i of e)Z7(t,i,r,n);else r[e.type.major](t,e,n)}function mpe(t,e,r,n){let i=n instanceof Uint8Array,a=i?new yfe(n):fpe,s=w2(t,r);if(!Array.isArray(s)&&r.quickEncodeToken){let o=r.quickEncodeToken(s);if(o)return i?(a.push(o),a.toBytes()):o;let d=e[s.type.major];if(d.encodedSize){let l=d.encodedSize(s,r);if(i||(a=new K7(l)),d(a,s,r),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return i?a.toBytes():j7(a.chunks[0])}}return a.reset(),Z7(a,s,e,r),a.toBytes(!0)}function Gs(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function ype({didDocument:t,id:e,type:r}){return t?.service?.filter(n=>!(e&&n.id!==e||r&&n.type!==r))??[]}async function gpe({didDocument:t,publicKeyJwk:e,publicKeyMultibase:r}){let n=eE({didDocument:t});for(let i of n)if(e&&i.publicKeyJwk){if(await Ar({jwk:e})===await Ar({jwk:i.publicKeyJwk}))return i}else if(r&&i.publicKeyMultibase&&r===i.publicKeyMultibase)return i;return null}function eE({didDocument:t}){if(!t)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...t.verificationMethod?.filter(L2)??[]),Object.keys(J2).forEach(r=>{e.push(...t[r]?.filter(L2)??[])}),e}function Y7({didDocument:t}){let e=eE({didDocument:t}).map(r=>r.type);return[...new Set(e)]}function X7({didDocument:t,methodId:e}){let r=[];return Object.keys(J2).forEach(n=>{if(Array.isArray(t[n])){let i=t[n],a=Gs(e);i.some(s=>{let o=Gs(s)===a,d=L2(s)&&Gs(s.id)===a;return o||d})&&r.push(n)}}),r}function Q7(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function wpe(t){return!(!Q7(t)||t.type!=="DecentralizedWebNode")}function L2(t){return!(!t||typeof t!="object"||t===null||!("id"in t&&"type"in t&&"controller"in t)||typeof t.id!="string"||typeof t.type!="string"||typeof t.controller!="string")}function bh(t){return!(!t||typeof t!="object"||t===null)&&"uri"in t&&"document"in t&&"metadata"in t&&(!("keyManager"in t)||t.keyManager===void 0)}function ez({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=Oa.addPrefix({code:e,data:t,name:r}),i=it.uint8Array(n).toBase58Btc();return it.base58Btc(i).toMultibase()}function tz({multibaseKeyId:t}){try{let e=it.multibase(t).toBase58Btc(),r=it.base58Btc(e).toUint8Array(),{code:n,data:i,name:a}=Oa.removePrefix({prefixedData:r});return{keyBytes:i,multicodecCode:n,multicodecName:a}}catch{throw new rt("invalidDid",`Invalid multibase identifier: ${t}`)}}function tb(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function az(t){return ArrayBuffer.isView(t)?"arraybufferview":Array.isArray(t)?"array":t instanceof Number?"number":t instanceof Boolean?"boolean":t instanceof Set?"set":t instanceof Map?"map":t instanceof String?"string":t instanceof ArrayBuffer?"arraybuffer":typeof t}function vr(t,e,r){let n=[],i=null;return vr._encode(n,t),i=bpe(n),vr.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,r),e):i}function lz(t,e,r){let n=0,i=1;for(let a=e;a<r;a++){let s=t[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 bt(t,e,r,n){return t==null||t.length===0?null:(typeof e!="number"&&n==null&&(n=e,e=void 0),typeof r!="number"&&n==null&&(n=r,r=void 0),bt.position=0,bt.encoding=n||null,bt.data=ArrayBuffer.isView(t)?new Uint8Array(t.slice(e,r)):Kl(t),bt.bytes=bt.data.length,bt.next())}function Dpe(t){let e=2;for(let r of t)e+=rE(r);return e}function Rpe(t){let e=2;for(let[r,n]of t){let i=Kl(r).byteLength;e+=tb(i)+1+i,e+=rE(n)}return e}function Cpe(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let i=Kl(r[n]).byteLength;e+=tb(i)+1+i,e+=rE(t[r[n]])}return e}function $pe(t){let e=Kl(t).byteLength;return tb(e)+1+e}function Bpe(t){let e=t.byteLength-t.byteOffset;return tb(e)+1+e}function rE(t){if(t==null)return 0;let e=az(t);switch(e){case"arraybufferview":return Bpe(t);case"string":return $pe(t);case"array":case"set":return Dpe(t);case"number":return 1+tb(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return Cpe(t);case"map":return Rpe(t);default:throw new TypeError(`Unsupported value of type "${e}"`)}}function pz(t){if(Ad.isFormat(t))return Ad.size;if(bf.isFormat(t))return bf.size;throw Error(`Invalid ip address: ${t}`)}function Kpe(t){return pz(t)===Ad.size?1:2}function Npe(t,e,r){r=~~r;let n=pz(t);return typeof e=="function"&&(e=e(r+n)),n===Ad.size?Ad.encode(t,e,r):bf.encode(t,e,r)}function Upe(t,e,r){if(e=~~e,r=r||t.length-e,r===Ad.size)return Ad.decode(t,e,r);if(r===bf.size)return bf.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${Ad.size} for v4 or ${bf.size} for v6.`)}function nE(t){switch(t){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_"+t}function Gv(t){switch(t.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 t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}function Lpe(t){switch(t){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_"+t}function qpe(t){switch(t){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_"+t}function hz(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t}function mz(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}function zpe(t){switch(t){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 t<0?null:`OPTION_${t}`}function dq(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.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=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}function yz(t){let e=0,r=t.length;for(let n=0;n<r;n+=1){let i=t.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===r||i>=56320||(t.charCodeAt(a)&64512)!==56320?e+=3:(n=a,e+=4)}}return e}function Hv(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(yz(t)+r));let i=r;for(let a=0;a<n;a+=1){let s=t.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 d=t.charCodeAt(o);(d&64512)!==56320?(e[i++]=239,e[i++]=191,e[i++]=189):(a=o,s=65536|(s&1023)<<10|d&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 Hv.bytes=i-r,e}function rb(t,e,r){let n="";e==null&&(e=0),r==null&&(r=t.length);for(let i=e;i<r;){let a=t[i++],s;if(a<=128)s=a;else if(a>191&&a<224)s=(a&31)<<6|t[i++]&63;else if(a>239&&a<365){s=((a&7)<<18|(t[i++]&63)<<12|(t[i++]&63)<<6|t[i++]&63)-65536;let o=55296|s>>10&1023;n+=String.fromCharCode(o),s=56320|s&1023}else s=(a&15)<<12|(t[i++]&63)<<6|t[i++]&63;n+=String.fromCharCode(s)}return rb.bytes=r-e,n}function xf(t){return typeof t=="string"?yz(t):t.byteLength}function M6(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):Hv(t)}function K6(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return Hv(e,t,r),Hv.bytes}function Fpe(t,e,r){let n="";for(let i=e;i<r;){let a=t[i++];n+=gz[a]}return n}function lq(t){return t.length>>>1}function Gpe(t,e,r,n){let i=0;for(;r<n;){let a=e.substr(i,2),s=kv[a];if(s===void 0)return;t[r++]=s,i+=2}return t}function Vo(t,e,r,n,i){return r<0&&(n-=r,r=0),n<0&&(n=0),i<0?new Uint8Array(0):r>=e.length||n>=i?0:Jpe(t,e,r,n,i)}function Jpe(t,e,r,n,i){i-n>e.length-r&&(i=n+e.length-r);let a=i-n,s=t.length-n;return a>s&&(a=s),(n!==0||i<t.length)&&(t=new Uint8Array(t.buffer,t.byteOffset+n,a)),e.set(t,r),a}function Fr({bytes:t=0,encode:e,decode:r,encodingLength:n}){return e.bytes=t,r.bytes=t,{encode:e,decode:r,encodingLength:n||(()=>t)}}function e6(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}function UR(t){switch(t.toUpperCase()){case"A":return vz;case"PTR":return Ky;case"CNAME":return Ky;case"DNAME":return Ky;case"TXT":return x2;case"NULL":return E2;case"AAAA":return _2;case"SRV":return A2;case"HINFO":return S2;case"CAA":return gf;case"NS":return b2;case"SOA":return P2;case"MX":return k2;case"OPT":return wf;case"DNSKEY":return Sd;case"RRSIG":return _v;case"RP":return Tv;case"NSEC":return Iv;case"NSEC3":return Dv;case"SSHFP":return Oy;case"DS":return Rv}return v2}function q2(t,e){if(t.questions)throw new Error("Only one .question object expected instead of a .questions array!");let r=Object.assign({type:e},t);return r.question&&(r.questions=[r.question],delete r.question),r}function bz(t){let e=G2(t),r=new Uint8Array(2+e.byteLength);return st(r,e.byteLength),Vo(e,r,2,0,e.length),bz.bytes=r.byteLength,r}function Pz(t){let e=Ut(t,0);if(t.byteLength<e+2)return null;let r=t6(t.slice(2));return Pz.bytes=t6.bytes,r}function jy(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function Cv(t,e,r,n){for(let i=0;i<t.length;i++)e.encode(t[i],r,n),n+=e.encode.bytes;return n}function u2(t,e,r,n){for(let i=0;i<t.length;i++)t[i]=e.decode(r,n),n+=e.decode.bytes;return n}function xz(t,e){let r=it.uint8Array(t).toBase32Z();return new URL(r,e).href}async function the({gatewayUri:t,publicKeyBytes:e}){let r=it.uint8Array(e).toBase32Z(),n=xz(e,t),i;try{if(i=await fetch(n,{method:"GET",signal:AbortSignal.timeout(3e4)}),!i.ok)throw new rt("notFound",`Pkarr record not found for: ${r}`)}catch(s){throw s instanceof rt?s:new rt("internalError",`Failed to fetch Pkarr record: ${s.message}`)}let a=await i.arrayBuffer();if(!a)throw new rt("notFound",`Pkarr record not found for: ${r}`);if(a.byteLength<72)throw new rt("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${a.byteLength}`);if(a.byteLength>1072)throw new rt("invalidDidDocumentLength",`Pkarr response exceeds 1000 byte limit: ${a.byteLength}`);return{k:e,seq:Number(new DataView(a).getBigUint64(64)),sig:new Uint8Array(a,0,64),v:new Uint8Array(a,72)}}async function rhe({gatewayUri:t,bep44Message:e}){let r=it.uint8Array(e.k).toBase32Z(),n=xz(e.k,t),i=new Uint8Array(e.v.length+72);i.set(e.sig,0),new DataView(i.buffer).setBigUint64(e.sig.length,BigInt(e.seq)),i.set(e.v,e.sig.length+8);let a;try{a=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:i,signal:AbortSignal.timeout(3e4)})}catch(s){throw new rt("internalError",`Failed to put Pkarr record for identifier ${r}: ${s.message}`)}return a.ok}async function nhe({dnsPacket:t,publicKeyBytes:e,signer:r}){let n=Math.ceil(Date.now()/1e3),i=G2(t),a=fz.encode({seq:n,v:i}).subarray(1,-1);if(a.length>1e3)throw new rt("invalidDidDocumentLength",`DNS packet exceeds the 1000 byte maximum size: ${a.length} bytes`);let s=await r.sign({data:new Uint8Array(a)});return{k:e,seq:n,sig:s,v:i}}async function ihe({bep44Message:t}){let e=await Qi.bytesToPublicKey({publicKeyBytes:t.k}),r=fz.encode({seq:t.seq,v:t.v}).subarray(1,-1);if(!await Qi.verify({key:e,signature:t.sig,data:new Uint8Array(r)}))throw new rt("invalidSignature","Invalid signature for DHT BEP44 message");return t6(t.v)}async function Sz({didUri:t}){let e=N6({didUri:t});return await Qi.bytesToPublicKey({publicKeyBytes:e})}function N6({didUri:t}){let e=Fn.parse(t);if(!e)throw new rt("invalidDid",`Invalid DID URI: ${t}`);if(e.method!==Ez)throw new rt("methodNotSupported",`Method not supported: ${e.method}`);let r;try{r=it.base32Z(e.id).toUint8Array()}catch{throw new rt("invalidPublicKey","Failed to decode method-specific identifier")}if(r.length!==32)throw new rt("invalidPublicKeyLength",`Invalid public key length: ${r.length}`);return r}async function she({identityKey:t}){let e=await Qi.publicKeyToBytes({publicKey:t}),r=it.uint8Array(e).toBase32Z();return`did:${Ez}:${r}`}function U6(t){let e={Ed25519:Qi,"P-256":{publicKeyToBytes:async({publicKey:r})=>{let n=await ws.publicKeyToBytes({publicKey:r});return await ws.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:ws.bytesToPublicKey,privateKeyToBytes:ws.privateKeyToBytes,bytesToPrivateKey:ws.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:r})=>{let n=await Xi.publicKeyToBytes({publicKey:r});return await Xi.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:Xi.bytesToPublicKey,privateKeyToBytes:Xi.privateKeyToBytes,bytesToPrivateKey:Xi.bytesToPrivateKey},X25519:Dy}[t];if(!e)throw new rt("invalidPublicKeyType",`Unsupported curve: ${t}`);return e}async function Az({newDid:t,previousDidProof:e}){let r=await Sz({didUri:e.previousDid}),n=N6({didUri:t}),i=it.base64Url(e.signature).toUint8Array();if(!await Qi.verify({key:r,data:n,signature:i}))throw new rt("invalidPreviousDidProof","The previous DID proof is invalid.")}function Vv(t){if(typeof t=="string")return t;if(t instanceof Uint8Array)return it.uint8Array(t).toString();if(Array.isArray(t))return t.map(e=>Vv(e)).join("");throw new rt("internalError","Pkarr returned DNS TXT record with invalid data type")}function $v(t){return Vv(t).split(T2).reduce((e,r)=>{let[n,i]=r.split("=");return e[n]=i,e},{})}function Tz(t){if(t.length<=255)return t;let e=[];for(let r=0;r<t.length;r+=255)e.push(t.slice(r,r+255));return e}async function ahe({didUri:t,dnsPacket:e}){let r={id:t},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=Vv(a.data);r.alsoKnownAs=o.split(Fs);break}case s.startsWith("cnt"):{let o=Vv(a.data);r.controller=o.includes(Fs)?o.split(Fs):o;break}case s.startsWith("k"):{let{id:o,t:d,k:l,c,a:u}=$v(a.data),f=it.base64Url(l).toUint8Array(),h=O6[Number(d)],p=await U6(h).bytesToPublicKey({publicKeyBytes:f});p.alg=u||_z[Number(d)];let m=s==="k0"?"0":o!==void 0?o:await Ar({jwk:p});r.verificationMethod??=[];let y=`${t}#${m}`;r.verificationMethod.push({id:y,type:"JsonWebKey",controller:c??t,publicKeyJwk:p}),i.set(s,y);break}case s.startsWith("s"):{let{id:o,t:d,se:l,...c}=$v(a.data),u=l.includes(Fs)?l.split(Fs):[l],f=Object.fromEntries(Object.entries(c).map(([h,p])=>[h,p.includes(Fs)?p.split(Fs):p]));r.service??=[],r.service.push({...f,id:`${t}#${o}`,type:d,serviceEndpoint:u});break}case s.startsWith("typ"):{let{id:o}=$v(a.data);n.types=o.split(Fs).map(d=>Number(d));break}case s.startsWith("did"):{let o=h=>h.split(Fs).map(p=>i.get(p)).filter(p=>typeof p=="string"),{auth:d,asm:l,del:c,inv:u,agm:f}=$v(a.data);d&&(r.authentication=o(d)),l&&(r.assertionMethod=o(l)),c&&(r.capabilityDelegation=o(c)),u&&(r.capabilityInvocation=o(u)),f&&(r.keyAgreement=o(f));break}}}return{didDocument:r,didDocumentMetadata:n,didResolutionMetadata:{}}}async function che({didDocument:t,didMetadata:e,authoritativeGatewayUris:r,previousDidProof:n}){let i=[],a=[],s=new Map,o=[],d=[];if(n!==void 0){let{signature:c,previousDid:u}=n;await Az({newDid:t.id,previousDidProof:n}),i.push({type:"TXT",name:"_prv._did.",ttl:pf,data:`id=${u};s=${c}`})}if(t.alsoKnownAs&&i.push({type:"TXT",name:"_aka._did.",ttl:pf,data:t.alsoKnownAs.join(Fs)}),t.controller){let c=Array.isArray(t.controller)?t.controller.join(Fs):t.controller;i.push({type:"TXT",name:"_cnt._did.",ttl:pf,data:c})}for(let[c,u]of t.verificationMethod?.entries()??[]){let f=`k${c}`;d.push(f);let h=u.id.split("#").pop();s.set(h,f);let p=u.publicKeyJwk;if(!(p?.crv&&p.crv in kz))throw new rt("invalidPublicKeyType",`Verification method '${u.id}' contains an unsupported key type: ${p?.crv??"undefined"}`);let m=O6[p.crv],y=await U6(p.crv).publicKeyToBytes({publicKey:p}),b=it.uint8Array(y).toBase64Url(),w=[`t=${m}`,`k=${b}`];h!=="0"&&await Ar({jwk:p})!==h&&w.unshift(`id=${h}`),p.alg!==_z[m]&&w.push(`a=${p.alg}`),u.controller!==t.id&&w.push(`c=${u.controller}`),i.push({type:"TXT",name:`_${f}._did.`,ttl:pf,data:w.join(T2)})}t.service?.forEach((c,u)=>{let f=`s${u}`;o.push(f);let{id:h,type:p,serviceEndpoint:m,...y}=c;h=Gs(h),m=Array.isArray(m)?m.join(","):m;let b=Object.entries({id:h,t:p,se:m,...y}).map(([S,k])=>`${S}=${k}`).join(T2),w=Tz(b);i.push({type:"TXT",name:`_${f}._did.`,ttl:pf,data:w})});let l=[`v=${ohe}`];if(d.length&&l.push(`vm=${d.join(Fs)}`),Object.keys(J2).forEach(c=>{let u=t[c]?.map(f=>s.get(f.split("#").pop()));if(u){let f=iz[c];l.push(`${f}=${u.join(Fs)}`)}}),o.length&&l.push(`svc=${o.join(Fs)}`),e.types?.length){let c=e.types.map(u=>typeof u=="string"?nz[u]:u);i.push({type:"TXT",name:"_typ._did.",ttl:pf,data:`id=${c.join(Fs)}`})}i.push({type:"TXT",name:"_did."+pq(t.id)+".",ttl:pf,data:l.join(T2)});for(let c of r||[])a.push({type:"NS",name:"_did."+pq(t.id)+".",ttl:pf,data:c+"."});return{id:0,type:"response",flags:Qpe,answers:[...i,...a]}}function pq(t){return t.split(":")[2]}function Rz(t,e,r){e=e||[],r=r||0;for(var n=r;t>=xhe;)e[r++]=t&255|gq,t/=128;for(;t&Phe;)e[r++]=t&255|gq,t>>>=7;return e[r]=t|0,Rz.bytes=r-n+1,e}function s6(t,n){var r=0,n=n||0,i=0,a=n,s,o=t.length;do{if(a>=o)throw s6.bytes=0,new RangeError("Could not decode varint");s=t[a++],r+=i<28?(s&wq)<<i:(s&wq)*Math.pow(2,i),i+=7}while(s>=She);return s6.bytes=a-n,r}function Zhe(t){t=V6(t);let e=Uy+8;(t.length<e||t.length>1024)&&Si("expected proper params");let r=et(aE(t),H6-1n)+1n;return J6(r)}function ome(t){let e=t.toLowerCase();if(e==="localhost"||e==="localhost.")return!0;let r=e.split(".");if(r.length===4){let i=r.map(Number);if(i.every(a=>!Number.isNaN(a)&&a>=0&&a<=255)){let[a,s]=i;if(a===10||a===172&&s>=16&&s<=31||a===192&&s===168||a===127||a===169&&s===254||a===0)return!0}}let n=e;return n.startsWith("[")&&n.endsWith("]")&&(n=n.slice(1,-1)),!!(n.includes(":")&&(n==="::1"||n==="::"||n==="::0"||n.startsWith("fe80:")||n.startsWith("fe80%")||n.startsWith("fc")||n.startsWith("fd")))}var Gce,l6,Hce,Vce,Wce,Jce,Qt,u6,Zce,ph,Yce,Xce,Td,Qce,ede,f6,qq,zq,Fq,tde,rde,nde,ide,W2,p6,oh,sde,ode,Gq,ade,cde,Hq,dde,lde,ude,A9,Vq,fde,Wq,Jq,pde,hde,mde,Zq,yde,gde,Yq,J2,Ai,Zi,Fn,rt,wde,$a,fo,vde,Pde,xde,Ede,oNe,Sde,h6,Ade,kde,_de,t7,Tde,r7,n7,Ide,Dde,Wo,y2,aNe,cNe,dNe,lNe,uNe,fNe,pNe,k9,Ra,hNe,mNe,yNe,_l,gNe,yv,_9,c2,Qp,it,Kv,$de,Bde,Ev,Ode,T9,jde,Mde,Kde,Nde,Ude,I9,Lde,qde,zde,Fde,Gde,Hde,Vde,Wde,Jde,Zde,Yde,Xde,j2,M2,Uv,Lv,Qde,ele,tle,m6,D9,R9,GR,wNe,rle,nle,ile,gv,sle,C9,ole,Oa,vNe,nf,ale,Z2,o7,a7,Y2,cle,dle,Tl,mle,g6,$R,B9,yle,BR,OR,wd,ble,h7,bNe,y7,xle,Ele,Sle,sf,of,Ale,g7,ui,hn,rh,kle,HR,j9,M9,PNe,_le,Dle,Rle,Mle,jR,Nle,Ule,sh,Bl,Da,xNe,K9,ENe,E7,S7,k7,N9,Gle,WR,U9,JR,Fo,SNe,ANe,g2,MR,vd,kNe,Zle,_Ne,eue,tue,rue,nue,af,cf,iue,qv,oue,I7,aue,q9,Wi,due,Xi,D7,lue,uue,fue,Aa,Ji,pue,ws,Il,z9,d2,ZR,mue,yue,gue,wue,vue,bue,Pue,xue,Eue,Sue,Aue,kue,_ue,Iue,Due,Rue,Cue,$ue,Bue,Oue,Nt,jue,Mue,df,lf,Kue,C7,bc,qo,l2,Nue,Uue,wv,KR,zv,F9,TNe,Fue,YR,Gue,G9,Hue,Vue,H9,Ba,Fv,eh,INe,DNe,Sv,Yue,RNe,CNe,$Ne,BNe,ONe,jNe,MNe,KNe,NNe,UNe,ka,Xue,Qi,Dl,Que,efe,tfe,uf,rfe,Dy,vv,nfe,Rl,NR,Ec,ife,sfe,Se,tt,Zv,cfe,dfe,lfe,ufe,Cl,ffe,pfe,hfe,mfe,K7,yfe,xn,N7,Yv,es,A6,U7,W9,Rfe,Kfe,L7,q7,z7,F7,G7,Ta,Pc,je,Nl,dpe,upe,fpe,J9,ff,Pf,LNe,qNe,zNe,FNe,GNe,HNe,VNe,WNe,JNe,ZNe,YNe,XNe,QNe,Y9,vs,Ca,X9,Q9,eUe,tUe,rUe,nUe,eq,tq,rq,nq,B6,bs,eb,nz,O6,iz,iq,sz,sq,vpe,bpe,oq,Ppe,bv,xpe,oz,Epe,Kl,aq,cq,iUe,tE,cz,dz,Spe,Ape,kpe,_pe,Tpe,j6,Ipe,uz,Ope,fz,jpe,Mpe,Ad,bf,fh,kv,gz,Hpe,Vpe,Wpe,Ol,Ut,jl,st,Zpe,uq,QR,Ype,wz,Xpe,Ze,li,Ry,v2,b2,P2,x2,E2,S2,Ky,A2,gf,k2,vz,_2,fq,$l,wf,Sd,_v,Tv,Ho,Iv,Dv,Rv,Oy,Ia,Ny,Qpe,ts,z2,F2,G2,t6,ehe,Ez,ohe,pf,T2,Fs,kz,_z,hq,Iz,po,mq,My,Ln,qn,sUe,dhe,lhe,uhe,fhe,Dz,phe,hhe,mhe,yhe,iE,oUe,aUe,yq,cUe,zy,ghe,n6,Ed,zo,L6,xc,whe,Wv,vhe,gq,bhe,Phe,xhe,Ehe,She,wq,Ahe,khe,_he,The,Ihe,Dhe,Rhe,Che,$he,Bhe,Ohe,jhe,H2,vq,bq,Pq,xq,Mhe,Cz,$z,Khe,Bz,Eq,dUe,Pv,Go,o6,f2,a6,Iy,p2,Oz,Sq,Nhe,Yi,D2,c6,d6,h2,uo,Mz,q6,Fy,Uhe,lt,Aq,kq,Gy,V2,R2,Kz,z6,F6,Lhe,qhe,_q,Nz,bd,zhe,Tq,Fhe,LR,Iq,Ghe,nh,Hhe,Vhe,G6,dh,H6,Uz,Lz,qz,Uy,Dq,Si,sE,zz,qR,Fz,Gz,Jv,V6,et,Rq,Cq,Hy,Nv,C2,Hz,W6,oE,aE,$q,J6,Bq,Oq,Vz,Whe,Jhe,jq,$2,Yhe,ih,Xhe,Qhe,Mq,Kq,xv,eme,tme,Nq,rme,Wz,ho,nme,B2,m2,ime,Uq,Jz,nb,sme,Zz,Yz,ame,cme,cE,dme,dE,lme,Zy,Jo=F(()=>{"use strict";g();Gce=Object.create,l6=Object.defineProperty,Hce=Object.getOwnPropertyDescriptor,Vce=Object.getOwnPropertyNames,Wce=Object.getPrototypeOf,Jce=Object.prototype.hasOwnProperty,Qt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),u6=(t,e)=>{for(var r in e)l6(t,r,{get:e[r],enumerable:!0})},Zce=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Vce(e))!Jce.call(t,i)&&i!==r&&l6(t,i,{get:()=>e[i],enumerable:!(n=Hce(e,i))||n.enumerable});return t},ph=(t,e,r)=>(r=t!=null?Gce(Wce(t)):{},Zce(e||!t||!t.__esModule?l6(r,"default",{value:t,enumerable:!0}):r,t)),Yce=Qt((t,e)=>{var r=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,n=()=>r.now(),i=o=>o&&o===Math.floor(o)&&o>0&&isFinite(o),a=o=>o===1/0||i(o),s=class Lq{constructor({max:d=1/0,ttl:l,updateAgeOnGet:c=!1,checkAgeOnGet:u=!1,noUpdateTTL:f=!1,dispose:h,noDisposeOnSet:p=!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(d))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=l,this.max=d,this.updateAgeOnGet=!!c,this.checkAgeOnGet=!!u,this.noUpdateTTL=!!f,this.noDisposeOnSet=!!p,h!==void 0){if(typeof h!="function")throw new TypeError("dispose must be function if set");this.dispose=h}this.timer=void 0,this.timerExpiration=void 0}setTimer(d,l){if(this.timerExpiration<d)return;this.timer&&clearTimeout(this.timer);let c=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let u in this.expirations){this.setTimer(u,u-n());break}},l);c.unref&&c.unref(),this.timerExpiration=d,this.timer=c}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 d=this.dispose!==Lq.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[l,c]of d)this.dispose(c,l,"delete")}setTTL(d,l=this.ttl){let c=this.expirationMap.get(d);if(c!==void 0){let u=this.expirations[c];!u||u.length<=1?delete this.expirations[c]:this.expirations[c]=u.filter(f=>f!==d)}if(l!==1/0){let u=Math.floor(n()+l);this.expirationMap.set(d,u),this.expirations[u]||(this.expirations[u]=[],this.setTimer(u,l)),this.expirations[u].push(d)}else this.expirationMap.set(d,1/0)}set(d,l,{ttl:c=this.ttl,noUpdateTTL:u=this.noUpdateTTL,noDisposeOnSet:f=this.noDisposeOnSet}={}){if(!a(c))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(d)){u||this.setTTL(d,c);let h=this.data.get(d);h!==l&&(this.data.set(d,l),f||this.dispose(h,d,"set"))}else this.setTTL(d,c),this.data.set(d,l);for(;this.size>this.max;)this.purgeToCapacity();return this}has(d){return this.data.has(d)}getRemainingTTL(d){let l=this.expirationMap.get(d);return l===1/0?l:l!==void 0?Math.max(0,Math.ceil(l-n())):0}get(d,{updateAgeOnGet:l=this.updateAgeOnGet,ttl:c=this.ttl,checkAgeOnGet:u=this.checkAgeOnGet}={}){let f=this.data.get(d);if(u&&this.getRemainingTTL(d)===0){this.delete(d);return}return l&&this.setTTL(d,c),f}dispose(d,l){}delete(d){let l=this.expirationMap.get(d);if(l!==void 0){let c=this.data.get(d);this.data.delete(d),this.expirationMap.delete(d);let u=this.expirations[l];return u&&(u.length<=1?delete this.expirations[l]:this.expirations[l]=u.filter(f=>f!==d)),this.dispose(c,d,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let d in this.expirations){let l=this.expirations[d];if(this.size-l.length>=this.max){delete this.expirations[d];let c=[];for(let u of l)c.push([u,this.data.get(u)]),this.data.delete(u),this.expirationMap.delete(u);for(let[u,f]of c)this.dispose(f,u,"evict")}else{let c=this.size-this.max,u=[];for(let f of l.splice(0,c))u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of u)this.dispose(h,f,"evict");return}}}get size(){return this.data.size}purgeStale(){let d=Math.ceil(n());for(let l in this.expirations){if(l==="Infinity"||l>d)return;let c=[...this.expirations[l]||[]],u=[];delete this.expirations[l];for(let f of c)u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of u)this.dispose(h,f,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let d in this.expirations)for(let l of this.expirations[d])yield[l,this.data.get(l)]}*keys(){for(let d in this.expirations)for(let l of this.expirations[d])yield l}*values(){for(let d in this.expirations)for(let l of this.expirations[d])yield this.data.get(l)}[Symbol.iterator](){return this.entries()}};e.exports=s}),Xce=Qt(t=>{"use strict";t.supports=function(...e){let r=e.reduce((n,i)=>Object.assign(n,i),{});return Object.assign(r,{snapshots:r.snapshots||!1,permanence:r.permanence||!1,seek:r.seek||!1,clear:r.clear||!1,getMany:r.getMany||!1,keyIterator:r.keyIterator||!1,valueIterator:r.valueIterator||!1,iteratorNextv:r.iteratorNextv||!1,iteratorAll:r.iteratorAll||!1,status:r.status||!1,createIfMissing:r.createIfMissing||!1,errorIfExists:r.errorIfExists||!1,deferredOpen:r.deferredOpen||!1,promises:r.promises||!1,streams:r.streams||!1,encodings:Object.assign({},r.encodings),events:Object.assign({},r.events),additionalMethods:Object.assign({},r.additionalMethods)})}}),Td=Qt((t,e)=>{"use strict";e.exports=class extends Error{constructor(r,n){super(r||""),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)}}}),Qce=Qt(t=>{"use strict";t.byteLength=d,t.toByteArray=c,t.fromByteArray=h;var e=[],r=[],n=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(a=0,s=i.length;a<s;++a)e[a]=i[a],r[i.charCodeAt(a)]=a;var a,s;r[45]=62,r[95]=63;function o(p){var m=p.length;if(m%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var y=p.indexOf("=");y===-1&&(y=m);var b=y===m?0:4-y%4;return[y,b]}function d(p){var m=o(p),y=m[0],b=m[1];return(y+b)*3/4-b}function l(p,m,y){return(m+y)*3/4-y}function c(p){var m,y=o(p),b=y[0],w=y[1],S=new n(l(p,b,w)),k=0,T=w>0?b-4:b,D;for(D=0;D<T;D+=4)m=r[p.charCodeAt(D)]<<18|r[p.charCodeAt(D+1)]<<12|r[p.charCodeAt(D+2)]<<6|r[p.charCodeAt(D+3)],S[k++]=m>>16&255,S[k++]=m>>8&255,S[k++]=m&255;return w===2&&(m=r[p.charCodeAt(D)]<<2|r[p.charCodeAt(D+1)]>>4,S[k++]=m&255),w===1&&(m=r[p.charCodeAt(D)]<<10|r[p.charCodeAt(D+1)]<<4|r[p.charCodeAt(D+2)]>>2,S[k++]=m>>8&255,S[k++]=m&255),S}function u(p){return e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63]}function f(p,m,y){for(var b,w=[],S=m;S<y;S+=3)b=(p[S]<<16&16711680)+(p[S+1]<<8&65280)+(p[S+2]&255),w.push(u(b));return w.join("")}function h(p){for(var m,y=p.length,b=y%3,w=[],S=16383,k=0,T=y-b;k<T;k+=S)w.push(f(p,k,k+S>T?T:k+S));return b===1?(m=p[y-1],w.push(e[m>>2]+e[m<<4&63]+"==")):b===2&&(m=(p[y-2]<<8)+p[y-1],w.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),w.join("")}}),ede=Qt(t=>{t.read=function(e,r,n,i,a){var s,o,d=a*8-i-1,l=(1<<d)-1,c=l>>1,u=-7,f=n?a-1:0,h=n?-1:1,p=e[r+f];for(f+=h,s=p&(1<<-u)-1,p>>=-u,u+=d;u>0;s=s*256+e[r+f],f+=h,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=i;u>0;o=o*256+e[r+f],f+=h,u-=8);if(s===0)s=1-c;else{if(s===l)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,i),s=s-c}return(p?-1:1)*o*Math.pow(2,s-i)},t.write=function(e,r,n,i,a,s){var o,d,l,c=s*8-a-1,u=(1<<c)-1,f=u>>1,h=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=i?0:s-1,m=i?1:-1,y=r<0||r===0&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(d=isNaN(r)?1:0,o=u):(o=Math.floor(Math.log(r)/Math.LN2),r*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+f>=1?r+=h/l:r+=h*Math.pow(2,1-f),r*l>=2&&(o++,l/=2),o+f>=u?(d=0,o=u):o+f>=1?(d=(r*l-1)*Math.pow(2,a),o=o+f):(d=r*Math.pow(2,f-1)*Math.pow(2,a),o=0));a>=8;e[n+p]=d&255,p+=m,d/=256,a-=8);for(o=o<<a|d,c+=a;c>0;e[n+p]=o&255,p+=m,o/=256,c-=8);e[n+p-m]|=y*128}}),f6=Qt(t=>{"use strict";var e=Qce(),r=ede(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=o,t.SlowBuffer=w,t.INSPECT_MAX_BYTES=50;var i=2147483647;t.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 _=new Uint8Array(1),O={foo:function(){return 42}};return Object.setPrototypeOf(O,Uint8Array.prototype),Object.setPrototypeOf(_,O),_.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(_){if(_>i)throw new RangeError('The value "'+_+'" is invalid for option "size"');let O=new Uint8Array(_);return Object.setPrototypeOf(O,o.prototype),O}function o(_,O,U){if(typeof _=="number"){if(typeof O=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(_)}return d(_,O,U)}o.poolSize=8192;function d(_,O,U){if(typeof _=="string")return f(_,O);if(ArrayBuffer.isView(_))return p(_);if(_==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _);if(ke(_,ArrayBuffer)||_&&ke(_.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ke(_,SharedArrayBuffer)||_&&ke(_.buffer,SharedArrayBuffer)))return m(_,O,U);if(typeof _=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let te=_.valueOf&&_.valueOf();if(te!=null&&te!==_)return o.from(te,O,U);let ce=y(_);if(ce)return ce;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof _[Symbol.toPrimitive]=="function")return o.from(_[Symbol.toPrimitive]("string"),O,U);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _)}o.from=function(_,O,U){return d(_,O,U)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function l(_){if(typeof _!="number")throw new TypeError('"size" argument must be of type number');if(_<0)throw new RangeError('The value "'+_+'" is invalid for option "size"')}function c(_,O,U){return l(_),_<=0?s(_):O!==void 0?typeof U=="string"?s(_).fill(O,U):s(_).fill(O):s(_)}o.alloc=function(_,O,U){return c(_,O,U)};function u(_){return l(_),s(_<0?0:b(_)|0)}o.allocUnsafe=function(_){return u(_)},o.allocUnsafeSlow=function(_){return u(_)};function f(_,O){if((typeof O!="string"||O==="")&&(O="utf8"),!o.isEncoding(O))throw new TypeError("Unknown encoding: "+O);let U=S(_,O)|0,te=s(U),ce=te.write(_,O);return ce!==U&&(te=te.slice(0,ce)),te}function h(_){let O=_.length<0?0:b(_.length)|0,U=s(O);for(let te=0;te<O;te+=1)U[te]=_[te]&255;return U}function p(_){if(ke(_,Uint8Array)){let O=new Uint8Array(_);return m(O.buffer,O.byteOffset,O.byteLength)}return h(_)}function m(_,O,U){if(O<0||_.byteLength<O)throw new RangeError('"offset" is outside of buffer bounds');if(_.byteLength<O+(U||0))throw new RangeError('"length" is outside of buffer bounds');let te;return O===void 0&&U===void 0?te=new Uint8Array(_):U===void 0?te=new Uint8Array(_,O):te=new Uint8Array(_,O,U),Object.setPrototypeOf(te,o.prototype),te}function y(_){if(o.isBuffer(_)){let O=b(_.length)|0,U=s(O);return U.length===0||_.copy(U,0,0,O),U}if(_.length!==void 0)return typeof _.length!="number"||ot(_.length)?s(0):h(_);if(_.type==="Buffer"&&Array.isArray(_.data))return h(_.data)}function b(_){if(_>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return _|0}function w(_){return+_!=_&&(_=0),o.alloc(+_)}o.isBuffer=function(_){return _!=null&&_._isBuffer===!0&&_!==o.prototype},o.compare=function(_,O){if(ke(_,Uint8Array)&&(_=o.from(_,_.offset,_.byteLength)),ke(O,Uint8Array)&&(O=o.from(O,O.offset,O.byteLength)),!o.isBuffer(_)||!o.isBuffer(O))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(_===O)return 0;let U=_.length,te=O.length;for(let ce=0,me=Math.min(U,te);ce<me;++ce)if(_[ce]!==O[ce]){U=_[ce],te=O[ce];break}return U<te?-1:te<U?1:0},o.isEncoding=function(_){switch(String(_).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(_,O){if(!Array.isArray(_))throw new TypeError('"list" argument must be an Array of Buffers');if(_.length===0)return o.alloc(0);let U;if(O===void 0)for(O=0,U=0;U<_.length;++U)O+=_[U].length;let te=o.allocUnsafe(O),ce=0;for(U=0;U<_.length;++U){let me=_[U];if(ke(me,Uint8Array))ce+me.length>te.length?(o.isBuffer(me)||(me=o.from(me)),me.copy(te,ce)):Uint8Array.prototype.set.call(te,me,ce);else if(o.isBuffer(me))me.copy(te,ce);else throw new TypeError('"list" argument must be an Array of Buffers');ce+=me.length}return te};function S(_,O){if(o.isBuffer(_))return _.length;if(ArrayBuffer.isView(_)||ke(_,ArrayBuffer))return _.byteLength;if(typeof _!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof _);let U=_.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&U===0)return 0;let ce=!1;for(;;)switch(O){case"ascii":case"latin1":case"binary":return U;case"utf8":case"utf-8":return Pe(_).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U*2;case"hex":return U>>>1;case"base64":return Je(_).length;default:if(ce)return te?-1:Pe(_).length;O=(""+O).toLowerCase(),ce=!0}}o.byteLength=S;function k(_,O,U){let te=!1;if((O===void 0||O<0)&&(O=0),O>this.length||((U===void 0||U>this.length)&&(U=this.length),U<=0)||(U>>>=0,O>>>=0,U<=O))return"";for(_||(_="utf8");;)switch(_){case"hex":return A(this,O,U);case"utf8":case"utf-8":return R(this,O,U);case"ascii":return E(this,O,U);case"latin1":case"binary":return x(this,O,U);case"base64":return ee(this,O,U);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,O,U);default:if(te)throw new TypeError("Unknown encoding: "+_);_=(_+"").toLowerCase(),te=!0}}o.prototype._isBuffer=!0;function T(_,O,U){let te=_[O];_[O]=_[U],_[U]=te}o.prototype.swap16=function(){let _=this.length;if(_%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let O=0;O<_;O+=2)T(this,O,O+1);return this},o.prototype.swap32=function(){let _=this.length;if(_%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let O=0;O<_;O+=4)T(this,O,O+3),T(this,O+1,O+2);return this},o.prototype.swap64=function(){let _=this.length;if(_%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let O=0;O<_;O+=8)T(this,O,O+7),T(this,O+1,O+6),T(this,O+2,O+5),T(this,O+3,O+4);return this},o.prototype.toString=function(){let _=this.length;return _===0?"":arguments.length===0?R(this,0,_):k.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(_){if(!o.isBuffer(_))throw new TypeError("Argument must be a Buffer");return this===_?!0:o.compare(this,_)===0},o.prototype.inspect=function(){let _="",O=t.INSPECT_MAX_BYTES;return _=this.toString("hex",0,O).replace(/(.{2})/g,"$1 ").trim(),this.length>O&&(_+=" ... "),"<Buffer "+_+">"},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(_,O,U,te,ce){if(ke(_,Uint8Array)&&(_=o.from(_,_.offset,_.byteLength)),!o.isBuffer(_))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof _);if(O===void 0&&(O=0),U===void 0&&(U=_?_.length:0),te===void 0&&(te=0),ce===void 0&&(ce=this.length),O<0||U>_.length||te<0||ce>this.length)throw new RangeError("out of range index");if(te>=ce&&O>=U)return 0;if(te>=ce)return-1;if(O>=U)return 1;if(O>>>=0,U>>>=0,te>>>=0,ce>>>=0,this===_)return 0;let me=ce-te,Ae=U-O,Ft=Math.min(me,Ae),Xn=this.slice(te,ce),Gr=_.slice(O,U);for(let kr=0;kr<Ft;++kr)if(Xn[kr]!==Gr[kr]){me=Xn[kr],Ae=Gr[kr];break}return me<Ae?-1:Ae<me?1:0};function D(_,O,U,te,ce){if(_.length===0)return-1;if(typeof U=="string"?(te=U,U=0):U>2147483647?U=2147483647:U<-2147483648&&(U=-2147483648),U=+U,ot(U)&&(U=ce?0:_.length-1),U<0&&(U=_.length+U),U>=_.length){if(ce)return-1;U=_.length-1}else if(U<0)if(ce)U=0;else return-1;if(typeof O=="string"&&(O=o.from(O,te)),o.isBuffer(O))return O.length===0?-1:K(_,O,U,te,ce);if(typeof O=="number")return O=O&255,typeof Uint8Array.prototype.indexOf=="function"?ce?Uint8Array.prototype.indexOf.call(_,O,U):Uint8Array.prototype.lastIndexOf.call(_,O,U):K(_,[O],U,te,ce);throw new TypeError("val must be string, number or Buffer")}function K(_,O,U,te,ce){let me=1,Ae=_.length,Ft=O.length;if(te!==void 0&&(te=String(te).toLowerCase(),te==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(_.length<2||O.length<2)return-1;me=2,Ae/=2,Ft/=2,U/=2}function Xn(kr,yr){return me===1?kr[yr]:kr.readUInt16BE(yr*me)}let Gr;if(ce){let kr=-1;for(Gr=U;Gr<Ae;Gr++)if(Xn(_,Gr)===Xn(O,kr===-1?0:Gr-kr)){if(kr===-1&&(kr=Gr),Gr-kr+1===Ft)return kr*me}else kr!==-1&&(Gr-=Gr-kr),kr=-1}else for(U+Ft>Ae&&(U=Ae-Ft),Gr=U;Gr>=0;Gr--){let kr=!0;for(let yr=0;yr<Ft;yr++)if(Xn(_,Gr+yr)!==Xn(O,yr)){kr=!1;break}if(kr)return Gr}return-1}o.prototype.includes=function(_,O,U){return this.indexOf(_,O,U)!==-1},o.prototype.indexOf=function(_,O,U){return D(this,_,O,U,!0)},o.prototype.lastIndexOf=function(_,O,U){return D(this,_,O,U,!1)};function C(_,O,U,te){U=Number(U)||0;let ce=_.length-U;te?(te=Number(te),te>ce&&(te=ce)):te=ce;let me=O.length;te>me/2&&(te=me/2);let Ae;for(Ae=0;Ae<te;++Ae){let Ft=parseInt(O.substr(Ae*2,2),16);if(ot(Ft))return Ae;_[U+Ae]=Ft}return Ae}function G(_,O,U,te){return Ct(Pe(O,_.length-U),_,U,te)}function z(_,O,U,te){return Ct(Ne(O),_,U,te)}function N(_,O,U,te){return Ct(Je(O),_,U,te)}function V(_,O,U,te){return Ct(He(O,_.length-U),_,U,te)}o.prototype.write=function(_,O,U,te){if(O===void 0)te="utf8",U=this.length,O=0;else if(U===void 0&&typeof O=="string")te=O,U=this.length,O=0;else if(isFinite(O))O=O>>>0,isFinite(U)?(U=U>>>0,te===void 0&&(te="utf8")):(te=U,U=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let ce=this.length-O;if((U===void 0||U>ce)&&(U=ce),_.length>0&&(U<0||O<0)||O>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");let me=!1;for(;;)switch(te){case"hex":return C(this,_,O,U);case"utf8":case"utf-8":return G(this,_,O,U);case"ascii":case"latin1":case"binary":return z(this,_,O,U);case"base64":return N(this,_,O,U);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,_,O,U);default:if(me)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),me=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ee(_,O,U){return O===0&&U===_.length?e.fromByteArray(_):e.fromByteArray(_.slice(O,U))}function R(_,O,U){U=Math.min(_.length,U);let te=[],ce=O;for(;ce<U;){let me=_[ce],Ae=null,Ft=me>239?4:me>223?3:me>191?2:1;if(ce+Ft<=U){let Xn,Gr,kr,yr;switch(Ft){case 1:me<128&&(Ae=me);break;case 2:Xn=_[ce+1],(Xn&192)===128&&(yr=(me&31)<<6|Xn&63,yr>127&&(Ae=yr));break;case 3:Xn=_[ce+1],Gr=_[ce+2],(Xn&192)===128&&(Gr&192)===128&&(yr=(me&15)<<12|(Xn&63)<<6|Gr&63,yr>2047&&(yr<55296||yr>57343)&&(Ae=yr));break;case 4:Xn=_[ce+1],Gr=_[ce+2],kr=_[ce+3],(Xn&192)===128&&(Gr&192)===128&&(kr&192)===128&&(yr=(me&15)<<18|(Xn&63)<<12|(Gr&63)<<6|kr&63,yr>65535&&yr<1114112&&(Ae=yr))}}Ae===null?(Ae=65533,Ft=1):Ae>65535&&(Ae-=65536,te.push(Ae>>>10&1023|55296),Ae=56320|Ae&1023),te.push(Ae),ce+=Ft}return P(te)}var B=4096;function P(_){let O=_.length;if(O<=B)return String.fromCharCode.apply(String,_);let U="",te=0;for(;te<O;)U+=String.fromCharCode.apply(String,_.slice(te,te+=B));return U}function E(_,O,U){let te="";U=Math.min(_.length,U);for(let ce=O;ce<U;++ce)te+=String.fromCharCode(_[ce]&127);return te}function x(_,O,U){let te="";U=Math.min(_.length,U);for(let ce=O;ce<U;++ce)te+=String.fromCharCode(_[ce]);return te}function A(_,O,U){let te=_.length;(!O||O<0)&&(O=0),(!U||U<0||U>te)&&(U=te);let ce="";for(let me=O;me<U;++me)ce+=_t[_[me]];return ce}function I(_,O,U){let te=_.slice(O,U),ce="";for(let me=0;me<te.length-1;me+=2)ce+=String.fromCharCode(te[me]+te[me+1]*256);return ce}o.prototype.slice=function(_,O){let U=this.length;_=~~_,O=O===void 0?U:~~O,_<0?(_+=U,_<0&&(_=0)):_>U&&(_=U),O<0?(O+=U,O<0&&(O=0)):O>U&&(O=U),O<_&&(O=_);let te=this.subarray(_,O);return Object.setPrototypeOf(te,o.prototype),te};function M(_,O,U){if(_%1!==0||_<0)throw new RangeError("offset is not uint");if(_+O>U)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(_,O,U){_=_>>>0,O=O>>>0,U||M(_,O,this.length);let te=this[_],ce=1,me=0;for(;++me<O&&(ce*=256);)te+=this[_+me]*ce;return te},o.prototype.readUintBE=o.prototype.readUIntBE=function(_,O,U){_=_>>>0,O=O>>>0,U||M(_,O,this.length);let te=this[_+--O],ce=1;for(;O>0&&(ce*=256);)te+=this[_+--O]*ce;return te},o.prototype.readUint8=o.prototype.readUInt8=function(_,O){return _=_>>>0,O||M(_,1,this.length),this[_]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(_,O){return _=_>>>0,O||M(_,2,this.length),this[_]|this[_+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(_,O){return _=_>>>0,O||M(_,2,this.length),this[_]<<8|this[_+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(_,O){return _=_>>>0,O||M(_,4,this.length),(this[_]|this[_+1]<<8|this[_+2]<<16)+this[_+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(_,O){return _=_>>>0,O||M(_,4,this.length),this[_]*16777216+(this[_+1]<<16|this[_+2]<<8|this[_+3])},o.prototype.readBigUInt64LE=Rt(function(_){_=_>>>0,ue(_,"offset");let O=this[_],U=this[_+7];(O===void 0||U===void 0)&&pe(_,this.length-8);let te=O+this[++_]*2**8+this[++_]*2**16+this[++_]*2**24,ce=this[++_]+this[++_]*2**8+this[++_]*2**16+U*2**24;return BigInt(te)+(BigInt(ce)<<BigInt(32))}),o.prototype.readBigUInt64BE=Rt(function(_){_=_>>>0,ue(_,"offset");let O=this[_],U=this[_+7];(O===void 0||U===void 0)&&pe(_,this.length-8);let te=O*2**24+this[++_]*2**16+this[++_]*2**8+this[++_],ce=this[++_]*2**24+this[++_]*2**16+this[++_]*2**8+U;return(BigInt(te)<<BigInt(32))+BigInt(ce)}),o.prototype.readIntLE=function(_,O,U){_=_>>>0,O=O>>>0,U||M(_,O,this.length);let te=this[_],ce=1,me=0;for(;++me<O&&(ce*=256);)te+=this[_+me]*ce;return ce*=128,te>=ce&&(te-=Math.pow(2,8*O)),te},o.prototype.readIntBE=function(_,O,U){_=_>>>0,O=O>>>0,U||M(_,O,this.length);let te=O,ce=1,me=this[_+--te];for(;te>0&&(ce*=256);)me+=this[_+--te]*ce;return ce*=128,me>=ce&&(me-=Math.pow(2,8*O)),me},o.prototype.readInt8=function(_,O){return _=_>>>0,O||M(_,1,this.length),this[_]&128?(255-this[_]+1)*-1:this[_]},o.prototype.readInt16LE=function(_,O){_=_>>>0,O||M(_,2,this.length);let U=this[_]|this[_+1]<<8;return U&32768?U|4294901760:U},o.prototype.readInt16BE=function(_,O){_=_>>>0,O||M(_,2,this.length);let U=this[_+1]|this[_]<<8;return U&32768?U|4294901760:U},o.prototype.readInt32LE=function(_,O){return _=_>>>0,O||M(_,4,this.length),this[_]|this[_+1]<<8|this[_+2]<<16|this[_+3]<<24},o.prototype.readInt32BE=function(_,O){return _=_>>>0,O||M(_,4,this.length),this[_]<<24|this[_+1]<<16|this[_+2]<<8|this[_+3]},o.prototype.readBigInt64LE=Rt(function(_){_=_>>>0,ue(_,"offset");let O=this[_],U=this[_+7];(O===void 0||U===void 0)&&pe(_,this.length-8);let te=this[_+4]+this[_+5]*2**8+this[_+6]*2**16+(U<<24);return(BigInt(te)<<BigInt(32))+BigInt(O+this[++_]*2**8+this[++_]*2**16+this[++_]*2**24)}),o.prototype.readBigInt64BE=Rt(function(_){_=_>>>0,ue(_,"offset");let O=this[_],U=this[_+7];(O===void 0||U===void 0)&&pe(_,this.length-8);let te=(O<<24)+this[++_]*2**16+this[++_]*2**8+this[++_];return(BigInt(te)<<BigInt(32))+BigInt(this[++_]*2**24+this[++_]*2**16+this[++_]*2**8+U)}),o.prototype.readFloatLE=function(_,O){return _=_>>>0,O||M(_,4,this.length),r.read(this,_,!0,23,4)},o.prototype.readFloatBE=function(_,O){return _=_>>>0,O||M(_,4,this.length),r.read(this,_,!1,23,4)},o.prototype.readDoubleLE=function(_,O){return _=_>>>0,O||M(_,8,this.length),r.read(this,_,!0,52,8)},o.prototype.readDoubleBE=function(_,O){return _=_>>>0,O||M(_,8,this.length),r.read(this,_,!1,52,8)};function q(_,O,U,te,ce,me){if(!o.isBuffer(_))throw new TypeError('"buffer" argument must be a Buffer instance');if(O>ce||O<me)throw new RangeError('"value" argument is out of bounds');if(U+te>_.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(_,O,U,te){if(_=+_,O=O>>>0,U=U>>>0,!te){let Ae=Math.pow(2,8*U)-1;q(this,_,O,U,Ae,0)}let ce=1,me=0;for(this[O]=_&255;++me<U&&(ce*=256);)this[O+me]=_/ce&255;return O+U},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(_,O,U,te){if(_=+_,O=O>>>0,U=U>>>0,!te){let Ae=Math.pow(2,8*U)-1;q(this,_,O,U,Ae,0)}let ce=U-1,me=1;for(this[O+ce]=_&255;--ce>=0&&(me*=256);)this[O+ce]=_/me&255;return O+U},o.prototype.writeUint8=o.prototype.writeUInt8=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,1,255,0),this[O]=_&255,O+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,2,65535,0),this[O]=_&255,this[O+1]=_>>>8,O+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,2,65535,0),this[O]=_>>>8,this[O+1]=_&255,O+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,4,4294967295,0),this[O+3]=_>>>24,this[O+2]=_>>>16,this[O+1]=_>>>8,this[O]=_&255,O+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,4,4294967295,0),this[O]=_>>>24,this[O+1]=_>>>16,this[O+2]=_>>>8,this[O+3]=_&255,O+4};function H(_,O,U,te,ce){le(O,te,ce,_,U,7);let me=Number(O&BigInt(4294967295));_[U++]=me,me=me>>8,_[U++]=me,me=me>>8,_[U++]=me,me=me>>8,_[U++]=me;let Ae=Number(O>>BigInt(32)&BigInt(4294967295));return _[U++]=Ae,Ae=Ae>>8,_[U++]=Ae,Ae=Ae>>8,_[U++]=Ae,Ae=Ae>>8,_[U++]=Ae,U}function W(_,O,U,te,ce){le(O,te,ce,_,U,7);let me=Number(O&BigInt(4294967295));_[U+7]=me,me=me>>8,_[U+6]=me,me=me>>8,_[U+5]=me,me=me>>8,_[U+4]=me;let Ae=Number(O>>BigInt(32)&BigInt(4294967295));return _[U+3]=Ae,Ae=Ae>>8,_[U+2]=Ae,Ae=Ae>>8,_[U+1]=Ae,Ae=Ae>>8,_[U]=Ae,U+8}o.prototype.writeBigUInt64LE=Rt(function(_,O=0){return H(this,_,O,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=Rt(function(_,O=0){return W(this,_,O,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(_,O,U,te){if(_=+_,O=O>>>0,!te){let Ft=Math.pow(2,8*U-1);q(this,_,O,U,Ft-1,-Ft)}let ce=0,me=1,Ae=0;for(this[O]=_&255;++ce<U&&(me*=256);)_<0&&Ae===0&&this[O+ce-1]!==0&&(Ae=1),this[O+ce]=(_/me>>0)-Ae&255;return O+U},o.prototype.writeIntBE=function(_,O,U,te){if(_=+_,O=O>>>0,!te){let Ft=Math.pow(2,8*U-1);q(this,_,O,U,Ft-1,-Ft)}let ce=U-1,me=1,Ae=0;for(this[O+ce]=_&255;--ce>=0&&(me*=256);)_<0&&Ae===0&&this[O+ce+1]!==0&&(Ae=1),this[O+ce]=(_/me>>0)-Ae&255;return O+U},o.prototype.writeInt8=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,1,127,-128),_<0&&(_=255+_+1),this[O]=_&255,O+1},o.prototype.writeInt16LE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,2,32767,-32768),this[O]=_&255,this[O+1]=_>>>8,O+2},o.prototype.writeInt16BE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,2,32767,-32768),this[O]=_>>>8,this[O+1]=_&255,O+2},o.prototype.writeInt32LE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,4,2147483647,-2147483648),this[O]=_&255,this[O+1]=_>>>8,this[O+2]=_>>>16,this[O+3]=_>>>24,O+4},o.prototype.writeInt32BE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,4,2147483647,-2147483648),_<0&&(_=4294967295+_+1),this[O]=_>>>24,this[O+1]=_>>>16,this[O+2]=_>>>8,this[O+3]=_&255,O+4},o.prototype.writeBigInt64LE=Rt(function(_,O=0){return H(this,_,O,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=Rt(function(_,O=0){return W(this,_,O,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function J(_,O,U,te,ce,me){if(U+te>_.length)throw new RangeError("Index out of range");if(U<0)throw new RangeError("Index out of range")}function X(_,O,U,te,ce){return O=+O,U=U>>>0,ce||J(_,O,U,4,34028234663852886e22,-34028234663852886e22),r.write(_,O,U,te,23,4),U+4}o.prototype.writeFloatLE=function(_,O,U){return X(this,_,O,!0,U)},o.prototype.writeFloatBE=function(_,O,U){return X(this,_,O,!1,U)};function L(_,O,U,te,ce){return O=+O,U=U>>>0,ce||J(_,O,U,8,17976931348623157e292,-17976931348623157e292),r.write(_,O,U,te,52,8),U+8}o.prototype.writeDoubleLE=function(_,O,U){return L(this,_,O,!0,U)},o.prototype.writeDoubleBE=function(_,O,U){return L(this,_,O,!1,U)},o.prototype.copy=function(_,O,U,te){if(!o.isBuffer(_))throw new TypeError("argument should be a Buffer");if(U||(U=0),!te&&te!==0&&(te=this.length),O>=_.length&&(O=_.length),O||(O=0),te>0&&te<U&&(te=U),te===U||_.length===0||this.length===0)return 0;if(O<0)throw new RangeError("targetStart out of bounds");if(U<0||U>=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),_.length-O<te-U&&(te=_.length-O+U);let ce=te-U;return this===_&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(O,U,te):Uint8Array.prototype.set.call(_,this.subarray(U,te),O),ce},o.prototype.fill=function(_,O,U,te){if(typeof _=="string"){if(typeof O=="string"?(te=O,O=0,U=this.length):typeof U=="string"&&(te=U,U=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(_.length===1){let me=_.charCodeAt(0);(te==="utf8"&&me<128||te==="latin1")&&(_=me)}}else typeof _=="number"?_=_&255:typeof _=="boolean"&&(_=Number(_));if(O<0||this.length<O||this.length<U)throw new RangeError("Out of range index");if(U<=O)return this;O=O>>>0,U=U===void 0?this.length:U>>>0,_||(_=0);let ce;if(typeof _=="number")for(ce=O;ce<U;++ce)this[ce]=_;else{let me=o.isBuffer(_)?_:o.from(_,te),Ae=me.length;if(Ae===0)throw new TypeError('The value "'+_+'" is invalid for argument "value"');for(ce=0;ce<U-O;++ce)this[ce+O]=me[ce%Ae]}return this};var Q={};function se(_,O,U){Q[_]=class extends U{constructor(){super(),Object.defineProperty(this,"message",{value:O.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${_}]`,this.stack,delete this.name}get code(){return _}set code(te){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:te,writable:!0})}toString(){return`${this.name} [${_}]: ${this.message}`}}}se("ERR_BUFFER_OUT_OF_BOUNDS",function(_){return _?`${_} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),se("ERR_INVALID_ARG_TYPE",function(_,O){return`The "${_}" argument must be of type number. Received type ${typeof O}`},TypeError),se("ERR_OUT_OF_RANGE",function(_,O,U){let te=`The value of "${_}" is out of range.`,ce=U;return Number.isInteger(U)&&Math.abs(U)>2**32?ce=re(String(U)):typeof U=="bigint"&&(ce=String(U),(U>BigInt(2)**BigInt(32)||U<-(BigInt(2)**BigInt(32)))&&(ce=re(ce)),ce+="n"),te+=` It must be ${O}. Received ${ce}`,te},RangeError);function re(_){let O="",U=_.length,te=_[0]==="-"?1:0;for(;U>=te+4;U-=3)O=`_${_.slice(U-3,U)}${O}`;return`${_.slice(0,U)}${O}`}function Y(_,O,U){ue(O,"offset"),(_[O]===void 0||_[O+U]===void 0)&&pe(O,_.length-(U+1))}function le(_,O,U,te,ce,me){if(_>U||_<O){let Ae=typeof O=="bigint"?"n":"",Ft;throw me>3?O===0||O===BigInt(0)?Ft=`>= 0${Ae} and < 2${Ae} ** ${(me+1)*8}${Ae}`:Ft=`>= -(2${Ae} ** ${(me+1)*8-1}${Ae}) and < 2 ** ${(me+1)*8-1}${Ae}`:Ft=`>= ${O}${Ae} and <= ${U}${Ae}`,new Q.ERR_OUT_OF_RANGE("value",Ft,_)}Y(te,ce,me)}function ue(_,O){if(typeof _!="number")throw new Q.ERR_INVALID_ARG_TYPE(O,"number",_)}function pe(_,O,U){throw Math.floor(_)!==_?(ue(_,U),new Q.ERR_OUT_OF_RANGE(U||"offset","an integer",_)):O<0?new Q.ERR_BUFFER_OUT_OF_BOUNDS:new Q.ERR_OUT_OF_RANGE(U||"offset",`>= ${U?1:0} and <= ${O}`,_)}var xe=/[^+/0-9A-Za-z-_]/g;function de(_){if(_=_.split("=")[0],_=_.trim().replace(xe,""),_.length<2)return"";for(;_.length%4!==0;)_=_+"=";return _}function Pe(_,O){O=O||1/0;let U,te=_.length,ce=null,me=[];for(let Ae=0;Ae<te;++Ae){if(U=_.charCodeAt(Ae),U>55295&&U<57344){if(!ce){if(U>56319){(O-=3)>-1&&me.push(239,191,189);continue}else if(Ae+1===te){(O-=3)>-1&&me.push(239,191,189);continue}ce=U;continue}if(U<56320){(O-=3)>-1&&me.push(239,191,189),ce=U;continue}U=(ce-55296<<10|U-56320)+65536}else ce&&(O-=3)>-1&&me.push(239,191,189);if(ce=null,U<128){if((O-=1)<0)break;me.push(U)}else if(U<2048){if((O-=2)<0)break;me.push(U>>6|192,U&63|128)}else if(U<65536){if((O-=3)<0)break;me.push(U>>12|224,U>>6&63|128,U&63|128)}else if(U<1114112){if((O-=4)<0)break;me.push(U>>18|240,U>>12&63|128,U>>6&63|128,U&63|128)}else throw new Error("Invalid code point")}return me}function Ne(_){let O=[];for(let U=0;U<_.length;++U)O.push(_.charCodeAt(U)&255);return O}function He(_,O){let U,te,ce,me=[];for(let Ae=0;Ae<_.length&&!((O-=2)<0);++Ae)U=_.charCodeAt(Ae),te=U>>8,ce=U%256,me.push(ce),me.push(te);return me}function Je(_){return e.toByteArray(de(_))}function Ct(_,O,U,te){let ce;for(ce=0;ce<te&&!(ce+U>=O.length||ce>=_.length);++ce)O[ce+U]=_[ce];return ce}function ke(_,O){return _ instanceof O||_!=null&&_.constructor!=null&&_.constructor.name!=null&&_.constructor.name===O.name}function ot(_){return _!==_}var _t=function(){let _="0123456789abcdef",O=new Array(256);for(let U=0;U<16;++U){let te=U*16;for(let ce=0;ce<16;++ce)O[te+ce]=_[U]+_[ce]}return O}();function Rt(_){return typeof BigInt>"u"?zt:_}function zt(){throw new Error("BigInt not supported")}}),qq=Qt((t,e)=>{"use strict";var r=null;e.exports=function(){return r===null&&(r={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),r}}),zq=Qt(t=>{"use strict";var e=Td(),r=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"||!r.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"})}};t.Encoding=n}),Fq=Qt(t=>{"use strict";var{Buffer:e}=f6()||{},{Encoding:r}=zq(),n=qq(),i=class extends r{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 r{constructor(o){super({...o,format:"view"})}createBufferTranscoder(){return new i({encode:o=>{let d=this.encode(o);return e.from(d.buffer,d.byteOffset,d.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},s=class extends r{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:d}=n();return new a({encode:l=>o.encode(this.encode(l)),decode:l=>this.decode(d.decode(l)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};t.BufferFormat=i,t.ViewFormat=a,t.UTF8Format=s}),tde=Qt(t=>{"use strict";var{Buffer:e}=f6()||{Buffer:{isBuffer:()=>!1}},{textEncoder:r,textDecoder:n}=qq()(),{BufferFormat:i,ViewFormat:a,UTF8Format:s}=Fq(),o=d=>d;t.utf8=new s({encode:function(d){return e.isBuffer(d)?d.toString("utf8"):ArrayBuffer.isView(d)?n.decode(d):String(d)},decode:o,name:"utf8",createViewTranscoder(){return new a({encode:function(d){return ArrayBuffer.isView(d)?d:r.encode(d)},decode:function(d){return n.decode(d)},name:`${this.name}+view`})},createBufferTranscoder(){return new i({encode:function(d){return e.isBuffer(d)?d:ArrayBuffer.isView(d)?e.from(d.buffer,d.byteOffset,d.byteLength):e.from(String(d),"utf8")},decode:function(d){return d.toString("utf8")},name:`${this.name}+buffer`})}}),t.json=new s({encode:JSON.stringify,decode:JSON.parse,name:"json"}),t.buffer=new i({encode:function(d){return e.isBuffer(d)?d:ArrayBuffer.isView(d)?e.from(d.buffer,d.byteOffset,d.byteLength):e.from(String(d),"utf8")},decode:o,name:"buffer",createViewTranscoder(){return new a({encode:function(d){return ArrayBuffer.isView(d)?d:e.from(String(d),"utf8")},decode:function(d){return e.from(d.buffer,d.byteOffset,d.byteLength)},name:`${this.name}+view`})}}),t.view=new a({encode:function(d){return ArrayBuffer.isView(d)?d:r.encode(d)},decode:o,name:"view",createBufferTranscoder(){return new i({encode:function(d){return e.isBuffer(d)?d:ArrayBuffer.isView(d)?e.from(d.buffer,d.byteOffset,d.byteLength):e.from(String(d),"utf8")},decode:o,name:`${this.name}+buffer`})}}),t.hex=new i({encode:function(d){return e.isBuffer(d)?d:e.from(String(d),"hex")},decode:function(d){return d.toString("hex")},name:"hex"}),t.base64=new i({encode:function(d){return e.isBuffer(d)?d:e.from(String(d),"base64")},decode:function(d){return d.toString("base64")},name:"base64"})}),rde=Qt(t=>{"use strict";var e=Td(),r=tde(),{Encoding:n}=zq(),{BufferFormat:i,ViewFormat:a,UTF8Format:s}=Fq(),o=Symbol("formats"),d=Symbol("encodings"),l=new Set(["buffer","view","utf8"]),c=class{constructor(y){if(Array.isArray(y)){if(!y.every(b=>l.has(b)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[d]=new Map,this[o]=new Set(y);for(let b in r)try{this.encoding(b)}catch(w){if(w.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw w}}encodings(){return Array.from(new Set(this[d].values()))}encoding(y){let b=this[d].get(y);if(b===void 0){if(typeof y=="string"&&y!==""){if(b=p[y],!b)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");b=u(y)}let{name:w,format:S}=b;if(!this[o].has(S))if(this[o].has("view"))b=b.createViewTranscoder();else if(this[o].has("buffer"))b=b.createBufferTranscoder();else if(this[o].has("utf8"))b=b.createUTF8Transcoder();else throw new e(`Encoding '${w}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let k of[y,w,b.name,b.commonName])this[d].set(k,b)}return b}};t.Transcoder=c;function u(y){if(y instanceof n)return y;let b="type"in y&&typeof y.type=="string"?y.type:void 0,w=y.name||b||`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 h={binary:r.buffer,"utf-8":r.utf8},p={...r,...h},m=0}),nde=Qt((t,e)=>{"use strict";var r=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function a(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function s(l,c,u,f,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new a(u,f||l,h),m=n?n+c:c;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],p]:l._events[m].push(p):(l._events[m]=p,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function d(){this._events=new i,this._eventsCount=0}d.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)r.call(c,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},d.prototype.listeners=function(l){var c=n?n+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var f=0,h=u.length,p=new Array(h);f<h;f++)p[f]=u[f].fn;return p},d.prototype.listenerCount=function(l){var c=n?n+l:l,u=this._events[c];return u?u.fn?1:u.length:0},d.prototype.emit=function(l,c,u,f,h,p){var m=n?n+l:l;if(!this._events[m])return!1;var y=this._events[m],b=arguments.length,w,S;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),b){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,c),!0;case 3:return y.fn.call(y.context,c,u),!0;case 4:return y.fn.call(y.context,c,u,f),!0;case 5:return y.fn.call(y.context,c,u,f,h),!0;case 6:return y.fn.call(y.context,c,u,f,h,p),!0}for(S=1,w=new Array(b-1);S<b;S++)w[S-1]=arguments[S];y.fn.apply(y.context,w)}else{var k=y.length,T;for(S=0;S<k;S++)switch(y[S].once&&this.removeListener(l,y[S].fn,void 0,!0),b){case 1:y[S].fn.call(y[S].context);break;case 2:y[S].fn.call(y[S].context,c);break;case 3:y[S].fn.call(y[S].context,c,u);break;case 4:y[S].fn.call(y[S].context,c,u,f);break;default:if(!w)for(T=1,w=new Array(b-1);T<b;T++)w[T-1]=arguments[T];y[S].fn.apply(y[S].context,w)}}return!0},d.prototype.on=function(l,c,u){return s(this,l,c,u,!1)},d.prototype.once=function(l,c,u){return s(this,l,c,u,!0)},d.prototype.removeListener=function(l,c,u,f){var h=n?n+l:l;if(!this._events[h])return this;if(!c)return o(this,h),this;var p=this._events[h];if(p.fn)p.fn===c&&(!f||p.once)&&(!u||p.context===u)&&o(this,h);else{for(var m=0,y=[],b=p.length;m<b;m++)(p[m].fn!==c||f&&!p[m].once||u&&p[m].context!==u)&&y.push(p[m]);y.length?this._events[h]=y.length===1?y[0]:y:o(this,h)}return this},d.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&o(this,c)):(this._events=new i,this._eventsCount=0),this},d.prototype.off=d.prototype.removeListener,d.prototype.addListener=d.prototype.on,d.prefixed=n,d.EventEmitter=d,typeof e<"u"&&(e.exports=d)}),ide=Qt((t,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:r=>Promise.resolve().then(r)}),W2=Qt(t=>{"use strict";var e=ide();t.fromCallback=function(r,n){if(r===void 0){var i=new Promise(function(a,s){r=function(o,d){o?s(o):a(d)}});r[n!==void 0?n:"promise"]=i}else if(typeof r!="function")throw new TypeError("Callback must be a function");return r},t.fromPromise=function(r,n){if(n===void 0)return r;r.then(function(i){e(()=>n(null,i))}).catch(function(i){e(()=>n(i))})}}),p6=Qt(t=>{"use strict";t.getCallback=function(e,r){return typeof e=="function"?e:r},t.getOptions=function(e,r){return typeof e=="object"&&e!==null?e:r!==void 0?r:{}}}),oh=Qt(t=>{"use strict";var{fromCallback:e}=W2(),r=Td(),{getOptions:n,getCallback:i}=p6(),a=Symbol("promise"),s=Symbol("callback"),o=Symbol("working"),d=Symbol("handleOne"),l=Symbol("handleMany"),c=Symbol("autoClose"),u=Symbol("finishWork"),f=Symbol("returnMany"),h=Symbol("closing"),p=Symbol("handleClose"),m=Symbol("closed"),y=Symbol("closeCallbacks"),b=Symbol("keyEncoding"),w=Symbol("valueEncoding"),S=Symbol("abortOnClose"),k=Symbol("legacy"),T=Symbol("keys"),D=Symbol("values"),K=Symbol("limit"),C=Symbol("count"),G=Object.freeze({}),z=()=>{},N=!1,V=class{constructor(E,x,A){if(typeof E!="object"||E===null){let I=E===null?"null":typeof E;throw new TypeError(`The first argument must be an abstract-level database, received ${I}`)}if(typeof x!="object"||x===null)throw new TypeError("The second argument must be an options object");this[m]=!1,this[y]=[],this[o]=!1,this[h]=!1,this[c]=!1,this[s]=null,this[d]=this[d].bind(this),this[l]=this[l].bind(this),this[p]=this[p].bind(this),this[b]=x[b],this[w]=x[w],this[k]=A,this[K]=Number.isInteger(x.limit)&&x.limit>=0?x.limit:1/0,this[C]=0,this[S]=!!x.abortOnClose,this.db=E,this.db.attachResource(this),this.nextTick=E.nextTick}get count(){return this[C]}get limit(){return this[K]}next(E){let x;if(E===void 0)x=new Promise((A,I)=>{E=(M,q,H)=>{M?I(M):this[k]?q===void 0&&H===void 0?A():A([q,H]):A(q)}});else if(typeof E!="function")throw new TypeError("Callback must be a function");return this[h]?this.nextTick(E,new r("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[o]?this.nextTick(E,new r("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[o]=!0,this[s]=E,this[C]>=this[K]?this.nextTick(this[d],null):this._next(this[d])),x}_next(E){this.nextTick(E)}nextv(E,x,A){return A=i(x,A),A=e(A,a),x=n(x,G),Number.isInteger(E)?(this[h]?this.nextTick(A,new r("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[o]?this.nextTick(A,new r("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(E<1&&(E=1),this[K]<1/0&&(E=Math.min(E,this[K]-this[C])),this[o]=!0,this[s]=A,E<=0?this.nextTick(this[l],null,[]):this._nextv(E,x,this[l])),A[a]):(this.nextTick(A,new TypeError("The first argument 'size' must be an integer")),A[a])}_nextv(E,x,A){let I=[],M=(q,H,W)=>{if(q)return A(q);if(this[k]?H===void 0&&W===void 0:H===void 0)return A(null,I);I.push(this[k]?[H,W]:H),I.length===E?A(null,I):this._next(M)};this._next(M)}all(E,x){return x=i(E,x),x=e(x,a),E=n(E,G),this[h]?this.nextTick(x,new r("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[o]?this.nextTick(x,new r("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[o]=!0,this[s]=x,this[c]=!0,this[C]>=this[K]?this.nextTick(this[l],null,[]):this._all(E,this[l])),x[a]}_all(E,x){let A=this[C],I=[],M=()=>{let H=this[K]<1/0?Math.min(1e3,this[K]-A):1e3;H<=0?this.nextTick(x,null,I):this._nextv(H,G,q)},q=(H,W)=>{H?x(H):W.length===0?x(null,I):(I.push.apply(I,W),A+=W.length,M())};M()}[u](){let E=this[s];return this[S]&&E===null?z:(this[o]=!1,this[s]=null,this[h]&&this._close(this[p]),E)}[f](E,x,A){this[c]?this.close(E.bind(null,x,A)):E(x,A)}seek(E,x){if(x=n(x,G),!this[h]){if(this[o])throw new r("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let A=this.db.keyEncoding(x.keyEncoding||this[b]),I=A.format;x.keyEncoding!==I&&(x={...x,keyEncoding:I});let M=this.db.prefixKey(A.encode(E),I);this._seek(M,x)}}}_seek(E,x){throw new r("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(E){return E=e(E,a),this[m]?this.nextTick(E):this[h]?this[y].push(E):(this[h]=!0,this[y].push(E),this[o]?this[S]&&this[u]()(new r("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[p])),E[a]}_close(E){this.nextTick(E)}[p](){this[m]=!0,this.db.detachResource(this);let E=this[y];this[y]=[];for(let x of E)x()}async*[Symbol.asyncIterator](){try{let E;for(;(E=await this.next())!==void 0;)yield E}finally{this[m]||await this.close()}}},ee=class extends V{constructor(E,x){super(E,x,!0),this[T]=x.keys!==!1,this[D]=x.values!==!1}[d](E,x,A){let I=this[u]();if(E)return I(E);try{x=this[T]&&x!==void 0?this[b].decode(x):void 0,A=this[D]&&A!==void 0?this[w].decode(A):void 0}catch(M){return I(new P("entry",M))}x===void 0&&A===void 0||this[C]++,I(null,x,A)}[l](E,x){let A=this[u]();if(E)return this[f](A,E);try{for(let I of x){let M=I[0],q=I[1];I[0]=this[T]&&M!==void 0?this[b].decode(M):void 0,I[1]=this[D]&&q!==void 0?this[w].decode(q):void 0}}catch(I){return this[f](A,new P("entries",I))}this[C]+=x.length,this[f](A,null,x)}end(E){return!N&&typeof console<"u"&&(N=!0,console.warn(new r("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(E)}},R=class extends V{constructor(E,x){super(E,x,!1)}[d](E,x){let A=this[u]();if(E)return A(E);try{x=x!==void 0?this[b].decode(x):void 0}catch(I){return A(new P("key",I))}x!==void 0&&this[C]++,A(null,x)}[l](E,x){let A=this[u]();if(E)return this[f](A,E);try{for(let I=0;I<x.length;I++){let M=x[I];x[I]=M!==void 0?this[b].decode(M):void 0}}catch(I){return this[f](A,new P("keys",I))}this[C]+=x.length,this[f](A,null,x)}},B=class extends V{constructor(E,x){super(E,x,!1)}[d](E,x){let A=this[u]();if(E)return A(E);try{x=x!==void 0?this[w].decode(x):void 0}catch(I){return A(new P("value",I))}x!==void 0&&this[C]++,A(null,x)}[l](E,x){let A=this[u]();if(E)return this[f](A,E);try{for(let I=0;I<x.length;I++){let M=x[I];x[I]=M!==void 0?this[w].decode(M):void 0}}catch(I){return this[f](A,new P("values",I))}this[C]+=x.length,this[f](A,null,x)}},P=class extends r{constructor(E,x){super(`Iterator could not decode ${E}`,{code:"LEVEL_DECODE_ERROR",cause:x})}};for(let E of["_ended property","_nexting property","_end method"])Object.defineProperty(ee.prototype,E.split(" ")[0],{get(){throw new r(`The ${E} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new r(`The ${E} has been removed`,{code:"LEVEL_LEGACY"})}});ee.keyEncoding=b,ee.valueEncoding=w,t.AbstractIterator=ee,t.AbstractKeyIterator=R,t.AbstractValueIterator=B}),sde=Qt(t=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:r}=oh(),n=Symbol("iterator"),i=Symbol("callback"),a=Symbol("handleOne"),s=Symbol("handleMany"),o=class extends e{constructor(l,c){super(l,c),this[n]=l.iterator({...c,keys:!0,values:!1}),this[a]=this[a].bind(this),this[s]=this[s].bind(this)}},d=class extends r{constructor(l,c){super(l,c),this[n]=l.iterator({...c,keys:!1,values:!0}),this[a]=this[a].bind(this),this[s]=this[s].bind(this)}};for(let l of[o,d]){let c=l===o,u=c?f=>f[0]:f=>f[1];l.prototype._next=function(f){this[i]=f,this[n].next(this[a])},l.prototype[a]=function(f,h,p){let m=this[i];f?m(f):m(null,c?h:p)},l.prototype._nextv=function(f,h,p){this[i]=p,this[n].nextv(f,h,this[s])},l.prototype._all=function(f,h){this[i]=h,this[n].all(f,this[s])},l.prototype[s]=function(f,h){let p=this[i];f?p(f):p(null,h.map(u))},l.prototype._seek=function(f,h){this[n].seek(f,h)},l.prototype._close=function(f){this[n].close(f)}}t.DefaultKeyIterator=o,t.DefaultValueIterator=d}),ode=Qt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=oh(),i=Td(),a=Symbol("nut"),s=Symbol("undefer"),o=Symbol("factory"),d=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 r{constructor(u,f){super(u,f),this[a]=null,this[o]=()=>u.keys(f),this.db.defer(()=>this[s]())}},c=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[d,l,c])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,h,p){this[a]!==null?this[a].nextv(f,h,p):this.db.status==="opening"?this.db.defer(()=>this._nextv(f,h,p)):this.nextTick(p,new i("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._all=function(f,h){this[a]!==null?this[a].all(h):this.db.status==="opening"?this.db.defer(()=>this._all(f,h)):this.nextTick(h,new i("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._seek=function(f,h){this[a]!==null?this[a]._seek(f,h):this.db.status==="opening"&&this.db.defer(()=>this._seek(f,h))},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)};t.DeferredIterator=d,t.DeferredKeyIterator=l,t.DeferredValueIterator=c}),Gq=Qt(t=>{"use strict";var{fromCallback:e}=W2(),r=Td(),{getCallback:n,getOptions:i}=p6(),a=Symbol("promise"),s=Symbol("status"),o=Symbol("operations"),d=Symbol("finishClose"),l=Symbol("closeCallbacks"),c=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[d]=this[d].bind(this),this.db=u,this.db.attachResource(this),this.nextTick=u.nextTick}get length(){return this[o].length}put(u,f,h){if(this[s]!=="open")throw new r("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let p=this.db._checkKey(u)||this.db._checkValue(f);if(p)throw p;let m=h&&h.sublevel!=null?h.sublevel:this.db,y=h,b=m.keyEncoding(h&&h.keyEncoding),w=m.valueEncoding(h&&h.valueEncoding),S=b.format;h={...h,keyEncoding:S,valueEncoding:w.format},m!==this.db&&(h.sublevel=null);let k=m.prefixKey(b.encode(u),S),T=w.encode(f);return this._put(k,T,h),this[o].push({...y,type:"put",key:u,value:f}),this}_put(u,f,h){}del(u,f){if(this[s]!=="open")throw new r("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let h=this.db._checkKey(u);if(h)throw h;let p=f&&f.sublevel!=null?f.sublevel:this.db,m=f,y=p.keyEncoding(f&&f.keyEncoding),b=y.format;return f={...f,keyEncoding:b},p!==this.db&&(f.sublevel=null),this._del(p.prefixKey(y.encode(u),b),f),this[o].push({...m,type:"del",key:u}),this}_del(u,f){}clear(){if(this[s]!=="open")throw new r("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 r("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,h=>{this[s]="closing",this[l].push(()=>f(h)),h||this.db.emit("batch",this[o]),this._close(this[d])})),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[d]))),u[a]}_close(u){this.nextTick(u)}[d](){this[s]="closed",this.db.detachResource(this);let u=this[l];this[l]=[];for(let f of u)f()}};t.AbstractChainedBatch=c}),ade=Qt(t=>{"use strict";var{AbstractChainedBatch:e}=Gq(),r=Td(),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 r("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};t.DefaultChainedBatch=i}),cde=Qt((t,e)=>{"use strict";var r=Td(),n=Object.prototype.hasOwnProperty,i=new Set(["lt","lte","gt","gte"]);e.exports=function(a,s){let o={};for(let d in a)if(n.call(a,d)&&!(d==="keyEncoding"||d==="valueEncoding")){if(d==="start"||d==="end")throw new r(`The legacy range option '${d}' has been removed`,{code:"LEVEL_LEGACY"});if(d==="encoding")throw new r("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});i.has(d)?o[d]=s.encode(a[d]):o[d]=a[d]}return o.reverse=!!o.reverse,o.limit=Number.isInteger(o.limit)&&o.limit>=0?o.limit:-1,o}}),Hq=Qt((t,e)=>{var r;e.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):n=>(r||(r=Promise.resolve())).then(n).catch(i=>setTimeout(()=>{throw i},0))}),dde=Qt((t,e)=>{"use strict";var r=Hq();e.exports=function(n,...i){i.length===0?r(n):r(()=>n(...i))}}),lde=Qt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=oh(),i=Symbol("unfix"),a=Symbol("iterator"),s=Symbol("handleOne"),o=Symbol("handleMany"),d=Symbol("callback"),l=class extends e{constructor(f,h,p,m){super(f,h),this[a]=p,this[i]=m,this[s]=this[s].bind(this),this[o]=this[o].bind(this),this[d]=null}[s](f,h,p){let m=this[d];if(f)return m(f);h!==void 0&&(h=this[i](h)),m(f,h,p)}[o](f,h){let p=this[d];if(f)return p(f);for(let m of h){let y=m[0];y!==void 0&&(m[0]=this[i](y))}p(f,h)}},c=class extends r{constructor(f,h,p,m){super(f,h),this[a]=p,this[i]=m,this[s]=this[s].bind(this),this[o]=this[o].bind(this),this[d]=null}[s](f,h){let p=this[d];if(f)return p(f);h!==void 0&&(h=this[i](h)),p(f,h)}[o](f,h){let p=this[d];if(f)return p(f);for(let m=0;m<h.length;m++){let y=h[m];y!==void 0&&(h[m]=this[i](y))}p(f,h)}},u=class extends n{constructor(f,h,p){super(f,h),this[a]=p}};for(let f of[l,c])f.prototype._next=function(h){this[d]=h,this[a].next(this[s])},f.prototype._nextv=function(h,p,m){this[d]=m,this[a].nextv(h,p,this[o])},f.prototype._all=function(h,p){this[d]=p,this[a].all(h,this[o])};for(let f of[u])f.prototype._next=function(h){this[a].next(h)},f.prototype._nextv=function(h,p,m){this[a].nextv(h,p,m)},f.prototype._all=function(h,p){this[a].all(h,p)};for(let f of[l,c,u])f.prototype._seek=function(h,p){this[a].seek(h,p)},f.prototype._close=function(h){this[a].close(h)};t.AbstractSublevelIterator=l,t.AbstractSublevelKeyIterator=c,t.AbstractSublevelValueIterator=u}),ude=Qt((t,e)=>{"use strict";var r=Td(),{Buffer:n}=f6()||{},{AbstractSublevelIterator:i,AbstractSublevelKeyIterator:a,AbstractSublevelValueIterator:s}=lde(),o=Symbol("prefix"),d=Symbol("upperBound"),l=Symbol("prefixRange"),c=Symbol("parent"),u=Symbol("unfix"),f=new TextEncoder,h={separator:"!"};e.exports=function({AbstractLevel:S}){class k extends S{static defaults(D){if(typeof D=="string")throw new r("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(D&&D.open)throw new r("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return D==null?h:D.separator?D:{...D,separator:"!"}}constructor(D,K,C){let{separator:G,manifest:z,...N}=k.defaults(C);K=w(K,G);let V=G.charCodeAt(0)+1,ee=D[c]||D;if(!f.encode(K).every(P=>P>V&&P<127))throw new r(`Prefix must use bytes > ${V} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(p(ee,z),N);let R=(D.prefix||"")+G+K+G,B=R.slice(0,-1)+String.fromCharCode(V);this[c]=ee,this[o]=new y(R),this[d]=new y(B),this[u]=new b,this.nextTick=ee.nextTick}prefixKey(D,K){if(K==="utf8")return this[o].utf8+D;if(D.byteLength===0)return this[o][K];if(K==="view"){let C=this[o].view,G=new Uint8Array(C.byteLength+D.byteLength);return G.set(C,0),G.set(D,C.byteLength),G}else{let C=this[o].buffer;return n.concat([C,D],C.byteLength+D.byteLength)}}[l](D,K){D.gte!==void 0?D.gte=this.prefixKey(D.gte,K):D.gt!==void 0?D.gt=this.prefixKey(D.gt,K):D.gte=this[o][K],D.lte!==void 0?D.lte=this.prefixKey(D.lte,K):D.lt!==void 0?D.lt=this.prefixKey(D.lt,K):D.lte=this[d][K]}get prefix(){return this[o].utf8}get db(){return this[c]}_open(D,K){this[c].open({passive:!0},K)}_put(D,K,C,G){this[c].put(D,K,C,G)}_get(D,K,C){this[c].get(D,K,C)}_getMany(D,K,C){this[c].getMany(D,K,C)}_del(D,K,C){this[c].del(D,K,C)}_batch(D,K,C){this[c].batch(D,K,C)}_clear(D,K){this[l](D,D.keyEncoding),this[c].clear(D,K)}_iterator(D){this[l](D,D.keyEncoding);let K=this[c].iterator(D),C=this[u].get(this[o].utf8.length,D.keyEncoding);return new i(this,D,K,C)}_keys(D){this[l](D,D.keyEncoding);let K=this[c].keys(D),C=this[u].get(this[o].utf8.length,D.keyEncoding);return new a(this,D,K,C)}_values(D){this[l](D,D.keyEncoding);let K=this[c].values(D);return new s(this,D,K)}}return{AbstractSublevel:k}};var p=function(S,k){return{...S.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...k,encodings:{utf8:m(S,"utf8"),buffer:m(S,"buffer"),view:m(S,"view")}}},m=function(S,k){return S.supports.encodings[k]?S.keyEncoding(k).name===k:!1},y=class{constructor(S){this.utf8=S,this.view=f.encode(S),this.buffer=n?n.from(this.view.buffer,0,this.view.byteLength):{}}},b=class{constructor(){this.cache=new Map}get(S,k){let T=this.cache.get(k);return T===void 0&&(k==="view"?T=(function(D,K){return K.subarray(D)}).bind(null,S):T=(function(D,K){return K.slice(D)}).bind(null,S),this.cache.set(k,T)),T}},w=function(S,k){let T=0,D=S.length;for(;T<D&&S[T]===k;)T++;for(;D>T&&S[D-1]===k;)D--;return S.slice(T,D)}}),A9=Qt(t=>{"use strict";var{supports:e}=Xce(),{Transcoder:r}=rde(),{EventEmitter:n}=nde(),{fromCallback:i}=W2(),a=Td(),{AbstractIterator:s}=oh(),{DefaultKeyIterator:o,DefaultValueIterator:d}=sde(),{DeferredIterator:l,DeferredKeyIterator:c,DeferredValueIterator:u}=ode(),{DefaultChainedBatch:f}=ade(),{getCallback:h,getOptions:p}=p6(),m=cde(),y=Symbol("promise"),b=Symbol("landed"),w=Symbol("resources"),S=Symbol("closeResources"),k=Symbol("operations"),T=Symbol("undefer"),D=Symbol("deferOpen"),K=Symbol("options"),C=Symbol("status"),G=Symbol("defaultOptions"),z=Symbol("transcoder"),N=Symbol("keyEncoding"),V=Symbol("valueEncoding"),ee=()=>{},R=class extends n{constructor(x,A){if(super(),typeof x!="object"||x===null)throw new TypeError("The first argument 'manifest' must be an object");A=p(A);let{keyEncoding:I,valueEncoding:M,passive:q,...H}=A;this[w]=new Set,this[k]=[],this[D]=!0,this[K]=H,this[C]="opening",this.supports=e(x,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:x.snapshots!==!1,permanence:x.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:x.encodings||{},events:Object.assign({},x.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[z]=new r(E(this)),this[N]=this[z].encoding(I||"utf8"),this[V]=this[z].encoding(M||"utf8");for(let W of this[z].encodings())this.supports.encodings[W.commonName]||(this.supports.encodings[W.commonName]=!0);this[G]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[N].commonName,valueEncoding:this[V].commonName}),key:Object.freeze({keyEncoding:this[N].commonName})},this.nextTick(()=>{this[D]&&this.open({passive:!1},ee)})}get status(){return this[C]}keyEncoding(x){return this[z].encoding(x??this[N])}valueEncoding(x){return this[z].encoding(x??this[V])}open(x,A){A=h(x,A),A=i(A,y),x={...this[K],...p(x)},x.createIfMissing=x.createIfMissing!==!1,x.errorIfExists=!!x.errorIfExists;let I=M=>{this[C]==="closing"||this[C]==="opening"?this.once(b,M?()=>I(M):I):this[C]!=="open"?A(new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:M})):A()};return x.passive?this[C]==="opening"?this.once(b,I):this.nextTick(I):this[C]==="closed"||this[D]?(this[D]=!1,this[C]="opening",this.emit("opening"),this._open(x,M=>{if(M){this[C]="closed",this[S](()=>{this.emit(b),I(M)}),this[T]();return}this[C]="open",this[T](),this.emit(b),this[C]==="open"&&this.emit("open"),this[C]==="open"&&this.emit("ready"),I()})):this[C]==="open"?this.nextTick(I):this.once(b,()=>this.open(x,A)),A[y]}_open(x,A){this.nextTick(A)}close(x){x=i(x,y);let A=I=>{this[C]==="opening"||this[C]==="closing"?this.once(b,I?A(I):A):this[C]!=="closed"?x(new a("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:I})):x()};if(this[C]==="open"){this[C]="closing",this.emit("closing");let I=M=>{this[C]="open",this[T](),this.emit(b),A(M)};this[S](()=>{this._close(M=>{if(M)return I(M);this[C]="closed",this[T](),this.emit(b),this[C]==="closed"&&this.emit("closed"),A()})})}else this[C]==="closed"?this.nextTick(A):this.once(b,()=>this.close(x));return x[y]}[S](x){if(this[w].size===0)return this.nextTick(x);let A=this[w].size,I=!0,M=()=>{--A===0&&(I?this.nextTick(x):x())};for(let q of this[w])q.close(M);I=!1,this[w].clear()}_close(x){this.nextTick(x)}get(x,A,I){if(I=h(A,I),I=i(I,y),A=p(A,this[G].entry),this[C]==="opening")return this.defer(()=>this.get(x,A,I)),I[y];if(P(this,I))return I[y];let M=this._checkKey(x);if(M)return this.nextTick(I,M),I[y];let q=this.keyEncoding(A.keyEncoding),H=this.valueEncoding(A.valueEncoding),W=q.format,J=H.format;return(A.keyEncoding!==W||A.valueEncoding!==J)&&(A=Object.assign({},A,{keyEncoding:W,valueEncoding:J})),this._get(this.prefixKey(q.encode(x),W),A,(X,L)=>{if(X)return(X.code==="LEVEL_NOT_FOUND"||X.notFound||/NotFound/i.test(X))&&(X.code||(X.code="LEVEL_NOT_FOUND"),X.notFound||(X.notFound=!0),X.status||(X.status=404)),I(X);try{L=H.decode(L)}catch(Q){return I(new a("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:Q}))}I(null,L)}),I[y]}_get(x,A,I){this.nextTick(I,new Error("NotFound"))}getMany(x,A,I){if(I=h(A,I),I=i(I,y),A=p(A,this[G].entry),this[C]==="opening")return this.defer(()=>this.getMany(x,A,I)),I[y];if(P(this,I))return I[y];if(!Array.isArray(x))return this.nextTick(I,new TypeError("The first argument 'keys' must be an array")),I[y];if(x.length===0)return this.nextTick(I,null,[]),I[y];let M=this.keyEncoding(A.keyEncoding),q=this.valueEncoding(A.valueEncoding),H=M.format,W=q.format;(A.keyEncoding!==H||A.valueEncoding!==W)&&(A=Object.assign({},A,{keyEncoding:H,valueEncoding:W}));let J=new Array(x.length);for(let X=0;X<x.length;X++){let L=x[X],Q=this._checkKey(L);if(Q)return this.nextTick(I,Q),I[y];J[X]=this.prefixKey(M.encode(L),H)}return this._getMany(J,A,(X,L)=>{if(X)return I(X);try{for(let Q=0;Q<L.length;Q++)L[Q]!==void 0&&(L[Q]=q.decode(L[Q]))}catch(Q){return I(new a(`Could not decode one or more of ${L.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:Q}))}I(null,L)}),I[y]}_getMany(x,A,I){this.nextTick(I,null,new Array(x.length).fill(void 0))}put(x,A,I,M){if(M=h(I,M),M=i(M,y),I=p(I,this[G].entry),this[C]==="opening")return this.defer(()=>this.put(x,A,I,M)),M[y];if(P(this,M))return M[y];let q=this._checkKey(x)||this._checkValue(A);if(q)return this.nextTick(M,q),M[y];let H=this.keyEncoding(I.keyEncoding),W=this.valueEncoding(I.valueEncoding),J=H.format,X=W.format;(I.keyEncoding!==J||I.valueEncoding!==X)&&(I=Object.assign({},I,{keyEncoding:J,valueEncoding:X}));let L=this.prefixKey(H.encode(x),J),Q=W.encode(A);return this._put(L,Q,I,se=>{if(se)return M(se);this.emit("put",x,A),M()}),M[y]}_put(x,A,I,M){this.nextTick(M)}del(x,A,I){if(I=h(A,I),I=i(I,y),A=p(A,this[G].key),this[C]==="opening")return this.defer(()=>this.del(x,A,I)),I[y];if(P(this,I))return I[y];let M=this._checkKey(x);if(M)return this.nextTick(I,M),I[y];let q=this.keyEncoding(A.keyEncoding),H=q.format;return A.keyEncoding!==H&&(A=Object.assign({},A,{keyEncoding:H})),this._del(this.prefixKey(q.encode(x),H),A,W=>{if(W)return I(W);this.emit("del",x),I()}),I[y]}_del(x,A,I){this.nextTick(I)}batch(x,A,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 x=="function"?I=x:I=h(A,I),I=i(I,y),A=p(A,this[G].empty),this[C]==="opening")return this.defer(()=>this.batch(x,A,I)),I[y];if(P(this,I))return I[y];if(!Array.isArray(x))return this.nextTick(I,new TypeError("The first argument 'operations' must be an array")),I[y];if(x.length===0)return this.nextTick(I),I[y];let M=new Array(x.length),{keyEncoding:q,valueEncoding:H,...W}=A;for(let J=0;J<x.length;J++){if(typeof x[J]!="object"||x[J]===null)return this.nextTick(I,new TypeError("A batch operation must be an object")),I[y];let X=Object.assign({},x[J]);if(X.type!=="put"&&X.type!=="del")return this.nextTick(I,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),I[y];let L=this._checkKey(X.key);if(L)return this.nextTick(I,L),I[y];let Q=X.sublevel!=null?X.sublevel:this,se=Q.keyEncoding(X.keyEncoding||q),re=se.format;if(X.key=Q.prefixKey(se.encode(X.key),re),X.keyEncoding=re,X.type==="put"){let Y=this._checkValue(X.value);if(Y)return this.nextTick(I,Y),I[y];let le=Q.valueEncoding(X.valueEncoding||H);X.value=le.encode(X.value),X.valueEncoding=le.format}Q!==this&&(X.sublevel=null),M[J]=X}return this._batch(M,W,J=>{if(J)return I(J);this.emit("batch",x),I()}),I[y]}_batch(x,A,I){this.nextTick(I)}sublevel(x,A){return this._sublevel(x,B.defaults(A))}_sublevel(x,A){return new B(this,x,A)}prefixKey(x,A){return x}clear(x,A){if(A=h(x,A),A=i(A,y),x=p(x,this[G].empty),this[C]==="opening")return this.defer(()=>this.clear(x,A)),A[y];if(P(this,A))return A[y];let I=x,M=this.keyEncoding(x.keyEncoding);return x=m(x,M),x.keyEncoding=M.format,x.limit===0?this.nextTick(A):this._clear(x,q=>{if(q)return A(q);this.emit("clear",I),A()}),A[y]}_clear(x,A){this.nextTick(A)}iterator(x){let A=this.keyEncoding(x&&x.keyEncoding),I=this.valueEncoding(x&&x.valueEncoding);if(x=m(x,A),x.keys=x.keys!==!1,x.values=x.values!==!1,x[s.keyEncoding]=A,x[s.valueEncoding]=I,x.keyEncoding=A.format,x.valueEncoding=I.format,this[C]==="opening")return new l(this,x);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(x)}_iterator(x){return new s(this,x)}keys(x){let A=this.keyEncoding(x&&x.keyEncoding),I=this.valueEncoding(x&&x.valueEncoding);if(x=m(x,A),x[s.keyEncoding]=A,x[s.valueEncoding]=I,x.keyEncoding=A.format,x.valueEncoding=I.format,this[C]==="opening")return new c(this,x);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(x)}_keys(x){return new o(this,x)}values(x){let A=this.keyEncoding(x&&x.keyEncoding),I=this.valueEncoding(x&&x.valueEncoding);if(x=m(x,A),x[s.keyEncoding]=A,x[s.valueEncoding]=I,x.keyEncoding=A.format,x.valueEncoding=I.format,this[C]==="opening")return new u(this,x);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(x)}_values(x){return new d(this,x)}defer(x){if(typeof x!="function")throw new TypeError("The first argument must be a function");this[k].push(x)}[T](){if(this[k].length===0)return;let x=this[k];this[k]=[];for(let A of x)A()}attachResource(x){if(typeof x!="object"||x===null||typeof x.close!="function")throw new TypeError("The first argument must be a resource object");this[w].add(x)}detachResource(x){this[w].delete(x)}_chainedBatch(){return new f(this)}_checkKey(x){if(x==null)return new a("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(x){if(x==null)return new a("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};R.prototype.nextTick=dde();var{AbstractSublevel:B}=ude()({AbstractLevel:R});t.AbstractLevel=R,t.AbstractSublevel=B;var P=function(x,A){return x[C]!=="open"?(x.nextTick(A,new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},E=function(x){return Object.keys(x.supports.encodings).filter(A=>!!x.supports.encodings[A])}}),Vq=Qt(t=>{"use strict";t.AbstractLevel=A9().AbstractLevel,t.AbstractSublevel=A9().AbstractSublevel,t.AbstractIterator=oh().AbstractIterator,t.AbstractKeyIterator=oh().AbstractKeyIterator,t.AbstractValueIterator=oh().AbstractValueIterator,t.AbstractChainedBatch=Gq().AbstractChainedBatch}),fde=Qt((t,e)=>{e.exports=n;var r=Hq();function n(i,a,s){if(typeof a!="number")throw new Error("second argument must be a Number");let o,d,l,c,u,f=!0,h;Array.isArray(i)?(o=[],l=d=i.length):(c=Object.keys(i),o={},l=d=c.length);function p(y){function b(){s&&s(y,o),s=null}f?r(b):b()}function m(y,b,w){if(o[y]=w,b&&(u=!0),--l===0||b)p(b);else if(!u&&h<d){let S;c?(S=c[h],h+=1,i[S](function(k,T){m(S,k,T)})):(S=h,h+=1,i[S](function(k,T){m(S,k,T)}))}}h=a,l?c?c.some(function(y,b){return i[y](function(w,S){m(y,w,S)}),b===a-1}):i.some(function(y,b){return y(function(w,S){m(b,w,S)}),b===a-1}):p(null),f=!1}}),Wq=Qt((t,e)=>{"use strict";e.exports=function(r){let n=r.gte!==void 0?r.gte:r.gt!==void 0?r.gt:void 0,i=r.lte!==void 0?r.lte:r.lt!==void 0?r.lt:void 0,a=r.gte===void 0,s=r.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}}),Jq=Qt((t,e)=>{"use strict";var r=new TextEncoder;e.exports=function(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):r.encode(n)}}),pde=Qt(t=>{"use strict";var{AbstractIterator:e}=Vq(),r=Wq(),n=Jq(),i=Symbol("cache"),a=Symbol("finished"),s=Symbol("options"),o=Symbol("currentOptions"),d=Symbol("position"),l=Symbol("location"),c=Symbol("first"),u={},f=class extends e{constructor(p,m,y){super(p,y),this[i]=[],this[a]=this.limit===0,this[s]=y,this[o]={...y},this[d]=void 0,this[l]=m,this[c]=!0}_nextv(p,m,y){if(this[c]=!1,this[a])return this.nextTick(y,null,[]);if(this[i].length>0)return p=Math.min(p,this[i].length),this.nextTick(y,null,this[i].splice(0,p));this[d]!==void 0&&(this[s].reverse?(this[o].lt=this[d],this[o].lte=void 0):(this[o].gt=this[d],this[o].gte=void 0));let b;try{b=r(this[o])}catch{return this[a]=!0,this.nextTick(y,null,[])}let w=this.db.db.transaction([this[l]],"readonly"),S=w.objectStore(this[l]),k=[];if(this[s].reverse){let T=!this[s].values&&S.openKeyCursor?"openKeyCursor":"openCursor";S[T](b,"prev").onsuccess=D=>{let K=D.target.result;if(K){let{key:C,value:G}=K;this[d]=C,k.push([this[s].keys&&C!==void 0?n(C):void 0,this[s].values&&G!==void 0?n(G):void 0]),k.length<p?K.continue():h(w)}else this[a]=!0}}else{let T,D,K=()=>{if(T===void 0||D===void 0)return;let C=Math.max(T.length,D.length);C===0||p===1/0?this[a]=!0:this[d]=T[C-1],k.length=C;for(let G=0;G<C;G++){let z=T[G],N=D[G];k[G]=[this[s].keys&&z!==void 0?n(z):void 0,this[s].values&&N!==void 0?n(N):void 0]}h(w)};this[s].keys||p<1/0?S.getAllKeys(b,p<1/0?p:void 0).onsuccess=C=>{T=C.target.result,K()}:(T=[],this.nextTick(K)),this[s].values?S.getAll(b,p<1/0?p:void 0).onsuccess=C=>{D=C.target.result,K()}:(D=[],this.nextTick(K))}w.onabort=()=>{y(w.error||new Error("aborted by user")),y=null},w.oncomplete=()=>{y(null,k),y=null}}_next(p){if(this[i].length>0){let[m,y]=this[i].shift();this.nextTick(p,null,m,y)}else if(this[a])this.nextTick(p);else{let m=Math.min(100,this.limit-this.count);this[c]&&(this[c]=!1,m=1),this._nextv(m,u,(y,b)=>{if(y)return p(y);this[i]=b,this._next(p)})}}_all(p,m){this[c]=!1;let y=this[i].splice(0,this[i].length),b=this.limit-this.count-y.length;if(b<=0)return this.nextTick(m,null,y);this._nextv(b,u,(w,S)=>{if(w)return m(w);y.length>0&&(S=y.concat(S)),m(null,S)})}_seek(p,m){this[c]=!0,this[i]=[],this[a]=!1,this[d]=void 0,this[o]={...this[s]};let y;try{y=r(this[s])}catch{this[a]=!0;return}y!==null&&!y.includes(p)?this[a]=!0:this[s].reverse?this[o].lte=p:this[o].gte=p}};t.Iterator=f;function h(p){typeof p.commit=="function"&&p.commit()}}),hde=Qt((t,e)=>{"use strict";e.exports=function(r,n,i,a,s){if(a.limit===0)return r.nextTick(s);let o=r.db.transaction([n],"readwrite"),d=o.objectStore(n),l=0;o.oncomplete=function(){s()},o.onabort=function(){s(o.error||new Error("aborted by user"))};let c=d.openKeyCursor?"openKeyCursor":"openCursor",u=a.reverse?"prev":"next";d[c](i,u).onsuccess=function(f){let h=f.target.result;h&&(d.delete(h.key).onsuccess=function(){(a.limit<=0||++l<a.limit)&&h.continue()})}}}),mde=Qt(t=>{"use strict";var{AbstractLevel:e}=Vq(),r=Td(),n=fde(),{fromCallback:i}=W2(),{Iterator:a}=pde(),s=Jq(),o=hde(),d=Wq(),l="level-js-",c=Symbol("idb"),u=Symbol("namePrefix"),f=Symbol("location"),h=Symbol("version"),p=Symbol("store"),m=Symbol("onComplete"),y=Symbol("promise"),b=class extends e{constructor(w,S,k){if(typeof S=="function"||typeof k=="function")throw new r("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:T,version:D,...K}=S||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},K),typeof w!="string")throw new Error("constructor requires a location string argument");this[f]=w,this[u]=T??l,this[h]=parseInt(D||1,10),this[c]=null}get location(){return this[f]}get namePrefix(){return this[u]}get version(){return this[h]}get db(){return this[c]}get type(){return"browser-level"}_open(w,S){let k=indexedDB.open(this[u]+this[f],this[h]);k.onerror=function(){S(k.error||new Error("unknown error"))},k.onsuccess=()=>{this[c]=k.result,S()},k.onupgradeneeded=T=>{let D=T.target.result;D.objectStoreNames.contains(this[f])||D.createObjectStore(this[f])}}[p](w){return this[c].transaction([this[f]],w).objectStore(this[f])}[m](w,S){let k=w.transaction;k.onabort=function(){S(k.error||new Error("aborted by user"))},k.oncomplete=function(){S(null,w.result)}}_get(w,S,k){let T=this[p]("readonly"),D;try{D=T.get(w)}catch(K){return this.nextTick(k,K)}this[m](D,function(K,C){if(K)return k(K);if(C===void 0)return k(new r("Entry not found",{code:"LEVEL_NOT_FOUND"}));k(null,s(C))})}_getMany(w,S,k){let T=this[p]("readonly"),D=w.map(K=>C=>{let G;try{G=T.get(K)}catch(z){return C(z)}G.onsuccess=()=>{let z=G.result;C(null,z===void 0?z:s(z))},G.onerror=z=>{z.stopPropagation(),C(G.error)}});n(D,16,k)}_del(w,S,k){let T=this[p]("readwrite"),D;try{D=T.delete(w)}catch(K){return this.nextTick(k,K)}this[m](D,k)}_put(w,S,k,T){let D=this[p]("readwrite"),K;try{K=D.put(S,w)}catch(C){return this.nextTick(T,C)}this[m](K,T)}_iterator(w){return new a(this,this[f],w)}_batch(w,S,k){let T=this[p]("readwrite"),D=T.transaction,K=0,C;D.onabort=function(){k(C||D.error||new Error("aborted by user"))},D.oncomplete=function(){k()};function G(){let z=w[K++],N=z.key,V;try{V=z.type==="del"?T.delete(N):T.put(z.value,N)}catch(ee){C=ee,D.abort();return}K<w.length?V.onsuccess=G:typeof D.commit=="function"&&D.commit()}G()}_clear(w,S){let k,T;try{k=d(w)}catch{return this.nextTick(S)}if(w.limit>=0)return o(this,this[f],k,w,S);try{let D=this[p]("readwrite");T=k?D.delete(k):D.clear()}catch(D){return this.nextTick(S,D)}this[m](T,S)}_close(w){this[c].close(),this.nextTick(w)}};b.destroy=function(w,S,k){typeof S=="function"&&(k=S,S=l),k=i(k,y);let T=indexedDB.deleteDatabase(S+w);return T.onsuccess=function(){k()},T.onerror=function(D){k(D)},k[y]},t.BrowserLevel=b}),Zq=Qt(t=>{t.Level=mde().BrowserLevel}),yde=Qt((t,e)=>{(function(r,n){typeof t=="object"&&typeof e<"u"?n(t):typeof define=="function"&&define.amd?define(["exports"],n):n(r.URI=r.URI||{})})(t,function(r){"use strict";function n(){for(var Z=arguments.length,oe=Array(Z),ae=0;ae<Z;ae++)oe[ae]=arguments[ae];if(oe.length>1){oe[0]=oe[0].slice(0,-1);for(var ve=oe.length-1,Ee=1;Ee<ve;++Ee)oe[Ee]=oe[Ee].slice(1,-1);return oe[ve]=oe[ve].slice(1),oe.join("")}else return oe[0]}function i(Z){return"(?:"+Z+")"}function a(Z){return Z===void 0?"undefined":Z===null?"null":Object.prototype.toString.call(Z).split(" ").pop().split("]").shift().toLowerCase()}function s(Z){return Z.toUpperCase()}function o(Z){return Z!=null?Z instanceof Array?Z:typeof Z.length!="number"||Z.split||Z.setInterval||Z.call?[Z]:Array.prototype.slice.call(Z):[]}function d(Z,oe){var ae=Z;if(oe)for(var ve in oe)ae[ve]=oe[ve];return ae}function l(Z){var oe="[A-Za-z]",ae="[\\x0D]",ve="[0-9]",Ee="[\\x22]",We=n(ve,"[A-Fa-f]"),Mt="[\\x0A]",br="[\\x20]",Yr=i(i("%[EFef]"+We+"%"+We+We+"%"+We+We)+"|"+i("%[89A-Fa-f]"+We+"%"+We+We)+"|"+i("%"+We+We)),Xr="[\\:\\/\\?\\#\\[\\]\\@]",fr="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",Sn=n(Xr,fr),Vn=Z?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",mn=Z?"[\\uE000-\\uF8FF]":"[]",Cr=n(oe,ve,"[\\-\\.\\_\\~]",Vn),_r=i(oe+n(oe,ve,"[\\+\\-\\.]")+"*"),rs=i(i(Yr+"|"+n(Cr,fr,"[\\:]"))+"*"),Eg=i(i("25[0-5]")+"|"+i("2[0-4]"+ve)+"|"+i("1"+ve+ve)+"|"+i("[1-9]"+ve)+"|"+ve),Ws=i(i("25[0-5]")+"|"+i("2[0-4]"+ve)+"|"+i("1"+ve+ve)+"|"+i("0?[1-9]"+ve)+"|0?0?"+ve),Na=i(Ws+"\\."+Ws+"\\."+Ws+"\\."+Ws),$r=i(We+"{1,4}"),wo=i(i($r+"\\:"+$r)+"|"+Na),Xo=i(i($r+"\\:")+"{6}"+wo),Cd=i("\\:\\:"+i($r+"\\:")+"{5}"+wo),jf=i(i($r)+"?\\:\\:"+i($r+"\\:")+"{4}"+wo),Ac=i(i(i($r+"\\:")+"{0,1}"+$r)+"?\\:\\:"+i($r+"\\:")+"{3}"+wo),Ab=i(i(i($r+"\\:")+"{0,2}"+$r)+"?\\:\\:"+i($r+"\\:")+"{2}"+wo),kb=i(i(i($r+"\\:")+"{0,3}"+$r)+"?\\:\\:"+$r+"\\:"+wo),Oh=i(i(i($r+"\\:")+"{0,4}"+$r)+"?\\:\\:"+wo),jh=i(i(i($r+"\\:")+"{0,5}"+$r)+"?\\:\\:"+$r),Mh=i(i(i($r+"\\:")+"{0,6}"+$r)+"?\\:\\:"),Mf=i([Xo,Cd,jf,Ac,Ab,kb,Oh,jh,Mh].join("|")),Kh=i(i(Cr+"|"+Yr)+"+"),Nh=i(Mf+"\\%25"+Kh),zH=i(Mf+i("\\%25|\\%(?!"+We+"{2})")+Kh),FH=i("[vV]"+We+"+\\."+n(Cr,fr,"[\\:]")+"+"),GH=i("\\["+i(zH+"|"+Mf+"|"+FH)+"\\]"),F5=i(i(Yr+"|"+n(Cr,fr))+"*"),Sg=i(GH+"|"+Na+"(?!"+F5+")|"+F5),Ag=i(ve+"*"),G5=i(i(rs+"@")+"?"+Sg+i("\\:"+Ag)+"?"),kg=i(Yr+"|"+n(Cr,fr,"[\\:\\@]")),HH=i(kg+"*"),H5=i(kg+"+"),VH=i(i(Yr+"|"+n(Cr,fr,"[\\@]"))+"+"),$d=i(i("\\/"+HH)+"*"),Uh=i("\\/"+i(H5+$d)+"?"),nS=i(VH+$d),_b=i(H5+$d),Lh="(?!"+kg+")",_ge=i($d+"|"+Uh+"|"+nS+"|"+_b+"|"+Lh),qh=i(i(kg+"|"+n("[\\/\\?]",mn))+"*"),_g=i(i(kg+"|[\\/\\?]")+"*"),V5=i(i("\\/\\/"+G5+$d)+"|"+Uh+"|"+_b+"|"+Lh),WH=i(_r+"\\:"+V5+i("\\?"+qh)+"?"+i("\\#"+_g)+"?"),JH=i(i("\\/\\/"+G5+$d)+"|"+Uh+"|"+nS+"|"+Lh),ZH=i(JH+i("\\?"+qh)+"?"+i("\\#"+_g)+"?"),Tge=i(WH+"|"+ZH),Ige=i(_r+"\\:"+V5+i("\\?"+qh)+"?"),Dge="^("+_r+")\\:"+i(i("\\/\\/("+i("("+rs+")@")+"?("+Sg+")"+i("\\:("+Ag+")")+"?)")+"?("+$d+"|"+Uh+"|"+_b+"|"+Lh+")")+i("\\?("+qh+")")+"?"+i("\\#("+_g+")")+"?$",Rge="^(){0}"+i(i("\\/\\/("+i("("+rs+")@")+"?("+Sg+")"+i("\\:("+Ag+")")+"?)")+"?("+$d+"|"+Uh+"|"+nS+"|"+Lh+")")+i("\\?("+qh+")")+"?"+i("\\#("+_g+")")+"?$",Cge="^("+_r+")\\:"+i(i("\\/\\/("+i("("+rs+")@")+"?("+Sg+")"+i("\\:("+Ag+")")+"?)")+"?("+$d+"|"+Uh+"|"+_b+"|"+Lh+")")+i("\\?("+qh+")")+"?$",$ge="^"+i("\\#("+_g+")")+"?$",Bge="^"+i("("+rs+")@")+"?("+Sg+")"+i("\\:("+Ag+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",oe,ve,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",Cr,fr),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",Cr,fr),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",Cr,fr),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",Cr,fr),"g"),NOT_QUERY:new RegExp(n("[^\\%]",Cr,fr,"[\\:\\@\\/\\?]",mn),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",Cr,fr,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",Cr,fr),"g"),UNRESERVED:new RegExp(Cr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",Cr,Sn),"g"),PCT_ENCODED:new RegExp(Yr,"g"),IPV4ADDRESS:new RegExp("^("+Na+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Mf+")"+i(i("\\%25|\\%(?!"+We+"{2})")+"("+Kh+")")+"?\\]?$")}}var c=l(!1),u=l(!0),f=function(){function Z(oe,ae){var ve=[],Ee=!0,We=!1,Mt=void 0;try{for(var br=oe[Symbol.iterator](),Yr;!(Ee=(Yr=br.next()).done)&&(ve.push(Yr.value),!(ae&&ve.length===ae));Ee=!0);}catch(Xr){We=!0,Mt=Xr}finally{try{!Ee&&br.return&&br.return()}finally{if(We)throw Mt}}return ve}return function(oe,ae){if(Array.isArray(oe))return oe;if(Symbol.iterator in Object(oe))return Z(oe,ae);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),h=function(Z){if(Array.isArray(Z)){for(var oe=0,ae=Array(Z.length);oe<Z.length;oe++)ae[oe]=Z[oe];return ae}else return Array.from(Z)},p=2147483647,m=36,y=1,b=26,w=38,S=700,k=72,T=128,D="-",K=/^xn--/,C=/[^\0-\x7E]/,G=/[\x2E\u3002\uFF0E\uFF61]/g,z={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},N=m-y,V=Math.floor,ee=String.fromCharCode;function R(Z){throw new RangeError(z[Z])}function B(Z,oe){for(var ae=[],ve=Z.length;ve--;)ae[ve]=oe(Z[ve]);return ae}function P(Z,oe){var ae=Z.split("@"),ve="";ae.length>1&&(ve=ae[0]+"@",Z=ae[1]),Z=Z.replace(G,".");var Ee=Z.split("."),We=B(Ee,oe).join(".");return ve+We}function E(Z){for(var oe=[],ae=0,ve=Z.length;ae<ve;){var Ee=Z.charCodeAt(ae++);if(Ee>=55296&&Ee<=56319&&ae<ve){var We=Z.charCodeAt(ae++);(We&64512)==56320?oe.push(((Ee&1023)<<10)+(We&1023)+65536):(oe.push(Ee),ae--)}else oe.push(Ee)}return oe}var x=function(Z){return String.fromCodePoint.apply(String,h(Z))},A=function(Z){return Z-48<10?Z-22:Z-65<26?Z-65:Z-97<26?Z-97:m},I=function(Z,oe){return Z+22+75*(Z<26)-((oe!=0)<<5)},M=function(Z,oe,ae){var ve=0;for(Z=ae?V(Z/S):Z>>1,Z+=V(Z/oe);Z>N*b>>1;ve+=m)Z=V(Z/N);return V(ve+(N+1)*Z/(Z+w))},q=function(Z){var oe=[],ae=Z.length,ve=0,Ee=T,We=k,Mt=Z.lastIndexOf(D);Mt<0&&(Mt=0);for(var br=0;br<Mt;++br)Z.charCodeAt(br)>=128&&R("not-basic"),oe.push(Z.charCodeAt(br));for(var Yr=Mt>0?Mt+1:0;Yr<ae;){for(var Xr=ve,fr=1,Sn=m;;Sn+=m){Yr>=ae&&R("invalid-input");var Vn=A(Z.charCodeAt(Yr++));(Vn>=m||Vn>V((p-ve)/fr))&&R("overflow"),ve+=Vn*fr;var mn=Sn<=We?y:Sn>=We+b?b:Sn-We;if(Vn<mn)break;var Cr=m-mn;fr>V(p/Cr)&&R("overflow"),fr*=Cr}var _r=oe.length+1;We=M(ve-Xr,_r,Xr==0),V(ve/_r)>p-Ee&&R("overflow"),Ee+=V(ve/_r),ve%=_r,oe.splice(ve++,0,Ee)}return String.fromCodePoint.apply(String,oe)},H=function(Z){var oe=[];Z=E(Z);var ae=Z.length,ve=T,Ee=0,We=k,Mt=!0,br=!1,Yr=void 0;try{for(var Xr=Z[Symbol.iterator](),fr;!(Mt=(fr=Xr.next()).done);Mt=!0){var Sn=fr.value;Sn<128&&oe.push(ee(Sn))}}catch(Nh){br=!0,Yr=Nh}finally{try{!Mt&&Xr.return&&Xr.return()}finally{if(br)throw Yr}}var Vn=oe.length,mn=Vn;for(Vn&&oe.push(D);mn<ae;){var Cr=p,_r=!0,rs=!1,Eg=void 0;try{for(var Ws=Z[Symbol.iterator](),Na;!(_r=(Na=Ws.next()).done);_r=!0){var $r=Na.value;$r>=ve&&$r<Cr&&(Cr=$r)}}catch(Nh){rs=!0,Eg=Nh}finally{try{!_r&&Ws.return&&Ws.return()}finally{if(rs)throw Eg}}var wo=mn+1;Cr-ve>V((p-Ee)/wo)&&R("overflow"),Ee+=(Cr-ve)*wo,ve=Cr;var Xo=!0,Cd=!1,jf=void 0;try{for(var Ac=Z[Symbol.iterator](),Ab;!(Xo=(Ab=Ac.next()).done);Xo=!0){var kb=Ab.value;if(kb<ve&&++Ee>p&&R("overflow"),kb==ve){for(var Oh=Ee,jh=m;;jh+=m){var Mh=jh<=We?y:jh>=We+b?b:jh-We;if(Oh<Mh)break;var Mf=Oh-Mh,Kh=m-Mh;oe.push(ee(I(Mh+Mf%Kh,0))),Oh=V(Mf/Kh)}oe.push(ee(I(Oh,0))),We=M(Ee,wo,mn==Vn),Ee=0,++mn}}}catch(Nh){Cd=!0,jf=Nh}finally{try{!Xo&&Ac.return&&Ac.return()}finally{if(Cd)throw jf}}++Ee,++ve}return oe.join("")},W=function(Z){return P(Z,function(oe){return K.test(oe)?q(oe.slice(4).toLowerCase()):oe})},J=function(Z){return P(Z,function(oe){return C.test(oe)?"xn--"+H(oe):oe})},X={version:"2.1.0",ucs2:{decode:E,encode:x},decode:q,encode:H,toASCII:J,toUnicode:W},L={};function Q(Z){var oe=Z.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 se(Z){for(var oe="",ae=0,ve=Z.length;ae<ve;){var Ee=parseInt(Z.substr(ae+1,2),16);if(Ee<128)oe+=String.fromCharCode(Ee),ae+=3;else if(Ee>=194&&Ee<224){if(ve-ae>=6){var We=parseInt(Z.substr(ae+4,2),16);oe+=String.fromCharCode((Ee&31)<<6|We&63)}else oe+=Z.substr(ae,6);ae+=6}else if(Ee>=224){if(ve-ae>=9){var Mt=parseInt(Z.substr(ae+4,2),16),br=parseInt(Z.substr(ae+7,2),16);oe+=String.fromCharCode((Ee&15)<<12|(Mt&63)<<6|br&63)}else oe+=Z.substr(ae,9);ae+=9}else oe+=Z.substr(ae,3),ae+=3}return oe}function re(Z,oe){function ae(ve){var Ee=se(ve);return Ee.match(oe.UNRESERVED)?Ee:ve}return Z.scheme&&(Z.scheme=String(Z.scheme).replace(oe.PCT_ENCODED,ae).toLowerCase().replace(oe.NOT_SCHEME,"")),Z.userinfo!==void 0&&(Z.userinfo=String(Z.userinfo).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_USERINFO,Q).replace(oe.PCT_ENCODED,s)),Z.host!==void 0&&(Z.host=String(Z.host).replace(oe.PCT_ENCODED,ae).toLowerCase().replace(oe.NOT_HOST,Q).replace(oe.PCT_ENCODED,s)),Z.path!==void 0&&(Z.path=String(Z.path).replace(oe.PCT_ENCODED,ae).replace(Z.scheme?oe.NOT_PATH:oe.NOT_PATH_NOSCHEME,Q).replace(oe.PCT_ENCODED,s)),Z.query!==void 0&&(Z.query=String(Z.query).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_QUERY,Q).replace(oe.PCT_ENCODED,s)),Z.fragment!==void 0&&(Z.fragment=String(Z.fragment).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_FRAGMENT,Q).replace(oe.PCT_ENCODED,s)),Z}function Y(Z){return Z.replace(/^0*(.*)/,"$1")||"0"}function le(Z,oe){var ae=Z.match(oe.IPV4ADDRESS)||[],ve=f(ae,2),Ee=ve[1];return Ee?Ee.split(".").map(Y).join("."):Z}function ue(Z,oe){var ae=Z.match(oe.IPV6ADDRESS)||[],ve=f(ae,3),Ee=ve[1],We=ve[2];if(Ee){for(var Mt=Ee.toLowerCase().split("::").reverse(),br=f(Mt,2),Yr=br[0],Xr=br[1],fr=Xr?Xr.split(":").map(Y):[],Sn=Yr.split(":").map(Y),Vn=oe.IPV4ADDRESS.test(Sn[Sn.length-1]),mn=Vn?7:8,Cr=Sn.length-mn,_r=Array(mn),rs=0;rs<mn;++rs)_r[rs]=fr[rs]||Sn[Cr+rs]||"";Vn&&(_r[mn-1]=le(_r[mn-1],oe));var Eg=_r.reduce(function(Xo,Cd,jf){if(!Cd||Cd==="0"){var Ac=Xo[Xo.length-1];Ac&&Ac.index+Ac.length===jf?Ac.length++:Xo.push({index:jf,length:1})}return Xo},[]),Ws=Eg.sort(function(Xo,Cd){return Cd.length-Xo.length})[0],Na=void 0;if(Ws&&Ws.length>1){var $r=_r.slice(0,Ws.index),wo=_r.slice(Ws.index+Ws.length);Na=$r.join(":")+"::"+wo.join(":")}else Na=_r.join(":");return We&&(Na+="%"+We),Na}else return Z}var pe=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,xe="".match(/(){0}/)[1]===void 0;function de(Z){var oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ae={},ve=oe.iri!==!1?u:c;oe.reference==="suffix"&&(Z=(oe.scheme?oe.scheme+":":"")+"//"+Z);var Ee=Z.match(pe);if(Ee){xe?(ae.scheme=Ee[1],ae.userinfo=Ee[3],ae.host=Ee[4],ae.port=parseInt(Ee[5],10),ae.path=Ee[6]||"",ae.query=Ee[7],ae.fragment=Ee[8],isNaN(ae.port)&&(ae.port=Ee[5])):(ae.scheme=Ee[1]||void 0,ae.userinfo=Z.indexOf("@")!==-1?Ee[3]:void 0,ae.host=Z.indexOf("//")!==-1?Ee[4]:void 0,ae.port=parseInt(Ee[5],10),ae.path=Ee[6]||"",ae.query=Z.indexOf("?")!==-1?Ee[7]:void 0,ae.fragment=Z.indexOf("#")!==-1?Ee[8]:void 0,isNaN(ae.port)&&(ae.port=Z.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?Ee[4]:void 0)),ae.host&&(ae.host=ue(le(ae.host,ve),ve)),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 We=L[(oe.scheme||ae.scheme||"").toLowerCase()];if(!oe.unicodeSupport&&(!We||!We.unicodeSupport)){if(ae.host&&(oe.domainHost||We&&We.domainHost))try{ae.host=X.toASCII(ae.host.replace(ve.PCT_ENCODED,se).toLowerCase())}catch(Mt){ae.error=ae.error||"Host's domain name can not be converted to ASCII via punycode: "+Mt}re(ae,c)}else re(ae,ve);We&&We.parse&&We.parse(ae,oe)}else ae.error=ae.error||"URI can not be parsed.";return ae}function Pe(Z,oe){var ae=oe.iri!==!1?u:c,ve=[];return Z.userinfo!==void 0&&(ve.push(Z.userinfo),ve.push("@")),Z.host!==void 0&&ve.push(ue(le(String(Z.host),ae),ae).replace(ae.IPV6ADDRESS,function(Ee,We,Mt){return"["+We+(Mt?"%25"+Mt:"")+"]"})),(typeof Z.port=="number"||typeof Z.port=="string")&&(ve.push(":"),ve.push(String(Z.port))),ve.length?ve.join(""):void 0}var Ne=/^\.\.?\//,He=/^\/\.(\/|$)/,Je=/^\/\.\.(\/|$)/,Ct=/^\/?(?:.|\n)*?(?=\/|$)/;function ke(Z){for(var oe=[];Z.length;)if(Z.match(Ne))Z=Z.replace(Ne,"");else if(Z.match(He))Z=Z.replace(He,"/");else if(Z.match(Je))Z=Z.replace(Je,"/"),oe.pop();else if(Z==="."||Z==="..")Z="";else{var ae=Z.match(Ct);if(ae){var ve=ae[0];Z=Z.slice(ve.length),oe.push(ve)}else throw new Error("Unexpected dot segment condition")}return oe.join("")}function ot(Z){var oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ae=oe.iri?u:c,ve=[],Ee=L[(oe.scheme||Z.scheme||"").toLowerCase()];if(Ee&&Ee.serialize&&Ee.serialize(Z,oe),Z.host&&!ae.IPV6ADDRESS.test(Z.host)&&(oe.domainHost||Ee&&Ee.domainHost))try{Z.host=oe.iri?X.toUnicode(Z.host):X.toASCII(Z.host.replace(ae.PCT_ENCODED,se).toLowerCase())}catch(br){Z.error=Z.error||"Host's domain name can not be converted to "+(oe.iri?"Unicode":"ASCII")+" via punycode: "+br}re(Z,ae),oe.reference!=="suffix"&&Z.scheme&&(ve.push(Z.scheme),ve.push(":"));var We=Pe(Z,oe);if(We!==void 0&&(oe.reference!=="suffix"&&ve.push("//"),ve.push(We),Z.path&&Z.path.charAt(0)!=="/"&&ve.push("/")),Z.path!==void 0){var Mt=Z.path;!oe.absolutePath&&(!Ee||!Ee.absolutePath)&&(Mt=ke(Mt)),We===void 0&&(Mt=Mt.replace(/^\/\//,"/%2F")),ve.push(Mt)}return Z.query!==void 0&&(ve.push("?"),ve.push(Z.query)),Z.fragment!==void 0&&(ve.push("#"),ve.push(Z.fragment)),ve.join("")}function _t(Z,oe){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},ve=arguments[3],Ee={};return ve||(Z=de(ot(Z,ae),ae),oe=de(ot(oe,ae),ae)),ae=ae||{},!ae.tolerant&&oe.scheme?(Ee.scheme=oe.scheme,Ee.userinfo=oe.userinfo,Ee.host=oe.host,Ee.port=oe.port,Ee.path=ke(oe.path||""),Ee.query=oe.query):(oe.userinfo!==void 0||oe.host!==void 0||oe.port!==void 0?(Ee.userinfo=oe.userinfo,Ee.host=oe.host,Ee.port=oe.port,Ee.path=ke(oe.path||""),Ee.query=oe.query):(oe.path?(oe.path.charAt(0)==="/"?Ee.path=ke(oe.path):((Z.userinfo!==void 0||Z.host!==void 0||Z.port!==void 0)&&!Z.path?Ee.path="/"+oe.path:Z.path?Ee.path=Z.path.slice(0,Z.path.lastIndexOf("/")+1)+oe.path:Ee.path=oe.path,Ee.path=ke(Ee.path)),Ee.query=oe.query):(Ee.path=Z.path,oe.query!==void 0?Ee.query=oe.query:Ee.query=Z.query),Ee.userinfo=Z.userinfo,Ee.host=Z.host,Ee.port=Z.port),Ee.scheme=Z.scheme),Ee.fragment=oe.fragment,Ee}function Rt(Z,oe,ae){var ve=d({scheme:"null"},ae);return ot(_t(de(Z,ve),de(oe,ve),ve,!0),ve)}function zt(Z,oe){return typeof Z=="string"?Z=ot(de(Z,oe),oe):a(Z)==="object"&&(Z=de(ot(Z,oe),oe)),Z}function _(Z,oe,ae){return typeof Z=="string"?Z=ot(de(Z,ae),ae):a(Z)==="object"&&(Z=ot(Z,ae)),typeof oe=="string"?oe=ot(de(oe,ae),ae):a(oe)==="object"&&(oe=ot(oe,ae)),Z===oe}function O(Z,oe){return Z&&Z.toString().replace(!oe||!oe.iri?c.ESCAPE:u.ESCAPE,Q)}function U(Z,oe){return Z&&Z.toString().replace(!oe||!oe.iri?c.PCT_ENCODED:u.PCT_ENCODED,se)}var te={scheme:"http",domainHost:!0,parse:function(Z,oe){return Z.host||(Z.error=Z.error||"HTTP URIs must have a host."),Z},serialize:function(Z,oe){var ae=String(Z.scheme).toLowerCase()==="https";return(Z.port===(ae?443:80)||Z.port==="")&&(Z.port=void 0),Z.path||(Z.path="/"),Z}},ce={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function me(Z){return typeof Z.secure=="boolean"?Z.secure:String(Z.scheme).toLowerCase()==="wss"}var Ae={scheme:"ws",domainHost:!0,parse:function(Z,oe){var ae=Z;return ae.secure=me(ae),ae.resourceName=(ae.path||"/")+(ae.query?"?"+ae.query:""),ae.path=void 0,ae.query=void 0,ae},serialize:function(Z,oe){if((Z.port===(me(Z)?443:80)||Z.port==="")&&(Z.port=void 0),typeof Z.secure=="boolean"&&(Z.scheme=Z.secure?"wss":"ws",Z.secure=void 0),Z.resourceName){var ae=Z.resourceName.split("?"),ve=f(ae,2),Ee=ve[0],We=ve[1];Z.path=Ee&&Ee!=="/"?Ee:void 0,Z.query=We,Z.resourceName=void 0}return Z.fragment=void 0,Z}},Ft={scheme:"wss",domainHost:Ae.domainHost,parse:Ae.parse,serialize:Ae.serialize},Xn={},Gr=!0,kr="[A-Za-z0-9\\-\\.\\_\\~"+(Gr?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",yr="[0-9A-Fa-f]",$H=i(i("%[EFef]"+yr+"%"+yr+yr+"%"+yr+yr)+"|"+i("%[89A-Fa-f]"+yr+"%"+yr+yr)+"|"+i("%"+yr+yr)),BH="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",OH="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",jH=n(OH,'[\\"\\\\]'),MH="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",KH=new RegExp(kr,"g"),Bh=new RegExp($H,"g"),NH=new RegExp(n("[^]",BH,"[\\.]",'[\\"]',jH),"g"),U5=new RegExp(n("[^]",kr,MH),"g"),UH=U5;function rS(Z){var oe=se(Z);return oe.match(KH)?oe:Z}var L5={scheme:"mailto",parse:function(Z,oe){var ae=Z,ve=ae.to=ae.path?ae.path.split(","):[];if(ae.path=void 0,ae.query){for(var Ee=!1,We={},Mt=ae.query.split("&"),br=0,Yr=Mt.length;br<Yr;++br){var Xr=Mt[br].split("=");switch(Xr[0]){case"to":for(var fr=Xr[1].split(","),Sn=0,Vn=fr.length;Sn<Vn;++Sn)ve.push(fr[Sn]);break;case"subject":ae.subject=U(Xr[1],oe);break;case"body":ae.body=U(Xr[1],oe);break;default:Ee=!0,We[U(Xr[0],oe)]=U(Xr[1],oe);break}}Ee&&(ae.headers=We)}ae.query=void 0;for(var mn=0,Cr=ve.length;mn<Cr;++mn){var _r=ve[mn].split("@");if(_r[0]=U(_r[0]),oe.unicodeSupport)_r[1]=U(_r[1],oe).toLowerCase();else try{_r[1]=X.toASCII(U(_r[1],oe).toLowerCase())}catch(rs){ae.error=ae.error||"Email address's domain name can not be converted to ASCII via punycode: "+rs}ve[mn]=_r.join("@")}return ae},serialize:function(Z,oe){var ae=Z,ve=o(Z.to);if(ve){for(var Ee=0,We=ve.length;Ee<We;++Ee){var Mt=String(ve[Ee]),br=Mt.lastIndexOf("@"),Yr=Mt.slice(0,br).replace(Bh,rS).replace(Bh,s).replace(NH,Q),Xr=Mt.slice(br+1);try{Xr=oe.iri?X.toUnicode(Xr):X.toASCII(U(Xr,oe).toLowerCase())}catch(mn){ae.error=ae.error||"Email address's domain name can not be converted to "+(oe.iri?"Unicode":"ASCII")+" via punycode: "+mn}ve[Ee]=Yr+"@"+Xr}ae.path=ve.join(",")}var fr=Z.headers=Z.headers||{};Z.subject&&(fr.subject=Z.subject),Z.body&&(fr.body=Z.body);var Sn=[];for(var Vn in fr)fr[Vn]!==Xn[Vn]&&Sn.push(Vn.replace(Bh,rS).replace(Bh,s).replace(U5,Q)+"="+fr[Vn].replace(Bh,rS).replace(Bh,s).replace(UH,Q));return Sn.length&&(ae.query=Sn.join("&")),ae}},LH=/^([^\:]+)\:(.*)/,q5={scheme:"urn",parse:function(Z,oe){var ae=Z.path&&Z.path.match(LH),ve=Z;if(ae){var Ee=oe.scheme||ve.scheme||"urn",We=ae[1].toLowerCase(),Mt=ae[2],br=Ee+":"+(oe.nid||We),Yr=L[br];ve.nid=We,ve.nss=Mt,ve.path=void 0,Yr&&(ve=Yr.parse(ve,oe))}else ve.error=ve.error||"URN can not be parsed.";return ve},serialize:function(Z,oe){var ae=oe.scheme||Z.scheme||"urn",ve=Z.nid,Ee=ae+":"+(oe.nid||ve),We=L[Ee];We&&(Z=We.serialize(Z,oe));var Mt=Z,br=Z.nss;return Mt.path=(ve||oe.nid)+":"+br,Mt}},qH=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,z5={scheme:"urn:uuid",parse:function(Z,oe){var ae=Z;return ae.uuid=ae.nss,ae.nss=void 0,!oe.tolerant&&(!ae.uuid||!ae.uuid.match(qH))&&(ae.error=ae.error||"UUID is not valid."),ae},serialize:function(Z,oe){var ae=Z;return ae.nss=(Z.uuid||"").toLowerCase(),ae}};L[te.scheme]=te,L[ce.scheme]=ce,L[Ae.scheme]=Ae,L[Ft.scheme]=Ft,L[L5.scheme]=L5,L[q5.scheme]=q5,L[z5.scheme]=z5,r.SCHEMES=L,r.pctEncChar=Q,r.pctDecChars=se,r.parse=de,r.removeDotSegments=ke,r.serialize=ot,r.resolveComponents=_t,r.resolve=Rt,r.normalize=zt,r.equal=_,r.escapeComponent=O,r.unescapeComponent=U,Object.defineProperty(r,"__esModule",{value:!0})})}),gde=Qt((t,e)=>{"use strict";e.exports=function r(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?r(n.toJSON()):Array.isArray(n)?`[${n.reduce((i,a,s)=>`${i}${s===0?"":","}${r(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}${r(a)}:${r(n[a])}`},"")}}`}}),Yq=Qt((t,e)=>{var r=1e3,n=r*60,i=n*60,a=i*24,s=a*7,o=a*365.25;e.exports=function(f,h){h=h||{};var p=typeof f;if(p==="string"&&f.length>0)return d(f);if(p==="number"&&isFinite(f))return h.long?c(f):l(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function d(f){if(f=String(f),!(f.length>100)){var h=/^(-?(?:\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(h){var p=parseFloat(h[1]),m=(h[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return p*o;case"weeks":case"week":case"w":return p*s;case"days":case"day":case"d":return p*a;case"hours":case"hour":case"hrs":case"hr":case"h":return p*i;case"minutes":case"minute":case"mins":case"min":case"m":return p*n;case"seconds":case"second":case"secs":case"sec":case"s":return p*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function l(f){var h=Math.abs(f);return h>=a?Math.round(f/a)+"d":h>=i?Math.round(f/i)+"h":h>=n?Math.round(f/n)+"m":h>=r?Math.round(f/r)+"s":f+"ms"}function c(f){var h=Math.abs(f);return h>=a?u(f,h,a,"day"):h>=i?u(f,h,i,"hour"):h>=n?u(f,h,n,"minute"):h>=r?u(f,h,r,"second"):f+" ms"}function u(f,h,p,m){var y=h>=p*1.5;return Math.round(f/p)+" "+m+(y?"s":"")}}),J2=(t=>(t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation",t))(J2||{}),Ai={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},Zi=class Xq{constructor({method:e,id:r,path:n,query:i,fragment:a,params:s}){this.uri=`did:${e}:${r}`,this.method=e,this.id=r,this.path=n,this.query=i,this.fragment=a,this.params=s}static parse(e){if(!e||e.length>2048)return null;let r=Xq.DID_URI_PATTERN.exec(e);if(!r||!r.groups)return null;let{method:n,id:i,path:a,query:s,fragment:o}=r.groups,d={uri:`did:${n}:${i}`,method:n,id:i};if(a&&(d.path=a),s&&(d.query=s.slice(1)),o&&(d.fragment=o.slice(1)),s){let l={},c=s.slice(1).split("&");for(let u of c){let[f,h]=u.split("=");l[f]=h}d.params=l}return d}};Zi.METHOD_PATTERN="([a-z0-9]+)",Zi.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",Zi.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${Zi.PCT_ENCODED_PATTERN})`,Zi.METHOD_ID_PATTERN=`((?:${Zi.ID_CHAR_PATTERN}*:)*(${Zi.ID_CHAR_PATTERN}+))`,Zi.PATH_PATTERN="(/[^#?]*)?",Zi.QUERY_PATTERN="([?][^#]*)?",Zi.FRAGMENT_PATTERN="(#.*)?",Zi.DID_URI_PATTERN=new RegExp("^did:(?<method>"+Zi.METHOD_PATTERN+"):(?<id>"+Zi.METHOD_ID_PATTERN+")(?<path>"+Zi.PATH_PATTERN+")(?<query>"+Zi.QUERY_PATTERN+")(?<fragment>"+Zi.FRAGMENT_PATTERN+")$");Fn=Zi,rt=class Qq extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,this.name="DidError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Qq)}},wde=(t=>(t.InvalidDid="invalidDid",t.MethodNotSupported="methodNotSupported",t.InternalError="internalError",t.InvalidDidDocument="invalidDidDocument",t.InvalidDidDocumentLength="invalidDidDocumentLength",t.InvalidDidUrl="invalidDidUrl",t.InvalidPreviousDidProof="invalidPreviousDidProof",t.InvalidPublicKey="invalidPublicKey",t.InvalidPublicKeyLength="invalidPublicKeyLength",t.InvalidPublicKeyType="invalidPublicKeyType",t.InvalidSignature="invalidSignature",t.NotFound="notFound",t.RepresentationNotSupported="representationNotSupported",t.UnsupportedPublicKeyType="unsupportedPublicKeyType",t))(wde||{}),$a=class e7 extends Error{constructor(e,r){super(r),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e7)}};(function(t){t.AlgorithmNotSupported="algorithmNotSupported",t.EncodingError="encodingError",t.InvalidCoseSign1="invalidCoseSign1",t.InvalidEat="invalidEat",t.InvalidJwe="invalidJwe",t.InvalidJwk="invalidJwk",t.OperationNotSupported="operationNotSupported"})(fo||(fo={}));vde=ph(Yce(),1);Pde=bde,xde=Pde,Ede=xde,oNe=new Uint8Array(0),Sde=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},h6=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Ade=class{constructor(t,e,r){this.name=t,this.prefix=e,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},kde=class{constructor(t,e,r){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return t7(this,t)}},_de=class{constructor(t){this.decoders=t}or(t){return t7(this,t)}decode(t){let e=t[0],r=this.decoders[e];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},t7=(t,e)=>new _de({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Tde=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new Ade(t,e,r),this.decoder=new kde(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},r7=({name:t,prefix:e,encode:r,decode:n})=>new Tde(t,e,r,n),n7=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=Ede(r,e);return r7({prefix:t,name:e,encode:n,decode:a=>h6(i(a))})},Ide=(t,e,r,n)=>{let i={};for(let c=0;c<e.length;++c)i[e[c]]=c;let a=t.length;for(;t[a-1]==="=";)--a;let s=new Uint8Array(a*r/8|0),o=0,d=0,l=0;for(let c=0;c<a;++c){let u=i[t[c]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);d=d<<r|u,o+=r,o>=8&&(o-=8,s[l++]=255&d>>o)}if(o>=r||255&d<<8-o)throw new SyntaxError("Unexpected end of data");return s},Dde=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,a="",s=0,o=0;for(let d=0;d<t.length;++d)for(o=o<<8|t[d],s+=8;s>r;)s-=r,a+=e[i&o>>s];if(s&&(a+=e[i&o<<r-s]),n)for(;a.length*r&7;)a+="=";return a},Wo=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>r7({prefix:e,name:t,encode(i){return Dde(i,n,r)},decode(i){return Ide(i,n,r,t)}}),y2=Wo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),aNe=Wo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cNe=Wo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),dNe=Wo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),lNe=Wo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),uNe=Wo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fNe=Wo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),pNe=Wo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),k9=Wo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Ra=n7({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),hNe=n7({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),mNe=Wo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),yNe=Wo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_l=Wo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),gNe=Wo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});yv=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},_9=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(a){r[a]=t[a]&&function(s){return new Promise(function(o,d){s=t[a](s),i(o,d,s.done,s.value)})}}function i(a,s,o,d){Promise.resolve(d).then(function(l){a({value:l,done:o})},s)}},c2=new TextEncoder,Qp=new TextDecoder,it=class lo{constructor(e,r){this.data=e,this.format=r}static arrayBuffer(e){return new lo(e,"ArrayBuffer")}static asyncIterable(e){if(!Cde(e))throw new TypeError("Input must be of type AsyncIterable.");return new lo(e,"AsyncIterable")}static base32Z(e){return new lo(e,"Base32Z")}static base58Btc(e){return new lo(e,"Base58Btc")}static base64Url(e){return new lo(e,"Base64Url")}static bufferSource(e){return new lo(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 lo(e,"Hex")}static multibase(e){return new lo(e,"Multibase")}static object(e){return new lo(e,"Object")}static string(e){return new lo(e,"String")}static uint8Array(e){return new lo(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return Ra.baseDecode(this.data).buffer;case"Base64Url":return _l.baseDecode(this.data).buffer;case"BufferSource":{if(zR(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return Rde(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 yv(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 k9.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 Ra.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return Ra.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 _l.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return _l.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=c2.encode(e);return _l.baseEncode(r)}case"String":{let e=c2.encode(this.data);return _l.baseEncode(e)}case"Uint8Array":return _l.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return yv(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let d=[];try{for(var a=!0,s=_9(this.data),o;o=yield s.next(),e=o.done,!e;a=!0){i=o.value,a=!1;let l=i;d.push(l)}}catch(l){r={error:l}}finally{try{!a&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(r)throw r.error}}return new Blob(d)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(r,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let r=this.toUint8Array();return lo.uint8Array(r).toHex()}case"Base64Url":{let r=this.toUint8Array();return lo.uint8Array(r).toHex()}case"Uint8Array":{let r="";for(let n=0;n<this.data.length;n++)r+=e[this.data[n]];return r}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=_l.baseDecode(this.data),r=Qp.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=Qp.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return yv(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 Qp.decode(this.data);case"Base64Url":{let e=_l.baseDecode(this.data);return Qp.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return Qp.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return yv(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let d="";try{for(var a=!0,s=_9(this.data),o;o=yield s.next(),e=o.done,!e;a=!0){i=o.value,a=!1;let l=i;typeof l=="string"?d+=l:d+=Qp.decode(l,{stream:!0})}}catch(l){r={error:l}}finally{try{!a&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(r)throw r.error}}return d+=Qp.decode(void 0,{stream:!1}),d}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 k9.baseDecode(this.data);case"Base58Btc":return Ra.baseDecode(this.data);case"Base64Url":return _l.baseDecode(this.data);case"BufferSource":{let e=zR(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 r=0;r<this.data.length;r+=2){let n=parseInt(this.data.substring(r,r+2),16);if(isNaN(n))throw new TypeError("Input is not a valid hexadecimal string.");e[r/2]=n}return e}case"Object":{let e=JSON.stringify(this.data);return c2.encode(e)}case"String":return c2.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return yv(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(t){t.Debug="debug",t.Silent="silent"})(Kv||(Kv={}));$de=class{constructor(){this.logLevel=Kv.Silent}setLogLevel(t){this.logLevel=t}log(t){this.info(t)}info(t){this.logLevel!==Kv.Silent&&console.info(t)}error(t){this.logLevel!==Kv.Silent&&console.error(t)}},Bde=new $de;typeof window<"u"&&(window.enboxLogger=Bde);Ev={};u6(Ev,{decode:()=>M2,encodeTo:()=>Uv,encodingLength:()=>Lv});Ode=i7,T9=128,jde=127,Mde=~jde,Kde=Math.pow(2,31);Nde=FR,Ude=128,I9=127;Lde=Math.pow(2,7),qde=Math.pow(2,14),zde=Math.pow(2,21),Fde=Math.pow(2,28),Gde=Math.pow(2,35),Hde=Math.pow(2,42),Vde=Math.pow(2,49),Wde=Math.pow(2,56),Jde=Math.pow(2,63),Zde=function(t){return t<Lde?1:t<qde?2:t<zde?3:t<Fde?4:t<Gde?5:t<Hde?6:t<Vde?7:t<Wde?8:t<Jde?9:10},Yde={encode:Ode,decode:Nde,encodingLength:Zde},Xde=Yde,j2=Xde,M2=(t,e=0)=>[j2.decode(t,e),j2.decode.bytes],Uv=(t,e,r=0)=>(j2.encode(t,e,r),e),Lv=t=>j2.encodingLength(t),Qde=(t,e)=>{let r=e.byteLength,n=Lv(t),i=n+Lv(r),a=new Uint8Array(i+r);return Uv(t,a,0),Uv(r,a,n),a.set(e,i),new m6(t,r,e,a)},ele=t=>{let e=h6(t),[r,n]=M2(e),[i,a]=M2(e.subarray(n)),s=e.subarray(n+a);if(s.byteLength!==i)throw new Error("Incorrect length");return new m6(r,i,s,e)},tle=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Sde(t.bytes,r.bytes)}},m6=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},D9=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return nle(r,GR(t),e||Ra.encoder);default:return ile(r,GR(t),e||y2.encoder)}},R9=new WeakMap,GR=t=>{let e=R9.get(t);if(e==null){let r=new Map;return R9.set(t,r),r}return e},wNe=class gs{constructor(e,r,n,i){this.code=r,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:r}=this;if(e!==gv)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==sle)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return gs.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Qde(e,r);return gs.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 gs.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&tle(e.multihash,n.multihash)}toString(e){return D9(this,e)}toJSON(){return{"/":D9(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 r=e;if(r instanceof gs)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:a,bytes:s}=r;return new gs(n,i,a,s||C9(n,i,a.bytes))}else if(r[ole]===!0){let{version:n,multihash:i,code:a}=r,s=ele(i);return gs.create(n,a,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==gv)throw new Error(`Version 0 CID must use dag-pb (code: ${gv}) block encoding`);return new gs(e,r,n,n.bytes)}case 1:{let i=C9(e,r,n.bytes);return new gs(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return gs.create(0,gv,e)}static createV1(e,r){return gs.create(1,e,r)}static decode(e){let[r,n]=gs.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=gs.inspectBytes(e),n=r.size-r.multihashSize,i=h6(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let a=i.subarray(r.multihashSize-r.digestSize),s=new m6(r.multihashCode,r.digestSize,a,i);return[r.version===0?gs.createV0(s):gs.createV1(r.codec,s),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[u,f]=M2(e.subarray(r));return r+=f,u},i=n(),a=gv;if(i===18?(i=0,r=0):a=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=r,o=n(),d=n(),l=r+d,c=l-s;return{version:i,codec:a,multihashCode:o,digestSize:d,multihashSize:c,size:l}}static parse(e,r){let[n,i]=rle(e,r),a=gs.decode(i);if(a.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return GR(a).set(n,e),a}},rle=(t,e)=>{switch(t[0]){case"Q":{let r=e||Ra;return[Ra.prefix,r.decode(`${Ra.prefix}${t}`)]}case Ra.prefix:{let r=e||Ra;return[Ra.prefix,r.decode(t)]}case y2.prefix:{let r=e||y2;return[y2.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},nle=(t,e,r)=>{let{prefix:n}=r;if(n!==Ra.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let a=r.encode(t).slice(1);return e.set(n,a),a}else return i},ile=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let a=r.encode(t);return e.set(n,a),a}else return i},gv=112,sle=18,C9=(t,e,r)=>{let n=Lv(t),i=n+Lv(e),a=new Uint8Array(i+r.byteLength);return Uv(t,a,0),Uv(e,a,n),a.set(r,i),a},ole=Symbol.for("@ipld/js-cid/CID"),Oa=class hf{static addPrefix(e){var r;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=hf.codeToName.has(n)?n:hf.nameToCode.get(a),n===void 0)throw new Error(`Unsupported multicodec: ${(r=e.name)!==null&&r!==void 0?r:e.code}`);let s=Ev.encodingLength(n),o=new Uint8Array(s+i.byteLength);return o.set(i,s),Ev.encodeTo(n,o),o}static getCodeFromData(e){let{prefixedData:r}=e,[n,i]=Ev.decode(r);return n}static getCodeFromName(e){let{name:r}=e,n=hf.nameToCode.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static getNameFromCode(e){let{code:r}=e,n=hf.codeToName.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static registerCodec(e){hf.codeToName.set(e.code,e.name),hf.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:r}=e,[n,i]=Ev.decode(r),a=hf.codeToName.get(n);if(a===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:r.slice(i),name:a}}};Oa.codeToName=new Map;Oa.nameToCode=new Map;Oa.registerCodec({code:237,name:"ed25519-pub"});Oa.registerCodec({code:4864,name:"ed25519-priv"});Oa.registerCodec({code:236,name:"x25519-pub"});Oa.registerCodec({code:4866,name:"x25519-priv"});Oa.registerCodec({code:231,name:"secp256k1-pub"});Oa.registerCodec({code:4865,name:"secp256k1-priv"});vNe=ph(Zq(),1),nf=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},ale=class{constructor(){this.store=new Map}clear(){return nf(this,void 0,void 0,function*(){this.store.clear()})}open(){return nf(this,void 0,void 0,function*(){})}close(){return nf(this,void 0,void 0,function*(){})}delete(t){return nf(this,void 0,void 0,function*(){return this.store.delete(t)})}get(t){return nf(this,void 0,void 0,function*(){return this.store.get(t)})}has(t){return nf(this,void 0,void 0,function*(){return this.store.has(t)})}list(){return nf(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(t,e){return nf(this,void 0,void 0,function*(){this.store.set(t,e)})}},Z2=class{},o7={};u6(o7,{bitGet:()=>hle,bitLen:()=>ple,bitMask:()=>g6,bitSet:()=>mle,bytesToHex:()=>lh,bytesToNumberBE:()=>ah,bytesToNumberLE:()=>vf,concatBytes:()=>uh,createHmacDrbg:()=>d7,ensureBytes:()=>zn,equalBytes:()=>ule,hexToBytes:()=>Ly,hexToNumber:()=>y6,isBytes:()=>kd,numberToBytesBE:()=>_d,numberToBytesLE:()=>qy,numberToHexUnpadded:()=>c7,numberToVarBytesBE:()=>lle,utf8ToBytes:()=>fle,validateObject:()=>hh});a7=BigInt(0),Y2=BigInt(1),cle=BigInt(2);dle=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));Tl={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};mle=(t,e,r)=>t|(r?Y2:a7)<<BigInt(e),g6=t=>(cle<<BigInt(t-1))-Y2,$R=t=>new Uint8Array(t),B9=t=>Uint8Array.from(t);yle={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||kd(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};BR=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;OR=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),wd=(t,e)=>t<<32-e|t>>>e,ble=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ble)throw new Error("Non little-endian hardware is not supported");h7=class{clone(){return this._cloneInto()}},bNe={}.toString;y7=class extends h7{constructor(t,e,r,n){super(),this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=OR(this.buffer)}update(t){K2(this);let{view:e,buffer:r,blockLen:n}=this;t=w6(t);let i=t.length;for(let a=0;a<i;){let s=Math.min(n-this.pos,i-a);if(s===n){let o=OR(t);for(;n<=i-a;a+=n)this.process(o,a);continue}r.set(t.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){K2(this),vle(t,this),this.finished=!0;let{buffer:e,view:r,blockLen:n,isLE:i}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(r,0),a=0);for(let c=a;c<n;c++)e[c]=0;Ple(r,n-8,BigInt(this.length*8),i),this.process(r,0);let s=OR(t),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=o/4,l=this.get();if(d>l.length)throw new Error("_sha2: outputLen bigger than state");for(let c=0;c<d;c++)s.setUint32(4*c,l[c],i)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let r=t.slice(0,e);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:r,length:n,finished:i,destroyed:a,pos:s}=this;return t.length=n,t.pos=s,t.finished=i,t.destroyed=a,n%e&&t.buffer.set(r),t}},xle=(t,e,r)=>t&e^~t&r,Ele=(t,e,r)=>t&e^t&r^e&r,Sle=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]),sf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),of=new Uint32Array(64),Ale=class extends y7{constructor(){super(64,32,8,!1),this.A=sf[0]|0,this.B=sf[1]|0,this.C=sf[2]|0,this.D=sf[3]|0,this.E=sf[4]|0,this.F=sf[5]|0,this.G=sf[6]|0,this.H=sf[7]|0}get(){let{A:t,B:e,C:r,D:n,E:i,F:a,G:s,H:o}=this;return[t,e,r,n,i,a,s,o]}set(t,e,r,n,i,a,s,o){this.A=t|0,this.B=e|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=s|0,this.H=o|0}process(t,e){for(let c=0;c<16;c++,e+=4)of[c]=t.getUint32(e,!1);for(let c=16;c<64;c++){let u=of[c-15],f=of[c-2],h=wd(u,7)^wd(u,18)^u>>>3,p=wd(f,17)^wd(f,19)^f>>>10;of[c]=p+of[c-7]+h+of[c-16]|0}let{A:r,B:n,C:i,D:a,E:s,F:o,G:d,H:l}=this;for(let c=0;c<64;c++){let u=wd(s,6)^wd(s,11)^wd(s,25),f=l+u+xle(s,o,d)+Sle[c]+of[c]|0,h=(wd(r,2)^wd(r,13)^wd(r,22))+Ele(r,n,i)|0;l=d,d=o,o=s,s=a+f|0,a=i,i=n,n=r,r=f+h|0}r=r+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,d=d+this.G|0,l=l+this.H|0,this.set(r,n,i,a,s,o,d,l)}roundClean(){of.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},g7=m7(()=>new Ale),ui=BigInt(0),hn=BigInt(1),rh=BigInt(2),kle=BigInt(3),HR=BigInt(4),j9=BigInt(5),M9=BigInt(8),PNe=BigInt(9),_le=BigInt(16);Dle=(t,e)=>(Zr(t,e)&hn)===hn,Rle=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];Mle=BigInt(0),jR=BigInt(1);({bytesToNumberBE:Nle,hexToBytes:Ule}=o7),sh={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(t){let{Err:e}=sh;if(t.length<2||t[0]!==2)throw new e("Invalid signature integer tag");let r=t[1],n=t.subarray(2,r+2);if(!r||n.length!==r)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:Nle(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=sh,r=typeof t=="string"?Ule(t):t;if(!kd(r))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new e("Invalid signature tag");if(r[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:i,l:a}=sh._parseInt(r.subarray(2)),{d:s,l:o}=sh._parseInt(a);if(o.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(t){let e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,r=l=>{let c=l.toString(16);return c.length&1?`0${c}`:c},n=e(r(t.s)),i=e(r(t.r)),a=n.length/2,s=i.length/2,o=r(a),d=r(s);return`30${r(s+a+4)}02${d}${i}02${o}${n}`}},Bl=BigInt(0),Da=BigInt(1),xNe=BigInt(2),K9=BigInt(3),ENe=BigInt(4);E7=class extends h7{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,wle(t);let r=w6(e);if(this.iHash=t.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(r.length>n?t.create().update(r).digest():r);for(let a=0;a<i.length;a++)i[a]^=54;this.iHash.update(i),this.oHash=t.create();for(let a=0;a<i.length;a++)i[a]^=106;this.oHash.update(i),i.fill(0)}update(t){return K2(this),this.iHash.update(t),this}digestInto(t){K2(this),l7(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:r,finished:n,destroyed:i,blockLen:a,outputLen:s}=this;return t=t,t.finished=n,t.destroyed=i,t.blockLen=a,t.outputLen=s,t.oHash=e._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},S7=(t,e,r)=>new E7(t,e).update(r).digest();S7.create=(t,e)=>new E7(t,e);k7=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),N9=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Gle=BigInt(1),WR=BigInt(2),U9=(t,e)=>(t+e/WR)/e;JR=b6(k7,void 0,void 0,{sqrt:Hle}),Fo=A7({a:BigInt(0),b:BigInt(7),Fp:JR,n:N9,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=N9,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Gle*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=r,s=BigInt("0x100000000000000000000000000000000"),o=U9(a*t,e),d=U9(-n*t,e),l=Zr(t-o*r-d*i,e),c=Zr(-o*n-d*a,e),u=l>s,f=c>s;if(u&&(l=e-l),f&&(c=e-c),l>s||c>s)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:c}}}},g7),SNe=BigInt(0),ANe=Fo.ProjectivePoint;g2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,MR=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),vd=(t,e)=>t<<32-e|t>>>e,kNe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;Zle=class{clone(){return this._cloneInto()}},_Ne={}.toString;eue=(t,e,r)=>t&e^~t&r,tue=(t,e,r)=>t&e^t&r^e&r,rue=class extends Zle{constructor(t,e,r,n){super(),this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=MR(this.buffer)}update(t){L9(this);let{view:e,buffer:r,blockLen:n}=this;t=T7(t);let i=t.length;for(let a=0;a<i;){let s=Math.min(n-this.pos,i-a);if(s===n){let o=MR(t);for(;n<=i-a;a+=n)this.process(o,a);continue}r.set(t.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){L9(this),Wle(t,this),this.finished=!0;let{buffer:e,view:r,blockLen:n,isLE:i}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(r,0),a=0);for(let c=a;c<n;c++)e[c]=0;Qle(r,n-8,BigInt(this.length*8),i),this.process(r,0);let s=MR(t),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=o/4,l=this.get();if(d>l.length)throw new Error("_sha2: outputLen bigger than state");for(let c=0;c<d;c++)s.setUint32(4*c,l[c],i)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let r=t.slice(0,e);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:r,length:n,finished:i,destroyed:a,pos:s}=this;return t.length=n,t.pos=s,t.finished=i,t.destroyed=a,n%e&&t.buffer.set(r),t}},nue=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]),af=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cf=new Uint32Array(64),iue=class extends rue{constructor(){super(64,32,8,!1),this.A=af[0]|0,this.B=af[1]|0,this.C=af[2]|0,this.D=af[3]|0,this.E=af[4]|0,this.F=af[5]|0,this.G=af[6]|0,this.H=af[7]|0}get(){let{A:t,B:e,C:r,D:n,E:i,F:a,G:s,H:o}=this;return[t,e,r,n,i,a,s,o]}set(t,e,r,n,i,a,s,o){this.A=t|0,this.B=e|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=s|0,this.H=o|0}process(t,e){for(let c=0;c<16;c++,e+=4)cf[c]=t.getUint32(e,!1);for(let c=16;c<64;c++){let u=cf[c-15],f=cf[c-2],h=vd(u,7)^vd(u,18)^u>>>3,p=vd(f,17)^vd(f,19)^f>>>10;cf[c]=p+cf[c-7]+h+cf[c-16]|0}let{A:r,B:n,C:i,D:a,E:s,F:o,G:d,H:l}=this;for(let c=0;c<64;c++){let u=vd(s,6)^vd(s,11)^vd(s,25),f=l+u+eue(s,o,d)+nue[c]+cf[c]|0,h=(vd(r,2)^vd(r,13)^vd(r,22))+tue(r,n,i)|0;l=d,d=o,o=s,s=a+f|0,a=i,i=n,n=r,r=f+h|0}r=r+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,d=d+this.G|0,l=l+this.H|0,this.set(r,n,i,a,s,o,d,l)}roundClean(){cf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},qv=Yle(()=>new iue);oue=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},I7=class{static digest(t){return oue(this,arguments,void 0,function*({data:e}){return qv(e)})}},aue=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},q9="urn:jwk:";Wi=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},due=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Xi=class Pd{static adjustSignatureToLowS(e){return Wi(this,arguments,void 0,function*({signature:r}){let n=Fo.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Wi(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield Pd.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"secp256k1",d:it.uint8Array(r).toBase64Url(),x:it.uint8Array(n.x).toBase64Url(),y:it.uint8Array(n.y).toBase64Url()};return i.kid=yield Ar({jwk:i}),i})}static bytesToPublicKey(e){return Wi(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield Pd.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"secp256k1",x:it.uint8Array(n.x).toBase64Url(),y:it.uint8Array(n.y).toBase64Url()};return i.kid=yield Ar({jwk:i}),i})}static compressPublicKey(e){return Wi(this,arguments,void 0,function*({publicKeyBytes:r}){return Fo.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Wi(this,arguments,void 0,function*({key:r}){let n=yield Pd.privateKeyToBytes({privateKey:r}),i=yield Pd.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"secp256k1",x:it.uint8Array(i.x).toBase64Url(),y:it.uint8Array(i.y).toBase64Url()};return a.kid=yield Ar({jwk:a}),a})}static convertDerToCompactSignature(e){return Wi(this,arguments,void 0,function*({derSignature:r}){return Fo.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Wi(this,arguments,void 0,function*({publicKeyBytes:r}){return Fo.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Wi(this,void 0,void 0,function*(){let e=Fo.utils.randomPrivateKey(),r=yield Pd.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield Ar({jwk:r}),r})}static getPublicKey(e){return Wi(this,arguments,void 0,function*({key:r}){var n;if(!(ch(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=r,a=due(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield Ar({jwk:a})),a})}static privateKeyToBytes(e){return Wi(this,arguments,void 0,function*({privateKey:r}){if(!ch(r))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return it.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Wi(this,arguments,void 0,function*({publicKey:r}){if(!(x6(r)&&r.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=it.base64Url(r.x).toUint8Array(),a=it.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...i,...a])})}static sharedSecret(e){return Wi(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.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 Pd.privateKeyToBytes({privateKey:r}),a=yield Pd.publicKeyToBytes({publicKey:n});return Fo.getSharedSecret(i,a,!0).slice(1)})}static sign(e){return Wi(this,arguments,void 0,function*({data:r,key:n}){let i=yield Pd.privateKeyToBytes({privateKey:n}),a=qv(r);return Fo.sign(a,i).toCompactRawBytes()})}static validatePrivateKey(e){return Wi(this,arguments,void 0,function*({privateKeyBytes:r}){return Fo.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Wi(this,arguments,void 0,function*({publicKeyBytes:r}){try{Fo.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Wi(this,arguments,void 0,function*({key:r,signature:n,data:i}){let a=yield Pd.publicKeyToBytes({publicKey:r}),s=qv(i);return Fo.verify(n,s,a,{lowS:!1})})}static getCurvePoint(e){return Wi(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Fo.getPublicKey(r));let n=Fo.ProjectivePoint.fromHex(r),i=_d(n.x,32),a=_d(n.y,32);return{x:i,y:a}})}},D7=b6(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),lue=D7.create(BigInt("-3")),uue=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),fue=A7({a:lue,b:uue,Fp:D7,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},g7),Aa=fue,Ji=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},pue=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},ws=class xd{static adjustSignatureToLowS(e){return Ji(this,arguments,void 0,function*({signature:r}){let n=Aa.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Ji(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield xd.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"P-256",d:it.uint8Array(r).toBase64Url(),x:it.uint8Array(n.x).toBase64Url(),y:it.uint8Array(n.y).toBase64Url()};return i.kid=yield Ar({jwk:i}),i})}static bytesToPublicKey(e){return Ji(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield xd.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"P-256",x:it.uint8Array(n.x).toBase64Url(),y:it.uint8Array(n.y).toBase64Url()};return i.kid=yield Ar({jwk:i}),i})}static compressPublicKey(e){return Ji(this,arguments,void 0,function*({publicKeyBytes:r}){return Aa.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Ji(this,arguments,void 0,function*({key:r}){let n=yield xd.privateKeyToBytes({privateKey:r}),i=yield xd.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"P-256",x:it.uint8Array(i.x).toBase64Url(),y:it.uint8Array(i.y).toBase64Url()};return a.kid=yield Ar({jwk:a}),a})}static convertDerToCompactSignature(e){return Ji(this,arguments,void 0,function*({derSignature:r}){return Aa.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Ji(this,arguments,void 0,function*({publicKeyBytes:r}){return Aa.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Ji(this,void 0,void 0,function*(){let e=Aa.utils.randomPrivateKey(),r=yield xd.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield Ar({jwk:r}),r})}static getPublicKey(e){return Ji(this,arguments,void 0,function*({key:r}){var n;if(!(ch(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=r,a=pue(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield Ar({jwk:a})),a})}static privateKeyToBytes(e){return Ji(this,arguments,void 0,function*({privateKey:r}){if(!ch(r))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return it.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Ji(this,arguments,void 0,function*({publicKey:r}){if(!(x6(r)&&r.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=it.base64Url(r.x).toUint8Array(),a=it.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...i,...a])})}static sharedSecret(e){return Ji(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.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 xd.privateKeyToBytes({privateKey:r}),a=yield xd.publicKeyToBytes({publicKey:n});return Aa.getSharedSecret(i,a,!0).slice(1)})}static sign(e){return Ji(this,arguments,void 0,function*({data:r,key:n}){let i=yield xd.privateKeyToBytes({privateKey:n}),a=qv(r);return Aa.sign(a,i).toCompactRawBytes()})}static validatePrivateKey(e){return Ji(this,arguments,void 0,function*({privateKeyBytes:r}){return Aa.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Ji(this,arguments,void 0,function*({publicKeyBytes:r}){try{Aa.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Ji(this,arguments,void 0,function*({key:r,signature:n,data:i}){let a=yield xd.publicKeyToBytes({publicKey:r}),s=qv(i);return Aa.verify(n,s,a,{lowS:!1})})}static getCurvePoint(e){return Ji(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Aa.getPublicKey(r));let n=Aa.ProjectivePoint.fromHex(r),i=_d(n.x,32),a=_d(n.y,32);return{x:i,y:a}})}},Il=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},z9=class extends Z2{bytesToPrivateKey(t){return Il(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield Xi.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield ws.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256",n}default:throw new $a(fo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return Il(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield Xi.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield ws.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256",n}default:throw new $a(fo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return Il(this,arguments,void 0,function*({key:e}){if(!ch(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield Xi.computePublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield ws.computePublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return Il(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let r=yield Xi.generateKey();return r.alg="ES256K",r}case"ES256":case"secp256r1":{let r=yield ws.generateKey();return r.alg="ES256",r}}})}getPublicKey(t){return Il(this,arguments,void 0,function*({key:e}){if(!ch(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield Xi.getPublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield ws.getPublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return Il(this,arguments,void 0,function*({key:e,data:r}){if(!ch(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield Xi.sign({key:e,data:r});case"P-256":return yield ws.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return Il(this,arguments,void 0,function*({key:e,signature:r,data:n}){if(!x6(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(e.crv){case"secp256k1":return yield Xi.verify({key:e,signature:r,data:n});case"P-256":return yield ws.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return Il(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield Xi.privateKeyToBytes({privateKey:e});case"P-256":return yield ws.privateKeyToBytes({privateKey:e});default:throw new $a(fo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return Il(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield Xi.publicKeyToBytes({publicKey:e});case"P-256":return yield ws.publicKeyToBytes({publicKey:e});default:throw new $a(fo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},d2=BigInt(4294967295),ZR=BigInt(32);mue=(t,e)=>BigInt(t>>>0)<<ZR|BigInt(e>>>0),yue=(t,e,r)=>t>>>r,gue=(t,e,r)=>t<<32-r|e>>>r,wue=(t,e,r)=>t>>>r|e<<32-r,vue=(t,e,r)=>t<<32-r|e>>>r,bue=(t,e,r)=>t<<64-r|e>>>r-32,Pue=(t,e,r)=>t>>>r-32|e<<64-r,xue=(t,e)=>e,Eue=(t,e)=>t,Sue=(t,e,r)=>t<<r|e>>>32-r,Aue=(t,e,r)=>e<<r|t>>>32-r,kue=(t,e,r)=>e<<r-32|t>>>64-r,_ue=(t,e,r)=>t<<r-32|e>>>64-r;Iue=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Due=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Rue=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Cue=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,$ue=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Bue=(t,e,r,n,i,a)=>e+r+n+i+a+(t/2**32|0)|0,Oue={fromBig:R7,split:hue,toBig:mue,shrSH:yue,shrSL:gue,rotrSH:wue,rotrSL:vue,rotrBH:bue,rotrBL:Pue,rotr32H:xue,rotr32L:Eue,rotlSH:Sue,rotlSL:Aue,rotlBH:kue,rotlBL:_ue,add:Tue,add3L:Iue,add3H:Due,add4L:Rue,add4H:Cue,add5H:Bue,add5L:$ue},Nt=Oue,[jue,Mue]=Nt.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(t=>BigInt(t))),df=new Uint32Array(80),lf=new Uint32Array(80),Kue=class extends y7{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:t,Al:e,Bh:r,Bl:n,Ch:i,Cl:a,Dh:s,Dl:o,Eh:d,El:l,Fh:c,Fl:u,Gh:f,Gl:h,Hh:p,Hl:m}=this;return[t,e,r,n,i,a,s,o,d,l,c,u,f,h,p,m]}set(t,e,r,n,i,a,s,o,d,l,c,u,f,h,p,m){this.Ah=t|0,this.Al=e|0,this.Bh=r|0,this.Bl=n|0,this.Ch=i|0,this.Cl=a|0,this.Dh=s|0,this.Dl=o|0,this.Eh=d|0,this.El=l|0,this.Fh=c|0,this.Fl=u|0,this.Gh=f|0,this.Gl=h|0,this.Hh=p|0,this.Hl=m|0}process(t,e){for(let w=0;w<16;w++,e+=4)df[w]=t.getUint32(e),lf[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let S=df[w-15]|0,k=lf[w-15]|0,T=Nt.rotrSH(S,k,1)^Nt.rotrSH(S,k,8)^Nt.shrSH(S,k,7),D=Nt.rotrSL(S,k,1)^Nt.rotrSL(S,k,8)^Nt.shrSL(S,k,7),K=df[w-2]|0,C=lf[w-2]|0,G=Nt.rotrSH(K,C,19)^Nt.rotrBH(K,C,61)^Nt.shrSH(K,C,6),z=Nt.rotrSL(K,C,19)^Nt.rotrBL(K,C,61)^Nt.shrSL(K,C,6),N=Nt.add4L(D,z,lf[w-7],lf[w-16]),V=Nt.add4H(N,T,G,df[w-7],df[w-16]);df[w]=V|0,lf[w]=N|0}let{Ah:r,Al:n,Bh:i,Bl:a,Ch:s,Cl:o,Dh:d,Dl:l,Eh:c,El:u,Fh:f,Fl:h,Gh:p,Gl:m,Hh:y,Hl:b}=this;for(let w=0;w<80;w++){let S=Nt.rotrSH(c,u,14)^Nt.rotrSH(c,u,18)^Nt.rotrBH(c,u,41),k=Nt.rotrSL(c,u,14)^Nt.rotrSL(c,u,18)^Nt.rotrBL(c,u,41),T=c&f^~c&p,D=u&h^~u&m,K=Nt.add5L(b,k,D,Mue[w],lf[w]),C=Nt.add5H(K,y,S,T,jue[w],df[w]),G=K|0,z=Nt.rotrSH(r,n,28)^Nt.rotrBH(r,n,34)^Nt.rotrBH(r,n,39),N=Nt.rotrSL(r,n,28)^Nt.rotrBL(r,n,34)^Nt.rotrBL(r,n,39),V=r&i^r&s^i&s,ee=n&a^n&o^a&o;y=p|0,b=m|0,p=f|0,m=h|0,f=c|0,h=u|0,{h:c,l:u}=Nt.add(d|0,l|0,C|0,G|0),d=s|0,l=o|0,s=i|0,o=a|0,i=r|0,a=n|0;let R=Nt.add3L(G,N,ee);r=Nt.add3H(R,C,z,V),n=R|0}({h:r,l:n}=Nt.add(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:a}=Nt.add(this.Bh|0,this.Bl|0,i|0,a|0),{h:s,l:o}=Nt.add(this.Ch|0,this.Cl|0,s|0,o|0),{h:d,l}=Nt.add(this.Dh|0,this.Dl|0,d|0,l|0),{h:c,l:u}=Nt.add(this.Eh|0,this.El|0,c|0,u|0),{h:f,l:h}=Nt.add(this.Fh|0,this.Fl|0,f|0,h|0),{h:p,l:m}=Nt.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:y,l:b}=Nt.add(this.Hh|0,this.Hl|0,y|0,b|0),this.set(r,n,i,a,s,o,d,l,c,u,f,h,p,m,y,b)}roundClean(){df.fill(0),lf.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)}},C7=m7(()=>new Kue),bc=BigInt(0),qo=BigInt(1),l2=BigInt(2),Nue=BigInt(8),Uue={zip215:!0};wv=BigInt(0),KR=BigInt(1);zv=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),F9=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),TNe=BigInt(0),Fue=BigInt(1),YR=BigInt(2),Gue=BigInt(5),G9=BigInt(10),Hue=BigInt(20),Vue=BigInt(40),H9=BigInt(80);Ba=b6(zv,void 0,!0),Fv={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ba,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:C7,randomBytes:v6,adjustScalarBytes:B7,uvRatio:Wue},eh=S6(Fv);INe=S6({...Fv,domain:O7}),DNe=S6({...Fv,domain:O7,prehash:C7}),Sv=zue({P:zv,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=zv,{pow_p_5_8:r,b2:n}=$7(t);return Zr(Pn(r,BigInt(3),e)*n,e)},adjustScalarBytes:B7,randomBytes:v6});Yue=(Ba.ORDER+BigInt(3))/BigInt(8),RNe=Ba.pow(YR,Yue),CNe=Ba.sqrt(Ba.neg(Ba.ONE)),$Ne=(Ba.ORDER-BigInt(5))/BigInt(8),BNe=BigInt(486662),ONe=Ole(Ba,Ba.neg(BigInt(486664))),jNe=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),MNe=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),KNe=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),NNe=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),UNe=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),ka=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Xue=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Qi=class mf{static bytesToPrivateKey(e){return ka(this,arguments,void 0,function*({privateKeyBytes:r}){let n=eh.getPublicKey(r),i={crv:"Ed25519",d:it.uint8Array(r).toBase64Url(),kty:"OKP",x:it.uint8Array(n).toBase64Url()};return i.kid=yield Ar({jwk:i}),i})}static bytesToPublicKey(e){return ka(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:it.uint8Array(r).toBase64Url()};return n.kid=yield Ar({jwk:n}),n})}static computePublicKey(e){return ka(this,arguments,void 0,function*({key:r}){let n=yield mf.privateKeyToBytes({privateKey:r}),i=eh.getPublicKey(n),a={kty:"OKP",crv:"Ed25519",x:it.uint8Array(i).toBase64Url()};return a.kid=yield Ar({jwk:a}),a})}static convertPrivateKeyToX25519(e){return ka(this,arguments,void 0,function*({privateKey:r}){let n=yield mf.privateKeyToBytes({privateKey:r}),i=Zue(n),a=Sv.getPublicKey(i),s={kty:"OKP",crv:"X25519",d:it.uint8Array(i).toBase64Url(),x:it.uint8Array(a).toBase64Url()};return s.kid=yield Ar({jwk:s}),s})}static convertPublicKeyToX25519(e){return ka(this,arguments,void 0,function*({publicKey:r}){let n=yield mf.publicKeyToBytes({publicKey:r});if(!(yield mf.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let i=Jue(n),a={kty:"OKP",crv:"X25519",x:it.uint8Array(i).toBase64Url()};return a.kid=yield Ar({jwk:a}),a})}static generateKey(){return ka(this,void 0,void 0,function*(){let e=eh.utils.randomPrivateKey(),r=yield mf.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield Ar({jwk:r}),r})}static getPublicKey(e){return ka(this,arguments,void 0,function*({key:r}){var n;if(!(Ml(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=r,a=Xue(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield Ar({jwk:a})),a})}static privateKeyToBytes(e){return ka(this,arguments,void 0,function*({privateKey:r}){if(!Ml(r))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return it.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return ka(this,arguments,void 0,function*({publicKey:r}){if(!E6(r))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return it.base64Url(r.x).toUint8Array()})}static sign(e){return ka(this,arguments,void 0,function*({key:r,data:n}){let i=yield mf.privateKeyToBytes({privateKey:r});return eh.sign(n,i)})}static validatePublicKey(e){return ka(this,arguments,void 0,function*({publicKeyBytes:r}){try{eh.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return ka(this,arguments,void 0,function*({key:r,signature:n,data:i}){let a=yield mf.publicKeyToBytes({publicKey:r});return eh.verify(n,i,a)})}},Dl=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Que=class extends Z2{bytesToPrivateKey(t){return Dl(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"Ed25519":{let n=yield Qi.bytesToPrivateKey({privateKeyBytes:r});return n.alg="EdDSA",n}default:throw new $a(fo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return Dl(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"Ed25519":{let n=yield Qi.bytesToPublicKey({publicKeyBytes:r});return n.alg="EdDSA",n}default:throw new $a(fo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return Dl(this,arguments,void 0,function*({key:e}){if(!Ml(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield Qi.computePublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return Dl(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let r=yield Qi.generateKey();return r.alg="EdDSA",r}}})}getPublicKey(t){return Dl(this,arguments,void 0,function*({key:e}){if(!Ml(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield Qi.getPublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return Dl(this,arguments,void 0,function*({key:e,data:r}){if(!Ml(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield Qi.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return Dl(this,arguments,void 0,function*({key:e,signature:r,data:n}){if(!E6(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield Qi.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return Dl(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"Ed25519":return yield Qi.privateKeyToBytes({privateKey:e});default:throw new $a(fo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return Dl(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield Qi.publicKeyToBytes({publicKey:e});default:throw new $a(fo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},efe=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},tfe=class extends Z2{digest(t){return efe(this,arguments,void 0,function*({algorithm:e,data:r}){switch(e){case"SHA-256":return yield I7.digest({data:r})}})}},uf=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},rfe=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Dy=class Av{static bytesToPrivateKey(e){return uf(this,arguments,void 0,function*({privateKeyBytes:r}){let n=Sv.getPublicKey(r),i={kty:"OKP",crv:"X25519",d:it.uint8Array(r).toBase64Url(),x:it.uint8Array(n).toBase64Url()};return i.kid=yield Ar({jwk:i}),i})}static bytesToPublicKey(e){return uf(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:it.uint8Array(r).toBase64Url()};return n.kid=yield Ar({jwk:n}),n})}static computePublicKey(e){return uf(this,arguments,void 0,function*({key:r}){let n=yield Av.privateKeyToBytes({privateKey:r}),i=Sv.getPublicKey(n),a={kty:"OKP",crv:"X25519",x:it.uint8Array(i).toBase64Url()};return a.kid=yield Ar({jwk:a}),a})}static generateKey(){return uf(this,void 0,void 0,function*(){let e=Sv.utils.randomPrivateKey(),r=yield Av.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield Ar({jwk:r}),r})}static getPublicKey(e){return uf(this,arguments,void 0,function*({key:r}){var n;if(!(Ml(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=r,a=rfe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield Ar({jwk:a})),a})}static privateKeyToBytes(e){return uf(this,arguments,void 0,function*({privateKey:r}){if(!Ml(r))throw new Error("X25519: The provided key is not a valid OKP private key.");return it.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return uf(this,arguments,void 0,function*({publicKey:r}){if(!E6(r))throw new Error("X25519: The provided key is not a valid OKP public key.");return it.base64Url(r.x).toUint8Array()})}static sharedSecret(e){return uf(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.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 Av.privateKeyToBytes({privateKey:r}),a=yield Av.publicKeyToBytes({publicKey:n});return Sv.getSharedSecret(i,a)})}},vv=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},nfe=class extends Z2{bytesToPrivateKey(t){return vv(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"X25519":return Dy.bytesToPrivateKey({privateKeyBytes:r});default:throw new $a(fo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return vv(this,arguments,void 0,function*({key:e}){if(!Ml(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Dy.computePublicKey({key:e});default:throw new $a(fo.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(t){return vv(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return Dy.generateKey();default:throw new $a(fo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(t){return vv(this,arguments,void 0,function*({key:e}){if(!Ml(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Dy.getPublicKey({key:e});default:throw new $a(fo.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return vv(this,arguments,void 0,function*({privateKey:e}){return Dy.privateKeyToBytes({privateKey:e})})}},Rl=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},NR={Ed25519:{implementation:Que,names:["Ed25519"]},secp256k1:{implementation:z9,names:["ES256K","secp256k1"]},secp256r1:{implementation:z9,names:["ES256","secp256r1"]},"SHA-256":{implementation:tfe,names:["SHA-256"]},X25519:{implementation:nfe,names:["X25519"]}},Ec=class{constructor(t){var e;this._algorithmInstances=new Map,this._keyStore=(e=t?.keyStore)!==null&&e!==void 0?e:new ale}digest(t){return Rl(this,arguments,void 0,function*({algorithm:e,data:r}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:r})})}exportKey(t){return Rl(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(t){return Rl(this,arguments,void 0,function*({algorithm:e}){let r=yield this.getAlgorithm({algorithm:e}).generateKey({algorithm:e});if(r?.kid===void 0)throw new Error("Generated key is missing a required property: kid");let n=`${q9}${r.kid}`;return yield this._keyStore.set(n,r),n})}getKeyUri(t){return Rl(this,arguments,void 0,function*({key:e}){let r=yield Ar({jwk:e});return`${q9}${r}`})}getPublicKey(t){return Rl(this,arguments,void 0,function*({keyUri:e}){let r=yield this.getPrivateKey({keyUri:e}),n=this.getAlgorithmName({key:r});return yield this.getAlgorithm({algorithm:n}).getPublicKey({key:r})})}importKey(t){return Rl(this,arguments,void 0,function*({key:e}){var r;if(!cue(e))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let n=structuredClone(e);(r=n.kid)!==null&&r!==void 0||(n.kid=yield Ar({jwk:n}));let i=yield this.getKeyUri({key:n});return yield this._keyStore.set(i,n),i})}sign(t){return Rl(this,arguments,void 0,function*({keyUri:e,data:r}){let n=yield this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:i}).sign({data:r,key:n})})}verify(t){return Rl(this,arguments,void 0,function*({key:e,signature:r,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:r,data:n})})}getAlgorithm({algorithm:t}){var e;let r=(e=NR[t])===null||e===void 0?void 0:e.implementation;if(!r)throw new Error(`Algorithm not supported: ${t}`);return this._algorithmInstances.has(r)||this._algorithmInstances.set(r,new r),this._algorithmInstances.get(r)}getAlgorithmName({key:t}){let e=t.alg,r=t.crv;for(let n in NR){let i=NR[n];if(e&&i.names.includes(e)||r&&i.names.includes(r))return n}throw new Error(`Unable to determine algorithm based on provided input: alg=${e}, crv=${r}`)}getPrivateKey(t){return Rl(this,arguments,void 0,function*({keyUri:e}){let r=yield this._keyStore.get(e);if(!r)throw new Error(`Key not found: ${e}`);return r})}},ife=class XR{static getJoseSignatureAlgorithmFromPublicKey(e){let r={Ed25519:"EdDSA","P-256":"ES256","P-384":"ES384","P-521":"ES512",secp256k1:"ES256K"};if(e.alg&&Object.values(r).includes(e.alg))return e.alg;if(e.crv&&Object.keys(r).includes(e.crv))return r[e.crv];throw new Error(`Unable to determine algorithm based on provided input: alg=${e.alg}, crv=${e.crv}. Supported 'alg' values: ${Object.values(r).join(", ")}. Supported 'crv' values: ${Object.keys(r).join(", ")}.`)}static randomBytes(e){return Xle(e)}static randomUuid(){return g2.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 r=Math.pow(10,e)-1,n;if(e<=6){let i=Math.pow(10,e);do{let a=XR.randomBytes(Math.ceil(e/2));n=new DataView(a.buffer).getUint16(0,!1)%i}while(n>r)}else{let i=Math.pow(10,10);do{let a=XR.randomBytes(4);n=new DataView(a.buffer).getUint32(0,!1)%i}while(n>r)}return n.toString().padStart(e,"0")}},sfe=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];Se=class{constructor(t,e,r){this.major=t,this.majorEncoded=t<<5,this.name=e,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(t){return this.major<t.major?-1:this.major>t.major?1:0}static equals(t,e){return t===e||t.major===e.major&&t.name===e.name}};Se.uint=new Se(0,"uint",!0);Se.negint=new Se(1,"negint",!0);Se.bytes=new Se(2,"bytes",!0);Se.string=new Se(3,"string",!0);Se.array=new Se(4,"array",!1);Se.map=new Se(5,"map",!1);Se.tag=new Se(6,"tag",!1);Se.float=new Se(7,"float",!0);Se.false=new Se(7,"false",!0);Se.true=new Se(7,"true",!0);Se.null=new Se(7,"null",!0);Se.undefined=new Se(7,"undefined",!0);Se.break=new Se(7,"break",!0);tt=class{constructor(t,e,r){this.type=t,this.value=e,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}},Zv=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",cfe=new TextEncoder;dfe=24,lfe=200,ufe=Zv?t=>t.length>=dfe?globalThis.Buffer.from(t):V9(t):t=>t.length>=lfe?cfe.encode(t):V9(t),Cl=t=>Uint8Array.from(t),ffe=Zv?(t,e,r)=>N2(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),pfe=Zv?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),j7(globalThis.Buffer.concat(t,e))):(t,e)=>{let r=new Uint8Array(e),n=0;for(let i of t)n+i.length>r.length&&(i=i.subarray(0,r.length-n)),r.set(i,n),n+=i.length;return r},hfe=Zv?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);mfe=256,K7=class{constructor(t=mfe){this.chunkSize=t,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(t){let e=this.chunks[this.chunks.length-1];if(this.cursor+t.length<=this.maxCursor+1){let r=e.length-(this.maxCursor-this.cursor)-1;e.set(t,r)}else{if(e){let r=e.length-(this.maxCursor-this.cursor)-1;r<e.length&&(this.chunks[this.chunks.length-1]=e.subarray(0,r),this.maxCursor=this.cursor-1)}t.length<64&&t.length<this.chunkSize?(e=hfe(this.chunkSize),this.chunks.push(e),this.maxCursor+=e.length,this._initReuseChunk===null&&(this._initReuseChunk=e),e.set(t,0)):(this.chunks.push(t),this.maxCursor+=t.length)}this.cursor+=t.length}toBytes(t=!1){let e;if(this.chunks.length===1){let r=this.chunks[0];t&&this.cursor>r.length/2?(e=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):e=ffe(r,0,this.cursor)}else e=pfe(this.chunks,this.cursor);return t&&this.reset(),e}},yfe=class{constructor(t){this.dest=t,this.cursor=0,this.chunks=[t]}reset(){this.cursor=0}push(t){if(this.cursor+t.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(t,this.cursor),this.cursor+=t.length}toBytes(t=!1){let e=this.dest.subarray(0,this.cursor);return t&&this.reset(),e}},xn="CBOR decode error:",N7="CBOR encode error:",Yv=[];Yv[23]=1;Yv[24]=2;Yv[25]=3;Yv[26]=5;Yv[27]=9;es=[24,256,65536,4294967296,BigInt("18446744073709551616")];vh.encodedSize=function(t){return ja.encodedSize(t.value)};ja.encodedSize=function(t){return t<es[0]?1:t<es[1]?2:t<es[2]?3:t<es[3]?5:9};vh.compareTokens=function(t,e){return t.value<e.value?-1:t.value>e.value?1:0};A6=BigInt(-1),U7=BigInt(1);k6.encodedSize=function(t){let e=t.value,r=typeof e=="bigint"?e*A6-U7:e*-1-1;return r<es[0]?1:r<es[1]?2:r<es[2]?3:r<es[3]?5:9};k6.compareTokens=function(t,e){return t.value<e.value?1:t.value>e.value?-1:0};X2.encodedSize=function(t){let e=U2(t);return ja.encodedSize(e.length)+e.length};X2.compareTokens=function(t,e){return Dfe(U2(t),U2(e))};W9=new TextDecoder,Rfe=32;Kfe=X2;_6.compareTokens=vh.compareTokens;_6.encodedSize=function(t){return ja.encodedSize(t.value)};T6.compareTokens=vh.compareTokens;T6.encodedSize=function(t){return ja.encodedSize(t.value)};I6.compareTokens=vh.compareTokens;I6.encodedSize=function(t){return ja.encodedSize(t.value)};L7=20,q7=21,z7=22,F7=23;R6.encodedSize=function(t,e){let r=t.value;if(r===!1||r===!0||r===null||r===void 0)return 1;if(!e||e.float64!==!0){H7(r);let n=C6(Pc,1);if(r===n||Number.isNaN(r))return 3;if(V7(r),n=$6(Pc,1),r===n)return 5}return 9};G7=new ArrayBuffer(9),Ta=new DataView(G7,1),Pc=new Uint8Array(G7,0);R6.compareTokens=vh.compareTokens;je=[];for(let t=0;t<=23;t++)je[t]=mr;je[24]=gfe;je[25]=wfe;je[26]=vfe;je[27]=bfe;je[28]=mr;je[29]=mr;je[30]=mr;je[31]=mr;for(let t=32;t<=55;t++)je[t]=mr;je[56]=Pfe;je[57]=xfe;je[58]=Efe;je[59]=Sfe;je[60]=mr;je[61]=mr;je[62]=mr;je[63]=mr;for(let t=64;t<=87;t++)je[t]=Afe;je[88]=kfe;je[89]=_fe;je[90]=Tfe;je[91]=Ife;je[92]=mr;je[93]=mr;je[94]=mr;je[95]=Q2("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)je[t]=$fe;je[120]=Bfe;je[121]=Ofe;je[122]=jfe;je[123]=Mfe;je[124]=mr;je[125]=mr;je[126]=mr;je[127]=Q2("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)je[t]=Nfe;je[152]=Ufe;je[153]=Lfe;je[154]=qfe;je[155]=zfe;je[156]=mr;je[157]=mr;je[158]=mr;je[159]=Ffe;for(let t=160;t<=183;t++)je[t]=Gfe;je[184]=Hfe;je[185]=Vfe;je[186]=Wfe;je[187]=Jfe;je[188]=mr;je[189]=mr;je[190]=mr;je[191]=Zfe;for(let t=192;t<=215;t++)je[t]=Yfe;je[216]=Xfe;je[217]=Qfe;je[218]=epe;je[219]=tpe;je[220]=mr;je[221]=mr;je[222]=mr;je[223]=mr;for(let t=224;t<=243;t++)je[t]=Q2("simple values are not supported");je[244]=mr;je[245]=mr;je[246]=mr;je[247]=rpe;je[248]=Q2("simple values are not supported");je[249]=ipe;je[250]=spe;je[251]=ope;je[252]=mr;je[253]=mr;je[254]=mr;je[255]=npe;Nl=[];for(let t=0;t<24;t++)Nl[t]=new tt(Se.uint,t,1);for(let t=-1;t>=-24;t--)Nl[31-t]=new tt(Se.negint,t,1);Nl[64]=new tt(Se.bytes,new Uint8Array(0),1);Nl[96]=new tt(Se.string,"",1);Nl[128]=new tt(Se.array,0,1);Nl[160]=new tt(Se.map,0,1);Nl[244]=new tt(Se.false,!1,1);Nl[245]=new tt(Se.true,!0,1);Nl[246]=new tt(Se.null,null,1);dpe=Object.freeze({float64:!0,mapSorter:hpe,quickEncodeToken:cpe});upe=lpe(),fpe=new K7,J9=class J7{constructor(e,r){this.obj=e,this.parent=r}includes(e){let r=this;do if(r.obj===e)return!0;while(r=r.parent);return!1}static createCheck(e,r){if(e&&e.includes(r))throw new Error(`${N7} object contains circular references`);return new J7(r,e)}},ff={null:new tt(Se.null,null),undefined:new tt(Se.undefined,void 0),true:new tt(Se.true,!0),false:new tt(Se.false,!1),emptyArray:new tt(Se.array,0),emptyMap:new tt(Se.map,0)},Pf={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new tt(Se.float,t):t>=0?new tt(Se.uint,t):new tt(Se.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new tt(Se.uint,t):new tt(Se.negint,t)},Uint8Array(t,e,r,n){return new tt(Se.bytes,t)},string(t,e,r,n){return new tt(Se.string,t)},boolean(t,e,r,n){return t?ff.true:ff.false},null(t,e,r,n){return ff.null},undefined(t,e,r,n){return ff.undefined},ArrayBuffer(t,e,r,n){return new tt(Se.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new tt(Se.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[ff.emptyArray,new tt(Se.break)]:ff.emptyArray;n=J9.createCheck(n,t);let i=[],a=0;for(let s of t)i[a++]=w2(s,r,n);return r.addBreakTokens?[new tt(Se.array,t.length),i,new tt(Se.break)]:[new tt(Se.array,t.length),i]},Object(t,e,r,n){let i=e!=="Object",a=i?t.keys():Object.keys(t),s=i?t.size:a.length,o;if(s){o=new Array(s),n=J9.createCheck(n,t);let d=!i&&r.ignoreUndefinedProperties,l=0;for(let c of a){let u=i?t.get(c):t[c];d&&u===void 0||(o[l++]=[w2(c,r,n),w2(u,r,n)])}l<s&&(o.length=l)}return o?.length?(ppe(o,r),r.addBreakTokens?[new tt(Se.map,o.length),o,new tt(Se.break)]:[new tt(Se.map,o.length),o]):r.addBreakTokens===!0?[ff.emptyMap,new tt(Se.break)]:ff.emptyMap}};Pf.Map=Pf.Object;Pf.Buffer=Pf.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Pf[`${t}Array`]=Pf.DataView;LNe=Se.uint.majorEncoded,qNe=Se.negint.majorEncoded,zNe=Se.bytes.majorEncoded,FNe=Se.string.majorEncoded,GNe=Se.array.majorEncoded,HNe=Se.float.majorEncoded|L7,VNe=Se.float.majorEncoded|q7,WNe=Se.float.majorEncoded|z7,JNe=Se.float.majorEncoded|F7,ZNe=BigInt(-1),YNe=BigInt(1);XNe=Symbol.for("DONE"),QNe=Symbol.for("BREAK");(function(t){t[t.OKP=1]="OKP",t[t.EC2=2]="EC2",t[t.Symmetric=4]="Symmetric"})(Y9||(Y9={}));(function(t){t[t.P256=1]="P256",t[t.P384=2]="P384",t[t.P521=3]="P521",t[t.X25519=4]="X25519",t[t.X448=5]="X448",t[t.Ed25519=6]="Ed25519",t[t.Ed448=7]="Ed448",t[t.Secp256k1=8]="Secp256k1"})(vs||(vs={}));(function(t){t[t.EdDSA=-8]="EdDSA",t[t.ES256=-7]="ES256",t[t.ES384=-35]="ES384",t[t.ES512=-36]="ES512",t[t.ES256K=-47]="ES256K"})(Ca||(Ca={}));(function(t){t[t.Kty=1]="Kty",t[t.Kid=2]="Kid",t[t.Alg=3]="Alg",t[t.KeyOps=4]="KeyOps",t[t.BaseIv=5]="BaseIv"})(X9||(X9={}));(function(t){t[t.Crv=-1]="Crv",t[t.X=-2]="X",t[t.Y=-3]="Y",t[t.D=-4]="D"})(Q9||(Q9={}));eUe={"P-256":vs.P256,"P-384":vs.P384,"P-521":vs.P521,X25519:vs.X25519,Ed25519:vs.Ed25519,Ed448:vs.Ed448,secp256k1:vs.Secp256k1},tUe={[vs.P256]:"P-256",[vs.P384]:"P-384",[vs.P521]:"P-521",[vs.X25519]:"X25519",[vs.Ed25519]:"Ed25519",[vs.Ed448]:"Ed448",[vs.Secp256k1]:"secp256k1"},rUe={EdDSA:Ca.EdDSA,ES256:Ca.ES256,ES384:Ca.ES384,ES512:Ca.ES512,ES256K:Ca.ES256K},nUe={[Ca.EdDSA]:"EdDSA",[Ca.ES256]:"ES256",[Ca.ES384]:"ES384",[Ca.ES512]:"ES512",[Ca.ES256K]:"ES256K"};(function(t){t[t.Alg=1]="Alg",t[t.Crit=2]="Crit",t[t.ContentType=3]="ContentType",t[t.Kid=4]="Kid"})(eq||(eq={}));(function(t){t[t.Iss=1]="Iss",t[t.Sub=2]="Sub",t[t.Aud=3]="Aud",t[t.Exp=4]="Exp",t[t.Nbf=5]="Nbf",t[t.Iat=6]="Iat",t[t.Cti=7]="Cti",t[t.Nonce=10]="Nonce",t[t.Ueid=256]="Ueid",t[t.Sueids=257]="Sueids",t[t.Oemid=258]="Oemid",t[t.Hwmodel=259]="Hwmodel",t[t.Hwversion=260]="Hwversion",t[t.Secboot=262]="Secboot",t[t.Dbgstat=263]="Dbgstat",t[t.Location=264]="Location",t[t.Profile=265]="Profile",t[t.Submods=266]="Submods",t[t.Measres=272]="Measres",t[t.Intuse=268]="Intuse"})(tq||(tq={}));(function(t){t[t.Enabled=0]="Enabled",t[t.Disabled=1]="Disabled",t[t.DisabledSinceBoot=2]="DisabledSinceBoot",t[t.DisabledPermanently=3]="DisabledPermanently",t[t.DisabledFullyAndPermanently=4]="DisabledFullyAndPermanently"})(rq||(rq={}));(function(t){t[t.Unrestricted=1]="Unrestricted",t[t.Restricted=2]="Restricted",t[t.SecureRestricted=3]="SecureRestricted",t[t.Hardware=4]="Hardware"})(nq||(nq={}));B6={};u6(B6,{extractDidFragment:()=>Gs,getServices:()=>ype,getVerificationMethodByKey:()=>gpe,getVerificationMethodTypes:()=>Y7,getVerificationMethods:()=>eE,getVerificationRelationshipsById:()=>X7,isDidService:()=>Q7,isDidVerificationMethod:()=>L2,isDwnDidService:()=>wpe,isPortableDid:()=>bh,keyBytesToMultibaseId:()=>ez,multibaseIdToKeyBytes:()=>tz});bs=class rz{constructor({uri:e,document:r,metadata:n,keyManager:i}){this.uri=e,this.document=r,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 r=[];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});r.push({...a})}e.privateKeys=r}return e}async getSigner(e){let r=this.document.verificationMethod?.find(s=>Gs(s.id)===(Gs(e?.methodId)??Gs(this.document.assertionMethod?.[0])));if(!(r&&r.publicKeyJwk))throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");let n=await this.keyManager.getKeyUri({key:r.publicKeyJwk}),i=await this.keyManager.getPublicKey({keyUri:n}),a=this.keyManager;return{algorithm:ife.getJoseSignatureAlgorithmFromPublicKey(i),keyId:r.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:r=new Ec}){let n=eE({didDocument:e.document});if(n.length===0)throw new rt("invalidDidDocument","At least one verification method is required but 0 were given");for(let i of e.privateKeys??[]){let a=await r.getKeyUri({key:i});await r.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1)||await r.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 r.getKeyUri({key:i.publicKeyJwk});await r.getPublicKey({keyUri:a})}return new rz({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:r})}},eb=class{static async getSigningMethod(t){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")}static async resolve(t,e){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")}},nz=(t=>(t[t.Discoverable=0]="Discoverable",t[t.Organization=1]="Organization",t[t.Government=2]="Government",t[t.Corporation=3]="Corporation",t[t.LocalBusiness=4]="LocalBusiness",t[t.SoftwarePackage=5]="SoftwarePackage",t[t.WebApp=6]="WebApp",t[t.FinancialInstitution=7]="FinancialInstitution",t))(nz||{}),O6=(t=>(t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519",t))(O6||{}),iz=(t=>(t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm",t))(iz||{}),iq="0123456789abcdef",sz=[],sq=[];for(let t=0;t<256;t++)sz[t]=iq[t>>4&15]+iq[t&15],t<16&&(t<10?sq[48+t]=t:sq[87+t]=t);vpe=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=sz[t[n++]];return r},bpe=(t,e=0)=>{let r=t.length||0;if(!e){let s=r;for(;s--;)e+=t[s].length}let n=new Uint8Array(e),i=e,a=r;for(;a--;)i-=t[a].length,n.set(t[a],i);return n},oq="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ppe=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(bv=0;bv<oq.length;bv++)Ppe[oq.charCodeAt(bv)]=bv;xpe=new TextDecoder,oz=(t,e)=>e?new TextDecoder(e).decode(t):xpe.decode(t),Epe=new TextEncoder,Kl=t=>Epe.encode(t),aq=typeof window<"u"?window:self,cq=aq.crypto||aq.msCrypto||{},iUe=cq.subtle||cq.webkitSubtle;vr.bytes=-1;vr._floatConversionDetected=!1;vr._encode=function(t,e){if(e!=null)switch(az(e)){case"object":vr.dict(t,e);break;case"map":vr.dictMap(t,e);break;case"array":vr.list(t,e);break;case"set":vr.listSet(t,e);break;case"string":vr.string(t,e);break;case"number":vr.number(t,e);break;case"boolean":vr.number(t,e);break;case"arraybufferview":vr.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":vr.buffer(t,new Uint8Array(e));break}};tE=new Uint8Array([101]),cz=new Uint8Array([100]),dz=new Uint8Array([108]);vr.buffer=function(t,e){t.push(Kl(e.length+":"),e)};vr.string=function(t,e){t.push(Kl(Kl(e).byteLength+":"+e))};vr.number=function(t,e){if(Number.isInteger(e))return t.push(Kl("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,i=e%r<<0,a=n*r+i;t.push(Kl("i"+a+"e")),a!==e&&!vr._floatConversionDetected&&(vr._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())};vr.dict=function(t,e){t.push(cz);let r=0,n,i=Object.keys(e).sort(),a=i.length;for(;r<a;r++)n=i[r],e[n]!=null&&(vr.string(t,n),vr._encode(t,e[n]));t.push(tE)};vr.dictMap=function(t,e){t.push(cz);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?vr._encode(t,n):vr.string(t,String(n)),vr._encode(t,e.get(n)));t.push(tE)};vr.list=function(t,e){let r=0,n=e.length;for(t.push(dz);r<n;r++)e[r]!=null&&vr._encode(t,e[r]);t.push(tE)};vr.listSet=function(t,e){t.push(dz);for(let r of e)r!=null&&vr._encode(t,r);t.push(tE)};Spe=vr,Ape=105,kpe=58,_pe=100,Tpe=108,j6=101;bt.bytes=0;bt.position=0;bt.data=null;bt.encoding=null;bt.next=function(){switch(bt.data[bt.position]){case _pe:return bt.dictionary();case Tpe:return bt.list();case Ape:return bt.integer();default:return bt.buffer()}};bt.find=function(t){let e=bt.position,r=bt.data.length,n=bt.data;for(;e<r;){if(n[e]===t)return e;e++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(t)+'" [0x'+t.toString(16)+"]")};bt.dictionary=function(){bt.position++;let t={};for(;bt.data[bt.position]!==j6;){let e=bt.buffer(),r=oz(e);r.includes("\uFFFD")&&(r=vpe(e)),t[r]=bt.next()}return bt.position++,t};bt.list=function(){bt.position++;let t=[];for(;bt.data[bt.position]!==j6;)t.push(bt.next());return bt.position++,t};bt.integer=function(){let t=bt.find(j6),e=lz(bt.data,bt.position+1,t);return bt.position+=t+1-bt.position,e};bt.buffer=function(){let t=bt.find(kpe),e=lz(bt.data,bt.position,t),r=++t+e;return bt.position=r,bt.encoding?oz(bt.data.slice(t,r)):bt.data.slice(t,r)};Ipe=bt;uz=rE,Ope=uz,fz={encode:Spe,decode:Ipe,byteLength:uz,encodingLength:Ope},jpe=/^(\d{1,3}\.){3,3}\d{1,3}$/,Mpe=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,Ad={name:"v4",size:4,isFormat:t=>jpe.test(t),encode(t,e,r){r=~~r,e=e||new Uint8Array(r+4);let n=t.length,i=0;for(let a=0;a<n;){let s=t.charCodeAt(a++);s===46?(e[r++]=i,i=0):i=i*10+(s-48)}return e[r]=i,e},decode(t,e){return e=~~e,`${t[e++]}.${t[e++]}.${t[e++]}.${t[e]}`}},bf={name:"v6",size:16,isFormat:t=>t.length>0&&Mpe.test(t),encode(t,e,r){r=~~r;let n=r+16,i=-1,a=0,s=0,o=!0,d=!1;e=e||new Uint8Array(r+16);for(let l=0;l<t.length;l++){let c=t.charCodeAt(l);c===58?(o?i!==-1?(r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2):r<n&&(i=r):(d===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=a>>8),r<n-1&&(e[r+1]=a&255),r+=2),a=0,s=0),o=!0,d=!1):c===46?(r<n&&(e[r]=s),r++,s=0,a=0,o=!1,d=!0):(o=!1,c>=97?c-=87:c>=65?c-=55:(c-=48,s=s*10+c),a=(a<<4)+c)}if(o===!1)d===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=a>>8),r<n-1&&(e[r+1]=a&255),r+=2);else if(i===0)r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2;else if(i!==-1){r+=2;for(let l=Math.min(r-1,n-1);l>=i+2;l--)e[l]=e[l-2];e[i]=0,e[i+1]=0,i=r}if(i!==r&&i!==-1)for(r>n-2&&(r=n-2);n>i;)e[--n]=r<n&&r>i?e[--r]:0;else for(;r<n;)e[r++]=0;return e},decode(t,e){e=~~e;let r="";for(let n=0;n<16;n+=2)n!==0&&(r+=":"),r+=(t[e+n]<<8|t[e+n+1]).toString(16);return r.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};Hv.bytes=0;rb.bytes=0;fh=t=>t instanceof Uint8Array;kv={},gz=new Array(255);for(let t=0;t<=15;t+=1){let e=t.toString(16),r=e.toUpperCase();for(let n=0;n<=15;n+=1){let i=n.toString(16),a=i.toUpperCase(),s=t<<4|n,o=`${e}${i}`;gz[s]=o,kv[o]=s,kv[`${r}${i}`]=s,kv[`${e}${a}`]=s,kv[`${r}${a}`]=s}}Hpe=Math.pow(2,24),Vpe=Math.pow(2,16),Wpe=Math.pow(2,8),Ol=(t,e)=>t[e]*Hpe+t[e+1]*Vpe+t[e+2]*Wpe+t[e+3],Ut=(t,e)=>t[e]<<8|t[e+1],jl=(t,e,r)=>(e=+e,t[r+3]=e,e=e>>>8,t[r+2]=e,e=e>>>8,t[r+1]=e,e=e>>>8,t[r]=e,r+4),st=(t,e,r)=>(t[r]=e>>8,t[r+1]=e&255,r+2);Zpe=0,uq=32768,QR=32768,Ype=~QR,wz=32768,Xpe=~wz;Ze=Fr({encode(t,e,r){e||(e=new Uint8Array(Ze.encodingLength(t))),r||(r=0);let n=r,i=t.replace(/^\.|\.$/gm,"");if(i.length){let a=i.split(".");for(let s=0;s<a.length;s++){let o=K6(e,a[s],r+1);e[r]=o,r+=o+1}}return e[r++]=0,Ze.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=[],n=e,i=0,a=0,s=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let o=t[e++];if(a+=s?0:1,o===0)break;if(o&192)if((o&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let d=Ut(t,e-1)-49152;if(d>=n)throw new Error("Cannot decode name (bad pointer)");e=d,n=d,a+=s?0:1,s=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+o>t.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=o+1,i>254)throw new Error("Cannot decode name (name too long)");r.push(rb(t,e,e+o)),e+=o,a+=s?0:o}}return Ze.decode.bytes=a,r.length===0?".":r.join(".")},encodingLength(t){return t==="."||t===".."?1:xf(t.replace(/^\.|\.$/gm,""))+2}}),li=Fr({encode(t,e,r){e||(e=new Uint8Array(li.encodingLength(t))),r||(r=0);let n=K6(e,t,r+1);return e[r]=n,li.encode.bytes=n+1,e},decode(t,e){e||(e=0);let r=t[e],n=rb(t,e+1,e+1+r);return li.decode.bytes=r+1,n},encodingLength(t){return xf(t)+1}}),Ry=Fr({bytes:12,encode(t,e,r){e||(e=new Uint8Array(Ry.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?uq:Zpe;return st(e,t.id||0,r),st(e,n|i,r+2),st(e,t.questions.length,r+4),st(e,t.answers.length,r+6),st(e,t.authorities.length,r+8),st(e,t.additionals.length,r+10),e},decode(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=Ut(t,e+2);return{id:Ut(t,e),type:r&uq?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:qpe(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:Lpe(r&15),questions:new Array(Ut(t,e+4)),answers:new Array(Ut(t,e+6)),authorities:new Array(Ut(t,e+8)),additionals:new Array(Ut(t,e+10))}},encodingLength(){return 12}}),v2=Fr({encode(t,e,r){e||(e=new Uint8Array(v2.encodingLength(t))),r||(r=0);let n=t.length;return st(e,n,r),Vo(t,e,r+2,0,n),v2.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=Ut(t,e),n=t.slice(e+2,e+2+r);return v2.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),b2=Fr({encode(t,e,r){return e||(e=new Uint8Array(b2.encodingLength(t))),r||(r=0),Ze.encode(t,e,r+2),st(e,Ze.encode.bytes,r),b2.encode.bytes=Ze.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Ut(t,e),n=Ze.decode(t,e+2);return b2.decode.bytes=r+2,n},encodingLength(t){return Ze.encodingLength(t)+2}}),P2=Fr({encode(t,e,r){e||(e=new Uint8Array(P2.encodingLength(t))),r||(r=0);let n=r;return r+=2,Ze.encode(t.mname,e,r),r+=Ze.encode.bytes,Ze.encode(t.rname,e,r),r+=Ze.encode.bytes,jl(e,t.serial||0,r),r+=4,jl(e,t.refresh||0,r),r+=4,jl(e,t.retry||0,r),r+=4,jl(e,t.expire||0,r),r+=4,jl(e,t.minimum||0,r),r+=4,st(e,r-n-2,n),P2.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=Ze.decode(t,e),e+=Ze.decode.bytes,n.rname=Ze.decode(t,e),e+=Ze.decode.bytes,n.serial=Ol(t,e),e+=4,n.refresh=Ol(t,e),e+=4,n.retry=Ol(t,e),e+=4,n.expire=Ol(t,e),e+=4,n.minimum=Ol(t,e),e+=4,P2.decode.bytes=e-r,n},encodingLength(t){return 22+Ze.encodingLength(t.mname)+Ze.encodingLength(t.rname)}}),x2=Fr({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let i=0;i<t.length;i++)if(typeof t[i]=="string"&&(t[i]=M6(t[i])),!fh(t[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(x2.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(i){e[r++]=i.length,Vo(i,e,r,0,i.length),r+=i.length}),st(e,r-n-2,n),x2.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=Ut(t,e);e+=2;let i=[];for(;n>0;){let a=t[e++];if(--n,n<a)throw new Error("Buffer overflow");i.push(t.slice(e,e+a)),e+=a,n-=a}return x2.decode.bytes=e-r,i},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=xf(r)+1:e+=r.length+1}),e}}),E2=Fr({encode(t,e,r){e||(e=new Uint8Array(E2.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=M6(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let i=t.length;return Vo(t,e,r,0,i),r+=i,st(e,r-n-2,n),E2.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=Ut(t,e);e+=2;let i=t.slice(e,e+n);return e+=n,E2.decode.bytes=e-r,i},encodingLength(t){return t?(fh(t)?t.length:xf(t))+2:2}}),S2=Fr({encode(t,e,r){e||(e=new Uint8Array(S2.encodingLength(t))),r||(r=0);let n=r;return r+=2,li.encode(t.cpu,e,r),r+=li.encode.bytes,li.encode(t.os,e,r),r+=li.encode.bytes,st(e,r-n-2,n),S2.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=li.decode(t,e),e+=li.decode.bytes,n.os=li.decode(t,e),e+=li.decode.bytes,S2.decode.bytes=e-r,n},encodingLength(t){return li.encodingLength(t.cpu)+li.encodingLength(t.os)+2}}),Ky=Fr({encode(t,e,r){return e||(e=new Uint8Array(Ky.encodingLength(t))),r||(r=0),Ze.encode(t,e,r+2),st(e,Ze.encode.bytes,r),Ky.encode.bytes=Ze.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Ze.decode(t,e+2);return Ky.decode.bytes=Ze.decode.bytes+2,r},encodingLength(t){return Ze.encodingLength(t)+2}}),A2=Fr({encode(t,e,r){e||(e=new Uint8Array(A2.encodingLength(t))),r||(r=0),st(e,t.priority||0,r+2),st(e,t.weight||0,r+4),st(e,t.port||0,r+6),Ze.encode(t.target,e,r+8);let n=Ze.encode.bytes+6;return st(e,n,r),A2.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=Ut(t,e),n={};return n.priority=Ut(t,e+2),n.weight=Ut(t,e+4),n.port=Ut(t,e+6),n.target=Ze.decode(t,e+8),A2.decode.bytes=r+2,n},encodingLength(t){return 8+Ze.encodingLength(t.target)}}),gf=Fr({encode(t,e,r){let n=gf.encodingLength(t);return e||(e=new Uint8Array(gf.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=gf.ISSUER_CRITICAL),st(e,n-2,r),r+=2,e[r]=t.flags||0,r+=1,li.encode(t.tag,e,r),r+=li.encode.bytes,K6(e,t.value,r),r+=xf(t.value),gf.encode.bytes=n,e},decode(t,e){e||(e=0);let r=Ut(t,e);e+=2;let n=e,i={};return i.flags=t[e],e+=1,i.tag=li.decode(t,e),e+=li.decode.bytes,i.value=rb(t,e,n+r),i.issuerCritical=!!(i.flags&gf.ISSUER_CRITICAL),gf.decode.bytes=r+2,i},encodingLength(t){return li.encodingLength(t.tag)+li.encodingLength(t.value)+2}});gf.ISSUER_CRITICAL=128;k2=Fr({encode(t,e,r){e||(e=new Uint8Array(k2.encodingLength(t))),r||(r=0);let n=r;return r+=2,st(e,t.preference||0,r),r+=2,Ze.encode(t.exchange,e,r),r+=Ze.encode.bytes,st(e,r-n-2,n),k2.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=Ut(t,e),e+=2,n.exchange=Ze.decode(t,e),e+=Ze.decode.bytes,k2.decode.bytes=e-r,n},encodingLength(t){return 4+Ze.encodingLength(t.exchange)}}),vz=Fr({encode(t,e,r){return e||(e=new Uint8Array(vz.encodingLength(t))),r||(r=0),st(e,4,r),r+=2,Ad.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,Ad.decode(t,e)},bytes:6}),_2=Fr({encode(t,e,r){return e||(e=new Uint8Array(_2.encodingLength(t))),r||(r=0),st(e,16,r),r+=2,bf.encode(t,e,r),_2.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=bf.decode(t,e);return _2.decode.bytes=18,r},bytes:18}),fq=t=>new Uint8Array(t),$l=Fr({encode(t,e,r){e||(e=new Uint8Array($l.encodingLength(t))),r||(r=0);let n=r,i=dq(t.code);if(st(e,i,r),r+=2,t.data)st(e,t.data.length,r),r+=2,Vo(t.data,e,r),r+=t.data.length;else switch(i){case 8:{let a=t.sourcePrefixLength||0,s=t.family||Kpe(t.ip,fq),o=Npe(t.ip,fq),d=Math.ceil(a/8);st(e,d+4,r),r+=2,st(e,s,r),r+=2,e[r++]=a,e[r++]=t.scopePrefixLength||0,Vo(o,e,r,0,d),r+=d}break;case 11:t.timeout?(st(e,2,r),r+=2,st(e,t.timeout,r),r+=2):(st(e,0,r),r+=2);break;case 12:{let a=t.length||0;st(e,a,r),r+=2,e.fill(0,r,r+a),r+=a}break;case 14:{let a=t.tags.length*2;st(e,a,r),r+=2;for(let s of t.tags)st(e,s,r),r+=2}break;default:throw new Error(`Unknown roption code: ${t.code}`)}return $l.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=Ut(t,e),r.type=zpe(r.code),e+=2;let n=Ut(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=Ut(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let i=new Uint8Array(r.family===1?4:16);Vo(t,i,0,e,e+n-4),r.ip=Upe(i)}break;case 11:n>0&&(r.timeout=Ut(t,e),e+=2);break;case 14:r.tags=[];for(let i=0;i<n;i+=2)r.tags.push(Ut(t,e)),e+=2}return $l.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(dq(t.code)){case 8:{let e=t.sourcePrefixLength||0;return Math.ceil(e/8)+8}case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)}}),wf=Fr({encode(t,e,r){e||(e=new Uint8Array(wf.encodingLength(t))),r||(r=0);let n=r,i=jy(t,$l);return st(e,i,r),r=Cv(t,$l,e,r+2),wf.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],i=Ut(t,e);e+=2;let a=0;for(;i>0;)n[a++]=$l.decode(t,e),e+=$l.decode.bytes,i-=$l.decode.bytes;return wf.decode.bytes=e-r,n},encodingLength(t){return 2+jy(t||[],$l)}}),Sd=Fr({encode(t,e,r){e||(e=new Uint8Array(Sd.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!fh(i))throw new Error("Key must be a Buffer");return r+=2,st(e,t.flags,r),r+=2,e[r]=Sd.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,Vo(i,e,r,0,i.length),r+=i.length,Sd.encode.bytes=r-n,st(e,Sd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=Ut(t,e);if(e+=2,n.flags=Ut(t,e),e+=2,t[e]!==Sd.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t[e],e+=1,n.key=t.slice(e,r+i+2),e+=n.key.length,Sd.decode.bytes=e-r,n},encodingLength(t){return 6+xf(t.key)}});Sd.PROTOCOL_DNSSEC=3;Sd.ZONE_KEY=128;Sd.SECURE_ENTRYPOINT=32768;_v=Fr({encode(t,e,r){e||(e=new Uint8Array(_v.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!fh(i))throw new Error("Signature must be a Buffer");return r+=2,st(e,Gv(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,jl(e,t.originalTTL,r),r+=4,jl(e,t.expiration,r),r+=4,jl(e,t.inception,r),r+=4,st(e,t.keyTag,r),r+=2,Ze.encode(t.signersName,e,r),r+=Ze.encode.bytes,Vo(i,e,r,0,i.length),r+=i.length,_v.encode.bytes=r-n,st(e,_v.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=Ut(t,e);return e+=2,n.typeCovered=nE(Ut(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=Ol(t,e),e+=4,n.expiration=Ol(t,e),e+=4,n.inception=Ol(t,e),e+=4,n.keyTag=Ut(t,e),e+=2,n.signersName=Ze.decode(t,e),e+=Ze.decode.bytes,n.signature=t.slice(e,r+i+2),e+=n.signature.length,_v.decode.bytes=e-r,n},encodingLength(t){return 20+Ze.encodingLength(t.signersName)+xf(t.signature)}}),Tv=Fr({encode(t,e,r){e||(e=new Uint8Array(Tv.encodingLength(t))),r||(r=0);let n=r;return r+=2,Ze.encode(t.mbox||".",e,r),r+=Ze.encode.bytes,Ze.encode(t.txt||".",e,r),r+=Ze.encode.bytes,Tv.encode.bytes=r-n,st(e,Tv.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=Ze.decode(t,e)||".",e+=Ze.decode.bytes,n.txt=Ze.decode(t,e)||".",e+=Ze.decode.bytes,Tv.decode.bytes=e-r,n},encodingLength(t){return 2+Ze.encodingLength(t.mbox||".")+Ze.encodingLength(t.txt||".")}}),Ho=Fr({encode(t,e,r){e||(e=new Uint8Array(Ho.encodingLength(t))),r||(r=0);let n=r,i=[];for(let a=0;a<t.length;a++){let s=Gv(t[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=M6(i[a]);e[r]=a,r+=1,e[r]=s.length,r+=1,Vo(s,e,r,0,s.length),r+=s.length}return Ho.encode.bytes=r-n,e},decode(t,e,r){e||(e=0);let n=e,i=[];for(;e-n<r;){let a=t[e];e+=1;let s=t[e];e+=1;for(let o=0;o<s;o++){let d=t[e+o];for(let l=0;l<8;l++)if(d&1<<7-l){let c=nE(a<<8|o<<3|l);i.push(c)}}e+=s}return Ho.decode.bytes=e-n,i},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let i=Gv(t[n]);e[i>>8]=Math.max(e[i>>8]||0,i&255)}let r=0;for(let n=0;n<e.length;n++)e[n]!==void 0&&(r+=2+Math.ceil((e[n]+1)/8));return r}}),Iv=Fr({encode(t,e,r){e||(e=new Uint8Array(Iv.encodingLength(t))),r||(r=0);let n=r;return r+=2,Ze.encode(t.nextDomain,e,r),r+=Ze.encode.bytes,Ho.encode(t.rrtypes,e,r),r+=Ho.encode.bytes,Iv.encode.bytes=r-n,st(e,Iv.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=Ut(t,e);return e+=2,n.nextDomain=Ze.decode(t,e),e+=Ze.decode.bytes,n.rrtypes=Ho.decode(t,e,i-(e-r)),e+=Ho.decode.bytes,Iv.decode.bytes=e-r,n},encodingLength(t){return 2+Ze.encodingLength(t.nextDomain)+Ho.encodingLength(t.rrtypes)}}),Dv=Fr({encode(t,e,r){e||(e=new Uint8Array(Dv.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!fh(i))throw new Error("salt must be a Buffer");let a=t.nextDomain;if(!fh(a))throw new Error("nextDomain must be a Buffer");return r+=2,e[r]=t.algorithm,r+=1,e[r]=t.flags,r+=1,st(e,t.iterations,r),r+=2,e[r]=i.length,r+=1,Vo(i,e,r,0,i.length),r+=i.length,e[r]=a.length,r+=1,Vo(a,e,r,0,a.length),r+=a.length,Ho.encode(t.rrtypes,e,r),r+=Ho.encode.bytes,Dv.encode.bytes=r-n,st(e,Dv.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=Ut(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=Ut(t,e),e+=2;let a=t[e];e+=1,n.salt=t.slice(e,e+a),e+=a;let s=t[e];return e+=1,n.nextDomain=t.slice(e,e+s),e+=s,n.rrtypes=Ho.decode(t,e,i-(e-r)),e+=Ho.decode.bytes,Dv.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+Ho.encodingLength(t.rrtypes)}}),Rv=Fr({encode(t,e,r){e||(e=new Uint8Array(Rv.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!fh(i))throw new Error("Digest must be a Buffer");return r+=2,st(e,t.keyTag,r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.digestType,r+=1,Vo(i,e,r,0,i.length),r+=i.length,Rv.encode.bytes=r-n,st(e,Rv.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=Ut(t,e);return e+=2,n.keyTag=Ut(t,e),e+=2,n.algorithm=t[e],e+=1,n.digestType=t[e],e+=1,n.digest=t.slice(e,r+i+2),e+=n.digest.length,Rv.decode.bytes=e-r,n},encodingLength(t){return 6+xf(t.digest)}}),Oy=Fr({encode(t,e,r){e||(e=new Uint8Array(Oy.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let i=lq(t.fingerprint),a=e6(t.hash);if(i!==a)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${i} != ${a}`);return Gpe(e,t.fingerprint,r,r+=i),Oy.encode.bytes=r-n,st(e,Oy.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};e+=2,n.algorithm=t[e],e+=1,n.hash=t[e],e+=1;let i=e6(n.hash);return n.fingerprint=Fpe(t,e,e+i),e+=i,Oy.decode.bytes=e-r,n},encodingLength(t){return 4+lq(t.fingerprint)}});Oy.getFingerprintLengthForHashType=e6;Ia=Fr({encode(t,e,r){e||(e=new Uint8Array(Ia.encodingLength(t))),r||(r=0);let n=r;if(Ze.encode(t.name,e,r),r+=Ze.encode.bytes,st(e,Gv(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");st(e,t.udpPayloadSize||4096,r+2),e[r+4]=t.extendedRcode||0,e[r+5]=t.ednsVersion||0,st(e,t.flags||0,r+6),r+=8,wf.encode(t.options||[],e,r),r+=wf.encode.bytes}else{let i=mz(t.class===void 0?"IN":t.class);t.flush&&(i|=QR),st(e,i,r+2),jl(e,t.ttl||0,r+4),r+=8;let a=UR(t.type);a.encode(t.data,e,r),r+=a.encode.bytes}return Ia.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={},n=e;if(r.name=Ze.decode(t,e),e+=Ze.decode.bytes,r.type=nE(Ut(t,e)),r.type==="OPT")r.udpPayloadSize=Ut(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=Ut(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=wf.decode(t,e+8),e+=8+wf.decode.bytes;else{let i=Ut(t,e+2);r.ttl=Ol(t,e+4),r.class=hz(i&Ype),r.flush=!!(i&QR);let a=UR(r.type);r.data=a.decode(t,e+8),e+=8+a.decode.bytes}return Ia.decode.bytes=e-n,r},encodingLength(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return Ze.encodingLength(t.name)+8+UR(t.type).encodingLength(e)}}),Ny=Fr({encode(t,e,r){e||(e=new Uint8Array(Ny.encodingLength(t))),r||(r=0);let n=r;return Ze.encode(t.name,e,r),r+=Ze.encode.bytes,st(e,Gv(t.type),r),r+=2,st(e,mz(t.class===void 0?"IN":t.class),r),r+=2,Ny.encode.bytes=r-n,t},decode(t,e){e||(e=0);let r=e,n={};return n.name=Ze.decode(t,e),e+=Ze.decode.bytes,n.type=nE(Ut(t,e)),e+=2,n.class=hz(Ut(t,e)),e+=2,n.class&wz&&(n.class&=Xpe),Ny.decode.bytes=e-r,n},encodingLength(t){return Ze.encodingLength(t.name)+4}}),Qpe=1024,ts={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(ehe(t))),r||(r=0);let i=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),Ry.encode(t,e,r),r+=Ry.encode.bytes,r=Cv(t.questions,Ny,e,r),r=Cv(t.answers,Ia,e,r),r=Cv(t.authorities,Ia,e,r),r=Cv(t.additionals,Ia,e,r),ts.encode.bytes=r-i,n&&G2.bytes!==e.length?e.slice(0,G2.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=Ry.decode(t,e);return e+=Ry.decode.bytes,e=u2(n.questions,Ny,t,e),e=u2(n.answers,Ia,t,e),e=u2(n.authorities,Ia,t,e),e=u2(n.additionals,Ia,t,e),ts.decode.bytes=e-r,n},encodingLength:function(t){return Ry.encodingLength(t)+jy(t.questions||[],Ny)+jy(t.answers||[],Ia)+jy(t.authorities||[],Ia)+jy(t.additionals||[],Ia)}};ts.encode.bytes=0;ts.decode.bytes=0;z2={encode:function(t,e,r){return e=ts.encode(q2(t,"query"),e,r),z2.encode.bytes=ts.encode.bytes,e},decode:function(t,e){let r=ts.decode(t,e);return z2.decode.bytes=ts.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return ts.encodingLength(q2(t,"query"))}};z2.encode.bytes=0;z2.decode.bytes=0;F2={encode:function(t,e,r){return e=ts.encode(q2(t,"response"),e,r),F2.encode.bytes=ts.encode.bytes,e},decode:function(t,e){let r=ts.decode(t,e);return F2.decode.bytes=ts.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return ts.encodingLength(q2(t,"response"))}};F2.encode.bytes=0;F2.decode.bytes=0;G2=ts.encode,t6=ts.decode,ehe=ts.encodingLength;bz.bytes=0;Pz.bytes=0;Ez="dht";ohe=0,pf=7200,T2=";",Fs=",",kz={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},_z={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};hq=j.DID_DHT_GATEWAY_URI||"https://enbox-did-dht.fly.dev",Iz=class r6 extends eb{static async create({keyManager:e=new Ec,options:r={}}={}){if(r.verificationMethods?.some(c=>!(c.algorithm in kz)))throw new Error("One or more verification method algorithms are not supported");let n=r.verificationMethods?.filter(c=>"id"in c).map(c=>c.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(r.services?.some(c=>!c.id||!c.type||!c.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 My.identityKeyToIdentifier({identityKey:a}),o={id:s,...r.alsoKnownAs&&{alsoKnownAs:r.alsoKnownAs},...r.controllers&&{controller:r.controllers}},d=[...r.verificationMethods??[]];d?.some(c=>c.id?.split("#").pop()==="0")||d.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let c of d){let u=c.id&&c.id.split("#").pop()==="0"?i:await e.generateKey({algorithm:c.algorithm}),f=await e.getPublicKey({keyUri:u}),h=c.id??f.kid??await Ar({jwk:f});h=`${s}#${Gs(h)}`,o.verificationMethod??=[],o.verificationMethod.push({id:h,type:"JsonWebKey",controller:c.controller??s,publicKeyJwk:f});for(let p of c.purposes??[])o[p]??=[],o[p].push(h)}r.services?.forEach(c=>{o.service??=[],c.id=`${s}#${c.id.split("#").pop()}`,o.service.push(c)});let l=new bs({uri:s,document:o,metadata:{published:!1,...r.types&&{types:r.types}},keyManager:e});if(r.publish??!0){let c=await r6.publish({did:l,gatewayUri:r.gatewayUri});l.metadata=c.didDocumentMetadata}return l}static async import({portableDid:e,keyManager:r=new Ec}){if(Fn.parse(e.uri)?.method!==r6.methodName)throw new rt("methodNotSupported","Method not supported");let n=await bs.import({portableDid:e,keyManager:r});if(!n.document.verificationMethod?.some(i=>i.id?.split("#").pop()==="0"))throw new rt("invalidDidDocument","DID document must contain an Identity Key");return n}static async getSigningMethod({didDocument:e,methodId:r="#0"}){let n=Fn.parse(e.id);if(n&&n.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(a=>Gs(a.id)===(Gs(r)??Gs(e.assertionMethod?.[0])));if(!(i&&i.publicKeyJwk))throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async publish({did:e,gatewayUri:r=hq}){return await mq.put({did:e,gatewayUri:r})}static async resolve(e,r={}){let n=r?.gatewayUri??hq;try{await My.identifierToIdentityKey({didUri:e});let{didDocument:i,didDocumentMetadata:a}=await mq.get({didUri:e,gatewayUri:n});return{...Ai,didDocument:i,didDocumentMetadata:a}}catch(i){if(!(i instanceof rt))throw new Error(i);return{...Ai,didResolutionMetadata:{error:i.code,...i.message&&{errorMessage:i.message}}}}}};Iz.methodName="dht";po=Iz,mq=class Bv{static async get({didUri:e,gatewayUri:r}){let n=My.identifierToIdentityKeyBytes({didUri:e}),i=await Bv.pkarrGet({gatewayUri:r,publicKeyBytes:n}),a=await My.parseBep44GetMessage({bep44Message:i}),s=await Bv.fromDnsPacket({didUri:e,dnsPacket:a});return s.didDocumentMetadata.versionId=i.seq.toString(),s}static async put({did:e,gatewayUri:r}){let n=await Bv.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[r]}),i=await My.createBep44PutMessage({dnsPacket:n,publicKeyBytes:My.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),a=await Bv.pkarrPut({gatewayUri:r,bep44Message:i});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:a,versionId:i.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return the(e)}static async pkarrPut(e){return rhe(e)}static async fromDnsPacket(e){return ahe(e)}static async toDnsPacket(e){return che(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},My=class{static async createBep44PutMessage(t){return nhe(t)}static async identifierToIdentityKey(t){return Sz(t)}static identifierToIdentityKeyBytes(t){return N6(t)}static async identityKeyToIdentifier(t){return she(t)}static keyConverter(t){return U6(t)}static async parseBep44GetMessage(t){return ihe(t)}static parseTxtDataToObject(t){return $v(t)}static parseTxtDataToString(t){return Vv(t)}static async validatePreviousDidProof(t){return Az(t)}static chunkDataIfNeeded(t){return Tz(t)}},Ln={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"},qn=class extends Error{constructor(t,e){super(`${t}: ${e}`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}},sUe=new Uint8Array(0),dhe=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},lhe=class{constructor(t,e,r){this.name=t,this.prefix=e,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},uhe=class{constructor(t,e,r){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Dz(this,t)}},fhe=class{constructor(t){this.decoders=t}or(t){return Dz(this,t)}decode(t){let e=t[0],r=this.decoders[e];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Dz=(t,e)=>new fhe({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),phe=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new lhe(t,e,r),this.decoder=new uhe(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},hhe=({name:t,prefix:e,encode:r,decode:n})=>new phe(t,e,r,n),mhe=(t,e,r,n)=>{let i={};for(let c=0;c<e.length;++c)i[e[c]]=c;let a=t.length;for(;t[a-1]==="=";)--a;let s=new Uint8Array(a*r/8|0),o=0,d=0,l=0;for(let c=0;c<a;++c){let u=i[t[c]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);d=d<<r|u,o+=r,o>=8&&(o-=8,s[l++]=255&d>>o)}if(o>=r||255&d<<8-o)throw new SyntaxError("Unexpected end of data");return s},yhe=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,a="",s=0,o=0;for(let d=0;d<t.length;++d)for(o=o<<8|t[d],s+=8;s>r;)s-=r,a+=e[i&o>>s];if(s&&(a+=e[i&o<<r-s]),n)for(;a.length*r&7;)a+="=";return a},iE=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>hhe({prefix:e,name:t,encode(i){return yhe(i,n,r)},decode(i){return mhe(i,n,r,t)}}),oUe=iE({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),aUe=iE({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),yq=iE({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),cUe=iE({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),zy=class I2{static encode(e){return yq.baseEncode(e)}static decodeAsBytes(e,r){if(!I2.isBase64UrlString(e))throw new qn(Ln.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return yq.baseDecode(e)}static decodeAsString(e,r){let n=I2.decodeAsBytes(e,r);return I2.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)}},ghe=ph(yde(),1);(function(t){t.Public="public",t.Private="private"})(n6||(n6={}));Ed=n6,zo=class{static validateEs256kOperationKey(t,e){let r=new Set(["kty","crv","x","y"]);e===Ed.Private&&r.add("d");for(let n in t)if(!r.has(n))throw new qn(Ln.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${n}'.`);if(t.crv!=="secp256k1")throw new qn(Ln.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${t.crv}.'`);if(t.kty!=="EC")throw new qn(Ln.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${t.kty}.'`);if(t.x.length!==43)throw new qn(Ln.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(t.y.length!==43)throw new qn(Ln.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(e===Ed.Private&&(t.d===void 0||t.d.length!==43))throw new qn(Ln.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(t){if(t.length>50)throw new qn(Ln.IdTooLong,`Key ID length ${t.length} exceed max allowed length of 50.`);if(!zy.isBase64UrlString(t))throw new qn(Ln.IdNotUsingBase64UrlCharacterSet,`Key ID '${t}' is not a Base64URL string.`)}static validatePublicKeyPurposes(t){if(t===void 0)return;let e=new Set;for(let r of t){if(e.has(r))throw new qn(Ln.PublicKeyPurposeDuplicated,`Public key purpose '${r}' already specified.`);e.add(r)}}},L6=class{};L6.hashAlgorithmInMultihashCode=18;L6.maxCanonicalizedDeltaSizeInBytes=1e3;xc=L6,whe=ph(gde(),1),Wv=class i6{static canonicalizeAsBytes(e){let r=i6.removeAllUndefinedProperties(e),n=whe.default(r);return zy.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let r in e)typeof e[r]=="object"?i6.removeAllUndefinedProperties(e[r]):e[r]===void 0&&delete e[r];return e}},vhe=Rz,gq=128,bhe=127,Phe=~bhe,xhe=Math.pow(2,31);Ehe=s6,She=128,wq=127;Ahe=Math.pow(2,7),khe=Math.pow(2,14),_he=Math.pow(2,21),The=Math.pow(2,28),Ihe=Math.pow(2,35),Dhe=Math.pow(2,42),Rhe=Math.pow(2,49),Che=Math.pow(2,56),$he=Math.pow(2,63),Bhe=function(t){return t<Ahe?1:t<khe?2:t<_he?3:t<The?4:t<Ihe?5:t<Dhe?6:t<Rhe?7:t<Che?8:t<$he?9:10},Ohe={encode:vhe,decode:Ehe,encodingLength:Bhe},jhe=Ohe,H2=jhe,vq=(t,e=0)=>[H2.decode(t,e),H2.decode.bytes],bq=(t,e,r=0)=>(H2.encode(t,e,r),e),Pq=t=>H2.encodingLength(t),xq=(t,e)=>{let r=e.byteLength,n=Pq(t),i=n+Pq(r),a=new Uint8Array(i+r);return bq(t,a,0),bq(r,a,n),a.set(e,i),new Cz(t,r,e,a)},Mhe=t=>{let e=dhe(t),[r,n]=vq(e),[i,a]=vq(e.subarray(n)),s=e.subarray(n+a);if(s.byteLength!==i)throw new Error("Incorrect length");return new Cz(r,i,s,e)},Cz=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},$z=({name:t,code:e,encode:r})=>new Khe(t,e,r),Khe=class{constructor(t,e,r){this.name=t,this.code=e,this.encode=r}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?xq(this.code,e):e.then(r=>xq(this.code,r))}else throw Error("Unknown type, must be binary type")}},Bz=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Eq=$z({name:"sha2-256",code:18,encode:Bz("SHA-256")}),dUe=$z({name:"sha2-512",code:19,encode:Bz("SHA-512")}),Pv=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Go=class Ov{static hash(e,r){return Pv(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield Eq.digest(e)).bytes;break;default:throw new qn(Ln.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return Pv(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield Eq.encode(e);break;default:throw new qn(Ln.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return Pv(this,void 0,void 0,function*(){let n=Wv.canonicalizeAsBytes(e);return yield Ov.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return Pv(this,void 0,void 0,function*(){let n=Wv.canonicalizeAsBytes(e),i=yield Ov.hashAsNonMultihashBytes(n,r);return yield Ov.hashThenEncode(i,r)})}static hashThenEncode(e,r){return Pv(this,void 0,void 0,function*(){let n=yield Ov.hash(e,r);return zy.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,i=zy.decodeAsBytes(e,r);try{n=Mhe(i)}catch{throw new qn(Ln.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let a=xc.hashAlgorithmInMultihashCode;if(a!==n.code)throw new qn(Ln.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${a} or change IonSdkConfig to desired hashing algorithm.`)}};(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(o6||(o6={}));f2=o6;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})(a6||(a6={}));Iy=a6,p2=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Oz=class _a{static createCreateRequest(e){return p2(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,a=e.document.services;zo.validateEs256kOperationKey(r,Ed.Public),zo.validateEs256kOperationKey(n,Ed.Public),_a.validateDidDocumentKeys(i),_a.validateServices(a);let s=xc.hashAlgorithmInMultihashCode,o=[{action:Iy.Replace,document:e.document}],d={updateCommitment:yield Go.canonicalizeThenDoubleHashThenEncode(n,s),patches:o};_a.validateDeltaSize(d);let l={deltaHash:yield Go.canonicalizeThenHashThenEncode(d,s),recoveryCommitment:yield Go.canonicalizeThenDoubleHashThenEncode(r,s)};return{type:f2.Create,suffixData:l,delta:d}})}static createDeactivateRequest(e){return p2(this,void 0,void 0,function*(){_a.validateDidSuffix(e.didSuffix),zo.validateEs256kOperationKey(e.recoveryPublicKey,Ed.Public);let r=xc.hashAlgorithmInMultihashCode,n=yield Go.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},a=yield e.signer.sign({alg:"ES256K"},i);return{type:f2.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:a}})}static createRecoverRequest(e){return p2(this,void 0,void 0,function*(){_a.validateDidSuffix(e.didSuffix),zo.validateEs256kOperationKey(e.recoveryPublicKey,Ed.Public),zo.validateEs256kOperationKey(e.nextRecoveryPublicKey,Ed.Public),zo.validateEs256kOperationKey(e.nextUpdatePublicKey,Ed.Public),_a.validateDidDocumentKeys(e.document.publicKeys),_a.validateServices(e.document.services);let r=xc.hashAlgorithmInMultihashCode,n=yield Go.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i=[{action:Iy.Replace,document:e.document}],a=yield Go.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),s={patches:i,updateCommitment:a},o=yield Go.canonicalizeThenHashThenEncode(s,r),d={recoveryCommitment:yield Go.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,r),recoveryKey:e.recoveryPublicKey,deltaHash:o},l=yield e.signer.sign({alg:"ES256K"},d);return{type:f2.Recover,didSuffix:e.didSuffix,revealValue:n,delta:s,signedData:l}})}static createUpdateRequest(e){return p2(this,void 0,void 0,function*(){if(_a.validateDidSuffix(e.didSuffix),zo.validateEs256kOperationKey(e.updatePublicKey,Ed.Public),zo.validateEs256kOperationKey(e.nextUpdatePublicKey,Ed.Public),_a.validateServices(e.servicesToAdd),_a.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let p of e.idsOfServicesToRemove)zo.validateId(p);if(e.idsOfPublicKeysToRemove!==void 0)for(let p of e.idsOfPublicKeysToRemove)zo.validateId(p);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let p={action:Iy.AddServices,services:n};r.push(p)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let p={action:Iy.RemoveServices,ids:i};r.push(p)}let a=e.publicKeysToAdd;if(a!==void 0&&a.length>0){let p={action:Iy.AddPublicKeys,publicKeys:a};r.push(p)}let s=e.idsOfPublicKeysToRemove;if(s!==void 0&&s.length>0){let p={action:Iy.RemovePublicKeys,ids:s};r.push(p)}let o=xc.hashAlgorithmInMultihashCode,d=yield Go.canonicalizeThenHashThenEncode(e.updatePublicKey,o),l=yield Go.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,o),c={patches:r,updateCommitment:l},u=yield Go.canonicalizeThenHashThenEncode(c,o),f={updateKey:e.updatePublicKey,deltaHash:u},h=yield e.signer.sign({alg:"ES256K"},f);return{type:f2.Update,didSuffix:e.didSuffix,revealValue:d,delta:c,signedData:h}})}static validateDidSuffix(e){Go.validateEncodedHashComputedUsingSupportedHashAlgorithm(e,"didSuffix")}static validateDidDocumentKeys(e){if(e===void 0)return;let r=new Set;for(let n of e){if(Array.isArray(n.publicKeyJwk))throw new qn(Ln.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(zo.validateId(n.id),r.has(n.id))throw new qn(Ln.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);r.add(n.id),zo.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let r=new Set;for(let n of e){if(_a.validateService(n),r.has(n.id))throw new qn(Ln.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){zo.validateId(e.id);let r=30;if(e.type.length>r){let n=`Service endpoint type length ${e.type.length} exceeds max allowed length of ${r}.`;throw new qn(Ln.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new qn(Ln.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&ghe.parse(e.serviceEndpoint).error!==void 0)throw new qn(Ln.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let r=Wv.canonicalizeAsBytes(e);if(r.length>xc.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${xc.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new qn(Ln.DeltaExceedsMaximumSize,n)}}},Sq=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Nhe=class jz{static createLongFormDid(e){return Sq(this,void 0,void 0,function*(){let r=yield Oz.createCreateRequest(e),n=yield jz.computeDidUniqueSuffix(r.suffixData),i;xc.network===void 0||xc.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${xc.network}:${n}`;let a={suffixData:r.suffixData,delta:r.delta},s=Wv.canonicalizeAsBytes(a),o=zy.encode(s);return`${i}:${o}`})}static computeDidUniqueSuffix(e){return Sq(this,void 0,void 0,function*(){let r=Wv.canonicalizeAsBytes(e),n=yield Go.hash(r,xc.hashAlgorithmInMultihashCode);return zy.encode(n)})}},Yi=2n**255n-19n,D2=2n**252n+27742317777372353535851937790883648493n,c6=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,d6=0x6666666666666666666666666666666666666666666666666666666666666658n,h2={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Yi,n:D2,h:8,Gx:c6,Gy:d6},uo=(t="")=>{throw new Error(t)},Mz=t=>typeof t=="string",q6=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?uo("Uint8Array expected"):t,Fy=t=>new Uint8Array(t),Uhe=(t,e)=>q6(Mz(t)?F6(t):Fy(t),e),lt=(t,e=Yi)=>{let r=t%e;return r>=0n?r:e+r},Aq=t=>t instanceof Gy?t:uo("Point expected"),Gy=class Cy{constructor(e,r,n,i){this.ex=e,this.ey=r,this.ez=n,this.et=i}static fromAffine(e){return new Cy(e.x,e.y,1n,lt(e.x*e.y))}static fromHex(e,r=!0){let{d:n}=h2;e=Uhe(e,32);let i=e.slice();i[31]=e[31]&-129;let a=qhe(i);a===0n||(r&&!(0n<a&&a<Yi)&&uo("bad y coord 1"),!r&&!(0n<a&&a<2n**256n)&&uo("bad y coord 2"));let s=lt(a*a),o=lt(s-1n),d=lt(n*s+1n),{isValid:l,value:c}=Fhe(o,d);l||uo("bad y coordinate 3");let u=(c&1n)===1n;return(e[31]&128)!==0!==u&&(c=lt(-c)),new Cy(c,a,1n,lt(c*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){let{ex:r,ey:n,ez:i}=this,{ex:a,ey:s,ez:o}=Aq(e),d=lt(r*o),l=lt(a*i),c=lt(n*o),u=lt(s*i);return d===l&&c===u}is0(){return this.equals(R2)}negate(){return new Cy(lt(-this.ex),this.ey,this.ez,lt(-this.et))}double(){let{ex:e,ey:r,ez:n}=this,{a:i}=h2,a=lt(e*e),s=lt(r*r),o=lt(2n*lt(n*n)),d=lt(i*a),l=e+r,c=lt(lt(l*l)-a-s),u=d+s,f=u-o,h=d-s,p=lt(c*f),m=lt(u*h),y=lt(c*h),b=lt(f*u);return new Cy(p,m,b,y)}add(e){let{ex:r,ey:n,ez:i,et:a}=this,{ex:s,ey:o,ez:d,et:l}=Aq(e),{a:c,d:u}=h2,f=lt(r*s),h=lt(n*o),p=lt(a*u*l),m=lt(i*d),y=lt((r+n)*(s+o)-f-h),b=lt(m-p),w=lt(m+p),S=lt(h-c*f),k=lt(y*b),T=lt(w*S),D=lt(y*S),K=lt(b*w);return new Cy(k,T,K,D)}mul(e,r=!0){if(e===0n)return r===!0?uo("cannot multiply by 0"):R2;if(typeof e=="bigint"&&0n<e&&e<D2||uo("invalid scalar, must be < L"),!r&&this.is0()||e===1n)return this;if(this.equals(V2))return Vhe(e).p;let n=R2,i=V2;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):r&&(i=i.add(a));return n}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(h2.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(D2/2n,!1).double();return D2%2n&&(e=e.add(this)),e.is0()}toAffine(){let{ex:e,ey:r,ez:n}=this;if(this.is0())return{x:0n,y:0n};let i=Nz(n);return lt(n*i)!==1n&&uo("invalid inverse"),{x:lt(e*i),y:lt(r*i)}}toRawBytes(){let{x:e,y:r}=this.toAffine(),n=Lhe(r);return n[31]|=e&1n?128:0,n}toHex(){return z6(this.toRawBytes())}};Gy.BASE=new Gy(c6,d6,1n,lt(c6*d6));Gy.ZERO=new Gy(0n,1n,1n,0n);({BASE:V2,ZERO:R2}=Gy),Kz=(t,e)=>t.toString(16).padStart(e,"0"),z6=t=>Array.from(t).map(e=>Kz(e,2)).join(""),F6=t=>{let e=t.length;(!Mz(t)||e%2)&&uo("hex invalid 1");let r=Fy(e/2);for(let n=0;n<r.length;n++){let i=n*2,a=t.slice(i,i+2),s=Number.parseInt(a,16);(Number.isNaN(s)||s<0)&&uo("hex invalid 2"),r[n]=s}return r},Lhe=t=>F6(Kz(t,32*2)).reverse(),qhe=t=>BigInt("0x"+z6(Fy(q6(t)).reverse())),_q=(...t)=>{let e=Fy(t.reduce((n,i)=>n+q6(i).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},Nz=(t,e=Yi)=>{(t===0n||e<=0n)&&uo("no inverse n="+t+" mod="+e);let r=lt(t,e),n=e,i=0n,a=1n,s=1n,o=0n;for(;r!==0n;){let d=n/r,l=n%r,c=i-s*d,u=a-o*d;n=r,r=l,i=s,a=o,s=c,o=u}return n===1n?lt(i,e):uo("no inverse")},bd=(t,e)=>{let r=t;for(;e-- >0n;)r*=r,r%=Yi;return r},zhe=t=>{let e=t*t%Yi*t%Yi,r=bd(e,2n)*e%Yi,n=bd(r,1n)*t%Yi,i=bd(n,5n)*n%Yi,a=bd(i,10n)*i%Yi,s=bd(a,20n)*a%Yi,o=bd(s,40n)*s%Yi,d=bd(o,80n)*o%Yi,l=bd(d,80n)*o%Yi,c=bd(l,10n)*i%Yi;return{pow_p_5_8:bd(c,2n)*t%Yi,b2:e}},Tq=19681161376707505956807079304988542015446066515923890162744021073123829784752n,Fhe=(t,e)=>{let r=lt(e*e*e),n=lt(r*r*e),i=zhe(t*n).pow_p_5_8,a=lt(t*r*i),s=lt(e*a*a),o=a,d=lt(a*Tq),l=s===t,c=s===lt(-t),u=s===lt(-t*Tq);return l&&(a=o),(c||u)&&(a=d),(lt(a)&1n)===1n&&(a=lt(-a)),{isValid:l||c,value:a}},Iq=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,Ghe={bytesToHex:z6,hexToBytes:F6,concatBytes:_q,mod:lt,invert:Nz,randomBytes:t=>{let e=Iq();return e||uo("crypto.getRandomValues must be defined"),e.getRandomValues(Fy(t))},sha512Async:async(...t)=>{let e=Iq();e||uo("crypto.subtle or etc.sha512Async must be defined");let r=_q(...t);return Fy(await e.subtle.digest("SHA-512",r.buffer))},sha512Sync:void 0};Object.defineProperties(Ghe,{sha512Sync:{configurable:!1,get(){return LR},set(t){LR||(LR=t)}}});nh=8,Hhe=()=>{let t=[],e=256/nh+1,r=V2,n=r;for(let i=0;i<e;i++){n=r,t.push(n);for(let a=1;a<2**(nh-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},Vhe=t=>{let e=kq||(kq=Hhe()),r=(c,u)=>{let f=u.negate();return c?f:u},n=R2,i=V2,a=1+256/nh,s=2**(nh-1),o=BigInt(2**nh-1),d=2**nh,l=BigInt(nh);for(let c=0;c<a;c++){let u=c*s,f=Number(t&o);t>>=l,f>s&&(f-=d,t+=1n);let h=u,p=u+Math.abs(f)-1,m=c%2!==0,y=f<0;f===0?i=i.add(r(m,e[h])):n=n.add(r(y,e[p]))}return{p:n,f:i}},G6=2n**256n,dh=G6-0x1000003d1n,H6=G6-0x14551231950b75fc4402da1732fc9bebfn,Uz=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Lz=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,qz={p:dh,n:H6,a:0n,b:7n,Gx:Uz,Gy:Lz},Uy=32,Dq=t=>et(et(t*t)*t+qz.b),Si=(t="")=>{throw new Error(t)},sE=t=>typeof t=="bigint",zz=t=>typeof t=="string",qR=t=>sE(t)&&0n<t&&t<dh,Fz=t=>sE(t)&&0n<t&&t<H6,Gz=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?Si("Uint8Array expected"):t,Jv=t=>new Uint8Array(t),V6=(t,e)=>Gz(zz(t)?oE(t):Jv(t),e),et=(t,e=dh)=>{let r=t%e;return r>=0n?r:e+r},Rq=t=>t instanceof Hy?t:Si("Point expected"),Hy=class $y{constructor(e,r,n){this.px=e,this.py=r,this.pz=n}static fromAffine(e){return new $y(e.x,e.y,1n)}static fromHex(e){e=V6(e);let r,n=e[0],i=e.subarray(1),a=$q(i,0,Uy),s=e.length;if(s===33&&[2,3].includes(n)){qR(a)||Si("Point hex invalid: x not FE");let o=Whe(Dq(a)),d=(o&1n)===1n;(n&1)===1!==d&&(o=et(-o)),r=new $y(a,o,1n)}return s===65&&n===4&&(r=new $y(a,$q(i,Uy,2*Uy),1n)),r?r.ok():Si("Point is not on curve")}static fromPrivateKey(e){return Nv.mul(Jhe(e))}get x(){return this.aff().x}get y(){return this.aff().y}equals(e){let{px:r,py:n,pz:i}=this,{px:a,py:s,pz:o}=Rq(e),d=et(r*o),l=et(a*i),c=et(n*o),u=et(s*i);return d===l&&c===u}negate(){return new $y(this.px,et(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:r,py:n,pz:i}=this,{px:a,py:s,pz:o}=Rq(e),{a:d,b:l}=qz,c=0n,u=0n,f=0n,h=et(l*3n),p=et(r*a),m=et(n*s),y=et(i*o),b=et(r+n),w=et(a+s);b=et(b*w),w=et(p+m),b=et(b-w),w=et(r+i);let S=et(a+o);return w=et(w*S),S=et(p+y),w=et(w-S),S=et(n+i),c=et(s+o),S=et(S*c),c=et(m+y),S=et(S-c),f=et(d*w),c=et(h*y),f=et(c+f),c=et(m-f),f=et(m+f),u=et(c*f),m=et(p+p),m=et(m+p),y=et(d*y),w=et(h*w),m=et(m+y),y=et(p-y),y=et(d*y),w=et(w+y),p=et(m*w),u=et(u+p),p=et(S*w),c=et(b*c),c=et(c-p),p=et(b*m),f=et(S*f),f=et(f+p),new $y(c,u,f)}mul(e,r=!0){if(!r&&e===0n)return C2;if(Fz(e)||Si("invalid scalar"),this.equals(Nv))return Qhe(e).p;let n=C2,i=Nv;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):r&&(i=i.add(a));return n}mulAddQUns(e,r,n){return this.mul(r,!1).add(e.mul(n,!1)).ok()}toAffine(){let{px:e,py:r,pz:n}=this;if(this.equals(C2))return{x:0n,y:0n};if(n===1n)return{x:e,y:r};let i=Vz(n);return et(n*i)!==1n&&Si("invalid inverse"),{x:et(e*i),y:et(r*i)}}assertValidity(){let{x:e,y:r}=this.aff();return(!qR(e)||!qR(r))&&Si("Point invalid: x or y"),et(r*r)===Dq(e)?this:Si("Point invalid: not on curve")}multiply(e){return this.mul(e)}aff(){return this.toAffine()}ok(){return this.assertValidity()}toHex(e=!0){let{x:r,y:n}=this.aff();return(e?(n&1n)===0n?"02":"03":"04")+Bq(r)+(e?"":Bq(n))}toRawBytes(e=!0){return oE(this.toHex(e))}};Hy.BASE=new Hy(Uz,Lz,1n);Hy.ZERO=new Hy(0n,1n,0n);({BASE:Nv,ZERO:C2}=Hy),Hz=(t,e)=>t.toString(16).padStart(e,"0"),W6=t=>Array.from(t).map(e=>Hz(e,2)).join(""),oE=t=>{let e=t.length;(!zz(t)||e%2)&&Si("hex invalid 1");let r=Jv(e/2);for(let n=0;n<r.length;n++){let i=n*2,a=t.slice(i,i+2),s=Number.parseInt(a,16);(Number.isNaN(s)||s<0)&&Si("hex invalid 2"),r[n]=s}return r},aE=t=>BigInt("0x"+(W6(t)||"0")),$q=(t,e,r)=>aE(t.slice(e,r)),J6=t=>sE(t)&&t>=0n&&t<G6?oE(Hz(t,2*Uy)):Si("bigint expected"),Bq=t=>W6(J6(t)),Oq=(...t)=>{let e=Jv(t.reduce((n,i)=>n+Gz(i).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},Vz=(t,e=dh)=>{(t===0n||e<=0n)&&Si("no inverse n="+t+" mod="+e);let r=et(t,e),n=e,i=0n,a=1n,s=1n,o=0n;for(;r!==0n;){let d=n/r,l=n%r,c=i-s*d,u=a-o*d;n=r,r=l,i=s,a=o,s=c,o=u}return n===1n?et(i,e):Si("no inverse")},Whe=t=>{let e=1n;for(let r=t,n=(dh+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*r%dh),r=r*r%dh;return et(e*e)===t?e:Si("sqrt invalid")},Jhe=t=>(sE(t)||(t=aE(V6(t,Uy))),Fz(t)?t:Si("private key out of range")),jq=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;Yhe={hexToBytes:oE,bytesToHex:W6,concatBytes:Oq,bytesToNumberBE:aE,numberToBytesBE:J6,mod:et,invert:Vz,hmacSha256Async:async(t,...e)=>{let r=jq();if(!r)return Si("etc.hmacSha256Async not set");let n=r.subtle,i=await n.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return Jv(await n.sign("HMAC",i,Oq(...e)))},hmacSha256Sync:$2,hashToPrivateKey:Zhe,randomBytes:t=>{let e=jq();return e||Si("crypto.getRandomValues must be defined"),e.getRandomValues(Jv(t))}};Object.defineProperties(Yhe,{hmacSha256Sync:{configurable:!1,get(){return $2},set(t){$2||($2=t)}}});ih=8,Xhe=()=>{let t=[],e=256/ih+1,r=Nv,n=r;for(let i=0;i<e;i++){n=r,t.push(n);for(let a=1;a<2**(ih-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},Qhe=t=>{let e=Cq||(Cq=Xhe()),r=(c,u)=>{let f=u.negate();return c?f:u},n=C2,i=Nv,a=1+256/ih,s=2**(ih-1),o=BigInt(2**ih-1),d=2**ih,l=BigInt(ih);for(let c=0;c<a;c++){let u=c*s,f=Number(t&o);t>>=l,f>s&&(f-=d,t+=1n);let h=u,p=u+Math.abs(f)-1,m=c%2!==0,y=f<0;f===0?i=i.add(r(m,e[h])):n=n.add(r(y,e[p]))}return{p:n,f:i}};(function(t){t.Mainnet="mainnet",t.Testnet="test"})(Mq||(Mq={}));(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(Kq||(Kq={}));xv=class th{static appendPathToUrl({baseUrl:e,path:r}){let n=new URL(e);return n.pathname=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",n.pathname+=r.startsWith("/")?r.substring(1):r,n.toString()}static async computeLongFormDidUri({recoveryKey:e,updateKey:r,services:n,verificationMethods:i}){let a=await th.createIonDocument({services:n,verificationMethods:i}),s=th.normalizeJwk(e),o=th.normalizeJwk(r);return await Nhe.createLongFormDid({document:a,recoveryKey:s,updateKey:o})}static async constructCreateRequest({ionDocument:e,recoveryKey:r,updateKey:n}){return await Oz.createCreateRequest({document:e,recoveryKey:th.normalizeJwk(r),updateKey:th.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:r}){let n=[];for(let a of r){let s=a.id??a.publicKeyJwk.kid??await Ar({jwk:a.publicKeyJwk});s=`${s.split("#").pop()}`;let o={id:s,publicKeyJwk:th.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 r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);return n}},eme=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519",t))(eme||{}),tme={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},Nq="https://ion.tbd.engineering",rme=class jv extends eb{static async create({keyManager:e=new Ec,options:r={}}={}){if(r.verificationMethods?.some(p=>!(p.algorithm in tme)))throw new Error("One or more verification method algorithms are not supported");let n=r.verificationMethods?.filter(p=>"id"in p).map(p=>p.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(r.services?.some(p=>!p.id||!p.type||!p.serviceEndpoint))throw new Error("One or more services are missing required properties");let i={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},a=[];for(let p of r.verificationMethods??[i]){let m=await e.generateKey({algorithm:p.algorithm}),y=await e.getPublicKey({keyUri:m});a.push({id:p.id,publicKeyJwk:y,purposes:p.purposes??["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let s=await e.generateKey({algorithm:"secp256k1"}),o=await e.getPublicKey({keyUri:s}),d=await e.generateKey({algorithm:"secp256k1"}),l=await e.getPublicKey({keyUri:d}),c=await xv.computeLongFormDidUri({recoveryKey:o,updateKey:l,services:r.services??[],verificationMethods:a}),{didDocument:u,didResolutionMetadata:f}=await jv.resolve(c,{gatewayUri:r.gatewayUri});if(u===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let h=new bs({uri:c,document:u,metadata:{published:!1,canonicalId:c.split(":",3).join(":"),recoveryKey:o,updateKey:l},keyManager:e});if(r.publish??!0){let p=await jv.publish({did:h,gatewayUri:r.gatewayUri});h.metadata=p.didDocumentMetadata}return h}static async getSigningMethod({didDocument:e,methodId:r}){let n=Fn.parse(e.id);if(n&&n.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(a=>a.id===(r??e.assertionMethod?.[0]));if(!(i&&i.publicKeyJwk))throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async import({portableDid:e,keyManager:r=new Ec}){if(Fn.parse(e.uri)?.method!==jv.methodName)throw new rt("methodNotSupported","Method not supported");return await bs.import({portableDid:e,keyManager:r})}static async publish({did:e,gatewayUri:r=Nq}){let n=e.document.verificationMethod?.map(s=>({id:s.id,publicKeyJwk:s.publicKeyJwk,purposes:X7({didDocument:e.document,methodId:s.id})}))??[],i=await xv.createIonDocument({services:e.document.service??[],verificationMethods:n}),a=await xv.constructCreateRequest({ionDocument:i,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let s=xv.appendPathToUrl({baseUrl:r,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,r={}){let n=Fn.parse(e);if(!n)return{...Ai,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==jv.methodName)return{...Ai,didResolutionMetadata:{error:"methodNotSupported"}};let i=r?.gatewayUri??Nq;try{let a=xv.appendPathToUrl({baseUrl:i,path:`/identifiers/${e}`}),s=await fetch(a,{signal:AbortSignal.timeout(3e4)});if(!s.ok)throw new rt("notFound",`Unable to find DID document for: ${e}`);let{didDocument:o,didDocumentMetadata:d}=await s.json();return{...Ai,...o&&{didDocument:o},didDocumentMetadata:{published:d?.method?.published,...d}}}catch(a){if(!(a instanceof rt))throw new Error(a);return{...Ai,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};rme.methodName="ion";Wz=class Mv extends eb{static async create({keyManager:e=new Ec,options:r={}}={}){if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=r.algorithm??r.verificationMethods?.[0]?.algorithm??"Ed25519",i=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:i}),s=it.object(a).toBase64Url(),o=`did:${Mv.methodName}:${s}`,d=(await Mv.resolve(o)).didDocument;return new bs({uri:o,document:d,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let r=Fn.parse(e.id);if(r&&r.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.verificationMethod??[];if(!(n&&n.publicKeyJwk))throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return n}static async import({portableDid:e,keyManager:r=new Ec}){if(Fn.parse(e.uri)?.method!==Mv.methodName)throw new rt("methodNotSupported","Method not supported");let n=await bs.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new rt("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){let n=Fn.parse(e),i;try{i=n?it.base64Url(n.id).toObject():void 0}catch{}if(!n||!i)return{...Ai,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==Mv.methodName)return{...Ai,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{...Ai,didDocument:a}}};Wz.methodName="jwk";ho=Wz,nme={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},B2=class By{static async jwkToMulticodec({jwk:e}){let r=[];e.crv&&(r.push(e.crv),e.d?r.push("private"):r.push("public"));let n=r.join(":"),i=By.JWK_TO_MULTICODEC[n];if(i===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:Oa.getCodeFromName({name:i}),name:i}}static keyCompressor(e){let r={"P-256":ws.compressPublicKey,secp256k1:Xi.compressPublicKey}[e];if(!r)throw new rt("invalidPublicKeyType",`Unsupported curve: ${e}`);return r}static keyConverter(e){let r={Ed25519:Qi,"P-256":ws,secp256k1:Xi}[e];if(!r)throw new rt("invalidPublicKeyType",`Unsupported curve: ${e}`);return r}static async multicodecToJwk({code:e,name:r}){if(!(r?!e:e))throw new Error("Either 'name' or 'code' must be defined, but not both.");r=r===void 0?Oa.getNameFromCode({code:e}):r;let n=r,i=By.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 nme))throw new rt("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let r=await By.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(r=await By.keyCompressor(e.crv)({publicKeyBytes:r}));let{name:n}=await By.jwkToMulticodec({jwk:e});return ez({keyBytes:r,multicodecName:n})}};B2.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},B2.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},B2.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:""}};m2=B2,ime=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t))(ime||{}),Uq={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},Jz=class yf extends eb{static async create({keyManager:e=new Ec,options:r={}}={}){if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=r.algorithm??r.verificationMethods?.[0]?.algorithm??"Ed25519",i=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:i}),s=await m2.publicKeyToMultibaseId({publicKey:a}),o=`did:${yf.methodName}:${s}`,d=(await yf.resolve(o,r)).didDocument;return new bs({uri:o,document:d,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let r=Fn.parse(e.id);if(r&&r.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.assertionMethod||[],i=e.verificationMethod?.find(a=>a.id===n);if(!(i&&i.publicKeyJwk))throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async import({portableDid:e,keyManager:r=new Ec}){if(Fn.parse(e.uri)?.method!==yf.methodName)throw new rt("methodNotSupported","Method not supported");let n=await bs.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new rt("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){try{let n=await yf.createDocument({didUri:e,options:r});return{...Ai,didDocument:n}}catch(n){if(!(n instanceof rt))throw new Error(n);return{...Ai,didResolutionMetadata:{error:n.code,...n.message&&{errorMessage:n.message}}}}}static async createDocument({didUri:e,options:r={}}){let{defaultContext:n="https://www.w3.org/ns/did/v1",enableExperimentalPublicKeyTypes:i=!1,publicKeyFormat:a="JsonWebKey2020"}=r,s={id:""},o=Fn.parse(e);if(!o)throw new rt("invalidDid",`Invalid DID URI: ${e}`);let d=o.id;if(o.method!==yf.methodName)throw new rt("methodNotSupported",`Method not supported: ${o.method}`);if(!yf.validateIdentifier(o))throw new rt("invalidDid",`Invalid DID URI: ${e}`);let l=await yf.createSignatureMethod({didUri:e,multibaseValue:d,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 c=[n];return Y7({didDocument:s}).forEach(u=>{let f=Uq[u];c.push(f)}),s["@context"]=c,s}static async createSignatureMethod({didUri:e,multibaseValue:r,options:n}){let{enableExperimentalPublicKeyTypes:i,publicKeyFormat:a}=n,s={id:"",type:"",controller:""},{keyBytes:o,multicodecCode:d,multicodecName:l}=tz({multibaseKeyId:r}),c=o.byteLength,u=m2.MULTICODEC_PUBLIC_KEY_LENGTH[d];if(c!==u)throw new rt("invalidPublicKeyLength",`Expected ${c} bytes. Actual: ${u}`);let f=!1;switch(l){case"secp256k1-pub":f=await Xi.validatePublicKey({publicKeyBytes:o});break;case"ed25519-pub":f=await Qi.validatePublicKey({publicKeyBytes:o});break}if(!f)throw new rt("invalidPublicKey","Invalid public key detected.");s.id=`${e}#${r}`;try{new URL(s.id)}catch{throw new rt("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(a in Uq))throw new rt("unsupportedPublicKeyType",`Unsupported format: ${a}`);if(i===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(a))throw new rt("invalidPublicKeyType",`Specified '${a}' without setting enableExperimentalPublicKeyTypes to true.`);if(s.type=a,s.controller=e,a==="Ed25519VerificationKey2020"&&(s.publicKeyMultibase=r),a==="JsonWebKey2020"){let{crv:h}=await m2.multicodecToJwk({code:d});s.publicKeyJwk=await m2.keyConverter(h).bytesToPublicKey({publicKeyBytes:o})}return s}static validateIdentifier(e){let{method:r,id:n}=e,[i]=e.uri.split(":",1);return i==="did"&&r==="key"&&!0&&zR(n)==="String"&&n.startsWith("z")}};Jz.methodName="key";nb=Jz,sme=3e4;Zz=class O2 extends eb{static async create({keyManager:e=new Ec,options:r}){if(!r.domain)throw new rt("invalidDid","The 'domain' option is required for did:web creation");if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");let n=r.path?`${r.domain}:${r.path}`:r.domain,i=`did:${O2.methodName}:${n}`;if(!Fn.parse(i))throw new rt("invalidDid",`The constructed DID URI is invalid: ${i}`);let a=r.verificationMethods??[{algorithm:r.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 d=a[o],l=await e.generateKey({algorithm:d.algorithm}),c=await e.getPublicKey({keyUri:l}),u=d.id?.split("#").pop()??`key-${o}`,f=`${i}#${u}`;s.verificationMethod??=[],s.verificationMethod.push({id:f,type:"JsonWebKey",controller:d.controller??i,publicKeyJwk:c});for(let h of d.purposes??[])s[h]??=[],s[h].push(f)}return r.services&&(s.service=r.services.map(o=>({...o,id:`${i}#${o.id.split("#").pop()}`}))),new bs({uri:i,document:s,metadata:{published:!1},keyManager:e})}static async getSigningMethod({didDocument:e,methodId:r}){let n=Fn.parse(e.id);if(n&&n.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${n.method}`);let i=Gs(r)??Gs(e.assertionMethod?.[0]),a=i?e.verificationMethod?.find(s=>Gs(s.id)===i):e.verificationMethod?.[0];if(!(a&&a.publicKeyJwk))throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return a}static async import({portableDid:e,keyManager:r=new Ec}){if(Fn.parse(e.uri)?.method!==O2.methodName)throw new rt("methodNotSupported","Method not supported");return await bs.import({portableDid:e,keyManager:r})}static async resolve(e,r){let n=Fn.parse(e);if(!n)return{...Ai,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==O2.methodName)return{...Ai,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=new URL(a);if(ome(s.hostname))return{...Ai,didResolutionMetadata:{error:"notFound"}};let o=await fetch(a,{signal:AbortSignal.timeout(sme)});if(!o.ok)throw new Error("HTTP error status code returned");let d=await o.json();return{...Ai,didDocument:d}}catch{return{...Ai,didResolutionMetadata:{error:"notFound"}}}}};Zz.methodName="web";Yz=Zz,ame=ph(Zq(),1),cme=ph(Yq(),1),cE=class{constructor({db:t,location:e="DATA/DID_RESOLVERCACHE",ttl:r="15m"}={}){this.cache=t??new ame.Level(e),this.ttl=(0,cme.default)(r)}open(){return this.cache.open()}async get(t){try{let e=await this.cache.get(t),r=JSON.parse(e);if(Date.now()>=r.ttlMillis){this.cache.nextTick(()=>this.cache.del(t));return}else return r.value}catch(e){if(e.notFound)return;throw e}}set(t,e){let r={ttlMillis:Date.now()+this.ttl,value:e},n=JSON.stringify(r);return this.cache.put(t,n)}delete(t){return this.cache.del(t)}clear(){return this.cache.clear()}close(){return this.cache.close()}},dme=ph(Yq(),1),dE=class{constructor({ttl:t="15m"}={}){this.cache=new vde.default({ttl:(0,dme.default)(t)})}async open(){}async get(t){if(!t)throw new Error("Key cannot be null or undefined");return this.cache.get(t)}async set(t,e){this.cache.set(t,e)}async delete(t){this.cache.delete(t)}async clear(){this.cache.clear()}async close(){}},lme={open(){return Promise.resolve()},get(t){return Promise.resolve(void 0)},set(t,e){return Promise.resolve()},delete(t){return Promise.resolve()},clear(){return Promise.resolve()},close(){return Promise.resolve()}},Zy=class{constructor({cache:t,didResolvers:e}){this.didResolvers=new Map,this.cache=t||lme;for(let r of e)this.didResolvers.set(r.methodName,r)}async open(){await this.cache.open()}async close(){await this.cache.close()}async resolve(t,e){let r=Fn.parse(t);if(!r)return{...Ai,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${t}`}};let n=this.didResolvers.get(r.method);if(!n)return{...Ai,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${r.method}`}};let i=await this.cache.get(r.uri);if(i)return i;{let a=await n.resolve(r.uri,e);return a.didResolutionMetadata.error||await this.cache.set(r.uri,a),a}}async dereference(t,e){let r=Fn.parse(t);if(!r)return{dereferencingMetadata:{error:"invalidDidUrl"},contentStream:null,contentMetadata:{}};let{didDocument:n,didResolutionMetadata:i,didDocumentMetadata:a}=await this.resolve(r.uri);if(!n)return{dereferencingMetadata:{error:i.error},contentStream:null,contentMetadata:{}};if(!r.fragment||r.query)return{dereferencingMetadata:{contentType:"application/did+json"},contentStream:n,contentMetadata:a};let{service:s=[],verificationMethod:o=[]}=n,d=new Set([t,r.fragment,`#${r.fragment}`]),l;for(let c of o)if(d.has(c.id)){l=c;break}for(let c of s)if(d.has(c.id)){l=c;break}return l?{dereferencingMetadata:{contentType:"application/did+json"},contentStream:l,contentMetadata:i}:{dereferencingMetadata:{error:"notFound"},contentStream:null,contentMetadata:{}}}};});var Yy,Xz=F(()=>{"use strict";g();_I();kI();wr();Uo();oN();cN();lN();Lo();s9();o9();v9();b9();P9();x9();E9();S9();t2();CR();Jo();lr();Yy=class t{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 Ty({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new e2(e.resumableTaskStore,this.storageController),this._coreProtocols=new dy,this._coreProtocols.register(new dt);let r={didResolver:this.didResolver,messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,resumableTaskManager:this.resumableTaskManager,coreProtocols:this._coreProtocols,eventLog:this.eventLog};this.methodHandlers={[be.Messages+ge.Read]:new ax(r),[be.Messages+ge.Subscribe]:new lx(r),[be.Messages+ge.Sync]:new fx(r),[be.Protocols+ge.Configure]:new Zx(r),[be.Protocols+ge.Query]:new Xx(r),[be.Records+ge.Count]:new Qx(r),[be.Records+ge.Delete]:new r2(r),[be.Records+ge.Query]:new n2(r),[be.Records+ge.Read]:new i2(r),[be.Records+ge.Subscribe]:new o2(r),[be.Records+ge.Write]:new a2(r)}}static async create(e){e.didResolver||(e.didResolver=new Zy({didResolvers:[po,ho,nb,Yz],cache:new dE}),e.ownsResolver=!0),e.tenantGate??=new ly;let r=new t(e);return await r.open(),r}async open(){this.ownsResolver&&typeof this.didResolver.open=="function"&&await this.didResolver.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(),this.ownsResolver&&typeof this.didResolver.close=="function"&&await this.didResolver.close()}get coreProtocols(){return this._coreProtocols}get storage(){return{messageStore:this.messageStore,stateIndex:this.stateIndex,eventLog:this.eventLog}}async processMessage(e,r,n={}){let i=await this.validateTenant(e)??await this.validateMessageIntegrity(r);if(i!==void 0)return i;let{dataStream:a,subscriptionHandler:s}=n,o=r.descriptor.interface+r.descriptor.method;return await this.methodHandlers[o].handle({tenant:e,message:r,dataStream:a,subscriptionHandler:s})}async validateTenant(e){let r=await this.tenantGate.isActiveTenant(e);if(!r.isActiveTenant)return{status:{code:401,detail:r.detail??`DID ${e} is not an active tenant.`}}}async validateMessageIntegrity(e){let r=e?.descriptor?.interface,n=e?.descriptor?.method;if(r===void 0||n===void 0)return{status:{code:400,detail:`Both interface and method must be present, interface: ${r}, method: ${n}`}};try{we.validateJsonSchema(e)}catch(i){return wt(i,400)}}}});function ume(t){return new Promise((e,r)=>{if(t.aborted){r(t.reason);return}t.addEventListener("abort",()=>{r(t.reason)})})}async function Gn(t,e){return e?Promise.race([t,ume(e)]):t}var lE=F(()=>{"use strict";g()});import{Level as fme}from"level";async function Hs(t,e){return new fme(t,{...e,keyEncoding:"utf8"})}var Ma,Ef=F(()=>{"use strict";g();lE();Ma=class t{config;db;constructor(e,r){this.config={createLevelDatabase:Hs,...e},this.db=r}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,r)=>{let n=()=>{this.db.open().then(e).catch(r)};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,r)=>{let n=()=>{this.db.close().then(e).catch(r)};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 t(this.config,this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding}))}async get(e,r){r?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),r?.signal);try{return await Gn(this.db.get(String(e)),r?.signal)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async has(e,r){return!!await this.get(e,r)}async*keys(e){e?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),e?.signal);for await(let r of this.db.keys())e?.signal?.throwIfAborted(),yield r}async*iterator(e,r){r?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),r?.signal);for await(let n of this.db.iterator(e))r?.signal?.throwIfAborted(),yield n}async put(e,r,n){return n?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),n?.signal),Gn(this.db.put(String(e),r),n?.signal)}async delete(e,r){return r?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),r?.signal),Gn(this.db.del(String(e)),r?.signal)}async isEmpty(e){for await(let r of this.keys(e))return!1;return!0}async clear(){await this.createLevelDatabase(),await this.db.clear(),await this.compactUnderlyingStorage()}async batch(e,r){return r?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),r?.signal),Gn(this.db.batch(e),r?.signal)}createPartitionOperation(e,r){return{...r,sublevel:this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}async compactUnderlyingStorage(e){e?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),e?.signal);let r=this.sublevelRange;if(!r)return;let n=this.root;if(n.db.supports.additionalMethods.compactRange)return Gn(n.db.compactRange?.(...r),e?.signal)}get sublevelRange(){let e=this.db.prefix;if(!e)return;let r=e.slice(0,-1)+String.fromCharCode(e.charCodeAt(e.length-1)+1);return[e,r]}get root(){let e=this.db;for(let r=e.db;r&&r!==e;)e=r;return new t(this.config,e)}async createLevelDatabase(){this.db??=await this.config.createLevelDatabase(this.config.location,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}});var Sf,uE=F(()=>{"use strict";g();vw();Ef();Sf=class t{config;db;constructor(e,r){this.config={createLevelDatabase:Hs,...e},this.db=r??new Ma({...this.config,valueEncoding:"binary"})}async open(){return this.db.open()}async close(){return this.db.close()}async partition(e){let r=await this.db.partition(e);return new t({...this.config,location:""},r)}async put(e,r,n){return await this.db.put(String(e),r,n),er.parse(e.toString())}async get(e,r){return await this.db.get(String(e),r)}async has(e,r){return this.db.has(String(e),r)}async delete(e,r){return this.db.delete(String(e),r)}async isEmpty(e){return this.db.isEmpty(e)}async*putMany(e,r){for await(let n of e)await this.put(n.cid,n.block,r),yield n.cid}async*getMany(e,r){for await(let n of e)yield{cid:n,block:await this.get(n,r)}}async*getAll(e){let r=this.db.iterator({keys:!0,keyEncoding:"buffer"},e);for await(let[n,i]of r)yield{cid:er.decode(n),block:i}}async*deleteMany(e,r){for await(let n of e)await this.delete(n,r),yield n}async clear(){return this.db.clear()}}});function pme(t){return t[Symbol.asyncIterator]!=null}function hme(t){if(pme(t))return(async()=>{let r;for await(let n of t)r=n;return r})();let e;for(let r of t)e=r;return e}var Qz,eF=F(()=>{g();Qz=hme});var tF,mme,rF,yme,nF,iF=F(()=>{g();Kf();Wh();tF=0,mme="identity",rF=Ua,yme=t=>Ff(tF,rF(t)),nF={code:tF,name:mme,encode:rF,digest:yme}});var sF,gme,oF,aF=F(()=>{g();Pm();sF=An(ia(),1);tl();gme=async(t,e,r,n,i,a,s,o)=>{let d=await s.get(t,o),l=hk(d),c=l,u=r;for(;n.length>0;){let f=n[0];if(f in c){n.shift(),u=`${u}/${f}`;let h=er.asCID(c[f]);if(h!=null)return{entry:{type:"object",name:e,path:r,cid:t,node:d,depth:a,size:BigInt(d.length),content:async function*(){yield l}},next:{cid:h,name:f,path:u,toResolve:n}};c=c[f]}else throw(0,sF.default)(new Error(`No property named ${f} found in cbor node ${t}`),"ERR_NO_PROP")}return{entry:{type:"object",name:e,path:r,cid:t,node:d,depth:a,size:BigInt(d.length),content:async function*(){yield l}}}},oF=gme});function wme(t,e,r,n){let i=BigInt(t.length),a=BigInt(e+i);return r>=a||n<e?new Uint8Array(0):(n>=e&&n<a&&(t=t.subarray(0,Number(n-e))),r>=e&&r<a&&(t=t.subarray(Number(r-e))),t)}var Ph,fE=F(()=>{g();Ph=wme});var ib,vme,Xy,pE=F(()=>{g();ib=An(ia(),1),vme=(t,e=0,r=t)=>{let n=BigInt(t),i=BigInt(e??0),a=BigInt(r);if(a!==n&&(a=i+a),a>n&&(a=n),i<0n)throw(0,ib.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,ib.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(a<0n)throw(0,ib.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(a>n)throw(0,ib.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:i,end:a}},Xy=vme});var cF,bme,Pme,dF,lF=F(()=>{g();cF=An(ia(),1);Wh();nl();fE();pE();bme=t=>{async function*e(r={}){let{start:n,end:i}=Xy(t.length,r.offset,r.length),a=Ph(t,0n,n,i);r.onProgress?.(new Dn("unixfs:exporter:progress:identity",{bytesRead:BigInt(a.byteLength),totalBytes:i-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Pme=async(t,e,r,n,i,a,s,o)=>{if(n.length>0)throw(0,cF.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let d=Ub(t.multihash.bytes);return{entry:{type:"identity",name:e,path:r,cid:t,content:bme(d.digest),depth:a,size:BigInt(d.digest.length),node:d.digest}}},dF=Pme});var uF,xme,Eme,fF,pF=F(()=>{g();uF=An(ia(),1);nl();fE();pE();xme=t=>{async function*e(r={}){let{start:n,end:i}=Xy(t.length,r.offset,r.length),a=Ph(t,0n,n,i);r.onProgress?.(new Dn("unixfs:exporter:progress:raw",{bytesRead:BigInt(a.byteLength),totalBytes:i-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Eme=async(t,e,r,n,i,a,s,o)=>{if(n.length>0)throw(0,uF.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let d=await s.get(t,o);return{entry:{type:"raw",name:e,path:r,cid:t,content:xme(d),depth:a,size:BigInt(d.length),node:d}}},fF=Eme});var Sme,Ame,hF,kme,mF,yF,gF=F(()=>{g();sa();h_();m_();Sme=async function(t){return(await q1.encode(t)).slice(0,8).reverse()},Ame=async(t,e,r)=>{await Promise.all(t.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 Nc({hash:r._options.hash,bits:r._options.bits},e,i));return}await r.put(n.Name.substring(2),!0)}))},hF=t=>t.toString(16).toUpperCase().padStart(2,"0").substring(0,2),kme=t=>{let e=t.bucket,r=[];for(;e._parent!=null;)r.push(e),e=e._parent;return r.push(e),r.reverse()},mF=async(t,e,r,n,i)=>{if(n==null){let c=G1({hashFn:Sme});n={rootBucket:c,hamtDepth:1,lastBucket:c}}await Ame(t.Links,n.lastBucket,n.rootBucket);let a=await n.rootBucket._findNewBucketAndPos(e),s=hF(a.pos),o=kme(a);o.length>n.hamtDepth&&(n.lastBucket=o[n.hamtDepth],s=hF(n.lastBucket._posAtParent));let d=t.Links.find(c=>{if(c.Name==null)return!1;let u=c.Name.substring(0,2),f=c.Name.substring(2);return!(u!==s||f!==""&&f!==e)});if(d==null)return;if(d.Name!=null&&d.Name.substring(2)===e)return d.Hash;n.hamtDepth++;let l=await r.get(d.Hash,i);return t=rl(l),mF(t,e,r,n,i)},yF=mF});function _me(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[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(),[r](){return this}}}var hE,Z6=F(()=>{g();hE=_me});function Tme(t){return t[Symbol.asyncIterator]!=null}function Ime(t,e){let r=0;if(Tme(t))return async function*(){for await(let d of t)await e(d,r++)&&(yield d)}();let n=hE(t),{value:i,done:a}=n.next();if(a===!0)return function*(){}();let s=e(i,r++);if(typeof s.then=="function")return async function*(){await s&&(yield i);for(let d of n)await e(d,r++)&&(yield d)}();let o=e;return function*(){s===!0&&(yield i);for(let d of n)o(d,r++)&&(yield d)}()}var wF,vF=F(()=>{g();Z6();wF=Ime});function Dme(t){return t[Symbol.asyncIterator]!=null}function Rme(t,e){let r=0;if(Dme(t))return async function*(){for await(let d of t)yield e(d,r++)}();let n=hE(t),{value:i,done:a}=n.next();if(a===!0)return function*(){}();let s=e(i,r++);if(typeof s.then=="function")return async function*(){yield await s;for(let d of n)yield e(d,r++)}();let o=e;return function*(){yield s;for(let d of n)yield o(d,r++)}()}var Qy,mE=F(()=>{g();Z6();Qy=Rme});function mo(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var yE=F(()=>{g()});async function*xh(t,e={}){let r=e.concurrency??1/0;r<1&&(r=1/0);let n=e.ordered??!1,i=new EventTarget,a=[],s=mo(),o=mo(),d=!1,l,c=!1;i.addEventListener("task-complete",()=>{o.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of t){if(a.length===r&&(s=mo(),await s.promise),c)break;let m={done:!1};a.push(m),p().then(y=>{m.done=!0,m.ok=!0,m.value=y,i.dispatchEvent(new gE("task-complete"))},y=>{m.done=!0,m.err=y,i.dispatchEvent(new gE("task-complete"))})}d=!0,i.dispatchEvent(new gE("task-complete"))}catch(p){l=p,i.dispatchEvent(new gE("task-complete"))}});function u(){return n?a[0]?.done:!!a.find(p=>p.done)}function*f(){for(;a.length>0&&a[0].done;){let p=a[0];if(a.shift(),p.ok)yield p.value;else throw c=!0,s.resolve(),p.err;s.resolve()}}function*h(){for(;u();)for(let p=0;p<a.length;p++)if(a[p].done){let m=a[p];if(a.splice(p,1),p--,m.ok)yield m.value;else throw c=!0,s.resolve(),m.err;s.resolve()}}for(;;){if(u()||(o=mo(),await o.promise),l!=null||(n?yield*f():yield*h(),l!=null))throw l;if(d&&a.length===0)break}}var gE,wE=F(()=>{g();yE();gE=globalThis.CustomEvent??Event});var vE,eg,bF=F(()=>{g();vE=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}},eg=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new vE(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 r=this.head;this.head=r.next=new vE(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}});function bE(t={}){return Cme(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Cme(t,e){e=e??{};let r=e.onEnd,n=new eg,i,a,s,o=mo(),d=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,b)=>{a=w=>{a=null,n.push(w);try{y(t(n))}catch(S){b(S)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{o.resolve(),o=mo()})}},l=y=>a!=null?a(y):(n.push(y),i),c=y=>(n=new eg,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?c(y):l({done:!0})),h=()=>(n=new eg,f(),{done:!0}),p=y=>(f(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:d,return:h,throw:p,push:u,end:f,get readableLength(){return n.size},onEmpty:async y=>{let b=y?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let w,S;b!=null&&(w=new Promise((k,T)=>{S=()=>{T(new Y6)},b.addEventListener("abort",S)}));try{await Promise.race([o.promise,w])}finally{S!=null&&b!=null&&b?.removeEventListener("abort",S)}}},r==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:u,end(y){return m.end(y),r!=null&&(r(y),r=void 0),i},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},i}var Y6,X6=F(()=>{g();yE();bF();Y6=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}}});function $me(t){return t.reason}async function PF(t,e,r){if(e==null)return t;let n=r?.translateError??$me;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([t,new Promise((a,s)=>{i=()=>{s(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var xF=F(()=>{g()});function EF(){return new Q6}var Q6,SF=F(()=>{g();yE();xF();Q6=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=mo(),this.haveNext=mo()}[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=mo(),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,r){await this._push(e,r)}async end(e,r){e!=null?await this.throw(e):await this._push(void 0,r)}async _push(e,r){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=mo(),await PF(this.readNext.promise,r?.signal,r)}}});function Bme(t){return t[Symbol.asyncIterator]!=null}async function Ome(t,e,r){try{await Promise.all(t.map(async n=>{for await(let i of n)await e.push(i,{signal:r}),r.throwIfAborted()})),await e.end(void 0,{signal:r})}catch(n){await e.end(n,{signal:r}).catch(()=>{})}}async function*jme(t){let e=new AbortController,r=EF();Ome(t,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort()}}function*Mme(t){for(let e of t)yield*e}function Kme(...t){let e=[];for(let r of t)Bme(r)||e.push(r);return e.length===t.length?Mme(e):jme(t)}var AF,kF=F(()=>{g();SF();AF=Kme});function tg(t,...e){if(t==null)throw new Error("Empty pipeline");if(e5(t)){let n=t;t=()=>n.source}else if(TF(t)||_F(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&e5(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)e5(r[n])&&(r[n]=Ume(r[n]));return Nme(...r)}var Nme,_F,TF,e5,Ume,PE=F(()=>{g();X6();kF();Nme=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},_F=t=>t?.[Symbol.asyncIterator]!=null,TF=t=>t?.[Symbol.iterator]!=null,e5=t=>t==null?!1:t.sink!=null&&t.source!=null,Ume=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=bE({objectMode:!0});r.then(()=>{n.end()},s=>{n.end(s)});let i,a=t.source;if(_F(a))i=async function*(){yield*a,n.end()};else if(TF(a))i=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return AF(n,i())}return t.source}});var Lme,IF,DF=F(()=>{g();vF();mE();wE();PE();nl();Lme=(t,e,r,n,i,a,s)=>{async function*o(d={}){let l=d.offset??0,c=d.length??e.Links.length,u=e.Links.slice(l,c);d.onProgress?.(new Dn("unixfs:exporter:walk:directory",{cid:t})),yield*tg(u,f=>Qy(f,h=>async()=>{let p=h.Name??"",m=`${n}/${p}`;return(await i(h.Hash,p,m,[],a+1,s,d)).entry}),f=>xh(f,{ordered:!0}),f=>wF(f,h=>h!=null))}return o},IF=Lme});var CF=_e((yqe,t5)=>{"use strict";g();var qme=Object.prototype.hasOwnProperty,Vs="~";function sb(){}Object.create&&(sb.prototype=Object.create(null),new sb().__proto__||(Vs=!1));function zme(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function RF(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var a=new zme(r,n||t,i),s=Vs?Vs+e:e;return t._events[s]?t._events[s].fn?t._events[s]=[t._events[s],a]:t._events[s].push(a):(t._events[s]=a,t._eventsCount++),t}function xE(t,e){--t._eventsCount===0?t._events=new sb:delete t._events[e]}function Ps(){this._events=new sb,this._eventsCount=0}Ps.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)qme.call(r,n)&&e.push(Vs?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};Ps.prototype.listeners=function(e){var r=Vs?Vs+e:e,n=this._events[r];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};Ps.prototype.listenerCount=function(e){var r=Vs?Vs+e:e,n=this._events[r];return n?n.fn?1:n.length:0};Ps.prototype.emit=function(e,r,n,i,a,s){var o=Vs?Vs+e:e;if(!this._events[o])return!1;var d=this._events[o],l=arguments.length,c,u;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,r),!0;case 3:return d.fn.call(d.context,r,n),!0;case 4:return d.fn.call(d.context,r,n,i),!0;case 5:return d.fn.call(d.context,r,n,i,a),!0;case 6:return d.fn.call(d.context,r,n,i,a,s),!0}for(u=1,c=new Array(l-1);u<l;u++)c[u-1]=arguments[u];d.fn.apply(d.context,c)}else{var f=d.length,h;for(u=0;u<f;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),l){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,r);break;case 3:d[u].fn.call(d[u].context,r,n);break;case 4:d[u].fn.call(d[u].context,r,n,i);break;default:if(!c)for(h=1,c=new Array(l-1);h<l;h++)c[h-1]=arguments[h];d[u].fn.apply(d[u].context,c)}}return!0};Ps.prototype.on=function(e,r,n){return RF(this,e,r,n,!1)};Ps.prototype.once=function(e,r,n){return RF(this,e,r,n,!0)};Ps.prototype.removeListener=function(e,r,n,i){var a=Vs?Vs+e:e;if(!this._events[a])return this;if(!r)return xE(this,a),this;var s=this._events[a];if(s.fn)s.fn===r&&(!i||s.once)&&(!n||s.context===n)&&xE(this,a);else{for(var o=0,d=[],l=s.length;o<l;o++)(s[o].fn!==r||i&&!s[o].once||n&&s[o].context!==n)&&d.push(s[o]);d.length?this._events[a]=d.length===1?d[0]:d:xE(this,a)}return this};Ps.prototype.removeAllListeners=function(e){var r;return e?(r=Vs?Vs+e:e,this._events[r]&&xE(this,r)):(this._events=new sb,this._eventsCount=0),this};Ps.prototype.off=Ps.prototype.removeListener;Ps.prototype.addListener=Ps.prototype.on;Ps.prefixed=Vs;Ps.EventEmitter=Ps;typeof t5<"u"&&(t5.exports=Ps)});var r5,$F=F(()=>{g();r5=An(CF(),1)});function i5(t,e,r,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(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:d}=n;d.aborted&&o(OF(d)),d.addEventListener("abort",()=>{o(OF(d))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{s(r())}catch(c){o(c)}return}let d=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,l=r instanceof Error?r:new ob(d);typeof t.cancel=="function"&&t.cancel(),o(l)},e),(async()=>{try{s(await t)}catch(d){o(d)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return a.clear=()=>{clearTimeout(i),i=void 0},a}var ob,n5,BF,OF,jF=F(()=>{g();ob=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},n5=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},BF=t=>globalThis.DOMException===void 0?new n5(t):new DOMException(t),OF=t=>{let e=t.reason===void 0?BF("This operation was aborted."):t.reason;return e instanceof Error?e:BF(e)}});function s5(t,e,r){let n=0,i=t.length;for(;i>0;){let a=Math.trunc(i/2),s=n+a;r(t[s],e)<=0?(n=++s,i-=a+1):i=a}return n}var MF=F(()=>{g()});var Eh,Ul,o5,KF,NF=F(()=>{g();MF();Eh=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},o5=class{constructor(){Ul.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&Eh(this,Ul,"f")[this.size-1].priority>=r.priority){Eh(this,Ul,"f").push(n);return}let i=s5(Eh(this,Ul,"f"),n,(a,s)=>s.priority-a.priority);Eh(this,Ul,"f").splice(i,0,n)}dequeue(){let e=Eh(this,Ul,"f").shift();return e?.run}filter(e){return Eh(this,Ul,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return Eh(this,Ul,"f").length}};Ul=new WeakMap;KF=o5});var En,Ye,Hn,cb,db,kf,TE,lb,EE,Sc,ab,Zo,SE,Yo,ub,Af,AE,UF,LF,FF,qF,zF,kE,a5,c5,IE,GF,_E,DE,d5,HF,VF=F(()=>{g();$F();jF();NF();En=function(t,e,r,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"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},Ye=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},DE=class extends Error{},d5=class extends r5.default{constructor(e){var r,n,i,a;if(super(),Hn.add(this),cb.set(this,void 0),db.set(this,void 0),kf.set(this,0),TE.set(this,void 0),lb.set(this,void 0),EE.set(this,0),Sc.set(this,void 0),ab.set(this,void 0),Zo.set(this,void 0),SE.set(this,void 0),Yo.set(this,0),ub.set(this,void 0),Af.set(this,void 0),AE.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:KF,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.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})`);En(this,cb,e.carryoverConcurrencyCount,"f"),En(this,db,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),En(this,TE,e.intervalCap,"f"),En(this,lb,e.interval,"f"),En(this,Zo,new e.queueClass,"f"),En(this,SE,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,En(this,AE,e.throwOnTimeout===!0,"f"),En(this,Af,e.autoStart===!1,"f")}get concurrency(){return Ye(this,ub,"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})`);En(this,ub,e,"f"),Ye(this,Hn,"m",IE).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:Ye(this,AE,"f"),...r},new Promise((n,i)=>{Ye(this,Zo,"f").enqueue(async()=>{var a,s,o;En(this,Yo,(s=Ye(this,Yo,"f"),s++,s),"f"),En(this,kf,(o=Ye(this,kf,"f"),o++,o),"f");try{if(!((a=r.signal)===null||a===void 0)&&a.aborted)throw new DE("The task was aborted.");let d=e({signal:r.signal});r.timeout&&(d=i5(Promise.resolve(d),r.timeout)),r.signal&&(d=Promise.race([d,Ye(this,Hn,"m",GF).call(this,r.signal)]));let l=await d;n(l),this.emit("completed",l)}catch(d){if(d instanceof ob&&!r.throwOnTimeout){n();return}i(d),this.emit("error",d)}finally{Ye(this,Hn,"m",FF).call(this)}},r),this.emit("add"),Ye(this,Hn,"m",kE).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return Ye(this,Af,"f")?(En(this,Af,!1,"f"),Ye(this,Hn,"m",IE).call(this),this):this}pause(){En(this,Af,!0,"f")}clear(){En(this,Zo,new(Ye(this,SE,"f")),"f")}async onEmpty(){Ye(this,Zo,"f").size!==0&&await Ye(this,Hn,"m",_E).call(this,"empty")}async onSizeLessThan(e){Ye(this,Zo,"f").size<e||await Ye(this,Hn,"m",_E).call(this,"next",()=>Ye(this,Zo,"f").size<e)}async onIdle(){Ye(this,Yo,"f")===0&&Ye(this,Zo,"f").size===0||await Ye(this,Hn,"m",_E).call(this,"idle")}get size(){return Ye(this,Zo,"f").size}sizeBy(e){return Ye(this,Zo,"f").filter(e).length}get pending(){return Ye(this,Yo,"f")}get isPaused(){return Ye(this,Af,"f")}};cb=new WeakMap,db=new WeakMap,kf=new WeakMap,TE=new WeakMap,lb=new WeakMap,EE=new WeakMap,Sc=new WeakMap,ab=new WeakMap,Zo=new WeakMap,SE=new WeakMap,Yo=new WeakMap,ub=new WeakMap,Af=new WeakMap,AE=new WeakMap,Hn=new WeakSet,UF=function(){return Ye(this,db,"f")||Ye(this,kf,"f")<Ye(this,TE,"f")},LF=function(){return Ye(this,Yo,"f")<Ye(this,ub,"f")},FF=function(){var e;En(this,Yo,(e=Ye(this,Yo,"f"),e--,e),"f"),Ye(this,Hn,"m",kE).call(this),this.emit("next")},qF=function(){Ye(this,Hn,"m",c5).call(this),Ye(this,Hn,"m",a5).call(this),En(this,ab,void 0,"f")},zF=function(){let e=Date.now();if(Ye(this,Sc,"f")===void 0){let r=Ye(this,EE,"f")-e;if(r<0)En(this,kf,Ye(this,cb,"f")?Ye(this,Yo,"f"):0,"f");else return Ye(this,ab,"f")===void 0&&En(this,ab,setTimeout(()=>{Ye(this,Hn,"m",qF).call(this)},r),"f"),!0}return!1},kE=function(){if(Ye(this,Zo,"f").size===0)return Ye(this,Sc,"f")&&clearInterval(Ye(this,Sc,"f")),En(this,Sc,void 0,"f"),this.emit("empty"),Ye(this,Yo,"f")===0&&this.emit("idle"),!1;if(!Ye(this,Af,"f")){let e=!Ye(this,Hn,"a",zF);if(Ye(this,Hn,"a",UF)&&Ye(this,Hn,"a",LF)){let r=Ye(this,Zo,"f").dequeue();return r?(this.emit("active"),r(),e&&Ye(this,Hn,"m",a5).call(this),!0):!1}}return!1},a5=function(){Ye(this,db,"f")||Ye(this,Sc,"f")!==void 0||(En(this,Sc,setInterval(()=>{Ye(this,Hn,"m",c5).call(this)},Ye(this,lb,"f")),"f"),En(this,EE,Date.now()+Ye(this,lb,"f"),"f"))},c5=function(){Ye(this,kf,"f")===0&&Ye(this,Yo,"f")===0&&Ye(this,Sc,"f")&&(clearInterval(Ye(this,Sc,"f")),En(this,Sc,void 0,"f")),En(this,kf,Ye(this,cb,"f")?Ye(this,Yo,"f"):0,"f"),Ye(this,Hn,"m",IE).call(this)},IE=function(){for(;Ye(this,Hn,"m",kE).call(this););},GF=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new DE("The task was aborted."))},{once:!0})})},_E=async function(e,r){return new Promise(n=>{let i=()=>{r&&!r()||(this.off(e,i),n())};this.on(e,i)})};HF=d5});async function WF(t,e,r,n,i,a,s){if(e instanceof Uint8Array){let l=Ph(e,n,i,a);r.push(l);return}if(e.Data==null)throw(0,Sh.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let o;try{o=gi.unmarshal(e.Data)}catch(l){throw(0,Sh.default)(l,"ERR_NOT_UNIXFS")}if(o.data!=null){let l=o.data,c=Ph(l,n,i,a);r.push(c),n+=BigInt(c.byteLength)}let d=[];if(e.Links.length!==o.blockSizes.length)throw(0,Sh.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let l=0;l<e.Links.length;l++){let c=e.Links[l],u=n,f=u+o.blockSizes[l];if((i>=u&&i<f||a>=u&&a<=f||i<u&&a>f)&&d.push({link:c,blockStart:n}),n=f,n>a)break}await tg(d,l=>Qy(l,c=>async()=>{let u=await t.get(c.link.Hash,s);return{...c,block:u}}),l=>xh(l,{ordered:!0}),async l=>{for await(let{link:c,block:u,blockStart:f}of l){let h;switch(c.Hash.code){case Sw:h=rl(u);break;case wu:h=u;break;default:r.end((0,Sh.default)(new Error(`Unsupported codec: ${c.Hash.code}`),"ERR_NOT_UNIXFS"));return}let p=new HF({concurrency:1});p.on("error",m=>{r.end(m)}),p.add(async()=>{s.onProgress?.(new Dn("unixfs:exporter:walk:file",{cid:c.Hash})),await WF(t,h,r,f,i,a,s)}),await p.onIdle()}}),n>=a&&r.end()}var Sh,Fme,l5,JF=F(()=>{g();sa();Sh=An(ia(),1);gu();mE();wE();PE();X6();Cw();VF();nl();fE();pE();Fme=(t,e,r,n,i,a,s)=>{async function*o(d={}){let l=r.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:c,end:u}=Xy(l,d.offset,d.length);if(u===0n)return;let f=0n,h=u-c,p=bE();d.onProgress?.(new Dn("unixfs:exporter:walk:file",{cid:t})),WF(s,e,p,0n,c,u,d).catch(m=>{p.end(m)});for await(let m of p)if(m!=null){if(f+=BigInt(m.byteLength),f>h)throw p.end(),(0,Sh.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===h&&p.end(),d.onProgress?.(new Dn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:h,fileSize:l})),yield m}if(f<h)throw(0,Sh.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return o},l5=Fme});async function*ZF(t,e,r,n,i,a){let s=t.Links,o=tg(s,d=>Qy(d,l=>async()=>{let c=l.Name!=null?l.Name.substring(2):null;if(c!=null&&c!==""){let u=await r(l.Hash,c,`${e}/${c}`,[],n+1,i,a);return{entries:u.entry==null?[]:[u.entry]}}else{let u=await i.get(l.Hash,a);return t=rl(u),a.onProgress?.(new Dn("unixfs:exporter:walk:hamt-sharded-directory",{cid:l.Hash})),{entries:ZF(t,e,r,n,i,a)}}}),d=>xh(d,{ordered:!0}));for await(let{entries:d}of o)yield*d}var Gme,YF,XF=F(()=>{g();sa();mE();wE();PE();nl();Gme=(t,e,r,n,i,a,s)=>{function o(d={}){return d.onProgress?.(new Dn("unixfs:exporter:walk:hamt-sharded-directory",{cid:t})),ZF(e,n,i,a,s,d)}return o};YF=Gme});var fb,Hme,Vme,Wme,QF,eG=F(()=>{g();sa();fb=An(ia(),1);gu();gF();DF();JF();XF();Hme=(t,e)=>t.Links.find(n=>n.Name===e)?.Hash,Vme={raw:l5,file:l5,directory:IF,"hamt-sharded-directory":YF,metadata:(t,e,r,n,i,a,s)=>()=>[],symlink:(t,e,r,n,i,a,s)=>()=>[]},Wme=async(t,e,r,n,i,a,s,o)=>{let d=await s.get(t,o),l=rl(d),c,u;if(e==null&&(e=t.toString()),l.Data==null)throw(0,fb.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{c=gi.unmarshal(l.Data)}catch(h){throw(0,fb.default)(h,"ERR_NOT_UNIXFS")}if(r==null&&(r=e),n.length>0){let h;if(c?.type==="hamt-sharded-directory"?h=await yF(l,n[0],s):h=Hme(l,n[0]),h==null)throw(0,fb.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let p=n.shift(),m=`${r}/${p}`;u={cid:h,toResolve:n,name:p??"",path:m}}let f=Vme[c.type](t,l,c,r,i,a,s);if(f==null)throw(0,fb.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return c.isDirectory()?{entry:{type:"directory",name:e,path:r,cid:t,content:f,unixfs:c,depth:a,node:l,size:c.fileSize()},next:u}:{entry:{type:"file",name:e,path:r,cid:t,content:f,unixfs:c,depth:a,node:l,size:c.fileSize()},next:u}},QF=Wme});var tG,Jme,rG,nG,iG=F(()=>{g();Pm();sa();tG=An(ia(),1);Cw();iF();aF();lF();pF();eG();Jme={[Sw]:QF,[wu]:fF,[pu]:oF,[nF.code]:dF},rG=async(t,e,r,n,i,a,s)=>{let o=Jme[t.code];if(o==null)throw(0,tG.default)(new Error(`No resolver for code ${t.code}`),"ERR_NO_RESOLVER");return o(t,e,r,n,rG,i,a,s)},nG=rG});async function*Xme(t,e,r={}){let{cid:n,toResolve:i}=Yme(t),a=n.toString(),s=a,o=i.length;for(;;){let d=await nG(n,a,s,i,o,e,r);if(d.entry==null&&d.next==null)throw(0,RE.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");if(d.entry!=null&&(yield d.entry),d.next==null)return;i=d.next.toResolve,n=d.next.cid,a=d.next.name,s=d.next.path}}async function sG(t,e,r={}){let n=await Qz(Xme(t,e,r));if(n==null)throw(0,RE.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");return n}var RE,Zme,Yme,oG=F(()=>{g();RE=An(ia(),1);eF();tl();iG();Zme=(t="")=>(t.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),Yme=t=>{if(t instanceof Uint8Array)return{cid:er.decode(t),toResolve:[]};let e=er.asCID(t);if(e!=null)return{cid:e,toResolve:[]};if(typeof t=="string"){t.indexOf("/ipfs/")===0&&(t=t.substring(6));let r=Zme(t);return{cid:er.parse(r[0]),toResolve:r.slice(1)}}throw(0,RE.default)(new Error(`Unknown path type ${t}`),"ERR_BAD_PATH")}});var u5,CE,_f,aG=F(()=>{"use strict";g();uE();Ef();hu();oG();w_();u5=new TextEncoder,CE=new TextDecoder,_f=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:Hs,...e},this.blockstore=new Sf({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase})}async open(){await this.blockstore.open()}async close(){await this.blockstore.close()}async put(e,r,n,i){let a=await this.getRefsPartition(e,r),s=await a.get(n);if(s){await i.cancel();let{dataSize:u}=JSON.parse(CE.decode(s));return{dataSize:u}}let o=await this.getRefcountsPartition(),d=await o.get(n),l=d?JSON.parse(CE.decode(d)):{count:0,dataSize:0},c;if(l.count>0)await i.cancel(),c=l.dataSize;else{let u=await this.getBlocksPartition(n),f=Ow([{content:Yt.asAsyncIterable(i)}],u,{cidVersion:1}),h;for await(h of f);c=Number(h.unixfs?.fileSize()??h.size)}return await a.put(n,u5.encode(JSON.stringify({dataSize:c}))),await o.put(n,u5.encode(JSON.stringify({count:l.count+1,dataSize:c}))),{dataSize:c}}async get(e,r,n){let a=await(await this.getRefsPartition(e,r)).get(n);if(!a)return;let{dataSize:s}=JSON.parse(CE.decode(a)),o=await this.getBlocksPartition(n);if(!await o.has(n))return;let c=(await sG(n,o)).content(),u=new ReadableStream({async pull(f){let h=await c.next();h.done?f.close():f.enqueue(h.value)}});return{dataSize:s,dataStream:u}}async delete(e,r,n){let i=await this.getRefsPartition(e,r);if(!await i.get(n))return;await i.delete(n);let s=await this.getRefcountsPartition(),o=await s.get(n);if(!o)return;let d=JSON.parse(CE.decode(o)),l=d.count-1;l<=0?(await(await this.getBlocksPartition(n)).clear(),await s.delete(n)):await s.put(n,u5.encode(JSON.stringify({count:l,dataSize:d.dataSize})))}async clear(){await this.blockstore.clear()}async getRefsPartition(e,r){return(await(await this.blockstore.db.partition("refs")).partition(e)).partition(r)}async getBlocksPartition(e){return(await this.blockstore.partition("blocks")).partition(e)}async getRefcountsPartition(){return this.blockstore.db.partition("refcounts")}}});async function cG(t,e,r){let n=`__compound:${r.name}__`;return(await t.partition(e)).partition(n)}function dG(t,e,r,n,i){let a=[];for(let l of r.properties){let c=e[l];if(c===void 0||Array.isArray(c))return;a.push(n(c))}let s=e[r.sortProperty];if(s===void 0||Array.isArray(s))return;let o=a.join($E),d=n(s);return o+$E+d+i+t}function lG(t,e,r){let n=[];for(let i of e.properties){let a=t[i];if(a===void 0||typeof a=="object")return;n.push(r(a))}return n.join($E)+$E}function uG(t,e,r,n,i,a){let s=dG(r.messageCid,r.indexes,n,i,a);if(s!==void 0)return pG(t,e,`__compound:${n.name}__`,{type:"put",key:s,value:JSON.stringify(r)})}function fG(t,e,r,n,i,a,s){let o=dG(r,n,i,a,s);if(o!==void 0)return pG(t,e,`__compound:${i.name}__`,{type:"del",key:o})}async function pG(t,e,r,n){return(await t.partition(e)).createPartitionOperation(r,n)}function f5(t,e,r){let n,i=0;for(let a of r){if(a.sortProperty!==e.sortProperty)continue;let s=!0;for(let o of a.properties){let d=t[o];if(d===void 0||typeof d=="object"){s=!1;break}}s&&a.properties.length>i&&(n=a,i=a.properties.length)}return n}async function hG(t,e,r,n,i,a,s,o,d){let{sortDirection:l=It.Ascending,cursor:c,limit:u}=n,f=lG(r,i,a);if(f===void 0)return o(e,[r],n,d);let h=await cG(t,e,i),p={};if(c!==void 0){let S=a(c.value),k=f+S+s+c.messageCid;l===It.Ascending?(p.gt=k,p.lt=f+"\xFF"):(p.lt=k,p.gt=f,p.reverse=!0)}else l===It.Ascending?(p.gt=f,p.lt=f+"\xFF"):(p.gt=f,p.lt=f+"\xFF",p.reverse=!0);let m=new Set(i.properties),y={},b=!1;for(let S in r)m.has(S)||(y[S]=r[S],b=!0);let w=[];for await(let[S,k]of h.iterator(p,d)){if(u!==void 0&&w.length===u)break;let T=JSON.parse(k);b&&!ir.matchFilter(T.indexes,y)||w.push(T)}return w}async function mG(t,e,r,n,i,a,s){let o=lG(r,n,i);if(o===void 0)return(await a(e,[r],{sortProperty:n.sortProperty},s)).length;let d=await cG(t,e,n),l=new Set(n.properties),c=!1,u={};for(let p in r)l.has(p)||(u[p]=r[p],c=!0);let f={gt:o,lt:o+"\xFF"},h=0;if(c)for await(let[p,m]of d.iterator(f,s)){let y=JSON.parse(m);ir.matchFilter(y.indexes,u)&&h++}else for await(let[p,m]of d.iterator(f,s))h++;return h}var $E,yG=F(()=>{"use strict";g();lc();Vc();$E=""});var gG,Ah,p5=F(()=>{"use strict";g();Di();b_();Vc();yG();Ef();xt();lc();gG="index",Ah=class t{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:Hs,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new Ma({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,r,n,i){if(pp(n))throw new ie(ne.IndexMissingIndexableProperty,"Index must include at least one valid indexable property");let a={messageCid:r,indexes:n},s=[];for(let c in n){let u=n[c];if(Array.isArray(u))for(let f of u){let h=this.createPutIndexedItemOperation(e,a,c,f);s.push(h)}else{let f=this.createPutIndexedItemOperation(e,a,c,u);s.push(f)}}for(let c of this._compoundIndexes){let u=uG(this.db,e,a,c,t.encodeValue,t.delimiter);u!==void 0&&s.push(u)}let o=this.createOperationForIndexesLookupPartition(e,{type:"put",key:r,value:JSON.stringify(n)});s.push(o);let d=await Promise.all(s);await(await this.db.partition(e)).batch(d,i)}async delete(e,r,n){let i=[],a=await this.getIndexes(e,r);if(a===void 0)return;let s=this.createOperationForIndexesLookupPartition(e,{type:"del",key:r});i.push(s);for(let l in a){let c=a[l];if(Array.isArray(c))for(let u of c){let f=this.createDeleteIndexedItemOperation(e,r,l,u);i.push(f)}else{let u=this.createDeleteIndexedItemOperation(e,r,l,c);i.push(u)}}for(let l of this._compoundIndexes){let c=fG(this.db,e,r,a,l,t.encodeValue,t.delimiter);c!==void 0&&i.push(c)}let o=await Promise.all(i);await(await this.db.partition(e)).batch(o,n)}async createPutIndexedItemOperation(e,r,n,i){let{messageCid:a}=r,s=t.keySegmentJoin(t.encodeValue(i),a);return this.createOperationForIndexPartition(e,n,{type:"put",key:s,value:JSON.stringify(r)})}async createDeleteIndexedItemOperation(e,r,n,i){let a=t.keySegmentJoin(t.encodeValue(i),r);return this.createOperationForIndexPartition(e,n,{type:"del",key:a})}async createOperationForIndexPartition(e,r,n){let i=await this.db.partition(e),a=t.getIndexPartitionName(r);return i.createPartitionOperation(a,n)}async createOperationForIndexesLookupPartition(e,r){return(await this.db.partition(e)).createPartitionOperation(gG,r)}static getIndexPartitionName(e){return`__${e}__`}async getIndexPartition(e,r){let n=t.getIndexPartitionName(r);return(await this.db.partition(e)).partition(n)}async getIndexesLookupPartition(e){return(await this.db.partition(e)).partition(gG)}async query(e,r,n,i){if(r.length===1&&!pp(r[0])){let a=f5(r[0],n,this._compoundIndexes);if(a!==void 0)return hG(this.db,e,r[0],n,a,t.encodeValue,t.delimiter,this.queryWithIteratorPaging.bind(this),i)}return t.shouldQueryWithInMemoryPaging(r,n)?this.queryWithInMemoryPaging(e,r,n,i):this.queryWithIteratorPaging(e,r,n,i)}async count(e,r,n,i){if(r.length===1&&!pp(r[0])){let s=f5(r[0],{...n},this._compoundIndexes);if(s!==void 0)return mG(this.db,e,r[0],s,t.encodeValue,this.query.bind(this),i)}return(await this.query(e,r,{...n},i)).length}async queryWithIteratorPaging(e,r,n,i){let{cursor:a,limit:s}=n,o=a?this.createStartingKeyFromCursor(a):"",d=[];for await(let l of this.getIndexIterator(e,o,n,i)){if(s!==void 0&&s===d.length)break;let{indexes:c}=l;ir.matchAnyFilter(c,r)&&d.push(l)}return d}async*getIndexIterator(e,r,n,i){let{sortProperty:a,sortDirection:s=It.Ascending,cursor:o}=n,d={gt:r};s===It.Descending&&(d.reverse=!0,o!==void 0&&(d.lt=r,delete d.gt));let l=await this.getIndexPartition(e,a);for await(let[c,u]of l.iterator(d,i)){let{indexes:f,messageCid:h}=JSON.parse(u);yield{indexes:f,messageCid:h}}}createStartingKeyFromCursor(e){let{messageCid:r,value:n}=e;return t.keySegmentJoin(t.encodeValue(n),r)}static createCursorFromLastArrayItem(e,r){if(e.length>0)return this.createCursorFromItem(e.at(-1),r)}static createCursorFromItem(e,r){let{messageCid:n,indexes:i}=e,a=i[r];if(a===void 0)throw new ie(ne.IndexInvalidCursorSortProperty,`the sort property '${r}' is not defined within the given item.`);if(typeof a=="boolean"||Array.isArray(a))throw new ie(ne.IndexInvalidCursorValueType,`only string or number values are supported for cursors, a(n) ${typeof a} was given.`);return{messageCid:n,value:a}}async queryWithInMemoryPaging(e,r,n,i){let{sortProperty:a,sortDirection:s=It.Ascending,cursor:o,limit:d}=n,l=o?this.createStartingKeyFromCursor(o):void 0,c=new Map;r.length===0&&(r=[{}]);try{for(let p of r)await this.executeSingleFilterQuery(e,p,a,c,i)}catch(p){if(p.code===ne.IndexInvalidSortPropertyInMemory)return[]}let u=[...c.values()].sort((p,m)=>this.sortItems(p,m,a,s)),f=l!==void 0?this.findCursorStartingIndex(u,s,a,l):0;if(f<0)return[];let h=d!==void 0?f+d:void 0;return u.slice(f,h)}async executeSingleFilterQuery(e,r,n,i,a){let s=d=>{for(let l of d)if(!(i.has(l.messageCid)||!ir.matchFilter(l.indexes,r))){if(l.indexes[n]===void 0)throw new ie(ne.IndexInvalidSortPropertyInMemory,`invalid sort property ${n}`);i.set(l.messageCid,l)}};if(pp(r)){let d=await this.getAllItems(e,n);s(d);return}let o=yP.reduceFilter(r);for(let d in o){let l=o[d];if(ir.isEqualFilter(l)){let c=await this.filterExactMatches(e,d,l,a);s(c)}else if(ir.isOneOfFilter(l))for(let c of new Set(l)){let u=await this.filterExactMatches(e,d,c,a);s(u)}else if(ir.isRangeFilter(l)){let c=await this.filterRangeMatches(e,d,l,a);s(c)}}}async getAllItems(e,r){let n=await this.getIndexPartition(e,r),i=[];for await(let[a,s]of n.iterator())i.push(JSON.parse(s));return i}async filterExactMatches(e,r,n,i){let a=t.keySegmentJoin(t.encodeValue(n)),s={gt:a},o=await this.getIndexPartition(e,r),d=[];for await(let[l,c]of o.iterator(s,i)){if(!l.startsWith(a))break;d.push(JSON.parse(c))}return d}async filterRangeMatches(e,r,n,i){let a={};for(let d in n){let l=d,c=t.encodeValue(n[l]);l==="lte"?a[l]=c+"\xFF":a[l]=c}a.gt===void 0&&a.gte===void 0&&(a.reverse=!0);let s=[],o=await this.getIndexPartition(e,r);for await(let[d,l]of o.iterator(a,i))"gt"in n&&this.extractIndexValueFromKey(d)===t.encodeValue(n.gt)||s.push(JSON.parse(l));return s}sortItems(e,r,n,i){let a=e.indexes[n],s=r.indexes[n],o=t.encodeValue(a)+e.messageCid,d=t.encodeValue(s)+r.messageCid;return i===It.Ascending?jw(o,d):jw(d,o)}findCursorStartingIndex(e,r,n,i){let a=d=>{let{messageCid:l,indexes:c}=d,u=c[n],f=t.keySegmentJoin(t.encodeValue(u),l);return r===It.Ascending?f>i:f<i},s=0,o=e.length;for(;s<o;){let d=s+o>>>1;a(e[d])?o=d:s=d+1}return s<e.length?s:-1}async getIndexes(e,r){let i=await(await this.getIndexesLookupPartition(e)).get(r);if(i!==void 0)return JSON.parse(i)}extractIndexValueFromKey(e){let[r]=e.split(t.delimiter);return r}static delimiter="\0";static keySegmentJoin(...e){return e.join(t.delimiter)}static encodeNumberValue(e){let r=Number.MAX_SAFE_INTEGER,n="!",i=String(Number.MAX_SAFE_INTEGER).length,a=e<0?n:"",s=e<0?r: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,r){for(let n of e)if(!t.isFilterConcise(n,r))return!1;return!0}static isFilterConcise(e,r){return e.recordId!==void 0?!0:r.cursor!==void 0?!1:e.protocolPath!==void 0||e.contextId!==void 0||e.parentId!==void 0||e.schema!==void 0}}});function BE({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*Qme(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let i=[...t,r],a=er.asCID(n);a?yield[i.join("/"),a]:typeof n=="object"&&(yield*h5(n,i))}else{let r=er.asCID(e);r?yield[t.join("/"),r]:yield*h5(e,t)}}function*h5(t,e){if(t==null||t instanceof Uint8Array)return;let r=er.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,i]of Object.entries(t)){let a=[...e,n];yield*Qme(a,i)}}function*eye(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let i=[...t,r];yield i.join("/"),typeof n=="object"&&!er.asCID(n)&&(yield*m5(n,i))}else yield*m5(e,t)}function*m5(t,e){if(!(t==null||typeof t!="object"))for(let[r,n]of Object.entries(t)){let i=[...e,r];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!er.asCID(n)&&(yield*eye(i,n))}}function tye(t,e){let r=t;for(let[n,i]of e.entries()){if(r=r[i],r==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let a=er.asCID(r);if(a)return{value:a,remaining:e.slice(n+1).join("/")}}return{value:r}}async function wG({value:t,codec:e,hasher:r}){if(typeof t>"u")throw new Error('Missing required argument "value"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.encode(t),i=await r.digest(n),a=er.create(1,e.code,i);return new OE({value:t,bytes:n,cid:a})}async function vG({bytes:t,codec:e,hasher:r}){if(!t)throw new Error('Missing required argument "bytes"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.decode(t),i=await r.digest(t),a=er.create(1,e.code,i);return new OE({value:n,bytes:t,cid:a})}var OE,bG=F(()=>{g();vw();bk();OE=class{constructor({cid:e,bytes:r,value:n}){if(!e||!r||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=r,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:BE(),bytes:BE(),value:BE(),asBlock:BE()})}links(){return h5(this.value,[])}tree(){return m5(this.value,[])}get(e="/"){return tye(this.value,e.split("/").filter(Boolean))}}});var nye,Tf,PG=F(()=>{"use strict";g();bG();Pm();uE();il();tl();Ef();lE();p5();wr();Jl();Vc();nye=[{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"}],Tf=class t{config;blockstore;index;constructor(e={}){this.config={blockstoreLocation:"MESSAGESTORE",indexLocation:"INDEX",createLevelDatabase:Hs,...e},this.blockstore=new Sf({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new Ah({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??nye})}async open(){await this.blockstore.open(),await this.index.open()}async close(){await this.blockstore.close(),await this.index.close()}async get(e,r,n){n?.signal?.throwIfAborted();let i=await Gn(this.blockstore.partition(e),n?.signal),a=er.parse(r),s=await i.get(a,n);return s?(await Gn(vG({bytes:s,codec:el,hasher:Bn}),n?.signal)).value:void 0}async query(e,r,n,i,a){a?.signal?.throwIfAborted();let s=t.buildQueryOptions(n,i),o=await this.index.query(e,r,s,a),d;i?.limit!==void 0&&i.limit<o.length&&(o.splice(-1),d=Ah.createCursorFromLastArrayItem(o,s.sortProperty));let l=[];for(let c=0;c<o.length;c++){let{messageCid:u}=o[c],f=await this.get(e,u,a);f&&l.push(f)}return{messages:l,cursor:d}}async count(e,r,n,i){i?.signal?.throwIfAborted();let a=t.buildQueryOptions(n);return this.index.count(e,r,a,i)}static buildQueryOptions(e={},r={}){let{limit:n,cursor:i}=r,{dateCreated:a,datePublished:s,messageTimestamp:o}=e,d=It.Ascending,l="messageTimestamp";return a!==void 0?l="dateCreated":s!==void 0?l="datePublished":o!==void 0&&(l="messageTimestamp"),e[l]!==void 0&&(d=e[l]),n!==void 0&&n>0&&(n=n+1),{sortDirection:d,sortProperty:l,limit:n,cursor:i}}async delete(e,r,n){n?.signal?.throwIfAborted();let i=await Gn(this.blockstore.partition(e),n?.signal),a=er.parse(r);await i.delete(a,n),await this.index.delete(e,r,n)}async put(e,r,n,i){i?.signal?.throwIfAborted();let a=await Gn(this.blockstore.partition(e),i?.signal),s=await Gn(wG({value:r,codec:el,hasher:Bn}),i?.signal),o=hr.parseCid(await we.getCid(r));await a.put(o,s.bytes,i);let d=o.toString();await this.index.put(e,d,n,i)}async clear(){await this.blockstore.clear(),await this.index.clear()}}});var If,xG=F(()=>{"use strict";g();il();Ef();If=class t{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:Hs,...e},this.db=new Ma({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,r){let n=await hr.computeCid(e),i={id:n,timeout:Date.now()+r*1e3,retryCount:0,task:e};return await this.db.put(n,JSON.stringify(i)),i}async grab(e){let r=[];for await(let[n,i]of this.db.iterator()){let a=JSON.parse(i);if(Date.now()>=a.timeout&&(a.timeout=Date.now()+t.taskTimeoutInSeconds*1e3,a.retryCount++,await this.db.put(a.id,JSON.stringify(a)),r.push(a)),r.length>=e)break}return r}async read(e){let r=await this.db.get(e);if(r)return JSON.parse(r)}async extend(e,r){let n=await this.db.get(e);if(n){let i=JSON.parse(n);i.timeout=Date.now()+r*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 EG(t){return{all:t=t||new Map,on:function(e,r){var n=t.get(e);n?n.push(r):t.set(e,[r])},off:function(e,r){var n=t.get(e);n&&(r?n.splice(n.indexOf(r)>>>0,1):t.set(e,[]))},emit:function(e,r){var n=t.get(e);n&&n.slice().map(function(i){i(r)}),(n=t.get("*"))&&n.slice().map(function(i){i(e,r)})}}}var SG=F(()=>{g()});var AG,Df,kG=F(()=>{"use strict";g();SG();lc();xt();AG="events",Df=class t{emitter=EG();isOpen=!1;errorHandler=e=>{console.error("event log error",e)};maxEventsPerTenant;tenantLogs=new Map;tenantSeqs=new Map;constructor(e={}){this.maxEventsPerTenant=e.maxEventsPerTenant??1e4,e.errorHandler&&(this.errorHandler=e.errorHandler)}async open(){this.isOpen=!0}async close(){this.isOpen=!1,this.emitter.all.clear(),this.tenantLogs.clear(),this.tenantSeqs.clear()}async emit(e,r,n){if(!this.isOpen)return this.errorHandler(new ie(ne.EventLogNotOpenError,"a message emitted when EventLog is closed")),"";let a=(this.tenantSeqs.get(e)??0)+1;this.tenantSeqs.set(e,a);let s=this.tenantLogs.get(e);if(s===void 0&&(s=new Map,this.tenantLogs.set(e,s)),s.set(a,{event:r,indexes:n}),s.size>this.maxEventsPerTenant){let d=s.size-this.maxEventsPerTenant,l=0;for(let c of s.keys()){if(l>=d)break;s.delete(c),l++}}let o=`${e}_${AG}`;return this.emitter.emit(o,{tenant:e,event:r,indexes:n,seq:a}),String(a)}async read(e,r={}){let{cursor:n,limit:i,filters:a}=r,s=n!==void 0?t.parseCursor(n):void 0,o=this.tenantLogs.get(e);if(o===void 0||o.size===0)return{events:[],cursor:n};let d=[],l=i??Number.MAX_SAFE_INTEGER;for(let[u,f]of o)if(!(s!==void 0&&u<=s)&&!(a!==void 0&&a.length>0&&!ir.matchAnyFilter(f.indexes,a))&&(d.push({seq:u,event:f.event,indexes:f.indexes}),d.length>=l))break;let c=d.length>0?d[d.length-1].seq:void 0;return{events:d,cursor:c!==void 0?String(c):n}}static parseCursor(e){let r=Number(e);if(Number.isNaN(r)||r<0)throw new ie(ne.EventLogNotOpenError,`invalid cursor: '${e}'`);return r}async subscribe(e,r,n,i){let a=`${e}_${AG}`,{cursor:s,filters:o}=i??{};if(s!==void 0){let l=t.parseCursor(s),c=[],u=!1,f=y=>{o!==void 0&&o.length>0&&!ir.matchAnyFilter(y.indexes,o)||(u?n({type:"event",cursor:String(y.seq),event:y.event}):c.push({event:y.event,seq:y.seq}))};this.emitter.on(a,f);let h=await this.read(e,{cursor:s,filters:o}),p=h.cursor??s,m=h.cursor!==void 0?Number(h.cursor):l;for(let y of h.events)n({type:"event",cursor:String(y.seq),event:y.event});u=!0;for(let y of c)y.seq>m&&n({type:"event",cursor:String(y.seq),event:y.event});return n({type:"eose",cursor:p}),{id:r,close:async()=>{this.emitter.off(a,f)}}}let d=l=>{o!==void 0&&o.length>0&&!ir.matchAnyFilter(l.indexes,o)||n({type:"event",cursor:String(l.seq),event:l.event})};return this.emitter.on(a,d),{id:r,close:async()=>{this.emitter.off(a,d)}}}async trim(e,r){let n=this.tenantLogs.get(e);if(n!==void 0)if(typeof r=="number")for(let i of n.keys())if(i<r)n.delete(i);else break;else for(let[i,a]of n)(a.indexes.messageTimestamp??"")<r&&n.delete(i)}}});var rg,y5=F(()=>{"use strict";g();Fu();rg=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 r=sn(e),n=await this.nodesPartition.get(r);if(n!==void 0)return this.deserializeNode(JSON.parse(n))}async putNode(e,r){this.ensureInitialized();let n=sn(e),i=this.serializeNode(r);await this.nodesPartition.put(n,JSON.stringify(i))}async deleteNode(e){this.ensureInitialized();let r=sn(e);await this.nodesPartition.delete(r)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return zu(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",sn(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:sn(e.leftHash),rightHash:sn(e.rightHash)}:{type:"leaf",keyHash:sn(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:zu(e.leftHash),rightHash:zu(e.rightHash)}:{type:"leaf",keyHash:zu(e.keyHash),valueCid:e.valueCid}}}});var ng,g5=F(()=>{"use strict";g();Fu();ng=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await Pl()}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 r=await qu(e),n=await uy(r,e),i={type:"leaf",keyHash:r,valueCid:e};await this.store.putNode(n,i);let a=await this.getRoot(),s=await this.insertAtNode(a,r,n,i,0);return await this.store.setRoot(s),s}async delete(e){let r=await qu(e),n=await this.getRoot(),i=await this.deleteAtNode(n,r,0);return await this.store.setRoot(i),i}async has(e){let r=await qu(e),n=await this.getRoot();return this.existsAtNode(n,r,0)}async getProof(e){let r=await qu(e),n=await this.getRoot();return this.generateProof(n,r,0)}async getSubtreeHash(e){let r=await this.getRoot();for(let n=0;n<e.length;n++){if(nn(r,this.defaultHashes[n]))return this.defaultHashes[e.length];let i=await this.store.getNode(r);if(i===void 0||i.type==="leaf")return i!==void 0&&i.type==="leaf"?this.computeSubtreeHashForLeaf(i,n,e):this.defaultHashes[e.length];let a=i;e[n]?r=a.rightHash:r=a.leftHash}return r}async getLeaves(e){let r=await this.getRoot();for(let n=0;n<e.length;n++){if(nn(r,this.defaultHashes[n]))return[];let i=await this.store.getNode(r);if(i===void 0)return[];if(i.type==="leaf")return this.leafMatchesPrefix(i.keyHash,e)?[i.valueCid]:[];let a=i;e[n]?r=a.rightHash:r=a.leftHash}return this.collectLeaves(r,e.length)}async diff(e){let r=await this.getRoot(),n=await e.getRoot();if(nn(r,n))return{onlyLocal:[],onlyRemote:[]};let i=[],a=[];return await this.diffAtNode(r,n,0,this,e,i,a),{onlyLocal:i,onlyRemote:a}}async insertAtNode(e,r,n,i,a){if(a>=fs||nn(e,this.defaultHashes[a]))return n;let s=await this.store.getNode(e);if(s===void 0)return n;if(s.type==="leaf")return nn(s.keyHash,r)?(await this.store.deleteNode(e),n):this.splitLeaves(s,e,i,n,a);let o=s,d=io(r,a),l,c;d?(l=o.leftHash,c=await this.insertAtNode(o.rightHash,r,n,i,a+1)):(l=await this.insertAtNode(o.leftHash,r,n,i,a+1),c=o.rightHash);let u=await xl(l,c);if(!nn(u,e)){let f={type:"internal",leftHash:l,rightHash:c};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async splitLeaves(e,r,n,i,a){let s=a;for(;s<fs&&io(e.keyHash,s)===io(n.keyHash,s);)s++;if(s>=fs)return i;let o=io(e.keyHash,s),d,l;o?(d=i,l=r):(d=r,l=i);let c=await xl(d,l);await this.store.putNode(c,{type:"internal",leftHash:d,rightHash:l});for(let u=s-1;u>=a;u--){let f=io(e.keyHash,u),h=this.defaultHashes[u+1],p,m;f?(p=h,m=c):(p=c,m=h),c=await xl(p,m),await this.store.putNode(c,{type:"internal",leftHash:p,rightHash:m})}return c}async deleteAtNode(e,r,n){if(n>=fs)return this.defaultHashes[fs];if(nn(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 nn(i.keyHash,r)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let a=i,s=io(r,n),o,d;if(s?(o=a.leftHash,d=await this.deleteAtNode(a.rightHash,r,n+1)):(o=await this.deleteAtNode(a.leftHash,r,n+1),d=a.rightHash),nn(o,this.defaultHashes[n+1])&&nn(d,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let l=nn(o,this.defaultHashes[n+1]),c=nn(d,this.defaultHashes[n+1]);if(l||c){let f=l?d:o,h=await this.store.getNode(f);if(h!==void 0&&h.type==="leaf")return await this.store.deleteNode(e),f}let u=await xl(o,d);if(!nn(u,e)){let f={type:"internal",leftHash:o,rightHash:d};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async existsAtNode(e,r,n){if(n>=fs||nn(e,this.defaultHashes[n]))return!1;let i=await this.store.getNode(e);if(i===void 0)return!1;if(i.type==="leaf")return nn(i.keyHash,r);let a=i;return io(r,n)?this.existsAtNode(a.rightHash,r,n+1):this.existsAtNode(a.leftHash,r,n+1)}async generateProof(e,r,n){if(n>=fs)return{siblings:[],leafNode:void 0,depth:n};if(nn(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=io(r,n),o,d;s?(o=a.rightHash,d=a.leftHash):(o=a.leftHash,d=a.rightHash);let l=await this.generateProof(o,r,n+1);return l.siblings.unshift(d),l}async computeSubtreeHashForLeaf(e,r,n){for(let i=r;i<n.length;i++)if(io(e.keyHash,i)!==n[i])return this.defaultHashes[n.length];return await uy(e.keyHash,e.valueCid)}leafMatchesPrefix(e,r){for(let n=0;n<r.length;n++)if(io(e,n)!==r[n])return!1;return!0}async collectLeaves(e,r){if(r>=fs||nn(e,this.defaultHashes[r]))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,r+1),s=await this.collectLeaves(i.rightHash,r+1);return[...a,...s]}async diffAtNode(e,r,n,i,a,s,o){if(nn(e,r)||n>=fs)return;let d=nn(e,this.defaultHashes[n]),l=nn(r,this.defaultHashes[n]);if(d&&!l){let f=await a.collectLeaves(r,n);o.push(...f);return}if(!d&&l){let f=await i.collectLeaves(e,n);s.push(...f);return}let c=await i.store.getNode(e),u=await a.store.getNode(r);if(c?.type==="leaf"&&u?.type==="leaf"){nn(c.keyHash,u.keyHash)?c.valueCid!==u.valueCid&&(s.push(c.valueCid),o.push(u.valueCid)):(s.push(c.valueCid),o.push(u.valueCid));return}if(c?.type==="leaf"){let f=await a.collectLeaves(r,n),h=c.valueCid;new Set(f).has(h)||s.push(h);for(let m of f)m!==h&&o.push(m);return}if(u?.type==="leaf"){let f=await i.collectLeaves(e,n),h=u.valueCid;new Set(f).has(h)||o.push(h);for(let m of f)m!==h&&s.push(m);return}if(c?.type==="internal"&&u?.type==="internal"){await this.diffAtNode(c.leftHash,u.leftHash,n+1,i,a,s,o),await this.diffAtNode(c.rightHash,u.rightHash,n+1,i,a,s,o);return}if(c===void 0){let f=await a.collectLeaves(r,n);o.push(...f)}if(u===void 0){let f=await i.collectLeaves(e,n);s.push(...f)}}}});var Rf,_G=F(()=>{"use strict";g();Fu();y5();g5();Ef();Rf=class{config;db;globalTrees=new Map;protocolTrees=new Map;constructor(e){this.config={location:"STATEINDEX",createLevelDatabase:Hs,...e}}async open(){this.db=new Ma({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await Pl()}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,r,n){await(await this.getGlobalTree(e)).insert(r);let a=n.protocol;a!==void 0&&await(await this.getProtocolTree(e,a)).insert(r),await this.storeIndexes(e,r,n)}async delete(e,r){let n=await this.getGlobalTree(e);for(let i of r){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,r){return(await this.getProtocolTree(e,r)).getRoot()}async getSubtreeHash(e,r){return(await this.getGlobalTree(e)).getSubtreeHash(r)}async getProtocolSubtreeHash(e,r,n){return(await this.getProtocolTree(e,r)).getSubtreeHash(n)}async getLeaves(e,r){return(await this.getGlobalTree(e)).getLeaves(r)}async getProtocolLeaves(e,r,n){return(await this.getProtocolTree(e,r)).getLeaves(n)}getGlobalTree(e){let r=this.globalTrees.get(e);return r!==void 0||(r=this.createTree(this.db,[e,"global"]),this.globalTrees.set(e,r)),r}getProtocolTree(e,r){let n=`${e}\0${r}`,i=this.protocolTrees.get(n);return i!==void 0||(i=this.createTree(this.db,[e,"proto",r]),this.protocolTrees.set(n,i)),i}async createTree(e,r){let n=e;for(let s of r)n=await n.partition(s);let i=new rg(n),a=new ng(i);return await a.initialize(),a}async storeIndexes(e,r,n){let i=await this.getMetaPartition(e),a={protocol:n.protocol};await i.put(r,JSON.stringify(a))}async getStoredIndexes(e,r){let i=await(await this.getMetaPartition(e)).get(r);if(i!==void 0)return JSON.parse(i)}async deleteStoredIndexes(e,r){await(await this.getMetaPartition(e)).delete(r)}async getMetaPartition(e){return(await this.db.partition(e)).partition("meta")}}});var jE,TG=F(()=>{"use strict";g();Fu();jE=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(sn(e))}async putNode(e,r){this.nodes.set(sn(e),r)}async deleteNode(e){this.nodes.delete(sn(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}}});var iye,ME,IG=F(()=>{"use strict";g();Pm();tl();hu();Jo();xS();kn();Rc();ox();dx();Lo();s1();Jx();Yx();Jn();nx();mv();ix();s2();Us();Di();Lb();Jl();us();wn();i0();lr();jm();iye={protocol:"http://test-protocol.xyz",published:!1,types:{testRecord:{}},structure:{testRecord:{}}},ME=class t{static async generatePersona(e){let r=e?.did;r||(r=`did:example:${t.randomString(32)}`);let n=t.randomString(10),i=e?.keyId??`${r}#${n}`,a=e?.keyPair??await La.generateKeyPair(),s=e?.encryptionKeyPair;if(!s){let d=await Gt.generateKey();s={publicJwk:await Gt.getPublicKey({key:d}),privateJwk:d}}return{did:r,keyId:i,keyPair:a,encryptionKeyPair:s,signer:new Zd({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:`${r}#${i}`})}}static async installDefaultTestProtocol(e,r){let n=await Pa.create({definition:iye,signer:ut.createSigner(r)}),i=await e.processMessage(r.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 r=e?.author??await t.generatePersona(),n=e?.protocolDefinition;if(!n){let o="record"+t.randomString(10);n={protocol:t.randomString(20),published:e?.published??!1,types:{},structure:{}},n.types[o]={schema:"test-object",dataFormats:["text/plain"]},n.structure[o]={}}let i=ut.createSigner(r),a={messageTimestamp:e?.messageTimestamp,definition:n,signer:i,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},s=await Pa.create(a);return{author:r,message:s.message,protocolsConfigure:s}}static async generateProtocolsQuery(e){let r=e?.author??await t.generatePersona(),n=ut.createSigner(r),i={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};tr(i);let a=await xa.create(i);return{author:r,message:a.message,protocolsQuery:a}}static async generateGrantCreate(e){let r=e?.author??await t.generatePersona(),n=e?.grantedTo??await t.generatePersona(),i=e?.dateExpires??St.createOffsetTimestamp({seconds:10}),a=e?.scope??{interface:be.Messages,method:ge.Read},s=ut.createSigner(r),o=n.did,d={signer:s,grantedTo:o,dateExpires:i,scope:a,description:e?.description??t.randomString(10),delegated:e?.delegated??!1,requestId:e?.requestId,conditions:e?.conditions},l=await dt.createGrant(d);return{dataStream:Yt.fromBytes(l.permissionGrantBytes),recordsWrite:l.recordsWrite,dataBytes:l.permissionGrantBytes,message:l.recordsWrite.message,dataEncodedMessage:l.dataEncodedMessage}}static async generateRecordsWrite(e){let r=e?.author??await t.generatePersona(),n=ut.createSigner(r),i=ut.createSigners(e?.attesters??[]),a=e?.dataCid,s=e?.dataSize,o,d;a===void 0&&s===void 0&&(o=e?.data??t.randomBytes(32),d=Yt.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://${t.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},c=await At.create(l),u=c.message;return{author:r,message:u,dataCid:a,dataSize:s,dataBytes:o,dataStream:d,recordsWrite:c}}static async generateProtocolEncryptedRecordsWrite(e){let{plaintextBytes:r,author:n,recipient:i,protocolDefinition:a,protocolPath:s,protocolParentContextId:o,protocolContextDerivingRootKeyId:d,protocolContextDerivedPublicKeyJwk:l}=e,c=t.randomBytes(12),u=t.randomBytes(32),{ciphertext:f,tag:h}=await Bi.aeadEncrypt(ii.A256GCM,u,c,r),p=s.split("/"),m=p[p.length-1],{message:y,dataStream:b,recordsWrite:w}=await t.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}),S={initializationVector:c,key:u,authenticationTag:h,keyEncryptionInputs:[]};if(e.encryptSymmetricKeyWithProtocolPathDerivedKey){let k=a.structure;for(let C of p)k=k[C];let T=k.$encryption?.publicKeyJwk,K={publicKeyId:k.$encryption?.rootKeyId,publicKey:T,derivationScheme:Ht.ProtocolPath};S.keyEncryptionInputs.push(K)}if(e.encryptSymmetricKeyWithProtocolContextDerivedKey){let k;if(o===void 0){let T={rootKeyId:n.keyId,derivationScheme:Ht.ProtocolContext,derivedPrivateKey:n.encryptionKeyPair.privateJwk},D=await At.getEntryId(n.did,y.descriptor),K=Te.constructKeyDerivationPathUsingProtocolContextScheme(D),C=await $s.derivePublicKey(T,K);k={publicKeyId:n.keyId,publicKey:C,derivationScheme:Ht.ProtocolContext}}else{if(d===void 0||l===void 0)throw new Error("`protocolContextDerivingRootKeyId` and `protocolContextDerivedPublicKeyJwk` must both be defined if `protocolContextId` is given");k={publicKeyId:d,publicKey:l,derivationScheme:Ht.ProtocolContext}}S.keyEncryptionInputs.push(k)}return await w.encryptSymmetricEncryptionKey(S),await w.sign({signer:ut.createSigner(n)}),{message:y,dataStream:b,recordsWrite:w,encryptedDataBytes:f,encryptionInput:S}}static async generateFromRecordsWrite(e){let r=e.existingWrite.message,n=St.getCurrentTimestamp(),i=!(e.published??r.descriptor.published),a=e.datePublished??(i?n:void 0),s=e.data??t.randomBytes(32),o=Yt.fromBytes(s),d={recordsWriteMessage:e.existingWrite.message,data:s,published:i,datePublished:a,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:ut.createSigner(e.author)},l=await At.createFrom(d);return{message:l.message,recordsWrite:l,dataBytes:s,dataStream:o}}static async generateRecordsQuery(e){let r=e?.author,n=e?.anonymous??!1;if(n&&r)throw new Error("Cannot have `author` and be anonymous at the same time.");r===void 0&&!n&&(r=await t.generatePersona());let i;r!==void 0&&(i=ut.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:t.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole};tr(a);let o=(await ha.create(a)).message;return{author:r,message:o}}static async generateRecordsSubscribe(e){let r=e?.author,n=e?.anonymous??!1;if(n&&r)throw new Error("Cannot have `author` and be anonymous at the same time.");r===void 0&&!n&&(r=await t.generatePersona());let i;r!==void 0&&(i=ut.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:t.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole,cursor:e?.cursor};tr(a);let o=(await Sa.create(a)).message;return{author:r,message:o}}static async generateRecordsCount(e){let r=e?.author,n=e?.anonymous??!1;if(n&&r)throw new Error("Cannot have `author` and be anonymous at the same time.");r===void 0&&!n&&(r=await t.generatePersona());let i;r!==void 0&&(i=ut.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:t.randomString(10)},protocolRole:e?.protocolRole};tr(a);let o=(await ad.create(a)).message;return{author:r,message:o}}static async generateRecordsDelete(e){let r=e?.author??await t.generateDidKeyPersona(),n=await Ea.create({recordId:e?.recordId??await t.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:ut.createSigner(r)});return{author:r,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let r=e?.author??await t.generatePersona(),n=ut.createSigner(r),i={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};tr(i);let a=await ld.create(i),s=a.message;return{author:r,messagesSubscribe:a,message:s}}static async generateMessagesRead(e){let r=e?.author??await t.generatePersona(),i={signer:ut.createSigner(r),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},a=await dd.create(i);return{author:r,messagesRead:a,message:a.message}}static generateAuthorization(){return{signature:t.generateAuthorizationSignature()}}static generateAuthorizationSignature(){return{payload:"anyPayload",signatures:[{protected:"anyProtectedHeader",signature:"anySignature"}]}}static async randomSignatureString(){let e=await Cg.generateKeyPair(),r=await Cg.sign(t.randomBytes(32),e.privateJwk);return De.bytesToBase64Url(r)}static randomString(e){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="";for(let i=0;i<e;i++)n+=r.charAt(Math.floor(Math.random()*r.length));return n}static randomBytes(e){let r=new Uint8Array(e);for(let n=0;n<e;n++)r[n]=Math.floor(Math.random()*256);return r}static async randomCborSha256Cid(){let e=t.randomBytes(32),r=await Bn.digest(e);return(await er.createV1(pu,r)).toString()}static randomInt(e,r){return Math.floor(Math.random()*(r-e)+e)}static randomTimestamp(e){let{year:r,month:n,day:i,hour:a,minute:s,second:o,millisecond:d,microsecond:l}=e||{};return St.createTimestamp({year:r||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:d||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 nb.create(),r=await nb.getSigningMethod({didDocument:e.document}),n=r.id,i=await e.export(),a={publicJwk:r.publicKeyJwk,privateJwk:i.privateKeys[0]},s=await Gt.generateKey(),d={publicJwk:await Gt.getPublicKey({key:s}),privateJwk:s};return{did:e.uri,keyId:n,keyPair:a,encryptionKeyPair:d,signer:new Zd({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:n})}}}});var KE,DG=F(()=>{"use strict";g();us();KE=class t{static pollRetrySleep=20;static pollTimeout=2e3;static async pollUntilSuccessOrTimeout(e,r=t.pollRetrySleep,n=t.pollTimeout){let i=Date.now();for(;;)try{return await e()}catch{if(Date.now()-i>=n)throw new Error("Operation timed out");await St.sleep(r)}}}});var RG={};ar(RG,{AllowAllTenantGate:()=>ly,BlockstoreLevel:()=>Sf,Cid:()=>hr,ContentEncryptionAlgorithm:()=>ii,CoreProtocolRegistry:()=>dy,DataStoreLevel:()=>_f,DataStream:()=>Yt,DateSort:()=>Kt,Dwn:()=>Yy,DwnConstant:()=>ma,DwnError:()=>ie,DwnErrorCode:()=>ne,DwnInterfaceName:()=>be,DwnMethodName:()=>ge,Encoder:()=>De,Encryption:()=>Bi,EventEmitterEventLog:()=>Df,HdKey:()=>$s,IndexLevel:()=>Ah,Jws:()=>ut,KeyAgreementAlgorithm:()=>n0,KeyDerivationScheme:()=>Ht,LevelWrapper:()=>Ma,Message:()=>we,MessageStoreLevel:()=>Tf,MessagesRead:()=>dd,MessagesSubscribe:()=>ld,MessagesSync:()=>Gu,PERMISSIONS_REVOCATION_PATH:()=>gP,PermissionConditionPublication:()=>Mm,PermissionGrant:()=>Ir,PermissionRequest:()=>cd,PermissionsProtocol:()=>dt,Poller:()=>KE,PrivateKeySigner:()=>Zd,ProtocolRecordLimitStrategy:()=>Hl,Protocols:()=>md,ProtocolsConfigure:()=>Pa,ProtocolsQuery:()=>xa,Records:()=>Te,RecordsCount:()=>ad,RecordsDelete:()=>Ea,RecordsQuery:()=>ha,RecordsRead:()=>gd,RecordsSubscribe:()=>Sa,RecordsWrite:()=>At,ResumableTaskStoreLevel:()=>If,SMTStoreLevel:()=>rg,SMTStoreMemory:()=>jE,SMT_DEPTH:()=>fs,Secp256k1:()=>La,Secp256r1:()=>Jd,SortDirection:()=>It,SparseMerkleTree:()=>ng,StateIndexLevel:()=>Rf,TestDataGenerator:()=>ME,Time:()=>St,ZERO_HASH:()=>ux,authenticate:()=>pn,createLevelDatabase:()=>Hs,executeUnlessAborted:()=>Gn,getBit:()=>io,getDefaultHashes:()=>II,getRuleSetAtPath:()=>yd,hashChildren:()=>xl,hashEquals:()=>nn,hashKey:()=>qu,hashLeaf:()=>uy,hashToHex:()=>sn,hexToHash:()=>zu,initDefaultHashes:()=>Pl,isCrossProtocolRef:()=>tf,parseCrossProtocolRef:()=>zs});var Yn=F(()=>{"use strict";g();Tg();No();kI();lT();_I();il();nx();ix();hu();jm();Xz();B0();xt();lr();kn();dx();i0();Us();lE();Rc();wr();ox();DI();nc();TI();Lo();s1();Yp();Jx();Yx();Jn();mv();RR();s2();Lb();AA();Vc();us();uT();hp();uE();aG();p5();Ef();PG();xG();kG();_G();g5();y5();TG();Fu();IG();DG()});var qE=_e((DGe,BG)=>{g();var sg=1e3,og=sg*60,ag=og*60,kh=ag*24,oye=kh*7,aye=kh*365.25;BG.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return cye(t);if(r==="number"&&isFinite(t))return e.long?lye(t):dye(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function cye(t){if(t=String(t),!(t.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(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*aye;case"weeks":case"week":case"w":return r*oye;case"days":case"day":case"d":return r*kh;case"hours":case"hour":case"hrs":case"hr":case"h":return r*ag;case"minutes":case"minute":case"mins":case"min":case"m":return r*og;case"seconds":case"second":case"secs":case"sec":case"s":return r*sg;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function dye(t){var e=Math.abs(t);return e>=kh?Math.round(t/kh)+"d":e>=ag?Math.round(t/ag)+"h":e>=og?Math.round(t/og)+"m":e>=sg?Math.round(t/sg)+"s":t+"ms"}function lye(t){var e=Math.abs(t);return e>=kh?LE(t,e,kh,"day"):e>=ag?LE(t,e,ag,"hour"):e>=og?LE(t,e,og,"minute"):e>=sg?LE(t,e,sg,"second"):t+" ms"}function LE(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});g();g();Yn();Yn();var Re=(c=>(c[c.MessagesRead=be.Messages+ge.Read]="MessagesRead",c[c.MessagesSubscribe=be.Messages+ge.Subscribe]="MessagesSubscribe",c[c.MessagesSync=be.Messages+ge.Sync]="MessagesSync",c[c.ProtocolsConfigure=be.Protocols+ge.Configure]="ProtocolsConfigure",c[c.ProtocolsQuery=be.Protocols+ge.Query]="ProtocolsQuery",c[c.RecordsDelete=be.Records+ge.Delete]="RecordsDelete",c[c.RecordsQuery=be.Records+ge.Query]="RecordsQuery",c[c.RecordsRead=be.Records+ge.Read]="RecordsRead",c[c.RecordsSubscribe=be.Records+ge.Subscribe]="RecordsSubscribe",c[c.RecordsWrite=be.Records+ge.Write]="RecordsWrite",c))(Re||{}),Id={[Re.MessagesRead]:dd,[Re.MessagesSubscribe]:ld,[Re.MessagesSync]:Gu,[Re.ProtocolsConfigure]:Pa,[Re.ProtocolsQuery]:xa,[Re.RecordsDelete]:Ea,[Re.RecordsQuery]:ha,[Re.RecordsRead]:gd,[Re.RecordsSubscribe]:Sa,[Re.RecordsWrite]:At};g();Jo();Er();var Cf=class extends cE{constructor({agent:r,db:n,location:i,ttl:a}){super({db:n,location:i,ttl:a});this._resolving=new Map;this._agent=r}get agent(){if(!this._agent)throw new Error("Agent not initialized");return this._agent}set agent(r){this._agent=r}async get(r){try{let n=await this.cache.get(r),i=JSON.parse(n);if(!this._resolving.has(r)&&Date.now()>=i.ttlMillis){this._resolving.set(r,!0);let a=await this.agent.did.get({didUri:r,tenant:this.agent.agentDid.uri});if(typeof a<"u")try{let s=await this.agent.did.resolve(r);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(d){d.message&&!d.message.includes("No changes detected, update aborted")&&Rs.error(`Error updating DID: ${d.message}`)}}}finally{this._resolving.delete(r)}else this._resolving.delete(r),this.cache.nextTick(()=>this.cache.del(r))}return i.value}catch(n){if(n.notFound)return;throw n}}};g();Yn();g();Jo();Yn();async function pb(t,e){let r=await e.dereference(`${t}#dwn`);if(r.dereferencingMetadata.error)throw new Error(`Failed to dereference '${t}#dwn': ${r.dereferencingMetadata.error}`);if(B6.isDwnDidService(r.contentStream)){let{serviceEndpoint:n}=r.contentStream,i=typeof n=="string"?[n]:Array.isArray(n)&&n.every(a=>typeof a=="string")?n:[];if(i.length>0)return i}return[]}function lGe(t){return we.getAuthor(t)}function uGe(t){return ut.decodePlainObjectPayload(t.authorization.signature)?.protocolRole}function Ll(t){return!t||typeof t!="object"||t===null?!1:"message"in t&&typeof t.message=="object"&&t.message!==null&&"descriptor"in t.message&&typeof t.message.descriptor=="object"&&t.message.descriptor!==null&&"interface"in t.message.descriptor&&t.message.descriptor.interface===be.Records&&"method"in t.message.descriptor&&t.message.descriptor.method===ge.Write}function sye(t){return we.getCid(t)}async function fGe(t,e){let r=e===Kt.CreatedAscending||e===Kt.CreatedDescending?t.descriptor.dateCreated:t.descriptor.datePublished;if(r===void 0)throw new Error("The dateCreated or datePublished property is missing from the record descriptor.");return{messageCid:await sye(t),value:r}}function pGe(t,e=3e3,r=3e5,n){let i=Date.now()+r,a=null,s=!0;return new Promise((o,d)=>{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 c=i-Date.now();if(c<=0){s=!1,console.log("Polling stopped: TTL reached"),o(null);return}console.log(`Polling... (Remaining time: ${Math.ceil(c/1e3)}s)`);try{let u=await t();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),d(u)}s&&(a=setTimeout(l,e))}l()})}function hb(t,e){return t.endsWith("/")&&(t=t.slice(0,-1)),e.startsWith("/")&&(e=e.slice(1)),`${t}/${e}`}var CG=class{constructor({didResolver:e,rpcClient:r}){this._didResolver=e,this._rpcClient=r}async recordsQuery(e,r){let n=await ha.create({filter:r.filter,dateSort:r.dateSort,pagination:r.pagination,messageTimestamp:r.messageTimestamp});return await this.sendRequest(e,n.message)}async recordsRead(e,r){let n=await gd.create({filter:r.filter,messageTimestamp:r.messageTimestamp});return await this.sendRequest(e,n.message)}async recordsSubscribe(e,r,n){let i=await Sa.create({filter:r.filter,dateSort:r.dateSort,pagination:r.pagination,messageTimestamp:r.messageTimestamp});return await this.sendRequest(e,i.message,void 0,n)}async recordsCount(e,r){let n=await ad.create({filter:r.filter,messageTimestamp:r.messageTimestamp});return await this.sendRequest(e,n.message)}async protocolsQuery(e,r){let n=await xa.create({filter:r?.filter,messageTimestamp:r?.messageTimestamp});return await this.sendRequest(e,n.message)}async sendRequest(e,r,n,i){let a=await pb(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 c=new URL(o);c.protocol=c.protocol==="http:"?"ws:":"wss:",o=c.toString()}return await this._rpcClient.sendDwnRequest({dwnUrl:o,targetDid:e,message:r,data:n,subscriptionHandler:i})}catch(d){s.push({url:o,message:d instanceof Error?d.message:"Unknown error"})}throw new Error(`AnonymousDwnApi: Failed to send request to '${e}': ${JSON.stringify(s)}`)}};g();var ig=class{constructor({did:e,metadata:r}){this.did=e,this.metadata=r}async export(){return{portableDid:await this.did.export(),metadata:{...this.metadata}}}};g();wn();var w5={"AES-GCM":{implementation:$m,names:["A128GCM","A192GCM","A256GCM"],operations:["bytesToPrivateKey","decrypt","encrypt","generateKey"]},"AES-KW":{implementation:Bm,names:["A128KW","A192KW","A256KW"],operations:["bytesToPrivateKey","generateKey","privateKeyToBytes","wrapKey","unwrapKey"]},Ed25519:{implementation:Fc,names:["Ed25519"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},HKDF:{implementation:fP,names:["HKDF-256","HKDF-384","HKDF-512"],operations:["deriveKey","deriveKeyBytes"]},PBKDF2:{implementation:hP,names:["PBES2-HS256+A128KW","PBES2-HS384+A192KW","PBES2-HS512+A256KW"],operations:["deriveKey","deriveKeyBytes"]},secp256k1:{implementation:oc,names:["ES256K","secp256k1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},secp256r1:{implementation:oc,names:["ES256","secp256r1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},"SHA-256":{implementation:_u,names:["SHA-256"],operations:["digest"]},X25519:{implementation:Iu,names:["X25519"],operations:["bytesToPrivateKey","generateKey"]}},yo=class{constructor(){this._algorithmInstances=new Map}async bytesToPrivateKey({algorithm:e,privateKeyBytes:r}){let n=this.getAlgorithmName({algorithm:e});return await this.getAlgorithm({algorithm:n}).bytesToPrivateKey({algorithm:e,privateKeyBytes:r})}async bytesToPublicKey({algorithm:e,publicKeyBytes:r}){let n=this.getAlgorithmName({algorithm:e});return await this.getAlgorithm({algorithm:n}).bytesToPublicKey({algorithm:e,publicKeyBytes:r})}async decrypt(e){let r=this.getAlgorithmName({key:e.key});return await this.getAlgorithm({algorithm:r}).decrypt(e)}async deriveKey(e){let r=this.getAlgorithmName({algorithm:e.algorithm}),n=this.getAlgorithm({algorithm:r}),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 Fe(Le.AlgorithmNotSupported,`The specified "algorithm" is not supported: ${e.algorithm}`)}let a=+(i.match(/\d+/)?.[0]??-1);if(a===-1)throw new Fe(Le.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 r=this.getAlgorithmName({algorithm:e.algorithm});return await this.getAlgorithm({algorithm:r}).deriveKeyBytes(e)}async digest({algorithm:e,data:r}){return await this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:r})}async encrypt(e){let r=this.getAlgorithmName({key:e.key});return await this.getAlgorithm({algorithm:r}).encrypt(e)}async generateKey(e){let r=this.getAlgorithmName({algorithm:e.algorithm}),i=await this.getAlgorithm({algorithm:r}).generateKey({algorithm:e.algorithm});return i.kid??=await vt({jwk:i}),i}async getPublicKey({key:e}){let r=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:r}).getPublicKey({key:e})}async privateKeyToBytes({privateKey:e}){let r=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:r}).privateKeyToBytes({privateKey:e})}async publicKeyToBytes({publicKey:e}){let r=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:r}).publicKeyToBytes({publicKey:e})}async sign({key:e,data:r}){let n=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:n}).sign({data:r,key:e})}async unwrapKey(e){let r=this.getAlgorithmName({key:e.decryptionKey});return await this.getAlgorithm({algorithm:r}).unwrapKey(e)}async verify({key:e,signature:r,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:r,data:n})}async wrapKey(e){let r=this.getAlgorithmName({key:e.encryptionKey});return await this.getAlgorithm({algorithm:r}).wrapKey(e)}getAlgorithm({algorithm:e}){let r=w5[e]?.implementation;if(!r)throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported: ${e}`);return this._algorithmInstances.has(r)||this._algorithmInstances.set(r,new r),this._algorithmInstances.get(r)}getAlgorithmName({algorithm:e,key:r}){let n=r?.alg??e,i=r?.crv;for(let a of Object.keys(w5)){let s=w5[a].names;if(n&&s.includes(n))return a;if(i&&s.includes(i))return a}throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported based on provided input: alg=${n}, crv=${i}. Please check the documentation for the list of supported algorithms.`)}};g();Jo();wn();g();Er();Jo();g();var NE={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:{}}},ql={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"}}}}},$G={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();wn();var ki="^",UE=class extends Gc{constructor(){super(),this._predefinedKeys=new Map,this._keyGenerator=this._predefinedKeys.keys()}async addPredefinedKeys({privateKeys:e}){let r={};for(let n of e){n.kid??=await vt({jwk:n});let i=await this.getKeyUri({key:n});r[i]=n}this._predefinedKeys=new Map(Object.entries(r)),this._keyGenerator=this._predefinedKeys.keys()}async exportKey({keyUri:e}){let r=this._predefinedKeys.get(e);if(!r)throw new Error(`DeterministicKeyGenerator.exportKey: Key not found: ${e}`);return r}async generateKey(e){let{value:r,done:n}=this._keyGenerator.next();if(n)throw new Error("Ran out of predefined keys");return r}async getPublicKey({keyUri:e}){let r=this._predefinedKeys.get(e);if(!r)throw new Error(`DeterministicKeyGenerator.getPublicKey: Key not found: ${e}`);let{d:n,...i}=r;return i}async sign({keyUri:e,data:r}){let n=this._predefinedKeys.get(e);if(!n)throw new Error(`DeterministicKeyGenerator.sign: Key not found: ${e}`);return await wi.sign({data:r,key:n})}};async function Dd({agent:t,tenant:e,didUri:r}){if(e)return e;if(t.agentDid)return t.agentDid.uri;if(!r)throw new Error("Failed to determine tenant DID: 'agent.agentDid', 'tenant', and 'didUri' are undefined");return r}g();var mb=An(qE(),1);Er();Yn();var $f=class{constructor(){this.name="DwnDataStore";this._cache=new cs.default({ttl:(0,mb.default)("15 minutes"),max:100});this._index=new cs.default({ttl:(0,mb.default)("21 days"),max:1e3});this._protocolInitializedCache=new cs.default({ttl:(0,mb.default)("21 days"),max:1e3});this._tenantEncryptionActive=new cs.default({ttl:(0,mb.default)("21 days"),max:1e3});this._recordProperties={dataFormat:"application/json",protocol:"",protocolPath:""}}async delete({id:e,agent:r,tenant:n}){let i=await Dd({agent:r,tenant:n,didUri:e}),a=await this.lookupRecordId({id:e,tenantDid:i,agent:r});if(!a)return!1;let{reply:{status:s}}=await r.dwn.processRequest({author:i,target:i,messageType:Re.RecordsDelete,messageParams:{recordId:a}});if(s.code===202)return this._index.delete(`${i}${ki}${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:r,tenant:n,useCache:i=!1}){let a=await Dd({agent:r,tenant:n,didUri:e}),s=await this.lookupRecordId({id:e,tenantDid:a,agent:r});if(s)return await this.getRecord({recordId:s,tenantDid:a,agent:r,useCache:i})}async list({agent:e,tenant:r}){let n=await Dd({tenant:r,agent:e});return await this.getAllRecords({agent:e,tenantDid:n})}async set({id:e,data:r,tenant:n,agent:i,preventDuplicates:a=!0,updateExisting:s=!1,useCache:o=!1}){let d=await Dd({agent:i,tenant:n,didUri:e});await this.initialize({tenant:d,agent:i});let l={...this._recordProperties};if(s){let p=await this.getExistingRecordEntry({id:e,tenantDid:d,agent:i});if(!p)throw new Error(`${this.name}: Update failed due to missing entry for: ${e}`);l.recordId=p.recordsWrite.recordId,l.dateCreated=p.recordsWrite.descriptor.dateCreated}else if(a&&await this.lookupRecordId({id:e,tenantDid:d,agent:i}))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${e}`);let c=he.object(r).toUint8Array(),u=this.isEncryptionActive(d),{message:f,reply:{status:h}}=await i.dwn.processRequest({author:d,target:d,messageType:Re.RecordsWrite,messageParams:{...this._recordProperties,...l},dataStream:new Blob([c],{type:"application/json"}),...u?{encryption:!0}:{}});if(!(f&&h.code===202))throw new Error(`${this.name}: Failed to write data to store for ${e}: ${h.detail}`);this._index.set(`${d}${ki}${e}`,f.recordId),o&&this._cache.set(f.recordId,r)}async initialize({tenant:e,agent:r}){let n=await Dd({agent:r,tenant:e});if(this._protocolInitializedCache.has(n))return;let{reply:{status:i,entries:a}}=await r.dwn.processRequest({author:n,target:n,messageType:Re.ProtocolsQuery,messageParams:{filter:{protocol:this._recordProtocolDefinition.protocol}}});if(i.code!==200)throw new Error(`Failed to query for protocols: ${i.code} - ${i.detail}`);if(a?.length===0)await this.installProtocol(n,r);else if(this.encryptionRequired&&!this._tenantEncryptionActive.has(n)){let s=a[0].descriptor?.definition,o=Object.keys(s?.structure??{})[0],d=!!(o&&s?.structure[o]?.$encryption);this._tenantEncryptionActive.set(n,d)}this._protocolInitializedCache.set(n,!0)}get encryptionRequired(){return Object.values(this._recordProtocolDefinition.types).some(e=>e.encryptionRequired===!0)}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:r,agent:n,useCache:i}){if(i){let d=this._cache.get(e);if(d)return d}let a=this.isEncryptionActive(r),{reply:s}=await n.dwn.processRequest({author:r,target:r,messageType:Re.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 Dm.consumeToJson({readableStream:s.entry.data});return i&&this._cache.set(e,o),o}async installProtocol(e,r){let n=this._recordProtocolDefinition,i=!1;if(this.encryptionRequired){let s=await r.dwn.getEncryptionKeyDeriver(e);n=await md.deriveAndInjectPublicEncryptionKeys(n,s),i=!0}this._tenantEncryptionActive.set(e,i);let{reply:{status:a}}=await r.dwn.processRequest({author:e,target:e,messageType:Re.ProtocolsConfigure,messageParams:{definition:n}});if(a.code!==202)throw new Error(`Failed to install protocol: ${a.code} - ${a.detail}`)}async lookupRecordId({id:e,tenantDid:r,agent:n}){let i=this._index.get(`${r}${ki}${e}`,{updateAgeOnGet:!0});return i||(await this.getAllRecords({agent:n,tenantDid:r}),i=this._index.get(`${r}${ki}${e}`)),i}async getExistingRecordEntry({id:e,tenantDid:r,agent:n}){let i=await this.lookupRecordId({id:e,tenantDid:r,agent:n});if(i){let{reply:a}=await n.dwn.processRequest({author:r,target:r,messageType:Re.RecordsRead,messageParams:{filter:{recordId:i}}});return a.entry}}},Bf=class{constructor(){this.name="InMemoryDataStore";this.store=new Map}async delete({id:e,agent:r,tenant:n}){let i=await Dd({agent:r,tenant:n,didUri:e});return this.store.has(`${i}${ki}${e}`)?(this.store.delete(`${i}${ki}${e}`),!0):!1}async get({id:e,agent:r,tenant:n}){let i=await Dd({agent:r,tenant:n,didUri:e});return this.store.get(`${i}${ki}${e}`)}async list({agent:e,tenant:r}){let n=await Dd({tenant:r,agent:e}),i=[];for(let[a,s]of this.store.entries())a.startsWith(`${n}${ki}`)&&i.push(s);return i}async set({id:e,data:r,tenant:n,agent:i,preventDuplicates:a,updateExisting:s}){let o=await Dd({agent:i,tenant:n,didUri:e});if(s){if(!this.store.has(`${o}${ki}${e}`))throw new Error(`${this.name}: Update failed due to missing entry for: ${e}`)}else if(a&&this.store.has(`${o}${ki}${e}`))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${e}`);let d=structuredClone(r);this.store.set(`${o}${ki}${e}`,d)}};var cg=class extends $f{constructor(){super(...arguments);this.name="DwnDidStore";this._recordProtocolDefinition=NE;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"portableDid",schema:this._recordProtocolDefinition.types.portableDid.schema}}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async list(r){return await super.list(r)}async set(r){return await super.set(r)}async getAllRecords({agent:r,tenantDid:n}){this._index.clear();let{reply:i}=await r.dwn.processRequest({author:n,target:n,messageType:Re.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=he.base64Url(s.encodedData).toObject();if(bh(o)){let d=`${n}${ki}${o.uri}`;this._index.set(d,s.recordId),this._cache.set(s.recordId,o),a.push(o)}}return a}},dg=class extends Bf{constructor(){super(...arguments);this.name="InMemoryDidStore"}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async list(r){return await super.list(r)}async set(r){return await super.set(r)}};var uye=(r=>(r.Create="Create",r.Resolve="Resolve",r))(uye||{});function OG(t,e){return t.messageType===e}var _h=class extends Zy{constructor({agent:r,didMethods:n,resolverCache:i,store:a}){if(!n)throw new TypeError("AgentDidApi: Required parameter missing: 'didMethods'");super({didResolvers:n,cache:i??new Cf({agent:r,location:"DATA/AGENT/DID_CACHE"})});this._didMethods=new Map;this._agent=r,this._store=a??new dg;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(r){this._agent=r,"agent"in this.cache&&(this.cache.agent=r)}async create({method:r,tenant:n,options:i,store:a}){let o=await this.getMethod(r).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:d,document:l,metadata:c}=o,u={uri:d,document:l,metadata:c};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:r,tenant:n}){let i=await this.get({didUri:r,tenant:n});if(!i)throw new Error(`AgentDidApi: Failed to export due to DID not found: ${r}`);return await i.export()}async get({didUri:r,tenant:n}){let i=await this._store.get({id:r,agent:this.agent,tenant:n,useCache:!0});return i?await bs.import({portableDid:i,keyManager:this.agent.keyManager}):void 0}async getSigningMethod({didUri:r,methodId:n}){let i=Fn.parse(r);if(!i)throw new Error(`Invalid DID URI: ${r}`);let a=this.getMethod(i.method),{didDocument:s,didResolutionMetadata:o}=await this.resolve(r);if(!s)throw new Error(`DID resolution failed for '${r}': ${JSON.stringify(o)}`);return await a.getSigningMethod({didDocument:s,methodId:n})}async update({tenant:r,portableDid:n,publish:i=!0}){let a=await this.get({didUri:n.uri,tenant:r??n.uri});if(!a)throw new Error(`AgentDidApi: Could not update, DID not found: ${n.uri}`);if(Hw(n.document)===Hw(a.document))throw new Error("AgentDidApi: No changes detected, update aborted");let s=await bs.import({keyManager:this.agent.keyManager,portableDid:n}),{uri:o,document:d,metadata:l}=s,c={uri:o,document:d,metadata:l};if(await this.cache.set(o,{didDocument:d,didResolutionMetadata:{},didDocumentMetadata:l}),await this._store.set({id:o,data:c,agent:this.agent,tenant:r??o,updateExisting:!0,useCache:!0}),i){let u=Fn.parse(o);u&&u.method==="dht"&&await po.publish({did:s})}return s}async import({portableDid:r,tenant:n}){let i=await bs.import({keyManager:this.agent.keyManager,portableDid:r}),{uri:a,document:s,metadata:o}=i,d={uri:a,document:s,metadata:o};return await this.cache.set(a,{didDocument:s,didResolutionMetadata:{},didDocumentMetadata:o}),await this._store.set({id:d.uri,data:d,agent:this.agent,tenant:n??d.uri,preventDuplicates:!0,useCache:!0}),i}async delete({didUri:r,tenant:n,deleteKey:i=!0}){let a=await this._store.get({id:r,agent:this.agent,tenant:n,useCache:!1});if(!a)throw new Error("AgentDidApi: Could not delete, DID not found");await this.cache.delete(r),await this._store.delete({id:r,agent:this.agent,tenant:n}),i&&await this.deleteKeys({portableDid:a})}async deleteKeys({portableDid:r}){for(let n of r.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(r){if(OG(r,"Create"))try{let n=await this.create({...r.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(OG(r,"Resolve")){let{didUri:n,options:i}=r.messageParams;return{result:await this.resolve(n,i),ok:!0,status:{code:200,message:"OK"}}}throw new Error(`AgentDidApi: Unsupported request type: ${r.messageType}`)}getMethod(r){let n=this._didMethods.get(r);if(n===void 0)throw new Error(`DID Method not supported: ${r}`);return n}};g();Er();Yn();wn();Jo();g();g();var fye="@enbox/dwn-server";function zE(t){return t.endsWith("/")?t.slice(0,-1):t}var Th=class{constructor(e,r=1e4,n){this._rpcClient=e;this._cacheTtlMs=r;this._discoveryFile=n;this._cacheExpiry=0}async getEndpoint(){let e=Date.now();if(e<this._cacheExpiry)return this._cachedEndpoint;let r=await this._tryDiscoveryFile();if(r!==void 0)return this._setCacheEntry(r,e),r;this._setCacheEntry(void 0,e)}async setCachedEndpoint(e){let r=zE(e),n=await this._validateEndpoint(r);return n&&this._setCacheEntry(r,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===fye}catch{return!1}}_setCacheEntry(e,r){this._cachedEndpoint=e,this._cacheExpiry=r+this._cacheTtlMs}};function pye(){try{let t=sS,e=t("node:fs/promises"),r=t("node:path"),n=t("node:os");return{async readFile(i){try{return await e.readFile(i,"utf-8")}catch{return null}},async writeFile(i,a){await e.mkdir(r.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 hye=".enbox",mye="dwn.json",FE=class{constructor(e,r){let n=e??pye();if(!n)throw new Error("DwnDiscoveryFile: No filesystem adapter available. Provide a DiscoveryFileFs implementation or run in Node.js / Bun.");if(this._fs=n,r)this._filePath=r;else{let a=sS("node:path");this._filePath=a.join(n.homedir(),hye,mye)}}get path(){return this._filePath}async read(){let e=await this._fs.readFile(this._filePath);if(e===null)return;let r;try{r=JSON.parse(e)}catch{await this._fs.removeFile(this._filePath);return}if(!yye(r)){await this._fs.removeFile(this._filePath);return}if(!this._fs.isProcessAlive(r.pid)){await this._fs.removeFile(this._filePath);return}let n={endpoint:zE(r.endpoint),pid:r.pid};return r.capabilities!==void 0&&(n.capabilities=r.capabilities),n}async write(e){let r={endpoint:zE(e.endpoint),pid:e.pid};e.capabilities!==void 0&&e.capabilities.length>0&&(r.capabilities=e.capabilities);let n=JSON.stringify(r,null,2);await this._fs.writeFile(this._filePath,n)}async remove(){await this._fs.removeFile(this._filePath)}};function yye(t){if(typeof t!="object"||t===null)return!1;let e=t;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(r=>typeof r=="string")))}g();Yn();function Rd(t,e){return t.messageType===e}function gye(t,e){return e.descriptor.interface+e.descriptor.method===t}function v5(t){return t===Re.RecordsDelete||t===Re.RecordsQuery||t===Re.RecordsRead||t===Re.RecordsSubscribe||t===Re.RecordsWrite}function b5(t){return t.interface===be.Records}function wye(t){return t.interface===be.Messages}g();wn();Yn();function GE(t){return t===ii.XC20P?24:12}function Ih(t,e,r,n,i){return{initializationVector:e,key:t,keyEncryptionInputs:[{publicKeyId:r,publicKey:n,derivationScheme:i}]}}async function HE(t,e,r,n=ii.A256GCM){let{ciphertextStream:i,tag:a}=await Bi.aeadEncryptStream(n,e,r,Yt.fromBytes(t)),s=await Yt.toBytes(i),o=Yt.fromBytes(s),d=await hr.computeDagPbCidFromStream(o);return{encryptedBytes:s,dataCid:d,dataSize:s.length,authenticationTag:a}}async function zl(t,e){let{didDocument:r,didResolutionMetadata:n}=await t.did.resolve(e);if(!r)throw new Error(`AgentDwnApi: Failed to resolve DID '${e}': ${JSON.stringify(n)}`);let i=r.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=r.verificationMethod?.find(c=>c.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!=="X25519")throw new Error(`AgentDwnApi: keyAgreement key for '${e}' uses curve '${o.crv}', but DWN encryption requires 'X25519'.`);let d=await t.keyManager.getKeyUri({key:o});return{keyId:s.id,keyUri:d,publicKeyJwk:o}}async function KG(t,e,r,n,i){let{keyId:a,keyUri:s}=await zl(t,e),o=Te.constructKeyDerivationPathUsingProtocolContextScheme(r),d=await t.keyManager.derivePublicKey({keyUri:s,derivationPath:o});return{encryptionInput:Ih(n,i,a,d,Ht.ProtocolContext),keyId:a,keyUri:s,contextDerivationPath:o}}function NG(t,e,r,n){let i=t.keyManager;return{rootKeyId:e,derivationScheme:n,decrypt:async(a,s)=>i.jweKeyUnwrap({keyUri:r,derivationPath:a,encryptedKey:s.encryptedKey,ephemeralPublicKey:s.ephemeralPublicKey})}}async function yb(t,e){let{keyId:r,keyUri:n}=await zl(t,e),i=t.keyManager;return{rootKeyId:r,derivationScheme:Ht.ProtocolPath,derivePublicKey:async a=>i.derivePublicKey({keyUri:n,derivationPath:a})}}async function gb(t,e){let{keyId:r,keyUri:n}=await zl(t,e);return NG(t,r,n,Ht.ProtocolPath)}function jG(t){return{rootKeyId:t.rootKeyId,derivationScheme:t.derivationScheme,decrypt:async(e,r)=>{let n=await Te.derivePrivateKey(t,e),i=await Gt.bytesToPrivateKey({privateKeyBytes:n});return Bi.ecdhEsUnwrapKey(i,r.ephemeralPublicKey,r.encryptedKey)}}}async function MG(t,e,r,n,i,a){let{encryption:s}=r;if(!s?.recipients.some(y=>y.header.derivationScheme===Ht.ProtocolContext)||!r.contextId)return gb(t,e);let d=s.recipients.find(y=>y.header.derivationScheme===Ht.ProtocolContext),l=r.contextId.split("/")[0],{keyId:c,keyUri:u}=await zl(t,e);if(d.header.kid===c)return NG(t,c,u,Ht.ProtocolContext);let f=`ctx~${e}~${l}`,h=i.get(f);if(h)return jG(h);let p=r.descriptor.protocol,m=await a({ownerDid:e,requesterDid:e,sourceProtocol:p,sourceContextId:l});if(!m){let{Jws:y}=await Promise.resolve().then(()=>(Yn(),RG)),b=n??y.getSignerDid(r.authorization.signature.signatures[0]);m=await a({ownerDid:b,requesterDid:e,sourceProtocol:p,sourceContextId:l})}if(!m)throw new Error(`AgentDwnApi: Failed to decrypt record '${r.recordId}'. Record uses context-derived encryption but no contextKey record could be found via the key-delivery protocol.`);return i.set(f,m),jG(m)}async function UG(t,e,r,n,i){if(!(!("encryption"in t)||!t.encryption)){if(Rd(t,Re.RecordsRead)){let a=e;if(a.status.code===200&&a.entry?.recordsWrite?.encryption&&a.entry?.data){let s=await MG(r,t.author,a.entry.recordsWrite,t.target,n,i);try{a.entry.data=await Te.decrypt(a.entry.recordsWrite,s,a.entry.data)}catch(o){throw new Error(`AgentDwnApi: Failed to decrypt record '${a.entry.recordsWrite.recordId}'. Original error: ${o.message}`)}}}if(Rd(t,Re.RecordsQuery)){let a=e;if(a.status.code===200&&a.entries){for(let s of a.entries)if(s.encryption&&s.encodedData){let o=await MG(r,t.author,s,t.target,n,i);try{let d=De.base64UrlToBytes(s.encodedData),l=Yt.fromBytes(d),c=await Te.decrypt(s,o,l),u=await Yt.toBytes(c);s.encodedData=De.bytesToBase64Url(u)}catch(d){throw new Error(`AgentDwnApi: Failed to decrypt record '${s.recordId}'. Original error: ${d.message}`)}}}}}}g();function LG(t,e){let r=e.split("/"),n=t.structure;for(let i of r)if(n=n[i],!n)return;return n}function hHe(t){return t.split("/")[0]||t}function x5(t,e){let r=LG(t,e);if(!r)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(r)?!0:P5(void 0,e,t)}function P5(t,e,r){let n=r.structure;function i(a){if(a.$actions){for(let s of a.$actions)if(s.who&&s.who!=="anyone"&&(t===void 0||s.who===t)&&s.of===e&&s.can?.includes("read"))return!0}for(let s in a)if(!s.startsWith("$")&&i(a[s]))return!0;return!1}return i(n)}function E5({protocolDefinition:t,protocolPath:e,recipient:r,tenantDid:n,authorDid:i}){let a=new Set,s=LG(t,e);return s&&(s.$role===!0&&r&&a.add(r),r&&r!==n&&P5("recipient",e,t)&&a.add(r),i&&i!==n&&P5("author",e,t)&&a.add(i),a.delete(n)),a}g();Yn();async function qG(t,e,r,n,i,a){if(i.get(e))return;let s=ql.protocol;if(!await n(e,s)){let d=await yb(t,e),l=await md.deriveAndInjectPublicEncryptionKeys(ql,d),{reply:{status:c}}=await r({author:e,target:e,messageType:Re.ProtocolsConfigure,messageParams:{definition:l}});if(c.code!==202)throw new Error(`AgentDwnApi: Failed to install key delivery protocol: ${c.code} - ${c.detail}`);a.delete(`${e}~${s}`)}i.set(e,!0)}async function zG(t,e,r,n,i){let{tenantDid:a,recipientDid:s,contextKeyData:o,sourceProtocol:d,sourceContextId:l,recipientKeyDeliveryPublicKey:c}=e;await n(a);let u=ql.protocol,f=new TextEncoder().encode(JSON.stringify(o)),h={protocol:u,protocolPath:"contextKey",dataFormat:"application/json",recipient:s,tags:{protocol:d,contextId:l}},p,m;if(c){let y=ii.A256GCM,b=crypto.getRandomValues(new Uint8Array(32)),w=crypto.getRandomValues(new Uint8Array(GE(y))),{encryptedBytes:S,dataCid:k,dataSize:T,authenticationTag:D}=await HE(f,b,w,y),K={...Ih(b,w,c.rootKeyId,c.publicKeyJwk,Ht.ProtocolPath),authenticationTag:D};({message:p,reply:{status:m}}=await r({author:a,target:a,messageType:Re.RecordsWrite,messageParams:{...h,dataCid:k,dataSize:T,encryptionInput:K},dataStream:new Blob([S])}))}else({message:p,reply:{status:m}}=await r({author:a,target:a,messageType:Re.RecordsWrite,messageParams:h,dataStream:new Blob([f],{type:"application/json"}),encryption:!0}));if(!(p&&m.code===202))throw new Error(`AgentDwnApi: Failed to write contextKey record for ${s}: ${m.code} - ${m.detail}`);return i(a,p).catch(y=>{console.warn(`AgentDwnApi: Eager send of contextKey record '${p.recordId}' to remote DWN failed: ${y.message}. Sync will deliver it later.`)}),p.recordId}async function FG(t,e,r,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:Re.RecordsWrite,messageCid:await we.getCid(r)});await i({targetDid:e,dwnEndpointUrls:s,message:r,data:o})}async function GG(t,e,r,n,i,a){let{ownerDid:s,requesterDid:o,sourceProtocol:d,sourceContextId:l}=e,c=ql.protocol,u=s===o,f={protocol:c,protocolPath:"contextKey",recipient:o,tags:{protocol:d,contextId:l}},h=p=>JSON.parse(new TextDecoder().decode(p));if(u){let{reply:p}=await r({author:o,target:s,messageType:Re.RecordsQuery,messageParams:{filter:f}});if(p.status.code!==200||!p.entries?.length)return;let m=p.entries[0].recordId,{reply:y}=await r({author:o,target:s,messageType:Re.RecordsRead,messageParams:{filter:{recordId:m}},encryption:!0}),b=y;return b.entry?.data?h(await Yt.toBytes(b.entry.data)):void 0}else{let p=await n(o),m=await a(s),y=await Id[Re.RecordsQuery].create({signer:p,filter:f}),b=await i({targetDid:s,dwnEndpointUrls:m,message:y.message});if(b.status.code!==200||!b.entries?.length)return;let w=b.entries[0].recordId,S=await Id[Re.RecordsRead].create({signer:p,filter:{recordId:w}}),k=await i({targetDid:s,dwnEndpointUrls:m,message:S.message});if(!k.entry?.data||!k.entry?.recordsWrite)return;let T=await gb(t,o),D=await Te.decrypt(k.entry.recordsWrite,T,k.entry.data);return h(await Yt.toBytes(D))}}g();Yn();async function HG(t,e,r,n,i){let a=`${t}~${e}`,s=i.get(a);if(s)return s;let o=await n(t),d=await Id[Re.ProtocolsQuery].create({filter:{protocol:e},signer:o}),l=await r.processMessage(t,d.message);if(l.status.code!==200||!l.entries?.length)return;let c=l.entries[0].descriptor.definition;return i.set(a,c),c}async function VG(t,e,r,n,i){let a=`remote~${t}~${e}`,s=i.get(a);if(s)return s;let o=await Id[Re.ProtocolsQuery].create({filter:{protocol:e}}),d=await n({targetDid:t,dwnEndpointUrls:await r(t),message:o.message});if(d.status.code!==200||!d.entries?.length)throw new Error(`AgentDwnApi: Failed to fetch protocol '${e}' from '${t}'. The recipient may not have the protocol installed.`);let l=d.entries[0].descriptor.definition;return i.set(a,l),l}async function WG(t,e,r,n,i,a,s){let o=await a(n),d=await Id[Re.RecordsQuery].create({signer:o,filter:{protocol:e,contextId:r}}),l=await i(t),c=await s({targetDid:t,dwnEndpointUrls:l,message:d.message});if(!(c.status.code!==200||!c.entries?.length)){for(let u of c.entries)if(u.encryption?.recipients){let f=u.encryption.recipients.find(h=>h.header.derivationScheme===Ht.ProtocolContext&&h.header.derivedPublicKey);if(f?.header.derivedPublicKey)return{rootKeyId:f.header.kid,derivedPublicKey:f.header.derivedPublicKey}}}}var Fl=class t{constructor(e){this._protocolDefinitionCache=new cs.default({ttl:30*60*1e3});this._contextKeyCache=new cs.default({ttl:30*60*1e3});this._contextDerivedKeyCache=new cs.default({ttl:30*60*1e3});this._localManagedDidCache=new cs.default({ttl:30*60*1e3});this._keyDeliveryProtocolInstalledCache=new cs.default({ttl:21*24*60*60*1e3,max:1e3});let{agent:r,localDwnStrategy:n="prefer"}=e;this._agent=r,this._dwn="dwn"in e?e.dwn:void 0,this._localDwnEndpoint="localDwnEndpoint"in e?e.localDwnEndpoint:void 0,this._localDwnStrategy=n,r&&(this._localDwnDiscovery=new Th(r.rpc,1e4,t._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 Th(e.rpc,1e4,t._tryCreateDiscoveryFile()),this._localManagedDidCache.clear()}get localDwnStrategy(){return this._localDwnStrategy}setLocalDwnStrategy(e){this._localDwnStrategy=e}async setCachedLocalDwnEndpoint(e){return this._localDwnDiscovery??=new Th(this.agent.rpc,1e4,t._tryCreateDiscoveryFile()),this._localDwnDiscovery.setCachedEndpoint(e)}async getDwnEndpointUrlsForTarget(e){if(!await this.shouldUseLocalDwnForTarget(e))return pb(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 pb(e,this.agent.did)}catch(s){if(!n)throw s}return n?[...new Set([n,...i])]:i}async getLocalDwnEndpoint(){return this._localDwnEndpoint?this._localDwnEndpoint:(this._localDwnDiscovery??=new Th(this.agent.rpc,1e4,t._tryCreateDiscoveryFile()),this._localDwnDiscovery.getEndpoint())}static _tryCreateDiscoveryFile(){try{return new FE}catch{return}}async shouldUseLocalDwnForTarget(e){if(this._localDwnStrategy==="off")return!1;let r=this._localManagedDidCache.get(e);if(r!==void 0)return r;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:r,didResolver:n,stateIndex:i,eventLog:a,messageStore:s,tenantGate:o,resumableTaskStore:d}){return r??=new _f({blockstoreLocation:`${e}/DWN_DATASTORE`}),n??=new Zy({didResolvers:[po,ho],cache:new cE({location:`${e}/DID_RESOLVERCACHE`})}),i??=new Rf({location:`${e}/DWN_STATEINDEX`}),s??=new Tf({blockstoreLocation:`${e}/DWN_MESSAGESTORE`,indexLocation:`${e}/DWN_MESSAGEINDEX`}),d??=new If({location:`${e}/DWN_RESUMABLETASKSTORE`}),a??=new Df,await Yy.create({dataStore:r,didResolver:n,stateIndex:i,eventLog:a,messageStore:s,tenantGate:o,resumableTaskStore:d})}async processRequest(e){let{message:r,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,r,{dataStream:n,subscriptionHandler:i});else{let s;if(n){let o=await Yt.toBytes(n);s=new Blob([o])}a=await this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:[this._localDwnEndpoint],message:r,data:s,subscriptionHandler:i})}return await this.postWriteKeyDelivery(e,r,a),await this.maybeDecryptReply(e,a),{reply:a,message:r,messageCid:await we.getCid(r)}}async processRawMessage(e,r,n){if(this._dwn)return this._dwn.processMessage(e,r,{dataStream:n?.dataStream});let i;if(n?.dataStream){let a=await Yt.toBytes(n.dataStream);i=new Blob([a])}return this.sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:[this._localDwnEndpoint],message:r,data:i})}async sendRequest(e){let r=await this.getDwnEndpointUrlsForTarget(e.target);if(r.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 c=l!==void 0?{...e.messageParams,cursor:l}:e.messageParams,u={...e,messageParams:c},{message:f}=await this.constructDwnMessage({request:u});return f});let d=await this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:r,message:i,data:a,subscriptionHandler:s,resubscribeFactory:o});return await this.maybeDecryptReply(e,d),n??=await we.getCid(i),{reply:d,message:i,messageCid:n}}async postWriteKeyDelivery(e,r,n){if(!Rd(e,Re.RecordsWrite)||!e.encryption||n.status.code!==202)return;let i=e.messageParams;if(i.protocol!==ql.protocol)try{let a=await this.getProtocolDefinition(e.target,i.protocol);if(!a)return;let s=r,o=ut.getSignerDid(s.authorization.signature.signatures[0]),d=o!==e.target,l=!i.parentContextId,c=i.protocolPath.split("/")[0],u=x5(a,c),f=E5({protocolDefinition:a,protocolPath:i.protocolPath,recipient:i.recipient,tenantDid:e.target,authorDid:d?o:void 0});if(f.size>0){let h=s.contextId?.split("/")[0]||s.contextId||s.recordId,{keyId:p,keyUri:m}=await zl(this.agent,e.target),y=[Ht.ProtocolContext,h],b=await this.agent.keyManager.derivePrivateKeyBytes({keyUri:m,derivationPath:y}),w=await Gt.bytesToPrivateKey({privateKeyBytes:b}),S={rootKeyId:p,derivationScheme:Ht.ProtocolContext,derivationPath:y,derivedPrivateKey:w},k=s.authorization?.authorKeyDeliveryPublicKey;for(let T of f)try{let D=T===o&&k?k:void 0;await this.writeContextKeyRecord({tenantDid:e.target,recipientDid:T,contextKeyData:S,sourceProtocol:i.protocol,sourceContextId:h,recipientKeyDeliveryPublicKey:D})}catch(D){console.warn(`AgentDwnApi: Key delivery to '${T}' for context '${h}' failed: ${D.message}. The participant may not be able to decrypt records in this context.`)}}}catch(a){console.warn(`AgentDwnApi: Post-write participant detection failed: ${a.message}`)}}async sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:r,message:n,data:i,subscriptionHandler:a,resubscribeFactory:s}){let o=[];if(n.descriptor.method===ge.Subscribe&&a===void 0)throw new Error("AgentDwnApi: Subscription handler is required for subscription requests.");for(let d of r)try{if(a!==void 0){if(!(await this.agent.rpc.getServerInfo(d)).webSocketSupport){o.push({url:d,message:"WebSocket support is not enabled on the server."});continue}let u=new URL(d);u.protocol=u.protocol==="http:"?"ws:":"wss:",d=u.toString()}return await this.agent.rpc.sendDwnRequest({dwnUrl:d,targetDid:e,message:n,data:i,subscription:a?{handler:a,resubscribeFactory:s}:void 0})}catch(l){o.push({url:d,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 r=e.rawMessage,n;if(Rd(e,Re.RecordsWrite)){let o=e.messageParams;if(e.dataStream&&!o?.data){let{dataStream:d}=e,l;if(d instanceof Blob){let[c,u]=d.stream().tee();l=c,n=u}else if(d instanceof ReadableStream){let[c,u]=d.tee();l=c,n=u}!r&&o&&(o.dataCid=await hr.computeDagPbCidFromStream(l),o.dataSize===void 0&&d instanceof Blob&&(o.dataSize=d.size))}}if(Rd(e,Re.ProtocolsConfigure)&&e.encryption&&!r){let o=e.messageParams,d=await yb(this.agent,e.author);o.definition=await md.deriveAndInjectPublicEncryptionKeys(o.definition,d),this._protocolDefinitionCache.delete(`${e.target}~${o.definition.protocol}`)}let i;if(Rd(e,Re.RecordsWrite)&&e.encryption&&!r){let o=e.messageParams;if(o?.protocol&&o.protocolPath){let d=e.target!==e.author,l;if(d?l=await this.fetchRemoteProtocolDefinition(e.target,o.protocol):l=await this.getProtocolDefinition(e.target,o.protocol),!l)throw new Error(`AgentDwnApi: Protocol '${o.protocol}' is not installed for '${e.target}'. Install the protocol before writing encrypted records.`);let c=o.protocolPath.split("/"),u=l.structure;for(let z of c)u=u[z];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],p=o.protocol===ql.protocol?!1:x5(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 Yt.toBytes(e.dataStream);else throw new Error("AgentDwnApi: Data must be provided for encrypted records.");let b=ii.A256GCM,w=crypto.getRandomValues(new Uint8Array(32)),S=crypto.getRandomValues(new Uint8Array(GE(b))),k,T=()=>Ih(w,S,u.$encryption.rootKeyId,u.$encryption.publicKeyJwk,Ht.ProtocolPath);if(d&&p&&m)k=T();else if(d&&p&&!m){let z=o.parentContextId.split("/")[0]||o.parentContextId,N=await this.extractDerivedPublicKey(e.target,o.protocol,z,e.author);N?k=Ih(w,S,N.rootKeyId,N.derivedPublicKey,Ht.ProtocolContext):k=T()}else if(d)k=T();else if(p&&!m){let z=o.parentContextId.split("/")[0]||o.parentContextId,N=this._contextKeyCache.get(z);if(!N){let{keyId:ee,keyUri:R}=await zl(this.agent,e.author),B=Te.constructKeyDerivationPathUsingProtocolContextScheme(z);N={keyId:ee,keyUri:R,contextDerivationPath:B},this._contextKeyCache.set(z,N)}let V=await this.agent.keyManager.derivePublicKey({keyUri:N.keyUri,derivationPath:N.contextDerivationPath});k=Ih(w,S,N.keyId,V,Ht.ProtocolContext)}else p&&m?k=void 0:k=T();let{encryptedBytes:D,dataCid:K,dataSize:C,authenticationTag:G}=await HE(y,w,S,b);if(o.dataCid=K,o.dataSize=C,delete o.data,n=Yt.fromBytes(D),e.dataStream=void 0,k?(k.authenticationTag=G,o.encryptionInput=k):i={dataEncryptionKey:w,dataEncryptionIV:S,encryptedBytes:D,authenticationTag:G},d&&p){let{keyId:z,keyUri:N}=await zl(this.agent,e.author),V=[Ht.ProtocolPath,ql.protocol,"contextKey"],ee=await this.agent.keyManager.derivePublicKey({keyUri:N,derivationPath:V});o.authorKeyDeliveryPublicKey={rootKeyId:z,publicKeyJwk:ee}}}}let a,s=Id[e.messageType];if(r){if(a=await s.parse(r),Ll(a)&&e.signAsOwner){let o=await this.getSigner(e.author);await a.signAsOwner(o)}else if(e.granteeDid&&Ll(a)&&e.signAsOwnerDelegate){let o=await this.getSigner(e.granteeDid),d=e.messageParams;await a.signAsOwnerDelegate(o,d.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);if(a=await s.create({...e.messageParams,signer:o}),i&&Rd(e,Re.RecordsWrite)){let d=a,l=d.message.recordId,{encryptionInput:c,keyId:u,keyUri:f,contextDerivationPath:h}=await KG(this.agent,e.author,l,i.dataEncryptionKey,i.dataEncryptionIV),p={...c,authenticationTag:i.authenticationTag};await d.encryptSymmetricEncryptionKey(p),await d.sign({signer:o}),this._contextKeyCache.set(l,{keyId:u,keyUri:f,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 r=await this.agent.agentDid.getSigner();return{algorithm:r.algorithm,keyId:r.keyId,sign:async n=>await r.sign({data:n})}}else try{let r=await this.agent.did.get({didUri:e});if(r){let o=await r.getSigner();return{algorithm:o.algorithm,keyId:o.keyId,sign:async d=>await o.sign({data:d})}}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:gn.getJoseSignatureAlgorithmFromPublicKey(a),keyId:n.id,sign:async o=>await s.sign({data:o,keyUri:i})}}catch(r){throw new Error(`AgentDwnApi: Unable to get signer for author '${e}': ${r.message}`)}}async getEncryptionKeyDeriver(e){return yb(this.agent,e)}async getEncryptionKeyInfo(e){return zl(this.agent,e)}async getKeyDecrypter(e){return gb(this.agent,e)}detectNewParticipants(e){return E5(e)}async getProtocolDefinition(e,r){if(!this._dwn)try{return await this.fetchRemoteProtocolDefinition(e,r)}catch{return}return HG(e,r,this._dwn,this.getSigner.bind(this),this._protocolDefinitionCache)}async fetchRemoteProtocolDefinition(e,r){return VG(e,r,this.getDwnEndpointUrlsForTarget.bind(this),this.sendDwnRpcRequest.bind(this),this._protocolDefinitionCache)}async extractDerivedPublicKey(e,r,n,i){return WG(e,r,n,i,this.getDwnEndpointUrlsForTarget.bind(this),this.getSigner.bind(this),this.sendDwnRpcRequest.bind(this))}async maybeDecryptReply(e,r){return UG(e,r,this.agent,this._contextDerivedKeyCache,this.fetchContextKeyRecord.bind(this))}async getDwnMessage({author:e,messageCid:r}){let n=await this.getSigner(e),i=await Id[Re.MessagesRead].create({messageCid:r,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,d={message:s.message};if(Ll(s)){let l=s.data;if(l){let c=await Yt.toBytes(l);d.data=new Blob([c],{type:s.message.descriptor.dataFormat})}}return d}async ensureKeyDeliveryProtocol(e){return qG(this.agent,e,this.processRequest.bind(this),this.getProtocolDefinition.bind(this),this._keyDeliveryProtocolInstalledCache,this._protocolDefinitionCache)}async writeContextKeyRecord(e){return zG(this.agent,e,this.processRequest.bind(this),this.ensureKeyDeliveryProtocol.bind(this),this.eagerSendContextKeyRecord.bind(this))}async eagerSendContextKeyRecord(e,r){return FG(this.agent,e,r,this.getDwnMessage.bind(this),this.sendDwnRpcRequest.bind(this),this.getDwnEndpointUrlsForTarget.bind(this))}async fetchContextKeyRecord(e){return GG(this.agent,e,this.processRequest.bind(this),this.getSigner.bind(this),this.sendDwnRpcRequest.bind(this),this.getDwnEndpointUrlsForTarget.bind(this))}};g();var ZG="dwn",YG="connect";function FHe(t){return`${ZG}://${YG}?callback=${encodeURIComponent(t)}`}function vye(t){let e=JSON.stringify(t);return xye(e)}function JG(t){try{let e=Eye(t),r=JSON.parse(e);return bye(r)?r:void 0}catch{return}}function GHe(t){try{let e=`${ZG}://`;if(!t.startsWith(e))return;let r=t.slice(e.length),n=r.indexOf("?");if(n===-1||r.slice(0,n)!==YG)return;let a=r.slice(n+1),o=new URLSearchParams(a).get("callback");return!o||o.length===0?void 0:{callback:o}}catch{return}}function HHe(t,e){let r=vye(e);return`${t.split("#")[0]}#${r}`}function VHe(t){let e=t.indexOf("#");if(e===-1)return JG(t);let r=t.slice(e+1);if(r.length!==0)return JG(r)}function bye(t){if(typeof t!="object"||t===null)return!1;let e=t;return!(typeof e.endpoint!="string"||e.endpoint.length===0||!Pye(e.endpoint))}function Pye(t){try{let r=new URL(t).hostname.toLowerCase();return!!(r==="127.0.0.1"||r==="::1"||r==="[::1]"||r==="localhost"||r.endsWith(".localhost"))}catch{return!1}}function xye(t){let e=new TextEncoder().encode(t),r="";for(let n=0;n<e.length;n++)r+=String.fromCharCode(e[n]);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Eye(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4;r===2?e+="==":r===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();aP();Gb();g();Yb();za();var Sye=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),QG=Uint8Array.from({length:16},(t,e)=>e),Aye=QG.map(t=>(9*t+5)%16),A5=[QG],k5=[Aye];for(let t=0;t<4;t++)for(let e of[A5,k5])e.push(e[t].map(r=>Sye[r]));var eH=[[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(t=>new Uint8Array(t)),kye=A5.map((t,e)=>t.map(r=>eH[e][r])),_ye=k5.map((t,e)=>t.map(r=>eH[e][r])),Tye=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Iye=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),VE=(t,e)=>t<<e|t>>>32-e;function XG(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}var WE=new Uint32Array(16),S5=class extends eu{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:r,h2:n,h3:i,h4:a}=this;return[e,r,n,i,a]}set(e,r,n,i,a){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=a|0}process(e,r){for(let h=0;h<16;h++,r+=4)WE[h]=e.getUint32(r,!0);let n=this.h0|0,i=n,a=this.h1|0,s=a,o=this.h2|0,d=o,l=this.h3|0,c=l,u=this.h4|0,f=u;for(let h=0;h<5;h++){let p=4-h,m=Tye[h],y=Iye[h],b=A5[h],w=k5[h],S=kye[h],k=_ye[h];for(let T=0;T<16;T++){let D=VE(n+XG(h,a,o,l)+WE[b[T]]+m,S[T])+u|0;n=u,u=l,l=VE(o,10)|0,o=a,a=D}for(let T=0;T<16;T++){let D=VE(i+XG(p,s,d,c)+WE[w[T]]+y,k[T])+f|0;i=f,f=c,c=VE(d,10)|0,d=s,s=D}}this.set(this.h1+o+c|0,this.h2+l+f|0,this.h3+u+i|0,this.h4+n+s|0,this.h0+a+d|0)}roundClean(){WE.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}},tH=Xh(()=>new S5);Gg();iP();za();Zh();var Dye=qg("ed25519 seed"),_5=2147483648,rH=new Uint8Array([0]);function nH(t,...e){return typeof t=="string"&&(t=m8(t)),Md(t,...e),t}var Rye=t=>tH(nu(t)),Cye=t=>Nd(t).getUint32(0,!1),T5=t=>{if(!Number.isSafeInteger(t)||t<0||t>2**32-1)throw new Error(`Invalid number=${t}. Should be from 0 to 2 ** 32 - 1`);let e=new Uint8Array(4);return Nd(e).setUint32(0,t,!1),e},JE=class t{get publicKeyRaw(){return da.getPublicKey(this.privateKey)}get publicKey(){return Gf(rH,this.publicKeyRaw)}get pubHash(){return Rye(this.publicKey)}get fingerprint(){return Cye(this.pubHash)}get fingerprintHex(){return OS(T5(this.fingerprint))}get parentFingerprintHex(){return OS(T5(this.parentFingerprint))}static fromMasterSeed(e){if(e=nH(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 r=Xl(ku,Dye,e);return new t({privateKey:r.slice(0,32),chainCode:r.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(Md(e.privateKey,32),Md(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,r=!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>=_5)throw new Error("Invalid index");(r||s[2]==="'")&&(o+=_5),i=i.deriveChild(o)}return i}deriveChild(e){if(e<_5)throw new Error(`Non-hardened child derivation not possible for Ed25519 (index=${e})`);let r=Gf(rH,this.privateKey,T5(e)),n=Xl(ku,this.chainCode,r);return new t({chainCode:n.slice(32),depth:this.depth+1,parentFingerprint:this.fingerprint,index:e,privateKey:n.slice(0,32)})}sign(e){return da.sign(e,this.privateKey)}verify(e,r){return r=nH(r,64),da.verify(r,e,this.publicKeyRaw)}};g();var I5=`abandon
10
+ deps: ${r}}`};var $oe={keyword:"dependencies",type:"object",schemaType:"object",error:hd.error,code(t){let[e,r]=Boe(t);rL(t,e),nL(t,r)}};function Boe({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let i=Array.isArray(t[n])?e:r;i[n]=t[n]}return[e,r]}function rL(t,e=t.schema){let{gen:r,data:n,it:i}=t;if(Object.keys(e).length===0)return;let a=r.let("missing");for(let s in e){let o=e[s];if(o.length===0)continue;let d=(0,dv.propertyInData)(r,n,s,i.opts.ownProperties);t.setParams({property:s,depsCount:o.length,deps:o.join(", ")}),i.allErrors?r.if(d,()=>{for(let l of o)(0,dv.checkReportMissingProp)(t,l)}):(r.if((0,WD._)`${d} && (${(0,dv.checkMissingProp)(t,o,a)})`),(0,dv.reportMissingProp)(t,a),r.else())}}hd.validatePropertyDeps=rL;function nL(t,e=t.schema){let{gen:r,data:n,keyword:i,it:a}=t,s=r.name("valid");for(let o in e)(0,Coe.alwaysValidSchema)(a,e[o])||(r.if((0,dv.propertyInData)(r,n,o,a.opts.ownProperties),()=>{let d=t.subschema({keyword:i,schemaProp:o},s);t.mergeValidEvaluated(d,s)},()=>r.var(s,!0)),t.ok(s))}hd.validateSchemaDeps=nL;hd.default=$oe});var sL=_e(JD=>{"use strict";g();Object.defineProperty(JD,"__esModule",{value:!0});var iL=Bt(),Ooe=Zt(),joe={message:"property name must be valid",params:({params:t})=>(0,iL._)`{propertyName: ${t.propertyName}}`},Moe={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:joe,code(t){let{gen:e,schema:r,data:n,it:i}=t;if((0,Ooe.alwaysValidSchema)(i,r))return;let a=e.name("valid");e.forIn("key",n,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},a),e.if((0,iL.not)(a),()=>{t.error(!0),i.allErrors||e.break()})}),t.ok(a)}};JD.default=Moe});var YD=_e(ZD=>{"use strict";g();Object.defineProperty(ZD,"__esModule",{value:!0});var Lx=wa(),vc=Bt(),Koe=ga(),qx=Zt(),Noe={message:"must NOT have additional properties",params:({params:t})=>(0,vc._)`{additionalProperty: ${t.additionalProperty}}`},Uoe={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Noe,code(t){let{gen:e,schema:r,parentSchema:n,data:i,errsCount:a,it:s}=t;if(!a)throw new Error("ajv implementation error");let{allErrors:o,opts:d}=s;if(s.props=!0,d.removeAdditional!=="all"&&(0,qx.alwaysValidSchema)(s,r))return;let l=(0,Lx.allSchemaProperties)(n.properties),c=(0,Lx.allSchemaProperties)(n.patternProperties);u(),t.ok((0,vc._)`${a} === ${Koe.default.errors}`);function u(){e.forIn("key",i,y=>{!l.length&&!c.length?p(y):e.if(f(y),()=>p(y))})}function f(y){let b;if(l.length>8){let w=(0,qx.schemaRefOrVal)(s,n.properties,"properties");b=(0,Lx.isOwnProperty)(e,w,y)}else l.length?b=(0,vc.or)(...l.map(w=>(0,vc._)`${y} === ${w}`)):b=vc.nil;return c.length&&(b=(0,vc.or)(b,...c.map(w=>(0,vc._)`${(0,Lx.usePattern)(t,w)}.test(${y})`))),(0,vc.not)(b)}function h(y){e.code((0,vc._)`delete ${i}[${y}]`)}function p(y){if(d.removeAdditional==="all"||d.removeAdditional&&r===!1){h(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),o||e.break();return}if(typeof r=="object"&&!(0,qx.alwaysValidSchema)(s,r)){let b=e.name("valid");d.removeAdditional==="failing"?(m(y,b,!1),e.if((0,vc.not)(b),()=>{t.reset(),h(y)})):(m(y,b),o||e.if((0,vc.not)(b),()=>e.break()))}}function m(y,b,w){let S={keyword:"additionalProperties",dataProp:y,dataPropType:qx.Type.Str};w===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(S,b)}}};ZD.default=Uoe});var cL=_e(QD=>{"use strict";g();Object.defineProperty(QD,"__esModule",{value:!0});var Loe=W0(),oL=wa(),XD=Zt(),aL=YD(),qoe={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:a}=t;a.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&aL.default.code(new Loe.KeywordCxt(a,aL.default,"additionalProperties"));let s=(0,oL.allSchemaProperties)(r);for(let u of s)a.definedProperties.add(u);a.opts.unevaluated&&s.length&&a.props!==!0&&(a.props=XD.mergeEvaluated.props(e,(0,XD.toHash)(s),a.props));let o=s.filter(u=>!(0,XD.alwaysValidSchema)(a,r[u]));if(o.length===0)return;let d=e.name("valid");for(let u of o)l(u)?c(u):(e.if((0,oL.propertyInData)(e,i,u,a.opts.ownProperties)),c(u),a.allErrors||e.else().var(d,!0),e.endIf()),t.it.definedProperties.add(u),t.ok(d);function l(u){return a.opts.useDefaults&&!a.compositeRule&&r[u].default!==void 0}function c(u){t.subschema({keyword:"properties",schemaProp:u,dataProp:u},d)}}};QD.default=qoe});var fL=_e(eR=>{"use strict";g();Object.defineProperty(eR,"__esModule",{value:!0});var dL=wa(),zx=Bt(),lL=Zt(),uL=Zt(),zoe={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:i,it:a}=t,{opts:s}=a,o=(0,dL.allSchemaProperties)(r),d=o.filter(m=>(0,lL.alwaysValidSchema)(a,r[m]));if(o.length===0||d.length===o.length&&(!a.opts.unevaluated||a.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&i.properties,c=e.name("valid");a.props!==!0&&!(a.props instanceof zx.Name)&&(a.props=(0,uL.evaluatedPropsToName)(e,a.props));let{props:u}=a;f();function f(){for(let m of o)l&&h(m),a.allErrors?p(m):(e.var(c,!0),p(m),e.if(c))}function h(m){for(let y in l)new RegExp(m).test(y)&&(0,lL.checkStrictMode)(a,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function p(m){e.forIn("key",n,y=>{e.if((0,zx._)`${(0,dL.usePattern)(t,m)}.test(${y})`,()=>{let b=d.includes(m);b||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:uL.Type.Str},c),a.opts.unevaluated&&u!==!0?e.assign((0,zx._)`${u}[${y}]`,!0):!b&&!a.allErrors&&e.if((0,zx.not)(c),()=>e.break())})})}}};eR.default=zoe});var pL=_e(tR=>{"use strict";g();Object.defineProperty(tR,"__esModule",{value:!0});var Foe=Zt(),Goe={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Foe.alwaysValidSchema)(n,r)){t.fail();return}let i=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),t.failResult(i,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};tR.default=Goe});var hL=_e(rR=>{"use strict";g();Object.defineProperty(rR,"__esModule",{value:!0});var Hoe=wa(),Voe={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Hoe.validateUnion,error:{message:"must match a schema in anyOf"}};rR.default=Voe});var mL=_e(nR=>{"use strict";g();Object.defineProperty(nR,"__esModule",{value:!0});var Fx=Bt(),Woe=Zt(),Joe={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Fx._)`{passingSchemas: ${t.passing}}`},Zoe={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Joe,code(t){let{gen:e,schema:r,parentSchema:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let a=r,s=e.let("valid",!1),o=e.let("passing",null),d=e.name("_valid");t.setParams({passing:o}),e.block(l),t.result(s,()=>t.reset(),()=>t.error(!0));function l(){a.forEach((c,u)=>{let f;(0,Woe.alwaysValidSchema)(i,c)?e.var(d,!0):f=t.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},d),u>0&&e.if((0,Fx._)`${d} && ${s}`).assign(s,!1).assign(o,(0,Fx._)`[${o}, ${u}]`).else(),e.if(d,()=>{e.assign(s,!0),e.assign(o,u),f&&t.mergeEvaluated(f,Fx.Name)})})}}};nR.default=Zoe});var yL=_e(iR=>{"use strict";g();Object.defineProperty(iR,"__esModule",{value:!0});var Yoe=Zt(),Xoe={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=e.name("valid");r.forEach((a,s)=>{if((0,Yoe.alwaysValidSchema)(n,a))return;let o=t.subschema({keyword:"allOf",schemaProp:s},i);t.ok(i),t.mergeEvaluated(o)})}};iR.default=Xoe});var vL=_e(sR=>{"use strict";g();Object.defineProperty(sR,"__esModule",{value:!0});var Gx=Bt(),wL=Zt(),Qoe={message:({params:t})=>(0,Gx.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Gx._)`{failingKeyword: ${t.ifClause}}`},eae={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Qoe,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,wL.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(d(),t.reset(),i&&a){let c=e.let("ifClause");t.setParams({ifClause:c}),e.if(o,l("then",c),l("else",c))}else i?e.if(o,l("then")):e.if((0,Gx.not)(o),l("else"));t.pass(s,()=>t.error(!0));function d(){let c=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},o);t.mergeEvaluated(c)}function l(c,u){return()=>{let f=t.subschema({keyword:c},o);e.assign(s,o),t.mergeValidEvaluated(f,s),u?e.assign(u,(0,Gx._)`${c}`):t.setParams({ifClause:c})}}}};function gL(t,e){let r=t.schema[e];return r!==void 0&&!(0,wL.alwaysValidSchema)(t,r)}sR.default=eae});var bL=_e(oR=>{"use strict";g();Object.defineProperty(oR,"__esModule",{value:!0});var tae=Zt(),rae={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,tae.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};oR.default=rae});var PL=_e(aR=>{"use strict";g();Object.defineProperty(aR,"__esModule",{value:!0});var nae=zD(),iae=XU(),sae=FD(),oae=eL(),aae=tL(),cae=Ux(),dae=sL(),lae=YD(),uae=cL(),fae=fL(),pae=pL(),hae=hL(),mae=mL(),yae=yL(),gae=vL(),wae=bL();function vae(t=!1){let e=[pae.default,hae.default,mae.default,yae.default,gae.default,wae.default,dae.default,lae.default,cae.default,uae.default,fae.default];return t?e.push(iae.default,oae.default):e.push(nae.default,sae.default),e.push(aae.default),e}aR.default=vae});var dR=_e(lv=>{"use strict";g();Object.defineProperty(lv,"__esModule",{value:!0});lv.dynamicAnchor=void 0;var cR=Bt(),bae=ga(),xL=Z0(),Pae=Bx(),xae={keyword:"$dynamicAnchor",schemaType:"string",code:t=>EL(t,t.schema)};function EL(t,e){let{gen:r,it:n}=t;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,cR._)`${bae.default.dynamicAnchors}${(0,cR.getProperty)(e)}`,a=n.errSchemaPath==="#"?n.validateName:Eae(t);r.if((0,cR._)`!${i}`,()=>r.assign(i,a))}lv.dynamicAnchor=EL;function Eae(t){let{schemaEnv:e,schema:r,self:n}=t.it,{root:i,baseId:a,localRefs:s,meta:o}=e.root,{schemaId:d}=n.opts,l=new xL.SchemaEnv({schema:r,schemaId:d,root:i,baseId:a,localRefs:s,meta:o});return xL.compileSchema.call(n,l),(0,Pae.getValidate)(t,l)}lv.default=xae});var lR=_e(uv=>{"use strict";g();Object.defineProperty(uv,"__esModule",{value:!0});uv.dynamicRef=void 0;var SL=Bt(),Sae=ga(),AL=Bx(),Aae={keyword:"$dynamicRef",schemaType:"string",code:t=>kL(t,t.schema)};function kL(t,e){let{gen:r,keyword:n,it:i}=t;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let a=e.slice(1);if(i.allErrors)s();else{let d=r.let("valid",!1);s(d),t.ok(d)}function s(d){if(i.schemaEnv.root.dynamicAnchors[a]){let l=r.let("_v",(0,SL._)`${Sae.default.dynamicAnchors}${(0,SL.getProperty)(a)}`);r.if(l,o(l,d),o(i.validateName,d))}else o(i.validateName,d)()}function o(d,l){return l?()=>r.block(()=>{(0,AL.callRef)(t,d),r.let(l,!0)}):()=>(0,AL.callRef)(t,d)}}uv.dynamicRef=kL;uv.default=Aae});var _L=_e(uR=>{"use strict";g();Object.defineProperty(uR,"__esModule",{value:!0});var kae=dR(),_ae=Zt(),Tae={keyword:"$recursiveAnchor",schemaType:"boolean",code(t){t.schema?(0,kae.dynamicAnchor)(t,""):(0,_ae.checkStrictMode)(t.it,"$recursiveAnchor: false is ignored")}};uR.default=Tae});var TL=_e(fR=>{"use strict";g();Object.defineProperty(fR,"__esModule",{value:!0});var Iae=lR(),Dae={keyword:"$recursiveRef",schemaType:"string",code:t=>(0,Iae.dynamicRef)(t,t.schema)};fR.default=Dae});var IL=_e(pR=>{"use strict";g();Object.defineProperty(pR,"__esModule",{value:!0});var Rae=dR(),Cae=lR(),$ae=_L(),Bae=TL(),Oae=[Rae.default,Cae.default,$ae.default,Bae.default];pR.default=Oae});var RL=_e(hR=>{"use strict";g();Object.defineProperty(hR,"__esModule",{value:!0});var DL=Ux(),jae={keyword:"dependentRequired",type:"object",schemaType:"object",error:DL.error,code:t=>(0,DL.validatePropertyDeps)(t)};hR.default=jae});var CL=_e(mR=>{"use strict";g();Object.defineProperty(mR,"__esModule",{value:!0});var Mae=Ux(),Kae={keyword:"dependentSchemas",type:"object",schemaType:"object",code:t=>(0,Mae.validateSchemaDeps)(t)};mR.default=Kae});var $L=_e(yR=>{"use strict";g();Object.defineProperty(yR,"__esModule",{value:!0});var Nae=Zt(),Uae={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:t,parentSchema:e,it:r}){e.contains===void 0&&(0,Nae.checkStrictMode)(r,`"${t}" without "contains" is ignored`)}};yR.default=Uae});var BL=_e(gR=>{"use strict";g();Object.defineProperty(gR,"__esModule",{value:!0});var Lae=RL(),qae=CL(),zae=$L(),Fae=[Lae.default,qae.default,zae.default];gR.default=Fae});var jL=_e(wR=>{"use strict";g();Object.defineProperty(wR,"__esModule",{value:!0});var Qu=Bt(),OL=Zt(),Gae=ga(),Hae={message:"must NOT have unevaluated properties",params:({params:t})=>(0,Qu._)`{unevaluatedProperty: ${t.unevaluatedProperty}}`},Vae={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Hae,code(t){let{gen:e,schema:r,data:n,errsCount:i,it:a}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:s,props:o}=a;o instanceof Qu.Name?e.if((0,Qu._)`${o} !== true`,()=>e.forIn("key",n,u=>e.if(l(o,u),()=>d(u)))):o!==!0&&e.forIn("key",n,u=>o===void 0?d(u):e.if(c(o,u),()=>d(u))),a.props=!0,t.ok((0,Qu._)`${i} === ${Gae.default.errors}`);function d(u){if(r===!1){t.setParams({unevaluatedProperty:u}),t.error(),s||e.break();return}if(!(0,OL.alwaysValidSchema)(a,r)){let f=e.name("valid");t.subschema({keyword:"unevaluatedProperties",dataProp:u,dataPropType:OL.Type.Str},f),s||e.if((0,Qu.not)(f),()=>e.break())}}function l(u,f){return(0,Qu._)`!${u} || !${u}[${f}]`}function c(u,f){let h=[];for(let p in u)u[p]===!0&&h.push((0,Qu._)`${f} !== ${p}`);return(0,Qu.and)(...h)}}};wR.default=Vae});var KL=_e(vR=>{"use strict";g();Object.defineProperty(vR,"__esModule",{value:!0});var Zp=Bt(),ML=Zt(),Wae={message:({params:{len:t}})=>(0,Zp.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Zp._)`{limit: ${t}}`},Jae={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Wae,code(t){let{gen:e,schema:r,data:n,it:i}=t,a=i.items||0;if(a===!0)return;let s=e.const("len",(0,Zp._)`${n}.length`);if(r===!1)t.setParams({len:a}),t.fail((0,Zp._)`${s} > ${a}`);else if(typeof r=="object"&&!(0,ML.alwaysValidSchema)(i,r)){let d=e.var("valid",(0,Zp._)`${s} <= ${a}`);e.if((0,Zp.not)(d),()=>o(d,a)),t.ok(d)}i.items=!0;function o(d,l){e.forRange("i",l,s,c=>{t.subschema({keyword:"unevaluatedItems",dataProp:c,dataPropType:ML.Type.Num},d),i.allErrors||e.if((0,Zp.not)(d),()=>e.break())})}}};vR.default=Jae});var NL=_e(bR=>{"use strict";g();Object.defineProperty(bR,"__esModule",{value:!0});var Zae=jL(),Yae=KL(),Xae=[Zae.default,Yae.default];bR.default=Xae});var UL=_e(PR=>{"use strict";g();Object.defineProperty(PR,"__esModule",{value:!0});var Un=Bt(),Qae={message:({schemaCode:t})=>(0,Un.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Un._)`{format: ${t}}`},ece={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Qae,code(t,e){let{gen:r,data:n,$data:i,schema:a,schemaCode:s,it:o}=t,{opts:d,errSchemaPath:l,schemaEnv:c,self:u}=o;if(!d.validateFormats)return;i?f():h();function f(){let p=r.scopeValue("formats",{ref:u.formats,code:d.code.formats}),m=r.const("fDef",(0,Un._)`${p}[${s}]`),y=r.let("fType"),b=r.let("format");r.if((0,Un._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,Un._)`${m}.type || "string"`).assign(b,(0,Un._)`${m}.validate`),()=>r.assign(y,(0,Un._)`"string"`).assign(b,m)),t.fail$data((0,Un.or)(w(),S()));function w(){return d.strictSchema===!1?Un.nil:(0,Un._)`${s} && !${b}`}function S(){let k=c.$async?(0,Un._)`(${m}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,Un._)`${b}(${n})`,T=(0,Un._)`(typeof ${b} == "function" ? ${k} : ${b}.test(${n}))`;return(0,Un._)`${b} && ${b} !== true && ${y} === ${e} && !${T}`}}function h(){let p=u.formats[a];if(!p){w();return}if(p===!0)return;let[m,y,b]=S(p);m===e&&t.pass(k());function w(){if(d.strictSchema===!1){u.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${a}" ignored in schema at path "${l}"`}}function S(T){let D=T instanceof RegExp?(0,Un.regexpCode)(T):d.code.formats?(0,Un._)`${d.code.formats}${(0,Un.getProperty)(a)}`:void 0,K=r.scopeValue("formats",{key:a,ref:T,code:D});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,Un._)`${K}.validate`]:["string",T,K]}function k(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!c.$async)throw new Error("async format in sync schema");return(0,Un._)`await ${b}(${n})`}return typeof y=="function"?(0,Un._)`${b}(${n})`:(0,Un._)`${b}.test(${n})`}}}};PR.default=ece});var LL=_e(xR=>{"use strict";g();Object.defineProperty(xR,"__esModule",{value:!0});var tce=UL(),rce=[tce.default];xR.default=rce});var qL=_e(Ey=>{"use strict";g();Object.defineProperty(Ey,"__esModule",{value:!0});Ey.contentVocabulary=Ey.metadataVocabulary=void 0;Ey.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ey.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var FL=_e(ER=>{"use strict";g();Object.defineProperty(ER,"__esModule",{value:!0});var nce=jU(),ice=WU(),sce=PL(),oce=IL(),ace=BL(),cce=NL(),dce=LL(),zL=qL(),lce=[oce.default,nce.default,ice.default,(0,sce.default)(!0),dce.default,zL.metadataVocabulary,zL.contentVocabulary,ace.default,cce.default];ER.default=lce});var HL=_e(Hx=>{"use strict";g();Object.defineProperty(Hx,"__esModule",{value:!0});Hx.DiscrError=void 0;var GL;(function(t){t.Tag="tag",t.Mapping="mapping"})(GL||(Hx.DiscrError=GL={}))});var WL=_e(AR=>{"use strict";g();Object.defineProperty(AR,"__esModule",{value:!0});var Sy=Bt(),SR=HL(),VL=Z0(),uce=J0(),fce=Zt(),pce={message:({params:{discrError:t,tagName:e}})=>t===SR.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Sy._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},hce={keyword:"discriminator",type:"object",schemaType:"object",error:pce,code(t){let{gen:e,data:r,schema:n,parentSchema:i,it:a}=t,{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 d=e.let("valid",!1),l=e.const("tag",(0,Sy._)`${r}${(0,Sy.getProperty)(o)}`);e.if((0,Sy._)`typeof ${l} == "string"`,()=>c(),()=>t.error(!1,{discrError:SR.DiscrError.Tag,tag:l,tagName:o})),t.ok(d);function c(){let h=f();e.if(!1);for(let p in h)e.elseIf((0,Sy._)`${l} === ${p}`),e.assign(d,u(h[p]));e.else(),t.error(!1,{discrError:SR.DiscrError.Mapping,tag:l,tagName:o}),e.endIf()}function u(h){let p=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:h},p);return t.mergeEvaluated(m,Sy.Name),p}function f(){var h;let p={},m=b(i),y=!0;for(let k=0;k<s.length;k++){let T=s[k];if(T?.$ref&&!(0,fce.schemaHasRulesButRef)(T,a.self.RULES)){let K=T.$ref;if(T=VL.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,K),T instanceof VL.SchemaEnv&&(T=T.schema),T===void 0)throw new uce.default(a.opts.uriResolver,a.baseId,K)}let D=(h=T?.properties)===null||h===void 0?void 0:h[o];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${o}"`);y=y&&(m||b(T)),w(D,k)}if(!y)throw new Error(`discriminator: "${o}" must be required`);return p;function b({required:k}){return Array.isArray(k)&&k.includes(o)}function w(k,T){if(k.const)S(k.const,T);else if(k.enum)for(let D of k.enum)S(D,T);else throw new Error(`discriminator: "properties/${o}" must have "const" or "enum"`)}function S(k,T){if(typeof k!="string"||k in p)throw new Error(`discriminator: "${o}" values must be unique strings`);p[k]=T}}}};AR.default=hce});var JL=_e((iOe,mce)=>{mce.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 ZL=_e((sOe,yce)=>{yce.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 YL=_e((oOe,gce)=>{gce.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 XL=_e((aOe,wce)=>{wce.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 QL=_e((cOe,vce)=>{vce.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 e9=_e((dOe,bce)=>{bce.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 t9=_e((lOe,Pce)=>{Pce.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 r9=_e((uOe,xce)=>{xce.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 n9=_e(kR=>{"use strict";g();Object.defineProperty(kR,"__esModule",{value:!0});var Ece=JL(),Sce=ZL(),Ace=YL(),kce=XL(),_ce=QL(),Tce=e9(),Ice=t9(),Dce=r9(),Rce=["/properties"];function Cce(t){return[Ece,Sce,Ace,kce,_ce,e(this,Tce),Ice,e(this,Dce)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function e(r,n){return t?r.$dataMetaSchema(n,Rce):n}}kR.default=Cce});var IR=_e((an,TR)=>{"use strict";g();Object.defineProperty(an,"__esModule",{value:!0});an.MissingRefError=an.ValidationError=an.CodeGen=an.Name=an.nil=an.stringify=an.str=an._=an.KeywordCxt=an.Ajv2020=void 0;var $ce=RU(),Bce=FL(),Oce=WL(),jce=n9(),_R="https://json-schema.org/draft/2020-12/schema",Ay=class extends $ce.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Bce.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Oce.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:r}=this.opts;r&&(jce.default.call(this,e),this.refs["http://json-schema.org/schema"]=_R)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_R)?_R:void 0)}};an.Ajv2020=Ay;TR.exports=an=Ay;TR.exports.Ajv2020=Ay;Object.defineProperty(an,"__esModule",{value:!0});an.default=Ay;var Mce=W0();Object.defineProperty(an,"KeywordCxt",{enumerable:!0,get:function(){return Mce.KeywordCxt}});var ky=Bt();Object.defineProperty(an,"_",{enumerable:!0,get:function(){return ky._}});Object.defineProperty(an,"str",{enumerable:!0,get:function(){return ky.str}});Object.defineProperty(an,"stringify",{enumerable:!0,get:function(){return ky.stringify}});Object.defineProperty(an,"nil",{enumerable:!0,get:function(){return ky.nil}});Object.defineProperty(an,"Name",{enumerable:!0,get:function(){return ky.Name}});Object.defineProperty(an,"CodeGen",{enumerable:!0,get:function(){return ky.CodeGen}});var Kce=Ax();Object.defineProperty(an,"ValidationError",{enumerable:!0,get:function(){return Kce.default}});var Nce=J0();Object.defineProperty(an,"MissingRefError",{enumerable:!0,get:function(){return Nce.default}})});var ef,Vx=F(()=>{"use strict";g();wP();xt();ef=class t{static async authorizeConfigure(e){let{protocolsConfigureMessage:r,expectedGrantor:n,expectedGrantee:i,permissionGrant:a,messageStore:s}=e;await $o.performBaseValidation({incomingMessage:r,expectedGrantor:n,expectedGrantee:i,permissionGrant:a,messageStore:s}),t.verifyScope(r,a.scope)}static async authorizeQuery(e){let{expectedGrantee:r,expectedGrantor:n,incomingMessage:i,permissionGrant:a,messageStore:s}=e;await $o.performBaseValidation({incomingMessage:i,expectedGrantor:n,expectedGrantee:r,permissionGrant:a,messageStore:s});let d=a.scope.protocol,l=i.descriptor.filter?.protocol;if(d!==void 0&&l!==d)throw new ie(ne.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch,`Grant protocol scope ${d} does not match protocol in message ${l}`)}static verifyScope(e,r){if(r.protocol!==void 0&&r.protocol!==e.descriptor.definition.protocol)throw new ie(ne.ProtocolsGrantAuthorizationScopeProtocolMismatch,"Grant scope specifies different protocol than what appears in the configure message.")}}});function zs(t){let e=t.indexOf(":");if(e===-1)return;let r=t.substring(0,e),n=t.substring(e+1);return{alias:r,protocolPath:n}}function tf(t){return t.includes(":")}function Wx(t){return t.split("/").slice(-1)[0]}function yd(t,e){let r=t.split("/"),n,i=e;for(let a of r){if(!Object.hasOwn(i,a))return;n=i[a],i=n}return n}var md,Yp=F(()=>{"use strict";g();wn();jm();md=class{static async deriveAndInjectPublicEncryptionKeys(e,r,n){let i=JSON.parse(JSON.stringify(e));if(typeof r!="string"){let l=r,c=[Ht.ProtocolPath,e.protocol];async function u(f,h){for(let p in f)if(!p.startsWith("$")){let m=[...h,p],y=f[p];if(y.$ref!==void 0){await u(y,m);continue}let b=await l.derivePublicKey(m);y.$encryption={rootKeyId:l.rootKeyId,publicKeyJwk:b},await u(y,m)}}return await u(i.structure,c),i}let a=r;async function s(l,c){for(let u in l)if(!u.startsWith("$")){let f=await $s.derivePrivateKey(c,[u]),h=l[u];if(h.$ref!==void 0){await s(h,f);continue}let p=await Gt.getPublicKey({key:f.derivedPrivateKey});h.$encryption={rootKeyId:a,publicKeyJwk:p},await s(h,f)}}let o={derivationScheme:Ht.ProtocolPath,derivedPrivateKey:n,rootKeyId:a},d=await $s.derivePrivateKey(o,[Ht.ProtocolPath,e.protocol]);return await s(i.structure,d),i}}});var i9,Pa,Jx=F(()=>{"use strict";g();mc();i9=An(IR(),1);wr();nc();Vx();us();xt();lr();Yp();ua();Tg();Pa=class t extends $n{static async parse(e){return we.validateJsonSchema(e),t.validateProtocolDefinition(e.descriptor.definition),await we.validateSignatureStructure(e.authorization.signature,e.descriptor),St.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:be.Protocols,method:ge.Configure,messageTimestamp:e.messageTimestamp??St.getCurrentTimestamp(),definition:t.normalizeDefinition(e.definition),...e.permissionGrantId!==void 0&&{permissionGrantId:e.permissionGrantId}},n=await we.createAuthorization({descriptor:r,signer:e.signer,delegatedGrant:e.delegatedGrant,permissionGrantId:e.permissionGrantId}),i={descriptor:r,authorization:n};return we.validateJsonSchema(i),t.validateProtocolDefinition(i.descriptor.definition),new t(i)}async authorizeAuthorDelegate(e){let r=Ir.parse(this.message.authorization.authorDelegatedGrant);await ef.authorizeConfigure({protocolsConfigureMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}static validateProtocolDefinition(e){let{protocol:r,types:n,uses:i}=e;si(r);for(let a in n){let s=n[a].schema;s!==void 0&&Wc(s)}i!==void 0&&t.validateUses(i,r),t.validateStructure(e)}static validateUses(e,r){let n=/^[a-zA-Z][a-zA-Z0-9_-]*$/;for(let i in e){if(!n.test(i))throw new ie(ne.ProtocolsConfigureInvalidUsesAlias,`invalid 'uses' alias '${i}': must match pattern ${n.toString()}.`);try{si(e[i])}catch{throw new ie(ne.ProtocolsConfigureInvalidUsesProtocolUrl,`invalid 'uses' protocol URL for alias '${i}': '${e[i]}' is not a valid normalized protocol URL.`)}if(e[i]===r)throw new ie(ne.ProtocolsConfigureInvalidUsesSelfReference,`'uses' alias '${i}' references the protocol's own URI '${r}'. a protocol cannot compose itself.`)}}static validateStructure(e){let{uses:r}=e,n=Object.keys(e.types),i=t.fetchAllRolePathsRecursively("",e.structure,[]);t.validateRuleSetRecursively({ruleSet:e.structure,ruleSetProtocolPath:"",recordTypes:n,roles:i,uses:r,types:e.types})}static fetchAllRolePathsRecursively(e,r,n){if(e.split("/").length>10)throw new ie(ne.ProtocolsConfigureRecordNestingDepthExceeded,"Record nesting depth exceeded 10 levels.");for(let i in r){if(i.startsWith("$"))continue;let a=r[i],s;e===""?s=i:s=`${e}/${i}`,a.$role?n.push(s):t.fetchAllRolePathsRecursively(s,a,n)}return n}static validateRuleSetRecursively(e){let{ruleSet:r,ruleSetProtocolPath:n,recordTypes:i,roles:a,uses:s,types:o}=e;if(r.$ref!==void 0){if(n.includes("/"))throw new ie(ne.ProtocolsConfigureInvalidRefNotAtRoot,`'$ref' at protocol path '${n}' is not allowed: '$ref' nodes are only supported at the root level of the structure.`);t.validateRefNode(r,n,s)}if(r.$size!==void 0){let{min:l=0,max:c}=r.$size;if(c!==void 0&&c<l)throw new ie(ne.ProtocolsConfigureInvalidSize,`Invalid size range found: max limit ${c} less than min limit ${l} at protocol path '${n}'`)}if(r.$recordLimit!==void 0){let{max:l,strategy:c}=r.$recordLimit;if(!Number.isInteger(l)||l<1)throw new ie(ne.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.max value ${l} at protocol path '${n}': must be an integer >= 1.`);let u=Object.values(Hl);if(!u.includes(c))throw new ie(ne.ProtocolsConfigureInvalidRecordLimit,`Invalid $recordLimit.strategy '${c}' at protocol path '${n}': must be one of ${u.join(", ")}.`)}if(r.$tags){let l=new i9.default.default,{$allowUndefinedTags:c,$requiredTags:u,...f}=r.$tags;for(let h in f){let p=f[h];if(!l.validateSchema(p)){let m=l.errorsText(l.errors,{dataVar:`${n}/$tags/${h}`});throw new ie(ne.ProtocolsConfigureInvalidTagSchema,`tags schema validation error: ${m}`)}}}let d=r.$actions??[];for(let l=0;l<d.length;l++){let c=d[l];if(c.role!==void 0){if(tf(c.role))t.validateCrossProtocolAlias(c.role,s,n,"role");else if(!a.includes(c.role))throw new ie(ne.ProtocolsConfigureRoleDoesNotExistAtGivenPath,`Role in action ${JSON.stringify(c)} for rule set ${n} does not exist.`)}if(c.who==="anyone"&&c.of)throw new ie(ne.ProtocolsConfigureInvalidActionOfNotAllowed,`'of' is not allowed at rule set protocol path (${n})`);if(c.who===kc.Recipient&&c.of===void 0&&c.can.some(f=>![Pr.CoUpdate,Pr.CoDelete,Pr.CoPrune].includes(f)))throw new ie(ne.ProtocolsConfigureInvalidRecipientOfAction,"Rules for `recipient` without `of` property must have `can` containing only `co-update`, `co-delete`, and `co-prune`.");if(c.who===kc.Author&&!c.of)throw new ie(ne.ProtocolsConfigureInvalidActionMissingOf,"'of' is required when 'author' is specified as 'who'");if(c.of!==void 0&&n!==""){if(tf(c.of))t.validateCrossProtocolAlias(c.of,s,n,"of");else if(!(n===c.of||n.startsWith(c.of+"/")))throw new ie(ne.ProtocolsConfigureInvalidActionOfNotAnAncestor,`'of' value '${c.of}' is not an ancestor of protocol path '${n}' in action rule ${JSON.stringify(c)}.`)}if(c.can!==void 0){if(c.can.includes(Pr.Update)&&!c.can.includes(Pr.Create))throw new ie(ne.ProtocolsConfigureInvalidActionUpdateWithoutCreate,`Action rule ${JSON.stringify(c)} contains 'update' action but missing the required 'create' action.`);if(c.can.includes(Pr.Delete)&&!c.can.includes(Pr.Create))throw new ie(ne.ProtocolsConfigureInvalidActionDeleteWithoutCreate,`Action rule ${JSON.stringify(c)} contains 'delete' action but missing the required 'create' action.`);if(c.can.includes(Pr.Prune)&&!c.can.includes(Pr.Create))throw new ie(ne.ProtocolsConfigureInvalidActionPruneWithoutCreate,`Action rule ${JSON.stringify(c)} contains 'prune' action but missing the required 'create' action.`)}for(let u=l+1;u<d.length;u++){let f=d[u];if(c.who!==void 0){if(c.who===f.who&&c.of===f.of)throw new ie(ne.ProtocolsConfigureDuplicateActorInRuleSet,`More than one action rule per actor ${c.who} of ${c.of} not allowed within a rule set: ${JSON.stringify(c)}`)}else if(c.role===f.role)throw new ie(ne.ProtocolsConfigureDuplicateRoleInRuleSet,`More than one action rule per role ${c.role} not allowed within a rule set: ${JSON.stringify(c)}`)}}if(n!==""){let l=n.split("/").pop();o[l]?.encryptionRequired===!0&&d.some(f=>f.who===kc.Anyone&&f.can.includes(Pr.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.`)}r.$delivery!==void 0&&(r.$actions===void 0||r.$actions.length===0)&&console.warn(`ProtocolsConfigure: protocol path '${n}' has $delivery: '${r.$delivery}' but no $actions rules. The server uses $actions to determine delivery targets \u2014 without $actions, no participants can be resolved for delivery.`),r.$immutable===!0&&d.length>0&&d.some(c=>c.can.includes(Pr.Update)||c.can.includes(Pr.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 r){if(l.startsWith("$"))continue;let c=r[l];if(c.$ref===void 0&&!i.includes(l))throw new ie(ne.ProtocolsConfigureInvalidRuleSetRecordType,`Rule set ${l} is not declared as an allowed type in the protocol definition.`);let u;n===""?u=l:u=`${n}/${l}`,t.validateRuleSetRecursively({ruleSet:c,ruleSetProtocolPath:u,recordTypes:i,roles:a,uses:s,types:o})}}static validateRefNode(e,r,n){let i=e.$ref,a=zs(i);if(a===void 0)throw new ie(ne.ProtocolsConfigureInvalidRefAlias,`'$ref' value '${i}' at protocol path '${r}' must be in 'alias:typePath' format.`);if(n===void 0||n[a.alias]===void 0)throw new ie(ne.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${a.alias}' at protocol path '${r}' 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 ie(ne.ProtocolsConfigureInvalidRefNodeHasDirectives,`'$ref' node at protocol path '${r}' must not have '${o}'. $ref nodes are pure attachment points \u2014 directives belong on child rule sets.`)}static validateCrossProtocolAlias(e,r,n,i){let a=zs(e);if(a===void 0){let s=i==="role"?ne.ProtocolsConfigureInvalidCrossProtocolRole:ne.ProtocolsConfigureInvalidCrossProtocolOf;throw new ie(s,`cross-protocol '${i}' reference '${e}' at protocol path '${n}' could not be parsed as a valid 'alias:path' format.`)}if(r===void 0||r[a.alias]===void 0){let s=i==="role"?ne.ProtocolsConfigureInvalidCrossProtocolRole:ne.ProtocolsConfigureInvalidCrossProtocolOf;throw new ie(s,`cross-protocol '${i}' alias '${a.alias}' in '${e}' at protocol path '${n}' does not exist in the 'uses' map.`)}}static normalizeDefinition(e){let r={};for(let i in e.types)r[i]={...e.types[i]};for(let i in r){let a=r[i].schema;a!==void 0&&(r[i].schema=xp(a))}let n;if(e.uses!==void 0){n={};for(let i in e.uses)try{n[i]=Bs(e.uses[i])}catch{n[i]=e.uses[i]}}return{...e,protocol:Bs(e.protocol),types:r,...n!==void 0&&{uses:n}}}}});var Zx,s9=F(()=>{"use strict";g();No();wr();Uo();Lo();Jx();Vx();xt();lr();Yp();Zx=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Pa.parse(r)}catch(c){return wt(c,400)}try{await pn(r.authorization,this.deps.didResolver),await t.authorizeProtocolsConfigure(e,n,this.deps.messageStore)}catch(c){return wt(c,401)}try{await t.validateCompositionDependencies(e,r.descriptor.definition,this.deps.messageStore)}catch(c){return wt(c,400)}let i={interface:be.Protocols,method:ge.Configure,protocol:r.descriptor.definition.protocol},{messages:a}=await this.deps.messageStore.query(e,[i]),s=await we.getCid(r);for(let c of a)if(await we.getCid(c)===s)return{status:{code:409,detail:"Conflict"}};let o=await we.getNewestMessage(a),d=!1;(o===void 0||await we.isNewer(r,o))&&(d=!0,o=r);let l;if(d){let c=t.constructIndexes(n,!0);await this.deps.messageStore.put(e,r,c);let u=await we.getCid(r);await this.deps.stateIndex.insert(e,u,c),this.deps.eventLog!==void 0&&await this.deps.eventLog.emit(e,{message:r},c),l={status:{code:202,detail:"Accepted"}}}else{let c=t.constructIndexes(n,!1);await this.deps.messageStore.put(e,r,c);let u=await we.getCid(r);await this.deps.stateIndex.insert(e,u,c),l={status:{code:202,detail:"Accepted"}}}for(let c of a)if(c!==o){let u=await Pa.parse(c),f=t.constructIndexes(u,!1),h=await we.getCid(c);await this.deps.messageStore.delete(e,h),await this.deps.messageStore.put(e,c,f)}return l}static constructIndexes(e,r){let{definition:n,...i}=e.message.descriptor,{author:a}=e;return{...i,author:a,protocol:n.protocol,published:n.published,isLatestBaseState:r}}static async authorizeProtocolsConfigure(e,r,n){if(r.isSignedByAuthorDelegate&&await r.authorizeAuthorDelegate(n),r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let i=await dt.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await ef.authorizeConfigure({protocolsConfigureMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:i,messageStore:n})}else throw new ie(ne.ProtocolsConfigureAuthorizationFailed,"message failed authorization")}static async validateCompositionDependencies(e,r,n){let{uses:i}=r;if(i===void 0)return;let a=new Map;for(let s in i){let o=i[s],d=await t.fetchInstalledProtocolDefinition(e,o,n);if(d===void 0)throw new ie(ne.ProtocolsConfigureComposedProtocolNotInstalled,`composed protocol '${o}' (alias '${s}') is not installed for tenant '${e}'.`);a.set(s,d)}t.validateRefsAndRolesRecursively(r.structure,"",a)}static async fetchInstalledProtocolDefinition(e,r,n){let i={interface:be.Protocols,method:ge.Configure,protocol:r,isLatestBaseState:!0},{messages:a}=await n.query(e,[i]);if(a.length!==0)return a[0].descriptor.definition}static validateRefsAndRolesRecursively(e,r,n){for(let i in e){if(i.startsWith("$"))continue;let a=e[i],s=r===""?i:`${r}/${i}`;if(a.$ref!==void 0){let d=zs(a.$ref);if(d!==void 0){let l=n.get(d.alias);if(l===void 0)throw new ie(ne.ProtocolsConfigureInvalidRefAlias,`'$ref' alias '${d.alias}' at protocol path '${s}' was not found in the referenced definitions map.`);let c=d.protocolPath.split("/"),u=l.structure;for(let f=0;f<c.length;f++){let h=c[f],p=u[h];if(p===void 0)throw new ie(ne.ProtocolsConfigureInvalidRefProtocolPath,`'$ref' at protocol path '${s}' references type path '${d.protocolPath}' which does not exist in protocol '${l.protocol}'.`);if(p.$ref!==void 0){let m=c.slice(0,f+1).join("/");throw new ie(ne.ProtocolsConfigureInvalidRefTargetThroughRef,`'$ref' at protocol path '${s}' references type path '${d.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=p}}}let o=a.$actions??[];for(let d of o){if(d.role!==void 0){let l=zs(d.role);if(l!==void 0){let c=n.get(l.alias);if(c===void 0)throw new ie(ne.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role alias '${l.alias}' in '${d.role}' at protocol path '${s}' was not found in the referenced definitions map.`);let u=yd(l.protocolPath,c.structure);if(u===void 0||!u.$role)throw new ie(ne.ProtocolsConfigureInvalidCrossProtocolRole,`cross-protocol role '${d.role}' at protocol path '${s}' does not point to a valid role ($role: true) in protocol '${c.protocol}'.`)}}if(d.of!==void 0){let l=zs(d.of);if(l!==void 0){let c=n.get(l.alias);if(c===void 0)throw new ie(ne.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' alias '${l.alias}' in '${d.of}' at protocol path '${s}' was not found in the referenced definitions map.`);if(yd(l.protocolPath,c.structure)===void 0)throw new ie(ne.ProtocolsConfigureInvalidCrossProtocolOf,`cross-protocol 'of' reference '${d.of}' at protocol path '${s}' does not point to a valid type path in protocol '${c.protocol}'.`)}}}t.validateRefsAndRolesRecursively(a,s,n)}}}});var xa,Yx=F(()=>{"use strict";g();mc();wr();Lo();Vx();Di();us();xt();lr();ua();xa=class t extends $n{static async parse(e){return e.authorization!==void 0&&await we.validateSignatureStructure(e.authorization.signature,e.descriptor),e.descriptor.filter!==void 0&&si(e.descriptor.filter.protocol),St.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:be.Protocols,method:ge.Query,messageTimestamp:e.messageTimestamp??St.getCurrentTimestamp(),filter:e.filter?t.normalizeFilter(e.filter):void 0,permissionGrantId:e.permissionGrantId};tr(r);let n;e.signer!==void 0&&(n=await we.createAuthorization({descriptor:r,signer:e.signer,permissionGrantId:e.permissionGrantId}));let i={descriptor:r,authorization:n};return we.validateJsonSchema(i),new t(i)}static normalizeFilter(e){return{...e,protocol:Bs(e.protocol)}}async authorize(e,r){if(this.author!==e)if(this.author!==void 0&&this.signaturePayload.permissionGrantId){let n=await dt.fetchGrant(e,r,this.signaturePayload.permissionGrantId);await ef.authorizeQuery({expectedGrantor:e,expectedGrantee:this.author,incomingMessage:this.message,permissionGrant:n,messageStore:r})}else throw new ie(ne.ProtocolsQueryUnauthorized,"The ProtocolsQuery failed authorization")}}});var Xx,o9=F(()=>{"use strict";g();No();xt();Uo();Yx();Di();lr();Xx=class{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await xa.parse(r)}catch(s){return wt(s,400)}try{await pn(r.authorization,this.deps.didResolver),await n.authorize(e,this.deps.messageStore)}catch(s){if(s.code===ne.AuthenticateJwsMissing||s.code===ne.ProtocolsQueryUnauthorized||s.code===ne.ProtocolsGrantAuthorizationQueryProtocolScopeMismatch){let o=await this.fetchPublishedProtocolsConfigure(e,n);return{status:{code:200,detail:"OK"},entries:o}}else return wt(s,401)}let i={...r.descriptor.filter,interface:be.Protocols,method:ge.Configure,isLatestBaseState:!0};tr(i);let{messages:a}=await this.deps.messageStore.query(e,[i]);return{status:{code:200,detail:"OK"},entries:a}}async fetchPublishedProtocolsConfigure(e,r){let n={...r.message.descriptor.filter,interface:be.Protocols,method:ge.Configure,published:!0,isLatestBaseState:!0},{messages:i}=await this.deps.messageStore.query(e,[n]);return i}}});async function fv(t,e,r,n,i,a,s,o){let d=e.signaturePayload?.protocolRole;if(d===void 0)return;let l=r,c=d;if(tf(d)){let p=zs(d);if(p===void 0)throw new ie(ne.ProtocolAuthorizationNotARole,`Cross-protocol role '${d}' could not be parsed as a valid 'alias:path' format.`);if(i.uses===void 0||i.uses[p.alias]===void 0)throw new ie(ne.ProtocolAuthorizationNotARole,`Cross-protocol role alias '${p.alias}' in '${d}' does not exist in the protocol's 'uses' map.`);l=i.uses[p.alias],c=p.protocolPath;let m=await s(t,l,a,o),y=yd(c,m.structure);if(y===void 0||!y.$role)throw new ie(ne.ProtocolAuthorizationNotARole,`Cross-protocol role path ${d} does not match role record type.`)}else{let p=yd(d,i.structure);if(p===void 0||!p.$role)throw new ie(ne.ProtocolAuthorizationNotARole,`Protocol path ${d} does not match role record type.`)}let u={interface:be.Records,method:ge.Write,protocol:l,protocolPath:c,recipient:e.author,isLatestBaseState:!0},f=c.split("/").length-1;if(n===void 0&&f>0)throw new ie(ne.ProtocolAuthorizationMissingContextId,"Could not verify role because contextId is missing.");if(f>0){let m=n.split("/").slice(0,f).join("/"),y=ir.constructPrefixFilterAsRangeFilter(m);u.contextId=y}let{messages:h}=await a.query(t,[u]);if(h.length===0)throw new ie(ne.ProtocolAuthorizationMatchingRoleRecordNotFound,`No matching role record found for protocol path ${c}`)}async function Uce(t,e,r){switch(e.message.descriptor.method){case ge.Delete:let n=e,i=n.message.descriptor.recordId,a=await At.fetchInitialRecordsWrite(r,t,i);if(a===void 0)return[];let s=[];return n.message.descriptor.prune?(s.push(Pr.CoPrune),e.author===a.author&&s.push(Pr.Prune)):(s.push(Pr.CoDelete),e.author===a.author&&s.push(Pr.Delete)),s;case ge.Count:return[Pr.Read];case ge.Query:return[Pr.Read];case ge.Read:return[Pr.Read];case ge.Subscribe:return[Pr.Read];case ge.Write:let d=e;if(await d.isInitialWrite())return d.message.descriptor.squash===!0?[Pr.Squash,Pr.Create]:[Pr.Create];{let l=e.message.recordId,c=await At.fetchInitialRecordsWrite(r,t,l);return c===void 0?[]:e.author===c.author?[Pr.CoUpdate,Pr.Update]:[Pr.CoUpdate]}}return[]}async function pv(t,e,r,n,i,a){let s=e.message.descriptor.method,o=await Uce(t,e,i),d=e.author,l=r.$actions;if(l===void 0)throw new ie(ne.ProtocolAuthorizationActionRulesNotFound,`no action rule defined for Records${s}, ${d} is unauthorized`);let c=e.signaturePayload?.protocolRole;for(let u of l){if(!u.can.some(p=>o.includes(p)))continue;if(u.who===kc.Anyone)return;if(d===void 0)continue;if(c!==void 0){if(u.role===c)return;continue}if(u.who===kc.Recipient&&u.of===void 0){let p;if(e.message.descriptor.method===ge.Write?p=e.message:p=n[n.length-1],p.descriptor.recipient===d)return;continue}if(await Lce(d,u,n,a))return}throw new ie(ne.ProtocolAuthorizationActionNotAllowed,`Inbound message action Records${s} by author ${e.author} not allowed.`)}async function Lce(t,e,r,n){let i=e.of;if(i===void 0)return!1;let a;if(tf(i)&&n?.uses!==void 0){let s=zs(i);if(s!==void 0){let o=n.uses[s.alias];o!==void 0&&(a=r.find(d=>d.descriptor.protocol===o&&d.descriptor.protocolPath===s.protocolPath))}}else a=r.find(s=>s.descriptor.protocolPath===i);if(a===void 0)return!1;if(e.who===kc.Recipient)return t===a.descriptor.recipient;{let s=(await At.parse(a)).author;return t===s}}var a9=F(()=>{"use strict";g();lc();Us();xt();lr();Yp();Tg()});async function _y(t,e,r){let n={interface:be.Records,method:ge.Write,recordId:e},{messages:i}=await r.query(t,[n]);return i.length===0?void 0:await At.getInitialWrite(i)}async function hv(t,e,r){if(e===void 0)return[];let n=[],i=e;for(;i!==void 0;){let a=await _y(t,i,r);if(a===void 0)throw new ie(ne.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 DR(t,e,r){let n=await _y(t,e.message.recordId,r);if(n!==void 0)return n.descriptor.messageTimestamp}var c9=F(()=>{"use strict";g();Us();xt();lr()});async function l9(t,e,r,n,i){let a=e.message.descriptor.protocolPath,s=Wx(a),o=e.message.descriptor.parentId;if(o===void 0){if(a!==s)throw new ie(ne.ProtocolAuthorizationParentlessIncorrectProtocolPath,`Declared protocol path '${a}' is not valid for records with no parent'.`);return}let d=e.message.descriptor.protocol,l=await qce(t,d,a,r,n,i),c={isLatestBaseState:!0,interface:be.Records,method:ge.Write,protocol:l,recordId:o},{messages:u}=await r.query(t,[c]),f=u[0];if(f===void 0)throw l!==d?new ie(ne.ProtocolAuthorizationCrossProtocolParentNotFound,`Could not find parent record '${o}' in protocol '${l}' for cross-protocol child at path '${a}'.`):new ie(ne.ProtocolAuthorizationIncorrectProtocolPath,`Could not find matching parent record to verify declared protocol path '${a}'.`);if(`${f.descriptor.protocolPath}/${s}`!==a)throw new ie(ne.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 ie(ne.ProtocolAuthorizationIncorrectContextId,`Declared contextId '${y}' is not the same as expected: '${m}'.`)}async function qce(t,e,r,n,i,a){let s=r.split("/");if(s.length<=1)return e;let o=await i(t,e,n,a),d=o.structure[s[0]];if(d?.$ref!==void 0){let l=zs(d.$ref);if(l!==void 0&&o.uses!==void 0){let c=o.uses[l.alias];if(c!==void 0)return s.length===2?c:e}}return e}async function u9(t,e,r,n,i,a){let s=e.descriptor.protocolPath,o=Wx(s),d=await zce(t,s,r,n,i,a);Fce(e,d,o)}async function zce(t,e,r,n,i,a){let s=e.split("/"),o=r.structure[s[0]];if(o?.$ref!==void 0&&s.length===1){let d=zs(o.$ref);if(d!==void 0&&r.uses!==void 0){let l=r.uses[d.alias];if(l!==void 0)return(await i(t,l,n,a)).types}}return r.types}function Fce(t,e,r){let n=r??Wx(t.descriptor.protocolPath);if(!Object.keys(e).includes(n))throw new ie(ne.ProtocolAuthorizationInvalidType,`record with type ${n} not allowed in protocol`);let a=e[n],{schema:s}=t.descriptor;if(a.schema!==void 0&&a.schema!==s)throw new ie(ne.ProtocolAuthorizationInvalidSchema,`type '${n}' must have schema '${a.schema}', instead has '${s}'`);let{dataFormat:o}=t.descriptor;if(a.dataFormats!==void 0&&!a.dataFormats.includes(o))throw new ie(ne.ProtocolAuthorizationIncorrectDataFormat,`type '${n}' must have data format in (${a.dataFormats}), instead has '${o}'`);if(a.encryptionRequired===!0&&t.encryption===void 0)throw new ie(ne.ProtocolAuthorizationEncryptionRequired,`type '${n}' requires encryption but message has no encryption metadata`)}function f9(t,e){let{min:r=0,max:n}=e.$size||{},i=t.message.descriptor.dataSize;if(i<r)throw new ie(ne.ProtocolAuthorizationMinSizeInvalid,`data size ${i} is less than allowed ${r}`);if(n!==void 0&&i>n)throw new ie(ne.ProtocolAuthorizationMaxSizeInvalid,`data size ${i} is more than allowed ${n}`)}function p9(t,e){if(e.$tags!==void 0){let{tags:r={},protocol:n,protocolPath:i}=t.message.descriptor,{$allowUndefinedTags:a,$requiredTags:s,...o}=e.$tags,d=a||!1,l=s||[],c=new d9.default.default,u=c.compile({type:"object",properties:o,required:l,additionalProperties:d});if(!u(r)){let h=c.errorsText(u.errors,{dataVar:`${n}/${i}/$tags`});throw new ie(ne.ProtocolAuthorizationTagsInvalidSchema,`tags schema validation error: ${h}`)}}}async function h9(t,e,r,n){if(!r.$role)return;let i=e,a=i.message.descriptor.recipient;if(a===void 0)throw new ie(ne.ProtocolAuthorizationRoleMissingRecipient,"Role records must have a recipient");let s=i.message.descriptor.protocolPath,o={interface:be.Records,method:ge.Write,isLatestBaseState:!0,protocol:i.message.descriptor.protocol,protocolPath:s,recipient:a},d=Te.getParentContextFromOfContextId(i.message.contextId);if(d!==""){let f=ir.constructPrefixFilterAsRangeFilter(d);o.contextId=f}let{messages:l}=await n.query(t,[o]);if(l.filter(f=>f.recordId!==i.message.recordId).length>0)throw new ie(ne.ProtocolAuthorizationDuplicateRoleRecipient,`DID '${a}' is already recipient of a role record at protocol path '${s} under the parent context ${d}.`)}async function m9(t,e,r,n){if(r.$recordLimit===void 0||!await e.isInitialWrite())return;let{max:a,strategy:s}=r.$recordLimit,o=e.message.descriptor.protocolPath,d={interface:be.Records,method:ge.Write,isLatestBaseState:!0,protocol:e.message.descriptor.protocol,protocolPath:o},l=Te.getParentContextFromOfContextId(e.message.contextId);if(l!==""){let u=ir.constructPrefixFilterAsRangeFilter(l);d.contextId=u}if(await n.count(t,[d])>=a)throw s===Hl.Reject?new ie(ne.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 ie(ne.ProtocolAuthorizationRecordLimitStrategyNotImplemented,`record limit strategy '${s}' is not yet implemented.`)}async function y9(t,e){if(t.message.descriptor.squash!==!0)return;if(e.$squash!==!0)throw new ie(ne.ProtocolAuthorizationSquashNotEnabled,`squash writes are not enabled at protocol path '${t.message.descriptor.protocolPath}': rule set must have $squash: true.`);if(!await t.isInitialWrite())throw new ie(ne.ProtocolAuthorizationSquashNotInitialWrite,"squash write must be an initial write (a new record): updates cannot be squash writes.")}async function g9(t,e){if(!(e.$immutable!==!0||await t.isInitialWrite()))throw new ie(ne.ProtocolAuthorizationImmutableRecord,`record at protocol path '${t.message.descriptor.protocolPath}' is immutable: updates are not allowed.`)}var d9,w9=F(()=>{"use strict";g();Tg();d9=An(IR(),1);lc();Jn();xt();lr();Yp()});var ys,Xp=F(()=>{"use strict";g();Yp();Vc();xt();lr();a9();c9();w9();ys=class t{static async validateReferentialIntegrity(e,r,n,i){let a=await DR(e,r,n),s=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,a,i),o=t.createBoundFetchDefinition(i);await u9(e,r.message,s,n,o,a),await l9(e,r,n,o,a);let d=t.getRuleSet(r.message.descriptor.protocolPath,s);await h9(e,r,d,n),f9(r,d),p9(r,d),await g9(r,d),await y9(r,d),await m9(e,r,d,n)}static async authorizeWrite(e,r,n,i){let a=await _y(e,r.message.recordId,n),s;a===void 0?s=await hv(e,r.message.descriptor.parentId,n):s=await hv(e,r.message.recordId,n);let o=await DR(e,r,n),d=await t.fetchProtocolDefinition(e,r.message.descriptor.protocol,n,o,i),l=t.getRuleSet(r.message.descriptor.protocolPath,d),c=t.createBoundFetchDefinition(i);await fv(e,r,r.message.descriptor.protocol,r.message.contextId,d,n,c,o),await pv(e,r,l,s,n,d)}static async authorizeRead(e,r,n,i,a){let s=await hv(e,n.message.recordId,i),o=await _y(e,n.message.recordId,i),d=o!==void 0?o.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,l=await t.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,d,a),c=t.getRuleSet(n.message.descriptor.protocolPath,l),u=t.createBoundFetchDefinition(a);await fv(e,r,n.message.descriptor.protocol,n.message.contextId,l,i,u,d),await pv(e,r,c,s,i,l)}static async authorizeQueryOrSubscribe(e,r,n,i){let{protocol:a,protocolPath:s,contextId:o}=r.message.descriptor.filter,d=await t.fetchProtocolDefinition(e,a,n,void 0,i),l=t.getRuleSet(s,d),c=t.createBoundFetchDefinition(i);await fv(e,r,a,o,d,n,c),await pv(e,r,l,[],n,d)}static async authorizeDelete(e,r,n,i,a){let s=await hv(e,r.message.descriptor.recordId,i),o=await _y(e,r.message.descriptor.recordId,i),d=o!==void 0?o.descriptor.messageTimestamp:n.message.descriptor.messageTimestamp,l=await t.fetchProtocolDefinition(e,n.message.descriptor.protocol,i,d,a),c=t.getRuleSet(n.message.descriptor.protocolPath,l),u=t.createBoundFetchDefinition(a);await fv(e,r,n.message.descriptor.protocol,n.message.contextId,l,i,u,d),await pv(e,r,c,s,i,l)}static async fetchProtocolDefinition(e,r,n,i,a){if(a!==void 0){let l=a.getDefinition(r);if(l!==void 0)return l}let s={interface:be.Protocols,method:ge.Configure,protocol:r};i!==void 0?s.messageTimestamp={lte:i}:s.isLatestBaseState=!0;let{messages:o}=await n.query(e,[s],{messageTimestamp:It.Descending},{limit:1});if(o.length===0)throw new ie(ne.ProtocolAuthorizationProtocolNotFound,`unable to find protocol definition for ${r}`);return o[0].descriptor.definition}static createBoundFetchDefinition(e){return(r,n,i,a)=>t.fetchProtocolDefinition(r,n,i,a,e)}static getRuleSet(e,r){let n=yd(e,r.structure);if(n===void 0)throw new ie(ne.ProtocolAuthorizationMissingRuleSet,`No rule set defined for protocolPath ${e}`);return n}}});var Qx,v9=F(()=>{"use strict";g();No();wr();Uo();Xp();Jn();nx();lr();Qx=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await ad.parse(r)}catch(a){return wt(a,400)}let i;if(Te.filterIncludesPublishedRecords(n.message.descriptor.filter)&&n.author===void 0)i=await this.countPublishedRecords(e,n);else{try{await pn(r.authorization,this.deps.didResolver),await t.authorizeRecordsCount(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(a){return wt(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,r){let{filter:n}=r.message.descriptor,i={...Te.convertFilter(n),interface:be.Records,method:ge.Write,isLatestBaseState:!0};return this.deps.messageStore.count(e,[i])}async countRecordsAsNonOwner(e,r){let{filter:n}=r.message.descriptor,i=[];return Te.filterIncludesPublishedRecords(n)&&i.push(t.buildPublishedRecordsFilter(r)),Te.filterIncludesUnpublishedRecords(n)&&(Te.shouldBuildUnpublishedAuthorFilter(n,r.author)&&i.push(t.buildUnpublishedRecordsByCountAuthorFilter(r)),Te.shouldProtocolAuthorize(r.signaturePayload)&&i.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),Te.shouldBuildUnpublishedRecipientFilter(n,r.author)&&i.push(t.buildUnpublishedRecordsForCountAuthorFilter(r))),this.deps.messageStore.count(e,i)}async countPublishedRecords(e,r){let n=t.buildPublishedRecordsFilter(r);return this.deps.messageStore.count(e,[n])}static buildPublishedRecordsFilter(e){let{filter:r}=e.message.descriptor;return{...Te.convertFilter(r),interface:be.Records,method:ge.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{...Te.convertFilter(r),interface:be.Records,method:ge.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{filter:r}=e.message.descriptor;return{...Te.convertFilter(r),interface:be.Records,method:ge.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByCountAuthorFilter(e){let{filter:r}=e.message.descriptor;return{...Te.convertFilter(r),author:e.author,interface:be.Records,method:ge.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsCount(e,r,n,i){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),Te.shouldProtocolAuthorize(r.signaturePayload)&&await ys.authorizeQueryOrSubscribe(e,r,n,i)}}});var Ea,mv=F(()=>{"use strict";g();mc();wr();nc();Jn();Jc();Di();us();lr();Ea=class t extends $n{static async parse(e){let r;return e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Te.validateDelegatedGrantReferentialIntegrity(e,r),St.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r=e.recordId,n=St.getCurrentTimestamp(),i={interface:be.Records,method:ge.Delete,messageTimestamp:e.messageTimestamp??n,recordId:r,prune:e.prune??!1},a=await we.createAuthorization({descriptor:i,signer:e.signer,protocolRole:e.protocolRole,permissionGrantId:e.permissionGrantId,delegatedGrant:e.delegatedGrant}),s={descriptor:i,authorization:a};return we.validateJsonSchema(s),new t(s)}constructIndexes(e){let n={...this.message.descriptor},{protocol:i,protocolPath:a,recipient:s,schema:o,parentId:d,dateCreated:l}=e.descriptor,c={isLatestBaseState:!0,protocol:i,protocolPath:a,recipient:s,schema:o,parentId:d,dateCreated:l,contextId:e.contextId,author:this.author,...n};return tr(c),c}async authorizeDelegate(e,r){let n=Ir.parse(this.message.authorization.authorDelegatedGrant);await jn.authorizeDelete({recordsDeleteMessage:this.message,recordsWriteToDelete:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}}});var rf,e2,t2=F(()=>{"use strict";g();(function(t){t.RecordsDelete="RecordsDelete",t.RecordsSquash="RecordsSquash"})(rf||(rf={}));e2=class t{resumableTaskStore;static timeoutExtensionFrequencyInSeconds=30;resumableTaskBatchSize=100;resumableTaskHandlers;constructor(e,r){this.resumableTaskStore=e,this.resumableTaskHandlers={[rf.RecordsDelete]:async n=>await r.performRecordsDelete(n),[rf.RecordsSquash]:async n=>await r.performRecordsSquash(n)}}async run(e){let r=t.timeoutExtensionFrequencyInSeconds*2,n=await this.resumableTaskStore.register(e,r);await this.runWithAutomaticTimeoutExtension(n)}async runWithAutomaticTimeoutExtension(e){let r=t.timeoutExtensionFrequencyInSeconds*2,n;try{n=setInterval(()=>{this.resumableTaskStore.extend(e.id,r)},t.timeoutExtensionFrequencyInSeconds*1e3);let i=this.resumableTaskHandlers[e.task.name];await i(e.task.data),await this.resumableTaskStore.delete(e.id)}finally{t.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 r=e;for(;r.length>0;){let n=r;r=[];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),r.push(i)}}}}});var r2,b9=F(()=>{"use strict";g();No();lr();wr();Uo();Lo();Xp();Jn();mv();Jc();Us();t2();r2=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await Ea.parse(r)}catch(l){return wt(l,400)}try{await pn(r.authorization,this.deps.didResolver)}catch(l){return wt(l,401)}let i={interface:be.Records,recordId:r.descriptor.recordId},{messages:a}=await this.deps.messageStore.query(e,[i]),s=await we.getNewestMessage(a);if(!Te.canPerformDeleteAgainstRecord(r,s))return{status:{code:404,detail:"Not Found"}};if(!await we.isNewer(r,s))return{status:{code:409,detail:"Conflict"}};try{let l=await At.fetchInitialRecordsWrite(this.deps.messageStore,e,r.descriptor.recordId);await t.authorizeRecordsDelete(e,n,l,this.deps.messageStore,this.deps.coreProtocols)}catch(l){return wt(l,401)}return await this.deps.resumableTaskManager.run({name:rf.RecordsDelete,data:{tenant:e,message:r}}),{status:{code:202,detail:"Accepted"}}}static async authorizeRecordsDelete(e,r,n,i,a){if(we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n.message,i),r.author!==e)if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let s=await dt.fetchGrant(e,i,r.signaturePayload.permissionGrantId);await jn.authorizeDelete({recordsDeleteMessage:r.message,recordsWriteToDelete:n.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:s,messageStore:i})}else await ys.authorizeDelete(e,r,n,i,a)}}});var n2,P9=F(()=>{"use strict";g();No();hp();wr();Uo();Xp();Jn();ix();Us();Vc();lr();n2=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await ha.parse(r)}catch(s){return wt(s,400)}let i,a;if(Te.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 pn(r.authorization,this.deps.didResolver),await t.authorizeRecordsQuery(e,n,this.deps.messageStore,this.deps.coreProtocols)}catch(s){return wt(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 At.isInitialWrite(s)){let d=(await this.deps.messageStore.query(e,[{recordId:s.recordId,isLatestBaseState:!1,method:ge.Write}])).messages[0];delete d.encodedData,s.initialWrite=d}return{status:{code:200,detail:"OK"},entries:i,cursor:a}}convertDateSort(e){switch(e){case Kt.CreatedAscending:return{dateCreated:It.Ascending};case Kt.CreatedDescending:return{dateCreated:It.Descending};case Kt.PublishedAscending:return{datePublished:It.Ascending};case Kt.PublishedDescending:return{datePublished:It.Descending};case Kt.UpdatedAscending:return{messageTimestamp:It.Ascending};case Kt.UpdatedDescending:return{messageTimestamp:It.Descending};default:return{dateCreated:It.Ascending}}}async fetchRecordsAsOwner(e,r){let{dateSort:n,filter:i,pagination:a}=r.message.descriptor,s={...Te.convertFilter(i,n),interface:be.Records,method:ge.Write,isLatestBaseState:!0},o=this.convertDateSort(n);return this.deps.messageStore.query(e,[s],o,a)}async fetchRecordsAsNonOwner(e,r){let{dateSort:n,pagination:i,filter:a}=r.message.descriptor,s=[];Te.filterIncludesPublishedRecords(a)&&s.push(t.buildPublishedRecordsFilter(r)),Te.filterIncludesUnpublishedRecords(a)&&(Te.shouldBuildUnpublishedAuthorFilter(a,r.author)&&s.push(t.buildUnpublishedRecordsByQueryAuthorFilter(r)),Te.shouldProtocolAuthorize(r.signaturePayload)&&s.push(t.buildUnpublishedProtocolAuthorizedRecordsFilter(r)),Te.shouldBuildUnpublishedRecipientFilter(a,r.author)&&s.push(t.buildUnpublishedRecordsForQueryAuthorFilter(r)));let o=this.convertDateSort(n);return this.deps.messageStore.query(e,s,o,i)}async fetchPublishedRecords(e,r){let{dateSort:n,pagination:i}=r.message.descriptor,a=t.buildPublishedRecordsFilter(r),s=this.convertDateSort(n);return this.deps.messageStore.query(e,[a],s,i)}static buildPublishedRecordsFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...Te.convertFilter(n,r),interface:be.Records,method:ge.Write,published:!0,isLatestBaseState:!0}}static buildUnpublishedRecordsForQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...Te.convertFilter(n,r),interface:be.Records,method:ge.Write,recipient:e.author,isLatestBaseState:!0,published:!1}}static buildUnpublishedProtocolAuthorizedRecordsFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...Te.convertFilter(n,r),interface:be.Records,method:ge.Write,isLatestBaseState:!0,published:!1}}static buildUnpublishedRecordsByQueryAuthorFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...Te.convertFilter(n,r),author:e.author,interface:be.Records,method:ge.Write,isLatestBaseState:!0,published:!1}}static async authorizeRecordsQuery(e,r,n,i){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),Te.shouldProtocolAuthorize(r.signaturePayload)&&await ys.authorizeQueryOrSubscribe(e,r,n,i)}}});var gd,RR=F(()=>{"use strict";g();mc();hp();wr();nc();Jn();Jc();Di();us();xt();lr();gd=class t extends $n{static async parse(e){if(e.descriptor.filter.published===!1&&(e.descriptor.dateSort===Kt.PublishedAscending||e.descriptor.dateSort===Kt.PublishedDescending))throw new ie(ne.RecordsReadParseFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${e.descriptor.dateSort}`);let r;return e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Te.validateDelegatedGrantReferentialIntegrity(e,r),St.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let{filter:r,signer:n,permissionGrantId:i,protocolRole:a,dateSort:s}=e,o=St.getCurrentTimestamp();if(e.filter.published===!1&&(s===Kt.PublishedAscending||s===Kt.PublishedDescending))throw new ie(ne.RecordsReadCreateFilterPublishedSortInvalid,`reads must not filter for \`published:false\` and sort by ${s}`);let d={interface:be.Records,method:ge.Read,filter:Te.normalizeFilter(r),messageTimestamp:e.messageTimestamp??o,permissionGrantId:i,dateSort:s};tr(d);let l;n!==void 0&&(l=await we.createAuthorization({descriptor:d,signer:n,permissionGrantId:i,protocolRole:a,delegatedGrant:e.delegatedGrant}));let c={descriptor:d,authorization:l};return we.validateJsonSchema(c),new t(c)}async authorizeDelegate(e,r){let n=Ir.parse(this.message.authorization.authorDelegatedGrant);await jn.authorizeRead({recordsReadMessage:this.message,recordsWriteMessageToBeRead:e,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:n,messageStore:r})}}});var i2,x9=F(()=>{"use strict";g();No();hu();kn();wr();Uo();Lo();Xp();Jn();Jc();RR();Us();xt();lr();i2=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r}){let n;try{n=await gd.parse(r)}catch(u){return wt(u,400)}try{n.author!==void 0&&await pn(r.authorization,this.deps.didResolver)}catch(u){return wt(u,401)}let i={interface:be.Records,isLatestBaseState:!0,...Te.convertFilter(r.descriptor.filter)},a=Te.convertDateSort(r.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===ge.Delete){let u=o,f=u.descriptor.recordId,h=await At.fetchInitialRecordsWriteMessage(this.deps.messageStore,e,f);if(h===void 0)return wt(new ie(ne.RecordsReadInitialWriteNotFound,"initial write for deleted record not found"),400);let p;try{p=await At.fetchNewestRecordsWrite(this.deps.messageStore,e,f)}catch{p=h}let m=await At.parse(p);try{await t.authorizeRecordsRead(e,n,m,this.deps.messageStore,this.deps.coreProtocols)}catch(y){return wt(y,401)}return{status:{code:404,detail:"Not Found"},entry:{recordsDelete:u,initialWrite:h}}}let d=o;try{let u=await At.parse(d);await t.authorizeRecordsRead(e,n,u,this.deps.messageStore,this.deps.coreProtocols)}catch(u){return wt(u,401)}let l;if(d.encodedData!==void 0){let u=De.base64UrlToBytes(d.encodedData);l=Yt.fromBytes(u),delete d.encodedData}else{let u=await this.deps.dataStore.get(e,d.recordId,d.descriptor.dataCid);if(u?.dataStream===void 0)return{status:{code:410,detail:"Record data not available"},entry:{recordsWrite:d}};l=u.dataStream}let c={status:{code:200,detail:"OK"},entry:{recordsWrite:d,data:l}};if(!await At.isInitialWrite(d)){let f=(await this.deps.messageStore.query(e,[{recordId:d.recordId,isLatestBaseState:!1,method:ge.Write}])).messages[0];delete f.encodedData,c.entry.initialWrite=f}return c}static async authorizeRecordsRead(e,r,n,i,a){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n.message,i);let{descriptor:s}=n.message;if(r.author!==e){if(s.published===!0)return;if(r.author!==void 0&&(r.author===s.recipient||r.author===n.author))return;if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let o=await dt.fetchGrant(e,i,r.signaturePayload.permissionGrantId);await jn.authorizeRead({recordsReadMessage:r.message,recordsWriteMessageToBeRead:n.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:o,messageStore:i})}else await ys.authorizeRead(e,r,n,i,a)}}}});var Sa,s2=F(()=>{"use strict";g();mc();wr();nc();Jn();Jc();Di();us();xt();lr();ua();Sa=class t extends $n{static async parse(e){let r;if(e.authorization!==void 0&&(r=await we.validateSignatureStructure(e.authorization.signature,e.descriptor)),await Te.validateDelegatedGrantReferentialIntegrity(e,r),r?.protocolRole!==void 0&&e.descriptor.filter.protocolPath===void 0)throw new ie(ne.RecordsSubscribeFilterMissingRequiredProperties,"Role-authorized subscriptions must include `protocolPath` in the filter");return e.descriptor.filter.protocol!==void 0&&si(e.descriptor.filter.protocol),e.descriptor.filter.schema!==void 0&&Wc(e.descriptor.filter.schema),St.validateTimestamp(e.descriptor.messageTimestamp),new t(e)}static async create(e){let r={interface:be.Records,method:ge.Subscribe,messageTimestamp:e.messageTimestamp??St.getCurrentTimestamp(),filter:Te.normalizeFilter(e.filter),dateSort:e.dateSort,pagination:e.pagination,cursor:e.cursor};tr(r);let n=e.signer,i;n&&(i=await we.createAuthorization({descriptor:r,signer:n,protocolRole:e.protocolRole,delegatedGrant:e.delegatedGrant}));let a={descriptor:r,authorization:i};return we.validateJsonSchema(a),new t(a)}async authorizeDelegate(e){let r=Ir.parse(this.message.authorization.authorDelegatedGrant);await jn.authorizeQueryOrSubscribe({incomingMessage:this.message,expectedGrantor:this.author,expectedGrantee:this.signer,permissionGrant:r,messageStore:e})}}});var o2,E9=F(()=>{"use strict";g();No();hp();wr();Uo();Xp();Jn();s2();Us();Vc();xt();lr();o2=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r,subscriptionHandler:n}){if(this.deps.eventLog===void 0)return wt(new ie(ne.RecordsSubscribeEventLogUnimplemented,"Subscriptions are not supported"),501);let i;try{i=await Sa.parse(r)}catch(f){return wt(f,400)}let a=[],s=[];if(Te.filterIncludesPublishedRecords(i.message.descriptor.filter)&&i.author===void 0)a=[t.buildPublishedEventFilter(i)],s=[t.buildPublishedQueryFilter(i)],delete r.authorization;else{try{await pn(r.authorization,this.deps.didResolver),await t.authorizeRecordsSubscribe(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(f){return wt(f,401)}i.author===e?(a=t.buildOwnerEventFilters(i),s=t.buildOwnerQueryFilters(i)):(a=t.buildNonOwnerEventFilters(i),s=t.buildNonOwnerQueryFilters(i))}let o=await we.getCid(r),{cursor:d}=i.message.descriptor;if(d!==void 0)try{let f=await this.deps.eventLog.subscribe(e,o,n,{cursor:d,filters:a});return{status:{code:200,detail:"OK"},subscription:f}}catch(f){return wt(f,500)}let l=await this.deps.eventLog.subscribe(e,o,n,{filters:a}),c,u;try{let{dateSort:f,pagination:h}=i.message.descriptor,p=t.convertDateSort(f),m=await this.deps.messageStore.query(e,s,p,h);c=m.messages,u=m.cursor;for(let y of c)if(!await At.isInitialWrite(y)){let w=(await this.deps.messageStore.query(e,[{recordId:y.recordId,isLatestBaseState:!1,method:ge.Write}])).messages[0];delete w.encodedData,y.initialWrite=w}}catch(f){return await l.close(),wt(f,500)}return{status:{code:200,detail:"OK"},subscription:l,entries:c,cursor:u}}static convertDateSort(e){switch(e){case Kt.CreatedAscending:return{dateCreated:It.Ascending};case Kt.CreatedDescending:return{dateCreated:It.Descending};case Kt.PublishedAscending:return{datePublished:It.Ascending};case Kt.PublishedDescending:return{datePublished:It.Descending};case Kt.UpdatedAscending:return{messageTimestamp:It.Ascending};case Kt.UpdatedDescending:return{messageTimestamp:It.Descending};default:return{dateCreated:It.Ascending}}}static buildOwnerEventFilters(e){let{filter:r}=e.message.descriptor;return[{...Te.convertFilter(r),interface:be.Records,method:[ge.Write,ge.Delete]}]}static buildNonOwnerEventFilters(e){let r=[],{filter:n}=e.message.descriptor;return Te.filterIncludesPublishedRecords(n)&&r.push(t.buildPublishedEventFilter(e)),Te.filterIncludesUnpublishedRecords(n)&&(Te.shouldBuildUnpublishedAuthorFilter(n,e.author)&&r.push({...Te.convertFilter(n),author:e.author,interface:be.Records,method:[ge.Write,ge.Delete],published:!1}),Te.shouldProtocolAuthorize(e.signaturePayload)&&r.push({...Te.convertFilter(n),interface:be.Records,method:[ge.Write,ge.Delete],published:!1}),Te.shouldBuildUnpublishedRecipientFilter(n,e.author)&&r.push({...Te.convertFilter(n),interface:be.Records,method:[ge.Write,ge.Delete],recipient:e.author,published:!1})),r}static buildPublishedEventFilter(e){return{...Te.convertFilter(e.message.descriptor.filter),interface:be.Records,method:[ge.Write,ge.Delete],published:!0}}static buildOwnerQueryFilters(e){let{dateSort:r,filter:n}=e.message.descriptor;return[{...Te.convertFilter(n,r),interface:be.Records,method:ge.Write,isLatestBaseState:!0}]}static buildNonOwnerQueryFilters(e){let r=[],{dateSort:n,filter:i}=e.message.descriptor;return Te.filterIncludesPublishedRecords(i)&&r.push(t.buildPublishedQueryFilter(e)),Te.filterIncludesUnpublishedRecords(i)&&(Te.shouldBuildUnpublishedAuthorFilter(i,e.author)&&r.push({...Te.convertFilter(i,n),author:e.author,interface:be.Records,method:ge.Write,isLatestBaseState:!0,published:!1}),Te.shouldProtocolAuthorize(e.signaturePayload)&&r.push({...Te.convertFilter(i,n),interface:be.Records,method:ge.Write,isLatestBaseState:!0,published:!1}),Te.shouldBuildUnpublishedRecipientFilter(i,e.author)&&r.push({...Te.convertFilter(i,n),interface:be.Records,method:ge.Write,recipient:e.author,isLatestBaseState:!0,published:!1})),r}static buildPublishedQueryFilter(e){let{dateSort:r,filter:n}=e.message.descriptor;return{...Te.convertFilter(n,r),interface:be.Records,method:ge.Write,published:!0,isLatestBaseState:!0}}static async authorizeRecordsSubscribe(e,r,n,i){we.isSignedByAuthorDelegate(r.message)&&await r.authorizeDelegate(n),Te.shouldProtocolAuthorize(r.signaturePayload)&&await ys.authorizeQueryOrSubscribe(e,r,n,i)}}});var Ty,CR=F(()=>{"use strict";g();B0();lc();wr();Jn();mv();Us();lr();Ty=class t{messageStore;dataStore;stateIndex;eventLog;constructor({messageStore:e,dataStore:r,stateIndex:n,eventLog:i}){this.messageStore=e,this.dataStore=r,this.stateIndex=n,this.eventLog=i}async performRecordsDelete({tenant:e,message:r}){let n={interface:be.Records,recordId:r.descriptor.recordId},{messages:i}=await this.messageStore.query(e,[n]),a=await we.getNewestMessage(i);if(!Te.canPerformDeleteAgainstRecord(r,a))return;let s=await Ea.parse(r),o=await At.getInitialWrite(i),d=s.constructIndexes(o),l=await we.getCid(r);await this.messageStore.put(e,r,d),await this.stateIndex.insert(e,l,d),this.eventLog!==void 0&&await this.eventLog.emit(e,{message:r,initialWrite:o},d),r.descriptor.prune&&await t.purgeRecordDescendants(e,r.descriptor.recordId,this.messageStore,this.dataStore,this.stateIndex),await t.deleteAllOlderMessagesButKeepInitialWrite(e,i,r,this.messageStore,this.dataStore,this.stateIndex)}async performRecordsSquash({tenant:e,message:r}){let{protocol:n,protocolPath:i,messageTimestamp:a}=r.descriptor,s={interface:be.Records,protocol:n,protocolPath:i},o=Te.getParentContextFromOfContextId(r.contextId);if(o!==void 0&&o!==""){let c=ir.constructPrefixFilterAsRangeFilter(o);s.contextId=c}let{messages:d}=await this.messageStore.query(e,[s]),l=new Map;for(let c of d){let u;Te.isRecordsWrite(c)?u=c.recordId:u=c.descriptor.recordId;let f=l.get(u);f!==void 0?f.push(c):l.set(u,[c])}for(let[c,u]of l){if(c===r.recordId)continue;let f=await we.getNewestMessage(u);if(f===void 0)continue;f.descriptor.messageTimestamp<a&&await t.purgeRecordMessages(e,u,this.messageStore,this.dataStore,this.stateIndex)}}static async deleteFromDataStoreIfNeeded(e,r,n,i){if(n.descriptor.method!==ge.Write)return;let a=n;a.descriptor.dataSize<=ma.maxDataSizeAllowedToBeEncoded||a.descriptor.dataCid!==i.descriptor.dataCid&&await e.delete(r,a.recordId,a.descriptor.dataCid)}static async purgeRecordDescendants(e,r,n,i,a){let s={interface:be.Records,parentId:r},{messages:o}=await n.query(e,[s]),d=new Map;for(let l of o){let c;Te.isRecordsWrite(l)?c=l.recordId:c=l.descriptor.recordId;let u=d.get(c);u?u.push(l):d.set(c,[l])}for(let l of d.keys())await t.purgeRecordDescendants(e,l,n,i,a);for(let l of d.keys())await t.purgeRecordMessages(e,d.get(l),n,i,a)}static async purgeRecordMessages(e,r,n,i,a){let s=r.filter(l=>l.descriptor.method===ge.Write),o=await we.getNewestMessage(s);await i.delete(e,o.recordId,o.descriptor.dataCid);let d=await Promise.all(r.map(l=>we.getCid(l)));await a.delete(e,d),await Promise.all(d.map(l=>n.delete(e,l)))}static async deleteAllOlderMessagesButKeepInitialWrite(e,r,n,i,a,s){let o=[];for(let d of r){if(await we.isOlder(d,n)){await t.deleteFromDataStoreIfNeeded(a,e,d,n);let c=await we.getCid(d);if(await i.delete(e,c),await At.isInitialWrite(d)){let p=await(await At.parse(d)).constructIndexes(!1),m=d;delete m.encodedData,await i.put(e,m,p)}else{let f=await we.getCid(d);o.push(f)}}await s.delete(e,o)}}}});var a2,S9=F(()=>{"use strict";g();No();il();hu();B0();kn();lc();wr();Uo();Lo();Xp();Jn();Jc();Us();t2();Vc();CR();xt();lr();a2=class t{deps;constructor(e){this.deps=e}async handle({tenant:e,message:r,dataStream:n}){let i;try{i=await At.parse(r),await ys.validateReferentialIntegrity(e,i,this.deps.messageStore,this.deps.coreProtocols)}catch(p){return wt(p,400)}try{await pn(r.authorization,this.deps.didResolver,r.attestation),await this.authorizeRecordsWrite(e,i,this.deps.messageStore)}catch(p){return wt(p,401)}let a={interface:be.Records,recordId:r.recordId},{messages:s}=await this.deps.messageStore.query(e,[a]),o=await i.isInitialWrite(),d;if(!o)try{d=await At.getInitialWrite(s),At.verifyEqualityOfImmutableProperties(d,r)}catch(p){return wt(p,400)}try{await this.enforceSquashBackstop(e,r)}catch(p){return wt(p,409)}let l=await we.getNewestMessage(s),c=!1,u;if(l===void 0||await we.isNewer(r,l)?(c=!0,u=r):u=l,!c)return{status:{code:409,detail:"Conflict"}};let f=r.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(r.descriptor.protocol):void 0;try{if(l?.descriptor.method===ge.Delete)throw new ie(ne.RecordsWriteNotAllowedAfterDelete,"RecordsWrite is not allowed after a RecordsDelete.");f?.preProcessWrite!==void 0&&await f.preProcessWrite(e,r,this.deps.messageStore);let p=!1,m=r;if(n!==void 0)m=await this.processMessageWithDataStream(e,r,n),p=!0;else if(!o){let b=l;m=await this.processMessageWithoutDataStream(e,r,b),p=!0}let y=await i.constructIndexes(p);await this.deps.messageStore.put(e,m,y),await this.deps.stateIndex.insert(e,await we.getCid(r),y),this.deps.eventLog!==void 0&&p&&await this.deps.eventLog.emit(e,{message:r,initialWrite:d},y)}catch(p){if(p instanceof ie&&(p.code===ne.RecordsWriteMissingEncodedDataInPrevious||p.code===ne.RecordsWriteMissingDataInPrevious||p.code===ne.RecordsWriteNotAllowedAfterDelete||p.code===ne.RecordsWriteDataCidMismatch||p.code===ne.RecordsWriteDataSizeMismatch||p.code.startsWith("SchemaValidator")||this.deps.coreProtocols?.mapErrorToStatusCode(p.code)!==void 0))return wt(p,400);throw p}let h={status:o&&n===void 0?{code:204,detail:"No Content"}:{code:202,detail:"Accepted"}};return await Ty.deleteAllOlderMessagesButKeepInitialWrite(e,s,u,this.deps.messageStore,this.deps.dataStore,this.deps.stateIndex),r.descriptor.squash===!0&&await this.deps.resumableTaskManager.run({name:rf.RecordsSquash,data:{tenant:e,message:r}}),f?.postProcessWrite!==void 0&&await f.postProcessWrite(e,i,{messageStore:this.deps.messageStore,dataStore:this.deps.dataStore,stateIndex:this.deps.stateIndex}),h}async cloneAndAddEncodedData(e,r){let n={...e};return n.encodedData=De.bytesToBase64Url(r),n}async processMessageWithDataStream(e,r,n){let i=r;if(r.descriptor.dataSize<=ma.maxDataSizeAllowedToBeEncoded){let a=await Yt.toBytes(n),s=await hr.computeDagPbCidFromBytes(a);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,s,a.length);let o=r.descriptor.protocol!==void 0?this.deps.coreProtocols?.get(r.descriptor.protocol):void 0;o?.validateRecord!==void 0&&o.validateRecord(r,a),i=await this.cloneAndAddEncodedData(r,a)}else{let[a,s]=Yt.duplicateDataStream(n,2);try{let[o,d]=await Promise.all([hr.computeDagPbCidFromStream(a),this.deps.dataStore.put(e,r.recordId,r.descriptor.dataCid,s)]);t.validateDataIntegrity(r.descriptor.dataCid,r.descriptor.dataSize,o,d.dataSize)}catch(o){throw await this.deps.dataStore.delete(e,r.recordId,r.descriptor.dataCid),o}}return i}async processMessageWithoutDataStream(e,r,n){let i={...r},{dataCid:a,dataSize:s}=r.descriptor;if(t.validateDataIntegrity(a,s,n.descriptor.dataCid,n.descriptor.dataSize),s<=ma.maxDataSizeAllowedToBeEncoded)if(n.encodedData!==void 0)i.encodedData=n.encodedData;else throw new ie(ne.RecordsWriteMissingEncodedDataInPrevious,"No dataStream was provided and unable to get data from previous message");else if(await this.deps.dataStore.get(e,n.recordId,r.descriptor.dataCid)===void 0)throw new ie(ne.RecordsWriteMissingDataInPrevious,"No dataStream was provided and unable to get data from previous message");return i}static validateDataIntegrity(e,r,n,i){if(e!==n)throw new ie(ne.RecordsWriteDataCidMismatch,`actual data CID ${n} does not match dataCid in descriptor: ${e}`);if(r!==i)throw new ie(ne.RecordsWriteDataSizeMismatch,`actual data size ${i} bytes does not match dataSize in descriptor: ${r}`)}async enforceSquashBackstop(e,r){if(r.descriptor.protocol===void 0||r.descriptor.protocolPath===void 0)return;let n;try{n=await ys.fetchProtocolDefinition(e,r.descriptor.protocol,this.deps.messageStore,void 0,this.deps.coreProtocols)}catch(c){console.warn(`enforceSquashBackstop: failed to fetch protocol definition for '${r.descriptor.protocol}':`,c);return}let i=r.descriptor.protocolPath.split("/"),a=n.structure[i[0]];for(let c=1;c<i.length&&a!==void 0;c++)a=a[i[c]];if(a===void 0||a.$squash!==!0)return;let s={interface:be.Records,method:ge.Write,isLatestBaseState:!0,protocol:r.descriptor.protocol,protocolPath:r.descriptor.protocolPath,squash:!0},o=Te.getParentContextFromOfContextId(r.contextId);if(o!==void 0&&o!==""){let c=ir.constructPrefixFilterAsRangeFilter(o);s.contextId=c}let{messages:d}=await this.deps.messageStore.query(e,[s],{messageTimestamp:It.Descending},{limit:1});if(d.length===0)return;let l=d[0];if(r.descriptor.messageTimestamp<=l.descriptor.messageTimestamp)throw new ie(ne.ProtocolAuthorizationSquashBackstop,`incoming message timestamp '${r.descriptor.messageTimestamp}' is not newer than the most recent squash record timestamp '${l.descriptor.messageTimestamp}' at protocol path '${r.descriptor.protocolPath}'.`)}async authorizeRecordsWrite(e,r,n){if(r.owner!==void 0&&r.owner!==e)throw new ie(ne.RecordsWriteOwnerAndTenantMismatch,`Owner ${r.owner} must be the same as tenant ${e} when specified.`);if(r.isSignedByAuthorDelegate&&await r.authorizeAuthorDelegate(n),r.isSignedByOwnerDelegate&&await r.authorizeOwnerDelegate(n),r.owner===void 0){if(r.author===e)return;if(r.author!==void 0&&r.signaturePayload.permissionGrantId!==void 0){let i=await dt.fetchGrant(e,n,r.signaturePayload.permissionGrantId);await jn.authorizeWrite({recordsWriteMessage:r.message,expectedGrantor:e,expectedGrantee:r.author,permissionGrant:i,messageStore:n})}else await ys.authorizeWrite(e,r,n,this.deps.coreProtocols)}}}});function bde(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var a=t.charAt(i),s=a.charCodeAt(0);if(r[s]!==255)throw new TypeError(a+" is ambiguous");r[s]=i}var o=t.length,d=t.charAt(0),l=Math.log(o)/Math.log(256),c=Math.log(256)/Math.log(o);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,y=0,b=0,w=p.length;b!==w&&p[b]===0;)b++,m++;for(var S=(w-b)*c+1>>>0,k=new Uint8Array(S);b!==w;){for(var T=p[b],D=0,K=S-1;(T!==0||D<y)&&K!==-1;K--,D++)T+=256*k[K]>>>0,k[K]=T%o>>>0,T=T/o>>>0;if(T!==0)throw new Error("Non-zero carry");y=D,b++}for(var C=S-y;C!==S&&k[C]===0;)C++;for(var G=d.repeat(m);C<S;++C)G+=t.charAt(k[C]);return G}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var y=0,b=0;p[m]===d;)y++,m++;for(var w=(p.length-m)*l+1>>>0,S=new Uint8Array(w);p[m];){var k=r[p.charCodeAt(m)];if(k===255)return;for(var T=0,D=w-1;(k!==0||T<b)&&D!==-1;D--,T++)k+=o*S[D]>>>0,S[D]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");b=T,m++}if(p[m]!==" "){for(var K=w-b;K!==w&&S[K]===0;)K++;for(var C=new Uint8Array(y+(w-K)),G=y;K!==w;)C[G++]=S[K++];return C}}}function h(p){var m=f(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:h}}function Rde(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function Cde(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function zR(t){let e=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[r,n]=e;return n}function i7(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Kde;)e[r++]=t&255|T9,t/=128;for(;t&Mde;)e[r++]=t&255|T9,t>>>=7;return e[r]=t|0,i7.bytes=r-n+1,e}function FR(t,n){var r=0,n=n||0,i=0,a=n,s,o=t.length;do{if(a>=o)throw FR.bytes=0,new RangeError("Could not decode varint");s=t[a++],r+=i<28?(s&I9)<<i:(s&I9)*Math.pow(2,i),i+=7}while(s>=Ude);return FR.bytes=a-n,r}function s7(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&s7(t[e])})}function kd(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function lh(t){if(!kd(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=dle[t[r]];return e}function c7(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function y6(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}function $9(t){if(t>=Tl._0&&t<=Tl._9)return t-Tl._0;if(t>=Tl._A&&t<=Tl._F)return t-(Tl._A-10);if(t>=Tl._a&&t<=Tl._f)return t-(Tl._a-10)}function Ly(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,r=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,a=0;i<r;i++,a+=2){let s=$9(t.charCodeAt(a)),o=$9(t.charCodeAt(a+1));if(s===void 0||o===void 0){let d=t[a]+t[a+1];throw new Error('hex string expected, got non-hex character "'+d+'" at index '+a)}n[i]=s*16+o}return n}function ah(t){return y6(lh(t))}function vf(t){if(!kd(t))throw new Error("Uint8Array expected");return y6(lh(Uint8Array.from(t).reverse()))}function _d(t,e){return Ly(t.toString(16).padStart(e*2,"0"))}function qy(t,e){return _d(t,e).reverse()}function lle(t){return Ly(c7(t))}function zn(t,e,r){let n;if(typeof e=="string")try{n=Ly(e)}catch(a){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${a}`)}else if(kd(e))n=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(`${t} expected ${r} bytes, got ${i}`);return n}function uh(...t){let e=0;for(let i=0;i<t.length;i++){let a=t[i];if(!kd(a))throw new Error("Uint8Array expected");e+=a.length}let r=new Uint8Array(e),n=0;for(let i=0;i<t.length;i++){let a=t[i];r.set(a,n),n+=a.length}return r}function ule(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function fle(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function ple(t){let e;for(e=0;t>a7;t>>=Y2,e+=1);return e}function hle(t,e){return t>>BigInt(e)&Y2}function d7(t,e,r){if(typeof t!="number"||t<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 r!="function")throw new Error("hmacFn must be a function");let n=$R(t),i=$R(t),a=0,s=()=>{n.fill(1),i.fill(0),a=0},o=(...c)=>r(i,n,...c),d=(c=$R())=>{i=o(B9([0]),c),n=o(),c.length!==0&&(i=o(B9([1]),c),n=o())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let c=0,u=[];for(;c<e;){n=o();let f=n.slice();u.push(f),c+=n.length}return uh(...u)};return(c,u)=>{s(),d(c);let f;for(;!(f=u(l()));)d();return s(),f}}function hh(t,e,r={}){let n=(i,a,s)=>{let o=yle[a];if(typeof o!="function")throw new Error(`Invalid validator "${a}", expected function`);let d=t[i];if(!(s&&d===void 0)&&!o(d,t))throw new Error(`Invalid param ${String(i)}=${d} (${typeof d}), expected ${a}`)};for(let[i,a]of Object.entries(e))n(i,a,!1);for(let[i,a]of Object.entries(r))n(i,a,!0);return t}function O9(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function gle(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function l7(t,...e){if(!gle(t))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function wle(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");O9(t.outputLen),O9(t.blockLen)}function K2(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function vle(t,e){l7(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}function u7(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function f7(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function w6(t){if(typeof t=="string"&&(t=f7(t)),!u7(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function p7(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!u7(i))throw new Error("Uint8Array expected");e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let a=t[n];r.set(a,i),i+=a.length}return r}function m7(t){let e=n=>t().update(w6(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function v6(t=32){if(BR&&typeof BR.getRandomValues=="function")return BR.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Ple(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),a=BigInt(4294967295),s=Number(r>>i&a),o=Number(r&a),d=n?4:0,l=n?0:4;t.setUint32(e+d,s,n),t.setUint32(e+l,o,n)}function Zr(t,e){let r=t%e;return r>=ui?r:e+r}function w7(t,e,r){if(r<=ui||e<ui)throw new Error("Expected power/modulo > 0");if(r===hn)return ui;let n=hn;for(;e>ui;)e&hn&&(n=n*t%r),t=t*t%r,e>>=hn;return n}function Pn(t,e,r){let n=t;for(;e-- >ui;)n*=n,n%=r;return n}function VR(t,e){if(t===ui||e<=ui)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Zr(t,e),n=e,i=ui,a=hn,s=hn,o=ui;for(;r!==ui;){let d=n/r,l=n%r,c=i-s*d,u=a-o*d;n=r,r=l,i=s,a=o,s=c,o=u}if(n!==hn)throw new Error("invert: does not exist");return Zr(i,e)}function Tle(t){let e=(t-hn)/rh,r,n,i;for(r=t-hn,n=0;r%rh===ui;r/=rh,n++);for(i=rh;i<t&&w7(i,e,t)!==t-hn;i++);if(n===1){let s=(t+hn)/HR;return function(o,d){let l=o.pow(d,s);if(!o.eql(o.sqr(l),d))throw new Error("Cannot find square root");return l}}let a=(r+hn)/rh;return function(s,o){if(s.pow(o,e)===s.neg(s.ONE))throw new Error("Cannot find square root");let d=n,l=s.pow(s.mul(s.ONE,i),r),c=s.pow(o,a),u=s.pow(o,r);for(;!s.eql(u,s.ONE);){if(s.eql(u,s.ZERO))return s.ZERO;let f=1;for(let p=s.sqr(u);f<d&&!s.eql(p,s.ONE);f++)p=s.sqr(p);let h=s.pow(l,hn<<BigInt(d-f-1));l=s.sqr(h),c=s.mul(c,h),u=s.mul(u,l),d=f}return c}}function Ile(t){if(t%HR===kle){let e=(t+hn)/HR;return function(r,n){let i=r.pow(n,e);if(!r.eql(r.sqr(i),n))throw new Error("Cannot find square root");return i}}if(t%M9===j9){let e=(t-j9)/M9;return function(r,n){let i=r.mul(n,rh),a=r.pow(i,e),s=r.mul(n,a),o=r.mul(r.mul(s,rh),a),d=r.mul(s,r.sub(o,r.ONE));if(!r.eql(r.sqr(d),n))throw new Error("Cannot find square root");return d}}return t%_le,Tle(t)}function Cle(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Rle.reduce((n,i)=>(n[i]="function",n),e);return hh(t,r)}function $le(t,e,r){if(r<ui)throw new Error("Expected power > 0");if(r===ui)return t.ONE;if(r===hn)return e;let n=t.ONE,i=e;for(;r>ui;)r&hn&&(n=t.mul(n,i)),i=t.sqr(i),r>>=hn;return n}function Ble(t,e){let r=new Array(e.length),n=e.reduce((a,s,o)=>t.is0(s)?a:(r[o]=a,t.mul(a,s)),t.ONE),i=t.inv(n);return e.reduceRight((a,s,o)=>t.is0(s)?a:(r[o]=t.mul(a,r[o]),t.mul(a,s)),i),r}function v7(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function b6(t,e,r=!1,n={}){if(t<=ui)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:i,nByteLength:a}=v7(t,e);if(a>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=Ile(t),o=Object.freeze({ORDER:t,BITS:i,BYTES:a,MASK:g6(i),ZERO:ui,ONE:hn,create:d=>Zr(d,t),isValid:d=>{if(typeof d!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof d}`);return ui<=d&&d<t},is0:d=>d===ui,isOdd:d=>(d&hn)===hn,neg:d=>Zr(-d,t),eql:(d,l)=>d===l,sqr:d=>Zr(d*d,t),add:(d,l)=>Zr(d+l,t),sub:(d,l)=>Zr(d-l,t),mul:(d,l)=>Zr(d*l,t),pow:(d,l)=>$le(o,d,l),div:(d,l)=>Zr(d*VR(l,t),t),sqrN:d=>d*d,addN:(d,l)=>d+l,subN:(d,l)=>d-l,mulN:(d,l)=>d*l,inv:d=>VR(d,t),sqrt:n.sqrt||(d=>s(o,d)),invertBatch:d=>Ble(o,d),cmov:(d,l,c)=>c?l:d,toBytes:d=>r?qy(d,a):_d(d,a),fromBytes:d=>{if(d.length!==a)throw new Error(`Fp.fromBytes: expected ${a}, got ${d.length}`);return r?vf(d):ah(d)}});return Object.freeze(o)}function Ole(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");let r=t.sqrt(e);return t.isOdd(r)?t.neg(r):r}function b7(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function P7(t){let e=b7(t);return e+Math.ceil(e/2)}function jle(t,e,r=!1){let n=t.length,i=b7(e),a=P7(e);if(n<16||n<a||n>1024)throw new Error(`expected ${a}-1024 bytes of input, got ${n}`);let s=r?ah(t):vf(t),o=Zr(s,e-hn)+hn;return r?qy(o,i):_d(o,i)}function x7(t,e){let r=(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:r,unsafeLadder(i,a){let s=t.ZERO,o=i;for(;a>Mle;)a&jR&&(s=s.add(o)),o=o.double(),a>>=jR;return s},precomputeWindow(i,a){let{windows:s,windowSize:o}=n(a),d=[],l=i,c=l;for(let u=0;u<s;u++){c=l,d.push(c);for(let f=1;f<o;f++)c=c.add(l),d.push(c);l=c.double()}return d},wNAF(i,a,s){let{windows:o,windowSize:d}=n(i),l=t.ZERO,c=t.BASE,u=BigInt(2**i-1),f=2**i,h=BigInt(i);for(let p=0;p<o;p++){let m=p*d,y=Number(s&u);s>>=h,y>d&&(y-=f,s+=jR);let b=m,w=m+Math.abs(y)-1,S=p%2!==0,k=y<0;y===0?c=c.add(r(S,a[b])):l=l.add(r(k,a[w]))}return{p:l,f:c}},wNAFCached(i,a,s,o){let d=i._WINDOW_SIZE||1,l=a.get(i);return l||(l=this.precomputeWindow(i,d),d!==1&&a.set(i,o(l))),this.wNAF(d,l,s)}}}function P6(t){return Cle(t.Fp),hh(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...v7(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Kle(t){let e=P6(t);hh(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}function Lle(t){let e=Kle(t),{Fp:r}=e,n=e.toBytes||((p,m,y)=>{let b=m.toAffine();return uh(Uint8Array.from([4]),r.toBytes(b.x),r.toBytes(b.y))}),i=e.fromBytes||(p=>{let m=p.subarray(1),y=r.fromBytes(m.subarray(0,r.BYTES)),b=r.fromBytes(m.subarray(r.BYTES,2*r.BYTES));return{x:y,y:b}});function a(p){let{a:m,b:y}=e,b=r.sqr(p),w=r.mul(b,p);return r.add(r.add(w,r.mul(p,m)),y)}if(!r.eql(r.sqr(e.Gy),a(e.Gx)))throw new Error("bad generator point: equation left != right");function s(p){return typeof p=="bigint"&&Bl<p&&p<e.n}function o(p){if(!s(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function d(p){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:b,n:w}=e;if(m&&typeof p!="bigint"){if(kd(p)&&(p=lh(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let S;try{S=typeof p=="bigint"?p:ah(zn("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return b&&(S=Zr(S,w)),o(S),S}let l=new Map;function c(p){if(!(p instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(m,y,b){if(this.px=m,this.py=y,this.pz=b,m==null||!r.isValid(m))throw new Error("x required");if(y==null||!r.isValid(y))throw new Error("y required");if(b==null||!r.isValid(b))throw new Error("z required")}static fromAffine(m){let{x:y,y:b}=m||{};if(!m||!r.isValid(y)||!r.isValid(b))throw new Error("invalid affine point");if(m instanceof u)throw new Error("projective point not allowed");let w=S=>r.eql(S,r.ZERO);return w(y)&&w(b)?u.ZERO:new u(y,b,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=r.invertBatch(m.map(b=>b.pz));return m.map((b,w)=>b.toAffine(y[w])).map(u.fromAffine)}static fromHex(m){let y=u.fromAffine(i(zn("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return u.BASE.multiply(d(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!r.isValid(m)||!r.isValid(y))throw new Error("bad point: x or y not FE");let b=r.sqr(y),w=a(m);if(!r.eql(b,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(r.isOdd)return!r.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){c(m);let{px:y,py:b,pz:w}=this,{px:S,py:k,pz:T}=m,D=r.eql(r.mul(y,T),r.mul(S,w)),K=r.eql(r.mul(b,T),r.mul(k,w));return D&&K}negate(){return new u(this.px,r.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,b=r.mul(y,K9),{px:w,py:S,pz:k}=this,T=r.ZERO,D=r.ZERO,K=r.ZERO,C=r.mul(w,w),G=r.mul(S,S),z=r.mul(k,k),N=r.mul(w,S);return N=r.add(N,N),K=r.mul(w,k),K=r.add(K,K),T=r.mul(m,K),D=r.mul(b,z),D=r.add(T,D),T=r.sub(G,D),D=r.add(G,D),D=r.mul(T,D),T=r.mul(N,T),K=r.mul(b,K),z=r.mul(m,z),N=r.sub(C,z),N=r.mul(m,N),N=r.add(N,K),K=r.add(C,C),C=r.add(K,C),C=r.add(C,z),C=r.mul(C,N),D=r.add(D,C),z=r.mul(S,k),z=r.add(z,z),C=r.mul(z,N),T=r.sub(T,C),K=r.mul(z,G),K=r.add(K,K),K=r.add(K,K),new u(T,D,K)}add(m){c(m);let{px:y,py:b,pz:w}=this,{px:S,py:k,pz:T}=m,D=r.ZERO,K=r.ZERO,C=r.ZERO,G=e.a,z=r.mul(e.b,K9),N=r.mul(y,S),V=r.mul(b,k),ee=r.mul(w,T),R=r.add(y,b),B=r.add(S,k);R=r.mul(R,B),B=r.add(N,V),R=r.sub(R,B),B=r.add(y,w);let P=r.add(S,T);return B=r.mul(B,P),P=r.add(N,ee),B=r.sub(B,P),P=r.add(b,w),D=r.add(k,T),P=r.mul(P,D),D=r.add(V,ee),P=r.sub(P,D),C=r.mul(G,B),D=r.mul(z,ee),C=r.add(D,C),D=r.sub(V,C),C=r.add(V,C),K=r.mul(D,C),V=r.add(N,N),V=r.add(V,N),ee=r.mul(G,ee),B=r.mul(z,B),V=r.add(V,ee),ee=r.sub(N,ee),ee=r.mul(G,ee),B=r.add(B,ee),N=r.mul(V,B),K=r.add(K,N),N=r.mul(P,B),D=r.mul(R,D),D=r.sub(D,N),N=r.mul(R,V),C=r.mul(P,C),C=r.add(C,N),new u(D,K,C)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return h.wNAFCached(this,l,m,y=>{let b=r.invertBatch(y.map(w=>w.pz));return y.map((w,S)=>w.toAffine(b[S])).map(u.fromAffine)})}multiplyUnsafe(m){let y=u.ZERO;if(m===Bl)return y;if(o(m),m===Da)return this;let{endo:b}=e;if(!b)return h.unsafeLadder(this,m);let{k1neg:w,k1:S,k2neg:k,k2:T}=b.splitScalar(m),D=y,K=y,C=this;for(;S>Bl||T>Bl;)S&Da&&(D=D.add(C)),T&Da&&(K=K.add(C)),C=C.double(),S>>=Da,T>>=Da;return w&&(D=D.negate()),k&&(K=K.negate()),K=new u(r.mul(K.px,b.beta),K.py,K.pz),D.add(K)}multiply(m){o(m);let y=m,b,w,{endo:S}=e;if(S){let{k1neg:k,k1:T,k2neg:D,k2:K}=S.splitScalar(y),{p:C,f:G}=this.wNAF(T),{p:z,f:N}=this.wNAF(K);C=h.constTimeNegate(k,C),z=h.constTimeNegate(D,z),z=new u(r.mul(z.px,S.beta),z.py,z.pz),b=C.add(z),w=G.add(N)}else{let{p:k,f:T}=this.wNAF(y);b=k,w=T}return u.normalizeZ([b,w])[0]}multiplyAndAddUnsafe(m,y,b){let w=u.BASE,S=(T,D)=>D===Bl||D===Da||!T.equals(w)?T.multiplyUnsafe(D):T.multiply(D),k=S(this,y).add(S(m,b));return k.is0()?void 0:k}toAffine(m){let{px:y,py:b,pz:w}=this,S=this.is0();m==null&&(m=S?r.ONE:r.inv(w));let k=r.mul(y,m),T=r.mul(b,m),D=r.mul(w,m);if(S)return{x:r.ZERO,y:r.ZERO};if(!r.eql(D,r.ONE))throw new Error("invZ was invalid");return{x:k,y:T}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===Da)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===Da?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return lh(this.toRawBytes(m))}}u.BASE=new u(e.Gx,e.Gy,r.ONE),u.ZERO=new u(r.ZERO,r.ONE,r.ZERO);let f=e.nBitLength,h=x7(u,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:a,isWithinCurveOrder:s}}function qle(t){let e=P6(t);return hh(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function zle(t){let e=qle(t),{Fp:r,n}=e,i=r.BYTES+1,a=2*r.BYTES+1;function s(B){return Bl<B&&B<r.ORDER}function o(B){return Zr(B,n)}function d(B){return VR(B,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:u,isWithinCurveOrder:f}=Lle({...e,toBytes(B,P,E){let x=P.toAffine(),A=r.toBytes(x.x),I=uh;return E?I(Uint8Array.from([P.hasEvenY()?2:3]),A):I(Uint8Array.from([4]),A,r.toBytes(x.y))},fromBytes(B){let P=B.length,E=B[0],x=B.subarray(1);if(P===i&&(E===2||E===3)){let A=ah(x);if(!s(A))throw new Error("Point is not on curve");let I=u(A),M=r.sqrt(I),q=(M&Da)===Da;return(E&1)===1!==q&&(M=r.neg(M)),{x:A,y:M}}else if(P===a&&E===4){let A=r.fromBytes(x.subarray(0,r.BYTES)),I=r.fromBytes(x.subarray(r.BYTES,2*r.BYTES));return{x:A,y:I}}else throw new Error(`Point of length ${P} was invalid. Expected ${i} compressed bytes or ${a} uncompressed bytes`)}}),h=B=>lh(_d(B,e.nByteLength));function p(B){let P=n>>Da;return B>P}function m(B){return p(B)?o(-B):B}let y=(B,P,E)=>ah(B.slice(P,E));class b{constructor(P,E,x){this.r=P,this.s=E,this.recovery=x,this.assertValidity()}static fromCompact(P){let E=e.nByteLength;return P=zn("compactSignature",P,E*2),new b(y(P,0,E),y(P,E,2*E))}static fromDER(P){let{r:E,s:x}=sh.toSig(zn("DER",P));return new b(E,x)}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(P){return new b(this.r,this.s,P)}recoverPublicKey(P){let{r:E,s:x,recovery:A}=this,I=K(zn("msgHash",P));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let M=A===2||A===3?E+e.n:E;if(M>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let q=A&1?"03":"02",H=l.fromHex(q+h(M)),W=d(M),J=o(-I*W),X=o(x*W),L=l.BASE.multiplyAndAddUnsafe(H,J,X);if(!L)throw new Error("point at infinify");return L.assertValidity(),L}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new b(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Ly(this.toDERHex())}toDERHex(){return sh.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ly(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let w={isValidPrivateKey(B){try{return c(B),!0}catch{return!1}},normPrivateKeyToScalar:c,randomPrivateKey:()=>{let B=P7(e.n);return jle(e.randomBytes(B),e.n)},precompute(B=8,P=l.BASE){return P._setWindowSize(B),P.multiply(BigInt(3)),P}};function S(B,P=!0){return l.fromPrivateKey(B).toRawBytes(P)}function k(B){let P=kd(B),E=typeof B=="string",x=(P||E)&&B.length;return P?x===i||x===a:E?x===2*i||x===2*a:B instanceof l}function T(B,P,E=!0){if(k(B))throw new Error("first arg must be private key");if(!k(P))throw new Error("second arg must be public key");return l.fromHex(P).multiply(c(B)).toRawBytes(E)}let D=e.bits2int||function(B){let P=ah(B),E=B.length*8-e.nBitLength;return E>0?P>>BigInt(E):P},K=e.bits2int_modN||function(B){return o(D(B))},C=g6(e.nBitLength);function G(B){if(typeof B!="bigint")throw new Error("bigint expected");if(!(Bl<=B&&B<C))throw new Error(`bigint expected < 2^${e.nBitLength}`);return _d(B,e.nByteLength)}function z(B,P,E=N){if(["recovered","canonical"].some(se=>se in E))throw new Error("sign() legacy options not supported");let{hash:x,randomBytes:A}=e,{lowS:I,prehash:M,extraEntropy:q}=E;I==null&&(I=!0),B=zn("msgHash",B),M&&(B=zn("prehashed msgHash",x(B)));let H=K(B),W=c(P),J=[G(W),G(H)];if(q!=null){let se=q===!0?A(r.BYTES):q;J.push(zn("extraEntropy",se))}let X=uh(...J),L=H;function Q(se){let re=D(se);if(!f(re))return;let Y=d(re),le=l.BASE.multiply(re).toAffine(),ue=o(le.x);if(ue===Bl)return;let pe=o(Y*o(L+ue*W));if(pe===Bl)return;let xe=(le.x===ue?0:2)|Number(le.y&Da),de=pe;return I&&p(pe)&&(de=m(pe),xe^=1),new b(ue,de,xe)}return{seed:X,k2sig:Q}}let N={lowS:e.lowS,prehash:!1},V={lowS:e.lowS,prehash:!1};function ee(B,P,E=N){let{seed:x,k2sig:A}=z(B,P,E),I=e;return d7(I.hash.outputLen,I.nByteLength,I.hmac)(x,A)}l.BASE._setWindowSize(8);function R(B,P,E,x=V){let A=B;if(P=zn("msgHash",P),E=zn("publicKey",E),"strict"in x)throw new Error("options.strict was renamed to lowS");let{lowS:I,prehash:M}=x,q,H;try{if(typeof A=="string"||kd(A))try{q=b.fromDER(A)}catch(Y){if(!(Y instanceof sh.Err))throw Y;q=b.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:Y,s:le}=A;q=new b(Y,le)}else throw new Error("PARSE");H=l.fromHex(E)}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;M&&(P=e.hash(P));let{r:W,s:J}=q,X=K(P),L=d(J),Q=o(X*L),se=o(W*L),re=l.BASE.multiplyAndAddUnsafe(H,Q,se)?.toAffine();return re?o(re.x)===W:!1}return{CURVE:e,getPublicKey:S,getSharedSecret:T,sign:ee,verify:R,ProjectivePoint:l,Signature:b,utils:w}}function Fle(t){return{hash:t,hmac:(e,...r)=>S7(t,e,p7(...r)),randomBytes:v6}}function A7(t,e){let r=n=>zle({...t,...Fle(n)});return Object.freeze({...r(e),create:r})}function Hle(t){let e=k7,r=BigInt(3),n=BigInt(6),i=BigInt(11),a=BigInt(22),s=BigInt(23),o=BigInt(44),d=BigInt(88),l=t*t*t%e,c=l*l*t%e,u=Pn(c,r,e)*c%e,f=Pn(u,r,e)*c%e,h=Pn(f,WR,e)*l%e,p=Pn(h,i,e)*h%e,m=Pn(p,a,e)*p%e,y=Pn(m,o,e)*m%e,b=Pn(y,d,e)*y%e,w=Pn(b,o,e)*m%e,S=Pn(w,r,e)*c%e,k=Pn(S,s,e)*p%e,T=Pn(k,n,e)*l%e,D=Pn(T,WR,e);if(!JR.eql(JR.sqr(D),t))throw new Error("Cannot find square root");return D}function Vle(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function _7(t,...e){if(!Vle(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function L9(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Wle(t,e){_7(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}function Jle(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function T7(t){return typeof t=="string"&&(t=Jle(t)),_7(t),t}function Yle(t){let e=n=>t().update(T7(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Xle(t=32){if(g2&&typeof g2.getRandomValues=="function")return g2.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Qle(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),a=BigInt(4294967295),s=Number(r>>i&a),o=Number(r&a),d=n?4:0,l=n?0:4;t.setUint32(e+d,s,n),t.setUint32(e+l,o,n)}function sue(t){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let i=Object.keys(n).sort(),a={};for(let s of i)a[s]=e(n[s]);return a}return n},r=e(t);return JSON.stringify(r)}function Ar(t){return aue(this,arguments,void 0,function*({jwk:e}){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);s7(n);let i=sue(n),a=it.string(i).toUint8Array(),s=yield I7.digest({data:a});return it.uint8Array(s).toBase64Url()})}function ch(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="EC"||typeof t.d!="string"||typeof t.x!="string")}function x6(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t)||"d"in t||t.kty!=="EC"||typeof t.x!="string")}function Ml(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="OKP"||typeof t.d!="string"||typeof t.x!="string")}function E6(t){return!(!t||typeof t!="object"||"d"in t||!("kty"in t&&"crv"in t&&"x"in t)||t.kty!=="OKP"||typeof t.x!="string")}function cue(t){if(!t||typeof t!="object")return!1;switch(t.kty){case"EC":case"OKP":case"RSA":return"d"in t;case"oct":return"k"in t;default:return!1}}function R7(t,e=!1){return e?{h:Number(t&d2),l:Number(t>>ZR&d2)}:{h:Number(t>>ZR&d2)|0,l:Number(t&d2)|0}}function hue(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){let{h:a,l:s}=R7(t[i],e);[r[i],n[i]]=[a,s]}return[r,n]}function Tue(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}function Lue(t){let e=P6(t);return hh(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function S6(t){let e=Lue(t),{Fp:r,n,prehash:i,hash:a,randomBytes:s,nByteLength:o,h:d}=e,l=l2<<BigInt(o*8)-qo,c=r.create,u=e.uvRatio||((E,x)=>{try{return{isValid:!0,value:r.sqrt(E*r.inv(x))}}catch{return{isValid:!1,value:bc}}}),f=e.adjustScalarBytes||(E=>E),h=e.domain||((E,x,A)=>{if(x.length||A)throw new Error("Contexts/pre-hash are not supported");return E}),p=E=>typeof E=="bigint"&&bc<E,m=(E,x)=>p(E)&&p(x)&&E<x,y=E=>E===bc||m(E,l);function b(E,x){if(m(E,x))return E;throw new Error(`Expected valid scalar < ${x}, got ${typeof E} ${E}`)}function w(E){return E===bc?E:b(E,n)}let S=new Map;function k(E){if(!(E instanceof T))throw new Error("ExtendedPoint expected")}class T{constructor(x,A,I,M){if(this.ex=x,this.ey=A,this.ez=I,this.et=M,!y(x))throw new Error("x required");if(!y(A))throw new Error("y required");if(!y(I))throw new Error("z required");if(!y(M))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(x){if(x instanceof T)throw new Error("extended point not allowed");let{x:A,y:I}=x||{};if(!y(A)||!y(I))throw new Error("invalid affine point");return new T(A,I,qo,c(A*I))}static normalizeZ(x){let A=r.invertBatch(x.map(I=>I.ez));return x.map((I,M)=>I.toAffine(A[M])).map(T.fromAffine)}_setWindowSize(x){this._WINDOW_SIZE=x,S.delete(this)}assertValidity(){let{a:x,d:A}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:I,ey:M,ez:q,et:H}=this,W=c(I*I),J=c(M*M),X=c(q*q),L=c(X*X),Q=c(W*x),se=c(X*c(Q+J)),re=c(L+c(A*c(W*J)));if(se!==re)throw new Error("bad point: equation left != right (1)");let Y=c(I*M),le=c(q*H);if(Y!==le)throw new Error("bad point: equation left != right (2)")}equals(x){k(x);let{ex:A,ey:I,ez:M}=this,{ex:q,ey:H,ez:W}=x,J=c(A*W),X=c(q*M),L=c(I*W),Q=c(H*M);return J===X&&L===Q}is0(){return this.equals(T.ZERO)}negate(){return new T(c(-this.ex),this.ey,this.ez,c(-this.et))}double(){let{a:x}=e,{ex:A,ey:I,ez:M}=this,q=c(A*A),H=c(I*I),W=c(l2*c(M*M)),J=c(x*q),X=A+I,L=c(c(X*X)-q-H),Q=J+H,se=Q-W,re=J-H,Y=c(L*se),le=c(Q*re),ue=c(L*re),pe=c(se*Q);return new T(Y,le,pe,ue)}add(x){k(x);let{a:A,d:I}=e,{ex:M,ey:q,ez:H,et:W}=this,{ex:J,ey:X,ez:L,et:Q}=x;if(A===BigInt(-1)){let Ct=c((q-M)*(X+J)),ke=c((q+M)*(X-J)),ot=c(ke-Ct);if(ot===bc)return this.double();let _t=c(H*l2*Q),Rt=c(W*l2*L),zt=Rt+_t,_=ke+Ct,O=Rt-_t,U=c(zt*ot),te=c(_*O),ce=c(zt*O),me=c(ot*_);return new T(U,te,me,ce)}let se=c(M*J),re=c(q*X),Y=c(W*I*Q),le=c(H*L),ue=c((M+q)*(J+X)-se-re),pe=le-Y,xe=le+Y,de=c(re-A*se),Pe=c(ue*pe),Ne=c(xe*de),He=c(ue*de),Je=c(pe*xe);return new T(Pe,Ne,Je,He)}subtract(x){return this.add(x.negate())}wNAF(x){return C.wNAFCached(this,S,x,T.normalizeZ)}multiply(x){let{p:A,f:I}=this.wNAF(b(x,n));return T.normalizeZ([A,I])[0]}multiplyUnsafe(x){let A=w(x);return A===bc?K:this.equals(K)||A===qo?this:this.equals(D)?this.wNAF(A).p:C.unsafeLadder(this,A)}isSmallOrder(){return this.multiplyUnsafe(d).is0()}isTorsionFree(){return C.unsafeLadder(this,n).is0()}toAffine(x){let{ex:A,ey:I,ez:M}=this,q=this.is0();x==null&&(x=q?Nue:r.inv(M));let H=c(A*x),W=c(I*x),J=c(M*x);if(q)return{x:bc,y:qo};if(J!==qo)throw new Error("invZ was invalid");return{x:H,y:W}}clearCofactor(){let{h:x}=e;return x===qo?this:this.multiplyUnsafe(x)}static fromHex(x,A=!1){let{d:I,a:M}=e,q=r.BYTES;x=zn("pointHex",x,q);let H=x.slice(),W=x[q-1];H[q-1]=W&-129;let J=vf(H);J===bc||(A?b(J,l):b(J,r.ORDER));let X=c(J*J),L=c(X-qo),Q=c(I*X-M),{isValid:se,value:re}=u(L,Q);if(!se)throw new Error("Point.fromHex: invalid y coordinate");let Y=(re&qo)===qo,le=(W&128)!==0;if(!A&&re===bc&&le)throw new Error("Point.fromHex: x=0 and x_0=1");return le!==Y&&(re=c(-re)),T.fromAffine({x:re,y:J})}static fromPrivateKey(x){return N(x).point}toRawBytes(){let{x,y:A}=this.toAffine(),I=qy(A,r.BYTES);return I[I.length-1]|=x&qo?128:0,I}toHex(){return lh(this.toRawBytes())}}T.BASE=new T(e.Gx,e.Gy,qo,c(e.Gx*e.Gy)),T.ZERO=new T(bc,qo,qo,bc);let{BASE:D,ZERO:K}=T,C=x7(T,o*8);function G(E){return Zr(E,n)}function z(E){return G(vf(E))}function N(E){let x=o;E=zn("private key",E,x);let A=zn("hashed private key",a(E),2*x),I=f(A.slice(0,x)),M=A.slice(x,2*x),q=z(I),H=D.multiply(q),W=H.toRawBytes();return{head:I,prefix:M,scalar:q,point:H,pointBytes:W}}function V(E){return N(E).pointBytes}function ee(E=new Uint8Array,...x){let A=uh(...x);return z(a(h(A,zn("context",E),!!i)))}function R(E,x,A={}){E=zn("message",E),i&&(E=i(E));let{prefix:I,scalar:M,pointBytes:q}=N(x),H=ee(A.context,I,E),W=D.multiply(H).toRawBytes(),J=ee(A.context,W,q,E),X=G(H+J*M);w(X);let L=uh(W,qy(X,r.BYTES));return zn("result",L,o*2)}let B=Uue;function P(E,x,A,I=B){let{context:M,zip215:q}=I,H=r.BYTES;E=zn("signature",E,2*H),x=zn("message",x),i&&(x=i(x));let W=vf(E.slice(H,2*H)),J,X,L;try{J=T.fromHex(A,q),X=T.fromHex(E.slice(0,H),q),L=D.multiplyUnsafe(W)}catch{return!1}if(!q&&J.isSmallOrder())return!1;let Q=ee(M,X.toRawBytes(),J.toRawBytes(),x);return X.add(J.multiplyUnsafe(Q)).subtract(L).clearCofactor().equals(T.ZERO)}return D._setWindowSize(8),{CURVE:e,getPublicKey:V,sign:R,verify:P,ExtendedPoint:T,utils:{getExtendedPublicKey:N,randomPrivateKey:()=>s(r.BYTES),precompute(E=8,x=T.BASE){return x._setWindowSize(E),x.multiply(BigInt(3)),x}}}}function que(t){return hh(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function zue(t){let e=que(t),{P:r}=e,n=S=>Zr(S,r),i=e.montgomeryBits,a=Math.ceil(i/8),s=e.nByteLength,o=e.adjustScalarBytes||(S=>S),d=e.powPminus2||(S=>w7(S,r-BigInt(2),r));function l(S,k,T){let D=n(S*(k-T));return k=n(k-D),T=n(T+D),[k,T]}function c(S){if(typeof S=="bigint"&&wv<=S&&S<r)return S;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let u=(e.a-BigInt(2))/BigInt(4);function f(S,k){let T=c(S),D=c(k),K=T,C=KR,G=wv,z=T,N=KR,V=wv,ee;for(let B=BigInt(i-1);B>=wv;B--){let P=D>>B&KR;V^=P,ee=l(V,C,z),C=ee[0],z=ee[1],ee=l(V,G,N),G=ee[0],N=ee[1],V=P;let E=C+G,x=n(E*E),A=C-G,I=n(A*A),M=x-I,q=z+N,H=z-N,W=n(H*E),J=n(q*A),X=W+J,L=W-J;z=n(X*X),N=n(K*n(L*L)),C=n(x*I),G=n(M*(x+n(u*M)))}ee=l(V,C,z),C=ee[0],z=ee[1],ee=l(V,G,N),G=ee[0],N=ee[1];let R=d(G);return n(C*R)}function h(S){return qy(n(S),a)}function p(S){let k=zn("u coordinate",S,a);return s===32&&(k[31]&=127),vf(k)}function m(S){let k=zn("scalar",S),T=k.length;if(T!==a&&T!==s)throw new Error(`Expected ${a} or ${s} bytes, got ${T}`);return vf(o(k))}function y(S,k){let T=p(k),D=m(S),K=f(T,D);if(K===wv)throw new Error("Invalid private or public key received");return h(K)}let b=h(e.Gu);function w(S){return y(S,b)}return{scalarMult:y,scalarMultBase:w,getSharedSecret:(S,k)=>y(S,k),getPublicKey:S=>w(S),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:b}}function $7(t){let e=zv,r=t*t%e*t%e,n=Pn(r,YR,e)*r%e,i=Pn(n,Fue,e)*t%e,a=Pn(i,Gue,e)*i%e,s=Pn(a,G9,e)*a%e,o=Pn(s,Hue,e)*s%e,d=Pn(o,Vue,e)*o%e,l=Pn(d,H9,e)*d%e,c=Pn(l,H9,e)*d%e,u=Pn(c,G9,e)*a%e;return{pow_p_5_8:Pn(u,YR,e)*t%e,b2:r}}function B7(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Wue(t,e){let r=zv,n=Zr(e*e*e,r),i=Zr(n*n*e,r),a=$7(t*i).pow_p_5_8,s=Zr(t*n*a,r),o=Zr(e*s*s,r),d=s,l=Zr(s*F9,r),c=o===t,u=o===Zr(-t,r),f=o===Zr(-t*F9,r);return c&&(s=d),(u||f)&&(s=l),Dle(s,r)&&(s=Zr(-s,r)),{isValid:c||u,value:s}}function O7(t,e,r){if(e.length>255)throw new Error("Context is too big");return p7(f7("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}function Jue(t){let{y:e}=eh.ExtendedPoint.fromHex(t),r=BigInt(1);return Ba.toBytes(Ba.create((r+e)*Ba.inv(r-e)))}function Zue(t){let e=Fv.hash(t.subarray(0,32));return Fv.adjustScalarBytes(e).subarray(0,32)}function ofe(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;return e==="string"||e==="number"||e==="bigint"||e==="symbol"?e:e==="function"?"Function":Array.isArray(t)?"Array":t instanceof Uint8Array?"Uint8Array":t.constructor===Object?"Object":afe(t)||"Object"}function afe(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(sfe.includes(e))return e}function N2(t){return Zv&&globalThis.Buffer.isBuffer(t)}function j7(t){return t instanceof Uint8Array?N2(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}function M7(t,e){if(N2(t)&&N2(e))return t.compare(e);for(let r=0;r<t.length;r++)if(t[r]!==e[r])return t[r]<e[r]?-1:1;return 0}function V9(t){let e=[],r=0;for(let n=0;n<t.length;n++){let i=t.charCodeAt(n);i<128?e[r++]=i:i<2048?(e[r++]=i>>6|192,e[r++]=i&63|128):(i&64512)===55296&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++n)&1023),e[r++]=i>>18|240,e[r++]=i>>12&63|128,e[r++]=i>>6&63|128,e[r++]=i&63|128):(i>=55296&&i<=57343&&(i=65533),e[r++]=i>>12|224,e[r++]=i>>6&63|128,e[r++]=i&63|128)}return e}function Vy(t,e,r){if(t.length-e<r)throw new Error(`${xn} not enough data for type`)}function mh(t,e,r){Vy(t,e,1);let n=t[e];if(r.strict===!0&&n<es[0])throw new Error(`${xn} integer encoded in more bytes than necessary (strict decode)`);return n}function yh(t,e,r){Vy(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<es[1])throw new Error(`${xn} integer encoded in more bytes than necessary (strict decode)`);return n}function gh(t,e,r){Vy(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<es[2])throw new Error(`${xn} integer encoded in more bytes than necessary (strict decode)`);return n}function wh(t,e,r){Vy(t,e,8);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],i=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],a=(BigInt(n)<<BigInt(32))+BigInt(i);if(r.strict===!0&&a<es[3])throw new Error(`${xn} integer encoded in more bytes than necessary (strict decode)`);if(a<=Number.MAX_SAFE_INTEGER)return Number(a);if(r.allowBigInt===!0)return a;throw new Error(`${xn} integers outside of the safe integer range are not supported`)}function gfe(t,e,r,n){return new tt(Se.uint,mh(t,e+1,n),2)}function wfe(t,e,r,n){return new tt(Se.uint,yh(t,e+1,n),3)}function vfe(t,e,r,n){return new tt(Se.uint,gh(t,e+1,n),5)}function bfe(t,e,r,n){return new tt(Se.uint,wh(t,e+1,n),9)}function vh(t,e){return ja(t,0,e.value)}function ja(t,e,r){if(r<es[0]){let n=Number(r);t.push([e|n])}else if(r<es[1]){let n=Number(r);t.push([e|24,n])}else if(r<es[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<es[3]){let n=Number(r);t.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(r);if(n<es[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,t.push(i)}else throw new Error(`${xn} encountered BigInt larger than allowable range`)}}function Pfe(t,e,r,n){return new tt(Se.negint,-1-mh(t,e+1,n),2)}function xfe(t,e,r,n){return new tt(Se.negint,-1-yh(t,e+1,n),3)}function Efe(t,e,r,n){return new tt(Se.negint,-1-gh(t,e+1,n),5)}function Sfe(t,e,r,n){let i=wh(t,e+1,n);if(typeof i!="bigint"){let a=-1-i;if(a>=Number.MIN_SAFE_INTEGER)return new tt(Se.negint,a,9)}if(n.allowBigInt!==!0)throw new Error(`${xn} integers outside of the safe integer range are not supported`);return new tt(Se.negint,A6-BigInt(i),9)}function k6(t,e){let r=e.value,n=typeof r=="bigint"?r*A6-U7:r*-1-1;ja(t,e.type.majorEncoded,n)}function Xv(t,e,r,n){Vy(t,e,r+n);let i=t.slice(e+r,e+r+n);return new tt(Se.bytes,i,r+n)}function Afe(t,e,r,n){return Xv(t,e,1,r)}function kfe(t,e,r,n){return Xv(t,e,2,mh(t,e+1,n))}function _fe(t,e,r,n){return Xv(t,e,3,yh(t,e+1,n))}function Tfe(t,e,r,n){return Xv(t,e,5,gh(t,e+1,n))}function Ife(t,e,r,n){let i=wh(t,e+1,n);if(typeof i=="bigint")throw new Error(`${xn} 64-bit integer bytes lengths not supported`);return Xv(t,e,9,i)}function U2(t){return t.encodedBytes===void 0&&(t.encodedBytes=Se.equals(t.type,Se.string)?ufe(t.value):t.value),t.encodedBytes}function X2(t,e){let r=U2(e);ja(t,e.type.majorEncoded,r.length),t.push(r)}function Dfe(t,e){return t.length<e.length?-1:t.length>e.length?1:M7(t,e)}function Cfe(t,e,r){if(r-e<Rfe){let n="";for(let i=e;i<r;i++){let a=t[i];if(a&128)return W9.decode(t.subarray(e,r));n+=String.fromCharCode(a)}return n}return W9.decode(t.subarray(e,r))}function Qv(t,e,r,n,i){let a=r+n;Vy(t,e,a);let s=new tt(Se.string,Cfe(t,e+r,e+a),a);return i.retainStringBytes===!0&&(s.byteValue=t.slice(e+r,e+a)),s}function $fe(t,e,r,n){return Qv(t,e,1,r,n)}function Bfe(t,e,r,n){return Qv(t,e,2,mh(t,e+1,n),n)}function Ofe(t,e,r,n){return Qv(t,e,3,yh(t,e+1,n),n)}function jfe(t,e,r,n){return Qv(t,e,5,gh(t,e+1,n),n)}function Mfe(t,e,r,n){let i=wh(t,e+1,n);if(typeof i=="bigint")throw new Error(`${xn} 64-bit integer string lengths not supported`);return Qv(t,e,9,i,n)}function Wy(t,e,r,n){return new tt(Se.array,n,r)}function Nfe(t,e,r,n){return Wy(t,e,1,r)}function Ufe(t,e,r,n){return Wy(t,e,2,mh(t,e+1,n))}function Lfe(t,e,r,n){return Wy(t,e,3,yh(t,e+1,n))}function qfe(t,e,r,n){return Wy(t,e,5,gh(t,e+1,n))}function zfe(t,e,r,n){let i=wh(t,e+1,n);if(typeof i=="bigint")throw new Error(`${xn} 64-bit integer array lengths not supported`);return Wy(t,e,9,i)}function Ffe(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${xn} indefinite length items not allowed`);return Wy(t,e,1,1/0)}function _6(t,e){ja(t,Se.array.majorEncoded,e.value)}function Jy(t,e,r,n){return new tt(Se.map,n,r)}function Gfe(t,e,r,n){return Jy(t,e,1,r)}function Hfe(t,e,r,n){return Jy(t,e,2,mh(t,e+1,n))}function Vfe(t,e,r,n){return Jy(t,e,3,yh(t,e+1,n))}function Wfe(t,e,r,n){return Jy(t,e,5,gh(t,e+1,n))}function Jfe(t,e,r,n){let i=wh(t,e+1,n);if(typeof i=="bigint")throw new Error(`${xn} 64-bit integer map lengths not supported`);return Jy(t,e,9,i)}function Zfe(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${xn} indefinite length items not allowed`);return Jy(t,e,1,1/0)}function T6(t,e){ja(t,Se.map.majorEncoded,e.value)}function Yfe(t,e,r,n){return new tt(Se.tag,r,1)}function Xfe(t,e,r,n){return new tt(Se.tag,mh(t,e+1,n),2)}function Qfe(t,e,r,n){return new tt(Se.tag,yh(t,e+1,n),3)}function epe(t,e,r,n){return new tt(Se.tag,gh(t,e+1,n),5)}function tpe(t,e,r,n){return new tt(Se.tag,wh(t,e+1,n),9)}function I6(t,e){ja(t,Se.tag.majorEncoded,e.value)}function rpe(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${xn} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new tt(Se.null,null,1):new tt(Se.undefined,void 0,1)}function npe(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${xn} indefinite length items not allowed`);return new tt(Se.break,void 0,1)}function D6(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${xn} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${xn} Infinity values are not supported`)}return new tt(Se.float,t,e)}function ipe(t,e,r,n){return D6(C6(t,e+1),3,n)}function spe(t,e,r,n){return D6($6(t,e+1),5,n)}function ope(t,e,r,n){return D6(W7(t,e+1),9,n)}function R6(t,e,r){let n=e.value;if(n===!1)t.push([Se.float.majorEncoded|L7]);else if(n===!0)t.push([Se.float.majorEncoded|q7]);else if(n===null)t.push([Se.float.majorEncoded|z7]);else if(n===void 0)t.push([Se.float.majorEncoded|F7]);else{let i,a=!1;(!r||r.float64!==!0)&&(H7(n),i=C6(Pc,1),n===i||Number.isNaN(n)?(Pc[0]=249,t.push(Pc.slice(0,3)),a=!0):(V7(n),i=$6(Pc,1),n===i&&(Pc[0]=250,t.push(Pc.slice(0,5)),a=!0))),a||(ape(n),i=W7(Pc,1),Pc[0]=251,t.push(Pc.slice(0,9)))}}function H7(t){if(t===1/0)Ta.setUint16(0,31744,!1);else if(t===-1/0)Ta.setUint16(0,64512,!1);else if(Number.isNaN(t))Ta.setUint16(0,32256,!1);else{Ta.setFloat32(0,t);let e=Ta.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)Ta.setUint16(0,31744,!1);else if(r===0)Ta.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let i=r-127;i<-24?Ta.setUint16(0,0):i<-14?Ta.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Ta.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function C6(t,e){if(t.length-e<2)throw new Error(`${xn} not enough data for float16`);let r=(t[e]<<8)+t[e+1];if(r===31744)return 1/0;if(r===64512)return-1/0;if(r===32256)return NaN;let n=r>>10&31,i=r&1023,a;return n===0?a=i*2**-24:n!==31?a=(i+1024)*2**(n-25):a=i===0?1/0:NaN,r&32768?-a:a}function V7(t){Ta.setFloat32(0,t,!1)}function $6(t,e){if(t.length-e<4)throw new Error(`${xn} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function ape(t){Ta.setFloat64(0,t,!1)}function W7(t,e){if(t.length-e<8)throw new Error(`${xn} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}function mr(t,e,r){throw new Error(`${xn} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function Q2(t){return()=>{throw new Error(`${xn} ${t}`)}}function cpe(t){switch(t.type){case Se.false:return Cl([244]);case Se.true:return Cl([245]);case Se.null:return Cl([246]);case Se.bytes:return t.value.length?void 0:Cl([64]);case Se.string:return t.value===""?Cl([96]):void 0;case Se.array:return t.value===0?Cl([128]):void 0;case Se.map:return t.value===0?Cl([160]):void 0;case Se.uint:return t.value<24?Cl([Number(t.value)]):void 0;case Se.negint:if(t.value>=-24)return Cl([31-Number(t.value)])}}function lpe(){let t=[];return t[Se.uint.major]=vh,t[Se.negint.major]=k6,t[Se.bytes.major]=X2,t[Se.string.major]=Kfe,t[Se.array.major]=_6,t[Se.map.major]=T6,t[Se.tag.major]=I6,t[Se.float.major]=R6,t}function w2(t,e={},r){let n=ofe(t),i=e&&e.typeEncoders&&e.typeEncoders[n]||Pf[n];if(typeof i=="function"){let s=i(t,n,e,r);if(s!=null)return s}let a=Pf[n];if(!a)throw new Error(`${N7} unsupported type: ${n}`);return a(t,n,e,r)}function ppe(t,e){e.mapSorter&&t.sort(e.mapSorter)}function hpe(t,e){if(t[0]instanceof tt&&e[0]instanceof tt){let r=t[0],n=e[0];return r._keyBytes||(r._keyBytes=Z9(r.value)),n._keyBytes||(n._keyBytes=Z9(n.value)),M7(r._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Z9(t){return mpe(t,upe,dpe)}function Z7(t,e,r,n){if(Array.isArray(e))for(let i of e)Z7(t,i,r,n);else r[e.type.major](t,e,n)}function mpe(t,e,r,n){let i=n instanceof Uint8Array,a=i?new yfe(n):fpe,s=w2(t,r);if(!Array.isArray(s)&&r.quickEncodeToken){let o=r.quickEncodeToken(s);if(o)return i?(a.push(o),a.toBytes()):o;let d=e[s.type.major];if(d.encodedSize){let l=d.encodedSize(s,r);if(i||(a=new K7(l)),d(a,s,r),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return i?a.toBytes():j7(a.chunks[0])}}return a.reset(),Z7(a,s,e,r),a.toBytes(!0)}function Gs(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function ype({didDocument:t,id:e,type:r}){return t?.service?.filter(n=>!(e&&n.id!==e||r&&n.type!==r))??[]}async function gpe({didDocument:t,publicKeyJwk:e,publicKeyMultibase:r}){let n=eE({didDocument:t});for(let i of n)if(e&&i.publicKeyJwk){if(await Ar({jwk:e})===await Ar({jwk:i.publicKeyJwk}))return i}else if(r&&i.publicKeyMultibase&&r===i.publicKeyMultibase)return i;return null}function eE({didDocument:t}){if(!t)throw new TypeError("Required parameter missing: 'didDocument'");let e=[];return e.push(...t.verificationMethod?.filter(L2)??[]),Object.keys(J2).forEach(r=>{e.push(...t[r]?.filter(L2)??[])}),e}function Y7({didDocument:t}){let e=eE({didDocument:t}).map(r=>r.type);return[...new Set(e)]}function X7({didDocument:t,methodId:e}){let r=[];return Object.keys(J2).forEach(n=>{if(Array.isArray(t[n])){let i=t[n],a=Gs(e);i.some(s=>{let o=Gs(s)===a,d=L2(s)&&Gs(s.id)===a;return o||d})&&r.push(n)}}),r}function Q7(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function wpe(t){return!(!Q7(t)||t.type!=="DecentralizedWebNode")}function L2(t){return!(!t||typeof t!="object"||t===null||!("id"in t&&"type"in t&&"controller"in t)||typeof t.id!="string"||typeof t.type!="string"||typeof t.controller!="string")}function bh(t){return!(!t||typeof t!="object"||t===null)&&"uri"in t&&"document"in t&&"metadata"in t&&(!("keyManager"in t)||t.keyManager===void 0)}function ez({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=Oa.addPrefix({code:e,data:t,name:r}),i=it.uint8Array(n).toBase58Btc();return it.base58Btc(i).toMultibase()}function tz({multibaseKeyId:t}){try{let e=it.multibase(t).toBase58Btc(),r=it.base58Btc(e).toUint8Array(),{code:n,data:i,name:a}=Oa.removePrefix({prefixedData:r});return{keyBytes:i,multicodecCode:n,multicodecName:a}}catch{throw new rt("invalidDid",`Invalid multibase identifier: ${t}`)}}function tb(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function az(t){return ArrayBuffer.isView(t)?"arraybufferview":Array.isArray(t)?"array":t instanceof Number?"number":t instanceof Boolean?"boolean":t instanceof Set?"set":t instanceof Map?"map":t instanceof String?"string":t instanceof ArrayBuffer?"arraybuffer":typeof t}function vr(t,e,r){let n=[],i=null;return vr._encode(n,t),i=bpe(n),vr.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,r),e):i}function lz(t,e,r){let n=0,i=1;for(let a=e;a<r;a++){let s=t[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 bt(t,e,r,n){return t==null||t.length===0?null:(typeof e!="number"&&n==null&&(n=e,e=void 0),typeof r!="number"&&n==null&&(n=r,r=void 0),bt.position=0,bt.encoding=n||null,bt.data=ArrayBuffer.isView(t)?new Uint8Array(t.slice(e,r)):Kl(t),bt.bytes=bt.data.length,bt.next())}function Dpe(t){let e=2;for(let r of t)e+=rE(r);return e}function Rpe(t){let e=2;for(let[r,n]of t){let i=Kl(r).byteLength;e+=tb(i)+1+i,e+=rE(n)}return e}function Cpe(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let i=Kl(r[n]).byteLength;e+=tb(i)+1+i,e+=rE(t[r[n]])}return e}function $pe(t){let e=Kl(t).byteLength;return tb(e)+1+e}function Bpe(t){let e=t.byteLength-t.byteOffset;return tb(e)+1+e}function rE(t){if(t==null)return 0;let e=az(t);switch(e){case"arraybufferview":return Bpe(t);case"string":return $pe(t);case"array":case"set":return Dpe(t);case"number":return 1+tb(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return Cpe(t);case"map":return Rpe(t);default:throw new TypeError(`Unsupported value of type "${e}"`)}}function pz(t){if(Ad.isFormat(t))return Ad.size;if(bf.isFormat(t))return bf.size;throw Error(`Invalid ip address: ${t}`)}function Kpe(t){return pz(t)===Ad.size?1:2}function Npe(t,e,r){r=~~r;let n=pz(t);return typeof e=="function"&&(e=e(r+n)),n===Ad.size?Ad.encode(t,e,r):bf.encode(t,e,r)}function Upe(t,e,r){if(e=~~e,r=r||t.length-e,r===Ad.size)return Ad.decode(t,e,r);if(r===bf.size)return bf.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${Ad.size} for v4 or ${bf.size} for v6.`)}function nE(t){switch(t){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_"+t}function Gv(t){switch(t.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 t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}function Lpe(t){switch(t){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_"+t}function qpe(t){switch(t){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_"+t}function hz(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t}function mz(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}function zpe(t){switch(t){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 t<0?null:`OPTION_${t}`}function dq(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.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=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}function yz(t){let e=0,r=t.length;for(let n=0;n<r;n+=1){let i=t.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===r||i>=56320||(t.charCodeAt(a)&64512)!==56320?e+=3:(n=a,e+=4)}}return e}function Hv(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(yz(t)+r));let i=r;for(let a=0;a<n;a+=1){let s=t.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 d=t.charCodeAt(o);(d&64512)!==56320?(e[i++]=239,e[i++]=191,e[i++]=189):(a=o,s=65536|(s&1023)<<10|d&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 Hv.bytes=i-r,e}function rb(t,e,r){let n="";e==null&&(e=0),r==null&&(r=t.length);for(let i=e;i<r;){let a=t[i++],s;if(a<=128)s=a;else if(a>191&&a<224)s=(a&31)<<6|t[i++]&63;else if(a>239&&a<365){s=((a&7)<<18|(t[i++]&63)<<12|(t[i++]&63)<<6|t[i++]&63)-65536;let o=55296|s>>10&1023;n+=String.fromCharCode(o),s=56320|s&1023}else s=(a&15)<<12|(t[i++]&63)<<6|t[i++]&63;n+=String.fromCharCode(s)}return rb.bytes=r-e,n}function xf(t){return typeof t=="string"?yz(t):t.byteLength}function M6(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):Hv(t)}function K6(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return Hv(e,t,r),Hv.bytes}function Fpe(t,e,r){let n="";for(let i=e;i<r;){let a=t[i++];n+=gz[a]}return n}function lq(t){return t.length>>>1}function Gpe(t,e,r,n){let i=0;for(;r<n;){let a=e.substr(i,2),s=kv[a];if(s===void 0)return;t[r++]=s,i+=2}return t}function Vo(t,e,r,n,i){return r<0&&(n-=r,r=0),n<0&&(n=0),i<0?new Uint8Array(0):r>=e.length||n>=i?0:Jpe(t,e,r,n,i)}function Jpe(t,e,r,n,i){i-n>e.length-r&&(i=n+e.length-r);let a=i-n,s=t.length-n;return a>s&&(a=s),(n!==0||i<t.length)&&(t=new Uint8Array(t.buffer,t.byteOffset+n,a)),e.set(t,r),a}function Fr({bytes:t=0,encode:e,decode:r,encodingLength:n}){return e.bytes=t,r.bytes=t,{encode:e,decode:r,encodingLength:n||(()=>t)}}function e6(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}function UR(t){switch(t.toUpperCase()){case"A":return vz;case"PTR":return Ky;case"CNAME":return Ky;case"DNAME":return Ky;case"TXT":return x2;case"NULL":return E2;case"AAAA":return _2;case"SRV":return A2;case"HINFO":return S2;case"CAA":return gf;case"NS":return b2;case"SOA":return P2;case"MX":return k2;case"OPT":return wf;case"DNSKEY":return Sd;case"RRSIG":return _v;case"RP":return Tv;case"NSEC":return Iv;case"NSEC3":return Dv;case"SSHFP":return Oy;case"DS":return Rv}return v2}function q2(t,e){if(t.questions)throw new Error("Only one .question object expected instead of a .questions array!");let r=Object.assign({type:e},t);return r.question&&(r.questions=[r.question],delete r.question),r}function bz(t){let e=G2(t),r=new Uint8Array(2+e.byteLength);return st(r,e.byteLength),Vo(e,r,2,0,e.length),bz.bytes=r.byteLength,r}function Pz(t){let e=Ut(t,0);if(t.byteLength<e+2)return null;let r=t6(t.slice(2));return Pz.bytes=t6.bytes,r}function jy(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function Cv(t,e,r,n){for(let i=0;i<t.length;i++)e.encode(t[i],r,n),n+=e.encode.bytes;return n}function u2(t,e,r,n){for(let i=0;i<t.length;i++)t[i]=e.decode(r,n),n+=e.decode.bytes;return n}function xz(t,e){let r=it.uint8Array(t).toBase32Z();return new URL(r,e).href}async function the({gatewayUri:t,publicKeyBytes:e}){let r=it.uint8Array(e).toBase32Z(),n=xz(e,t),i;try{if(i=await fetch(n,{method:"GET",signal:AbortSignal.timeout(3e4)}),!i.ok)throw new rt("notFound",`Pkarr record not found for: ${r}`)}catch(s){throw s instanceof rt?s:new rt("internalError",`Failed to fetch Pkarr record: ${s.message}`)}let a=await i.arrayBuffer();if(!a)throw new rt("notFound",`Pkarr record not found for: ${r}`);if(a.byteLength<72)throw new rt("invalidDidDocumentLength",`Pkarr response must be at least 72 bytes but got: ${a.byteLength}`);if(a.byteLength>1072)throw new rt("invalidDidDocumentLength",`Pkarr response exceeds 1000 byte limit: ${a.byteLength}`);return{k:e,seq:Number(new DataView(a).getBigUint64(64)),sig:new Uint8Array(a,0,64),v:new Uint8Array(a,72)}}async function rhe({gatewayUri:t,bep44Message:e}){let r=it.uint8Array(e.k).toBase32Z(),n=xz(e.k,t),i=new Uint8Array(e.v.length+72);i.set(e.sig,0),new DataView(i.buffer).setBigUint64(e.sig.length,BigInt(e.seq)),i.set(e.v,e.sig.length+8);let a;try{a=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:i,signal:AbortSignal.timeout(3e4)})}catch(s){throw new rt("internalError",`Failed to put Pkarr record for identifier ${r}: ${s.message}`)}return a.ok}async function nhe({dnsPacket:t,publicKeyBytes:e,signer:r}){let n=Math.ceil(Date.now()/1e3),i=G2(t),a=fz.encode({seq:n,v:i}).subarray(1,-1);if(a.length>1e3)throw new rt("invalidDidDocumentLength",`DNS packet exceeds the 1000 byte maximum size: ${a.length} bytes`);let s=await r.sign({data:new Uint8Array(a)});return{k:e,seq:n,sig:s,v:i}}async function ihe({bep44Message:t}){let e=await Qi.bytesToPublicKey({publicKeyBytes:t.k}),r=fz.encode({seq:t.seq,v:t.v}).subarray(1,-1);if(!await Qi.verify({key:e,signature:t.sig,data:new Uint8Array(r)}))throw new rt("invalidSignature","Invalid signature for DHT BEP44 message");return t6(t.v)}async function Sz({didUri:t}){let e=N6({didUri:t});return await Qi.bytesToPublicKey({publicKeyBytes:e})}function N6({didUri:t}){let e=Fn.parse(t);if(!e)throw new rt("invalidDid",`Invalid DID URI: ${t}`);if(e.method!==Ez)throw new rt("methodNotSupported",`Method not supported: ${e.method}`);let r;try{r=it.base32Z(e.id).toUint8Array()}catch{throw new rt("invalidPublicKey","Failed to decode method-specific identifier")}if(r.length!==32)throw new rt("invalidPublicKeyLength",`Invalid public key length: ${r.length}`);return r}async function she({identityKey:t}){let e=await Qi.publicKeyToBytes({publicKey:t}),r=it.uint8Array(e).toBase32Z();return`did:${Ez}:${r}`}function U6(t){let e={Ed25519:Qi,"P-256":{publicKeyToBytes:async({publicKey:r})=>{let n=await ws.publicKeyToBytes({publicKey:r});return await ws.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:ws.bytesToPublicKey,privateKeyToBytes:ws.privateKeyToBytes,bytesToPrivateKey:ws.bytesToPrivateKey},secp256k1:{publicKeyToBytes:async({publicKey:r})=>{let n=await Xi.publicKeyToBytes({publicKey:r});return await Xi.compressPublicKey({publicKeyBytes:n})},bytesToPublicKey:Xi.bytesToPublicKey,privateKeyToBytes:Xi.privateKeyToBytes,bytesToPrivateKey:Xi.bytesToPrivateKey},X25519:Dy}[t];if(!e)throw new rt("invalidPublicKeyType",`Unsupported curve: ${t}`);return e}async function Az({newDid:t,previousDidProof:e}){let r=await Sz({didUri:e.previousDid}),n=N6({didUri:t}),i=it.base64Url(e.signature).toUint8Array();if(!await Qi.verify({key:r,data:n,signature:i}))throw new rt("invalidPreviousDidProof","The previous DID proof is invalid.")}function Vv(t){if(typeof t=="string")return t;if(t instanceof Uint8Array)return it.uint8Array(t).toString();if(Array.isArray(t))return t.map(e=>Vv(e)).join("");throw new rt("internalError","Pkarr returned DNS TXT record with invalid data type")}function $v(t){return Vv(t).split(T2).reduce((e,r)=>{let[n,i]=r.split("=");return e[n]=i,e},{})}function Tz(t){if(t.length<=255)return t;let e=[];for(let r=0;r<t.length;r+=255)e.push(t.slice(r,r+255));return e}async function ahe({didUri:t,dnsPacket:e}){let r={id:t},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=Vv(a.data);r.alsoKnownAs=o.split(Fs);break}case s.startsWith("cnt"):{let o=Vv(a.data);r.controller=o.includes(Fs)?o.split(Fs):o;break}case s.startsWith("k"):{let{id:o,t:d,k:l,c,a:u}=$v(a.data),f=it.base64Url(l).toUint8Array(),h=O6[Number(d)],p=await U6(h).bytesToPublicKey({publicKeyBytes:f});p.alg=u||_z[Number(d)];let m=s==="k0"?"0":o!==void 0?o:await Ar({jwk:p});r.verificationMethod??=[];let y=`${t}#${m}`;r.verificationMethod.push({id:y,type:"JsonWebKey",controller:c??t,publicKeyJwk:p}),i.set(s,y);break}case s.startsWith("s"):{let{id:o,t:d,se:l,...c}=$v(a.data),u=l.includes(Fs)?l.split(Fs):[l],f=Object.fromEntries(Object.entries(c).map(([h,p])=>[h,p.includes(Fs)?p.split(Fs):p]));r.service??=[],r.service.push({...f,id:`${t}#${o}`,type:d,serviceEndpoint:u});break}case s.startsWith("typ"):{let{id:o}=$v(a.data);n.types=o.split(Fs).map(d=>Number(d));break}case s.startsWith("did"):{let o=h=>h.split(Fs).map(p=>i.get(p)).filter(p=>typeof p=="string"),{auth:d,asm:l,del:c,inv:u,agm:f}=$v(a.data);d&&(r.authentication=o(d)),l&&(r.assertionMethod=o(l)),c&&(r.capabilityDelegation=o(c)),u&&(r.capabilityInvocation=o(u)),f&&(r.keyAgreement=o(f));break}}}return{didDocument:r,didDocumentMetadata:n,didResolutionMetadata:{}}}async function che({didDocument:t,didMetadata:e,authoritativeGatewayUris:r,previousDidProof:n}){let i=[],a=[],s=new Map,o=[],d=[];if(n!==void 0){let{signature:c,previousDid:u}=n;await Az({newDid:t.id,previousDidProof:n}),i.push({type:"TXT",name:"_prv._did.",ttl:pf,data:`id=${u};s=${c}`})}if(t.alsoKnownAs&&i.push({type:"TXT",name:"_aka._did.",ttl:pf,data:t.alsoKnownAs.join(Fs)}),t.controller){let c=Array.isArray(t.controller)?t.controller.join(Fs):t.controller;i.push({type:"TXT",name:"_cnt._did.",ttl:pf,data:c})}for(let[c,u]of t.verificationMethod?.entries()??[]){let f=`k${c}`;d.push(f);let h=u.id.split("#").pop();s.set(h,f);let p=u.publicKeyJwk;if(!(p?.crv&&p.crv in kz))throw new rt("invalidPublicKeyType",`Verification method '${u.id}' contains an unsupported key type: ${p?.crv??"undefined"}`);let m=O6[p.crv],y=await U6(p.crv).publicKeyToBytes({publicKey:p}),b=it.uint8Array(y).toBase64Url(),w=[`t=${m}`,`k=${b}`];h!=="0"&&await Ar({jwk:p})!==h&&w.unshift(`id=${h}`),p.alg!==_z[m]&&w.push(`a=${p.alg}`),u.controller!==t.id&&w.push(`c=${u.controller}`),i.push({type:"TXT",name:`_${f}._did.`,ttl:pf,data:w.join(T2)})}t.service?.forEach((c,u)=>{let f=`s${u}`;o.push(f);let{id:h,type:p,serviceEndpoint:m,...y}=c;h=Gs(h),m=Array.isArray(m)?m.join(","):m;let b=Object.entries({id:h,t:p,se:m,...y}).map(([S,k])=>`${S}=${k}`).join(T2),w=Tz(b);i.push({type:"TXT",name:`_${f}._did.`,ttl:pf,data:w})});let l=[`v=${ohe}`];if(d.length&&l.push(`vm=${d.join(Fs)}`),Object.keys(J2).forEach(c=>{let u=t[c]?.map(f=>s.get(f.split("#").pop()));if(u){let f=iz[c];l.push(`${f}=${u.join(Fs)}`)}}),o.length&&l.push(`svc=${o.join(Fs)}`),e.types?.length){let c=e.types.map(u=>typeof u=="string"?nz[u]:u);i.push({type:"TXT",name:"_typ._did.",ttl:pf,data:`id=${c.join(Fs)}`})}i.push({type:"TXT",name:"_did."+pq(t.id)+".",ttl:pf,data:l.join(T2)});for(let c of r||[])a.push({type:"NS",name:"_did."+pq(t.id)+".",ttl:pf,data:c+"."});return{id:0,type:"response",flags:Qpe,answers:[...i,...a]}}function pq(t){return t.split(":")[2]}function Rz(t,e,r){e=e||[],r=r||0;for(var n=r;t>=xhe;)e[r++]=t&255|gq,t/=128;for(;t&Phe;)e[r++]=t&255|gq,t>>>=7;return e[r]=t|0,Rz.bytes=r-n+1,e}function s6(t,n){var r=0,n=n||0,i=0,a=n,s,o=t.length;do{if(a>=o)throw s6.bytes=0,new RangeError("Could not decode varint");s=t[a++],r+=i<28?(s&wq)<<i:(s&wq)*Math.pow(2,i),i+=7}while(s>=She);return s6.bytes=a-n,r}function Zhe(t){t=V6(t);let e=Uy+8;(t.length<e||t.length>1024)&&Si("expected proper params");let r=et(aE(t),H6-1n)+1n;return J6(r)}function ome(t){let e=t.toLowerCase();if(e==="localhost"||e==="localhost.")return!0;let r=e.split(".");if(r.length===4){let i=r.map(Number);if(i.every(a=>!Number.isNaN(a)&&a>=0&&a<=255)){let[a,s]=i;if(a===10||a===172&&s>=16&&s<=31||a===192&&s===168||a===127||a===169&&s===254||a===0)return!0}}let n=e;return n.startsWith("[")&&n.endsWith("]")&&(n=n.slice(1,-1)),!!(n.includes(":")&&(n==="::1"||n==="::"||n==="::0"||n.startsWith("fe80:")||n.startsWith("fe80%")||n.startsWith("fc")||n.startsWith("fd")))}var Gce,l6,Hce,Vce,Wce,Jce,Qt,u6,Zce,ph,Yce,Xce,Td,Qce,ede,f6,qq,zq,Fq,tde,rde,nde,ide,W2,p6,oh,sde,ode,Gq,ade,cde,Hq,dde,lde,ude,A9,Vq,fde,Wq,Jq,pde,hde,mde,Zq,yde,gde,Yq,J2,Ai,Zi,Fn,rt,wde,$a,fo,vde,Pde,xde,Ede,oNe,Sde,h6,Ade,kde,_de,t7,Tde,r7,n7,Ide,Dde,Wo,y2,aNe,cNe,dNe,lNe,uNe,fNe,pNe,k9,Ra,hNe,mNe,yNe,_l,gNe,yv,_9,c2,Qp,it,Kv,$de,Bde,Ev,Ode,T9,jde,Mde,Kde,Nde,Ude,I9,Lde,qde,zde,Fde,Gde,Hde,Vde,Wde,Jde,Zde,Yde,Xde,j2,M2,Uv,Lv,Qde,ele,tle,m6,D9,R9,GR,wNe,rle,nle,ile,gv,sle,C9,ole,Oa,vNe,nf,ale,Z2,o7,a7,Y2,cle,dle,Tl,mle,g6,$R,B9,yle,BR,OR,wd,ble,h7,bNe,y7,xle,Ele,Sle,sf,of,Ale,g7,ui,hn,rh,kle,HR,j9,M9,PNe,_le,Dle,Rle,Mle,jR,Nle,Ule,sh,Bl,Da,xNe,K9,ENe,E7,S7,k7,N9,Gle,WR,U9,JR,Fo,SNe,ANe,g2,MR,vd,kNe,Zle,_Ne,eue,tue,rue,nue,af,cf,iue,qv,oue,I7,aue,q9,Wi,due,Xi,D7,lue,uue,fue,Aa,Ji,pue,ws,Il,z9,d2,ZR,mue,yue,gue,wue,vue,bue,Pue,xue,Eue,Sue,Aue,kue,_ue,Iue,Due,Rue,Cue,$ue,Bue,Oue,Nt,jue,Mue,df,lf,Kue,C7,bc,qo,l2,Nue,Uue,wv,KR,zv,F9,TNe,Fue,YR,Gue,G9,Hue,Vue,H9,Ba,Fv,eh,INe,DNe,Sv,Yue,RNe,CNe,$Ne,BNe,ONe,jNe,MNe,KNe,NNe,UNe,ka,Xue,Qi,Dl,Que,efe,tfe,uf,rfe,Dy,vv,nfe,Rl,NR,Ec,ife,sfe,Se,tt,Zv,cfe,dfe,lfe,ufe,Cl,ffe,pfe,hfe,mfe,K7,yfe,xn,N7,Yv,es,A6,U7,W9,Rfe,Kfe,L7,q7,z7,F7,G7,Ta,Pc,je,Nl,dpe,upe,fpe,J9,ff,Pf,LNe,qNe,zNe,FNe,GNe,HNe,VNe,WNe,JNe,ZNe,YNe,XNe,QNe,Y9,vs,Ca,X9,Q9,eUe,tUe,rUe,nUe,eq,tq,rq,nq,B6,bs,eb,nz,O6,iz,iq,sz,sq,vpe,bpe,oq,Ppe,bv,xpe,oz,Epe,Kl,aq,cq,iUe,tE,cz,dz,Spe,Ape,kpe,_pe,Tpe,j6,Ipe,uz,Ope,fz,jpe,Mpe,Ad,bf,fh,kv,gz,Hpe,Vpe,Wpe,Ol,Ut,jl,st,Zpe,uq,QR,Ype,wz,Xpe,Ze,li,Ry,v2,b2,P2,x2,E2,S2,Ky,A2,gf,k2,vz,_2,fq,$l,wf,Sd,_v,Tv,Ho,Iv,Dv,Rv,Oy,Ia,Ny,Qpe,ts,z2,F2,G2,t6,ehe,Ez,ohe,pf,T2,Fs,kz,_z,hq,Iz,po,mq,My,Ln,qn,sUe,dhe,lhe,uhe,fhe,Dz,phe,hhe,mhe,yhe,iE,oUe,aUe,yq,cUe,zy,ghe,n6,Ed,zo,L6,xc,whe,Wv,vhe,gq,bhe,Phe,xhe,Ehe,She,wq,Ahe,khe,_he,The,Ihe,Dhe,Rhe,Che,$he,Bhe,Ohe,jhe,H2,vq,bq,Pq,xq,Mhe,Cz,$z,Khe,Bz,Eq,dUe,Pv,Go,o6,f2,a6,Iy,p2,Oz,Sq,Nhe,Yi,D2,c6,d6,h2,uo,Mz,q6,Fy,Uhe,lt,Aq,kq,Gy,V2,R2,Kz,z6,F6,Lhe,qhe,_q,Nz,bd,zhe,Tq,Fhe,LR,Iq,Ghe,nh,Hhe,Vhe,G6,dh,H6,Uz,Lz,qz,Uy,Dq,Si,sE,zz,qR,Fz,Gz,Jv,V6,et,Rq,Cq,Hy,Nv,C2,Hz,W6,oE,aE,$q,J6,Bq,Oq,Vz,Whe,Jhe,jq,$2,Yhe,ih,Xhe,Qhe,Mq,Kq,xv,eme,tme,Nq,rme,Wz,ho,nme,B2,m2,ime,Uq,Jz,nb,sme,Zz,Yz,ame,cme,cE,dme,dE,lme,Zy,Jo=F(()=>{"use strict";g();Gce=Object.create,l6=Object.defineProperty,Hce=Object.getOwnPropertyDescriptor,Vce=Object.getOwnPropertyNames,Wce=Object.getPrototypeOf,Jce=Object.prototype.hasOwnProperty,Qt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),u6=(t,e)=>{for(var r in e)l6(t,r,{get:e[r],enumerable:!0})},Zce=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Vce(e))!Jce.call(t,i)&&i!==r&&l6(t,i,{get:()=>e[i],enumerable:!(n=Hce(e,i))||n.enumerable});return t},ph=(t,e,r)=>(r=t!=null?Gce(Wce(t)):{},Zce(e||!t||!t.__esModule?l6(r,"default",{value:t,enumerable:!0}):r,t)),Yce=Qt((t,e)=>{var r=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,n=()=>r.now(),i=o=>o&&o===Math.floor(o)&&o>0&&isFinite(o),a=o=>o===1/0||i(o),s=class Lq{constructor({max:d=1/0,ttl:l,updateAgeOnGet:c=!1,checkAgeOnGet:u=!1,noUpdateTTL:f=!1,dispose:h,noDisposeOnSet:p=!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(d))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=l,this.max=d,this.updateAgeOnGet=!!c,this.checkAgeOnGet=!!u,this.noUpdateTTL=!!f,this.noDisposeOnSet=!!p,h!==void 0){if(typeof h!="function")throw new TypeError("dispose must be function if set");this.dispose=h}this.timer=void 0,this.timerExpiration=void 0}setTimer(d,l){if(this.timerExpiration<d)return;this.timer&&clearTimeout(this.timer);let c=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let u in this.expirations){this.setTimer(u,u-n());break}},l);c.unref&&c.unref(),this.timerExpiration=d,this.timer=c}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 d=this.dispose!==Lq.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[l,c]of d)this.dispose(c,l,"delete")}setTTL(d,l=this.ttl){let c=this.expirationMap.get(d);if(c!==void 0){let u=this.expirations[c];!u||u.length<=1?delete this.expirations[c]:this.expirations[c]=u.filter(f=>f!==d)}if(l!==1/0){let u=Math.floor(n()+l);this.expirationMap.set(d,u),this.expirations[u]||(this.expirations[u]=[],this.setTimer(u,l)),this.expirations[u].push(d)}else this.expirationMap.set(d,1/0)}set(d,l,{ttl:c=this.ttl,noUpdateTTL:u=this.noUpdateTTL,noDisposeOnSet:f=this.noDisposeOnSet}={}){if(!a(c))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(d)){u||this.setTTL(d,c);let h=this.data.get(d);h!==l&&(this.data.set(d,l),f||this.dispose(h,d,"set"))}else this.setTTL(d,c),this.data.set(d,l);for(;this.size>this.max;)this.purgeToCapacity();return this}has(d){return this.data.has(d)}getRemainingTTL(d){let l=this.expirationMap.get(d);return l===1/0?l:l!==void 0?Math.max(0,Math.ceil(l-n())):0}get(d,{updateAgeOnGet:l=this.updateAgeOnGet,ttl:c=this.ttl,checkAgeOnGet:u=this.checkAgeOnGet}={}){let f=this.data.get(d);if(u&&this.getRemainingTTL(d)===0){this.delete(d);return}return l&&this.setTTL(d,c),f}dispose(d,l){}delete(d){let l=this.expirationMap.get(d);if(l!==void 0){let c=this.data.get(d);this.data.delete(d),this.expirationMap.delete(d);let u=this.expirations[l];return u&&(u.length<=1?delete this.expirations[l]:this.expirations[l]=u.filter(f=>f!==d)),this.dispose(c,d,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let d in this.expirations){let l=this.expirations[d];if(this.size-l.length>=this.max){delete this.expirations[d];let c=[];for(let u of l)c.push([u,this.data.get(u)]),this.data.delete(u),this.expirationMap.delete(u);for(let[u,f]of c)this.dispose(f,u,"evict")}else{let c=this.size-this.max,u=[];for(let f of l.splice(0,c))u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of u)this.dispose(h,f,"evict");return}}}get size(){return this.data.size}purgeStale(){let d=Math.ceil(n());for(let l in this.expirations){if(l==="Infinity"||l>d)return;let c=[...this.expirations[l]||[]],u=[];delete this.expirations[l];for(let f of c)u.push([f,this.data.get(f)]),this.data.delete(f),this.expirationMap.delete(f);for(let[f,h]of u)this.dispose(h,f,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let d in this.expirations)for(let l of this.expirations[d])yield[l,this.data.get(l)]}*keys(){for(let d in this.expirations)for(let l of this.expirations[d])yield l}*values(){for(let d in this.expirations)for(let l of this.expirations[d])yield this.data.get(l)}[Symbol.iterator](){return this.entries()}};e.exports=s}),Xce=Qt(t=>{"use strict";t.supports=function(...e){let r=e.reduce((n,i)=>Object.assign(n,i),{});return Object.assign(r,{snapshots:r.snapshots||!1,permanence:r.permanence||!1,seek:r.seek||!1,clear:r.clear||!1,getMany:r.getMany||!1,keyIterator:r.keyIterator||!1,valueIterator:r.valueIterator||!1,iteratorNextv:r.iteratorNextv||!1,iteratorAll:r.iteratorAll||!1,status:r.status||!1,createIfMissing:r.createIfMissing||!1,errorIfExists:r.errorIfExists||!1,deferredOpen:r.deferredOpen||!1,promises:r.promises||!1,streams:r.streams||!1,encodings:Object.assign({},r.encodings),events:Object.assign({},r.events),additionalMethods:Object.assign({},r.additionalMethods)})}}),Td=Qt((t,e)=>{"use strict";e.exports=class extends Error{constructor(r,n){super(r||""),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)}}}),Qce=Qt(t=>{"use strict";t.byteLength=d,t.toByteArray=c,t.fromByteArray=h;var e=[],r=[],n=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(a=0,s=i.length;a<s;++a)e[a]=i[a],r[i.charCodeAt(a)]=a;var a,s;r[45]=62,r[95]=63;function o(p){var m=p.length;if(m%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var y=p.indexOf("=");y===-1&&(y=m);var b=y===m?0:4-y%4;return[y,b]}function d(p){var m=o(p),y=m[0],b=m[1];return(y+b)*3/4-b}function l(p,m,y){return(m+y)*3/4-y}function c(p){var m,y=o(p),b=y[0],w=y[1],S=new n(l(p,b,w)),k=0,T=w>0?b-4:b,D;for(D=0;D<T;D+=4)m=r[p.charCodeAt(D)]<<18|r[p.charCodeAt(D+1)]<<12|r[p.charCodeAt(D+2)]<<6|r[p.charCodeAt(D+3)],S[k++]=m>>16&255,S[k++]=m>>8&255,S[k++]=m&255;return w===2&&(m=r[p.charCodeAt(D)]<<2|r[p.charCodeAt(D+1)]>>4,S[k++]=m&255),w===1&&(m=r[p.charCodeAt(D)]<<10|r[p.charCodeAt(D+1)]<<4|r[p.charCodeAt(D+2)]>>2,S[k++]=m>>8&255,S[k++]=m&255),S}function u(p){return e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63]}function f(p,m,y){for(var b,w=[],S=m;S<y;S+=3)b=(p[S]<<16&16711680)+(p[S+1]<<8&65280)+(p[S+2]&255),w.push(u(b));return w.join("")}function h(p){for(var m,y=p.length,b=y%3,w=[],S=16383,k=0,T=y-b;k<T;k+=S)w.push(f(p,k,k+S>T?T:k+S));return b===1?(m=p[y-1],w.push(e[m>>2]+e[m<<4&63]+"==")):b===2&&(m=(p[y-2]<<8)+p[y-1],w.push(e[m>>10]+e[m>>4&63]+e[m<<2&63]+"=")),w.join("")}}),ede=Qt(t=>{t.read=function(e,r,n,i,a){var s,o,d=a*8-i-1,l=(1<<d)-1,c=l>>1,u=-7,f=n?a-1:0,h=n?-1:1,p=e[r+f];for(f+=h,s=p&(1<<-u)-1,p>>=-u,u+=d;u>0;s=s*256+e[r+f],f+=h,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=i;u>0;o=o*256+e[r+f],f+=h,u-=8);if(s===0)s=1-c;else{if(s===l)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,i),s=s-c}return(p?-1:1)*o*Math.pow(2,s-i)},t.write=function(e,r,n,i,a,s){var o,d,l,c=s*8-a-1,u=(1<<c)-1,f=u>>1,h=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=i?0:s-1,m=i?1:-1,y=r<0||r===0&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(d=isNaN(r)?1:0,o=u):(o=Math.floor(Math.log(r)/Math.LN2),r*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+f>=1?r+=h/l:r+=h*Math.pow(2,1-f),r*l>=2&&(o++,l/=2),o+f>=u?(d=0,o=u):o+f>=1?(d=(r*l-1)*Math.pow(2,a),o=o+f):(d=r*Math.pow(2,f-1)*Math.pow(2,a),o=0));a>=8;e[n+p]=d&255,p+=m,d/=256,a-=8);for(o=o<<a|d,c+=a;c>0;e[n+p]=o&255,p+=m,o/=256,c-=8);e[n+p-m]|=y*128}}),f6=Qt(t=>{"use strict";var e=Qce(),r=ede(),n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=o,t.SlowBuffer=w,t.INSPECT_MAX_BYTES=50;var i=2147483647;t.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 _=new Uint8Array(1),O={foo:function(){return 42}};return Object.setPrototypeOf(O,Uint8Array.prototype),Object.setPrototypeOf(_,O),_.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(_){if(_>i)throw new RangeError('The value "'+_+'" is invalid for option "size"');let O=new Uint8Array(_);return Object.setPrototypeOf(O,o.prototype),O}function o(_,O,U){if(typeof _=="number"){if(typeof O=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(_)}return d(_,O,U)}o.poolSize=8192;function d(_,O,U){if(typeof _=="string")return f(_,O);if(ArrayBuffer.isView(_))return p(_);if(_==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _);if(ke(_,ArrayBuffer)||_&&ke(_.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ke(_,SharedArrayBuffer)||_&&ke(_.buffer,SharedArrayBuffer)))return m(_,O,U);if(typeof _=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let te=_.valueOf&&_.valueOf();if(te!=null&&te!==_)return o.from(te,O,U);let ce=y(_);if(ce)return ce;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof _[Symbol.toPrimitive]=="function")return o.from(_[Symbol.toPrimitive]("string"),O,U);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof _)}o.from=function(_,O,U){return d(_,O,U)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function l(_){if(typeof _!="number")throw new TypeError('"size" argument must be of type number');if(_<0)throw new RangeError('The value "'+_+'" is invalid for option "size"')}function c(_,O,U){return l(_),_<=0?s(_):O!==void 0?typeof U=="string"?s(_).fill(O,U):s(_).fill(O):s(_)}o.alloc=function(_,O,U){return c(_,O,U)};function u(_){return l(_),s(_<0?0:b(_)|0)}o.allocUnsafe=function(_){return u(_)},o.allocUnsafeSlow=function(_){return u(_)};function f(_,O){if((typeof O!="string"||O==="")&&(O="utf8"),!o.isEncoding(O))throw new TypeError("Unknown encoding: "+O);let U=S(_,O)|0,te=s(U),ce=te.write(_,O);return ce!==U&&(te=te.slice(0,ce)),te}function h(_){let O=_.length<0?0:b(_.length)|0,U=s(O);for(let te=0;te<O;te+=1)U[te]=_[te]&255;return U}function p(_){if(ke(_,Uint8Array)){let O=new Uint8Array(_);return m(O.buffer,O.byteOffset,O.byteLength)}return h(_)}function m(_,O,U){if(O<0||_.byteLength<O)throw new RangeError('"offset" is outside of buffer bounds');if(_.byteLength<O+(U||0))throw new RangeError('"length" is outside of buffer bounds');let te;return O===void 0&&U===void 0?te=new Uint8Array(_):U===void 0?te=new Uint8Array(_,O):te=new Uint8Array(_,O,U),Object.setPrototypeOf(te,o.prototype),te}function y(_){if(o.isBuffer(_)){let O=b(_.length)|0,U=s(O);return U.length===0||_.copy(U,0,0,O),U}if(_.length!==void 0)return typeof _.length!="number"||ot(_.length)?s(0):h(_);if(_.type==="Buffer"&&Array.isArray(_.data))return h(_.data)}function b(_){if(_>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return _|0}function w(_){return+_!=_&&(_=0),o.alloc(+_)}o.isBuffer=function(_){return _!=null&&_._isBuffer===!0&&_!==o.prototype},o.compare=function(_,O){if(ke(_,Uint8Array)&&(_=o.from(_,_.offset,_.byteLength)),ke(O,Uint8Array)&&(O=o.from(O,O.offset,O.byteLength)),!o.isBuffer(_)||!o.isBuffer(O))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(_===O)return 0;let U=_.length,te=O.length;for(let ce=0,me=Math.min(U,te);ce<me;++ce)if(_[ce]!==O[ce]){U=_[ce],te=O[ce];break}return U<te?-1:te<U?1:0},o.isEncoding=function(_){switch(String(_).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(_,O){if(!Array.isArray(_))throw new TypeError('"list" argument must be an Array of Buffers');if(_.length===0)return o.alloc(0);let U;if(O===void 0)for(O=0,U=0;U<_.length;++U)O+=_[U].length;let te=o.allocUnsafe(O),ce=0;for(U=0;U<_.length;++U){let me=_[U];if(ke(me,Uint8Array))ce+me.length>te.length?(o.isBuffer(me)||(me=o.from(me)),me.copy(te,ce)):Uint8Array.prototype.set.call(te,me,ce);else if(o.isBuffer(me))me.copy(te,ce);else throw new TypeError('"list" argument must be an Array of Buffers');ce+=me.length}return te};function S(_,O){if(o.isBuffer(_))return _.length;if(ArrayBuffer.isView(_)||ke(_,ArrayBuffer))return _.byteLength;if(typeof _!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof _);let U=_.length,te=arguments.length>2&&arguments[2]===!0;if(!te&&U===0)return 0;let ce=!1;for(;;)switch(O){case"ascii":case"latin1":case"binary":return U;case"utf8":case"utf-8":return Pe(_).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U*2;case"hex":return U>>>1;case"base64":return Je(_).length;default:if(ce)return te?-1:Pe(_).length;O=(""+O).toLowerCase(),ce=!0}}o.byteLength=S;function k(_,O,U){let te=!1;if((O===void 0||O<0)&&(O=0),O>this.length||((U===void 0||U>this.length)&&(U=this.length),U<=0)||(U>>>=0,O>>>=0,U<=O))return"";for(_||(_="utf8");;)switch(_){case"hex":return A(this,O,U);case"utf8":case"utf-8":return R(this,O,U);case"ascii":return E(this,O,U);case"latin1":case"binary":return x(this,O,U);case"base64":return ee(this,O,U);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,O,U);default:if(te)throw new TypeError("Unknown encoding: "+_);_=(_+"").toLowerCase(),te=!0}}o.prototype._isBuffer=!0;function T(_,O,U){let te=_[O];_[O]=_[U],_[U]=te}o.prototype.swap16=function(){let _=this.length;if(_%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let O=0;O<_;O+=2)T(this,O,O+1);return this},o.prototype.swap32=function(){let _=this.length;if(_%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let O=0;O<_;O+=4)T(this,O,O+3),T(this,O+1,O+2);return this},o.prototype.swap64=function(){let _=this.length;if(_%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let O=0;O<_;O+=8)T(this,O,O+7),T(this,O+1,O+6),T(this,O+2,O+5),T(this,O+3,O+4);return this},o.prototype.toString=function(){let _=this.length;return _===0?"":arguments.length===0?R(this,0,_):k.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(_){if(!o.isBuffer(_))throw new TypeError("Argument must be a Buffer");return this===_?!0:o.compare(this,_)===0},o.prototype.inspect=function(){let _="",O=t.INSPECT_MAX_BYTES;return _=this.toString("hex",0,O).replace(/(.{2})/g,"$1 ").trim(),this.length>O&&(_+=" ... "),"<Buffer "+_+">"},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(_,O,U,te,ce){if(ke(_,Uint8Array)&&(_=o.from(_,_.offset,_.byteLength)),!o.isBuffer(_))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof _);if(O===void 0&&(O=0),U===void 0&&(U=_?_.length:0),te===void 0&&(te=0),ce===void 0&&(ce=this.length),O<0||U>_.length||te<0||ce>this.length)throw new RangeError("out of range index");if(te>=ce&&O>=U)return 0;if(te>=ce)return-1;if(O>=U)return 1;if(O>>>=0,U>>>=0,te>>>=0,ce>>>=0,this===_)return 0;let me=ce-te,Ae=U-O,Ft=Math.min(me,Ae),Xn=this.slice(te,ce),Gr=_.slice(O,U);for(let kr=0;kr<Ft;++kr)if(Xn[kr]!==Gr[kr]){me=Xn[kr],Ae=Gr[kr];break}return me<Ae?-1:Ae<me?1:0};function D(_,O,U,te,ce){if(_.length===0)return-1;if(typeof U=="string"?(te=U,U=0):U>2147483647?U=2147483647:U<-2147483648&&(U=-2147483648),U=+U,ot(U)&&(U=ce?0:_.length-1),U<0&&(U=_.length+U),U>=_.length){if(ce)return-1;U=_.length-1}else if(U<0)if(ce)U=0;else return-1;if(typeof O=="string"&&(O=o.from(O,te)),o.isBuffer(O))return O.length===0?-1:K(_,O,U,te,ce);if(typeof O=="number")return O=O&255,typeof Uint8Array.prototype.indexOf=="function"?ce?Uint8Array.prototype.indexOf.call(_,O,U):Uint8Array.prototype.lastIndexOf.call(_,O,U):K(_,[O],U,te,ce);throw new TypeError("val must be string, number or Buffer")}function K(_,O,U,te,ce){let me=1,Ae=_.length,Ft=O.length;if(te!==void 0&&(te=String(te).toLowerCase(),te==="ucs2"||te==="ucs-2"||te==="utf16le"||te==="utf-16le")){if(_.length<2||O.length<2)return-1;me=2,Ae/=2,Ft/=2,U/=2}function Xn(kr,yr){return me===1?kr[yr]:kr.readUInt16BE(yr*me)}let Gr;if(ce){let kr=-1;for(Gr=U;Gr<Ae;Gr++)if(Xn(_,Gr)===Xn(O,kr===-1?0:Gr-kr)){if(kr===-1&&(kr=Gr),Gr-kr+1===Ft)return kr*me}else kr!==-1&&(Gr-=Gr-kr),kr=-1}else for(U+Ft>Ae&&(U=Ae-Ft),Gr=U;Gr>=0;Gr--){let kr=!0;for(let yr=0;yr<Ft;yr++)if(Xn(_,Gr+yr)!==Xn(O,yr)){kr=!1;break}if(kr)return Gr}return-1}o.prototype.includes=function(_,O,U){return this.indexOf(_,O,U)!==-1},o.prototype.indexOf=function(_,O,U){return D(this,_,O,U,!0)},o.prototype.lastIndexOf=function(_,O,U){return D(this,_,O,U,!1)};function C(_,O,U,te){U=Number(U)||0;let ce=_.length-U;te?(te=Number(te),te>ce&&(te=ce)):te=ce;let me=O.length;te>me/2&&(te=me/2);let Ae;for(Ae=0;Ae<te;++Ae){let Ft=parseInt(O.substr(Ae*2,2),16);if(ot(Ft))return Ae;_[U+Ae]=Ft}return Ae}function G(_,O,U,te){return Ct(Pe(O,_.length-U),_,U,te)}function z(_,O,U,te){return Ct(Ne(O),_,U,te)}function N(_,O,U,te){return Ct(Je(O),_,U,te)}function V(_,O,U,te){return Ct(He(O,_.length-U),_,U,te)}o.prototype.write=function(_,O,U,te){if(O===void 0)te="utf8",U=this.length,O=0;else if(U===void 0&&typeof O=="string")te=O,U=this.length,O=0;else if(isFinite(O))O=O>>>0,isFinite(U)?(U=U>>>0,te===void 0&&(te="utf8")):(te=U,U=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let ce=this.length-O;if((U===void 0||U>ce)&&(U=ce),_.length>0&&(U<0||O<0)||O>this.length)throw new RangeError("Attempt to write outside buffer bounds");te||(te="utf8");let me=!1;for(;;)switch(te){case"hex":return C(this,_,O,U);case"utf8":case"utf-8":return G(this,_,O,U);case"ascii":case"latin1":case"binary":return z(this,_,O,U);case"base64":return N(this,_,O,U);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,_,O,U);default:if(me)throw new TypeError("Unknown encoding: "+te);te=(""+te).toLowerCase(),me=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ee(_,O,U){return O===0&&U===_.length?e.fromByteArray(_):e.fromByteArray(_.slice(O,U))}function R(_,O,U){U=Math.min(_.length,U);let te=[],ce=O;for(;ce<U;){let me=_[ce],Ae=null,Ft=me>239?4:me>223?3:me>191?2:1;if(ce+Ft<=U){let Xn,Gr,kr,yr;switch(Ft){case 1:me<128&&(Ae=me);break;case 2:Xn=_[ce+1],(Xn&192)===128&&(yr=(me&31)<<6|Xn&63,yr>127&&(Ae=yr));break;case 3:Xn=_[ce+1],Gr=_[ce+2],(Xn&192)===128&&(Gr&192)===128&&(yr=(me&15)<<12|(Xn&63)<<6|Gr&63,yr>2047&&(yr<55296||yr>57343)&&(Ae=yr));break;case 4:Xn=_[ce+1],Gr=_[ce+2],kr=_[ce+3],(Xn&192)===128&&(Gr&192)===128&&(kr&192)===128&&(yr=(me&15)<<18|(Xn&63)<<12|(Gr&63)<<6|kr&63,yr>65535&&yr<1114112&&(Ae=yr))}}Ae===null?(Ae=65533,Ft=1):Ae>65535&&(Ae-=65536,te.push(Ae>>>10&1023|55296),Ae=56320|Ae&1023),te.push(Ae),ce+=Ft}return P(te)}var B=4096;function P(_){let O=_.length;if(O<=B)return String.fromCharCode.apply(String,_);let U="",te=0;for(;te<O;)U+=String.fromCharCode.apply(String,_.slice(te,te+=B));return U}function E(_,O,U){let te="";U=Math.min(_.length,U);for(let ce=O;ce<U;++ce)te+=String.fromCharCode(_[ce]&127);return te}function x(_,O,U){let te="";U=Math.min(_.length,U);for(let ce=O;ce<U;++ce)te+=String.fromCharCode(_[ce]);return te}function A(_,O,U){let te=_.length;(!O||O<0)&&(O=0),(!U||U<0||U>te)&&(U=te);let ce="";for(let me=O;me<U;++me)ce+=_t[_[me]];return ce}function I(_,O,U){let te=_.slice(O,U),ce="";for(let me=0;me<te.length-1;me+=2)ce+=String.fromCharCode(te[me]+te[me+1]*256);return ce}o.prototype.slice=function(_,O){let U=this.length;_=~~_,O=O===void 0?U:~~O,_<0?(_+=U,_<0&&(_=0)):_>U&&(_=U),O<0?(O+=U,O<0&&(O=0)):O>U&&(O=U),O<_&&(O=_);let te=this.subarray(_,O);return Object.setPrototypeOf(te,o.prototype),te};function M(_,O,U){if(_%1!==0||_<0)throw new RangeError("offset is not uint");if(_+O>U)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(_,O,U){_=_>>>0,O=O>>>0,U||M(_,O,this.length);let te=this[_],ce=1,me=0;for(;++me<O&&(ce*=256);)te+=this[_+me]*ce;return te},o.prototype.readUintBE=o.prototype.readUIntBE=function(_,O,U){_=_>>>0,O=O>>>0,U||M(_,O,this.length);let te=this[_+--O],ce=1;for(;O>0&&(ce*=256);)te+=this[_+--O]*ce;return te},o.prototype.readUint8=o.prototype.readUInt8=function(_,O){return _=_>>>0,O||M(_,1,this.length),this[_]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(_,O){return _=_>>>0,O||M(_,2,this.length),this[_]|this[_+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(_,O){return _=_>>>0,O||M(_,2,this.length),this[_]<<8|this[_+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(_,O){return _=_>>>0,O||M(_,4,this.length),(this[_]|this[_+1]<<8|this[_+2]<<16)+this[_+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(_,O){return _=_>>>0,O||M(_,4,this.length),this[_]*16777216+(this[_+1]<<16|this[_+2]<<8|this[_+3])},o.prototype.readBigUInt64LE=Rt(function(_){_=_>>>0,ue(_,"offset");let O=this[_],U=this[_+7];(O===void 0||U===void 0)&&pe(_,this.length-8);let te=O+this[++_]*2**8+this[++_]*2**16+this[++_]*2**24,ce=this[++_]+this[++_]*2**8+this[++_]*2**16+U*2**24;return BigInt(te)+(BigInt(ce)<<BigInt(32))}),o.prototype.readBigUInt64BE=Rt(function(_){_=_>>>0,ue(_,"offset");let O=this[_],U=this[_+7];(O===void 0||U===void 0)&&pe(_,this.length-8);let te=O*2**24+this[++_]*2**16+this[++_]*2**8+this[++_],ce=this[++_]*2**24+this[++_]*2**16+this[++_]*2**8+U;return(BigInt(te)<<BigInt(32))+BigInt(ce)}),o.prototype.readIntLE=function(_,O,U){_=_>>>0,O=O>>>0,U||M(_,O,this.length);let te=this[_],ce=1,me=0;for(;++me<O&&(ce*=256);)te+=this[_+me]*ce;return ce*=128,te>=ce&&(te-=Math.pow(2,8*O)),te},o.prototype.readIntBE=function(_,O,U){_=_>>>0,O=O>>>0,U||M(_,O,this.length);let te=O,ce=1,me=this[_+--te];for(;te>0&&(ce*=256);)me+=this[_+--te]*ce;return ce*=128,me>=ce&&(me-=Math.pow(2,8*O)),me},o.prototype.readInt8=function(_,O){return _=_>>>0,O||M(_,1,this.length),this[_]&128?(255-this[_]+1)*-1:this[_]},o.prototype.readInt16LE=function(_,O){_=_>>>0,O||M(_,2,this.length);let U=this[_]|this[_+1]<<8;return U&32768?U|4294901760:U},o.prototype.readInt16BE=function(_,O){_=_>>>0,O||M(_,2,this.length);let U=this[_+1]|this[_]<<8;return U&32768?U|4294901760:U},o.prototype.readInt32LE=function(_,O){return _=_>>>0,O||M(_,4,this.length),this[_]|this[_+1]<<8|this[_+2]<<16|this[_+3]<<24},o.prototype.readInt32BE=function(_,O){return _=_>>>0,O||M(_,4,this.length),this[_]<<24|this[_+1]<<16|this[_+2]<<8|this[_+3]},o.prototype.readBigInt64LE=Rt(function(_){_=_>>>0,ue(_,"offset");let O=this[_],U=this[_+7];(O===void 0||U===void 0)&&pe(_,this.length-8);let te=this[_+4]+this[_+5]*2**8+this[_+6]*2**16+(U<<24);return(BigInt(te)<<BigInt(32))+BigInt(O+this[++_]*2**8+this[++_]*2**16+this[++_]*2**24)}),o.prototype.readBigInt64BE=Rt(function(_){_=_>>>0,ue(_,"offset");let O=this[_],U=this[_+7];(O===void 0||U===void 0)&&pe(_,this.length-8);let te=(O<<24)+this[++_]*2**16+this[++_]*2**8+this[++_];return(BigInt(te)<<BigInt(32))+BigInt(this[++_]*2**24+this[++_]*2**16+this[++_]*2**8+U)}),o.prototype.readFloatLE=function(_,O){return _=_>>>0,O||M(_,4,this.length),r.read(this,_,!0,23,4)},o.prototype.readFloatBE=function(_,O){return _=_>>>0,O||M(_,4,this.length),r.read(this,_,!1,23,4)},o.prototype.readDoubleLE=function(_,O){return _=_>>>0,O||M(_,8,this.length),r.read(this,_,!0,52,8)},o.prototype.readDoubleBE=function(_,O){return _=_>>>0,O||M(_,8,this.length),r.read(this,_,!1,52,8)};function q(_,O,U,te,ce,me){if(!o.isBuffer(_))throw new TypeError('"buffer" argument must be a Buffer instance');if(O>ce||O<me)throw new RangeError('"value" argument is out of bounds');if(U+te>_.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(_,O,U,te){if(_=+_,O=O>>>0,U=U>>>0,!te){let Ae=Math.pow(2,8*U)-1;q(this,_,O,U,Ae,0)}let ce=1,me=0;for(this[O]=_&255;++me<U&&(ce*=256);)this[O+me]=_/ce&255;return O+U},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(_,O,U,te){if(_=+_,O=O>>>0,U=U>>>0,!te){let Ae=Math.pow(2,8*U)-1;q(this,_,O,U,Ae,0)}let ce=U-1,me=1;for(this[O+ce]=_&255;--ce>=0&&(me*=256);)this[O+ce]=_/me&255;return O+U},o.prototype.writeUint8=o.prototype.writeUInt8=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,1,255,0),this[O]=_&255,O+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,2,65535,0),this[O]=_&255,this[O+1]=_>>>8,O+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,2,65535,0),this[O]=_>>>8,this[O+1]=_&255,O+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,4,4294967295,0),this[O+3]=_>>>24,this[O+2]=_>>>16,this[O+1]=_>>>8,this[O]=_&255,O+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,4,4294967295,0),this[O]=_>>>24,this[O+1]=_>>>16,this[O+2]=_>>>8,this[O+3]=_&255,O+4};function H(_,O,U,te,ce){le(O,te,ce,_,U,7);let me=Number(O&BigInt(4294967295));_[U++]=me,me=me>>8,_[U++]=me,me=me>>8,_[U++]=me,me=me>>8,_[U++]=me;let Ae=Number(O>>BigInt(32)&BigInt(4294967295));return _[U++]=Ae,Ae=Ae>>8,_[U++]=Ae,Ae=Ae>>8,_[U++]=Ae,Ae=Ae>>8,_[U++]=Ae,U}function W(_,O,U,te,ce){le(O,te,ce,_,U,7);let me=Number(O&BigInt(4294967295));_[U+7]=me,me=me>>8,_[U+6]=me,me=me>>8,_[U+5]=me,me=me>>8,_[U+4]=me;let Ae=Number(O>>BigInt(32)&BigInt(4294967295));return _[U+3]=Ae,Ae=Ae>>8,_[U+2]=Ae,Ae=Ae>>8,_[U+1]=Ae,Ae=Ae>>8,_[U]=Ae,U+8}o.prototype.writeBigUInt64LE=Rt(function(_,O=0){return H(this,_,O,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=Rt(function(_,O=0){return W(this,_,O,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(_,O,U,te){if(_=+_,O=O>>>0,!te){let Ft=Math.pow(2,8*U-1);q(this,_,O,U,Ft-1,-Ft)}let ce=0,me=1,Ae=0;for(this[O]=_&255;++ce<U&&(me*=256);)_<0&&Ae===0&&this[O+ce-1]!==0&&(Ae=1),this[O+ce]=(_/me>>0)-Ae&255;return O+U},o.prototype.writeIntBE=function(_,O,U,te){if(_=+_,O=O>>>0,!te){let Ft=Math.pow(2,8*U-1);q(this,_,O,U,Ft-1,-Ft)}let ce=U-1,me=1,Ae=0;for(this[O+ce]=_&255;--ce>=0&&(me*=256);)_<0&&Ae===0&&this[O+ce+1]!==0&&(Ae=1),this[O+ce]=(_/me>>0)-Ae&255;return O+U},o.prototype.writeInt8=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,1,127,-128),_<0&&(_=255+_+1),this[O]=_&255,O+1},o.prototype.writeInt16LE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,2,32767,-32768),this[O]=_&255,this[O+1]=_>>>8,O+2},o.prototype.writeInt16BE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,2,32767,-32768),this[O]=_>>>8,this[O+1]=_&255,O+2},o.prototype.writeInt32LE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,4,2147483647,-2147483648),this[O]=_&255,this[O+1]=_>>>8,this[O+2]=_>>>16,this[O+3]=_>>>24,O+4},o.prototype.writeInt32BE=function(_,O,U){return _=+_,O=O>>>0,U||q(this,_,O,4,2147483647,-2147483648),_<0&&(_=4294967295+_+1),this[O]=_>>>24,this[O+1]=_>>>16,this[O+2]=_>>>8,this[O+3]=_&255,O+4},o.prototype.writeBigInt64LE=Rt(function(_,O=0){return H(this,_,O,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=Rt(function(_,O=0){return W(this,_,O,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function J(_,O,U,te,ce,me){if(U+te>_.length)throw new RangeError("Index out of range");if(U<0)throw new RangeError("Index out of range")}function X(_,O,U,te,ce){return O=+O,U=U>>>0,ce||J(_,O,U,4,34028234663852886e22,-34028234663852886e22),r.write(_,O,U,te,23,4),U+4}o.prototype.writeFloatLE=function(_,O,U){return X(this,_,O,!0,U)},o.prototype.writeFloatBE=function(_,O,U){return X(this,_,O,!1,U)};function L(_,O,U,te,ce){return O=+O,U=U>>>0,ce||J(_,O,U,8,17976931348623157e292,-17976931348623157e292),r.write(_,O,U,te,52,8),U+8}o.prototype.writeDoubleLE=function(_,O,U){return L(this,_,O,!0,U)},o.prototype.writeDoubleBE=function(_,O,U){return L(this,_,O,!1,U)},o.prototype.copy=function(_,O,U,te){if(!o.isBuffer(_))throw new TypeError("argument should be a Buffer");if(U||(U=0),!te&&te!==0&&(te=this.length),O>=_.length&&(O=_.length),O||(O=0),te>0&&te<U&&(te=U),te===U||_.length===0||this.length===0)return 0;if(O<0)throw new RangeError("targetStart out of bounds");if(U<0||U>=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),_.length-O<te-U&&(te=_.length-O+U);let ce=te-U;return this===_&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(O,U,te):Uint8Array.prototype.set.call(_,this.subarray(U,te),O),ce},o.prototype.fill=function(_,O,U,te){if(typeof _=="string"){if(typeof O=="string"?(te=O,O=0,U=this.length):typeof U=="string"&&(te=U,U=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(_.length===1){let me=_.charCodeAt(0);(te==="utf8"&&me<128||te==="latin1")&&(_=me)}}else typeof _=="number"?_=_&255:typeof _=="boolean"&&(_=Number(_));if(O<0||this.length<O||this.length<U)throw new RangeError("Out of range index");if(U<=O)return this;O=O>>>0,U=U===void 0?this.length:U>>>0,_||(_=0);let ce;if(typeof _=="number")for(ce=O;ce<U;++ce)this[ce]=_;else{let me=o.isBuffer(_)?_:o.from(_,te),Ae=me.length;if(Ae===0)throw new TypeError('The value "'+_+'" is invalid for argument "value"');for(ce=0;ce<U-O;++ce)this[ce+O]=me[ce%Ae]}return this};var Q={};function se(_,O,U){Q[_]=class extends U{constructor(){super(),Object.defineProperty(this,"message",{value:O.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${_}]`,this.stack,delete this.name}get code(){return _}set code(te){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:te,writable:!0})}toString(){return`${this.name} [${_}]: ${this.message}`}}}se("ERR_BUFFER_OUT_OF_BOUNDS",function(_){return _?`${_} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),se("ERR_INVALID_ARG_TYPE",function(_,O){return`The "${_}" argument must be of type number. Received type ${typeof O}`},TypeError),se("ERR_OUT_OF_RANGE",function(_,O,U){let te=`The value of "${_}" is out of range.`,ce=U;return Number.isInteger(U)&&Math.abs(U)>2**32?ce=re(String(U)):typeof U=="bigint"&&(ce=String(U),(U>BigInt(2)**BigInt(32)||U<-(BigInt(2)**BigInt(32)))&&(ce=re(ce)),ce+="n"),te+=` It must be ${O}. Received ${ce}`,te},RangeError);function re(_){let O="",U=_.length,te=_[0]==="-"?1:0;for(;U>=te+4;U-=3)O=`_${_.slice(U-3,U)}${O}`;return`${_.slice(0,U)}${O}`}function Y(_,O,U){ue(O,"offset"),(_[O]===void 0||_[O+U]===void 0)&&pe(O,_.length-(U+1))}function le(_,O,U,te,ce,me){if(_>U||_<O){let Ae=typeof O=="bigint"?"n":"",Ft;throw me>3?O===0||O===BigInt(0)?Ft=`>= 0${Ae} and < 2${Ae} ** ${(me+1)*8}${Ae}`:Ft=`>= -(2${Ae} ** ${(me+1)*8-1}${Ae}) and < 2 ** ${(me+1)*8-1}${Ae}`:Ft=`>= ${O}${Ae} and <= ${U}${Ae}`,new Q.ERR_OUT_OF_RANGE("value",Ft,_)}Y(te,ce,me)}function ue(_,O){if(typeof _!="number")throw new Q.ERR_INVALID_ARG_TYPE(O,"number",_)}function pe(_,O,U){throw Math.floor(_)!==_?(ue(_,U),new Q.ERR_OUT_OF_RANGE(U||"offset","an integer",_)):O<0?new Q.ERR_BUFFER_OUT_OF_BOUNDS:new Q.ERR_OUT_OF_RANGE(U||"offset",`>= ${U?1:0} and <= ${O}`,_)}var xe=/[^+/0-9A-Za-z-_]/g;function de(_){if(_=_.split("=")[0],_=_.trim().replace(xe,""),_.length<2)return"";for(;_.length%4!==0;)_=_+"=";return _}function Pe(_,O){O=O||1/0;let U,te=_.length,ce=null,me=[];for(let Ae=0;Ae<te;++Ae){if(U=_.charCodeAt(Ae),U>55295&&U<57344){if(!ce){if(U>56319){(O-=3)>-1&&me.push(239,191,189);continue}else if(Ae+1===te){(O-=3)>-1&&me.push(239,191,189);continue}ce=U;continue}if(U<56320){(O-=3)>-1&&me.push(239,191,189),ce=U;continue}U=(ce-55296<<10|U-56320)+65536}else ce&&(O-=3)>-1&&me.push(239,191,189);if(ce=null,U<128){if((O-=1)<0)break;me.push(U)}else if(U<2048){if((O-=2)<0)break;me.push(U>>6|192,U&63|128)}else if(U<65536){if((O-=3)<0)break;me.push(U>>12|224,U>>6&63|128,U&63|128)}else if(U<1114112){if((O-=4)<0)break;me.push(U>>18|240,U>>12&63|128,U>>6&63|128,U&63|128)}else throw new Error("Invalid code point")}return me}function Ne(_){let O=[];for(let U=0;U<_.length;++U)O.push(_.charCodeAt(U)&255);return O}function He(_,O){let U,te,ce,me=[];for(let Ae=0;Ae<_.length&&!((O-=2)<0);++Ae)U=_.charCodeAt(Ae),te=U>>8,ce=U%256,me.push(ce),me.push(te);return me}function Je(_){return e.toByteArray(de(_))}function Ct(_,O,U,te){let ce;for(ce=0;ce<te&&!(ce+U>=O.length||ce>=_.length);++ce)O[ce+U]=_[ce];return ce}function ke(_,O){return _ instanceof O||_!=null&&_.constructor!=null&&_.constructor.name!=null&&_.constructor.name===O.name}function ot(_){return _!==_}var _t=function(){let _="0123456789abcdef",O=new Array(256);for(let U=0;U<16;++U){let te=U*16;for(let ce=0;ce<16;++ce)O[te+ce]=_[U]+_[ce]}return O}();function Rt(_){return typeof BigInt>"u"?zt:_}function zt(){throw new Error("BigInt not supported")}}),qq=Qt((t,e)=>{"use strict";var r=null;e.exports=function(){return r===null&&(r={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),r}}),zq=Qt(t=>{"use strict";var e=Td(),r=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"||!r.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"})}};t.Encoding=n}),Fq=Qt(t=>{"use strict";var{Buffer:e}=f6()||{},{Encoding:r}=zq(),n=qq(),i=class extends r{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 r{constructor(o){super({...o,format:"view"})}createBufferTranscoder(){return new i({encode:o=>{let d=this.encode(o);return e.from(d.buffer,d.byteOffset,d.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},s=class extends r{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:d}=n();return new a({encode:l=>o.encode(this.encode(l)),decode:l=>this.decode(d.decode(l)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};t.BufferFormat=i,t.ViewFormat=a,t.UTF8Format=s}),tde=Qt(t=>{"use strict";var{Buffer:e}=f6()||{Buffer:{isBuffer:()=>!1}},{textEncoder:r,textDecoder:n}=qq()(),{BufferFormat:i,ViewFormat:a,UTF8Format:s}=Fq(),o=d=>d;t.utf8=new s({encode:function(d){return e.isBuffer(d)?d.toString("utf8"):ArrayBuffer.isView(d)?n.decode(d):String(d)},decode:o,name:"utf8",createViewTranscoder(){return new a({encode:function(d){return ArrayBuffer.isView(d)?d:r.encode(d)},decode:function(d){return n.decode(d)},name:`${this.name}+view`})},createBufferTranscoder(){return new i({encode:function(d){return e.isBuffer(d)?d:ArrayBuffer.isView(d)?e.from(d.buffer,d.byteOffset,d.byteLength):e.from(String(d),"utf8")},decode:function(d){return d.toString("utf8")},name:`${this.name}+buffer`})}}),t.json=new s({encode:JSON.stringify,decode:JSON.parse,name:"json"}),t.buffer=new i({encode:function(d){return e.isBuffer(d)?d:ArrayBuffer.isView(d)?e.from(d.buffer,d.byteOffset,d.byteLength):e.from(String(d),"utf8")},decode:o,name:"buffer",createViewTranscoder(){return new a({encode:function(d){return ArrayBuffer.isView(d)?d:e.from(String(d),"utf8")},decode:function(d){return e.from(d.buffer,d.byteOffset,d.byteLength)},name:`${this.name}+view`})}}),t.view=new a({encode:function(d){return ArrayBuffer.isView(d)?d:r.encode(d)},decode:o,name:"view",createBufferTranscoder(){return new i({encode:function(d){return e.isBuffer(d)?d:ArrayBuffer.isView(d)?e.from(d.buffer,d.byteOffset,d.byteLength):e.from(String(d),"utf8")},decode:o,name:`${this.name}+buffer`})}}),t.hex=new i({encode:function(d){return e.isBuffer(d)?d:e.from(String(d),"hex")},decode:function(d){return d.toString("hex")},name:"hex"}),t.base64=new i({encode:function(d){return e.isBuffer(d)?d:e.from(String(d),"base64")},decode:function(d){return d.toString("base64")},name:"base64"})}),rde=Qt(t=>{"use strict";var e=Td(),r=tde(),{Encoding:n}=zq(),{BufferFormat:i,ViewFormat:a,UTF8Format:s}=Fq(),o=Symbol("formats"),d=Symbol("encodings"),l=new Set(["buffer","view","utf8"]),c=class{constructor(y){if(Array.isArray(y)){if(!y.every(b=>l.has(b)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[d]=new Map,this[o]=new Set(y);for(let b in r)try{this.encoding(b)}catch(w){if(w.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw w}}encodings(){return Array.from(new Set(this[d].values()))}encoding(y){let b=this[d].get(y);if(b===void 0){if(typeof y=="string"&&y!==""){if(b=p[y],!b)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");b=u(y)}let{name:w,format:S}=b;if(!this[o].has(S))if(this[o].has("view"))b=b.createViewTranscoder();else if(this[o].has("buffer"))b=b.createBufferTranscoder();else if(this[o].has("utf8"))b=b.createUTF8Transcoder();else throw new e(`Encoding '${w}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let k of[y,w,b.name,b.commonName])this[d].set(k,b)}return b}};t.Transcoder=c;function u(y){if(y instanceof n)return y;let b="type"in y&&typeof y.type=="string"?y.type:void 0,w=y.name||b||`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 h={binary:r.buffer,"utf-8":r.utf8},p={...r,...h},m=0}),nde=Qt((t,e)=>{"use strict";var r=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function a(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function s(l,c,u,f,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new a(u,f||l,h),m=n?n+c:c;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],p]:l._events[m].push(p):(l._events[m]=p,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function d(){this._events=new i,this._eventsCount=0}d.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)r.call(c,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},d.prototype.listeners=function(l){var c=n?n+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var f=0,h=u.length,p=new Array(h);f<h;f++)p[f]=u[f].fn;return p},d.prototype.listenerCount=function(l){var c=n?n+l:l,u=this._events[c];return u?u.fn?1:u.length:0},d.prototype.emit=function(l,c,u,f,h,p){var m=n?n+l:l;if(!this._events[m])return!1;var y=this._events[m],b=arguments.length,w,S;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),b){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,c),!0;case 3:return y.fn.call(y.context,c,u),!0;case 4:return y.fn.call(y.context,c,u,f),!0;case 5:return y.fn.call(y.context,c,u,f,h),!0;case 6:return y.fn.call(y.context,c,u,f,h,p),!0}for(S=1,w=new Array(b-1);S<b;S++)w[S-1]=arguments[S];y.fn.apply(y.context,w)}else{var k=y.length,T;for(S=0;S<k;S++)switch(y[S].once&&this.removeListener(l,y[S].fn,void 0,!0),b){case 1:y[S].fn.call(y[S].context);break;case 2:y[S].fn.call(y[S].context,c);break;case 3:y[S].fn.call(y[S].context,c,u);break;case 4:y[S].fn.call(y[S].context,c,u,f);break;default:if(!w)for(T=1,w=new Array(b-1);T<b;T++)w[T-1]=arguments[T];y[S].fn.apply(y[S].context,w)}}return!0},d.prototype.on=function(l,c,u){return s(this,l,c,u,!1)},d.prototype.once=function(l,c,u){return s(this,l,c,u,!0)},d.prototype.removeListener=function(l,c,u,f){var h=n?n+l:l;if(!this._events[h])return this;if(!c)return o(this,h),this;var p=this._events[h];if(p.fn)p.fn===c&&(!f||p.once)&&(!u||p.context===u)&&o(this,h);else{for(var m=0,y=[],b=p.length;m<b;m++)(p[m].fn!==c||f&&!p[m].once||u&&p[m].context!==u)&&y.push(p[m]);y.length?this._events[h]=y.length===1?y[0]:y:o(this,h)}return this},d.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&o(this,c)):(this._events=new i,this._eventsCount=0),this},d.prototype.off=d.prototype.removeListener,d.prototype.addListener=d.prototype.on,d.prefixed=n,d.EventEmitter=d,typeof e<"u"&&(e.exports=d)}),ide=Qt((t,e)=>{e.exports=typeof queueMicrotask=="function"?queueMicrotask:r=>Promise.resolve().then(r)}),W2=Qt(t=>{"use strict";var e=ide();t.fromCallback=function(r,n){if(r===void 0){var i=new Promise(function(a,s){r=function(o,d){o?s(o):a(d)}});r[n!==void 0?n:"promise"]=i}else if(typeof r!="function")throw new TypeError("Callback must be a function");return r},t.fromPromise=function(r,n){if(n===void 0)return r;r.then(function(i){e(()=>n(null,i))}).catch(function(i){e(()=>n(i))})}}),p6=Qt(t=>{"use strict";t.getCallback=function(e,r){return typeof e=="function"?e:r},t.getOptions=function(e,r){return typeof e=="object"&&e!==null?e:r!==void 0?r:{}}}),oh=Qt(t=>{"use strict";var{fromCallback:e}=W2(),r=Td(),{getOptions:n,getCallback:i}=p6(),a=Symbol("promise"),s=Symbol("callback"),o=Symbol("working"),d=Symbol("handleOne"),l=Symbol("handleMany"),c=Symbol("autoClose"),u=Symbol("finishWork"),f=Symbol("returnMany"),h=Symbol("closing"),p=Symbol("handleClose"),m=Symbol("closed"),y=Symbol("closeCallbacks"),b=Symbol("keyEncoding"),w=Symbol("valueEncoding"),S=Symbol("abortOnClose"),k=Symbol("legacy"),T=Symbol("keys"),D=Symbol("values"),K=Symbol("limit"),C=Symbol("count"),G=Object.freeze({}),z=()=>{},N=!1,V=class{constructor(E,x,A){if(typeof E!="object"||E===null){let I=E===null?"null":typeof E;throw new TypeError(`The first argument must be an abstract-level database, received ${I}`)}if(typeof x!="object"||x===null)throw new TypeError("The second argument must be an options object");this[m]=!1,this[y]=[],this[o]=!1,this[h]=!1,this[c]=!1,this[s]=null,this[d]=this[d].bind(this),this[l]=this[l].bind(this),this[p]=this[p].bind(this),this[b]=x[b],this[w]=x[w],this[k]=A,this[K]=Number.isInteger(x.limit)&&x.limit>=0?x.limit:1/0,this[C]=0,this[S]=!!x.abortOnClose,this.db=E,this.db.attachResource(this),this.nextTick=E.nextTick}get count(){return this[C]}get limit(){return this[K]}next(E){let x;if(E===void 0)x=new Promise((A,I)=>{E=(M,q,H)=>{M?I(M):this[k]?q===void 0&&H===void 0?A():A([q,H]):A(q)}});else if(typeof E!="function")throw new TypeError("Callback must be a function");return this[h]?this.nextTick(E,new r("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[o]?this.nextTick(E,new r("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[o]=!0,this[s]=E,this[C]>=this[K]?this.nextTick(this[d],null):this._next(this[d])),x}_next(E){this.nextTick(E)}nextv(E,x,A){return A=i(x,A),A=e(A,a),x=n(x,G),Number.isInteger(E)?(this[h]?this.nextTick(A,new r("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[o]?this.nextTick(A,new r("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(E<1&&(E=1),this[K]<1/0&&(E=Math.min(E,this[K]-this[C])),this[o]=!0,this[s]=A,E<=0?this.nextTick(this[l],null,[]):this._nextv(E,x,this[l])),A[a]):(this.nextTick(A,new TypeError("The first argument 'size' must be an integer")),A[a])}_nextv(E,x,A){let I=[],M=(q,H,W)=>{if(q)return A(q);if(this[k]?H===void 0&&W===void 0:H===void 0)return A(null,I);I.push(this[k]?[H,W]:H),I.length===E?A(null,I):this._next(M)};this._next(M)}all(E,x){return x=i(E,x),x=e(x,a),E=n(E,G),this[h]?this.nextTick(x,new r("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[o]?this.nextTick(x,new r("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[o]=!0,this[s]=x,this[c]=!0,this[C]>=this[K]?this.nextTick(this[l],null,[]):this._all(E,this[l])),x[a]}_all(E,x){let A=this[C],I=[],M=()=>{let H=this[K]<1/0?Math.min(1e3,this[K]-A):1e3;H<=0?this.nextTick(x,null,I):this._nextv(H,G,q)},q=(H,W)=>{H?x(H):W.length===0?x(null,I):(I.push.apply(I,W),A+=W.length,M())};M()}[u](){let E=this[s];return this[S]&&E===null?z:(this[o]=!1,this[s]=null,this[h]&&this._close(this[p]),E)}[f](E,x,A){this[c]?this.close(E.bind(null,x,A)):E(x,A)}seek(E,x){if(x=n(x,G),!this[h]){if(this[o])throw new r("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let A=this.db.keyEncoding(x.keyEncoding||this[b]),I=A.format;x.keyEncoding!==I&&(x={...x,keyEncoding:I});let M=this.db.prefixKey(A.encode(E),I);this._seek(M,x)}}}_seek(E,x){throw new r("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(E){return E=e(E,a),this[m]?this.nextTick(E):this[h]?this[y].push(E):(this[h]=!0,this[y].push(E),this[o]?this[S]&&this[u]()(new r("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[p])),E[a]}_close(E){this.nextTick(E)}[p](){this[m]=!0,this.db.detachResource(this);let E=this[y];this[y]=[];for(let x of E)x()}async*[Symbol.asyncIterator](){try{let E;for(;(E=await this.next())!==void 0;)yield E}finally{this[m]||await this.close()}}},ee=class extends V{constructor(E,x){super(E,x,!0),this[T]=x.keys!==!1,this[D]=x.values!==!1}[d](E,x,A){let I=this[u]();if(E)return I(E);try{x=this[T]&&x!==void 0?this[b].decode(x):void 0,A=this[D]&&A!==void 0?this[w].decode(A):void 0}catch(M){return I(new P("entry",M))}x===void 0&&A===void 0||this[C]++,I(null,x,A)}[l](E,x){let A=this[u]();if(E)return this[f](A,E);try{for(let I of x){let M=I[0],q=I[1];I[0]=this[T]&&M!==void 0?this[b].decode(M):void 0,I[1]=this[D]&&q!==void 0?this[w].decode(q):void 0}}catch(I){return this[f](A,new P("entries",I))}this[C]+=x.length,this[f](A,null,x)}end(E){return!N&&typeof console<"u"&&(N=!0,console.warn(new r("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(E)}},R=class extends V{constructor(E,x){super(E,x,!1)}[d](E,x){let A=this[u]();if(E)return A(E);try{x=x!==void 0?this[b].decode(x):void 0}catch(I){return A(new P("key",I))}x!==void 0&&this[C]++,A(null,x)}[l](E,x){let A=this[u]();if(E)return this[f](A,E);try{for(let I=0;I<x.length;I++){let M=x[I];x[I]=M!==void 0?this[b].decode(M):void 0}}catch(I){return this[f](A,new P("keys",I))}this[C]+=x.length,this[f](A,null,x)}},B=class extends V{constructor(E,x){super(E,x,!1)}[d](E,x){let A=this[u]();if(E)return A(E);try{x=x!==void 0?this[w].decode(x):void 0}catch(I){return A(new P("value",I))}x!==void 0&&this[C]++,A(null,x)}[l](E,x){let A=this[u]();if(E)return this[f](A,E);try{for(let I=0;I<x.length;I++){let M=x[I];x[I]=M!==void 0?this[w].decode(M):void 0}}catch(I){return this[f](A,new P("values",I))}this[C]+=x.length,this[f](A,null,x)}},P=class extends r{constructor(E,x){super(`Iterator could not decode ${E}`,{code:"LEVEL_DECODE_ERROR",cause:x})}};for(let E of["_ended property","_nexting property","_end method"])Object.defineProperty(ee.prototype,E.split(" ")[0],{get(){throw new r(`The ${E} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new r(`The ${E} has been removed`,{code:"LEVEL_LEGACY"})}});ee.keyEncoding=b,ee.valueEncoding=w,t.AbstractIterator=ee,t.AbstractKeyIterator=R,t.AbstractValueIterator=B}),sde=Qt(t=>{"use strict";var{AbstractKeyIterator:e,AbstractValueIterator:r}=oh(),n=Symbol("iterator"),i=Symbol("callback"),a=Symbol("handleOne"),s=Symbol("handleMany"),o=class extends e{constructor(l,c){super(l,c),this[n]=l.iterator({...c,keys:!0,values:!1}),this[a]=this[a].bind(this),this[s]=this[s].bind(this)}},d=class extends r{constructor(l,c){super(l,c),this[n]=l.iterator({...c,keys:!1,values:!0}),this[a]=this[a].bind(this),this[s]=this[s].bind(this)}};for(let l of[o,d]){let c=l===o,u=c?f=>f[0]:f=>f[1];l.prototype._next=function(f){this[i]=f,this[n].next(this[a])},l.prototype[a]=function(f,h,p){let m=this[i];f?m(f):m(null,c?h:p)},l.prototype._nextv=function(f,h,p){this[i]=p,this[n].nextv(f,h,this[s])},l.prototype._all=function(f,h){this[i]=h,this[n].all(f,this[s])},l.prototype[s]=function(f,h){let p=this[i];f?p(f):p(null,h.map(u))},l.prototype._seek=function(f,h){this[n].seek(f,h)},l.prototype._close=function(f){this[n].close(f)}}t.DefaultKeyIterator=o,t.DefaultValueIterator=d}),ode=Qt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=oh(),i=Td(),a=Symbol("nut"),s=Symbol("undefer"),o=Symbol("factory"),d=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 r{constructor(u,f){super(u,f),this[a]=null,this[o]=()=>u.keys(f),this.db.defer(()=>this[s]())}},c=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[d,l,c])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,h,p){this[a]!==null?this[a].nextv(f,h,p):this.db.status==="opening"?this.db.defer(()=>this._nextv(f,h,p)):this.nextTick(p,new i("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._all=function(f,h){this[a]!==null?this[a].all(h):this.db.status==="opening"?this.db.defer(()=>this._all(f,h)):this.nextTick(h,new i("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},u.prototype._seek=function(f,h){this[a]!==null?this[a]._seek(f,h):this.db.status==="opening"&&this.db.defer(()=>this._seek(f,h))},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)};t.DeferredIterator=d,t.DeferredKeyIterator=l,t.DeferredValueIterator=c}),Gq=Qt(t=>{"use strict";var{fromCallback:e}=W2(),r=Td(),{getCallback:n,getOptions:i}=p6(),a=Symbol("promise"),s=Symbol("status"),o=Symbol("operations"),d=Symbol("finishClose"),l=Symbol("closeCallbacks"),c=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[d]=this[d].bind(this),this.db=u,this.db.attachResource(this),this.nextTick=u.nextTick}get length(){return this[o].length}put(u,f,h){if(this[s]!=="open")throw new r("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let p=this.db._checkKey(u)||this.db._checkValue(f);if(p)throw p;let m=h&&h.sublevel!=null?h.sublevel:this.db,y=h,b=m.keyEncoding(h&&h.keyEncoding),w=m.valueEncoding(h&&h.valueEncoding),S=b.format;h={...h,keyEncoding:S,valueEncoding:w.format},m!==this.db&&(h.sublevel=null);let k=m.prefixKey(b.encode(u),S),T=w.encode(f);return this._put(k,T,h),this[o].push({...y,type:"put",key:u,value:f}),this}_put(u,f,h){}del(u,f){if(this[s]!=="open")throw new r("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let h=this.db._checkKey(u);if(h)throw h;let p=f&&f.sublevel!=null?f.sublevel:this.db,m=f,y=p.keyEncoding(f&&f.keyEncoding),b=y.format;return f={...f,keyEncoding:b},p!==this.db&&(f.sublevel=null),this._del(p.prefixKey(y.encode(u),b),f),this[o].push({...m,type:"del",key:u}),this}_del(u,f){}clear(){if(this[s]!=="open")throw new r("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 r("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,h=>{this[s]="closing",this[l].push(()=>f(h)),h||this.db.emit("batch",this[o]),this._close(this[d])})),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[d]))),u[a]}_close(u){this.nextTick(u)}[d](){this[s]="closed",this.db.detachResource(this);let u=this[l];this[l]=[];for(let f of u)f()}};t.AbstractChainedBatch=c}),ade=Qt(t=>{"use strict";var{AbstractChainedBatch:e}=Gq(),r=Td(),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 r("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};t.DefaultChainedBatch=i}),cde=Qt((t,e)=>{"use strict";var r=Td(),n=Object.prototype.hasOwnProperty,i=new Set(["lt","lte","gt","gte"]);e.exports=function(a,s){let o={};for(let d in a)if(n.call(a,d)&&!(d==="keyEncoding"||d==="valueEncoding")){if(d==="start"||d==="end")throw new r(`The legacy range option '${d}' has been removed`,{code:"LEVEL_LEGACY"});if(d==="encoding")throw new r("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});i.has(d)?o[d]=s.encode(a[d]):o[d]=a[d]}return o.reverse=!!o.reverse,o.limit=Number.isInteger(o.limit)&&o.limit>=0?o.limit:-1,o}}),Hq=Qt((t,e)=>{var r;e.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):n=>(r||(r=Promise.resolve())).then(n).catch(i=>setTimeout(()=>{throw i},0))}),dde=Qt((t,e)=>{"use strict";var r=Hq();e.exports=function(n,...i){i.length===0?r(n):r(()=>n(...i))}}),lde=Qt(t=>{"use strict";var{AbstractIterator:e,AbstractKeyIterator:r,AbstractValueIterator:n}=oh(),i=Symbol("unfix"),a=Symbol("iterator"),s=Symbol("handleOne"),o=Symbol("handleMany"),d=Symbol("callback"),l=class extends e{constructor(f,h,p,m){super(f,h),this[a]=p,this[i]=m,this[s]=this[s].bind(this),this[o]=this[o].bind(this),this[d]=null}[s](f,h,p){let m=this[d];if(f)return m(f);h!==void 0&&(h=this[i](h)),m(f,h,p)}[o](f,h){let p=this[d];if(f)return p(f);for(let m of h){let y=m[0];y!==void 0&&(m[0]=this[i](y))}p(f,h)}},c=class extends r{constructor(f,h,p,m){super(f,h),this[a]=p,this[i]=m,this[s]=this[s].bind(this),this[o]=this[o].bind(this),this[d]=null}[s](f,h){let p=this[d];if(f)return p(f);h!==void 0&&(h=this[i](h)),p(f,h)}[o](f,h){let p=this[d];if(f)return p(f);for(let m=0;m<h.length;m++){let y=h[m];y!==void 0&&(h[m]=this[i](y))}p(f,h)}},u=class extends n{constructor(f,h,p){super(f,h),this[a]=p}};for(let f of[l,c])f.prototype._next=function(h){this[d]=h,this[a].next(this[s])},f.prototype._nextv=function(h,p,m){this[d]=m,this[a].nextv(h,p,this[o])},f.prototype._all=function(h,p){this[d]=p,this[a].all(h,this[o])};for(let f of[u])f.prototype._next=function(h){this[a].next(h)},f.prototype._nextv=function(h,p,m){this[a].nextv(h,p,m)},f.prototype._all=function(h,p){this[a].all(h,p)};for(let f of[l,c,u])f.prototype._seek=function(h,p){this[a].seek(h,p)},f.prototype._close=function(h){this[a].close(h)};t.AbstractSublevelIterator=l,t.AbstractSublevelKeyIterator=c,t.AbstractSublevelValueIterator=u}),ude=Qt((t,e)=>{"use strict";var r=Td(),{Buffer:n}=f6()||{},{AbstractSublevelIterator:i,AbstractSublevelKeyIterator:a,AbstractSublevelValueIterator:s}=lde(),o=Symbol("prefix"),d=Symbol("upperBound"),l=Symbol("prefixRange"),c=Symbol("parent"),u=Symbol("unfix"),f=new TextEncoder,h={separator:"!"};e.exports=function({AbstractLevel:S}){class k extends S{static defaults(D){if(typeof D=="string")throw new r("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(D&&D.open)throw new r("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return D==null?h:D.separator?D:{...D,separator:"!"}}constructor(D,K,C){let{separator:G,manifest:z,...N}=k.defaults(C);K=w(K,G);let V=G.charCodeAt(0)+1,ee=D[c]||D;if(!f.encode(K).every(P=>P>V&&P<127))throw new r(`Prefix must use bytes > ${V} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(p(ee,z),N);let R=(D.prefix||"")+G+K+G,B=R.slice(0,-1)+String.fromCharCode(V);this[c]=ee,this[o]=new y(R),this[d]=new y(B),this[u]=new b,this.nextTick=ee.nextTick}prefixKey(D,K){if(K==="utf8")return this[o].utf8+D;if(D.byteLength===0)return this[o][K];if(K==="view"){let C=this[o].view,G=new Uint8Array(C.byteLength+D.byteLength);return G.set(C,0),G.set(D,C.byteLength),G}else{let C=this[o].buffer;return n.concat([C,D],C.byteLength+D.byteLength)}}[l](D,K){D.gte!==void 0?D.gte=this.prefixKey(D.gte,K):D.gt!==void 0?D.gt=this.prefixKey(D.gt,K):D.gte=this[o][K],D.lte!==void 0?D.lte=this.prefixKey(D.lte,K):D.lt!==void 0?D.lt=this.prefixKey(D.lt,K):D.lte=this[d][K]}get prefix(){return this[o].utf8}get db(){return this[c]}_open(D,K){this[c].open({passive:!0},K)}_put(D,K,C,G){this[c].put(D,K,C,G)}_get(D,K,C){this[c].get(D,K,C)}_getMany(D,K,C){this[c].getMany(D,K,C)}_del(D,K,C){this[c].del(D,K,C)}_batch(D,K,C){this[c].batch(D,K,C)}_clear(D,K){this[l](D,D.keyEncoding),this[c].clear(D,K)}_iterator(D){this[l](D,D.keyEncoding);let K=this[c].iterator(D),C=this[u].get(this[o].utf8.length,D.keyEncoding);return new i(this,D,K,C)}_keys(D){this[l](D,D.keyEncoding);let K=this[c].keys(D),C=this[u].get(this[o].utf8.length,D.keyEncoding);return new a(this,D,K,C)}_values(D){this[l](D,D.keyEncoding);let K=this[c].values(D);return new s(this,D,K)}}return{AbstractSublevel:k}};var p=function(S,k){return{...S.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...k,encodings:{utf8:m(S,"utf8"),buffer:m(S,"buffer"),view:m(S,"view")}}},m=function(S,k){return S.supports.encodings[k]?S.keyEncoding(k).name===k:!1},y=class{constructor(S){this.utf8=S,this.view=f.encode(S),this.buffer=n?n.from(this.view.buffer,0,this.view.byteLength):{}}},b=class{constructor(){this.cache=new Map}get(S,k){let T=this.cache.get(k);return T===void 0&&(k==="view"?T=(function(D,K){return K.subarray(D)}).bind(null,S):T=(function(D,K){return K.slice(D)}).bind(null,S),this.cache.set(k,T)),T}},w=function(S,k){let T=0,D=S.length;for(;T<D&&S[T]===k;)T++;for(;D>T&&S[D-1]===k;)D--;return S.slice(T,D)}}),A9=Qt(t=>{"use strict";var{supports:e}=Xce(),{Transcoder:r}=rde(),{EventEmitter:n}=nde(),{fromCallback:i}=W2(),a=Td(),{AbstractIterator:s}=oh(),{DefaultKeyIterator:o,DefaultValueIterator:d}=sde(),{DeferredIterator:l,DeferredKeyIterator:c,DeferredValueIterator:u}=ode(),{DefaultChainedBatch:f}=ade(),{getCallback:h,getOptions:p}=p6(),m=cde(),y=Symbol("promise"),b=Symbol("landed"),w=Symbol("resources"),S=Symbol("closeResources"),k=Symbol("operations"),T=Symbol("undefer"),D=Symbol("deferOpen"),K=Symbol("options"),C=Symbol("status"),G=Symbol("defaultOptions"),z=Symbol("transcoder"),N=Symbol("keyEncoding"),V=Symbol("valueEncoding"),ee=()=>{},R=class extends n{constructor(x,A){if(super(),typeof x!="object"||x===null)throw new TypeError("The first argument 'manifest' must be an object");A=p(A);let{keyEncoding:I,valueEncoding:M,passive:q,...H}=A;this[w]=new Set,this[k]=[],this[D]=!0,this[K]=H,this[C]="opening",this.supports=e(x,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:x.snapshots!==!1,permanence:x.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:x.encodings||{},events:Object.assign({},x.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[z]=new r(E(this)),this[N]=this[z].encoding(I||"utf8"),this[V]=this[z].encoding(M||"utf8");for(let W of this[z].encodings())this.supports.encodings[W.commonName]||(this.supports.encodings[W.commonName]=!0);this[G]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[N].commonName,valueEncoding:this[V].commonName}),key:Object.freeze({keyEncoding:this[N].commonName})},this.nextTick(()=>{this[D]&&this.open({passive:!1},ee)})}get status(){return this[C]}keyEncoding(x){return this[z].encoding(x??this[N])}valueEncoding(x){return this[z].encoding(x??this[V])}open(x,A){A=h(x,A),A=i(A,y),x={...this[K],...p(x)},x.createIfMissing=x.createIfMissing!==!1,x.errorIfExists=!!x.errorIfExists;let I=M=>{this[C]==="closing"||this[C]==="opening"?this.once(b,M?()=>I(M):I):this[C]!=="open"?A(new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:M})):A()};return x.passive?this[C]==="opening"?this.once(b,I):this.nextTick(I):this[C]==="closed"||this[D]?(this[D]=!1,this[C]="opening",this.emit("opening"),this._open(x,M=>{if(M){this[C]="closed",this[S](()=>{this.emit(b),I(M)}),this[T]();return}this[C]="open",this[T](),this.emit(b),this[C]==="open"&&this.emit("open"),this[C]==="open"&&this.emit("ready"),I()})):this[C]==="open"?this.nextTick(I):this.once(b,()=>this.open(x,A)),A[y]}_open(x,A){this.nextTick(A)}close(x){x=i(x,y);let A=I=>{this[C]==="opening"||this[C]==="closing"?this.once(b,I?A(I):A):this[C]!=="closed"?x(new a("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:I})):x()};if(this[C]==="open"){this[C]="closing",this.emit("closing");let I=M=>{this[C]="open",this[T](),this.emit(b),A(M)};this[S](()=>{this._close(M=>{if(M)return I(M);this[C]="closed",this[T](),this.emit(b),this[C]==="closed"&&this.emit("closed"),A()})})}else this[C]==="closed"?this.nextTick(A):this.once(b,()=>this.close(x));return x[y]}[S](x){if(this[w].size===0)return this.nextTick(x);let A=this[w].size,I=!0,M=()=>{--A===0&&(I?this.nextTick(x):x())};for(let q of this[w])q.close(M);I=!1,this[w].clear()}_close(x){this.nextTick(x)}get(x,A,I){if(I=h(A,I),I=i(I,y),A=p(A,this[G].entry),this[C]==="opening")return this.defer(()=>this.get(x,A,I)),I[y];if(P(this,I))return I[y];let M=this._checkKey(x);if(M)return this.nextTick(I,M),I[y];let q=this.keyEncoding(A.keyEncoding),H=this.valueEncoding(A.valueEncoding),W=q.format,J=H.format;return(A.keyEncoding!==W||A.valueEncoding!==J)&&(A=Object.assign({},A,{keyEncoding:W,valueEncoding:J})),this._get(this.prefixKey(q.encode(x),W),A,(X,L)=>{if(X)return(X.code==="LEVEL_NOT_FOUND"||X.notFound||/NotFound/i.test(X))&&(X.code||(X.code="LEVEL_NOT_FOUND"),X.notFound||(X.notFound=!0),X.status||(X.status=404)),I(X);try{L=H.decode(L)}catch(Q){return I(new a("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:Q}))}I(null,L)}),I[y]}_get(x,A,I){this.nextTick(I,new Error("NotFound"))}getMany(x,A,I){if(I=h(A,I),I=i(I,y),A=p(A,this[G].entry),this[C]==="opening")return this.defer(()=>this.getMany(x,A,I)),I[y];if(P(this,I))return I[y];if(!Array.isArray(x))return this.nextTick(I,new TypeError("The first argument 'keys' must be an array")),I[y];if(x.length===0)return this.nextTick(I,null,[]),I[y];let M=this.keyEncoding(A.keyEncoding),q=this.valueEncoding(A.valueEncoding),H=M.format,W=q.format;(A.keyEncoding!==H||A.valueEncoding!==W)&&(A=Object.assign({},A,{keyEncoding:H,valueEncoding:W}));let J=new Array(x.length);for(let X=0;X<x.length;X++){let L=x[X],Q=this._checkKey(L);if(Q)return this.nextTick(I,Q),I[y];J[X]=this.prefixKey(M.encode(L),H)}return this._getMany(J,A,(X,L)=>{if(X)return I(X);try{for(let Q=0;Q<L.length;Q++)L[Q]!==void 0&&(L[Q]=q.decode(L[Q]))}catch(Q){return I(new a(`Could not decode one or more of ${L.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:Q}))}I(null,L)}),I[y]}_getMany(x,A,I){this.nextTick(I,null,new Array(x.length).fill(void 0))}put(x,A,I,M){if(M=h(I,M),M=i(M,y),I=p(I,this[G].entry),this[C]==="opening")return this.defer(()=>this.put(x,A,I,M)),M[y];if(P(this,M))return M[y];let q=this._checkKey(x)||this._checkValue(A);if(q)return this.nextTick(M,q),M[y];let H=this.keyEncoding(I.keyEncoding),W=this.valueEncoding(I.valueEncoding),J=H.format,X=W.format;(I.keyEncoding!==J||I.valueEncoding!==X)&&(I=Object.assign({},I,{keyEncoding:J,valueEncoding:X}));let L=this.prefixKey(H.encode(x),J),Q=W.encode(A);return this._put(L,Q,I,se=>{if(se)return M(se);this.emit("put",x,A),M()}),M[y]}_put(x,A,I,M){this.nextTick(M)}del(x,A,I){if(I=h(A,I),I=i(I,y),A=p(A,this[G].key),this[C]==="opening")return this.defer(()=>this.del(x,A,I)),I[y];if(P(this,I))return I[y];let M=this._checkKey(x);if(M)return this.nextTick(I,M),I[y];let q=this.keyEncoding(A.keyEncoding),H=q.format;return A.keyEncoding!==H&&(A=Object.assign({},A,{keyEncoding:H})),this._del(this.prefixKey(q.encode(x),H),A,W=>{if(W)return I(W);this.emit("del",x),I()}),I[y]}_del(x,A,I){this.nextTick(I)}batch(x,A,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 x=="function"?I=x:I=h(A,I),I=i(I,y),A=p(A,this[G].empty),this[C]==="opening")return this.defer(()=>this.batch(x,A,I)),I[y];if(P(this,I))return I[y];if(!Array.isArray(x))return this.nextTick(I,new TypeError("The first argument 'operations' must be an array")),I[y];if(x.length===0)return this.nextTick(I),I[y];let M=new Array(x.length),{keyEncoding:q,valueEncoding:H,...W}=A;for(let J=0;J<x.length;J++){if(typeof x[J]!="object"||x[J]===null)return this.nextTick(I,new TypeError("A batch operation must be an object")),I[y];let X=Object.assign({},x[J]);if(X.type!=="put"&&X.type!=="del")return this.nextTick(I,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),I[y];let L=this._checkKey(X.key);if(L)return this.nextTick(I,L),I[y];let Q=X.sublevel!=null?X.sublevel:this,se=Q.keyEncoding(X.keyEncoding||q),re=se.format;if(X.key=Q.prefixKey(se.encode(X.key),re),X.keyEncoding=re,X.type==="put"){let Y=this._checkValue(X.value);if(Y)return this.nextTick(I,Y),I[y];let le=Q.valueEncoding(X.valueEncoding||H);X.value=le.encode(X.value),X.valueEncoding=le.format}Q!==this&&(X.sublevel=null),M[J]=X}return this._batch(M,W,J=>{if(J)return I(J);this.emit("batch",x),I()}),I[y]}_batch(x,A,I){this.nextTick(I)}sublevel(x,A){return this._sublevel(x,B.defaults(A))}_sublevel(x,A){return new B(this,x,A)}prefixKey(x,A){return x}clear(x,A){if(A=h(x,A),A=i(A,y),x=p(x,this[G].empty),this[C]==="opening")return this.defer(()=>this.clear(x,A)),A[y];if(P(this,A))return A[y];let I=x,M=this.keyEncoding(x.keyEncoding);return x=m(x,M),x.keyEncoding=M.format,x.limit===0?this.nextTick(A):this._clear(x,q=>{if(q)return A(q);this.emit("clear",I),A()}),A[y]}_clear(x,A){this.nextTick(A)}iterator(x){let A=this.keyEncoding(x&&x.keyEncoding),I=this.valueEncoding(x&&x.valueEncoding);if(x=m(x,A),x.keys=x.keys!==!1,x.values=x.values!==!1,x[s.keyEncoding]=A,x[s.valueEncoding]=I,x.keyEncoding=A.format,x.valueEncoding=I.format,this[C]==="opening")return new l(this,x);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(x)}_iterator(x){return new s(this,x)}keys(x){let A=this.keyEncoding(x&&x.keyEncoding),I=this.valueEncoding(x&&x.valueEncoding);if(x=m(x,A),x[s.keyEncoding]=A,x[s.valueEncoding]=I,x.keyEncoding=A.format,x.valueEncoding=I.format,this[C]==="opening")return new c(this,x);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(x)}_keys(x){return new o(this,x)}values(x){let A=this.keyEncoding(x&&x.keyEncoding),I=this.valueEncoding(x&&x.valueEncoding);if(x=m(x,A),x[s.keyEncoding]=A,x[s.valueEncoding]=I,x.keyEncoding=A.format,x.valueEncoding=I.format,this[C]==="opening")return new u(this,x);if(this[C]!=="open")throw new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(x)}_values(x){return new d(this,x)}defer(x){if(typeof x!="function")throw new TypeError("The first argument must be a function");this[k].push(x)}[T](){if(this[k].length===0)return;let x=this[k];this[k]=[];for(let A of x)A()}attachResource(x){if(typeof x!="object"||x===null||typeof x.close!="function")throw new TypeError("The first argument must be a resource object");this[w].add(x)}detachResource(x){this[w].delete(x)}_chainedBatch(){return new f(this)}_checkKey(x){if(x==null)return new a("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(x){if(x==null)return new a("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};R.prototype.nextTick=dde();var{AbstractSublevel:B}=ude()({AbstractLevel:R});t.AbstractLevel=R,t.AbstractSublevel=B;var P=function(x,A){return x[C]!=="open"?(x.nextTick(A,new a("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},E=function(x){return Object.keys(x.supports.encodings).filter(A=>!!x.supports.encodings[A])}}),Vq=Qt(t=>{"use strict";t.AbstractLevel=A9().AbstractLevel,t.AbstractSublevel=A9().AbstractSublevel,t.AbstractIterator=oh().AbstractIterator,t.AbstractKeyIterator=oh().AbstractKeyIterator,t.AbstractValueIterator=oh().AbstractValueIterator,t.AbstractChainedBatch=Gq().AbstractChainedBatch}),fde=Qt((t,e)=>{e.exports=n;var r=Hq();function n(i,a,s){if(typeof a!="number")throw new Error("second argument must be a Number");let o,d,l,c,u,f=!0,h;Array.isArray(i)?(o=[],l=d=i.length):(c=Object.keys(i),o={},l=d=c.length);function p(y){function b(){s&&s(y,o),s=null}f?r(b):b()}function m(y,b,w){if(o[y]=w,b&&(u=!0),--l===0||b)p(b);else if(!u&&h<d){let S;c?(S=c[h],h+=1,i[S](function(k,T){m(S,k,T)})):(S=h,h+=1,i[S](function(k,T){m(S,k,T)}))}}h=a,l?c?c.some(function(y,b){return i[y](function(w,S){m(y,w,S)}),b===a-1}):i.some(function(y,b){return y(function(w,S){m(b,w,S)}),b===a-1}):p(null),f=!1}}),Wq=Qt((t,e)=>{"use strict";e.exports=function(r){let n=r.gte!==void 0?r.gte:r.gt!==void 0?r.gt:void 0,i=r.lte!==void 0?r.lte:r.lt!==void 0?r.lt:void 0,a=r.gte===void 0,s=r.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}}),Jq=Qt((t,e)=>{"use strict";var r=new TextEncoder;e.exports=function(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):r.encode(n)}}),pde=Qt(t=>{"use strict";var{AbstractIterator:e}=Vq(),r=Wq(),n=Jq(),i=Symbol("cache"),a=Symbol("finished"),s=Symbol("options"),o=Symbol("currentOptions"),d=Symbol("position"),l=Symbol("location"),c=Symbol("first"),u={},f=class extends e{constructor(p,m,y){super(p,y),this[i]=[],this[a]=this.limit===0,this[s]=y,this[o]={...y},this[d]=void 0,this[l]=m,this[c]=!0}_nextv(p,m,y){if(this[c]=!1,this[a])return this.nextTick(y,null,[]);if(this[i].length>0)return p=Math.min(p,this[i].length),this.nextTick(y,null,this[i].splice(0,p));this[d]!==void 0&&(this[s].reverse?(this[o].lt=this[d],this[o].lte=void 0):(this[o].gt=this[d],this[o].gte=void 0));let b;try{b=r(this[o])}catch{return this[a]=!0,this.nextTick(y,null,[])}let w=this.db.db.transaction([this[l]],"readonly"),S=w.objectStore(this[l]),k=[];if(this[s].reverse){let T=!this[s].values&&S.openKeyCursor?"openKeyCursor":"openCursor";S[T](b,"prev").onsuccess=D=>{let K=D.target.result;if(K){let{key:C,value:G}=K;this[d]=C,k.push([this[s].keys&&C!==void 0?n(C):void 0,this[s].values&&G!==void 0?n(G):void 0]),k.length<p?K.continue():h(w)}else this[a]=!0}}else{let T,D,K=()=>{if(T===void 0||D===void 0)return;let C=Math.max(T.length,D.length);C===0||p===1/0?this[a]=!0:this[d]=T[C-1],k.length=C;for(let G=0;G<C;G++){let z=T[G],N=D[G];k[G]=[this[s].keys&&z!==void 0?n(z):void 0,this[s].values&&N!==void 0?n(N):void 0]}h(w)};this[s].keys||p<1/0?S.getAllKeys(b,p<1/0?p:void 0).onsuccess=C=>{T=C.target.result,K()}:(T=[],this.nextTick(K)),this[s].values?S.getAll(b,p<1/0?p:void 0).onsuccess=C=>{D=C.target.result,K()}:(D=[],this.nextTick(K))}w.onabort=()=>{y(w.error||new Error("aborted by user")),y=null},w.oncomplete=()=>{y(null,k),y=null}}_next(p){if(this[i].length>0){let[m,y]=this[i].shift();this.nextTick(p,null,m,y)}else if(this[a])this.nextTick(p);else{let m=Math.min(100,this.limit-this.count);this[c]&&(this[c]=!1,m=1),this._nextv(m,u,(y,b)=>{if(y)return p(y);this[i]=b,this._next(p)})}}_all(p,m){this[c]=!1;let y=this[i].splice(0,this[i].length),b=this.limit-this.count-y.length;if(b<=0)return this.nextTick(m,null,y);this._nextv(b,u,(w,S)=>{if(w)return m(w);y.length>0&&(S=y.concat(S)),m(null,S)})}_seek(p,m){this[c]=!0,this[i]=[],this[a]=!1,this[d]=void 0,this[o]={...this[s]};let y;try{y=r(this[s])}catch{this[a]=!0;return}y!==null&&!y.includes(p)?this[a]=!0:this[s].reverse?this[o].lte=p:this[o].gte=p}};t.Iterator=f;function h(p){typeof p.commit=="function"&&p.commit()}}),hde=Qt((t,e)=>{"use strict";e.exports=function(r,n,i,a,s){if(a.limit===0)return r.nextTick(s);let o=r.db.transaction([n],"readwrite"),d=o.objectStore(n),l=0;o.oncomplete=function(){s()},o.onabort=function(){s(o.error||new Error("aborted by user"))};let c=d.openKeyCursor?"openKeyCursor":"openCursor",u=a.reverse?"prev":"next";d[c](i,u).onsuccess=function(f){let h=f.target.result;h&&(d.delete(h.key).onsuccess=function(){(a.limit<=0||++l<a.limit)&&h.continue()})}}}),mde=Qt(t=>{"use strict";var{AbstractLevel:e}=Vq(),r=Td(),n=fde(),{fromCallback:i}=W2(),{Iterator:a}=pde(),s=Jq(),o=hde(),d=Wq(),l="level-js-",c=Symbol("idb"),u=Symbol("namePrefix"),f=Symbol("location"),h=Symbol("version"),p=Symbol("store"),m=Symbol("onComplete"),y=Symbol("promise"),b=class extends e{constructor(w,S,k){if(typeof S=="function"||typeof k=="function")throw new r("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:T,version:D,...K}=S||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},K),typeof w!="string")throw new Error("constructor requires a location string argument");this[f]=w,this[u]=T??l,this[h]=parseInt(D||1,10),this[c]=null}get location(){return this[f]}get namePrefix(){return this[u]}get version(){return this[h]}get db(){return this[c]}get type(){return"browser-level"}_open(w,S){let k=indexedDB.open(this[u]+this[f],this[h]);k.onerror=function(){S(k.error||new Error("unknown error"))},k.onsuccess=()=>{this[c]=k.result,S()},k.onupgradeneeded=T=>{let D=T.target.result;D.objectStoreNames.contains(this[f])||D.createObjectStore(this[f])}}[p](w){return this[c].transaction([this[f]],w).objectStore(this[f])}[m](w,S){let k=w.transaction;k.onabort=function(){S(k.error||new Error("aborted by user"))},k.oncomplete=function(){S(null,w.result)}}_get(w,S,k){let T=this[p]("readonly"),D;try{D=T.get(w)}catch(K){return this.nextTick(k,K)}this[m](D,function(K,C){if(K)return k(K);if(C===void 0)return k(new r("Entry not found",{code:"LEVEL_NOT_FOUND"}));k(null,s(C))})}_getMany(w,S,k){let T=this[p]("readonly"),D=w.map(K=>C=>{let G;try{G=T.get(K)}catch(z){return C(z)}G.onsuccess=()=>{let z=G.result;C(null,z===void 0?z:s(z))},G.onerror=z=>{z.stopPropagation(),C(G.error)}});n(D,16,k)}_del(w,S,k){let T=this[p]("readwrite"),D;try{D=T.delete(w)}catch(K){return this.nextTick(k,K)}this[m](D,k)}_put(w,S,k,T){let D=this[p]("readwrite"),K;try{K=D.put(S,w)}catch(C){return this.nextTick(T,C)}this[m](K,T)}_iterator(w){return new a(this,this[f],w)}_batch(w,S,k){let T=this[p]("readwrite"),D=T.transaction,K=0,C;D.onabort=function(){k(C||D.error||new Error("aborted by user"))},D.oncomplete=function(){k()};function G(){let z=w[K++],N=z.key,V;try{V=z.type==="del"?T.delete(N):T.put(z.value,N)}catch(ee){C=ee,D.abort();return}K<w.length?V.onsuccess=G:typeof D.commit=="function"&&D.commit()}G()}_clear(w,S){let k,T;try{k=d(w)}catch{return this.nextTick(S)}if(w.limit>=0)return o(this,this[f],k,w,S);try{let D=this[p]("readwrite");T=k?D.delete(k):D.clear()}catch(D){return this.nextTick(S,D)}this[m](T,S)}_close(w){this[c].close(),this.nextTick(w)}};b.destroy=function(w,S,k){typeof S=="function"&&(k=S,S=l),k=i(k,y);let T=indexedDB.deleteDatabase(S+w);return T.onsuccess=function(){k()},T.onerror=function(D){k(D)},k[y]},t.BrowserLevel=b}),Zq=Qt(t=>{t.Level=mde().BrowserLevel}),yde=Qt((t,e)=>{(function(r,n){typeof t=="object"&&typeof e<"u"?n(t):typeof define=="function"&&define.amd?define(["exports"],n):n(r.URI=r.URI||{})})(t,function(r){"use strict";function n(){for(var Z=arguments.length,oe=Array(Z),ae=0;ae<Z;ae++)oe[ae]=arguments[ae];if(oe.length>1){oe[0]=oe[0].slice(0,-1);for(var ve=oe.length-1,Ee=1;Ee<ve;++Ee)oe[Ee]=oe[Ee].slice(1,-1);return oe[ve]=oe[ve].slice(1),oe.join("")}else return oe[0]}function i(Z){return"(?:"+Z+")"}function a(Z){return Z===void 0?"undefined":Z===null?"null":Object.prototype.toString.call(Z).split(" ").pop().split("]").shift().toLowerCase()}function s(Z){return Z.toUpperCase()}function o(Z){return Z!=null?Z instanceof Array?Z:typeof Z.length!="number"||Z.split||Z.setInterval||Z.call?[Z]:Array.prototype.slice.call(Z):[]}function d(Z,oe){var ae=Z;if(oe)for(var ve in oe)ae[ve]=oe[ve];return ae}function l(Z){var oe="[A-Za-z]",ae="[\\x0D]",ve="[0-9]",Ee="[\\x22]",We=n(ve,"[A-Fa-f]"),Mt="[\\x0A]",br="[\\x20]",Yr=i(i("%[EFef]"+We+"%"+We+We+"%"+We+We)+"|"+i("%[89A-Fa-f]"+We+"%"+We+We)+"|"+i("%"+We+We)),Xr="[\\:\\/\\?\\#\\[\\]\\@]",fr="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",Sn=n(Xr,fr),Vn=Z?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",mn=Z?"[\\uE000-\\uF8FF]":"[]",Cr=n(oe,ve,"[\\-\\.\\_\\~]",Vn),_r=i(oe+n(oe,ve,"[\\+\\-\\.]")+"*"),rs=i(i(Yr+"|"+n(Cr,fr,"[\\:]"))+"*"),Eg=i(i("25[0-5]")+"|"+i("2[0-4]"+ve)+"|"+i("1"+ve+ve)+"|"+i("[1-9]"+ve)+"|"+ve),Ws=i(i("25[0-5]")+"|"+i("2[0-4]"+ve)+"|"+i("1"+ve+ve)+"|"+i("0?[1-9]"+ve)+"|0?0?"+ve),Na=i(Ws+"\\."+Ws+"\\."+Ws+"\\."+Ws),$r=i(We+"{1,4}"),wo=i(i($r+"\\:"+$r)+"|"+Na),Xo=i(i($r+"\\:")+"{6}"+wo),Cd=i("\\:\\:"+i($r+"\\:")+"{5}"+wo),jf=i(i($r)+"?\\:\\:"+i($r+"\\:")+"{4}"+wo),Ac=i(i(i($r+"\\:")+"{0,1}"+$r)+"?\\:\\:"+i($r+"\\:")+"{3}"+wo),Ab=i(i(i($r+"\\:")+"{0,2}"+$r)+"?\\:\\:"+i($r+"\\:")+"{2}"+wo),kb=i(i(i($r+"\\:")+"{0,3}"+$r)+"?\\:\\:"+$r+"\\:"+wo),Oh=i(i(i($r+"\\:")+"{0,4}"+$r)+"?\\:\\:"+wo),jh=i(i(i($r+"\\:")+"{0,5}"+$r)+"?\\:\\:"+$r),Mh=i(i(i($r+"\\:")+"{0,6}"+$r)+"?\\:\\:"),Mf=i([Xo,Cd,jf,Ac,Ab,kb,Oh,jh,Mh].join("|")),Kh=i(i(Cr+"|"+Yr)+"+"),Nh=i(Mf+"\\%25"+Kh),zH=i(Mf+i("\\%25|\\%(?!"+We+"{2})")+Kh),FH=i("[vV]"+We+"+\\."+n(Cr,fr,"[\\:]")+"+"),GH=i("\\["+i(zH+"|"+Mf+"|"+FH)+"\\]"),F5=i(i(Yr+"|"+n(Cr,fr))+"*"),Sg=i(GH+"|"+Na+"(?!"+F5+")|"+F5),Ag=i(ve+"*"),G5=i(i(rs+"@")+"?"+Sg+i("\\:"+Ag)+"?"),kg=i(Yr+"|"+n(Cr,fr,"[\\:\\@]")),HH=i(kg+"*"),H5=i(kg+"+"),VH=i(i(Yr+"|"+n(Cr,fr,"[\\@]"))+"+"),$d=i(i("\\/"+HH)+"*"),Uh=i("\\/"+i(H5+$d)+"?"),nS=i(VH+$d),_b=i(H5+$d),Lh="(?!"+kg+")",_ge=i($d+"|"+Uh+"|"+nS+"|"+_b+"|"+Lh),qh=i(i(kg+"|"+n("[\\/\\?]",mn))+"*"),_g=i(i(kg+"|[\\/\\?]")+"*"),V5=i(i("\\/\\/"+G5+$d)+"|"+Uh+"|"+_b+"|"+Lh),WH=i(_r+"\\:"+V5+i("\\?"+qh)+"?"+i("\\#"+_g)+"?"),JH=i(i("\\/\\/"+G5+$d)+"|"+Uh+"|"+nS+"|"+Lh),ZH=i(JH+i("\\?"+qh)+"?"+i("\\#"+_g)+"?"),Tge=i(WH+"|"+ZH),Ige=i(_r+"\\:"+V5+i("\\?"+qh)+"?"),Dge="^("+_r+")\\:"+i(i("\\/\\/("+i("("+rs+")@")+"?("+Sg+")"+i("\\:("+Ag+")")+"?)")+"?("+$d+"|"+Uh+"|"+_b+"|"+Lh+")")+i("\\?("+qh+")")+"?"+i("\\#("+_g+")")+"?$",Rge="^(){0}"+i(i("\\/\\/("+i("("+rs+")@")+"?("+Sg+")"+i("\\:("+Ag+")")+"?)")+"?("+$d+"|"+Uh+"|"+nS+"|"+Lh+")")+i("\\?("+qh+")")+"?"+i("\\#("+_g+")")+"?$",Cge="^("+_r+")\\:"+i(i("\\/\\/("+i("("+rs+")@")+"?("+Sg+")"+i("\\:("+Ag+")")+"?)")+"?("+$d+"|"+Uh+"|"+_b+"|"+Lh+")")+i("\\?("+qh+")")+"?$",$ge="^"+i("\\#("+_g+")")+"?$",Bge="^"+i("("+rs+")@")+"?("+Sg+")"+i("\\:("+Ag+")")+"?$";return{NOT_SCHEME:new RegExp(n("[^]",oe,ve,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(n("[^\\%\\:]",Cr,fr),"g"),NOT_HOST:new RegExp(n("[^\\%\\[\\]\\:]",Cr,fr),"g"),NOT_PATH:new RegExp(n("[^\\%\\/\\:\\@]",Cr,fr),"g"),NOT_PATH_NOSCHEME:new RegExp(n("[^\\%\\/\\@]",Cr,fr),"g"),NOT_QUERY:new RegExp(n("[^\\%]",Cr,fr,"[\\:\\@\\/\\?]",mn),"g"),NOT_FRAGMENT:new RegExp(n("[^\\%]",Cr,fr,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(n("[^]",Cr,fr),"g"),UNRESERVED:new RegExp(Cr,"g"),OTHER_CHARS:new RegExp(n("[^\\%]",Cr,Sn),"g"),PCT_ENCODED:new RegExp(Yr,"g"),IPV4ADDRESS:new RegExp("^("+Na+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Mf+")"+i(i("\\%25|\\%(?!"+We+"{2})")+"("+Kh+")")+"?\\]?$")}}var c=l(!1),u=l(!0),f=function(){function Z(oe,ae){var ve=[],Ee=!0,We=!1,Mt=void 0;try{for(var br=oe[Symbol.iterator](),Yr;!(Ee=(Yr=br.next()).done)&&(ve.push(Yr.value),!(ae&&ve.length===ae));Ee=!0);}catch(Xr){We=!0,Mt=Xr}finally{try{!Ee&&br.return&&br.return()}finally{if(We)throw Mt}}return ve}return function(oe,ae){if(Array.isArray(oe))return oe;if(Symbol.iterator in Object(oe))return Z(oe,ae);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),h=function(Z){if(Array.isArray(Z)){for(var oe=0,ae=Array(Z.length);oe<Z.length;oe++)ae[oe]=Z[oe];return ae}else return Array.from(Z)},p=2147483647,m=36,y=1,b=26,w=38,S=700,k=72,T=128,D="-",K=/^xn--/,C=/[^\0-\x7E]/,G=/[\x2E\u3002\uFF0E\uFF61]/g,z={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},N=m-y,V=Math.floor,ee=String.fromCharCode;function R(Z){throw new RangeError(z[Z])}function B(Z,oe){for(var ae=[],ve=Z.length;ve--;)ae[ve]=oe(Z[ve]);return ae}function P(Z,oe){var ae=Z.split("@"),ve="";ae.length>1&&(ve=ae[0]+"@",Z=ae[1]),Z=Z.replace(G,".");var Ee=Z.split("."),We=B(Ee,oe).join(".");return ve+We}function E(Z){for(var oe=[],ae=0,ve=Z.length;ae<ve;){var Ee=Z.charCodeAt(ae++);if(Ee>=55296&&Ee<=56319&&ae<ve){var We=Z.charCodeAt(ae++);(We&64512)==56320?oe.push(((Ee&1023)<<10)+(We&1023)+65536):(oe.push(Ee),ae--)}else oe.push(Ee)}return oe}var x=function(Z){return String.fromCodePoint.apply(String,h(Z))},A=function(Z){return Z-48<10?Z-22:Z-65<26?Z-65:Z-97<26?Z-97:m},I=function(Z,oe){return Z+22+75*(Z<26)-((oe!=0)<<5)},M=function(Z,oe,ae){var ve=0;for(Z=ae?V(Z/S):Z>>1,Z+=V(Z/oe);Z>N*b>>1;ve+=m)Z=V(Z/N);return V(ve+(N+1)*Z/(Z+w))},q=function(Z){var oe=[],ae=Z.length,ve=0,Ee=T,We=k,Mt=Z.lastIndexOf(D);Mt<0&&(Mt=0);for(var br=0;br<Mt;++br)Z.charCodeAt(br)>=128&&R("not-basic"),oe.push(Z.charCodeAt(br));for(var Yr=Mt>0?Mt+1:0;Yr<ae;){for(var Xr=ve,fr=1,Sn=m;;Sn+=m){Yr>=ae&&R("invalid-input");var Vn=A(Z.charCodeAt(Yr++));(Vn>=m||Vn>V((p-ve)/fr))&&R("overflow"),ve+=Vn*fr;var mn=Sn<=We?y:Sn>=We+b?b:Sn-We;if(Vn<mn)break;var Cr=m-mn;fr>V(p/Cr)&&R("overflow"),fr*=Cr}var _r=oe.length+1;We=M(ve-Xr,_r,Xr==0),V(ve/_r)>p-Ee&&R("overflow"),Ee+=V(ve/_r),ve%=_r,oe.splice(ve++,0,Ee)}return String.fromCodePoint.apply(String,oe)},H=function(Z){var oe=[];Z=E(Z);var ae=Z.length,ve=T,Ee=0,We=k,Mt=!0,br=!1,Yr=void 0;try{for(var Xr=Z[Symbol.iterator](),fr;!(Mt=(fr=Xr.next()).done);Mt=!0){var Sn=fr.value;Sn<128&&oe.push(ee(Sn))}}catch(Nh){br=!0,Yr=Nh}finally{try{!Mt&&Xr.return&&Xr.return()}finally{if(br)throw Yr}}var Vn=oe.length,mn=Vn;for(Vn&&oe.push(D);mn<ae;){var Cr=p,_r=!0,rs=!1,Eg=void 0;try{for(var Ws=Z[Symbol.iterator](),Na;!(_r=(Na=Ws.next()).done);_r=!0){var $r=Na.value;$r>=ve&&$r<Cr&&(Cr=$r)}}catch(Nh){rs=!0,Eg=Nh}finally{try{!_r&&Ws.return&&Ws.return()}finally{if(rs)throw Eg}}var wo=mn+1;Cr-ve>V((p-Ee)/wo)&&R("overflow"),Ee+=(Cr-ve)*wo,ve=Cr;var Xo=!0,Cd=!1,jf=void 0;try{for(var Ac=Z[Symbol.iterator](),Ab;!(Xo=(Ab=Ac.next()).done);Xo=!0){var kb=Ab.value;if(kb<ve&&++Ee>p&&R("overflow"),kb==ve){for(var Oh=Ee,jh=m;;jh+=m){var Mh=jh<=We?y:jh>=We+b?b:jh-We;if(Oh<Mh)break;var Mf=Oh-Mh,Kh=m-Mh;oe.push(ee(I(Mh+Mf%Kh,0))),Oh=V(Mf/Kh)}oe.push(ee(I(Oh,0))),We=M(Ee,wo,mn==Vn),Ee=0,++mn}}}catch(Nh){Cd=!0,jf=Nh}finally{try{!Xo&&Ac.return&&Ac.return()}finally{if(Cd)throw jf}}++Ee,++ve}return oe.join("")},W=function(Z){return P(Z,function(oe){return K.test(oe)?q(oe.slice(4).toLowerCase()):oe})},J=function(Z){return P(Z,function(oe){return C.test(oe)?"xn--"+H(oe):oe})},X={version:"2.1.0",ucs2:{decode:E,encode:x},decode:q,encode:H,toASCII:J,toUnicode:W},L={};function Q(Z){var oe=Z.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 se(Z){for(var oe="",ae=0,ve=Z.length;ae<ve;){var Ee=parseInt(Z.substr(ae+1,2),16);if(Ee<128)oe+=String.fromCharCode(Ee),ae+=3;else if(Ee>=194&&Ee<224){if(ve-ae>=6){var We=parseInt(Z.substr(ae+4,2),16);oe+=String.fromCharCode((Ee&31)<<6|We&63)}else oe+=Z.substr(ae,6);ae+=6}else if(Ee>=224){if(ve-ae>=9){var Mt=parseInt(Z.substr(ae+4,2),16),br=parseInt(Z.substr(ae+7,2),16);oe+=String.fromCharCode((Ee&15)<<12|(Mt&63)<<6|br&63)}else oe+=Z.substr(ae,9);ae+=9}else oe+=Z.substr(ae,3),ae+=3}return oe}function re(Z,oe){function ae(ve){var Ee=se(ve);return Ee.match(oe.UNRESERVED)?Ee:ve}return Z.scheme&&(Z.scheme=String(Z.scheme).replace(oe.PCT_ENCODED,ae).toLowerCase().replace(oe.NOT_SCHEME,"")),Z.userinfo!==void 0&&(Z.userinfo=String(Z.userinfo).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_USERINFO,Q).replace(oe.PCT_ENCODED,s)),Z.host!==void 0&&(Z.host=String(Z.host).replace(oe.PCT_ENCODED,ae).toLowerCase().replace(oe.NOT_HOST,Q).replace(oe.PCT_ENCODED,s)),Z.path!==void 0&&(Z.path=String(Z.path).replace(oe.PCT_ENCODED,ae).replace(Z.scheme?oe.NOT_PATH:oe.NOT_PATH_NOSCHEME,Q).replace(oe.PCT_ENCODED,s)),Z.query!==void 0&&(Z.query=String(Z.query).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_QUERY,Q).replace(oe.PCT_ENCODED,s)),Z.fragment!==void 0&&(Z.fragment=String(Z.fragment).replace(oe.PCT_ENCODED,ae).replace(oe.NOT_FRAGMENT,Q).replace(oe.PCT_ENCODED,s)),Z}function Y(Z){return Z.replace(/^0*(.*)/,"$1")||"0"}function le(Z,oe){var ae=Z.match(oe.IPV4ADDRESS)||[],ve=f(ae,2),Ee=ve[1];return Ee?Ee.split(".").map(Y).join("."):Z}function ue(Z,oe){var ae=Z.match(oe.IPV6ADDRESS)||[],ve=f(ae,3),Ee=ve[1],We=ve[2];if(Ee){for(var Mt=Ee.toLowerCase().split("::").reverse(),br=f(Mt,2),Yr=br[0],Xr=br[1],fr=Xr?Xr.split(":").map(Y):[],Sn=Yr.split(":").map(Y),Vn=oe.IPV4ADDRESS.test(Sn[Sn.length-1]),mn=Vn?7:8,Cr=Sn.length-mn,_r=Array(mn),rs=0;rs<mn;++rs)_r[rs]=fr[rs]||Sn[Cr+rs]||"";Vn&&(_r[mn-1]=le(_r[mn-1],oe));var Eg=_r.reduce(function(Xo,Cd,jf){if(!Cd||Cd==="0"){var Ac=Xo[Xo.length-1];Ac&&Ac.index+Ac.length===jf?Ac.length++:Xo.push({index:jf,length:1})}return Xo},[]),Ws=Eg.sort(function(Xo,Cd){return Cd.length-Xo.length})[0],Na=void 0;if(Ws&&Ws.length>1){var $r=_r.slice(0,Ws.index),wo=_r.slice(Ws.index+Ws.length);Na=$r.join(":")+"::"+wo.join(":")}else Na=_r.join(":");return We&&(Na+="%"+We),Na}else return Z}var pe=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,xe="".match(/(){0}/)[1]===void 0;function de(Z){var oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ae={},ve=oe.iri!==!1?u:c;oe.reference==="suffix"&&(Z=(oe.scheme?oe.scheme+":":"")+"//"+Z);var Ee=Z.match(pe);if(Ee){xe?(ae.scheme=Ee[1],ae.userinfo=Ee[3],ae.host=Ee[4],ae.port=parseInt(Ee[5],10),ae.path=Ee[6]||"",ae.query=Ee[7],ae.fragment=Ee[8],isNaN(ae.port)&&(ae.port=Ee[5])):(ae.scheme=Ee[1]||void 0,ae.userinfo=Z.indexOf("@")!==-1?Ee[3]:void 0,ae.host=Z.indexOf("//")!==-1?Ee[4]:void 0,ae.port=parseInt(Ee[5],10),ae.path=Ee[6]||"",ae.query=Z.indexOf("?")!==-1?Ee[7]:void 0,ae.fragment=Z.indexOf("#")!==-1?Ee[8]:void 0,isNaN(ae.port)&&(ae.port=Z.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?Ee[4]:void 0)),ae.host&&(ae.host=ue(le(ae.host,ve),ve)),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 We=L[(oe.scheme||ae.scheme||"").toLowerCase()];if(!oe.unicodeSupport&&(!We||!We.unicodeSupport)){if(ae.host&&(oe.domainHost||We&&We.domainHost))try{ae.host=X.toASCII(ae.host.replace(ve.PCT_ENCODED,se).toLowerCase())}catch(Mt){ae.error=ae.error||"Host's domain name can not be converted to ASCII via punycode: "+Mt}re(ae,c)}else re(ae,ve);We&&We.parse&&We.parse(ae,oe)}else ae.error=ae.error||"URI can not be parsed.";return ae}function Pe(Z,oe){var ae=oe.iri!==!1?u:c,ve=[];return Z.userinfo!==void 0&&(ve.push(Z.userinfo),ve.push("@")),Z.host!==void 0&&ve.push(ue(le(String(Z.host),ae),ae).replace(ae.IPV6ADDRESS,function(Ee,We,Mt){return"["+We+(Mt?"%25"+Mt:"")+"]"})),(typeof Z.port=="number"||typeof Z.port=="string")&&(ve.push(":"),ve.push(String(Z.port))),ve.length?ve.join(""):void 0}var Ne=/^\.\.?\//,He=/^\/\.(\/|$)/,Je=/^\/\.\.(\/|$)/,Ct=/^\/?(?:.|\n)*?(?=\/|$)/;function ke(Z){for(var oe=[];Z.length;)if(Z.match(Ne))Z=Z.replace(Ne,"");else if(Z.match(He))Z=Z.replace(He,"/");else if(Z.match(Je))Z=Z.replace(Je,"/"),oe.pop();else if(Z==="."||Z==="..")Z="";else{var ae=Z.match(Ct);if(ae){var ve=ae[0];Z=Z.slice(ve.length),oe.push(ve)}else throw new Error("Unexpected dot segment condition")}return oe.join("")}function ot(Z){var oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ae=oe.iri?u:c,ve=[],Ee=L[(oe.scheme||Z.scheme||"").toLowerCase()];if(Ee&&Ee.serialize&&Ee.serialize(Z,oe),Z.host&&!ae.IPV6ADDRESS.test(Z.host)&&(oe.domainHost||Ee&&Ee.domainHost))try{Z.host=oe.iri?X.toUnicode(Z.host):X.toASCII(Z.host.replace(ae.PCT_ENCODED,se).toLowerCase())}catch(br){Z.error=Z.error||"Host's domain name can not be converted to "+(oe.iri?"Unicode":"ASCII")+" via punycode: "+br}re(Z,ae),oe.reference!=="suffix"&&Z.scheme&&(ve.push(Z.scheme),ve.push(":"));var We=Pe(Z,oe);if(We!==void 0&&(oe.reference!=="suffix"&&ve.push("//"),ve.push(We),Z.path&&Z.path.charAt(0)!=="/"&&ve.push("/")),Z.path!==void 0){var Mt=Z.path;!oe.absolutePath&&(!Ee||!Ee.absolutePath)&&(Mt=ke(Mt)),We===void 0&&(Mt=Mt.replace(/^\/\//,"/%2F")),ve.push(Mt)}return Z.query!==void 0&&(ve.push("?"),ve.push(Z.query)),Z.fragment!==void 0&&(ve.push("#"),ve.push(Z.fragment)),ve.join("")}function _t(Z,oe){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},ve=arguments[3],Ee={};return ve||(Z=de(ot(Z,ae),ae),oe=de(ot(oe,ae),ae)),ae=ae||{},!ae.tolerant&&oe.scheme?(Ee.scheme=oe.scheme,Ee.userinfo=oe.userinfo,Ee.host=oe.host,Ee.port=oe.port,Ee.path=ke(oe.path||""),Ee.query=oe.query):(oe.userinfo!==void 0||oe.host!==void 0||oe.port!==void 0?(Ee.userinfo=oe.userinfo,Ee.host=oe.host,Ee.port=oe.port,Ee.path=ke(oe.path||""),Ee.query=oe.query):(oe.path?(oe.path.charAt(0)==="/"?Ee.path=ke(oe.path):((Z.userinfo!==void 0||Z.host!==void 0||Z.port!==void 0)&&!Z.path?Ee.path="/"+oe.path:Z.path?Ee.path=Z.path.slice(0,Z.path.lastIndexOf("/")+1)+oe.path:Ee.path=oe.path,Ee.path=ke(Ee.path)),Ee.query=oe.query):(Ee.path=Z.path,oe.query!==void 0?Ee.query=oe.query:Ee.query=Z.query),Ee.userinfo=Z.userinfo,Ee.host=Z.host,Ee.port=Z.port),Ee.scheme=Z.scheme),Ee.fragment=oe.fragment,Ee}function Rt(Z,oe,ae){var ve=d({scheme:"null"},ae);return ot(_t(de(Z,ve),de(oe,ve),ve,!0),ve)}function zt(Z,oe){return typeof Z=="string"?Z=ot(de(Z,oe),oe):a(Z)==="object"&&(Z=de(ot(Z,oe),oe)),Z}function _(Z,oe,ae){return typeof Z=="string"?Z=ot(de(Z,ae),ae):a(Z)==="object"&&(Z=ot(Z,ae)),typeof oe=="string"?oe=ot(de(oe,ae),ae):a(oe)==="object"&&(oe=ot(oe,ae)),Z===oe}function O(Z,oe){return Z&&Z.toString().replace(!oe||!oe.iri?c.ESCAPE:u.ESCAPE,Q)}function U(Z,oe){return Z&&Z.toString().replace(!oe||!oe.iri?c.PCT_ENCODED:u.PCT_ENCODED,se)}var te={scheme:"http",domainHost:!0,parse:function(Z,oe){return Z.host||(Z.error=Z.error||"HTTP URIs must have a host."),Z},serialize:function(Z,oe){var ae=String(Z.scheme).toLowerCase()==="https";return(Z.port===(ae?443:80)||Z.port==="")&&(Z.port=void 0),Z.path||(Z.path="/"),Z}},ce={scheme:"https",domainHost:te.domainHost,parse:te.parse,serialize:te.serialize};function me(Z){return typeof Z.secure=="boolean"?Z.secure:String(Z.scheme).toLowerCase()==="wss"}var Ae={scheme:"ws",domainHost:!0,parse:function(Z,oe){var ae=Z;return ae.secure=me(ae),ae.resourceName=(ae.path||"/")+(ae.query?"?"+ae.query:""),ae.path=void 0,ae.query=void 0,ae},serialize:function(Z,oe){if((Z.port===(me(Z)?443:80)||Z.port==="")&&(Z.port=void 0),typeof Z.secure=="boolean"&&(Z.scheme=Z.secure?"wss":"ws",Z.secure=void 0),Z.resourceName){var ae=Z.resourceName.split("?"),ve=f(ae,2),Ee=ve[0],We=ve[1];Z.path=Ee&&Ee!=="/"?Ee:void 0,Z.query=We,Z.resourceName=void 0}return Z.fragment=void 0,Z}},Ft={scheme:"wss",domainHost:Ae.domainHost,parse:Ae.parse,serialize:Ae.serialize},Xn={},Gr=!0,kr="[A-Za-z0-9\\-\\.\\_\\~"+(Gr?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",yr="[0-9A-Fa-f]",$H=i(i("%[EFef]"+yr+"%"+yr+yr+"%"+yr+yr)+"|"+i("%[89A-Fa-f]"+yr+"%"+yr+yr)+"|"+i("%"+yr+yr)),BH="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",OH="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",jH=n(OH,'[\\"\\\\]'),MH="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",KH=new RegExp(kr,"g"),Bh=new RegExp($H,"g"),NH=new RegExp(n("[^]",BH,"[\\.]",'[\\"]',jH),"g"),U5=new RegExp(n("[^]",kr,MH),"g"),UH=U5;function rS(Z){var oe=se(Z);return oe.match(KH)?oe:Z}var L5={scheme:"mailto",parse:function(Z,oe){var ae=Z,ve=ae.to=ae.path?ae.path.split(","):[];if(ae.path=void 0,ae.query){for(var Ee=!1,We={},Mt=ae.query.split("&"),br=0,Yr=Mt.length;br<Yr;++br){var Xr=Mt[br].split("=");switch(Xr[0]){case"to":for(var fr=Xr[1].split(","),Sn=0,Vn=fr.length;Sn<Vn;++Sn)ve.push(fr[Sn]);break;case"subject":ae.subject=U(Xr[1],oe);break;case"body":ae.body=U(Xr[1],oe);break;default:Ee=!0,We[U(Xr[0],oe)]=U(Xr[1],oe);break}}Ee&&(ae.headers=We)}ae.query=void 0;for(var mn=0,Cr=ve.length;mn<Cr;++mn){var _r=ve[mn].split("@");if(_r[0]=U(_r[0]),oe.unicodeSupport)_r[1]=U(_r[1],oe).toLowerCase();else try{_r[1]=X.toASCII(U(_r[1],oe).toLowerCase())}catch(rs){ae.error=ae.error||"Email address's domain name can not be converted to ASCII via punycode: "+rs}ve[mn]=_r.join("@")}return ae},serialize:function(Z,oe){var ae=Z,ve=o(Z.to);if(ve){for(var Ee=0,We=ve.length;Ee<We;++Ee){var Mt=String(ve[Ee]),br=Mt.lastIndexOf("@"),Yr=Mt.slice(0,br).replace(Bh,rS).replace(Bh,s).replace(NH,Q),Xr=Mt.slice(br+1);try{Xr=oe.iri?X.toUnicode(Xr):X.toASCII(U(Xr,oe).toLowerCase())}catch(mn){ae.error=ae.error||"Email address's domain name can not be converted to "+(oe.iri?"Unicode":"ASCII")+" via punycode: "+mn}ve[Ee]=Yr+"@"+Xr}ae.path=ve.join(",")}var fr=Z.headers=Z.headers||{};Z.subject&&(fr.subject=Z.subject),Z.body&&(fr.body=Z.body);var Sn=[];for(var Vn in fr)fr[Vn]!==Xn[Vn]&&Sn.push(Vn.replace(Bh,rS).replace(Bh,s).replace(U5,Q)+"="+fr[Vn].replace(Bh,rS).replace(Bh,s).replace(UH,Q));return Sn.length&&(ae.query=Sn.join("&")),ae}},LH=/^([^\:]+)\:(.*)/,q5={scheme:"urn",parse:function(Z,oe){var ae=Z.path&&Z.path.match(LH),ve=Z;if(ae){var Ee=oe.scheme||ve.scheme||"urn",We=ae[1].toLowerCase(),Mt=ae[2],br=Ee+":"+(oe.nid||We),Yr=L[br];ve.nid=We,ve.nss=Mt,ve.path=void 0,Yr&&(ve=Yr.parse(ve,oe))}else ve.error=ve.error||"URN can not be parsed.";return ve},serialize:function(Z,oe){var ae=oe.scheme||Z.scheme||"urn",ve=Z.nid,Ee=ae+":"+(oe.nid||ve),We=L[Ee];We&&(Z=We.serialize(Z,oe));var Mt=Z,br=Z.nss;return Mt.path=(ve||oe.nid)+":"+br,Mt}},qH=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,z5={scheme:"urn:uuid",parse:function(Z,oe){var ae=Z;return ae.uuid=ae.nss,ae.nss=void 0,!oe.tolerant&&(!ae.uuid||!ae.uuid.match(qH))&&(ae.error=ae.error||"UUID is not valid."),ae},serialize:function(Z,oe){var ae=Z;return ae.nss=(Z.uuid||"").toLowerCase(),ae}};L[te.scheme]=te,L[ce.scheme]=ce,L[Ae.scheme]=Ae,L[Ft.scheme]=Ft,L[L5.scheme]=L5,L[q5.scheme]=q5,L[z5.scheme]=z5,r.SCHEMES=L,r.pctEncChar=Q,r.pctDecChars=se,r.parse=de,r.removeDotSegments=ke,r.serialize=ot,r.resolveComponents=_t,r.resolve=Rt,r.normalize=zt,r.equal=_,r.escapeComponent=O,r.unescapeComponent=U,Object.defineProperty(r,"__esModule",{value:!0})})}),gde=Qt((t,e)=>{"use strict";e.exports=function r(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?r(n.toJSON()):Array.isArray(n)?`[${n.reduce((i,a,s)=>`${i}${s===0?"":","}${r(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}${r(a)}:${r(n[a])}`},"")}}`}}),Yq=Qt((t,e)=>{var r=1e3,n=r*60,i=n*60,a=i*24,s=a*7,o=a*365.25;e.exports=function(f,h){h=h||{};var p=typeof f;if(p==="string"&&f.length>0)return d(f);if(p==="number"&&isFinite(f))return h.long?c(f):l(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function d(f){if(f=String(f),!(f.length>100)){var h=/^(-?(?:\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(h){var p=parseFloat(h[1]),m=(h[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return p*o;case"weeks":case"week":case"w":return p*s;case"days":case"day":case"d":return p*a;case"hours":case"hour":case"hrs":case"hr":case"h":return p*i;case"minutes":case"minute":case"mins":case"min":case"m":return p*n;case"seconds":case"second":case"secs":case"sec":case"s":return p*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function l(f){var h=Math.abs(f);return h>=a?Math.round(f/a)+"d":h>=i?Math.round(f/i)+"h":h>=n?Math.round(f/n)+"m":h>=r?Math.round(f/r)+"s":f+"ms"}function c(f){var h=Math.abs(f);return h>=a?u(f,h,a,"day"):h>=i?u(f,h,i,"hour"):h>=n?u(f,h,n,"minute"):h>=r?u(f,h,r,"second"):f+" ms"}function u(f,h,p,m){var y=h>=p*1.5;return Math.round(f/p)+" "+m+(y?"s":"")}}),J2=(t=>(t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation",t))(J2||{}),Ai={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}},Zi=class Xq{constructor({method:e,id:r,path:n,query:i,fragment:a,params:s}){this.uri=`did:${e}:${r}`,this.method=e,this.id=r,this.path=n,this.query=i,this.fragment=a,this.params=s}static parse(e){if(!e||e.length>2048)return null;let r=Xq.DID_URI_PATTERN.exec(e);if(!r||!r.groups)return null;let{method:n,id:i,path:a,query:s,fragment:o}=r.groups,d={uri:`did:${n}:${i}`,method:n,id:i};if(a&&(d.path=a),s&&(d.query=s.slice(1)),o&&(d.fragment=o.slice(1)),s){let l={},c=s.slice(1).split("&");for(let u of c){let[f,h]=u.split("=");l[f]=h}d.params=l}return d}};Zi.METHOD_PATTERN="([a-z0-9]+)",Zi.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})",Zi.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${Zi.PCT_ENCODED_PATTERN})`,Zi.METHOD_ID_PATTERN=`((?:${Zi.ID_CHAR_PATTERN}*:)*(${Zi.ID_CHAR_PATTERN}+))`,Zi.PATH_PATTERN="(/[^#?]*)?",Zi.QUERY_PATTERN="([?][^#]*)?",Zi.FRAGMENT_PATTERN="(#.*)?",Zi.DID_URI_PATTERN=new RegExp("^did:(?<method>"+Zi.METHOD_PATTERN+"):(?<id>"+Zi.METHOD_ID_PATTERN+")(?<path>"+Zi.PATH_PATTERN+")(?<query>"+Zi.QUERY_PATTERN+")(?<fragment>"+Zi.FRAGMENT_PATTERN+")$");Fn=Zi,rt=class Qq extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,this.name="DidError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Qq)}},wde=(t=>(t.InvalidDid="invalidDid",t.MethodNotSupported="methodNotSupported",t.InternalError="internalError",t.InvalidDidDocument="invalidDidDocument",t.InvalidDidDocumentLength="invalidDidDocumentLength",t.InvalidDidUrl="invalidDidUrl",t.InvalidPreviousDidProof="invalidPreviousDidProof",t.InvalidPublicKey="invalidPublicKey",t.InvalidPublicKeyLength="invalidPublicKeyLength",t.InvalidPublicKeyType="invalidPublicKeyType",t.InvalidSignature="invalidSignature",t.NotFound="notFound",t.RepresentationNotSupported="representationNotSupported",t.UnsupportedPublicKeyType="unsupportedPublicKeyType",t))(wde||{}),$a=class e7 extends Error{constructor(e,r){super(r),this.code=e,this.name="CryptoError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e7)}};(function(t){t.AlgorithmNotSupported="algorithmNotSupported",t.EncodingError="encodingError",t.InvalidCoseSign1="invalidCoseSign1",t.InvalidEat="invalidEat",t.InvalidJwe="invalidJwe",t.InvalidJwk="invalidJwk",t.OperationNotSupported="operationNotSupported"})(fo||(fo={}));vde=ph(Yce(),1);Pde=bde,xde=Pde,Ede=xde,oNe=new Uint8Array(0),Sde=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},h6=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Ade=class{constructor(t,e,r){this.name=t,this.prefix=e,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},kde=class{constructor(t,e,r){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return t7(this,t)}},_de=class{constructor(t){this.decoders=t}or(t){return t7(this,t)}decode(t){let e=t[0],r=this.decoders[e];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},t7=(t,e)=>new _de({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Tde=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new Ade(t,e,r),this.decoder=new kde(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},r7=({name:t,prefix:e,encode:r,decode:n})=>new Tde(t,e,r,n),n7=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=Ede(r,e);return r7({prefix:t,name:e,encode:n,decode:a=>h6(i(a))})},Ide=(t,e,r,n)=>{let i={};for(let c=0;c<e.length;++c)i[e[c]]=c;let a=t.length;for(;t[a-1]==="=";)--a;let s=new Uint8Array(a*r/8|0),o=0,d=0,l=0;for(let c=0;c<a;++c){let u=i[t[c]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);d=d<<r|u,o+=r,o>=8&&(o-=8,s[l++]=255&d>>o)}if(o>=r||255&d<<8-o)throw new SyntaxError("Unexpected end of data");return s},Dde=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,a="",s=0,o=0;for(let d=0;d<t.length;++d)for(o=o<<8|t[d],s+=8;s>r;)s-=r,a+=e[i&o>>s];if(s&&(a+=e[i&o<<r-s]),n)for(;a.length*r&7;)a+="=";return a},Wo=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>r7({prefix:e,name:t,encode(i){return Dde(i,n,r)},decode(i){return Ide(i,n,r,t)}}),y2=Wo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),aNe=Wo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cNe=Wo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),dNe=Wo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),lNe=Wo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),uNe=Wo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fNe=Wo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),pNe=Wo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),k9=Wo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Ra=n7({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),hNe=n7({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),mNe=Wo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),yNe=Wo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_l=Wo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),gNe=Wo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});yv=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},_9=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(a){r[a]=t[a]&&function(s){return new Promise(function(o,d){s=t[a](s),i(o,d,s.done,s.value)})}}function i(a,s,o,d){Promise.resolve(d).then(function(l){a({value:l,done:o})},s)}},c2=new TextEncoder,Qp=new TextDecoder,it=class lo{constructor(e,r){this.data=e,this.format=r}static arrayBuffer(e){return new lo(e,"ArrayBuffer")}static asyncIterable(e){if(!Cde(e))throw new TypeError("Input must be of type AsyncIterable.");return new lo(e,"AsyncIterable")}static base32Z(e){return new lo(e,"Base32Z")}static base58Btc(e){return new lo(e,"Base58Btc")}static base64Url(e){return new lo(e,"Base64Url")}static bufferSource(e){return new lo(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 lo(e,"Hex")}static multibase(e){return new lo(e,"Multibase")}static object(e){return new lo(e,"Object")}static string(e){return new lo(e,"String")}static uint8Array(e){return new lo(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return Ra.baseDecode(this.data).buffer;case"Base64Url":return _l.baseDecode(this.data).buffer;case"BufferSource":{if(zR(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return Rde(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 yv(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 k9.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 Ra.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return Ra.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 _l.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return _l.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=c2.encode(e);return _l.baseEncode(r)}case"String":{let e=c2.encode(this.data);return _l.baseEncode(e)}case"Uint8Array":return _l.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return yv(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let d=[];try{for(var a=!0,s=_9(this.data),o;o=yield s.next(),e=o.done,!e;a=!0){i=o.value,a=!1;let l=i;d.push(l)}}catch(l){r={error:l}}finally{try{!a&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(r)throw r.error}}return new Blob(d)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(r,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let r=this.toUint8Array();return lo.uint8Array(r).toHex()}case"Base64Url":{let r=this.toUint8Array();return lo.uint8Array(r).toHex()}case"Uint8Array":{let r="";for(let n=0;n<this.data.length;n++)r+=e[this.data[n]];return r}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=_l.baseDecode(this.data),r=Qp.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=Qp.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return yv(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 Qp.decode(this.data);case"Base64Url":{let e=_l.baseDecode(this.data);return Qp.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return Qp.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return yv(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let d="";try{for(var a=!0,s=_9(this.data),o;o=yield s.next(),e=o.done,!e;a=!0){i=o.value,a=!1;let l=i;typeof l=="string"?d+=l:d+=Qp.decode(l,{stream:!0})}}catch(l){r={error:l}}finally{try{!a&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(r)throw r.error}}return d+=Qp.decode(void 0,{stream:!1}),d}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 k9.baseDecode(this.data);case"Base58Btc":return Ra.baseDecode(this.data);case"Base64Url":return _l.baseDecode(this.data);case"BufferSource":{let e=zR(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 r=0;r<this.data.length;r+=2){let n=parseInt(this.data.substring(r,r+2),16);if(isNaN(n))throw new TypeError("Input is not a valid hexadecimal string.");e[r/2]=n}return e}case"Object":{let e=JSON.stringify(this.data);return c2.encode(e)}case"String":return c2.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return yv(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(t){t.Debug="debug",t.Silent="silent"})(Kv||(Kv={}));$de=class{constructor(){this.logLevel=Kv.Silent}setLogLevel(t){this.logLevel=t}log(t){this.info(t)}info(t){this.logLevel!==Kv.Silent&&console.info(t)}error(t){this.logLevel!==Kv.Silent&&console.error(t)}},Bde=new $de;typeof window<"u"&&(window.enboxLogger=Bde);Ev={};u6(Ev,{decode:()=>M2,encodeTo:()=>Uv,encodingLength:()=>Lv});Ode=i7,T9=128,jde=127,Mde=~jde,Kde=Math.pow(2,31);Nde=FR,Ude=128,I9=127;Lde=Math.pow(2,7),qde=Math.pow(2,14),zde=Math.pow(2,21),Fde=Math.pow(2,28),Gde=Math.pow(2,35),Hde=Math.pow(2,42),Vde=Math.pow(2,49),Wde=Math.pow(2,56),Jde=Math.pow(2,63),Zde=function(t){return t<Lde?1:t<qde?2:t<zde?3:t<Fde?4:t<Gde?5:t<Hde?6:t<Vde?7:t<Wde?8:t<Jde?9:10},Yde={encode:Ode,decode:Nde,encodingLength:Zde},Xde=Yde,j2=Xde,M2=(t,e=0)=>[j2.decode(t,e),j2.decode.bytes],Uv=(t,e,r=0)=>(j2.encode(t,e,r),e),Lv=t=>j2.encodingLength(t),Qde=(t,e)=>{let r=e.byteLength,n=Lv(t),i=n+Lv(r),a=new Uint8Array(i+r);return Uv(t,a,0),Uv(r,a,n),a.set(e,i),new m6(t,r,e,a)},ele=t=>{let e=h6(t),[r,n]=M2(e),[i,a]=M2(e.subarray(n)),s=e.subarray(n+a);if(s.byteLength!==i)throw new Error("Incorrect length");return new m6(r,i,s,e)},tle=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Sde(t.bytes,r.bytes)}},m6=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},D9=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return nle(r,GR(t),e||Ra.encoder);default:return ile(r,GR(t),e||y2.encoder)}},R9=new WeakMap,GR=t=>{let e=R9.get(t);if(e==null){let r=new Map;return R9.set(t,r),r}return e},wNe=class gs{constructor(e,r,n,i){this.code=r,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:r}=this;if(e!==gv)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==sle)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return gs.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Qde(e,r);return gs.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 gs.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&tle(e.multihash,n.multihash)}toString(e){return D9(this,e)}toJSON(){return{"/":D9(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 r=e;if(r instanceof gs)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:a,bytes:s}=r;return new gs(n,i,a,s||C9(n,i,a.bytes))}else if(r[ole]===!0){let{version:n,multihash:i,code:a}=r,s=ele(i);return gs.create(n,a,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==gv)throw new Error(`Version 0 CID must use dag-pb (code: ${gv}) block encoding`);return new gs(e,r,n,n.bytes)}case 1:{let i=C9(e,r,n.bytes);return new gs(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return gs.create(0,gv,e)}static createV1(e,r){return gs.create(1,e,r)}static decode(e){let[r,n]=gs.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=gs.inspectBytes(e),n=r.size-r.multihashSize,i=h6(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let a=i.subarray(r.multihashSize-r.digestSize),s=new m6(r.multihashCode,r.digestSize,a,i);return[r.version===0?gs.createV0(s):gs.createV1(r.codec,s),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[u,f]=M2(e.subarray(r));return r+=f,u},i=n(),a=gv;if(i===18?(i=0,r=0):a=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=r,o=n(),d=n(),l=r+d,c=l-s;return{version:i,codec:a,multihashCode:o,digestSize:d,multihashSize:c,size:l}}static parse(e,r){let[n,i]=rle(e,r),a=gs.decode(i);if(a.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return GR(a).set(n,e),a}},rle=(t,e)=>{switch(t[0]){case"Q":{let r=e||Ra;return[Ra.prefix,r.decode(`${Ra.prefix}${t}`)]}case Ra.prefix:{let r=e||Ra;return[Ra.prefix,r.decode(t)]}case y2.prefix:{let r=e||y2;return[y2.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},nle=(t,e,r)=>{let{prefix:n}=r;if(n!==Ra.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let a=r.encode(t).slice(1);return e.set(n,a),a}else return i},ile=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let a=r.encode(t);return e.set(n,a),a}else return i},gv=112,sle=18,C9=(t,e,r)=>{let n=Lv(t),i=n+Lv(e),a=new Uint8Array(i+r.byteLength);return Uv(t,a,0),Uv(e,a,n),a.set(r,i),a},ole=Symbol.for("@ipld/js-cid/CID"),Oa=class hf{static addPrefix(e){var r;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=hf.codeToName.has(n)?n:hf.nameToCode.get(a),n===void 0)throw new Error(`Unsupported multicodec: ${(r=e.name)!==null&&r!==void 0?r:e.code}`);let s=Ev.encodingLength(n),o=new Uint8Array(s+i.byteLength);return o.set(i,s),Ev.encodeTo(n,o),o}static getCodeFromData(e){let{prefixedData:r}=e,[n,i]=Ev.decode(r);return n}static getCodeFromName(e){let{name:r}=e,n=hf.nameToCode.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static getNameFromCode(e){let{code:r}=e,n=hf.codeToName.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static registerCodec(e){hf.codeToName.set(e.code,e.name),hf.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:r}=e,[n,i]=Ev.decode(r),a=hf.codeToName.get(n);if(a===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:r.slice(i),name:a}}};Oa.codeToName=new Map;Oa.nameToCode=new Map;Oa.registerCodec({code:237,name:"ed25519-pub"});Oa.registerCodec({code:4864,name:"ed25519-priv"});Oa.registerCodec({code:236,name:"x25519-pub"});Oa.registerCodec({code:4866,name:"x25519-priv"});Oa.registerCodec({code:231,name:"secp256k1-pub"});Oa.registerCodec({code:4865,name:"secp256k1-priv"});vNe=ph(Zq(),1),nf=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},ale=class{constructor(){this.store=new Map}clear(){return nf(this,void 0,void 0,function*(){this.store.clear()})}open(){return nf(this,void 0,void 0,function*(){})}close(){return nf(this,void 0,void 0,function*(){})}delete(t){return nf(this,void 0,void 0,function*(){return this.store.delete(t)})}get(t){return nf(this,void 0,void 0,function*(){return this.store.get(t)})}has(t){return nf(this,void 0,void 0,function*(){return this.store.has(t)})}list(){return nf(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(t,e){return nf(this,void 0,void 0,function*(){this.store.set(t,e)})}},Z2=class{},o7={};u6(o7,{bitGet:()=>hle,bitLen:()=>ple,bitMask:()=>g6,bitSet:()=>mle,bytesToHex:()=>lh,bytesToNumberBE:()=>ah,bytesToNumberLE:()=>vf,concatBytes:()=>uh,createHmacDrbg:()=>d7,ensureBytes:()=>zn,equalBytes:()=>ule,hexToBytes:()=>Ly,hexToNumber:()=>y6,isBytes:()=>kd,numberToBytesBE:()=>_d,numberToBytesLE:()=>qy,numberToHexUnpadded:()=>c7,numberToVarBytesBE:()=>lle,utf8ToBytes:()=>fle,validateObject:()=>hh});a7=BigInt(0),Y2=BigInt(1),cle=BigInt(2);dle=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));Tl={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};mle=(t,e,r)=>t|(r?Y2:a7)<<BigInt(e),g6=t=>(cle<<BigInt(t-1))-Y2,$R=t=>new Uint8Array(t),B9=t=>Uint8Array.from(t);yle={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||kd(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};BR=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;OR=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),wd=(t,e)=>t<<32-e|t>>>e,ble=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ble)throw new Error("Non little-endian hardware is not supported");h7=class{clone(){return this._cloneInto()}},bNe={}.toString;y7=class extends h7{constructor(t,e,r,n){super(),this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=OR(this.buffer)}update(t){K2(this);let{view:e,buffer:r,blockLen:n}=this;t=w6(t);let i=t.length;for(let a=0;a<i;){let s=Math.min(n-this.pos,i-a);if(s===n){let o=OR(t);for(;n<=i-a;a+=n)this.process(o,a);continue}r.set(t.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){K2(this),vle(t,this),this.finished=!0;let{buffer:e,view:r,blockLen:n,isLE:i}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(r,0),a=0);for(let c=a;c<n;c++)e[c]=0;Ple(r,n-8,BigInt(this.length*8),i),this.process(r,0);let s=OR(t),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=o/4,l=this.get();if(d>l.length)throw new Error("_sha2: outputLen bigger than state");for(let c=0;c<d;c++)s.setUint32(4*c,l[c],i)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let r=t.slice(0,e);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:r,length:n,finished:i,destroyed:a,pos:s}=this;return t.length=n,t.pos=s,t.finished=i,t.destroyed=a,n%e&&t.buffer.set(r),t}},xle=(t,e,r)=>t&e^~t&r,Ele=(t,e,r)=>t&e^t&r^e&r,Sle=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]),sf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),of=new Uint32Array(64),Ale=class extends y7{constructor(){super(64,32,8,!1),this.A=sf[0]|0,this.B=sf[1]|0,this.C=sf[2]|0,this.D=sf[3]|0,this.E=sf[4]|0,this.F=sf[5]|0,this.G=sf[6]|0,this.H=sf[7]|0}get(){let{A:t,B:e,C:r,D:n,E:i,F:a,G:s,H:o}=this;return[t,e,r,n,i,a,s,o]}set(t,e,r,n,i,a,s,o){this.A=t|0,this.B=e|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=s|0,this.H=o|0}process(t,e){for(let c=0;c<16;c++,e+=4)of[c]=t.getUint32(e,!1);for(let c=16;c<64;c++){let u=of[c-15],f=of[c-2],h=wd(u,7)^wd(u,18)^u>>>3,p=wd(f,17)^wd(f,19)^f>>>10;of[c]=p+of[c-7]+h+of[c-16]|0}let{A:r,B:n,C:i,D:a,E:s,F:o,G:d,H:l}=this;for(let c=0;c<64;c++){let u=wd(s,6)^wd(s,11)^wd(s,25),f=l+u+xle(s,o,d)+Sle[c]+of[c]|0,h=(wd(r,2)^wd(r,13)^wd(r,22))+Ele(r,n,i)|0;l=d,d=o,o=s,s=a+f|0,a=i,i=n,n=r,r=f+h|0}r=r+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,d=d+this.G|0,l=l+this.H|0,this.set(r,n,i,a,s,o,d,l)}roundClean(){of.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},g7=m7(()=>new Ale),ui=BigInt(0),hn=BigInt(1),rh=BigInt(2),kle=BigInt(3),HR=BigInt(4),j9=BigInt(5),M9=BigInt(8),PNe=BigInt(9),_le=BigInt(16);Dle=(t,e)=>(Zr(t,e)&hn)===hn,Rle=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];Mle=BigInt(0),jR=BigInt(1);({bytesToNumberBE:Nle,hexToBytes:Ule}=o7),sh={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(t){let{Err:e}=sh;if(t.length<2||t[0]!==2)throw new e("Invalid signature integer tag");let r=t[1],n=t.subarray(2,r+2);if(!r||n.length!==r)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:Nle(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=sh,r=typeof t=="string"?Ule(t):t;if(!kd(r))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new e("Invalid signature tag");if(r[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:i,l:a}=sh._parseInt(r.subarray(2)),{d:s,l:o}=sh._parseInt(a);if(o.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(t){let e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,r=l=>{let c=l.toString(16);return c.length&1?`0${c}`:c},n=e(r(t.s)),i=e(r(t.r)),a=n.length/2,s=i.length/2,o=r(a),d=r(s);return`30${r(s+a+4)}02${d}${i}02${o}${n}`}},Bl=BigInt(0),Da=BigInt(1),xNe=BigInt(2),K9=BigInt(3),ENe=BigInt(4);E7=class extends h7{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,wle(t);let r=w6(e);if(this.iHash=t.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(r.length>n?t.create().update(r).digest():r);for(let a=0;a<i.length;a++)i[a]^=54;this.iHash.update(i),this.oHash=t.create();for(let a=0;a<i.length;a++)i[a]^=106;this.oHash.update(i),i.fill(0)}update(t){return K2(this),this.iHash.update(t),this}digestInto(t){K2(this),l7(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:r,finished:n,destroyed:i,blockLen:a,outputLen:s}=this;return t=t,t.finished=n,t.destroyed=i,t.blockLen=a,t.outputLen=s,t.oHash=e._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},S7=(t,e,r)=>new E7(t,e).update(r).digest();S7.create=(t,e)=>new E7(t,e);k7=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),N9=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Gle=BigInt(1),WR=BigInt(2),U9=(t,e)=>(t+e/WR)/e;JR=b6(k7,void 0,void 0,{sqrt:Hle}),Fo=A7({a:BigInt(0),b:BigInt(7),Fp:JR,n:N9,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=N9,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Gle*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),a=r,s=BigInt("0x100000000000000000000000000000000"),o=U9(a*t,e),d=U9(-n*t,e),l=Zr(t-o*r-d*i,e),c=Zr(-o*n-d*a,e),u=l>s,f=c>s;if(u&&(l=e-l),f&&(c=e-c),l>s||c>s)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:c}}}},g7),SNe=BigInt(0),ANe=Fo.ProjectivePoint;g2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,MR=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),vd=(t,e)=>t<<32-e|t>>>e,kNe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;Zle=class{clone(){return this._cloneInto()}},_Ne={}.toString;eue=(t,e,r)=>t&e^~t&r,tue=(t,e,r)=>t&e^t&r^e&r,rue=class extends Zle{constructor(t,e,r,n){super(),this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=MR(this.buffer)}update(t){L9(this);let{view:e,buffer:r,blockLen:n}=this;t=T7(t);let i=t.length;for(let a=0;a<i;){let s=Math.min(n-this.pos,i-a);if(s===n){let o=MR(t);for(;n<=i-a;a+=n)this.process(o,a);continue}r.set(t.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===n&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){L9(this),Wle(t,this),this.finished=!0;let{buffer:e,view:r,blockLen:n,isLE:i}=this,{pos:a}=this;e[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>n-a&&(this.process(r,0),a=0);for(let c=a;c<n;c++)e[c]=0;Qle(r,n-8,BigInt(this.length*8),i),this.process(r,0);let s=MR(t),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=o/4,l=this.get();if(d>l.length)throw new Error("_sha2: outputLen bigger than state");for(let c=0;c<d;c++)s.setUint32(4*c,l[c],i)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let r=t.slice(0,e);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:r,length:n,finished:i,destroyed:a,pos:s}=this;return t.length=n,t.pos=s,t.finished=i,t.destroyed=a,n%e&&t.buffer.set(r),t}},nue=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]),af=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cf=new Uint32Array(64),iue=class extends rue{constructor(){super(64,32,8,!1),this.A=af[0]|0,this.B=af[1]|0,this.C=af[2]|0,this.D=af[3]|0,this.E=af[4]|0,this.F=af[5]|0,this.G=af[6]|0,this.H=af[7]|0}get(){let{A:t,B:e,C:r,D:n,E:i,F:a,G:s,H:o}=this;return[t,e,r,n,i,a,s,o]}set(t,e,r,n,i,a,s,o){this.A=t|0,this.B=e|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=s|0,this.H=o|0}process(t,e){for(let c=0;c<16;c++,e+=4)cf[c]=t.getUint32(e,!1);for(let c=16;c<64;c++){let u=cf[c-15],f=cf[c-2],h=vd(u,7)^vd(u,18)^u>>>3,p=vd(f,17)^vd(f,19)^f>>>10;cf[c]=p+cf[c-7]+h+cf[c-16]|0}let{A:r,B:n,C:i,D:a,E:s,F:o,G:d,H:l}=this;for(let c=0;c<64;c++){let u=vd(s,6)^vd(s,11)^vd(s,25),f=l+u+eue(s,o,d)+nue[c]+cf[c]|0,h=(vd(r,2)^vd(r,13)^vd(r,22))+tue(r,n,i)|0;l=d,d=o,o=s,s=a+f|0,a=i,i=n,n=r,r=f+h|0}r=r+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,d=d+this.G|0,l=l+this.H|0,this.set(r,n,i,a,s,o,d,l)}roundClean(){cf.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},qv=Yle(()=>new iue);oue=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},I7=class{static digest(t){return oue(this,arguments,void 0,function*({data:e}){return qv(e)})}},aue=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},q9="urn:jwk:";Wi=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},due=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Xi=class Pd{static adjustSignatureToLowS(e){return Wi(this,arguments,void 0,function*({signature:r}){let n=Fo.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Wi(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield Pd.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"secp256k1",d:it.uint8Array(r).toBase64Url(),x:it.uint8Array(n.x).toBase64Url(),y:it.uint8Array(n.y).toBase64Url()};return i.kid=yield Ar({jwk:i}),i})}static bytesToPublicKey(e){return Wi(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield Pd.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"secp256k1",x:it.uint8Array(n.x).toBase64Url(),y:it.uint8Array(n.y).toBase64Url()};return i.kid=yield Ar({jwk:i}),i})}static compressPublicKey(e){return Wi(this,arguments,void 0,function*({publicKeyBytes:r}){return Fo.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Wi(this,arguments,void 0,function*({key:r}){let n=yield Pd.privateKeyToBytes({privateKey:r}),i=yield Pd.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"secp256k1",x:it.uint8Array(i.x).toBase64Url(),y:it.uint8Array(i.y).toBase64Url()};return a.kid=yield Ar({jwk:a}),a})}static convertDerToCompactSignature(e){return Wi(this,arguments,void 0,function*({derSignature:r}){return Fo.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Wi(this,arguments,void 0,function*({publicKeyBytes:r}){return Fo.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Wi(this,void 0,void 0,function*(){let e=Fo.utils.randomPrivateKey(),r=yield Pd.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield Ar({jwk:r}),r})}static getPublicKey(e){return Wi(this,arguments,void 0,function*({key:r}){var n;if(!(ch(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=r,a=due(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield Ar({jwk:a})),a})}static privateKeyToBytes(e){return Wi(this,arguments,void 0,function*({privateKey:r}){if(!ch(r))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return it.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Wi(this,arguments,void 0,function*({publicKey:r}){if(!(x6(r)&&r.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=it.base64Url(r.x).toUint8Array(),a=it.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...i,...a])})}static sharedSecret(e){return Wi(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.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 Pd.privateKeyToBytes({privateKey:r}),a=yield Pd.publicKeyToBytes({publicKey:n});return Fo.getSharedSecret(i,a,!0).slice(1)})}static sign(e){return Wi(this,arguments,void 0,function*({data:r,key:n}){let i=yield Pd.privateKeyToBytes({privateKey:n}),a=qv(r);return Fo.sign(a,i).toCompactRawBytes()})}static validatePrivateKey(e){return Wi(this,arguments,void 0,function*({privateKeyBytes:r}){return Fo.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Wi(this,arguments,void 0,function*({publicKeyBytes:r}){try{Fo.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Wi(this,arguments,void 0,function*({key:r,signature:n,data:i}){let a=yield Pd.publicKeyToBytes({publicKey:r}),s=qv(i);return Fo.verify(n,s,a,{lowS:!1})})}static getCurvePoint(e){return Wi(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Fo.getPublicKey(r));let n=Fo.ProjectivePoint.fromHex(r),i=_d(n.x,32),a=_d(n.y,32);return{x:i,y:a}})}},D7=b6(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),lue=D7.create(BigInt("-3")),uue=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),fue=A7({a:lue,b:uue,Fp:D7,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},g7),Aa=fue,Ji=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},pue=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},ws=class xd{static adjustSignatureToLowS(e){return Ji(this,arguments,void 0,function*({signature:r}){let n=Aa.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Ji(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield xd.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"P-256",d:it.uint8Array(r).toBase64Url(),x:it.uint8Array(n.x).toBase64Url(),y:it.uint8Array(n.y).toBase64Url()};return i.kid=yield Ar({jwk:i}),i})}static bytesToPublicKey(e){return Ji(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield xd.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"P-256",x:it.uint8Array(n.x).toBase64Url(),y:it.uint8Array(n.y).toBase64Url()};return i.kid=yield Ar({jwk:i}),i})}static compressPublicKey(e){return Ji(this,arguments,void 0,function*({publicKeyBytes:r}){return Aa.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Ji(this,arguments,void 0,function*({key:r}){let n=yield xd.privateKeyToBytes({privateKey:r}),i=yield xd.getCurvePoint({keyBytes:n}),a={kty:"EC",crv:"P-256",x:it.uint8Array(i.x).toBase64Url(),y:it.uint8Array(i.y).toBase64Url()};return a.kid=yield Ar({jwk:a}),a})}static convertDerToCompactSignature(e){return Ji(this,arguments,void 0,function*({derSignature:r}){return Aa.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Ji(this,arguments,void 0,function*({publicKeyBytes:r}){return Aa.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Ji(this,void 0,void 0,function*(){let e=Aa.utils.randomPrivateKey(),r=yield xd.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield Ar({jwk:r}),r})}static getPublicKey(e){return Ji(this,arguments,void 0,function*({key:r}){var n;if(!(ch(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=r,a=pue(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield Ar({jwk:a})),a})}static privateKeyToBytes(e){return Ji(this,arguments,void 0,function*({privateKey:r}){if(!ch(r))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return it.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Ji(this,arguments,void 0,function*({publicKey:r}){if(!(x6(r)&&r.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=it.base64Url(r.x).toUint8Array(),a=it.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...i,...a])})}static sharedSecret(e){return Ji(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.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 xd.privateKeyToBytes({privateKey:r}),a=yield xd.publicKeyToBytes({publicKey:n});return Aa.getSharedSecret(i,a,!0).slice(1)})}static sign(e){return Ji(this,arguments,void 0,function*({data:r,key:n}){let i=yield xd.privateKeyToBytes({privateKey:n}),a=qv(r);return Aa.sign(a,i).toCompactRawBytes()})}static validatePrivateKey(e){return Ji(this,arguments,void 0,function*({privateKeyBytes:r}){return Aa.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Ji(this,arguments,void 0,function*({publicKeyBytes:r}){try{Aa.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Ji(this,arguments,void 0,function*({key:r,signature:n,data:i}){let a=yield xd.publicKeyToBytes({publicKey:r}),s=qv(i);return Aa.verify(n,s,a,{lowS:!1})})}static getCurvePoint(e){return Ji(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Aa.getPublicKey(r));let n=Aa.ProjectivePoint.fromHex(r),i=_d(n.x,32),a=_d(n.y,32);return{x:i,y:a}})}},Il=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},z9=class extends Z2{bytesToPrivateKey(t){return Il(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield Xi.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield ws.bytesToPrivateKey({privateKeyBytes:r});return n.alg="ES256",n}default:throw new $a(fo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return Il(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"ES256K":case"secp256k1":{let n=yield Xi.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield ws.bytesToPublicKey({publicKeyBytes:r});return n.alg="ES256",n}default:throw new $a(fo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return Il(this,arguments,void 0,function*({key:e}){if(!ch(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield Xi.computePublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield ws.computePublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return Il(this,arguments,void 0,function*({algorithm:e}){switch(e){case"ES256K":case"secp256k1":{let r=yield Xi.generateKey();return r.alg="ES256K",r}case"ES256":case"secp256r1":{let r=yield ws.generateKey();return r.alg="ES256",r}}})}getPublicKey(t){return Il(this,arguments,void 0,function*({key:e}){if(!ch(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":{let r=yield Xi.getPublicKey({key:e});return r.alg="ES256K",r}case"P-256":{let r=yield ws.getPublicKey({key:e});return r.alg="ES256",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return Il(this,arguments,void 0,function*({key:e,data:r}){if(!ch(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(e.crv){case"secp256k1":return yield Xi.sign({key:e,data:r});case"P-256":return yield ws.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return Il(this,arguments,void 0,function*({key:e,signature:r,data:n}){if(!x6(e))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(e.crv){case"secp256k1":return yield Xi.verify({key:e,signature:r,data:n});case"P-256":return yield ws.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return Il(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"secp256k1":return yield Xi.privateKeyToBytes({privateKey:e});case"P-256":return yield ws.privateKeyToBytes({privateKey:e});default:throw new $a(fo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return Il(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"secp256k1":return yield Xi.publicKeyToBytes({publicKey:e});case"P-256":return yield ws.publicKeyToBytes({publicKey:e});default:throw new $a(fo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},d2=BigInt(4294967295),ZR=BigInt(32);mue=(t,e)=>BigInt(t>>>0)<<ZR|BigInt(e>>>0),yue=(t,e,r)=>t>>>r,gue=(t,e,r)=>t<<32-r|e>>>r,wue=(t,e,r)=>t>>>r|e<<32-r,vue=(t,e,r)=>t<<32-r|e>>>r,bue=(t,e,r)=>t<<64-r|e>>>r-32,Pue=(t,e,r)=>t>>>r-32|e<<64-r,xue=(t,e)=>e,Eue=(t,e)=>t,Sue=(t,e,r)=>t<<r|e>>>32-r,Aue=(t,e,r)=>e<<r|t>>>32-r,kue=(t,e,r)=>e<<r-32|t>>>64-r,_ue=(t,e,r)=>t<<r-32|e>>>64-r;Iue=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Due=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Rue=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Cue=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,$ue=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Bue=(t,e,r,n,i,a)=>e+r+n+i+a+(t/2**32|0)|0,Oue={fromBig:R7,split:hue,toBig:mue,shrSH:yue,shrSL:gue,rotrSH:wue,rotrSL:vue,rotrBH:bue,rotrBL:Pue,rotr32H:xue,rotr32L:Eue,rotlSH:Sue,rotlSL:Aue,rotlBH:kue,rotlBL:_ue,add:Tue,add3L:Iue,add3H:Due,add4L:Rue,add4H:Cue,add5H:Bue,add5L:$ue},Nt=Oue,[jue,Mue]=Nt.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(t=>BigInt(t))),df=new Uint32Array(80),lf=new Uint32Array(80),Kue=class extends y7{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:t,Al:e,Bh:r,Bl:n,Ch:i,Cl:a,Dh:s,Dl:o,Eh:d,El:l,Fh:c,Fl:u,Gh:f,Gl:h,Hh:p,Hl:m}=this;return[t,e,r,n,i,a,s,o,d,l,c,u,f,h,p,m]}set(t,e,r,n,i,a,s,o,d,l,c,u,f,h,p,m){this.Ah=t|0,this.Al=e|0,this.Bh=r|0,this.Bl=n|0,this.Ch=i|0,this.Cl=a|0,this.Dh=s|0,this.Dl=o|0,this.Eh=d|0,this.El=l|0,this.Fh=c|0,this.Fl=u|0,this.Gh=f|0,this.Gl=h|0,this.Hh=p|0,this.Hl=m|0}process(t,e){for(let w=0;w<16;w++,e+=4)df[w]=t.getUint32(e),lf[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let S=df[w-15]|0,k=lf[w-15]|0,T=Nt.rotrSH(S,k,1)^Nt.rotrSH(S,k,8)^Nt.shrSH(S,k,7),D=Nt.rotrSL(S,k,1)^Nt.rotrSL(S,k,8)^Nt.shrSL(S,k,7),K=df[w-2]|0,C=lf[w-2]|0,G=Nt.rotrSH(K,C,19)^Nt.rotrBH(K,C,61)^Nt.shrSH(K,C,6),z=Nt.rotrSL(K,C,19)^Nt.rotrBL(K,C,61)^Nt.shrSL(K,C,6),N=Nt.add4L(D,z,lf[w-7],lf[w-16]),V=Nt.add4H(N,T,G,df[w-7],df[w-16]);df[w]=V|0,lf[w]=N|0}let{Ah:r,Al:n,Bh:i,Bl:a,Ch:s,Cl:o,Dh:d,Dl:l,Eh:c,El:u,Fh:f,Fl:h,Gh:p,Gl:m,Hh:y,Hl:b}=this;for(let w=0;w<80;w++){let S=Nt.rotrSH(c,u,14)^Nt.rotrSH(c,u,18)^Nt.rotrBH(c,u,41),k=Nt.rotrSL(c,u,14)^Nt.rotrSL(c,u,18)^Nt.rotrBL(c,u,41),T=c&f^~c&p,D=u&h^~u&m,K=Nt.add5L(b,k,D,Mue[w],lf[w]),C=Nt.add5H(K,y,S,T,jue[w],df[w]),G=K|0,z=Nt.rotrSH(r,n,28)^Nt.rotrBH(r,n,34)^Nt.rotrBH(r,n,39),N=Nt.rotrSL(r,n,28)^Nt.rotrBL(r,n,34)^Nt.rotrBL(r,n,39),V=r&i^r&s^i&s,ee=n&a^n&o^a&o;y=p|0,b=m|0,p=f|0,m=h|0,f=c|0,h=u|0,{h:c,l:u}=Nt.add(d|0,l|0,C|0,G|0),d=s|0,l=o|0,s=i|0,o=a|0,i=r|0,a=n|0;let R=Nt.add3L(G,N,ee);r=Nt.add3H(R,C,z,V),n=R|0}({h:r,l:n}=Nt.add(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:a}=Nt.add(this.Bh|0,this.Bl|0,i|0,a|0),{h:s,l:o}=Nt.add(this.Ch|0,this.Cl|0,s|0,o|0),{h:d,l}=Nt.add(this.Dh|0,this.Dl|0,d|0,l|0),{h:c,l:u}=Nt.add(this.Eh|0,this.El|0,c|0,u|0),{h:f,l:h}=Nt.add(this.Fh|0,this.Fl|0,f|0,h|0),{h:p,l:m}=Nt.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:y,l:b}=Nt.add(this.Hh|0,this.Hl|0,y|0,b|0),this.set(r,n,i,a,s,o,d,l,c,u,f,h,p,m,y,b)}roundClean(){df.fill(0),lf.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)}},C7=m7(()=>new Kue),bc=BigInt(0),qo=BigInt(1),l2=BigInt(2),Nue=BigInt(8),Uue={zip215:!0};wv=BigInt(0),KR=BigInt(1);zv=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),F9=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),TNe=BigInt(0),Fue=BigInt(1),YR=BigInt(2),Gue=BigInt(5),G9=BigInt(10),Hue=BigInt(20),Vue=BigInt(40),H9=BigInt(80);Ba=b6(zv,void 0,!0),Fv={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ba,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:C7,randomBytes:v6,adjustScalarBytes:B7,uvRatio:Wue},eh=S6(Fv);INe=S6({...Fv,domain:O7}),DNe=S6({...Fv,domain:O7,prehash:C7}),Sv=zue({P:zv,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=zv,{pow_p_5_8:r,b2:n}=$7(t);return Zr(Pn(r,BigInt(3),e)*n,e)},adjustScalarBytes:B7,randomBytes:v6});Yue=(Ba.ORDER+BigInt(3))/BigInt(8),RNe=Ba.pow(YR,Yue),CNe=Ba.sqrt(Ba.neg(Ba.ONE)),$Ne=(Ba.ORDER-BigInt(5))/BigInt(8),BNe=BigInt(486662),ONe=Ole(Ba,Ba.neg(BigInt(486664))),jNe=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),MNe=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),KNe=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),NNe=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),UNe=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),ka=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Xue=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Qi=class mf{static bytesToPrivateKey(e){return ka(this,arguments,void 0,function*({privateKeyBytes:r}){let n=eh.getPublicKey(r),i={crv:"Ed25519",d:it.uint8Array(r).toBase64Url(),kty:"OKP",x:it.uint8Array(n).toBase64Url()};return i.kid=yield Ar({jwk:i}),i})}static bytesToPublicKey(e){return ka(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:it.uint8Array(r).toBase64Url()};return n.kid=yield Ar({jwk:n}),n})}static computePublicKey(e){return ka(this,arguments,void 0,function*({key:r}){let n=yield mf.privateKeyToBytes({privateKey:r}),i=eh.getPublicKey(n),a={kty:"OKP",crv:"Ed25519",x:it.uint8Array(i).toBase64Url()};return a.kid=yield Ar({jwk:a}),a})}static convertPrivateKeyToX25519(e){return ka(this,arguments,void 0,function*({privateKey:r}){let n=yield mf.privateKeyToBytes({privateKey:r}),i=Zue(n),a=Sv.getPublicKey(i),s={kty:"OKP",crv:"X25519",d:it.uint8Array(i).toBase64Url(),x:it.uint8Array(a).toBase64Url()};return s.kid=yield Ar({jwk:s}),s})}static convertPublicKeyToX25519(e){return ka(this,arguments,void 0,function*({publicKey:r}){let n=yield mf.publicKeyToBytes({publicKey:r});if(!(yield mf.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let i=Jue(n),a={kty:"OKP",crv:"X25519",x:it.uint8Array(i).toBase64Url()};return a.kid=yield Ar({jwk:a}),a})}static generateKey(){return ka(this,void 0,void 0,function*(){let e=eh.utils.randomPrivateKey(),r=yield mf.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield Ar({jwk:r}),r})}static getPublicKey(e){return ka(this,arguments,void 0,function*({key:r}){var n;if(!(Ml(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=r,a=Xue(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield Ar({jwk:a})),a})}static privateKeyToBytes(e){return ka(this,arguments,void 0,function*({privateKey:r}){if(!Ml(r))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return it.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return ka(this,arguments,void 0,function*({publicKey:r}){if(!E6(r))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return it.base64Url(r.x).toUint8Array()})}static sign(e){return ka(this,arguments,void 0,function*({key:r,data:n}){let i=yield mf.privateKeyToBytes({privateKey:r});return eh.sign(n,i)})}static validatePublicKey(e){return ka(this,arguments,void 0,function*({publicKeyBytes:r}){try{eh.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return ka(this,arguments,void 0,function*({key:r,signature:n,data:i}){let a=yield mf.publicKeyToBytes({publicKey:r});return eh.verify(n,i,a)})}},Dl=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Que=class extends Z2{bytesToPrivateKey(t){return Dl(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"Ed25519":{let n=yield Qi.bytesToPrivateKey({privateKeyBytes:r});return n.alg="EdDSA",n}default:throw new $a(fo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}bytesToPublicKey(t){return Dl(this,arguments,void 0,function*({algorithm:e,publicKeyBytes:r}){switch(e){case"Ed25519":{let n=yield Qi.bytesToPublicKey({publicKeyBytes:r});return n.alg="EdDSA",n}default:throw new $a(fo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return Dl(this,arguments,void 0,function*({key:e}){if(!Ml(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield Qi.computePublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}generateKey(t){return Dl(this,arguments,void 0,function*({algorithm:e}){switch(e){case"Ed25519":{let r=yield Qi.generateKey();return r.alg="EdDSA",r}}})}getPublicKey(t){return Dl(this,arguments,void 0,function*({key:e}){if(!Ml(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":{let r=yield Qi.getPublicKey({key:e});return r.alg="EdDSA",r}default:throw new Error(`Unsupported curve: ${e.crv}`)}})}sign(t){return Dl(this,arguments,void 0,function*({key:e,data:r}){if(!Ml(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"Ed25519":return yield Qi.sign({key:e,data:r});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}verify(t){return Dl(this,arguments,void 0,function*({key:e,signature:r,data:n}){if(!E6(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(e.crv){case"Ed25519":return yield Qi.verify({key:e,signature:r,data:n});default:throw new Error(`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return Dl(this,arguments,void 0,function*({privateKey:e}){switch(e.crv){case"Ed25519":return yield Qi.privateKeyToBytes({privateKey:e});default:throw new $a(fo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}publicKeyToBytes(t){return Dl(this,arguments,void 0,function*({publicKey:e}){switch(e.crv){case"Ed25519":return yield Qi.publicKeyToBytes({publicKey:e});default:throw new $a(fo.AlgorithmNotSupported,`Curve not supported: ${e.crv}`)}})}},efe=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},tfe=class extends Z2{digest(t){return efe(this,arguments,void 0,function*({algorithm:e,data:r}){switch(e){case"SHA-256":return yield I7.digest({data:r})}})}},uf=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},rfe=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Dy=class Av{static bytesToPrivateKey(e){return uf(this,arguments,void 0,function*({privateKeyBytes:r}){let n=Sv.getPublicKey(r),i={kty:"OKP",crv:"X25519",d:it.uint8Array(r).toBase64Url(),x:it.uint8Array(n).toBase64Url()};return i.kid=yield Ar({jwk:i}),i})}static bytesToPublicKey(e){return uf(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:it.uint8Array(r).toBase64Url()};return n.kid=yield Ar({jwk:n}),n})}static computePublicKey(e){return uf(this,arguments,void 0,function*({key:r}){let n=yield Av.privateKeyToBytes({privateKey:r}),i=Sv.getPublicKey(n),a={kty:"OKP",crv:"X25519",x:it.uint8Array(i).toBase64Url()};return a.kid=yield Ar({jwk:a}),a})}static generateKey(){return uf(this,void 0,void 0,function*(){let e=Sv.utils.randomPrivateKey(),r=yield Av.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield Ar({jwk:r}),r})}static getPublicKey(e){return uf(this,arguments,void 0,function*({key:r}){var n;if(!(Ml(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=r,a=rfe(r,["d"]);return(n=a.kid)!==null&&n!==void 0||(a.kid=yield Ar({jwk:a})),a})}static privateKeyToBytes(e){return uf(this,arguments,void 0,function*({privateKey:r}){if(!Ml(r))throw new Error("X25519: The provided key is not a valid OKP private key.");return it.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return uf(this,arguments,void 0,function*({publicKey:r}){if(!E6(r))throw new Error("X25519: The provided key is not a valid OKP public key.");return it.base64Url(r.x).toUint8Array()})}static sharedSecret(e){return uf(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.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 Av.privateKeyToBytes({privateKey:r}),a=yield Av.publicKeyToBytes({publicKey:n});return Sv.getSharedSecret(i,a)})}},vv=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},nfe=class extends Z2{bytesToPrivateKey(t){return vv(this,arguments,void 0,function*({algorithm:e,privateKeyBytes:r}){switch(e){case"X25519":return Dy.bytesToPrivateKey({privateKeyBytes:r});default:throw new $a(fo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}computePublicKey(t){return vv(this,arguments,void 0,function*({key:e}){if(!Ml(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Dy.computePublicKey({key:e});default:throw new $a(fo.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}generateKey(t){return vv(this,arguments,void 0,function*({algorithm:e}){switch(e){case"X25519":return Dy.generateKey();default:throw new $a(fo.AlgorithmNotSupported,`Algorithm not supported: ${e}`)}})}getPublicKey(t){return vv(this,arguments,void 0,function*({key:e}){if(!Ml(e))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(e.crv){case"X25519":return Dy.getPublicKey({key:e});default:throw new $a(fo.AlgorithmNotSupported,`Unsupported curve: ${e.crv}`)}})}privateKeyToBytes(t){return vv(this,arguments,void 0,function*({privateKey:e}){return Dy.privateKeyToBytes({privateKey:e})})}},Rl=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},NR={Ed25519:{implementation:Que,names:["Ed25519"]},secp256k1:{implementation:z9,names:["ES256K","secp256k1"]},secp256r1:{implementation:z9,names:["ES256","secp256r1"]},"SHA-256":{implementation:tfe,names:["SHA-256"]},X25519:{implementation:nfe,names:["X25519"]}},Ec=class{constructor(t){var e;this._algorithmInstances=new Map,this._keyStore=(e=t?.keyStore)!==null&&e!==void 0?e:new ale}digest(t){return Rl(this,arguments,void 0,function*({algorithm:e,data:r}){return yield this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:r})})}exportKey(t){return Rl(this,arguments,void 0,function*({keyUri:e}){return yield this.getPrivateKey({keyUri:e})})}generateKey(t){return Rl(this,arguments,void 0,function*({algorithm:e}){let r=yield this.getAlgorithm({algorithm:e}).generateKey({algorithm:e});if(r?.kid===void 0)throw new Error("Generated key is missing a required property: kid");let n=`${q9}${r.kid}`;return yield this._keyStore.set(n,r),n})}getKeyUri(t){return Rl(this,arguments,void 0,function*({key:e}){let r=yield Ar({jwk:e});return`${q9}${r}`})}getPublicKey(t){return Rl(this,arguments,void 0,function*({keyUri:e}){let r=yield this.getPrivateKey({keyUri:e}),n=this.getAlgorithmName({key:r});return yield this.getAlgorithm({algorithm:n}).getPublicKey({key:r})})}importKey(t){return Rl(this,arguments,void 0,function*({key:e}){var r;if(!cue(e))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let n=structuredClone(e);(r=n.kid)!==null&&r!==void 0||(n.kid=yield Ar({jwk:n}));let i=yield this.getKeyUri({key:n});return yield this._keyStore.set(i,n),i})}sign(t){return Rl(this,arguments,void 0,function*({keyUri:e,data:r}){let n=yield this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:i}).sign({data:r,key:n})})}verify(t){return Rl(this,arguments,void 0,function*({key:e,signature:r,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:r,data:n})})}getAlgorithm({algorithm:t}){var e;let r=(e=NR[t])===null||e===void 0?void 0:e.implementation;if(!r)throw new Error(`Algorithm not supported: ${t}`);return this._algorithmInstances.has(r)||this._algorithmInstances.set(r,new r),this._algorithmInstances.get(r)}getAlgorithmName({key:t}){let e=t.alg,r=t.crv;for(let n in NR){let i=NR[n];if(e&&i.names.includes(e)||r&&i.names.includes(r))return n}throw new Error(`Unable to determine algorithm based on provided input: alg=${e}, crv=${r}`)}getPrivateKey(t){return Rl(this,arguments,void 0,function*({keyUri:e}){let r=yield this._keyStore.get(e);if(!r)throw new Error(`Key not found: ${e}`);return r})}},ife=class XR{static getJoseSignatureAlgorithmFromPublicKey(e){let r={Ed25519:"EdDSA","P-256":"ES256","P-384":"ES384","P-521":"ES512",secp256k1:"ES256K"};if(e.alg&&Object.values(r).includes(e.alg))return e.alg;if(e.crv&&Object.keys(r).includes(e.crv))return r[e.crv];throw new Error(`Unable to determine algorithm based on provided input: alg=${e.alg}, crv=${e.crv}. Supported 'alg' values: ${Object.values(r).join(", ")}. Supported 'crv' values: ${Object.keys(r).join(", ")}.`)}static randomBytes(e){return Xle(e)}static randomUuid(){return g2.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 r=Math.pow(10,e)-1,n;if(e<=6){let i=Math.pow(10,e);do{let a=XR.randomBytes(Math.ceil(e/2));n=new DataView(a.buffer).getUint16(0,!1)%i}while(n>r)}else{let i=Math.pow(10,10);do{let a=XR.randomBytes(4);n=new DataView(a.buffer).getUint32(0,!1)%i}while(n>r)}return n.toString().padStart(e,"0")}},sfe=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];Se=class{constructor(t,e,r){this.major=t,this.majorEncoded=t<<5,this.name=e,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(t){return this.major<t.major?-1:this.major>t.major?1:0}static equals(t,e){return t===e||t.major===e.major&&t.name===e.name}};Se.uint=new Se(0,"uint",!0);Se.negint=new Se(1,"negint",!0);Se.bytes=new Se(2,"bytes",!0);Se.string=new Se(3,"string",!0);Se.array=new Se(4,"array",!1);Se.map=new Se(5,"map",!1);Se.tag=new Se(6,"tag",!1);Se.float=new Se(7,"float",!0);Se.false=new Se(7,"false",!0);Se.true=new Se(7,"true",!0);Se.null=new Se(7,"null",!0);Se.undefined=new Se(7,"undefined",!0);Se.break=new Se(7,"break",!0);tt=class{constructor(t,e,r){this.type=t,this.value=e,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}},Zv=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",cfe=new TextEncoder;dfe=24,lfe=200,ufe=Zv?t=>t.length>=dfe?globalThis.Buffer.from(t):V9(t):t=>t.length>=lfe?cfe.encode(t):V9(t),Cl=t=>Uint8Array.from(t),ffe=Zv?(t,e,r)=>N2(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),pfe=Zv?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),j7(globalThis.Buffer.concat(t,e))):(t,e)=>{let r=new Uint8Array(e),n=0;for(let i of t)n+i.length>r.length&&(i=i.subarray(0,r.length-n)),r.set(i,n),n+=i.length;return r},hfe=Zv?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);mfe=256,K7=class{constructor(t=mfe){this.chunkSize=t,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(t){let e=this.chunks[this.chunks.length-1];if(this.cursor+t.length<=this.maxCursor+1){let r=e.length-(this.maxCursor-this.cursor)-1;e.set(t,r)}else{if(e){let r=e.length-(this.maxCursor-this.cursor)-1;r<e.length&&(this.chunks[this.chunks.length-1]=e.subarray(0,r),this.maxCursor=this.cursor-1)}t.length<64&&t.length<this.chunkSize?(e=hfe(this.chunkSize),this.chunks.push(e),this.maxCursor+=e.length,this._initReuseChunk===null&&(this._initReuseChunk=e),e.set(t,0)):(this.chunks.push(t),this.maxCursor+=t.length)}this.cursor+=t.length}toBytes(t=!1){let e;if(this.chunks.length===1){let r=this.chunks[0];t&&this.cursor>r.length/2?(e=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):e=ffe(r,0,this.cursor)}else e=pfe(this.chunks,this.cursor);return t&&this.reset(),e}},yfe=class{constructor(t){this.dest=t,this.cursor=0,this.chunks=[t]}reset(){this.cursor=0}push(t){if(this.cursor+t.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(t,this.cursor),this.cursor+=t.length}toBytes(t=!1){let e=this.dest.subarray(0,this.cursor);return t&&this.reset(),e}},xn="CBOR decode error:",N7="CBOR encode error:",Yv=[];Yv[23]=1;Yv[24]=2;Yv[25]=3;Yv[26]=5;Yv[27]=9;es=[24,256,65536,4294967296,BigInt("18446744073709551616")];vh.encodedSize=function(t){return ja.encodedSize(t.value)};ja.encodedSize=function(t){return t<es[0]?1:t<es[1]?2:t<es[2]?3:t<es[3]?5:9};vh.compareTokens=function(t,e){return t.value<e.value?-1:t.value>e.value?1:0};A6=BigInt(-1),U7=BigInt(1);k6.encodedSize=function(t){let e=t.value,r=typeof e=="bigint"?e*A6-U7:e*-1-1;return r<es[0]?1:r<es[1]?2:r<es[2]?3:r<es[3]?5:9};k6.compareTokens=function(t,e){return t.value<e.value?1:t.value>e.value?-1:0};X2.encodedSize=function(t){let e=U2(t);return ja.encodedSize(e.length)+e.length};X2.compareTokens=function(t,e){return Dfe(U2(t),U2(e))};W9=new TextDecoder,Rfe=32;Kfe=X2;_6.compareTokens=vh.compareTokens;_6.encodedSize=function(t){return ja.encodedSize(t.value)};T6.compareTokens=vh.compareTokens;T6.encodedSize=function(t){return ja.encodedSize(t.value)};I6.compareTokens=vh.compareTokens;I6.encodedSize=function(t){return ja.encodedSize(t.value)};L7=20,q7=21,z7=22,F7=23;R6.encodedSize=function(t,e){let r=t.value;if(r===!1||r===!0||r===null||r===void 0)return 1;if(!e||e.float64!==!0){H7(r);let n=C6(Pc,1);if(r===n||Number.isNaN(r))return 3;if(V7(r),n=$6(Pc,1),r===n)return 5}return 9};G7=new ArrayBuffer(9),Ta=new DataView(G7,1),Pc=new Uint8Array(G7,0);R6.compareTokens=vh.compareTokens;je=[];for(let t=0;t<=23;t++)je[t]=mr;je[24]=gfe;je[25]=wfe;je[26]=vfe;je[27]=bfe;je[28]=mr;je[29]=mr;je[30]=mr;je[31]=mr;for(let t=32;t<=55;t++)je[t]=mr;je[56]=Pfe;je[57]=xfe;je[58]=Efe;je[59]=Sfe;je[60]=mr;je[61]=mr;je[62]=mr;je[63]=mr;for(let t=64;t<=87;t++)je[t]=Afe;je[88]=kfe;je[89]=_fe;je[90]=Tfe;je[91]=Ife;je[92]=mr;je[93]=mr;je[94]=mr;je[95]=Q2("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)je[t]=$fe;je[120]=Bfe;je[121]=Ofe;je[122]=jfe;je[123]=Mfe;je[124]=mr;je[125]=mr;je[126]=mr;je[127]=Q2("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)je[t]=Nfe;je[152]=Ufe;je[153]=Lfe;je[154]=qfe;je[155]=zfe;je[156]=mr;je[157]=mr;je[158]=mr;je[159]=Ffe;for(let t=160;t<=183;t++)je[t]=Gfe;je[184]=Hfe;je[185]=Vfe;je[186]=Wfe;je[187]=Jfe;je[188]=mr;je[189]=mr;je[190]=mr;je[191]=Zfe;for(let t=192;t<=215;t++)je[t]=Yfe;je[216]=Xfe;je[217]=Qfe;je[218]=epe;je[219]=tpe;je[220]=mr;je[221]=mr;je[222]=mr;je[223]=mr;for(let t=224;t<=243;t++)je[t]=Q2("simple values are not supported");je[244]=mr;je[245]=mr;je[246]=mr;je[247]=rpe;je[248]=Q2("simple values are not supported");je[249]=ipe;je[250]=spe;je[251]=ope;je[252]=mr;je[253]=mr;je[254]=mr;je[255]=npe;Nl=[];for(let t=0;t<24;t++)Nl[t]=new tt(Se.uint,t,1);for(let t=-1;t>=-24;t--)Nl[31-t]=new tt(Se.negint,t,1);Nl[64]=new tt(Se.bytes,new Uint8Array(0),1);Nl[96]=new tt(Se.string,"",1);Nl[128]=new tt(Se.array,0,1);Nl[160]=new tt(Se.map,0,1);Nl[244]=new tt(Se.false,!1,1);Nl[245]=new tt(Se.true,!0,1);Nl[246]=new tt(Se.null,null,1);dpe=Object.freeze({float64:!0,mapSorter:hpe,quickEncodeToken:cpe});upe=lpe(),fpe=new K7,J9=class J7{constructor(e,r){this.obj=e,this.parent=r}includes(e){let r=this;do if(r.obj===e)return!0;while(r=r.parent);return!1}static createCheck(e,r){if(e&&e.includes(r))throw new Error(`${N7} object contains circular references`);return new J7(r,e)}},ff={null:new tt(Se.null,null),undefined:new tt(Se.undefined,void 0),true:new tt(Se.true,!0),false:new tt(Se.false,!1),emptyArray:new tt(Se.array,0),emptyMap:new tt(Se.map,0)},Pf={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new tt(Se.float,t):t>=0?new tt(Se.uint,t):new tt(Se.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new tt(Se.uint,t):new tt(Se.negint,t)},Uint8Array(t,e,r,n){return new tt(Se.bytes,t)},string(t,e,r,n){return new tt(Se.string,t)},boolean(t,e,r,n){return t?ff.true:ff.false},null(t,e,r,n){return ff.null},undefined(t,e,r,n){return ff.undefined},ArrayBuffer(t,e,r,n){return new tt(Se.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new tt(Se.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[ff.emptyArray,new tt(Se.break)]:ff.emptyArray;n=J9.createCheck(n,t);let i=[],a=0;for(let s of t)i[a++]=w2(s,r,n);return r.addBreakTokens?[new tt(Se.array,t.length),i,new tt(Se.break)]:[new tt(Se.array,t.length),i]},Object(t,e,r,n){let i=e!=="Object",a=i?t.keys():Object.keys(t),s=i?t.size:a.length,o;if(s){o=new Array(s),n=J9.createCheck(n,t);let d=!i&&r.ignoreUndefinedProperties,l=0;for(let c of a){let u=i?t.get(c):t[c];d&&u===void 0||(o[l++]=[w2(c,r,n),w2(u,r,n)])}l<s&&(o.length=l)}return o?.length?(ppe(o,r),r.addBreakTokens?[new tt(Se.map,o.length),o,new tt(Se.break)]:[new tt(Se.map,o.length),o]):r.addBreakTokens===!0?[ff.emptyMap,new tt(Se.break)]:ff.emptyMap}};Pf.Map=Pf.Object;Pf.Buffer=Pf.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Pf[`${t}Array`]=Pf.DataView;LNe=Se.uint.majorEncoded,qNe=Se.negint.majorEncoded,zNe=Se.bytes.majorEncoded,FNe=Se.string.majorEncoded,GNe=Se.array.majorEncoded,HNe=Se.float.majorEncoded|L7,VNe=Se.float.majorEncoded|q7,WNe=Se.float.majorEncoded|z7,JNe=Se.float.majorEncoded|F7,ZNe=BigInt(-1),YNe=BigInt(1);XNe=Symbol.for("DONE"),QNe=Symbol.for("BREAK");(function(t){t[t.OKP=1]="OKP",t[t.EC2=2]="EC2",t[t.Symmetric=4]="Symmetric"})(Y9||(Y9={}));(function(t){t[t.P256=1]="P256",t[t.P384=2]="P384",t[t.P521=3]="P521",t[t.X25519=4]="X25519",t[t.X448=5]="X448",t[t.Ed25519=6]="Ed25519",t[t.Ed448=7]="Ed448",t[t.Secp256k1=8]="Secp256k1"})(vs||(vs={}));(function(t){t[t.EdDSA=-8]="EdDSA",t[t.ES256=-7]="ES256",t[t.ES384=-35]="ES384",t[t.ES512=-36]="ES512",t[t.ES256K=-47]="ES256K"})(Ca||(Ca={}));(function(t){t[t.Kty=1]="Kty",t[t.Kid=2]="Kid",t[t.Alg=3]="Alg",t[t.KeyOps=4]="KeyOps",t[t.BaseIv=5]="BaseIv"})(X9||(X9={}));(function(t){t[t.Crv=-1]="Crv",t[t.X=-2]="X",t[t.Y=-3]="Y",t[t.D=-4]="D"})(Q9||(Q9={}));eUe={"P-256":vs.P256,"P-384":vs.P384,"P-521":vs.P521,X25519:vs.X25519,Ed25519:vs.Ed25519,Ed448:vs.Ed448,secp256k1:vs.Secp256k1},tUe={[vs.P256]:"P-256",[vs.P384]:"P-384",[vs.P521]:"P-521",[vs.X25519]:"X25519",[vs.Ed25519]:"Ed25519",[vs.Ed448]:"Ed448",[vs.Secp256k1]:"secp256k1"},rUe={EdDSA:Ca.EdDSA,ES256:Ca.ES256,ES384:Ca.ES384,ES512:Ca.ES512,ES256K:Ca.ES256K},nUe={[Ca.EdDSA]:"EdDSA",[Ca.ES256]:"ES256",[Ca.ES384]:"ES384",[Ca.ES512]:"ES512",[Ca.ES256K]:"ES256K"};(function(t){t[t.Alg=1]="Alg",t[t.Crit=2]="Crit",t[t.ContentType=3]="ContentType",t[t.Kid=4]="Kid"})(eq||(eq={}));(function(t){t[t.Iss=1]="Iss",t[t.Sub=2]="Sub",t[t.Aud=3]="Aud",t[t.Exp=4]="Exp",t[t.Nbf=5]="Nbf",t[t.Iat=6]="Iat",t[t.Cti=7]="Cti",t[t.Nonce=10]="Nonce",t[t.Ueid=256]="Ueid",t[t.Sueids=257]="Sueids",t[t.Oemid=258]="Oemid",t[t.Hwmodel=259]="Hwmodel",t[t.Hwversion=260]="Hwversion",t[t.Secboot=262]="Secboot",t[t.Dbgstat=263]="Dbgstat",t[t.Location=264]="Location",t[t.Profile=265]="Profile",t[t.Submods=266]="Submods",t[t.Measres=272]="Measres",t[t.Intuse=268]="Intuse"})(tq||(tq={}));(function(t){t[t.Enabled=0]="Enabled",t[t.Disabled=1]="Disabled",t[t.DisabledSinceBoot=2]="DisabledSinceBoot",t[t.DisabledPermanently=3]="DisabledPermanently",t[t.DisabledFullyAndPermanently=4]="DisabledFullyAndPermanently"})(rq||(rq={}));(function(t){t[t.Unrestricted=1]="Unrestricted",t[t.Restricted=2]="Restricted",t[t.SecureRestricted=3]="SecureRestricted",t[t.Hardware=4]="Hardware"})(nq||(nq={}));B6={};u6(B6,{extractDidFragment:()=>Gs,getServices:()=>ype,getVerificationMethodByKey:()=>gpe,getVerificationMethodTypes:()=>Y7,getVerificationMethods:()=>eE,getVerificationRelationshipsById:()=>X7,isDidService:()=>Q7,isDidVerificationMethod:()=>L2,isDwnDidService:()=>wpe,isPortableDid:()=>bh,keyBytesToMultibaseId:()=>ez,multibaseIdToKeyBytes:()=>tz});bs=class rz{constructor({uri:e,document:r,metadata:n,keyManager:i}){this.uri=e,this.document=r,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 r=[];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});r.push({...a})}e.privateKeys=r}return e}async getSigner(e){let r=this.document.verificationMethod?.find(s=>Gs(s.id)===(Gs(e?.methodId)??Gs(this.document.assertionMethod?.[0])));if(!(r&&r.publicKeyJwk))throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");let n=await this.keyManager.getKeyUri({key:r.publicKeyJwk}),i=await this.keyManager.getPublicKey({keyUri:n}),a=this.keyManager;return{algorithm:ife.getJoseSignatureAlgorithmFromPublicKey(i),keyId:r.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:r=new Ec}){let n=eE({didDocument:e.document});if(n.length===0)throw new rt("invalidDidDocument","At least one verification method is required but 0 were given");for(let i of e.privateKeys??[]){let a=await r.getKeyUri({key:i});await r.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1)||await r.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 r.getKeyUri({key:i.publicKeyJwk});await r.getPublicKey({keyUri:a})}return new rz({uri:e.uri,document:e.document,metadata:e.metadata,keyManager:r})}},eb=class{static async getSigningMethod(t){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")}static async resolve(t,e){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")}},nz=(t=>(t[t.Discoverable=0]="Discoverable",t[t.Organization=1]="Organization",t[t.Government=2]="Government",t[t.Corporation=3]="Corporation",t[t.LocalBusiness=4]="LocalBusiness",t[t.SoftwarePackage=5]="SoftwarePackage",t[t.WebApp=6]="WebApp",t[t.FinancialInstitution=7]="FinancialInstitution",t))(nz||{}),O6=(t=>(t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519",t))(O6||{}),iz=(t=>(t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm",t))(iz||{}),iq="0123456789abcdef",sz=[],sq=[];for(let t=0;t<256;t++)sz[t]=iq[t>>4&15]+iq[t&15],t<16&&(t<10?sq[48+t]=t:sq[87+t]=t);vpe=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=sz[t[n++]];return r},bpe=(t,e=0)=>{let r=t.length||0;if(!e){let s=r;for(;s--;)e+=t[s].length}let n=new Uint8Array(e),i=e,a=r;for(;a--;)i-=t[a].length,n.set(t[a],i);return n},oq="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ppe=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(bv=0;bv<oq.length;bv++)Ppe[oq.charCodeAt(bv)]=bv;xpe=new TextDecoder,oz=(t,e)=>e?new TextDecoder(e).decode(t):xpe.decode(t),Epe=new TextEncoder,Kl=t=>Epe.encode(t),aq=typeof window<"u"?window:self,cq=aq.crypto||aq.msCrypto||{},iUe=cq.subtle||cq.webkitSubtle;vr.bytes=-1;vr._floatConversionDetected=!1;vr._encode=function(t,e){if(e!=null)switch(az(e)){case"object":vr.dict(t,e);break;case"map":vr.dictMap(t,e);break;case"array":vr.list(t,e);break;case"set":vr.listSet(t,e);break;case"string":vr.string(t,e);break;case"number":vr.number(t,e);break;case"boolean":vr.number(t,e);break;case"arraybufferview":vr.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":vr.buffer(t,new Uint8Array(e));break}};tE=new Uint8Array([101]),cz=new Uint8Array([100]),dz=new Uint8Array([108]);vr.buffer=function(t,e){t.push(Kl(e.length+":"),e)};vr.string=function(t,e){t.push(Kl(Kl(e).byteLength+":"+e))};vr.number=function(t,e){if(Number.isInteger(e))return t.push(Kl("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,i=e%r<<0,a=n*r+i;t.push(Kl("i"+a+"e")),a!==e&&!vr._floatConversionDetected&&(vr._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())};vr.dict=function(t,e){t.push(cz);let r=0,n,i=Object.keys(e).sort(),a=i.length;for(;r<a;r++)n=i[r],e[n]!=null&&(vr.string(t,n),vr._encode(t,e[n]));t.push(tE)};vr.dictMap=function(t,e){t.push(cz);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?vr._encode(t,n):vr.string(t,String(n)),vr._encode(t,e.get(n)));t.push(tE)};vr.list=function(t,e){let r=0,n=e.length;for(t.push(dz);r<n;r++)e[r]!=null&&vr._encode(t,e[r]);t.push(tE)};vr.listSet=function(t,e){t.push(dz);for(let r of e)r!=null&&vr._encode(t,r);t.push(tE)};Spe=vr,Ape=105,kpe=58,_pe=100,Tpe=108,j6=101;bt.bytes=0;bt.position=0;bt.data=null;bt.encoding=null;bt.next=function(){switch(bt.data[bt.position]){case _pe:return bt.dictionary();case Tpe:return bt.list();case Ape:return bt.integer();default:return bt.buffer()}};bt.find=function(t){let e=bt.position,r=bt.data.length,n=bt.data;for(;e<r;){if(n[e]===t)return e;e++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(t)+'" [0x'+t.toString(16)+"]")};bt.dictionary=function(){bt.position++;let t={};for(;bt.data[bt.position]!==j6;){let e=bt.buffer(),r=oz(e);r.includes("\uFFFD")&&(r=vpe(e)),t[r]=bt.next()}return bt.position++,t};bt.list=function(){bt.position++;let t=[];for(;bt.data[bt.position]!==j6;)t.push(bt.next());return bt.position++,t};bt.integer=function(){let t=bt.find(j6),e=lz(bt.data,bt.position+1,t);return bt.position+=t+1-bt.position,e};bt.buffer=function(){let t=bt.find(kpe),e=lz(bt.data,bt.position,t),r=++t+e;return bt.position=r,bt.encoding?oz(bt.data.slice(t,r)):bt.data.slice(t,r)};Ipe=bt;uz=rE,Ope=uz,fz={encode:Spe,decode:Ipe,byteLength:uz,encodingLength:Ope},jpe=/^(\d{1,3}\.){3,3}\d{1,3}$/,Mpe=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,Ad={name:"v4",size:4,isFormat:t=>jpe.test(t),encode(t,e,r){r=~~r,e=e||new Uint8Array(r+4);let n=t.length,i=0;for(let a=0;a<n;){let s=t.charCodeAt(a++);s===46?(e[r++]=i,i=0):i=i*10+(s-48)}return e[r]=i,e},decode(t,e){return e=~~e,`${t[e++]}.${t[e++]}.${t[e++]}.${t[e]}`}},bf={name:"v6",size:16,isFormat:t=>t.length>0&&Mpe.test(t),encode(t,e,r){r=~~r;let n=r+16,i=-1,a=0,s=0,o=!0,d=!1;e=e||new Uint8Array(r+16);for(let l=0;l<t.length;l++){let c=t.charCodeAt(l);c===58?(o?i!==-1?(r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2):r<n&&(i=r):(d===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=a>>8),r<n-1&&(e[r+1]=a&255),r+=2),a=0,s=0),o=!0,d=!1):c===46?(r<n&&(e[r]=s),r++,s=0,a=0,o=!1,d=!0):(o=!1,c>=97?c-=87:c>=65?c-=55:(c-=48,s=s*10+c),a=(a<<4)+c)}if(o===!1)d===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=a>>8),r<n-1&&(e[r+1]=a&255),r+=2);else if(i===0)r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2;else if(i!==-1){r+=2;for(let l=Math.min(r-1,n-1);l>=i+2;l--)e[l]=e[l-2];e[i]=0,e[i+1]=0,i=r}if(i!==r&&i!==-1)for(r>n-2&&(r=n-2);n>i;)e[--n]=r<n&&r>i?e[--r]:0;else for(;r<n;)e[r++]=0;return e},decode(t,e){e=~~e;let r="";for(let n=0;n<16;n+=2)n!==0&&(r+=":"),r+=(t[e+n]<<8|t[e+n+1]).toString(16);return r.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};Hv.bytes=0;rb.bytes=0;fh=t=>t instanceof Uint8Array;kv={},gz=new Array(255);for(let t=0;t<=15;t+=1){let e=t.toString(16),r=e.toUpperCase();for(let n=0;n<=15;n+=1){let i=n.toString(16),a=i.toUpperCase(),s=t<<4|n,o=`${e}${i}`;gz[s]=o,kv[o]=s,kv[`${r}${i}`]=s,kv[`${e}${a}`]=s,kv[`${r}${a}`]=s}}Hpe=Math.pow(2,24),Vpe=Math.pow(2,16),Wpe=Math.pow(2,8),Ol=(t,e)=>t[e]*Hpe+t[e+1]*Vpe+t[e+2]*Wpe+t[e+3],Ut=(t,e)=>t[e]<<8|t[e+1],jl=(t,e,r)=>(e=+e,t[r+3]=e,e=e>>>8,t[r+2]=e,e=e>>>8,t[r+1]=e,e=e>>>8,t[r]=e,r+4),st=(t,e,r)=>(t[r]=e>>8,t[r+1]=e&255,r+2);Zpe=0,uq=32768,QR=32768,Ype=~QR,wz=32768,Xpe=~wz;Ze=Fr({encode(t,e,r){e||(e=new Uint8Array(Ze.encodingLength(t))),r||(r=0);let n=r,i=t.replace(/^\.|\.$/gm,"");if(i.length){let a=i.split(".");for(let s=0;s<a.length;s++){let o=K6(e,a[s],r+1);e[r]=o,r+=o+1}}return e[r++]=0,Ze.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=[],n=e,i=0,a=0,s=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let o=t[e++];if(a+=s?0:1,o===0)break;if(o&192)if((o&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let d=Ut(t,e-1)-49152;if(d>=n)throw new Error("Cannot decode name (bad pointer)");e=d,n=d,a+=s?0:1,s=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+o>t.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=o+1,i>254)throw new Error("Cannot decode name (name too long)");r.push(rb(t,e,e+o)),e+=o,a+=s?0:o}}return Ze.decode.bytes=a,r.length===0?".":r.join(".")},encodingLength(t){return t==="."||t===".."?1:xf(t.replace(/^\.|\.$/gm,""))+2}}),li=Fr({encode(t,e,r){e||(e=new Uint8Array(li.encodingLength(t))),r||(r=0);let n=K6(e,t,r+1);return e[r]=n,li.encode.bytes=n+1,e},decode(t,e){e||(e=0);let r=t[e],n=rb(t,e+1,e+1+r);return li.decode.bytes=r+1,n},encodingLength(t){return xf(t)+1}}),Ry=Fr({bytes:12,encode(t,e,r){e||(e=new Uint8Array(Ry.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?uq:Zpe;return st(e,t.id||0,r),st(e,n|i,r+2),st(e,t.questions.length,r+4),st(e,t.answers.length,r+6),st(e,t.authorities.length,r+8),st(e,t.additionals.length,r+10),e},decode(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=Ut(t,e+2);return{id:Ut(t,e),type:r&uq?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:qpe(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:Lpe(r&15),questions:new Array(Ut(t,e+4)),answers:new Array(Ut(t,e+6)),authorities:new Array(Ut(t,e+8)),additionals:new Array(Ut(t,e+10))}},encodingLength(){return 12}}),v2=Fr({encode(t,e,r){e||(e=new Uint8Array(v2.encodingLength(t))),r||(r=0);let n=t.length;return st(e,n,r),Vo(t,e,r+2,0,n),v2.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=Ut(t,e),n=t.slice(e+2,e+2+r);return v2.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),b2=Fr({encode(t,e,r){return e||(e=new Uint8Array(b2.encodingLength(t))),r||(r=0),Ze.encode(t,e,r+2),st(e,Ze.encode.bytes,r),b2.encode.bytes=Ze.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Ut(t,e),n=Ze.decode(t,e+2);return b2.decode.bytes=r+2,n},encodingLength(t){return Ze.encodingLength(t)+2}}),P2=Fr({encode(t,e,r){e||(e=new Uint8Array(P2.encodingLength(t))),r||(r=0);let n=r;return r+=2,Ze.encode(t.mname,e,r),r+=Ze.encode.bytes,Ze.encode(t.rname,e,r),r+=Ze.encode.bytes,jl(e,t.serial||0,r),r+=4,jl(e,t.refresh||0,r),r+=4,jl(e,t.retry||0,r),r+=4,jl(e,t.expire||0,r),r+=4,jl(e,t.minimum||0,r),r+=4,st(e,r-n-2,n),P2.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=Ze.decode(t,e),e+=Ze.decode.bytes,n.rname=Ze.decode(t,e),e+=Ze.decode.bytes,n.serial=Ol(t,e),e+=4,n.refresh=Ol(t,e),e+=4,n.retry=Ol(t,e),e+=4,n.expire=Ol(t,e),e+=4,n.minimum=Ol(t,e),e+=4,P2.decode.bytes=e-r,n},encodingLength(t){return 22+Ze.encodingLength(t.mname)+Ze.encodingLength(t.rname)}}),x2=Fr({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let i=0;i<t.length;i++)if(typeof t[i]=="string"&&(t[i]=M6(t[i])),!fh(t[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(x2.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(i){e[r++]=i.length,Vo(i,e,r,0,i.length),r+=i.length}),st(e,r-n-2,n),x2.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=Ut(t,e);e+=2;let i=[];for(;n>0;){let a=t[e++];if(--n,n<a)throw new Error("Buffer overflow");i.push(t.slice(e,e+a)),e+=a,n-=a}return x2.decode.bytes=e-r,i},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=xf(r)+1:e+=r.length+1}),e}}),E2=Fr({encode(t,e,r){e||(e=new Uint8Array(E2.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=M6(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let i=t.length;return Vo(t,e,r,0,i),r+=i,st(e,r-n-2,n),E2.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=Ut(t,e);e+=2;let i=t.slice(e,e+n);return e+=n,E2.decode.bytes=e-r,i},encodingLength(t){return t?(fh(t)?t.length:xf(t))+2:2}}),S2=Fr({encode(t,e,r){e||(e=new Uint8Array(S2.encodingLength(t))),r||(r=0);let n=r;return r+=2,li.encode(t.cpu,e,r),r+=li.encode.bytes,li.encode(t.os,e,r),r+=li.encode.bytes,st(e,r-n-2,n),S2.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=li.decode(t,e),e+=li.decode.bytes,n.os=li.decode(t,e),e+=li.decode.bytes,S2.decode.bytes=e-r,n},encodingLength(t){return li.encodingLength(t.cpu)+li.encodingLength(t.os)+2}}),Ky=Fr({encode(t,e,r){return e||(e=new Uint8Array(Ky.encodingLength(t))),r||(r=0),Ze.encode(t,e,r+2),st(e,Ze.encode.bytes,r),Ky.encode.bytes=Ze.encode.bytes+2,e},decode(t,e){e||(e=0);let r=Ze.decode(t,e+2);return Ky.decode.bytes=Ze.decode.bytes+2,r},encodingLength(t){return Ze.encodingLength(t)+2}}),A2=Fr({encode(t,e,r){e||(e=new Uint8Array(A2.encodingLength(t))),r||(r=0),st(e,t.priority||0,r+2),st(e,t.weight||0,r+4),st(e,t.port||0,r+6),Ze.encode(t.target,e,r+8);let n=Ze.encode.bytes+6;return st(e,n,r),A2.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=Ut(t,e),n={};return n.priority=Ut(t,e+2),n.weight=Ut(t,e+4),n.port=Ut(t,e+6),n.target=Ze.decode(t,e+8),A2.decode.bytes=r+2,n},encodingLength(t){return 8+Ze.encodingLength(t.target)}}),gf=Fr({encode(t,e,r){let n=gf.encodingLength(t);return e||(e=new Uint8Array(gf.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=gf.ISSUER_CRITICAL),st(e,n-2,r),r+=2,e[r]=t.flags||0,r+=1,li.encode(t.tag,e,r),r+=li.encode.bytes,K6(e,t.value,r),r+=xf(t.value),gf.encode.bytes=n,e},decode(t,e){e||(e=0);let r=Ut(t,e);e+=2;let n=e,i={};return i.flags=t[e],e+=1,i.tag=li.decode(t,e),e+=li.decode.bytes,i.value=rb(t,e,n+r),i.issuerCritical=!!(i.flags&gf.ISSUER_CRITICAL),gf.decode.bytes=r+2,i},encodingLength(t){return li.encodingLength(t.tag)+li.encodingLength(t.value)+2}});gf.ISSUER_CRITICAL=128;k2=Fr({encode(t,e,r){e||(e=new Uint8Array(k2.encodingLength(t))),r||(r=0);let n=r;return r+=2,st(e,t.preference||0,r),r+=2,Ze.encode(t.exchange,e,r),r+=Ze.encode.bytes,st(e,r-n-2,n),k2.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=Ut(t,e),e+=2,n.exchange=Ze.decode(t,e),e+=Ze.decode.bytes,k2.decode.bytes=e-r,n},encodingLength(t){return 4+Ze.encodingLength(t.exchange)}}),vz=Fr({encode(t,e,r){return e||(e=new Uint8Array(vz.encodingLength(t))),r||(r=0),st(e,4,r),r+=2,Ad.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,Ad.decode(t,e)},bytes:6}),_2=Fr({encode(t,e,r){return e||(e=new Uint8Array(_2.encodingLength(t))),r||(r=0),st(e,16,r),r+=2,bf.encode(t,e,r),_2.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=bf.decode(t,e);return _2.decode.bytes=18,r},bytes:18}),fq=t=>new Uint8Array(t),$l=Fr({encode(t,e,r){e||(e=new Uint8Array($l.encodingLength(t))),r||(r=0);let n=r,i=dq(t.code);if(st(e,i,r),r+=2,t.data)st(e,t.data.length,r),r+=2,Vo(t.data,e,r),r+=t.data.length;else switch(i){case 8:{let a=t.sourcePrefixLength||0,s=t.family||Kpe(t.ip,fq),o=Npe(t.ip,fq),d=Math.ceil(a/8);st(e,d+4,r),r+=2,st(e,s,r),r+=2,e[r++]=a,e[r++]=t.scopePrefixLength||0,Vo(o,e,r,0,d),r+=d}break;case 11:t.timeout?(st(e,2,r),r+=2,st(e,t.timeout,r),r+=2):(st(e,0,r),r+=2);break;case 12:{let a=t.length||0;st(e,a,r),r+=2,e.fill(0,r,r+a),r+=a}break;case 14:{let a=t.tags.length*2;st(e,a,r),r+=2;for(let s of t.tags)st(e,s,r),r+=2}break;default:throw new Error(`Unknown roption code: ${t.code}`)}return $l.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=Ut(t,e),r.type=zpe(r.code),e+=2;let n=Ut(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=Ut(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let i=new Uint8Array(r.family===1?4:16);Vo(t,i,0,e,e+n-4),r.ip=Upe(i)}break;case 11:n>0&&(r.timeout=Ut(t,e),e+=2);break;case 14:r.tags=[];for(let i=0;i<n;i+=2)r.tags.push(Ut(t,e)),e+=2}return $l.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(dq(t.code)){case 8:{let e=t.sourcePrefixLength||0;return Math.ceil(e/8)+8}case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)}}),wf=Fr({encode(t,e,r){e||(e=new Uint8Array(wf.encodingLength(t))),r||(r=0);let n=r,i=jy(t,$l);return st(e,i,r),r=Cv(t,$l,e,r+2),wf.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],i=Ut(t,e);e+=2;let a=0;for(;i>0;)n[a++]=$l.decode(t,e),e+=$l.decode.bytes,i-=$l.decode.bytes;return wf.decode.bytes=e-r,n},encodingLength(t){return 2+jy(t||[],$l)}}),Sd=Fr({encode(t,e,r){e||(e=new Uint8Array(Sd.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!fh(i))throw new Error("Key must be a Buffer");return r+=2,st(e,t.flags,r),r+=2,e[r]=Sd.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,Vo(i,e,r,0,i.length),r+=i.length,Sd.encode.bytes=r-n,st(e,Sd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=Ut(t,e);if(e+=2,n.flags=Ut(t,e),e+=2,t[e]!==Sd.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t[e],e+=1,n.key=t.slice(e,r+i+2),e+=n.key.length,Sd.decode.bytes=e-r,n},encodingLength(t){return 6+xf(t.key)}});Sd.PROTOCOL_DNSSEC=3;Sd.ZONE_KEY=128;Sd.SECURE_ENTRYPOINT=32768;_v=Fr({encode(t,e,r){e||(e=new Uint8Array(_v.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!fh(i))throw new Error("Signature must be a Buffer");return r+=2,st(e,Gv(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,jl(e,t.originalTTL,r),r+=4,jl(e,t.expiration,r),r+=4,jl(e,t.inception,r),r+=4,st(e,t.keyTag,r),r+=2,Ze.encode(t.signersName,e,r),r+=Ze.encode.bytes,Vo(i,e,r,0,i.length),r+=i.length,_v.encode.bytes=r-n,st(e,_v.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=Ut(t,e);return e+=2,n.typeCovered=nE(Ut(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=Ol(t,e),e+=4,n.expiration=Ol(t,e),e+=4,n.inception=Ol(t,e),e+=4,n.keyTag=Ut(t,e),e+=2,n.signersName=Ze.decode(t,e),e+=Ze.decode.bytes,n.signature=t.slice(e,r+i+2),e+=n.signature.length,_v.decode.bytes=e-r,n},encodingLength(t){return 20+Ze.encodingLength(t.signersName)+xf(t.signature)}}),Tv=Fr({encode(t,e,r){e||(e=new Uint8Array(Tv.encodingLength(t))),r||(r=0);let n=r;return r+=2,Ze.encode(t.mbox||".",e,r),r+=Ze.encode.bytes,Ze.encode(t.txt||".",e,r),r+=Ze.encode.bytes,Tv.encode.bytes=r-n,st(e,Tv.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=Ze.decode(t,e)||".",e+=Ze.decode.bytes,n.txt=Ze.decode(t,e)||".",e+=Ze.decode.bytes,Tv.decode.bytes=e-r,n},encodingLength(t){return 2+Ze.encodingLength(t.mbox||".")+Ze.encodingLength(t.txt||".")}}),Ho=Fr({encode(t,e,r){e||(e=new Uint8Array(Ho.encodingLength(t))),r||(r=0);let n=r,i=[];for(let a=0;a<t.length;a++){let s=Gv(t[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=M6(i[a]);e[r]=a,r+=1,e[r]=s.length,r+=1,Vo(s,e,r,0,s.length),r+=s.length}return Ho.encode.bytes=r-n,e},decode(t,e,r){e||(e=0);let n=e,i=[];for(;e-n<r;){let a=t[e];e+=1;let s=t[e];e+=1;for(let o=0;o<s;o++){let d=t[e+o];for(let l=0;l<8;l++)if(d&1<<7-l){let c=nE(a<<8|o<<3|l);i.push(c)}}e+=s}return Ho.decode.bytes=e-n,i},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let i=Gv(t[n]);e[i>>8]=Math.max(e[i>>8]||0,i&255)}let r=0;for(let n=0;n<e.length;n++)e[n]!==void 0&&(r+=2+Math.ceil((e[n]+1)/8));return r}}),Iv=Fr({encode(t,e,r){e||(e=new Uint8Array(Iv.encodingLength(t))),r||(r=0);let n=r;return r+=2,Ze.encode(t.nextDomain,e,r),r+=Ze.encode.bytes,Ho.encode(t.rrtypes,e,r),r+=Ho.encode.bytes,Iv.encode.bytes=r-n,st(e,Iv.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=Ut(t,e);return e+=2,n.nextDomain=Ze.decode(t,e),e+=Ze.decode.bytes,n.rrtypes=Ho.decode(t,e,i-(e-r)),e+=Ho.decode.bytes,Iv.decode.bytes=e-r,n},encodingLength(t){return 2+Ze.encodingLength(t.nextDomain)+Ho.encodingLength(t.rrtypes)}}),Dv=Fr({encode(t,e,r){e||(e=new Uint8Array(Dv.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!fh(i))throw new Error("salt must be a Buffer");let a=t.nextDomain;if(!fh(a))throw new Error("nextDomain must be a Buffer");return r+=2,e[r]=t.algorithm,r+=1,e[r]=t.flags,r+=1,st(e,t.iterations,r),r+=2,e[r]=i.length,r+=1,Vo(i,e,r,0,i.length),r+=i.length,e[r]=a.length,r+=1,Vo(a,e,r,0,a.length),r+=a.length,Ho.encode(t.rrtypes,e,r),r+=Ho.encode.bytes,Dv.encode.bytes=r-n,st(e,Dv.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=Ut(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=Ut(t,e),e+=2;let a=t[e];e+=1,n.salt=t.slice(e,e+a),e+=a;let s=t[e];return e+=1,n.nextDomain=t.slice(e,e+s),e+=s,n.rrtypes=Ho.decode(t,e,i-(e-r)),e+=Ho.decode.bytes,Dv.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+Ho.encodingLength(t.rrtypes)}}),Rv=Fr({encode(t,e,r){e||(e=new Uint8Array(Rv.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!fh(i))throw new Error("Digest must be a Buffer");return r+=2,st(e,t.keyTag,r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.digestType,r+=1,Vo(i,e,r,0,i.length),r+=i.length,Rv.encode.bytes=r-n,st(e,Rv.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=Ut(t,e);return e+=2,n.keyTag=Ut(t,e),e+=2,n.algorithm=t[e],e+=1,n.digestType=t[e],e+=1,n.digest=t.slice(e,r+i+2),e+=n.digest.length,Rv.decode.bytes=e-r,n},encodingLength(t){return 6+xf(t.digest)}}),Oy=Fr({encode(t,e,r){e||(e=new Uint8Array(Oy.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let i=lq(t.fingerprint),a=e6(t.hash);if(i!==a)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${i} != ${a}`);return Gpe(e,t.fingerprint,r,r+=i),Oy.encode.bytes=r-n,st(e,Oy.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};e+=2,n.algorithm=t[e],e+=1,n.hash=t[e],e+=1;let i=e6(n.hash);return n.fingerprint=Fpe(t,e,e+i),e+=i,Oy.decode.bytes=e-r,n},encodingLength(t){return 4+lq(t.fingerprint)}});Oy.getFingerprintLengthForHashType=e6;Ia=Fr({encode(t,e,r){e||(e=new Uint8Array(Ia.encodingLength(t))),r||(r=0);let n=r;if(Ze.encode(t.name,e,r),r+=Ze.encode.bytes,st(e,Gv(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");st(e,t.udpPayloadSize||4096,r+2),e[r+4]=t.extendedRcode||0,e[r+5]=t.ednsVersion||0,st(e,t.flags||0,r+6),r+=8,wf.encode(t.options||[],e,r),r+=wf.encode.bytes}else{let i=mz(t.class===void 0?"IN":t.class);t.flush&&(i|=QR),st(e,i,r+2),jl(e,t.ttl||0,r+4),r+=8;let a=UR(t.type);a.encode(t.data,e,r),r+=a.encode.bytes}return Ia.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={},n=e;if(r.name=Ze.decode(t,e),e+=Ze.decode.bytes,r.type=nE(Ut(t,e)),r.type==="OPT")r.udpPayloadSize=Ut(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=Ut(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=wf.decode(t,e+8),e+=8+wf.decode.bytes;else{let i=Ut(t,e+2);r.ttl=Ol(t,e+4),r.class=hz(i&Ype),r.flush=!!(i&QR);let a=UR(r.type);r.data=a.decode(t,e+8),e+=8+a.decode.bytes}return Ia.decode.bytes=e-n,r},encodingLength(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return Ze.encodingLength(t.name)+8+UR(t.type).encodingLength(e)}}),Ny=Fr({encode(t,e,r){e||(e=new Uint8Array(Ny.encodingLength(t))),r||(r=0);let n=r;return Ze.encode(t.name,e,r),r+=Ze.encode.bytes,st(e,Gv(t.type),r),r+=2,st(e,mz(t.class===void 0?"IN":t.class),r),r+=2,Ny.encode.bytes=r-n,t},decode(t,e){e||(e=0);let r=e,n={};return n.name=Ze.decode(t,e),e+=Ze.decode.bytes,n.type=nE(Ut(t,e)),e+=2,n.class=hz(Ut(t,e)),e+=2,n.class&wz&&(n.class&=Xpe),Ny.decode.bytes=e-r,n},encodingLength(t){return Ze.encodingLength(t.name)+4}}),Qpe=1024,ts={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(ehe(t))),r||(r=0);let i=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),Ry.encode(t,e,r),r+=Ry.encode.bytes,r=Cv(t.questions,Ny,e,r),r=Cv(t.answers,Ia,e,r),r=Cv(t.authorities,Ia,e,r),r=Cv(t.additionals,Ia,e,r),ts.encode.bytes=r-i,n&&G2.bytes!==e.length?e.slice(0,G2.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=Ry.decode(t,e);return e+=Ry.decode.bytes,e=u2(n.questions,Ny,t,e),e=u2(n.answers,Ia,t,e),e=u2(n.authorities,Ia,t,e),e=u2(n.additionals,Ia,t,e),ts.decode.bytes=e-r,n},encodingLength:function(t){return Ry.encodingLength(t)+jy(t.questions||[],Ny)+jy(t.answers||[],Ia)+jy(t.authorities||[],Ia)+jy(t.additionals||[],Ia)}};ts.encode.bytes=0;ts.decode.bytes=0;z2={encode:function(t,e,r){return e=ts.encode(q2(t,"query"),e,r),z2.encode.bytes=ts.encode.bytes,e},decode:function(t,e){let r=ts.decode(t,e);return z2.decode.bytes=ts.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return ts.encodingLength(q2(t,"query"))}};z2.encode.bytes=0;z2.decode.bytes=0;F2={encode:function(t,e,r){return e=ts.encode(q2(t,"response"),e,r),F2.encode.bytes=ts.encode.bytes,e},decode:function(t,e){let r=ts.decode(t,e);return F2.decode.bytes=ts.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return ts.encodingLength(q2(t,"response"))}};F2.encode.bytes=0;F2.decode.bytes=0;G2=ts.encode,t6=ts.decode,ehe=ts.encodingLength;bz.bytes=0;Pz.bytes=0;Ez="dht";ohe=0,pf=7200,T2=";",Fs=",",kz={Ed25519:0,ES256K:1,ES256:2,"P-256":2,secp256k1:1,secp256r1:2,X25519:3},_z={0:"EdDSA",1:"ES256K",2:"ES256",3:"ECDH-ES+A256KW"};hq=j.DID_DHT_GATEWAY_URI||"https://enbox-did-dht.fly.dev",Iz=class r6 extends eb{static async create({keyManager:e=new Ec,options:r={}}={}){if(r.verificationMethods?.some(c=>!(c.algorithm in kz)))throw new Error("One or more verification method algorithms are not supported");let n=r.verificationMethods?.filter(c=>"id"in c).map(c=>c.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(r.services?.some(c=>!c.id||!c.type||!c.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 My.identityKeyToIdentifier({identityKey:a}),o={id:s,...r.alsoKnownAs&&{alsoKnownAs:r.alsoKnownAs},...r.controllers&&{controller:r.controllers}},d=[...r.verificationMethods??[]];d?.some(c=>c.id?.split("#").pop()==="0")||d.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let c of d){let u=c.id&&c.id.split("#").pop()==="0"?i:await e.generateKey({algorithm:c.algorithm}),f=await e.getPublicKey({keyUri:u}),h=c.id??f.kid??await Ar({jwk:f});h=`${s}#${Gs(h)}`,o.verificationMethod??=[],o.verificationMethod.push({id:h,type:"JsonWebKey",controller:c.controller??s,publicKeyJwk:f});for(let p of c.purposes??[])o[p]??=[],o[p].push(h)}r.services?.forEach(c=>{o.service??=[],c.id=`${s}#${c.id.split("#").pop()}`,o.service.push(c)});let l=new bs({uri:s,document:o,metadata:{published:!1,...r.types&&{types:r.types}},keyManager:e});if(r.publish??!0){let c=await r6.publish({did:l,gatewayUri:r.gatewayUri});l.metadata=c.didDocumentMetadata}return l}static async import({portableDid:e,keyManager:r=new Ec}){if(Fn.parse(e.uri)?.method!==r6.methodName)throw new rt("methodNotSupported","Method not supported");let n=await bs.import({portableDid:e,keyManager:r});if(!n.document.verificationMethod?.some(i=>i.id?.split("#").pop()==="0"))throw new rt("invalidDidDocument","DID document must contain an Identity Key");return n}static async getSigningMethod({didDocument:e,methodId:r="#0"}){let n=Fn.parse(e.id);if(n&&n.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(a=>Gs(a.id)===(Gs(r)??Gs(e.assertionMethod?.[0])));if(!(i&&i.publicKeyJwk))throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async publish({did:e,gatewayUri:r=hq}){return await mq.put({did:e,gatewayUri:r})}static async resolve(e,r={}){let n=r?.gatewayUri??hq;try{await My.identifierToIdentityKey({didUri:e});let{didDocument:i,didDocumentMetadata:a}=await mq.get({didUri:e,gatewayUri:n});return{...Ai,didDocument:i,didDocumentMetadata:a}}catch(i){if(!(i instanceof rt))throw new Error(i);return{...Ai,didResolutionMetadata:{error:i.code,...i.message&&{errorMessage:i.message}}}}}};Iz.methodName="dht";po=Iz,mq=class Bv{static async get({didUri:e,gatewayUri:r}){let n=My.identifierToIdentityKeyBytes({didUri:e}),i=await Bv.pkarrGet({gatewayUri:r,publicKeyBytes:n}),a=await My.parseBep44GetMessage({bep44Message:i}),s=await Bv.fromDnsPacket({didUri:e,dnsPacket:a});return s.didDocumentMetadata.versionId=i.seq.toString(),s}static async put({did:e,gatewayUri:r}){let n=await Bv.toDnsPacket({didDocument:e.document,didMetadata:e.metadata,authoritativeGatewayUris:[r]}),i=await My.createBep44PutMessage({dnsPacket:n,publicKeyBytes:My.identifierToIdentityKeyBytes({didUri:e.uri}),signer:await e.getSigner({methodId:"0"})}),a=await Bv.pkarrPut({gatewayUri:r,bep44Message:i});return{didDocument:e.document,didDocumentMetadata:{...e.metadata,published:a,versionId:i.seq.toString()},didRegistrationMetadata:{}}}static async pkarrGet(e){return the(e)}static async pkarrPut(e){return rhe(e)}static async fromDnsPacket(e){return ahe(e)}static async toDnsPacket(e){return che(e)}static getUniqueDidSuffix(e){return e.split(":")[2]}},My=class{static async createBep44PutMessage(t){return nhe(t)}static async identifierToIdentityKey(t){return Sz(t)}static identifierToIdentityKeyBytes(t){return N6(t)}static async identityKeyToIdentifier(t){return she(t)}static keyConverter(t){return U6(t)}static async parseBep44GetMessage(t){return ihe(t)}static parseTxtDataToObject(t){return $v(t)}static parseTxtDataToString(t){return Vv(t)}static async validatePreviousDidProof(t){return Az(t)}static chunkDataIfNeeded(t){return Tz(t)}},Ln={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"},qn=class extends Error{constructor(t,e){super(`${t}: ${e}`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}},sUe=new Uint8Array(0),dhe=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},lhe=class{constructor(t,e,r){this.name=t,this.prefix=e,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},uhe=class{constructor(t,e,r){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Dz(this,t)}},fhe=class{constructor(t){this.decoders=t}or(t){return Dz(this,t)}decode(t){let e=t[0],r=this.decoders[e];if(r)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Dz=(t,e)=>new fhe({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),phe=class{constructor(t,e,r,n){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=n,this.encoder=new lhe(t,e,r),this.decoder=new uhe(t,e,n)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},hhe=({name:t,prefix:e,encode:r,decode:n})=>new phe(t,e,r,n),mhe=(t,e,r,n)=>{let i={};for(let c=0;c<e.length;++c)i[e[c]]=c;let a=t.length;for(;t[a-1]==="=";)--a;let s=new Uint8Array(a*r/8|0),o=0,d=0,l=0;for(let c=0;c<a;++c){let u=i[t[c]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);d=d<<r|u,o+=r,o>=8&&(o-=8,s[l++]=255&d>>o)}if(o>=r||255&d<<8-o)throw new SyntaxError("Unexpected end of data");return s},yhe=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,a="",s=0,o=0;for(let d=0;d<t.length;++d)for(o=o<<8|t[d],s+=8;s>r;)s-=r,a+=e[i&o>>s];if(s&&(a+=e[i&o<<r-s]),n)for(;a.length*r&7;)a+="=";return a},iE=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>hhe({prefix:e,name:t,encode(i){return yhe(i,n,r)},decode(i){return mhe(i,n,r,t)}}),oUe=iE({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),aUe=iE({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),yq=iE({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),cUe=iE({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),zy=class I2{static encode(e){return yq.baseEncode(e)}static decodeAsBytes(e,r){if(!I2.isBase64UrlString(e))throw new qn(Ln.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return yq.baseDecode(e)}static decodeAsString(e,r){let n=I2.decodeAsBytes(e,r);return I2.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)}},ghe=ph(yde(),1);(function(t){t.Public="public",t.Private="private"})(n6||(n6={}));Ed=n6,zo=class{static validateEs256kOperationKey(t,e){let r=new Set(["kty","crv","x","y"]);e===Ed.Private&&r.add("d");for(let n in t)if(!r.has(n))throw new qn(Ln.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${n}'.`);if(t.crv!=="secp256k1")throw new qn(Ln.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${t.crv}.'`);if(t.kty!=="EC")throw new qn(Ln.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${t.kty}.'`);if(t.x.length!==43)throw new qn(Ln.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(t.y.length!==43)throw new qn(Ln.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(e===Ed.Private&&(t.d===void 0||t.d.length!==43))throw new qn(Ln.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(t){if(t.length>50)throw new qn(Ln.IdTooLong,`Key ID length ${t.length} exceed max allowed length of 50.`);if(!zy.isBase64UrlString(t))throw new qn(Ln.IdNotUsingBase64UrlCharacterSet,`Key ID '${t}' is not a Base64URL string.`)}static validatePublicKeyPurposes(t){if(t===void 0)return;let e=new Set;for(let r of t){if(e.has(r))throw new qn(Ln.PublicKeyPurposeDuplicated,`Public key purpose '${r}' already specified.`);e.add(r)}}},L6=class{};L6.hashAlgorithmInMultihashCode=18;L6.maxCanonicalizedDeltaSizeInBytes=1e3;xc=L6,whe=ph(gde(),1),Wv=class i6{static canonicalizeAsBytes(e){let r=i6.removeAllUndefinedProperties(e),n=whe.default(r);return zy.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let r in e)typeof e[r]=="object"?i6.removeAllUndefinedProperties(e[r]):e[r]===void 0&&delete e[r];return e}},vhe=Rz,gq=128,bhe=127,Phe=~bhe,xhe=Math.pow(2,31);Ehe=s6,She=128,wq=127;Ahe=Math.pow(2,7),khe=Math.pow(2,14),_he=Math.pow(2,21),The=Math.pow(2,28),Ihe=Math.pow(2,35),Dhe=Math.pow(2,42),Rhe=Math.pow(2,49),Che=Math.pow(2,56),$he=Math.pow(2,63),Bhe=function(t){return t<Ahe?1:t<khe?2:t<_he?3:t<The?4:t<Ihe?5:t<Dhe?6:t<Rhe?7:t<Che?8:t<$he?9:10},Ohe={encode:vhe,decode:Ehe,encodingLength:Bhe},jhe=Ohe,H2=jhe,vq=(t,e=0)=>[H2.decode(t,e),H2.decode.bytes],bq=(t,e,r=0)=>(H2.encode(t,e,r),e),Pq=t=>H2.encodingLength(t),xq=(t,e)=>{let r=e.byteLength,n=Pq(t),i=n+Pq(r),a=new Uint8Array(i+r);return bq(t,a,0),bq(r,a,n),a.set(e,i),new Cz(t,r,e,a)},Mhe=t=>{let e=dhe(t),[r,n]=vq(e),[i,a]=vq(e.subarray(n)),s=e.subarray(n+a);if(s.byteLength!==i)throw new Error("Incorrect length");return new Cz(r,i,s,e)},Cz=class{constructor(t,e,r,n){this.code=t,this.size=e,this.digest=r,this.bytes=n}},$z=({name:t,code:e,encode:r})=>new Khe(t,e,r),Khe=class{constructor(t,e,r){this.name=t,this.code=e,this.encode=r}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?xq(this.code,e):e.then(r=>xq(this.code,r))}else throw Error("Unknown type, must be binary type")}},Bz=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Eq=$z({name:"sha2-256",code:18,encode:Bz("SHA-256")}),dUe=$z({name:"sha2-512",code:19,encode:Bz("SHA-512")}),Pv=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Go=class Ov{static hash(e,r){return Pv(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield Eq.digest(e)).bytes;break;default:throw new qn(Ln.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return Pv(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield Eq.encode(e);break;default:throw new qn(Ln.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return Pv(this,void 0,void 0,function*(){let n=Wv.canonicalizeAsBytes(e);return yield Ov.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return Pv(this,void 0,void 0,function*(){let n=Wv.canonicalizeAsBytes(e),i=yield Ov.hashAsNonMultihashBytes(n,r);return yield Ov.hashThenEncode(i,r)})}static hashThenEncode(e,r){return Pv(this,void 0,void 0,function*(){let n=yield Ov.hash(e,r);return zy.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,i=zy.decodeAsBytes(e,r);try{n=Mhe(i)}catch{throw new qn(Ln.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let a=xc.hashAlgorithmInMultihashCode;if(a!==n.code)throw new qn(Ln.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${a} or change IonSdkConfig to desired hashing algorithm.`)}};(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(o6||(o6={}));f2=o6;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})(a6||(a6={}));Iy=a6,p2=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Oz=class _a{static createCreateRequest(e){return p2(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,a=e.document.services;zo.validateEs256kOperationKey(r,Ed.Public),zo.validateEs256kOperationKey(n,Ed.Public),_a.validateDidDocumentKeys(i),_a.validateServices(a);let s=xc.hashAlgorithmInMultihashCode,o=[{action:Iy.Replace,document:e.document}],d={updateCommitment:yield Go.canonicalizeThenDoubleHashThenEncode(n,s),patches:o};_a.validateDeltaSize(d);let l={deltaHash:yield Go.canonicalizeThenHashThenEncode(d,s),recoveryCommitment:yield Go.canonicalizeThenDoubleHashThenEncode(r,s)};return{type:f2.Create,suffixData:l,delta:d}})}static createDeactivateRequest(e){return p2(this,void 0,void 0,function*(){_a.validateDidSuffix(e.didSuffix),zo.validateEs256kOperationKey(e.recoveryPublicKey,Ed.Public);let r=xc.hashAlgorithmInMultihashCode,n=yield Go.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},a=yield e.signer.sign({alg:"ES256K"},i);return{type:f2.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:a}})}static createRecoverRequest(e){return p2(this,void 0,void 0,function*(){_a.validateDidSuffix(e.didSuffix),zo.validateEs256kOperationKey(e.recoveryPublicKey,Ed.Public),zo.validateEs256kOperationKey(e.nextRecoveryPublicKey,Ed.Public),zo.validateEs256kOperationKey(e.nextUpdatePublicKey,Ed.Public),_a.validateDidDocumentKeys(e.document.publicKeys),_a.validateServices(e.document.services);let r=xc.hashAlgorithmInMultihashCode,n=yield Go.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i=[{action:Iy.Replace,document:e.document}],a=yield Go.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),s={patches:i,updateCommitment:a},o=yield Go.canonicalizeThenHashThenEncode(s,r),d={recoveryCommitment:yield Go.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,r),recoveryKey:e.recoveryPublicKey,deltaHash:o},l=yield e.signer.sign({alg:"ES256K"},d);return{type:f2.Recover,didSuffix:e.didSuffix,revealValue:n,delta:s,signedData:l}})}static createUpdateRequest(e){return p2(this,void 0,void 0,function*(){if(_a.validateDidSuffix(e.didSuffix),zo.validateEs256kOperationKey(e.updatePublicKey,Ed.Public),zo.validateEs256kOperationKey(e.nextUpdatePublicKey,Ed.Public),_a.validateServices(e.servicesToAdd),_a.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let p of e.idsOfServicesToRemove)zo.validateId(p);if(e.idsOfPublicKeysToRemove!==void 0)for(let p of e.idsOfPublicKeysToRemove)zo.validateId(p);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let p={action:Iy.AddServices,services:n};r.push(p)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let p={action:Iy.RemoveServices,ids:i};r.push(p)}let a=e.publicKeysToAdd;if(a!==void 0&&a.length>0){let p={action:Iy.AddPublicKeys,publicKeys:a};r.push(p)}let s=e.idsOfPublicKeysToRemove;if(s!==void 0&&s.length>0){let p={action:Iy.RemovePublicKeys,ids:s};r.push(p)}let o=xc.hashAlgorithmInMultihashCode,d=yield Go.canonicalizeThenHashThenEncode(e.updatePublicKey,o),l=yield Go.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,o),c={patches:r,updateCommitment:l},u=yield Go.canonicalizeThenHashThenEncode(c,o),f={updateKey:e.updatePublicKey,deltaHash:u},h=yield e.signer.sign({alg:"ES256K"},f);return{type:f2.Update,didSuffix:e.didSuffix,revealValue:d,delta:c,signedData:h}})}static validateDidSuffix(e){Go.validateEncodedHashComputedUsingSupportedHashAlgorithm(e,"didSuffix")}static validateDidDocumentKeys(e){if(e===void 0)return;let r=new Set;for(let n of e){if(Array.isArray(n.publicKeyJwk))throw new qn(Ln.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(zo.validateId(n.id),r.has(n.id))throw new qn(Ln.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);r.add(n.id),zo.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let r=new Set;for(let n of e){if(_a.validateService(n),r.has(n.id))throw new qn(Ln.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){zo.validateId(e.id);let r=30;if(e.type.length>r){let n=`Service endpoint type length ${e.type.length} exceeds max allowed length of ${r}.`;throw new qn(Ln.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new qn(Ln.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&ghe.parse(e.serviceEndpoint).error!==void 0)throw new qn(Ln.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let r=Wv.canonicalizeAsBytes(e);if(r.length>xc.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${xc.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new qn(Ln.DeltaExceedsMaximumSize,n)}}},Sq=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Nhe=class jz{static createLongFormDid(e){return Sq(this,void 0,void 0,function*(){let r=yield Oz.createCreateRequest(e),n=yield jz.computeDidUniqueSuffix(r.suffixData),i;xc.network===void 0||xc.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${xc.network}:${n}`;let a={suffixData:r.suffixData,delta:r.delta},s=Wv.canonicalizeAsBytes(a),o=zy.encode(s);return`${i}:${o}`})}static computeDidUniqueSuffix(e){return Sq(this,void 0,void 0,function*(){let r=Wv.canonicalizeAsBytes(e),n=yield Go.hash(r,xc.hashAlgorithmInMultihashCode);return zy.encode(n)})}},Yi=2n**255n-19n,D2=2n**252n+27742317777372353535851937790883648493n,c6=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,d6=0x6666666666666666666666666666666666666666666666666666666666666658n,h2={a:-1n,d:37095705934669439343138083508754565189542113879843219016388785533085940283555n,p:Yi,n:D2,h:8,Gx:c6,Gy:d6},uo=(t="")=>{throw new Error(t)},Mz=t=>typeof t=="string",q6=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?uo("Uint8Array expected"):t,Fy=t=>new Uint8Array(t),Uhe=(t,e)=>q6(Mz(t)?F6(t):Fy(t),e),lt=(t,e=Yi)=>{let r=t%e;return r>=0n?r:e+r},Aq=t=>t instanceof Gy?t:uo("Point expected"),Gy=class Cy{constructor(e,r,n,i){this.ex=e,this.ey=r,this.ez=n,this.et=i}static fromAffine(e){return new Cy(e.x,e.y,1n,lt(e.x*e.y))}static fromHex(e,r=!0){let{d:n}=h2;e=Uhe(e,32);let i=e.slice();i[31]=e[31]&-129;let a=qhe(i);a===0n||(r&&!(0n<a&&a<Yi)&&uo("bad y coord 1"),!r&&!(0n<a&&a<2n**256n)&&uo("bad y coord 2"));let s=lt(a*a),o=lt(s-1n),d=lt(n*s+1n),{isValid:l,value:c}=Fhe(o,d);l||uo("bad y coordinate 3");let u=(c&1n)===1n;return(e[31]&128)!==0!==u&&(c=lt(-c)),new Cy(c,a,1n,lt(c*a))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){let{ex:r,ey:n,ez:i}=this,{ex:a,ey:s,ez:o}=Aq(e),d=lt(r*o),l=lt(a*i),c=lt(n*o),u=lt(s*i);return d===l&&c===u}is0(){return this.equals(R2)}negate(){return new Cy(lt(-this.ex),this.ey,this.ez,lt(-this.et))}double(){let{ex:e,ey:r,ez:n}=this,{a:i}=h2,a=lt(e*e),s=lt(r*r),o=lt(2n*lt(n*n)),d=lt(i*a),l=e+r,c=lt(lt(l*l)-a-s),u=d+s,f=u-o,h=d-s,p=lt(c*f),m=lt(u*h),y=lt(c*h),b=lt(f*u);return new Cy(p,m,b,y)}add(e){let{ex:r,ey:n,ez:i,et:a}=this,{ex:s,ey:o,ez:d,et:l}=Aq(e),{a:c,d:u}=h2,f=lt(r*s),h=lt(n*o),p=lt(a*u*l),m=lt(i*d),y=lt((r+n)*(s+o)-f-h),b=lt(m-p),w=lt(m+p),S=lt(h-c*f),k=lt(y*b),T=lt(w*S),D=lt(y*S),K=lt(b*w);return new Cy(k,T,K,D)}mul(e,r=!0){if(e===0n)return r===!0?uo("cannot multiply by 0"):R2;if(typeof e=="bigint"&&0n<e&&e<D2||uo("invalid scalar, must be < L"),!r&&this.is0()||e===1n)return this;if(this.equals(V2))return Vhe(e).p;let n=R2,i=V2;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):r&&(i=i.add(a));return n}multiply(e){return this.mul(e)}clearCofactor(){return this.mul(BigInt(h2.h),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let e=this.mul(D2/2n,!1).double();return D2%2n&&(e=e.add(this)),e.is0()}toAffine(){let{ex:e,ey:r,ez:n}=this;if(this.is0())return{x:0n,y:0n};let i=Nz(n);return lt(n*i)!==1n&&uo("invalid inverse"),{x:lt(e*i),y:lt(r*i)}}toRawBytes(){let{x:e,y:r}=this.toAffine(),n=Lhe(r);return n[31]|=e&1n?128:0,n}toHex(){return z6(this.toRawBytes())}};Gy.BASE=new Gy(c6,d6,1n,lt(c6*d6));Gy.ZERO=new Gy(0n,1n,1n,0n);({BASE:V2,ZERO:R2}=Gy),Kz=(t,e)=>t.toString(16).padStart(e,"0"),z6=t=>Array.from(t).map(e=>Kz(e,2)).join(""),F6=t=>{let e=t.length;(!Mz(t)||e%2)&&uo("hex invalid 1");let r=Fy(e/2);for(let n=0;n<r.length;n++){let i=n*2,a=t.slice(i,i+2),s=Number.parseInt(a,16);(Number.isNaN(s)||s<0)&&uo("hex invalid 2"),r[n]=s}return r},Lhe=t=>F6(Kz(t,32*2)).reverse(),qhe=t=>BigInt("0x"+z6(Fy(q6(t)).reverse())),_q=(...t)=>{let e=Fy(t.reduce((n,i)=>n+q6(i).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},Nz=(t,e=Yi)=>{(t===0n||e<=0n)&&uo("no inverse n="+t+" mod="+e);let r=lt(t,e),n=e,i=0n,a=1n,s=1n,o=0n;for(;r!==0n;){let d=n/r,l=n%r,c=i-s*d,u=a-o*d;n=r,r=l,i=s,a=o,s=c,o=u}return n===1n?lt(i,e):uo("no inverse")},bd=(t,e)=>{let r=t;for(;e-- >0n;)r*=r,r%=Yi;return r},zhe=t=>{let e=t*t%Yi*t%Yi,r=bd(e,2n)*e%Yi,n=bd(r,1n)*t%Yi,i=bd(n,5n)*n%Yi,a=bd(i,10n)*i%Yi,s=bd(a,20n)*a%Yi,o=bd(s,40n)*s%Yi,d=bd(o,80n)*o%Yi,l=bd(d,80n)*o%Yi,c=bd(l,10n)*i%Yi;return{pow_p_5_8:bd(c,2n)*t%Yi,b2:e}},Tq=19681161376707505956807079304988542015446066515923890162744021073123829784752n,Fhe=(t,e)=>{let r=lt(e*e*e),n=lt(r*r*e),i=zhe(t*n).pow_p_5_8,a=lt(t*r*i),s=lt(e*a*a),o=a,d=lt(a*Tq),l=s===t,c=s===lt(-t),u=s===lt(-t*Tq);return l&&(a=o),(c||u)&&(a=d),(lt(a)&1n)===1n&&(a=lt(-a)),{isValid:l||c,value:a}},Iq=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0,Ghe={bytesToHex:z6,hexToBytes:F6,concatBytes:_q,mod:lt,invert:Nz,randomBytes:t=>{let e=Iq();return e||uo("crypto.getRandomValues must be defined"),e.getRandomValues(Fy(t))},sha512Async:async(...t)=>{let e=Iq();e||uo("crypto.subtle or etc.sha512Async must be defined");let r=_q(...t);return Fy(await e.subtle.digest("SHA-512",r.buffer))},sha512Sync:void 0};Object.defineProperties(Ghe,{sha512Sync:{configurable:!1,get(){return LR},set(t){LR||(LR=t)}}});nh=8,Hhe=()=>{let t=[],e=256/nh+1,r=V2,n=r;for(let i=0;i<e;i++){n=r,t.push(n);for(let a=1;a<2**(nh-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},Vhe=t=>{let e=kq||(kq=Hhe()),r=(c,u)=>{let f=u.negate();return c?f:u},n=R2,i=V2,a=1+256/nh,s=2**(nh-1),o=BigInt(2**nh-1),d=2**nh,l=BigInt(nh);for(let c=0;c<a;c++){let u=c*s,f=Number(t&o);t>>=l,f>s&&(f-=d,t+=1n);let h=u,p=u+Math.abs(f)-1,m=c%2!==0,y=f<0;f===0?i=i.add(r(m,e[h])):n=n.add(r(y,e[p]))}return{p:n,f:i}},G6=2n**256n,dh=G6-0x1000003d1n,H6=G6-0x14551231950b75fc4402da1732fc9bebfn,Uz=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Lz=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,qz={p:dh,n:H6,a:0n,b:7n,Gx:Uz,Gy:Lz},Uy=32,Dq=t=>et(et(t*t)*t+qz.b),Si=(t="")=>{throw new Error(t)},sE=t=>typeof t=="bigint",zz=t=>typeof t=="string",qR=t=>sE(t)&&0n<t&&t<dh,Fz=t=>sE(t)&&0n<t&&t<H6,Gz=(t,e)=>!(t instanceof Uint8Array)||typeof e=="number"&&e>0&&t.length!==e?Si("Uint8Array expected"):t,Jv=t=>new Uint8Array(t),V6=(t,e)=>Gz(zz(t)?oE(t):Jv(t),e),et=(t,e=dh)=>{let r=t%e;return r>=0n?r:e+r},Rq=t=>t instanceof Hy?t:Si("Point expected"),Hy=class $y{constructor(e,r,n){this.px=e,this.py=r,this.pz=n}static fromAffine(e){return new $y(e.x,e.y,1n)}static fromHex(e){e=V6(e);let r,n=e[0],i=e.subarray(1),a=$q(i,0,Uy),s=e.length;if(s===33&&[2,3].includes(n)){qR(a)||Si("Point hex invalid: x not FE");let o=Whe(Dq(a)),d=(o&1n)===1n;(n&1)===1!==d&&(o=et(-o)),r=new $y(a,o,1n)}return s===65&&n===4&&(r=new $y(a,$q(i,Uy,2*Uy),1n)),r?r.ok():Si("Point is not on curve")}static fromPrivateKey(e){return Nv.mul(Jhe(e))}get x(){return this.aff().x}get y(){return this.aff().y}equals(e){let{px:r,py:n,pz:i}=this,{px:a,py:s,pz:o}=Rq(e),d=et(r*o),l=et(a*i),c=et(n*o),u=et(s*i);return d===l&&c===u}negate(){return new $y(this.px,et(-this.py),this.pz)}double(){return this.add(this)}add(e){let{px:r,py:n,pz:i}=this,{px:a,py:s,pz:o}=Rq(e),{a:d,b:l}=qz,c=0n,u=0n,f=0n,h=et(l*3n),p=et(r*a),m=et(n*s),y=et(i*o),b=et(r+n),w=et(a+s);b=et(b*w),w=et(p+m),b=et(b-w),w=et(r+i);let S=et(a+o);return w=et(w*S),S=et(p+y),w=et(w-S),S=et(n+i),c=et(s+o),S=et(S*c),c=et(m+y),S=et(S-c),f=et(d*w),c=et(h*y),f=et(c+f),c=et(m-f),f=et(m+f),u=et(c*f),m=et(p+p),m=et(m+p),y=et(d*y),w=et(h*w),m=et(m+y),y=et(p-y),y=et(d*y),w=et(w+y),p=et(m*w),u=et(u+p),p=et(S*w),c=et(b*c),c=et(c-p),p=et(b*m),f=et(S*f),f=et(f+p),new $y(c,u,f)}mul(e,r=!0){if(!r&&e===0n)return C2;if(Fz(e)||Si("invalid scalar"),this.equals(Nv))return Qhe(e).p;let n=C2,i=Nv;for(let a=this;e>0n;a=a.double(),e>>=1n)e&1n?n=n.add(a):r&&(i=i.add(a));return n}mulAddQUns(e,r,n){return this.mul(r,!1).add(e.mul(n,!1)).ok()}toAffine(){let{px:e,py:r,pz:n}=this;if(this.equals(C2))return{x:0n,y:0n};if(n===1n)return{x:e,y:r};let i=Vz(n);return et(n*i)!==1n&&Si("invalid inverse"),{x:et(e*i),y:et(r*i)}}assertValidity(){let{x:e,y:r}=this.aff();return(!qR(e)||!qR(r))&&Si("Point invalid: x or y"),et(r*r)===Dq(e)?this:Si("Point invalid: not on curve")}multiply(e){return this.mul(e)}aff(){return this.toAffine()}ok(){return this.assertValidity()}toHex(e=!0){let{x:r,y:n}=this.aff();return(e?(n&1n)===0n?"02":"03":"04")+Bq(r)+(e?"":Bq(n))}toRawBytes(e=!0){return oE(this.toHex(e))}};Hy.BASE=new Hy(Uz,Lz,1n);Hy.ZERO=new Hy(0n,1n,0n);({BASE:Nv,ZERO:C2}=Hy),Hz=(t,e)=>t.toString(16).padStart(e,"0"),W6=t=>Array.from(t).map(e=>Hz(e,2)).join(""),oE=t=>{let e=t.length;(!zz(t)||e%2)&&Si("hex invalid 1");let r=Jv(e/2);for(let n=0;n<r.length;n++){let i=n*2,a=t.slice(i,i+2),s=Number.parseInt(a,16);(Number.isNaN(s)||s<0)&&Si("hex invalid 2"),r[n]=s}return r},aE=t=>BigInt("0x"+(W6(t)||"0")),$q=(t,e,r)=>aE(t.slice(e,r)),J6=t=>sE(t)&&t>=0n&&t<G6?oE(Hz(t,2*Uy)):Si("bigint expected"),Bq=t=>W6(J6(t)),Oq=(...t)=>{let e=Jv(t.reduce((n,i)=>n+Gz(i).length,0)),r=0;return t.forEach(n=>{e.set(n,r),r+=n.length}),e},Vz=(t,e=dh)=>{(t===0n||e<=0n)&&Si("no inverse n="+t+" mod="+e);let r=et(t,e),n=e,i=0n,a=1n,s=1n,o=0n;for(;r!==0n;){let d=n/r,l=n%r,c=i-s*d,u=a-o*d;n=r,r=l,i=s,a=o,s=c,o=u}return n===1n?et(i,e):Si("no inverse")},Whe=t=>{let e=1n;for(let r=t,n=(dh+1n)/4n;n>0n;n>>=1n)n&1n&&(e=e*r%dh),r=r*r%dh;return et(e*e)===t?e:Si("sqrt invalid")},Jhe=t=>(sE(t)||(t=aE(V6(t,Uy))),Fz(t)?t:Si("private key out of range")),jq=()=>typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;Yhe={hexToBytes:oE,bytesToHex:W6,concatBytes:Oq,bytesToNumberBE:aE,numberToBytesBE:J6,mod:et,invert:Vz,hmacSha256Async:async(t,...e)=>{let r=jq();if(!r)return Si("etc.hmacSha256Async not set");let n=r.subtle,i=await n.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return Jv(await n.sign("HMAC",i,Oq(...e)))},hmacSha256Sync:$2,hashToPrivateKey:Zhe,randomBytes:t=>{let e=jq();return e||Si("crypto.getRandomValues must be defined"),e.getRandomValues(Jv(t))}};Object.defineProperties(Yhe,{hmacSha256Sync:{configurable:!1,get(){return $2},set(t){$2||($2=t)}}});ih=8,Xhe=()=>{let t=[],e=256/ih+1,r=Nv,n=r;for(let i=0;i<e;i++){n=r,t.push(n);for(let a=1;a<2**(ih-1);a++)n=n.add(r),t.push(n);r=n.double()}return t},Qhe=t=>{let e=Cq||(Cq=Xhe()),r=(c,u)=>{let f=u.negate();return c?f:u},n=C2,i=Nv,a=1+256/ih,s=2**(ih-1),o=BigInt(2**ih-1),d=2**ih,l=BigInt(ih);for(let c=0;c<a;c++){let u=c*s,f=Number(t&o);t>>=l,f>s&&(f-=d,t+=1n);let h=u,p=u+Math.abs(f)-1,m=c%2!==0,y=f<0;f===0?i=i.add(r(m,e[h])):n=n.add(r(y,e[p]))}return{p:n,f:i}};(function(t){t.Mainnet="mainnet",t.Testnet="test"})(Mq||(Mq={}));(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(Kq||(Kq={}));xv=class th{static appendPathToUrl({baseUrl:e,path:r}){let n=new URL(e);return n.pathname=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",n.pathname+=r.startsWith("/")?r.substring(1):r,n.toString()}static async computeLongFormDidUri({recoveryKey:e,updateKey:r,services:n,verificationMethods:i}){let a=await th.createIonDocument({services:n,verificationMethods:i}),s=th.normalizeJwk(e),o=th.normalizeJwk(r);return await Nhe.createLongFormDid({document:a,recoveryKey:s,updateKey:o})}static async constructCreateRequest({ionDocument:e,recoveryKey:r,updateKey:n}){return await Oz.createCreateRequest({document:e,recoveryKey:th.normalizeJwk(r),updateKey:th.normalizeJwk(n)})}static async createIonDocument({services:e,verificationMethods:r}){let n=[];for(let a of r){let s=a.id??a.publicKeyJwk.kid??await Ar({jwk:a.publicKeyJwk});s=`${s.split("#").pop()}`;let o={id:s,publicKeyJwk:th.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 r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);return n}},eme=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519",t))(eme||{}),tme={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},Nq="https://ion.tbd.engineering",rme=class jv extends eb{static async create({keyManager:e=new Ec,options:r={}}={}){if(r.verificationMethods?.some(p=>!(p.algorithm in tme)))throw new Error("One or more verification method algorithms are not supported");let n=r.verificationMethods?.filter(p=>"id"in p).map(p=>p.id);if(n&&n.length!==new Set(n).size)throw new Error("One or more verification method IDs are not unique");if(r.services?.some(p=>!p.id||!p.type||!p.serviceEndpoint))throw new Error("One or more services are missing required properties");let i={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},a=[];for(let p of r.verificationMethods??[i]){let m=await e.generateKey({algorithm:p.algorithm}),y=await e.getPublicKey({keyUri:m});a.push({id:p.id,publicKeyJwk:y,purposes:p.purposes??["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let s=await e.generateKey({algorithm:"secp256k1"}),o=await e.getPublicKey({keyUri:s}),d=await e.generateKey({algorithm:"secp256k1"}),l=await e.getPublicKey({keyUri:d}),c=await xv.computeLongFormDidUri({recoveryKey:o,updateKey:l,services:r.services??[],verificationMethods:a}),{didDocument:u,didResolutionMetadata:f}=await jv.resolve(c,{gatewayUri:r.gatewayUri});if(u===null)throw new Error(`Unable to resolve DID during creation: ${f?.error}`);let h=new bs({uri:c,document:u,metadata:{published:!1,canonicalId:c.split(":",3).join(":"),recoveryKey:o,updateKey:l},keyManager:e});if(r.publish??!0){let p=await jv.publish({did:h,gatewayUri:r.gatewayUri});h.metadata=p.didDocumentMetadata}return h}static async getSigningMethod({didDocument:e,methodId:r}){let n=Fn.parse(e.id);if(n&&n.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${n.method}`);let i=e.verificationMethod?.find(a=>a.id===(r??e.assertionMethod?.[0]));if(!(i&&i.publicKeyJwk))throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async import({portableDid:e,keyManager:r=new Ec}){if(Fn.parse(e.uri)?.method!==jv.methodName)throw new rt("methodNotSupported","Method not supported");return await bs.import({portableDid:e,keyManager:r})}static async publish({did:e,gatewayUri:r=Nq}){let n=e.document.verificationMethod?.map(s=>({id:s.id,publicKeyJwk:s.publicKeyJwk,purposes:X7({didDocument:e.document,methodId:s.id})}))??[],i=await xv.createIonDocument({services:e.document.service??[],verificationMethods:n}),a=await xv.constructCreateRequest({ionDocument:i,recoveryKey:e.metadata.recoveryKey,updateKey:e.metadata.updateKey});try{let s=xv.appendPathToUrl({baseUrl:r,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,r={}){let n=Fn.parse(e);if(!n)return{...Ai,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==jv.methodName)return{...Ai,didResolutionMetadata:{error:"methodNotSupported"}};let i=r?.gatewayUri??Nq;try{let a=xv.appendPathToUrl({baseUrl:i,path:`/identifiers/${e}`}),s=await fetch(a,{signal:AbortSignal.timeout(3e4)});if(!s.ok)throw new rt("notFound",`Unable to find DID document for: ${e}`);let{didDocument:o,didDocumentMetadata:d}=await s.json();return{...Ai,...o&&{didDocument:o},didDocumentMetadata:{published:d?.method?.published,...d}}}catch(a){if(!(a instanceof rt))throw new Error(a);return{...Ai,didResolutionMetadata:{error:a.code,...a.message&&{errorMessage:a.message}}}}}};rme.methodName="ion";Wz=class Mv extends eb{static async create({keyManager:e=new Ec,options:r={}}={}){if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=r.algorithm??r.verificationMethods?.[0]?.algorithm??"Ed25519",i=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:i}),s=it.object(a).toBase64Url(),o=`did:${Mv.methodName}:${s}`,d=(await Mv.resolve(o)).didDocument;return new bs({uri:o,document:d,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let r=Fn.parse(e.id);if(r&&r.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.verificationMethod??[];if(!(n&&n.publicKeyJwk))throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return n}static async import({portableDid:e,keyManager:r=new Ec}){if(Fn.parse(e.uri)?.method!==Mv.methodName)throw new rt("methodNotSupported","Method not supported");let n=await bs.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new rt("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){let n=Fn.parse(e),i;try{i=n?it.base64Url(n.id).toObject():void 0}catch{}if(!n||!i)return{...Ai,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==Mv.methodName)return{...Ai,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{...Ai,didDocument:a}}};Wz.methodName="jwk";ho=Wz,nme={Ed25519:"Ed25519",ES256K:"secp256k1",ES256:"secp256r1","P-256":"secp256r1",secp256k1:"secp256k1",secp256r1:"secp256r1"},B2=class By{static async jwkToMulticodec({jwk:e}){let r=[];e.crv&&(r.push(e.crv),e.d?r.push("private"):r.push("public"));let n=r.join(":"),i=By.JWK_TO_MULTICODEC[n];if(i===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${n}'`);return{code:Oa.getCodeFromName({name:i}),name:i}}static keyCompressor(e){let r={"P-256":ws.compressPublicKey,secp256k1:Xi.compressPublicKey}[e];if(!r)throw new rt("invalidPublicKeyType",`Unsupported curve: ${e}`);return r}static keyConverter(e){let r={Ed25519:Qi,"P-256":ws,secp256k1:Xi}[e];if(!r)throw new rt("invalidPublicKeyType",`Unsupported curve: ${e}`);return r}static async multicodecToJwk({code:e,name:r}){if(!(r?!e:e))throw new Error("Either 'name' or 'code' must be defined, but not both.");r=r===void 0?Oa.getNameFromCode({code:e}):r;let n=r,i=By.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 nme))throw new rt("invalidPublicKeyType",`Public key contains an unsupported key type: ${e?.crv??"undefined"}`);let r=await By.keyConverter(e.crv).publicKeyToBytes({publicKey:e});/^(secp256k1|P-256|P-384|P-521)$/.test(e.crv)&&(r=await By.keyCompressor(e.crv)({publicKeyBytes:r}));let{name:n}=await By.jwkToMulticodec({jwk:e});return ez({keyBytes:r,multicodecName:n})}};B2.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv"},B2.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,237:32},B2.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:""}};m2=B2,ime=(t=>(t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t))(ime||{}),Uq={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1"},Jz=class yf extends eb{static async create({keyManager:e=new Ec,options:r={}}={}){if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let n=r.algorithm??r.verificationMethods?.[0]?.algorithm??"Ed25519",i=await e.generateKey({algorithm:n}),a=await e.getPublicKey({keyUri:i}),s=await m2.publicKeyToMultibaseId({publicKey:a}),o=`did:${yf.methodName}:${s}`,d=(await yf.resolve(o,r)).didDocument;return new bs({uri:o,document:d,metadata:{},keyManager:e})}static async getSigningMethod({didDocument:e}){let r=Fn.parse(e.id);if(r&&r.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${r.method}`);let[n]=e.assertionMethod||[],i=e.verificationMethod?.find(a=>a.id===n);if(!(i&&i.publicKeyJwk))throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return i}static async import({portableDid:e,keyManager:r=new Ec}){if(Fn.parse(e.uri)?.method!==yf.methodName)throw new rt("methodNotSupported","Method not supported");let n=await bs.import({portableDid:e,keyManager:r});if(n.document.verificationMethod.length!==1)throw new rt("invalidDidDocument","DID document must contain exactly one verification method");return n}static async resolve(e,r){try{let n=await yf.createDocument({didUri:e,options:r});return{...Ai,didDocument:n}}catch(n){if(!(n instanceof rt))throw new Error(n);return{...Ai,didResolutionMetadata:{error:n.code,...n.message&&{errorMessage:n.message}}}}}static async createDocument({didUri:e,options:r={}}){let{defaultContext:n="https://www.w3.org/ns/did/v1",enableExperimentalPublicKeyTypes:i=!1,publicKeyFormat:a="JsonWebKey2020"}=r,s={id:""},o=Fn.parse(e);if(!o)throw new rt("invalidDid",`Invalid DID URI: ${e}`);let d=o.id;if(o.method!==yf.methodName)throw new rt("methodNotSupported",`Method not supported: ${o.method}`);if(!yf.validateIdentifier(o))throw new rt("invalidDid",`Invalid DID URI: ${e}`);let l=await yf.createSignatureMethod({didUri:e,multibaseValue:d,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 c=[n];return Y7({didDocument:s}).forEach(u=>{let f=Uq[u];c.push(f)}),s["@context"]=c,s}static async createSignatureMethod({didUri:e,multibaseValue:r,options:n}){let{enableExperimentalPublicKeyTypes:i,publicKeyFormat:a}=n,s={id:"",type:"",controller:""},{keyBytes:o,multicodecCode:d,multicodecName:l}=tz({multibaseKeyId:r}),c=o.byteLength,u=m2.MULTICODEC_PUBLIC_KEY_LENGTH[d];if(c!==u)throw new rt("invalidPublicKeyLength",`Expected ${c} bytes. Actual: ${u}`);let f=!1;switch(l){case"secp256k1-pub":f=await Xi.validatePublicKey({publicKeyBytes:o});break;case"ed25519-pub":f=await Qi.validatePublicKey({publicKeyBytes:o});break}if(!f)throw new rt("invalidPublicKey","Invalid public key detected.");s.id=`${e}#${r}`;try{new URL(s.id)}catch{throw new rt("invalidDidUrl","Verification Method ID is not a valid DID URL.")}if(!(a in Uq))throw new rt("unsupportedPublicKeyType",`Unsupported format: ${a}`);if(i===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(a))throw new rt("invalidPublicKeyType",`Specified '${a}' without setting enableExperimentalPublicKeyTypes to true.`);if(s.type=a,s.controller=e,a==="Ed25519VerificationKey2020"&&(s.publicKeyMultibase=r),a==="JsonWebKey2020"){let{crv:h}=await m2.multicodecToJwk({code:d});s.publicKeyJwk=await m2.keyConverter(h).bytesToPublicKey({publicKeyBytes:o})}return s}static validateIdentifier(e){let{method:r,id:n}=e,[i]=e.uri.split(":",1);return i==="did"&&r==="key"&&!0&&zR(n)==="String"&&n.startsWith("z")}};Jz.methodName="key";nb=Jz,sme=3e4;Zz=class O2 extends eb{static async create({keyManager:e=new Ec,options:r}){if(!r.domain)throw new rt("invalidDid","The 'domain' option is required for did:web creation");if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");let n=r.path?`${r.domain}:${r.path}`:r.domain,i=`did:${O2.methodName}:${n}`;if(!Fn.parse(i))throw new rt("invalidDid",`The constructed DID URI is invalid: ${i}`);let a=r.verificationMethods??[{algorithm:r.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 d=a[o],l=await e.generateKey({algorithm:d.algorithm}),c=await e.getPublicKey({keyUri:l}),u=d.id?.split("#").pop()??`key-${o}`,f=`${i}#${u}`;s.verificationMethod??=[],s.verificationMethod.push({id:f,type:"JsonWebKey",controller:d.controller??i,publicKeyJwk:c});for(let h of d.purposes??[])s[h]??=[],s[h].push(f)}return r.services&&(s.service=r.services.map(o=>({...o,id:`${i}#${o.id.split("#").pop()}`}))),new bs({uri:i,document:s,metadata:{published:!1},keyManager:e})}static async getSigningMethod({didDocument:e,methodId:r}){let n=Fn.parse(e.id);if(n&&n.method!==this.methodName)throw new rt("methodNotSupported",`Method not supported: ${n.method}`);let i=Gs(r)??Gs(e.assertionMethod?.[0]),a=i?e.verificationMethod?.find(s=>Gs(s.id)===i):e.verificationMethod?.[0];if(!(a&&a.publicKeyJwk))throw new rt("internalError","A verification method intended for signing could not be determined from the DID Document");return a}static async import({portableDid:e,keyManager:r=new Ec}){if(Fn.parse(e.uri)?.method!==O2.methodName)throw new rt("methodNotSupported","Method not supported");return await bs.import({portableDid:e,keyManager:r})}static async resolve(e,r){let n=Fn.parse(e);if(!n)return{...Ai,didResolutionMetadata:{error:"invalidDid"}};if(n.method!==O2.methodName)return{...Ai,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=new URL(a);if(ome(s.hostname))return{...Ai,didResolutionMetadata:{error:"notFound"}};let o=await fetch(a,{signal:AbortSignal.timeout(sme)});if(!o.ok)throw new Error("HTTP error status code returned");let d=await o.json();return{...Ai,didDocument:d}}catch{return{...Ai,didResolutionMetadata:{error:"notFound"}}}}};Zz.methodName="web";Yz=Zz,ame=ph(Zq(),1),cme=ph(Yq(),1),cE=class{constructor({db:t,location:e="DATA/DID_RESOLVERCACHE",ttl:r="15m"}={}){this.cache=t??new ame.Level(e),this.ttl=(0,cme.default)(r)}open(){return this.cache.open()}async get(t){try{let e=await this.cache.get(t),r=JSON.parse(e);if(Date.now()>=r.ttlMillis){this.cache.nextTick(()=>this.cache.del(t));return}else return r.value}catch(e){if(e.notFound)return;throw e}}set(t,e){let r={ttlMillis:Date.now()+this.ttl,value:e},n=JSON.stringify(r);return this.cache.put(t,n)}delete(t){return this.cache.del(t)}clear(){return this.cache.clear()}close(){return this.cache.close()}},dme=ph(Yq(),1),dE=class{constructor({ttl:t="15m"}={}){this.cache=new vde.default({ttl:(0,dme.default)(t)})}async open(){}async get(t){if(!t)throw new Error("Key cannot be null or undefined");return this.cache.get(t)}async set(t,e){this.cache.set(t,e)}async delete(t){this.cache.delete(t)}async clear(){this.cache.clear()}async close(){}},lme={open(){return Promise.resolve()},get(t){return Promise.resolve(void 0)},set(t,e){return Promise.resolve()},delete(t){return Promise.resolve()},clear(){return Promise.resolve()},close(){return Promise.resolve()}},Zy=class{constructor({cache:t,didResolvers:e}){this.didResolvers=new Map,this.cache=t||lme;for(let r of e)this.didResolvers.set(r.methodName,r)}async open(){await this.cache.open()}async close(){await this.cache.close()}async resolve(t,e){let r=Fn.parse(t);if(!r)return{...Ai,didResolutionMetadata:{error:"invalidDid",errorMessage:`Invalid DID URI: ${t}`}};let n=this.didResolvers.get(r.method);if(!n)return{...Ai,didResolutionMetadata:{error:"methodNotSupported",errorMessage:`Method not supported: ${r.method}`}};let i=await this.cache.get(r.uri);if(i)return i;{let a=await n.resolve(r.uri,e);return a.didResolutionMetadata.error||await this.cache.set(r.uri,a),a}}async dereference(t,e){let r=Fn.parse(t);if(!r)return{dereferencingMetadata:{error:"invalidDidUrl"},contentStream:null,contentMetadata:{}};let{didDocument:n,didResolutionMetadata:i,didDocumentMetadata:a}=await this.resolve(r.uri);if(!n)return{dereferencingMetadata:{error:i.error},contentStream:null,contentMetadata:{}};if(!r.fragment||r.query)return{dereferencingMetadata:{contentType:"application/did+json"},contentStream:n,contentMetadata:a};let{service:s=[],verificationMethod:o=[]}=n,d=new Set([t,r.fragment,`#${r.fragment}`]),l;for(let c of o)if(d.has(c.id)){l=c;break}for(let c of s)if(d.has(c.id)){l=c;break}return l?{dereferencingMetadata:{contentType:"application/did+json"},contentStream:l,contentMetadata:i}:{dereferencingMetadata:{error:"notFound"},contentStream:null,contentMetadata:{}}}};});var Yy,Xz=F(()=>{"use strict";g();_I();kI();wr();Uo();oN();cN();lN();Lo();s9();o9();v9();b9();P9();x9();E9();S9();t2();CR();Jo();lr();Yy=class t{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 Ty({messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,eventLog:this.eventLog}),this.resumableTaskManager=new e2(e.resumableTaskStore,this.storageController),this._coreProtocols=new dy,this._coreProtocols.register(new dt);let r={didResolver:this.didResolver,messageStore:this.messageStore,dataStore:this.dataStore,stateIndex:this.stateIndex,resumableTaskManager:this.resumableTaskManager,coreProtocols:this._coreProtocols,eventLog:this.eventLog};this.methodHandlers={[be.Messages+ge.Read]:new ax(r),[be.Messages+ge.Subscribe]:new lx(r),[be.Messages+ge.Sync]:new fx(r),[be.Protocols+ge.Configure]:new Zx(r),[be.Protocols+ge.Query]:new Xx(r),[be.Records+ge.Count]:new Qx(r),[be.Records+ge.Delete]:new r2(r),[be.Records+ge.Query]:new n2(r),[be.Records+ge.Read]:new i2(r),[be.Records+ge.Subscribe]:new o2(r),[be.Records+ge.Write]:new a2(r)}}static async create(e){e.didResolver||(e.didResolver=new Zy({didResolvers:[po,ho,nb,Yz],cache:new dE}),e.ownsResolver=!0),e.tenantGate??=new ly;let r=new t(e);return await r.open(),r}async open(){this.ownsResolver&&typeof this.didResolver.open=="function"&&await this.didResolver.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(),this.ownsResolver&&typeof this.didResolver.close=="function"&&await this.didResolver.close()}get coreProtocols(){return this._coreProtocols}get storage(){return{messageStore:this.messageStore,stateIndex:this.stateIndex,eventLog:this.eventLog}}async processMessage(e,r,n={}){let i=await this.validateTenant(e)??await this.validateMessageIntegrity(r);if(i!==void 0)return i;let{dataStream:a,subscriptionHandler:s}=n,o=r.descriptor.interface+r.descriptor.method;return await this.methodHandlers[o].handle({tenant:e,message:r,dataStream:a,subscriptionHandler:s})}async validateTenant(e){let r=await this.tenantGate.isActiveTenant(e);if(!r.isActiveTenant)return{status:{code:401,detail:r.detail??`DID ${e} is not an active tenant.`}}}async validateMessageIntegrity(e){let r=e?.descriptor?.interface,n=e?.descriptor?.method;if(r===void 0||n===void 0)return{status:{code:400,detail:`Both interface and method must be present, interface: ${r}, method: ${n}`}};try{we.validateJsonSchema(e)}catch(i){return wt(i,400)}}}});function ume(t){return new Promise((e,r)=>{if(t.aborted){r(t.reason);return}t.addEventListener("abort",()=>{r(t.reason)})})}async function Gn(t,e){return e?Promise.race([t,ume(e)]):t}var lE=F(()=>{"use strict";g()});import{Level as fme}from"level";async function Hs(t,e){return new fme(t,{...e,keyEncoding:"utf8"})}var Ma,Ef=F(()=>{"use strict";g();lE();Ma=class t{config;db;constructor(e,r){this.config={createLevelDatabase:Hs,...e},this.db=r}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,r)=>{let n=()=>{this.db.open().then(e).catch(r)};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,r)=>{let n=()=>{this.db.close().then(e).catch(r)};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 t(this.config,this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding}))}async get(e,r){r?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),r?.signal);try{return await Gn(this.db.get(String(e)),r?.signal)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async has(e,r){return!!await this.get(e,r)}async*keys(e){e?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),e?.signal);for await(let r of this.db.keys())e?.signal?.throwIfAborted(),yield r}async*iterator(e,r){r?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),r?.signal);for await(let n of this.db.iterator(e))r?.signal?.throwIfAborted(),yield n}async put(e,r,n){return n?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),n?.signal),Gn(this.db.put(String(e),r),n?.signal)}async delete(e,r){return r?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),r?.signal),Gn(this.db.del(String(e)),r?.signal)}async isEmpty(e){for await(let r of this.keys(e))return!1;return!0}async clear(){await this.createLevelDatabase(),await this.db.clear(),await this.compactUnderlyingStorage()}async batch(e,r){return r?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),r?.signal),Gn(this.db.batch(e),r?.signal)}createPartitionOperation(e,r){return{...r,sublevel:this.db.sublevel(e,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}async compactUnderlyingStorage(e){e?.signal?.throwIfAborted(),await Gn(this.createLevelDatabase(),e?.signal);let r=this.sublevelRange;if(!r)return;let n=this.root;if(n.db.supports.additionalMethods.compactRange)return Gn(n.db.compactRange?.(...r),e?.signal)}get sublevelRange(){let e=this.db.prefix;if(!e)return;let r=e.slice(0,-1)+String.fromCharCode(e.charCodeAt(e.length-1)+1);return[e,r]}get root(){let e=this.db;for(let r=e.db;r&&r!==e;)e=r;return new t(this.config,e)}async createLevelDatabase(){this.db??=await this.config.createLevelDatabase(this.config.location,{keyEncoding:"utf8",valueEncoding:this.config.valueEncoding})}}});var Sf,uE=F(()=>{"use strict";g();vw();Ef();Sf=class t{config;db;constructor(e,r){this.config={createLevelDatabase:Hs,...e},this.db=r??new Ma({...this.config,valueEncoding:"binary"})}async open(){return this.db.open()}async close(){return this.db.close()}async partition(e){let r=await this.db.partition(e);return new t({...this.config,location:""},r)}async put(e,r,n){return await this.db.put(String(e),r,n),er.parse(e.toString())}async get(e,r){return await this.db.get(String(e),r)}async has(e,r){return this.db.has(String(e),r)}async delete(e,r){return this.db.delete(String(e),r)}async isEmpty(e){return this.db.isEmpty(e)}async*putMany(e,r){for await(let n of e)await this.put(n.cid,n.block,r),yield n.cid}async*getMany(e,r){for await(let n of e)yield{cid:n,block:await this.get(n,r)}}async*getAll(e){let r=this.db.iterator({keys:!0,keyEncoding:"buffer"},e);for await(let[n,i]of r)yield{cid:er.decode(n),block:i}}async*deleteMany(e,r){for await(let n of e)await this.delete(n,r),yield n}async clear(){return this.db.clear()}}});function pme(t){return t[Symbol.asyncIterator]!=null}function hme(t){if(pme(t))return(async()=>{let r;for await(let n of t)r=n;return r})();let e;for(let r of t)e=r;return e}var Qz,eF=F(()=>{g();Qz=hme});var tF,mme,rF,yme,nF,iF=F(()=>{g();Kf();Wh();tF=0,mme="identity",rF=Ua,yme=t=>Ff(tF,rF(t)),nF={code:tF,name:mme,encode:rF,digest:yme}});var sF,gme,oF,aF=F(()=>{g();Pm();sF=An(ia(),1);tl();gme=async(t,e,r,n,i,a,s,o)=>{let d=await s.get(t,o),l=hk(d),c=l,u=r;for(;n.length>0;){let f=n[0];if(f in c){n.shift(),u=`${u}/${f}`;let h=er.asCID(c[f]);if(h!=null)return{entry:{type:"object",name:e,path:r,cid:t,node:d,depth:a,size:BigInt(d.length),content:async function*(){yield l}},next:{cid:h,name:f,path:u,toResolve:n}};c=c[f]}else throw(0,sF.default)(new Error(`No property named ${f} found in cbor node ${t}`),"ERR_NO_PROP")}return{entry:{type:"object",name:e,path:r,cid:t,node:d,depth:a,size:BigInt(d.length),content:async function*(){yield l}}}},oF=gme});function wme(t,e,r,n){let i=BigInt(t.length),a=BigInt(e+i);return r>=a||n<e?new Uint8Array(0):(n>=e&&n<a&&(t=t.subarray(0,Number(n-e))),r>=e&&r<a&&(t=t.subarray(Number(r-e))),t)}var Ph,fE=F(()=>{g();Ph=wme});var ib,vme,Xy,pE=F(()=>{g();ib=An(ia(),1),vme=(t,e=0,r=t)=>{let n=BigInt(t),i=BigInt(e??0),a=BigInt(r);if(a!==n&&(a=i+a),a>n&&(a=n),i<0n)throw(0,ib.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,ib.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(a<0n)throw(0,ib.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(a>n)throw(0,ib.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:i,end:a}},Xy=vme});var cF,bme,Pme,dF,lF=F(()=>{g();cF=An(ia(),1);Wh();nl();fE();pE();bme=t=>{async function*e(r={}){let{start:n,end:i}=Xy(t.length,r.offset,r.length),a=Ph(t,0n,n,i);r.onProgress?.(new Dn("unixfs:exporter:progress:identity",{bytesRead:BigInt(a.byteLength),totalBytes:i-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Pme=async(t,e,r,n,i,a,s,o)=>{if(n.length>0)throw(0,cF.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let d=Ub(t.multihash.bytes);return{entry:{type:"identity",name:e,path:r,cid:t,content:bme(d.digest),depth:a,size:BigInt(d.digest.length),node:d.digest}}},dF=Pme});var uF,xme,Eme,fF,pF=F(()=>{g();uF=An(ia(),1);nl();fE();pE();xme=t=>{async function*e(r={}){let{start:n,end:i}=Xy(t.length,r.offset,r.length),a=Ph(t,0n,n,i);r.onProgress?.(new Dn("unixfs:exporter:progress:raw",{bytesRead:BigInt(a.byteLength),totalBytes:i-n,fileSize:BigInt(t.byteLength)})),yield a}return e},Eme=async(t,e,r,n,i,a,s,o)=>{if(n.length>0)throw(0,uF.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let d=await s.get(t,o);return{entry:{type:"raw",name:e,path:r,cid:t,content:xme(d),depth:a,size:BigInt(d.length),node:d}}},fF=Eme});var Sme,Ame,hF,kme,mF,yF,gF=F(()=>{g();sa();h_();m_();Sme=async function(t){return(await q1.encode(t)).slice(0,8).reverse()},Ame=async(t,e,r)=>{await Promise.all(t.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 Nc({hash:r._options.hash,bits:r._options.bits},e,i));return}await r.put(n.Name.substring(2),!0)}))},hF=t=>t.toString(16).toUpperCase().padStart(2,"0").substring(0,2),kme=t=>{let e=t.bucket,r=[];for(;e._parent!=null;)r.push(e),e=e._parent;return r.push(e),r.reverse()},mF=async(t,e,r,n,i)=>{if(n==null){let c=G1({hashFn:Sme});n={rootBucket:c,hamtDepth:1,lastBucket:c}}await Ame(t.Links,n.lastBucket,n.rootBucket);let a=await n.rootBucket._findNewBucketAndPos(e),s=hF(a.pos),o=kme(a);o.length>n.hamtDepth&&(n.lastBucket=o[n.hamtDepth],s=hF(n.lastBucket._posAtParent));let d=t.Links.find(c=>{if(c.Name==null)return!1;let u=c.Name.substring(0,2),f=c.Name.substring(2);return!(u!==s||f!==""&&f!==e)});if(d==null)return;if(d.Name!=null&&d.Name.substring(2)===e)return d.Hash;n.hamtDepth++;let l=await r.get(d.Hash,i);return t=rl(l),mF(t,e,r,n,i)},yF=mF});function _me(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[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(),[r](){return this}}}var hE,Z6=F(()=>{g();hE=_me});function Tme(t){return t[Symbol.asyncIterator]!=null}function Ime(t,e){let r=0;if(Tme(t))return async function*(){for await(let d of t)await e(d,r++)&&(yield d)}();let n=hE(t),{value:i,done:a}=n.next();if(a===!0)return function*(){}();let s=e(i,r++);if(typeof s.then=="function")return async function*(){await s&&(yield i);for(let d of n)await e(d,r++)&&(yield d)}();let o=e;return function*(){s===!0&&(yield i);for(let d of n)o(d,r++)&&(yield d)}()}var wF,vF=F(()=>{g();Z6();wF=Ime});function Dme(t){return t[Symbol.asyncIterator]!=null}function Rme(t,e){let r=0;if(Dme(t))return async function*(){for await(let d of t)yield e(d,r++)}();let n=hE(t),{value:i,done:a}=n.next();if(a===!0)return function*(){}();let s=e(i,r++);if(typeof s.then=="function")return async function*(){yield await s;for(let d of n)yield e(d,r++)}();let o=e;return function*(){yield s;for(let d of n)yield o(d,r++)}()}var Qy,mE=F(()=>{g();Z6();Qy=Rme});function mo(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var yE=F(()=>{g()});async function*xh(t,e={}){let r=e.concurrency??1/0;r<1&&(r=1/0);let n=e.ordered??!1,i=new EventTarget,a=[],s=mo(),o=mo(),d=!1,l,c=!1;i.addEventListener("task-complete",()=>{o.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of t){if(a.length===r&&(s=mo(),await s.promise),c)break;let m={done:!1};a.push(m),p().then(y=>{m.done=!0,m.ok=!0,m.value=y,i.dispatchEvent(new gE("task-complete"))},y=>{m.done=!0,m.err=y,i.dispatchEvent(new gE("task-complete"))})}d=!0,i.dispatchEvent(new gE("task-complete"))}catch(p){l=p,i.dispatchEvent(new gE("task-complete"))}});function u(){return n?a[0]?.done:!!a.find(p=>p.done)}function*f(){for(;a.length>0&&a[0].done;){let p=a[0];if(a.shift(),p.ok)yield p.value;else throw c=!0,s.resolve(),p.err;s.resolve()}}function*h(){for(;u();)for(let p=0;p<a.length;p++)if(a[p].done){let m=a[p];if(a.splice(p,1),p--,m.ok)yield m.value;else throw c=!0,s.resolve(),m.err;s.resolve()}}for(;;){if(u()||(o=mo(),await o.promise),l!=null||(n?yield*f():yield*h(),l!=null))throw l;if(d&&a.length===0)break}}var gE,wE=F(()=>{g();yE();gE=globalThis.CustomEvent??Event});var vE,eg,bF=F(()=>{g();vE=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}},eg=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new vE(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 r=this.head;this.head=r.next=new vE(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}});function bE(t={}){return Cme(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Cme(t,e){e=e??{};let r=e.onEnd,n=new eg,i,a,s,o=mo(),d=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,b)=>{a=w=>{a=null,n.push(w);try{y(t(n))}catch(S){b(S)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{o.resolve(),o=mo()})}},l=y=>a!=null?a(y):(n.push(y),i),c=y=>(n=new eg,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?c(y):l({done:!0})),h=()=>(n=new eg,f(),{done:!0}),p=y=>(f(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:d,return:h,throw:p,push:u,end:f,get readableLength(){return n.size},onEmpty:async y=>{let b=y?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let w,S;b!=null&&(w=new Promise((k,T)=>{S=()=>{T(new Y6)},b.addEventListener("abort",S)}));try{await Promise.race([o.promise,w])}finally{S!=null&&b!=null&&b?.removeEventListener("abort",S)}}},r==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:u,end(y){return m.end(y),r!=null&&(r(y),r=void 0),i},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},i}var Y6,X6=F(()=>{g();yE();bF();Y6=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}}});function $me(t){return t.reason}async function PF(t,e,r){if(e==null)return t;let n=r?.translateError??$me;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([t,new Promise((a,s)=>{i=()=>{s(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var xF=F(()=>{g()});function EF(){return new Q6}var Q6,SF=F(()=>{g();yE();xF();Q6=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=mo(),this.haveNext=mo()}[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=mo(),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,r){await this._push(e,r)}async end(e,r){e!=null?await this.throw(e):await this._push(void 0,r)}async _push(e,r){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=mo(),await PF(this.readNext.promise,r?.signal,r)}}});function Bme(t){return t[Symbol.asyncIterator]!=null}async function Ome(t,e,r){try{await Promise.all(t.map(async n=>{for await(let i of n)await e.push(i,{signal:r}),r.throwIfAborted()})),await e.end(void 0,{signal:r})}catch(n){await e.end(n,{signal:r}).catch(()=>{})}}async function*jme(t){let e=new AbortController,r=EF();Ome(t,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort()}}function*Mme(t){for(let e of t)yield*e}function Kme(...t){let e=[];for(let r of t)Bme(r)||e.push(r);return e.length===t.length?Mme(e):jme(t)}var AF,kF=F(()=>{g();SF();AF=Kme});function tg(t,...e){if(t==null)throw new Error("Empty pipeline");if(e5(t)){let n=t;t=()=>n.source}else if(TF(t)||_F(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&e5(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)e5(r[n])&&(r[n]=Ume(r[n]));return Nme(...r)}var Nme,_F,TF,e5,Ume,PE=F(()=>{g();X6();kF();Nme=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},_F=t=>t?.[Symbol.asyncIterator]!=null,TF=t=>t?.[Symbol.iterator]!=null,e5=t=>t==null?!1:t.sink!=null&&t.source!=null,Ume=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=bE({objectMode:!0});r.then(()=>{n.end()},s=>{n.end(s)});let i,a=t.source;if(_F(a))i=async function*(){yield*a,n.end()};else if(TF(a))i=function*(){yield*a,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return AF(n,i())}return t.source}});var Lme,IF,DF=F(()=>{g();vF();mE();wE();PE();nl();Lme=(t,e,r,n,i,a,s)=>{async function*o(d={}){let l=d.offset??0,c=d.length??e.Links.length,u=e.Links.slice(l,c);d.onProgress?.(new Dn("unixfs:exporter:walk:directory",{cid:t})),yield*tg(u,f=>Qy(f,h=>async()=>{let p=h.Name??"",m=`${n}/${p}`;return(await i(h.Hash,p,m,[],a+1,s,d)).entry}),f=>xh(f,{ordered:!0}),f=>wF(f,h=>h!=null))}return o},IF=Lme});var CF=_e((yqe,t5)=>{"use strict";g();var qme=Object.prototype.hasOwnProperty,Vs="~";function sb(){}Object.create&&(sb.prototype=Object.create(null),new sb().__proto__||(Vs=!1));function zme(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function RF(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var a=new zme(r,n||t,i),s=Vs?Vs+e:e;return t._events[s]?t._events[s].fn?t._events[s]=[t._events[s],a]:t._events[s].push(a):(t._events[s]=a,t._eventsCount++),t}function xE(t,e){--t._eventsCount===0?t._events=new sb:delete t._events[e]}function Ps(){this._events=new sb,this._eventsCount=0}Ps.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)qme.call(r,n)&&e.push(Vs?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};Ps.prototype.listeners=function(e){var r=Vs?Vs+e:e,n=this._events[r];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};Ps.prototype.listenerCount=function(e){var r=Vs?Vs+e:e,n=this._events[r];return n?n.fn?1:n.length:0};Ps.prototype.emit=function(e,r,n,i,a,s){var o=Vs?Vs+e:e;if(!this._events[o])return!1;var d=this._events[o],l=arguments.length,c,u;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,r),!0;case 3:return d.fn.call(d.context,r,n),!0;case 4:return d.fn.call(d.context,r,n,i),!0;case 5:return d.fn.call(d.context,r,n,i,a),!0;case 6:return d.fn.call(d.context,r,n,i,a,s),!0}for(u=1,c=new Array(l-1);u<l;u++)c[u-1]=arguments[u];d.fn.apply(d.context,c)}else{var f=d.length,h;for(u=0;u<f;u++)switch(d[u].once&&this.removeListener(e,d[u].fn,void 0,!0),l){case 1:d[u].fn.call(d[u].context);break;case 2:d[u].fn.call(d[u].context,r);break;case 3:d[u].fn.call(d[u].context,r,n);break;case 4:d[u].fn.call(d[u].context,r,n,i);break;default:if(!c)for(h=1,c=new Array(l-1);h<l;h++)c[h-1]=arguments[h];d[u].fn.apply(d[u].context,c)}}return!0};Ps.prototype.on=function(e,r,n){return RF(this,e,r,n,!1)};Ps.prototype.once=function(e,r,n){return RF(this,e,r,n,!0)};Ps.prototype.removeListener=function(e,r,n,i){var a=Vs?Vs+e:e;if(!this._events[a])return this;if(!r)return xE(this,a),this;var s=this._events[a];if(s.fn)s.fn===r&&(!i||s.once)&&(!n||s.context===n)&&xE(this,a);else{for(var o=0,d=[],l=s.length;o<l;o++)(s[o].fn!==r||i&&!s[o].once||n&&s[o].context!==n)&&d.push(s[o]);d.length?this._events[a]=d.length===1?d[0]:d:xE(this,a)}return this};Ps.prototype.removeAllListeners=function(e){var r;return e?(r=Vs?Vs+e:e,this._events[r]&&xE(this,r)):(this._events=new sb,this._eventsCount=0),this};Ps.prototype.off=Ps.prototype.removeListener;Ps.prototype.addListener=Ps.prototype.on;Ps.prefixed=Vs;Ps.EventEmitter=Ps;typeof t5<"u"&&(t5.exports=Ps)});var r5,$F=F(()=>{g();r5=An(CF(),1)});function i5(t,e,r,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(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:d}=n;d.aborted&&o(OF(d)),d.addEventListener("abort",()=>{o(OF(d))})}i=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{s(r())}catch(c){o(c)}return}let d=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,l=r instanceof Error?r:new ob(d);typeof t.cancel=="function"&&t.cancel(),o(l)},e),(async()=>{try{s(await t)}catch(d){o(d)}finally{n.customTimers.clearTimeout.call(void 0,i)}})()});return a.clear=()=>{clearTimeout(i),i=void 0},a}var ob,n5,BF,OF,jF=F(()=>{g();ob=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},n5=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},BF=t=>globalThis.DOMException===void 0?new n5(t):new DOMException(t),OF=t=>{let e=t.reason===void 0?BF("This operation was aborted."):t.reason;return e instanceof Error?e:BF(e)}});function s5(t,e,r){let n=0,i=t.length;for(;i>0;){let a=Math.trunc(i/2),s=n+a;r(t[s],e)<=0?(n=++s,i-=a+1):i=a}return n}var MF=F(()=>{g()});var Eh,Ul,o5,KF,NF=F(()=>{g();MF();Eh=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},o5=class{constructor(){Ul.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&Eh(this,Ul,"f")[this.size-1].priority>=r.priority){Eh(this,Ul,"f").push(n);return}let i=s5(Eh(this,Ul,"f"),n,(a,s)=>s.priority-a.priority);Eh(this,Ul,"f").splice(i,0,n)}dequeue(){let e=Eh(this,Ul,"f").shift();return e?.run}filter(e){return Eh(this,Ul,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return Eh(this,Ul,"f").length}};Ul=new WeakMap;KF=o5});var En,Ye,Hn,cb,db,kf,TE,lb,EE,Sc,ab,Zo,SE,Yo,ub,Af,AE,UF,LF,FF,qF,zF,kE,a5,c5,IE,GF,_E,DE,d5,HF,VF=F(()=>{g();$F();jF();NF();En=function(t,e,r,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"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},Ye=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},DE=class extends Error{},d5=class extends r5.default{constructor(e){var r,n,i,a;if(super(),Hn.add(this),cb.set(this,void 0),db.set(this,void 0),kf.set(this,0),TE.set(this,void 0),lb.set(this,void 0),EE.set(this,0),Sc.set(this,void 0),ab.set(this,void 0),Zo.set(this,void 0),SE.set(this,void 0),Yo.set(this,0),ub.set(this,void 0),Af.set(this,void 0),AE.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:KF,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.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})`);En(this,cb,e.carryoverConcurrencyCount,"f"),En(this,db,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),En(this,TE,e.intervalCap,"f"),En(this,lb,e.interval,"f"),En(this,Zo,new e.queueClass,"f"),En(this,SE,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,En(this,AE,e.throwOnTimeout===!0,"f"),En(this,Af,e.autoStart===!1,"f")}get concurrency(){return Ye(this,ub,"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})`);En(this,ub,e,"f"),Ye(this,Hn,"m",IE).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:Ye(this,AE,"f"),...r},new Promise((n,i)=>{Ye(this,Zo,"f").enqueue(async()=>{var a,s,o;En(this,Yo,(s=Ye(this,Yo,"f"),s++,s),"f"),En(this,kf,(o=Ye(this,kf,"f"),o++,o),"f");try{if(!((a=r.signal)===null||a===void 0)&&a.aborted)throw new DE("The task was aborted.");let d=e({signal:r.signal});r.timeout&&(d=i5(Promise.resolve(d),r.timeout)),r.signal&&(d=Promise.race([d,Ye(this,Hn,"m",GF).call(this,r.signal)]));let l=await d;n(l),this.emit("completed",l)}catch(d){if(d instanceof ob&&!r.throwOnTimeout){n();return}i(d),this.emit("error",d)}finally{Ye(this,Hn,"m",FF).call(this)}},r),this.emit("add"),Ye(this,Hn,"m",kE).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return Ye(this,Af,"f")?(En(this,Af,!1,"f"),Ye(this,Hn,"m",IE).call(this),this):this}pause(){En(this,Af,!0,"f")}clear(){En(this,Zo,new(Ye(this,SE,"f")),"f")}async onEmpty(){Ye(this,Zo,"f").size!==0&&await Ye(this,Hn,"m",_E).call(this,"empty")}async onSizeLessThan(e){Ye(this,Zo,"f").size<e||await Ye(this,Hn,"m",_E).call(this,"next",()=>Ye(this,Zo,"f").size<e)}async onIdle(){Ye(this,Yo,"f")===0&&Ye(this,Zo,"f").size===0||await Ye(this,Hn,"m",_E).call(this,"idle")}get size(){return Ye(this,Zo,"f").size}sizeBy(e){return Ye(this,Zo,"f").filter(e).length}get pending(){return Ye(this,Yo,"f")}get isPaused(){return Ye(this,Af,"f")}};cb=new WeakMap,db=new WeakMap,kf=new WeakMap,TE=new WeakMap,lb=new WeakMap,EE=new WeakMap,Sc=new WeakMap,ab=new WeakMap,Zo=new WeakMap,SE=new WeakMap,Yo=new WeakMap,ub=new WeakMap,Af=new WeakMap,AE=new WeakMap,Hn=new WeakSet,UF=function(){return Ye(this,db,"f")||Ye(this,kf,"f")<Ye(this,TE,"f")},LF=function(){return Ye(this,Yo,"f")<Ye(this,ub,"f")},FF=function(){var e;En(this,Yo,(e=Ye(this,Yo,"f"),e--,e),"f"),Ye(this,Hn,"m",kE).call(this),this.emit("next")},qF=function(){Ye(this,Hn,"m",c5).call(this),Ye(this,Hn,"m",a5).call(this),En(this,ab,void 0,"f")},zF=function(){let e=Date.now();if(Ye(this,Sc,"f")===void 0){let r=Ye(this,EE,"f")-e;if(r<0)En(this,kf,Ye(this,cb,"f")?Ye(this,Yo,"f"):0,"f");else return Ye(this,ab,"f")===void 0&&En(this,ab,setTimeout(()=>{Ye(this,Hn,"m",qF).call(this)},r),"f"),!0}return!1},kE=function(){if(Ye(this,Zo,"f").size===0)return Ye(this,Sc,"f")&&clearInterval(Ye(this,Sc,"f")),En(this,Sc,void 0,"f"),this.emit("empty"),Ye(this,Yo,"f")===0&&this.emit("idle"),!1;if(!Ye(this,Af,"f")){let e=!Ye(this,Hn,"a",zF);if(Ye(this,Hn,"a",UF)&&Ye(this,Hn,"a",LF)){let r=Ye(this,Zo,"f").dequeue();return r?(this.emit("active"),r(),e&&Ye(this,Hn,"m",a5).call(this),!0):!1}}return!1},a5=function(){Ye(this,db,"f")||Ye(this,Sc,"f")!==void 0||(En(this,Sc,setInterval(()=>{Ye(this,Hn,"m",c5).call(this)},Ye(this,lb,"f")),"f"),En(this,EE,Date.now()+Ye(this,lb,"f"),"f"))},c5=function(){Ye(this,kf,"f")===0&&Ye(this,Yo,"f")===0&&Ye(this,Sc,"f")&&(clearInterval(Ye(this,Sc,"f")),En(this,Sc,void 0,"f")),En(this,kf,Ye(this,cb,"f")?Ye(this,Yo,"f"):0,"f"),Ye(this,Hn,"m",IE).call(this)},IE=function(){for(;Ye(this,Hn,"m",kE).call(this););},GF=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new DE("The task was aborted."))},{once:!0})})},_E=async function(e,r){return new Promise(n=>{let i=()=>{r&&!r()||(this.off(e,i),n())};this.on(e,i)})};HF=d5});async function WF(t,e,r,n,i,a,s){if(e instanceof Uint8Array){let l=Ph(e,n,i,a);r.push(l);return}if(e.Data==null)throw(0,Sh.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let o;try{o=gi.unmarshal(e.Data)}catch(l){throw(0,Sh.default)(l,"ERR_NOT_UNIXFS")}if(o.data!=null){let l=o.data,c=Ph(l,n,i,a);r.push(c),n+=BigInt(c.byteLength)}let d=[];if(e.Links.length!==o.blockSizes.length)throw(0,Sh.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let l=0;l<e.Links.length;l++){let c=e.Links[l],u=n,f=u+o.blockSizes[l];if((i>=u&&i<f||a>=u&&a<=f||i<u&&a>f)&&d.push({link:c,blockStart:n}),n=f,n>a)break}await tg(d,l=>Qy(l,c=>async()=>{let u=await t.get(c.link.Hash,s);return{...c,block:u}}),l=>xh(l,{ordered:!0}),async l=>{for await(let{link:c,block:u,blockStart:f}of l){let h;switch(c.Hash.code){case Sw:h=rl(u);break;case wu:h=u;break;default:r.end((0,Sh.default)(new Error(`Unsupported codec: ${c.Hash.code}`),"ERR_NOT_UNIXFS"));return}let p=new HF({concurrency:1});p.on("error",m=>{r.end(m)}),p.add(async()=>{s.onProgress?.(new Dn("unixfs:exporter:walk:file",{cid:c.Hash})),await WF(t,h,r,f,i,a,s)}),await p.onIdle()}}),n>=a&&r.end()}var Sh,Fme,l5,JF=F(()=>{g();sa();Sh=An(ia(),1);gu();mE();wE();PE();X6();Cw();VF();nl();fE();pE();Fme=(t,e,r,n,i,a,s)=>{async function*o(d={}){let l=r.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:c,end:u}=Xy(l,d.offset,d.length);if(u===0n)return;let f=0n,h=u-c,p=bE();d.onProgress?.(new Dn("unixfs:exporter:walk:file",{cid:t})),WF(s,e,p,0n,c,u,d).catch(m=>{p.end(m)});for await(let m of p)if(m!=null){if(f+=BigInt(m.byteLength),f>h)throw p.end(),(0,Sh.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===h&&p.end(),d.onProgress?.(new Dn("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:h,fileSize:l})),yield m}if(f<h)throw(0,Sh.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return o},l5=Fme});async function*ZF(t,e,r,n,i,a){let s=t.Links,o=tg(s,d=>Qy(d,l=>async()=>{let c=l.Name!=null?l.Name.substring(2):null;if(c!=null&&c!==""){let u=await r(l.Hash,c,`${e}/${c}`,[],n+1,i,a);return{entries:u.entry==null?[]:[u.entry]}}else{let u=await i.get(l.Hash,a);return t=rl(u),a.onProgress?.(new Dn("unixfs:exporter:walk:hamt-sharded-directory",{cid:l.Hash})),{entries:ZF(t,e,r,n,i,a)}}}),d=>xh(d,{ordered:!0}));for await(let{entries:d}of o)yield*d}var Gme,YF,XF=F(()=>{g();sa();mE();wE();PE();nl();Gme=(t,e,r,n,i,a,s)=>{function o(d={}){return d.onProgress?.(new Dn("unixfs:exporter:walk:hamt-sharded-directory",{cid:t})),ZF(e,n,i,a,s,d)}return o};YF=Gme});var fb,Hme,Vme,Wme,QF,eG=F(()=>{g();sa();fb=An(ia(),1);gu();gF();DF();JF();XF();Hme=(t,e)=>t.Links.find(n=>n.Name===e)?.Hash,Vme={raw:l5,file:l5,directory:IF,"hamt-sharded-directory":YF,metadata:(t,e,r,n,i,a,s)=>()=>[],symlink:(t,e,r,n,i,a,s)=>()=>[]},Wme=async(t,e,r,n,i,a,s,o)=>{let d=await s.get(t,o),l=rl(d),c,u;if(e==null&&(e=t.toString()),l.Data==null)throw(0,fb.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{c=gi.unmarshal(l.Data)}catch(h){throw(0,fb.default)(h,"ERR_NOT_UNIXFS")}if(r==null&&(r=e),n.length>0){let h;if(c?.type==="hamt-sharded-directory"?h=await yF(l,n[0],s):h=Hme(l,n[0]),h==null)throw(0,fb.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let p=n.shift(),m=`${r}/${p}`;u={cid:h,toResolve:n,name:p??"",path:m}}let f=Vme[c.type](t,l,c,r,i,a,s);if(f==null)throw(0,fb.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return c.isDirectory()?{entry:{type:"directory",name:e,path:r,cid:t,content:f,unixfs:c,depth:a,node:l,size:c.fileSize()},next:u}:{entry:{type:"file",name:e,path:r,cid:t,content:f,unixfs:c,depth:a,node:l,size:c.fileSize()},next:u}},QF=Wme});var tG,Jme,rG,nG,iG=F(()=>{g();Pm();sa();tG=An(ia(),1);Cw();iF();aF();lF();pF();eG();Jme={[Sw]:QF,[wu]:fF,[pu]:oF,[nF.code]:dF},rG=async(t,e,r,n,i,a,s)=>{let o=Jme[t.code];if(o==null)throw(0,tG.default)(new Error(`No resolver for code ${t.code}`),"ERR_NO_RESOLVER");return o(t,e,r,n,rG,i,a,s)},nG=rG});async function*Xme(t,e,r={}){let{cid:n,toResolve:i}=Yme(t),a=n.toString(),s=a,o=i.length;for(;;){let d=await nG(n,a,s,i,o,e,r);if(d.entry==null&&d.next==null)throw(0,RE.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");if(d.entry!=null&&(yield d.entry),d.next==null)return;i=d.next.toResolve,n=d.next.cid,a=d.next.name,s=d.next.path}}async function sG(t,e,r={}){let n=await Qz(Xme(t,e,r));if(n==null)throw(0,RE.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");return n}var RE,Zme,Yme,oG=F(()=>{g();RE=An(ia(),1);eF();tl();iG();Zme=(t="")=>(t.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),Yme=t=>{if(t instanceof Uint8Array)return{cid:er.decode(t),toResolve:[]};let e=er.asCID(t);if(e!=null)return{cid:e,toResolve:[]};if(typeof t=="string"){t.indexOf("/ipfs/")===0&&(t=t.substring(6));let r=Zme(t);return{cid:er.parse(r[0]),toResolve:r.slice(1)}}throw(0,RE.default)(new Error(`Unknown path type ${t}`),"ERR_BAD_PATH")}});var u5,CE,_f,aG=F(()=>{"use strict";g();uE();Ef();hu();oG();w_();u5=new TextEncoder,CE=new TextDecoder,_f=class{config;blockstore;constructor(e={}){this.config={blockstoreLocation:"DATASTORE",createLevelDatabase:Hs,...e},this.blockstore=new Sf({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase})}async open(){await this.blockstore.open()}async close(){await this.blockstore.close()}async put(e,r,n,i){let a=await this.getRefsPartition(e,r),s=await a.get(n);if(s){await i.cancel();let{dataSize:u}=JSON.parse(CE.decode(s));return{dataSize:u}}let o=await this.getRefcountsPartition(),d=await o.get(n),l=d?JSON.parse(CE.decode(d)):{count:0,dataSize:0},c;if(l.count>0)await i.cancel(),c=l.dataSize;else{let u=await this.getBlocksPartition(n),f=Ow([{content:Yt.asAsyncIterable(i)}],u,{cidVersion:1}),h;for await(h of f);c=Number(h.unixfs?.fileSize()??h.size)}return await a.put(n,u5.encode(JSON.stringify({dataSize:c}))),await o.put(n,u5.encode(JSON.stringify({count:l.count+1,dataSize:c}))),{dataSize:c}}async get(e,r,n){let a=await(await this.getRefsPartition(e,r)).get(n);if(!a)return;let{dataSize:s}=JSON.parse(CE.decode(a)),o=await this.getBlocksPartition(n);if(!await o.has(n))return;let c=(await sG(n,o)).content(),u=new ReadableStream({async pull(f){let h=await c.next();h.done?f.close():f.enqueue(h.value)}});return{dataSize:s,dataStream:u}}async delete(e,r,n){let i=await this.getRefsPartition(e,r);if(!await i.get(n))return;await i.delete(n);let s=await this.getRefcountsPartition(),o=await s.get(n);if(!o)return;let d=JSON.parse(CE.decode(o)),l=d.count-1;l<=0?(await(await this.getBlocksPartition(n)).clear(),await s.delete(n)):await s.put(n,u5.encode(JSON.stringify({count:l,dataSize:d.dataSize})))}async clear(){await this.blockstore.clear()}async getRefsPartition(e,r){return(await(await this.blockstore.db.partition("refs")).partition(e)).partition(r)}async getBlocksPartition(e){return(await this.blockstore.partition("blocks")).partition(e)}async getRefcountsPartition(){return this.blockstore.db.partition("refcounts")}}});async function cG(t,e,r){let n=`__compound:${r.name}__`;return(await t.partition(e)).partition(n)}function dG(t,e,r,n,i){let a=[];for(let l of r.properties){let c=e[l];if(c===void 0||Array.isArray(c))return;a.push(n(c))}let s=e[r.sortProperty];if(s===void 0||Array.isArray(s))return;let o=a.join($E),d=n(s);return o+$E+d+i+t}function lG(t,e,r){let n=[];for(let i of e.properties){let a=t[i];if(a===void 0||typeof a=="object")return;n.push(r(a))}return n.join($E)+$E}function uG(t,e,r,n,i,a){let s=dG(r.messageCid,r.indexes,n,i,a);if(s!==void 0)return pG(t,e,`__compound:${n.name}__`,{type:"put",key:s,value:JSON.stringify(r)})}function fG(t,e,r,n,i,a,s){let o=dG(r,n,i,a,s);if(o!==void 0)return pG(t,e,`__compound:${i.name}__`,{type:"del",key:o})}async function pG(t,e,r,n){return(await t.partition(e)).createPartitionOperation(r,n)}function f5(t,e,r){let n,i=0;for(let a of r){if(a.sortProperty!==e.sortProperty)continue;let s=!0;for(let o of a.properties){let d=t[o];if(d===void 0||typeof d=="object"){s=!1;break}}s&&a.properties.length>i&&(n=a,i=a.properties.length)}return n}async function hG(t,e,r,n,i,a,s,o,d){let{sortDirection:l=It.Ascending,cursor:c,limit:u}=n,f=lG(r,i,a);if(f===void 0)return o(e,[r],n,d);let h=await cG(t,e,i),p={};if(c!==void 0){let S=a(c.value),k=f+S+s+c.messageCid;l===It.Ascending?(p.gt=k,p.lt=f+"\xFF"):(p.lt=k,p.gt=f,p.reverse=!0)}else l===It.Ascending?(p.gt=f,p.lt=f+"\xFF"):(p.gt=f,p.lt=f+"\xFF",p.reverse=!0);let m=new Set(i.properties),y={},b=!1;for(let S in r)m.has(S)||(y[S]=r[S],b=!0);let w=[];for await(let[S,k]of h.iterator(p,d)){if(u!==void 0&&w.length===u)break;let T=JSON.parse(k);b&&!ir.matchFilter(T.indexes,y)||w.push(T)}return w}async function mG(t,e,r,n,i,a,s){let o=lG(r,n,i);if(o===void 0)return(await a(e,[r],{sortProperty:n.sortProperty},s)).length;let d=await cG(t,e,n),l=new Set(n.properties),c=!1,u={};for(let p in r)l.has(p)||(u[p]=r[p],c=!0);let f={gt:o,lt:o+"\xFF"},h=0;if(c)for await(let[p,m]of d.iterator(f,s)){let y=JSON.parse(m);ir.matchFilter(y.indexes,u)&&h++}else for await(let[p,m]of d.iterator(f,s))h++;return h}var $E,yG=F(()=>{"use strict";g();lc();Vc();$E=""});var gG,Ah,p5=F(()=>{"use strict";g();Di();b_();Vc();yG();Ef();xt();lc();gG="index",Ah=class t{db;config;_compoundIndexes;constructor(e){this.config={createLevelDatabase:Hs,...e},this._compoundIndexes=e.compoundIndexes??[],this.db=new Ma({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,r,n,i){if(pp(n))throw new ie(ne.IndexMissingIndexableProperty,"Index must include at least one valid indexable property");let a={messageCid:r,indexes:n},s=[];for(let c in n){let u=n[c];if(Array.isArray(u))for(let f of u){let h=this.createPutIndexedItemOperation(e,a,c,f);s.push(h)}else{let f=this.createPutIndexedItemOperation(e,a,c,u);s.push(f)}}for(let c of this._compoundIndexes){let u=uG(this.db,e,a,c,t.encodeValue,t.delimiter);u!==void 0&&s.push(u)}let o=this.createOperationForIndexesLookupPartition(e,{type:"put",key:r,value:JSON.stringify(n)});s.push(o);let d=await Promise.all(s);await(await this.db.partition(e)).batch(d,i)}async delete(e,r,n){let i=[],a=await this.getIndexes(e,r);if(a===void 0)return;let s=this.createOperationForIndexesLookupPartition(e,{type:"del",key:r});i.push(s);for(let l in a){let c=a[l];if(Array.isArray(c))for(let u of c){let f=this.createDeleteIndexedItemOperation(e,r,l,u);i.push(f)}else{let u=this.createDeleteIndexedItemOperation(e,r,l,c);i.push(u)}}for(let l of this._compoundIndexes){let c=fG(this.db,e,r,a,l,t.encodeValue,t.delimiter);c!==void 0&&i.push(c)}let o=await Promise.all(i);await(await this.db.partition(e)).batch(o,n)}async createPutIndexedItemOperation(e,r,n,i){let{messageCid:a}=r,s=t.keySegmentJoin(t.encodeValue(i),a);return this.createOperationForIndexPartition(e,n,{type:"put",key:s,value:JSON.stringify(r)})}async createDeleteIndexedItemOperation(e,r,n,i){let a=t.keySegmentJoin(t.encodeValue(i),r);return this.createOperationForIndexPartition(e,n,{type:"del",key:a})}async createOperationForIndexPartition(e,r,n){let i=await this.db.partition(e),a=t.getIndexPartitionName(r);return i.createPartitionOperation(a,n)}async createOperationForIndexesLookupPartition(e,r){return(await this.db.partition(e)).createPartitionOperation(gG,r)}static getIndexPartitionName(e){return`__${e}__`}async getIndexPartition(e,r){let n=t.getIndexPartitionName(r);return(await this.db.partition(e)).partition(n)}async getIndexesLookupPartition(e){return(await this.db.partition(e)).partition(gG)}async query(e,r,n,i){if(r.length===1&&!pp(r[0])){let a=f5(r[0],n,this._compoundIndexes);if(a!==void 0)return hG(this.db,e,r[0],n,a,t.encodeValue,t.delimiter,this.queryWithIteratorPaging.bind(this),i)}return t.shouldQueryWithInMemoryPaging(r,n)?this.queryWithInMemoryPaging(e,r,n,i):this.queryWithIteratorPaging(e,r,n,i)}async count(e,r,n,i){if(r.length===1&&!pp(r[0])){let s=f5(r[0],{...n},this._compoundIndexes);if(s!==void 0)return mG(this.db,e,r[0],s,t.encodeValue,this.query.bind(this),i)}return(await this.query(e,r,{...n},i)).length}async queryWithIteratorPaging(e,r,n,i){let{cursor:a,limit:s}=n,o=a?this.createStartingKeyFromCursor(a):"",d=[];for await(let l of this.getIndexIterator(e,o,n,i)){if(s!==void 0&&s===d.length)break;let{indexes:c}=l;ir.matchAnyFilter(c,r)&&d.push(l)}return d}async*getIndexIterator(e,r,n,i){let{sortProperty:a,sortDirection:s=It.Ascending,cursor:o}=n,d={gt:r};s===It.Descending&&(d.reverse=!0,o!==void 0&&(d.lt=r,delete d.gt));let l=await this.getIndexPartition(e,a);for await(let[c,u]of l.iterator(d,i)){let{indexes:f,messageCid:h}=JSON.parse(u);yield{indexes:f,messageCid:h}}}createStartingKeyFromCursor(e){let{messageCid:r,value:n}=e;return t.keySegmentJoin(t.encodeValue(n),r)}static createCursorFromLastArrayItem(e,r){if(e.length>0)return this.createCursorFromItem(e.at(-1),r)}static createCursorFromItem(e,r){let{messageCid:n,indexes:i}=e,a=i[r];if(a===void 0)throw new ie(ne.IndexInvalidCursorSortProperty,`the sort property '${r}' is not defined within the given item.`);if(typeof a=="boolean"||Array.isArray(a))throw new ie(ne.IndexInvalidCursorValueType,`only string or number values are supported for cursors, a(n) ${typeof a} was given.`);return{messageCid:n,value:a}}async queryWithInMemoryPaging(e,r,n,i){let{sortProperty:a,sortDirection:s=It.Ascending,cursor:o,limit:d}=n,l=o?this.createStartingKeyFromCursor(o):void 0,c=new Map;r.length===0&&(r=[{}]);try{for(let p of r)await this.executeSingleFilterQuery(e,p,a,c,i)}catch(p){if(p.code===ne.IndexInvalidSortPropertyInMemory)return[]}let u=[...c.values()].sort((p,m)=>this.sortItems(p,m,a,s)),f=l!==void 0?this.findCursorStartingIndex(u,s,a,l):0;if(f<0)return[];let h=d!==void 0?f+d:void 0;return u.slice(f,h)}async executeSingleFilterQuery(e,r,n,i,a){let s=d=>{for(let l of d)if(!(i.has(l.messageCid)||!ir.matchFilter(l.indexes,r))){if(l.indexes[n]===void 0)throw new ie(ne.IndexInvalidSortPropertyInMemory,`invalid sort property ${n}`);i.set(l.messageCid,l)}};if(pp(r)){let d=await this.getAllItems(e,n);s(d);return}let o=yP.reduceFilter(r);for(let d in o){let l=o[d];if(ir.isEqualFilter(l)){let c=await this.filterExactMatches(e,d,l,a);s(c)}else if(ir.isOneOfFilter(l))for(let c of new Set(l)){let u=await this.filterExactMatches(e,d,c,a);s(u)}else if(ir.isRangeFilter(l)){let c=await this.filterRangeMatches(e,d,l,a);s(c)}}}async getAllItems(e,r){let n=await this.getIndexPartition(e,r),i=[];for await(let[a,s]of n.iterator())i.push(JSON.parse(s));return i}async filterExactMatches(e,r,n,i){let a=t.keySegmentJoin(t.encodeValue(n)),s={gt:a},o=await this.getIndexPartition(e,r),d=[];for await(let[l,c]of o.iterator(s,i)){if(!l.startsWith(a))break;d.push(JSON.parse(c))}return d}async filterRangeMatches(e,r,n,i){let a={};for(let d in n){let l=d,c=t.encodeValue(n[l]);l==="lte"?a[l]=c+"\xFF":a[l]=c}a.gt===void 0&&a.gte===void 0&&(a.reverse=!0);let s=[],o=await this.getIndexPartition(e,r);for await(let[d,l]of o.iterator(a,i))"gt"in n&&this.extractIndexValueFromKey(d)===t.encodeValue(n.gt)||s.push(JSON.parse(l));return s}sortItems(e,r,n,i){let a=e.indexes[n],s=r.indexes[n],o=t.encodeValue(a)+e.messageCid,d=t.encodeValue(s)+r.messageCid;return i===It.Ascending?jw(o,d):jw(d,o)}findCursorStartingIndex(e,r,n,i){let a=d=>{let{messageCid:l,indexes:c}=d,u=c[n],f=t.keySegmentJoin(t.encodeValue(u),l);return r===It.Ascending?f>i:f<i},s=0,o=e.length;for(;s<o;){let d=s+o>>>1;a(e[d])?o=d:s=d+1}return s<e.length?s:-1}async getIndexes(e,r){let i=await(await this.getIndexesLookupPartition(e)).get(r);if(i!==void 0)return JSON.parse(i)}extractIndexValueFromKey(e){let[r]=e.split(t.delimiter);return r}static delimiter="\0";static keySegmentJoin(...e){return e.join(t.delimiter)}static encodeNumberValue(e){let r=Number.MAX_SAFE_INTEGER,n="!",i=String(Number.MAX_SAFE_INTEGER).length,a=e<0?n:"",s=e<0?r: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,r){for(let n of e)if(!t.isFilterConcise(n,r))return!1;return!0}static isFilterConcise(e,r){return e.recordId!==void 0?!0:r.cursor!==void 0?!1:e.protocolPath!==void 0||e.contextId!==void 0||e.parentId!==void 0||e.schema!==void 0}}});function BE({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*Qme(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let i=[...t,r],a=er.asCID(n);a?yield[i.join("/"),a]:typeof n=="object"&&(yield*h5(n,i))}else{let r=er.asCID(e);r?yield[t.join("/"),r]:yield*h5(e,t)}}function*h5(t,e){if(t==null||t instanceof Uint8Array)return;let r=er.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,i]of Object.entries(t)){let a=[...e,n];yield*Qme(a,i)}}function*eye(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let i=[...t,r];yield i.join("/"),typeof n=="object"&&!er.asCID(n)&&(yield*m5(n,i))}else yield*m5(e,t)}function*m5(t,e){if(!(t==null||typeof t!="object"))for(let[r,n]of Object.entries(t)){let i=[...e,r];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!er.asCID(n)&&(yield*eye(i,n))}}function tye(t,e){let r=t;for(let[n,i]of e.entries()){if(r=r[i],r==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let a=er.asCID(r);if(a)return{value:a,remaining:e.slice(n+1).join("/")}}return{value:r}}async function wG({value:t,codec:e,hasher:r}){if(typeof t>"u")throw new Error('Missing required argument "value"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.encode(t),i=await r.digest(n),a=er.create(1,e.code,i);return new OE({value:t,bytes:n,cid:a})}async function vG({bytes:t,codec:e,hasher:r}){if(!t)throw new Error('Missing required argument "bytes"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.decode(t),i=await r.digest(t),a=er.create(1,e.code,i);return new OE({value:n,bytes:t,cid:a})}var OE,bG=F(()=>{g();vw();bk();OE=class{constructor({cid:e,bytes:r,value:n}){if(!e||!r||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=r,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:BE(),bytes:BE(),value:BE(),asBlock:BE()})}links(){return h5(this.value,[])}tree(){return m5(this.value,[])}get(e="/"){return tye(this.value,e.split("/").filter(Boolean))}}});var nye,Tf,PG=F(()=>{"use strict";g();bG();Pm();uE();il();tl();Ef();lE();p5();wr();Jl();Vc();nye=[{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"}],Tf=class t{config;blockstore;index;constructor(e={}){this.config={blockstoreLocation:"MESSAGESTORE",indexLocation:"INDEX",createLevelDatabase:Hs,...e},this.blockstore=new Sf({location:this.config.blockstoreLocation,createLevelDatabase:this.config.createLevelDatabase}),this.index=new Ah({location:this.config.indexLocation,createLevelDatabase:this.config.createLevelDatabase,compoundIndexes:this.config.compoundIndexes??nye})}async open(){await this.blockstore.open(),await this.index.open()}async close(){await this.blockstore.close(),await this.index.close()}async get(e,r,n){n?.signal?.throwIfAborted();let i=await Gn(this.blockstore.partition(e),n?.signal),a=er.parse(r),s=await i.get(a,n);return s?(await Gn(vG({bytes:s,codec:el,hasher:Bn}),n?.signal)).value:void 0}async query(e,r,n,i,a){a?.signal?.throwIfAborted();let s=t.buildQueryOptions(n,i),o=await this.index.query(e,r,s,a),d;i?.limit!==void 0&&i.limit<o.length&&(o.splice(-1),d=Ah.createCursorFromLastArrayItem(o,s.sortProperty));let l=[];for(let c=0;c<o.length;c++){let{messageCid:u}=o[c],f=await this.get(e,u,a);f&&l.push(f)}return{messages:l,cursor:d}}async count(e,r,n,i){i?.signal?.throwIfAborted();let a=t.buildQueryOptions(n);return this.index.count(e,r,a,i)}static buildQueryOptions(e={},r={}){let{limit:n,cursor:i}=r,{dateCreated:a,datePublished:s,messageTimestamp:o}=e,d=It.Ascending,l="messageTimestamp";return a!==void 0?l="dateCreated":s!==void 0?l="datePublished":o!==void 0&&(l="messageTimestamp"),e[l]!==void 0&&(d=e[l]),n!==void 0&&n>0&&(n=n+1),{sortDirection:d,sortProperty:l,limit:n,cursor:i}}async delete(e,r,n){n?.signal?.throwIfAborted();let i=await Gn(this.blockstore.partition(e),n?.signal),a=er.parse(r);await i.delete(a,n),await this.index.delete(e,r,n)}async put(e,r,n,i){i?.signal?.throwIfAborted();let a=await Gn(this.blockstore.partition(e),i?.signal),s=await Gn(wG({value:r,codec:el,hasher:Bn}),i?.signal),o=hr.parseCid(await we.getCid(r));await a.put(o,s.bytes,i);let d=o.toString();await this.index.put(e,d,n,i)}async clear(){await this.blockstore.clear(),await this.index.clear()}}});var If,xG=F(()=>{"use strict";g();il();Ef();If=class t{static taskTimeoutInSeconds=60;db;config;constructor(e){this.config={location:"RESUMABLE-TASK-STORE",createLevelDatabase:Hs,...e},this.db=new Ma({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,r){let n=await hr.computeCid(e),i={id:n,timeout:Date.now()+r*1e3,retryCount:0,task:e};return await this.db.put(n,JSON.stringify(i)),i}async grab(e){let r=[];for await(let[n,i]of this.db.iterator()){let a=JSON.parse(i);if(Date.now()>=a.timeout&&(a.timeout=Date.now()+t.taskTimeoutInSeconds*1e3,a.retryCount++,await this.db.put(a.id,JSON.stringify(a)),r.push(a)),r.length>=e)break}return r}async read(e){let r=await this.db.get(e);if(r)return JSON.parse(r)}async extend(e,r){let n=await this.db.get(e);if(n){let i=JSON.parse(n);i.timeout=Date.now()+r*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 EG(t){return{all:t=t||new Map,on:function(e,r){var n=t.get(e);n?n.push(r):t.set(e,[r])},off:function(e,r){var n=t.get(e);n&&(r?n.splice(n.indexOf(r)>>>0,1):t.set(e,[]))},emit:function(e,r){var n=t.get(e);n&&n.slice().map(function(i){i(r)}),(n=t.get("*"))&&n.slice().map(function(i){i(e,r)})}}}var SG=F(()=>{g()});var AG,Df,kG=F(()=>{"use strict";g();SG();lc();xt();AG="events",Df=class t{emitter=EG();isOpen=!1;errorHandler=e=>{console.error("event log error",e)};maxEventsPerTenant;tenantLogs=new Map;tenantSeqs=new Map;constructor(e={}){this.maxEventsPerTenant=e.maxEventsPerTenant??1e4,e.errorHandler&&(this.errorHandler=e.errorHandler)}async open(){this.isOpen=!0}async close(){this.isOpen=!1,this.emitter.all.clear(),this.tenantLogs.clear(),this.tenantSeqs.clear()}async emit(e,r,n){if(!this.isOpen)return this.errorHandler(new ie(ne.EventLogNotOpenError,"a message emitted when EventLog is closed")),"";let a=(this.tenantSeqs.get(e)??0)+1;this.tenantSeqs.set(e,a);let s=this.tenantLogs.get(e);if(s===void 0&&(s=new Map,this.tenantLogs.set(e,s)),s.set(a,{event:r,indexes:n}),s.size>this.maxEventsPerTenant){let d=s.size-this.maxEventsPerTenant,l=0;for(let c of s.keys()){if(l>=d)break;s.delete(c),l++}}let o=`${e}_${AG}`;return this.emitter.emit(o,{tenant:e,event:r,indexes:n,seq:a}),String(a)}async read(e,r={}){let{cursor:n,limit:i,filters:a}=r,s=n!==void 0?t.parseCursor(n):void 0,o=this.tenantLogs.get(e);if(o===void 0||o.size===0)return{events:[],cursor:n};let d=[],l=i??Number.MAX_SAFE_INTEGER;for(let[u,f]of o)if(!(s!==void 0&&u<=s)&&!(a!==void 0&&a.length>0&&!ir.matchAnyFilter(f.indexes,a))&&(d.push({seq:u,event:f.event,indexes:f.indexes}),d.length>=l))break;let c=d.length>0?d[d.length-1].seq:void 0;return{events:d,cursor:c!==void 0?String(c):n}}static parseCursor(e){let r=Number(e);if(Number.isNaN(r)||r<0)throw new ie(ne.EventLogNotOpenError,`invalid cursor: '${e}'`);return r}async subscribe(e,r,n,i){let a=`${e}_${AG}`,{cursor:s,filters:o}=i??{};if(s!==void 0){let l=t.parseCursor(s),c=[],u=!1,f=y=>{o!==void 0&&o.length>0&&!ir.matchAnyFilter(y.indexes,o)||(u?n({type:"event",cursor:String(y.seq),event:y.event}):c.push({event:y.event,seq:y.seq}))};this.emitter.on(a,f);let h=await this.read(e,{cursor:s,filters:o}),p=h.cursor??s,m=h.cursor!==void 0?Number(h.cursor):l;for(let y of h.events)n({type:"event",cursor:String(y.seq),event:y.event});u=!0;for(let y of c)y.seq>m&&n({type:"event",cursor:String(y.seq),event:y.event});return n({type:"eose",cursor:p}),{id:r,close:async()=>{this.emitter.off(a,f)}}}let d=l=>{o!==void 0&&o.length>0&&!ir.matchAnyFilter(l.indexes,o)||n({type:"event",cursor:String(l.seq),event:l.event})};return this.emitter.on(a,d),{id:r,close:async()=>{this.emitter.off(a,d)}}}async trim(e,r){let n=this.tenantLogs.get(e);if(n!==void 0)if(typeof r=="number")for(let i of n.keys())if(i<r)n.delete(i);else break;else for(let[i,a]of n)(a.indexes.messageTimestamp??"")<r&&n.delete(i)}}});var rg,y5=F(()=>{"use strict";g();Fu();rg=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 r=sn(e),n=await this.nodesPartition.get(r);if(n!==void 0)return this.deserializeNode(JSON.parse(n))}async putNode(e,r){this.ensureInitialized();let n=sn(e),i=this.serializeNode(r);await this.nodesPartition.put(n,JSON.stringify(i))}async deleteNode(e){this.ensureInitialized();let r=sn(e);await this.nodesPartition.delete(r)}async getRoot(){this.ensureInitialized();let e=await this.metaPartition.get("root");if(e!==void 0)return zu(e)}async setRoot(e){this.ensureInitialized(),await this.metaPartition.put("root",sn(e))}ensureInitialized(){if(!this.initialized)throw new Error("SMTStoreLevel not initialized. Call open() first.")}serializeNode(e){return e.type==="internal"?{type:"internal",leftHash:sn(e.leftHash),rightHash:sn(e.rightHash)}:{type:"leaf",keyHash:sn(e.keyHash),valueCid:e.valueCid}}deserializeNode(e){return e.type==="internal"?{type:"internal",leftHash:zu(e.leftHash),rightHash:zu(e.rightHash)}:{type:"leaf",keyHash:zu(e.keyHash),valueCid:e.valueCid}}}});var ng,g5=F(()=>{"use strict";g();Fu();ng=class{store;defaultHashes;constructor(e){this.store=e}async initialize(){await this.store.open(),this.defaultHashes=await Pl()}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 r=await qu(e),n=await uy(r,e),i={type:"leaf",keyHash:r,valueCid:e};await this.store.putNode(n,i);let a=await this.getRoot(),s=await this.insertAtNode(a,r,n,i,0);return await this.store.setRoot(s),s}async delete(e){let r=await qu(e),n=await this.getRoot(),i=await this.deleteAtNode(n,r,0);return await this.store.setRoot(i),i}async has(e){let r=await qu(e),n=await this.getRoot();return this.existsAtNode(n,r,0)}async getProof(e){let r=await qu(e),n=await this.getRoot();return this.generateProof(n,r,0)}async getSubtreeHash(e){let r=await this.getRoot();for(let n=0;n<e.length;n++){if(nn(r,this.defaultHashes[n]))return this.defaultHashes[e.length];let i=await this.store.getNode(r);if(i===void 0||i.type==="leaf")return i!==void 0&&i.type==="leaf"?this.computeSubtreeHashForLeaf(i,n,e):this.defaultHashes[e.length];let a=i;e[n]?r=a.rightHash:r=a.leftHash}return r}async getLeaves(e){let r=await this.getRoot();for(let n=0;n<e.length;n++){if(nn(r,this.defaultHashes[n]))return[];let i=await this.store.getNode(r);if(i===void 0)return[];if(i.type==="leaf")return this.leafMatchesPrefix(i.keyHash,e)?[i.valueCid]:[];let a=i;e[n]?r=a.rightHash:r=a.leftHash}return this.collectLeaves(r,e.length)}async diff(e){let r=await this.getRoot(),n=await e.getRoot();if(nn(r,n))return{onlyLocal:[],onlyRemote:[]};let i=[],a=[];return await this.diffAtNode(r,n,0,this,e,i,a),{onlyLocal:i,onlyRemote:a}}async insertAtNode(e,r,n,i,a){if(a>=fs||nn(e,this.defaultHashes[a]))return n;let s=await this.store.getNode(e);if(s===void 0)return n;if(s.type==="leaf")return nn(s.keyHash,r)?(await this.store.deleteNode(e),n):this.splitLeaves(s,e,i,n,a);let o=s,d=io(r,a),l,c;d?(l=o.leftHash,c=await this.insertAtNode(o.rightHash,r,n,i,a+1)):(l=await this.insertAtNode(o.leftHash,r,n,i,a+1),c=o.rightHash);let u=await xl(l,c);if(!nn(u,e)){let f={type:"internal",leftHash:l,rightHash:c};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async splitLeaves(e,r,n,i,a){let s=a;for(;s<fs&&io(e.keyHash,s)===io(n.keyHash,s);)s++;if(s>=fs)return i;let o=io(e.keyHash,s),d,l;o?(d=i,l=r):(d=r,l=i);let c=await xl(d,l);await this.store.putNode(c,{type:"internal",leftHash:d,rightHash:l});for(let u=s-1;u>=a;u--){let f=io(e.keyHash,u),h=this.defaultHashes[u+1],p,m;f?(p=h,m=c):(p=c,m=h),c=await xl(p,m),await this.store.putNode(c,{type:"internal",leftHash:p,rightHash:m})}return c}async deleteAtNode(e,r,n){if(n>=fs)return this.defaultHashes[fs];if(nn(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 nn(i.keyHash,r)?(await this.store.deleteNode(e),this.defaultHashes[n]):e;let a=i,s=io(r,n),o,d;if(s?(o=a.leftHash,d=await this.deleteAtNode(a.rightHash,r,n+1)):(o=await this.deleteAtNode(a.leftHash,r,n+1),d=a.rightHash),nn(o,this.defaultHashes[n+1])&&nn(d,this.defaultHashes[n+1]))return await this.store.deleteNode(e),this.defaultHashes[n];let l=nn(o,this.defaultHashes[n+1]),c=nn(d,this.defaultHashes[n+1]);if(l||c){let f=l?d:o,h=await this.store.getNode(f);if(h!==void 0&&h.type==="leaf")return await this.store.deleteNode(e),f}let u=await xl(o,d);if(!nn(u,e)){let f={type:"internal",leftHash:o,rightHash:d};await this.store.putNode(u,f),await this.store.deleteNode(e)}return u}async existsAtNode(e,r,n){if(n>=fs||nn(e,this.defaultHashes[n]))return!1;let i=await this.store.getNode(e);if(i===void 0)return!1;if(i.type==="leaf")return nn(i.keyHash,r);let a=i;return io(r,n)?this.existsAtNode(a.rightHash,r,n+1):this.existsAtNode(a.leftHash,r,n+1)}async generateProof(e,r,n){if(n>=fs)return{siblings:[],leafNode:void 0,depth:n};if(nn(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=io(r,n),o,d;s?(o=a.rightHash,d=a.leftHash):(o=a.leftHash,d=a.rightHash);let l=await this.generateProof(o,r,n+1);return l.siblings.unshift(d),l}async computeSubtreeHashForLeaf(e,r,n){for(let i=r;i<n.length;i++)if(io(e.keyHash,i)!==n[i])return this.defaultHashes[n.length];return await uy(e.keyHash,e.valueCid)}leafMatchesPrefix(e,r){for(let n=0;n<r.length;n++)if(io(e,n)!==r[n])return!1;return!0}async collectLeaves(e,r){if(r>=fs||nn(e,this.defaultHashes[r]))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,r+1),s=await this.collectLeaves(i.rightHash,r+1);return[...a,...s]}async diffAtNode(e,r,n,i,a,s,o){if(nn(e,r)||n>=fs)return;let d=nn(e,this.defaultHashes[n]),l=nn(r,this.defaultHashes[n]);if(d&&!l){let f=await a.collectLeaves(r,n);o.push(...f);return}if(!d&&l){let f=await i.collectLeaves(e,n);s.push(...f);return}let c=await i.store.getNode(e),u=await a.store.getNode(r);if(c?.type==="leaf"&&u?.type==="leaf"){nn(c.keyHash,u.keyHash)?c.valueCid!==u.valueCid&&(s.push(c.valueCid),o.push(u.valueCid)):(s.push(c.valueCid),o.push(u.valueCid));return}if(c?.type==="leaf"){let f=await a.collectLeaves(r,n),h=c.valueCid;new Set(f).has(h)||s.push(h);for(let m of f)m!==h&&o.push(m);return}if(u?.type==="leaf"){let f=await i.collectLeaves(e,n),h=u.valueCid;new Set(f).has(h)||o.push(h);for(let m of f)m!==h&&s.push(m);return}if(c?.type==="internal"&&u?.type==="internal"){await this.diffAtNode(c.leftHash,u.leftHash,n+1,i,a,s,o),await this.diffAtNode(c.rightHash,u.rightHash,n+1,i,a,s,o);return}if(c===void 0){let f=await a.collectLeaves(r,n);o.push(...f)}if(u===void 0){let f=await i.collectLeaves(e,n);s.push(...f)}}}});var Rf,_G=F(()=>{"use strict";g();Fu();y5();g5();Ef();Rf=class{config;db;globalTrees=new Map;protocolTrees=new Map;constructor(e){this.config={location:"STATEINDEX",createLevelDatabase:Hs,...e}}async open(){this.db=new Ma({location:this.config.location,createLevelDatabase:this.config.createLevelDatabase,keyEncoding:"utf8"}),await this.db.open(),await Pl()}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,r,n){await(await this.getGlobalTree(e)).insert(r);let a=n.protocol;a!==void 0&&await(await this.getProtocolTree(e,a)).insert(r),await this.storeIndexes(e,r,n)}async delete(e,r){let n=await this.getGlobalTree(e);for(let i of r){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,r){return(await this.getProtocolTree(e,r)).getRoot()}async getSubtreeHash(e,r){return(await this.getGlobalTree(e)).getSubtreeHash(r)}async getProtocolSubtreeHash(e,r,n){return(await this.getProtocolTree(e,r)).getSubtreeHash(n)}async getLeaves(e,r){return(await this.getGlobalTree(e)).getLeaves(r)}async getProtocolLeaves(e,r,n){return(await this.getProtocolTree(e,r)).getLeaves(n)}getGlobalTree(e){let r=this.globalTrees.get(e);return r!==void 0||(r=this.createTree(this.db,[e,"global"]),this.globalTrees.set(e,r)),r}getProtocolTree(e,r){let n=`${e}\0${r}`,i=this.protocolTrees.get(n);return i!==void 0||(i=this.createTree(this.db,[e,"proto",r]),this.protocolTrees.set(n,i)),i}async createTree(e,r){let n=e;for(let s of r)n=await n.partition(s);let i=new rg(n),a=new ng(i);return await a.initialize(),a}async storeIndexes(e,r,n){let i=await this.getMetaPartition(e),a={protocol:n.protocol};await i.put(r,JSON.stringify(a))}async getStoredIndexes(e,r){let i=await(await this.getMetaPartition(e)).get(r);if(i!==void 0)return JSON.parse(i)}async deleteStoredIndexes(e,r){await(await this.getMetaPartition(e)).delete(r)}async getMetaPartition(e){return(await this.db.partition(e)).partition("meta")}}});var jE,TG=F(()=>{"use strict";g();Fu();jE=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(sn(e))}async putNode(e,r){this.nodes.set(sn(e),r)}async deleteNode(e){this.nodes.delete(sn(e))}async getRoot(){return this.root}async setRoot(e){this.root=e}get size(){return this.nodes.size}}});var iye,ME,IG=F(()=>{"use strict";g();Pm();tl();hu();Jo();xS();kn();Rc();ox();dx();Lo();s1();Jx();Yx();Jn();nx();mv();ix();s2();Us();Di();Lb();Jl();us();wn();i0();lr();jm();iye={protocol:"http://test-protocol.xyz",published:!1,types:{testRecord:{}},structure:{testRecord:{}}},ME=class t{static async generatePersona(e){let r=e?.did;r||(r=`did:example:${t.randomString(32)}`);let n=t.randomString(10),i=e?.keyId??`${r}#${n}`,a=e?.keyPair??await La.generateKeyPair(),s=e?.encryptionKeyPair;if(!s){let d=await Gt.generateKey();s={publicJwk:await Gt.getPublicKey({key:d}),privateJwk:d}}return{did:r,keyId:i,keyPair:a,encryptionKeyPair:s,signer:new Zd({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:`${r}#${i}`})}}static async installDefaultTestProtocol(e,r){let n=await Pa.create({definition:iye,signer:ut.createSigner(r)}),i=await e.processMessage(r.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 r=e?.author??await t.generatePersona(),n=e?.protocolDefinition;if(!n){let o="record"+t.randomString(10);n={protocol:t.randomString(20),published:e?.published??!1,types:{},structure:{}},n.types[o]={schema:"test-object",dataFormats:["text/plain"]},n.structure[o]={}}let i=ut.createSigner(r),a={messageTimestamp:e?.messageTimestamp,definition:n,signer:i,permissionGrantId:e?.permissionGrantId,delegatedGrant:e?.delegatedGrant},s=await Pa.create(a);return{author:r,message:s.message,protocolsConfigure:s}}static async generateProtocolsQuery(e){let r=e?.author??await t.generatePersona(),n=ut.createSigner(r),i={messageTimestamp:e?.messageTimestamp,filter:e?.filter,signer:n,permissionGrantId:e?.permissionGrantId};tr(i);let a=await xa.create(i);return{author:r,message:a.message,protocolsQuery:a}}static async generateGrantCreate(e){let r=e?.author??await t.generatePersona(),n=e?.grantedTo??await t.generatePersona(),i=e?.dateExpires??St.createOffsetTimestamp({seconds:10}),a=e?.scope??{interface:be.Messages,method:ge.Read},s=ut.createSigner(r),o=n.did,d={signer:s,grantedTo:o,dateExpires:i,scope:a,description:e?.description??t.randomString(10),delegated:e?.delegated??!1,requestId:e?.requestId,conditions:e?.conditions},l=await dt.createGrant(d);return{dataStream:Yt.fromBytes(l.permissionGrantBytes),recordsWrite:l.recordsWrite,dataBytes:l.permissionGrantBytes,message:l.recordsWrite.message,dataEncodedMessage:l.dataEncodedMessage}}static async generateRecordsWrite(e){let r=e?.author??await t.generatePersona(),n=ut.createSigner(r),i=ut.createSigners(e?.attesters??[]),a=e?.dataCid,s=e?.dataSize,o,d;a===void 0&&s===void 0&&(o=e?.data??t.randomBytes(32),d=Yt.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://${t.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},c=await At.create(l),u=c.message;return{author:r,message:u,dataCid:a,dataSize:s,dataBytes:o,dataStream:d,recordsWrite:c}}static async generateProtocolEncryptedRecordsWrite(e){let{plaintextBytes:r,author:n,recipient:i,protocolDefinition:a,protocolPath:s,protocolParentContextId:o,protocolContextDerivingRootKeyId:d,protocolContextDerivedPublicKeyJwk:l}=e,c=t.randomBytes(12),u=t.randomBytes(32),{ciphertext:f,tag:h}=await Bi.aeadEncrypt(ii.A256GCM,u,c,r),p=s.split("/"),m=p[p.length-1],{message:y,dataStream:b,recordsWrite:w}=await t.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}),S={initializationVector:c,key:u,authenticationTag:h,keyEncryptionInputs:[]};if(e.encryptSymmetricKeyWithProtocolPathDerivedKey){let k=a.structure;for(let C of p)k=k[C];let T=k.$encryption?.publicKeyJwk,K={publicKeyId:k.$encryption?.rootKeyId,publicKey:T,derivationScheme:Ht.ProtocolPath};S.keyEncryptionInputs.push(K)}if(e.encryptSymmetricKeyWithProtocolContextDerivedKey){let k;if(o===void 0){let T={rootKeyId:n.keyId,derivationScheme:Ht.ProtocolContext,derivedPrivateKey:n.encryptionKeyPair.privateJwk},D=await At.getEntryId(n.did,y.descriptor),K=Te.constructKeyDerivationPathUsingProtocolContextScheme(D),C=await $s.derivePublicKey(T,K);k={publicKeyId:n.keyId,publicKey:C,derivationScheme:Ht.ProtocolContext}}else{if(d===void 0||l===void 0)throw new Error("`protocolContextDerivingRootKeyId` and `protocolContextDerivedPublicKeyJwk` must both be defined if `protocolContextId` is given");k={publicKeyId:d,publicKey:l,derivationScheme:Ht.ProtocolContext}}S.keyEncryptionInputs.push(k)}return await w.encryptSymmetricEncryptionKey(S),await w.sign({signer:ut.createSigner(n)}),{message:y,dataStream:b,recordsWrite:w,encryptedDataBytes:f,encryptionInput:S}}static async generateFromRecordsWrite(e){let r=e.existingWrite.message,n=St.getCurrentTimestamp(),i=!(e.published??r.descriptor.published),a=e.datePublished??(i?n:void 0),s=e.data??t.randomBytes(32),o=Yt.fromBytes(s),d={recordsWriteMessage:e.existingWrite.message,data:s,published:i,datePublished:a,messageTimestamp:e.messageTimestamp,protocolRole:e.protocolRole,tags:e.tags,signer:ut.createSigner(e.author)},l=await At.createFrom(d);return{message:l.message,recordsWrite:l,dataBytes:s,dataStream:o}}static async generateRecordsQuery(e){let r=e?.author,n=e?.anonymous??!1;if(n&&r)throw new Error("Cannot have `author` and be anonymous at the same time.");r===void 0&&!n&&(r=await t.generatePersona());let i;r!==void 0&&(i=ut.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:t.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole};tr(a);let o=(await ha.create(a)).message;return{author:r,message:o}}static async generateRecordsSubscribe(e){let r=e?.author,n=e?.anonymous??!1;if(n&&r)throw new Error("Cannot have `author` and be anonymous at the same time.");r===void 0&&!n&&(r=await t.generatePersona());let i;r!==void 0&&(i=ut.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:t.randomString(10)},dateSort:e?.dateSort,pagination:e?.pagination,protocolRole:e?.protocolRole,cursor:e?.cursor};tr(a);let o=(await Sa.create(a)).message;return{author:r,message:o}}static async generateRecordsCount(e){let r=e?.author,n=e?.anonymous??!1;if(n&&r)throw new Error("Cannot have `author` and be anonymous at the same time.");r===void 0&&!n&&(r=await t.generatePersona());let i;r!==void 0&&(i=ut.createSigner(r));let a={messageTimestamp:e?.messageTimestamp,signer:i,filter:e?.filter??{schema:t.randomString(10)},protocolRole:e?.protocolRole};tr(a);let o=(await ad.create(a)).message;return{author:r,message:o}}static async generateRecordsDelete(e){let r=e?.author??await t.generateDidKeyPersona(),n=await Ea.create({recordId:e?.recordId??await t.randomCborSha256Cid(),protocolRole:e?.protocolRole,signer:ut.createSigner(r)});return{author:r,recordsDelete:n,message:n.message}}static async generateMessagesSubscribe(e){let r=e?.author??await t.generatePersona(),n=ut.createSigner(r),i={filters:e?.filters,messageTimestamp:e?.messageTimestamp,permissionGrantId:e?.permissionGrantId,cursor:e?.cursor,signer:n};tr(i);let a=await ld.create(i),s=a.message;return{author:r,messagesSubscribe:a,message:s}}static async generateMessagesRead(e){let r=e?.author??await t.generatePersona(),i={signer:ut.createSigner(r),messageCid:e.messageCid,permissionGrantId:e.permissionGrantId},a=await dd.create(i);return{author:r,messagesRead:a,message:a.message}}static generateAuthorization(){return{signature:t.generateAuthorizationSignature()}}static generateAuthorizationSignature(){return{payload:"anyPayload",signatures:[{protected:"anyProtectedHeader",signature:"anySignature"}]}}static async randomSignatureString(){let e=await Cg.generateKeyPair(),r=await Cg.sign(t.randomBytes(32),e.privateJwk);return De.bytesToBase64Url(r)}static randomString(e){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="";for(let i=0;i<e;i++)n+=r.charAt(Math.floor(Math.random()*r.length));return n}static randomBytes(e){let r=new Uint8Array(e);for(let n=0;n<e;n++)r[n]=Math.floor(Math.random()*256);return r}static async randomCborSha256Cid(){let e=t.randomBytes(32),r=await Bn.digest(e);return(await er.createV1(pu,r)).toString()}static randomInt(e,r){return Math.floor(Math.random()*(r-e)+e)}static randomTimestamp(e){let{year:r,month:n,day:i,hour:a,minute:s,second:o,millisecond:d,microsecond:l}=e||{};return St.createTimestamp({year:r||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:d||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 nb.create(),r=await nb.getSigningMethod({didDocument:e.document}),n=r.id,i=await e.export(),a={publicJwk:r.publicKeyJwk,privateJwk:i.privateKeys[0]},s=await Gt.generateKey(),d={publicJwk:await Gt.getPublicKey({key:s}),privateJwk:s};return{did:e.uri,keyId:n,keyPair:a,encryptionKeyPair:d,signer:new Zd({privateJwk:a.privateJwk,algorithm:a.privateJwk.alg,keyId:n})}}}});var KE,DG=F(()=>{"use strict";g();us();KE=class t{static pollRetrySleep=20;static pollTimeout=2e3;static async pollUntilSuccessOrTimeout(e,r=t.pollRetrySleep,n=t.pollTimeout){let i=Date.now();for(;;)try{return await e()}catch{if(Date.now()-i>=n)throw new Error("Operation timed out");await St.sleep(r)}}}});var RG={};ar(RG,{AllowAllTenantGate:()=>ly,BlockstoreLevel:()=>Sf,Cid:()=>hr,ContentEncryptionAlgorithm:()=>ii,CoreProtocolRegistry:()=>dy,DataStoreLevel:()=>_f,DataStream:()=>Yt,DateSort:()=>Kt,Dwn:()=>Yy,DwnConstant:()=>ma,DwnError:()=>ie,DwnErrorCode:()=>ne,DwnInterfaceName:()=>be,DwnMethodName:()=>ge,Encoder:()=>De,Encryption:()=>Bi,EventEmitterEventLog:()=>Df,HdKey:()=>$s,IndexLevel:()=>Ah,Jws:()=>ut,KeyAgreementAlgorithm:()=>n0,KeyDerivationScheme:()=>Ht,LevelWrapper:()=>Ma,Message:()=>we,MessageStoreLevel:()=>Tf,MessagesRead:()=>dd,MessagesSubscribe:()=>ld,MessagesSync:()=>Gu,PERMISSIONS_REVOCATION_PATH:()=>gP,PermissionConditionPublication:()=>Mm,PermissionGrant:()=>Ir,PermissionRequest:()=>cd,PermissionsProtocol:()=>dt,Poller:()=>KE,PrivateKeySigner:()=>Zd,ProtocolRecordLimitStrategy:()=>Hl,Protocols:()=>md,ProtocolsConfigure:()=>Pa,ProtocolsQuery:()=>xa,Records:()=>Te,RecordsCount:()=>ad,RecordsDelete:()=>Ea,RecordsQuery:()=>ha,RecordsRead:()=>gd,RecordsSubscribe:()=>Sa,RecordsWrite:()=>At,ResumableTaskStoreLevel:()=>If,SMTStoreLevel:()=>rg,SMTStoreMemory:()=>jE,SMT_DEPTH:()=>fs,Secp256k1:()=>La,Secp256r1:()=>Jd,SortDirection:()=>It,SparseMerkleTree:()=>ng,StateIndexLevel:()=>Rf,TestDataGenerator:()=>ME,Time:()=>St,ZERO_HASH:()=>ux,authenticate:()=>pn,createLevelDatabase:()=>Hs,executeUnlessAborted:()=>Gn,getBit:()=>io,getDefaultHashes:()=>II,getRuleSetAtPath:()=>yd,hashChildren:()=>xl,hashEquals:()=>nn,hashKey:()=>qu,hashLeaf:()=>uy,hashToHex:()=>sn,hexToHash:()=>zu,initDefaultHashes:()=>Pl,isCrossProtocolRef:()=>tf,parseCrossProtocolRef:()=>zs});var Yn=F(()=>{"use strict";g();Tg();No();kI();lT();_I();il();nx();ix();hu();jm();Xz();B0();xt();lr();kn();dx();i0();Us();lE();Rc();wr();ox();DI();nc();TI();Lo();s1();Yp();Jx();Yx();Jn();mv();RR();s2();Lb();AA();Vc();us();uT();hp();uE();aG();p5();Ef();PG();xG();kG();_G();g5();y5();TG();Fu();IG();DG()});var qE=_e((DGe,BG)=>{g();var sg=1e3,og=sg*60,ag=og*60,kh=ag*24,oye=kh*7,aye=kh*365.25;BG.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return cye(t);if(r==="number"&&isFinite(t))return e.long?lye(t):dye(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function cye(t){if(t=String(t),!(t.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(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*aye;case"weeks":case"week":case"w":return r*oye;case"days":case"day":case"d":return r*kh;case"hours":case"hour":case"hrs":case"hr":case"h":return r*ag;case"minutes":case"minute":case"mins":case"min":case"m":return r*og;case"seconds":case"second":case"secs":case"sec":case"s":return r*sg;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function dye(t){var e=Math.abs(t);return e>=kh?Math.round(t/kh)+"d":e>=ag?Math.round(t/ag)+"h":e>=og?Math.round(t/og)+"m":e>=sg?Math.round(t/sg)+"s":t+"ms"}function lye(t){var e=Math.abs(t);return e>=kh?LE(t,e,kh,"day"):e>=ag?LE(t,e,ag,"hour"):e>=og?LE(t,e,og,"minute"):e>=sg?LE(t,e,sg,"second"):t+" ms"}function LE(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});g();g();Yn();Yn();var Re=(c=>(c[c.MessagesRead=be.Messages+ge.Read]="MessagesRead",c[c.MessagesSubscribe=be.Messages+ge.Subscribe]="MessagesSubscribe",c[c.MessagesSync=be.Messages+ge.Sync]="MessagesSync",c[c.ProtocolsConfigure=be.Protocols+ge.Configure]="ProtocolsConfigure",c[c.ProtocolsQuery=be.Protocols+ge.Query]="ProtocolsQuery",c[c.RecordsDelete=be.Records+ge.Delete]="RecordsDelete",c[c.RecordsQuery=be.Records+ge.Query]="RecordsQuery",c[c.RecordsRead=be.Records+ge.Read]="RecordsRead",c[c.RecordsSubscribe=be.Records+ge.Subscribe]="RecordsSubscribe",c[c.RecordsWrite=be.Records+ge.Write]="RecordsWrite",c))(Re||{}),Id={[Re.MessagesRead]:dd,[Re.MessagesSubscribe]:ld,[Re.MessagesSync]:Gu,[Re.ProtocolsConfigure]:Pa,[Re.ProtocolsQuery]:xa,[Re.RecordsDelete]:Ea,[Re.RecordsQuery]:ha,[Re.RecordsRead]:gd,[Re.RecordsSubscribe]:Sa,[Re.RecordsWrite]:At};g();Jo();Er();var Cf=class extends cE{constructor({agent:r,db:n,location:i,ttl:a}){super({db:n,location:i,ttl:a});this._resolving=new Map;this._agent=r}get agent(){if(!this._agent)throw new Error("Agent not initialized");return this._agent}set agent(r){this._agent=r}async get(r){try{let n=await this.cache.get(r),i=JSON.parse(n);if(!this._resolving.has(r)&&Date.now()>=i.ttlMillis){this._resolving.set(r,!0);let a=await this.agent.did.get({didUri:r,tenant:this.agent.agentDid.uri});if(typeof a<"u")try{let s=await this.agent.did.resolve(r);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(d){d.message&&!d.message.includes("No changes detected, update aborted")&&Rs.error(`Error updating DID: ${d.message}`)}}}finally{this._resolving.delete(r)}else this._resolving.delete(r),this.cache.nextTick(()=>this.cache.del(r))}return i.value}catch(n){if(n.notFound)return;throw n}}};g();Yn();g();Jo();Yn();async function pb(t,e){let r=await e.dereference(`${t}#dwn`);if(r.dereferencingMetadata.error)throw new Error(`Failed to dereference '${t}#dwn': ${r.dereferencingMetadata.error}`);if(B6.isDwnDidService(r.contentStream)){let{serviceEndpoint:n}=r.contentStream,i=typeof n=="string"?[n]:Array.isArray(n)&&n.every(a=>typeof a=="string")?n:[];if(i.length>0)return i}return[]}function lGe(t){return we.getAuthor(t)}function uGe(t){return ut.decodePlainObjectPayload(t.authorization.signature)?.protocolRole}function Ll(t){return!t||typeof t!="object"||t===null?!1:"message"in t&&typeof t.message=="object"&&t.message!==null&&"descriptor"in t.message&&typeof t.message.descriptor=="object"&&t.message.descriptor!==null&&"interface"in t.message.descriptor&&t.message.descriptor.interface===be.Records&&"method"in t.message.descriptor&&t.message.descriptor.method===ge.Write}function sye(t){return we.getCid(t)}async function fGe(t,e){let r=e===Kt.CreatedAscending||e===Kt.CreatedDescending?t.descriptor.dateCreated:t.descriptor.datePublished;if(r===void 0)throw new Error("The dateCreated or datePublished property is missing from the record descriptor.");return{messageCid:await sye(t),value:r}}function pGe(t,e=3e3,r=3e5,n){let i=Date.now()+r,a=null,s=!0;return new Promise((o,d)=>{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 c=i-Date.now();if(c<=0){s=!1,console.log("Polling stopped: TTL reached"),o(null);return}console.log(`Polling... (Remaining time: ${Math.ceil(c/1e3)}s)`);try{let u=await t();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),d(u)}s&&(a=setTimeout(l,e))}l()})}function hb(t,e){return t.endsWith("/")&&(t=t.slice(0,-1)),e.startsWith("/")&&(e=e.slice(1)),`${t}/${e}`}var CG=class{constructor({didResolver:e,rpcClient:r}){this._didResolver=e,this._rpcClient=r}async recordsQuery(e,r){let n=await ha.create({filter:r.filter,dateSort:r.dateSort,pagination:r.pagination,messageTimestamp:r.messageTimestamp});return await this.sendRequest(e,n.message)}async recordsRead(e,r){let n=await gd.create({filter:r.filter,messageTimestamp:r.messageTimestamp});return await this.sendRequest(e,n.message)}async recordsSubscribe(e,r,n){let i=await Sa.create({filter:r.filter,dateSort:r.dateSort,pagination:r.pagination,messageTimestamp:r.messageTimestamp});return await this.sendRequest(e,i.message,void 0,n)}async recordsCount(e,r){let n=await ad.create({filter:r.filter,messageTimestamp:r.messageTimestamp});return await this.sendRequest(e,n.message)}async protocolsQuery(e,r){let n=await xa.create({filter:r?.filter,messageTimestamp:r?.messageTimestamp});return await this.sendRequest(e,n.message)}async sendRequest(e,r,n,i){let a=await pb(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 c=new URL(o);c.protocol=c.protocol==="http:"?"ws:":"wss:",o=c.toString()}return await this._rpcClient.sendDwnRequest({dwnUrl:o,targetDid:e,message:r,data:n,subscriptionHandler:i})}catch(d){s.push({url:o,message:d instanceof Error?d.message:"Unknown error"})}throw new Error(`AnonymousDwnApi: Failed to send request to '${e}': ${JSON.stringify(s)}`)}};g();var ig=class{constructor({did:e,metadata:r}){this.did=e,this.metadata=r}async export(){return{portableDid:await this.did.export(),metadata:{...this.metadata}}}};g();wn();var w5={"AES-GCM":{implementation:$m,names:["A128GCM","A192GCM","A256GCM"],operations:["bytesToPrivateKey","decrypt","encrypt","generateKey"]},"AES-KW":{implementation:Bm,names:["A128KW","A192KW","A256KW"],operations:["bytesToPrivateKey","generateKey","privateKeyToBytes","wrapKey","unwrapKey"]},Ed25519:{implementation:Fc,names:["Ed25519"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},HKDF:{implementation:fP,names:["HKDF-256","HKDF-384","HKDF-512"],operations:["deriveKey","deriveKeyBytes"]},PBKDF2:{implementation:hP,names:["PBES2-HS256+A128KW","PBES2-HS384+A192KW","PBES2-HS512+A256KW"],operations:["deriveKey","deriveKeyBytes"]},secp256k1:{implementation:oc,names:["ES256K","secp256k1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},secp256r1:{implementation:oc,names:["ES256","secp256r1"],operations:["bytesToPrivateKey","bytesToPublicKey","generateKey","sign","verify"]},"SHA-256":{implementation:_u,names:["SHA-256"],operations:["digest"]},X25519:{implementation:Iu,names:["X25519"],operations:["bytesToPrivateKey","generateKey"]}},yo=class{constructor(){this._algorithmInstances=new Map}async bytesToPrivateKey({algorithm:e,privateKeyBytes:r}){let n=this.getAlgorithmName({algorithm:e});return await this.getAlgorithm({algorithm:n}).bytesToPrivateKey({algorithm:e,privateKeyBytes:r})}async bytesToPublicKey({algorithm:e,publicKeyBytes:r}){let n=this.getAlgorithmName({algorithm:e});return await this.getAlgorithm({algorithm:n}).bytesToPublicKey({algorithm:e,publicKeyBytes:r})}async decrypt(e){let r=this.getAlgorithmName({key:e.key});return await this.getAlgorithm({algorithm:r}).decrypt(e)}async deriveKey(e){let r=this.getAlgorithmName({algorithm:e.algorithm}),n=this.getAlgorithm({algorithm:r}),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 Fe(Le.AlgorithmNotSupported,`The specified "algorithm" is not supported: ${e.algorithm}`)}let a=+(i.match(/\d+/)?.[0]??-1);if(a===-1)throw new Fe(Le.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 r=this.getAlgorithmName({algorithm:e.algorithm});return await this.getAlgorithm({algorithm:r}).deriveKeyBytes(e)}async digest({algorithm:e,data:r}){return await this.getAlgorithm({algorithm:e}).digest({algorithm:e,data:r})}async encrypt(e){let r=this.getAlgorithmName({key:e.key});return await this.getAlgorithm({algorithm:r}).encrypt(e)}async generateKey(e){let r=this.getAlgorithmName({algorithm:e.algorithm}),i=await this.getAlgorithm({algorithm:r}).generateKey({algorithm:e.algorithm});return i.kid??=await vt({jwk:i}),i}async getPublicKey({key:e}){let r=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:r}).getPublicKey({key:e})}async privateKeyToBytes({privateKey:e}){let r=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:r}).privateKeyToBytes({privateKey:e})}async publicKeyToBytes({publicKey:e}){let r=this.getAlgorithmName({key:e});return await this.getAlgorithm({algorithm:r}).publicKeyToBytes({publicKey:e})}async sign({key:e,data:r}){let n=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:n}).sign({data:r,key:e})}async unwrapKey(e){let r=this.getAlgorithmName({key:e.decryptionKey});return await this.getAlgorithm({algorithm:r}).unwrapKey(e)}async verify({key:e,signature:r,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:r,data:n})}async wrapKey(e){let r=this.getAlgorithmName({key:e.encryptionKey});return await this.getAlgorithm({algorithm:r}).wrapKey(e)}getAlgorithm({algorithm:e}){let r=w5[e]?.implementation;if(!r)throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported: ${e}`);return this._algorithmInstances.has(r)||this._algorithmInstances.set(r,new r),this._algorithmInstances.get(r)}getAlgorithmName({algorithm:e,key:r}){let n=r?.alg??e,i=r?.crv;for(let a of Object.keys(w5)){let s=w5[a].names;if(n&&s.includes(n))return a;if(i&&s.includes(i))return a}throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported based on provided input: alg=${n}, crv=${i}. Please check the documentation for the list of supported algorithms.`)}};g();Jo();wn();g();Er();Jo();g();var NE={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:{}}},ql={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"}}}}},$G={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();wn();var ki="^",UE=class extends Gc{constructor(){super(),this._predefinedKeys=new Map,this._keyGenerator=this._predefinedKeys.keys()}async addPredefinedKeys({privateKeys:e}){let r={};for(let n of e){n.kid??=await vt({jwk:n});let i=await this.getKeyUri({key:n});r[i]=n}this._predefinedKeys=new Map(Object.entries(r)),this._keyGenerator=this._predefinedKeys.keys()}async exportKey({keyUri:e}){let r=this._predefinedKeys.get(e);if(!r)throw new Error(`DeterministicKeyGenerator.exportKey: Key not found: ${e}`);return r}async generateKey(e){let{value:r,done:n}=this._keyGenerator.next();if(n)throw new Error("Ran out of predefined keys");return r}async getPublicKey({keyUri:e}){let r=this._predefinedKeys.get(e);if(!r)throw new Error(`DeterministicKeyGenerator.getPublicKey: Key not found: ${e}`);let{d:n,...i}=r;return i}async sign({keyUri:e,data:r}){let n=this._predefinedKeys.get(e);if(!n)throw new Error(`DeterministicKeyGenerator.sign: Key not found: ${e}`);return await wi.sign({data:r,key:n})}};async function Dd({agent:t,tenant:e,didUri:r}){if(e)return e;if(t.agentDid)return t.agentDid.uri;if(!r)throw new Error("Failed to determine tenant DID: 'agent.agentDid', 'tenant', and 'didUri' are undefined");return r}g();var mb=An(qE(),1);Er();Yn();var $f=class{constructor(){this.name="DwnDataStore";this._cache=new cs.default({ttl:(0,mb.default)("15 minutes"),max:100});this._index=new cs.default({ttl:(0,mb.default)("21 days"),max:1e3});this._protocolInitializedCache=new cs.default({ttl:(0,mb.default)("21 days"),max:1e3});this._tenantEncryptionActive=new cs.default({ttl:(0,mb.default)("21 days"),max:1e3});this._recordProperties={dataFormat:"application/json",protocol:"",protocolPath:""}}async delete({id:e,agent:r,tenant:n}){let i=await Dd({agent:r,tenant:n,didUri:e}),a=await this.lookupRecordId({id:e,tenantDid:i,agent:r});if(!a)return!1;let{reply:{status:s}}=await r.dwn.processRequest({author:i,target:i,messageType:Re.RecordsDelete,messageParams:{recordId:a}});if(s.code===202)return this._index.delete(`${i}${ki}${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:r,tenant:n,useCache:i=!1}){let a=await Dd({agent:r,tenant:n,didUri:e}),s=await this.lookupRecordId({id:e,tenantDid:a,agent:r});if(s)return await this.getRecord({recordId:s,tenantDid:a,agent:r,useCache:i})}async list({agent:e,tenant:r}){let n=await Dd({tenant:r,agent:e});return await this.getAllRecords({agent:e,tenantDid:n})}async set({id:e,data:r,tenant:n,agent:i,preventDuplicates:a=!0,updateExisting:s=!1,useCache:o=!1}){let d=await Dd({agent:i,tenant:n,didUri:e});await this.initialize({tenant:d,agent:i});let l={...this._recordProperties};if(s){let p=await this.getExistingRecordEntry({id:e,tenantDid:d,agent:i});if(!p)throw new Error(`${this.name}: Update failed due to missing entry for: ${e}`);l.recordId=p.recordsWrite.recordId,l.dateCreated=p.recordsWrite.descriptor.dateCreated}else if(a&&await this.lookupRecordId({id:e,tenantDid:d,agent:i}))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${e}`);let c=he.object(r).toUint8Array(),u=this.isEncryptionActive(d),{message:f,reply:{status:h}}=await i.dwn.processRequest({author:d,target:d,messageType:Re.RecordsWrite,messageParams:{...this._recordProperties,...l},dataStream:new Blob([c],{type:"application/json"}),...u?{encryption:!0}:{}});if(!(f&&h.code===202))throw new Error(`${this.name}: Failed to write data to store for ${e}: ${h.detail}`);this._index.set(`${d}${ki}${e}`,f.recordId),o&&this._cache.set(f.recordId,r)}async initialize({tenant:e,agent:r}){let n=await Dd({agent:r,tenant:e});if(this._protocolInitializedCache.has(n))return;let{reply:{status:i,entries:a}}=await r.dwn.processRequest({author:n,target:n,messageType:Re.ProtocolsQuery,messageParams:{filter:{protocol:this._recordProtocolDefinition.protocol}}});if(i.code!==200)throw new Error(`Failed to query for protocols: ${i.code} - ${i.detail}`);if(a?.length===0)await this.installProtocol(n,r);else if(this.encryptionRequired&&!this._tenantEncryptionActive.has(n)){let s=a[0].descriptor?.definition,o=Object.keys(s?.structure??{})[0],d=!!(o&&s?.structure[o]?.$encryption);this._tenantEncryptionActive.set(n,d)}this._protocolInitializedCache.set(n,!0)}get encryptionRequired(){return Object.values(this._recordProtocolDefinition.types).some(e=>e.encryptionRequired===!0)}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:r,agent:n,useCache:i}){if(i){let d=this._cache.get(e);if(d)return d}let a=this.isEncryptionActive(r),{reply:s}=await n.dwn.processRequest({author:r,target:r,messageType:Re.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 Dm.consumeToJson({readableStream:s.entry.data});return i&&this._cache.set(e,o),o}async installProtocol(e,r){let n=this._recordProtocolDefinition,i=!1;if(this.encryptionRequired){let s=await r.dwn.getEncryptionKeyDeriver(e);n=await md.deriveAndInjectPublicEncryptionKeys(n,s),i=!0}this._tenantEncryptionActive.set(e,i);let{reply:{status:a}}=await r.dwn.processRequest({author:e,target:e,messageType:Re.ProtocolsConfigure,messageParams:{definition:n}});if(a.code!==202)throw new Error(`Failed to install protocol: ${a.code} - ${a.detail}`)}async lookupRecordId({id:e,tenantDid:r,agent:n}){let i=this._index.get(`${r}${ki}${e}`,{updateAgeOnGet:!0});return i||(await this.getAllRecords({agent:n,tenantDid:r}),i=this._index.get(`${r}${ki}${e}`)),i}async getExistingRecordEntry({id:e,tenantDid:r,agent:n}){let i=await this.lookupRecordId({id:e,tenantDid:r,agent:n});if(i){let{reply:a}=await n.dwn.processRequest({author:r,target:r,messageType:Re.RecordsRead,messageParams:{filter:{recordId:i}}});return a.entry}}},Bf=class{constructor(){this.name="InMemoryDataStore";this.store=new Map}async delete({id:e,agent:r,tenant:n}){let i=await Dd({agent:r,tenant:n,didUri:e});return this.store.has(`${i}${ki}${e}`)?(this.store.delete(`${i}${ki}${e}`),!0):!1}async get({id:e,agent:r,tenant:n}){let i=await Dd({agent:r,tenant:n,didUri:e});return this.store.get(`${i}${ki}${e}`)}async list({agent:e,tenant:r}){let n=await Dd({tenant:r,agent:e}),i=[];for(let[a,s]of this.store.entries())a.startsWith(`${n}${ki}`)&&i.push(s);return i}async set({id:e,data:r,tenant:n,agent:i,preventDuplicates:a,updateExisting:s}){let o=await Dd({agent:i,tenant:n,didUri:e});if(s){if(!this.store.has(`${o}${ki}${e}`))throw new Error(`${this.name}: Update failed due to missing entry for: ${e}`)}else if(a&&this.store.has(`${o}${ki}${e}`))throw new Error(`${this.name}: Import failed due to duplicate entry for: ${e}`);let d=structuredClone(r);this.store.set(`${o}${ki}${e}`,d)}};var cg=class extends $f{constructor(){super(...arguments);this.name="DwnDidStore";this._recordProtocolDefinition=NE;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"portableDid",schema:this._recordProtocolDefinition.types.portableDid.schema}}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async list(r){return await super.list(r)}async set(r){return await super.set(r)}async getAllRecords({agent:r,tenantDid:n}){this._index.clear();let{reply:i}=await r.dwn.processRequest({author:n,target:n,messageType:Re.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=he.base64Url(s.encodedData).toObject();if(bh(o)){let d=`${n}${ki}${o.uri}`;this._index.set(d,s.recordId),this._cache.set(s.recordId,o),a.push(o)}}return a}},dg=class extends Bf{constructor(){super(...arguments);this.name="InMemoryDidStore"}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async list(r){return await super.list(r)}async set(r){return await super.set(r)}};var uye=(r=>(r.Create="Create",r.Resolve="Resolve",r))(uye||{});function OG(t,e){return t.messageType===e}var _h=class extends Zy{constructor({agent:r,didMethods:n,resolverCache:i,store:a}){if(!n)throw new TypeError("AgentDidApi: Required parameter missing: 'didMethods'");super({didResolvers:n,cache:i??new Cf({agent:r,location:"DATA/AGENT/DID_CACHE"})});this._didMethods=new Map;this._agent=r,this._store=a??new dg;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(r){this._agent=r,"agent"in this.cache&&(this.cache.agent=r)}async create({method:r,tenant:n,options:i,store:a}){let o=await this.getMethod(r).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:d,document:l,metadata:c}=o,u={uri:d,document:l,metadata:c};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:r,tenant:n}){let i=await this.get({didUri:r,tenant:n});if(!i)throw new Error(`AgentDidApi: Failed to export due to DID not found: ${r}`);return await i.export()}async get({didUri:r,tenant:n}){let i=await this._store.get({id:r,agent:this.agent,tenant:n,useCache:!0});return i?await bs.import({portableDid:i,keyManager:this.agent.keyManager}):void 0}async getSigningMethod({didUri:r,methodId:n}){let i=Fn.parse(r);if(!i)throw new Error(`Invalid DID URI: ${r}`);let a=this.getMethod(i.method),{didDocument:s,didResolutionMetadata:o}=await this.resolve(r);if(!s)throw new Error(`DID resolution failed for '${r}': ${JSON.stringify(o)}`);return await a.getSigningMethod({didDocument:s,methodId:n})}async update({tenant:r,portableDid:n,publish:i=!0}){let a=await this.get({didUri:n.uri,tenant:r??n.uri});if(!a)throw new Error(`AgentDidApi: Could not update, DID not found: ${n.uri}`);if(Hw(n.document)===Hw(a.document))throw new Error("AgentDidApi: No changes detected, update aborted");let s=await bs.import({keyManager:this.agent.keyManager,portableDid:n}),{uri:o,document:d,metadata:l}=s,c={uri:o,document:d,metadata:l};if(await this.cache.set(o,{didDocument:d,didResolutionMetadata:{},didDocumentMetadata:l}),await this._store.set({id:o,data:c,agent:this.agent,tenant:r??o,updateExisting:!0,useCache:!0}),i){let u=Fn.parse(o);u&&u.method==="dht"&&await po.publish({did:s})}return s}async import({portableDid:r,tenant:n}){let i=await bs.import({keyManager:this.agent.keyManager,portableDid:r}),{uri:a,document:s,metadata:o}=i,d={uri:a,document:s,metadata:o};return await this.cache.set(a,{didDocument:s,didResolutionMetadata:{},didDocumentMetadata:o}),await this._store.set({id:d.uri,data:d,agent:this.agent,tenant:n??d.uri,preventDuplicates:!0,useCache:!0}),i}async delete({didUri:r,tenant:n,deleteKey:i=!0}){let a=await this._store.get({id:r,agent:this.agent,tenant:n,useCache:!1});if(!a)throw new Error("AgentDidApi: Could not delete, DID not found");await this.cache.delete(r),await this._store.delete({id:r,agent:this.agent,tenant:n}),i&&await this.deleteKeys({portableDid:a})}async deleteKeys({portableDid:r}){for(let n of r.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(r){if(OG(r,"Create"))try{let n=await this.create({...r.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(OG(r,"Resolve")){let{didUri:n,options:i}=r.messageParams;return{result:await this.resolve(n,i),ok:!0,status:{code:200,message:"OK"}}}throw new Error(`AgentDidApi: Unsupported request type: ${r.messageType}`)}getMethod(r){let n=this._didMethods.get(r);if(n===void 0)throw new Error(`DID Method not supported: ${r}`);return n}};g();Er();Yn();wn();Jo();g();g();var fye="@enbox/dwn-server";function zE(t){return t.endsWith("/")?t.slice(0,-1):t}var Th=class{constructor(e,r=1e4,n){this._rpcClient=e;this._cacheTtlMs=r;this._discoveryFile=n;this._cacheExpiry=0}async getEndpoint(){let e=Date.now();if(e<this._cacheExpiry)return this._cachedEndpoint;let r=await this._tryDiscoveryFile();if(r!==void 0)return this._setCacheEntry(r,e),r;this._setCacheEntry(void 0,e)}async setCachedEndpoint(e){let r=zE(e),n=await this._validateEndpoint(r);return n&&this._setCacheEntry(r,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===fye}catch{return!1}}_setCacheEntry(e,r){this._cachedEndpoint=e,this._cacheExpiry=r+this._cacheTtlMs}};function pye(){try{let t=sS,e=t("node:fs/promises"),r=t("node:path"),n=t("node:os");return{async readFile(i){try{return await e.readFile(i,"utf-8")}catch{return null}},async writeFile(i,a){await e.mkdir(r.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 hye=".enbox",mye="dwn.json",FE=class{constructor(e,r){let n=e??pye();if(!n)throw new Error("DwnDiscoveryFile: No filesystem adapter available. Provide a DiscoveryFileFs implementation or run in Node.js / Bun.");if(this._fs=n,r)this._filePath=r;else{let a=sS("node:path");this._filePath=a.join(n.homedir(),hye,mye)}}get path(){return this._filePath}async read(){let e=await this._fs.readFile(this._filePath);if(e===null)return;let r;try{r=JSON.parse(e)}catch{await this._fs.removeFile(this._filePath);return}if(!yye(r)){await this._fs.removeFile(this._filePath);return}if(!this._fs.isProcessAlive(r.pid)){await this._fs.removeFile(this._filePath);return}let n={endpoint:zE(r.endpoint),pid:r.pid};return r.capabilities!==void 0&&(n.capabilities=r.capabilities),n}async write(e){let r={endpoint:zE(e.endpoint),pid:e.pid};e.capabilities!==void 0&&e.capabilities.length>0&&(r.capabilities=e.capabilities);let n=JSON.stringify(r,null,2);await this._fs.writeFile(this._filePath,n)}async remove(){await this._fs.removeFile(this._filePath)}};function yye(t){if(typeof t!="object"||t===null)return!1;let e=t;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(r=>typeof r=="string")))}g();Yn();function Rd(t,e){return t.messageType===e}function gye(t,e){return e.descriptor.interface+e.descriptor.method===t}function v5(t){return t===Re.RecordsDelete||t===Re.RecordsQuery||t===Re.RecordsRead||t===Re.RecordsSubscribe||t===Re.RecordsWrite}function b5(t){return t.interface===be.Records}function wye(t){return t.interface===be.Messages}g();wn();Yn();function GE(t){return t===ii.XC20P?24:12}function Ih(t,e,r,n,i){return{initializationVector:e,key:t,keyEncryptionInputs:[{publicKeyId:r,publicKey:n,derivationScheme:i}]}}async function HE(t,e,r,n=ii.A256GCM){let{ciphertextStream:i,tag:a}=await Bi.aeadEncryptStream(n,e,r,Yt.fromBytes(t)),s=await Yt.toBytes(i),o=Yt.fromBytes(s),d=await hr.computeDagPbCidFromStream(o);return{encryptedBytes:s,dataCid:d,dataSize:s.length,authenticationTag:a}}async function zl(t,e){let{didDocument:r,didResolutionMetadata:n}=await t.did.resolve(e);if(!r)throw new Error(`AgentDwnApi: Failed to resolve DID '${e}': ${JSON.stringify(n)}`);let i=r.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=r.verificationMethod?.find(c=>c.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!=="X25519")throw new Error(`AgentDwnApi: keyAgreement key for '${e}' uses curve '${o.crv}', but DWN encryption requires 'X25519'.`);let d=await t.keyManager.getKeyUri({key:o});return{keyId:s.id,keyUri:d,publicKeyJwk:o}}async function KG(t,e,r,n,i){let{keyId:a,keyUri:s}=await zl(t,e),o=Te.constructKeyDerivationPathUsingProtocolContextScheme(r),d=await t.keyManager.derivePublicKey({keyUri:s,derivationPath:o});return{encryptionInput:Ih(n,i,a,d,Ht.ProtocolContext),keyId:a,keyUri:s,contextDerivationPath:o}}function NG(t,e,r,n){let i=t.keyManager;return{rootKeyId:e,derivationScheme:n,decrypt:async(a,s)=>i.jweKeyUnwrap({keyUri:r,derivationPath:a,encryptedKey:s.encryptedKey,ephemeralPublicKey:s.ephemeralPublicKey})}}async function yb(t,e){let{keyId:r,keyUri:n}=await zl(t,e),i=t.keyManager;return{rootKeyId:r,derivationScheme:Ht.ProtocolPath,derivePublicKey:async a=>i.derivePublicKey({keyUri:n,derivationPath:a})}}async function gb(t,e){let{keyId:r,keyUri:n}=await zl(t,e);return NG(t,r,n,Ht.ProtocolPath)}function jG(t){return{rootKeyId:t.rootKeyId,derivationScheme:t.derivationScheme,decrypt:async(e,r)=>{let n=await Te.derivePrivateKey(t,e),i=await Gt.bytesToPrivateKey({privateKeyBytes:n});return Bi.ecdhEsUnwrapKey(i,r.ephemeralPublicKey,r.encryptedKey)}}}async function MG(t,e,r,n,i,a){let{encryption:s}=r;if(!s?.recipients.some(y=>y.header.derivationScheme===Ht.ProtocolContext)||!r.contextId)return gb(t,e);let d=s.recipients.find(y=>y.header.derivationScheme===Ht.ProtocolContext),l=r.contextId.split("/")[0],{keyId:c,keyUri:u}=await zl(t,e);if(d.header.kid===c)return NG(t,c,u,Ht.ProtocolContext);let f=`ctx~${e}~${l}`,h=i.get(f);if(h)return jG(h);let p=r.descriptor.protocol,m=await a({ownerDid:e,requesterDid:e,sourceProtocol:p,sourceContextId:l});if(!m){let{Jws:y}=await Promise.resolve().then(()=>(Yn(),RG)),b=n??y.getSignerDid(r.authorization.signature.signatures[0]);m=await a({ownerDid:b,requesterDid:e,sourceProtocol:p,sourceContextId:l})}if(!m)throw new Error(`AgentDwnApi: Failed to decrypt record '${r.recordId}'. Record uses context-derived encryption but no contextKey record could be found via the key-delivery protocol.`);return i.set(f,m),jG(m)}async function UG(t,e,r,n,i){if(!(!("encryption"in t)||!t.encryption)){if(Rd(t,Re.RecordsRead)){let a=e;if(a.status.code===200&&a.entry?.recordsWrite?.encryption&&a.entry?.data){let s=await MG(r,t.author,a.entry.recordsWrite,t.target,n,i);try{a.entry.data=await Te.decrypt(a.entry.recordsWrite,s,a.entry.data)}catch(o){throw new Error(`AgentDwnApi: Failed to decrypt record '${a.entry.recordsWrite.recordId}'. Original error: ${o.message}`)}}}if(Rd(t,Re.RecordsQuery)){let a=e;if(a.status.code===200&&a.entries){for(let s of a.entries)if(s.encryption&&s.encodedData){let o=await MG(r,t.author,s,t.target,n,i);try{let d=De.base64UrlToBytes(s.encodedData),l=Yt.fromBytes(d),c=await Te.decrypt(s,o,l),u=await Yt.toBytes(c);s.encodedData=De.bytesToBase64Url(u)}catch(d){throw new Error(`AgentDwnApi: Failed to decrypt record '${s.recordId}'. Original error: ${d.message}`)}}}}}}g();function LG(t,e){let r=e.split("/"),n=t.structure;for(let i of r)if(n=n[i],!n)return;return n}function hHe(t){return t.split("/")[0]||t}function x5(t,e){let r=LG(t,e);if(!r)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(r)?!0:P5(void 0,e,t)}function P5(t,e,r){let n=r.structure;function i(a){if(a.$actions){for(let s of a.$actions)if(s.who&&s.who!=="anyone"&&(t===void 0||s.who===t)&&s.of===e&&s.can?.includes("read"))return!0}for(let s in a)if(!s.startsWith("$")&&i(a[s]))return!0;return!1}return i(n)}function E5({protocolDefinition:t,protocolPath:e,recipient:r,tenantDid:n,authorDid:i}){let a=new Set,s=LG(t,e);return s&&(s.$role===!0&&r&&a.add(r),r&&r!==n&&P5("recipient",e,t)&&a.add(r),i&&i!==n&&P5("author",e,t)&&a.add(i),a.delete(n)),a}g();Yn();async function qG(t,e,r,n,i,a){if(i.get(e))return;let s=ql.protocol;if(!await n(e,s)){let d=await yb(t,e),l=await md.deriveAndInjectPublicEncryptionKeys(ql,d),{reply:{status:c}}=await r({author:e,target:e,messageType:Re.ProtocolsConfigure,messageParams:{definition:l}});if(c.code!==202)throw new Error(`AgentDwnApi: Failed to install key delivery protocol: ${c.code} - ${c.detail}`);a.delete(`${e}~${s}`)}i.set(e,!0)}async function zG(t,e,r,n,i){let{tenantDid:a,recipientDid:s,contextKeyData:o,sourceProtocol:d,sourceContextId:l,recipientKeyDeliveryPublicKey:c}=e;await n(a);let u=ql.protocol,f=new TextEncoder().encode(JSON.stringify(o)),h={protocol:u,protocolPath:"contextKey",dataFormat:"application/json",recipient:s,tags:{protocol:d,contextId:l}},p,m;if(c){let y=ii.A256GCM,b=crypto.getRandomValues(new Uint8Array(32)),w=crypto.getRandomValues(new Uint8Array(GE(y))),{encryptedBytes:S,dataCid:k,dataSize:T,authenticationTag:D}=await HE(f,b,w,y),K={...Ih(b,w,c.rootKeyId,c.publicKeyJwk,Ht.ProtocolPath),authenticationTag:D};({message:p,reply:{status:m}}=await r({author:a,target:a,messageType:Re.RecordsWrite,messageParams:{...h,dataCid:k,dataSize:T,encryptionInput:K},dataStream:new Blob([S])}))}else({message:p,reply:{status:m}}=await r({author:a,target:a,messageType:Re.RecordsWrite,messageParams:h,dataStream:new Blob([f],{type:"application/json"}),encryption:!0}));if(!(p&&m.code===202))throw new Error(`AgentDwnApi: Failed to write contextKey record for ${s}: ${m.code} - ${m.detail}`);return i(a,p).catch(y=>{console.warn(`AgentDwnApi: Eager send of contextKey record '${p.recordId}' to remote DWN failed: ${y.message}. Sync will deliver it later.`)}),p.recordId}async function FG(t,e,r,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:Re.RecordsWrite,messageCid:await we.getCid(r)});await i({targetDid:e,dwnEndpointUrls:s,message:r,data:o})}async function GG(t,e,r,n,i,a){let{ownerDid:s,requesterDid:o,sourceProtocol:d,sourceContextId:l}=e,c=ql.protocol,u=s===o,f={protocol:c,protocolPath:"contextKey",recipient:o,tags:{protocol:d,contextId:l}},h=p=>JSON.parse(new TextDecoder().decode(p));if(u){let{reply:p}=await r({author:o,target:s,messageType:Re.RecordsQuery,messageParams:{filter:f}});if(p.status.code!==200||!p.entries?.length)return;let m=p.entries[0].recordId,{reply:y}=await r({author:o,target:s,messageType:Re.RecordsRead,messageParams:{filter:{recordId:m}},encryption:!0}),b=y;return b.entry?.data?h(await Yt.toBytes(b.entry.data)):void 0}else{let p=await n(o),m=await a(s),y=await Id[Re.RecordsQuery].create({signer:p,filter:f}),b=await i({targetDid:s,dwnEndpointUrls:m,message:y.message});if(b.status.code!==200||!b.entries?.length)return;let w=b.entries[0].recordId,S=await Id[Re.RecordsRead].create({signer:p,filter:{recordId:w}}),k=await i({targetDid:s,dwnEndpointUrls:m,message:S.message});if(!k.entry?.data||!k.entry?.recordsWrite)return;let T=await gb(t,o),D=await Te.decrypt(k.entry.recordsWrite,T,k.entry.data);return h(await Yt.toBytes(D))}}g();Yn();async function HG(t,e,r,n,i){let a=`${t}~${e}`,s=i.get(a);if(s)return s;let o=await n(t),d=await Id[Re.ProtocolsQuery].create({filter:{protocol:e},signer:o}),l=await r.processMessage(t,d.message);if(l.status.code!==200||!l.entries?.length)return;let c=l.entries[0].descriptor.definition;return i.set(a,c),c}async function VG(t,e,r,n,i){let a=`remote~${t}~${e}`,s=i.get(a);if(s)return s;let o=await Id[Re.ProtocolsQuery].create({filter:{protocol:e}}),d=await n({targetDid:t,dwnEndpointUrls:await r(t),message:o.message});if(d.status.code!==200||!d.entries?.length)throw new Error(`AgentDwnApi: Failed to fetch protocol '${e}' from '${t}'. The recipient may not have the protocol installed.`);let l=d.entries[0].descriptor.definition;return i.set(a,l),l}async function WG(t,e,r,n,i,a,s){let o=await a(n),d=await Id[Re.RecordsQuery].create({signer:o,filter:{protocol:e,contextId:r}}),l=await i(t),c=await s({targetDid:t,dwnEndpointUrls:l,message:d.message});if(!(c.status.code!==200||!c.entries?.length)){for(let u of c.entries)if(u.encryption?.recipients){let f=u.encryption.recipients.find(h=>h.header.derivationScheme===Ht.ProtocolContext&&h.header.derivedPublicKey);if(f?.header.derivedPublicKey)return{rootKeyId:f.header.kid,derivedPublicKey:f.header.derivedPublicKey}}}}var Fl=class t{constructor(e){this._protocolDefinitionCache=new cs.default({ttl:30*60*1e3});this._contextKeyCache=new cs.default({ttl:30*60*1e3});this._contextDerivedKeyCache=new cs.default({ttl:30*60*1e3});this._localManagedDidCache=new cs.default({ttl:30*60*1e3});this._keyDeliveryProtocolInstalledCache=new cs.default({ttl:21*24*60*60*1e3,max:1e3});let{agent:r,localDwnStrategy:n="prefer"}=e;this._agent=r,this._dwn="dwn"in e?e.dwn:void 0,this._localDwnEndpoint="localDwnEndpoint"in e?e.localDwnEndpoint:void 0,this._localDwnStrategy=n,r&&(this._localDwnDiscovery=new Th(r.rpc,1e4,t._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 Th(e.rpc,1e4,t._tryCreateDiscoveryFile()),this._localManagedDidCache.clear()}get localDwnStrategy(){return this._localDwnStrategy}setLocalDwnStrategy(e){this._localDwnStrategy=e}async setCachedLocalDwnEndpoint(e){return this._localDwnDiscovery??=new Th(this.agent.rpc,1e4,t._tryCreateDiscoveryFile()),this._localDwnDiscovery.setCachedEndpoint(e)}async getDwnEndpointUrlsForTarget(e){if(!await this.shouldUseLocalDwnForTarget(e))return pb(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 pb(e,this.agent.did)}catch(s){if(!n)throw s}return n?[...new Set([n,...i])]:i}async getLocalDwnEndpoint(){return this._localDwnEndpoint?this._localDwnEndpoint:(this._localDwnDiscovery??=new Th(this.agent.rpc,1e4,t._tryCreateDiscoveryFile()),this._localDwnDiscovery.getEndpoint())}static _tryCreateDiscoveryFile(){try{return new FE}catch{return}}async shouldUseLocalDwnForTarget(e){if(this._localDwnStrategy==="off")return!1;let r=this._localManagedDidCache.get(e);if(r!==void 0)return r;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:r,didResolver:n,stateIndex:i,eventLog:a,messageStore:s,tenantGate:o,resumableTaskStore:d}){return r??=new _f({blockstoreLocation:`${e}/DWN_DATASTORE`}),n??=new Zy({didResolvers:[po,ho],cache:new cE({location:`${e}/DID_RESOLVERCACHE`})}),i??=new Rf({location:`${e}/DWN_STATEINDEX`}),s??=new Tf({blockstoreLocation:`${e}/DWN_MESSAGESTORE`,indexLocation:`${e}/DWN_MESSAGEINDEX`}),d??=new If({location:`${e}/DWN_RESUMABLETASKSTORE`}),a??=new Df,await Yy.create({dataStore:r,didResolver:n,stateIndex:i,eventLog:a,messageStore:s,tenantGate:o,resumableTaskStore:d})}async processRequest(e){let{message:r,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,r,{dataStream:n,subscriptionHandler:i});else{let s;if(n){let o=await Yt.toBytes(n);s=new Blob([o])}a=await this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:[this._localDwnEndpoint],message:r,data:s,subscriptionHandler:i})}return await this.postWriteKeyDelivery(e,r,a),await this.maybeDecryptReply(e,a),{reply:a,message:r,messageCid:await we.getCid(r)}}async processRawMessage(e,r,n){if(this._dwn)return this._dwn.processMessage(e,r,{dataStream:n?.dataStream});let i;if(n?.dataStream){let a=await Yt.toBytes(n.dataStream);i=new Blob([a])}return this.sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:[this._localDwnEndpoint],message:r,data:i})}async sendRequest(e){let r=await this.getDwnEndpointUrlsForTarget(e.target);if(r.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 c=l!==void 0?{...e.messageParams,cursor:l}:e.messageParams,u={...e,messageParams:c},{message:f}=await this.constructDwnMessage({request:u});return f});let d=await this.sendDwnRpcRequest({targetDid:e.target,dwnEndpointUrls:r,message:i,data:a,subscriptionHandler:s,resubscribeFactory:o});return await this.maybeDecryptReply(e,d),n??=await we.getCid(i),{reply:d,message:i,messageCid:n}}async postWriteKeyDelivery(e,r,n){if(!Rd(e,Re.RecordsWrite)||!e.encryption||n.status.code!==202)return;let i=e.messageParams;if(i.protocol!==ql.protocol)try{let a=await this.getProtocolDefinition(e.target,i.protocol);if(!a)return;let s=r,o=ut.getSignerDid(s.authorization.signature.signatures[0]),d=o!==e.target,l=!i.parentContextId,c=i.protocolPath.split("/")[0],u=x5(a,c),f=E5({protocolDefinition:a,protocolPath:i.protocolPath,recipient:i.recipient,tenantDid:e.target,authorDid:d?o:void 0});if(f.size>0){let h=s.contextId?.split("/")[0]||s.contextId||s.recordId,{keyId:p,keyUri:m}=await zl(this.agent,e.target),y=[Ht.ProtocolContext,h],b=await this.agent.keyManager.derivePrivateKeyBytes({keyUri:m,derivationPath:y}),w=await Gt.bytesToPrivateKey({privateKeyBytes:b}),S={rootKeyId:p,derivationScheme:Ht.ProtocolContext,derivationPath:y,derivedPrivateKey:w},k=s.authorization?.authorKeyDeliveryPublicKey;for(let T of f)try{let D=T===o&&k?k:void 0;await this.writeContextKeyRecord({tenantDid:e.target,recipientDid:T,contextKeyData:S,sourceProtocol:i.protocol,sourceContextId:h,recipientKeyDeliveryPublicKey:D})}catch(D){console.warn(`AgentDwnApi: Key delivery to '${T}' for context '${h}' failed: ${D.message}. The participant may not be able to decrypt records in this context.`)}}}catch(a){console.warn(`AgentDwnApi: Post-write participant detection failed: ${a.message}`)}}async sendDwnRpcRequest({targetDid:e,dwnEndpointUrls:r,message:n,data:i,subscriptionHandler:a,resubscribeFactory:s}){let o=[];if(n.descriptor.method===ge.Subscribe&&a===void 0)throw new Error("AgentDwnApi: Subscription handler is required for subscription requests.");for(let d of r)try{if(a!==void 0){if(!(await this.agent.rpc.getServerInfo(d)).webSocketSupport){o.push({url:d,message:"WebSocket support is not enabled on the server."});continue}let u=new URL(d);u.protocol=u.protocol==="http:"?"ws:":"wss:",d=u.toString()}return await this.agent.rpc.sendDwnRequest({dwnUrl:d,targetDid:e,message:n,data:i,subscription:a?{handler:a,resubscribeFactory:s}:void 0})}catch(l){o.push({url:d,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 r=e.rawMessage,n;if(Rd(e,Re.RecordsWrite)){let o=e.messageParams;if(e.dataStream&&!o?.data){let{dataStream:d}=e,l;if(d instanceof Blob){let[c,u]=d.stream().tee();l=c,n=u}else if(d instanceof ReadableStream){let[c,u]=d.tee();l=c,n=u}!r&&o&&(o.dataCid=await hr.computeDagPbCidFromStream(l),o.dataSize===void 0&&d instanceof Blob&&(o.dataSize=d.size))}}if(Rd(e,Re.ProtocolsConfigure)&&e.encryption&&!r){let o=e.messageParams,d=await yb(this.agent,e.author);o.definition=await md.deriveAndInjectPublicEncryptionKeys(o.definition,d),this._protocolDefinitionCache.delete(`${e.target}~${o.definition.protocol}`)}let i;if(Rd(e,Re.RecordsWrite)&&e.encryption&&!r){let o=e.messageParams;if(o?.protocol&&o.protocolPath){let d=e.target!==e.author,l;if(d?l=await this.fetchRemoteProtocolDefinition(e.target,o.protocol):l=await this.getProtocolDefinition(e.target,o.protocol),!l)throw new Error(`AgentDwnApi: Protocol '${o.protocol}' is not installed for '${e.target}'. Install the protocol before writing encrypted records.`);let c=o.protocolPath.split("/"),u=l.structure;for(let z of c)u=u[z];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],p=o.protocol===ql.protocol?!1:x5(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 Yt.toBytes(e.dataStream);else throw new Error("AgentDwnApi: Data must be provided for encrypted records.");let b=ii.A256GCM,w=crypto.getRandomValues(new Uint8Array(32)),S=crypto.getRandomValues(new Uint8Array(GE(b))),k,T=()=>Ih(w,S,u.$encryption.rootKeyId,u.$encryption.publicKeyJwk,Ht.ProtocolPath);if(d&&p&&m)k=T();else if(d&&p&&!m){let z=o.parentContextId.split("/")[0]||o.parentContextId,N=await this.extractDerivedPublicKey(e.target,o.protocol,z,e.author);N?k=Ih(w,S,N.rootKeyId,N.derivedPublicKey,Ht.ProtocolContext):k=T()}else if(d)k=T();else if(p&&!m){let z=o.parentContextId.split("/")[0]||o.parentContextId,N=this._contextKeyCache.get(z);if(!N){let{keyId:ee,keyUri:R}=await zl(this.agent,e.author),B=Te.constructKeyDerivationPathUsingProtocolContextScheme(z);N={keyId:ee,keyUri:R,contextDerivationPath:B},this._contextKeyCache.set(z,N)}let V=await this.agent.keyManager.derivePublicKey({keyUri:N.keyUri,derivationPath:N.contextDerivationPath});k=Ih(w,S,N.keyId,V,Ht.ProtocolContext)}else p&&m?k=void 0:k=T();let{encryptedBytes:D,dataCid:K,dataSize:C,authenticationTag:G}=await HE(y,w,S,b);if(o.dataCid=K,o.dataSize=C,delete o.data,n=Yt.fromBytes(D),e.dataStream=void 0,k?(k.authenticationTag=G,o.encryptionInput=k):i={dataEncryptionKey:w,dataEncryptionIV:S,encryptedBytes:D,authenticationTag:G},d&&p){let{keyId:z,keyUri:N}=await zl(this.agent,e.author),V=[Ht.ProtocolPath,ql.protocol,"contextKey"],ee=await this.agent.keyManager.derivePublicKey({keyUri:N,derivationPath:V});o.authorKeyDeliveryPublicKey={rootKeyId:z,publicKeyJwk:ee}}}}let a,s=Id[e.messageType];if(r){if(a=await s.parse(r),Ll(a)&&e.signAsOwner){let o=await this.getSigner(e.author);await a.signAsOwner(o)}else if(e.granteeDid&&Ll(a)&&e.signAsOwnerDelegate){let o=await this.getSigner(e.granteeDid),d=e.messageParams;await a.signAsOwnerDelegate(o,d.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);if(a=await s.create({...e.messageParams,signer:o}),i&&Rd(e,Re.RecordsWrite)){let d=a,l=d.message.recordId,{encryptionInput:c,keyId:u,keyUri:f,contextDerivationPath:h}=await KG(this.agent,e.author,l,i.dataEncryptionKey,i.dataEncryptionIV),p={...c,authenticationTag:i.authenticationTag};await d.encryptSymmetricEncryptionKey(p),await d.sign({signer:o}),this._contextKeyCache.set(l,{keyId:u,keyUri:f,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 r=await this.agent.agentDid.getSigner();return{algorithm:r.algorithm,keyId:r.keyId,sign:async n=>await r.sign({data:n})}}else try{let r=await this.agent.did.get({didUri:e});if(r){let o=await r.getSigner();return{algorithm:o.algorithm,keyId:o.keyId,sign:async d=>await o.sign({data:d})}}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:gn.getJoseSignatureAlgorithmFromPublicKey(a),keyId:n.id,sign:async o=>await s.sign({data:o,keyUri:i})}}catch(r){throw new Error(`AgentDwnApi: Unable to get signer for author '${e}': ${r.message}`)}}async getEncryptionKeyDeriver(e){return yb(this.agent,e)}async getEncryptionKeyInfo(e){return zl(this.agent,e)}async getKeyDecrypter(e){return gb(this.agent,e)}detectNewParticipants(e){return E5(e)}async getProtocolDefinition(e,r){if(!this._dwn)try{return await this.fetchRemoteProtocolDefinition(e,r)}catch(n){let i=n instanceof Error?n.message:"";if(i.includes("not found")||i.includes("404")||i.includes("No protocol"))return;throw n}return HG(e,r,this._dwn,this.getSigner.bind(this),this._protocolDefinitionCache)}async fetchRemoteProtocolDefinition(e,r){return VG(e,r,this.getDwnEndpointUrlsForTarget.bind(this),this.sendDwnRpcRequest.bind(this),this._protocolDefinitionCache)}async extractDerivedPublicKey(e,r,n,i){return WG(e,r,n,i,this.getDwnEndpointUrlsForTarget.bind(this),this.getSigner.bind(this),this.sendDwnRpcRequest.bind(this))}async maybeDecryptReply(e,r){return UG(e,r,this.agent,this._contextDerivedKeyCache,this.fetchContextKeyRecord.bind(this))}async getDwnMessage({author:e,messageCid:r}){let n=await this.getSigner(e),i=await Id[Re.MessagesRead].create({messageCid:r,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,d={message:s.message};if(Ll(s)){let l=s.data;if(l){let c=await Yt.toBytes(l);d.data=new Blob([c],{type:s.message.descriptor.dataFormat})}}return d}async ensureKeyDeliveryProtocol(e){return qG(this.agent,e,this.processRequest.bind(this),this.getProtocolDefinition.bind(this),this._keyDeliveryProtocolInstalledCache,this._protocolDefinitionCache)}async writeContextKeyRecord(e){return zG(this.agent,e,this.processRequest.bind(this),this.ensureKeyDeliveryProtocol.bind(this),this.eagerSendContextKeyRecord.bind(this))}async eagerSendContextKeyRecord(e,r){return FG(this.agent,e,r,this.getDwnMessage.bind(this),this.sendDwnRpcRequest.bind(this),this.getDwnEndpointUrlsForTarget.bind(this))}async fetchContextKeyRecord(e){return GG(this.agent,e,this.processRequest.bind(this),this.getSigner.bind(this),this.sendDwnRpcRequest.bind(this),this.getDwnEndpointUrlsForTarget.bind(this))}};g();var ZG="dwn",YG="connect";function FHe(t){return`${ZG}://${YG}?callback=${encodeURIComponent(t)}`}function vye(t){let e=JSON.stringify(t);return xye(e)}function JG(t){try{let e=Eye(t),r=JSON.parse(e);return bye(r)?r:void 0}catch{return}}function GHe(t){try{let e=`${ZG}://`;if(!t.startsWith(e))return;let r=t.slice(e.length),n=r.indexOf("?");if(n===-1||r.slice(0,n)!==YG)return;let a=r.slice(n+1),o=new URLSearchParams(a).get("callback");return!o||o.length===0?void 0:{callback:o}}catch{return}}function HHe(t,e){let r=vye(e);return`${t.split("#")[0]}#${r}`}function VHe(t){let e=t.indexOf("#");if(e===-1)return JG(t);let r=t.slice(e+1);if(r.length!==0)return JG(r)}function bye(t){if(typeof t!="object"||t===null)return!1;let e=t;return!(typeof e.endpoint!="string"||e.endpoint.length===0||!Pye(e.endpoint))}function Pye(t){try{let r=new URL(t).hostname.toLowerCase();return!!(r==="127.0.0.1"||r==="::1"||r==="[::1]"||r==="localhost"||r.endsWith(".localhost"))}catch{return!1}}function xye(t){let e=new TextEncoder().encode(t),r="";for(let n=0;n<e.length;n++)r+=String.fromCharCode(e[n]);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Eye(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4;r===2?e+="==":r===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();aP();Gb();g();Yb();za();var Sye=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),QG=Uint8Array.from({length:16},(t,e)=>e),Aye=QG.map(t=>(9*t+5)%16),A5=[QG],k5=[Aye];for(let t=0;t<4;t++)for(let e of[A5,k5])e.push(e[t].map(r=>Sye[r]));var eH=[[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(t=>new Uint8Array(t)),kye=A5.map((t,e)=>t.map(r=>eH[e][r])),_ye=k5.map((t,e)=>t.map(r=>eH[e][r])),Tye=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),Iye=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]),VE=(t,e)=>t<<e|t>>>32-e;function XG(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}var WE=new Uint32Array(16),S5=class extends eu{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:r,h2:n,h3:i,h4:a}=this;return[e,r,n,i,a]}set(e,r,n,i,a){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=a|0}process(e,r){for(let h=0;h<16;h++,r+=4)WE[h]=e.getUint32(r,!0);let n=this.h0|0,i=n,a=this.h1|0,s=a,o=this.h2|0,d=o,l=this.h3|0,c=l,u=this.h4|0,f=u;for(let h=0;h<5;h++){let p=4-h,m=Tye[h],y=Iye[h],b=A5[h],w=k5[h],S=kye[h],k=_ye[h];for(let T=0;T<16;T++){let D=VE(n+XG(h,a,o,l)+WE[b[T]]+m,S[T])+u|0;n=u,u=l,l=VE(o,10)|0,o=a,a=D}for(let T=0;T<16;T++){let D=VE(i+XG(p,s,d,c)+WE[w[T]]+y,k[T])+f|0;i=f,f=c,c=VE(d,10)|0,d=s,s=D}}this.set(this.h1+o+c|0,this.h2+l+f|0,this.h3+u+i|0,this.h4+n+s|0,this.h0+a+d|0)}roundClean(){WE.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}},tH=Xh(()=>new S5);Gg();iP();za();Zh();var Dye=qg("ed25519 seed"),_5=2147483648,rH=new Uint8Array([0]);function nH(t,...e){return typeof t=="string"&&(t=m8(t)),Md(t,...e),t}var Rye=t=>tH(nu(t)),Cye=t=>Nd(t).getUint32(0,!1),T5=t=>{if(!Number.isSafeInteger(t)||t<0||t>2**32-1)throw new Error(`Invalid number=${t}. Should be from 0 to 2 ** 32 - 1`);let e=new Uint8Array(4);return Nd(e).setUint32(0,t,!1),e},JE=class t{get publicKeyRaw(){return da.getPublicKey(this.privateKey)}get publicKey(){return Gf(rH,this.publicKeyRaw)}get pubHash(){return Rye(this.publicKey)}get fingerprint(){return Cye(this.pubHash)}get fingerprintHex(){return OS(T5(this.fingerprint))}get parentFingerprintHex(){return OS(T5(this.parentFingerprint))}static fromMasterSeed(e){if(e=nH(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 r=Xl(ku,Dye,e);return new t({privateKey:r.slice(0,32),chainCode:r.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(Md(e.privateKey,32),Md(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,r=!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>=_5)throw new Error("Invalid index");(r||s[2]==="'")&&(o+=_5),i=i.deriveChild(o)}return i}deriveChild(e){if(e<_5)throw new Error(`Non-hardened child derivation not possible for Ed25519 (index=${e})`);let r=Gf(rH,this.privateKey,T5(e)),n=Xl(ku,this.chainCode,r);return new t({chainCode:n.slice(32),depth:this.depth+1,parentFingerprint:this.fingerprint,index:e,privateKey:n.slice(0,32)})}sign(e){return da.sign(e,this.privateKey)}verify(e,r){return r=nH(r,64),da.verify(r,e,this.publicKeyRaw)}};g();var I5=`abandon
11
11
  ability
12
12
  able
13
13
  about
@@ -2057,7 +2057,7 @@ zone
2057
2057
  zoo`.split(`
2058
2058
  `);Jo();Er();g();Zh();g();Zh();Gb();za();function $ye(t,e,r,n){qb(t);let i=g8({dkLen:32,asyncTick:10},n),{c:a,dkLen:s,asyncTick:o}=i;if(Zl(a),Zl(s),Zl(o),a<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let d=Yl(e),l=Yl(r),c=new Uint8Array(s),u=Xl.create(t,d),f=u._cloneInto().update(l);return{c:a,dkLen:s,asyncTick:o,DK:c,PRF:u,PRFSalt:f}}function Bye(t,e,r,n,i){return t.destroy(),e.destroy(),n&&n.destroy(),i.fill(0),r}async function iH(t,e,r,n){let{c:i,dkLen:a,asyncTick:s,DK:o,PRF:d,PRFSalt:l}=$ye(t,e,r,n),c,u=new Uint8Array(4),f=Nd(u),h=new Uint8Array(d.outputLen);for(let p=1,m=0;m<a;p++,m+=d.outputLen){let y=o.subarray(m,m+d.outputLen);f.setInt32(0,p,!1),(c=l._cloneInto(c)).update(u).digestInto(h),y.set(h.subarray(0,y.length)),await y8(i-1,s,()=>{d._cloneInto(c).update(h).digestInto(h);for(let b=0;b<y.length;b++)y[b]^=h[b]})}return Bye(d,l,o,c,h)}Gg();iP();za();g();function Dh(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function ZE(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Oye(...t){let e=a=>a,r=(a,s)=>o=>a(s(o)),n=t.map(a=>a.encode).reduceRight(r,e),i=t.map(a=>a.decode).reduce(r,e);return{encode:n,decode:i}}function jye(t){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(r=>{if(r<0||r>=t.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${t.length})`);return t[r]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(r=>{if(typeof r!="string")throw new Error(`alphabet.decode: not string element=${r}`);let n=t.indexOf(r);if(n===-1)throw new Error(`Unknown letter: "${r}". Allowed: ${t}`);return n})}}}function Mye(t=""){if(typeof t!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let r of e)if(typeof r!="string")throw new Error(`join.encode: non-string input=${r}`);return e.join(t)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(t)}}}function Kye(t,e="="){if(typeof e!="string")throw new Error("padding chr should be string");return{encode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let n of r)if(typeof n!="string")throw new Error(`padding.encode: non-string input=${n}`);for(;r.length*t%8;)r.push(e);return r},decode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of r)if(typeof i!="string")throw new Error(`padding.decode: non-string input=${i}`);let n=r.length;if(n*t%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&r[n-1]===e;n--)if(!((n-1)*t%8))throw new Error("Invalid padding: string has too much padding");return r.slice(0,n)}}}function D5(t,e,r){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: wrong to=${r}, base cannot be less than 2`);if(!Array.isArray(t))throw new Error("convertRadix: data should be array");if(!t.length)return[];let n=0,i=[],a=Array.from(t);for(a.forEach(s=>{if(s<0||s>=e)throw new Error(`Wrong integer: ${s}`)});;){let s=0,o=!0;for(let d=n;d<a.length;d++){let l=a[d],c=e*s+l;if(!Number.isSafeInteger(c)||e*s/e!==s||c-l!==e*s)throw new Error("convertRadix: carry overflow");s=c%r;let u=Math.floor(c/r);if(a[d]=u,!Number.isSafeInteger(u)||u*r+s!==c)throw new Error("convertRadix: carry overflow");if(o)u?o=!1:n=d;else continue}if(i.push(s),o)break}for(let s=0;s<t.length-1&&t[s]===0;s++)i.push(0);return i.reverse()}var sH=(t,e)=>e?sH(e,t%e):t,YE=(t,e)=>t+(e-sH(t,e));function R5(t,e,r,n){if(!Array.isArray(t))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(YE(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${YE(e,r)}`);let i=0,a=0,s=2**r-1,o=[];for(let d of t){if(d>=2**e)throw new Error(`convertRadix2: invalid data word=${d} from=${e}`);if(i=i<<e|d,a+e>32)throw new Error(`convertRadix2: carry overflow pos=${a} from=${e}`);for(a+=e;a>=r;a-=r)o.push((i>>a-r&s)>>>0);i&=2**a-1}if(i=i<<r-a&s,!n&&a>=e)throw new Error("Excess padding");if(!n&&i)throw new Error(`Non-zero padding: ${i}`);return n&&a>0&&o.push(i>>>0),o}function Nye(t){return{encode:e=>{if(!ZE(e))throw new Error("radix.encode input should be Uint8Array");return D5(Array.from(e),2**8,t)},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("radix.decode input should be array of numbers");return Uint8Array.from(D5(e,t,2**8))}}}function Uye(t,e=!1){if(t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(YE(8,t)>32||YE(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!ZE(r))throw new Error("radix2.encode input should be Uint8Array");return R5(Array.from(r),8,t,!e)},decode:r=>{if(!Array.isArray(r)||r.length&&typeof r[0]!="number")throw new Error("radix2.decode input should be array of numbers");return Uint8Array.from(R5(r,t,8,e))}}}function Lye(t,e){if(typeof e!="function")throw new Error("checksum fn should be function");return{encode(r){if(!ZE(r))throw new Error("checksum.encode: input should be Uint8Array");let n=e(r).slice(0,t),i=new Uint8Array(r.length+t);return i.set(r),i.set(n,r.length),i},decode(r){if(!ZE(r))throw new Error("checksum.decode: input should be Uint8Array");let n=r.slice(0,-t),i=e(n).slice(0,t),a=r.slice(-t);for(let s=0;s<t;s++)if(i[s]!==a[s])throw new Error("Invalid checksum");return n}}}var wb={alphabet:jye,chain:Oye,checksum:Lye,convertRadix:D5,convertRadix2:R5,radix:Nye,radix2:Uye,join:Mye,padding:Kye};var qye=t=>t[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";function oH(t){if(typeof t!="string")throw new TypeError(`Invalid mnemonic type: ${typeof t}`);return t.normalize("NFKD")}function aH(t){let e=oH(t),r=e.split(" ");if(![12,15,18,21,24].includes(r.length))throw new Error("Invalid mnemonic");return{nfkd:e,words:r}}function cH(t){Md(t,16,20,24,28,32)}function dH(t,e=128){if(Zl(e),e%32!==0||e>256)throw new TypeError("Invalid entropy");return Gye(Hf(e/8),t)}var zye=t=>{let e=8-t.length/4;return new Uint8Array([nu(t)[0]>>e<<e])};function lH(t){if(!Array.isArray(t)||t.length!==2048||typeof t[0]!="string")throw new Error("Wordlist: expected array of 2048 strings");return t.forEach(e=>{if(typeof e!="string")throw new Error(`Wordlist: non-string element: ${e}`)}),wb.chain(wb.checksum(1,zye),wb.radix2(11,!0),wb.alphabet(t))}function Fye(t,e){let{words:r}=aH(t),n=lH(e).decode(r);return cH(n),n}function Gye(t,e){return cH(t),lH(e).encode(t).join(qye(e)?"\u3000":" ")}function uH(t,e){try{Fye(t,e)}catch{return!1}return!0}var Hye=t=>oH(`mnemonic${t}`);function fH(t,e=""){return iH(ku,aH(t).nfkd,Hye(e),{c:2048,dkLen:64})}g();wn();g();Er();wn();g();Er();wn();function bb(t){return typeof t=="object"&&t!==null&&"alg"in t&&t.alg!==void 0&&"enc"in t&&t.enc!==void 0}var vb=class{static async decrypt({key:e,encryptedKey:r,joseHeader:n,crypto:i},a){let s=a?.minP2cCount??1e3;switch(n.alg){case"dir":{if(r!==void 0)throw new Fe(Le.InvalidJwe,'JWE "encrypted_key" is not allowed when using "dir" (Direct Encryption Mode).');if(e instanceof Uint8Array)throw new Fe(Le.InvalidJwe,'Key management "key" must be a Key URI or JWK when using "dir" (Direct Encryption Mode).');return e}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(typeof n.p2c!="number")throw new Fe(Le.InvalidJwe,'JOSE Header "p2c" (PBES2 Count) is missing or not a number.');if(n.p2c<s)throw new Fe(Le.InvalidJwe,`JOSE Header "p2c" (PBES2 Count) is ${n.p2c}, which is below the minimum of ${s}.`);if(typeof n.p2s!="string")throw new Fe(Le.InvalidJwe,'JOSE Header "p2s" (PBES2 salt) is missing or not a string.');if(!(e instanceof Uint8Array))throw new Fe(Le.InvalidJwe,'Key management "key" must be a Uint8Array when using "PBES2" (Key Encryption Mode).');if(r===void 0)throw new Fe(Le.InvalidJwe,'JWE "encrypted_key" is required when using "PBES2" (Key Encryption Mode).');let o;try{o=new Uint8Array([...he.string(n.alg).toUint8Array(),0,...he.base64Url(n.p2s).toUint8Array()])}catch{throw new Fe(Le.EncodingError,'Failed to decode the JOSE Header "p2s" (PBES2 salt) value.')}let d=await i.deriveKey({algorithm:n.alg,baseKeyBytes:e,iterations:n.p2c,salt:o});if(!(d.alg&&["A128KW","A192KW","A256KW"].includes(d.alg)))throw new Fe(Le.AlgorithmNotSupported,`Unsupported Key Encryption Algorithm (alg) value: ${d.alg}`);return await i.unwrapKey({decryptionKey:d,wrappedKeyBytes:r,wrappedKeyAlgorithm:n.enc})}default:throw new Fe(Le.AlgorithmNotSupported,`Unsupported "alg" (Algorithm) Header Parameter value: ${n.alg}`)}}static async encrypt({key:e,joseHeader:r,crypto:n}){let i,a;switch(r.alg){case"dir":{if(a!==void 0)throw new Fe(Le.InvalidJwe,'JWE "encrypted_key" is not allowed when using "dir" (Direct Encryption Mode).');if(e instanceof Uint8Array)throw new Fe(Le.InvalidJwe,'Key management "key" must be a Key URI or JWK when using "dir" (Direct Encryption Mode).');i=e;break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(typeof r.p2c!="number")throw new Fe(Le.InvalidJwe,'JOSE Header "p2c" (PBES2 Count) is missing or not a number.');if(typeof r.p2s!="string")throw new Fe(Le.InvalidJwe,'JOSE Header "p2s" (PBES2 salt) is missing or not a string.');if(!(e instanceof Uint8Array))throw new Fe(Le.InvalidJwe,'Key management "key" must be a Uint8Array when using "PBES2" (Key Encryption Mode).');i=await n.generateKey({algorithm:r.enc});let s;try{s=new Uint8Array([...he.string(r.alg).toUint8Array(),0,...he.base64Url(r.p2s).toUint8Array()])}catch{throw new Fe(Le.EncodingError,'Failed to decode the JOSE Header "p2s" (PBES2 salt) value.')}let o=await n.deriveKey({algorithm:r.alg,baseKeyBytes:e,iterations:r.p2c,salt:s});a=await n.wrapKey({encryptionKey:o,unwrappedKey:i});break}default:throw new Fe(Le.AlgorithmNotSupported,`Unsupported "alg" (Algorithm) Header Parameter value: ${r.alg}`)}return{cek:i,encryptedKey:a}}};function C5(t,e){if(e!==void 0)try{if(typeof e!="string")throw new Error;return he.base64Url(e).toUint8Array()}catch{throw new Fe(Le.InvalidJwe,`Failed to decode the JWE Header parameter '${t}' from Base64 URL format to Uint8Array. Ensure the value is properly encoded in Base64 URL format without padding.`)}}var Pb=class t{constructor(e){this.ciphertext="";Object.assign(this,e)}static async decrypt({jwe:e,key:r,keyManager:n=new Gc,crypto:i=new yo,options:a={}}){if(!Yw(i))throw new Fe(Le.OperationNotSupported,'Crypto API does not support the "encrypt" operation.');if(!Yw(n))throw new Fe(Le.OperationNotSupported,'Key Manager does not support the "decrypt" operation.');if(!e.protected&&!e.header&&!e.unprotected)throw new Fe(Le.InvalidJwe,'JWE is missing the required JOSE header parameters. Please provide at least one of the following: "protected", "header", or "unprotected"');if(typeof e.ciphertext!="string")throw new Fe(Le.InvalidJwe,"JWE Ciphertext is missing or not a string.");let s;if(e.protected)try{s=he.base64Url(e.protected).toObject()}catch{throw new Error("JWE Protected Header is invalid")}if(pH(s,e.header,e.unprotected))throw new Error('Duplicate properties detected. Please ensure that each parameter is defined only once across the JWE "header", "protected", and "unprotected" objects.');let o={...s,...e.header,...e.unprotected};if(!bb(o))throw new Error('JWE Header is missing required "alg" (Algorithm) and/or "enc" (Encryption) Header Parameters');if(Array.isArray(a.allowedAlgValues)&&!a.allowedAlgValues.includes(o.alg))throw new Error(`"alg" (Algorithm) Header Parameter value not allowed: ${o.alg}`);if(Array.isArray(a.allowedEncValues)&&!a.allowedEncValues.includes(o.enc))throw new Error(`"enc" (Encryption Algorithm) Header Parameter value not allowed: ${o.enc}`);let d;try{let p=e.encrypted_key?he.base64Url(e.encrypted_key).toUint8Array():void 0;d=await vb.decrypt({key:r,encryptedKey:p,joseHeader:o,keyManager:n,crypto:i},{minP2cCount:a.minP2cCount})}catch(p){if(p instanceof Fe&&(p.code===Le.InvalidJwe||p.code===Le.AlgorithmNotSupported))throw p;d=typeof r=="string"?await n.generateKey({algorithm:o.enc}):await i.generateKey({algorithm:o.enc})}let l=C5("iv",e.iv),c=C5("tag",e.tag),u=c!==void 0?new Uint8Array([...he.base64Url(e.ciphertext).toUint8Array(),...c??[]]):he.base64Url(e.ciphertext).toUint8Array(),f=e.aad!==void 0?new Uint8Array([...he.string(e.protected??"").toUint8Array(),...he.string(".").toUint8Array(),...he.string(e.aad).toUint8Array()]):he.string(e.protected??"").toUint8Array();return{plaintext:typeof d=="string"?await n.decrypt({keyUri:d,data:u,iv:l,additionalData:f}):await i.decrypt({key:d,data:u,iv:l,additionalData:f}),protectedHeader:s,additionalAuthenticatedData:C5("aad",e.aad),sharedUnprotectedHeader:e.unprotected,unprotectedHeader:e.header}}static async encrypt({key:e,plaintext:r,additionalAuthenticatedData:n,protectedHeader:i,sharedUnprotectedHeader:a,unprotectedHeader:s,keyManager:o=new Gc,crypto:d=new yo}){if(!Yw(d))throw new Fe(Le.OperationNotSupported,'Crypto API does not support the "encrypt" operation.');if(!Yw(o))throw new Fe(Le.OperationNotSupported,'Key Manager does not support the "decrypt" operation.');if(!i&&!a&&!s)throw new Fe(Le.InvalidJwe,'JWE is missing the required JOSE header parameters. Please provide at least one of the following: "protectedHeader", "sharedUnprotectedHeader", or "unprotectedHeader"');if(!(r instanceof Uint8Array))throw new Fe(Le.InvalidJwe,"Plaintext is missing or not a byte array.");if(pH(i,a,s))throw new Error('Duplicate properties detected. Please ensure that each parameter is defined only once across the JWE "protectedHeader", "sharedUnprotectedHeader", and "unprotectedHeader" objects.');let l={...i,...a,...s};if(!bb(l))throw new Error('JWE Header is missing required "alg" (Algorithm) and/or "enc" (Encryption) Header Parameters');let{cek:c,encryptedKey:u}=await vb.encrypt({key:e,joseHeader:l,keyManager:o,crypto:d}),f;switch(l.enc){case"A128GCM":case"A192GCM":case"A256GCM":f=gn.randomBytes(12);break;default:f=new Uint8Array(0)}let h=i?he.object(i).toBase64Url():"",p,m;n?(m=he.uint8Array(n).toBase64Url(),p=he.string(h+"."+m).toUint8Array()):p=he.string(h).toUint8Array();let y=typeof c=="string"?await o.encrypt({keyUri:c,data:r,iv:f,additionalData:p}):await d.encrypt({key:c,data:r,iv:f,additionalData:p}),b=y.slice(0,-16),w=y.slice(-16),S=new t({ciphertext:he.uint8Array(b).toBase64Url()});return u&&(S.encrypted_key=he.uint8Array(u).toBase64Url()),i&&(S.protected=h),a&&(S.unprotected=a),s&&(S.header=s),f&&(S.iv=he.uint8Array(f).toBase64Url()),m&&(S.aad=m),w&&(S.tag=he.uint8Array(w).toBase64Url()),S}};function pH(...t){let e=new Set,r=t.filter(Boolean);for(let n of r)for(let i in n){if(e.has(i))return!0;e.add(i)}return!1}var Gl=class{static async decrypt({jwe:e,key:r,keyManager:n=new Gc,crypto:i=new yo,options:a={}}){if(typeof e!="string")throw new Fe(Le.InvalidJwe,"Invalid JWE format. JWE must be a string.");let{0:s,1:o,2:d,3:l,4:c,length:u}=e.split(".");if(u!==5)throw new Fe(Le.InvalidJwe,"Invalid JWE format. JWE must have 5 parts.");let f=await Pb.decrypt({jwe:{ciphertext:l,encrypted_key:o||void 0,iv:d||void 0,protected:s,tag:c||void 0},key:r,keyManager:n,crypto:i,options:a});if(!bb(f.protectedHeader))throw new Fe(Le.InvalidJwe,"Decrypt operation failed due to missing or malformed JWE Protected Header");return{plaintext:f.plaintext,protectedHeader:f.protectedHeader}}static async encrypt({plaintext:e,protectedHeader:r,key:n,keyManager:i=new Gc,crypto:a=new yo,options:s={}}){let o=await Pb.encrypt({plaintext:e,protectedHeader:r,key:n,keyManager:i,crypto:a,options:s});return[o.protected,o.encrypted_key,o.iv,o.ciphertext,o.tag].join(".")}};g();wn();wn();Yn();g();Er();wn();var lg=class extends $f{constructor(){super(...arguments);this.name="DwnKeyStore";this._recordProtocolDefinition=$G;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"privateJwk",schema:this._recordProtocolDefinition.types.privateJwk.schema}}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async set(r){await super.set(r)}async list(r){return await super.list(r)}async getAllRecords({agent:r,tenantDid:n}){this._index.clear();let{reply:i}=await r.dwn.processRequest({author:n,target:n,messageType:Re.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let s of i.entries??[]){let o;if(s.encryption){let{reply:d}=await r.dwn.processRequest({author:n,target:n,messageType:Re.RecordsRead,messageParams:{filter:{recordId:s.recordId}},encryption:!0}),l=d;if(!l.entry?.data)throw new Error(`${this.name}: Failed to read encrypted key record: ${s.recordId}`);o=await Dm.consumeToJson({readableStream:l.entry.data})}else{if(!s.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);o=he.base64Url(s.encodedData).toObject()}if(vp(o)){let d=`${n}${ki}${wp}${o.kid}`;this._index.set(d,s.recordId),this._cache.set(s.recordId,o),a.push(o)}}return a}},ug=class extends Bf{constructor(){super(...arguments);this.name="InMemoryKeyStore"}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async list(r){return await super.list(r)}async set(r){return await super.set(r)}};var $5={"AES-GCM":{implementation:$m,names:["A128GCM","A192GCM","A256GCM"]},"AES-KW":{implementation:Bm,names:["A128KW","A192KW","A256KW"]},Ed25519:{implementation:Fc,names:["Ed25519"]},secp256k1:{implementation:oc,names:["ES256K","secp256k1"]},secp256r1:{implementation:oc,names:["ES256","secp256r1"]},"SHA-256":{implementation:_u,names:["SHA-256"]},X25519:{implementation:Iu,names:["X25519"]}},go=class{constructor({agent:e,keyStore:r}={}){this._algorithmInstances=new Map;this._agent=e,this._keyStore=r??new ug}get agent(){if(this._agent===void 0)throw new Error("LocalKeyManager: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e}async decrypt({keyUri:e,...r}){let n=await this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return await this.getAlgorithm({algorithm:i}).decrypt({key:n,...r})}digest(e){throw new Error("Method not implemented.")}async encrypt({keyUri:e,...r}){let n=await this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return await this.getAlgorithm({algorithm:i}).encrypt({key:n,...r})}async exportKey({keyUri:e}){return await this.getPrivateKey({keyUri:e})}async generateKey({algorithm:e}){let r=this.getAlgorithmName({key:{alg:e}}),i=await this.getAlgorithm({algorithm:r}).generateKey({algorithm:e});i.kid??=await vt({jwk:i});let a=await this.getKeyUri({key:i});return await this._keyStore.set({id:a,data:i,agent:this.agent,preventDuplicates:!1,useCache:!0}),a}async getKeyUri({key:e}){let r=await vt({jwk:e});return`${wp}${r}`}async getPublicKey({keyUri:e}){let r=await this.getPrivateKey({keyUri:e}),n=this.getAlgorithmName({key:r});return await this.getAlgorithm({algorithm:n}).getPublicKey({key:r})}async derivePublicKey({keyUri:e,derivationPath:r}){let n=await this.getX25519PrivateKeyBytes({keyUri:e}),i=await $s.derivePrivateKeyBytes(n,r),a=await Gt.bytesToPrivateKey({privateKeyBytes:i});return await Gt.getPublicKey({key:a})}async jweKeyUnwrap({keyUri:e,derivationPath:r,encryptedKey:n,ephemeralPublicKey:i}){let a=await this.getX25519PrivateKeyBytes({keyUri:e}),s=await $s.derivePrivateKeyBytes(a,r),o=await Gt.bytesToPrivateKey({privateKeyBytes:s});return Bi.ecdhEsUnwrapKey(o,i,n)}async derivePrivateKeyBytes({keyUri:e,derivationPath:r}){let n=await this.getX25519PrivateKeyBytes({keyUri:e});return $s.derivePrivateKeyBytes(n,r)}async importKey({key:e}){if(!vp(e))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let r=structuredClone(e);r.kid??=await vt({jwk:r});let n=await this.getKeyUri({key:r});return await this._keyStore.set({id:n,data:r,agent:this.agent,preventDuplicates:!0,useCache:!0}),n}async sign({keyUri:e,data:r}){let n=await this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:i}).sign({data:r,key:n})}async unwrapKey({wrappedKeyBytes:e,wrappedKeyAlgorithm:r,decryptionKeyUri:n}){let i=await this.getPrivateKey({keyUri:n}),a=this.getAlgorithmName({key:i});return await this.getAlgorithm({algorithm:a}).unwrapKey({wrappedKeyBytes:e,wrappedKeyAlgorithm:r,decryptionKey:i})}async verify({key:e,signature:r,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:r,data:n})}async wrapKey({unwrappedKey:e,encryptionKeyUri:r}){let n=await this.getPrivateKey({keyUri:r}),i=this.getAlgorithmName({key:n});return await this.getAlgorithm({algorithm:i}).wrapKey({unwrappedKey:e,encryptionKey:n})}async deleteKey({keyUri:e}){if(!await this._keyStore.get({id:e,agent:this.agent,useCache:!0}))throw new Error(`Key not found: ${e}`);await this._keyStore.delete({id:e,agent:this.agent})}getAlgorithm({algorithm:e}){let r=$5[e]?.implementation;if(!r)throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported: ${e}`);return this._algorithmInstances.has(r)||this._algorithmInstances.set(r,new r),this._algorithmInstances.get(r)}getAlgorithmName({key:e}){let r=e.alg,n=e.crv;for(let i of Object.keys($5)){let a=$5[i].names;if(r&&a.includes(r))return i;if(n&&a.includes(n))return i}throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported based on provided input: alg=${r}, crv=${n}. Please check the documentation for the list of supported algorithms.`)}async getX25519PrivateKeyBytes({keyUri:e}){let r=await this.getPrivateKey({keyUri:e});return Gt.privateKeyToBytes({privateKey:r})}async getPrivateKey({keyUri:e}){try{let n=this.agent?.agentDid?.keyManager;if(n&&typeof n.exportKey=="function"){let i=await n.exportKey({keyUri:e});if(i&&vp(i))return i}}catch{}let r=await this._keyStore.get({id:e,agent:this.agent,useCache:!0});if(!r)throw new Error(`Key not found: ${e}`);return r}};function hH(t){return typeof t!="string"||t.trim().length===0}function Vye(t){return typeof t=="object"&&t!==null&&"dateCreated"in t&&typeof t.dateCreated=="string"&&"size"in t&&typeof t.size=="number"&&"data"in t&&typeof t.data=="string"}function Wye(t){return typeof t=="object"&&t!==null&&"initialized"in t&&typeof t.initialized=="boolean"&&"lastBackup"in t&&"lastRestore"in t}var Rh=class{constructor({keyDerivationWorkFactor:e,store:r}={}){this.crypto=new yo;this._keyDerivationWorkFactor=e??21e4,this._store=r??new bu}async backup(){if(this.isLocked()||await this.isInitialized()===!1)throw new Error("HdIdentityVault: Unable to proceed with the backup operation because the identity vault has not been initialized and unlocked. Please ensure the vault is properly initialized with a secure password before attempting to backup its contents.");let e={did:await this.getStoredDid(),contentEncryptionKey:await this.getStoredContentEncryptionKey(),status:await this.getStatus()},r=he.object(e).toBase64Url(),n={data:r,dateCreated:new Date().toISOString(),size:r.length};return await this.setStatus({lastBackup:n.dateCreated}),n}async changePassword({oldPassword:e,newPassword:r}){if(await this.isInitialized()===!1)throw new Error("HdIdentityVault: Unable to proceed with the change password operation because the identity vault has not been initialized. Please ensure the vault is properly initialized with a secure password before trying again.");await this.lock();let n=await this.getStoredContentEncryptionKey(),i,a;try{let o;({plaintext:o,protectedHeader:i}=await Gl.decrypt({jwe:n,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new go,options:{minP2cCount:1}})),a=he.uint8Array(o).toObject()}catch{throw new Error("HdIdentityVault: Unable to change the vault password due to an incorrectly entered old password.")}let s=await Gl.encrypt({key:he.string(r).toUint8Array(),protectedHeader:i,plaintext:he.object(a).toUint8Array(),crypto:this.crypto,keyManager:new go});await this._store.set("contentEncryptionKey",s),this._contentEncryptionKey=a}async getDid(){if(this.isLocked())throw new Error("HdIdentityVault: Vault has not been initialized and unlocked.");let e=await this.getStoredDid(),{plaintext:r}=await Gl.decrypt({jwe:e,key:this._contentEncryptionKey,crypto:this.crypto,keyManager:new go,options:{minP2cCount:1}}),n=he.uint8Array(r).toObject();if(!bh(n))throw new Error("HdIdentityVault: Unable to decode malformed DID in identity vault");return await bs.import({portableDid:n})}async getStatus(){let e=await this._store.get("vaultStatus");if(!e)return{initialized:!1,lastBackup:null,lastRestore:null};let r=he.string(e).toObject();if(!Wye(r))throw new Error("HdIdentityVault: Invalid IdentityVaultStatus object in store");return r.initialized&&(this._cachedInitialized=!0),r}async initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}){if(await this.isInitialized())throw new Error("HdIdentityVault: Vault has already been initialized.");if(hH(e))throw new Error(`HdIdentityVault: The password is required and cannot be blank. Please provide a ' +
2059
2059
  'valid, non-empty password.`);if(r&&hH(r))throw new Error(`HdIdentityVault: The password is required and cannot be blank. Please provide a ' +
2060
- 'valid, non-empty password.`);if(r??=dH(I5,128),!uH(r,I5))throw new Error("HdIdentityVault: The provided recovery phrase is invalid. Please ensure that the recovery phrase is a correctly formatted series of 12 words.");let i=await fH(r),a=JE.fromMasterSeed(i),s=a.derive("m/44'/0'/0'/0'/0'"),o=await this.crypto.deriveKey({algorithm:"HKDF-512",baseKeyBytes:s.privateKey,salt:"",info:"vault_cek",derivedKeyAlgorithm:"A256GCM"}),d=await this.crypto.deriveKeyBytes({algorithm:"HKDF-512",baseKeyBytes:s.publicKey,salt:"",info:"vault_unlock_salt",length:256}),l={alg:"PBES2-HS512+A256KW",enc:"A256GCM",cty:"text/plain",p2c:this._keyDerivationWorkFactor,p2s:he.uint8Array(d).toBase64Url()},c=await Gl.encrypt({key:he.string(e).toUint8Array(),protectedHeader:l,plaintext:he.object(o).toUint8Array(),crypto:this.crypto,keyManager:new go});await this._store.set("contentEncryptionKey",c);let u=a.derive("m/44'/0'/1708523827'/0'/0'"),f=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:u.privateKey}),h=a.derive("m/44'/0'/1708523827'/0'/1'"),p=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:h.privateKey}),m=a.derive("m/44'/0'/1708523827'/0'/2'"),y=await this.crypto.bytesToPrivateKey({algorithm:"X25519",privateKeyBytes:m.privateKey}),b=new UE;await b.addPredefinedKeys({privateKeys:[f,p,y]});let w={verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]};n&&n.length&&(w.services=[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:n}]);let k=await(await po.create({keyManager:b,options:w})).export(),T={alg:"dir",enc:"A256GCM",cty:"json"},D=await Gl.encrypt({key:o,plaintext:he.object(k).toUint8Array(),protectedHeader:T,crypto:this.crypto,keyManager:new go});return await this._store.set("did",D),this._contentEncryptionKey=o,await this.setStatus({initialized:!0}),r}async isInitialized(){return this._cachedInitialized===!0?!0:this.getStatus().then(({initialized:e})=>e)}isLocked(){return!this._contentEncryptionKey}async lock(){if(await this.isInitialized()===!1)throw new Error("HdIdentityVault: Lock operation failed. Vault has not been initialized.");this._contentEncryptionKey&&(this._contentEncryptionKey.k=""),this._contentEncryptionKey=void 0}async restore({backup:e,password:r}){if(!Vye(e))throw new Error("HdIdentityVault: Restore operation failed due to invalid backup object.");let n,i,a;try{a=await this.getStoredDid(),i=await this.getStoredContentEncryptionKey(),n=await this.getStatus()}catch{throw new Error("HdIdentityVault: The restore operation cannot proceed because the existing vault contents are missing or inaccessible. If the problem persists consider re-initializing the vault and retrying the restore.")}try{let s=he.base64Url(e.data).toObject();await this._store.set("did",s.did),await this._store.set("contentEncryptionKey",s.contentEncryptionKey),await this.setStatus(s.status),await this.unlock({password:r})}catch{throw await this.setStatus(n),await this._store.set("contentEncryptionKey",i),await this._store.set("did",a),new Error("HdIdentityVault: Restore operation failed due to invalid backup data or an incorrect password. Please verify the password is correct for the provided backup and try again.")}await this.setStatus({lastRestore:new Date().toISOString()})}async unlock({password:e}){await this.lock();let r=await this.getStoredContentEncryptionKey();try{let{plaintext:n}=await Gl.decrypt({jwe:r,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new go,options:{minP2cCount:1}}),i=he.uint8Array(n).toObject();this._contentEncryptionKey=i}catch{throw new Error("HdIdentityVault: Unable to unlock the vault due to an incorrect password.")}}async getStoredDid(){let e=await this._store.get("did");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the DID record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async getStoredContentEncryptionKey(){let e=await this._store.get("contentEncryptionKey");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the Content Encryption Key record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async setStatus({initialized:e,lastBackup:r,lastRestore:n}){let i=await this.getStatus();return i.initialized=e??i.initialized,i.lastBackup=r??i.lastBackup,i.lastRestore=n??i.lastRestore,await this._store.set("vaultStatus",JSON.stringify(i)),this._cachedInitialized=i.initialized,!0}};g();Jo();g();Er();function Jye(t){return!(!t||typeof t!="object"||t===null)&&"name"in t}var fg=class extends $f{constructor(){super(...arguments);this.name="DwnIdentityStore";this._recordProtocolDefinition=NE;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"identityMetadata",schema:this._recordProtocolDefinition.types.identityMetadata.schema}}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async set(r){return await super.set(r)}async list(r){return await super.list(r)}async getAllRecords({agent:r,tenantDid:n}){this._index.clear();let{reply:i}=await r.dwn.processRequest({author:n,target:n,messageType:Re.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=he.base64Url(s.encodedData).toObject();if(Jye(o)){let d=`${n}${ki}${o.uri}`;this._index.set(d,s.recordId),this._cache.set(s.recordId,o),a.push(o)}}return a}},pg=class extends Bf{constructor(){super(...arguments);this.name="InMemoryIdentityStore"}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async list(r){return await super.list(r)}async set(r){return await super.set(r)}};function SWe(t){return!(!t||typeof t!="object"||t===null)&&"did"in t&&"metadata"in t&&bh(t.did)}var Ch=class{constructor({agent:e,store:r}={}){this._agent=e,this._store=r??new pg}get agent(){if(this._agent===void 0)throw new Error("AgentIdentityApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e}get tenant(){if(!this._agent)throw new Error("AgentIdentityApi: The agent must be set to perform tenant specific actions.");return this._agent.agentDid.uri}async create({metadata:e,didMethod:r="dht",didOptions:n,store:i}){let a=await this.agent.did.create({method:r,options:n,tenant:this.tenant,store:i}),s=new ig({did:a,metadata:{...e,uri:a.uri,tenant:this.tenant}});return(i??!0)&&await this._store.set({id:s.did.uri,data:s.metadata,agent:this.agent,tenant:s.metadata.tenant,preventDuplicates:!1,useCache:!0}),s}async export({didUri:e}){let r=await this.get({didUri:e});if(!r)throw new Error(`AgentIdentityApi: Failed to export due to Identity not found: ${e}`);return await r.export()}async get({didUri:e}){let r=await this._store.get({id:e,agent:this.agent,useCache:!0});if(!r)return;let n=await this.agent.did.get({didUri:e,tenant:r.tenant});if(!n)throw new Error(`AgentIdentityApi: Identity is present in the store but DID is missing: ${e}`);return new ig({did:n,metadata:r})}async import({portableIdentity:e}){e.metadata.tenant=this.tenant;let r=await this.agent.did.import({portableDid:e.portableDid,tenant:e.metadata.tenant});if(!r)throw new Error(`AgentIdentityApi: Failed to import Identity: ${e.metadata.uri}`);let n=new ig({did:r,metadata:e.metadata});return await this._store.set({id:n.did.uri,data:n.metadata,agent:this.agent,tenant:n.metadata.tenant,preventDuplicates:!0,useCache:!0}),n}async list({tenant:e}={}){let r=await this._store.list({agent:this.agent,tenant:e});return(await Promise.all(r.map(i=>this.get({didUri:i.uri})))).filter(i=>typeof i<"u")}async delete({didUri:e}){if(!await this._store.get({id:e,agent:this.agent,useCache:!0}))throw new Error(`AgentIdentityApi: Failed to purge due to Identity not found: ${e}`);await this._store.delete({id:e,agent:this.agent})}getDwnEndpoints({didUri:e}){return this.agent.dwn.getDwnEndpointUrlsForTarget(e)}async setDwnEndpoints({didUri:e,endpoints:r}){let n=await this.agent.did.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set DWN endpoints due to DID not found: ${e}`);let i=await n.export(),a=i.document.service?.find(s=>s.id.endsWith("dwn"));if(a)a.serviceEndpoint=r;else{let s={id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:r};i.document.service?i.document.service.push(s):i.document.service=[s]}await this.agent.did.update({portableDid:i,tenant:this.agent.agentDid.uri})}async setMetadataName({didUri:e,name:r}){if(!r)throw new Error("AgentIdentityApi: Failed to set metadata name due to missing name value.");let n=await this.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set metadata name due to Identity not found: ${e}`);if(n.metadata.name===r)throw new Error("AgentIdentityApi: No changes detected.");await this._store.set({id:n.did.uri,data:{...n.metadata,name:r},agent:this.agent,tenant:n.metadata.tenant,updateExisting:!0,useCache:!0})}async connectedIdentity({connectedDid:e}={}){let r=await this.list();if(!(r.length<1))return e?r.find(n=>n.metadata.connectedDid===e):r.find(n=>n.metadata.connectedDid!==void 0)}};g();Yn();Er();var Ka=class t{constructor({agent:e}={}){this._cachedPermissions=new cs.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:r,delegate:n,messageType:i,protocol:a,cached:s=!1}){let o=[e,r,i,a].join("~"),d=s?this._cachedPermissions.get(o):void 0;if(d)return d;let l=await this.fetchGrants({author:r,target:r,grantor:e,grantee:r}),c=await t.matchGrantFromArray(e,r,{messageType:i,protocol:a},l,n);if(!c)throw new Error(`CachedPermissions: No permissions found for ${i}: ${a}`);return this._cachedPermissions.set(o,c),c}async fetchGrants({author:e,target:r,grantee:n,grantor:i,protocol:a,remote:s=!1,checkRevoked:o=!0}){let d=a?{protocol:a}:void 0,l={author:e,target:r,messageType:Re.RecordsQuery,messageParams:{filter:{author:i,recipient:n,protocol:dt.uri,protocolPath:dt.grantPath,tags:d}}},{reply:c}=s?await this.agent.sendDwnRequest(l):await this.agent.processDwnRequest(l);if(c.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${c.status.detail}`);let u=o?await this.fetchRevokedGrantIds({author:e,target:r,grantor:i,remote:s,tags:d}):new Set,f=[];for(let h of c.entries){if(u.has(h.recordId))continue;let p=Ir.parse(h);f.push({grant:p,message:h})}return f}async fetchRevokedGrantIds({author:e,target:r,grantor:n,remote:i,tags:a}){let s={author:e,target:r,messageType:Re.RecordsQuery,messageParams:{filter:{author:n,protocol:dt.uri,protocolPath:dt.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 d=new Set;for(let l of o.entries)l.descriptor.parentId!==void 0&&d.add(l.descriptor.parentId);return d}async fetchRequests({author:e,target:r,protocol:n,remote:i=!1}){let a=n?{protocol:n}:void 0,s={author:e,target:r,messageType:Re.RecordsQuery,messageParams:{filter:{protocol:dt.uri,protocolPath:dt.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 d=[];for(let l of o.entries){let c=cd.parse(l);d.push({request:c,message:l})}return d}async isGrantRevoked({author:e,target:r,grantRecordId:n,remote:i=!1}){let a={author:e,target:r,messageType:Re.RecordsRead,messageParams:{filter:{parentId:n,protocol:dt.uri,protocolPath:dt.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:r,store:n=!1,delegated:i=!1,...a}=e,s;dt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope},d=he.object(o).toUint8Array(),l={recipient:a.grantedTo,protocol:dt.uri,protocolPath:dt.grantPath,dataFormat:"application/json",tags:s},{reply:c,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${c.status.detail}`);let f={...u,encodedData:he.uint8Array(d).toBase64Url()};return{grant:Ir.parse(f),message:f}}async createRequest(e){let{author:r,store:n=!1,delegated:i=!1,...a}=e,s;dt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={description:a.description,delegated:i,scope:a.scope},d=he.object(o).toUint8Array(),l={protocol:dt.uri,protocolPath:dt.requestPath,dataFormat:"application/json",tags:s},{reply:c,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${c.status.detail}`);let f={...u,encodedData:he.uint8Array(d).toBase64Url()};return{request:cd.parse(f),message:f}}async createRevocation(e){let{author:r,store:n=!1,grant:i,description:a}=e,s={description:a},o=he.object(s).toUint8Array(),d;dt.hasProtocolScope(i.scope)&&(d={protocol:i.scope.protocol});let l={parentContextId:i.id,protocol:dt.uri,protocolPath:dt.revocationPath,dataFormat:"application/json",tags:d},{reply:c,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([o])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${c.status.detail}`);return{message:{...u,encodedData:he.uint8Array(o).toBase64Url()}}}async clear(){this._cachedPermissions.clear()}static async matchGrantFromArray(e,r,n,i,a=!1){let s;for(let o of i){let{grant:d,message:l}=o;if(a===!0&&d.delegated!==!0)continue;let{messageType:c,protocol:u,protocolPath:f,contextId:h}=n;if(this.matchScopeFromGrant(e,r,c,d,u,f,h)){if(d.scope.interface+d.scope.method===c)return{grant:d,message:l};s||(s={grant:d,message:l})}}return s}static matchScopeFromGrant(e,r,n,i,a,s,o){if(i.grantee!==r||i.grantor!==e)return!1;let d=i.scope,l=d.interface+d.method;if(l===n||l===Re.MessagesRead&&(n===Re.MessagesSync||n===Re.MessagesSubscribe))if(v5(n)){let u=d;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=d;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();var EH=An(qE(),1);Yn();import{Level as Qye}from"level";g();Yn();function mH(t){let e=t.descriptor;return e.interface!==be.Records||e.method!==ge.Write?!1:e.dateCreated===e.messageTimestamp}function hg(t){if(t.length<=1)return t;let e=new Map,r=new Map,n=new Map,i=new Map;for(let c=0;c<t.length;c++){let u=t[c];e.set(c,u);let f=u.message.descriptor;if(f.interface===be.Protocols&&f.method===ge.Configure){let h=f.definition?.protocol;h&&r.set(h,c)}if(f.interface===be.Records&&f.method===ge.Write){let h=u.message.recordId;mH(u.message)&&h&&n.set(h,c),f.protocol===dt.uri&&f.protocolPath===dt.grantPath&&h&&i.set(h,c)}}let a=new Map,s=new Array(t.length).fill(0),o=(c,u)=>{if(c===u)return;a.has(c)||a.set(c,new Set);let f=a.get(c);f.has(u)||(f.add(u),s[u]++)};for(let c=0;c<t.length;c++){let u=t[c].message.descriptor;if(u.interface===be.Records){let h=u.protocol;h&&r.has(h)&&o(r.get(h),c)}if(u.interface===be.Records&&u.parentId){let h=u.parentId;n.has(h)&&o(n.get(h),c)}if(u.interface===be.Records&&u.method===ge.Write){let h=t[c].message.recordId;h&&!mH(t[c].message)&&n.has(h)&&o(n.get(h),c)}if(u.interface===be.Records&&u.method===ge.Delete){let h=u.recordId;h&&n.has(h)&&o(n.get(h),c)}let f=u.permissionGrantId;f&&i.has(f)&&o(i.get(f),c)}let d=[];for(let c=0;c<t.length;c++)s[c]===0&&d.push(c);let l=[];for(;d.length>0;){let c=d.shift();l.push(e.get(c));let u=a.get(c);if(u)for(let f of u)s[f]--,s[f]===0&&d.push(f)}if(l.length<t.length){let c=new Set(l);for(let u=0;u<t.length;u++){let f=e.get(u);c.has(f)||l.push(f)}}return l}g();Yn();var Zye=1048576;function gH(t){return t.status.code===202||t.status.code===204||t.status.code===409||t.entry?.message.descriptor.interface===be.Records&&t.entry?.message.descriptor.method===ge.Delete&&t.status.code===404}async function wH(t){try{return await we.getCid(t)}catch{return"unknown"}}async function vH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,prefetched:a,agent:s,permissionsApi:o}){let d=[];if(a)for(let p of a){if(!p.message)continue;let m={message:p.message};if(p.encodedData){let y=De.base64UrlToBytes(p.encodedData);m.bufferedData=y,m.dataStream=new ReadableStream({start(b){b.enqueue(y),b.close()}})}d.push(m)}let l=i.length>0?await yH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:s,permissionsApi:o}):[],c=[...d,...l],u=hg(c);await Yye(u);let f=3,h=u;for(let p=0;p<=f&&h.length>0;p++){let m=[];for(let y of h){let b=y.bufferedData?new ReadableStream({start(S){S.enqueue(y.bufferedData),S.close()}}):y.dataStream,w=await s.dwn.processRawMessage(t,y.message,{dataStream:b});gH(w)||m.push(y)}if(m.length>0){let y=[],b=[];for(let w of m)if(w.bufferedData||!w.dataStream)b.push(w);else{let S=await wH(w.message);y.push(S)}if(y.length>0){let w=await yH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:y,agent:s,permissionsApi:o});b.push(...w)}h=hg(b)}else h=[]}}async function Yye(t){for(let e of t){if(!e.dataStream)continue;let r=[],n=0,i=!1,a=e.dataStream.getReader();try{for(;;){let{done:d,value:l}=await a.read();if(d)break;if(n+=l.byteLength,n>Zye){i=!0;break}r.push(l)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let s=new Uint8Array(n),o=0;for(let d of r)s.set(d,o),o+=d.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(d){d.enqueue(s),d.close()}})}}async function yH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:s}){let o=[],d;if(r)try{d=(await s.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id}catch(u){return console.error("SyncEngineLevel: pull - Error fetching MessagesRead permission grant for delegate DID",u),o}let l=4,c=0;for(;c<i.length;){let u=i.slice(c,c+l);c+=l;let f=await Promise.all(u.map(async h=>{let p=await a.processDwnRequest({store:!1,author:t,target:t,messageType:Re.MessagesRead,granteeDid:r,messageParams:{messageCid:h,permissionGrantId:d}}),m;try{m=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,message:p.message})}catch(w){console.error(`SyncEngineLevel: pull - failed to read ${h} from ${e}:`,w.message??w);return}if(m.status.code!==200||!m.entry?.message)return;let y=m.entry,b;return Ll(y)&&y.data&&(b=y.data),{message:y.message,dataStream:b}}));for(let h of f)h&&o.push(h)}return o}async function B5({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:s}){let o=[];for(let l of i){let c=await Xye({author:t,messageCid:l,delegateDid:r,protocol:n,agent:a,permissionsApi:s});c&&o.push(c)}let d=hg(o);for(let l of d)try{let c=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,data:l.dataStream,message:l.message});if(!gH(c)){let u=await wH(l.message);console.error(`SyncEngineLevel: push failed for ${u}: ${c.status.code} ${c.status.detail}`)}}catch(c){let u=c.message??c;throw new Error(`SyncEngineLevel: push to ${e} failed: ${u}`)}}async function Xye({author:t,delegateDid:e,protocol:r,messageCid:n,agent:i,permissionsApi:a}){let s;if(e)try{s=(await a.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesRead,delegateDid:e,protocol:r,cached:!0})).grant.id}catch(c){console.error("SyncEngineLevel: push - Error fetching MessagesRead permission grant for delegate DID",c);return}let{reply:o}=await i.dwn.processRequest({author:t,target:t,messageType:Re.MessagesRead,granteeDid:e,messageParams:{messageCid:n,permissionGrantId:s}});if(o.status.code!==200||!o.entry)return;let d=o.entry,l={message:d.message};return Ll(d)&&d.data&&(l.dataStream=d.data),l}var bH=16,PH=8,ege=4,O5=class{constructor(e){this._waiting=[];this._permits=e}async acquire(){if(this._permits>0){this._permits--;return}return new Promise(e=>{this._waiting.push(e)})}release(){let e=this._waiting.shift();e?e():this._permits++}async run(e){await this.acquire();try{return await e()}finally{this.release()}}},xH="^",tge=250,Of=class Of{constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1;this._syncMode="poll";this._liveSubscriptions=[];this._localSubscriptions=[];this._connectivityState="unknown";this._pendingPushCids=new Map;this._consecutiveFailures=0;this._agent=e,this._permissionsApi=new Ka({agent:e}),this._db=n||new Qye(r??"DATA/AGENT/SYNC_STORE")}get agent(){if(this._agent===void 0)throw new Error("SyncEngineLevel: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._permissionsApi=new Ka({agent:e})}get connectivityState(){return this._connectivityState}async clear(){await this._permissionsApi.clear(),await this._db.clear()}async close(){await this._db.close()}async registerIdentity({did:e,options:r}){let n=this._db.sublevel("registeredIdentities");if(await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is already registered.`);r??={protocols:[]},await n.put(e,JSON.stringify(r))}async unregisterIdentity(e){let r=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await r.del(e)}async getIdentityOptions(e){let r=this._db.sublevel("registeredIdentities");try{let n=await r.get(e);if(n)return JSON.parse(n)}catch(n){let i=n;if(i.code==="LEVEL_NOT_FOUND")return;throw new Error(`SyncEngineLevel: Error reading level: ${i.code}.`)}}async updateIdentityOptions({did:e,options:r}){let n=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await n.put(e,JSON.stringify(r))}async sync(e){if(this._syncLock)throw new Error("SyncEngineLevel: Sync operation is already in progress.");this._syncLock=!0;try{let r=await this.getSyncTargets(),n=new Set,i=!1;for(let a of r){let{did:s,delegateDid:o,dwnUrl:d,protocol:l}=a;if(!n.has(d))try{let c=await this.getLocalRoot(s,o,l),u=await this.getRemoteRoot(s,d,o,l);if(c===u)continue;let f=await this.diffWithRemote({did:s,dwnUrl:d,delegateDid:o,protocol:l});if((!e||e==="pull")&&f.onlyRemote.length>0){let h=[],p=[];for(let m of f.onlyRemote)m.message?m.message.descriptor.interface==="Records"&&m.message.descriptor.method==="Write"&&m.message.descriptor.dataCid&&!m.encodedData?p.push(m.messageCid):h.push(m):p.push(m.messageCid);await this.pullMessages({did:s,dwnUrl:d,delegateDid:o,protocol:l,messageCids:p,prefetched:h})}(!e||e==="push")&&f.onlyLocal.length>0&&await this.pushMessages({did:s,dwnUrl:d,delegateDid:o,protocol:l,messageCids:f.onlyLocal})}catch(c){n.add(d),i=!0,console.error(`SyncEngineLevel: Error syncing ${s} with ${d}`,c)}}i?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):(this._consecutiveFailures=0,r.length>0&&(this._connectivityState="online"))}finally{this._syncLock=!1}}async startSync(e){let r=e.mode??"poll",n=e.interval??(r==="live"?"5m":"2m"),i=(0,EH.default)(n);(this._liveSubscriptions.length>0||this._localSubscriptions.length>0)&&await this.teardownLiveSync(),this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncMode=r,r==="live"?await this.startLiveSync(i):await this.startPollSync(i)}async stopSync(e=2e3){let r=0;for(;this._syncLock;){if(r>=e)throw new Error(`SyncEngineLevel: Existing sync operation did not complete within ${e} milliseconds.`);r+=100,await new Promise(n=>{setTimeout(n,e<100?e:100)})}this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),await this.teardownLiveSync()}async startPollSync(e){let r=async()=>{if(this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{await this.sync()}catch(a){console.error("SyncEngineLevel: Error during sync operation",a)}let n=Math.min(Math.pow(2,this._consecutiveFailures),Of.MAX_BACKOFF_MULTIPLIER),i=this._consecutiveFailures>0?e*n:e;this._syncIntervalId||(this._syncIntervalId=setInterval(r,i))};this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(r,e),this._syncLock||await this.sync()}async startLiveSync(e){try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=await this.getSyncTargets();for(let i of r)try{await this.openLivePullSubscription(i),await this.openLocalPushSubscription(i)}catch(a){console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,a)}let n=async()=>{if(!this._syncLock)try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during SMT integrity check",i)}};this._syncIntervalId=setInterval(n,e)}async teardownLiveSync(){this._pushDebounceTimer&&(clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=void 0),this._pendingPushCids.clear();for(let e of this._liveSubscriptions)try{await e.close()}catch{}this._liveSubscriptions=[];for(let e of this._localSubscriptions)try{await e.close()}catch{}this._localSubscriptions=[]}async openLivePullSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=this.buildCursorKey(r,i,a),o=await this.getCursor(s),d=a?[{protocol:a}]:[],l;if(n)try{l=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{try{l=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch(h){console.error("SyncEngineLevel: Could not find permission grant for live pull subscription",h);return}}let c=async h=>{if(h.type==="eose"){await this.setCursor(s,h.cursor),this._connectivityState="online";return}if(h.type==="event"){let p=h.event;try{let m=this.extractDataStream(p);await this.agent.dwn.processRawMessage(r,p.message,{dataStream:m})}catch(m){console.error(`SyncEngineLevel: Error processing live-pull event for ${r}`,m)}await this.setCursor(s,h.cursor)}},f=(await this.agent.dwn.sendRequest({author:r,target:r,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:d,cursor:o,permissionGrantId:l},subscriptionHandler:c})).reply;if(f.status.code!==200||!f.subscription){console.error(`SyncEngineLevel: MessagesSubscribe failed for ${r} -> ${i}: ${f.status.code} ${f.status.detail}`);return}this._liveSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await f.subscription.close()}}),this._connectivityState="online"}async openLocalPushSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=a?[{protocol:a}]:[],o;if(n)try{o=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{return}let d=u=>{if(u.type!=="event")return;let f=this.buildCursorKey(r,i,a),h=this.tryGetCidSync(u.event.message);if(h===void 0)return;let p=this._pendingPushCids.get(f);p||(p={did:r,dwnUrl:i,delegateDid:n,protocol:a,cids:[]},this._pendingPushCids.set(f,p)),p.cids.push(h),this._pushDebounceTimer&&clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=setTimeout(()=>{this.flushPendingPushes()},tge)},c=(await this.agent.dwn.processRequest({author:r,target:r,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:s,permissionGrantId:o},subscriptionHandler:d})).reply;if(c.status.code!==200||!c.subscription){console.error(`SyncEngineLevel: Local MessagesSubscribe failed for ${r}: ${c.status.code} ${c.status.detail}`);return}this._localSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await c.subscription.close()}})}async flushPendingPushes(){this._pushDebounceTimer=void 0;let e=[...this._pendingPushCids.entries()];this._pendingPushCids.clear();for(let[,r]of e){let{did:n,dwnUrl:i,delegateDid:a,protocol:s,cids:o}=r;if(o.length!==0)try{await B5({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:o,agent:this.agent,permissionsApi:this._permissionsApi})}catch(d){console.error(`SyncEngineLevel: Push-on-write failed for ${n} -> ${i}`,d)}}}buildCursorKey(e,r,n){let i=`${e}${xH}${r}`;return n?`${i}${xH}${n}`:i}async getCursor(e){let r=this._db.sublevel("syncCursors");try{return await r.get(e)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async setCursor(e,r){await this._db.sublevel("syncCursors").put(e,r)}extractDataStream(e){if(Ll(e)&&e.data)return e.data}tryGetCidSync(e){let r;return we.getCid(e).then(n=>{r=n}),r??e.messageCid??void 0}async getDefaultHashHex(e){if(this._defaultHashHex===void 0){let r=await Pl(),n=new Map;for(let i=0;i<=bH;i++)n.set(i,sn(r[i]));this._defaultHashHex=n}return this._defaultHashHex.get(e)??""}static parseBitPrefix(e){return Array.from(e,r=>r==="1")}get stateIndex(){if(!this.agent.dwn.isRemoteMode)return this.agent.dwn.node.storage.stateIndex}async getLocalRoot(e,r,n){let i=this.stateIndex;if(i){let d=n!==void 0?await i.getProtocolRoot(e,n):await i.getRoot(e);return sn(d)}let a=await this.getSyncPermissionGrantId(e,r,n);return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:a}})).reply.root??""}async getRemoteRoot(e,r,n,i){let a=await this.getSyncPermissionGrantId(e,n,i),s=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"root",protocol:i,permissionGrantId:a}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:s.message})).root??""}async walkTreeDiff({did:e,dwnUrl:r,delegateDid:n,protocol:i}){let a=[],s=[],o=await this.getSyncPermissionGrantId(e,n,i),d=new O5(ege),l=async c=>{let[u,f]=await Promise.all([this.getLocalSubtreeHash(e,c,n,i,o),d.run(()=>this.getRemoteSubtreeHash(e,r,c,n,i,o))]);if(u===f)return;let h=await this.getDefaultHashHex(c.length);if(f===h&&u!==h){let p=await this.getLocalLeaves(e,c,n,i,o);a.push(...p);return}if(u===h&&f!==h){let p=await d.run(()=>this.getRemoteLeaves(e,r,c,n,i,o));s.push(...p);return}if(c.length>=bH){let[p,m]=await Promise.all([this.getLocalLeaves(e,c,n,i,o),d.run(()=>this.getRemoteLeaves(e,r,c,n,i,o))]),y=new Set(p),b=new Set(m);for(let w of p)b.has(w)||a.push(w);for(let w of m)y.has(w)||s.push(w);return}await Promise.all([l(c+"0"),l(c+"1")])};return await l(""),{onlyLocal:a,onlyRemote:s}}async diffWithRemote({did:e,dwnUrl:r,delegateDid:n,protocol:i}){let a=await this.collectLocalSubtreeHashes(e,i,PH),s=await this.getSyncPermissionGrantId(e,n,i),o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"diff",protocol:i,hashes:a,depth:PH,permissionGrantId:s}}),d=await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message});if(d.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${d.status.code}: ${d.status.detail}`);let l=await this.getSyncPermissionGrantId(e,n,i),c=[];for(let u of d.onlyLocal??[]){let f=await this.getLocalLeaves(e,u,n,i,l);c.push(...f)}return{onlyRemote:d.onlyRemote??[],onlyLocal:c}}async collectLocalSubtreeHashes(e,r,n){let i={},a=await this.getDefaultHashHex(n),s=this.stateIndex,o=async(d,l)=>{let c;if(s){let u=Of.parseBitPrefix(d),f=r!==void 0?await s.getProtocolSubtreeHash(e,r,u):await s.getSubtreeHash(e,u);c=sn(f)}else c=await this.getLocalSubtreeHash(e,d,void 0,r);if(c!==a){if(l>=n){i[d]=c;return}await Promise.all([o(d+"0",l+1),o(d+"1",l+1)])}};return await o("",0),i}async getLocalSubtreeHash(e,r,n,i,a){let s=this.stateIndex;if(s){let l=Of.parseBitPrefix(r),c=i!==void 0?await s.getProtocolSubtreeHash(e,i,l):await s.getSubtreeHash(e,l);return sn(c)}return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash??""}async getRemoteSubtreeHash(e,r,n,i,a,s){let o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:i,messageParams:{action:"subtree",prefix:n,protocol:a,permissionGrantId:s}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).hash??""}async getLocalLeaves(e,r,n,i,a){let s=this.stateIndex;if(s){let l=Of.parseBitPrefix(r);return i!==void 0?await s.getProtocolLeaves(e,i,l):await s.getLeaves(e,l)}return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries??[]}async getRemoteLeaves(e,r,n,i,a,s){let o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:i,messageParams:{action:"leaves",prefix:n,protocol:a,permissionGrantId:s}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).entries??[]}async pullMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s}){return vH({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:this.agent,permissionsApi:this._permissionsApi})}async pushMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a}){return B5({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:this.agent,permissionsApi:this._permissionsApi})}static topologicalSort(e){return hg(e)}async getSyncTargets(){let e=[];for await(let[r,n]of this._db.sublevel("registeredIdentities").iterator()){let i;try{i=JSON.parse(n)}catch{i={protocols:[]}}let{protocols:a,delegateDid:s}=i,o=await this.agent.dwn.getDwnEndpointUrlsForTarget(r);if(o.length!==0)for(let d of o)if(a.length===0)e.push({did:r,delegateDid:s,dwnUrl:d});else for(let l of a)e.push({did:r,delegateDid:s,dwnUrl:d,protocol:l})}return e}async getSyncPermissionGrantId(e,r,n){if(r)try{return(await this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Re.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id}catch(i){console.error("SyncEngineLevel: Error fetching MessagesSync permission grant for delegate DID",i);return}}};Of.MAX_CONSECUTIVE_FAILURES=5,Of.MAX_BACKOFF_MULTIPLIER=4;var mg=Of;g();Yn();Jo();Er();import{Level as pge}from"level";g();g();g();Er();wn();g();g();var SH=An(qE(),1);Er();var yg=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},XE=class{constructor({ttl:e="15m"}={}){this.cache=new cs.default({ttl:(0,SH.default)(e)})}get(e){return yg(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return yg(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return yg(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return yg(this,void 0,void 0,function*(){this.cache.clear()})}open(){return yg(this,void 0,void 0,function*(){})}close(){return yg(this,void 0,void 0,function*(){})}};g();wn();Yn();g();var gg=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};g();var wg;(function(t){t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.ParseError=-32700]="ParseError",t[t.TransportError=-32300]="TransportError",t[t.BadRequest=-50400]="BadRequest",t[t.Unauthorized=-50401]="Unauthorized",t[t.Forbidden=-50403]="Forbidden",t[t.Conflict=-50409]="Conflict",t[t.TooManyRequests=-50429]="TooManyRequests"})(wg||(wg={}));var vg=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),QE=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),AH=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function $h(t){try{return JSON.parse(t)}catch{return null}}var j5=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},rge=3,nge=500,ige=1e4,sge=3e4,kH=new Set([408,429,500,502,503,504]);function oge(t,e){return t instanceof TypeError?!0:e?kH.has(e.status):!1}function age(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=.5+Math.random()*.5;return n*i}function cge(t){let e=t.headers.get("retry-after");if(e===null)return;let r=Number(e);if(!Number.isNaN(r)&&r>=0)return r*1e3;let n=new Date(e);if(!Number.isNaN(n.getTime())){let i=n.getTime()-Date.now();return i>0?i:0}}var eS=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new XE,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:rge,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:nge,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:ige}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return j5(this,void 0,void 0,function*(){var r,n,i;let a=gn.randomUuid(),s=vg(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},d={method:"POST",headers:o};if(e.data){o["content-type"]="application/octet-stream";let h=e.data;if(h instanceof ReadableStream)if(t.isBunRuntime()){let p=yield Yt.toBytes(h);h=new Blob([p],{type:"application/octet-stream"})}else d.duplex="half";d.body=h}let l=yield this.fetchWithRetry(e.dwnUrl,d);if(l.status===429){let h=parseInt((r=l.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new gg(h)}let c,u=l.headers.has("dwn-response");if(u){let h=$h(l.headers.get("dwn-response"));if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);c=h}else{let h=yield l.text(),p=$h(h);if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${l.status}`);c=p}if(c.error){let{code:h,message:p}=c.error;if(h===wg.TooManyRequests){let m=(i=(n=c.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new gg(m)}throw new Error(`(${h}) - ${p}`)}let{reply:f}=c.result;if(u){let h=new Uint8Array(yield l.arrayBuffer()),p=Yt.fromBytes(h);f.record?f.record.data=p:f.entry&&(f.entry.data=p)}return f})}getServerInfo(e){return j5(this,void 0,void 0,function*(){var r;let n=yield this.serverInfoCache.get(e);if(n)return n;let i=new URL(e);i.pathname.endsWith("/")?i.pathname+="info":i.pathname+="/info";try{let a=yield this.fetchWithRetry(i.toString());if(a.status===429){let s=parseInt((r=a.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new gg(s)}if(a.ok){let s=yield a.json(),o={maxFileSize:s.maxFileSize,maxInFlight:s.maxInFlight,providerAuth:s.providerAuth,registrationRequirements:s.registrationRequirements,server:s.server,sdkVersion:s.sdkVersion,url:s.url,version:s.version,webSocketSupport:s.webSocketSupport};return this.serverInfoCache.set(e,o),o}else throw new Error(`HTTP (${a.status}) - ${a.statusText}`)}catch(a){throw new Error(`Error encountered while processing response from ${i.toString()}: ${a.message}`)}})}fetchWithRetry(e,r){return j5(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let d=0;d<=n;d++){try{let f=AbortSignal.timeout(sge),h=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),p=yield fetch(e,h);if(!kH.has(p.status)||d===n)return p;o=p}catch(f){if(!oge(f)||d===n)throw f;s=f}let l=o?cge(o):void 0,c=age(d,i,a),u=l!==void 0?Math.max(l,c):c;yield new Promise(f=>{setTimeout(f,u)})}if(o)return o;throw s})}};g();wn();var xb=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})};function M5(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var _H=3e3,dge=3e4,lge=1e3,uge=3e4,fge=1/0,tS=class t{constructor(e,r,n,i){this.socket=e,this.responseTimeout=r,this.messageHandlers=new Map,this.subscriptionHandlerIds=new Set,this.closedByUser=!1,this.reconnecting=!1,this._isConnected=!1,this.url=n,this.options=i,this._isConnected=!0}get isConnected(){return this._isConnected}static connect(e){return xb(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=_H,responseTimeout:s=dge}=n,o;try{o=yield t.createWebSocket(r,a)}catch(l){throw(i=n.onerror)===null||i===void 0||i.call(n,l),l}let d=new t(o,s,r,n);return d.wireSocket(o),d})}close(){this.closedByUser=!0,this._isConnected=!1,this.socket.close()}request(e){return xb(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=gn.randomUuid());let a=s=>{let o=$h(M5(s.data));if(o.id===e.id)return this.messageHandlers.delete(e.id),r(o)};this.messageHandlers.set(e.id,a),this.send(e),setTimeout(()=>{this.messageHandlers.delete(e.id),n(new Error("request timed out"))},this.responseTimeout)})})}subscribe(e,r){return xb(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=d=>{let l=$h(M5(d.data));l.id===n&&(l.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),r(l))};this.messageHandlers.set(n,a),this.subscriptionHandlerIds.add(n);let s=yield this.request(e);return s.error?(i?this.messageHandlers.set(n,i):(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n)),{response:s}):{response:s,close:()=>xb(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=gn.randomUuid(),n=QE(r,"rpc.subscribe.close",{},e);return this.request(n)}send(e){this.socket.send(JSON.stringify(e))}static createWebSocket(e,r){return new Promise((n,i)=>{let a=new WebSocket(e),s=()=>{l(),n(a)},o=c=>{l(),i(c)},d=setTimeout(()=>{l(),a.close(),i(new Error("connect timed out"))},r),l=()=>{clearTimeout(d),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=$h(M5(r.data));if(n===null)return;let i=this.messageHandlers.get(n.id);i&&i(r)}),e.addEventListener("close",()=>{var r,n,i,a,s;if(this._isConnected=!1,this.closedByUser){(n=(r=this.options).onclose)===null||n===void 0||n.call(r);return}this.rejectPendingRequests(),(a=(i=this.options).onclose)===null||a===void 0||a.call(i),((s=this.options.autoReconnect)!==null&&s!==void 0?s:!0)&&!this.reconnecting&&this.attemptReconnect()}),e.addEventListener("error",r=>{var n,i;(i=(n=this.options).onerror)===null||i===void 0||i.call(n,r)})}rejectPendingRequests(){for(let[e,r]of this.messageHandlers)if(!this.subscriptionHandlerIds.has(e)){let n=JSON.stringify({jsonrpc:"2.0",id:e,error:{code:wg.TransportError,message:"WebSocket connection closed unexpectedly"}});r({data:n}),this.messageHandlers.delete(e)}}attemptReconnect(){var e,r,n,i;this.reconnecting=!0;let a=(e=this.options.baseReconnectDelay)!==null&&e!==void 0?e:lge,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:uge,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:fge,d=(i=this.options.connectTimeout)!==null&&i!==void 0?i:_H,l=0,c=()=>xb(this,void 0,void 0,function*(){var u,f,h,p;if(this.closedByUser){this.reconnecting=!1;return}if(l++,l>o){this.reconnecting=!1;return}(f=(u=this.options).onreconnecting)===null||f===void 0||f.call(u,l);let y=Math.min(a*Math.pow(2,l-1),s)*(.5+Math.random()*.5);if(yield new Promise(b=>setTimeout(b,y)),this.closedByUser){this.reconnecting=!1;return}try{let b=yield t.createWebSocket(this.url,d);this.socket=b,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(b),(p=(h=this.options).onreconnected)===null||p===void 0||p.call(h)}catch{yield c()}});c()}};g();g();g();wn();g();wn();var bg=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Eb=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return bg(this,void 0,void 0,function*(){let r=new URL(e.dwnUrl);if(r.protocol!=="ws:"&&r.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${r.protocol}`);if(!t.connections.has(r.host))try{let d=yield t.createConnection(r);t.connections.set(r.host,d)}catch(d){throw new Error(`Error connecting to ${r.host}: ${d.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:s,subscription:o}=e;return o?t.subscriptionRequest(i,a,s,o.handler,o.resubscribeFactory):t.processMessage(i,a,s)})}static createConnection(e){return bg(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield tS.connect(e.toString(),{onclose:()=>{t.connections.delete(r);for(let a of n.values())a.handler({type:"disconnected"})},onreconnecting:a=>{for(let s of n.values())s.handler({type:"reconnecting",attempt:a})},onreconnected:()=>{let a={socket:i,subscriptions:n,url:e.toString()};t.connections.set(r,a),t.resubscribeAll(a)}});return{socket:i,subscriptions:n,url:e.toString()}})}static processMessage(e,r,n){return bg(this,void 0,void 0,function*(){let i=gn.randomUuid(),a=vg(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:d,result:l}=o;if(d!==void 0)throw new Error(`error sending DWN request: ${d.message}`);return l.reply})}static subscriptionRequest(e,r,n,i,a){return bg(this,void 0,void 0,function*(){let s=gn.randomUuid(),o=gn.randomUuid(),d=QE(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:l,subscriptions:c}=e,{response:u,close:f}=yield l.subscribe(d,y=>{let{result:b,error:w}=y;if(w){let k=c.get(o);k&&k.subscription.close(),c.delete(o);return}let S=b.subscription;if(i(S),"cursor"in S&&S.cursor){let k=c.get(o);k&&(k.lastCursor=S.cursor),l.send(AH(o,S.cursor))}}),{error:h,result:p}=u;if(h)throw new Error(`could not subscribe via jsonrpc socket: ${h.message}`);let{reply:m}=p;if(m.subscription&&f){let y=()=>bg(this,void 0,void 0,function*(){c.delete(o),yield f()}),b={subscription:Object.assign(Object.assign({},m.subscription),{close:y}),target:r,message:n,handler:i,resubscribeFactory:a};c.set(o,b),m.subscription.close=y}return m})}static resubscribeAll(e){return bg(this,void 0,void 0,function*(){let r=[...e.subscriptions.entries()];e.subscriptions.clear();for(let[,n]of r)try{let i;n.resubscribeFactory?i=yield n.resubscribeFactory(n.lastCursor):i=n.message,yield t.subscriptionRequest(e,n.target,i,n.handler,n.resubscribeFactory),n.handler({type:"reconnected"})}catch{}})}};Eb.connections=new Map;var Sb=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},TH;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(TH||(TH={}));var Pg=class{constructor(e=[]){this.transportClients=new Map,e=[new K5,new N5,...e];for(let r of e)for(let n of r.transportProtocols)this.transportClients.set(n,r)}get transportProtocols(){return Array.from(this.transportClients.keys())}sendDidRequest(e){return Sb(this,void 0,void 0,function*(){let r=new URL(e.url),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDidRequest(e)})}sendDwnRequest(e){let r=new URL(e.dwnUrl),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDwnRequest(e)}getServerInfo(e){return Sb(this,void 0,void 0,function*(){let r=new URL(e),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.getServerInfo(e)})}},K5=class extends eS{sendDidRequest(e){return Sb(this,void 0,void 0,function*(){let r=gn.randomUuid(),n=vg(r,e.method,{data:e.data}),i=new Request(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a;try{let s=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(s.ok){if(a=yield s.json(),a.error){let{code:o,message:d}=a.error;throw new Error(`JSON RPC (${o}) - ${d}`)}}else throw new Error(`HTTP (${s.status}) - ${s.statusText}`)}catch(s){throw new Error(`Error encountered while processing response from ${e.url}: ${s.message}`)}return a.result})}},N5=class extends Eb{sendDidRequest(e){return Sb(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return Sb(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};g();var IH=class t{constructor(e){this.agent=e.agent,this.agentStores=e.agentStores,this.didResolverCache=e.didResolverCache,this.dwn=e.dwn,this.dwnDataStore=e.dwnDataStore,this.dwnStateIndex=e.dwnStateIndex,this.dwnMessageStore=e.dwnMessageStore,this.syncStore=e.syncStore,this.vaultStore=e.vaultStore,this.dwnResumableTaskStore=e.dwnResumableTaskStore,this.dwnStores=e.dwnStores}async clearStorage(){if(await this.agent.sync.stopSync(),this.agent.agentDid=void 0,await this.didResolverCache.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.syncStore.clear(),await this.vaultStore.clear(),this.agent.vault._cachedInitialized=void 0,await this.agent.permissions.clear(),this.dwnStores.clear(),this.agentStores==="memory"){let{didApi:e,identityApi:r,permissionsApi:n,keyManager:i}=t.useMemoryStores({agent:this.agent});this.agent.did=e,this.agent.identity=r,this.agent.keyManager=i,this.agent.permissions=n}}async clearDwnStores(){await this.syncStore.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.agent.permissions.clear(),this.dwnStores.clear()}async closeStorage(){await this.didResolverCache.close(),await this.dwnDataStore.close(),await this.dwnStateIndex.close(),await this.dwnMessageStore.close(),await this.dwnResumableTaskStore.close(),await this.syncStore.close(),await this.vaultStore.close()}async createAgentDid(){this.agent.agentDid=await po.create({options:{publish:!0,gatewayUri:j.DID_DHT_GATEWAY_URI??"http://localhost:7527",verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]}})}async createIdentity({name:e,testDwnUrls:r}){return await this.agent.identity.create({didMethod:"dht",didOptions:{services:[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:r}],verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]},metadata:{name:e}})}static async setup({agentClass:e,agentStores:r,testDataLocation:n}){r??="memory",n??="__TESTDATA__";let i=G=>`${n}/${G}`,a=new yo,s=new Pg,o={keyStore:new lg,identityStore:new fg,didStore:new cg,clear:()=>{o.keyStore._protocolInitializedCache?.clear(),o.identityStore._protocolInitializedCache?.clear(),o.didStore._protocolInitializedCache?.clear()}},{agentVault:d,didApi:l,identityApi:c,keyManager:u,didResolverCache:f,vaultStore:h,permissionsApi:p}=r==="memory"?t.useMemoryStores():t.useDiskStores({testDataLocation:n,stores:o}),m=new _f({blockstoreLocation:i("DWN_DATASTORE")}),y=new Rf({location:i("DWN_STATEINDEX")}),b=new Df,w=new If({location:i("DWN_RESUMABLETASKSTORE")}),S=new Tf({blockstoreLocation:i("DWN_MESSAGESTORE"),indexLocation:i("DWN_MESSAGEINDEX")}),k=await Fl.createDwn({dataPath:n,dataStore:m,didResolver:l,stateIndex:y,eventLog:b,messageStore:S,resumableTaskStore:w}),T=new Fl({dwn:k,localDwnStrategy:"off"}),D=new pge(i("SYNC_STORE")),K=new mg({db:D}),C=new e({agentVault:d,cryptoApi:a,didApi:l,dwnApi:T,identityApi:c,keyManager:u,permissionsApi:p,rpcClient:s,syncApi:K});return new t({agent:C,agentStores:r,didResolverCache:f,dwn:k,dwnDataStore:m,dwnStateIndex:y,dwnMessageStore:S,dwnResumableTaskStore:w,dwnStores:o,syncStore:D,vaultStore:h})}static useDiskStores({agent:e,testDataLocation:r,stores:n}){let i=m=>`${r}/${m}`,a=new Im({location:i("VAULT_STORE")}),s=new Rh({keyDerivationWorkFactor:1,store:a}),{didStore:o,identityStore:d,keyStore:l}=n,c=new Cf({location:i("DID_RESOLVERCACHE")}),u=new _h({agent:e,didMethods:[po,ho],resolverCache:c,store:o}),f=new Ch({agent:e,store:d}),h=new go({agent:e,keyStore:l}),p=new Ka({agent:e});return{agentVault:s,didApi:u,didResolverCache:c,identityApi:f,keyManager:h,permissionsApi:p,vaultStore:a}}static useMemoryStores({agent:e}={}){let r=new bu,n=new Rh({keyDerivationWorkFactor:1,store:r}),i=new dE,a=new _h({agent:e,didMethods:[po,ho],resolverCache:i,store:new dg}),s=new go({agent:e,keyStore:new ug}),o=new Ch({agent:e,store:new pg}),d=new Ka({agent:e});return{agentVault:n,didApi:a,didResolverCache:i,identityApi:o,keyManager:s,permissionsApi:d,vaultStore:r}}};g();Jo();Er();wn();Yn();function hge({baseURL:t,endpoint:e,authParam:r,tokenParam:n}){switch(e){case"pushedAuthorizationRequest":return hb(t,"par");case"authorize":if(!r)throw new Error("authParam must be provided when building an authorize URL");return hb(t,`authorize/${r}.jwt`);case"callback":return hb(t,"callback");case"token":if(!n)throw new Error("tokenParam must be provided when building a token URL");return hb(t,`token/${n}.jwt`);default:throw new Error(`Unknown connect endpoint: ${e}`)}}async function mge({did:t,data:e}){let r=he.object({alg:"EdDSA",kid:t.document.verificationMethod[0].id,typ:"JWT"}).toBase64Url(),n=he.object(e).toBase64Url(),a=await(await t.getSigner()).sign({data:he.string(`${r}.${n}`).toUint8Array()}),s=he.uint8Array(a).toBase64Url();return`${r}.${n}.${s}`}async function DH({jwt:t}){let[e,r,n]=t.split("."),i=he.base64Url(e).toObject();if(!i.kid)throw new Error('Connect: JWT missing required "kid" header value.');let{didDocument:a}=await ho.resolve(i.kid.split("#")[0]);if(!a)throw new Error("Connect: JWT verification failed \u2014 could not resolve DID.");let{publicKeyJwk:s}=a.verificationMethod?.find(l=>l.id===i.kid)??{};if(!s)throw new Error("Connect: JWT verification failed \u2014 public key not found in DID document.");if(!await new Fc().verify({key:s,signature:he.base64Url(n).toUint8Array(),data:he.string(`${e}.${r}`).toUint8Array()}))throw new Error("Connect: JWT verification failed \u2014 invalid signature.");return he.base64Url(r).toObject()}async function yge({jwt:t,encryptionKey:e}){let r={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT"},n=gn.randomBytes(24),i=he.object(r).toUint8Array(),a=he.string(t).toUint8Array(),s=await Hc.encryptRaw({data:a,keyBytes:e,nonce:n,additionalData:i}),o=s.subarray(0,-16),d=s.subarray(-16);return[he.object(r).toBase64Url(),"",he.uint8Array(n).toBase64Url(),he.uint8Array(o).toBase64Url(),he.uint8Array(d).toBase64Url()].join(".")}async function RH({jwe:t,encryptionKey:e}){let[r,,n,i,a]=t.split("."),s=he.base64Url(e).toUint8Array(),o=he.base64Url(r).toUint8Array(),d=he.base64Url(n).toUint8Array(),l=he.base64Url(i).toUint8Array(),c=he.base64Url(a).toUint8Array(),u=new Uint8Array([...l,...c]),f=await Hc.decryptRaw({data:u,keyBytes:s,nonce:d,additionalData:o});return he.uint8Array(f).toString()}async function gge(t,e){let r=await t.export(),n=e.verificationMethod?.[0].publicKeyJwk,i=r.privateKeys?.[0];n.alg="EdDSA";let a=await wi.convertPublicKeyToX25519({publicKey:n}),s=await wi.convertPrivateKeyToX25519({privateKey:i}),o=await Gt.sharedSecret({privateKeyA:s,publicKeyB:a});return Om.deriveKeyBytes({baseKeyBytes:new Uint8Array(o),hash:"SHA-256",salt:new Uint8Array,info:new Uint8Array,length:256})}async function wge({jwt:t,encryptionKey:e,delegateDidKeyId:r,pin:n}){let i={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT",kid:r},a=gn.randomBytes(24),s=n?{...i,pin:n}:{...i},o=he.object(s).toUint8Array(),d=he.string(t).toUint8Array(),l=await Hc.encryptRaw({data:d,keyBytes:e,nonce:a,additionalData:o}),c=l.subarray(0,-16),u=l.subarray(-16);return[he.object(i).toBase64Url(),"",he.uint8Array(a).toBase64Url(),he.uint8Array(c).toBase64Url(),he.uint8Array(u).toBase64Url()].join(".")}async function vge(t,e,r){let[n,,i,a,s]=e.split("."),o=he.base64Url(n).toObject();if(!o.kid)throw new Error('Connect: JWE protected header is missing required "kid" property.');let d=await ho.resolve(o.kid.split("#")[0]),l=await xg.deriveSharedKey(t,d.didDocument),c=r?{...o,pin:r}:{...o},u=he.object(c).toUint8Array(),f=he.base64Url(i).toUint8Array(),h=he.base64Url(a).toUint8Array(),p=he.base64Url(s).toUint8Array(),m=new Uint8Array([...h,...p]),y=await Hc.decryptRaw({data:m,keyBytes:l,nonce:f,additionalData:u});return he.uint8Array(y).toString()}async function bge(t){let e=gn.randomBytes(16),r=gn.randomBytes(16);return{...t,nonce:he.uint8Array(r).toBase64Url(),responseMode:"direct_post",state:he.uint8Array(e).toBase64Url(),supportedDidMethods:t.supportedDidMethods??["did:dht","did:jwk"]}}async function Pge(t,e){let n=await(await fetch(t,{signal:AbortSignal.timeout(3e4)})).text(),i=await RH({jwe:n,encryptionKey:e});return await DH({jwt:i})}async function xge(t){let e=Math.floor(Date.now()/1e3);return{...t,iat:e,exp:e+600}}function Ege(t){return b5(t)?!0:t.interface===be.Protocols&&t.method===ge.Configure}async function Sge(t,e,r,n){let i=new Ka({agent:r});Rs.log(`Creating permission grants for ${n.length} scopes...`);let a=await Promise.all(n.map(d=>{let l=Ege(d);return i.createGrant({delegated:l,store:!0,grantedTo:e.uri,scope:d,dateExpires:"2040-06-25T16:09:16.693356Z",author:t})})),s=await r.dwn.getDwnEndpointUrlsForTarget(t);Rs.log(`Sending ${a.length} permission grants to ${s.length} DWN endpoint(s)...`);let o=a.map(async d=>{let{encodedData:l,...c}=d.message,u=he.base64Url(l).toUint8Array(),f=!1;for(let h of s)try{let p=await r.rpc.sendDwnRequest({dwnUrl:h,targetDid:t,message:c,data:new Blob([u])});p.status.code===202||p.status.code===409?f=!0:Rs.error(`Grant send to ${h} returned ${p.status.code}: ${p.status.detail}`)}catch(p){Rs.error(`Grant send to ${h} failed: ${p.message}`)}if(!f)throw new Error("Could not send permission grant to any DWN endpoint.");return d.message});try{return await Promise.all(o)}catch(d){throw Rs.error(`Error during batch-send of permission grants: ${d}`),d}}async function Age(t,e,r){let n=await e.processDwnRequest({author:t,messageType:Re.ProtocolsQuery,target:t,messageParams:{filter:{protocol:r.protocol}}});if(n.reply.status.code!==200)throw new Error(`Could not fetch protocol: ${n.reply.status.detail}`);if(n.reply.entries===void 0||n.reply.entries.length===0){Rs.log(`Protocol does not exist, creating: ${r.protocol}`);let{reply:i,message:a}=await e.sendDwnRequest({author:t,target:t,messageType:Re.ProtocolsConfigure,messageParams:{definition:r}});if(i.status.code!==202&&i.status.code!==409)throw new Error(`Could not send protocol: ${i.status.detail}`);await e.processDwnRequest({author:t,target:t,messageType:Re.ProtocolsConfigure,rawMessage:a})}else{Rs.log(`Protocol already exists: ${r.protocol}`);let i=n.reply.entries[0],{reply:a}=await e.sendDwnRequest({author:t,target:t,messageType:Re.ProtocolsConfigure,rawMessage:i});if(a.status.code!==202&&a.status.code!==409)throw new Error(`Could not send protocol: ${a.status.detail}`)}}async function kge(t,e,r,n){let i=await ho.create(),a=await i.export(),s=e.permissionRequests.map(async p=>{let{protocolDefinition:m,permissionScopes:y}=p;if(!y.every(w=>"protocol"in w&&w.protocol===m.protocol))throw new Error("All permission scopes must match the protocol URI they are provided with.");return await Age(t,n,m),xg.createPermissionGrants(t,i,n,y)}),o=(await Promise.all(s)).flat();Rs.log("Building connect response...");let d=await xg.createConnectResponse({providerDid:t,delegateDid:i.uri,aud:e.clientDid,nonce:e.nonce,delegateGrants:o,delegatePortableDid:a});Rs.log("Signing connect response...");let l=await xg.signJwt({did:i,data:d}),c=await ho.resolve(e.clientDid),u=await xg.deriveSharedKey(i,c?.didDocument);Rs.log("Encrypting connect response...");let f=await xg.encryptResponse({jwt:l,encryptionKey:u,delegateDidKeyId:i.document.verificationMethod[0].id,pin:r}),h=new URLSearchParams({id_token:f,state:e.state}).toString();Rs.log(`Sending connect response to: ${e.callbackUrl}`),await fetch(e.callbackUrl,{body:h,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(3e4)})}var xg={buildConnectUrl:hge,signJwt:mge,verifyJwt:DH,encryptRequest:yge,decryptRequest:RH,encryptResponse:wge,decryptResponse:vge,deriveSharedKey:gge,createConnectRequest:bge,getConnectRequest:Pge,createConnectResponse:xge,createPermissionGrants:Sge,submitConnectResponse:kge};g();Er();Jo();var CH=class t{constructor(e){this._agentDid=e.agentDid,this.crypto=e.cryptoApi,this.did=e.didApi,this.dwn=e.dwnApi,this.identity=e.identityApi,this.keyManager=e.keyManager,this.permissions=e.permissionsApi,this.rpc=e.rpcClient,this.sync=e.syncApi,this.vault=e.agentVault,this.did.agent=this,this.dwn.agent=this,this.identity.agent=this,this.keyManager.agent=this,this.permissions.agent=this,this.sync.agent=this}get agentDid(){if(this._agentDid===void 0)throw new Error('EnboxUserAgent: The "agentDid" property is not set. Ensure the agent is properly initialized and a DID is assigned.');return this._agentDid}set agentDid(e){this._agentDid=e}static async create({dataPath:e="DATA/AGENT",localDwnStrategy:r,localDwnEndpoint:n,agentDid:i,agentVault:a,cryptoApi:s,didApi:o,dwnApi:d,identityApi:l,keyManager:c,permissionsApi:u,rpcClient:f,syncApi:h}={}){return a??=new Rh({keyDerivationWorkFactor:21e4,store:new Im({location:`${e}/VAULT_STORE`})}),s??=new yo,o??=new _h({didMethods:[po,ho],resolverCache:new Cf({location:`${e}/DID_RESOLVERCACHE`}),store:new cg}),d||(n?d=new Fl({localDwnEndpoint:n,localDwnStrategy:r??"prefer"}):d=new Fl({dwn:await Fl.createDwn({dataPath:e,didResolver:o}),localDwnStrategy:r??"prefer"})),r&&d.setLocalDwnStrategy(r),l??=new Ch({store:new fg}),c??=new go({keyStore:new lg}),u??=new Ka,f??=new Pg,h??=new mg({dataPath:e}),new t({agentDid:i,agentVault:a,cryptoApi:s,didApi:o,dwnApi:d,keyManager:c,permissionsApi:u,identityApi:l,rpcClient:f,syncApi:h})}async firstLaunch(){return await this.vault.isInitialized()===!1}async initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}){return r=await this.vault.initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}),r}async processDidRequest(e){return this.did.processRequest(e)}async processDwnRequest(e){return this.dwn.processRequest(e)}async processVcRequest(e){throw new Error("Not implemented")}async sendDidRequest(e){throw new Error("Not implemented")}async sendDwnRequest(e){return this.dwn.sendRequest(e)}async sendVcRequest(e){throw new Error("Not implemented")}async start({password:e}){this.vault.isLocked()&&await this.vault.unlock({password:e}),this.agentDid=await this.vault.getDid()}};export{yo as AgentCryptoApi,_h as AgentDidApi,Cf as AgentDidResolverCache,Fl as AgentDwnApi,Ch as AgentIdentityApi,Ka as AgentPermissionsApi,CG as AnonymousDwnApi,ig as BearerIdentity,hye as DISCOVERY_DIR,mye as DISCOVERY_FILENAME,YG as DWN_CONNECT_PATH,ZG as DWN_PROTOCOL_SCHEME,uye as DidInterface,ma as DwnConstant,ii as DwnContentEncryptionAlgorithm,$f as DwnDataStore,Kt as DwnDateSort,cg as DwnDidStore,FE as DwnDiscoveryFile,fg as DwnIdentityStore,Re as DwnInterface,Ht as DwnKeyDerivationScheme,lg as DwnKeyStore,Ir as DwnPermissionGrant,cd as DwnPermissionRequest,dt as DwnPermissionsProtocol,xg as EnboxConnectProtocol,CH as EnboxUserAgent,Rh as HdIdentityVault,Bf as InMemoryDataStore,dg as InMemoryDidStore,pg as InMemoryIdentityStore,ug as InMemoryKeyStore,Th as LocalDwnDiscovery,go as LocalKeyManager,IH as PlatformAgentTestHarness,mg as SyncEngineLevel,jG as buildContextKeyDecrypter,FHe as buildDwnConnectUrl,HHe as buildDwnDiscoveryRedirectUrl,Ih as buildEncryptionInput,NG as buildKmsDecryptCallback,hb as concatenateUrl,pye as createNodeDiscoveryFileFs,JG as decodeDwnDiscoveryPayload,KG as deriveContextEncryptionInput,E5 as detectNewParticipants,Id as dwnMessageConstructors,FG as eagerSendContextKeyRecord,vye as encodeDwnDiscoveryPayload,HE as encryptAndComputeCid,qG as ensureKeyDeliveryProtocol,GG as fetchContextKeyRecord,pb as getDwnServiceEndpointUrls,yb as getEncryptionKeyDeriver,zl as getEncryptionKeyInfo,gb as getKeyDecrypter,fGe as getPaginationCursor,lGe as getRecordAuthor,sye as getRecordMessageCid,uGe as getRecordProtocolRole,hHe as getRootContextId,LG as getRuleSetAtPath,P5 as hasRelationalReadAccess,OG as isDidRequest,gye as isDwnMessage,Rd as isDwnRequest,Jye as isIdentityMetadata,wye as isMessagesPermissionScope,x5 as isMultiPartyContext,SWe as isPortableIdentity,b5 as isRecordPermissionScope,v5 as isRecordsType,Ll as isRecordsWrite,GE as ivLength,fye as localDwnServerName,UG as maybeDecryptReply,zE as normalizeBaseUrl,GHe as parseDwnConnectUrl,pGe as pollWithTtl,VHe as readDwnDiscoveryPayloadFromUrl,MG as resolveKeyDecrypter,zG as writeContextKeyRecord};
2060
+ 'valid, non-empty password.`);if(r??=dH(I5,128),!uH(r,I5))throw new Error("HdIdentityVault: The provided recovery phrase is invalid. Please ensure that the recovery phrase is a correctly formatted series of 12 words.");let i=await fH(r),a=JE.fromMasterSeed(i),s=a.derive("m/44'/0'/0'/0'/0'"),o=await this.crypto.deriveKey({algorithm:"HKDF-512",baseKeyBytes:s.privateKey,salt:"",info:"vault_cek",derivedKeyAlgorithm:"A256GCM"}),d=await this.crypto.deriveKeyBytes({algorithm:"HKDF-512",baseKeyBytes:s.publicKey,salt:"",info:"vault_unlock_salt",length:256}),l={alg:"PBES2-HS512+A256KW",enc:"A256GCM",cty:"text/plain",p2c:this._keyDerivationWorkFactor,p2s:he.uint8Array(d).toBase64Url()},c=await Gl.encrypt({key:he.string(e).toUint8Array(),protectedHeader:l,plaintext:he.object(o).toUint8Array(),crypto:this.crypto,keyManager:new go});await this._store.set("contentEncryptionKey",c);let u=a.derive("m/44'/0'/1708523827'/0'/0'"),f=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:u.privateKey}),h=a.derive("m/44'/0'/1708523827'/0'/1'"),p=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:h.privateKey}),m=a.derive("m/44'/0'/1708523827'/0'/2'"),y=await this.crypto.bytesToPrivateKey({algorithm:"X25519",privateKeyBytes:m.privateKey}),b=new UE;await b.addPredefinedKeys({privateKeys:[f,p,y]});let w={verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]};n&&n.length&&(w.services=[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:n}]);let k=await(await po.create({keyManager:b,options:w})).export(),T={alg:"dir",enc:"A256GCM",cty:"json"},D=await Gl.encrypt({key:o,plaintext:he.object(k).toUint8Array(),protectedHeader:T,crypto:this.crypto,keyManager:new go});return await this._store.set("did",D),this._contentEncryptionKey=o,await this.setStatus({initialized:!0}),r}async isInitialized(){return this._cachedInitialized===!0?!0:this.getStatus().then(({initialized:e})=>e)}isLocked(){return!this._contentEncryptionKey}async lock(){if(await this.isInitialized()===!1)throw new Error("HdIdentityVault: Lock operation failed. Vault has not been initialized.");this._contentEncryptionKey&&(this._contentEncryptionKey.k=""),this._contentEncryptionKey=void 0}async restore({backup:e,password:r}){if(!Vye(e))throw new Error("HdIdentityVault: Restore operation failed due to invalid backup object.");let n,i,a;try{a=await this.getStoredDid(),i=await this.getStoredContentEncryptionKey(),n=await this.getStatus()}catch{throw new Error("HdIdentityVault: The restore operation cannot proceed because the existing vault contents are missing or inaccessible. If the problem persists consider re-initializing the vault and retrying the restore.")}try{let s=he.base64Url(e.data).toObject();await this._store.set("did",s.did),await this._store.set("contentEncryptionKey",s.contentEncryptionKey),await this.setStatus(s.status),await this.unlock({password:r})}catch{throw await this.setStatus(n),await this._store.set("contentEncryptionKey",i),await this._store.set("did",a),new Error("HdIdentityVault: Restore operation failed due to invalid backup data or an incorrect password. Please verify the password is correct for the provided backup and try again.")}await this.setStatus({lastRestore:new Date().toISOString()})}async unlock({password:e}){await this.lock();let r=await this.getStoredContentEncryptionKey();try{let{plaintext:n}=await Gl.decrypt({jwe:r,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new go,options:{minP2cCount:1}}),i=he.uint8Array(n).toObject();this._contentEncryptionKey=i}catch{throw new Error("HdIdentityVault: Unable to unlock the vault due to an incorrect password.")}}async getStoredDid(){let e=await this._store.get("did");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the DID record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async getStoredContentEncryptionKey(){let e=await this._store.get("contentEncryptionKey");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the Content Encryption Key record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async setStatus({initialized:e,lastBackup:r,lastRestore:n}){let i=await this.getStatus();return i.initialized=e??i.initialized,i.lastBackup=r??i.lastBackup,i.lastRestore=n??i.lastRestore,await this._store.set("vaultStatus",JSON.stringify(i)),this._cachedInitialized=i.initialized,!0}};g();Jo();g();Er();function Jye(t){return!(!t||typeof t!="object"||t===null)&&"name"in t}var fg=class extends $f{constructor(){super(...arguments);this.name="DwnIdentityStore";this._recordProtocolDefinition=NE;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"identityMetadata",schema:this._recordProtocolDefinition.types.identityMetadata.schema}}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async set(r){return await super.set(r)}async list(r){return await super.list(r)}async getAllRecords({agent:r,tenantDid:n}){this._index.clear();let{reply:i}=await r.dwn.processRequest({author:n,target:n,messageType:Re.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=he.base64Url(s.encodedData).toObject();if(Jye(o)){let d=`${n}${ki}${o.uri}`;this._index.set(d,s.recordId),this._cache.set(s.recordId,o),a.push(o)}}return a}},pg=class extends Bf{constructor(){super(...arguments);this.name="InMemoryIdentityStore"}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async list(r){return await super.list(r)}async set(r){return await super.set(r)}};function SWe(t){return!(!t||typeof t!="object"||t===null)&&"did"in t&&"metadata"in t&&bh(t.did)}var Ch=class{constructor({agent:e,store:r}={}){this._agent=e,this._store=r??new pg}get agent(){if(this._agent===void 0)throw new Error("AgentIdentityApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e}get tenant(){if(!this._agent)throw new Error("AgentIdentityApi: The agent must be set to perform tenant specific actions.");return this._agent.agentDid.uri}async create({metadata:e,didMethod:r="dht",didOptions:n,store:i}){let a=await this.agent.did.create({method:r,options:n,tenant:this.tenant,store:i}),s=new ig({did:a,metadata:{...e,uri:a.uri,tenant:this.tenant}});return(i??!0)&&await this._store.set({id:s.did.uri,data:s.metadata,agent:this.agent,tenant:s.metadata.tenant,preventDuplicates:!1,useCache:!0}),s}async export({didUri:e}){let r=await this.get({didUri:e});if(!r)throw new Error(`AgentIdentityApi: Failed to export due to Identity not found: ${e}`);return await r.export()}async get({didUri:e}){let r=await this._store.get({id:e,agent:this.agent,useCache:!0});if(!r)return;let n=await this.agent.did.get({didUri:e,tenant:r.tenant});if(!n)throw new Error(`AgentIdentityApi: Identity is present in the store but DID is missing: ${e}`);return new ig({did:n,metadata:r})}async import({portableIdentity:e}){e.metadata.tenant=this.tenant;let r=await this.agent.did.import({portableDid:e.portableDid,tenant:e.metadata.tenant});if(!r)throw new Error(`AgentIdentityApi: Failed to import Identity: ${e.metadata.uri}`);let n=new ig({did:r,metadata:e.metadata});return await this._store.set({id:n.did.uri,data:n.metadata,agent:this.agent,tenant:n.metadata.tenant,preventDuplicates:!0,useCache:!0}),n}async list({tenant:e}={}){let r=await this._store.list({agent:this.agent,tenant:e});return(await Promise.all(r.map(i=>this.get({didUri:i.uri})))).filter(i=>typeof i<"u")}async delete({didUri:e}){if(!await this._store.get({id:e,agent:this.agent,useCache:!0}))throw new Error(`AgentIdentityApi: Failed to purge due to Identity not found: ${e}`);await this._store.delete({id:e,agent:this.agent})}getDwnEndpoints({didUri:e}){return this.agent.dwn.getDwnEndpointUrlsForTarget(e)}async setDwnEndpoints({didUri:e,endpoints:r}){let n=await this.agent.did.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set DWN endpoints due to DID not found: ${e}`);let i=await n.export(),a=i.document.service?.find(s=>s.id.endsWith("dwn"));if(a)a.serviceEndpoint=r;else{let s={id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:r};i.document.service?i.document.service.push(s):i.document.service=[s]}await this.agent.did.update({portableDid:i,tenant:this.agent.agentDid.uri})}async setMetadataName({didUri:e,name:r}){if(!r)throw new Error("AgentIdentityApi: Failed to set metadata name due to missing name value.");let n=await this.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set metadata name due to Identity not found: ${e}`);if(n.metadata.name===r)throw new Error("AgentIdentityApi: No changes detected.");await this._store.set({id:n.did.uri,data:{...n.metadata,name:r},agent:this.agent,tenant:n.metadata.tenant,updateExisting:!0,useCache:!0})}async connectedIdentity({connectedDid:e}={}){let r=await this.list();if(!(r.length<1))return e?r.find(n=>n.metadata.connectedDid===e):r.find(n=>n.metadata.connectedDid!==void 0)}};g();Yn();Er();var Ka=class t{constructor({agent:e}={}){this._cachedPermissions=new cs.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:r,delegate:n,messageType:i,protocol:a,cached:s=!1}){let o=[e,r,i,a].join("~"),d=s?this._cachedPermissions.get(o):void 0;if(d)return d;let l=await this.fetchGrants({author:r,target:r,grantor:e,grantee:r}),c=await t.matchGrantFromArray(e,r,{messageType:i,protocol:a},l,n);if(!c)throw new Error(`CachedPermissions: No permissions found for ${i}: ${a}`);return this._cachedPermissions.set(o,c),c}async fetchGrants({author:e,target:r,grantee:n,grantor:i,protocol:a,remote:s=!1,checkRevoked:o=!0}){let d=a?{protocol:a}:void 0,l={author:e,target:r,messageType:Re.RecordsQuery,messageParams:{filter:{author:i,recipient:n,protocol:dt.uri,protocolPath:dt.grantPath,tags:d}}},{reply:c}=s?await this.agent.sendDwnRequest(l):await this.agent.processDwnRequest(l);if(c.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${c.status.detail}`);let u=o?await this.fetchRevokedGrantIds({author:e,target:r,grantor:i,remote:s,tags:d}):new Set,f=[];for(let h of c.entries){if(u.has(h.recordId))continue;let p=Ir.parse(h);f.push({grant:p,message:h})}return f}async fetchRevokedGrantIds({author:e,target:r,grantor:n,remote:i,tags:a}){let s={author:e,target:r,messageType:Re.RecordsQuery,messageParams:{filter:{author:n,protocol:dt.uri,protocolPath:dt.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 d=new Set;for(let l of o.entries)l.descriptor.parentId!==void 0&&d.add(l.descriptor.parentId);return d}async fetchRequests({author:e,target:r,protocol:n,remote:i=!1}){let a=n?{protocol:n}:void 0,s={author:e,target:r,messageType:Re.RecordsQuery,messageParams:{filter:{protocol:dt.uri,protocolPath:dt.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 d=[];for(let l of o.entries){let c=cd.parse(l);d.push({request:c,message:l})}return d}async isGrantRevoked({author:e,target:r,grantRecordId:n,remote:i=!1}){let a={author:e,target:r,messageType:Re.RecordsRead,messageParams:{filter:{parentId:n,protocol:dt.uri,protocolPath:dt.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:r,store:n=!1,delegated:i=!1,...a}=e,s;dt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope},d=he.object(o).toUint8Array(),l={recipient:a.grantedTo,protocol:dt.uri,protocolPath:dt.grantPath,dataFormat:"application/json",tags:s},{reply:c,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${c.status.detail}`);let f={...u,encodedData:he.uint8Array(d).toBase64Url()};return{grant:Ir.parse(f),message:f}}async createRequest(e){let{author:r,store:n=!1,delegated:i=!1,...a}=e,s;dt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={description:a.description,delegated:i,scope:a.scope},d=he.object(o).toUint8Array(),l={protocol:dt.uri,protocolPath:dt.requestPath,dataFormat:"application/json",tags:s},{reply:c,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${c.status.detail}`);let f={...u,encodedData:he.uint8Array(d).toBase64Url()};return{request:cd.parse(f),message:f}}async createRevocation(e){let{author:r,store:n=!1,grant:i,description:a}=e,s={description:a},o=he.object(s).toUint8Array(),d;dt.hasProtocolScope(i.scope)&&(d={protocol:i.scope.protocol});let l={parentContextId:i.id,protocol:dt.uri,protocolPath:dt.revocationPath,dataFormat:"application/json",tags:d},{reply:c,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([o])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${c.status.detail}`);return{message:{...u,encodedData:he.uint8Array(o).toBase64Url()}}}async clear(){this._cachedPermissions.clear()}static async matchGrantFromArray(e,r,n,i,a=!1){let s;for(let o of i){let{grant:d,message:l}=o;if(a===!0&&d.delegated!==!0)continue;let{messageType:c,protocol:u,protocolPath:f,contextId:h}=n;if(this.matchScopeFromGrant(e,r,c,d,u,f,h)){if(d.scope.interface+d.scope.method===c)return{grant:d,message:l};s||(s={grant:d,message:l})}}return s}static matchScopeFromGrant(e,r,n,i,a,s,o){if(i.grantee!==r||i.grantor!==e)return!1;let d=i.scope,l=d.interface+d.method;if(l===n||l===Re.MessagesRead&&(n===Re.MessagesSync||n===Re.MessagesSubscribe))if(v5(n)){let u=d;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=d;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();var EH=An(qE(),1);Yn();import{Level as Qye}from"level";g();Yn();function mH(t){let e=t.descriptor;return e.interface!==be.Records||e.method!==ge.Write?!1:e.dateCreated===e.messageTimestamp}function hg(t){if(t.length<=1)return t;let e=new Map,r=new Map,n=new Map,i=new Map;for(let c=0;c<t.length;c++){let u=t[c];e.set(c,u);let f=u.message.descriptor;if(f.interface===be.Protocols&&f.method===ge.Configure){let h=f.definition?.protocol;h&&r.set(h,c)}if(f.interface===be.Records&&f.method===ge.Write){let h=u.message.recordId;mH(u.message)&&h&&n.set(h,c),f.protocol===dt.uri&&f.protocolPath===dt.grantPath&&h&&i.set(h,c)}}let a=new Map,s=new Array(t.length).fill(0),o=(c,u)=>{if(c===u)return;a.has(c)||a.set(c,new Set);let f=a.get(c);f.has(u)||(f.add(u),s[u]++)};for(let c=0;c<t.length;c++){let u=t[c].message.descriptor;if(u.interface===be.Records){let h=u.protocol;h&&r.has(h)&&o(r.get(h),c)}if(u.interface===be.Records&&u.parentId){let h=u.parentId;n.has(h)&&o(n.get(h),c)}if(u.interface===be.Records&&u.method===ge.Write){let h=t[c].message.recordId;h&&!mH(t[c].message)&&n.has(h)&&o(n.get(h),c)}if(u.interface===be.Records&&u.method===ge.Delete){let h=u.recordId;h&&n.has(h)&&o(n.get(h),c)}let f=u.permissionGrantId;f&&i.has(f)&&o(i.get(f),c)}let d=[];for(let c=0;c<t.length;c++)s[c]===0&&d.push(c);let l=[];for(;d.length>0;){let c=d.shift();l.push(e.get(c));let u=a.get(c);if(u)for(let f of u)s[f]--,s[f]===0&&d.push(f)}if(l.length<t.length){let c=new Set(l);for(let u=0;u<t.length;u++){let f=e.get(u);c.has(f)||l.push(f)}}return l}g();Yn();var Zye=1048576;function gH(t){return t.status.code===202||t.status.code===204||t.status.code===409||t.entry?.message.descriptor.interface===be.Records&&t.entry?.message.descriptor.method===ge.Delete&&t.status.code===404}async function wH(t){try{return await we.getCid(t)}catch{return"unknown"}}async function vH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,prefetched:a,agent:s,permissionsApi:o}){let d=[];if(a)for(let p of a){if(!p.message)continue;let m={message:p.message};if(p.encodedData){let y=De.base64UrlToBytes(p.encodedData);m.bufferedData=y,m.dataStream=new ReadableStream({start(b){b.enqueue(y),b.close()}})}d.push(m)}let l=i.length>0?await yH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:s,permissionsApi:o}):[],c=[...d,...l],u=hg(c);await Yye(u);let f=3,h=u;for(let p=0;p<=f&&h.length>0;p++){let m=[];for(let y of h){let b=y.bufferedData?new ReadableStream({start(S){S.enqueue(y.bufferedData),S.close()}}):y.dataStream,w=await s.dwn.processRawMessage(t,y.message,{dataStream:b});gH(w)||m.push(y)}if(m.length>0){let y=[],b=[];for(let w of m)if(w.bufferedData||!w.dataStream)b.push(w);else{let S=await wH(w.message);y.push(S)}if(y.length>0){let w=await yH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:y,agent:s,permissionsApi:o});b.push(...w)}h=hg(b)}else h=[]}}async function Yye(t){for(let e of t){if(!e.dataStream)continue;let r=[],n=0,i=!1,a=e.dataStream.getReader();try{for(;;){let{done:d,value:l}=await a.read();if(d)break;if(n+=l.byteLength,n>Zye){i=!0;break}r.push(l)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let s=new Uint8Array(n),o=0;for(let d of r)s.set(d,o),o+=d.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(d){d.enqueue(s),d.close()}})}}async function yH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:s}){let o=[],d;r&&(d=(await s.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id);let l=4,c=0;for(;c<i.length;){let u=i.slice(c,c+l);c+=l;let f=await Promise.all(u.map(async h=>{let p=await a.processDwnRequest({store:!1,author:t,target:t,messageType:Re.MessagesRead,granteeDid:r,messageParams:{messageCid:h,permissionGrantId:d}}),m;try{m=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,message:p.message})}catch(w){console.error(`SyncEngineLevel: pull - failed to read ${h} from ${e}:`,w.message??w);return}if(m.status.code!==200||!m.entry?.message)return;let y=m.entry,b;return Ll(y)&&y.data&&(b=y.data),{message:y.message,dataStream:b}}));for(let h of f)h&&o.push(h)}return o}async function B5({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:s}){let o=[];for(let l of i){let c=await Xye({author:t,messageCid:l,delegateDid:r,protocol:n,agent:a,permissionsApi:s});c&&o.push(c)}let d=hg(o);for(let l of d)try{let c=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,data:l.dataStream,message:l.message});if(!gH(c)){let u=await wH(l.message);console.error(`SyncEngineLevel: push failed for ${u}: ${c.status.code} ${c.status.detail}`)}}catch(c){let u=c.message??c;throw new Error(`SyncEngineLevel: push to ${e} failed: ${u}`)}}async function Xye({author:t,delegateDid:e,protocol:r,messageCid:n,agent:i,permissionsApi:a}){let s;e&&(s=(await a.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesRead,delegateDid:e,protocol:r,cached:!0})).grant.id);let{reply:o}=await i.dwn.processRequest({author:t,target:t,messageType:Re.MessagesRead,granteeDid:e,messageParams:{messageCid:n,permissionGrantId:s}});if(o.status.code!==200||!o.entry)return;let d=o.entry,l={message:d.message};return Ll(d)&&d.data&&(l.dataStream=d.data),l}var bH=16,PH=8,ege=4,O5=class{constructor(e){this._waiting=[];this._permits=e}async acquire(){if(this._permits>0){this._permits--;return}return new Promise(e=>{this._waiting.push(e)})}release(){let e=this._waiting.shift();e?e():this._permits++}async run(e){await this.acquire();try{return await e()}finally{this.release()}}},xH="^",tge=250,Of=class Of{constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1;this._syncMode="poll";this._liveSubscriptions=[];this._localSubscriptions=[];this._connectivityState="unknown";this._pendingPushCids=new Map;this._consecutiveFailures=0;this._agent=e,this._permissionsApi=new Ka({agent:e}),this._db=n||new Qye(r??"DATA/AGENT/SYNC_STORE")}get agent(){if(this._agent===void 0)throw new Error("SyncEngineLevel: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._permissionsApi=new Ka({agent:e})}get connectivityState(){return this._connectivityState}async clear(){await this._permissionsApi.clear(),await this._db.clear()}async close(){await this._db.close()}async registerIdentity({did:e,options:r}){let n=this._db.sublevel("registeredIdentities");if(await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is already registered.`);r??={protocols:[]},await n.put(e,JSON.stringify(r))}async unregisterIdentity(e){let r=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await r.del(e)}async getIdentityOptions(e){let r=this._db.sublevel("registeredIdentities");try{let n=await r.get(e);if(n)return JSON.parse(n)}catch(n){let i=n;if(i.code==="LEVEL_NOT_FOUND")return;throw new Error(`SyncEngineLevel: Error reading level: ${i.code}.`)}}async updateIdentityOptions({did:e,options:r}){let n=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await n.put(e,JSON.stringify(r))}async sync(e){if(this._syncLock)throw new Error("SyncEngineLevel: Sync operation is already in progress.");this._syncLock=!0;try{let r=await this.getSyncTargets(),n=new Set,i=!1;for(let a of r){let{did:s,delegateDid:o,dwnUrl:d,protocol:l}=a;if(!n.has(d))try{let c=await this.getLocalRoot(s,o,l),u=await this.getRemoteRoot(s,d,o,l);if(c===u)continue;let f=await this.diffWithRemote({did:s,dwnUrl:d,delegateDid:o,protocol:l});if((!e||e==="pull")&&f.onlyRemote.length>0){let h=[],p=[];for(let m of f.onlyRemote)m.message?m.message.descriptor.interface==="Records"&&m.message.descriptor.method==="Write"&&m.message.descriptor.dataCid&&!m.encodedData?p.push(m.messageCid):h.push(m):p.push(m.messageCid);await this.pullMessages({did:s,dwnUrl:d,delegateDid:o,protocol:l,messageCids:p,prefetched:h})}(!e||e==="push")&&f.onlyLocal.length>0&&await this.pushMessages({did:s,dwnUrl:d,delegateDid:o,protocol:l,messageCids:f.onlyLocal})}catch(c){n.add(d),i=!0,console.error(`SyncEngineLevel: Error syncing ${s} with ${d}`,c)}}i?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):(this._consecutiveFailures=0,r.length>0&&(this._connectivityState="online"))}finally{this._syncLock=!1}}async startSync(e){let r=e.mode??"poll",n=e.interval??(r==="live"?"5m":"2m"),i=(0,EH.default)(n);(this._liveSubscriptions.length>0||this._localSubscriptions.length>0)&&await this.teardownLiveSync(),this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncMode=r,r==="live"?await this.startLiveSync(i):await this.startPollSync(i)}async stopSync(e=2e3){let r=0;for(;this._syncLock;){if(r>=e)throw new Error(`SyncEngineLevel: Existing sync operation did not complete within ${e} milliseconds.`);r+=100,await new Promise(n=>{setTimeout(n,e<100?e:100)})}this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),await this.teardownLiveSync()}async startPollSync(e){let r=async()=>{if(this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{await this.sync()}catch(a){console.error("SyncEngineLevel: Error during sync operation",a)}let n=Math.min(Math.pow(2,this._consecutiveFailures),Of.MAX_BACKOFF_MULTIPLIER),i=this._consecutiveFailures>0?e*n:e;this._syncIntervalId||(this._syncIntervalId=setInterval(r,i))};this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(r,e),this._syncLock||await this.sync()}async startLiveSync(e){try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=await this.getSyncTargets();for(let i of r)try{await this.openLivePullSubscription(i),await this.openLocalPushSubscription(i)}catch(a){console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,a)}let n=async()=>{if(!this._syncLock)try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during SMT integrity check",i)}};this._syncIntervalId=setInterval(n,e)}async teardownLiveSync(){this._pushDebounceTimer&&(clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=void 0),this._pendingPushCids.clear();for(let e of this._liveSubscriptions)try{await e.close()}catch{}this._liveSubscriptions=[];for(let e of this._localSubscriptions)try{await e.close()}catch{}this._localSubscriptions=[]}async openLivePullSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=this.buildCursorKey(r,i,a),o=await this.getCursor(s),d=a?[{protocol:a}]:[],l;if(n)try{l=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{l=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}let c=async h=>{if(h.type==="eose"){await this.setCursor(s,h.cursor),this._connectivityState="online";return}if(h.type==="event"){let p=h.event;try{let m=this.extractDataStream(p);await this.agent.dwn.processRawMessage(r,p.message,{dataStream:m})}catch(m){console.error(`SyncEngineLevel: Error processing live-pull event for ${r}`,m)}await this.setCursor(s,h.cursor)}},f=(await this.agent.dwn.sendRequest({author:r,target:r,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:d,cursor:o,permissionGrantId:l},subscriptionHandler:c})).reply;if(f.status.code!==200||!f.subscription){console.error(`SyncEngineLevel: MessagesSubscribe failed for ${r} -> ${i}: ${f.status.code} ${f.status.detail}`);return}this._liveSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await f.subscription.close()}}),this._connectivityState="online"}async openLocalPushSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=a?[{protocol:a}]:[],o;n&&(o=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id);let d=u=>{if(u.type!=="event")return;let f=this.buildCursorKey(r,i,a),h=this.tryGetCidSync(u.event.message);if(h===void 0)return;let p=this._pendingPushCids.get(f);p||(p={did:r,dwnUrl:i,delegateDid:n,protocol:a,cids:[]},this._pendingPushCids.set(f,p)),p.cids.push(h),this._pushDebounceTimer&&clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=setTimeout(()=>{this.flushPendingPushes()},tge)},c=(await this.agent.dwn.processRequest({author:r,target:r,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:s,permissionGrantId:o},subscriptionHandler:d})).reply;if(c.status.code!==200||!c.subscription){console.error(`SyncEngineLevel: Local MessagesSubscribe failed for ${r}: ${c.status.code} ${c.status.detail}`);return}this._localSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await c.subscription.close()}})}async flushPendingPushes(){this._pushDebounceTimer=void 0;let e=[...this._pendingPushCids.entries()];this._pendingPushCids.clear();for(let[,r]of e){let{did:n,dwnUrl:i,delegateDid:a,protocol:s,cids:o}=r;if(o.length!==0)try{await B5({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:o,agent:this.agent,permissionsApi:this._permissionsApi})}catch(d){console.error(`SyncEngineLevel: Push-on-write failed for ${n} -> ${i}`,d)}}}buildCursorKey(e,r,n){let i=`${e}${xH}${r}`;return n?`${i}${xH}${n}`:i}async getCursor(e){let r=this._db.sublevel("syncCursors");try{return await r.get(e)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async setCursor(e,r){await this._db.sublevel("syncCursors").put(e,r)}extractDataStream(e){if(Ll(e)&&e.data)return e.data}tryGetCidSync(e){let r;return we.getCid(e).then(n=>{r=n}),r??e.messageCid??void 0}async getDefaultHashHex(e){if(this._defaultHashHex===void 0){let r=await Pl(),n=new Map;for(let i=0;i<=bH;i++)n.set(i,sn(r[i]));this._defaultHashHex=n}return this._defaultHashHex.get(e)??""}static parseBitPrefix(e){return Array.from(e,r=>r==="1")}get stateIndex(){if(!this.agent.dwn.isRemoteMode)return this.agent.dwn.node.storage.stateIndex}async getLocalRoot(e,r,n){let i=this.stateIndex;if(i){let d=n!==void 0?await i.getProtocolRoot(e,n):await i.getRoot(e);return sn(d)}let a=await this.getSyncPermissionGrantId(e,r,n);return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:a}})).reply.root??""}async getRemoteRoot(e,r,n,i){let a=await this.getSyncPermissionGrantId(e,n,i),s=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"root",protocol:i,permissionGrantId:a}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:s.message})).root??""}async walkTreeDiff({did:e,dwnUrl:r,delegateDid:n,protocol:i}){let a=[],s=[],o=await this.getSyncPermissionGrantId(e,n,i),d=new O5(ege),l=async c=>{let[u,f]=await Promise.all([this.getLocalSubtreeHash(e,c,n,i,o),d.run(()=>this.getRemoteSubtreeHash(e,r,c,n,i,o))]);if(u===f)return;let h=await this.getDefaultHashHex(c.length);if(f===h&&u!==h){let p=await this.getLocalLeaves(e,c,n,i,o);a.push(...p);return}if(u===h&&f!==h){let p=await d.run(()=>this.getRemoteLeaves(e,r,c,n,i,o));s.push(...p);return}if(c.length>=bH){let[p,m]=await Promise.all([this.getLocalLeaves(e,c,n,i,o),d.run(()=>this.getRemoteLeaves(e,r,c,n,i,o))]),y=new Set(p),b=new Set(m);for(let w of p)b.has(w)||a.push(w);for(let w of m)y.has(w)||s.push(w);return}await Promise.all([l(c+"0"),l(c+"1")])};return await l(""),{onlyLocal:a,onlyRemote:s}}async diffWithRemote({did:e,dwnUrl:r,delegateDid:n,protocol:i}){let a=await this.collectLocalSubtreeHashes(e,i,PH),s=await this.getSyncPermissionGrantId(e,n,i),o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"diff",protocol:i,hashes:a,depth:PH,permissionGrantId:s}}),d=await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message});if(d.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${d.status.code}: ${d.status.detail}`);let l=await this.getSyncPermissionGrantId(e,n,i),c=[];for(let u of d.onlyLocal??[]){let f=await this.getLocalLeaves(e,u,n,i,l);c.push(...f)}return{onlyRemote:d.onlyRemote??[],onlyLocal:c}}async collectLocalSubtreeHashes(e,r,n){let i={},a=await this.getDefaultHashHex(n),s=this.stateIndex,o=async(d,l)=>{let c;if(s){let u=Of.parseBitPrefix(d),f=r!==void 0?await s.getProtocolSubtreeHash(e,r,u):await s.getSubtreeHash(e,u);c=sn(f)}else c=await this.getLocalSubtreeHash(e,d,void 0,r);if(c!==a){if(l>=n){i[d]=c;return}await Promise.all([o(d+"0",l+1),o(d+"1",l+1)])}};return await o("",0),i}async getLocalSubtreeHash(e,r,n,i,a){let s=this.stateIndex;if(s){let l=Of.parseBitPrefix(r),c=i!==void 0?await s.getProtocolSubtreeHash(e,i,l):await s.getSubtreeHash(e,l);return sn(c)}return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash??""}async getRemoteSubtreeHash(e,r,n,i,a,s){let o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:i,messageParams:{action:"subtree",prefix:n,protocol:a,permissionGrantId:s}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).hash??""}async getLocalLeaves(e,r,n,i,a){let s=this.stateIndex;if(s){let l=Of.parseBitPrefix(r);return i!==void 0?await s.getProtocolLeaves(e,i,l):await s.getLeaves(e,l)}return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries??[]}async getRemoteLeaves(e,r,n,i,a,s){let o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:i,messageParams:{action:"leaves",prefix:n,protocol:a,permissionGrantId:s}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).entries??[]}async pullMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s}){return vH({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:this.agent,permissionsApi:this._permissionsApi})}async pushMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a}){return B5({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:this.agent,permissionsApi:this._permissionsApi})}static topologicalSort(e){return hg(e)}async getSyncTargets(){let e=[];for await(let[r,n]of this._db.sublevel("registeredIdentities").iterator()){let i;try{i=JSON.parse(n)}catch(d){console.warn(`SyncEngineLevel: Corrupt sync options for ${r}, falling back to global sync:`,d),i={protocols:[]}}let{protocols:a,delegateDid:s}=i,o=await this.agent.dwn.getDwnEndpointUrlsForTarget(r);if(o.length!==0)for(let d of o)if(a.length===0)e.push({did:r,delegateDid:s,dwnUrl:d});else for(let l of a)e.push({did:r,delegateDid:s,dwnUrl:d,protocol:l})}return e}async getSyncPermissionGrantId(e,r,n){return r?(await this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Re.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id:void 0}};Of.MAX_CONSECUTIVE_FAILURES=5,Of.MAX_BACKOFF_MULTIPLIER=4;var mg=Of;g();Yn();Jo();Er();import{Level as pge}from"level";g();g();g();Er();wn();g();g();var SH=An(qE(),1);Er();var yg=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},XE=class{constructor({ttl:e="15m"}={}){this.cache=new cs.default({ttl:(0,SH.default)(e)})}get(e){return yg(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return yg(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return yg(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return yg(this,void 0,void 0,function*(){this.cache.clear()})}open(){return yg(this,void 0,void 0,function*(){})}close(){return yg(this,void 0,void 0,function*(){})}};g();wn();Yn();g();var gg=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};g();var wg;(function(t){t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.ParseError=-32700]="ParseError",t[t.TransportError=-32300]="TransportError",t[t.BadRequest=-50400]="BadRequest",t[t.Unauthorized=-50401]="Unauthorized",t[t.Forbidden=-50403]="Forbidden",t[t.Conflict=-50409]="Conflict",t[t.TooManyRequests=-50429]="TooManyRequests"})(wg||(wg={}));var vg=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),QE=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),AH=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function $h(t){try{return JSON.parse(t)}catch{return null}}var j5=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},rge=3,nge=500,ige=1e4,sge=3e4,kH=new Set([408,429,500,502,503,504]);function oge(t,e){return t instanceof TypeError?!0:e?kH.has(e.status):!1}function age(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=.5+Math.random()*.5;return n*i}function cge(t){let e=t.headers.get("retry-after");if(e===null)return;let r=Number(e);if(!Number.isNaN(r)&&r>=0)return r*1e3;let n=new Date(e);if(!Number.isNaN(n.getTime())){let i=n.getTime()-Date.now();return i>0?i:0}}var eS=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new XE,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:rge,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:nge,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:ige}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return j5(this,void 0,void 0,function*(){var r,n,i;let a=gn.randomUuid(),s=vg(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},d={method:"POST",headers:o};if(e.data){o["content-type"]="application/octet-stream";let h=e.data;if(h instanceof ReadableStream)if(t.isBunRuntime()){let p=yield Yt.toBytes(h);h=new Blob([p],{type:"application/octet-stream"})}else d.duplex="half";d.body=h}let l=yield this.fetchWithRetry(e.dwnUrl,d);if(l.status===429){let h=parseInt((r=l.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new gg(h)}let c,u=l.headers.has("dwn-response");if(u){let h=$h(l.headers.get("dwn-response"));if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);c=h}else{let h=yield l.text(),p=$h(h);if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${l.status}`);c=p}if(c.error){let{code:h,message:p}=c.error;if(h===wg.TooManyRequests){let m=(i=(n=c.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new gg(m)}throw new Error(`(${h}) - ${p}`)}let{reply:f}=c.result;if(u){let h=new Uint8Array(yield l.arrayBuffer()),p=Yt.fromBytes(h);f.record?f.record.data=p:f.entry&&(f.entry.data=p)}return f})}getServerInfo(e){return j5(this,void 0,void 0,function*(){var r;let n=yield this.serverInfoCache.get(e);if(n)return n;let i=new URL(e);i.pathname.endsWith("/")?i.pathname+="info":i.pathname+="/info";try{let a=yield this.fetchWithRetry(i.toString());if(a.status===429){let s=parseInt((r=a.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new gg(s)}if(a.ok){let s=yield a.json(),o={maxFileSize:s.maxFileSize,maxInFlight:s.maxInFlight,providerAuth:s.providerAuth,registrationRequirements:s.registrationRequirements,server:s.server,sdkVersion:s.sdkVersion,url:s.url,version:s.version,webSocketSupport:s.webSocketSupport};return this.serverInfoCache.set(e,o),o}else throw new Error(`HTTP (${a.status}) - ${a.statusText}`)}catch(a){throw new Error(`Error encountered while processing response from ${i.toString()}: ${a.message}`)}})}fetchWithRetry(e,r){return j5(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let d=0;d<=n;d++){try{let f=AbortSignal.timeout(sge),h=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),p=yield fetch(e,h);if(!kH.has(p.status)||d===n)return p;o=p}catch(f){if(!oge(f)||d===n)throw f;s=f}let l=o?cge(o):void 0,c=age(d,i,a),u=l!==void 0?Math.max(l,c):c;yield new Promise(f=>{setTimeout(f,u)})}if(o)return o;throw s})}};g();wn();var xb=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})};function M5(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var _H=3e3,dge=3e4,lge=1e3,uge=3e4,fge=1/0,tS=class t{constructor(e,r,n,i){this.socket=e,this.responseTimeout=r,this.messageHandlers=new Map,this.subscriptionHandlerIds=new Set,this.closedByUser=!1,this.reconnecting=!1,this._isConnected=!1,this.url=n,this.options=i,this._isConnected=!0}get isConnected(){return this._isConnected}static connect(e){return xb(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=_H,responseTimeout:s=dge}=n,o;try{o=yield t.createWebSocket(r,a)}catch(l){throw(i=n.onerror)===null||i===void 0||i.call(n,l),l}let d=new t(o,s,r,n);return d.wireSocket(o),d})}close(){this.closedByUser=!0,this._isConnected=!1,this.socket.close()}request(e){return xb(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=gn.randomUuid());let a=s=>{let o=$h(M5(s.data));if(o.id===e.id)return this.messageHandlers.delete(e.id),r(o)};this.messageHandlers.set(e.id,a),this.send(e),setTimeout(()=>{this.messageHandlers.delete(e.id),n(new Error("request timed out"))},this.responseTimeout)})})}subscribe(e,r){return xb(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=d=>{let l=$h(M5(d.data));l.id===n&&(l.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),r(l))};this.messageHandlers.set(n,a),this.subscriptionHandlerIds.add(n);let s=yield this.request(e);return s.error?(i?this.messageHandlers.set(n,i):(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n)),{response:s}):{response:s,close:()=>xb(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=gn.randomUuid(),n=QE(r,"rpc.subscribe.close",{},e);return this.request(n)}send(e){this.socket.send(JSON.stringify(e))}static createWebSocket(e,r){return new Promise((n,i)=>{let a=new WebSocket(e),s=()=>{l(),n(a)},o=c=>{l(),i(c)},d=setTimeout(()=>{l(),a.close(),i(new Error("connect timed out"))},r),l=()=>{clearTimeout(d),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=$h(M5(r.data));if(n===null)return;let i=this.messageHandlers.get(n.id);i&&i(r)}),e.addEventListener("close",()=>{var r,n,i,a,s;if(this._isConnected=!1,this.closedByUser){(n=(r=this.options).onclose)===null||n===void 0||n.call(r);return}this.rejectPendingRequests(),(a=(i=this.options).onclose)===null||a===void 0||a.call(i),((s=this.options.autoReconnect)!==null&&s!==void 0?s:!0)&&!this.reconnecting&&this.attemptReconnect()}),e.addEventListener("error",r=>{var n,i;(i=(n=this.options).onerror)===null||i===void 0||i.call(n,r)})}rejectPendingRequests(){for(let[e,r]of this.messageHandlers)if(!this.subscriptionHandlerIds.has(e)){let n=JSON.stringify({jsonrpc:"2.0",id:e,error:{code:wg.TransportError,message:"WebSocket connection closed unexpectedly"}});r({data:n}),this.messageHandlers.delete(e)}}attemptReconnect(){var e,r,n,i;this.reconnecting=!0;let a=(e=this.options.baseReconnectDelay)!==null&&e!==void 0?e:lge,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:uge,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:fge,d=(i=this.options.connectTimeout)!==null&&i!==void 0?i:_H,l=0,c=()=>xb(this,void 0,void 0,function*(){var u,f,h,p;if(this.closedByUser){this.reconnecting=!1;return}if(l++,l>o){this.reconnecting=!1;return}(f=(u=this.options).onreconnecting)===null||f===void 0||f.call(u,l);let y=Math.min(a*Math.pow(2,l-1),s)*(.5+Math.random()*.5);if(yield new Promise(b=>setTimeout(b,y)),this.closedByUser){this.reconnecting=!1;return}try{let b=yield t.createWebSocket(this.url,d);this.socket=b,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(b),(p=(h=this.options).onreconnected)===null||p===void 0||p.call(h)}catch{yield c()}});c()}};g();g();g();wn();g();wn();var bg=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Eb=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return bg(this,void 0,void 0,function*(){let r=new URL(e.dwnUrl);if(r.protocol!=="ws:"&&r.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${r.protocol}`);if(!t.connections.has(r.host))try{let d=yield t.createConnection(r);t.connections.set(r.host,d)}catch(d){throw new Error(`Error connecting to ${r.host}: ${d.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:s,subscription:o}=e;return o?t.subscriptionRequest(i,a,s,o.handler,o.resubscribeFactory):t.processMessage(i,a,s)})}static createConnection(e){return bg(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield tS.connect(e.toString(),{onclose:()=>{t.connections.delete(r);for(let a of n.values())a.handler({type:"disconnected"})},onreconnecting:a=>{for(let s of n.values())s.handler({type:"reconnecting",attempt:a})},onreconnected:()=>{let a={socket:i,subscriptions:n,url:e.toString()};t.connections.set(r,a),t.resubscribeAll(a)}});return{socket:i,subscriptions:n,url:e.toString()}})}static processMessage(e,r,n){return bg(this,void 0,void 0,function*(){let i=gn.randomUuid(),a=vg(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:d,result:l}=o;if(d!==void 0)throw new Error(`error sending DWN request: ${d.message}`);return l.reply})}static subscriptionRequest(e,r,n,i,a){return bg(this,void 0,void 0,function*(){let s=gn.randomUuid(),o=gn.randomUuid(),d=QE(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:l,subscriptions:c}=e,{response:u,close:f}=yield l.subscribe(d,y=>{let{result:b,error:w}=y;if(w){let k=c.get(o);k&&k.subscription.close(),c.delete(o);return}let S=b.subscription;if(i(S),"cursor"in S&&S.cursor){let k=c.get(o);k&&(k.lastCursor=S.cursor),l.send(AH(o,S.cursor))}}),{error:h,result:p}=u;if(h)throw new Error(`could not subscribe via jsonrpc socket: ${h.message}`);let{reply:m}=p;if(m.subscription&&f){let y=()=>bg(this,void 0,void 0,function*(){c.delete(o),yield f()}),b={subscription:Object.assign(Object.assign({},m.subscription),{close:y}),target:r,message:n,handler:i,resubscribeFactory:a};c.set(o,b),m.subscription.close=y}return m})}static resubscribeAll(e){return bg(this,void 0,void 0,function*(){let r=[...e.subscriptions.entries()];e.subscriptions.clear();for(let[,n]of r)try{let i;n.resubscribeFactory?i=yield n.resubscribeFactory(n.lastCursor):i=n.message,yield t.subscriptionRequest(e,n.target,i,n.handler,n.resubscribeFactory),n.handler({type:"reconnected"})}catch{}})}};Eb.connections=new Map;var Sb=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},TH;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(TH||(TH={}));var Pg=class{constructor(e=[]){this.transportClients=new Map,e=[new K5,new N5,...e];for(let r of e)for(let n of r.transportProtocols)this.transportClients.set(n,r)}get transportProtocols(){return Array.from(this.transportClients.keys())}sendDidRequest(e){return Sb(this,void 0,void 0,function*(){let r=new URL(e.url),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDidRequest(e)})}sendDwnRequest(e){let r=new URL(e.dwnUrl),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDwnRequest(e)}getServerInfo(e){return Sb(this,void 0,void 0,function*(){let r=new URL(e),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.getServerInfo(e)})}},K5=class extends eS{sendDidRequest(e){return Sb(this,void 0,void 0,function*(){let r=gn.randomUuid(),n=vg(r,e.method,{data:e.data}),i=new Request(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a;try{let s=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(s.ok){if(a=yield s.json(),a.error){let{code:o,message:d}=a.error;throw new Error(`JSON RPC (${o}) - ${d}`)}}else throw new Error(`HTTP (${s.status}) - ${s.statusText}`)}catch(s){throw new Error(`Error encountered while processing response from ${e.url}: ${s.message}`)}return a.result})}},N5=class extends Eb{sendDidRequest(e){return Sb(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return Sb(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};g();var IH=class t{constructor(e){this.agent=e.agent,this.agentStores=e.agentStores,this.didResolverCache=e.didResolverCache,this.dwn=e.dwn,this.dwnDataStore=e.dwnDataStore,this.dwnStateIndex=e.dwnStateIndex,this.dwnMessageStore=e.dwnMessageStore,this.syncStore=e.syncStore,this.vaultStore=e.vaultStore,this.dwnResumableTaskStore=e.dwnResumableTaskStore,this.dwnStores=e.dwnStores}async clearStorage(){if(await this.agent.sync.stopSync(),this.agent.agentDid=void 0,await this.didResolverCache.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.syncStore.clear(),await this.vaultStore.clear(),this.agent.vault._cachedInitialized=void 0,await this.agent.permissions.clear(),this.dwnStores.clear(),this.agentStores==="memory"){let{didApi:e,identityApi:r,permissionsApi:n,keyManager:i}=t.useMemoryStores({agent:this.agent});this.agent.did=e,this.agent.identity=r,this.agent.keyManager=i,this.agent.permissions=n}}async clearDwnStores(){await this.syncStore.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.agent.permissions.clear(),this.dwnStores.clear()}async closeStorage(){await this.didResolverCache.close(),await this.dwnDataStore.close(),await this.dwnStateIndex.close(),await this.dwnMessageStore.close(),await this.dwnResumableTaskStore.close(),await this.syncStore.close(),await this.vaultStore.close()}async createAgentDid(){this.agent.agentDid=await po.create({options:{publish:!0,gatewayUri:j.DID_DHT_GATEWAY_URI??"http://localhost:7527",verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]}})}async createIdentity({name:e,testDwnUrls:r}){return await this.agent.identity.create({didMethod:"dht",didOptions:{services:[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:r}],verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]},metadata:{name:e}})}static async setup({agentClass:e,agentStores:r,testDataLocation:n}){r??="memory",n??="__TESTDATA__";let i=G=>`${n}/${G}`,a=new yo,s=new Pg,o={keyStore:new lg,identityStore:new fg,didStore:new cg,clear:()=>{o.keyStore._protocolInitializedCache?.clear(),o.identityStore._protocolInitializedCache?.clear(),o.didStore._protocolInitializedCache?.clear()}},{agentVault:d,didApi:l,identityApi:c,keyManager:u,didResolverCache:f,vaultStore:h,permissionsApi:p}=r==="memory"?t.useMemoryStores():t.useDiskStores({testDataLocation:n,stores:o}),m=new _f({blockstoreLocation:i("DWN_DATASTORE")}),y=new Rf({location:i("DWN_STATEINDEX")}),b=new Df,w=new If({location:i("DWN_RESUMABLETASKSTORE")}),S=new Tf({blockstoreLocation:i("DWN_MESSAGESTORE"),indexLocation:i("DWN_MESSAGEINDEX")}),k=await Fl.createDwn({dataPath:n,dataStore:m,didResolver:l,stateIndex:y,eventLog:b,messageStore:S,resumableTaskStore:w}),T=new Fl({dwn:k,localDwnStrategy:"off"}),D=new pge(i("SYNC_STORE")),K=new mg({db:D}),C=new e({agentVault:d,cryptoApi:a,didApi:l,dwnApi:T,identityApi:c,keyManager:u,permissionsApi:p,rpcClient:s,syncApi:K});return new t({agent:C,agentStores:r,didResolverCache:f,dwn:k,dwnDataStore:m,dwnStateIndex:y,dwnMessageStore:S,dwnResumableTaskStore:w,dwnStores:o,syncStore:D,vaultStore:h})}static useDiskStores({agent:e,testDataLocation:r,stores:n}){let i=m=>`${r}/${m}`,a=new Im({location:i("VAULT_STORE")}),s=new Rh({keyDerivationWorkFactor:1,store:a}),{didStore:o,identityStore:d,keyStore:l}=n,c=new Cf({location:i("DID_RESOLVERCACHE")}),u=new _h({agent:e,didMethods:[po,ho],resolverCache:c,store:o}),f=new Ch({agent:e,store:d}),h=new go({agent:e,keyStore:l}),p=new Ka({agent:e});return{agentVault:s,didApi:u,didResolverCache:c,identityApi:f,keyManager:h,permissionsApi:p,vaultStore:a}}static useMemoryStores({agent:e}={}){let r=new bu,n=new Rh({keyDerivationWorkFactor:1,store:r}),i=new dE,a=new _h({agent:e,didMethods:[po,ho],resolverCache:i,store:new dg}),s=new go({agent:e,keyStore:new ug}),o=new Ch({agent:e,store:new pg}),d=new Ka({agent:e});return{agentVault:n,didApi:a,didResolverCache:i,identityApi:o,keyManager:s,permissionsApi:d,vaultStore:r}}};g();Jo();Er();wn();Yn();function hge({baseURL:t,endpoint:e,authParam:r,tokenParam:n}){switch(e){case"pushedAuthorizationRequest":return hb(t,"par");case"authorize":if(!r)throw new Error("authParam must be provided when building an authorize URL");return hb(t,`authorize/${r}.jwt`);case"callback":return hb(t,"callback");case"token":if(!n)throw new Error("tokenParam must be provided when building a token URL");return hb(t,`token/${n}.jwt`);default:throw new Error(`Unknown connect endpoint: ${e}`)}}async function mge({did:t,data:e}){let r=he.object({alg:"EdDSA",kid:t.document.verificationMethod[0].id,typ:"JWT"}).toBase64Url(),n=he.object(e).toBase64Url(),a=await(await t.getSigner()).sign({data:he.string(`${r}.${n}`).toUint8Array()}),s=he.uint8Array(a).toBase64Url();return`${r}.${n}.${s}`}async function DH({jwt:t}){let[e,r,n]=t.split("."),i=he.base64Url(e).toObject();if(!i.kid)throw new Error('Connect: JWT missing required "kid" header value.');let{didDocument:a}=await ho.resolve(i.kid.split("#")[0]);if(!a)throw new Error("Connect: JWT verification failed \u2014 could not resolve DID.");let{publicKeyJwk:s}=a.verificationMethod?.find(l=>l.id===i.kid)??{};if(!s)throw new Error("Connect: JWT verification failed \u2014 public key not found in DID document.");if(!await new Fc().verify({key:s,signature:he.base64Url(n).toUint8Array(),data:he.string(`${e}.${r}`).toUint8Array()}))throw new Error("Connect: JWT verification failed \u2014 invalid signature.");return he.base64Url(r).toObject()}async function yge({jwt:t,encryptionKey:e}){let r={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT"},n=gn.randomBytes(24),i=he.object(r).toUint8Array(),a=he.string(t).toUint8Array(),s=await Hc.encryptRaw({data:a,keyBytes:e,nonce:n,additionalData:i}),o=s.subarray(0,-16),d=s.subarray(-16);return[he.object(r).toBase64Url(),"",he.uint8Array(n).toBase64Url(),he.uint8Array(o).toBase64Url(),he.uint8Array(d).toBase64Url()].join(".")}async function RH({jwe:t,encryptionKey:e}){let[r,,n,i,a]=t.split("."),s=he.base64Url(e).toUint8Array(),o=he.base64Url(r).toUint8Array(),d=he.base64Url(n).toUint8Array(),l=he.base64Url(i).toUint8Array(),c=he.base64Url(a).toUint8Array(),u=new Uint8Array([...l,...c]),f=await Hc.decryptRaw({data:u,keyBytes:s,nonce:d,additionalData:o});return he.uint8Array(f).toString()}async function gge(t,e){let r=await t.export(),n=e.verificationMethod?.[0].publicKeyJwk,i=r.privateKeys?.[0];n.alg="EdDSA";let a=await wi.convertPublicKeyToX25519({publicKey:n}),s=await wi.convertPrivateKeyToX25519({privateKey:i}),o=await Gt.sharedSecret({privateKeyA:s,publicKeyB:a});return Om.deriveKeyBytes({baseKeyBytes:new Uint8Array(o),hash:"SHA-256",salt:new Uint8Array,info:new Uint8Array,length:256})}async function wge({jwt:t,encryptionKey:e,delegateDidKeyId:r,pin:n}){let i={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT",kid:r},a=gn.randomBytes(24),s=n?{...i,pin:n}:{...i},o=he.object(s).toUint8Array(),d=he.string(t).toUint8Array(),l=await Hc.encryptRaw({data:d,keyBytes:e,nonce:a,additionalData:o}),c=l.subarray(0,-16),u=l.subarray(-16);return[he.object(i).toBase64Url(),"",he.uint8Array(a).toBase64Url(),he.uint8Array(c).toBase64Url(),he.uint8Array(u).toBase64Url()].join(".")}async function vge(t,e,r){let[n,,i,a,s]=e.split("."),o=he.base64Url(n).toObject();if(!o.kid)throw new Error('Connect: JWE protected header is missing required "kid" property.');let d=await ho.resolve(o.kid.split("#")[0]),l=await xg.deriveSharedKey(t,d.didDocument),c=r?{...o,pin:r}:{...o},u=he.object(c).toUint8Array(),f=he.base64Url(i).toUint8Array(),h=he.base64Url(a).toUint8Array(),p=he.base64Url(s).toUint8Array(),m=new Uint8Array([...h,...p]),y=await Hc.decryptRaw({data:m,keyBytes:l,nonce:f,additionalData:u});return he.uint8Array(y).toString()}async function bge(t){let e=gn.randomBytes(16),r=gn.randomBytes(16);return{...t,nonce:he.uint8Array(r).toBase64Url(),responseMode:"direct_post",state:he.uint8Array(e).toBase64Url(),supportedDidMethods:t.supportedDidMethods??["did:dht","did:jwk"]}}async function Pge(t,e){let n=await(await fetch(t,{signal:AbortSignal.timeout(3e4)})).text(),i=await RH({jwe:n,encryptionKey:e});return await DH({jwt:i})}async function xge(t){let e=Math.floor(Date.now()/1e3);return{...t,iat:e,exp:e+600}}function Ege(t){return b5(t)?!0:t.interface===be.Protocols&&t.method===ge.Configure}async function Sge(t,e,r,n){let i=new Ka({agent:r});Rs.log(`Creating permission grants for ${n.length} scopes...`);let a=await Promise.all(n.map(d=>{let l=Ege(d);return i.createGrant({delegated:l,store:!0,grantedTo:e.uri,scope:d,dateExpires:"2040-06-25T16:09:16.693356Z",author:t})})),s=await r.dwn.getDwnEndpointUrlsForTarget(t);Rs.log(`Sending ${a.length} permission grants to ${s.length} DWN endpoint(s)...`);let o=a.map(async d=>{let{encodedData:l,...c}=d.message,u=he.base64Url(l).toUint8Array(),f=!1;for(let h of s)try{let p=await r.rpc.sendDwnRequest({dwnUrl:h,targetDid:t,message:c,data:new Blob([u])});p.status.code===202||p.status.code===409?f=!0:Rs.error(`Grant send to ${h} returned ${p.status.code}: ${p.status.detail}`)}catch(p){Rs.error(`Grant send to ${h} failed: ${p.message}`)}if(!f)throw new Error("Could not send permission grant to any DWN endpoint.");return d.message});try{return await Promise.all(o)}catch(d){throw Rs.error(`Error during batch-send of permission grants: ${d}`),d}}async function Age(t,e,r){let n=await e.processDwnRequest({author:t,messageType:Re.ProtocolsQuery,target:t,messageParams:{filter:{protocol:r.protocol}}});if(n.reply.status.code!==200)throw new Error(`Could not fetch protocol: ${n.reply.status.detail}`);if(n.reply.entries===void 0||n.reply.entries.length===0){Rs.log(`Protocol does not exist, creating: ${r.protocol}`);let{reply:i,message:a}=await e.sendDwnRequest({author:t,target:t,messageType:Re.ProtocolsConfigure,messageParams:{definition:r}});if(i.status.code!==202&&i.status.code!==409)throw new Error(`Could not send protocol: ${i.status.detail}`);await e.processDwnRequest({author:t,target:t,messageType:Re.ProtocolsConfigure,rawMessage:a})}else{Rs.log(`Protocol already exists: ${r.protocol}`);let i=n.reply.entries[0],{reply:a}=await e.sendDwnRequest({author:t,target:t,messageType:Re.ProtocolsConfigure,rawMessage:i});if(a.status.code!==202&&a.status.code!==409)throw new Error(`Could not send protocol: ${a.status.detail}`)}}async function kge(t,e,r,n){let i=await ho.create(),a=await i.export(),s=e.permissionRequests.map(async p=>{let{protocolDefinition:m,permissionScopes:y}=p;if(!y.every(w=>"protocol"in w&&w.protocol===m.protocol))throw new Error("All permission scopes must match the protocol URI they are provided with.");return await Age(t,n,m),xg.createPermissionGrants(t,i,n,y)}),o=(await Promise.all(s)).flat();Rs.log("Building connect response...");let d=await xg.createConnectResponse({providerDid:t,delegateDid:i.uri,aud:e.clientDid,nonce:e.nonce,delegateGrants:o,delegatePortableDid:a});Rs.log("Signing connect response...");let l=await xg.signJwt({did:i,data:d}),c=await ho.resolve(e.clientDid),u=await xg.deriveSharedKey(i,c?.didDocument);Rs.log("Encrypting connect response...");let f=await xg.encryptResponse({jwt:l,encryptionKey:u,delegateDidKeyId:i.document.verificationMethod[0].id,pin:r}),h=new URLSearchParams({id_token:f,state:e.state}).toString();Rs.log(`Sending connect response to: ${e.callbackUrl}`),await fetch(e.callbackUrl,{body:h,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(3e4)})}var xg={buildConnectUrl:hge,signJwt:mge,verifyJwt:DH,encryptRequest:yge,decryptRequest:RH,encryptResponse:wge,decryptResponse:vge,deriveSharedKey:gge,createConnectRequest:bge,getConnectRequest:Pge,createConnectResponse:xge,createPermissionGrants:Sge,submitConnectResponse:kge};g();Er();Jo();var CH=class t{constructor(e){this._agentDid=e.agentDid,this.crypto=e.cryptoApi,this.did=e.didApi,this.dwn=e.dwnApi,this.identity=e.identityApi,this.keyManager=e.keyManager,this.permissions=e.permissionsApi,this.rpc=e.rpcClient,this.sync=e.syncApi,this.vault=e.agentVault,this.did.agent=this,this.dwn.agent=this,this.identity.agent=this,this.keyManager.agent=this,this.permissions.agent=this,this.sync.agent=this}get agentDid(){if(this._agentDid===void 0)throw new Error('EnboxUserAgent: The "agentDid" property is not set. Ensure the agent is properly initialized and a DID is assigned.');return this._agentDid}set agentDid(e){this._agentDid=e}static async create({dataPath:e="DATA/AGENT",localDwnStrategy:r,localDwnEndpoint:n,agentDid:i,agentVault:a,cryptoApi:s,didApi:o,dwnApi:d,identityApi:l,keyManager:c,permissionsApi:u,rpcClient:f,syncApi:h}={}){return a??=new Rh({keyDerivationWorkFactor:21e4,store:new Im({location:`${e}/VAULT_STORE`})}),s??=new yo,o??=new _h({didMethods:[po,ho],resolverCache:new Cf({location:`${e}/DID_RESOLVERCACHE`}),store:new cg}),d||(n?d=new Fl({localDwnEndpoint:n,localDwnStrategy:r??"prefer"}):d=new Fl({dwn:await Fl.createDwn({dataPath:e,didResolver:o}),localDwnStrategy:r??"prefer"})),r&&d.setLocalDwnStrategy(r),l??=new Ch({store:new fg}),c??=new go({keyStore:new lg}),u??=new Ka,f??=new Pg,h??=new mg({dataPath:e}),new t({agentDid:i,agentVault:a,cryptoApi:s,didApi:o,dwnApi:d,keyManager:c,permissionsApi:u,identityApi:l,rpcClient:f,syncApi:h})}async firstLaunch(){return await this.vault.isInitialized()===!1}async initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}){return r=await this.vault.initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}),r}async processDidRequest(e){return this.did.processRequest(e)}async processDwnRequest(e){return this.dwn.processRequest(e)}async processVcRequest(e){throw new Error("Not implemented")}async sendDidRequest(e){throw new Error("Not implemented")}async sendDwnRequest(e){return this.dwn.sendRequest(e)}async sendVcRequest(e){throw new Error("Not implemented")}async start({password:e}){this.vault.isLocked()&&await this.vault.unlock({password:e}),this.agentDid=await this.vault.getDid()}};export{yo as AgentCryptoApi,_h as AgentDidApi,Cf as AgentDidResolverCache,Fl as AgentDwnApi,Ch as AgentIdentityApi,Ka as AgentPermissionsApi,CG as AnonymousDwnApi,ig as BearerIdentity,hye as DISCOVERY_DIR,mye as DISCOVERY_FILENAME,YG as DWN_CONNECT_PATH,ZG as DWN_PROTOCOL_SCHEME,uye as DidInterface,ma as DwnConstant,ii as DwnContentEncryptionAlgorithm,$f as DwnDataStore,Kt as DwnDateSort,cg as DwnDidStore,FE as DwnDiscoveryFile,fg as DwnIdentityStore,Re as DwnInterface,Ht as DwnKeyDerivationScheme,lg as DwnKeyStore,Ir as DwnPermissionGrant,cd as DwnPermissionRequest,dt as DwnPermissionsProtocol,xg as EnboxConnectProtocol,CH as EnboxUserAgent,Rh as HdIdentityVault,Bf as InMemoryDataStore,dg as InMemoryDidStore,pg as InMemoryIdentityStore,ug as InMemoryKeyStore,Th as LocalDwnDiscovery,go as LocalKeyManager,IH as PlatformAgentTestHarness,mg as SyncEngineLevel,jG as buildContextKeyDecrypter,FHe as buildDwnConnectUrl,HHe as buildDwnDiscoveryRedirectUrl,Ih as buildEncryptionInput,NG as buildKmsDecryptCallback,hb as concatenateUrl,pye as createNodeDiscoveryFileFs,JG as decodeDwnDiscoveryPayload,KG as deriveContextEncryptionInput,E5 as detectNewParticipants,Id as dwnMessageConstructors,FG as eagerSendContextKeyRecord,vye as encodeDwnDiscoveryPayload,HE as encryptAndComputeCid,qG as ensureKeyDeliveryProtocol,GG as fetchContextKeyRecord,pb as getDwnServiceEndpointUrls,yb as getEncryptionKeyDeriver,zl as getEncryptionKeyInfo,gb as getKeyDecrypter,fGe as getPaginationCursor,lGe as getRecordAuthor,sye as getRecordMessageCid,uGe as getRecordProtocolRole,hHe as getRootContextId,LG as getRuleSetAtPath,P5 as hasRelationalReadAccess,OG as isDidRequest,gye as isDwnMessage,Rd as isDwnRequest,Jye as isIdentityMetadata,wye as isMessagesPermissionScope,x5 as isMultiPartyContext,SWe as isPortableIdentity,b5 as isRecordPermissionScope,v5 as isRecordsType,Ll as isRecordsWrite,GE as ivLength,fye as localDwnServerName,UG as maybeDecryptReply,zE as normalizeBaseUrl,GHe as parseDwnConnectUrl,pGe as pollWithTtl,VHe as readDwnDiscoveryPayloadFromUrl,MG as resolveKeyDecrypter,zG as writeContextKeyRecord};
2061
2061
  /*! Bundled license information:
2062
2062
 
2063
2063
  ieee754/index.js: